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