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