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