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