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