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