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