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