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