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