]> git.sesse.net Git - ffmpeg/blob - libavcodec/aacdec.c
Merge commit 'a9d8d35e4833fc4dfbf557ce73c84e9ca6224427'
[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 "fmtconvert.h"
91 #include "lpc.h"
92 #include "kbdwin.h"
93 #include "sinewin.h"
94
95 #include "aac.h"
96 #include "aactab.h"
97 #include "aacdectab.h"
98 #include "cbrt_tablegen.h"
99 #include "sbr.h"
100 #include "aacsbr.h"
101 #include "mpeg4audio.h"
102 #include "aacadtsdec.h"
103 #include "libavutil/intfloat.h"
104
105 #include <assert.h>
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
805     if (get_bits1(gb))       // dependsOnCoreCoder
806         skip_bits(gb, 14);   // coreCoderDelay
807     extension_flag = get_bits1(gb);
808
809     if (m4ac->object_type == AOT_AAC_SCALABLE ||
810         m4ac->object_type == AOT_ER_AAC_SCALABLE)
811         skip_bits(gb, 3);     // layerNr
812
813     if (channel_config == 0) {
814         skip_bits(gb, 4);  // element_instance_tag
815         tags = decode_pce(avctx, m4ac, layout_map, gb);
816         if (tags < 0)
817             return tags;
818     } else {
819         if ((ret = set_default_channel_config(avctx, layout_map,
820                                               &tags, channel_config)))
821             return ret;
822     }
823
824     if (count_channels(layout_map, tags) > 1) {
825         m4ac->ps = 0;
826     } else if (m4ac->sbr == 1 && m4ac->ps == -1)
827         m4ac->ps = 1;
828
829     if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
830         return ret;
831
832     if (extension_flag) {
833         switch (m4ac->object_type) {
834         case AOT_ER_BSAC:
835             skip_bits(gb, 5);    // numOfSubFrame
836             skip_bits(gb, 11);   // layer_length
837             break;
838         case AOT_ER_AAC_LC:
839         case AOT_ER_AAC_LTP:
840         case AOT_ER_AAC_SCALABLE:
841         case AOT_ER_AAC_LD:
842             res_flags = get_bits(gb, 3);
843             if (res_flags) {
844                 avpriv_report_missing_feature(avctx,
845                                               "AAC data resilience (flags %x)",
846                                               res_flags);
847                 return AVERROR_PATCHWELCOME;
848             }
849             break;
850         }
851         skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
852     }
853     switch (m4ac->object_type) {
854     case AOT_ER_AAC_LC:
855     case AOT_ER_AAC_LTP:
856     case AOT_ER_AAC_SCALABLE:
857     case AOT_ER_AAC_LD:
858         ep_config = get_bits(gb, 2);
859         if (ep_config) {
860             avpriv_report_missing_feature(avctx,
861                                           "epConfig %d", ep_config);
862             return AVERROR_PATCHWELCOME;
863         }
864     }
865     return 0;
866 }
867
868 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
869                                      GetBitContext *gb,
870                                      MPEG4AudioConfig *m4ac,
871                                      int channel_config)
872 {
873     int ret, ep_config, res_flags;
874     uint8_t layout_map[MAX_ELEM_ID*4][3];
875     int tags = 0;
876     const int ELDEXT_TERM = 0;
877
878     m4ac->ps  = 0;
879     m4ac->sbr = 0;
880
881     if (get_bits1(gb)) { // frameLengthFlag
882         avpriv_request_sample(avctx, "960/120 MDCT window");
883         return AVERROR_PATCHWELCOME;
884     }
885
886     res_flags = get_bits(gb, 3);
887     if (res_flags) {
888         avpriv_report_missing_feature(avctx,
889                                       "AAC data resilience (flags %x)",
890                                       res_flags);
891         return AVERROR_PATCHWELCOME;
892     }
893
894     if (get_bits1(gb)) { // ldSbrPresentFlag
895         avpriv_report_missing_feature(avctx,
896                                       "Low Delay SBR");
897         return AVERROR_PATCHWELCOME;
898     }
899
900     while (get_bits(gb, 4) != ELDEXT_TERM) {
901         int len = get_bits(gb, 4);
902         if (len == 15)
903             len += get_bits(gb, 8);
904         if (len == 15 + 255)
905             len += get_bits(gb, 16);
906         if (get_bits_left(gb) < len * 8 + 4) {
907             av_log(ac->avctx, AV_LOG_ERROR, overread_err);
908             return AVERROR_INVALIDDATA;
909         }
910         skip_bits_long(gb, 8 * len);
911     }
912
913     if ((ret = set_default_channel_config(avctx, layout_map,
914                                           &tags, channel_config)))
915         return ret;
916
917     if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
918         return ret;
919
920     ep_config = get_bits(gb, 2);
921     if (ep_config) {
922         avpriv_report_missing_feature(avctx,
923                                       "epConfig %d", ep_config);
924         return AVERROR_PATCHWELCOME;
925     }
926     return 0;
927 }
928
929 /**
930  * Decode audio specific configuration; reference: table 1.13.
931  *
932  * @param   ac          pointer to AACContext, may be null
933  * @param   avctx       pointer to AVCCodecContext, used for logging
934  * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
935  * @param   data        pointer to buffer holding an audio specific config
936  * @param   bit_size    size of audio specific config or data in bits
937  * @param   sync_extension look for an appended sync extension
938  *
939  * @return  Returns error status or number of consumed bits. <0 - error
940  */
941 static int decode_audio_specific_config(AACContext *ac,
942                                         AVCodecContext *avctx,
943                                         MPEG4AudioConfig *m4ac,
944                                         const uint8_t *data, int bit_size,
945                                         int sync_extension)
946 {
947     GetBitContext gb;
948     int i, ret;
949
950     av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
951     for (i = 0; i < bit_size >> 3; i++)
952         av_dlog(avctx, "%02x ", data[i]);
953     av_dlog(avctx, "\n");
954
955     if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
956         return ret;
957
958     if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
959                                           sync_extension)) < 0)
960         return AVERROR_INVALIDDATA;
961     if (m4ac->sampling_index > 12) {
962         av_log(avctx, AV_LOG_ERROR,
963                "invalid sampling rate index %d\n",
964                m4ac->sampling_index);
965         return AVERROR_INVALIDDATA;
966     }
967     if (m4ac->object_type == AOT_ER_AAC_LD &&
968         (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
969         av_log(avctx, AV_LOG_ERROR,
970                "invalid low delay sampling rate index %d\n",
971                m4ac->sampling_index);
972         return AVERROR_INVALIDDATA;
973     }
974
975     skip_bits_long(&gb, i);
976
977     switch (m4ac->object_type) {
978     case AOT_AAC_MAIN:
979     case AOT_AAC_LC:
980     case AOT_AAC_LTP:
981     case AOT_ER_AAC_LC:
982     case AOT_ER_AAC_LD:
983         if ((ret = decode_ga_specific_config(ac, avctx, &gb,
984                                             m4ac, m4ac->chan_config)) < 0)
985             return ret;
986         break;
987     case AOT_ER_AAC_ELD:
988         if ((ret = decode_eld_specific_config(ac, avctx, &gb,
989                                               m4ac, m4ac->chan_config)) < 0)
990             return ret;
991         break;
992     default:
993         avpriv_report_missing_feature(avctx,
994                                       "Audio object type %s%d",
995                                       m4ac->sbr == 1 ? "SBR+" : "",
996                                       m4ac->object_type);
997         return AVERROR(ENOSYS);
998     }
999
1000     av_dlog(avctx,
1001             "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1002             m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1003             m4ac->sample_rate, m4ac->sbr,
1004             m4ac->ps);
1005
1006     return get_bits_count(&gb);
1007 }
1008
1009 /**
1010  * linear congruential pseudorandom number generator
1011  *
1012  * @param   previous_val    pointer to the current state of the generator
1013  *
1014  * @return  Returns a 32-bit pseudorandom integer
1015  */
1016 static av_always_inline int lcg_random(unsigned previous_val)
1017 {
1018     union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1019     return v.s;
1020 }
1021
1022 static av_always_inline void reset_predict_state(PredictorState *ps)
1023 {
1024     ps->r0   = 0.0f;
1025     ps->r1   = 0.0f;
1026     ps->cor0 = 0.0f;
1027     ps->cor1 = 0.0f;
1028     ps->var0 = 1.0f;
1029     ps->var1 = 1.0f;
1030 }
1031
1032 static void reset_all_predictors(PredictorState *ps)
1033 {
1034     int i;
1035     for (i = 0; i < MAX_PREDICTORS; i++)
1036         reset_predict_state(&ps[i]);
1037 }
1038
1039 static int sample_rate_idx (int rate)
1040 {
1041          if (92017 <= rate) return 0;
1042     else if (75132 <= rate) return 1;
1043     else if (55426 <= rate) return 2;
1044     else if (46009 <= rate) return 3;
1045     else if (37566 <= rate) return 4;
1046     else if (27713 <= rate) return 5;
1047     else if (23004 <= rate) return 6;
1048     else if (18783 <= rate) return 7;
1049     else if (13856 <= rate) return 8;
1050     else if (11502 <= rate) return 9;
1051     else if (9391  <= rate) return 10;
1052     else                    return 11;
1053 }
1054
1055 static void reset_predictor_group(PredictorState *ps, int group_num)
1056 {
1057     int i;
1058     for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1059         reset_predict_state(&ps[i]);
1060 }
1061
1062 #define AAC_INIT_VLC_STATIC(num, size)                                     \
1063     INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num],     \
1064          ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]),  \
1065                                     sizeof(ff_aac_spectral_bits[num][0]),  \
1066         ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1067                                     sizeof(ff_aac_spectral_codes[num][0]), \
1068         size);
1069
1070 static void aacdec_init(AACContext *ac);
1071
1072 static av_cold int aac_decode_init(AVCodecContext *avctx)
1073 {
1074     AACContext *ac = avctx->priv_data;
1075     int ret;
1076
1077     ac->avctx = avctx;
1078     ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1079
1080     aacdec_init(ac);
1081
1082     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1083
1084     if (avctx->extradata_size > 0) {
1085         if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1086                                                 avctx->extradata,
1087                                                 avctx->extradata_size * 8,
1088                                                 1)) < 0)
1089             return ret;
1090     } else {
1091         int sr, i;
1092         uint8_t layout_map[MAX_ELEM_ID*4][3];
1093         int layout_map_tags;
1094
1095         sr = sample_rate_idx(avctx->sample_rate);
1096         ac->oc[1].m4ac.sampling_index = sr;
1097         ac->oc[1].m4ac.channels = avctx->channels;
1098         ac->oc[1].m4ac.sbr = -1;
1099         ac->oc[1].m4ac.ps = -1;
1100
1101         for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1102             if (ff_mpeg4audio_channels[i] == avctx->channels)
1103                 break;
1104         if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1105             i = 0;
1106         }
1107         ac->oc[1].m4ac.chan_config = i;
1108
1109         if (ac->oc[1].m4ac.chan_config) {
1110             int ret = set_default_channel_config(avctx, layout_map,
1111                 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1112             if (!ret)
1113                 output_configure(ac, layout_map, layout_map_tags,
1114                                  OC_GLOBAL_HDR, 0);
1115             else if (avctx->err_recognition & AV_EF_EXPLODE)
1116                 return AVERROR_INVALIDDATA;
1117         }
1118     }
1119
1120     if (avctx->channels > MAX_CHANNELS) {
1121         av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1122         return AVERROR_INVALIDDATA;
1123     }
1124
1125     AAC_INIT_VLC_STATIC( 0, 304);
1126     AAC_INIT_VLC_STATIC( 1, 270);
1127     AAC_INIT_VLC_STATIC( 2, 550);
1128     AAC_INIT_VLC_STATIC( 3, 300);
1129     AAC_INIT_VLC_STATIC( 4, 328);
1130     AAC_INIT_VLC_STATIC( 5, 294);
1131     AAC_INIT_VLC_STATIC( 6, 306);
1132     AAC_INIT_VLC_STATIC( 7, 268);
1133     AAC_INIT_VLC_STATIC( 8, 510);
1134     AAC_INIT_VLC_STATIC( 9, 366);
1135     AAC_INIT_VLC_STATIC(10, 462);
1136
1137     ff_aac_sbr_init();
1138
1139     ff_fmt_convert_init(&ac->fmt_conv, avctx);
1140     avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
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     // window initialization
1161     ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1162     ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1163     ff_init_ff_sine_windows(10);
1164     ff_init_ff_sine_windows( 9);
1165     ff_init_ff_sine_windows( 7);
1166
1167     cbrt_tableinit();
1168
1169     return 0;
1170 }
1171
1172 /**
1173  * Skip data_stream_element; reference: table 4.10.
1174  */
1175 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1176 {
1177     int byte_align = get_bits1(gb);
1178     int count = get_bits(gb, 8);
1179     if (count == 255)
1180         count += get_bits(gb, 8);
1181     if (byte_align)
1182         align_get_bits(gb);
1183
1184     if (get_bits_left(gb) < 8 * count) {
1185         av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1186         return AVERROR_INVALIDDATA;
1187     }
1188     skip_bits_long(gb, 8 * count);
1189     return 0;
1190 }
1191
1192 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1193                              GetBitContext *gb)
1194 {
1195     int sfb;
1196     if (get_bits1(gb)) {
1197         ics->predictor_reset_group = get_bits(gb, 5);
1198         if (ics->predictor_reset_group == 0 ||
1199             ics->predictor_reset_group > 30) {
1200             av_log(ac->avctx, AV_LOG_ERROR,
1201                    "Invalid Predictor Reset Group.\n");
1202             return AVERROR_INVALIDDATA;
1203         }
1204     }
1205     for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1206         ics->prediction_used[sfb] = get_bits1(gb);
1207     }
1208     return 0;
1209 }
1210
1211 /**
1212  * Decode Long Term Prediction data; reference: table 4.xx.
1213  */
1214 static void decode_ltp(LongTermPrediction *ltp,
1215                        GetBitContext *gb, uint8_t max_sfb)
1216 {
1217     int sfb;
1218
1219     ltp->lag  = get_bits(gb, 11);
1220     ltp->coef = ltp_coef[get_bits(gb, 3)];
1221     for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1222         ltp->used[sfb] = get_bits1(gb);
1223 }
1224
1225 /**
1226  * Decode Individual Channel Stream info; reference: table 4.6.
1227  */
1228 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1229                            GetBitContext *gb)
1230 {
1231     int aot = ac->oc[1].m4ac.object_type;
1232     if (aot != AOT_ER_AAC_ELD) {
1233         if (get_bits1(gb)) {
1234             av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1235             return AVERROR_INVALIDDATA;
1236         }
1237         ics->window_sequence[1] = ics->window_sequence[0];
1238         ics->window_sequence[0] = get_bits(gb, 2);
1239         if (aot == AOT_ER_AAC_LD &&
1240             ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1241             av_log(ac->avctx, AV_LOG_ERROR,
1242                    "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1243                    "window sequence %d found.\n", ics->window_sequence[0]);
1244             ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1245             return AVERROR_INVALIDDATA;
1246         }
1247         ics->use_kb_window[1]   = ics->use_kb_window[0];
1248         ics->use_kb_window[0]   = get_bits1(gb);
1249     }
1250     ics->num_window_groups  = 1;
1251     ics->group_len[0]       = 1;
1252     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1253         int i;
1254         ics->max_sfb = get_bits(gb, 4);
1255         for (i = 0; i < 7; i++) {
1256             if (get_bits1(gb)) {
1257                 ics->group_len[ics->num_window_groups - 1]++;
1258             } else {
1259                 ics->num_window_groups++;
1260                 ics->group_len[ics->num_window_groups - 1] = 1;
1261             }
1262         }
1263         ics->num_windows       = 8;
1264         ics->swb_offset        =    ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1265         ics->num_swb           =   ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1266         ics->tns_max_bands     = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1267         ics->predictor_present = 0;
1268     } else {
1269         ics->max_sfb               = get_bits(gb, 6);
1270         ics->num_windows           = 1;
1271         if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1272             ics->swb_offset        =     ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];
1273             ics->num_swb           =    ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];
1274             ics->tns_max_bands     =  ff_tns_max_bands_512[ac->oc[1].m4ac.sampling_index];
1275             if (!ics->num_swb || !ics->swb_offset)
1276                 return AVERROR_BUG;
1277         } else {
1278             ics->swb_offset        =    ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1279             ics->num_swb           =   ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1280             ics->tns_max_bands     = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1281         }
1282         if (aot != AOT_ER_AAC_ELD) {
1283             ics->predictor_present     = get_bits1(gb);
1284             ics->predictor_reset_group = 0;
1285         }
1286         if (ics->predictor_present) {
1287             if (aot == AOT_AAC_MAIN) {
1288                 if (decode_prediction(ac, ics, gb)) {
1289                     goto fail;
1290                 }
1291             } else if (aot == AOT_AAC_LC ||
1292                        aot == AOT_ER_AAC_LC) {
1293                 av_log(ac->avctx, AV_LOG_ERROR,
1294                        "Prediction is not allowed in AAC-LC.\n");
1295                 goto fail;
1296             } else {
1297                 if (aot == AOT_ER_AAC_LD) {
1298                     av_log(ac->avctx, AV_LOG_ERROR,
1299                            "LTP in ER AAC LD not yet implemented.\n");
1300                     return AVERROR_PATCHWELCOME;
1301                 }
1302                 if ((ics->ltp.present = get_bits(gb, 1)))
1303                     decode_ltp(&ics->ltp, gb, ics->max_sfb);
1304             }
1305         }
1306     }
1307
1308     if (ics->max_sfb > ics->num_swb) {
1309         av_log(ac->avctx, AV_LOG_ERROR,
1310                "Number of scalefactor bands in group (%d) "
1311                "exceeds limit (%d).\n",
1312                ics->max_sfb, ics->num_swb);
1313         goto fail;
1314     }
1315
1316     return 0;
1317 fail:
1318     ics->max_sfb = 0;
1319     return AVERROR_INVALIDDATA;
1320 }
1321
1322 /**
1323  * Decode band types (section_data payload); reference: table 4.46.
1324  *
1325  * @param   band_type           array of the used band type
1326  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1327  *
1328  * @return  Returns error status. 0 - OK, !0 - error
1329  */
1330 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1331                              int band_type_run_end[120], GetBitContext *gb,
1332                              IndividualChannelStream *ics)
1333 {
1334     int g, idx = 0;
1335     const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1336     for (g = 0; g < ics->num_window_groups; g++) {
1337         int k = 0;
1338         while (k < ics->max_sfb) {
1339             uint8_t sect_end = k;
1340             int sect_len_incr;
1341             int sect_band_type = get_bits(gb, 4);
1342             if (sect_band_type == 12) {
1343                 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1344                 return AVERROR_INVALIDDATA;
1345             }
1346             do {
1347                 sect_len_incr = get_bits(gb, bits);
1348                 sect_end += sect_len_incr;
1349                 if (get_bits_left(gb) < 0) {
1350                     av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1351                     return AVERROR_INVALIDDATA;
1352                 }
1353                 if (sect_end > ics->max_sfb) {
1354                     av_log(ac->avctx, AV_LOG_ERROR,
1355                            "Number of bands (%d) exceeds limit (%d).\n",
1356                            sect_end, ics->max_sfb);
1357                     return AVERROR_INVALIDDATA;
1358                 }
1359             } while (sect_len_incr == (1 << bits) - 1);
1360             for (; k < sect_end; k++) {
1361                 band_type        [idx]   = sect_band_type;
1362                 band_type_run_end[idx++] = sect_end;
1363             }
1364         }
1365     }
1366     return 0;
1367 }
1368
1369 /**
1370  * Decode scalefactors; reference: table 4.47.
1371  *
1372  * @param   global_gain         first scalefactor value as scalefactors are differentially coded
1373  * @param   band_type           array of the used band type
1374  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1375  * @param   sf                  array of scalefactors or intensity stereo positions
1376  *
1377  * @return  Returns error status. 0 - OK, !0 - error
1378  */
1379 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1380                                unsigned int global_gain,
1381                                IndividualChannelStream *ics,
1382                                enum BandType band_type[120],
1383                                int band_type_run_end[120])
1384 {
1385     int g, i, idx = 0;
1386     int offset[3] = { global_gain, global_gain - 90, 0 };
1387     int clipped_offset;
1388     int noise_flag = 1;
1389     for (g = 0; g < ics->num_window_groups; g++) {
1390         for (i = 0; i < ics->max_sfb;) {
1391             int run_end = band_type_run_end[idx];
1392             if (band_type[idx] == ZERO_BT) {
1393                 for (; i < run_end; i++, idx++)
1394                     sf[idx] = 0.0;
1395             } else if ((band_type[idx] == INTENSITY_BT) ||
1396                        (band_type[idx] == INTENSITY_BT2)) {
1397                 for (; i < run_end; i++, idx++) {
1398                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1399                     clipped_offset = av_clip(offset[2], -155, 100);
1400                     if (offset[2] != clipped_offset) {
1401                         avpriv_request_sample(ac->avctx,
1402                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1403                                               "Clipped intensity stereo position (%d -> %d)",
1404                                               offset[2], clipped_offset);
1405                     }
1406                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1407                 }
1408             } else if (band_type[idx] == NOISE_BT) {
1409                 for (; i < run_end; i++, idx++) {
1410                     if (noise_flag-- > 0)
1411                         offset[1] += get_bits(gb, 9) - 256;
1412                     else
1413                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1414                     clipped_offset = av_clip(offset[1], -100, 155);
1415                     if (offset[1] != clipped_offset) {
1416                         avpriv_request_sample(ac->avctx,
1417                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1418                                               "Clipped noise gain (%d -> %d)",
1419                                               offset[1], clipped_offset);
1420                     }
1421                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1422                 }
1423             } else {
1424                 for (; i < run_end; i++, idx++) {
1425                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1426                     if (offset[0] > 255U) {
1427                         av_log(ac->avctx, AV_LOG_ERROR,
1428                                "Scalefactor (%d) out of range.\n", offset[0]);
1429                         return AVERROR_INVALIDDATA;
1430                     }
1431                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1432                 }
1433             }
1434         }
1435     }
1436     return 0;
1437 }
1438
1439 /**
1440  * Decode pulse data; reference: table 4.7.
1441  */
1442 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1443                          const uint16_t *swb_offset, int num_swb)
1444 {
1445     int i, pulse_swb;
1446     pulse->num_pulse = get_bits(gb, 2) + 1;
1447     pulse_swb        = get_bits(gb, 6);
1448     if (pulse_swb >= num_swb)
1449         return -1;
1450     pulse->pos[0]    = swb_offset[pulse_swb];
1451     pulse->pos[0]   += get_bits(gb, 5);
1452     if (pulse->pos[0] >= swb_offset[num_swb])
1453         return -1;
1454     pulse->amp[0]    = get_bits(gb, 4);
1455     for (i = 1; i < pulse->num_pulse; i++) {
1456         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1457         if (pulse->pos[i] >= swb_offset[num_swb])
1458             return -1;
1459         pulse->amp[i] = get_bits(gb, 4);
1460     }
1461     return 0;
1462 }
1463
1464 /**
1465  * Decode Temporal Noise Shaping data; reference: table 4.48.
1466  *
1467  * @return  Returns error status. 0 - OK, !0 - error
1468  */
1469 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1470                       GetBitContext *gb, const IndividualChannelStream *ics)
1471 {
1472     int w, filt, i, coef_len, coef_res, coef_compress;
1473     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1474     const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1475     for (w = 0; w < ics->num_windows; w++) {
1476         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1477             coef_res = get_bits1(gb);
1478
1479             for (filt = 0; filt < tns->n_filt[w]; filt++) {
1480                 int tmp2_idx;
1481                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1482
1483                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1484                     av_log(ac->avctx, AV_LOG_ERROR,
1485                            "TNS filter order %d is greater than maximum %d.\n",
1486                            tns->order[w][filt], tns_max_order);
1487                     tns->order[w][filt] = 0;
1488                     return AVERROR_INVALIDDATA;
1489                 }
1490                 if (tns->order[w][filt]) {
1491                     tns->direction[w][filt] = get_bits1(gb);
1492                     coef_compress = get_bits1(gb);
1493                     coef_len = coef_res + 3 - coef_compress;
1494                     tmp2_idx = 2 * coef_compress + coef_res;
1495
1496                     for (i = 0; i < tns->order[w][filt]; i++)
1497                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1498                 }
1499             }
1500         }
1501     }
1502     return 0;
1503 }
1504
1505 /**
1506  * Decode Mid/Side data; reference: table 4.54.
1507  *
1508  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1509  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1510  *                      [3] reserved for scalable AAC
1511  */
1512 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1513                                    int ms_present)
1514 {
1515     int idx;
1516     if (ms_present == 1) {
1517         for (idx = 0;
1518              idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1519              idx++)
1520             cpe->ms_mask[idx] = get_bits1(gb);
1521     } else if (ms_present == 2) {
1522         memset(cpe->ms_mask, 1,  sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1523     }
1524 }
1525
1526 #ifndef VMUL2
1527 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1528                            const float *scale)
1529 {
1530     float s = *scale;
1531     *dst++ = v[idx    & 15] * s;
1532     *dst++ = v[idx>>4 & 15] * s;
1533     return dst;
1534 }
1535 #endif
1536
1537 #ifndef VMUL4
1538 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1539                            const float *scale)
1540 {
1541     float s = *scale;
1542     *dst++ = v[idx    & 3] * s;
1543     *dst++ = v[idx>>2 & 3] * s;
1544     *dst++ = v[idx>>4 & 3] * s;
1545     *dst++ = v[idx>>6 & 3] * s;
1546     return dst;
1547 }
1548 #endif
1549
1550 #ifndef VMUL2S
1551 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1552                             unsigned sign, const float *scale)
1553 {
1554     union av_intfloat32 s0, s1;
1555
1556     s0.f = s1.f = *scale;
1557     s0.i ^= sign >> 1 << 31;
1558     s1.i ^= sign      << 31;
1559
1560     *dst++ = v[idx    & 15] * s0.f;
1561     *dst++ = v[idx>>4 & 15] * s1.f;
1562
1563     return dst;
1564 }
1565 #endif
1566
1567 #ifndef VMUL4S
1568 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1569                             unsigned sign, const float *scale)
1570 {
1571     unsigned nz = idx >> 12;
1572     union av_intfloat32 s = { .f = *scale };
1573     union av_intfloat32 t;
1574
1575     t.i = s.i ^ (sign & 1U<<31);
1576     *dst++ = v[idx    & 3] * t.f;
1577
1578     sign <<= nz & 1; nz >>= 1;
1579     t.i = s.i ^ (sign & 1U<<31);
1580     *dst++ = v[idx>>2 & 3] * t.f;
1581
1582     sign <<= nz & 1; nz >>= 1;
1583     t.i = s.i ^ (sign & 1U<<31);
1584     *dst++ = v[idx>>4 & 3] * t.f;
1585
1586     sign <<= nz & 1;
1587     t.i = s.i ^ (sign & 1U<<31);
1588     *dst++ = v[idx>>6 & 3] * t.f;
1589
1590     return dst;
1591 }
1592 #endif
1593
1594 /**
1595  * Decode spectral data; reference: table 4.50.
1596  * Dequantize and scale spectral data; reference: 4.6.3.3.
1597  *
1598  * @param   coef            array of dequantized, scaled spectral data
1599  * @param   sf              array of scalefactors or intensity stereo positions
1600  * @param   pulse_present   set if pulses are present
1601  * @param   pulse           pointer to pulse data struct
1602  * @param   band_type       array of the used band type
1603  *
1604  * @return  Returns error status. 0 - OK, !0 - error
1605  */
1606 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1607                                        GetBitContext *gb, const float sf[120],
1608                                        int pulse_present, const Pulse *pulse,
1609                                        const IndividualChannelStream *ics,
1610                                        enum BandType band_type[120])
1611 {
1612     int i, k, g, idx = 0;
1613     const int c = 1024 / ics->num_windows;
1614     const uint16_t *offsets = ics->swb_offset;
1615     float *coef_base = coef;
1616
1617     for (g = 0; g < ics->num_windows; g++)
1618         memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1619                sizeof(float) * (c - offsets[ics->max_sfb]));
1620
1621     for (g = 0; g < ics->num_window_groups; g++) {
1622         unsigned g_len = ics->group_len[g];
1623
1624         for (i = 0; i < ics->max_sfb; i++, idx++) {
1625             const unsigned cbt_m1 = band_type[idx] - 1;
1626             float *cfo = coef + offsets[i];
1627             int off_len = offsets[i + 1] - offsets[i];
1628             int group;
1629
1630             if (cbt_m1 >= INTENSITY_BT2 - 1) {
1631                 for (group = 0; group < g_len; group++, cfo+=128) {
1632                     memset(cfo, 0, off_len * sizeof(float));
1633                 }
1634             } else if (cbt_m1 == NOISE_BT - 1) {
1635                 for (group = 0; group < g_len; group++, cfo+=128) {
1636                     float scale;
1637                     float band_energy;
1638
1639                     for (k = 0; k < off_len; k++) {
1640                         ac->random_state  = lcg_random(ac->random_state);
1641                         cfo[k] = ac->random_state;
1642                     }
1643
1644                     band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1645                     scale = sf[idx] / sqrtf(band_energy);
1646                     ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1647                 }
1648             } else {
1649                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1650                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1651                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1652                 OPEN_READER(re, gb);
1653
1654                 switch (cbt_m1 >> 1) {
1655                 case 0:
1656                     for (group = 0; group < g_len; group++, cfo+=128) {
1657                         float *cf = cfo;
1658                         int len = off_len;
1659
1660                         do {
1661                             int code;
1662                             unsigned cb_idx;
1663
1664                             UPDATE_CACHE(re, gb);
1665                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1666                             cb_idx = cb_vector_idx[code];
1667                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
1668                         } while (len -= 4);
1669                     }
1670                     break;
1671
1672                 case 1:
1673                     for (group = 0; group < g_len; group++, cfo+=128) {
1674                         float *cf = cfo;
1675                         int len = off_len;
1676
1677                         do {
1678                             int code;
1679                             unsigned nnz;
1680                             unsigned cb_idx;
1681                             uint32_t bits;
1682
1683                             UPDATE_CACHE(re, gb);
1684                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1685                             cb_idx = cb_vector_idx[code];
1686                             nnz = cb_idx >> 8 & 15;
1687                             bits = nnz ? GET_CACHE(re, gb) : 0;
1688                             LAST_SKIP_BITS(re, gb, nnz);
1689                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1690                         } while (len -= 4);
1691                     }
1692                     break;
1693
1694                 case 2:
1695                     for (group = 0; group < g_len; group++, cfo+=128) {
1696                         float *cf = cfo;
1697                         int len = off_len;
1698
1699                         do {
1700                             int code;
1701                             unsigned cb_idx;
1702
1703                             UPDATE_CACHE(re, gb);
1704                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1705                             cb_idx = cb_vector_idx[code];
1706                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
1707                         } while (len -= 2);
1708                     }
1709                     break;
1710
1711                 case 3:
1712                 case 4:
1713                     for (group = 0; group < g_len; group++, cfo+=128) {
1714                         float *cf = cfo;
1715                         int len = off_len;
1716
1717                         do {
1718                             int code;
1719                             unsigned nnz;
1720                             unsigned cb_idx;
1721                             unsigned sign;
1722
1723                             UPDATE_CACHE(re, gb);
1724                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1725                             cb_idx = cb_vector_idx[code];
1726                             nnz = cb_idx >> 8 & 15;
1727                             sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1728                             LAST_SKIP_BITS(re, gb, nnz);
1729                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1730                         } while (len -= 2);
1731                     }
1732                     break;
1733
1734                 default:
1735                     for (group = 0; group < g_len; group++, cfo+=128) {
1736                         float *cf = cfo;
1737                         uint32_t *icf = (uint32_t *) cf;
1738                         int len = off_len;
1739
1740                         do {
1741                             int code;
1742                             unsigned nzt, nnz;
1743                             unsigned cb_idx;
1744                             uint32_t bits;
1745                             int j;
1746
1747                             UPDATE_CACHE(re, gb);
1748                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1749
1750                             if (!code) {
1751                                 *icf++ = 0;
1752                                 *icf++ = 0;
1753                                 continue;
1754                             }
1755
1756                             cb_idx = cb_vector_idx[code];
1757                             nnz = cb_idx >> 12;
1758                             nzt = cb_idx >> 8;
1759                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1760                             LAST_SKIP_BITS(re, gb, nnz);
1761
1762                             for (j = 0; j < 2; j++) {
1763                                 if (nzt & 1<<j) {
1764                                     uint32_t b;
1765                                     int n;
1766                                     /* The total length of escape_sequence must be < 22 bits according
1767                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1768                                     UPDATE_CACHE(re, gb);
1769                                     b = GET_CACHE(re, gb);
1770                                     b = 31 - av_log2(~b);
1771
1772                                     if (b > 8) {
1773                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1774                                         return AVERROR_INVALIDDATA;
1775                                     }
1776
1777                                     SKIP_BITS(re, gb, b + 1);
1778                                     b += 4;
1779                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
1780                                     LAST_SKIP_BITS(re, gb, b);
1781                                     *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1782                                     bits <<= 1;
1783                                 } else {
1784                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1785                                     *icf++ = (bits & 1U<<31) | v;
1786                                     bits <<= !!v;
1787                                 }
1788                                 cb_idx >>= 4;
1789                             }
1790                         } while (len -= 2);
1791
1792                         ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1793                     }
1794                 }
1795
1796                 CLOSE_READER(re, gb);
1797             }
1798         }
1799         coef += g_len << 7;
1800     }
1801
1802     if (pulse_present) {
1803         idx = 0;
1804         for (i = 0; i < pulse->num_pulse; i++) {
1805             float co = coef_base[ pulse->pos[i] ];
1806             while (offsets[idx + 1] <= pulse->pos[i])
1807                 idx++;
1808             if (band_type[idx] != NOISE_BT && sf[idx]) {
1809                 float ico = -pulse->amp[i];
1810                 if (co) {
1811                     co /= sf[idx];
1812                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1813                 }
1814                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1815             }
1816         }
1817     }
1818     return 0;
1819 }
1820
1821 static av_always_inline float flt16_round(float pf)
1822 {
1823     union av_intfloat32 tmp;
1824     tmp.f = pf;
1825     tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1826     return tmp.f;
1827 }
1828
1829 static av_always_inline float flt16_even(float pf)
1830 {
1831     union av_intfloat32 tmp;
1832     tmp.f = pf;
1833     tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1834     return tmp.f;
1835 }
1836
1837 static av_always_inline float flt16_trunc(float pf)
1838 {
1839     union av_intfloat32 pun;
1840     pun.f = pf;
1841     pun.i &= 0xFFFF0000U;
1842     return pun.f;
1843 }
1844
1845 static av_always_inline void predict(PredictorState *ps, float *coef,
1846                                      int output_enable)
1847 {
1848     const float a     = 0.953125; // 61.0 / 64
1849     const float alpha = 0.90625;  // 29.0 / 32
1850     float e0, e1;
1851     float pv;
1852     float k1, k2;
1853     float   r0 = ps->r0,     r1 = ps->r1;
1854     float cor0 = ps->cor0, cor1 = ps->cor1;
1855     float var0 = ps->var0, var1 = ps->var1;
1856
1857     k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1858     k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1859
1860     pv = flt16_round(k1 * r0 + k2 * r1);
1861     if (output_enable)
1862         *coef += pv;
1863
1864     e0 = *coef;
1865     e1 = e0 - k1 * r0;
1866
1867     ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1868     ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1869     ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1870     ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1871
1872     ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1873     ps->r0 = flt16_trunc(a * e0);
1874 }
1875
1876 /**
1877  * Apply AAC-Main style frequency domain prediction.
1878  */
1879 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1880 {
1881     int sfb, k;
1882
1883     if (!sce->ics.predictor_initialized) {
1884         reset_all_predictors(sce->predictor_state);
1885         sce->ics.predictor_initialized = 1;
1886     }
1887
1888     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1889         for (sfb = 0;
1890              sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1891              sfb++) {
1892             for (k = sce->ics.swb_offset[sfb];
1893                  k < sce->ics.swb_offset[sfb + 1];
1894                  k++) {
1895                 predict(&sce->predictor_state[k], &sce->coeffs[k],
1896                         sce->ics.predictor_present &&
1897                         sce->ics.prediction_used[sfb]);
1898             }
1899         }
1900         if (sce->ics.predictor_reset_group)
1901             reset_predictor_group(sce->predictor_state,
1902                                   sce->ics.predictor_reset_group);
1903     } else
1904         reset_all_predictors(sce->predictor_state);
1905 }
1906
1907 /**
1908  * Decode an individual_channel_stream payload; reference: table 4.44.
1909  *
1910  * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
1911  * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1912  *
1913  * @return  Returns error status. 0 - OK, !0 - error
1914  */
1915 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1916                       GetBitContext *gb, int common_window, int scale_flag)
1917 {
1918     Pulse pulse;
1919     TemporalNoiseShaping    *tns = &sce->tns;
1920     IndividualChannelStream *ics = &sce->ics;
1921     float *out = sce->coeffs;
1922     int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1923     int ret;
1924
1925     eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1926     er_syntax  = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1927                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1928                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1929                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1930
1931     /* This assignment is to silence a GCC warning about the variable being used
1932      * uninitialized when in fact it always is.
1933      */
1934     pulse.num_pulse = 0;
1935
1936     global_gain = get_bits(gb, 8);
1937
1938     if (!common_window && !scale_flag) {
1939         if (decode_ics_info(ac, ics, gb) < 0)
1940             return AVERROR_INVALIDDATA;
1941     }
1942
1943     if ((ret = decode_band_types(ac, sce->band_type,
1944                                  sce->band_type_run_end, gb, ics)) < 0)
1945         return ret;
1946     if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1947                                   sce->band_type, sce->band_type_run_end)) < 0)
1948         return ret;
1949
1950     pulse_present = 0;
1951     if (!scale_flag) {
1952         if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1953             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1954                 av_log(ac->avctx, AV_LOG_ERROR,
1955                        "Pulse tool not allowed in eight short sequence.\n");
1956                 return AVERROR_INVALIDDATA;
1957             }
1958             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1959                 av_log(ac->avctx, AV_LOG_ERROR,
1960                        "Pulse data corrupt or invalid.\n");
1961                 return AVERROR_INVALIDDATA;
1962             }
1963         }
1964         tns->present = get_bits1(gb);
1965         if (tns->present && !er_syntax)
1966             if (decode_tns(ac, tns, gb, ics) < 0)
1967                 return AVERROR_INVALIDDATA;
1968         if (!eld_syntax && get_bits1(gb)) {
1969             avpriv_request_sample(ac->avctx, "SSR");
1970             return AVERROR_PATCHWELCOME;
1971         }
1972         // I see no textual basis in the spec for this occurring after SSR gain
1973         // control, but this is what both reference and real implmentations do
1974         if (tns->present && er_syntax)
1975             if (decode_tns(ac, tns, gb, ics) < 0)
1976                 return AVERROR_INVALIDDATA;
1977     }
1978
1979     if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1980                                     &pulse, ics, sce->band_type) < 0)
1981         return AVERROR_INVALIDDATA;
1982
1983     if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1984         apply_prediction(ac, sce);
1985
1986     return 0;
1987 }
1988
1989 /**
1990  * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1991  */
1992 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1993 {
1994     const IndividualChannelStream *ics = &cpe->ch[0].ics;
1995     float *ch0 = cpe->ch[0].coeffs;
1996     float *ch1 = cpe->ch[1].coeffs;
1997     int g, i, group, idx = 0;
1998     const uint16_t *offsets = ics->swb_offset;
1999     for (g = 0; g < ics->num_window_groups; g++) {
2000         for (i = 0; i < ics->max_sfb; i++, idx++) {
2001             if (cpe->ms_mask[idx] &&
2002                 cpe->ch[0].band_type[idx] < NOISE_BT &&
2003                 cpe->ch[1].band_type[idx] < NOISE_BT) {
2004                 for (group = 0; group < ics->group_len[g]; group++) {
2005                     ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
2006                                                ch1 + group * 128 + offsets[i],
2007                                                offsets[i+1] - offsets[i]);
2008                 }
2009             }
2010         }
2011         ch0 += ics->group_len[g] * 128;
2012         ch1 += ics->group_len[g] * 128;
2013     }
2014 }
2015
2016 /**
2017  * intensity stereo decoding; reference: 4.6.8.2.3
2018  *
2019  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
2020  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
2021  *                      [3] reserved for scalable AAC
2022  */
2023 static void apply_intensity_stereo(AACContext *ac,
2024                                    ChannelElement *cpe, int ms_present)
2025 {
2026     const IndividualChannelStream *ics = &cpe->ch[1].ics;
2027     SingleChannelElement         *sce1 = &cpe->ch[1];
2028     float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2029     const uint16_t *offsets = ics->swb_offset;
2030     int g, group, i, idx = 0;
2031     int c;
2032     float scale;
2033     for (g = 0; g < ics->num_window_groups; g++) {
2034         for (i = 0; i < ics->max_sfb;) {
2035             if (sce1->band_type[idx] == INTENSITY_BT ||
2036                 sce1->band_type[idx] == INTENSITY_BT2) {
2037                 const int bt_run_end = sce1->band_type_run_end[idx];
2038                 for (; i < bt_run_end; i++, idx++) {
2039                     c = -1 + 2 * (sce1->band_type[idx] - 14);
2040                     if (ms_present)
2041                         c *= 1 - 2 * cpe->ms_mask[idx];
2042                     scale = c * sce1->sf[idx];
2043                     for (group = 0; group < ics->group_len[g]; group++)
2044                         ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2045                                                     coef0 + group * 128 + offsets[i],
2046                                                     scale,
2047                                                     offsets[i + 1] - offsets[i]);
2048                 }
2049             } else {
2050                 int bt_run_end = sce1->band_type_run_end[idx];
2051                 idx += bt_run_end - i;
2052                 i    = bt_run_end;
2053             }
2054         }
2055         coef0 += ics->group_len[g] * 128;
2056         coef1 += ics->group_len[g] * 128;
2057     }
2058 }
2059
2060 /**
2061  * Decode a channel_pair_element; reference: table 4.4.
2062  *
2063  * @return  Returns error status. 0 - OK, !0 - error
2064  */
2065 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2066 {
2067     int i, ret, common_window, ms_present = 0;
2068     int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2069
2070     common_window = eld_syntax || get_bits1(gb);
2071     if (common_window) {
2072         if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2073             return AVERROR_INVALIDDATA;
2074         i = cpe->ch[1].ics.use_kb_window[0];
2075         cpe->ch[1].ics = cpe->ch[0].ics;
2076         cpe->ch[1].ics.use_kb_window[1] = i;
2077         if (cpe->ch[1].ics.predictor_present &&
2078             (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2079             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2080                 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2081         ms_present = get_bits(gb, 2);
2082         if (ms_present == 3) {
2083             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2084             return AVERROR_INVALIDDATA;
2085         } else if (ms_present)
2086             decode_mid_side_stereo(cpe, gb, ms_present);
2087     }
2088     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2089         return ret;
2090     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2091         return ret;
2092
2093     if (common_window) {
2094         if (ms_present)
2095             apply_mid_side_stereo(ac, cpe);
2096         if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2097             apply_prediction(ac, &cpe->ch[0]);
2098             apply_prediction(ac, &cpe->ch[1]);
2099         }
2100     }
2101
2102     apply_intensity_stereo(ac, cpe, ms_present);
2103     return 0;
2104 }
2105
2106 static const float cce_scale[] = {
2107     1.09050773266525765921, //2^(1/8)
2108     1.18920711500272106672, //2^(1/4)
2109     M_SQRT2,
2110     2,
2111 };
2112
2113 /**
2114  * Decode coupling_channel_element; reference: table 4.8.
2115  *
2116  * @return  Returns error status. 0 - OK, !0 - error
2117  */
2118 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2119 {
2120     int num_gain = 0;
2121     int c, g, sfb, ret;
2122     int sign;
2123     float scale;
2124     SingleChannelElement *sce = &che->ch[0];
2125     ChannelCoupling     *coup = &che->coup;
2126
2127     coup->coupling_point = 2 * get_bits1(gb);
2128     coup->num_coupled = get_bits(gb, 3);
2129     for (c = 0; c <= coup->num_coupled; c++) {
2130         num_gain++;
2131         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2132         coup->id_select[c] = get_bits(gb, 4);
2133         if (coup->type[c] == TYPE_CPE) {
2134             coup->ch_select[c] = get_bits(gb, 2);
2135             if (coup->ch_select[c] == 3)
2136                 num_gain++;
2137         } else
2138             coup->ch_select[c] = 2;
2139     }
2140     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2141
2142     sign  = get_bits(gb, 1);
2143     scale = cce_scale[get_bits(gb, 2)];
2144
2145     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2146         return ret;
2147
2148     for (c = 0; c < num_gain; c++) {
2149         int idx  = 0;
2150         int cge  = 1;
2151         int gain = 0;
2152         float gain_cache = 1.0;
2153         if (c) {
2154             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2155             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2156             gain_cache = powf(scale, -gain);
2157         }
2158         if (coup->coupling_point == AFTER_IMDCT) {
2159             coup->gain[c][0] = gain_cache;
2160         } else {
2161             for (g = 0; g < sce->ics.num_window_groups; g++) {
2162                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2163                     if (sce->band_type[idx] != ZERO_BT) {
2164                         if (!cge) {
2165                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2166                             if (t) {
2167                                 int s = 1;
2168                                 t = gain += t;
2169                                 if (sign) {
2170                                     s  -= 2 * (t & 0x1);
2171                                     t >>= 1;
2172                                 }
2173                                 gain_cache = powf(scale, -t) * s;
2174                             }
2175                         }
2176                         coup->gain[c][idx] = gain_cache;
2177                     }
2178                 }
2179             }
2180         }
2181     }
2182     return 0;
2183 }
2184
2185 /**
2186  * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2187  *
2188  * @return  Returns number of bytes consumed.
2189  */
2190 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2191                                          GetBitContext *gb)
2192 {
2193     int i;
2194     int num_excl_chan = 0;
2195
2196     do {
2197         for (i = 0; i < 7; i++)
2198             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2199     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2200
2201     return num_excl_chan / 7;
2202 }
2203
2204 /**
2205  * Decode dynamic range information; reference: table 4.52.
2206  *
2207  * @return  Returns number of bytes consumed.
2208  */
2209 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2210                                 GetBitContext *gb)
2211 {
2212     int n             = 1;
2213     int drc_num_bands = 1;
2214     int i;
2215
2216     /* pce_tag_present? */
2217     if (get_bits1(gb)) {
2218         che_drc->pce_instance_tag  = get_bits(gb, 4);
2219         skip_bits(gb, 4); // tag_reserved_bits
2220         n++;
2221     }
2222
2223     /* excluded_chns_present? */
2224     if (get_bits1(gb)) {
2225         n += decode_drc_channel_exclusions(che_drc, gb);
2226     }
2227
2228     /* drc_bands_present? */
2229     if (get_bits1(gb)) {
2230         che_drc->band_incr            = get_bits(gb, 4);
2231         che_drc->interpolation_scheme = get_bits(gb, 4);
2232         n++;
2233         drc_num_bands += che_drc->band_incr;
2234         for (i = 0; i < drc_num_bands; i++) {
2235             che_drc->band_top[i] = get_bits(gb, 8);
2236             n++;
2237         }
2238     }
2239
2240     /* prog_ref_level_present? */
2241     if (get_bits1(gb)) {
2242         che_drc->prog_ref_level = get_bits(gb, 7);
2243         skip_bits1(gb); // prog_ref_level_reserved_bits
2244         n++;
2245     }
2246
2247     for (i = 0; i < drc_num_bands; i++) {
2248         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2249         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2250         n++;
2251     }
2252
2253     return n;
2254 }
2255
2256 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2257     uint8_t buf[256];
2258     int i, major, minor;
2259
2260     if (len < 13+7*8)
2261         goto unknown;
2262
2263     get_bits(gb, 13); len -= 13;
2264
2265     for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2266         buf[i] = get_bits(gb, 8);
2267
2268     buf[i] = 0;
2269     if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2270         av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2271
2272     if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2273         ac->avctx->internal->skip_samples = 1024;
2274     }
2275
2276 unknown:
2277     skip_bits_long(gb, len);
2278
2279     return 0;
2280 }
2281
2282 /**
2283  * Decode extension data (incomplete); reference: table 4.51.
2284  *
2285  * @param   cnt length of TYPE_FIL syntactic element in bytes
2286  *
2287  * @return Returns number of bytes consumed
2288  */
2289 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2290                                     ChannelElement *che, enum RawDataBlockType elem_type)
2291 {
2292     int crc_flag = 0;
2293     int res = cnt;
2294     int type = get_bits(gb, 4);
2295
2296     if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2297         av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2298
2299     switch (type) { // extension type
2300     case EXT_SBR_DATA_CRC:
2301         crc_flag++;
2302     case EXT_SBR_DATA:
2303         if (!che) {
2304             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2305             return res;
2306         } else if (!ac->oc[1].m4ac.sbr) {
2307             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2308             skip_bits_long(gb, 8 * cnt - 4);
2309             return res;
2310         } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2311             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2312             skip_bits_long(gb, 8 * cnt - 4);
2313             return res;
2314         } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2315             ac->oc[1].m4ac.sbr = 1;
2316             ac->oc[1].m4ac.ps = 1;
2317             ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2318             output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2319                              ac->oc[1].status, 1);
2320         } else {
2321             ac->oc[1].m4ac.sbr = 1;
2322             ac->avctx->profile = FF_PROFILE_AAC_HE;
2323         }
2324         res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2325         break;
2326     case EXT_DYNAMIC_RANGE:
2327         res = decode_dynamic_range(&ac->che_drc, gb);
2328         break;
2329     case EXT_FILL:
2330         decode_fill(ac, gb, 8 * cnt - 4);
2331         break;
2332     case EXT_FILL_DATA:
2333     case EXT_DATA_ELEMENT:
2334     default:
2335         skip_bits_long(gb, 8 * cnt - 4);
2336         break;
2337     };
2338     return res;
2339 }
2340
2341 /**
2342  * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2343  *
2344  * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
2345  * @param   coef    spectral coefficients
2346  */
2347 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2348                       IndividualChannelStream *ics, int decode)
2349 {
2350     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2351     int w, filt, m, i;
2352     int bottom, top, order, start, end, size, inc;
2353     float lpc[TNS_MAX_ORDER];
2354     float tmp[TNS_MAX_ORDER+1];
2355
2356     for (w = 0; w < ics->num_windows; w++) {
2357         bottom = ics->num_swb;
2358         for (filt = 0; filt < tns->n_filt[w]; filt++) {
2359             top    = bottom;
2360             bottom = FFMAX(0, top - tns->length[w][filt]);
2361             order  = tns->order[w][filt];
2362             if (order == 0)
2363                 continue;
2364
2365             // tns_decode_coef
2366             compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2367
2368             start = ics->swb_offset[FFMIN(bottom, mmm)];
2369             end   = ics->swb_offset[FFMIN(   top, mmm)];
2370             if ((size = end - start) <= 0)
2371                 continue;
2372             if (tns->direction[w][filt]) {
2373                 inc = -1;
2374                 start = end - 1;
2375             } else {
2376                 inc = 1;
2377             }
2378             start += w * 128;
2379
2380             if (decode) {
2381                 // ar filter
2382                 for (m = 0; m < size; m++, start += inc)
2383                     for (i = 1; i <= FFMIN(m, order); i++)
2384                         coef[start] -= coef[start - i * inc] * lpc[i - 1];
2385             } else {
2386                 // ma filter
2387                 for (m = 0; m < size; m++, start += inc) {
2388                     tmp[0] = coef[start];
2389                     for (i = 1; i <= FFMIN(m, order); i++)
2390                         coef[start] += tmp[i] * lpc[i - 1];
2391                     for (i = order; i > 0; i--)
2392                         tmp[i] = tmp[i - 1];
2393                 }
2394             }
2395         }
2396     }
2397 }
2398
2399 /**
2400  *  Apply windowing and MDCT to obtain the spectral
2401  *  coefficient from the predicted sample by LTP.
2402  */
2403 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2404                                    float *in, IndividualChannelStream *ics)
2405 {
2406     const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2407     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2408     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2409     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2410
2411     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2412         ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2413     } else {
2414         memset(in, 0, 448 * sizeof(float));
2415         ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2416     }
2417     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2418         ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2419     } else {
2420         ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2421         memset(in + 1024 + 576, 0, 448 * sizeof(float));
2422     }
2423     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2424 }
2425
2426 /**
2427  * Apply the long term prediction
2428  */
2429 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2430 {
2431     const LongTermPrediction *ltp = &sce->ics.ltp;
2432     const uint16_t *offsets = sce->ics.swb_offset;
2433     int i, sfb;
2434
2435     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2436         float *predTime = sce->ret;
2437         float *predFreq = ac->buf_mdct;
2438         int16_t num_samples = 2048;
2439
2440         if (ltp->lag < 1024)
2441             num_samples = ltp->lag + 1024;
2442         for (i = 0; i < num_samples; i++)
2443             predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2444         memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2445
2446         ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2447
2448         if (sce->tns.present)
2449             ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2450
2451         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2452             if (ltp->used[sfb])
2453                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2454                     sce->coeffs[i] += predFreq[i];
2455     }
2456 }
2457
2458 /**
2459  * Update the LTP buffer for next frame
2460  */
2461 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2462 {
2463     IndividualChannelStream *ics = &sce->ics;
2464     float *saved     = sce->saved;
2465     float *saved_ltp = sce->coeffs;
2466     const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2467     const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2468     int i;
2469
2470     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2471         memcpy(saved_ltp,       saved, 512 * sizeof(float));
2472         memset(saved_ltp + 576, 0,     448 * sizeof(float));
2473         ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2474         for (i = 0; i < 64; i++)
2475             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2476     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2477         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
2478         memset(saved_ltp + 576, 0,                  448 * sizeof(float));
2479         ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2480         for (i = 0; i < 64; i++)
2481             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2482     } else { // LONG_STOP or ONLY_LONG
2483         ac->fdsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
2484         for (i = 0; i < 512; i++)
2485             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2486     }
2487
2488     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2489     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
2490     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
2491 }
2492
2493 /**
2494  * Conduct IMDCT and windowing.
2495  */
2496 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2497 {
2498     IndividualChannelStream *ics = &sce->ics;
2499     float *in    = sce->coeffs;
2500     float *out   = sce->ret;
2501     float *saved = sce->saved;
2502     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2503     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2504     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2505     float *buf  = ac->buf_mdct;
2506     float *temp = ac->temp;
2507     int i;
2508
2509     // imdct
2510     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2511         for (i = 0; i < 1024; i += 128)
2512             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2513     } else
2514         ac->mdct.imdct_half(&ac->mdct, buf, in);
2515
2516     /* window overlapping
2517      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2518      * and long to short transitions are considered to be short to short
2519      * transitions. This leaves just two cases (long to long and short to short)
2520      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2521      */
2522     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2523             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2524         ac->fdsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
2525     } else {
2526         memcpy(                         out,               saved,            448 * sizeof(float));
2527
2528         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2529             ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
2530             ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
2531             ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
2532             ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
2533             ac->fdsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
2534             memcpy(                     out + 448 + 4*128, temp, 64 * sizeof(float));
2535         } else {
2536             ac->fdsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
2537             memcpy(                     out + 576,         buf + 64,         448 * sizeof(float));
2538         }
2539     }
2540
2541     // buffer update
2542     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2543         memcpy(                     saved,       temp + 64,         64 * sizeof(float));
2544         ac->fdsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
2545         ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2546         ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2547         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2548     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2549         memcpy(                     saved,       buf + 512,        448 * sizeof(float));
2550         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2551     } else { // LONG_STOP or ONLY_LONG
2552         memcpy(                     saved,       buf + 512,        512 * sizeof(float));
2553     }
2554 }
2555
2556 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2557 {
2558     IndividualChannelStream *ics = &sce->ics;
2559     float *in    = sce->coeffs;
2560     float *out   = sce->ret;
2561     float *saved = sce->saved;
2562     float *buf  = ac->buf_mdct;
2563
2564     // imdct
2565     ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2566
2567     // window overlapping
2568     if (ics->use_kb_window[1]) {
2569         // AAC LD uses a low overlap sine window instead of a KBD window
2570         memcpy(out, saved, 192 * sizeof(float));
2571         ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2572         memcpy(                     out + 320, buf + 64, 192 * sizeof(float));
2573     } else {
2574         ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2575     }
2576
2577     // buffer update
2578     memcpy(saved, buf + 256, 256 * sizeof(float));
2579 }
2580
2581 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2582 {
2583     float *in    = sce->coeffs;
2584     float *out   = sce->ret;
2585     float *saved = sce->saved;
2586     const float *const window = ff_aac_eld_window;
2587     float *buf  = ac->buf_mdct;
2588     int i;
2589     const int n  = 512;
2590     const int n2 = n >> 1;
2591     const int n4 = n >> 2;
2592
2593     // Inverse transform, mapped to the conventional IMDCT by
2594     // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2595     // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2596     // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2597     // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2598     for (i = 0; i < n2; i+=2) {
2599         float temp;
2600         temp =  in[i    ]; in[i    ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2601         temp = -in[i + 1]; in[i + 1] =  in[n - 2 - i]; in[n - 2 - i] = temp;
2602     }
2603     ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2604     for (i = 0; i < n; i+=2) {
2605         buf[i] = -buf[i];
2606     }
2607     // Like with the regular IMDCT at this point we still have the middle half
2608     // of a transform but with even symmetry on the left and odd symmetry on
2609     // the right
2610
2611     // window overlapping
2612     // The spec says to use samples [0..511] but the reference decoder uses
2613     // samples [128..639].
2614     for (i = n4; i < n2; i ++) {
2615         out[i - n4] =    buf[n2 - 1 - i]       * window[i       - n4] +
2616                        saved[      i + n2]     * window[i +   n - n4] +
2617                       -saved[  n + n2 - 1 - i] * window[i + 2*n - n4] +
2618                       -saved[2*n + n2 + i]     * window[i + 3*n - n4];
2619     }
2620     for (i = 0; i < n2; i ++) {
2621         out[n4 + i] =    buf[i]               * window[i + n2       - n4] +
2622                       -saved[      n - 1 - i] * window[i + n2 +   n - n4] +
2623                       -saved[  n + i]         * window[i + n2 + 2*n - n4] +
2624                        saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2625     }
2626     for (i = 0; i < n4; i ++) {
2627         out[n2 + n4 + i] =    buf[      i + n2]     * window[i +   n - n4] +
2628                            -saved[      n2 - 1 - i] * window[i + 2*n - n4] +
2629                            -saved[  n + n2 + i]     * window[i + 3*n - n4];
2630     }
2631
2632     // buffer update
2633     memmove(saved + n, saved, 2 * n * sizeof(float));
2634     memcpy( saved,       buf,     n * sizeof(float));
2635 }
2636
2637 /**
2638  * Apply dependent channel coupling (applied before IMDCT).
2639  *
2640  * @param   index   index into coupling gain array
2641  */
2642 static void apply_dependent_coupling(AACContext *ac,
2643                                      SingleChannelElement *target,
2644                                      ChannelElement *cce, int index)
2645 {
2646     IndividualChannelStream *ics = &cce->ch[0].ics;
2647     const uint16_t *offsets = ics->swb_offset;
2648     float *dest = target->coeffs;
2649     const float *src = cce->ch[0].coeffs;
2650     int g, i, group, k, idx = 0;
2651     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2652         av_log(ac->avctx, AV_LOG_ERROR,
2653                "Dependent coupling is not supported together with LTP\n");
2654         return;
2655     }
2656     for (g = 0; g < ics->num_window_groups; g++) {
2657         for (i = 0; i < ics->max_sfb; i++, idx++) {
2658             if (cce->ch[0].band_type[idx] != ZERO_BT) {
2659                 const float gain = cce->coup.gain[index][idx];
2660                 for (group = 0; group < ics->group_len[g]; group++) {
2661                     for (k = offsets[i]; k < offsets[i + 1]; k++) {
2662                         // FIXME: SIMDify
2663                         dest[group * 128 + k] += gain * src[group * 128 + k];
2664                     }
2665                 }
2666             }
2667         }
2668         dest += ics->group_len[g] * 128;
2669         src  += ics->group_len[g] * 128;
2670     }
2671 }
2672
2673 /**
2674  * Apply independent channel coupling (applied after IMDCT).
2675  *
2676  * @param   index   index into coupling gain array
2677  */
2678 static void apply_independent_coupling(AACContext *ac,
2679                                        SingleChannelElement *target,
2680                                        ChannelElement *cce, int index)
2681 {
2682     int i;
2683     const float gain = cce->coup.gain[index][0];
2684     const float *src = cce->ch[0].ret;
2685     float *dest = target->ret;
2686     const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2687
2688     for (i = 0; i < len; i++)
2689         dest[i] += gain * src[i];
2690 }
2691
2692 /**
2693  * channel coupling transformation interface
2694  *
2695  * @param   apply_coupling_method   pointer to (in)dependent coupling function
2696  */
2697 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2698                                    enum RawDataBlockType type, int elem_id,
2699                                    enum CouplingPoint coupling_point,
2700                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2701 {
2702     int i, c;
2703
2704     for (i = 0; i < MAX_ELEM_ID; i++) {
2705         ChannelElement *cce = ac->che[TYPE_CCE][i];
2706         int index = 0;
2707
2708         if (cce && cce->coup.coupling_point == coupling_point) {
2709             ChannelCoupling *coup = &cce->coup;
2710
2711             for (c = 0; c <= coup->num_coupled; c++) {
2712                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2713                     if (coup->ch_select[c] != 1) {
2714                         apply_coupling_method(ac, &cc->ch[0], cce, index);
2715                         if (coup->ch_select[c] != 0)
2716                             index++;
2717                     }
2718                     if (coup->ch_select[c] != 2)
2719                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
2720                 } else
2721                     index += 1 + (coup->ch_select[c] == 3);
2722             }
2723         }
2724     }
2725 }
2726
2727 /**
2728  * Convert spectral data to float samples, applying all supported tools as appropriate.
2729  */
2730 static void spectral_to_sample(AACContext *ac)
2731 {
2732     int i, type;
2733     void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2734     switch (ac->oc[1].m4ac.object_type) {
2735     case AOT_ER_AAC_LD:
2736         imdct_and_window = imdct_and_windowing_ld;
2737         break;
2738     case AOT_ER_AAC_ELD:
2739         imdct_and_window = imdct_and_windowing_eld;
2740         break;
2741     default:
2742         imdct_and_window = ac->imdct_and_windowing;
2743     }
2744     for (type = 3; type >= 0; type--) {
2745         for (i = 0; i < MAX_ELEM_ID; i++) {
2746             ChannelElement *che = ac->che[type][i];
2747             if (che && che->present) {
2748                 if (type <= TYPE_CPE)
2749                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2750                 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2751                     if (che->ch[0].ics.predictor_present) {
2752                         if (che->ch[0].ics.ltp.present)
2753                             ac->apply_ltp(ac, &che->ch[0]);
2754                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2755                             ac->apply_ltp(ac, &che->ch[1]);
2756                     }
2757                 }
2758                 if (che->ch[0].tns.present)
2759                     ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2760                 if (che->ch[1].tns.present)
2761                     ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2762                 if (type <= TYPE_CPE)
2763                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2764                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2765                     imdct_and_window(ac, &che->ch[0]);
2766                     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2767                         ac->update_ltp(ac, &che->ch[0]);
2768                     if (type == TYPE_CPE) {
2769                         imdct_and_window(ac, &che->ch[1]);
2770                         if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2771                             ac->update_ltp(ac, &che->ch[1]);
2772                     }
2773                     if (ac->oc[1].m4ac.sbr > 0) {
2774                         ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2775                     }
2776                 }
2777                 if (type <= TYPE_CCE)
2778                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2779                 che->present = 0;
2780             } else if (che) {
2781                 av_log(ac->avctx, AV_LOG_WARNING, "ChannelElement %d.%d missing \n", type, i);
2782             }
2783         }
2784     }
2785 }
2786
2787 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2788 {
2789     int size;
2790     AACADTSHeaderInfo hdr_info;
2791     uint8_t layout_map[MAX_ELEM_ID*4][3];
2792     int layout_map_tags, ret;
2793
2794     size = avpriv_aac_parse_header(gb, &hdr_info);
2795     if (size > 0) {
2796         if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2797             // This is 2 for "VLB " audio in NSV files.
2798             // See samples/nsv/vlb_audio.
2799             avpriv_report_missing_feature(ac->avctx,
2800                                           "More than one AAC RDB per ADTS frame");
2801             ac->warned_num_aac_frames = 1;
2802         }
2803         push_output_configuration(ac);
2804         if (hdr_info.chan_config) {
2805             ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2806             if ((ret = set_default_channel_config(ac->avctx,
2807                                                   layout_map,
2808                                                   &layout_map_tags,
2809                                                   hdr_info.chan_config)) < 0)
2810                 return ret;
2811             if ((ret = output_configure(ac, layout_map, layout_map_tags,
2812                                         FFMAX(ac->oc[1].status,
2813                                               OC_TRIAL_FRAME), 0)) < 0)
2814                 return ret;
2815         } else {
2816             ac->oc[1].m4ac.chan_config = 0;
2817             /**
2818              * dual mono frames in Japanese DTV can have chan_config 0
2819              * WITHOUT specifying PCE.
2820              *  thus, set dual mono as default.
2821              */
2822             if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2823                 layout_map_tags = 2;
2824                 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2825                 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2826                 layout_map[0][1] = 0;
2827                 layout_map[1][1] = 1;
2828                 if (output_configure(ac, layout_map, layout_map_tags,
2829                                      OC_TRIAL_FRAME, 0))
2830                     return -7;
2831             }
2832         }
2833         ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
2834         ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
2835         ac->oc[1].m4ac.object_type     = hdr_info.object_type;
2836         if (ac->oc[0].status != OC_LOCKED ||
2837             ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2838             ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2839             ac->oc[1].m4ac.sbr = -1;
2840             ac->oc[1].m4ac.ps  = -1;
2841         }
2842         if (!hdr_info.crc_absent)
2843             skip_bits(gb, 16);
2844     }
2845     return size;
2846 }
2847
2848 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2849                                int *got_frame_ptr, GetBitContext *gb)
2850 {
2851     AACContext *ac = avctx->priv_data;
2852     ChannelElement *che;
2853     int err, i;
2854     int samples = 1024;
2855     int chan_config = ac->oc[1].m4ac.chan_config;
2856     int aot = ac->oc[1].m4ac.object_type;
2857
2858     if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2859         samples >>= 1;
2860
2861     ac->frame = data;
2862
2863     if ((err = frame_configure_elements(avctx)) < 0)
2864         return err;
2865
2866     // The FF_PROFILE_AAC_* defines are all object_type - 1
2867     // This may lead to an undefined profile being signaled
2868     ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2869
2870     ac->tags_mapped = 0;
2871
2872     if (chan_config < 0 || chan_config >= 8) {
2873         avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2874                               ac->oc[1].m4ac.chan_config);
2875         return AVERROR_INVALIDDATA;
2876     }
2877     for (i = 0; i < tags_per_config[chan_config]; i++) {
2878         const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2879         const int elem_id   = aac_channel_layout_map[chan_config-1][i][1];
2880         if (!(che=get_che(ac, elem_type, elem_id))) {
2881             av_log(ac->avctx, AV_LOG_ERROR,
2882                    "channel element %d.%d is not allocated\n",
2883                    elem_type, elem_id);
2884             return AVERROR_INVALIDDATA;
2885         }
2886         che->present = 1;
2887         if (aot != AOT_ER_AAC_ELD)
2888             skip_bits(gb, 4);
2889         switch (elem_type) {
2890         case TYPE_SCE:
2891             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2892             break;
2893         case TYPE_CPE:
2894             err = decode_cpe(ac, gb, che);
2895             break;
2896         case TYPE_LFE:
2897             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2898             break;
2899         }
2900         if (err < 0)
2901             return err;
2902     }
2903
2904     spectral_to_sample(ac);
2905
2906     ac->frame->nb_samples = samples;
2907     ac->frame->sample_rate = avctx->sample_rate;
2908     *got_frame_ptr = 1;
2909
2910     skip_bits_long(gb, get_bits_left(gb));
2911     return 0;
2912 }
2913
2914 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2915                                 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2916 {
2917     AACContext *ac = avctx->priv_data;
2918     ChannelElement *che = NULL, *che_prev = NULL;
2919     enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2920     int err, elem_id;
2921     int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2922     int is_dmono, sce_count = 0;
2923
2924     ac->frame = data;
2925
2926     if (show_bits(gb, 12) == 0xfff) {
2927         if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2928             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2929             goto fail;
2930         }
2931         if (ac->oc[1].m4ac.sampling_index > 12) {
2932             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2933             err = AVERROR_INVALIDDATA;
2934             goto fail;
2935         }
2936     }
2937
2938     if ((err = frame_configure_elements(avctx)) < 0)
2939         goto fail;
2940
2941     // The FF_PROFILE_AAC_* defines are all object_type - 1
2942     // This may lead to an undefined profile being signaled
2943     ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2944
2945     ac->tags_mapped = 0;
2946     // parse
2947     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2948         elem_id = get_bits(gb, 4);
2949
2950         if (avctx->debug & FF_DEBUG_STARTCODE)
2951             av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
2952
2953         if (elem_type < TYPE_DSE) {
2954             if (!(che=get_che(ac, elem_type, elem_id))) {
2955                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2956                        elem_type, elem_id);
2957                 err = AVERROR_INVALIDDATA;
2958                 goto fail;
2959             }
2960             samples = 1024;
2961             che->present = 1;
2962         }
2963
2964         switch (elem_type) {
2965
2966         case TYPE_SCE:
2967             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2968             audio_found = 1;
2969             sce_count++;
2970             break;
2971
2972         case TYPE_CPE:
2973             err = decode_cpe(ac, gb, che);
2974             audio_found = 1;
2975             break;
2976
2977         case TYPE_CCE:
2978             err = decode_cce(ac, gb, che);
2979             break;
2980
2981         case TYPE_LFE:
2982             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2983             audio_found = 1;
2984             break;
2985
2986         case TYPE_DSE:
2987             err = skip_data_stream_element(ac, gb);
2988             break;
2989
2990         case TYPE_PCE: {
2991             uint8_t layout_map[MAX_ELEM_ID*4][3];
2992             int tags;
2993             push_output_configuration(ac);
2994             tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2995             if (tags < 0) {
2996                 err = tags;
2997                 break;
2998             }
2999             if (pce_found) {
3000                 av_log(avctx, AV_LOG_ERROR,
3001                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
3002             } else {
3003                 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
3004                 if (!err)
3005                     ac->oc[1].m4ac.chan_config = 0;
3006                 pce_found = 1;
3007             }
3008             break;
3009         }
3010
3011         case TYPE_FIL:
3012             if (elem_id == 15)
3013                 elem_id += get_bits(gb, 8) - 1;
3014             if (get_bits_left(gb) < 8 * elem_id) {
3015                     av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3016                     err = AVERROR_INVALIDDATA;
3017                     goto fail;
3018             }
3019             while (elem_id > 0)
3020                 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
3021             err = 0; /* FIXME */
3022             break;
3023
3024         default:
3025             err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3026             break;
3027         }
3028
3029         che_prev       = che;
3030         elem_type_prev = elem_type;
3031
3032         if (err)
3033             goto fail;
3034
3035         if (get_bits_left(gb) < 3) {
3036             av_log(avctx, AV_LOG_ERROR, overread_err);
3037             err = AVERROR_INVALIDDATA;
3038             goto fail;
3039         }
3040     }
3041
3042     spectral_to_sample(ac);
3043
3044     multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3045     samples <<= multiplier;
3046
3047     if (ac->oc[1].status && audio_found) {
3048         avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3049         avctx->frame_size = samples;
3050         ac->oc[1].status = OC_LOCKED;
3051     }
3052
3053     if (multiplier) {
3054         int side_size;
3055         const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
3056         if (side && side_size>=4)
3057             AV_WL32(side, 2*AV_RL32(side));
3058     }
3059
3060     *got_frame_ptr = !!samples;
3061     if (samples) {
3062         ac->frame->nb_samples = samples;
3063         ac->frame->sample_rate = avctx->sample_rate;
3064     } else
3065         av_frame_unref(ac->frame);
3066     *got_frame_ptr = !!samples;
3067
3068     /* for dual-mono audio (SCE + SCE) */
3069     is_dmono = ac->dmono_mode && sce_count == 2 &&
3070                ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
3071     if (is_dmono) {
3072         if (ac->dmono_mode == 1)
3073             ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3074         else if (ac->dmono_mode == 2)
3075             ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3076     }
3077
3078     return 0;
3079 fail:
3080     pop_output_configuration(ac);
3081     return err;
3082 }
3083
3084 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3085                             int *got_frame_ptr, AVPacket *avpkt)
3086 {
3087     AACContext *ac = avctx->priv_data;
3088     const uint8_t *buf = avpkt->data;
3089     int buf_size = avpkt->size;
3090     GetBitContext gb;
3091     int buf_consumed;
3092     int buf_offset;
3093     int err;
3094     int new_extradata_size;
3095     const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3096                                        AV_PKT_DATA_NEW_EXTRADATA,
3097                                        &new_extradata_size);
3098     int jp_dualmono_size;
3099     const uint8_t *jp_dualmono   = av_packet_get_side_data(avpkt,
3100                                        AV_PKT_DATA_JP_DUALMONO,
3101                                        &jp_dualmono_size);
3102
3103     if (new_extradata && 0) {
3104         av_free(avctx->extradata);
3105         avctx->extradata = av_mallocz(new_extradata_size +
3106                                       FF_INPUT_BUFFER_PADDING_SIZE);
3107         if (!avctx->extradata)
3108             return AVERROR(ENOMEM);
3109         avctx->extradata_size = new_extradata_size;
3110         memcpy(avctx->extradata, new_extradata, new_extradata_size);
3111         push_output_configuration(ac);
3112         if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3113                                          avctx->extradata,
3114                                          avctx->extradata_size*8, 1) < 0) {
3115             pop_output_configuration(ac);
3116             return AVERROR_INVALIDDATA;
3117         }
3118     }
3119
3120     ac->dmono_mode = 0;
3121     if (jp_dualmono && jp_dualmono_size > 0)
3122         ac->dmono_mode =  1 + *jp_dualmono;
3123     if (ac->force_dmono_mode >= 0)
3124         ac->dmono_mode = ac->force_dmono_mode;
3125
3126     if (INT_MAX / 8 <= buf_size)
3127         return AVERROR_INVALIDDATA;
3128
3129     if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3130         return err;
3131
3132     switch (ac->oc[1].m4ac.object_type) {
3133     case AOT_ER_AAC_LC:
3134     case AOT_ER_AAC_LTP:
3135     case AOT_ER_AAC_LD:
3136     case AOT_ER_AAC_ELD:
3137         err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3138         break;
3139     default:
3140         err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3141     }
3142     if (err < 0)
3143         return err;
3144
3145     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3146     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3147         if (buf[buf_offset])
3148             break;
3149
3150     return buf_size > buf_offset ? buf_consumed : buf_size;
3151 }
3152
3153 static av_cold int aac_decode_close(AVCodecContext *avctx)
3154 {
3155     AACContext *ac = avctx->priv_data;
3156     int i, type;
3157
3158     for (i = 0; i < MAX_ELEM_ID; i++) {
3159         for (type = 0; type < 4; type++) {
3160             if (ac->che[type][i])
3161                 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3162             av_freep(&ac->che[type][i]);
3163         }
3164     }
3165
3166     ff_mdct_end(&ac->mdct);
3167     ff_mdct_end(&ac->mdct_small);
3168     ff_mdct_end(&ac->mdct_ld);
3169     ff_mdct_end(&ac->mdct_ltp);
3170     return 0;
3171 }
3172
3173
3174 #define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
3175
3176 struct LATMContext {
3177     AACContext aac_ctx;     ///< containing AACContext
3178     int initialized;        ///< initialized after a valid extradata was seen
3179
3180     // parser data
3181     int audio_mux_version_A; ///< LATM syntax version
3182     int frame_length_type;   ///< 0/1 variable/fixed frame length
3183     int frame_length;        ///< frame length for fixed frame length
3184 };
3185
3186 static inline uint32_t latm_get_value(GetBitContext *b)
3187 {
3188     int length = get_bits(b, 2);
3189
3190     return get_bits_long(b, (length+1)*8);
3191 }
3192
3193 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
3194                                              GetBitContext *gb, int asclen)
3195 {
3196     AACContext *ac        = &latmctx->aac_ctx;
3197     AVCodecContext *avctx = ac->avctx;
3198     MPEG4AudioConfig m4ac = { 0 };
3199     int config_start_bit  = get_bits_count(gb);
3200     int sync_extension    = 0;
3201     int bits_consumed, esize;
3202
3203     if (asclen) {
3204         sync_extension = 1;
3205         asclen         = FFMIN(asclen, get_bits_left(gb));
3206     } else
3207         asclen         = get_bits_left(gb);
3208
3209     if (config_start_bit % 8) {
3210         avpriv_request_sample(latmctx->aac_ctx.avctx,
3211                               "Non-byte-aligned audio-specific config");
3212         return AVERROR_PATCHWELCOME;
3213     }
3214     if (asclen <= 0)
3215         return AVERROR_INVALIDDATA;
3216     bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3217                                          gb->buffer + (config_start_bit / 8),
3218                                          asclen, sync_extension);
3219
3220     if (bits_consumed < 0)
3221         return AVERROR_INVALIDDATA;
3222
3223     if (!latmctx->initialized ||
3224         ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3225         ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3226
3227         if(latmctx->initialized) {
3228             av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3229         } else {
3230             av_log(avctx, AV_LOG_DEBUG, "initializing latmctx\n");
3231         }
3232         latmctx->initialized = 0;
3233
3234         esize = (bits_consumed+7) / 8;
3235
3236         if (avctx->extradata_size < esize) {
3237             av_free(avctx->extradata);
3238             avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
3239             if (!avctx->extradata)
3240                 return AVERROR(ENOMEM);
3241         }
3242
3243         avctx->extradata_size = esize;
3244         memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3245         memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3246     }
3247     skip_bits_long(gb, bits_consumed);
3248
3249     return bits_consumed;
3250 }
3251
3252 static int read_stream_mux_config(struct LATMContext *latmctx,
3253                                   GetBitContext *gb)
3254 {
3255     int ret, audio_mux_version = get_bits(gb, 1);
3256
3257     latmctx->audio_mux_version_A = 0;
3258     if (audio_mux_version)
3259         latmctx->audio_mux_version_A = get_bits(gb, 1);
3260
3261     if (!latmctx->audio_mux_version_A) {
3262
3263         if (audio_mux_version)
3264             latm_get_value(gb);                 // taraFullness
3265
3266         skip_bits(gb, 1);                       // allStreamSameTimeFraming
3267         skip_bits(gb, 6);                       // numSubFrames
3268         // numPrograms
3269         if (get_bits(gb, 4)) {                  // numPrograms
3270             avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3271             return AVERROR_PATCHWELCOME;
3272         }
3273
3274         // for each program (which there is only one in DVB)
3275
3276         // for each layer (which there is only one in DVB)
3277         if (get_bits(gb, 3)) {                   // numLayer
3278             avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3279             return AVERROR_PATCHWELCOME;
3280         }
3281
3282         // for all but first stream: use_same_config = get_bits(gb, 1);
3283         if (!audio_mux_version) {
3284             if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3285                 return ret;
3286         } else {
3287             int ascLen = latm_get_value(gb);
3288             if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3289                 return ret;
3290             ascLen -= ret;
3291             skip_bits_long(gb, ascLen);
3292         }
3293
3294         latmctx->frame_length_type = get_bits(gb, 3);
3295         switch (latmctx->frame_length_type) {
3296         case 0:
3297             skip_bits(gb, 8);       // latmBufferFullness
3298             break;
3299         case 1:
3300             latmctx->frame_length = get_bits(gb, 9);
3301             break;
3302         case 3:
3303         case 4:
3304         case 5:
3305             skip_bits(gb, 6);       // CELP frame length table index
3306             break;
3307         case 6:
3308         case 7:
3309             skip_bits(gb, 1);       // HVXC frame length table index
3310             break;
3311         }
3312
3313         if (get_bits(gb, 1)) {                  // other data
3314             if (audio_mux_version) {
3315                 latm_get_value(gb);             // other_data_bits
3316             } else {
3317                 int esc;
3318                 do {
3319                     esc = get_bits(gb, 1);
3320                     skip_bits(gb, 8);
3321                 } while (esc);
3322             }
3323         }
3324
3325         if (get_bits(gb, 1))                     // crc present
3326             skip_bits(gb, 8);                    // config_crc
3327     }
3328
3329     return 0;
3330 }
3331
3332 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3333 {
3334     uint8_t tmp;
3335
3336     if (ctx->frame_length_type == 0) {
3337         int mux_slot_length = 0;
3338         do {
3339             tmp = get_bits(gb, 8);
3340             mux_slot_length += tmp;
3341         } while (tmp == 255);
3342         return mux_slot_length;
3343     } else if (ctx->frame_length_type == 1) {
3344         return ctx->frame_length;
3345     } else if (ctx->frame_length_type == 3 ||
3346                ctx->frame_length_type == 5 ||
3347                ctx->frame_length_type == 7) {
3348         skip_bits(gb, 2);          // mux_slot_length_coded
3349     }
3350     return 0;
3351 }
3352
3353 static int read_audio_mux_element(struct LATMContext *latmctx,
3354                                   GetBitContext *gb)
3355 {
3356     int err;
3357     uint8_t use_same_mux = get_bits(gb, 1);
3358     if (!use_same_mux) {
3359         if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3360             return err;
3361     } else if (!latmctx->aac_ctx.avctx->extradata) {
3362         av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3363                "no decoder config found\n");
3364         return AVERROR(EAGAIN);
3365     }
3366     if (latmctx->audio_mux_version_A == 0) {
3367         int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3368         if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3369             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3370             return AVERROR_INVALIDDATA;
3371         } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3372             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3373                    "frame length mismatch %d << %d\n",
3374                    mux_slot_length_bytes * 8, get_bits_left(gb));
3375             return AVERROR_INVALIDDATA;
3376         }
3377     }
3378     return 0;
3379 }
3380
3381
3382 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3383                              int *got_frame_ptr, AVPacket *avpkt)
3384 {
3385     struct LATMContext *latmctx = avctx->priv_data;
3386     int                 muxlength, err;
3387     GetBitContext       gb;
3388
3389     if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
3390         return err;
3391
3392     // check for LOAS sync word
3393     if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3394         return AVERROR_INVALIDDATA;
3395
3396     muxlength = get_bits(&gb, 13) + 3;
3397     // not enough data, the parser should have sorted this out
3398     if (muxlength > avpkt->size)
3399         return AVERROR_INVALIDDATA;
3400
3401     if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3402         return err;
3403
3404     if (!latmctx->initialized) {
3405         if (!avctx->extradata) {
3406             *got_frame_ptr = 0;
3407             return avpkt->size;
3408         } else {
3409             push_output_configuration(&latmctx->aac_ctx);
3410             if ((err = decode_audio_specific_config(
3411                     &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3412                     avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3413                 pop_output_configuration(&latmctx->aac_ctx);
3414                 return err;
3415             }
3416             latmctx->initialized = 1;
3417         }
3418     }
3419
3420     if (show_bits(&gb, 12) == 0xfff) {
3421         av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3422                "ADTS header detected, probably as result of configuration "
3423                "misparsing\n");
3424         return AVERROR_INVALIDDATA;
3425     }
3426
3427     if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
3428         return err;
3429
3430     return muxlength;
3431 }
3432
3433 static av_cold int latm_decode_init(AVCodecContext *avctx)
3434 {
3435     struct LATMContext *latmctx = avctx->priv_data;
3436     int ret = aac_decode_init(avctx);
3437
3438     if (avctx->extradata_size > 0)
3439         latmctx->initialized = !ret;
3440
3441     return ret;
3442 }
3443
3444 static void aacdec_init(AACContext *c)
3445 {
3446     c->imdct_and_windowing                      = imdct_and_windowing;
3447     c->apply_ltp                                = apply_ltp;
3448     c->apply_tns                                = apply_tns;
3449     c->windowing_and_mdct_ltp                   = windowing_and_mdct_ltp;
3450     c->update_ltp                               = update_ltp;
3451
3452     if(ARCH_MIPS)
3453         ff_aacdec_init_mips(c);
3454 }
3455 /**
3456  * AVOptions for Japanese DTV specific extensions (ADTS only)
3457  */
3458 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3459 static const AVOption options[] = {
3460     {"dual_mono_mode", "Select the channel to decode for dual mono",
3461      offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3462      AACDEC_FLAGS, "dual_mono_mode"},
3463
3464     {"auto", "autoselection",            0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3465     {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3466     {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3467     {"both", "Select both channels",     0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3468
3469     {NULL},
3470 };
3471
3472 static const AVClass aac_decoder_class = {
3473     .class_name = "AAC decoder",
3474     .item_name  = av_default_item_name,
3475     .option     = options,
3476     .version    = LIBAVUTIL_VERSION_INT,
3477 };
3478
3479 static const AVProfile profiles[] = {
3480     { FF_PROFILE_AAC_MAIN,  "Main"     },
3481     { FF_PROFILE_AAC_LOW,   "LC"       },
3482     { FF_PROFILE_AAC_SSR,   "SSR"      },
3483     { FF_PROFILE_AAC_LTP,   "LTP"      },
3484     { FF_PROFILE_AAC_HE,    "HE-AAC"   },
3485     { FF_PROFILE_AAC_HE_V2, "HE-AACv2" },
3486     { FF_PROFILE_AAC_LD,    "LD"       },
3487     { FF_PROFILE_AAC_ELD,   "ELD"      },
3488     { FF_PROFILE_UNKNOWN },
3489 };
3490
3491 AVCodec ff_aac_decoder = {
3492     .name            = "aac",
3493     .long_name       = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3494     .type            = AVMEDIA_TYPE_AUDIO,
3495     .id              = AV_CODEC_ID_AAC,
3496     .priv_data_size  = sizeof(AACContext),
3497     .init            = aac_decode_init,
3498     .close           = aac_decode_close,
3499     .decode          = aac_decode_frame,
3500     .sample_fmts     = (const enum AVSampleFormat[]) {
3501         AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3502     },
3503     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3504     .channel_layouts = aac_channel_layout,
3505     .flush = flush,
3506     .priv_class      = &aac_decoder_class,
3507     .profiles        = profiles,
3508 };
3509
3510 /*
3511     Note: This decoder filter is intended to decode LATM streams transferred
3512     in MPEG transport streams which only contain one program.
3513     To do a more complex LATM demuxing a separate LATM demuxer should be used.
3514 */
3515 AVCodec ff_aac_latm_decoder = {
3516     .name            = "aac_latm",
3517     .long_name       = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3518     .type            = AVMEDIA_TYPE_AUDIO,
3519     .id              = AV_CODEC_ID_AAC_LATM,
3520     .priv_data_size  = sizeof(struct LATMContext),
3521     .init            = latm_decode_init,
3522     .close           = aac_decode_close,
3523     .decode          = latm_decode_frame,
3524     .sample_fmts     = (const enum AVSampleFormat[]) {
3525         AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3526     },
3527     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3528     .channel_layouts = aac_channel_layout,
3529     .flush = flush,
3530     .profiles        = profiles,
3531 };