Patch for bug #13211
"MythTV needs a backport from FFmpeg 3.3/3.4 to make German DVB-T2 HD with 5.1 audio work"
https://code.mythtv.org/trac/ticket/13211

diff --git a/mythtv/external/FFmpeg/libavcodec/aacdec_template.c b/mythtv/external/FFmpeg/libavcodec/aacdec_template.c
index 883ed527f7..f8a8dc4332 100644
--- a/mythtv/external/FFmpeg/libavcodec/aacdec_template.c
+++ b/mythtv/external/FFmpeg/libavcodec/aacdec_template.c
@@ -406,11 +406,15 @@ static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
 /**
  * Save current output configuration if and only if it has been locked.
  */
-static void push_output_configuration(AACContext *ac) {
+static int push_output_configuration(AACContext *ac) {
+    int pushed = 0;
+
     if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
         ac->oc[0] = ac->oc[1];
+        pushed = 1;
     }
     ac->oc[1].status = OC_NONE;
+    return pushed;
 }
 
 /**
@@ -452,7 +456,7 @@ static int output_configure(AACContext *ac,
         int id =           layout_map[i][1];
         id_map[type][id] = type_counts[type]++;
         if (id_map[type][id] >= MAX_ELEM_ID) {
-            avpriv_request_sample(ac->avctx, "Remapped id too large\n");
+            avpriv_request_sample(ac->avctx, "Too large remapped id");
             return AVERROR_PATCHWELCOME;
         }
     }
@@ -715,6 +719,13 @@ static void decode_channel_map(uint8_t layout_map[][3],
     }
 }
 
+static inline void relative_align_get_bits(GetBitContext *gb,
+                                           int reference_position) {
+    int n = (reference_position - get_bits_count(gb) & 7);
+    if (n)
+        skip_bits(gb, n);
+}
+
 /**
  * Decode program configuration element; reference: table 4.2.
  *
@@ -722,7 +733,7 @@ static void decode_channel_map(uint8_t layout_map[][3],
  */
 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
                       uint8_t (*layout_map)[3],
-                      GetBitContext *gb)
+                      GetBitContext *gb, int byte_align_ref)
 {
     int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
     int sampling_index;
@@ -770,7 +781,7 @@ static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
     decode_channel_map(layout_map + tags, AAC_CHANNEL_CC,    gb, num_cc);
     tags += num_cc;
 
-    align_get_bits(gb);
+    relative_align_get_bits(gb, byte_align_ref);
 
     /* comment field, first byte is length */
     comment_len = get_bits(gb, 8) * 8;
@@ -792,6 +803,7 @@ static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
  */
 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
                                      GetBitContext *gb,
+                                     int get_bit_alignment,
                                      MPEG4AudioConfig *m4ac,
                                      int channel_config)
 {
@@ -815,7 +827,7 @@ static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
 
     if (channel_config == 0) {
         skip_bits(gb, 4);  // element_instance_tag
-        tags = decode_pce(avctx, m4ac, layout_map, gb);
+        tags = decode_pce(avctx, m4ac, layout_map, gb, get_bit_alignment);
         if (tags < 0)
             return tags;
     } else {
@@ -937,37 +949,26 @@ static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
  * @param   ac          pointer to AACContext, may be null
  * @param   avctx       pointer to AVCCodecContext, used for logging
  * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
- * @param   data        pointer to buffer holding an audio specific config
- * @param   bit_size    size of audio specific config or data in bits
+ * @param   gb          buffer holding an audio specific config
+ * @param   get_bit_alignment relative alignment for byte align operations
  * @param   sync_extension look for an appended sync extension
  *
  * @return  Returns error status or number of consumed bits. <0 - error
  */
-static int decode_audio_specific_config(AACContext *ac,
-                                        AVCodecContext *avctx,
-                                        MPEG4AudioConfig *m4ac,
-                                        const uint8_t *data, int64_t bit_size,
-                                        int sync_extension)
+static int decode_audio_specific_config_gb(AACContext *ac,
+                                           AVCodecContext *avctx,
+                                           MPEG4AudioConfig *m4ac,
+                                           GetBitContext *gb,
+                                           int get_bit_alignment,
+                                           int sync_extension)
 {
-    GetBitContext gb;
     int i, ret;
+    GetBitContext gbc = *gb;
 
-    if (bit_size < 0 || bit_size > INT_MAX) {
-        av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
+    /* function ff_mpeg4audio_get_config_gb is not avaible in FFmpeg 3.2 */
+    if ((i = ff_mpeg4audio_get_config_gb(m4ac, &gbc, sync_extension)) < 0)
         return AVERROR_INVALIDDATA;
-    }
-
-    ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
-    for (i = 0; i < bit_size >> 3; i++)
-        ff_dlog(avctx, "%02x ", data[i]);
-    ff_dlog(avctx, "\n");
 
-    if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
-        return ret;
-
-    if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
-                                          sync_extension)) < 0)
-        return AVERROR_INVALIDDATA;
     if (m4ac->sampling_index > 12) {
         av_log(avctx, AV_LOG_ERROR,
                "invalid sampling rate index %d\n",
@@ -982,7 +983,7 @@ static int decode_audio_specific_config(AACContext *ac,
         return AVERROR_INVALIDDATA;
     }
 
-    skip_bits_long(&gb, i);
+    skip_bits_long(gb, i);
 
     switch (m4ac->object_type) {
     case AOT_AAC_MAIN:
@@ -990,12 +991,12 @@ static int decode_audio_specific_config(AACContext *ac,
     case AOT_AAC_LTP:
     case AOT_ER_AAC_LC:
     case AOT_ER_AAC_LD:
-        if ((ret = decode_ga_specific_config(ac, avctx, &gb,
+        if ((ret = decode_ga_specific_config(ac, avctx, gb, get_bit_alignment,
                                             m4ac, m4ac->chan_config)) < 0)
             return ret;
         break;
     case AOT_ER_AAC_ELD:
-        if ((ret = decode_eld_specific_config(ac, avctx, &gb,
+        if ((ret = decode_eld_specific_config(ac, avctx, gb,
                                               m4ac, m4ac->chan_config)) < 0)
             return ret;
         break;
@@ -1013,7 +1014,37 @@ static int decode_audio_specific_config(AACContext *ac,
             m4ac->sample_rate, m4ac->sbr,
             m4ac->ps);
 
-    return get_bits_count(&gb);
+    return get_bits_count(gb);
+}
+
+static int decode_audio_specific_config(AACContext *ac,
+                                        AVCodecContext *avctx,
+                                        MPEG4AudioConfig *m4ac,
+                                        const uint8_t *data, int64_t bit_size,
+                                        int sync_extension)
+{
+    int i, ret;
+    GetBitContext gb;
+
+    if (bit_size < 0 || bit_size > INT_MAX) {
+        av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
+    for (i = 0; i < bit_size >> 3; i++)
+        ff_dlog(avctx, "%02x ", data[i]);
+    ff_dlog(avctx, "\n");
+
+    if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
+        return ret;
+
+    /* if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, */
+    /*                                      sync_extension)) < 0)  */
+    /*    return AVERROR_INVALIDDATA;                              */
+
+    return decode_audio_specific_config_gb(ac, avctx, m4ac, &gb, 0,
+                                           sync_extension);
 }
 
 /**
@@ -1255,6 +1286,8 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
     const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
     const int aot = m4ac->object_type;
     const int sampling_index = m4ac->sampling_index;
+    int ret_fail = AVERROR_INVALIDDATA;
+
     if (aot != AOT_ER_AAC_ELD) {
         if (get_bits1(gb)) {
             av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
@@ -1305,8 +1338,10 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
                 ics->num_swb       =    ff_aac_num_swb_512[sampling_index];
                 ics->tns_max_bands =  ff_tns_max_bands_512[sampling_index];
             }
-            if (!ics->num_swb || !ics->swb_offset)
-                return AVERROR_BUG;
+            if (!ics->num_swb || !ics->swb_offset) {
+                ret_fail = AVERROR_BUG;
+                goto fail;
+            }
         } else {
             ics->swb_offset    =    ff_swb_offset_1024[sampling_index];
             ics->num_swb       =   ff_aac_num_swb_1024[sampling_index];
@@ -1330,7 +1365,8 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
                 if (aot == AOT_ER_AAC_LD) {
                     av_log(ac->avctx, AV_LOG_ERROR,
                            "LTP in ER AAC LD not yet implemented.\n");
-                    return AVERROR_PATCHWELCOME;
+                    ret_fail = AVERROR_PATCHWELCOME;
+                    goto fail;
                 }
                 if ((ics->ltp.present = get_bits(gb, 1)))
                     decode_ltp(&ics->ltp, gb, ics->max_sfb);
@@ -1349,7 +1385,7 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
     return 0;
 fail:
     ics->max_sfb = 0;
-    return AVERROR_INVALIDDATA;
+    return ret_fail;
 }
 
 /**
@@ -1936,16 +1972,17 @@ static int decode_ics(AACContext *ac, SingleChannelElement *sce,
     global_gain = get_bits(gb, 8);
 
     if (!common_window && !scale_flag) {
-        if (decode_ics_info(ac, ics, gb) < 0)
-            return AVERROR_INVALIDDATA;
+        ret = decode_ics_info(ac, ics, gb);
+        if (ret < 0)
+            goto fail;
     }
 
     if ((ret = decode_band_types(ac, sce->band_type,
                                  sce->band_type_run_end, gb, ics)) < 0)
-        return ret;
+        goto fail;
     if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
                                   sce->band_type, sce->band_type_run_end)) < 0)
-        return ret;
+        goto fail;
 
     pulse_present = 0;
     if (!scale_flag) {
@@ -1953,37 +1990,48 @@ static int decode_ics(AACContext *ac, SingleChannelElement *sce,
             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
                 av_log(ac->avctx, AV_LOG_ERROR,
                        "Pulse tool not allowed in eight short sequence.\n");
-                return AVERROR_INVALIDDATA;
+                ret = AVERROR_INVALIDDATA;
+                goto fail;
             }
             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
                 av_log(ac->avctx, AV_LOG_ERROR,
                        "Pulse data corrupt or invalid.\n");
-                return AVERROR_INVALIDDATA;
+                ret = AVERROR_INVALIDDATA;
+                goto fail;
             }
         }
         tns->present = get_bits1(gb);
-        if (tns->present && !er_syntax)
-            if (decode_tns(ac, tns, gb, ics) < 0)
-                return AVERROR_INVALIDDATA;
+        if (tns->present && !er_syntax) {
+            ret = decode_tns(ac, tns, gb, ics);
+            if (ret < 0)
+                goto fail;
+        }
         if (!eld_syntax && get_bits1(gb)) {
             avpriv_request_sample(ac->avctx, "SSR");
-            return AVERROR_PATCHWELCOME;
+            ret = AVERROR_PATCHWELCOME;
+            goto fail;
         }
         // I see no textual basis in the spec for this occurring after SSR gain
         // control, but this is what both reference and real implmentations do
-        if (tns->present && er_syntax)
-            if (decode_tns(ac, tns, gb, ics) < 0)
-                return AVERROR_INVALIDDATA;
+        if (tns->present && er_syntax) {
+            ret = decode_tns(ac, tns, gb, ics);
+            if (ret < 0)
+                goto fail;
+        }
     }
 
-    if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
-                                    &pulse, ics, sce->band_type) < 0)
-        return AVERROR_INVALIDDATA;
+    ret = decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
+                                    &pulse, ics, sce->band_type);
+    if (ret < 0)
+        goto fail;
 
     if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
         apply_prediction(ac, sce);
 
     return 0;
+fail:
+    tns->present = 0;
+    return ret;
 }
 
 /**
@@ -2155,7 +2203,11 @@ static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
 
     sign  = get_bits(gb, 1);
-    scale = AAC_RENAME(cce_scale)[get_bits(gb, 2)];
+#if USE_FIXED
+    scale = get_bits(gb, 2);
+#else
+    scale = cce_scale[get_bits(gb, 2)];
+#endif
 
     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
         return ret;
@@ -2169,6 +2221,10 @@ static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
             gain_cache = GET_GAIN(scale, gain);
+#if USE_FIXED
+            if ((abs(gain_cache)-1024) >> 3 > 30)
+                return AVERROR(ERANGE);
+#endif
         }
         if (coup->coupling_point == AFTER_IMDCT) {
             coup->gain[c][0] = gain_cache;
@@ -2186,6 +2242,10 @@ static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
                                     t >>= 1;
                                 }
                                 gain_cache = GET_GAIN(scale, t) * s;
+#if USE_FIXED
+                                if ((abs(gain_cache)-1024) >> 3 > 30)
+                                    return AVERROR(ERANGE);
+#endif
                             }
                         }
                         coup->gain[c][idx] = gain_cache;
@@ -2923,10 +2983,11 @@ static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
 {
     AACContext *ac = avctx->priv_data;
     ChannelElement *che = NULL, *che_prev = NULL;
-    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
+    enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
     int err, elem_id;
     int samples = 0, multiplier, audio_found = 0, pce_found = 0;
     int is_dmono, sce_count = 0;
+    int payload_alignment;
 
     ac->frame = data;
 
@@ -2949,6 +3010,7 @@ static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
     // This may lead to an undefined profile being signaled
     ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
 
+    payload_alignment = get_bits_count(gb);
     ac->tags_mapped = 0;
     // parse
     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
@@ -3002,8 +3064,15 @@ static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
         case TYPE_PCE: {
             uint8_t layout_map[MAX_ELEM_ID*4][3];
             int tags;
-            push_output_configuration(ac);
-            tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
+
+            int pushed = push_output_configuration(ac);
+            if (pce_found && !pushed) {
+                err = AVERROR_INVALIDDATA;
+                goto fail;
+            }
+
+            tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
+                              payload_alignment);
             if (tags < 0) {
                 err = tags;
                 break;
@@ -3011,6 +3080,7 @@ static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
             if (pce_found) {
                 av_log(avctx, AV_LOG_ERROR,
                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
+                pop_output_configuration(ac);
             } else {
                 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
                 if (!err)
@@ -3029,7 +3099,7 @@ static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
                     goto fail;
             }
             while (elem_id > 0)
-                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
+                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
             err = 0; /* FIXME */
             break;
 
@@ -3038,8 +3108,10 @@ static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
             break;
         }
 
-        che_prev       = che;
-        elem_type_prev = elem_type;
+        if (elem_type < TYPE_DSE) {
+            che_prev      = che;
+            che_prev_type = elem_type;
+        }
 
         if (err)
             goto fail;
diff --git a/mythtv/external/FFmpeg/libavcodec/mpeg4audio.c b/mythtv/external/FFmpeg/libavcodec/mpeg4audio.c
index 188d843eee..84f384eeb6 100644
--- a/mythtv/external/FFmpeg/libavcodec/mpeg4audio.c
+++ b/mythtv/external/FFmpeg/libavcodec/mpeg4audio.c
@@ -78,6 +78,75 @@ static inline int get_sample_rate(GetBitContext *gb, int *index)
         avpriv_mpeg4audio_sample_rates[*index];
 }
 
+int ff_mpeg4audio_get_config_gb(MPEG4AudioConfig *c, GetBitContext *gb,
+                                int sync_extension)
+{
+    int specific_config_bitindex, ret;
+    int start_bit_index = get_bits_count(gb);
+    c->object_type = get_object_type(gb);
+    c->sample_rate = get_sample_rate(gb, &c->sampling_index);
+    c->chan_config = get_bits(gb, 4);
+    if (c->chan_config < FF_ARRAY_ELEMS(ff_mpeg4audio_channels))
+        c->channels = ff_mpeg4audio_channels[c->chan_config];
+    c->sbr = -1;
+    c->ps  = -1;
+    if (c->object_type == AOT_SBR || (c->object_type == AOT_PS &&
+        // check for W6132 Annex YYYY draft MP3onMP4
+        !(show_bits(gb, 3) & 0x03 && !(show_bits(gb, 9) & 0x3F)))) {
+        if (c->object_type == AOT_PS)
+            c->ps = 1;
+        c->ext_object_type = AOT_SBR;
+        c->sbr = 1;
+        c->ext_sample_rate = get_sample_rate(gb, &c->ext_sampling_index);
+        c->object_type = get_object_type(gb);
+        if (c->object_type == AOT_ER_BSAC)
+            c->ext_chan_config = get_bits(gb, 4);
+    } else {
+        c->ext_object_type = AOT_NULL;
+        c->ext_sample_rate = 0;
+    }
+    specific_config_bitindex = get_bits_count(gb);
+
+    if (c->object_type == AOT_ALS) {
+        skip_bits(gb, 5);
+        if (show_bits_long(gb, 24) != MKBETAG('\0','A','L','S'))
+            skip_bits_long(gb, 24);
+
+        specific_config_bitindex = get_bits_count(gb);
+
+        ret = parse_config_ALS(gb, c);
+        if (ret < 0)
+            return ret;
+    }
+
+    if (c->ext_object_type != AOT_SBR && sync_extension) {
+        while (get_bits_left(gb) > 15) {
+            if (show_bits(gb, 11) == 0x2b7) { // sync extension
+                get_bits(gb, 11);
+                c->ext_object_type = get_object_type(gb);
+                if (c->ext_object_type == AOT_SBR && (c->sbr = get_bits1(gb)) == 1) {
+                    c->ext_sample_rate = get_sample_rate(gb, &c->ext_sampling_index);
+                    if (c->ext_sample_rate == c->sample_rate)
+                        c->sbr = -1;
+                }
+                if (get_bits_left(gb) > 11 && get_bits(gb, 11) == 0x548)
+                    c->ps = get_bits1(gb);
+                break;
+            } else
+                get_bits1(gb); // skip 1 bit
+        }
+    }
+
+    //PS requires SBR
+    if (!c->sbr)
+        c->ps = 0;
+    //Limit implicit PS to the HE-AACv2 Profile
+    if ((c->ps == -1 && c->object_type != AOT_AAC_LC) || c->channels & ~0x01)
+        c->ps = 0;
+
+    return specific_config_bitindex - start_bit_index;
+}
+
 int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf,
                                  int bit_size, int sync_extension)
 {
