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