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