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