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