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