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