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