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