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