OSDN Git Service

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