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