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