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