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