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