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