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