]> git.sesse.net Git - ffmpeg/blob - libavcodec/aacdec.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / aacdec.c
1 /*
2  * AAC decoder
3  * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4  * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
5  *
6  * AAC LATM decoder
7  * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8  * Copyright (c) 2010      Janne Grunau <janne-libav@jannau.net>
9  *
10  * This file is part of FFmpeg.
11  *
12  * FFmpeg is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * FFmpeg is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with FFmpeg; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26
27 /**
28  * @file
29  * AAC decoder
30  * @author Oded Shimon  ( ods15 ods15 dyndns org )
31  * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
32  */
33
34 /*
35  * supported tools
36  *
37  * Support?             Name
38  * N (code in SoC repo) gain control
39  * Y                    block switching
40  * Y                    window shapes - standard
41  * N                    window shapes - Low Delay
42  * Y                    filterbank - standard
43  * N (code in SoC repo) filterbank - Scalable Sample Rate
44  * Y                    Temporal Noise Shaping
45  * Y                    Long Term Prediction
46  * Y                    intensity stereo
47  * Y                    channel coupling
48  * Y                    frequency domain prediction
49  * Y                    Perceptual Noise Substitution
50  * Y                    Mid/Side stereo
51  * N                    Scalable Inverse AAC Quantization
52  * N                    Frequency Selective Switch
53  * N                    upsampling filter
54  * Y                    quantization & coding - AAC
55  * N                    quantization & coding - TwinVQ
56  * N                    quantization & coding - BSAC
57  * N                    AAC Error Resilience tools
58  * N                    Error Resilience payload syntax
59  * N                    Error Protection tool
60  * N                    CELP
61  * N                    Silence Compression
62  * N                    HVXC
63  * N                    HVXC 4kbits/s VR
64  * N                    Structured Audio tools
65  * N                    Structured Audio Sample Bank Format
66  * N                    MIDI
67  * N                    Harmonic and Individual Lines plus Noise
68  * N                    Text-To-Speech Interface
69  * Y                    Spectral Band Replication
70  * Y (not in this code) Layer-1
71  * Y (not in this code) Layer-2
72  * Y (not in this code) Layer-3
73  * N                    SinuSoidal Coding (Transient, Sinusoid, Noise)
74  * Y                    Parametric Stereo
75  * N                    Direct Stream Transfer
76  *
77  * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78  *       - HE AAC v2 comprises LC AAC with Spectral Band Replication and
79            Parametric Stereo.
80  */
81
82 #include "libavutil/float_dsp.h"
83 #include "avcodec.h"
84 #include "internal.h"
85 #include "get_bits.h"
86 #include "dsputil.h"
87 #include "fft.h"
88 #include "fmtconvert.h"
89 #include "lpc.h"
90 #include "kbdwin.h"
91 #include "sinewin.h"
92
93 #include "aac.h"
94 #include "aactab.h"
95 #include "aacdectab.h"
96 #include "cbrt_tablegen.h"
97 #include "sbr.h"
98 #include "aacsbr.h"
99 #include "mpeg4audio.h"
100 #include "aacadtsdec.h"
101 #include "libavutil/intfloat.h"
102
103 #include <assert.h>
104 #include <errno.h>
105 #include <math.h>
106 #include <string.h>
107
108 #if ARCH_ARM
109 #   include "arm/aac.h"
110 #endif
111
112 static VLC vlc_scalefactors;
113 static VLC vlc_spectral[11];
114
115 #define overread_err "Input buffer exhausted before END element found\n"
116
117 static int count_channels(uint8_t (*layout)[3], int tags)
118 {
119     int i, sum = 0;
120     for (i = 0; i < tags; i++) {
121         int syn_ele = layout[i][0];
122         int pos     = layout[i][2];
123         sum += (1 + (syn_ele == TYPE_CPE)) *
124                (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
125     }
126     return sum;
127 }
128
129 /**
130  * Check for the channel element in the current channel position configuration.
131  * If it exists, make sure the appropriate element is allocated and map the
132  * channel order to match the internal FFmpeg channel layout.
133  *
134  * @param   che_pos current channel position configuration
135  * @param   type channel element type
136  * @param   id channel element id
137  * @param   channels count of the number of channels in the configuration
138  *
139  * @return  Returns error status. 0 - OK, !0 - error
140  */
141 static av_cold int che_configure(AACContext *ac,
142                                  enum ChannelPosition che_pos,
143                                  int type, int id, int *channels)
144 {
145     if (che_pos) {
146         if (!ac->che[type][id]) {
147             if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
148                 return AVERROR(ENOMEM);
149             ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
150         }
151         if (type != TYPE_CCE) {
152             if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
153                 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
154                 return AVERROR_INVALIDDATA;
155             }
156             ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
157             if (type == TYPE_CPE ||
158                 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
159                 ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
160             }
161         }
162     } else {
163         if (ac->che[type][id])
164             ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
165         av_freep(&ac->che[type][id]);
166     }
167     return 0;
168 }
169
170 struct elem_to_channel {
171     uint64_t av_position;
172     uint8_t syn_ele;
173     uint8_t elem_id;
174     uint8_t aac_position;
175 };
176
177 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
178                        uint8_t (*layout_map)[3], int offset, uint64_t left,
179     uint64_t right, int pos)
180 {
181     if (layout_map[offset][0] == TYPE_CPE) {
182         e2c_vec[offset] = (struct elem_to_channel) {
183             .av_position = left | right, .syn_ele = TYPE_CPE,
184             .elem_id = layout_map[offset    ][1], .aac_position = pos };
185         return 1;
186     } else {
187         e2c_vec[offset]   = (struct elem_to_channel) {
188             .av_position = left, .syn_ele = TYPE_SCE,
189             .elem_id = layout_map[offset    ][1], .aac_position = pos };
190         e2c_vec[offset + 1] = (struct elem_to_channel) {
191             .av_position = right, .syn_ele = TYPE_SCE,
192             .elem_id = layout_map[offset + 1][1], .aac_position = pos };
193         return 2;
194     }
195 }
196
197 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos, int *current) {
198     int num_pos_channels = 0;
199     int first_cpe = 0;
200     int sce_parity = 0;
201     int i;
202     for (i = *current; i < tags; i++) {
203         if (layout_map[i][2] != pos)
204             break;
205         if (layout_map[i][0] == TYPE_CPE) {
206             if (sce_parity) {
207                 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
208                     sce_parity = 0;
209                 } else {
210                     return -1;
211                 }
212             }
213             num_pos_channels += 2;
214             first_cpe = 1;
215         } else {
216             num_pos_channels++;
217             sce_parity ^= 1;
218         }
219     }
220     if (sce_parity &&
221         ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
222             return -1;
223     *current = i;
224     return num_pos_channels;
225 }
226
227 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
228 {
229     int i, n, total_non_cc_elements;
230     struct elem_to_channel e2c_vec[4*MAX_ELEM_ID] = {{ 0 }};
231     int num_front_channels, num_side_channels, num_back_channels;
232     uint64_t layout;
233
234     if (FF_ARRAY_ELEMS(e2c_vec) < tags)
235         return 0;
236
237     i = 0;
238     num_front_channels =
239         count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
240     if (num_front_channels < 0)
241         return 0;
242     num_side_channels =
243         count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
244     if (num_side_channels < 0)
245         return 0;
246     num_back_channels =
247         count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
248     if (num_back_channels < 0)
249         return 0;
250
251     i = 0;
252     if (num_front_channels & 1) {
253         e2c_vec[i] = (struct elem_to_channel) {
254             .av_position = AV_CH_FRONT_CENTER, .syn_ele = TYPE_SCE,
255             .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_FRONT };
256         i++;
257         num_front_channels--;
258     }
259     if (num_front_channels >= 4) {
260         i += assign_pair(e2c_vec, layout_map, i,
261                          AV_CH_FRONT_LEFT_OF_CENTER,
262                          AV_CH_FRONT_RIGHT_OF_CENTER,
263                          AAC_CHANNEL_FRONT);
264         num_front_channels -= 2;
265     }
266     if (num_front_channels >= 2) {
267         i += assign_pair(e2c_vec, layout_map, i,
268                          AV_CH_FRONT_LEFT,
269                          AV_CH_FRONT_RIGHT,
270                          AAC_CHANNEL_FRONT);
271         num_front_channels -= 2;
272     }
273     while (num_front_channels >= 2) {
274         i += assign_pair(e2c_vec, layout_map, i,
275                          UINT64_MAX,
276                          UINT64_MAX,
277                          AAC_CHANNEL_FRONT);
278         num_front_channels -= 2;
279     }
280
281     if (num_side_channels >= 2) {
282         i += assign_pair(e2c_vec, layout_map, i,
283                          AV_CH_SIDE_LEFT,
284                          AV_CH_SIDE_RIGHT,
285                          AAC_CHANNEL_FRONT);
286         num_side_channels -= 2;
287     }
288     while (num_side_channels >= 2) {
289         i += assign_pair(e2c_vec, layout_map, i,
290                          UINT64_MAX,
291                          UINT64_MAX,
292                          AAC_CHANNEL_SIDE);
293         num_side_channels -= 2;
294     }
295
296     while (num_back_channels >= 4) {
297         i += assign_pair(e2c_vec, layout_map, i,
298                          UINT64_MAX,
299                          UINT64_MAX,
300                          AAC_CHANNEL_BACK);
301         num_back_channels -= 2;
302     }
303     if (num_back_channels >= 2) {
304         i += assign_pair(e2c_vec, layout_map, i,
305                          AV_CH_BACK_LEFT,
306                          AV_CH_BACK_RIGHT,
307                          AAC_CHANNEL_BACK);
308         num_back_channels -= 2;
309     }
310     if (num_back_channels) {
311         e2c_vec[i] = (struct elem_to_channel) {
312           .av_position = AV_CH_BACK_CENTER, .syn_ele = TYPE_SCE,
313           .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_BACK };
314         i++;
315         num_back_channels--;
316     }
317
318     if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
319         e2c_vec[i] = (struct elem_to_channel) {
320           .av_position = AV_CH_LOW_FREQUENCY, .syn_ele = TYPE_LFE,
321           .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_LFE };
322         i++;
323     }
324     while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
325         e2c_vec[i] = (struct elem_to_channel) {
326           .av_position = UINT64_MAX, .syn_ele = TYPE_LFE,
327           .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_LFE };
328         i++;
329     }
330
331     // Must choose a stable sort
332     total_non_cc_elements = n = i;
333     do {
334         int next_n = 0;
335         for (i = 1; i < n; i++) {
336             if (e2c_vec[i-1].av_position > e2c_vec[i].av_position) {
337                 FFSWAP(struct elem_to_channel, e2c_vec[i-1], e2c_vec[i]);
338                 next_n = i;
339             }
340         }
341         n = next_n;
342     } while (n > 0);
343
344     layout = 0;
345     for (i = 0; i < total_non_cc_elements; i++) {
346         layout_map[i][0] = e2c_vec[i].syn_ele;
347         layout_map[i][1] = e2c_vec[i].elem_id;
348         layout_map[i][2] = e2c_vec[i].aac_position;
349         if (e2c_vec[i].av_position != UINT64_MAX) {
350             layout |= e2c_vec[i].av_position;
351         }
352     }
353
354     return layout;
355 }
356
357 /**
358  * Save current output configuration if and only if it has been locked.
359  */
360 static void push_output_configuration(AACContext *ac) {
361     if (ac->oc[1].status == OC_LOCKED) {
362         ac->oc[0] = ac->oc[1];
363     }
364     ac->oc[1].status = OC_NONE;
365 }
366
367 /**
368  * Restore the previous output configuration if and only if the current
369  * configuration is unlocked.
370  */
371 static void pop_output_configuration(AACContext *ac) {
372     if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
373         ac->oc[1] = ac->oc[0];
374         ac->avctx->channels = ac->oc[1].channels;
375         ac->avctx->channel_layout = ac->oc[1].channel_layout;
376     }
377 }
378
379 /**
380  * Configure output channel order based on the current program configuration element.
381  *
382  * @return  Returns error status. 0 - OK, !0 - error
383  */
384 static int output_configure(AACContext *ac,
385                                     uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
386                             enum OCStatus oc_type)
387 {
388     AVCodecContext *avctx = ac->avctx;
389     int i, channels = 0, ret;
390     uint64_t layout = 0;
391
392     if (ac->oc[1].layout_map != layout_map) {
393         memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
394         ac->oc[1].layout_map_tags = tags;
395     }
396
397     // Try to sniff a reasonable channel order, otherwise output the
398     // channels in the order the PCE declared them.
399     if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
400         layout = sniff_channel_order(layout_map, tags);
401     for (i = 0; i < tags; i++) {
402         int type =     layout_map[i][0];
403         int id =       layout_map[i][1];
404         int position = layout_map[i][2];
405         // Allocate or free elements depending on if they are in the
406         // current program configuration.
407         ret = che_configure(ac, position, type, id, &channels);
408         if (ret < 0)
409             return ret;
410     }
411     if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
412         if (layout == AV_CH_FRONT_CENTER) {
413             layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
414         } else {
415             layout = 0;
416         }
417     }
418
419     memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
420     if (layout) avctx->channel_layout = layout;
421     ac->oc[1].channel_layout = layout;
422     avctx->channels = ac->oc[1].channels = channels;
423     ac->oc[1].status = oc_type;
424
425     return 0;
426 }
427
428 static void flush(AVCodecContext *avctx)
429 {
430     AACContext *ac= avctx->priv_data;
431     int type, i, j;
432
433     for (type = 3; type >= 0; type--) {
434         for (i = 0; i < MAX_ELEM_ID; i++) {
435             ChannelElement *che = ac->che[type][i];
436             if (che) {
437                 for (j = 0; j <= 1; j++) {
438                     memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
439                 }
440             }
441         }
442     }
443 }
444
445 /**
446  * Set up channel positions based on a default channel configuration
447  * as specified in table 1.17.
448  *
449  * @return  Returns error status. 0 - OK, !0 - error
450  */
451 static int set_default_channel_config(AVCodecContext *avctx,
452                                               uint8_t (*layout_map)[3],
453                                               int *tags,
454                                               int channel_config)
455 {
456     if (channel_config < 1 || channel_config > 7) {
457         av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
458                channel_config);
459         return -1;
460     }
461     *tags = tags_per_config[channel_config];
462     memcpy(layout_map, aac_channel_layout_map[channel_config-1], *tags * sizeof(*layout_map));
463     return 0;
464 }
465
466 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
467 {
468     // For PCE based channel configurations map the channels solely based on tags.
469     if (!ac->oc[1].m4ac.chan_config) {
470         return ac->tag_che_map[type][elem_id];
471     }
472     // Allow single CPE stereo files to be signalled with mono configuration.
473     if (!ac->tags_mapped && type == TYPE_CPE && ac->oc[1].m4ac.chan_config == 1) {
474         uint8_t layout_map[MAX_ELEM_ID*4][3];
475         int layout_map_tags;
476         push_output_configuration(ac);
477
478         av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
479
480         if (set_default_channel_config(ac->avctx, layout_map, &layout_map_tags,
481                                        2) < 0)
482             return NULL;
483         if (output_configure(ac, layout_map, layout_map_tags,
484                              OC_TRIAL_FRAME) < 0)
485             return NULL;
486
487         ac->oc[1].m4ac.chan_config = 2;
488         ac->oc[1].m4ac.ps = 0;
489     }
490     // And vice-versa
491     if (!ac->tags_mapped && type == TYPE_SCE && ac->oc[1].m4ac.chan_config == 2) {
492         uint8_t layout_map[MAX_ELEM_ID*4][3];
493         int layout_map_tags;
494         push_output_configuration(ac);
495
496         av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
497
498         if (set_default_channel_config(ac->avctx, layout_map, &layout_map_tags,
499                                        1) < 0)
500             return NULL;
501         if (output_configure(ac, layout_map, layout_map_tags,
502                              OC_TRIAL_FRAME) < 0)
503             return NULL;
504
505         ac->oc[1].m4ac.chan_config = 1;
506         if (ac->oc[1].m4ac.sbr)
507             ac->oc[1].m4ac.ps = -1;
508     }
509     // For indexed channel configurations map the channels solely based on position.
510     switch (ac->oc[1].m4ac.chan_config) {
511     case 7:
512         if (ac->tags_mapped == 3 && type == TYPE_CPE) {
513             ac->tags_mapped++;
514             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
515         }
516     case 6:
517         /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
518            instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
519            encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
520         if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
521             ac->tags_mapped++;
522             return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
523         }
524     case 5:
525         if (ac->tags_mapped == 2 && type == TYPE_CPE) {
526             ac->tags_mapped++;
527             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
528         }
529     case 4:
530         if (ac->tags_mapped == 2 && ac->oc[1].m4ac.chan_config == 4 && type == TYPE_SCE) {
531             ac->tags_mapped++;
532             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
533         }
534     case 3:
535     case 2:
536         if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) && type == TYPE_CPE) {
537             ac->tags_mapped++;
538             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
539         } else if (ac->oc[1].m4ac.chan_config == 2) {
540             return NULL;
541         }
542     case 1:
543         if (!ac->tags_mapped && type == TYPE_SCE) {
544             ac->tags_mapped++;
545             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
546         }
547     default:
548         return NULL;
549     }
550 }
551
552 /**
553  * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
554  *
555  * @param type speaker type/position for these channels
556  */
557 static void decode_channel_map(uint8_t layout_map[][3],
558                                enum ChannelPosition type,
559                                GetBitContext *gb, int n)
560 {
561     while (n--) {
562         enum RawDataBlockType syn_ele;
563         switch (type) {
564         case AAC_CHANNEL_FRONT:
565         case AAC_CHANNEL_BACK:
566         case AAC_CHANNEL_SIDE:
567             syn_ele = get_bits1(gb);
568             break;
569         case AAC_CHANNEL_CC:
570             skip_bits1(gb);
571             syn_ele = TYPE_CCE;
572             break;
573         case AAC_CHANNEL_LFE:
574             syn_ele = TYPE_LFE;
575             break;
576         default:
577             av_assert0(0);
578         }
579         layout_map[0][0] = syn_ele;
580         layout_map[0][1] = get_bits(gb, 4);
581         layout_map[0][2] = type;
582         layout_map++;
583     }
584 }
585
586 /**
587  * Decode program configuration element; reference: table 4.2.
588  *
589  * @return  Returns error status. 0 - OK, !0 - error
590  */
591 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
592                       uint8_t (*layout_map)[3],
593                       GetBitContext *gb)
594 {
595     int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
596     int comment_len;
597     int tags;
598
599     skip_bits(gb, 2);  // object_type
600
601     sampling_index = get_bits(gb, 4);
602     if (m4ac->sampling_index != sampling_index)
603         av_log(avctx, AV_LOG_WARNING, "Sample rate index in program config element does not match the sample rate index configured by the container.\n");
604
605     num_front       = get_bits(gb, 4);
606     num_side        = get_bits(gb, 4);
607     num_back        = get_bits(gb, 4);
608     num_lfe         = get_bits(gb, 2);
609     num_assoc_data  = get_bits(gb, 3);
610     num_cc          = get_bits(gb, 4);
611
612     if (get_bits1(gb))
613         skip_bits(gb, 4); // mono_mixdown_tag
614     if (get_bits1(gb))
615         skip_bits(gb, 4); // stereo_mixdown_tag
616
617     if (get_bits1(gb))
618         skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
619
620     if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
621         av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
622         return -1;
623     }
624     decode_channel_map(layout_map       , AAC_CHANNEL_FRONT, gb, num_front);
625     tags = num_front;
626     decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE,  gb, num_side);
627     tags += num_side;
628     decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK,  gb, num_back);
629     tags += num_back;
630     decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE,   gb, num_lfe);
631     tags += num_lfe;
632
633     skip_bits_long(gb, 4 * num_assoc_data);
634
635     decode_channel_map(layout_map + tags, AAC_CHANNEL_CC,    gb, num_cc);
636     tags += num_cc;
637
638     align_get_bits(gb);
639
640     /* comment field, first byte is length */
641     comment_len = get_bits(gb, 8) * 8;
642     if (get_bits_left(gb) < comment_len) {
643         av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
644         return -1;
645     }
646     skip_bits_long(gb, comment_len);
647     return tags;
648 }
649
650 /**
651  * Decode GA "General Audio" specific configuration; reference: table 4.1.
652  *
653  * @param   ac          pointer to AACContext, may be null
654  * @param   avctx       pointer to AVCCodecContext, used for logging
655  *
656  * @return  Returns error status. 0 - OK, !0 - error
657  */
658 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
659                                      GetBitContext *gb,
660                                      MPEG4AudioConfig *m4ac,
661                                      int channel_config)
662 {
663     int extension_flag, ret;
664     uint8_t layout_map[MAX_ELEM_ID*4][3];
665     int tags = 0;
666
667     if (get_bits1(gb)) { // frameLengthFlag
668         av_log_missing_feature(avctx, "960/120 MDCT window", 1);
669         return AVERROR_PATCHWELCOME;
670     }
671
672     if (get_bits1(gb))       // dependsOnCoreCoder
673         skip_bits(gb, 14);   // coreCoderDelay
674     extension_flag = get_bits1(gb);
675
676     if (m4ac->object_type == AOT_AAC_SCALABLE ||
677         m4ac->object_type == AOT_ER_AAC_SCALABLE)
678         skip_bits(gb, 3);     // layerNr
679
680     if (channel_config == 0) {
681         skip_bits(gb, 4);  // element_instance_tag
682         tags = decode_pce(avctx, m4ac, layout_map, gb);
683         if (tags < 0)
684             return tags;
685     } else {
686         if ((ret = set_default_channel_config(avctx, layout_map, &tags, channel_config)))
687             return ret;
688     }
689
690     if (count_channels(layout_map, tags) > 1) {
691         m4ac->ps = 0;
692     } else if (m4ac->sbr == 1 && m4ac->ps == -1)
693         m4ac->ps = 1;
694
695     if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR)))
696         return ret;
697
698     if (extension_flag) {
699         switch (m4ac->object_type) {
700         case AOT_ER_BSAC:
701             skip_bits(gb, 5);    // numOfSubFrame
702             skip_bits(gb, 11);   // layer_length
703             break;
704         case AOT_ER_AAC_LC:
705         case AOT_ER_AAC_LTP:
706         case AOT_ER_AAC_SCALABLE:
707         case AOT_ER_AAC_LD:
708             skip_bits(gb, 3);  /* aacSectionDataResilienceFlag
709                                     * aacScalefactorDataResilienceFlag
710                                     * aacSpectralDataResilienceFlag
711                                     */
712             break;
713         }
714         skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
715     }
716     return 0;
717 }
718
719 /**
720  * Decode audio specific configuration; reference: table 1.13.
721  *
722  * @param   ac          pointer to AACContext, may be null
723  * @param   avctx       pointer to AVCCodecContext, used for logging
724  * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
725  * @param   data        pointer to buffer holding an audio specific config
726  * @param   bit_size    size of audio specific config or data in bits
727  * @param   sync_extension look for an appended sync extension
728  *
729  * @return  Returns error status or number of consumed bits. <0 - error
730  */
731 static int decode_audio_specific_config(AACContext *ac,
732                                         AVCodecContext *avctx,
733                                         MPEG4AudioConfig *m4ac,
734                                         const uint8_t *data, int bit_size,
735                                         int sync_extension)
736 {
737     GetBitContext gb;
738     int i;
739
740     av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
741     for (i = 0; i < bit_size >> 3; i++)
742          av_dlog(avctx, "%02x ", data[i]);
743     av_dlog(avctx, "\n");
744
745     init_get_bits(&gb, data, bit_size);
746
747     if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
748         return -1;
749     if (m4ac->sampling_index > 12) {
750         av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
751         return -1;
752     }
753
754     skip_bits_long(&gb, i);
755
756     switch (m4ac->object_type) {
757     case AOT_AAC_MAIN:
758     case AOT_AAC_LC:
759     case AOT_AAC_LTP:
760         if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
761             return -1;
762         break;
763     default:
764         av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
765                m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
766         return -1;
767     }
768
769     av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
770             m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
771             m4ac->sample_rate, m4ac->sbr, m4ac->ps);
772
773     return get_bits_count(&gb);
774 }
775
776 /**
777  * linear congruential pseudorandom number generator
778  *
779  * @param   previous_val    pointer to the current state of the generator
780  *
781  * @return  Returns a 32-bit pseudorandom integer
782  */
783 static av_always_inline int lcg_random(unsigned previous_val)
784 {
785     return previous_val * 1664525 + 1013904223;
786 }
787
788 static av_always_inline void reset_predict_state(PredictorState *ps)
789 {
790     ps->r0   = 0.0f;
791     ps->r1   = 0.0f;
792     ps->cor0 = 0.0f;
793     ps->cor1 = 0.0f;
794     ps->var0 = 1.0f;
795     ps->var1 = 1.0f;
796 }
797
798 static void reset_all_predictors(PredictorState *ps)
799 {
800     int i;
801     for (i = 0; i < MAX_PREDICTORS; i++)
802         reset_predict_state(&ps[i]);
803 }
804
805 static int sample_rate_idx (int rate)
806 {
807          if (92017 <= rate) return 0;
808     else if (75132 <= rate) return 1;
809     else if (55426 <= rate) return 2;
810     else if (46009 <= rate) return 3;
811     else if (37566 <= rate) return 4;
812     else if (27713 <= rate) return 5;
813     else if (23004 <= rate) return 6;
814     else if (18783 <= rate) return 7;
815     else if (13856 <= rate) return 8;
816     else if (11502 <= rate) return 9;
817     else if (9391  <= rate) return 10;
818     else                    return 11;
819 }
820
821 static void reset_predictor_group(PredictorState *ps, int group_num)
822 {
823     int i;
824     for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
825         reset_predict_state(&ps[i]);
826 }
827
828 #define AAC_INIT_VLC_STATIC(num, size) \
829     INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
830          ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
831         ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
832         size);
833
834 static av_cold int aac_decode_init(AVCodecContext *avctx)
835 {
836     AACContext *ac = avctx->priv_data;
837     float output_scale_factor;
838
839     ac->avctx = avctx;
840     ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
841
842     if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
843         avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
844         output_scale_factor = 1.0 / 32768.0;
845     } else {
846         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
847         output_scale_factor = 1.0;
848     }
849
850     if (avctx->extradata_size > 0) {
851         if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
852                                          avctx->extradata,
853                                          avctx->extradata_size*8, 1) < 0)
854             return -1;
855     } else {
856         int sr, i;
857         uint8_t layout_map[MAX_ELEM_ID*4][3];
858         int layout_map_tags;
859
860         sr = sample_rate_idx(avctx->sample_rate);
861         ac->oc[1].m4ac.sampling_index = sr;
862         ac->oc[1].m4ac.channels = avctx->channels;
863         ac->oc[1].m4ac.sbr = -1;
864         ac->oc[1].m4ac.ps = -1;
865
866         for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
867             if (ff_mpeg4audio_channels[i] == avctx->channels)
868                 break;
869         if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
870             i = 0;
871         }
872         ac->oc[1].m4ac.chan_config = i;
873
874         if (ac->oc[1].m4ac.chan_config) {
875             int ret = set_default_channel_config(avctx, layout_map,
876                 &layout_map_tags, ac->oc[1].m4ac.chan_config);
877             if (!ret)
878                 output_configure(ac, layout_map, layout_map_tags,
879                                  OC_GLOBAL_HDR);
880             else if (avctx->err_recognition & AV_EF_EXPLODE)
881                 return AVERROR_INVALIDDATA;
882         }
883     }
884
885     AAC_INIT_VLC_STATIC( 0, 304);
886     AAC_INIT_VLC_STATIC( 1, 270);
887     AAC_INIT_VLC_STATIC( 2, 550);
888     AAC_INIT_VLC_STATIC( 3, 300);
889     AAC_INIT_VLC_STATIC( 4, 328);
890     AAC_INIT_VLC_STATIC( 5, 294);
891     AAC_INIT_VLC_STATIC( 6, 306);
892     AAC_INIT_VLC_STATIC( 7, 268);
893     AAC_INIT_VLC_STATIC( 8, 510);
894     AAC_INIT_VLC_STATIC( 9, 366);
895     AAC_INIT_VLC_STATIC(10, 462);
896
897     ff_aac_sbr_init();
898
899     ff_dsputil_init(&ac->dsp, avctx);
900     ff_fmt_convert_init(&ac->fmt_conv, avctx);
901     avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
902
903     ac->random_state = 0x1f2e3d4c;
904
905     ff_aac_tableinit();
906
907     INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
908                     ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
909                     ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
910                     352);
911
912     ff_mdct_init(&ac->mdct,       11, 1, output_scale_factor/1024.0);
913     ff_mdct_init(&ac->mdct_small,  8, 1, output_scale_factor/128.0);
914     ff_mdct_init(&ac->mdct_ltp,   11, 0, -2.0/output_scale_factor);
915     // window initialization
916     ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
917     ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
918     ff_init_ff_sine_windows(10);
919     ff_init_ff_sine_windows( 7);
920
921     cbrt_tableinit();
922
923     avcodec_get_frame_defaults(&ac->frame);
924     avctx->coded_frame = &ac->frame;
925
926     return 0;
927 }
928
929 /**
930  * Skip data_stream_element; reference: table 4.10.
931  */
932 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
933 {
934     int byte_align = get_bits1(gb);
935     int count = get_bits(gb, 8);
936     if (count == 255)
937         count += get_bits(gb, 8);
938     if (byte_align)
939         align_get_bits(gb);
940
941     if (get_bits_left(gb) < 8 * count) {
942         av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
943         return -1;
944     }
945     skip_bits_long(gb, 8 * count);
946     return 0;
947 }
948
949 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
950                              GetBitContext *gb)
951 {
952     int sfb;
953     if (get_bits1(gb)) {
954         ics->predictor_reset_group = get_bits(gb, 5);
955         if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
956             av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
957             return -1;
958         }
959     }
960     for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
961         ics->prediction_used[sfb] = get_bits1(gb);
962     }
963     return 0;
964 }
965
966 /**
967  * Decode Long Term Prediction data; reference: table 4.xx.
968  */
969 static void decode_ltp(LongTermPrediction *ltp,
970                        GetBitContext *gb, uint8_t max_sfb)
971 {
972     int sfb;
973
974     ltp->lag  = get_bits(gb, 11);
975     ltp->coef = ltp_coef[get_bits(gb, 3)];
976     for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
977         ltp->used[sfb] = get_bits1(gb);
978 }
979
980 /**
981  * Decode Individual Channel Stream info; reference: table 4.6.
982  */
983 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
984                            GetBitContext *gb)
985 {
986     if (get_bits1(gb)) {
987         av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
988         return AVERROR_INVALIDDATA;
989     }
990     ics->window_sequence[1] = ics->window_sequence[0];
991     ics->window_sequence[0] = get_bits(gb, 2);
992     ics->use_kb_window[1]   = ics->use_kb_window[0];
993     ics->use_kb_window[0]   = get_bits1(gb);
994     ics->num_window_groups  = 1;
995     ics->group_len[0]       = 1;
996     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
997         int i;
998         ics->max_sfb = get_bits(gb, 4);
999         for (i = 0; i < 7; i++) {
1000             if (get_bits1(gb)) {
1001                 ics->group_len[ics->num_window_groups - 1]++;
1002             } else {
1003                 ics->num_window_groups++;
1004                 ics->group_len[ics->num_window_groups - 1] = 1;
1005             }
1006         }
1007         ics->num_windows       = 8;
1008         ics->swb_offset        =    ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1009         ics->num_swb           =   ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1010         ics->tns_max_bands     = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1011         ics->predictor_present = 0;
1012     } else {
1013         ics->max_sfb               = get_bits(gb, 6);
1014         ics->num_windows           = 1;
1015         ics->swb_offset            =    ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1016         ics->num_swb               =   ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1017         ics->tns_max_bands         = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1018         ics->predictor_present     = get_bits1(gb);
1019         ics->predictor_reset_group = 0;
1020         if (ics->predictor_present) {
1021             if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1022                 if (decode_prediction(ac, ics, gb)) {
1023                     goto fail;
1024                 }
1025             } else if (ac->oc[1].m4ac.object_type == AOT_AAC_LC) {
1026                 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
1027                 goto fail;
1028             } else {
1029                 if ((ics->ltp.present = get_bits(gb, 1)))
1030                     decode_ltp(&ics->ltp, gb, ics->max_sfb);
1031             }
1032         }
1033     }
1034
1035     if (ics->max_sfb > ics->num_swb) {
1036         av_log(ac->avctx, AV_LOG_ERROR,
1037                "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
1038                ics->max_sfb, ics->num_swb);
1039         goto fail;
1040     }
1041
1042     return 0;
1043 fail:
1044     ics->max_sfb = 0;
1045     return AVERROR_INVALIDDATA;
1046 }
1047
1048 /**
1049  * Decode band types (section_data payload); reference: table 4.46.
1050  *
1051  * @param   band_type           array of the used band type
1052  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1053  *
1054  * @return  Returns error status. 0 - OK, !0 - error
1055  */
1056 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1057                              int band_type_run_end[120], GetBitContext *gb,
1058                              IndividualChannelStream *ics)
1059 {
1060     int g, idx = 0;
1061     const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1062     for (g = 0; g < ics->num_window_groups; g++) {
1063         int k = 0;
1064         while (k < ics->max_sfb) {
1065             uint8_t sect_end = k;
1066             int sect_len_incr;
1067             int sect_band_type = get_bits(gb, 4);
1068             if (sect_band_type == 12) {
1069                 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1070                 return -1;
1071             }
1072             do {
1073                 sect_len_incr = get_bits(gb, bits);
1074                 sect_end += sect_len_incr;
1075                 if (get_bits_left(gb) < 0) {
1076                     av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1077                     return -1;
1078                 }
1079                 if (sect_end > ics->max_sfb) {
1080                     av_log(ac->avctx, AV_LOG_ERROR,
1081                            "Number of bands (%d) exceeds limit (%d).\n",
1082                            sect_end, ics->max_sfb);
1083                     return -1;
1084                 }
1085             } while (sect_len_incr == (1 << bits) - 1);
1086             for (; k < sect_end; k++) {
1087                 band_type        [idx]   = sect_band_type;
1088                 band_type_run_end[idx++] = sect_end;
1089             }
1090         }
1091     }
1092     return 0;
1093 }
1094
1095 /**
1096  * Decode scalefactors; reference: table 4.47.
1097  *
1098  * @param   global_gain         first scalefactor value as scalefactors are differentially coded
1099  * @param   band_type           array of the used band type
1100  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1101  * @param   sf                  array of scalefactors or intensity stereo positions
1102  *
1103  * @return  Returns error status. 0 - OK, !0 - error
1104  */
1105 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1106                                unsigned int global_gain,
1107                                IndividualChannelStream *ics,
1108                                enum BandType band_type[120],
1109                                int band_type_run_end[120])
1110 {
1111     int g, i, idx = 0;
1112     int offset[3] = { global_gain, global_gain - 90, 0 };
1113     int clipped_offset;
1114     int noise_flag = 1;
1115     for (g = 0; g < ics->num_window_groups; g++) {
1116         for (i = 0; i < ics->max_sfb;) {
1117             int run_end = band_type_run_end[idx];
1118             if (band_type[idx] == ZERO_BT) {
1119                 for (; i < run_end; i++, idx++)
1120                     sf[idx] = 0.;
1121             } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
1122                 for (; i < run_end; i++, idx++) {
1123                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1124                     clipped_offset = av_clip(offset[2], -155, 100);
1125                     if (offset[2] != clipped_offset) {
1126                         av_log_ask_for_sample(ac->avctx, "Intensity stereo "
1127                                 "position clipped (%d -> %d).\nIf you heard an "
1128                                 "audible artifact, there may be a bug in the "
1129                                 "decoder. ", offset[2], clipped_offset);
1130                     }
1131                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1132                 }
1133             } else if (band_type[idx] == NOISE_BT) {
1134                 for (; i < run_end; i++, idx++) {
1135                     if (noise_flag-- > 0)
1136                         offset[1] += get_bits(gb, 9) - 256;
1137                     else
1138                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1139                     clipped_offset = av_clip(offset[1], -100, 155);
1140                     if (offset[1] != clipped_offset) {
1141                         av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
1142                                 "(%d -> %d).\nIf you heard an audible "
1143                                 "artifact, there may be a bug in the decoder. ",
1144                                 offset[1], clipped_offset);
1145                     }
1146                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1147                 }
1148             } else {
1149                 for (; i < run_end; i++, idx++) {
1150                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1151                     if (offset[0] > 255U) {
1152                         av_log(ac->avctx, AV_LOG_ERROR,
1153                                "Scalefactor (%d) out of range.\n", offset[0]);
1154                         return -1;
1155                     }
1156                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1157                 }
1158             }
1159         }
1160     }
1161     return 0;
1162 }
1163
1164 /**
1165  * Decode pulse data; reference: table 4.7.
1166  */
1167 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1168                          const uint16_t *swb_offset, int num_swb)
1169 {
1170     int i, pulse_swb;
1171     pulse->num_pulse = get_bits(gb, 2) + 1;
1172     pulse_swb        = get_bits(gb, 6);
1173     if (pulse_swb >= num_swb)
1174         return -1;
1175     pulse->pos[0]    = swb_offset[pulse_swb];
1176     pulse->pos[0]   += get_bits(gb, 5);
1177     if (pulse->pos[0] > 1023)
1178         return -1;
1179     pulse->amp[0]    = get_bits(gb, 4);
1180     for (i = 1; i < pulse->num_pulse; i++) {
1181         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1182         if (pulse->pos[i] > 1023)
1183             return -1;
1184         pulse->amp[i] = get_bits(gb, 4);
1185     }
1186     return 0;
1187 }
1188
1189 /**
1190  * Decode Temporal Noise Shaping data; reference: table 4.48.
1191  *
1192  * @return  Returns error status. 0 - OK, !0 - error
1193  */
1194 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1195                       GetBitContext *gb, const IndividualChannelStream *ics)
1196 {
1197     int w, filt, i, coef_len, coef_res, coef_compress;
1198     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1199     const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1200     for (w = 0; w < ics->num_windows; w++) {
1201         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1202             coef_res = get_bits1(gb);
1203
1204             for (filt = 0; filt < tns->n_filt[w]; filt++) {
1205                 int tmp2_idx;
1206                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1207
1208                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1209                     av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
1210                            tns->order[w][filt], tns_max_order);
1211                     tns->order[w][filt] = 0;
1212                     return -1;
1213                 }
1214                 if (tns->order[w][filt]) {
1215                     tns->direction[w][filt] = get_bits1(gb);
1216                     coef_compress = get_bits1(gb);
1217                     coef_len = coef_res + 3 - coef_compress;
1218                     tmp2_idx = 2 * coef_compress + coef_res;
1219
1220                     for (i = 0; i < tns->order[w][filt]; i++)
1221                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1222                 }
1223             }
1224         }
1225     }
1226     return 0;
1227 }
1228
1229 /**
1230  * Decode Mid/Side data; reference: table 4.54.
1231  *
1232  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1233  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1234  *                      [3] reserved for scalable AAC
1235  */
1236 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1237                                    int ms_present)
1238 {
1239     int idx;
1240     if (ms_present == 1) {
1241         for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
1242             cpe->ms_mask[idx] = get_bits1(gb);
1243     } else if (ms_present == 2) {
1244         memset(cpe->ms_mask, 1,  sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1245     }
1246 }
1247
1248 #ifndef VMUL2
1249 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1250                            const float *scale)
1251 {
1252     float s = *scale;
1253     *dst++ = v[idx    & 15] * s;
1254     *dst++ = v[idx>>4 & 15] * s;
1255     return dst;
1256 }
1257 #endif
1258
1259 #ifndef VMUL4
1260 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1261                            const float *scale)
1262 {
1263     float s = *scale;
1264     *dst++ = v[idx    & 3] * s;
1265     *dst++ = v[idx>>2 & 3] * s;
1266     *dst++ = v[idx>>4 & 3] * s;
1267     *dst++ = v[idx>>6 & 3] * s;
1268     return dst;
1269 }
1270 #endif
1271
1272 #ifndef VMUL2S
1273 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1274                             unsigned sign, const float *scale)
1275 {
1276     union av_intfloat32 s0, s1;
1277
1278     s0.f = s1.f = *scale;
1279     s0.i ^= sign >> 1 << 31;
1280     s1.i ^= sign      << 31;
1281
1282     *dst++ = v[idx    & 15] * s0.f;
1283     *dst++ = v[idx>>4 & 15] * s1.f;
1284
1285     return dst;
1286 }
1287 #endif
1288
1289 #ifndef VMUL4S
1290 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1291                             unsigned sign, const float *scale)
1292 {
1293     unsigned nz = idx >> 12;
1294     union av_intfloat32 s = { .f = *scale };
1295     union av_intfloat32 t;
1296
1297     t.i = s.i ^ (sign & 1U<<31);
1298     *dst++ = v[idx    & 3] * t.f;
1299
1300     sign <<= nz & 1; nz >>= 1;
1301     t.i = s.i ^ (sign & 1U<<31);
1302     *dst++ = v[idx>>2 & 3] * t.f;
1303
1304     sign <<= nz & 1; nz >>= 1;
1305     t.i = s.i ^ (sign & 1U<<31);
1306     *dst++ = v[idx>>4 & 3] * t.f;
1307
1308     sign <<= nz & 1;
1309     t.i = s.i ^ (sign & 1U<<31);
1310     *dst++ = v[idx>>6 & 3] * t.f;
1311
1312     return dst;
1313 }
1314 #endif
1315
1316 /**
1317  * Decode spectral data; reference: table 4.50.
1318  * Dequantize and scale spectral data; reference: 4.6.3.3.
1319  *
1320  * @param   coef            array of dequantized, scaled spectral data
1321  * @param   sf              array of scalefactors or intensity stereo positions
1322  * @param   pulse_present   set if pulses are present
1323  * @param   pulse           pointer to pulse data struct
1324  * @param   band_type       array of the used band type
1325  *
1326  * @return  Returns error status. 0 - OK, !0 - error
1327  */
1328 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1329                                        GetBitContext *gb, const float sf[120],
1330                                        int pulse_present, const Pulse *pulse,
1331                                        const IndividualChannelStream *ics,
1332                                        enum BandType band_type[120])
1333 {
1334     int i, k, g, idx = 0;
1335     const int c = 1024 / ics->num_windows;
1336     const uint16_t *offsets = ics->swb_offset;
1337     float *coef_base = coef;
1338
1339     for (g = 0; g < ics->num_windows; g++)
1340         memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1341
1342     for (g = 0; g < ics->num_window_groups; g++) {
1343         unsigned g_len = ics->group_len[g];
1344
1345         for (i = 0; i < ics->max_sfb; i++, idx++) {
1346             const unsigned cbt_m1 = band_type[idx] - 1;
1347             float *cfo = coef + offsets[i];
1348             int off_len = offsets[i + 1] - offsets[i];
1349             int group;
1350
1351             if (cbt_m1 >= INTENSITY_BT2 - 1) {
1352                 for (group = 0; group < g_len; group++, cfo+=128) {
1353                     memset(cfo, 0, off_len * sizeof(float));
1354                 }
1355             } else if (cbt_m1 == NOISE_BT - 1) {
1356                 for (group = 0; group < g_len; group++, cfo+=128) {
1357                     float scale;
1358                     float band_energy;
1359
1360                     for (k = 0; k < off_len; k++) {
1361                         ac->random_state  = lcg_random(ac->random_state);
1362                         cfo[k] = ac->random_state;
1363                     }
1364
1365                     band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1366                     scale = sf[idx] / sqrtf(band_energy);
1367                     ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1368                 }
1369             } else {
1370                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1371                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1372                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1373                 OPEN_READER(re, gb);
1374
1375                 switch (cbt_m1 >> 1) {
1376                 case 0:
1377                     for (group = 0; group < g_len; group++, cfo+=128) {
1378                         float *cf = cfo;
1379                         int len = off_len;
1380
1381                         do {
1382                             int code;
1383                             unsigned cb_idx;
1384
1385                             UPDATE_CACHE(re, gb);
1386                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1387                             cb_idx = cb_vector_idx[code];
1388                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
1389                         } while (len -= 4);
1390                     }
1391                     break;
1392
1393                 case 1:
1394                     for (group = 0; group < g_len; group++, cfo+=128) {
1395                         float *cf = cfo;
1396                         int len = off_len;
1397
1398                         do {
1399                             int code;
1400                             unsigned nnz;
1401                             unsigned cb_idx;
1402                             uint32_t bits;
1403
1404                             UPDATE_CACHE(re, gb);
1405                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1406                             cb_idx = cb_vector_idx[code];
1407                             nnz = cb_idx >> 8 & 15;
1408                             bits = nnz ? GET_CACHE(re, gb) : 0;
1409                             LAST_SKIP_BITS(re, gb, nnz);
1410                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1411                         } while (len -= 4);
1412                     }
1413                     break;
1414
1415                 case 2:
1416                     for (group = 0; group < g_len; group++, cfo+=128) {
1417                         float *cf = cfo;
1418                         int len = off_len;
1419
1420                         do {
1421                             int code;
1422                             unsigned cb_idx;
1423
1424                             UPDATE_CACHE(re, gb);
1425                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1426                             cb_idx = cb_vector_idx[code];
1427                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
1428                         } while (len -= 2);
1429                     }
1430                     break;
1431
1432                 case 3:
1433                 case 4:
1434                     for (group = 0; group < g_len; group++, cfo+=128) {
1435                         float *cf = cfo;
1436                         int len = off_len;
1437
1438                         do {
1439                             int code;
1440                             unsigned nnz;
1441                             unsigned cb_idx;
1442                             unsigned sign;
1443
1444                             UPDATE_CACHE(re, gb);
1445                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1446                             cb_idx = cb_vector_idx[code];
1447                             nnz = cb_idx >> 8 & 15;
1448                             sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1449                             LAST_SKIP_BITS(re, gb, nnz);
1450                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1451                         } while (len -= 2);
1452                     }
1453                     break;
1454
1455                 default:
1456                     for (group = 0; group < g_len; group++, cfo+=128) {
1457                         float *cf = cfo;
1458                         uint32_t *icf = (uint32_t *) cf;
1459                         int len = off_len;
1460
1461                         do {
1462                             int code;
1463                             unsigned nzt, nnz;
1464                             unsigned cb_idx;
1465                             uint32_t bits;
1466                             int j;
1467
1468                             UPDATE_CACHE(re, gb);
1469                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1470
1471                             if (!code) {
1472                                 *icf++ = 0;
1473                                 *icf++ = 0;
1474                                 continue;
1475                             }
1476
1477                             cb_idx = cb_vector_idx[code];
1478                             nnz = cb_idx >> 12;
1479                             nzt = cb_idx >> 8;
1480                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1481                             LAST_SKIP_BITS(re, gb, nnz);
1482
1483                             for (j = 0; j < 2; j++) {
1484                                 if (nzt & 1<<j) {
1485                                     uint32_t b;
1486                                     int n;
1487                                     /* The total length of escape_sequence must be < 22 bits according
1488                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1489                                     UPDATE_CACHE(re, gb);
1490                                     b = GET_CACHE(re, gb);
1491                                     b = 31 - av_log2(~b);
1492
1493                                     if (b > 8) {
1494                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1495                                         return -1;
1496                                     }
1497
1498                                     SKIP_BITS(re, gb, b + 1);
1499                                     b += 4;
1500                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
1501                                     LAST_SKIP_BITS(re, gb, b);
1502                                     *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1503                                     bits <<= 1;
1504                                 } else {
1505                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1506                                     *icf++ = (bits & 1U<<31) | v;
1507                                     bits <<= !!v;
1508                                 }
1509                                 cb_idx >>= 4;
1510                             }
1511                         } while (len -= 2);
1512
1513                         ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1514                     }
1515                 }
1516
1517                 CLOSE_READER(re, gb);
1518             }
1519         }
1520         coef += g_len << 7;
1521     }
1522
1523     if (pulse_present) {
1524         idx = 0;
1525         for (i = 0; i < pulse->num_pulse; i++) {
1526             float co = coef_base[ pulse->pos[i] ];
1527             while (offsets[idx + 1] <= pulse->pos[i])
1528                 idx++;
1529             if (band_type[idx] != NOISE_BT && sf[idx]) {
1530                 float ico = -pulse->amp[i];
1531                 if (co) {
1532                     co /= sf[idx];
1533                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1534                 }
1535                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1536             }
1537         }
1538     }
1539     return 0;
1540 }
1541
1542 static av_always_inline float flt16_round(float pf)
1543 {
1544     union av_intfloat32 tmp;
1545     tmp.f = pf;
1546     tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1547     return tmp.f;
1548 }
1549
1550 static av_always_inline float flt16_even(float pf)
1551 {
1552     union av_intfloat32 tmp;
1553     tmp.f = pf;
1554     tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1555     return tmp.f;
1556 }
1557
1558 static av_always_inline float flt16_trunc(float pf)
1559 {
1560     union av_intfloat32 pun;
1561     pun.f = pf;
1562     pun.i &= 0xFFFF0000U;
1563     return pun.f;
1564 }
1565
1566 static av_always_inline void predict(PredictorState *ps, float *coef,
1567                                      int output_enable)
1568 {
1569     const float a     = 0.953125; // 61.0 / 64
1570     const float alpha = 0.90625;  // 29.0 / 32
1571     float e0, e1;
1572     float pv;
1573     float k1, k2;
1574     float   r0 = ps->r0,     r1 = ps->r1;
1575     float cor0 = ps->cor0, cor1 = ps->cor1;
1576     float var0 = ps->var0, var1 = ps->var1;
1577
1578     k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1579     k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1580
1581     pv = flt16_round(k1 * r0 + k2 * r1);
1582     if (output_enable)
1583         *coef += pv;
1584
1585     e0 = *coef;
1586     e1 = e0 - k1 * r0;
1587
1588     ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1589     ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1590     ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1591     ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1592
1593     ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1594     ps->r0 = flt16_trunc(a * e0);
1595 }
1596
1597 /**
1598  * Apply AAC-Main style frequency domain prediction.
1599  */
1600 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1601 {
1602     int sfb, k;
1603
1604     if (!sce->ics.predictor_initialized) {
1605         reset_all_predictors(sce->predictor_state);
1606         sce->ics.predictor_initialized = 1;
1607     }
1608
1609     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1610         for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]; sfb++) {
1611             for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1612                 predict(&sce->predictor_state[k], &sce->coeffs[k],
1613                         sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1614             }
1615         }
1616         if (sce->ics.predictor_reset_group)
1617             reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1618     } else
1619         reset_all_predictors(sce->predictor_state);
1620 }
1621
1622 /**
1623  * Decode an individual_channel_stream payload; reference: table 4.44.
1624  *
1625  * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
1626  * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1627  *
1628  * @return  Returns error status. 0 - OK, !0 - error
1629  */
1630 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1631                       GetBitContext *gb, int common_window, int scale_flag)
1632 {
1633     Pulse pulse;
1634     TemporalNoiseShaping    *tns = &sce->tns;
1635     IndividualChannelStream *ics = &sce->ics;
1636     float *out = sce->coeffs;
1637     int global_gain, pulse_present = 0;
1638
1639     /* This assignment is to silence a GCC warning about the variable being used
1640      * uninitialized when in fact it always is.
1641      */
1642     pulse.num_pulse = 0;
1643
1644     global_gain = get_bits(gb, 8);
1645
1646     if (!common_window && !scale_flag) {
1647         if (decode_ics_info(ac, ics, gb) < 0)
1648             return AVERROR_INVALIDDATA;
1649     }
1650
1651     if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1652         return -1;
1653     if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1654         return -1;
1655
1656     pulse_present = 0;
1657     if (!scale_flag) {
1658         if ((pulse_present = get_bits1(gb))) {
1659             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1660                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1661                 return -1;
1662             }
1663             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1664                 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1665                 return -1;
1666             }
1667         }
1668         if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1669             return -1;
1670         if (get_bits1(gb)) {
1671             av_log_missing_feature(ac->avctx, "SSR", 1);
1672             return AVERROR_PATCHWELCOME;
1673         }
1674     }
1675
1676     if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1677         return -1;
1678
1679     if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1680         apply_prediction(ac, sce);
1681
1682     return 0;
1683 }
1684
1685 /**
1686  * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1687  */
1688 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1689 {
1690     const IndividualChannelStream *ics = &cpe->ch[0].ics;
1691     float *ch0 = cpe->ch[0].coeffs;
1692     float *ch1 = cpe->ch[1].coeffs;
1693     int g, i, group, idx = 0;
1694     const uint16_t *offsets = ics->swb_offset;
1695     for (g = 0; g < ics->num_window_groups; g++) {
1696         for (i = 0; i < ics->max_sfb; i++, idx++) {
1697             if (cpe->ms_mask[idx] &&
1698                     cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1699                 for (group = 0; group < ics->group_len[g]; group++) {
1700                     ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1701                                               ch1 + group * 128 + offsets[i],
1702                                               offsets[i+1] - offsets[i]);
1703                 }
1704             }
1705         }
1706         ch0 += ics->group_len[g] * 128;
1707         ch1 += ics->group_len[g] * 128;
1708     }
1709 }
1710
1711 /**
1712  * intensity stereo decoding; reference: 4.6.8.2.3
1713  *
1714  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1715  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1716  *                      [3] reserved for scalable AAC
1717  */
1718 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
1719 {
1720     const IndividualChannelStream *ics = &cpe->ch[1].ics;
1721     SingleChannelElement         *sce1 = &cpe->ch[1];
1722     float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1723     const uint16_t *offsets = ics->swb_offset;
1724     int g, group, i, idx = 0;
1725     int c;
1726     float scale;
1727     for (g = 0; g < ics->num_window_groups; g++) {
1728         for (i = 0; i < ics->max_sfb;) {
1729             if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1730                 const int bt_run_end = sce1->band_type_run_end[idx];
1731                 for (; i < bt_run_end; i++, idx++) {
1732                     c = -1 + 2 * (sce1->band_type[idx] - 14);
1733                     if (ms_present)
1734                         c *= 1 - 2 * cpe->ms_mask[idx];
1735                     scale = c * sce1->sf[idx];
1736                     for (group = 0; group < ics->group_len[g]; group++)
1737                         ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1738                                                    coef0 + group * 128 + offsets[i],
1739                                                    scale,
1740                                                    offsets[i + 1] - offsets[i]);
1741                 }
1742             } else {
1743                 int bt_run_end = sce1->band_type_run_end[idx];
1744                 idx += bt_run_end - i;
1745                 i    = bt_run_end;
1746             }
1747         }
1748         coef0 += ics->group_len[g] * 128;
1749         coef1 += ics->group_len[g] * 128;
1750     }
1751 }
1752
1753 /**
1754  * Decode a channel_pair_element; reference: table 4.4.
1755  *
1756  * @return  Returns error status. 0 - OK, !0 - error
1757  */
1758 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1759 {
1760     int i, ret, common_window, ms_present = 0;
1761
1762     common_window = get_bits1(gb);
1763     if (common_window) {
1764         if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1765             return AVERROR_INVALIDDATA;
1766         i = cpe->ch[1].ics.use_kb_window[0];
1767         cpe->ch[1].ics = cpe->ch[0].ics;
1768         cpe->ch[1].ics.use_kb_window[1] = i;
1769         if (cpe->ch[1].ics.predictor_present && (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1770             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1771                 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1772         ms_present = get_bits(gb, 2);
1773         if (ms_present == 3) {
1774             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1775             return -1;
1776         } else if (ms_present)
1777             decode_mid_side_stereo(cpe, gb, ms_present);
1778     }
1779     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1780         return ret;
1781     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1782         return ret;
1783
1784     if (common_window) {
1785         if (ms_present)
1786             apply_mid_side_stereo(ac, cpe);
1787         if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1788             apply_prediction(ac, &cpe->ch[0]);
1789             apply_prediction(ac, &cpe->ch[1]);
1790         }
1791     }
1792
1793     apply_intensity_stereo(ac, cpe, ms_present);
1794     return 0;
1795 }
1796
1797 static const float cce_scale[] = {
1798     1.09050773266525765921, //2^(1/8)
1799     1.18920711500272106672, //2^(1/4)
1800     M_SQRT2,
1801     2,
1802 };
1803
1804 /**
1805  * Decode coupling_channel_element; reference: table 4.8.
1806  *
1807  * @return  Returns error status. 0 - OK, !0 - error
1808  */
1809 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1810 {
1811     int num_gain = 0;
1812     int c, g, sfb, ret;
1813     int sign;
1814     float scale;
1815     SingleChannelElement *sce = &che->ch[0];
1816     ChannelCoupling     *coup = &che->coup;
1817
1818     coup->coupling_point = 2 * get_bits1(gb);
1819     coup->num_coupled = get_bits(gb, 3);
1820     for (c = 0; c <= coup->num_coupled; c++) {
1821         num_gain++;
1822         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1823         coup->id_select[c] = get_bits(gb, 4);
1824         if (coup->type[c] == TYPE_CPE) {
1825             coup->ch_select[c] = get_bits(gb, 2);
1826             if (coup->ch_select[c] == 3)
1827                 num_gain++;
1828         } else
1829             coup->ch_select[c] = 2;
1830     }
1831     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1832
1833     sign  = get_bits(gb, 1);
1834     scale = cce_scale[get_bits(gb, 2)];
1835
1836     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1837         return ret;
1838
1839     for (c = 0; c < num_gain; c++) {
1840         int idx  = 0;
1841         int cge  = 1;
1842         int gain = 0;
1843         float gain_cache = 1.;
1844         if (c) {
1845             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1846             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1847             gain_cache = powf(scale, -gain);
1848         }
1849         if (coup->coupling_point == AFTER_IMDCT) {
1850             coup->gain[c][0] = gain_cache;
1851         } else {
1852             for (g = 0; g < sce->ics.num_window_groups; g++) {
1853                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1854                     if (sce->band_type[idx] != ZERO_BT) {
1855                         if (!cge) {
1856                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1857                             if (t) {
1858                                 int s = 1;
1859                                 t = gain += t;
1860                                 if (sign) {
1861                                     s  -= 2 * (t & 0x1);
1862                                     t >>= 1;
1863                                 }
1864                                 gain_cache = powf(scale, -t) * s;
1865                             }
1866                         }
1867                         coup->gain[c][idx] = gain_cache;
1868                     }
1869                 }
1870             }
1871         }
1872     }
1873     return 0;
1874 }
1875
1876 /**
1877  * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1878  *
1879  * @return  Returns number of bytes consumed.
1880  */
1881 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1882                                          GetBitContext *gb)
1883 {
1884     int i;
1885     int num_excl_chan = 0;
1886
1887     do {
1888         for (i = 0; i < 7; i++)
1889             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1890     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1891
1892     return num_excl_chan / 7;
1893 }
1894
1895 /**
1896  * Decode dynamic range information; reference: table 4.52.
1897  *
1898  * @return  Returns number of bytes consumed.
1899  */
1900 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1901                                 GetBitContext *gb)
1902 {
1903     int n             = 1;
1904     int drc_num_bands = 1;
1905     int i;
1906
1907     /* pce_tag_present? */
1908     if (get_bits1(gb)) {
1909         che_drc->pce_instance_tag  = get_bits(gb, 4);
1910         skip_bits(gb, 4); // tag_reserved_bits
1911         n++;
1912     }
1913
1914     /* excluded_chns_present? */
1915     if (get_bits1(gb)) {
1916         n += decode_drc_channel_exclusions(che_drc, gb);
1917     }
1918
1919     /* drc_bands_present? */
1920     if (get_bits1(gb)) {
1921         che_drc->band_incr            = get_bits(gb, 4);
1922         che_drc->interpolation_scheme = get_bits(gb, 4);
1923         n++;
1924         drc_num_bands += che_drc->band_incr;
1925         for (i = 0; i < drc_num_bands; i++) {
1926             che_drc->band_top[i] = get_bits(gb, 8);
1927             n++;
1928         }
1929     }
1930
1931     /* prog_ref_level_present? */
1932     if (get_bits1(gb)) {
1933         che_drc->prog_ref_level = get_bits(gb, 7);
1934         skip_bits1(gb); // prog_ref_level_reserved_bits
1935         n++;
1936     }
1937
1938     for (i = 0; i < drc_num_bands; i++) {
1939         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1940         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1941         n++;
1942     }
1943
1944     return n;
1945 }
1946
1947 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
1948     uint8_t buf[256];
1949     int i, major, minor;
1950
1951     if (len < 13+7*8)
1952         goto unknown;
1953
1954     get_bits(gb, 13); len -= 13;
1955
1956     for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
1957         buf[i] = get_bits(gb, 8);
1958
1959     buf[i] = 0;
1960     if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
1961         av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
1962
1963     if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
1964         ac->avctx->internal->skip_samples = 1024;
1965     }
1966
1967 unknown:
1968     skip_bits_long(gb, len);
1969
1970     return 0;
1971 }
1972
1973 /**
1974  * Decode extension data (incomplete); reference: table 4.51.
1975  *
1976  * @param   cnt length of TYPE_FIL syntactic element in bytes
1977  *
1978  * @return Returns number of bytes consumed
1979  */
1980 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1981                                     ChannelElement *che, enum RawDataBlockType elem_type)
1982 {
1983     int crc_flag = 0;
1984     int res = cnt;
1985     switch (get_bits(gb, 4)) { // extension type
1986     case EXT_SBR_DATA_CRC:
1987         crc_flag++;
1988     case EXT_SBR_DATA:
1989         if (!che) {
1990             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1991             return res;
1992         } else if (!ac->oc[1].m4ac.sbr) {
1993             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1994             skip_bits_long(gb, 8 * cnt - 4);
1995             return res;
1996         } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
1997             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1998             skip_bits_long(gb, 8 * cnt - 4);
1999             return res;
2000         } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2001             ac->oc[1].m4ac.sbr = 1;
2002             ac->oc[1].m4ac.ps = 1;
2003             output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2004                              ac->oc[1].status);
2005         } else {
2006             ac->oc[1].m4ac.sbr = 1;
2007         }
2008         res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2009         break;
2010     case EXT_DYNAMIC_RANGE:
2011         res = decode_dynamic_range(&ac->che_drc, gb);
2012         break;
2013     case EXT_FILL:
2014         decode_fill(ac, gb, 8 * cnt - 4);
2015         break;
2016     case EXT_FILL_DATA:
2017     case EXT_DATA_ELEMENT:
2018     default:
2019         skip_bits_long(gb, 8 * cnt - 4);
2020         break;
2021     };
2022     return res;
2023 }
2024
2025 /**
2026  * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2027  *
2028  * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
2029  * @param   coef    spectral coefficients
2030  */
2031 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2032                       IndividualChannelStream *ics, int decode)
2033 {
2034     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2035     int w, filt, m, i;
2036     int bottom, top, order, start, end, size, inc;
2037     float lpc[TNS_MAX_ORDER];
2038     float tmp[TNS_MAX_ORDER+1];
2039
2040     for (w = 0; w < ics->num_windows; w++) {
2041         bottom = ics->num_swb;
2042         for (filt = 0; filt < tns->n_filt[w]; filt++) {
2043             top    = bottom;
2044             bottom = FFMAX(0, top - tns->length[w][filt]);
2045             order  = tns->order[w][filt];
2046             if (order == 0)
2047                 continue;
2048
2049             // tns_decode_coef
2050             compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2051
2052             start = ics->swb_offset[FFMIN(bottom, mmm)];
2053             end   = ics->swb_offset[FFMIN(   top, mmm)];
2054             if ((size = end - start) <= 0)
2055                 continue;
2056             if (tns->direction[w][filt]) {
2057                 inc = -1;
2058                 start = end - 1;
2059             } else {
2060                 inc = 1;
2061             }
2062             start += w * 128;
2063
2064             if (decode) {
2065                 // ar filter
2066                 for (m = 0; m < size; m++, start += inc)
2067                     for (i = 1; i <= FFMIN(m, order); i++)
2068                         coef[start] -= coef[start - i * inc] * lpc[i - 1];
2069             } else {
2070                 // ma filter
2071                 for (m = 0; m < size; m++, start += inc) {
2072                     tmp[0] = coef[start];
2073                     for (i = 1; i <= FFMIN(m, order); i++)
2074                         coef[start] += tmp[i] * lpc[i - 1];
2075                     for (i = order; i > 0; i--)
2076                         tmp[i] = tmp[i - 1];
2077                 }
2078             }
2079         }
2080     }
2081 }
2082
2083 /**
2084  *  Apply windowing and MDCT to obtain the spectral
2085  *  coefficient from the predicted sample by LTP.
2086  */
2087 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2088                                    float *in, IndividualChannelStream *ics)
2089 {
2090     const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2091     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2092     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2093     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2094
2095     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2096         ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2097     } else {
2098         memset(in, 0, 448 * sizeof(float));
2099         ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2100     }
2101     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2102         ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2103     } else {
2104         ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2105         memset(in + 1024 + 576, 0, 448 * sizeof(float));
2106     }
2107     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2108 }
2109
2110 /**
2111  * Apply the long term prediction
2112  */
2113 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2114 {
2115     const LongTermPrediction *ltp = &sce->ics.ltp;
2116     const uint16_t *offsets = sce->ics.swb_offset;
2117     int i, sfb;
2118
2119     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2120         float *predTime = sce->ret;
2121         float *predFreq = ac->buf_mdct;
2122         int16_t num_samples = 2048;
2123
2124         if (ltp->lag < 1024)
2125             num_samples = ltp->lag + 1024;
2126         for (i = 0; i < num_samples; i++)
2127             predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2128         memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2129
2130         windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2131
2132         if (sce->tns.present)
2133             apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2134
2135         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2136             if (ltp->used[sfb])
2137                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2138                     sce->coeffs[i] += predFreq[i];
2139     }
2140 }
2141
2142 /**
2143  * Update the LTP buffer for next frame
2144  */
2145 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2146 {
2147     IndividualChannelStream *ics = &sce->ics;
2148     float *saved     = sce->saved;
2149     float *saved_ltp = sce->coeffs;
2150     const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2151     const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2152     int i;
2153
2154     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2155         memcpy(saved_ltp,       saved, 512 * sizeof(float));
2156         memset(saved_ltp + 576, 0,     448 * sizeof(float));
2157         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2158         for (i = 0; i < 64; i++)
2159             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2160     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2161         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
2162         memset(saved_ltp + 576, 0,                  448 * sizeof(float));
2163         ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2164         for (i = 0; i < 64; i++)
2165             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2166     } else { // LONG_STOP or ONLY_LONG
2167         ac->dsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
2168         for (i = 0; i < 512; i++)
2169             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2170     }
2171
2172     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2173     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
2174     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
2175 }
2176
2177 /**
2178  * Conduct IMDCT and windowing.
2179  */
2180 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2181 {
2182     IndividualChannelStream *ics = &sce->ics;
2183     float *in    = sce->coeffs;
2184     float *out   = sce->ret;
2185     float *saved = sce->saved;
2186     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2187     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2188     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2189     float *buf  = ac->buf_mdct;
2190     float *temp = ac->temp;
2191     int i;
2192
2193     // imdct
2194     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2195         for (i = 0; i < 1024; i += 128)
2196             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2197     } else
2198         ac->mdct.imdct_half(&ac->mdct, buf, in);
2199
2200     /* window overlapping
2201      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2202      * and long to short transitions are considered to be short to short
2203      * transitions. This leaves just two cases (long to long and short to short)
2204      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2205      */
2206     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2207             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2208         ac->dsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
2209     } else {
2210         memcpy(                        out,               saved,            448 * sizeof(float));
2211
2212         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2213             ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
2214             ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
2215             ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
2216             ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
2217             ac->dsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
2218             memcpy(                    out + 448 + 4*128, temp, 64 * sizeof(float));
2219         } else {
2220             ac->dsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
2221             memcpy(                    out + 576,         buf + 64,         448 * sizeof(float));
2222         }
2223     }
2224
2225     // buffer update
2226     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2227         memcpy(                    saved,       temp + 64,         64 * sizeof(float));
2228         ac->dsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
2229         ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2230         ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2231         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2232     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2233         memcpy(                    saved,       buf + 512,        448 * sizeof(float));
2234         memcpy(                    saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2235     } else { // LONG_STOP or ONLY_LONG
2236         memcpy(                    saved,       buf + 512,        512 * sizeof(float));
2237     }
2238 }
2239
2240 /**
2241  * Apply dependent channel coupling (applied before IMDCT).
2242  *
2243  * @param   index   index into coupling gain array
2244  */
2245 static void apply_dependent_coupling(AACContext *ac,
2246                                      SingleChannelElement *target,
2247                                      ChannelElement *cce, int index)
2248 {
2249     IndividualChannelStream *ics = &cce->ch[0].ics;
2250     const uint16_t *offsets = ics->swb_offset;
2251     float *dest = target->coeffs;
2252     const float *src = cce->ch[0].coeffs;
2253     int g, i, group, k, idx = 0;
2254     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2255         av_log(ac->avctx, AV_LOG_ERROR,
2256                "Dependent coupling is not supported together with LTP\n");
2257         return;
2258     }
2259     for (g = 0; g < ics->num_window_groups; g++) {
2260         for (i = 0; i < ics->max_sfb; i++, idx++) {
2261             if (cce->ch[0].band_type[idx] != ZERO_BT) {
2262                 const float gain = cce->coup.gain[index][idx];
2263                 for (group = 0; group < ics->group_len[g]; group++) {
2264                     for (k = offsets[i]; k < offsets[i + 1]; k++) {
2265                         // XXX dsputil-ize
2266                         dest[group * 128 + k] += gain * src[group * 128 + k];
2267                     }
2268                 }
2269             }
2270         }
2271         dest += ics->group_len[g] * 128;
2272         src  += ics->group_len[g] * 128;
2273     }
2274 }
2275
2276 /**
2277  * Apply independent channel coupling (applied after IMDCT).
2278  *
2279  * @param   index   index into coupling gain array
2280  */
2281 static void apply_independent_coupling(AACContext *ac,
2282                                        SingleChannelElement *target,
2283                                        ChannelElement *cce, int index)
2284 {
2285     int i;
2286     const float gain = cce->coup.gain[index][0];
2287     const float *src = cce->ch[0].ret;
2288     float *dest = target->ret;
2289     const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2290
2291     for (i = 0; i < len; i++)
2292         dest[i] += gain * src[i];
2293 }
2294
2295 /**
2296  * channel coupling transformation interface
2297  *
2298  * @param   apply_coupling_method   pointer to (in)dependent coupling function
2299  */
2300 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2301                                    enum RawDataBlockType type, int elem_id,
2302                                    enum CouplingPoint coupling_point,
2303                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2304 {
2305     int i, c;
2306
2307     for (i = 0; i < MAX_ELEM_ID; i++) {
2308         ChannelElement *cce = ac->che[TYPE_CCE][i];
2309         int index = 0;
2310
2311         if (cce && cce->coup.coupling_point == coupling_point) {
2312             ChannelCoupling *coup = &cce->coup;
2313
2314             for (c = 0; c <= coup->num_coupled; c++) {
2315                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2316                     if (coup->ch_select[c] != 1) {
2317                         apply_coupling_method(ac, &cc->ch[0], cce, index);
2318                         if (coup->ch_select[c] != 0)
2319                             index++;
2320                     }
2321                     if (coup->ch_select[c] != 2)
2322                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
2323                 } else
2324                     index += 1 + (coup->ch_select[c] == 3);
2325             }
2326         }
2327     }
2328 }
2329
2330 /**
2331  * Convert spectral data to float samples, applying all supported tools as appropriate.
2332  */
2333 static void spectral_to_sample(AACContext *ac)
2334 {
2335     int i, type;
2336     for (type = 3; type >= 0; type--) {
2337         for (i = 0; i < MAX_ELEM_ID; i++) {
2338             ChannelElement *che = ac->che[type][i];
2339             if (che) {
2340                 if (type <= TYPE_CPE)
2341                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2342                 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2343                     if (che->ch[0].ics.predictor_present) {
2344                         if (che->ch[0].ics.ltp.present)
2345                             apply_ltp(ac, &che->ch[0]);
2346                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2347                             apply_ltp(ac, &che->ch[1]);
2348                     }
2349                 }
2350                 if (che->ch[0].tns.present)
2351                     apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2352                 if (che->ch[1].tns.present)
2353                     apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2354                 if (type <= TYPE_CPE)
2355                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2356                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2357                     imdct_and_windowing(ac, &che->ch[0]);
2358                     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2359                         update_ltp(ac, &che->ch[0]);
2360                     if (type == TYPE_CPE) {
2361                         imdct_and_windowing(ac, &che->ch[1]);
2362                         if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2363                             update_ltp(ac, &che->ch[1]);
2364                     }
2365                     if (ac->oc[1].m4ac.sbr > 0) {
2366                         ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2367                     }
2368                 }
2369                 if (type <= TYPE_CCE)
2370                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2371             }
2372         }
2373     }
2374 }
2375
2376 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2377 {
2378     int size;
2379     AACADTSHeaderInfo hdr_info;
2380     uint8_t layout_map[MAX_ELEM_ID*4][3];
2381     int layout_map_tags;
2382
2383     size = avpriv_aac_parse_header(gb, &hdr_info);
2384     if (size > 0) {
2385         if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2386             // This is 2 for "VLB " audio in NSV files.
2387             // See samples/nsv/vlb_audio.
2388             av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame", 0);
2389             ac->warned_num_aac_frames = 1;
2390         }
2391         push_output_configuration(ac);
2392         if (hdr_info.chan_config) {
2393             ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2394             if (set_default_channel_config(ac->avctx, layout_map,
2395                     &layout_map_tags, hdr_info.chan_config))
2396                 return -7;
2397             if (output_configure(ac, layout_map, layout_map_tags,
2398                                  FFMAX(ac->oc[1].status, OC_TRIAL_FRAME)))
2399                 return -7;
2400         } else {
2401             ac->oc[1].m4ac.chan_config = 0;
2402             /**
2403              * dual mono frames in Japanese DTV can have chan_config 0
2404              * WITHOUT specifying PCE.
2405              *  thus, set dual mono as default.
2406              */
2407             if (ac->enable_jp_dmono && ac->oc[0].status == OC_NONE) {
2408                 layout_map_tags = 2;
2409                 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2410                 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2411                 layout_map[0][1] = 0;
2412                 layout_map[1][1] = 1;
2413                 if (output_configure(ac, layout_map, layout_map_tags,
2414                                      OC_TRIAL_FRAME))
2415                     return -7;
2416             }
2417         }
2418         ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
2419         ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
2420         ac->oc[1].m4ac.object_type     = hdr_info.object_type;
2421         if (ac->oc[0].status != OC_LOCKED ||
2422             ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2423             ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2424             ac->oc[1].m4ac.sbr = -1;
2425             ac->oc[1].m4ac.ps  = -1;
2426         }
2427         if (!hdr_info.crc_absent)
2428             skip_bits(gb, 16);
2429     }
2430     return size;
2431 }
2432
2433 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2434                                 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2435 {
2436     AACContext *ac = avctx->priv_data;
2437     ChannelElement *che = NULL, *che_prev = NULL;
2438     enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2439     int err, elem_id;
2440     int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2441     int is_dmono, sce_count = 0;
2442     float *tmp = NULL;
2443
2444     if (show_bits(gb, 12) == 0xfff) {
2445         if (parse_adts_frame_header(ac, gb) < 0) {
2446             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2447             err = -1;
2448             goto fail;
2449         }
2450         if (ac->oc[1].m4ac.sampling_index > 12) {
2451             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2452             err = -1;
2453             goto fail;
2454         }
2455     }
2456
2457     ac->tags_mapped = 0;
2458     // parse
2459     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2460         elem_id = get_bits(gb, 4);
2461
2462         if (elem_type < TYPE_DSE) {
2463             if (!(che=get_che(ac, elem_type, elem_id))) {
2464                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2465                        elem_type, elem_id);
2466                 err = -1;
2467                 goto fail;
2468             }
2469             samples = 1024;
2470         }
2471
2472         switch (elem_type) {
2473
2474         case TYPE_SCE:
2475             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2476             audio_found = 1;
2477             sce_count++;
2478             break;
2479
2480         case TYPE_CPE:
2481             err = decode_cpe(ac, gb, che);
2482             audio_found = 1;
2483             break;
2484
2485         case TYPE_CCE:
2486             err = decode_cce(ac, gb, che);
2487             break;
2488
2489         case TYPE_LFE:
2490             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2491             audio_found = 1;
2492             break;
2493
2494         case TYPE_DSE:
2495             err = skip_data_stream_element(ac, gb);
2496             break;
2497
2498         case TYPE_PCE: {
2499             uint8_t layout_map[MAX_ELEM_ID*4][3];
2500             int tags;
2501             push_output_configuration(ac);
2502             tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2503             if (tags < 0) {
2504                 err = tags;
2505                 break;
2506             }
2507             if (pce_found) {
2508                 av_log(avctx, AV_LOG_ERROR,
2509                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2510                 pop_output_configuration(ac);
2511             } else {
2512                 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE);
2513                 if (!err)
2514                     ac->oc[1].m4ac.chan_config = 0;
2515                 pce_found = 1;
2516             }
2517             break;
2518         }
2519
2520         case TYPE_FIL:
2521             if (elem_id == 15)
2522                 elem_id += get_bits(gb, 8) - 1;
2523             if (get_bits_left(gb) < 8 * elem_id) {
2524                     av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
2525                     err = -1;
2526                     goto fail;
2527             }
2528             while (elem_id > 0)
2529                 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2530             err = 0; /* FIXME */
2531             break;
2532
2533         default:
2534             err = -1; /* should not happen, but keeps compiler happy */
2535             break;
2536         }
2537
2538         che_prev       = che;
2539         elem_type_prev = elem_type;
2540
2541         if (err)
2542             goto fail;
2543
2544         if (get_bits_left(gb) < 3) {
2545             av_log(avctx, AV_LOG_ERROR, overread_err);
2546             err = -1;
2547             goto fail;
2548         }
2549     }
2550
2551     spectral_to_sample(ac);
2552
2553     multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2554     samples <<= multiplier;
2555
2556     /* for dual-mono audio (SCE + SCE) */
2557     is_dmono = ac->enable_jp_dmono && sce_count == 2 &&
2558                ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
2559
2560     if (is_dmono) {
2561         if (ac->dmono_mode == 0) {
2562             tmp = ac->output_data[1];
2563             ac->output_data[1] = ac->output_data[0];
2564         } else if (ac->dmono_mode == 1) {
2565             tmp = ac->output_data[0];
2566             ac->output_data[0] = ac->output_data[1];
2567         }
2568     }
2569
2570     if (samples) {
2571         /* get output buffer */
2572         ac->frame.nb_samples = samples;
2573         if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
2574             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2575             err = -1;
2576             goto fail;
2577         }
2578
2579         if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
2580             ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
2581                                           (const float **)ac->output_data,
2582                                           samples, avctx->channels);
2583         else
2584             ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2585                                                    (const float **)ac->output_data,
2586                                                    samples, avctx->channels);
2587
2588         *(AVFrame *)data = ac->frame;
2589     }
2590     *got_frame_ptr = !!samples;
2591
2592     if (is_dmono) {
2593         if (ac->dmono_mode == 0)
2594             ac->output_data[1] = tmp;
2595         else if (ac->dmono_mode == 1)
2596             ac->output_data[0] = tmp;
2597     }
2598
2599     if (ac->oc[1].status && audio_found) {
2600         avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2601         avctx->frame_size = samples;
2602         ac->oc[1].status = OC_LOCKED;
2603     }
2604
2605     if (multiplier) {
2606         int side_size;
2607         uint32_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2608         if (side && side_size>=4)
2609             AV_WL32(side, 2*AV_RL32(side));
2610     }
2611     return 0;
2612 fail:
2613     pop_output_configuration(ac);
2614     return err;
2615 }
2616
2617 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2618                             int *got_frame_ptr, AVPacket *avpkt)
2619 {
2620     AACContext *ac = avctx->priv_data;
2621     const uint8_t *buf = avpkt->data;
2622     int buf_size = avpkt->size;
2623     GetBitContext gb;
2624     int buf_consumed;
2625     int buf_offset;
2626     int err;
2627     int new_extradata_size;
2628     const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2629                                        AV_PKT_DATA_NEW_EXTRADATA,
2630                                        &new_extradata_size);
2631     int jp_dualmono_size;
2632     const uint8_t *jp_dualmono   = av_packet_get_side_data(avpkt,
2633                                        AV_PKT_DATA_JP_DUALMONO,
2634                                        &jp_dualmono_size);
2635
2636     if (new_extradata && 0) {
2637         av_free(avctx->extradata);
2638         avctx->extradata = av_mallocz(new_extradata_size +
2639                                       FF_INPUT_BUFFER_PADDING_SIZE);
2640         if (!avctx->extradata)
2641             return AVERROR(ENOMEM);
2642         avctx->extradata_size = new_extradata_size;
2643         memcpy(avctx->extradata, new_extradata, new_extradata_size);
2644         push_output_configuration(ac);
2645         if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2646                                          avctx->extradata,
2647                                          avctx->extradata_size*8, 1) < 0) {
2648             pop_output_configuration(ac);
2649             return AVERROR_INVALIDDATA;
2650         }
2651     }
2652
2653     ac->enable_jp_dmono = !!jp_dualmono;
2654     ac->dmono_mode = 0;
2655     if (jp_dualmono && jp_dualmono_size > 0)
2656         ac->dmono_mode = *jp_dualmono;
2657
2658     init_get_bits(&gb, buf, buf_size * 8);
2659
2660     if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt)) < 0)
2661         return err;
2662
2663     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2664     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2665         if (buf[buf_offset])
2666             break;
2667
2668     return buf_size > buf_offset ? buf_consumed : buf_size;
2669 }
2670
2671 static av_cold int aac_decode_close(AVCodecContext *avctx)
2672 {
2673     AACContext *ac = avctx->priv_data;
2674     int i, type;
2675
2676     for (i = 0; i < MAX_ELEM_ID; i++) {
2677         for (type = 0; type < 4; type++) {
2678             if (ac->che[type][i])
2679                 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2680             av_freep(&ac->che[type][i]);
2681         }
2682     }
2683
2684     ff_mdct_end(&ac->mdct);
2685     ff_mdct_end(&ac->mdct_small);
2686     ff_mdct_end(&ac->mdct_ltp);
2687     return 0;
2688 }
2689
2690
2691 #define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
2692
2693 struct LATMContext {
2694     AACContext      aac_ctx;             ///< containing AACContext
2695     int             initialized;         ///< initialized after a valid extradata was seen
2696
2697     // parser data
2698     int             audio_mux_version_A; ///< LATM syntax version
2699     int             frame_length_type;   ///< 0/1 variable/fixed frame length
2700     int             frame_length;        ///< frame length for fixed frame length
2701 };
2702
2703 static inline uint32_t latm_get_value(GetBitContext *b)
2704 {
2705     int length = get_bits(b, 2);
2706
2707     return get_bits_long(b, (length+1)*8);
2708 }
2709
2710 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2711                                              GetBitContext *gb, int asclen)
2712 {
2713     AACContext *ac        = &latmctx->aac_ctx;
2714     AVCodecContext *avctx = ac->avctx;
2715     MPEG4AudioConfig m4ac = { 0 };
2716     int config_start_bit  = get_bits_count(gb);
2717     int sync_extension    = 0;
2718     int bits_consumed, esize;
2719
2720     if (asclen) {
2721         sync_extension = 1;
2722         asclen         = FFMIN(asclen, get_bits_left(gb));
2723     } else
2724         asclen         = get_bits_left(gb);
2725
2726     if (config_start_bit % 8) {
2727         av_log_missing_feature(latmctx->aac_ctx.avctx,
2728                                "Non-byte-aligned audio-specific config", 1);
2729         return AVERROR_PATCHWELCOME;
2730     }
2731     if (asclen <= 0)
2732         return AVERROR_INVALIDDATA;
2733     bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2734                                          gb->buffer + (config_start_bit / 8),
2735                                          asclen, sync_extension);
2736
2737     if (bits_consumed < 0)
2738         return AVERROR_INVALIDDATA;
2739
2740     if (!latmctx->initialized ||
2741         ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
2742         ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
2743
2744         if(latmctx->initialized) {
2745             av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2746         } else {
2747             av_log(avctx, AV_LOG_INFO, "initializing latmctx\n");
2748         }
2749         latmctx->initialized = 0;
2750
2751         esize = (bits_consumed+7) / 8;
2752
2753         if (avctx->extradata_size < esize) {
2754             av_free(avctx->extradata);
2755             avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2756             if (!avctx->extradata)
2757                 return AVERROR(ENOMEM);
2758         }
2759
2760         avctx->extradata_size = esize;
2761         memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2762         memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2763     }
2764     skip_bits_long(gb, bits_consumed);
2765
2766     return bits_consumed;
2767 }
2768
2769 static int read_stream_mux_config(struct LATMContext *latmctx,
2770                                   GetBitContext *gb)
2771 {
2772     int ret, audio_mux_version = get_bits(gb, 1);
2773
2774     latmctx->audio_mux_version_A = 0;
2775     if (audio_mux_version)
2776         latmctx->audio_mux_version_A = get_bits(gb, 1);
2777
2778     if (!latmctx->audio_mux_version_A) {
2779
2780         if (audio_mux_version)
2781             latm_get_value(gb);                 // taraFullness
2782
2783         skip_bits(gb, 1);                       // allStreamSameTimeFraming
2784         skip_bits(gb, 6);                       // numSubFrames
2785         // numPrograms
2786         if (get_bits(gb, 4)) {                  // numPrograms
2787             av_log_missing_feature(latmctx->aac_ctx.avctx,
2788                                    "Multiple programs", 1);
2789             return AVERROR_PATCHWELCOME;
2790         }
2791
2792         // for each program (which there is only one in DVB)
2793
2794         // for each layer (which there is only one in DVB)
2795         if (get_bits(gb, 3)) {                   // numLayer
2796             av_log_missing_feature(latmctx->aac_ctx.avctx,
2797                                    "Multiple layers", 1);
2798             return AVERROR_PATCHWELCOME;
2799         }
2800
2801         // for all but first stream: use_same_config = get_bits(gb, 1);
2802         if (!audio_mux_version) {
2803             if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2804                 return ret;
2805         } else {
2806             int ascLen = latm_get_value(gb);
2807             if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2808                 return ret;
2809             ascLen -= ret;
2810             skip_bits_long(gb, ascLen);
2811         }
2812
2813         latmctx->frame_length_type = get_bits(gb, 3);
2814         switch (latmctx->frame_length_type) {
2815         case 0:
2816             skip_bits(gb, 8);       // latmBufferFullness
2817             break;
2818         case 1:
2819             latmctx->frame_length = get_bits(gb, 9);
2820             break;
2821         case 3:
2822         case 4:
2823         case 5:
2824             skip_bits(gb, 6);       // CELP frame length table index
2825             break;
2826         case 6:
2827         case 7:
2828             skip_bits(gb, 1);       // HVXC frame length table index
2829             break;
2830         }
2831
2832         if (get_bits(gb, 1)) {                  // other data
2833             if (audio_mux_version) {
2834                 latm_get_value(gb);             // other_data_bits
2835             } else {
2836                 int esc;
2837                 do {
2838                     esc = get_bits(gb, 1);
2839                     skip_bits(gb, 8);
2840                 } while (esc);
2841             }
2842         }
2843
2844         if (get_bits(gb, 1))                     // crc present
2845             skip_bits(gb, 8);                    // config_crc
2846     }
2847
2848     return 0;
2849 }
2850
2851 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2852 {
2853     uint8_t tmp;
2854
2855     if (ctx->frame_length_type == 0) {
2856         int mux_slot_length = 0;
2857         do {
2858             tmp = get_bits(gb, 8);
2859             mux_slot_length += tmp;
2860         } while (tmp == 255);
2861         return mux_slot_length;
2862     } else if (ctx->frame_length_type == 1) {
2863         return ctx->frame_length;
2864     } else if (ctx->frame_length_type == 3 ||
2865                ctx->frame_length_type == 5 ||
2866                ctx->frame_length_type == 7) {
2867         skip_bits(gb, 2);          // mux_slot_length_coded
2868     }
2869     return 0;
2870 }
2871
2872 static int read_audio_mux_element(struct LATMContext *latmctx,
2873                                   GetBitContext *gb)
2874 {
2875     int err;
2876     uint8_t use_same_mux = get_bits(gb, 1);
2877     if (!use_same_mux) {
2878         if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2879             return err;
2880     } else if (!latmctx->aac_ctx.avctx->extradata) {
2881         av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2882                "no decoder config found\n");
2883         return AVERROR(EAGAIN);
2884     }
2885     if (latmctx->audio_mux_version_A == 0) {
2886         int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2887         if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2888             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2889             return AVERROR_INVALIDDATA;
2890         } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2891             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2892                    "frame length mismatch %d << %d\n",
2893                    mux_slot_length_bytes * 8, get_bits_left(gb));
2894             return AVERROR_INVALIDDATA;
2895         }
2896     }
2897     return 0;
2898 }
2899
2900
2901 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2902                              int *got_frame_ptr, AVPacket *avpkt)
2903 {
2904     struct LATMContext *latmctx = avctx->priv_data;
2905     int                 muxlength, err;
2906     GetBitContext       gb;
2907
2908     init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2909
2910     // check for LOAS sync word
2911     if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2912         return AVERROR_INVALIDDATA;
2913
2914     muxlength = get_bits(&gb, 13) + 3;
2915     // not enough data, the parser should have sorted this out
2916     if (muxlength > avpkt->size)
2917         return AVERROR_INVALIDDATA;
2918
2919     if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2920         return err;
2921
2922     if (!latmctx->initialized) {
2923         if (!avctx->extradata) {
2924             *got_frame_ptr = 0;
2925             return avpkt->size;
2926         } else {
2927             push_output_configuration(&latmctx->aac_ctx);
2928             if ((err = decode_audio_specific_config(
2929                     &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
2930                     avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
2931                 pop_output_configuration(&latmctx->aac_ctx);
2932                 return err;
2933             }
2934             latmctx->initialized = 1;
2935         }
2936     }
2937
2938     if (show_bits(&gb, 12) == 0xfff) {
2939         av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2940                "ADTS header detected, probably as result of configuration "
2941                "misparsing\n");
2942         return AVERROR_INVALIDDATA;
2943     }
2944
2945     if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
2946         return err;
2947
2948     return muxlength;
2949 }
2950
2951 static av_cold int latm_decode_init(AVCodecContext *avctx)
2952 {
2953     struct LATMContext *latmctx = avctx->priv_data;
2954     int ret = aac_decode_init(avctx);
2955
2956     if (avctx->extradata_size > 0)
2957         latmctx->initialized = !ret;
2958
2959     return ret;
2960 }
2961
2962
2963 AVCodec ff_aac_decoder = {
2964     .name            = "aac",
2965     .type            = AVMEDIA_TYPE_AUDIO,
2966     .id              = AV_CODEC_ID_AAC,
2967     .priv_data_size  = sizeof(AACContext),
2968     .init            = aac_decode_init,
2969     .close           = aac_decode_close,
2970     .decode          = aac_decode_frame,
2971     .long_name       = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
2972     .sample_fmts     = (const enum AVSampleFormat[]) {
2973         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2974     },
2975     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2976     .channel_layouts = aac_channel_layout,
2977     .flush = flush,
2978 };
2979
2980 /*
2981     Note: This decoder filter is intended to decode LATM streams transferred
2982     in MPEG transport streams which only contain one program.
2983     To do a more complex LATM demuxing a separate LATM demuxer should be used.
2984 */
2985 AVCodec ff_aac_latm_decoder = {
2986     .name            = "aac_latm",
2987     .type            = AVMEDIA_TYPE_AUDIO,
2988     .id              = AV_CODEC_ID_AAC_LATM,
2989     .priv_data_size  = sizeof(struct LATMContext),
2990     .init            = latm_decode_init,
2991     .close           = aac_decode_close,
2992     .decode          = latm_decode_frame,
2993     .long_name       = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
2994     .sample_fmts     = (const enum AVSampleFormat[]) {
2995         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2996     },
2997     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2998     .channel_layouts = aac_channel_layout,
2999     .flush = flush,
3000 };