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