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