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