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