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