]> git.sesse.net Git - ffmpeg/blob - libavcodec/aacdec.c
lavc: Add spherical packet side data API
[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                     avpriv_report_missing_feature(ac->avctx, "LTP in ER AAC LD");
1250                     return AVERROR_PATCHWELCOME;
1251                 }
1252                 if ((ics->ltp.present = get_bits(gb, 1)))
1253                     decode_ltp(&ics->ltp, gb, ics->max_sfb);
1254             }
1255         }
1256     }
1257
1258     if (ics->max_sfb > ics->num_swb) {
1259         av_log(ac->avctx, AV_LOG_ERROR,
1260                "Number of scalefactor bands in group (%d) "
1261                "exceeds limit (%d).\n",
1262                ics->max_sfb, ics->num_swb);
1263         return AVERROR_INVALIDDATA;
1264     }
1265
1266     return 0;
1267 }
1268
1269 /**
1270  * Decode band types (section_data payload); reference: table 4.46.
1271  *
1272  * @param   band_type           array of the used band type
1273  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1274  *
1275  * @return  Returns error status. 0 - OK, !0 - error
1276  */
1277 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1278                              int band_type_run_end[120], GetBitContext *gb,
1279                              IndividualChannelStream *ics)
1280 {
1281     int g, idx = 0;
1282     const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1283     for (g = 0; g < ics->num_window_groups; g++) {
1284         int k = 0;
1285         while (k < ics->max_sfb) {
1286             uint8_t sect_end = k;
1287             int sect_len_incr;
1288             int sect_band_type = get_bits(gb, 4);
1289             if (sect_band_type == 12) {
1290                 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1291                 return AVERROR_INVALIDDATA;
1292             }
1293             do {
1294                 sect_len_incr = get_bits(gb, bits);
1295                 sect_end += sect_len_incr;
1296                 if (get_bits_left(gb) < 0) {
1297                     av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1298                     return AVERROR_INVALIDDATA;
1299                 }
1300                 if (sect_end > ics->max_sfb) {
1301                     av_log(ac->avctx, AV_LOG_ERROR,
1302                            "Number of bands (%d) exceeds limit (%d).\n",
1303                            sect_end, ics->max_sfb);
1304                     return AVERROR_INVALIDDATA;
1305                 }
1306             } while (sect_len_incr == (1 << bits) - 1);
1307             for (; k < sect_end; k++) {
1308                 band_type        [idx]   = sect_band_type;
1309                 band_type_run_end[idx++] = sect_end;
1310             }
1311         }
1312     }
1313     return 0;
1314 }
1315
1316 /**
1317  * Decode scalefactors; reference: table 4.47.
1318  *
1319  * @param   global_gain         first scalefactor value as scalefactors are differentially coded
1320  * @param   band_type           array of the used band type
1321  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1322  * @param   sf                  array of scalefactors or intensity stereo positions
1323  *
1324  * @return  Returns error status. 0 - OK, !0 - error
1325  */
1326 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1327                                unsigned int global_gain,
1328                                IndividualChannelStream *ics,
1329                                enum BandType band_type[120],
1330                                int band_type_run_end[120])
1331 {
1332     int g, i, idx = 0;
1333     int offset[3] = { global_gain, global_gain - 90, 0 };
1334     int clipped_offset;
1335     int noise_flag = 1;
1336     for (g = 0; g < ics->num_window_groups; g++) {
1337         for (i = 0; i < ics->max_sfb;) {
1338             int run_end = band_type_run_end[idx];
1339             if (band_type[idx] == ZERO_BT) {
1340                 for (; i < run_end; i++, idx++)
1341                     sf[idx] = 0.0;
1342             } else if ((band_type[idx] == INTENSITY_BT) ||
1343                        (band_type[idx] == INTENSITY_BT2)) {
1344                 for (; i < run_end; i++, idx++) {
1345                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1346                     clipped_offset = av_clip(offset[2], -155, 100);
1347                     if (offset[2] != clipped_offset) {
1348                         avpriv_request_sample(ac->avctx,
1349                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1350                                               "Clipped intensity stereo position (%d -> %d)",
1351                                               offset[2], clipped_offset);
1352                     }
1353                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1354                 }
1355             } else if (band_type[idx] == NOISE_BT) {
1356                 for (; i < run_end; i++, idx++) {
1357                     if (noise_flag-- > 0)
1358                         offset[1] += get_bits(gb, 9) - 256;
1359                     else
1360                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1361                     clipped_offset = av_clip(offset[1], -100, 155);
1362                     if (offset[1] != clipped_offset) {
1363                         avpriv_request_sample(ac->avctx,
1364                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1365                                               "Clipped noise gain (%d -> %d)",
1366                                               offset[1], clipped_offset);
1367                     }
1368                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1369                 }
1370             } else {
1371                 for (; i < run_end; i++, idx++) {
1372                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1373                     if (offset[0] > 255U) {
1374                         av_log(ac->avctx, AV_LOG_ERROR,
1375                                "Scalefactor (%d) out of range.\n", offset[0]);
1376                         return AVERROR_INVALIDDATA;
1377                     }
1378                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1379                 }
1380             }
1381         }
1382     }
1383     return 0;
1384 }
1385
1386 /**
1387  * Decode pulse data; reference: table 4.7.
1388  */
1389 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1390                          const uint16_t *swb_offset, int num_swb)
1391 {
1392     int i, pulse_swb;
1393     pulse->num_pulse = get_bits(gb, 2) + 1;
1394     pulse_swb        = get_bits(gb, 6);
1395     if (pulse_swb >= num_swb)
1396         return -1;
1397     pulse->pos[0]    = swb_offset[pulse_swb];
1398     pulse->pos[0]   += get_bits(gb, 5);
1399     if (pulse->pos[0] > 1023)
1400         return -1;
1401     pulse->amp[0]    = get_bits(gb, 4);
1402     for (i = 1; i < pulse->num_pulse; i++) {
1403         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1404         if (pulse->pos[i] > 1023)
1405             return -1;
1406         pulse->amp[i] = get_bits(gb, 4);
1407     }
1408     return 0;
1409 }
1410
1411 /**
1412  * Decode Temporal Noise Shaping data; reference: table 4.48.
1413  *
1414  * @return  Returns error status. 0 - OK, !0 - error
1415  */
1416 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1417                       GetBitContext *gb, const IndividualChannelStream *ics)
1418 {
1419     int w, filt, i, coef_len, coef_res, coef_compress;
1420     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1421     const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1422     for (w = 0; w < ics->num_windows; w++) {
1423         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1424             coef_res = get_bits1(gb);
1425
1426             for (filt = 0; filt < tns->n_filt[w]; filt++) {
1427                 int tmp2_idx;
1428                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1429
1430                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1431                     av_log(ac->avctx, AV_LOG_ERROR,
1432                            "TNS filter order %d is greater than maximum %d.\n",
1433                            tns->order[w][filt], tns_max_order);
1434                     tns->order[w][filt] = 0;
1435                     return AVERROR_INVALIDDATA;
1436                 }
1437                 if (tns->order[w][filt]) {
1438                     tns->direction[w][filt] = get_bits1(gb);
1439                     coef_compress = get_bits1(gb);
1440                     coef_len = coef_res + 3 - coef_compress;
1441                     tmp2_idx = 2 * coef_compress + coef_res;
1442
1443                     for (i = 0; i < tns->order[w][filt]; i++)
1444                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1445                 }
1446             }
1447         }
1448     }
1449     return 0;
1450 }
1451
1452 /**
1453  * Decode Mid/Side data; reference: table 4.54.
1454  *
1455  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1456  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1457  *                      [3] reserved for scalable AAC
1458  */
1459 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1460                                    int ms_present)
1461 {
1462     int idx;
1463     int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1464     if (ms_present == 1) {
1465         for (idx = 0; idx < max_idx; idx++)
1466             cpe->ms_mask[idx] = get_bits1(gb);
1467     } else if (ms_present == 2) {
1468         memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1469     }
1470 }
1471
1472 #ifndef VMUL2
1473 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1474                            const float *scale)
1475 {
1476     float s = *scale;
1477     *dst++ = v[idx    & 15] * s;
1478     *dst++ = v[idx>>4 & 15] * s;
1479     return dst;
1480 }
1481 #endif
1482
1483 #ifndef VMUL4
1484 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1485                            const float *scale)
1486 {
1487     float s = *scale;
1488     *dst++ = v[idx    & 3] * s;
1489     *dst++ = v[idx>>2 & 3] * s;
1490     *dst++ = v[idx>>4 & 3] * s;
1491     *dst++ = v[idx>>6 & 3] * s;
1492     return dst;
1493 }
1494 #endif
1495
1496 #ifndef VMUL2S
1497 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1498                             unsigned sign, const float *scale)
1499 {
1500     union av_intfloat32 s0, s1;
1501
1502     s0.f = s1.f = *scale;
1503     s0.i ^= sign >> 1 << 31;
1504     s1.i ^= sign      << 31;
1505
1506     *dst++ = v[idx    & 15] * s0.f;
1507     *dst++ = v[idx>>4 & 15] * s1.f;
1508
1509     return dst;
1510 }
1511 #endif
1512
1513 #ifndef VMUL4S
1514 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1515                             unsigned sign, const float *scale)
1516 {
1517     unsigned nz = idx >> 12;
1518     union av_intfloat32 s = { .f = *scale };
1519     union av_intfloat32 t;
1520
1521     t.i = s.i ^ (sign & 1U<<31);
1522     *dst++ = v[idx    & 3] * t.f;
1523
1524     sign <<= nz & 1; nz >>= 1;
1525     t.i = s.i ^ (sign & 1U<<31);
1526     *dst++ = v[idx>>2 & 3] * t.f;
1527
1528     sign <<= nz & 1; nz >>= 1;
1529     t.i = s.i ^ (sign & 1U<<31);
1530     *dst++ = v[idx>>4 & 3] * t.f;
1531
1532     sign <<= nz & 1;
1533     t.i = s.i ^ (sign & 1U<<31);
1534     *dst++ = v[idx>>6 & 3] * t.f;
1535
1536     return dst;
1537 }
1538 #endif
1539
1540 /**
1541  * Decode spectral data; reference: table 4.50.
1542  * Dequantize and scale spectral data; reference: 4.6.3.3.
1543  *
1544  * @param   coef            array of dequantized, scaled spectral data
1545  * @param   sf              array of scalefactors or intensity stereo positions
1546  * @param   pulse_present   set if pulses are present
1547  * @param   pulse           pointer to pulse data struct
1548  * @param   band_type       array of the used band type
1549  *
1550  * @return  Returns error status. 0 - OK, !0 - error
1551  */
1552 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1553                                        GetBitContext *gb, const float sf[120],
1554                                        int pulse_present, const Pulse *pulse,
1555                                        const IndividualChannelStream *ics,
1556                                        enum BandType band_type[120])
1557 {
1558     int i, k, g, idx = 0;
1559     const int c = 1024 / ics->num_windows;
1560     const uint16_t *offsets = ics->swb_offset;
1561     float *coef_base = coef;
1562
1563     for (g = 0; g < ics->num_windows; g++)
1564         memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1565                sizeof(float) * (c - offsets[ics->max_sfb]));
1566
1567     for (g = 0; g < ics->num_window_groups; g++) {
1568         unsigned g_len = ics->group_len[g];
1569
1570         for (i = 0; i < ics->max_sfb; i++, idx++) {
1571             const unsigned cbt_m1 = band_type[idx] - 1;
1572             float *cfo = coef + offsets[i];
1573             int off_len = offsets[i + 1] - offsets[i];
1574             int group;
1575
1576             if (cbt_m1 >= INTENSITY_BT2 - 1) {
1577                 for (group = 0; group < g_len; group++, cfo+=128) {
1578                     memset(cfo, 0, off_len * sizeof(float));
1579                 }
1580             } else if (cbt_m1 == NOISE_BT - 1) {
1581                 for (group = 0; group < g_len; group++, cfo+=128) {
1582                     float scale;
1583                     float band_energy;
1584
1585                     for (k = 0; k < off_len; k++) {
1586                         ac->random_state  = lcg_random(ac->random_state);
1587                         cfo[k] = ac->random_state;
1588                     }
1589
1590                     band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1591                     scale = sf[idx] / sqrtf(band_energy);
1592                     ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1593                 }
1594             } else {
1595                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1596                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1597                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1598                 OPEN_READER(re, gb);
1599
1600                 switch (cbt_m1 >> 1) {
1601                 case 0:
1602                     for (group = 0; group < g_len; group++, cfo+=128) {
1603                         float *cf = cfo;
1604                         int len = off_len;
1605
1606                         do {
1607                             int code;
1608                             unsigned cb_idx;
1609
1610                             UPDATE_CACHE(re, gb);
1611                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1612                             cb_idx = cb_vector_idx[code];
1613                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
1614                         } while (len -= 4);
1615                     }
1616                     break;
1617
1618                 case 1:
1619                     for (group = 0; group < g_len; group++, cfo+=128) {
1620                         float *cf = cfo;
1621                         int len = off_len;
1622
1623                         do {
1624                             int code;
1625                             unsigned nnz;
1626                             unsigned cb_idx;
1627                             uint32_t bits;
1628
1629                             UPDATE_CACHE(re, gb);
1630                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1631                             cb_idx = cb_vector_idx[code];
1632                             nnz = cb_idx >> 8 & 15;
1633                             bits = nnz ? GET_CACHE(re, gb) : 0;
1634                             LAST_SKIP_BITS(re, gb, nnz);
1635                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1636                         } while (len -= 4);
1637                     }
1638                     break;
1639
1640                 case 2:
1641                     for (group = 0; group < g_len; group++, cfo+=128) {
1642                         float *cf = cfo;
1643                         int len = off_len;
1644
1645                         do {
1646                             int code;
1647                             unsigned cb_idx;
1648
1649                             UPDATE_CACHE(re, gb);
1650                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1651                             cb_idx = cb_vector_idx[code];
1652                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
1653                         } while (len -= 2);
1654                     }
1655                     break;
1656
1657                 case 3:
1658                 case 4:
1659                     for (group = 0; group < g_len; group++, cfo+=128) {
1660                         float *cf = cfo;
1661                         int len = off_len;
1662
1663                         do {
1664                             int code;
1665                             unsigned nnz;
1666                             unsigned cb_idx;
1667                             unsigned sign;
1668
1669                             UPDATE_CACHE(re, gb);
1670                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1671                             cb_idx = cb_vector_idx[code];
1672                             nnz = cb_idx >> 8 & 15;
1673                             sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1674                             LAST_SKIP_BITS(re, gb, nnz);
1675                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1676                         } while (len -= 2);
1677                     }
1678                     break;
1679
1680                 default:
1681                     for (group = 0; group < g_len; group++, cfo+=128) {
1682                         float *cf = cfo;
1683                         uint32_t *icf = (uint32_t *) cf;
1684                         int len = off_len;
1685
1686                         do {
1687                             int code;
1688                             unsigned nzt, nnz;
1689                             unsigned cb_idx;
1690                             uint32_t bits;
1691                             int j;
1692
1693                             UPDATE_CACHE(re, gb);
1694                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1695
1696                             if (!code) {
1697                                 *icf++ = 0;
1698                                 *icf++ = 0;
1699                                 continue;
1700                             }
1701
1702                             cb_idx = cb_vector_idx[code];
1703                             nnz = cb_idx >> 12;
1704                             nzt = cb_idx >> 8;
1705                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1706                             LAST_SKIP_BITS(re, gb, nnz);
1707
1708                             for (j = 0; j < 2; j++) {
1709                                 if (nzt & 1<<j) {
1710                                     uint32_t b;
1711                                     int n;
1712                                     /* The total length of escape_sequence must be < 22 bits according
1713                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1714                                     UPDATE_CACHE(re, gb);
1715                                     b = GET_CACHE(re, gb);
1716                                     b = 31 - av_log2(~b);
1717
1718                                     if (b > 8) {
1719                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1720                                         return AVERROR_INVALIDDATA;
1721                                     }
1722
1723                                     SKIP_BITS(re, gb, b + 1);
1724                                     b += 4;
1725                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
1726                                     LAST_SKIP_BITS(re, gb, b);
1727                                     *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1728                                     bits <<= 1;
1729                                 } else {
1730                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1731                                     *icf++ = (bits & 1U<<31) | v;
1732                                     bits <<= !!v;
1733                                 }
1734                                 cb_idx >>= 4;
1735                             }
1736                         } while (len -= 2);
1737
1738                         ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1739                     }
1740                 }
1741
1742                 CLOSE_READER(re, gb);
1743             }
1744         }
1745         coef += g_len << 7;
1746     }
1747
1748     if (pulse_present) {
1749         idx = 0;
1750         for (i = 0; i < pulse->num_pulse; i++) {
1751             float co = coef_base[ pulse->pos[i] ];
1752             while (offsets[idx + 1] <= pulse->pos[i])
1753                 idx++;
1754             if (band_type[idx] != NOISE_BT && sf[idx]) {
1755                 float ico = -pulse->amp[i];
1756                 if (co) {
1757                     co /= sf[idx];
1758                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1759                 }
1760                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1761             }
1762         }
1763     }
1764     return 0;
1765 }
1766
1767 static av_always_inline float flt16_round(float pf)
1768 {
1769     union av_intfloat32 tmp;
1770     tmp.f = pf;
1771     tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1772     return tmp.f;
1773 }
1774
1775 static av_always_inline float flt16_even(float pf)
1776 {
1777     union av_intfloat32 tmp;
1778     tmp.f = pf;
1779     tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1780     return tmp.f;
1781 }
1782
1783 static av_always_inline float flt16_trunc(float pf)
1784 {
1785     union av_intfloat32 pun;
1786     pun.f = pf;
1787     pun.i &= 0xFFFF0000U;
1788     return pun.f;
1789 }
1790
1791 static av_always_inline void predict(PredictorState *ps, float *coef,
1792                                      int output_enable)
1793 {
1794     const float a     = 0.953125; // 61.0 / 64
1795     const float alpha = 0.90625;  // 29.0 / 32
1796     float e0, e1;
1797     float pv;
1798     float k1, k2;
1799     float   r0 = ps->r0,     r1 = ps->r1;
1800     float cor0 = ps->cor0, cor1 = ps->cor1;
1801     float var0 = ps->var0, var1 = ps->var1;
1802
1803     k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1804     k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1805
1806     pv = flt16_round(k1 * r0 + k2 * r1);
1807     if (output_enable)
1808         *coef += pv;
1809
1810     e0 = *coef;
1811     e1 = e0 - k1 * r0;
1812
1813     ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1814     ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1815     ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1816     ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1817
1818     ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1819     ps->r0 = flt16_trunc(a * e0);
1820 }
1821
1822 /**
1823  * Apply AAC-Main style frequency domain prediction.
1824  */
1825 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1826 {
1827     int sfb, k;
1828
1829     if (!sce->ics.predictor_initialized) {
1830         reset_all_predictors(sce->predictor_state);
1831         sce->ics.predictor_initialized = 1;
1832     }
1833
1834     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1835         for (sfb = 0;
1836              sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1837              sfb++) {
1838             for (k = sce->ics.swb_offset[sfb];
1839                  k < sce->ics.swb_offset[sfb + 1];
1840                  k++) {
1841                 predict(&sce->predictor_state[k], &sce->coeffs[k],
1842                         sce->ics.predictor_present &&
1843                         sce->ics.prediction_used[sfb]);
1844             }
1845         }
1846         if (sce->ics.predictor_reset_group)
1847             reset_predictor_group(sce->predictor_state,
1848                                   sce->ics.predictor_reset_group);
1849     } else
1850         reset_all_predictors(sce->predictor_state);
1851 }
1852
1853 /**
1854  * Decode an individual_channel_stream payload; reference: table 4.44.
1855  *
1856  * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
1857  * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1858  *
1859  * @return  Returns error status. 0 - OK, !0 - error
1860  */
1861 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1862                       GetBitContext *gb, int common_window, int scale_flag)
1863 {
1864     Pulse pulse;
1865     TemporalNoiseShaping    *tns = &sce->tns;
1866     IndividualChannelStream *ics = &sce->ics;
1867     float *out = sce->coeffs;
1868     int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1869     int ret;
1870
1871     eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1872     er_syntax  = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1873                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1874                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1875                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1876
1877     /* This assignment is to silence a GCC warning about the variable being used
1878      * uninitialized when in fact it always is.
1879      */
1880     pulse.num_pulse = 0;
1881
1882     global_gain = get_bits(gb, 8);
1883
1884     if (!common_window && !scale_flag) {
1885         if (decode_ics_info(ac, ics, gb) < 0)
1886             return AVERROR_INVALIDDATA;
1887     }
1888
1889     if ((ret = decode_band_types(ac, sce->band_type,
1890                                  sce->band_type_run_end, gb, ics)) < 0)
1891         return ret;
1892     if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1893                                   sce->band_type, sce->band_type_run_end)) < 0)
1894         return ret;
1895
1896     pulse_present = 0;
1897     if (!scale_flag) {
1898         if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1899             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1900                 av_log(ac->avctx, AV_LOG_ERROR,
1901                        "Pulse tool not allowed in eight short sequence.\n");
1902                 return AVERROR_INVALIDDATA;
1903             }
1904             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1905                 av_log(ac->avctx, AV_LOG_ERROR,
1906                        "Pulse data corrupt or invalid.\n");
1907                 return AVERROR_INVALIDDATA;
1908             }
1909         }
1910         tns->present = get_bits1(gb);
1911         if (tns->present && !er_syntax)
1912             if (decode_tns(ac, tns, gb, ics) < 0)
1913                 return AVERROR_INVALIDDATA;
1914         if (!eld_syntax && get_bits1(gb)) {
1915             avpriv_request_sample(ac->avctx, "SSR");
1916             return AVERROR_PATCHWELCOME;
1917         }
1918         // I see no textual basis in the spec for this occurring after SSR gain
1919         // control, but this is what both reference and real implementations do
1920         if (tns->present && er_syntax)
1921             if (decode_tns(ac, tns, gb, ics) < 0)
1922                 return AVERROR_INVALIDDATA;
1923     }
1924
1925     if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1926                                     &pulse, ics, sce->band_type) < 0)
1927         return AVERROR_INVALIDDATA;
1928
1929     if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1930         apply_prediction(ac, sce);
1931
1932     return 0;
1933 }
1934
1935 /**
1936  * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1937  */
1938 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1939 {
1940     const IndividualChannelStream *ics = &cpe->ch[0].ics;
1941     float *ch0 = cpe->ch[0].coeffs;
1942     float *ch1 = cpe->ch[1].coeffs;
1943     int g, i, group, idx = 0;
1944     const uint16_t *offsets = ics->swb_offset;
1945     for (g = 0; g < ics->num_window_groups; g++) {
1946         for (i = 0; i < ics->max_sfb; i++, idx++) {
1947             if (cpe->ms_mask[idx] &&
1948                 cpe->ch[0].band_type[idx] < NOISE_BT &&
1949                 cpe->ch[1].band_type[idx] < NOISE_BT) {
1950                 for (group = 0; group < ics->group_len[g]; group++) {
1951                     ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1952                                                ch1 + group * 128 + offsets[i],
1953                                                offsets[i+1] - offsets[i]);
1954                 }
1955             }
1956         }
1957         ch0 += ics->group_len[g] * 128;
1958         ch1 += ics->group_len[g] * 128;
1959     }
1960 }
1961
1962 /**
1963  * intensity stereo decoding; reference: 4.6.8.2.3
1964  *
1965  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1966  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1967  *                      [3] reserved for scalable AAC
1968  */
1969 static void apply_intensity_stereo(AACContext *ac,
1970                                    ChannelElement *cpe, int ms_present)
1971 {
1972     const IndividualChannelStream *ics = &cpe->ch[1].ics;
1973     SingleChannelElement         *sce1 = &cpe->ch[1];
1974     float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1975     const uint16_t *offsets = ics->swb_offset;
1976     int g, group, i, idx = 0;
1977     int c;
1978     float scale;
1979     for (g = 0; g < ics->num_window_groups; g++) {
1980         for (i = 0; i < ics->max_sfb;) {
1981             if (sce1->band_type[idx] == INTENSITY_BT ||
1982                 sce1->band_type[idx] == INTENSITY_BT2) {
1983                 const int bt_run_end = sce1->band_type_run_end[idx];
1984                 for (; i < bt_run_end; i++, idx++) {
1985                     c = -1 + 2 * (sce1->band_type[idx] - 14);
1986                     if (ms_present)
1987                         c *= 1 - 2 * cpe->ms_mask[idx];
1988                     scale = c * sce1->sf[idx];
1989                     for (group = 0; group < ics->group_len[g]; group++)
1990                         ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1991                                                     coef0 + group * 128 + offsets[i],
1992                                                     scale,
1993                                                     offsets[i + 1] - offsets[i]);
1994                 }
1995             } else {
1996                 int bt_run_end = sce1->band_type_run_end[idx];
1997                 idx += bt_run_end - i;
1998                 i    = bt_run_end;
1999             }
2000         }
2001         coef0 += ics->group_len[g] * 128;
2002         coef1 += ics->group_len[g] * 128;
2003     }
2004 }
2005
2006 /**
2007  * Decode a channel_pair_element; reference: table 4.4.
2008  *
2009  * @return  Returns error status. 0 - OK, !0 - error
2010  */
2011 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2012 {
2013     int i, ret, common_window, ms_present = 0;
2014     int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2015
2016     common_window = eld_syntax || get_bits1(gb);
2017     if (common_window) {
2018         if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2019             return AVERROR_INVALIDDATA;
2020         i = cpe->ch[1].ics.use_kb_window[0];
2021         cpe->ch[1].ics = cpe->ch[0].ics;
2022         cpe->ch[1].ics.use_kb_window[1] = i;
2023         if (cpe->ch[1].ics.predictor_present &&
2024             (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2025             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2026                 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2027         ms_present = get_bits(gb, 2);
2028         if (ms_present == 3) {
2029             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2030             return AVERROR_INVALIDDATA;
2031         } else if (ms_present)
2032             decode_mid_side_stereo(cpe, gb, ms_present);
2033     }
2034     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2035         return ret;
2036     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2037         return ret;
2038
2039     if (common_window) {
2040         if (ms_present)
2041             apply_mid_side_stereo(ac, cpe);
2042         if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2043             apply_prediction(ac, &cpe->ch[0]);
2044             apply_prediction(ac, &cpe->ch[1]);
2045         }
2046     }
2047
2048     apply_intensity_stereo(ac, cpe, ms_present);
2049     return 0;
2050 }
2051
2052 static const float cce_scale[] = {
2053     1.09050773266525765921, //2^(1/8)
2054     1.18920711500272106672, //2^(1/4)
2055     M_SQRT2,
2056     2,
2057 };
2058
2059 /**
2060  * Decode coupling_channel_element; reference: table 4.8.
2061  *
2062  * @return  Returns error status. 0 - OK, !0 - error
2063  */
2064 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2065 {
2066     int num_gain = 0;
2067     int c, g, sfb, ret;
2068     int sign;
2069     float scale;
2070     SingleChannelElement *sce = &che->ch[0];
2071     ChannelCoupling     *coup = &che->coup;
2072
2073     coup->coupling_point = 2 * get_bits1(gb);
2074     coup->num_coupled = get_bits(gb, 3);
2075     for (c = 0; c <= coup->num_coupled; c++) {
2076         num_gain++;
2077         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2078         coup->id_select[c] = get_bits(gb, 4);
2079         if (coup->type[c] == TYPE_CPE) {
2080             coup->ch_select[c] = get_bits(gb, 2);
2081             if (coup->ch_select[c] == 3)
2082                 num_gain++;
2083         } else
2084             coup->ch_select[c] = 2;
2085     }
2086     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2087
2088     sign  = get_bits(gb, 1);
2089     scale = cce_scale[get_bits(gb, 2)];
2090
2091     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2092         return ret;
2093
2094     for (c = 0; c < num_gain; c++) {
2095         int idx  = 0;
2096         int cge  = 1;
2097         int gain = 0;
2098         float gain_cache = 1.0;
2099         if (c) {
2100             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2101             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2102             gain_cache = powf(scale, -gain);
2103         }
2104         if (coup->coupling_point == AFTER_IMDCT) {
2105             coup->gain[c][0] = gain_cache;
2106         } else {
2107             for (g = 0; g < sce->ics.num_window_groups; g++) {
2108                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2109                     if (sce->band_type[idx] != ZERO_BT) {
2110                         if (!cge) {
2111                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2112                             if (t) {
2113                                 int s = 1;
2114                                 t = gain += t;
2115                                 if (sign) {
2116                                     s  -= 2 * (t & 0x1);
2117                                     t >>= 1;
2118                                 }
2119                                 gain_cache = powf(scale, -t) * s;
2120                             }
2121                         }
2122                         coup->gain[c][idx] = gain_cache;
2123                     }
2124                 }
2125             }
2126         }
2127     }
2128     return 0;
2129 }
2130
2131 /**
2132  * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2133  *
2134  * @return  Returns number of bytes consumed.
2135  */
2136 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2137                                          GetBitContext *gb)
2138 {
2139     int i;
2140     int num_excl_chan = 0;
2141
2142     do {
2143         for (i = 0; i < 7; i++)
2144             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2145     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2146
2147     return num_excl_chan / 7;
2148 }
2149
2150 /**
2151  * Decode dynamic range information; reference: table 4.52.
2152  *
2153  * @return  Returns number of bytes consumed.
2154  */
2155 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2156                                 GetBitContext *gb)
2157 {
2158     int n             = 1;
2159     int drc_num_bands = 1;
2160     int i;
2161
2162     /* pce_tag_present? */
2163     if (get_bits1(gb)) {
2164         che_drc->pce_instance_tag  = get_bits(gb, 4);
2165         skip_bits(gb, 4); // tag_reserved_bits
2166         n++;
2167     }
2168
2169     /* excluded_chns_present? */
2170     if (get_bits1(gb)) {
2171         n += decode_drc_channel_exclusions(che_drc, gb);
2172     }
2173
2174     /* drc_bands_present? */
2175     if (get_bits1(gb)) {
2176         che_drc->band_incr            = get_bits(gb, 4);
2177         che_drc->interpolation_scheme = get_bits(gb, 4);
2178         n++;
2179         drc_num_bands += che_drc->band_incr;
2180         for (i = 0; i < drc_num_bands; i++) {
2181             che_drc->band_top[i] = get_bits(gb, 8);
2182             n++;
2183         }
2184     }
2185
2186     /* prog_ref_level_present? */
2187     if (get_bits1(gb)) {
2188         che_drc->prog_ref_level = get_bits(gb, 7);
2189         skip_bits1(gb); // prog_ref_level_reserved_bits
2190         n++;
2191     }
2192
2193     for (i = 0; i < drc_num_bands; i++) {
2194         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2195         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2196         n++;
2197     }
2198
2199     return n;
2200 }
2201
2202 /**
2203  * Decode extension data (incomplete); reference: table 4.51.
2204  *
2205  * @param   cnt length of TYPE_FIL syntactic element in bytes
2206  *
2207  * @return Returns number of bytes consumed
2208  */
2209 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2210                                     ChannelElement *che, enum RawDataBlockType elem_type)
2211 {
2212     int crc_flag = 0;
2213     int res = cnt;
2214     switch (get_bits(gb, 4)) { // extension type
2215     case EXT_SBR_DATA_CRC:
2216         crc_flag++;
2217     case EXT_SBR_DATA:
2218         if (!che) {
2219             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2220             return res;
2221         } else if (!ac->oc[1].m4ac.sbr) {
2222             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2223             skip_bits_long(gb, 8 * cnt - 4);
2224             return res;
2225         } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2226             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2227             skip_bits_long(gb, 8 * cnt - 4);
2228             return res;
2229         } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2230             ac->oc[1].m4ac.sbr = 1;
2231             ac->oc[1].m4ac.ps = 1;
2232             ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2233             output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2234                              ac->oc[1].status, 1);
2235         } else {
2236             ac->oc[1].m4ac.sbr = 1;
2237             ac->avctx->profile = FF_PROFILE_AAC_HE;
2238         }
2239         res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2240         break;
2241     case EXT_DYNAMIC_RANGE:
2242         res = decode_dynamic_range(&ac->che_drc, gb);
2243         break;
2244     case EXT_FILL:
2245     case EXT_FILL_DATA:
2246     case EXT_DATA_ELEMENT:
2247     default:
2248         skip_bits_long(gb, 8 * cnt - 4);
2249         break;
2250     };
2251     return res;
2252 }
2253
2254 /**
2255  * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2256  *
2257  * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
2258  * @param   coef    spectral coefficients
2259  */
2260 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2261                       IndividualChannelStream *ics, int decode)
2262 {
2263     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2264     int w, filt, m, i;
2265     int bottom, top, order, start, end, size, inc;
2266     float lpc[TNS_MAX_ORDER];
2267     float tmp[TNS_MAX_ORDER + 1];
2268
2269     for (w = 0; w < ics->num_windows; w++) {
2270         bottom = ics->num_swb;
2271         for (filt = 0; filt < tns->n_filt[w]; filt++) {
2272             top    = bottom;
2273             bottom = FFMAX(0, top - tns->length[w][filt]);
2274             order  = tns->order[w][filt];
2275             if (order == 0)
2276                 continue;
2277
2278             // tns_decode_coef
2279             compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2280
2281             start = ics->swb_offset[FFMIN(bottom, mmm)];
2282             end   = ics->swb_offset[FFMIN(   top, mmm)];
2283             if ((size = end - start) <= 0)
2284                 continue;
2285             if (tns->direction[w][filt]) {
2286                 inc = -1;
2287                 start = end - 1;
2288             } else {
2289                 inc = 1;
2290             }
2291             start += w * 128;
2292
2293             if (decode) {
2294                 // ar filter
2295                 for (m = 0; m < size; m++, start += inc)
2296                     for (i = 1; i <= FFMIN(m, order); i++)
2297                         coef[start] -= coef[start - i * inc] * lpc[i - 1];
2298             } else {
2299                 // ma filter
2300                 for (m = 0; m < size; m++, start += inc) {
2301                     tmp[0] = coef[start];
2302                     for (i = 1; i <= FFMIN(m, order); i++)
2303                         coef[start] += tmp[i] * lpc[i - 1];
2304                     for (i = order; i > 0; i--)
2305                         tmp[i] = tmp[i - 1];
2306                 }
2307             }
2308         }
2309     }
2310 }
2311
2312 /**
2313  *  Apply windowing and MDCT to obtain the spectral
2314  *  coefficient from the predicted sample by LTP.
2315  */
2316 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2317                                    float *in, IndividualChannelStream *ics)
2318 {
2319     const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2320     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2321     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2322     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2323
2324     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2325         ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2326     } else {
2327         memset(in, 0, 448 * sizeof(float));
2328         ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2329     }
2330     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2331         ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2332     } else {
2333         ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2334         memset(in + 1024 + 576, 0, 448 * sizeof(float));
2335     }
2336     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2337 }
2338
2339 /**
2340  * Apply the long term prediction
2341  */
2342 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2343 {
2344     const LongTermPrediction *ltp = &sce->ics.ltp;
2345     const uint16_t *offsets = sce->ics.swb_offset;
2346     int i, sfb;
2347
2348     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2349         float *predTime = sce->ret;
2350         float *predFreq = ac->buf_mdct;
2351         int16_t num_samples = 2048;
2352
2353         if (ltp->lag < 1024)
2354             num_samples = ltp->lag + 1024;
2355         for (i = 0; i < num_samples; i++)
2356             predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2357         memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2358
2359         windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2360
2361         if (sce->tns.present)
2362             apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2363
2364         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2365             if (ltp->used[sfb])
2366                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2367                     sce->coeffs[i] += predFreq[i];
2368     }
2369 }
2370
2371 /**
2372  * Update the LTP buffer for next frame
2373  */
2374 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2375 {
2376     IndividualChannelStream *ics = &sce->ics;
2377     float *saved     = sce->saved;
2378     float *saved_ltp = sce->coeffs;
2379     const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2380     const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2381     int i;
2382
2383     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2384         memcpy(saved_ltp,       saved, 512 * sizeof(float));
2385         memset(saved_ltp + 576, 0,     448 * sizeof(float));
2386         ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2387         for (i = 0; i < 64; i++)
2388             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2389     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2390         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
2391         memset(saved_ltp + 576, 0,                  448 * sizeof(float));
2392         ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2393         for (i = 0; i < 64; i++)
2394             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2395     } else { // LONG_STOP or ONLY_LONG
2396         ac->fdsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
2397         for (i = 0; i < 512; i++)
2398             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2399     }
2400
2401     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2402     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
2403     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
2404 }
2405
2406 /**
2407  * Conduct IMDCT and windowing.
2408  */
2409 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2410 {
2411     IndividualChannelStream *ics = &sce->ics;
2412     float *in    = sce->coeffs;
2413     float *out   = sce->ret;
2414     float *saved = sce->saved;
2415     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2416     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2417     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2418     float *buf  = ac->buf_mdct;
2419     float *temp = ac->temp;
2420     int i;
2421
2422     // imdct
2423     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2424         for (i = 0; i < 1024; i += 128)
2425             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2426     } else
2427         ac->mdct.imdct_half(&ac->mdct, buf, in);
2428
2429     /* window overlapping
2430      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2431      * and long to short transitions are considered to be short to short
2432      * transitions. This leaves just two cases (long to long and short to short)
2433      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2434      */
2435     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2436             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2437         ac->fdsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
2438     } else {
2439         memcpy(                         out,               saved,            448 * sizeof(float));
2440
2441         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2442             ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
2443             ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
2444             ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
2445             ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
2446             ac->fdsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
2447             memcpy(                     out + 448 + 4*128, temp, 64 * sizeof(float));
2448         } else {
2449             ac->fdsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
2450             memcpy(                     out + 576,         buf + 64,         448 * sizeof(float));
2451         }
2452     }
2453
2454     // buffer update
2455     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2456         memcpy(                     saved,       temp + 64,         64 * sizeof(float));
2457         ac->fdsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
2458         ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2459         ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2460         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2461     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2462         memcpy(                     saved,       buf + 512,        448 * sizeof(float));
2463         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2464     } else { // LONG_STOP or ONLY_LONG
2465         memcpy(                     saved,       buf + 512,        512 * sizeof(float));
2466     }
2467 }
2468
2469 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2470 {
2471     IndividualChannelStream *ics = &sce->ics;
2472     float *in    = sce->coeffs;
2473     float *out   = sce->ret;
2474     float *saved = sce->saved;
2475     float *buf  = ac->buf_mdct;
2476
2477     // imdct
2478     ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2479
2480     // window overlapping
2481     if (ics->use_kb_window[1]) {
2482         // AAC LD uses a low overlap sine window instead of a KBD window
2483         memcpy(out, saved, 192 * sizeof(float));
2484         ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2485         memcpy(                     out + 320, buf + 64, 192 * sizeof(float));
2486     } else {
2487         ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2488     }
2489
2490     // buffer update
2491     memcpy(saved, buf + 256, 256 * sizeof(float));
2492 }
2493
2494 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2495 {
2496     float *in    = sce->coeffs;
2497     float *out   = sce->ret;
2498     float *saved = sce->saved;
2499     float *buf  = ac->buf_mdct;
2500     int i;
2501     const int n  = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2502     const int n2 = n >> 1;
2503     const int n4 = n >> 2;
2504     const float *const window = n == 480 ? ff_aac_eld_window_480 :
2505                                            ff_aac_eld_window_512;
2506
2507     // Inverse transform, mapped to the conventional IMDCT by
2508     // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2509     // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2510     // Audio, Language and Image Processing, 2008. ICALIP 2008. International Conference on
2511     // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2512     for (i = 0; i < n2; i+=2) {
2513         float temp;
2514         temp =  in[i    ]; in[i    ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2515         temp = -in[i + 1]; in[i + 1] =  in[n - 2 - i]; in[n - 2 - i] = temp;
2516     }
2517     if (n == 480)
2518         ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
2519     else
2520         ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2521     for (i = 0; i < n; i+=2) {
2522         buf[i] = -buf[i];
2523     }
2524     // Like with the regular IMDCT at this point we still have the middle half
2525     // of a transform but with even symmetry on the left and odd symmetry on
2526     // the right
2527
2528     // window overlapping
2529     // The spec says to use samples [0..511] but the reference decoder uses
2530     // samples [128..639].
2531     for (i = n4; i < n2; i ++) {
2532         out[i - n4] =    buf[n2 - 1 - i]       * window[i       - n4] +
2533                        saved[      i + n2]     * window[i +   n - n4] +
2534                       -saved[  n + n2 - 1 - i] * window[i + 2*n - n4] +
2535                       -saved[2*n + n2 + i]     * window[i + 3*n - n4];
2536     }
2537     for (i = 0; i < n2; i ++) {
2538         out[n4 + i] =    buf[i]               * window[i + n2       - n4] +
2539                       -saved[      n - 1 - i] * window[i + n2 +   n - n4] +
2540                       -saved[  n + i]         * window[i + n2 + 2*n - n4] +
2541                        saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2542     }
2543     for (i = 0; i < n4; i ++) {
2544         out[n2 + n4 + i] =    buf[      i + n2]     * window[i +   n - n4] +
2545                            -saved[      n2 - 1 - i] * window[i + 2*n - n4] +
2546                            -saved[  n + n2 + i]     * window[i + 3*n - n4];
2547     }
2548
2549     // buffer update
2550     memmove(saved + n, saved, 2 * n * sizeof(float));
2551     memcpy( saved,       buf,     n * sizeof(float));
2552 }
2553
2554 /**
2555  * Apply dependent channel coupling (applied before IMDCT).
2556  *
2557  * @param   index   index into coupling gain array
2558  */
2559 static void apply_dependent_coupling(AACContext *ac,
2560                                      SingleChannelElement *target,
2561                                      ChannelElement *cce, int index)
2562 {
2563     IndividualChannelStream *ics = &cce->ch[0].ics;
2564     const uint16_t *offsets = ics->swb_offset;
2565     float *dest = target->coeffs;
2566     const float *src = cce->ch[0].coeffs;
2567     int g, i, group, k, idx = 0;
2568     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2569         av_log(ac->avctx, AV_LOG_ERROR,
2570                "Dependent coupling is not supported together with LTP\n");
2571         return;
2572     }
2573     for (g = 0; g < ics->num_window_groups; g++) {
2574         for (i = 0; i < ics->max_sfb; i++, idx++) {
2575             if (cce->ch[0].band_type[idx] != ZERO_BT) {
2576                 const float gain = cce->coup.gain[index][idx];
2577                 for (group = 0; group < ics->group_len[g]; group++) {
2578                     for (k = offsets[i]; k < offsets[i + 1]; k++) {
2579                         // FIXME: SIMDify
2580                         dest[group * 128 + k] += gain * src[group * 128 + k];
2581                     }
2582                 }
2583             }
2584         }
2585         dest += ics->group_len[g] * 128;
2586         src  += ics->group_len[g] * 128;
2587     }
2588 }
2589
2590 /**
2591  * Apply independent channel coupling (applied after IMDCT).
2592  *
2593  * @param   index   index into coupling gain array
2594  */
2595 static void apply_independent_coupling(AACContext *ac,
2596                                        SingleChannelElement *target,
2597                                        ChannelElement *cce, int index)
2598 {
2599     int i;
2600     const float gain = cce->coup.gain[index][0];
2601     const float *src = cce->ch[0].ret;
2602     float *dest = target->ret;
2603     const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2604
2605     for (i = 0; i < len; i++)
2606         dest[i] += gain * src[i];
2607 }
2608
2609 /**
2610  * channel coupling transformation interface
2611  *
2612  * @param   apply_coupling_method   pointer to (in)dependent coupling function
2613  */
2614 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2615                                    enum RawDataBlockType type, int elem_id,
2616                                    enum CouplingPoint coupling_point,
2617                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2618 {
2619     int i, c;
2620
2621     for (i = 0; i < MAX_ELEM_ID; i++) {
2622         ChannelElement *cce = ac->che[TYPE_CCE][i];
2623         int index = 0;
2624
2625         if (cce && cce->coup.coupling_point == coupling_point) {
2626             ChannelCoupling *coup = &cce->coup;
2627
2628             for (c = 0; c <= coup->num_coupled; c++) {
2629                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2630                     if (coup->ch_select[c] != 1) {
2631                         apply_coupling_method(ac, &cc->ch[0], cce, index);
2632                         if (coup->ch_select[c] != 0)
2633                             index++;
2634                     }
2635                     if (coup->ch_select[c] != 2)
2636                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
2637                 } else
2638                     index += 1 + (coup->ch_select[c] == 3);
2639             }
2640         }
2641     }
2642 }
2643
2644 /**
2645  * Convert spectral data to float samples, applying all supported tools as appropriate.
2646  */
2647 static void spectral_to_sample(AACContext *ac)
2648 {
2649     int i, type;
2650     void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2651     switch (ac->oc[1].m4ac.object_type) {
2652     case AOT_ER_AAC_LD:
2653         imdct_and_window = imdct_and_windowing_ld;
2654         break;
2655     case AOT_ER_AAC_ELD:
2656         imdct_and_window = imdct_and_windowing_eld;
2657         break;
2658     default:
2659         imdct_and_window = imdct_and_windowing;
2660     }
2661     for (type = 3; type >= 0; type--) {
2662         for (i = 0; i < MAX_ELEM_ID; i++) {
2663             ChannelElement *che = ac->che[type][i];
2664             if (che) {
2665                 if (type <= TYPE_CPE)
2666                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2667                 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2668                     if (che->ch[0].ics.predictor_present) {
2669                         if (che->ch[0].ics.ltp.present)
2670                             apply_ltp(ac, &che->ch[0]);
2671                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2672                             apply_ltp(ac, &che->ch[1]);
2673                     }
2674                 }
2675                 if (che->ch[0].tns.present)
2676                     apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2677                 if (che->ch[1].tns.present)
2678                     apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2679                 if (type <= TYPE_CPE)
2680                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2681                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2682                     imdct_and_window(ac, &che->ch[0]);
2683                     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2684                         update_ltp(ac, &che->ch[0]);
2685                     if (type == TYPE_CPE) {
2686                         imdct_and_window(ac, &che->ch[1]);
2687                         if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2688                             update_ltp(ac, &che->ch[1]);
2689                     }
2690                     if (ac->oc[1].m4ac.sbr > 0) {
2691                         ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2692                     }
2693                 }
2694                 if (type <= TYPE_CCE)
2695                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2696             }
2697         }
2698     }
2699 }
2700
2701 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2702 {
2703     int size;
2704     AACADTSHeaderInfo hdr_info;
2705     uint8_t layout_map[MAX_ELEM_ID*4][3];
2706     int layout_map_tags, ret;
2707
2708     size = avpriv_aac_parse_header(gb, &hdr_info);
2709     if (size > 0) {
2710         if (hdr_info.num_aac_frames != 1) {
2711             avpriv_report_missing_feature(ac->avctx,
2712                                           "More than one AAC RDB per ADTS frame");
2713             return AVERROR_PATCHWELCOME;
2714         }
2715         push_output_configuration(ac);
2716         if (hdr_info.chan_config) {
2717             ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2718             if ((ret = set_default_channel_config(ac->avctx,
2719                                                   layout_map,
2720                                                   &layout_map_tags,
2721                                                   hdr_info.chan_config)) < 0)
2722                 return ret;
2723             if ((ret = output_configure(ac, layout_map, layout_map_tags,
2724                                         FFMAX(ac->oc[1].status,
2725                                               OC_TRIAL_FRAME), 0)) < 0)
2726                 return ret;
2727         } else {
2728             ac->oc[1].m4ac.chan_config = 0;
2729         }
2730         ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
2731         ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
2732         ac->oc[1].m4ac.object_type     = hdr_info.object_type;
2733         ac->oc[1].m4ac.frame_length_short = 0;
2734         if (ac->oc[0].status != OC_LOCKED ||
2735             ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2736             ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2737             ac->oc[1].m4ac.sbr = -1;
2738             ac->oc[1].m4ac.ps  = -1;
2739         }
2740         if (!hdr_info.crc_absent)
2741             skip_bits(gb, 16);
2742     }
2743     return size;
2744 }
2745
2746 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2747                                int *got_frame_ptr, GetBitContext *gb)
2748 {
2749     AACContext *ac = avctx->priv_data;
2750     const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
2751     ChannelElement *che;
2752     int err, i;
2753     int samples = m4ac->frame_length_short ? 960 : 1024;
2754     int chan_config = m4ac->chan_config;
2755     int aot = m4ac->object_type;
2756
2757     if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2758         samples >>= 1;
2759
2760     ac->frame = data;
2761
2762     if ((err = frame_configure_elements(avctx)) < 0)
2763         return err;
2764
2765     // The FF_PROFILE_AAC_* defines are all object_type - 1
2766     // This may lead to an undefined profile being signaled
2767     ac->avctx->profile = aot - 1;
2768
2769     ac->tags_mapped = 0;
2770
2771     if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
2772         avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2773                               chan_config);
2774         return AVERROR_INVALIDDATA;
2775     }
2776     for (i = 0; i < tags_per_config[chan_config]; i++) {
2777         const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2778         const int elem_id   = aac_channel_layout_map[chan_config-1][i][1];
2779         if (!(che=get_che(ac, elem_type, elem_id))) {
2780             av_log(ac->avctx, AV_LOG_ERROR,
2781                    "channel element %d.%d is not allocated\n",
2782                    elem_type, elem_id);
2783             return AVERROR_INVALIDDATA;
2784         }
2785         if (aot != AOT_ER_AAC_ELD)
2786             skip_bits(gb, 4);
2787         switch (elem_type) {
2788         case TYPE_SCE:
2789             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2790             break;
2791         case TYPE_CPE:
2792             err = decode_cpe(ac, gb, che);
2793             break;
2794         case TYPE_LFE:
2795             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2796             break;
2797         }
2798         if (err < 0)
2799             return err;
2800     }
2801
2802     spectral_to_sample(ac);
2803
2804     ac->frame->nb_samples = samples;
2805     ac->frame->sample_rate = avctx->sample_rate;
2806     *got_frame_ptr = 1;
2807
2808     skip_bits_long(gb, get_bits_left(gb));
2809     return 0;
2810 }
2811
2812 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2813                                 int *got_frame_ptr, GetBitContext *gb)
2814 {
2815     AACContext *ac = avctx->priv_data;
2816     ChannelElement *che = NULL, *che_prev = NULL;
2817     enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2818     int err, elem_id;
2819     int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2820
2821     ac->frame = data;
2822
2823     if (show_bits(gb, 12) == 0xfff) {
2824         if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2825             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2826             goto fail;
2827         }
2828         if (ac->oc[1].m4ac.sampling_index > 12) {
2829             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2830             err = AVERROR_INVALIDDATA;
2831             goto fail;
2832         }
2833     }
2834
2835     if (avctx->channels)
2836         if ((err = frame_configure_elements(avctx)) < 0)
2837             goto fail;
2838
2839     // The FF_PROFILE_AAC_* defines are all object_type - 1
2840     // This may lead to an undefined profile being signaled
2841     ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2842
2843     ac->tags_mapped = 0;
2844     // parse
2845     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2846         elem_id = get_bits(gb, 4);
2847
2848         if (!avctx->channels && elem_type != TYPE_PCE) {
2849             err = AVERROR_INVALIDDATA;
2850             goto fail;
2851         }
2852
2853         if (elem_type < TYPE_DSE) {
2854             if (!(che=get_che(ac, elem_type, elem_id))) {
2855                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2856                        elem_type, elem_id);
2857                 err = AVERROR_INVALIDDATA;
2858                 goto fail;
2859             }
2860             samples = 1024;
2861         }
2862
2863         switch (elem_type) {
2864
2865         case TYPE_SCE:
2866             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2867             audio_found = 1;
2868             break;
2869
2870         case TYPE_CPE:
2871             err = decode_cpe(ac, gb, che);
2872             audio_found = 1;
2873             break;
2874
2875         case TYPE_CCE:
2876             err = decode_cce(ac, gb, che);
2877             break;
2878
2879         case TYPE_LFE:
2880             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2881             audio_found = 1;
2882             break;
2883
2884         case TYPE_DSE:
2885             err = skip_data_stream_element(ac, gb);
2886             break;
2887
2888         case TYPE_PCE: {
2889             uint8_t layout_map[MAX_ELEM_ID*4][3];
2890             int tags;
2891             push_output_configuration(ac);
2892             tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2893             if (tags < 0) {
2894                 err = tags;
2895                 break;
2896             }
2897             if (pce_found) {
2898                 av_log(avctx, AV_LOG_ERROR,
2899                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2900                 pop_output_configuration(ac);
2901             } else {
2902                 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2903                 pce_found = 1;
2904             }
2905             break;
2906         }
2907
2908         case TYPE_FIL:
2909             if (elem_id == 15)
2910                 elem_id += get_bits(gb, 8) - 1;
2911             if (get_bits_left(gb) < 8 * elem_id) {
2912                     av_log(avctx, AV_LOG_ERROR, overread_err);
2913                     err = AVERROR_INVALIDDATA;
2914                     goto fail;
2915             }
2916             while (elem_id > 0)
2917                 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2918             err = 0; /* FIXME */
2919             break;
2920
2921         default:
2922             err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2923             break;
2924         }
2925
2926         che_prev       = che;
2927         elem_type_prev = elem_type;
2928
2929         if (err)
2930             goto fail;
2931
2932         if (get_bits_left(gb) < 3) {
2933             av_log(avctx, AV_LOG_ERROR, overread_err);
2934             err = AVERROR_INVALIDDATA;
2935             goto fail;
2936         }
2937     }
2938
2939     if (!avctx->channels) {
2940         *got_frame_ptr = 0;
2941         return 0;
2942     }
2943
2944     spectral_to_sample(ac);
2945
2946     multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2947     samples <<= multiplier;
2948
2949     if (ac->oc[1].status && audio_found) {
2950         avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2951         avctx->frame_size = samples;
2952         ac->oc[1].status = OC_LOCKED;
2953     }
2954
2955     if (samples) {
2956         ac->frame->nb_samples = samples;
2957         ac->frame->sample_rate = avctx->sample_rate;
2958     }
2959     *got_frame_ptr = !!samples;
2960
2961     return 0;
2962 fail:
2963     pop_output_configuration(ac);
2964     return err;
2965 }
2966
2967 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2968                             int *got_frame_ptr, AVPacket *avpkt)
2969 {
2970     AACContext *ac = avctx->priv_data;
2971     const uint8_t *buf = avpkt->data;
2972     int buf_size = avpkt->size;
2973     GetBitContext gb;
2974     int buf_consumed;
2975     int buf_offset;
2976     int err;
2977     int new_extradata_size;
2978     const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2979                                        AV_PKT_DATA_NEW_EXTRADATA,
2980                                        &new_extradata_size);
2981
2982     if (new_extradata) {
2983         av_free(avctx->extradata);
2984         avctx->extradata = av_mallocz(new_extradata_size +
2985                                       AV_INPUT_BUFFER_PADDING_SIZE);
2986         if (!avctx->extradata)
2987             return AVERROR(ENOMEM);
2988         avctx->extradata_size = new_extradata_size;
2989         memcpy(avctx->extradata, new_extradata, new_extradata_size);
2990         push_output_configuration(ac);
2991         if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2992                                          avctx->extradata,
2993                                          avctx->extradata_size*8, 1) < 0) {
2994             pop_output_configuration(ac);
2995             return AVERROR_INVALIDDATA;
2996         }
2997     }
2998
2999     if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3000         return err;
3001
3002     switch (ac->oc[1].m4ac.object_type) {
3003     case AOT_ER_AAC_LC:
3004     case AOT_ER_AAC_LTP:
3005     case AOT_ER_AAC_LD:
3006     case AOT_ER_AAC_ELD:
3007         err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3008         break;
3009     default:
3010         err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb);
3011     }
3012     if (err < 0)
3013         return err;
3014
3015     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3016     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3017         if (buf[buf_offset])
3018             break;
3019
3020     return buf_size > buf_offset ? buf_consumed : buf_size;
3021 }
3022
3023 static av_cold int aac_decode_close(AVCodecContext *avctx)
3024 {
3025     AACContext *ac = avctx->priv_data;
3026     int i, type;
3027
3028     for (i = 0; i < MAX_ELEM_ID; i++) {
3029         for (type = 0; type < 4; type++) {
3030             if (ac->che[type][i])
3031                 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3032             av_freep(&ac->che[type][i]);
3033         }
3034     }
3035
3036     ff_mdct_end(&ac->mdct);
3037     ff_mdct_end(&ac->mdct_small);
3038     ff_mdct_end(&ac->mdct_ld);
3039     ff_mdct_end(&ac->mdct_ltp);
3040     ff_imdct15_uninit(&ac->mdct480);
3041     return 0;
3042 }
3043
3044
3045 #define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
3046
3047 struct LATMContext {
3048     AACContext aac_ctx;     ///< containing AACContext
3049     int initialized;        ///< initialized after a valid extradata was seen
3050
3051     // parser data
3052     int audio_mux_version_A; ///< LATM syntax version
3053     int frame_length_type;   ///< 0/1 variable/fixed frame length
3054     int frame_length;        ///< frame length for fixed frame length
3055 };
3056
3057 static inline uint32_t latm_get_value(GetBitContext *b)
3058 {
3059     int length = get_bits(b, 2);
3060
3061     return get_bits_long(b, (length+1)*8);
3062 }
3063
3064 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
3065                                              GetBitContext *gb, int asclen)
3066 {
3067     AACContext *ac        = &latmctx->aac_ctx;
3068     AVCodecContext *avctx = ac->avctx;
3069     MPEG4AudioConfig m4ac = { 0 };
3070     int config_start_bit  = get_bits_count(gb);
3071     int sync_extension    = 0;
3072     int bits_consumed, esize;
3073
3074     if (asclen) {
3075         sync_extension = 1;
3076         asclen         = FFMIN(asclen, get_bits_left(gb));
3077     } else
3078         asclen         = get_bits_left(gb);
3079
3080     if (config_start_bit % 8) {
3081         avpriv_request_sample(latmctx->aac_ctx.avctx,
3082                               "Non-byte-aligned audio-specific config");
3083         return AVERROR_PATCHWELCOME;
3084     }
3085     if (asclen <= 0)
3086         return AVERROR_INVALIDDATA;
3087     bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3088                                          gb->buffer + (config_start_bit / 8),
3089                                          asclen, sync_extension);
3090
3091     if (bits_consumed < 0)
3092         return AVERROR_INVALIDDATA;
3093
3094     if (!latmctx->initialized ||
3095         ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3096         ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3097
3098         av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3099         latmctx->initialized = 0;
3100
3101         esize = (bits_consumed+7) / 8;
3102
3103         if (avctx->extradata_size < esize) {
3104             av_free(avctx->extradata);
3105             avctx->extradata = av_malloc(esize + AV_INPUT_BUFFER_PADDING_SIZE);
3106             if (!avctx->extradata)
3107                 return AVERROR(ENOMEM);
3108         }
3109
3110         avctx->extradata_size = esize;
3111         memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3112         memset(avctx->extradata+esize, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3113     }
3114     skip_bits_long(gb, bits_consumed);
3115
3116     return bits_consumed;
3117 }
3118
3119 static int read_stream_mux_config(struct LATMContext *latmctx,
3120                                   GetBitContext *gb)
3121 {
3122     int ret, audio_mux_version = get_bits(gb, 1);
3123
3124     latmctx->audio_mux_version_A = 0;
3125     if (audio_mux_version)
3126         latmctx->audio_mux_version_A = get_bits(gb, 1);
3127
3128     if (!latmctx->audio_mux_version_A) {
3129
3130         if (audio_mux_version)
3131             latm_get_value(gb);                 // taraFullness
3132
3133         skip_bits(gb, 1);                       // allStreamSameTimeFraming
3134         skip_bits(gb, 6);                       // numSubFrames
3135         // numPrograms
3136         if (get_bits(gb, 4)) {                  // numPrograms
3137             avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3138             return AVERROR_PATCHWELCOME;
3139         }
3140
3141         // for each program (which there is only on in DVB)
3142
3143         // for each layer (which there is only on in DVB)
3144         if (get_bits(gb, 3)) {                   // numLayer
3145             avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3146             return AVERROR_PATCHWELCOME;
3147         }
3148
3149         // for all but first stream: use_same_config = get_bits(gb, 1);
3150         if (!audio_mux_version) {
3151             if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3152                 return ret;
3153         } else {
3154             int ascLen = latm_get_value(gb);
3155             if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3156                 return ret;
3157             ascLen -= ret;
3158             skip_bits_long(gb, ascLen);
3159         }
3160
3161         latmctx->frame_length_type = get_bits(gb, 3);
3162         switch (latmctx->frame_length_type) {
3163         case 0:
3164             skip_bits(gb, 8);       // latmBufferFullness
3165             break;
3166         case 1:
3167             latmctx->frame_length = get_bits(gb, 9);
3168             break;
3169         case 3:
3170         case 4:
3171         case 5:
3172             skip_bits(gb, 6);       // CELP frame length table index
3173             break;
3174         case 6:
3175         case 7:
3176             skip_bits(gb, 1);       // HVXC frame length table index
3177             break;
3178         }
3179
3180         if (get_bits(gb, 1)) {                  // other data
3181             if (audio_mux_version) {
3182                 latm_get_value(gb);             // other_data_bits
3183             } else {
3184                 int esc;
3185                 do {
3186                     esc = get_bits(gb, 1);
3187                     skip_bits(gb, 8);
3188                 } while (esc);
3189             }
3190         }
3191
3192         if (get_bits(gb, 1))                     // crc present
3193             skip_bits(gb, 8);                    // config_crc
3194     }
3195
3196     return 0;
3197 }
3198
3199 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3200 {
3201     uint8_t tmp;
3202
3203     if (ctx->frame_length_type == 0) {
3204         int mux_slot_length = 0;
3205         do {
3206             tmp = get_bits(gb, 8);
3207             mux_slot_length += tmp;
3208         } while (tmp == 255);
3209         return mux_slot_length;
3210     } else if (ctx->frame_length_type == 1) {
3211         return ctx->frame_length;
3212     } else if (ctx->frame_length_type == 3 ||
3213                ctx->frame_length_type == 5 ||
3214                ctx->frame_length_type == 7) {
3215         skip_bits(gb, 2);          // mux_slot_length_coded
3216     }
3217     return 0;
3218 }
3219
3220 static int read_audio_mux_element(struct LATMContext *latmctx,
3221                                   GetBitContext *gb)
3222 {
3223     int err;
3224     uint8_t use_same_mux = get_bits(gb, 1);
3225     if (!use_same_mux) {
3226         if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3227             return err;
3228     } else if (!latmctx->aac_ctx.avctx->extradata) {
3229         av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3230                "no decoder config found\n");
3231         return AVERROR(EAGAIN);
3232     }
3233     if (latmctx->audio_mux_version_A == 0) {
3234         int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3235         if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3236             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3237             return AVERROR_INVALIDDATA;
3238         } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3239             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3240                    "frame length mismatch %d << %d\n",
3241                    mux_slot_length_bytes * 8, get_bits_left(gb));
3242             return AVERROR_INVALIDDATA;
3243         }
3244     }
3245     return 0;
3246 }
3247
3248
3249 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3250                              int *got_frame_ptr, AVPacket *avpkt)
3251 {
3252     struct LATMContext *latmctx = avctx->priv_data;
3253     int                 muxlength, err;
3254     GetBitContext       gb;
3255
3256     if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
3257         return err;
3258
3259     // check for LOAS sync word
3260     if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3261         return AVERROR_INVALIDDATA;
3262
3263     muxlength = get_bits(&gb, 13) + 3;
3264     // not enough data, the parser should have sorted this
3265     if (muxlength > avpkt->size)
3266         return AVERROR_INVALIDDATA;
3267
3268     if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3269         return err;
3270
3271     if (!latmctx->initialized) {
3272         if (!avctx->extradata) {
3273             *got_frame_ptr = 0;
3274             return avpkt->size;
3275         } else {
3276             push_output_configuration(&latmctx->aac_ctx);
3277             if ((err = decode_audio_specific_config(
3278                     &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3279                     avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3280                 pop_output_configuration(&latmctx->aac_ctx);
3281                 return err;
3282             }
3283             latmctx->initialized = 1;
3284         }
3285     }
3286
3287     if (show_bits(&gb, 12) == 0xfff) {
3288         av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3289                "ADTS header detected, probably as result of configuration "
3290                "misparsing\n");
3291         return AVERROR_INVALIDDATA;
3292     }
3293
3294     switch (latmctx->aac_ctx.oc[1].m4ac.object_type) {
3295     case AOT_ER_AAC_LC:
3296     case AOT_ER_AAC_LTP:
3297     case AOT_ER_AAC_LD:
3298     case AOT_ER_AAC_ELD:
3299         err = aac_decode_er_frame(avctx, out, got_frame_ptr, &gb);
3300         break;
3301     default:
3302         err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb);
3303     }
3304     if (err < 0)
3305         return err;
3306
3307     return muxlength;
3308 }
3309
3310 static av_cold int latm_decode_init(AVCodecContext *avctx)
3311 {
3312     struct LATMContext *latmctx = avctx->priv_data;
3313     int ret = aac_decode_init(avctx);
3314
3315     if (avctx->extradata_size > 0)
3316         latmctx->initialized = !ret;
3317
3318     return ret;
3319 }
3320
3321
3322 AVCodec ff_aac_decoder = {
3323     .name            = "aac",
3324     .long_name       = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3325     .type            = AVMEDIA_TYPE_AUDIO,
3326     .id              = AV_CODEC_ID_AAC,
3327     .priv_data_size  = sizeof(AACContext),
3328     .init            = aac_decode_init,
3329     .close           = aac_decode_close,
3330     .decode          = aac_decode_frame,
3331     .sample_fmts     = (const enum AVSampleFormat[]) {
3332         AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3333     },
3334     .capabilities    = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
3335     .caps_internal   = FF_CODEC_CAP_INIT_THREADSAFE,
3336     .channel_layouts = aac_channel_layout,
3337 };
3338
3339 /*
3340     Note: This decoder filter is intended to decode LATM streams transferred
3341     in MPEG transport streams which only contain one program.
3342     To do a more complex LATM demuxing a separate LATM demuxer should be used.
3343 */
3344 AVCodec ff_aac_latm_decoder = {
3345     .name            = "aac_latm",
3346     .long_name       = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3347     .type            = AVMEDIA_TYPE_AUDIO,
3348     .id              = AV_CODEC_ID_AAC_LATM,
3349     .priv_data_size  = sizeof(struct LATMContext),
3350     .init            = latm_decode_init,
3351     .close           = aac_decode_close,
3352     .decode          = latm_decode_frame,
3353     .sample_fmts     = (const enum AVSampleFormat[]) {
3354         AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3355     },
3356     .capabilities    = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
3357     .caps_internal   = FF_CODEC_CAP_INIT_THREADSAFE,
3358     .channel_layouts = aac_channel_layout,
3359 };