]> git.sesse.net Git - ffmpeg/blob - libavcodec/aacdec.c
indeo: Do not reference mismatched tiles
[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;
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             skip_bits(gb, 3);      /* aacSectionDataResilienceFlag
756                                     * aacScalefactorDataResilienceFlag
757                                     * aacSpectralDataResilienceFlag
758                                     */
759             break;
760         }
761         skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
762     }
763     return 0;
764 }
765
766 /**
767  * Decode audio specific configuration; reference: table 1.13.
768  *
769  * @param   ac          pointer to AACContext, may be null
770  * @param   avctx       pointer to AVCCodecContext, used for logging
771  * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
772  * @param   data        pointer to buffer holding an audio specific config
773  * @param   bit_size    size of audio specific config or data in bits
774  * @param   sync_extension look for an appended sync extension
775  *
776  * @return  Returns error status or number of consumed bits. <0 - error
777  */
778 static int decode_audio_specific_config(AACContext *ac,
779                                         AVCodecContext *avctx,
780                                         MPEG4AudioConfig *m4ac,
781                                         const uint8_t *data, int bit_size,
782                                         int sync_extension)
783 {
784     GetBitContext gb;
785     int i, ret;
786
787     av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
788     for (i = 0; i < avctx->extradata_size; i++)
789         av_dlog(avctx, "%02x ", avctx->extradata[i]);
790     av_dlog(avctx, "\n");
791
792     init_get_bits(&gb, data, bit_size);
793
794     if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
795                                           sync_extension)) < 0)
796         return AVERROR_INVALIDDATA;
797     if (m4ac->sampling_index > 12) {
798         av_log(avctx, AV_LOG_ERROR,
799                "invalid sampling rate index %d\n",
800                m4ac->sampling_index);
801         return AVERROR_INVALIDDATA;
802     }
803
804     skip_bits_long(&gb, i);
805
806     switch (m4ac->object_type) {
807     case AOT_AAC_MAIN:
808     case AOT_AAC_LC:
809     case AOT_AAC_LTP:
810         if ((ret = decode_ga_specific_config(ac, avctx, &gb,
811                                             m4ac, m4ac->chan_config)) < 0)
812             return ret;
813         break;
814     default:
815         av_log(avctx, AV_LOG_ERROR,
816                "Audio object type %s%d is not supported.\n",
817                m4ac->sbr == 1 ? "SBR+" : "",
818                m4ac->object_type);
819         return AVERROR(ENOSYS);
820     }
821
822     av_dlog(avctx,
823             "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
824             m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
825             m4ac->sample_rate, m4ac->sbr,
826             m4ac->ps);
827
828     return get_bits_count(&gb);
829 }
830
831 /**
832  * linear congruential pseudorandom number generator
833  *
834  * @param   previous_val    pointer to the current state of the generator
835  *
836  * @return  Returns a 32-bit pseudorandom integer
837  */
838 static av_always_inline int lcg_random(int previous_val)
839 {
840     union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
841     return v.s;
842 }
843
844 static av_always_inline void reset_predict_state(PredictorState *ps)
845 {
846     ps->r0   = 0.0f;
847     ps->r1   = 0.0f;
848     ps->cor0 = 0.0f;
849     ps->cor1 = 0.0f;
850     ps->var0 = 1.0f;
851     ps->var1 = 1.0f;
852 }
853
854 static void reset_all_predictors(PredictorState *ps)
855 {
856     int i;
857     for (i = 0; i < MAX_PREDICTORS; i++)
858         reset_predict_state(&ps[i]);
859 }
860
861 static int sample_rate_idx (int rate)
862 {
863          if (92017 <= rate) return 0;
864     else if (75132 <= rate) return 1;
865     else if (55426 <= rate) return 2;
866     else if (46009 <= rate) return 3;
867     else if (37566 <= rate) return 4;
868     else if (27713 <= rate) return 5;
869     else if (23004 <= rate) return 6;
870     else if (18783 <= rate) return 7;
871     else if (13856 <= rate) return 8;
872     else if (11502 <= rate) return 9;
873     else if (9391  <= rate) return 10;
874     else                    return 11;
875 }
876
877 static void reset_predictor_group(PredictorState *ps, int group_num)
878 {
879     int i;
880     for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
881         reset_predict_state(&ps[i]);
882 }
883
884 #define AAC_INIT_VLC_STATIC(num, size)                                     \
885     INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num],     \
886          ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]),  \
887                                     sizeof(ff_aac_spectral_bits[num][0]),  \
888         ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
889                                     sizeof(ff_aac_spectral_codes[num][0]), \
890         size);
891
892 static av_cold int aac_decode_init(AVCodecContext *avctx)
893 {
894     AACContext *ac = avctx->priv_data;
895     int ret;
896
897     ac->avctx = avctx;
898     ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
899
900     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
901
902     if (avctx->extradata_size > 0) {
903         if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
904                                                 avctx->extradata,
905                                                 avctx->extradata_size * 8,
906                                                 1)) < 0)
907             return ret;
908     } else {
909         int sr, i;
910         uint8_t layout_map[MAX_ELEM_ID*4][3];
911         int layout_map_tags;
912
913         sr = sample_rate_idx(avctx->sample_rate);
914         ac->oc[1].m4ac.sampling_index = sr;
915         ac->oc[1].m4ac.channels = avctx->channels;
916         ac->oc[1].m4ac.sbr = -1;
917         ac->oc[1].m4ac.ps = -1;
918
919         for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
920             if (ff_mpeg4audio_channels[i] == avctx->channels)
921                 break;
922         if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
923             i = 0;
924         }
925         ac->oc[1].m4ac.chan_config = i;
926
927         if (ac->oc[1].m4ac.chan_config) {
928             int ret = set_default_channel_config(avctx, layout_map,
929                 &layout_map_tags, ac->oc[1].m4ac.chan_config);
930             if (!ret)
931                 output_configure(ac, layout_map, layout_map_tags,
932                                  OC_GLOBAL_HDR, 0);
933             else if (avctx->err_recognition & AV_EF_EXPLODE)
934                 return AVERROR_INVALIDDATA;
935         }
936     }
937
938     AAC_INIT_VLC_STATIC( 0, 304);
939     AAC_INIT_VLC_STATIC( 1, 270);
940     AAC_INIT_VLC_STATIC( 2, 550);
941     AAC_INIT_VLC_STATIC( 3, 300);
942     AAC_INIT_VLC_STATIC( 4, 328);
943     AAC_INIT_VLC_STATIC( 5, 294);
944     AAC_INIT_VLC_STATIC( 6, 306);
945     AAC_INIT_VLC_STATIC( 7, 268);
946     AAC_INIT_VLC_STATIC( 8, 510);
947     AAC_INIT_VLC_STATIC( 9, 366);
948     AAC_INIT_VLC_STATIC(10, 462);
949
950     ff_aac_sbr_init();
951
952     ff_fmt_convert_init(&ac->fmt_conv, avctx);
953     avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
954
955     ac->random_state = 0x1f2e3d4c;
956
957     ff_aac_tableinit();
958
959     INIT_VLC_STATIC(&vlc_scalefactors, 7,
960                     FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
961                     ff_aac_scalefactor_bits,
962                     sizeof(ff_aac_scalefactor_bits[0]),
963                     sizeof(ff_aac_scalefactor_bits[0]),
964                     ff_aac_scalefactor_code,
965                     sizeof(ff_aac_scalefactor_code[0]),
966                     sizeof(ff_aac_scalefactor_code[0]),
967                     352);
968
969     ff_mdct_init(&ac->mdct,       11, 1, 1.0 / (32768.0 * 1024.0));
970     ff_mdct_init(&ac->mdct_small,  8, 1, 1.0 / (32768.0 * 128.0));
971     ff_mdct_init(&ac->mdct_ltp,   11, 0, -2.0 * 32768.0);
972     // window initialization
973     ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
974     ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
975     ff_init_ff_sine_windows(10);
976     ff_init_ff_sine_windows( 7);
977
978     cbrt_tableinit();
979
980     return 0;
981 }
982
983 /**
984  * Skip data_stream_element; reference: table 4.10.
985  */
986 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
987 {
988     int byte_align = get_bits1(gb);
989     int count = get_bits(gb, 8);
990     if (count == 255)
991         count += get_bits(gb, 8);
992     if (byte_align)
993         align_get_bits(gb);
994
995     if (get_bits_left(gb) < 8 * count) {
996         av_log(ac->avctx, AV_LOG_ERROR, overread_err);
997         return AVERROR_INVALIDDATA;
998     }
999     skip_bits_long(gb, 8 * count);
1000     return 0;
1001 }
1002
1003 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1004                              GetBitContext *gb)
1005 {
1006     int sfb;
1007     if (get_bits1(gb)) {
1008         ics->predictor_reset_group = get_bits(gb, 5);
1009         if (ics->predictor_reset_group == 0 ||
1010             ics->predictor_reset_group > 30) {
1011             av_log(ac->avctx, AV_LOG_ERROR,
1012                    "Invalid Predictor Reset Group.\n");
1013             return AVERROR_INVALIDDATA;
1014         }
1015     }
1016     for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1017         ics->prediction_used[sfb] = get_bits1(gb);
1018     }
1019     return 0;
1020 }
1021
1022 /**
1023  * Decode Long Term Prediction data; reference: table 4.xx.
1024  */
1025 static void decode_ltp(LongTermPrediction *ltp,
1026                        GetBitContext *gb, uint8_t max_sfb)
1027 {
1028     int sfb;
1029
1030     ltp->lag  = get_bits(gb, 11);
1031     ltp->coef = ltp_coef[get_bits(gb, 3)];
1032     for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1033         ltp->used[sfb] = get_bits1(gb);
1034 }
1035
1036 /**
1037  * Decode Individual Channel Stream info; reference: table 4.6.
1038  */
1039 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1040                            GetBitContext *gb)
1041 {
1042     if (get_bits1(gb)) {
1043         av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1044         return AVERROR_INVALIDDATA;
1045     }
1046     ics->window_sequence[1] = ics->window_sequence[0];
1047     ics->window_sequence[0] = get_bits(gb, 2);
1048     ics->use_kb_window[1]   = ics->use_kb_window[0];
1049     ics->use_kb_window[0]   = get_bits1(gb);
1050     ics->num_window_groups  = 1;
1051     ics->group_len[0]       = 1;
1052     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1053         int i;
1054         ics->max_sfb = get_bits(gb, 4);
1055         for (i = 0; i < 7; i++) {
1056             if (get_bits1(gb)) {
1057                 ics->group_len[ics->num_window_groups - 1]++;
1058             } else {
1059                 ics->num_window_groups++;
1060                 ics->group_len[ics->num_window_groups - 1] = 1;
1061             }
1062         }
1063         ics->num_windows       = 8;
1064         ics->swb_offset        =    ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1065         ics->num_swb           =   ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1066         ics->tns_max_bands     = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1067         ics->predictor_present = 0;
1068     } else {
1069         ics->max_sfb               = get_bits(gb, 6);
1070         ics->num_windows           = 1;
1071         ics->swb_offset            =    ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1072         ics->num_swb               =   ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1073         ics->tns_max_bands         = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1074         ics->predictor_present     = get_bits1(gb);
1075         ics->predictor_reset_group = 0;
1076         if (ics->predictor_present) {
1077             if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1078                 if (decode_prediction(ac, ics, gb)) {
1079                     return AVERROR_INVALIDDATA;
1080                 }
1081             } else if (ac->oc[1].m4ac.object_type == AOT_AAC_LC) {
1082                 av_log(ac->avctx, AV_LOG_ERROR,
1083                        "Prediction is not allowed in AAC-LC.\n");
1084                 return AVERROR_INVALIDDATA;
1085             } else {
1086                 if ((ics->ltp.present = get_bits(gb, 1)))
1087                     decode_ltp(&ics->ltp, gb, ics->max_sfb);
1088             }
1089         }
1090     }
1091
1092     if (ics->max_sfb > ics->num_swb) {
1093         av_log(ac->avctx, AV_LOG_ERROR,
1094                "Number of scalefactor bands in group (%d) "
1095                "exceeds limit (%d).\n",
1096                ics->max_sfb, ics->num_swb);
1097         return AVERROR_INVALIDDATA;
1098     }
1099
1100     return 0;
1101 }
1102
1103 /**
1104  * Decode band types (section_data payload); reference: table 4.46.
1105  *
1106  * @param   band_type           array of the used band type
1107  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1108  *
1109  * @return  Returns error status. 0 - OK, !0 - error
1110  */
1111 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1112                              int band_type_run_end[120], GetBitContext *gb,
1113                              IndividualChannelStream *ics)
1114 {
1115     int g, idx = 0;
1116     const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1117     for (g = 0; g < ics->num_window_groups; g++) {
1118         int k = 0;
1119         while (k < ics->max_sfb) {
1120             uint8_t sect_end = k;
1121             int sect_len_incr;
1122             int sect_band_type = get_bits(gb, 4);
1123             if (sect_band_type == 12) {
1124                 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1125                 return AVERROR_INVALIDDATA;
1126             }
1127             do {
1128                 sect_len_incr = get_bits(gb, bits);
1129                 sect_end += sect_len_incr;
1130                 if (get_bits_left(gb) < 0) {
1131                     av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1132                     return AVERROR_INVALIDDATA;
1133                 }
1134                 if (sect_end > ics->max_sfb) {
1135                     av_log(ac->avctx, AV_LOG_ERROR,
1136                            "Number of bands (%d) exceeds limit (%d).\n",
1137                            sect_end, ics->max_sfb);
1138                     return AVERROR_INVALIDDATA;
1139                 }
1140             } while (sect_len_incr == (1 << bits) - 1);
1141             for (; k < sect_end; k++) {
1142                 band_type        [idx]   = sect_band_type;
1143                 band_type_run_end[idx++] = sect_end;
1144             }
1145         }
1146     }
1147     return 0;
1148 }
1149
1150 /**
1151  * Decode scalefactors; reference: table 4.47.
1152  *
1153  * @param   global_gain         first scalefactor value as scalefactors are differentially coded
1154  * @param   band_type           array of the used band type
1155  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1156  * @param   sf                  array of scalefactors or intensity stereo positions
1157  *
1158  * @return  Returns error status. 0 - OK, !0 - error
1159  */
1160 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1161                                unsigned int global_gain,
1162                                IndividualChannelStream *ics,
1163                                enum BandType band_type[120],
1164                                int band_type_run_end[120])
1165 {
1166     int g, i, idx = 0;
1167     int offset[3] = { global_gain, global_gain - 90, 0 };
1168     int clipped_offset;
1169     int noise_flag = 1;
1170     for (g = 0; g < ics->num_window_groups; g++) {
1171         for (i = 0; i < ics->max_sfb;) {
1172             int run_end = band_type_run_end[idx];
1173             if (band_type[idx] == ZERO_BT) {
1174                 for (; i < run_end; i++, idx++)
1175                     sf[idx] = 0.;
1176             } else if ((band_type[idx] == INTENSITY_BT) ||
1177                        (band_type[idx] == INTENSITY_BT2)) {
1178                 for (; i < run_end; i++, idx++) {
1179                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1180                     clipped_offset = av_clip(offset[2], -155, 100);
1181                     if (offset[2] != clipped_offset) {
1182                         avpriv_request_sample(ac->avctx,
1183                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1184                                               "Clipped intensity stereo position (%d -> %d)",
1185                                               offset[2], clipped_offset);
1186                     }
1187                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1188                 }
1189             } else if (band_type[idx] == NOISE_BT) {
1190                 for (; i < run_end; i++, idx++) {
1191                     if (noise_flag-- > 0)
1192                         offset[1] += get_bits(gb, 9) - 256;
1193                     else
1194                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1195                     clipped_offset = av_clip(offset[1], -100, 155);
1196                     if (offset[1] != clipped_offset) {
1197                         avpriv_request_sample(ac->avctx,
1198                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1199                                               "Clipped noise gain (%d -> %d)",
1200                                               offset[1], clipped_offset);
1201                     }
1202                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1203                 }
1204             } else {
1205                 for (; i < run_end; i++, idx++) {
1206                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1207                     if (offset[0] > 255U) {
1208                         av_log(ac->avctx, AV_LOG_ERROR,
1209                                "Scalefactor (%d) out of range.\n", offset[0]);
1210                         return AVERROR_INVALIDDATA;
1211                     }
1212                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1213                 }
1214             }
1215         }
1216     }
1217     return 0;
1218 }
1219
1220 /**
1221  * Decode pulse data; reference: table 4.7.
1222  */
1223 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1224                          const uint16_t *swb_offset, int num_swb)
1225 {
1226     int i, pulse_swb;
1227     pulse->num_pulse = get_bits(gb, 2) + 1;
1228     pulse_swb        = get_bits(gb, 6);
1229     if (pulse_swb >= num_swb)
1230         return -1;
1231     pulse->pos[0]    = swb_offset[pulse_swb];
1232     pulse->pos[0]   += get_bits(gb, 5);
1233     if (pulse->pos[0] > 1023)
1234         return -1;
1235     pulse->amp[0]    = get_bits(gb, 4);
1236     for (i = 1; i < pulse->num_pulse; i++) {
1237         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1238         if (pulse->pos[i] > 1023)
1239             return -1;
1240         pulse->amp[i] = get_bits(gb, 4);
1241     }
1242     return 0;
1243 }
1244
1245 /**
1246  * Decode Temporal Noise Shaping data; reference: table 4.48.
1247  *
1248  * @return  Returns error status. 0 - OK, !0 - error
1249  */
1250 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1251                       GetBitContext *gb, const IndividualChannelStream *ics)
1252 {
1253     int w, filt, i, coef_len, coef_res, coef_compress;
1254     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1255     const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1256     for (w = 0; w < ics->num_windows; w++) {
1257         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1258             coef_res = get_bits1(gb);
1259
1260             for (filt = 0; filt < tns->n_filt[w]; filt++) {
1261                 int tmp2_idx;
1262                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1263
1264                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1265                     av_log(ac->avctx, AV_LOG_ERROR,
1266                            "TNS filter order %d is greater than maximum %d.\n",
1267                            tns->order[w][filt], tns_max_order);
1268                     tns->order[w][filt] = 0;
1269                     return AVERROR_INVALIDDATA;
1270                 }
1271                 if (tns->order[w][filt]) {
1272                     tns->direction[w][filt] = get_bits1(gb);
1273                     coef_compress = get_bits1(gb);
1274                     coef_len = coef_res + 3 - coef_compress;
1275                     tmp2_idx = 2 * coef_compress + coef_res;
1276
1277                     for (i = 0; i < tns->order[w][filt]; i++)
1278                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1279                 }
1280             }
1281         }
1282     }
1283     return 0;
1284 }
1285
1286 /**
1287  * Decode Mid/Side data; reference: table 4.54.
1288  *
1289  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1290  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1291  *                      [3] reserved for scalable AAC
1292  */
1293 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1294                                    int ms_present)
1295 {
1296     int idx;
1297     if (ms_present == 1) {
1298         for (idx = 0;
1299              idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1300              idx++)
1301             cpe->ms_mask[idx] = get_bits1(gb);
1302     } else if (ms_present == 2) {
1303         memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
1304     }
1305 }
1306
1307 #ifndef VMUL2
1308 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1309                            const float *scale)
1310 {
1311     float s = *scale;
1312     *dst++ = v[idx    & 15] * s;
1313     *dst++ = v[idx>>4 & 15] * s;
1314     return dst;
1315 }
1316 #endif
1317
1318 #ifndef VMUL4
1319 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1320                            const float *scale)
1321 {
1322     float s = *scale;
1323     *dst++ = v[idx    & 3] * s;
1324     *dst++ = v[idx>>2 & 3] * s;
1325     *dst++ = v[idx>>4 & 3] * s;
1326     *dst++ = v[idx>>6 & 3] * s;
1327     return dst;
1328 }
1329 #endif
1330
1331 #ifndef VMUL2S
1332 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1333                             unsigned sign, const float *scale)
1334 {
1335     union av_intfloat32 s0, s1;
1336
1337     s0.f = s1.f = *scale;
1338     s0.i ^= sign >> 1 << 31;
1339     s1.i ^= sign      << 31;
1340
1341     *dst++ = v[idx    & 15] * s0.f;
1342     *dst++ = v[idx>>4 & 15] * s1.f;
1343
1344     return dst;
1345 }
1346 #endif
1347
1348 #ifndef VMUL4S
1349 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1350                             unsigned sign, const float *scale)
1351 {
1352     unsigned nz = idx >> 12;
1353     union av_intfloat32 s = { .f = *scale };
1354     union av_intfloat32 t;
1355
1356     t.i = s.i ^ (sign & 1U<<31);
1357     *dst++ = v[idx    & 3] * t.f;
1358
1359     sign <<= nz & 1; nz >>= 1;
1360     t.i = s.i ^ (sign & 1U<<31);
1361     *dst++ = v[idx>>2 & 3] * t.f;
1362
1363     sign <<= nz & 1; nz >>= 1;
1364     t.i = s.i ^ (sign & 1U<<31);
1365     *dst++ = v[idx>>4 & 3] * t.f;
1366
1367     sign <<= nz & 1;
1368     t.i = s.i ^ (sign & 1U<<31);
1369     *dst++ = v[idx>>6 & 3] * t.f;
1370
1371     return dst;
1372 }
1373 #endif
1374
1375 /**
1376  * Decode spectral data; reference: table 4.50.
1377  * Dequantize and scale spectral data; reference: 4.6.3.3.
1378  *
1379  * @param   coef            array of dequantized, scaled spectral data
1380  * @param   sf              array of scalefactors or intensity stereo positions
1381  * @param   pulse_present   set if pulses are present
1382  * @param   pulse           pointer to pulse data struct
1383  * @param   band_type       array of the used band type
1384  *
1385  * @return  Returns error status. 0 - OK, !0 - error
1386  */
1387 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1388                                        GetBitContext *gb, const float sf[120],
1389                                        int pulse_present, const Pulse *pulse,
1390                                        const IndividualChannelStream *ics,
1391                                        enum BandType band_type[120])
1392 {
1393     int i, k, g, idx = 0;
1394     const int c = 1024 / ics->num_windows;
1395     const uint16_t *offsets = ics->swb_offset;
1396     float *coef_base = coef;
1397
1398     for (g = 0; g < ics->num_windows; g++)
1399         memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1400                sizeof(float) * (c - offsets[ics->max_sfb]));
1401
1402     for (g = 0; g < ics->num_window_groups; g++) {
1403         unsigned g_len = ics->group_len[g];
1404
1405         for (i = 0; i < ics->max_sfb; i++, idx++) {
1406             const unsigned cbt_m1 = band_type[idx] - 1;
1407             float *cfo = coef + offsets[i];
1408             int off_len = offsets[i + 1] - offsets[i];
1409             int group;
1410
1411             if (cbt_m1 >= INTENSITY_BT2 - 1) {
1412                 for (group = 0; group < g_len; group++, cfo+=128) {
1413                     memset(cfo, 0, off_len * sizeof(float));
1414                 }
1415             } else if (cbt_m1 == NOISE_BT - 1) {
1416                 for (group = 0; group < g_len; group++, cfo+=128) {
1417                     float scale;
1418                     float band_energy;
1419
1420                     for (k = 0; k < off_len; k++) {
1421                         ac->random_state  = lcg_random(ac->random_state);
1422                         cfo[k] = ac->random_state;
1423                     }
1424
1425                     band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1426                     scale = sf[idx] / sqrtf(band_energy);
1427                     ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1428                 }
1429             } else {
1430                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1431                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1432                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1433                 OPEN_READER(re, gb);
1434
1435                 switch (cbt_m1 >> 1) {
1436                 case 0:
1437                     for (group = 0; group < g_len; group++, cfo+=128) {
1438                         float *cf = cfo;
1439                         int len = off_len;
1440
1441                         do {
1442                             int code;
1443                             unsigned cb_idx;
1444
1445                             UPDATE_CACHE(re, gb);
1446                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1447                             cb_idx = cb_vector_idx[code];
1448                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
1449                         } while (len -= 4);
1450                     }
1451                     break;
1452
1453                 case 1:
1454                     for (group = 0; group < g_len; group++, cfo+=128) {
1455                         float *cf = cfo;
1456                         int len = off_len;
1457
1458                         do {
1459                             int code;
1460                             unsigned nnz;
1461                             unsigned cb_idx;
1462                             uint32_t bits;
1463
1464                             UPDATE_CACHE(re, gb);
1465                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1466                             cb_idx = cb_vector_idx[code];
1467                             nnz = cb_idx >> 8 & 15;
1468                             bits = nnz ? GET_CACHE(re, gb) : 0;
1469                             LAST_SKIP_BITS(re, gb, nnz);
1470                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1471                         } while (len -= 4);
1472                     }
1473                     break;
1474
1475                 case 2:
1476                     for (group = 0; group < g_len; group++, cfo+=128) {
1477                         float *cf = cfo;
1478                         int len = off_len;
1479
1480                         do {
1481                             int code;
1482                             unsigned cb_idx;
1483
1484                             UPDATE_CACHE(re, gb);
1485                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1486                             cb_idx = cb_vector_idx[code];
1487                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
1488                         } while (len -= 2);
1489                     }
1490                     break;
1491
1492                 case 3:
1493                 case 4:
1494                     for (group = 0; group < g_len; group++, cfo+=128) {
1495                         float *cf = cfo;
1496                         int len = off_len;
1497
1498                         do {
1499                             int code;
1500                             unsigned nnz;
1501                             unsigned cb_idx;
1502                             unsigned sign;
1503
1504                             UPDATE_CACHE(re, gb);
1505                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1506                             cb_idx = cb_vector_idx[code];
1507                             nnz = cb_idx >> 8 & 15;
1508                             sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1509                             LAST_SKIP_BITS(re, gb, nnz);
1510                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1511                         } while (len -= 2);
1512                     }
1513                     break;
1514
1515                 default:
1516                     for (group = 0; group < g_len; group++, cfo+=128) {
1517                         float *cf = cfo;
1518                         uint32_t *icf = (uint32_t *) cf;
1519                         int len = off_len;
1520
1521                         do {
1522                             int code;
1523                             unsigned nzt, nnz;
1524                             unsigned cb_idx;
1525                             uint32_t bits;
1526                             int j;
1527
1528                             UPDATE_CACHE(re, gb);
1529                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1530
1531                             if (!code) {
1532                                 *icf++ = 0;
1533                                 *icf++ = 0;
1534                                 continue;
1535                             }
1536
1537                             cb_idx = cb_vector_idx[code];
1538                             nnz = cb_idx >> 12;
1539                             nzt = cb_idx >> 8;
1540                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1541                             LAST_SKIP_BITS(re, gb, nnz);
1542
1543                             for (j = 0; j < 2; j++) {
1544                                 if (nzt & 1<<j) {
1545                                     uint32_t b;
1546                                     int n;
1547                                     /* The total length of escape_sequence must be < 22 bits according
1548                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1549                                     UPDATE_CACHE(re, gb);
1550                                     b = GET_CACHE(re, gb);
1551                                     b = 31 - av_log2(~b);
1552
1553                                     if (b > 8) {
1554                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1555                                         return AVERROR_INVALIDDATA;
1556                                     }
1557
1558                                     SKIP_BITS(re, gb, b + 1);
1559                                     b += 4;
1560                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
1561                                     LAST_SKIP_BITS(re, gb, b);
1562                                     *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1563                                     bits <<= 1;
1564                                 } else {
1565                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1566                                     *icf++ = (bits & 1U<<31) | v;
1567                                     bits <<= !!v;
1568                                 }
1569                                 cb_idx >>= 4;
1570                             }
1571                         } while (len -= 2);
1572
1573                         ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1574                     }
1575                 }
1576
1577                 CLOSE_READER(re, gb);
1578             }
1579         }
1580         coef += g_len << 7;
1581     }
1582
1583     if (pulse_present) {
1584         idx = 0;
1585         for (i = 0; i < pulse->num_pulse; i++) {
1586             float co = coef_base[ pulse->pos[i] ];
1587             while (offsets[idx + 1] <= pulse->pos[i])
1588                 idx++;
1589             if (band_type[idx] != NOISE_BT && sf[idx]) {
1590                 float ico = -pulse->amp[i];
1591                 if (co) {
1592                     co /= sf[idx];
1593                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1594                 }
1595                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1596             }
1597         }
1598     }
1599     return 0;
1600 }
1601
1602 static av_always_inline float flt16_round(float pf)
1603 {
1604     union av_intfloat32 tmp;
1605     tmp.f = pf;
1606     tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1607     return tmp.f;
1608 }
1609
1610 static av_always_inline float flt16_even(float pf)
1611 {
1612     union av_intfloat32 tmp;
1613     tmp.f = pf;
1614     tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1615     return tmp.f;
1616 }
1617
1618 static av_always_inline float flt16_trunc(float pf)
1619 {
1620     union av_intfloat32 pun;
1621     pun.f = pf;
1622     pun.i &= 0xFFFF0000U;
1623     return pun.f;
1624 }
1625
1626 static av_always_inline void predict(PredictorState *ps, float *coef,
1627                                      int output_enable)
1628 {
1629     const float a     = 0.953125; // 61.0 / 64
1630     const float alpha = 0.90625;  // 29.0 / 32
1631     float e0, e1;
1632     float pv;
1633     float k1, k2;
1634     float   r0 = ps->r0,     r1 = ps->r1;
1635     float cor0 = ps->cor0, cor1 = ps->cor1;
1636     float var0 = ps->var0, var1 = ps->var1;
1637
1638     k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1639     k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1640
1641     pv = flt16_round(k1 * r0 + k2 * r1);
1642     if (output_enable)
1643         *coef += pv;
1644
1645     e0 = *coef;
1646     e1 = e0 - k1 * r0;
1647
1648     ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1649     ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1650     ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1651     ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1652
1653     ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1654     ps->r0 = flt16_trunc(a * e0);
1655 }
1656
1657 /**
1658  * Apply AAC-Main style frequency domain prediction.
1659  */
1660 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1661 {
1662     int sfb, k;
1663
1664     if (!sce->ics.predictor_initialized) {
1665         reset_all_predictors(sce->predictor_state);
1666         sce->ics.predictor_initialized = 1;
1667     }
1668
1669     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1670         for (sfb = 0;
1671              sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1672              sfb++) {
1673             for (k = sce->ics.swb_offset[sfb];
1674                  k < sce->ics.swb_offset[sfb + 1];
1675                  k++) {
1676                 predict(&sce->predictor_state[k], &sce->coeffs[k],
1677                         sce->ics.predictor_present &&
1678                         sce->ics.prediction_used[sfb]);
1679             }
1680         }
1681         if (sce->ics.predictor_reset_group)
1682             reset_predictor_group(sce->predictor_state,
1683                                   sce->ics.predictor_reset_group);
1684     } else
1685         reset_all_predictors(sce->predictor_state);
1686 }
1687
1688 /**
1689  * Decode an individual_channel_stream payload; reference: table 4.44.
1690  *
1691  * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
1692  * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1693  *
1694  * @return  Returns error status. 0 - OK, !0 - error
1695  */
1696 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1697                       GetBitContext *gb, int common_window, int scale_flag)
1698 {
1699     Pulse pulse;
1700     TemporalNoiseShaping    *tns = &sce->tns;
1701     IndividualChannelStream *ics = &sce->ics;
1702     float *out = sce->coeffs;
1703     int global_gain, pulse_present = 0;
1704     int ret;
1705
1706     /* This assignment is to silence a GCC warning about the variable being used
1707      * uninitialized when in fact it always is.
1708      */
1709     pulse.num_pulse = 0;
1710
1711     global_gain = get_bits(gb, 8);
1712
1713     if (!common_window && !scale_flag) {
1714         if (decode_ics_info(ac, ics, gb) < 0)
1715             return AVERROR_INVALIDDATA;
1716     }
1717
1718     if ((ret = decode_band_types(ac, sce->band_type,
1719                                  sce->band_type_run_end, gb, ics)) < 0)
1720         return ret;
1721     if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1722                                   sce->band_type, sce->band_type_run_end)) < 0)
1723         return ret;
1724
1725     pulse_present = 0;
1726     if (!scale_flag) {
1727         if ((pulse_present = get_bits1(gb))) {
1728             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1729                 av_log(ac->avctx, AV_LOG_ERROR,
1730                        "Pulse tool not allowed in eight short sequence.\n");
1731                 return AVERROR_INVALIDDATA;
1732             }
1733             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1734                 av_log(ac->avctx, AV_LOG_ERROR,
1735                        "Pulse data corrupt or invalid.\n");
1736                 return AVERROR_INVALIDDATA;
1737             }
1738         }
1739         if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1740             return AVERROR_INVALIDDATA;
1741         if (get_bits1(gb)) {
1742             avpriv_request_sample(ac->avctx, "SSR");
1743             return AVERROR_PATCHWELCOME;
1744         }
1745     }
1746
1747     if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1748                                     &pulse, ics, sce->band_type) < 0)
1749         return AVERROR_INVALIDDATA;
1750
1751     if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1752         apply_prediction(ac, sce);
1753
1754     return 0;
1755 }
1756
1757 /**
1758  * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1759  */
1760 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1761 {
1762     const IndividualChannelStream *ics = &cpe->ch[0].ics;
1763     float *ch0 = cpe->ch[0].coeffs;
1764     float *ch1 = cpe->ch[1].coeffs;
1765     int g, i, group, idx = 0;
1766     const uint16_t *offsets = ics->swb_offset;
1767     for (g = 0; g < ics->num_window_groups; g++) {
1768         for (i = 0; i < ics->max_sfb; i++, idx++) {
1769             if (cpe->ms_mask[idx] &&
1770                 cpe->ch[0].band_type[idx] < NOISE_BT &&
1771                 cpe->ch[1].band_type[idx] < NOISE_BT) {
1772                 for (group = 0; group < ics->group_len[g]; group++) {
1773                     ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1774                                                ch1 + group * 128 + offsets[i],
1775                                                offsets[i+1] - offsets[i]);
1776                 }
1777             }
1778         }
1779         ch0 += ics->group_len[g] * 128;
1780         ch1 += ics->group_len[g] * 128;
1781     }
1782 }
1783
1784 /**
1785  * intensity stereo decoding; reference: 4.6.8.2.3
1786  *
1787  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1788  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1789  *                      [3] reserved for scalable AAC
1790  */
1791 static void apply_intensity_stereo(AACContext *ac,
1792                                    ChannelElement *cpe, int ms_present)
1793 {
1794     const IndividualChannelStream *ics = &cpe->ch[1].ics;
1795     SingleChannelElement         *sce1 = &cpe->ch[1];
1796     float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1797     const uint16_t *offsets = ics->swb_offset;
1798     int g, group, i, idx = 0;
1799     int c;
1800     float scale;
1801     for (g = 0; g < ics->num_window_groups; g++) {
1802         for (i = 0; i < ics->max_sfb;) {
1803             if (sce1->band_type[idx] == INTENSITY_BT ||
1804                 sce1->band_type[idx] == INTENSITY_BT2) {
1805                 const int bt_run_end = sce1->band_type_run_end[idx];
1806                 for (; i < bt_run_end; i++, idx++) {
1807                     c = -1 + 2 * (sce1->band_type[idx] - 14);
1808                     if (ms_present)
1809                         c *= 1 - 2 * cpe->ms_mask[idx];
1810                     scale = c * sce1->sf[idx];
1811                     for (group = 0; group < ics->group_len[g]; group++)
1812                         ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1813                                                     coef0 + group * 128 + offsets[i],
1814                                                     scale,
1815                                                     offsets[i + 1] - offsets[i]);
1816                 }
1817             } else {
1818                 int bt_run_end = sce1->band_type_run_end[idx];
1819                 idx += bt_run_end - i;
1820                 i    = bt_run_end;
1821             }
1822         }
1823         coef0 += ics->group_len[g] * 128;
1824         coef1 += ics->group_len[g] * 128;
1825     }
1826 }
1827
1828 /**
1829  * Decode a channel_pair_element; reference: table 4.4.
1830  *
1831  * @return  Returns error status. 0 - OK, !0 - error
1832  */
1833 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1834 {
1835     int i, ret, common_window, ms_present = 0;
1836
1837     common_window = get_bits1(gb);
1838     if (common_window) {
1839         if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1840             return AVERROR_INVALIDDATA;
1841         i = cpe->ch[1].ics.use_kb_window[0];
1842         cpe->ch[1].ics = cpe->ch[0].ics;
1843         cpe->ch[1].ics.use_kb_window[1] = i;
1844         if (cpe->ch[1].ics.predictor_present &&
1845             (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1846             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1847                 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1848         ms_present = get_bits(gb, 2);
1849         if (ms_present == 3) {
1850             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1851             return AVERROR_INVALIDDATA;
1852         } else if (ms_present)
1853             decode_mid_side_stereo(cpe, gb, ms_present);
1854     }
1855     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1856         return ret;
1857     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1858         return ret;
1859
1860     if (common_window) {
1861         if (ms_present)
1862             apply_mid_side_stereo(ac, cpe);
1863         if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1864             apply_prediction(ac, &cpe->ch[0]);
1865             apply_prediction(ac, &cpe->ch[1]);
1866         }
1867     }
1868
1869     apply_intensity_stereo(ac, cpe, ms_present);
1870     return 0;
1871 }
1872
1873 static const float cce_scale[] = {
1874     1.09050773266525765921, //2^(1/8)
1875     1.18920711500272106672, //2^(1/4)
1876     M_SQRT2,
1877     2,
1878 };
1879
1880 /**
1881  * Decode coupling_channel_element; reference: table 4.8.
1882  *
1883  * @return  Returns error status. 0 - OK, !0 - error
1884  */
1885 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1886 {
1887     int num_gain = 0;
1888     int c, g, sfb, ret;
1889     int sign;
1890     float scale;
1891     SingleChannelElement *sce = &che->ch[0];
1892     ChannelCoupling     *coup = &che->coup;
1893
1894     coup->coupling_point = 2 * get_bits1(gb);
1895     coup->num_coupled = get_bits(gb, 3);
1896     for (c = 0; c <= coup->num_coupled; c++) {
1897         num_gain++;
1898         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1899         coup->id_select[c] = get_bits(gb, 4);
1900         if (coup->type[c] == TYPE_CPE) {
1901             coup->ch_select[c] = get_bits(gb, 2);
1902             if (coup->ch_select[c] == 3)
1903                 num_gain++;
1904         } else
1905             coup->ch_select[c] = 2;
1906     }
1907     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1908
1909     sign  = get_bits(gb, 1);
1910     scale = cce_scale[get_bits(gb, 2)];
1911
1912     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1913         return ret;
1914
1915     for (c = 0; c < num_gain; c++) {
1916         int idx  = 0;
1917         int cge  = 1;
1918         int gain = 0;
1919         float gain_cache = 1.;
1920         if (c) {
1921             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1922             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1923             gain_cache = powf(scale, -gain);
1924         }
1925         if (coup->coupling_point == AFTER_IMDCT) {
1926             coup->gain[c][0] = gain_cache;
1927         } else {
1928             for (g = 0; g < sce->ics.num_window_groups; g++) {
1929                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1930                     if (sce->band_type[idx] != ZERO_BT) {
1931                         if (!cge) {
1932                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1933                             if (t) {
1934                                 int s = 1;
1935                                 t = gain += t;
1936                                 if (sign) {
1937                                     s  -= 2 * (t & 0x1);
1938                                     t >>= 1;
1939                                 }
1940                                 gain_cache = powf(scale, -t) * s;
1941                             }
1942                         }
1943                         coup->gain[c][idx] = gain_cache;
1944                     }
1945                 }
1946             }
1947         }
1948     }
1949     return 0;
1950 }
1951
1952 /**
1953  * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1954  *
1955  * @return  Returns number of bytes consumed.
1956  */
1957 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1958                                          GetBitContext *gb)
1959 {
1960     int i;
1961     int num_excl_chan = 0;
1962
1963     do {
1964         for (i = 0; i < 7; i++)
1965             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1966     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1967
1968     return num_excl_chan / 7;
1969 }
1970
1971 /**
1972  * Decode dynamic range information; reference: table 4.52.
1973  *
1974  * @return  Returns number of bytes consumed.
1975  */
1976 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1977                                 GetBitContext *gb)
1978 {
1979     int n             = 1;
1980     int drc_num_bands = 1;
1981     int i;
1982
1983     /* pce_tag_present? */
1984     if (get_bits1(gb)) {
1985         che_drc->pce_instance_tag  = get_bits(gb, 4);
1986         skip_bits(gb, 4); // tag_reserved_bits
1987         n++;
1988     }
1989
1990     /* excluded_chns_present? */
1991     if (get_bits1(gb)) {
1992         n += decode_drc_channel_exclusions(che_drc, gb);
1993     }
1994
1995     /* drc_bands_present? */
1996     if (get_bits1(gb)) {
1997         che_drc->band_incr            = get_bits(gb, 4);
1998         che_drc->interpolation_scheme = get_bits(gb, 4);
1999         n++;
2000         drc_num_bands += che_drc->band_incr;
2001         for (i = 0; i < drc_num_bands; i++) {
2002             che_drc->band_top[i] = get_bits(gb, 8);
2003             n++;
2004         }
2005     }
2006
2007     /* prog_ref_level_present? */
2008     if (get_bits1(gb)) {
2009         che_drc->prog_ref_level = get_bits(gb, 7);
2010         skip_bits1(gb); // prog_ref_level_reserved_bits
2011         n++;
2012     }
2013
2014     for (i = 0; i < drc_num_bands; i++) {
2015         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2016         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2017         n++;
2018     }
2019
2020     return n;
2021 }
2022
2023 /**
2024  * Decode extension data (incomplete); reference: table 4.51.
2025  *
2026  * @param   cnt length of TYPE_FIL syntactic element in bytes
2027  *
2028  * @return Returns number of bytes consumed
2029  */
2030 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2031                                     ChannelElement *che, enum RawDataBlockType elem_type)
2032 {
2033     int crc_flag = 0;
2034     int res = cnt;
2035     switch (get_bits(gb, 4)) { // extension type
2036     case EXT_SBR_DATA_CRC:
2037         crc_flag++;
2038     case EXT_SBR_DATA:
2039         if (!che) {
2040             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2041             return res;
2042         } else if (!ac->oc[1].m4ac.sbr) {
2043             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2044             skip_bits_long(gb, 8 * cnt - 4);
2045             return res;
2046         } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2047             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2048             skip_bits_long(gb, 8 * cnt - 4);
2049             return res;
2050         } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2051             ac->oc[1].m4ac.sbr = 1;
2052             ac->oc[1].m4ac.ps = 1;
2053             output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2054                              ac->oc[1].status, 1);
2055         } else {
2056             ac->oc[1].m4ac.sbr = 1;
2057         }
2058         res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2059         break;
2060     case EXT_DYNAMIC_RANGE:
2061         res = decode_dynamic_range(&ac->che_drc, gb);
2062         break;
2063     case EXT_FILL:
2064     case EXT_FILL_DATA:
2065     case EXT_DATA_ELEMENT:
2066     default:
2067         skip_bits_long(gb, 8 * cnt - 4);
2068         break;
2069     };
2070     return res;
2071 }
2072
2073 /**
2074  * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2075  *
2076  * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
2077  * @param   coef    spectral coefficients
2078  */
2079 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2080                       IndividualChannelStream *ics, int decode)
2081 {
2082     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2083     int w, filt, m, i;
2084     int bottom, top, order, start, end, size, inc;
2085     float lpc[TNS_MAX_ORDER];
2086     float tmp[TNS_MAX_ORDER + 1];
2087
2088     for (w = 0; w < ics->num_windows; w++) {
2089         bottom = ics->num_swb;
2090         for (filt = 0; filt < tns->n_filt[w]; filt++) {
2091             top    = bottom;
2092             bottom = FFMAX(0, top - tns->length[w][filt]);
2093             order  = tns->order[w][filt];
2094             if (order == 0)
2095                 continue;
2096
2097             // tns_decode_coef
2098             compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2099
2100             start = ics->swb_offset[FFMIN(bottom, mmm)];
2101             end   = ics->swb_offset[FFMIN(   top, mmm)];
2102             if ((size = end - start) <= 0)
2103                 continue;
2104             if (tns->direction[w][filt]) {
2105                 inc = -1;
2106                 start = end - 1;
2107             } else {
2108                 inc = 1;
2109             }
2110             start += w * 128;
2111
2112             if (decode) {
2113                 // ar filter
2114                 for (m = 0; m < size; m++, start += inc)
2115                     for (i = 1; i <= FFMIN(m, order); i++)
2116                         coef[start] -= coef[start - i * inc] * lpc[i - 1];
2117             } else {
2118                 // ma filter
2119                 for (m = 0; m < size; m++, start += inc) {
2120                     tmp[0] = coef[start];
2121                     for (i = 1; i <= FFMIN(m, order); i++)
2122                         coef[start] += tmp[i] * lpc[i - 1];
2123                     for (i = order; i > 0; i--)
2124                         tmp[i] = tmp[i - 1];
2125                 }
2126             }
2127         }
2128     }
2129 }
2130
2131 /**
2132  *  Apply windowing and MDCT to obtain the spectral
2133  *  coefficient from the predicted sample by LTP.
2134  */
2135 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2136                                    float *in, IndividualChannelStream *ics)
2137 {
2138     const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2139     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2140     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2141     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2142
2143     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2144         ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2145     } else {
2146         memset(in, 0, 448 * sizeof(float));
2147         ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2148     }
2149     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2150         ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2151     } else {
2152         ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2153         memset(in + 1024 + 576, 0, 448 * sizeof(float));
2154     }
2155     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2156 }
2157
2158 /**
2159  * Apply the long term prediction
2160  */
2161 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2162 {
2163     const LongTermPrediction *ltp = &sce->ics.ltp;
2164     const uint16_t *offsets = sce->ics.swb_offset;
2165     int i, sfb;
2166
2167     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2168         float *predTime = sce->ret;
2169         float *predFreq = ac->buf_mdct;
2170         int16_t num_samples = 2048;
2171
2172         if (ltp->lag < 1024)
2173             num_samples = ltp->lag + 1024;
2174         for (i = 0; i < num_samples; i++)
2175             predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2176         memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2177
2178         windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2179
2180         if (sce->tns.present)
2181             apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2182
2183         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2184             if (ltp->used[sfb])
2185                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2186                     sce->coeffs[i] += predFreq[i];
2187     }
2188 }
2189
2190 /**
2191  * Update the LTP buffer for next frame
2192  */
2193 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2194 {
2195     IndividualChannelStream *ics = &sce->ics;
2196     float *saved     = sce->saved;
2197     float *saved_ltp = sce->coeffs;
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     int i;
2201
2202     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2203         memcpy(saved_ltp,       saved, 512 * sizeof(float));
2204         memset(saved_ltp + 576, 0,     448 * sizeof(float));
2205         ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2206         for (i = 0; i < 64; i++)
2207             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2208     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2209         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(float));
2210         memset(saved_ltp + 576, 0,                  448 * sizeof(float));
2211         ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2212         for (i = 0; i < 64; i++)
2213             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2214     } else { // LONG_STOP or ONLY_LONG
2215         ac->fdsp.vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
2216         for (i = 0; i < 512; i++)
2217             saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2218     }
2219
2220     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2221     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
2222     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
2223 }
2224
2225 /**
2226  * Conduct IMDCT and windowing.
2227  */
2228 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2229 {
2230     IndividualChannelStream *ics = &sce->ics;
2231     float *in    = sce->coeffs;
2232     float *out   = sce->ret;
2233     float *saved = sce->saved;
2234     const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2235     const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2236     const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2237     float *buf  = ac->buf_mdct;
2238     float *temp = ac->temp;
2239     int i;
2240
2241     // imdct
2242     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2243         for (i = 0; i < 1024; i += 128)
2244             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2245     } else
2246         ac->mdct.imdct_half(&ac->mdct, buf, in);
2247
2248     /* window overlapping
2249      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2250      * and long to short transitions are considered to be short to short
2251      * transitions. This leaves just two cases (long to long and short to short)
2252      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2253      */
2254     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2255             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2256         ac->fdsp.vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
2257     } else {
2258         memcpy(                         out,               saved,            448 * sizeof(float));
2259
2260         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2261             ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
2262             ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
2263             ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
2264             ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
2265             ac->fdsp.vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
2266             memcpy(                     out + 448 + 4*128, temp, 64 * sizeof(float));
2267         } else {
2268             ac->fdsp.vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
2269             memcpy(                     out + 576,         buf + 64,         448 * sizeof(float));
2270         }
2271     }
2272
2273     // buffer update
2274     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2275         memcpy(                     saved,       temp + 64,         64 * sizeof(float));
2276         ac->fdsp.vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
2277         ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2278         ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2279         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2280     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2281         memcpy(                     saved,       buf + 512,        448 * sizeof(float));
2282         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(float));
2283     } else { // LONG_STOP or ONLY_LONG
2284         memcpy(                     saved,       buf + 512,        512 * sizeof(float));
2285     }
2286 }
2287
2288 /**
2289  * Apply dependent channel coupling (applied before IMDCT).
2290  *
2291  * @param   index   index into coupling gain array
2292  */
2293 static void apply_dependent_coupling(AACContext *ac,
2294                                      SingleChannelElement *target,
2295                                      ChannelElement *cce, int index)
2296 {
2297     IndividualChannelStream *ics = &cce->ch[0].ics;
2298     const uint16_t *offsets = ics->swb_offset;
2299     float *dest = target->coeffs;
2300     const float *src = cce->ch[0].coeffs;
2301     int g, i, group, k, idx = 0;
2302     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2303         av_log(ac->avctx, AV_LOG_ERROR,
2304                "Dependent coupling is not supported together with LTP\n");
2305         return;
2306     }
2307     for (g = 0; g < ics->num_window_groups; g++) {
2308         for (i = 0; i < ics->max_sfb; i++, idx++) {
2309             if (cce->ch[0].band_type[idx] != ZERO_BT) {
2310                 const float gain = cce->coup.gain[index][idx];
2311                 for (group = 0; group < ics->group_len[g]; group++) {
2312                     for (k = offsets[i]; k < offsets[i + 1]; k++) {
2313                         // XXX dsputil-ize
2314                         dest[group * 128 + k] += gain * src[group * 128 + k];
2315                     }
2316                 }
2317             }
2318         }
2319         dest += ics->group_len[g] * 128;
2320         src  += ics->group_len[g] * 128;
2321     }
2322 }
2323
2324 /**
2325  * Apply independent channel coupling (applied after IMDCT).
2326  *
2327  * @param   index   index into coupling gain array
2328  */
2329 static void apply_independent_coupling(AACContext *ac,
2330                                        SingleChannelElement *target,
2331                                        ChannelElement *cce, int index)
2332 {
2333     int i;
2334     const float gain = cce->coup.gain[index][0];
2335     const float *src = cce->ch[0].ret;
2336     float *dest = target->ret;
2337     const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2338
2339     for (i = 0; i < len; i++)
2340         dest[i] += gain * src[i];
2341 }
2342
2343 /**
2344  * channel coupling transformation interface
2345  *
2346  * @param   apply_coupling_method   pointer to (in)dependent coupling function
2347  */
2348 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2349                                    enum RawDataBlockType type, int elem_id,
2350                                    enum CouplingPoint coupling_point,
2351                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2352 {
2353     int i, c;
2354
2355     for (i = 0; i < MAX_ELEM_ID; i++) {
2356         ChannelElement *cce = ac->che[TYPE_CCE][i];
2357         int index = 0;
2358
2359         if (cce && cce->coup.coupling_point == coupling_point) {
2360             ChannelCoupling *coup = &cce->coup;
2361
2362             for (c = 0; c <= coup->num_coupled; c++) {
2363                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2364                     if (coup->ch_select[c] != 1) {
2365                         apply_coupling_method(ac, &cc->ch[0], cce, index);
2366                         if (coup->ch_select[c] != 0)
2367                             index++;
2368                     }
2369                     if (coup->ch_select[c] != 2)
2370                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
2371                 } else
2372                     index += 1 + (coup->ch_select[c] == 3);
2373             }
2374         }
2375     }
2376 }
2377
2378 /**
2379  * Convert spectral data to float samples, applying all supported tools as appropriate.
2380  */
2381 static void spectral_to_sample(AACContext *ac)
2382 {
2383     int i, type;
2384     for (type = 3; type >= 0; type--) {
2385         for (i = 0; i < MAX_ELEM_ID; i++) {
2386             ChannelElement *che = ac->che[type][i];
2387             if (che) {
2388                 if (type <= TYPE_CPE)
2389                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2390                 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2391                     if (che->ch[0].ics.predictor_present) {
2392                         if (che->ch[0].ics.ltp.present)
2393                             apply_ltp(ac, &che->ch[0]);
2394                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2395                             apply_ltp(ac, &che->ch[1]);
2396                     }
2397                 }
2398                 if (che->ch[0].tns.present)
2399                     apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2400                 if (che->ch[1].tns.present)
2401                     apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2402                 if (type <= TYPE_CPE)
2403                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2404                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2405                     imdct_and_windowing(ac, &che->ch[0]);
2406                     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2407                         update_ltp(ac, &che->ch[0]);
2408                     if (type == TYPE_CPE) {
2409                         imdct_and_windowing(ac, &che->ch[1]);
2410                         if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2411                             update_ltp(ac, &che->ch[1]);
2412                     }
2413                     if (ac->oc[1].m4ac.sbr > 0) {
2414                         ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2415                     }
2416                 }
2417                 if (type <= TYPE_CCE)
2418                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2419             }
2420         }
2421     }
2422 }
2423
2424 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2425 {
2426     int size;
2427     AACADTSHeaderInfo hdr_info;
2428     uint8_t layout_map[MAX_ELEM_ID*4][3];
2429     int layout_map_tags;
2430
2431     size = avpriv_aac_parse_header(gb, &hdr_info);
2432     if (size > 0) {
2433         if (hdr_info.num_aac_frames != 1) {
2434             avpriv_report_missing_feature(ac->avctx,
2435                                           "More than one AAC RDB per ADTS frame");
2436             return AVERROR_PATCHWELCOME;
2437         }
2438         push_output_configuration(ac);
2439         if (hdr_info.chan_config) {
2440             ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2441             if (set_default_channel_config(ac->avctx, layout_map,
2442                     &layout_map_tags, hdr_info.chan_config))
2443                 return -7;
2444             if (output_configure(ac, layout_map, layout_map_tags,
2445                                  FFMAX(ac->oc[1].status, OC_TRIAL_FRAME), 0))
2446                 return -7;
2447         } else {
2448             ac->oc[1].m4ac.chan_config = 0;
2449         }
2450         ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
2451         ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
2452         ac->oc[1].m4ac.object_type     = hdr_info.object_type;
2453         if (ac->oc[0].status != OC_LOCKED ||
2454             ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2455             ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2456             ac->oc[1].m4ac.sbr = -1;
2457             ac->oc[1].m4ac.ps  = -1;
2458         }
2459         if (!hdr_info.crc_absent)
2460             skip_bits(gb, 16);
2461     }
2462     return size;
2463 }
2464
2465 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2466                                 int *got_frame_ptr, GetBitContext *gb)
2467 {
2468     AACContext *ac = avctx->priv_data;
2469     ChannelElement *che = NULL, *che_prev = NULL;
2470     enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2471     int err, elem_id;
2472     int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2473
2474     ac->frame = data;
2475
2476     if (show_bits(gb, 12) == 0xfff) {
2477         if (parse_adts_frame_header(ac, gb) < 0) {
2478             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2479             err = -1;
2480             goto fail;
2481         }
2482         if (ac->oc[1].m4ac.sampling_index > 12) {
2483             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2484             err = -1;
2485             goto fail;
2486         }
2487     }
2488
2489     if (frame_configure_elements(avctx) < 0) {
2490         err = -1;
2491         goto fail;
2492     }
2493
2494     ac->tags_mapped = 0;
2495     // parse
2496     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2497         elem_id = get_bits(gb, 4);
2498
2499         if (elem_type < TYPE_DSE) {
2500             if (!(che=get_che(ac, elem_type, elem_id))) {
2501                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2502                        elem_type, elem_id);
2503                 err = -1;
2504                 goto fail;
2505             }
2506             samples = 1024;
2507         }
2508
2509         switch (elem_type) {
2510
2511         case TYPE_SCE:
2512             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2513             audio_found = 1;
2514             break;
2515
2516         case TYPE_CPE:
2517             err = decode_cpe(ac, gb, che);
2518             audio_found = 1;
2519             break;
2520
2521         case TYPE_CCE:
2522             err = decode_cce(ac, gb, che);
2523             break;
2524
2525         case TYPE_LFE:
2526             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2527             audio_found = 1;
2528             break;
2529
2530         case TYPE_DSE:
2531             err = skip_data_stream_element(ac, gb);
2532             break;
2533
2534         case TYPE_PCE: {
2535             uint8_t layout_map[MAX_ELEM_ID*4][3];
2536             int tags;
2537             push_output_configuration(ac);
2538             tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2539             if (tags < 0) {
2540                 err = tags;
2541                 break;
2542             }
2543             if (pce_found) {
2544                 av_log(avctx, AV_LOG_ERROR,
2545                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2546                 pop_output_configuration(ac);
2547             } else {
2548                 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2549                 pce_found = 1;
2550             }
2551             break;
2552         }
2553
2554         case TYPE_FIL:
2555             if (elem_id == 15)
2556                 elem_id += get_bits(gb, 8) - 1;
2557             if (get_bits_left(gb) < 8 * elem_id) {
2558                     av_log(avctx, AV_LOG_ERROR, overread_err);
2559                     err = -1;
2560                     goto fail;
2561             }
2562             while (elem_id > 0)
2563                 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2564             err = 0; /* FIXME */
2565             break;
2566
2567         default:
2568             err = -1; /* should not happen, but keeps compiler happy */
2569             break;
2570         }
2571
2572         che_prev       = che;
2573         elem_type_prev = elem_type;
2574
2575         if (err)
2576             goto fail;
2577
2578         if (get_bits_left(gb) < 3) {
2579             av_log(avctx, AV_LOG_ERROR, overread_err);
2580             err = -1;
2581             goto fail;
2582         }
2583     }
2584
2585     spectral_to_sample(ac);
2586
2587     multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2588     samples <<= multiplier;
2589
2590     if (samples)
2591         ac->frame->nb_samples = samples;
2592     *got_frame_ptr = !!samples;
2593
2594     if (ac->oc[1].status && audio_found) {
2595         avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2596         avctx->frame_size = samples;
2597         ac->oc[1].status = OC_LOCKED;
2598     }
2599
2600     return 0;
2601 fail:
2602     pop_output_configuration(ac);
2603     return err;
2604 }
2605
2606 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2607                             int *got_frame_ptr, AVPacket *avpkt)
2608 {
2609     AACContext *ac = avctx->priv_data;
2610     const uint8_t *buf = avpkt->data;
2611     int buf_size = avpkt->size;
2612     GetBitContext gb;
2613     int buf_consumed;
2614     int buf_offset;
2615     int err;
2616     int new_extradata_size;
2617     const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2618                                        AV_PKT_DATA_NEW_EXTRADATA,
2619                                        &new_extradata_size);
2620
2621     if (new_extradata) {
2622         av_free(avctx->extradata);
2623         avctx->extradata = av_mallocz(new_extradata_size +
2624                                       FF_INPUT_BUFFER_PADDING_SIZE);
2625         if (!avctx->extradata)
2626             return AVERROR(ENOMEM);
2627         avctx->extradata_size = new_extradata_size;
2628         memcpy(avctx->extradata, new_extradata, new_extradata_size);
2629         push_output_configuration(ac);
2630         if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2631                                          avctx->extradata,
2632                                          avctx->extradata_size*8, 1) < 0) {
2633             pop_output_configuration(ac);
2634             return AVERROR_INVALIDDATA;
2635         }
2636     }
2637
2638     init_get_bits(&gb, buf, buf_size * 8);
2639
2640     if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
2641         return err;
2642
2643     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2644     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2645         if (buf[buf_offset])
2646             break;
2647
2648     return buf_size > buf_offset ? buf_consumed : buf_size;
2649 }
2650
2651 static av_cold int aac_decode_close(AVCodecContext *avctx)
2652 {
2653     AACContext *ac = avctx->priv_data;
2654     int i, type;
2655
2656     for (i = 0; i < MAX_ELEM_ID; i++) {
2657         for (type = 0; type < 4; type++) {
2658             if (ac->che[type][i])
2659                 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2660             av_freep(&ac->che[type][i]);
2661         }
2662     }
2663
2664     ff_mdct_end(&ac->mdct);
2665     ff_mdct_end(&ac->mdct_small);
2666     ff_mdct_end(&ac->mdct_ltp);
2667     return 0;
2668 }
2669
2670
2671 #define LOAS_SYNC_WORD   0x2b7       ///< 11 bits LOAS sync word
2672
2673 struct LATMContext {
2674     AACContext aac_ctx;     ///< containing AACContext
2675     int initialized;        ///< initilized after a valid extradata was seen
2676
2677     // parser data
2678     int audio_mux_version_A; ///< LATM syntax version
2679     int frame_length_type;   ///< 0/1 variable/fixed frame length
2680     int frame_length;        ///< frame length for fixed frame length
2681 };
2682
2683 static inline uint32_t latm_get_value(GetBitContext *b)
2684 {
2685     int length = get_bits(b, 2);
2686
2687     return get_bits_long(b, (length+1)*8);
2688 }
2689
2690 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2691                                              GetBitContext *gb, int asclen)
2692 {
2693     AACContext *ac        = &latmctx->aac_ctx;
2694     AVCodecContext *avctx = ac->avctx;
2695     MPEG4AudioConfig m4ac = { 0 };
2696     int config_start_bit  = get_bits_count(gb);
2697     int sync_extension    = 0;
2698     int bits_consumed, esize;
2699
2700     if (asclen) {
2701         sync_extension = 1;
2702         asclen         = FFMIN(asclen, get_bits_left(gb));
2703     } else
2704         asclen         = get_bits_left(gb);
2705
2706     if (config_start_bit % 8) {
2707         avpriv_request_sample(latmctx->aac_ctx.avctx,
2708                               "Non-byte-aligned audio-specific config");
2709         return AVERROR_PATCHWELCOME;
2710     }
2711     if (asclen <= 0)
2712         return AVERROR_INVALIDDATA;
2713     bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2714                                          gb->buffer + (config_start_bit / 8),
2715                                          asclen, sync_extension);
2716
2717     if (bits_consumed < 0)
2718         return AVERROR_INVALIDDATA;
2719
2720     if (ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
2721         ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
2722
2723         av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2724         latmctx->initialized = 0;
2725
2726         esize = (bits_consumed+7) / 8;
2727
2728         if (avctx->extradata_size < esize) {
2729             av_free(avctx->extradata);
2730             avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2731             if (!avctx->extradata)
2732                 return AVERROR(ENOMEM);
2733         }
2734
2735         avctx->extradata_size = esize;
2736         memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2737         memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2738     }
2739     skip_bits_long(gb, bits_consumed);
2740
2741     return bits_consumed;
2742 }
2743
2744 static int read_stream_mux_config(struct LATMContext *latmctx,
2745                                   GetBitContext *gb)
2746 {
2747     int ret, audio_mux_version = get_bits(gb, 1);
2748
2749     latmctx->audio_mux_version_A = 0;
2750     if (audio_mux_version)
2751         latmctx->audio_mux_version_A = get_bits(gb, 1);
2752
2753     if (!latmctx->audio_mux_version_A) {
2754
2755         if (audio_mux_version)
2756             latm_get_value(gb);                 // taraFullness
2757
2758         skip_bits(gb, 1);                       // allStreamSameTimeFraming
2759         skip_bits(gb, 6);                       // numSubFrames
2760         // numPrograms
2761         if (get_bits(gb, 4)) {                  // numPrograms
2762             avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
2763             return AVERROR_PATCHWELCOME;
2764         }
2765
2766         // for each program (which there is only on in DVB)
2767
2768         // for each layer (which there is only on in DVB)
2769         if (get_bits(gb, 3)) {                   // numLayer
2770             avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
2771             return AVERROR_PATCHWELCOME;
2772         }
2773
2774         // for all but first stream: use_same_config = get_bits(gb, 1);
2775         if (!audio_mux_version) {
2776             if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2777                 return ret;
2778         } else {
2779             int ascLen = latm_get_value(gb);
2780             if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2781                 return ret;
2782             ascLen -= ret;
2783             skip_bits_long(gb, ascLen);
2784         }
2785
2786         latmctx->frame_length_type = get_bits(gb, 3);
2787         switch (latmctx->frame_length_type) {
2788         case 0:
2789             skip_bits(gb, 8);       // latmBufferFullness
2790             break;
2791         case 1:
2792             latmctx->frame_length = get_bits(gb, 9);
2793             break;
2794         case 3:
2795         case 4:
2796         case 5:
2797             skip_bits(gb, 6);       // CELP frame length table index
2798             break;
2799         case 6:
2800         case 7:
2801             skip_bits(gb, 1);       // HVXC frame length table index
2802             break;
2803         }
2804
2805         if (get_bits(gb, 1)) {                  // other data
2806             if (audio_mux_version) {
2807                 latm_get_value(gb);             // other_data_bits
2808             } else {
2809                 int esc;
2810                 do {
2811                     esc = get_bits(gb, 1);
2812                     skip_bits(gb, 8);
2813                 } while (esc);
2814             }
2815         }
2816
2817         if (get_bits(gb, 1))                     // crc present
2818             skip_bits(gb, 8);                    // config_crc
2819     }
2820
2821     return 0;
2822 }
2823
2824 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2825 {
2826     uint8_t tmp;
2827
2828     if (ctx->frame_length_type == 0) {
2829         int mux_slot_length = 0;
2830         do {
2831             tmp = get_bits(gb, 8);
2832             mux_slot_length += tmp;
2833         } while (tmp == 255);
2834         return mux_slot_length;
2835     } else if (ctx->frame_length_type == 1) {
2836         return ctx->frame_length;
2837     } else if (ctx->frame_length_type == 3 ||
2838                ctx->frame_length_type == 5 ||
2839                ctx->frame_length_type == 7) {
2840         skip_bits(gb, 2);          // mux_slot_length_coded
2841     }
2842     return 0;
2843 }
2844
2845 static int read_audio_mux_element(struct LATMContext *latmctx,
2846                                   GetBitContext *gb)
2847 {
2848     int err;
2849     uint8_t use_same_mux = get_bits(gb, 1);
2850     if (!use_same_mux) {
2851         if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2852             return err;
2853     } else if (!latmctx->aac_ctx.avctx->extradata) {
2854         av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2855                "no decoder config found\n");
2856         return AVERROR(EAGAIN);
2857     }
2858     if (latmctx->audio_mux_version_A == 0) {
2859         int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2860         if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2861             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2862             return AVERROR_INVALIDDATA;
2863         } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2864             av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2865                    "frame length mismatch %d << %d\n",
2866                    mux_slot_length_bytes * 8, get_bits_left(gb));
2867             return AVERROR_INVALIDDATA;
2868         }
2869     }
2870     return 0;
2871 }
2872
2873
2874 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2875                              int *got_frame_ptr, AVPacket *avpkt)
2876 {
2877     struct LATMContext *latmctx = avctx->priv_data;
2878     int                 muxlength, err;
2879     GetBitContext       gb;
2880
2881     init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2882
2883     // check for LOAS sync word
2884     if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2885         return AVERROR_INVALIDDATA;
2886
2887     muxlength = get_bits(&gb, 13) + 3;
2888     // not enough data, the parser should have sorted this
2889     if (muxlength > avpkt->size)
2890         return AVERROR_INVALIDDATA;
2891
2892     if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2893         return err;
2894
2895     if (!latmctx->initialized) {
2896         if (!avctx->extradata) {
2897             *got_frame_ptr = 0;
2898             return avpkt->size;
2899         } else {
2900             push_output_configuration(&latmctx->aac_ctx);
2901             if ((err = decode_audio_specific_config(
2902                     &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
2903                     avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
2904                 pop_output_configuration(&latmctx->aac_ctx);
2905                 return err;
2906             }
2907             latmctx->initialized = 1;
2908         }
2909     }
2910
2911     if (show_bits(&gb, 12) == 0xfff) {
2912         av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2913                "ADTS header detected, probably as result of configuration "
2914                "misparsing\n");
2915         return AVERROR_INVALIDDATA;
2916     }
2917
2918     if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2919         return err;
2920
2921     return muxlength;
2922 }
2923
2924 static av_cold int latm_decode_init(AVCodecContext *avctx)
2925 {
2926     struct LATMContext *latmctx = avctx->priv_data;
2927     int ret = aac_decode_init(avctx);
2928
2929     if (avctx->extradata_size > 0)
2930         latmctx->initialized = !ret;
2931
2932     return ret;
2933 }
2934
2935
2936 AVCodec ff_aac_decoder = {
2937     .name            = "aac",
2938     .type            = AVMEDIA_TYPE_AUDIO,
2939     .id              = AV_CODEC_ID_AAC,
2940     .priv_data_size  = sizeof(AACContext),
2941     .init            = aac_decode_init,
2942     .close           = aac_decode_close,
2943     .decode          = aac_decode_frame,
2944     .long_name       = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
2945     .sample_fmts     = (const enum AVSampleFormat[]) {
2946         AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
2947     },
2948     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2949     .channel_layouts = aac_channel_layout,
2950 };
2951
2952 /*
2953     Note: This decoder filter is intended to decode LATM streams transferred
2954     in MPEG transport streams which only contain one program.
2955     To do a more complex LATM demuxing a separate LATM demuxer should be used.
2956 */
2957 AVCodec ff_aac_latm_decoder = {
2958     .name            = "aac_latm",
2959     .type            = AVMEDIA_TYPE_AUDIO,
2960     .id              = AV_CODEC_ID_AAC_LATM,
2961     .priv_data_size  = sizeof(struct LATMContext),
2962     .init            = latm_decode_init,
2963     .close           = aac_decode_close,
2964     .decode          = latm_decode_frame,
2965     .long_name       = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
2966     .sample_fmts     = (const enum AVSampleFormat[]) {
2967         AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
2968     },
2969     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2970     .channel_layouts = aac_channel_layout,
2971 };