]> git.sesse.net Git - ffmpeg/blob - libavcodec/aacdec_template.c
avcodec/aacdec_template: Avoid code duplication when initializing VLCs
[ffmpeg] / libavcodec / aacdec_template.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  * Copyright (c) 2008-2013 Alex Converse <alex.converse@gmail.com>
6  *
7  * AAC LATM decoder
8  * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
9  * Copyright (c) 2010      Janne Grunau <janne-libav@jannau.net>
10  *
11  * AAC decoder fixed-point implementation
12  * Copyright (c) 2013
13  *      MIPS Technologies, Inc., California.
14  *
15  * This file is part of FFmpeg.
16  *
17  * FFmpeg is free software; you can redistribute it and/or
18  * modify it under the terms of the GNU Lesser General Public
19  * License as published by the Free Software Foundation; either
20  * version 2.1 of the License, or (at your option) any later version.
21  *
22  * FFmpeg is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25  * Lesser General Public License for more details.
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with FFmpeg; if not, write to the Free Software
29  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30  */
31
32 /**
33  * @file
34  * AAC decoder
35  * @author Oded Shimon  ( ods15 ods15 dyndns org )
36  * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
37  *
38  * AAC decoder fixed-point implementation
39  * @author Stanislav Ocovaj ( stanislav.ocovaj imgtec com )
40  * @author Nedeljko Babic ( nedeljko.babic imgtec com )
41  */
42
43 /*
44  * supported tools
45  *
46  * Support?                     Name
47  * N (code in SoC repo)         gain control
48  * Y                            block switching
49  * Y                            window shapes - standard
50  * N                            window shapes - Low Delay
51  * Y                            filterbank - standard
52  * N (code in SoC repo)         filterbank - Scalable Sample Rate
53  * Y                            Temporal Noise Shaping
54  * Y                            Long Term Prediction
55  * Y                            intensity stereo
56  * Y                            channel coupling
57  * Y                            frequency domain prediction
58  * Y                            Perceptual Noise Substitution
59  * Y                            Mid/Side stereo
60  * N                            Scalable Inverse AAC Quantization
61  * N                            Frequency Selective Switch
62  * N                            upsampling filter
63  * Y                            quantization & coding - AAC
64  * N                            quantization & coding - TwinVQ
65  * N                            quantization & coding - BSAC
66  * N                            AAC Error Resilience tools
67  * N                            Error Resilience payload syntax
68  * N                            Error Protection tool
69  * N                            CELP
70  * N                            Silence Compression
71  * N                            HVXC
72  * N                            HVXC 4kbits/s VR
73  * N                            Structured Audio tools
74  * N                            Structured Audio Sample Bank Format
75  * N                            MIDI
76  * N                            Harmonic and Individual Lines plus Noise
77  * N                            Text-To-Speech Interface
78  * Y                            Spectral Band Replication
79  * Y (not in this code)         Layer-1
80  * Y (not in this code)         Layer-2
81  * Y (not in this code)         Layer-3
82  * N                            SinuSoidal Coding (Transient, Sinusoid, Noise)
83  * Y                            Parametric Stereo
84  * N                            Direct Stream Transfer
85  * Y  (not in fixed point code) Enhanced AAC Low Delay (ER AAC ELD)
86  *
87  * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
88  *       - HE AAC v2 comprises LC AAC with Spectral Band Replication and
89            Parametric Stereo.
90  */
91
92 #include "libavutil/thread.h"
93
94 static VLC vlc_scalefactors;
95 static VLC vlc_spectral[11];
96
97 static int output_configure(AACContext *ac,
98                             uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
99                             enum OCStatus oc_type, int get_new_frame);
100
101 #define overread_err "Input buffer exhausted before END element found\n"
102
103 static int count_channels(uint8_t (*layout)[3], int tags)
104 {
105     int i, sum = 0;
106     for (i = 0; i < tags; i++) {
107         int syn_ele = layout[i][0];
108         int pos     = layout[i][2];
109         sum += (1 + (syn_ele == TYPE_CPE)) *
110                (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
111     }
112     return sum;
113 }
114
115 /**
116  * Check for the channel element in the current channel position configuration.
117  * If it exists, make sure the appropriate element is allocated and map the
118  * channel order to match the internal FFmpeg channel layout.
119  *
120  * @param   che_pos current channel position configuration
121  * @param   type channel element type
122  * @param   id channel element id
123  * @param   channels count of the number of channels in the configuration
124  *
125  * @return  Returns error status. 0 - OK, !0 - error
126  */
127 static av_cold int che_configure(AACContext *ac,
128                                  enum ChannelPosition che_pos,
129                                  int type, int id, int *channels)
130 {
131     if (*channels >= MAX_CHANNELS)
132         return AVERROR_INVALIDDATA;
133     if (che_pos) {
134         if (!ac->che[type][id]) {
135             if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
136                 return AVERROR(ENOMEM);
137             AAC_RENAME(ff_aac_sbr_ctx_init)(ac, &ac->che[type][id]->sbr, type);
138         }
139         if (type != TYPE_CCE) {
140             if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
141                 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
142                 return AVERROR_INVALIDDATA;
143             }
144             ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
145             if (type == TYPE_CPE ||
146                 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
147                 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
148             }
149         }
150     } else {
151         if (ac->che[type][id])
152             AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][id]->sbr);
153         av_freep(&ac->che[type][id]);
154     }
155     return 0;
156 }
157
158 static int frame_configure_elements(AVCodecContext *avctx)
159 {
160     AACContext *ac = avctx->priv_data;
161     int type, id, ch, ret;
162
163     /* set channel pointers to internal buffers by default */
164     for (type = 0; type < 4; type++) {
165         for (id = 0; id < MAX_ELEM_ID; id++) {
166             ChannelElement *che = ac->che[type][id];
167             if (che) {
168                 che->ch[0].ret = che->ch[0].ret_buf;
169                 che->ch[1].ret = che->ch[1].ret_buf;
170             }
171         }
172     }
173
174     /* get output buffer */
175     av_frame_unref(ac->frame);
176     if (!avctx->channels)
177         return 1;
178
179     ac->frame->nb_samples = 2048;
180     if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
181         return ret;
182
183     /* map output channel pointers to AVFrame data */
184     for (ch = 0; ch < avctx->channels; ch++) {
185         if (ac->output_element[ch])
186             ac->output_element[ch]->ret = (INTFLOAT *)ac->frame->extended_data[ch];
187     }
188
189     return 0;
190 }
191
192 struct elem_to_channel {
193     uint64_t av_position;
194     uint8_t syn_ele;
195     uint8_t elem_id;
196     uint8_t aac_position;
197 };
198
199 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
200                        uint8_t (*layout_map)[3], int offset, uint64_t left,
201                        uint64_t right, int pos, uint64_t *layout)
202 {
203     if (layout_map[offset][0] == TYPE_CPE) {
204         e2c_vec[offset] = (struct elem_to_channel) {
205             .av_position  = left | right,
206             .syn_ele      = TYPE_CPE,
207             .elem_id      = layout_map[offset][1],
208             .aac_position = pos
209         };
210         if (e2c_vec[offset].av_position != UINT64_MAX)
211             *layout |= e2c_vec[offset].av_position;
212
213         return 1;
214     } else {
215         e2c_vec[offset] = (struct elem_to_channel) {
216             .av_position  = left,
217             .syn_ele      = TYPE_SCE,
218             .elem_id      = layout_map[offset][1],
219             .aac_position = pos
220         };
221         e2c_vec[offset + 1] = (struct elem_to_channel) {
222             .av_position  = right,
223             .syn_ele      = TYPE_SCE,
224             .elem_id      = layout_map[offset + 1][1],
225             .aac_position = pos
226         };
227         if (left != UINT64_MAX)
228             *layout |= left;
229
230         if (right != UINT64_MAX)
231             *layout |= right;
232
233         return 2;
234     }
235 }
236
237 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
238                                  int *current)
239 {
240     int num_pos_channels = 0;
241     int first_cpe        = 0;
242     int sce_parity       = 0;
243     int i;
244     for (i = *current; i < tags; i++) {
245         if (layout_map[i][2] != pos)
246             break;
247         if (layout_map[i][0] == TYPE_CPE) {
248             if (sce_parity) {
249                 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
250                     sce_parity = 0;
251                 } else {
252                     return -1;
253                 }
254             }
255             num_pos_channels += 2;
256             first_cpe         = 1;
257         } else {
258             num_pos_channels++;
259             sce_parity ^= 1;
260         }
261     }
262     if (sce_parity &&
263         ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
264         return -1;
265     *current = i;
266     return num_pos_channels;
267 }
268
269 #define PREFIX_FOR_22POINT2 (AV_CH_LAYOUT_7POINT1_WIDE_BACK|AV_CH_BACK_CENTER|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT|AV_CH_LOW_FREQUENCY_2)
270 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
271 {
272     int i, n, total_non_cc_elements;
273     struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
274     int num_front_channels, num_side_channels, num_back_channels;
275     uint64_t layout = 0;
276
277     if (FF_ARRAY_ELEMS(e2c_vec) < tags)
278         return 0;
279
280     i = 0;
281     num_front_channels =
282         count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
283     if (num_front_channels < 0)
284         return 0;
285     num_side_channels =
286         count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
287     if (num_side_channels < 0)
288         return 0;
289     num_back_channels =
290         count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
291     if (num_back_channels < 0)
292         return 0;
293
294     if (num_side_channels == 0 && num_back_channels >= 4) {
295         num_side_channels = 2;
296         num_back_channels -= 2;
297     }
298
299     i = 0;
300     if (num_front_channels & 1) {
301         e2c_vec[i] = (struct elem_to_channel) {
302             .av_position  = AV_CH_FRONT_CENTER,
303             .syn_ele      = TYPE_SCE,
304             .elem_id      = layout_map[i][1],
305             .aac_position = AAC_CHANNEL_FRONT
306         };
307         layout |= e2c_vec[i].av_position;
308         i++;
309         num_front_channels--;
310     }
311     if (num_front_channels >= 4) {
312         i += assign_pair(e2c_vec, layout_map, i,
313                          AV_CH_FRONT_LEFT_OF_CENTER,
314                          AV_CH_FRONT_RIGHT_OF_CENTER,
315                          AAC_CHANNEL_FRONT, &layout);
316         num_front_channels -= 2;
317     }
318     if (num_front_channels >= 2) {
319         i += assign_pair(e2c_vec, layout_map, i,
320                          AV_CH_FRONT_LEFT,
321                          AV_CH_FRONT_RIGHT,
322                          AAC_CHANNEL_FRONT, &layout);
323         num_front_channels -= 2;
324     }
325     while (num_front_channels >= 2) {
326         i += assign_pair(e2c_vec, layout_map, i,
327                          UINT64_MAX,
328                          UINT64_MAX,
329                          AAC_CHANNEL_FRONT, &layout);
330         num_front_channels -= 2;
331     }
332
333     if (num_side_channels >= 2) {
334         i += assign_pair(e2c_vec, layout_map, i,
335                          AV_CH_SIDE_LEFT,
336                          AV_CH_SIDE_RIGHT,
337                          AAC_CHANNEL_FRONT, &layout);
338         num_side_channels -= 2;
339     }
340     while (num_side_channels >= 2) {
341         i += assign_pair(e2c_vec, layout_map, i,
342                          UINT64_MAX,
343                          UINT64_MAX,
344                          AAC_CHANNEL_SIDE, &layout);
345         num_side_channels -= 2;
346     }
347
348     while (num_back_channels >= 4) {
349         i += assign_pair(e2c_vec, layout_map, i,
350                          UINT64_MAX,
351                          UINT64_MAX,
352                          AAC_CHANNEL_BACK, &layout);
353         num_back_channels -= 2;
354     }
355     if (num_back_channels >= 2) {
356         i += assign_pair(e2c_vec, layout_map, i,
357                          AV_CH_BACK_LEFT,
358                          AV_CH_BACK_RIGHT,
359                          AAC_CHANNEL_BACK, &layout);
360         num_back_channels -= 2;
361     }
362     if (num_back_channels) {
363         e2c_vec[i] = (struct elem_to_channel) {
364             .av_position  = AV_CH_BACK_CENTER,
365             .syn_ele      = TYPE_SCE,
366             .elem_id      = layout_map[i][1],
367             .aac_position = AAC_CHANNEL_BACK
368         };
369         layout |= e2c_vec[i].av_position;
370         i++;
371         num_back_channels--;
372     }
373
374     if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
375         e2c_vec[i] = (struct elem_to_channel) {
376             .av_position  = AV_CH_LOW_FREQUENCY,
377             .syn_ele      = TYPE_LFE,
378             .elem_id      = layout_map[i][1],
379             .aac_position = AAC_CHANNEL_LFE
380         };
381         layout |= e2c_vec[i].av_position;
382         i++;
383     }
384     if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
385         e2c_vec[i] = (struct elem_to_channel) {
386             .av_position  = AV_CH_LOW_FREQUENCY_2,
387             .syn_ele      = TYPE_LFE,
388             .elem_id      = layout_map[i][1],
389             .aac_position = AAC_CHANNEL_LFE
390         };
391         layout |= e2c_vec[i].av_position;
392         i++;
393     }
394     while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
395         e2c_vec[i] = (struct elem_to_channel) {
396             .av_position  = UINT64_MAX,
397             .syn_ele      = TYPE_LFE,
398             .elem_id      = layout_map[i][1],
399             .aac_position = AAC_CHANNEL_LFE
400         };
401         i++;
402     }
403
404     // The previous checks would end up at 8 at this point for 22.2
405     if (layout == PREFIX_FOR_22POINT2 && tags == 16 && i == 8) {
406         const uint8_t (*reference_layout_map)[3] = aac_channel_layout_map[12];
407         for (int j = 0; j < tags; j++) {
408             if (layout_map[j][0] != reference_layout_map[j][0] ||
409                 layout_map[j][2] != reference_layout_map[j][2])
410                 goto end_of_layout_definition;
411         }
412
413         e2c_vec[i] = (struct elem_to_channel) {
414             .av_position  = AV_CH_TOP_FRONT_CENTER,
415             .syn_ele      = layout_map[i][0],
416             .elem_id      = layout_map[i][1],
417             .aac_position = layout_map[i][2]
418         }; layout |= e2c_vec[i].av_position; i++;
419         i += assign_pair(e2c_vec, layout_map, i,
420                          AV_CH_TOP_FRONT_LEFT,
421                          AV_CH_TOP_FRONT_RIGHT,
422                          AAC_CHANNEL_FRONT,
423                          &layout);
424         i += assign_pair(e2c_vec, layout_map, i,
425                          AV_CH_TOP_SIDE_LEFT,
426                          AV_CH_TOP_SIDE_RIGHT,
427                          AAC_CHANNEL_SIDE,
428                          &layout);
429         e2c_vec[i] = (struct elem_to_channel) {
430             .av_position  = AV_CH_TOP_CENTER,
431             .syn_ele      = layout_map[i][0],
432             .elem_id      = layout_map[i][1],
433             .aac_position = layout_map[i][2]
434         }; layout |= e2c_vec[i].av_position; i++;
435         i += assign_pair(e2c_vec, layout_map, i,
436                          AV_CH_TOP_BACK_LEFT,
437                          AV_CH_TOP_BACK_RIGHT,
438                          AAC_CHANNEL_BACK,
439                          &layout);
440         e2c_vec[i] = (struct elem_to_channel) {
441             .av_position  = AV_CH_TOP_BACK_CENTER,
442             .syn_ele      = layout_map[i][0],
443             .elem_id      = layout_map[i][1],
444             .aac_position = layout_map[i][2]
445         }; layout |= e2c_vec[i].av_position; i++;
446         e2c_vec[i] = (struct elem_to_channel) {
447             .av_position  = AV_CH_BOTTOM_FRONT_CENTER,
448             .syn_ele      = layout_map[i][0],
449             .elem_id      = layout_map[i][1],
450             .aac_position = layout_map[i][2]
451         }; layout |= e2c_vec[i].av_position; i++;
452         i += assign_pair(e2c_vec, layout_map, i,
453                          AV_CH_BOTTOM_FRONT_LEFT,
454                          AV_CH_BOTTOM_FRONT_RIGHT,
455                          AAC_CHANNEL_FRONT,
456                          &layout);
457     }
458
459 end_of_layout_definition:
460
461     total_non_cc_elements = n = i;
462
463     if (layout == AV_CH_LAYOUT_22POINT2) {
464         // For 22.2 reorder the result as needed
465         FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[0]);   // FL & FR first (final), FC third
466         FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[1]);   // FC second (final), FLc & FRc third
467         FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[2]);   // LFE1 third (final), FLc & FRc seventh
468         FFSWAP(struct elem_to_channel, e2c_vec[4], e2c_vec[3]);   // BL & BR fourth (final), SiL & SiR fifth
469         FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[4]);   // FLc & FRc fifth (final), SiL & SiR seventh
470         FFSWAP(struct elem_to_channel, e2c_vec[7], e2c_vec[6]);   // LFE2 seventh (final), SiL & SiR eight (final)
471         FFSWAP(struct elem_to_channel, e2c_vec[9], e2c_vec[8]);   // TpFL & TpFR ninth (final), TFC tenth (final)
472         FFSWAP(struct elem_to_channel, e2c_vec[11], e2c_vec[10]); // TC eleventh (final), TpSiL & TpSiR twelth
473         FFSWAP(struct elem_to_channel, e2c_vec[12], e2c_vec[11]); // TpBL & TpBR twelth (final), TpSiL & TpSiR thirteenth (final)
474     } else {
475         // For everything else, utilize the AV channel position define as a
476         // stable sort.
477         do {
478             int next_n = 0;
479             for (i = 1; i < n; i++)
480                 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
481                     FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
482                     next_n = i;
483                 }
484             n = next_n;
485         } while (n > 0);
486
487     }
488
489     for (i = 0; i < total_non_cc_elements; i++) {
490         layout_map[i][0] = e2c_vec[i].syn_ele;
491         layout_map[i][1] = e2c_vec[i].elem_id;
492         layout_map[i][2] = e2c_vec[i].aac_position;
493     }
494
495     return layout;
496 }
497
498 /**
499  * Save current output configuration if and only if it has been locked.
500  */
501 static int push_output_configuration(AACContext *ac) {
502     int pushed = 0;
503
504     if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
505         ac->oc[0] = ac->oc[1];
506         pushed = 1;
507     }
508     ac->oc[1].status = OC_NONE;
509     return pushed;
510 }
511
512 /**
513  * Restore the previous output configuration if and only if the current
514  * configuration is unlocked.
515  */
516 static void pop_output_configuration(AACContext *ac) {
517     if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
518         ac->oc[1] = ac->oc[0];
519         ac->avctx->channels = ac->oc[1].channels;
520         ac->avctx->channel_layout = ac->oc[1].channel_layout;
521         output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
522                          ac->oc[1].status, 0);
523     }
524 }
525
526 /**
527  * Configure output channel order based on the current program
528  * configuration element.
529  *
530  * @return  Returns error status. 0 - OK, !0 - error
531  */
532 static int output_configure(AACContext *ac,
533                             uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
534                             enum OCStatus oc_type, int get_new_frame)
535 {
536     AVCodecContext *avctx = ac->avctx;
537     int i, channels = 0, ret;
538     uint64_t layout = 0;
539     uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
540     uint8_t type_counts[TYPE_END] = { 0 };
541
542     if (ac->oc[1].layout_map != layout_map) {
543         memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
544         ac->oc[1].layout_map_tags = tags;
545     }
546     for (i = 0; i < tags; i++) {
547         int type =         layout_map[i][0];
548         int id =           layout_map[i][1];
549         id_map[type][id] = type_counts[type]++;
550         if (id_map[type][id] >= MAX_ELEM_ID) {
551             avpriv_request_sample(ac->avctx, "Too large remapped id");
552             return AVERROR_PATCHWELCOME;
553         }
554     }
555     // Try to sniff a reasonable channel order, otherwise output the
556     // channels in the order the PCE declared them.
557     if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
558         layout = sniff_channel_order(layout_map, tags);
559     for (i = 0; i < tags; i++) {
560         int type =     layout_map[i][0];
561         int id =       layout_map[i][1];
562         int iid =      id_map[type][id];
563         int position = layout_map[i][2];
564         // Allocate or free elements depending on if they are in the
565         // current program configuration.
566         ret = che_configure(ac, position, type, iid, &channels);
567         if (ret < 0)
568             return ret;
569         ac->tag_che_map[type][id] = ac->che[type][iid];
570     }
571     if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
572         if (layout == AV_CH_FRONT_CENTER) {
573             layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
574         } else {
575             layout = 0;
576         }
577     }
578
579     if (layout) avctx->channel_layout = layout;
580                             ac->oc[1].channel_layout = layout;
581     avctx->channels       = ac->oc[1].channels       = channels;
582     ac->oc[1].status = oc_type;
583
584     if (get_new_frame) {
585         if ((ret = frame_configure_elements(ac->avctx)) < 0)
586             return ret;
587     }
588
589     return 0;
590 }
591
592 static void flush(AVCodecContext *avctx)
593 {
594     AACContext *ac= avctx->priv_data;
595     int type, i, j;
596
597     for (type = 3; type >= 0; type--) {
598         for (i = 0; i < MAX_ELEM_ID; i++) {
599             ChannelElement *che = ac->che[type][i];
600             if (che) {
601                 for (j = 0; j <= 1; j++) {
602                     memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
603                 }
604             }
605         }
606     }
607 }
608
609 /**
610  * Set up channel positions based on a default channel configuration
611  * as specified in table 1.17.
612  *
613  * @return  Returns error status. 0 - OK, !0 - error
614  */
615 static int set_default_channel_config(AACContext *ac, AVCodecContext *avctx,
616                                       uint8_t (*layout_map)[3],
617                                       int *tags,
618                                       int channel_config)
619 {
620     if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
621         channel_config > 13) {
622         av_log(avctx, AV_LOG_ERROR,
623                "invalid default channel configuration (%d)\n",
624                channel_config);
625         return AVERROR_INVALIDDATA;
626     }
627     *tags = tags_per_config[channel_config];
628     memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
629            *tags * sizeof(*layout_map));
630
631     /*
632      * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
633      * However, at least Nero AAC encoder encodes 7.1 streams using the default
634      * channel config 7, mapping the side channels of the original audio stream
635      * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
636      * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
637      * the incorrect streams as if they were correct (and as the encoder intended).
638      *
639      * As actual intended 7.1(wide) streams are very rare, default to assuming a
640      * 7.1 layout was intended.
641      */
642     if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT && (!ac || !ac->warned_71_wide++)) {
643         av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
644                " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
645                " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
646         layout_map[2][2] = AAC_CHANNEL_SIDE;
647     }
648
649     return 0;
650 }
651
652 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
653 {
654     /* For PCE based channel configurations map the channels solely based
655      * on tags. */
656     if (!ac->oc[1].m4ac.chan_config) {
657         return ac->tag_che_map[type][elem_id];
658     }
659     // Allow single CPE stereo files to be signalled with mono configuration.
660     if (!ac->tags_mapped && type == TYPE_CPE &&
661         ac->oc[1].m4ac.chan_config == 1) {
662         uint8_t layout_map[MAX_ELEM_ID*4][3];
663         int layout_map_tags;
664         push_output_configuration(ac);
665
666         av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
667
668         if (set_default_channel_config(ac, ac->avctx, layout_map,
669                                        &layout_map_tags, 2) < 0)
670             return NULL;
671         if (output_configure(ac, layout_map, layout_map_tags,
672                              OC_TRIAL_FRAME, 1) < 0)
673             return NULL;
674
675         ac->oc[1].m4ac.chan_config = 2;
676         ac->oc[1].m4ac.ps = 0;
677     }
678     // And vice-versa
679     if (!ac->tags_mapped && type == TYPE_SCE &&
680         ac->oc[1].m4ac.chan_config == 2) {
681         uint8_t layout_map[MAX_ELEM_ID * 4][3];
682         int layout_map_tags;
683         push_output_configuration(ac);
684
685         av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
686
687         if (set_default_channel_config(ac, ac->avctx, layout_map,
688                                        &layout_map_tags, 1) < 0)
689             return NULL;
690         if (output_configure(ac, layout_map, layout_map_tags,
691                              OC_TRIAL_FRAME, 1) < 0)
692             return NULL;
693
694         ac->oc[1].m4ac.chan_config = 1;
695         if (ac->oc[1].m4ac.sbr)
696             ac->oc[1].m4ac.ps = -1;
697     }
698     /* For indexed channel configurations map the channels solely based
699      * on position. */
700     switch (ac->oc[1].m4ac.chan_config) {
701     case 13:
702         if (ac->tags_mapped > 3 && ((type == TYPE_CPE && elem_id < 8) ||
703                                     (type == TYPE_SCE && elem_id < 6) ||
704                                     (type == TYPE_LFE && elem_id < 2))) {
705             ac->tags_mapped++;
706             return ac->tag_che_map[type][elem_id] = ac->che[type][elem_id];
707         }
708     case 12:
709     case 7:
710         if (ac->tags_mapped == 3 && type == TYPE_CPE) {
711             ac->tags_mapped++;
712             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
713         }
714     case 11:
715         if (ac->tags_mapped == 2 &&
716             ac->oc[1].m4ac.chan_config == 11 &&
717             type == TYPE_SCE) {
718             ac->tags_mapped++;
719             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
720         }
721     case 6:
722         /* Some streams incorrectly code 5.1 audio as
723          * SCE[0] CPE[0] CPE[1] SCE[1]
724          * instead of
725          * SCE[0] CPE[0] CPE[1] LFE[0].
726          * If we seem to have encountered such a stream, transfer
727          * the LFE[0] element to the SCE[1]'s mapping */
728         if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
729             if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
730                 av_log(ac->avctx, AV_LOG_WARNING,
731                    "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
732                    type == TYPE_SCE ? "SCE" : "LFE", elem_id);
733                 ac->warned_remapping_once++;
734             }
735             ac->tags_mapped++;
736             return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
737         }
738     case 5:
739         if (ac->tags_mapped == 2 && type == TYPE_CPE) {
740             ac->tags_mapped++;
741             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
742         }
743     case 4:
744         /* Some streams incorrectly code 4.0 audio as
745          * SCE[0] CPE[0] LFE[0]
746          * instead of
747          * SCE[0] CPE[0] SCE[1].
748          * If we seem to have encountered such a stream, transfer
749          * the SCE[1] element to the LFE[0]'s mapping */
750         if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
751             if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
752                 av_log(ac->avctx, AV_LOG_WARNING,
753                    "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
754                    type == TYPE_SCE ? "SCE" : "LFE", elem_id);
755                 ac->warned_remapping_once++;
756             }
757             ac->tags_mapped++;
758             return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
759         }
760         if (ac->tags_mapped == 2 &&
761             ac->oc[1].m4ac.chan_config == 4 &&
762             type == TYPE_SCE) {
763             ac->tags_mapped++;
764             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
765         }
766     case 3:
767     case 2:
768         if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
769             type == TYPE_CPE) {
770             ac->tags_mapped++;
771             return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
772         } else if (ac->oc[1].m4ac.chan_config == 2) {
773             return NULL;
774         }
775     case 1:
776         if (!ac->tags_mapped && type == TYPE_SCE) {
777             ac->tags_mapped++;
778             return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
779         }
780     default:
781         return NULL;
782     }
783 }
784
785 /**
786  * Decode an array of 4 bit element IDs, optionally interleaved with a
787  * stereo/mono switching bit.
788  *
789  * @param type speaker type/position for these channels
790  */
791 static void decode_channel_map(uint8_t layout_map[][3],
792                                enum ChannelPosition type,
793                                GetBitContext *gb, int n)
794 {
795     while (n--) {
796         enum RawDataBlockType syn_ele;
797         switch (type) {
798         case AAC_CHANNEL_FRONT:
799         case AAC_CHANNEL_BACK:
800         case AAC_CHANNEL_SIDE:
801             syn_ele = get_bits1(gb);
802             break;
803         case AAC_CHANNEL_CC:
804             skip_bits1(gb);
805             syn_ele = TYPE_CCE;
806             break;
807         case AAC_CHANNEL_LFE:
808             syn_ele = TYPE_LFE;
809             break;
810         default:
811             // AAC_CHANNEL_OFF has no channel map
812             av_assert0(0);
813         }
814         layout_map[0][0] = syn_ele;
815         layout_map[0][1] = get_bits(gb, 4);
816         layout_map[0][2] = type;
817         layout_map++;
818     }
819 }
820
821 static inline void relative_align_get_bits(GetBitContext *gb,
822                                            int reference_position) {
823     int n = (reference_position - get_bits_count(gb) & 7);
824     if (n)
825         skip_bits(gb, n);
826 }
827
828 /**
829  * Decode program configuration element; reference: table 4.2.
830  *
831  * @return  Returns error status. 0 - OK, !0 - error
832  */
833 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
834                       uint8_t (*layout_map)[3],
835                       GetBitContext *gb, int byte_align_ref)
836 {
837     int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
838     int sampling_index;
839     int comment_len;
840     int tags;
841
842     skip_bits(gb, 2);  // object_type
843
844     sampling_index = get_bits(gb, 4);
845     if (m4ac->sampling_index != sampling_index)
846         av_log(avctx, AV_LOG_WARNING,
847                "Sample rate index in program config element does not "
848                "match the sample rate index configured by the container.\n");
849
850     num_front       = get_bits(gb, 4);
851     num_side        = get_bits(gb, 4);
852     num_back        = get_bits(gb, 4);
853     num_lfe         = get_bits(gb, 2);
854     num_assoc_data  = get_bits(gb, 3);
855     num_cc          = get_bits(gb, 4);
856
857     if (get_bits1(gb))
858         skip_bits(gb, 4); // mono_mixdown_tag
859     if (get_bits1(gb))
860         skip_bits(gb, 4); // stereo_mixdown_tag
861
862     if (get_bits1(gb))
863         skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
864
865     if (get_bits_left(gb) < 5 * (num_front + num_side + num_back + num_cc) + 4 *(num_lfe + num_assoc_data + num_cc)) {
866         av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
867         return -1;
868     }
869     decode_channel_map(layout_map       , AAC_CHANNEL_FRONT, gb, num_front);
870     tags = num_front;
871     decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE,  gb, num_side);
872     tags += num_side;
873     decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK,  gb, num_back);
874     tags += num_back;
875     decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE,   gb, num_lfe);
876     tags += num_lfe;
877
878     skip_bits_long(gb, 4 * num_assoc_data);
879
880     decode_channel_map(layout_map + tags, AAC_CHANNEL_CC,    gb, num_cc);
881     tags += num_cc;
882
883     relative_align_get_bits(gb, byte_align_ref);
884
885     /* comment field, first byte is length */
886     comment_len = get_bits(gb, 8) * 8;
887     if (get_bits_left(gb) < comment_len) {
888         av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
889         return AVERROR_INVALIDDATA;
890     }
891     skip_bits_long(gb, comment_len);
892     return tags;
893 }
894
895 /**
896  * Decode GA "General Audio" specific configuration; reference: table 4.1.
897  *
898  * @param   ac          pointer to AACContext, may be null
899  * @param   avctx       pointer to AVCCodecContext, used for logging
900  *
901  * @return  Returns error status. 0 - OK, !0 - error
902  */
903 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
904                                      GetBitContext *gb,
905                                      int get_bit_alignment,
906                                      MPEG4AudioConfig *m4ac,
907                                      int channel_config)
908 {
909     int extension_flag, ret, ep_config, res_flags;
910     uint8_t layout_map[MAX_ELEM_ID*4][3];
911     int tags = 0;
912
913 #if USE_FIXED
914     if (get_bits1(gb)) { // frameLengthFlag
915         avpriv_report_missing_feature(avctx, "Fixed point 960/120 MDCT window");
916         return AVERROR_PATCHWELCOME;
917     }
918     m4ac->frame_length_short = 0;
919 #else
920     m4ac->frame_length_short = get_bits1(gb);
921     if (m4ac->frame_length_short && m4ac->sbr == 1) {
922       avpriv_report_missing_feature(avctx, "SBR with 960 frame length");
923       if (ac) ac->warned_960_sbr = 1;
924       m4ac->sbr = 0;
925       m4ac->ps = 0;
926     }
927 #endif
928
929     if (get_bits1(gb))       // dependsOnCoreCoder
930         skip_bits(gb, 14);   // coreCoderDelay
931     extension_flag = get_bits1(gb);
932
933     if (m4ac->object_type == AOT_AAC_SCALABLE ||
934         m4ac->object_type == AOT_ER_AAC_SCALABLE)
935         skip_bits(gb, 3);     // layerNr
936
937     if (channel_config == 0) {
938         skip_bits(gb, 4);  // element_instance_tag
939         tags = decode_pce(avctx, m4ac, layout_map, gb, get_bit_alignment);
940         if (tags < 0)
941             return tags;
942     } else {
943         if ((ret = set_default_channel_config(ac, avctx, layout_map,
944                                               &tags, channel_config)))
945             return ret;
946     }
947
948     if (count_channels(layout_map, tags) > 1) {
949         m4ac->ps = 0;
950     } else if (m4ac->sbr == 1 && m4ac->ps == -1)
951         m4ac->ps = 1;
952
953     if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
954         return ret;
955
956     if (extension_flag) {
957         switch (m4ac->object_type) {
958         case AOT_ER_BSAC:
959             skip_bits(gb, 5);    // numOfSubFrame
960             skip_bits(gb, 11);   // layer_length
961             break;
962         case AOT_ER_AAC_LC:
963         case AOT_ER_AAC_LTP:
964         case AOT_ER_AAC_SCALABLE:
965         case AOT_ER_AAC_LD:
966             res_flags = get_bits(gb, 3);
967             if (res_flags) {
968                 avpriv_report_missing_feature(avctx,
969                                               "AAC data resilience (flags %x)",
970                                               res_flags);
971                 return AVERROR_PATCHWELCOME;
972             }
973             break;
974         }
975         skip_bits1(gb);    // extensionFlag3 (TBD in version 3)
976     }
977     switch (m4ac->object_type) {
978     case AOT_ER_AAC_LC:
979     case AOT_ER_AAC_LTP:
980     case AOT_ER_AAC_SCALABLE:
981     case AOT_ER_AAC_LD:
982         ep_config = get_bits(gb, 2);
983         if (ep_config) {
984             avpriv_report_missing_feature(avctx,
985                                           "epConfig %d", ep_config);
986             return AVERROR_PATCHWELCOME;
987         }
988     }
989     return 0;
990 }
991
992 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
993                                      GetBitContext *gb,
994                                      MPEG4AudioConfig *m4ac,
995                                      int channel_config)
996 {
997     int ret, ep_config, res_flags;
998     uint8_t layout_map[MAX_ELEM_ID*4][3];
999     int tags = 0;
1000     const int ELDEXT_TERM = 0;
1001
1002     m4ac->ps  = 0;
1003     m4ac->sbr = 0;
1004 #if USE_FIXED
1005     if (get_bits1(gb)) { // frameLengthFlag
1006         avpriv_request_sample(avctx, "960/120 MDCT window");
1007         return AVERROR_PATCHWELCOME;
1008     }
1009 #else
1010     m4ac->frame_length_short = get_bits1(gb);
1011 #endif
1012     res_flags = get_bits(gb, 3);
1013     if (res_flags) {
1014         avpriv_report_missing_feature(avctx,
1015                                       "AAC data resilience (flags %x)",
1016                                       res_flags);
1017         return AVERROR_PATCHWELCOME;
1018     }
1019
1020     if (get_bits1(gb)) { // ldSbrPresentFlag
1021         avpriv_report_missing_feature(avctx,
1022                                       "Low Delay SBR");
1023         return AVERROR_PATCHWELCOME;
1024     }
1025
1026     while (get_bits(gb, 4) != ELDEXT_TERM) {
1027         int len = get_bits(gb, 4);
1028         if (len == 15)
1029             len += get_bits(gb, 8);
1030         if (len == 15 + 255)
1031             len += get_bits(gb, 16);
1032         if (get_bits_left(gb) < len * 8 + 4) {
1033             av_log(avctx, AV_LOG_ERROR, overread_err);
1034             return AVERROR_INVALIDDATA;
1035         }
1036         skip_bits_long(gb, 8 * len);
1037     }
1038
1039     if ((ret = set_default_channel_config(ac, avctx, layout_map,
1040                                           &tags, channel_config)))
1041         return ret;
1042
1043     if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
1044         return ret;
1045
1046     ep_config = get_bits(gb, 2);
1047     if (ep_config) {
1048         avpriv_report_missing_feature(avctx,
1049                                       "epConfig %d", ep_config);
1050         return AVERROR_PATCHWELCOME;
1051     }
1052     return 0;
1053 }
1054
1055 /**
1056  * Decode audio specific configuration; reference: table 1.13.
1057  *
1058  * @param   ac          pointer to AACContext, may be null
1059  * @param   avctx       pointer to AVCCodecContext, used for logging
1060  * @param   m4ac        pointer to MPEG4AudioConfig, used for parsing
1061  * @param   gb          buffer holding an audio specific config
1062  * @param   get_bit_alignment relative alignment for byte align operations
1063  * @param   sync_extension look for an appended sync extension
1064  *
1065  * @return  Returns error status or number of consumed bits. <0 - error
1066  */
1067 static int decode_audio_specific_config_gb(AACContext *ac,
1068                                            AVCodecContext *avctx,
1069                                            MPEG4AudioConfig *m4ac,
1070                                            GetBitContext *gb,
1071                                            int get_bit_alignment,
1072                                            int sync_extension)
1073 {
1074     int i, ret;
1075     GetBitContext gbc = *gb;
1076
1077     if ((i = ff_mpeg4audio_get_config_gb(m4ac, &gbc, sync_extension, avctx)) < 0)
1078         return AVERROR_INVALIDDATA;
1079
1080     if (m4ac->sampling_index > 12) {
1081         av_log(avctx, AV_LOG_ERROR,
1082                "invalid sampling rate index %d\n",
1083                m4ac->sampling_index);
1084         return AVERROR_INVALIDDATA;
1085     }
1086     if (m4ac->object_type == AOT_ER_AAC_LD &&
1087         (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
1088         av_log(avctx, AV_LOG_ERROR,
1089                "invalid low delay sampling rate index %d\n",
1090                m4ac->sampling_index);
1091         return AVERROR_INVALIDDATA;
1092     }
1093
1094     skip_bits_long(gb, i);
1095
1096     switch (m4ac->object_type) {
1097     case AOT_AAC_MAIN:
1098     case AOT_AAC_LC:
1099     case AOT_AAC_SSR:
1100     case AOT_AAC_LTP:
1101     case AOT_ER_AAC_LC:
1102     case AOT_ER_AAC_LD:
1103         if ((ret = decode_ga_specific_config(ac, avctx, gb, get_bit_alignment,
1104                                             m4ac, m4ac->chan_config)) < 0)
1105             return ret;
1106         break;
1107     case AOT_ER_AAC_ELD:
1108         if ((ret = decode_eld_specific_config(ac, avctx, gb,
1109                                               m4ac, m4ac->chan_config)) < 0)
1110             return ret;
1111         break;
1112     default:
1113         avpriv_report_missing_feature(avctx,
1114                                       "Audio object type %s%d",
1115                                       m4ac->sbr == 1 ? "SBR+" : "",
1116                                       m4ac->object_type);
1117         return AVERROR(ENOSYS);
1118     }
1119
1120     ff_dlog(avctx,
1121             "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1122             m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1123             m4ac->sample_rate, m4ac->sbr,
1124             m4ac->ps);
1125
1126     return get_bits_count(gb);
1127 }
1128
1129 static int decode_audio_specific_config(AACContext *ac,
1130                                         AVCodecContext *avctx,
1131                                         MPEG4AudioConfig *m4ac,
1132                                         const uint8_t *data, int64_t bit_size,
1133                                         int sync_extension)
1134 {
1135     int i, ret;
1136     GetBitContext gb;
1137
1138     if (bit_size < 0 || bit_size > INT_MAX) {
1139         av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
1140         return AVERROR_INVALIDDATA;
1141     }
1142
1143     ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
1144     for (i = 0; i < bit_size >> 3; i++)
1145         ff_dlog(avctx, "%02x ", data[i]);
1146     ff_dlog(avctx, "\n");
1147
1148     if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
1149         return ret;
1150
1151     return decode_audio_specific_config_gb(ac, avctx, m4ac, &gb, 0,
1152                                            sync_extension);
1153 }
1154
1155 /**
1156  * linear congruential pseudorandom number generator
1157  *
1158  * @param   previous_val    pointer to the current state of the generator
1159  *
1160  * @return  Returns a 32-bit pseudorandom integer
1161  */
1162 static av_always_inline int lcg_random(unsigned previous_val)
1163 {
1164     union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1165     return v.s;
1166 }
1167
1168 static void reset_all_predictors(PredictorState *ps)
1169 {
1170     int i;
1171     for (i = 0; i < MAX_PREDICTORS; i++)
1172         reset_predict_state(&ps[i]);
1173 }
1174
1175 static int sample_rate_idx (int rate)
1176 {
1177          if (92017 <= rate) return 0;
1178     else if (75132 <= rate) return 1;
1179     else if (55426 <= rate) return 2;
1180     else if (46009 <= rate) return 3;
1181     else if (37566 <= rate) return 4;
1182     else if (27713 <= rate) return 5;
1183     else if (23004 <= rate) return 6;
1184     else if (18783 <= rate) return 7;
1185     else if (13856 <= rate) return 8;
1186     else if (11502 <= rate) return 9;
1187     else if (9391  <= rate) return 10;
1188     else                    return 11;
1189 }
1190
1191 static void reset_predictor_group(PredictorState *ps, int group_num)
1192 {
1193     int i;
1194     for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1195         reset_predict_state(&ps[i]);
1196 }
1197
1198 static void aacdec_init(AACContext *ac);
1199
1200 static av_cold void aac_static_table_init(void)
1201 {
1202     static VLC_TYPE vlc_buf[304 + 270 + 550 + 300 + 328 +
1203                             294 + 306 + 268 + 510 + 366 + 462][2];
1204     for (unsigned i = 0, offset = 0; i < 11; i++) {
1205         vlc_spectral[i].table           = &vlc_buf[offset];
1206         vlc_spectral[i].table_allocated = FF_ARRAY_ELEMS(vlc_buf) - offset;
1207         init_vlc(&vlc_spectral[i], 8, ff_aac_spectral_sizes[i],
1208                  ff_aac_spectral_bits[i],  sizeof(ff_aac_spectral_bits[i][0]),
1209                                            sizeof(ff_aac_spectral_bits[i][0]),
1210                  ff_aac_spectral_codes[i], sizeof(ff_aac_spectral_codes[i][0]),
1211                                            sizeof(ff_aac_spectral_codes[i][0]),
1212                  INIT_VLC_STATIC_OVERLONG);
1213         offset += vlc_spectral[i].table_size;
1214     }
1215
1216     AAC_RENAME(ff_aac_sbr_init)();
1217
1218     ff_aac_tableinit();
1219
1220     INIT_VLC_STATIC(&vlc_scalefactors, 7,
1221                     FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1222                     ff_aac_scalefactor_bits,
1223                     sizeof(ff_aac_scalefactor_bits[0]),
1224                     sizeof(ff_aac_scalefactor_bits[0]),
1225                     ff_aac_scalefactor_code,
1226                     sizeof(ff_aac_scalefactor_code[0]),
1227                     sizeof(ff_aac_scalefactor_code[0]),
1228                     352);
1229
1230     // window initialization
1231     AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_1024), 4.0, 1024);
1232     AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_128), 6.0, 128);
1233 #if !USE_FIXED
1234     AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_960), 4.0, 960);
1235     AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_120), 6.0, 120);
1236     AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_960), 960);
1237     AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_120), 120);
1238 #endif
1239     AAC_RENAME(ff_init_ff_sine_windows)(10);
1240     AAC_RENAME(ff_init_ff_sine_windows)( 9);
1241     AAC_RENAME(ff_init_ff_sine_windows)( 7);
1242
1243     AAC_RENAME(ff_cbrt_tableinit)();
1244 }
1245
1246 static AVOnce aac_table_init = AV_ONCE_INIT;
1247
1248 static av_cold int aac_decode_init(AVCodecContext *avctx)
1249 {
1250     AACContext *ac = avctx->priv_data;
1251     int ret;
1252
1253     if (avctx->sample_rate > 96000)
1254         return AVERROR_INVALIDDATA;
1255
1256     ret = ff_thread_once(&aac_table_init, &aac_static_table_init);
1257     if (ret != 0)
1258         return AVERROR_UNKNOWN;
1259
1260     ac->avctx = avctx;
1261     ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1262
1263     aacdec_init(ac);
1264 #if USE_FIXED
1265     avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1266 #else
1267     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1268 #endif /* USE_FIXED */
1269
1270     if (avctx->extradata_size > 0) {
1271         if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1272                                                 avctx->extradata,
1273                                                 avctx->extradata_size * 8LL,
1274                                                 1)) < 0)
1275             return ret;
1276     } else {
1277         int sr, i;
1278         uint8_t layout_map[MAX_ELEM_ID*4][3];
1279         int layout_map_tags;
1280
1281         sr = sample_rate_idx(avctx->sample_rate);
1282         ac->oc[1].m4ac.sampling_index = sr;
1283         ac->oc[1].m4ac.channels = avctx->channels;
1284         ac->oc[1].m4ac.sbr = -1;
1285         ac->oc[1].m4ac.ps = -1;
1286
1287         for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1288             if (ff_mpeg4audio_channels[i] == avctx->channels)
1289                 break;
1290         if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1291             i = 0;
1292         }
1293         ac->oc[1].m4ac.chan_config = i;
1294
1295         if (ac->oc[1].m4ac.chan_config) {
1296             int ret = set_default_channel_config(ac, avctx, layout_map,
1297                 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1298             if (!ret)
1299                 output_configure(ac, layout_map, layout_map_tags,
1300                                  OC_GLOBAL_HDR, 0);
1301             else if (avctx->err_recognition & AV_EF_EXPLODE)
1302                 return AVERROR_INVALIDDATA;
1303         }
1304     }
1305
1306     if (avctx->channels > MAX_CHANNELS) {
1307         av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1308         return AVERROR_INVALIDDATA;
1309     }
1310
1311 #if USE_FIXED
1312     ac->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1313 #else
1314     ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1315 #endif /* USE_FIXED */
1316     if (!ac->fdsp) {
1317         return AVERROR(ENOMEM);
1318     }
1319
1320     ac->random_state = 0x1f2e3d4c;
1321
1322     AAC_RENAME_32(ff_mdct_init)(&ac->mdct,       11, 1, 1.0 / RANGE15(1024.0));
1323     AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ld,    10, 1, 1.0 / RANGE15(512.0));
1324     AAC_RENAME_32(ff_mdct_init)(&ac->mdct_small,  8, 1, 1.0 / RANGE15(128.0));
1325     AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ltp,   11, 0, RANGE15(-2.0));
1326 #if !USE_FIXED
1327     ret = ff_mdct15_init(&ac->mdct120, 1, 3, 1.0f/(16*1024*120*2));
1328     if (ret < 0)
1329         return ret;
1330     ret = ff_mdct15_init(&ac->mdct480, 1, 5, 1.0f/(16*1024*960));
1331     if (ret < 0)
1332         return ret;
1333     ret = ff_mdct15_init(&ac->mdct960, 1, 6, 1.0f/(16*1024*960*2));
1334     if (ret < 0)
1335         return ret;
1336 #endif
1337
1338     return 0;
1339 }
1340
1341 /**
1342  * Skip data_stream_element; reference: table 4.10.
1343  */
1344 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1345 {
1346     int byte_align = get_bits1(gb);
1347     int count = get_bits(gb, 8);
1348     if (count == 255)
1349         count += get_bits(gb, 8);
1350     if (byte_align)
1351         align_get_bits(gb);
1352
1353     if (get_bits_left(gb) < 8 * count) {
1354         av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1355         return AVERROR_INVALIDDATA;
1356     }
1357     skip_bits_long(gb, 8 * count);
1358     return 0;
1359 }
1360
1361 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1362                              GetBitContext *gb)
1363 {
1364     int sfb;
1365     if (get_bits1(gb)) {
1366         ics->predictor_reset_group = get_bits(gb, 5);
1367         if (ics->predictor_reset_group == 0 ||
1368             ics->predictor_reset_group > 30) {
1369             av_log(ac->avctx, AV_LOG_ERROR,
1370                    "Invalid Predictor Reset Group.\n");
1371             return AVERROR_INVALIDDATA;
1372         }
1373     }
1374     for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1375         ics->prediction_used[sfb] = get_bits1(gb);
1376     }
1377     return 0;
1378 }
1379
1380 /**
1381  * Decode Long Term Prediction data; reference: table 4.xx.
1382  */
1383 static void decode_ltp(LongTermPrediction *ltp,
1384                        GetBitContext *gb, uint8_t max_sfb)
1385 {
1386     int sfb;
1387
1388     ltp->lag  = get_bits(gb, 11);
1389     ltp->coef = ltp_coef[get_bits(gb, 3)];
1390     for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1391         ltp->used[sfb] = get_bits1(gb);
1392 }
1393
1394 /**
1395  * Decode Individual Channel Stream info; reference: table 4.6.
1396  */
1397 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1398                            GetBitContext *gb)
1399 {
1400     const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1401     const int aot = m4ac->object_type;
1402     const int sampling_index = m4ac->sampling_index;
1403     int ret_fail = AVERROR_INVALIDDATA;
1404
1405     if (aot != AOT_ER_AAC_ELD) {
1406         if (get_bits1(gb)) {
1407             av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1408             if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1409                 return AVERROR_INVALIDDATA;
1410         }
1411         ics->window_sequence[1] = ics->window_sequence[0];
1412         ics->window_sequence[0] = get_bits(gb, 2);
1413         if (aot == AOT_ER_AAC_LD &&
1414             ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1415             av_log(ac->avctx, AV_LOG_ERROR,
1416                    "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1417                    "window sequence %d found.\n", ics->window_sequence[0]);
1418             ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1419             return AVERROR_INVALIDDATA;
1420         }
1421         ics->use_kb_window[1]   = ics->use_kb_window[0];
1422         ics->use_kb_window[0]   = get_bits1(gb);
1423     }
1424     ics->num_window_groups  = 1;
1425     ics->group_len[0]       = 1;
1426     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1427         int i;
1428         ics->max_sfb = get_bits(gb, 4);
1429         for (i = 0; i < 7; i++) {
1430             if (get_bits1(gb)) {
1431                 ics->group_len[ics->num_window_groups - 1]++;
1432             } else {
1433                 ics->num_window_groups++;
1434                 ics->group_len[ics->num_window_groups - 1] = 1;
1435             }
1436         }
1437         ics->num_windows       = 8;
1438         if (m4ac->frame_length_short) {
1439             ics->swb_offset    =  ff_swb_offset_120[sampling_index];
1440             ics->num_swb       = ff_aac_num_swb_120[sampling_index];
1441         } else {
1442             ics->swb_offset    =  ff_swb_offset_128[sampling_index];
1443             ics->num_swb       = ff_aac_num_swb_128[sampling_index];
1444         }
1445         ics->tns_max_bands     = ff_tns_max_bands_128[sampling_index];
1446         ics->predictor_present = 0;
1447     } else {
1448         ics->max_sfb           = get_bits(gb, 6);
1449         ics->num_windows       = 1;
1450         if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1451             if (m4ac->frame_length_short) {
1452                 ics->swb_offset    =     ff_swb_offset_480[sampling_index];
1453                 ics->num_swb       =    ff_aac_num_swb_480[sampling_index];
1454                 ics->tns_max_bands =  ff_tns_max_bands_480[sampling_index];
1455             } else {
1456                 ics->swb_offset    =     ff_swb_offset_512[sampling_index];
1457                 ics->num_swb       =    ff_aac_num_swb_512[sampling_index];
1458                 ics->tns_max_bands =  ff_tns_max_bands_512[sampling_index];
1459             }
1460             if (!ics->num_swb || !ics->swb_offset) {
1461                 ret_fail = AVERROR_BUG;
1462                 goto fail;
1463             }
1464         } else {
1465             if (m4ac->frame_length_short) {
1466                 ics->num_swb    = ff_aac_num_swb_960[sampling_index];
1467                 ics->swb_offset = ff_swb_offset_960[sampling_index];
1468             } else {
1469                 ics->num_swb    = ff_aac_num_swb_1024[sampling_index];
1470                 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1471             }
1472             ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1473         }
1474         if (aot != AOT_ER_AAC_ELD) {
1475             ics->predictor_present     = get_bits1(gb);
1476             ics->predictor_reset_group = 0;
1477         }
1478         if (ics->predictor_present) {
1479             if (aot == AOT_AAC_MAIN) {
1480                 if (decode_prediction(ac, ics, gb)) {
1481                     goto fail;
1482                 }
1483             } else if (aot == AOT_AAC_LC ||
1484                        aot == AOT_ER_AAC_LC) {
1485                 av_log(ac->avctx, AV_LOG_ERROR,
1486                        "Prediction is not allowed in AAC-LC.\n");
1487                 goto fail;
1488             } else {
1489                 if (aot == AOT_ER_AAC_LD) {
1490                     av_log(ac->avctx, AV_LOG_ERROR,
1491                            "LTP in ER AAC LD not yet implemented.\n");
1492                     ret_fail = AVERROR_PATCHWELCOME;
1493                     goto fail;
1494                 }
1495                 if ((ics->ltp.present = get_bits(gb, 1)))
1496                     decode_ltp(&ics->ltp, gb, ics->max_sfb);
1497             }
1498         }
1499     }
1500
1501     if (ics->max_sfb > ics->num_swb) {
1502         av_log(ac->avctx, AV_LOG_ERROR,
1503                "Number of scalefactor bands in group (%d) "
1504                "exceeds limit (%d).\n",
1505                ics->max_sfb, ics->num_swb);
1506         goto fail;
1507     }
1508
1509     return 0;
1510 fail:
1511     ics->max_sfb = 0;
1512     return ret_fail;
1513 }
1514
1515 /**
1516  * Decode band types (section_data payload); reference: table 4.46.
1517  *
1518  * @param   band_type           array of the used band type
1519  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1520  *
1521  * @return  Returns error status. 0 - OK, !0 - error
1522  */
1523 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1524                              int band_type_run_end[120], GetBitContext *gb,
1525                              IndividualChannelStream *ics)
1526 {
1527     int g, idx = 0;
1528     const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1529     for (g = 0; g < ics->num_window_groups; g++) {
1530         int k = 0;
1531         while (k < ics->max_sfb) {
1532             uint8_t sect_end = k;
1533             int sect_len_incr;
1534             int sect_band_type = get_bits(gb, 4);
1535             if (sect_band_type == 12) {
1536                 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1537                 return AVERROR_INVALIDDATA;
1538             }
1539             do {
1540                 sect_len_incr = get_bits(gb, bits);
1541                 sect_end += sect_len_incr;
1542                 if (get_bits_left(gb) < 0) {
1543                     av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1544                     return AVERROR_INVALIDDATA;
1545                 }
1546                 if (sect_end > ics->max_sfb) {
1547                     av_log(ac->avctx, AV_LOG_ERROR,
1548                            "Number of bands (%d) exceeds limit (%d).\n",
1549                            sect_end, ics->max_sfb);
1550                     return AVERROR_INVALIDDATA;
1551                 }
1552             } while (sect_len_incr == (1 << bits) - 1);
1553             for (; k < sect_end; k++) {
1554                 band_type        [idx]   = sect_band_type;
1555                 band_type_run_end[idx++] = sect_end;
1556             }
1557         }
1558     }
1559     return 0;
1560 }
1561
1562 /**
1563  * Decode scalefactors; reference: table 4.47.
1564  *
1565  * @param   global_gain         first scalefactor value as scalefactors are differentially coded
1566  * @param   band_type           array of the used band type
1567  * @param   band_type_run_end   array of the last scalefactor band of a band type run
1568  * @param   sf                  array of scalefactors or intensity stereo positions
1569  *
1570  * @return  Returns error status. 0 - OK, !0 - error
1571  */
1572 static int decode_scalefactors(AACContext *ac, INTFLOAT sf[120], GetBitContext *gb,
1573                                unsigned int global_gain,
1574                                IndividualChannelStream *ics,
1575                                enum BandType band_type[120],
1576                                int band_type_run_end[120])
1577 {
1578     int g, i, idx = 0;
1579     int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
1580     int clipped_offset;
1581     int noise_flag = 1;
1582     for (g = 0; g < ics->num_window_groups; g++) {
1583         for (i = 0; i < ics->max_sfb;) {
1584             int run_end = band_type_run_end[idx];
1585             if (band_type[idx] == ZERO_BT) {
1586                 for (; i < run_end; i++, idx++)
1587                     sf[idx] = FIXR(0.);
1588             } else if ((band_type[idx] == INTENSITY_BT) ||
1589                        (band_type[idx] == INTENSITY_BT2)) {
1590                 for (; i < run_end; i++, idx++) {
1591                     offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1592                     clipped_offset = av_clip(offset[2], -155, 100);
1593                     if (offset[2] != clipped_offset) {
1594                         avpriv_request_sample(ac->avctx,
1595                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1596                                               "Clipped intensity stereo position (%d -> %d)",
1597                                               offset[2], clipped_offset);
1598                     }
1599 #if USE_FIXED
1600                     sf[idx] = 100 - clipped_offset;
1601 #else
1602                     sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1603 #endif /* USE_FIXED */
1604                 }
1605             } else if (band_type[idx] == NOISE_BT) {
1606                 for (; i < run_end; i++, idx++) {
1607                     if (noise_flag-- > 0)
1608                         offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
1609                     else
1610                         offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1611                     clipped_offset = av_clip(offset[1], -100, 155);
1612                     if (offset[1] != clipped_offset) {
1613                         avpriv_request_sample(ac->avctx,
1614                                               "If you heard an audible artifact, there may be a bug in the decoder. "
1615                                               "Clipped noise gain (%d -> %d)",
1616                                               offset[1], clipped_offset);
1617                     }
1618 #if USE_FIXED
1619                     sf[idx] = -(100 + clipped_offset);
1620 #else
1621                     sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1622 #endif /* USE_FIXED */
1623                 }
1624             } else {
1625                 for (; i < run_end; i++, idx++) {
1626                     offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1627                     if (offset[0] > 255U) {
1628                         av_log(ac->avctx, AV_LOG_ERROR,
1629                                "Scalefactor (%d) out of range.\n", offset[0]);
1630                         return AVERROR_INVALIDDATA;
1631                     }
1632 #if USE_FIXED
1633                     sf[idx] = -offset[0];
1634 #else
1635                     sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1636 #endif /* USE_FIXED */
1637                 }
1638             }
1639         }
1640     }
1641     return 0;
1642 }
1643
1644 /**
1645  * Decode pulse data; reference: table 4.7.
1646  */
1647 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1648                          const uint16_t *swb_offset, int num_swb)
1649 {
1650     int i, pulse_swb;
1651     pulse->num_pulse = get_bits(gb, 2) + 1;
1652     pulse_swb        = get_bits(gb, 6);
1653     if (pulse_swb >= num_swb)
1654         return -1;
1655     pulse->pos[0]    = swb_offset[pulse_swb];
1656     pulse->pos[0]   += get_bits(gb, 5);
1657     if (pulse->pos[0] >= swb_offset[num_swb])
1658         return -1;
1659     pulse->amp[0]    = get_bits(gb, 4);
1660     for (i = 1; i < pulse->num_pulse; i++) {
1661         pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1662         if (pulse->pos[i] >= swb_offset[num_swb])
1663             return -1;
1664         pulse->amp[i] = get_bits(gb, 4);
1665     }
1666     return 0;
1667 }
1668
1669 /**
1670  * Decode Temporal Noise Shaping data; reference: table 4.48.
1671  *
1672  * @return  Returns error status. 0 - OK, !0 - error
1673  */
1674 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1675                       GetBitContext *gb, const IndividualChannelStream *ics)
1676 {
1677     int w, filt, i, coef_len, coef_res, coef_compress;
1678     const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1679     const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1680     for (w = 0; w < ics->num_windows; w++) {
1681         if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1682             coef_res = get_bits1(gb);
1683
1684             for (filt = 0; filt < tns->n_filt[w]; filt++) {
1685                 int tmp2_idx;
1686                 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1687
1688                 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1689                     av_log(ac->avctx, AV_LOG_ERROR,
1690                            "TNS filter order %d is greater than maximum %d.\n",
1691                            tns->order[w][filt], tns_max_order);
1692                     tns->order[w][filt] = 0;
1693                     return AVERROR_INVALIDDATA;
1694                 }
1695                 if (tns->order[w][filt]) {
1696                     tns->direction[w][filt] = get_bits1(gb);
1697                     coef_compress = get_bits1(gb);
1698                     coef_len = coef_res + 3 - coef_compress;
1699                     tmp2_idx = 2 * coef_compress + coef_res;
1700
1701                     for (i = 0; i < tns->order[w][filt]; i++)
1702                         tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1703                 }
1704             }
1705         }
1706     }
1707     return 0;
1708 }
1709
1710 /**
1711  * Decode Mid/Side data; reference: table 4.54.
1712  *
1713  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
1714  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
1715  *                      [3] reserved for scalable AAC
1716  */
1717 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1718                                    int ms_present)
1719 {
1720     int idx;
1721     int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1722     if (ms_present == 1) {
1723         for (idx = 0; idx < max_idx; idx++)
1724             cpe->ms_mask[idx] = get_bits1(gb);
1725     } else if (ms_present == 2) {
1726         memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1727     }
1728 }
1729
1730 /**
1731  * Decode spectral data; reference: table 4.50.
1732  * Dequantize and scale spectral data; reference: 4.6.3.3.
1733  *
1734  * @param   coef            array of dequantized, scaled spectral data
1735  * @param   sf              array of scalefactors or intensity stereo positions
1736  * @param   pulse_present   set if pulses are present
1737  * @param   pulse           pointer to pulse data struct
1738  * @param   band_type       array of the used band type
1739  *
1740  * @return  Returns error status. 0 - OK, !0 - error
1741  */
1742 static int decode_spectrum_and_dequant(AACContext *ac, INTFLOAT coef[1024],
1743                                        GetBitContext *gb, const INTFLOAT sf[120],
1744                                        int pulse_present, const Pulse *pulse,
1745                                        const IndividualChannelStream *ics,
1746                                        enum BandType band_type[120])
1747 {
1748     int i, k, g, idx = 0;
1749     const int c = 1024 / ics->num_windows;
1750     const uint16_t *offsets = ics->swb_offset;
1751     INTFLOAT *coef_base = coef;
1752
1753     for (g = 0; g < ics->num_windows; g++)
1754         memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1755                sizeof(INTFLOAT) * (c - offsets[ics->max_sfb]));
1756
1757     for (g = 0; g < ics->num_window_groups; g++) {
1758         unsigned g_len = ics->group_len[g];
1759
1760         for (i = 0; i < ics->max_sfb; i++, idx++) {
1761             const unsigned cbt_m1 = band_type[idx] - 1;
1762             INTFLOAT *cfo = coef + offsets[i];
1763             int off_len = offsets[i + 1] - offsets[i];
1764             int group;
1765
1766             if (cbt_m1 >= INTENSITY_BT2 - 1) {
1767                 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1768                     memset(cfo, 0, off_len * sizeof(*cfo));
1769                 }
1770             } else if (cbt_m1 == NOISE_BT - 1) {
1771                 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1772                     INTFLOAT band_energy;
1773 #if USE_FIXED
1774                     for (k = 0; k < off_len; k++) {
1775                         ac->random_state  = lcg_random(ac->random_state);
1776                         cfo[k] = ac->random_state >> 3;
1777                     }
1778
1779                     band_energy = ac->fdsp->scalarproduct_fixed(cfo, cfo, off_len);
1780                     band_energy = fixed_sqrt(band_energy, 31);
1781                     noise_scale(cfo, sf[idx], band_energy, off_len);
1782 #else
1783                     float scale;
1784
1785                     for (k = 0; k < off_len; k++) {
1786                         ac->random_state  = lcg_random(ac->random_state);
1787                         cfo[k] = ac->random_state;
1788                     }
1789
1790                     band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
1791                     scale = sf[idx] / sqrtf(band_energy);
1792                     ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
1793 #endif /* USE_FIXED */
1794                 }
1795             } else {
1796 #if !USE_FIXED
1797                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1798 #endif /* !USE_FIXED */
1799                 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1800                 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1801                 OPEN_READER(re, gb);
1802
1803                 switch (cbt_m1 >> 1) {
1804                 case 0:
1805                     for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1806                         INTFLOAT *cf = cfo;
1807                         int len = off_len;
1808
1809                         do {
1810                             int code;
1811                             unsigned cb_idx;
1812
1813                             UPDATE_CACHE(re, gb);
1814                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1815                             cb_idx = cb_vector_idx[code];
1816 #if USE_FIXED
1817                             cf = DEC_SQUAD(cf, cb_idx);
1818 #else
1819                             cf = VMUL4(cf, vq, cb_idx, sf + idx);
1820 #endif /* USE_FIXED */
1821                         } while (len -= 4);
1822                     }
1823                     break;
1824
1825                 case 1:
1826                     for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1827                         INTFLOAT *cf = cfo;
1828                         int len = off_len;
1829
1830                         do {
1831                             int code;
1832                             unsigned nnz;
1833                             unsigned cb_idx;
1834                             uint32_t bits;
1835
1836                             UPDATE_CACHE(re, gb);
1837                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1838                             cb_idx = cb_vector_idx[code];
1839                             nnz = cb_idx >> 8 & 15;
1840                             bits = nnz ? GET_CACHE(re, gb) : 0;
1841                             LAST_SKIP_BITS(re, gb, nnz);
1842 #if USE_FIXED
1843                             cf = DEC_UQUAD(cf, cb_idx, bits);
1844 #else
1845                             cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1846 #endif /* USE_FIXED */
1847                         } while (len -= 4);
1848                     }
1849                     break;
1850
1851                 case 2:
1852                     for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1853                         INTFLOAT *cf = cfo;
1854                         int len = off_len;
1855
1856                         do {
1857                             int code;
1858                             unsigned cb_idx;
1859
1860                             UPDATE_CACHE(re, gb);
1861                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1862                             cb_idx = cb_vector_idx[code];
1863 #if USE_FIXED
1864                             cf = DEC_SPAIR(cf, cb_idx);
1865 #else
1866                             cf = VMUL2(cf, vq, cb_idx, sf + idx);
1867 #endif /* USE_FIXED */
1868                         } while (len -= 2);
1869                     }
1870                     break;
1871
1872                 case 3:
1873                 case 4:
1874                     for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1875                         INTFLOAT *cf = cfo;
1876                         int len = off_len;
1877
1878                         do {
1879                             int code;
1880                             unsigned nnz;
1881                             unsigned cb_idx;
1882                             unsigned sign;
1883
1884                             UPDATE_CACHE(re, gb);
1885                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1886                             cb_idx = cb_vector_idx[code];
1887                             nnz = cb_idx >> 8 & 15;
1888                             sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1889                             LAST_SKIP_BITS(re, gb, nnz);
1890 #if USE_FIXED
1891                             cf = DEC_UPAIR(cf, cb_idx, sign);
1892 #else
1893                             cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1894 #endif /* USE_FIXED */
1895                         } while (len -= 2);
1896                     }
1897                     break;
1898
1899                 default:
1900                     for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1901 #if USE_FIXED
1902                         int *icf = cfo;
1903                         int v;
1904 #else
1905                         float *cf = cfo;
1906                         uint32_t *icf = (uint32_t *) cf;
1907 #endif /* USE_FIXED */
1908                         int len = off_len;
1909
1910                         do {
1911                             int code;
1912                             unsigned nzt, nnz;
1913                             unsigned cb_idx;
1914                             uint32_t bits;
1915                             int j;
1916
1917                             UPDATE_CACHE(re, gb);
1918                             GET_VLC(code, re, gb, vlc_tab, 8, 2);
1919
1920                             if (!code) {
1921                                 *icf++ = 0;
1922                                 *icf++ = 0;
1923                                 continue;
1924                             }
1925
1926                             cb_idx = cb_vector_idx[code];
1927                             nnz = cb_idx >> 12;
1928                             nzt = cb_idx >> 8;
1929                             bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1930                             LAST_SKIP_BITS(re, gb, nnz);
1931
1932                             for (j = 0; j < 2; j++) {
1933                                 if (nzt & 1<<j) {
1934                                     uint32_t b;
1935                                     int n;
1936                                     /* The total length of escape_sequence must be < 22 bits according
1937                                        to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1938                                     UPDATE_CACHE(re, gb);
1939                                     b = GET_CACHE(re, gb);
1940                                     b = 31 - av_log2(~b);
1941
1942                                     if (b > 8) {
1943                                         av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1944                                         return AVERROR_INVALIDDATA;
1945                                     }
1946
1947                                     SKIP_BITS(re, gb, b + 1);
1948                                     b += 4;
1949                                     n = (1 << b) + SHOW_UBITS(re, gb, b);
1950                                     LAST_SKIP_BITS(re, gb, b);
1951 #if USE_FIXED
1952                                     v = n;
1953                                     if (bits & 1U<<31)
1954                                         v = -v;
1955                                     *icf++ = v;
1956 #else
1957                                     *icf++ = ff_cbrt_tab[n] | (bits & 1U<<31);
1958 #endif /* USE_FIXED */
1959                                     bits <<= 1;
1960                                 } else {
1961 #if USE_FIXED
1962                                     v = cb_idx & 15;
1963                                     if (bits & 1U<<31)
1964                                         v = -v;
1965                                     *icf++ = v;
1966 #else
1967                                     unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1968                                     *icf++ = (bits & 1U<<31) | v;
1969 #endif /* USE_FIXED */
1970                                     bits <<= !!v;
1971                                 }
1972                                 cb_idx >>= 4;
1973                             }
1974                         } while (len -= 2);
1975 #if !USE_FIXED
1976                         ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1977 #endif /* !USE_FIXED */
1978                     }
1979                 }
1980
1981                 CLOSE_READER(re, gb);
1982             }
1983         }
1984         coef += g_len << 7;
1985     }
1986
1987     if (pulse_present) {
1988         idx = 0;
1989         for (i = 0; i < pulse->num_pulse; i++) {
1990             INTFLOAT co = coef_base[ pulse->pos[i] ];
1991             while (offsets[idx + 1] <= pulse->pos[i])
1992                 idx++;
1993             if (band_type[idx] != NOISE_BT && sf[idx]) {
1994                 INTFLOAT ico = -pulse->amp[i];
1995 #if USE_FIXED
1996                 if (co) {
1997                     ico = co + (co > 0 ? -ico : ico);
1998                 }
1999                 coef_base[ pulse->pos[i] ] = ico;
2000 #else
2001                 if (co) {
2002                     co /= sf[idx];
2003                     ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
2004                 }
2005                 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
2006 #endif /* USE_FIXED */
2007             }
2008         }
2009     }
2010 #if USE_FIXED
2011     coef = coef_base;
2012     idx = 0;
2013     for (g = 0; g < ics->num_window_groups; g++) {
2014         unsigned g_len = ics->group_len[g];
2015
2016         for (i = 0; i < ics->max_sfb; i++, idx++) {
2017             const unsigned cbt_m1 = band_type[idx] - 1;
2018             int *cfo = coef + offsets[i];
2019             int off_len = offsets[i + 1] - offsets[i];
2020             int group;
2021
2022             if (cbt_m1 < NOISE_BT - 1) {
2023                 for (group = 0; group < (int)g_len; group++, cfo+=128) {
2024                     ac->vector_pow43(cfo, off_len);
2025                     ac->subband_scale(cfo, cfo, sf[idx], 34, off_len, ac->avctx);
2026                 }
2027             }
2028         }
2029         coef += g_len << 7;
2030     }
2031 #endif /* USE_FIXED */
2032     return 0;
2033 }
2034
2035 /**
2036  * Apply AAC-Main style frequency domain prediction.
2037  */
2038 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
2039 {
2040     int sfb, k;
2041
2042     if (!sce->ics.predictor_initialized) {
2043         reset_all_predictors(sce->predictor_state);
2044         sce->ics.predictor_initialized = 1;
2045     }
2046
2047     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2048         for (sfb = 0;
2049              sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
2050              sfb++) {
2051             for (k = sce->ics.swb_offset[sfb];
2052                  k < sce->ics.swb_offset[sfb + 1];
2053                  k++) {
2054                 predict(&sce->predictor_state[k], &sce->coeffs[k],
2055                         sce->ics.predictor_present &&
2056                         sce->ics.prediction_used[sfb]);
2057             }
2058         }
2059         if (sce->ics.predictor_reset_group)
2060             reset_predictor_group(sce->predictor_state,
2061                                   sce->ics.predictor_reset_group);
2062     } else
2063         reset_all_predictors(sce->predictor_state);
2064 }
2065
2066 static void decode_gain_control(SingleChannelElement * sce, GetBitContext * gb)
2067 {
2068     // wd_num, wd_test, aloc_size
2069     static const uint8_t gain_mode[4][3] = {
2070         {1, 0, 5},  // ONLY_LONG_SEQUENCE = 0,
2071         {2, 1, 2},  // LONG_START_SEQUENCE,
2072         {8, 0, 2},  // EIGHT_SHORT_SEQUENCE,
2073         {2, 1, 5},  // LONG_STOP_SEQUENCE
2074     };
2075
2076     const int mode = sce->ics.window_sequence[0];
2077     uint8_t bd, wd, ad;
2078
2079     // FIXME: Store the gain control data on |sce| and do something with it.
2080     uint8_t max_band = get_bits(gb, 2);
2081     for (bd = 0; bd < max_band; bd++) {
2082         for (wd = 0; wd < gain_mode[mode][0]; wd++) {
2083             uint8_t adjust_num = get_bits(gb, 3);
2084             for (ad = 0; ad < adjust_num; ad++) {
2085                 skip_bits(gb, 4 + ((wd == 0 && gain_mode[mode][1])
2086                                      ? 4
2087                                      : gain_mode[mode][2]));
2088             }
2089         }
2090     }
2091 }
2092
2093 /**
2094  * Decode an individual_channel_stream payload; reference: table 4.44.
2095  *
2096  * @param   common_window   Channels have independent [0], or shared [1], Individual Channel Stream information.
2097  * @param   scale_flag      scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
2098  *
2099  * @return  Returns error status. 0 - OK, !0 - error
2100  */
2101 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
2102                       GetBitContext *gb, int common_window, int scale_flag)
2103 {
2104     Pulse pulse;
2105     TemporalNoiseShaping    *tns = &sce->tns;
2106     IndividualChannelStream *ics = &sce->ics;
2107     INTFLOAT *out = sce->coeffs;
2108     int global_gain, eld_syntax, er_syntax, pulse_present = 0;
2109     int ret;
2110
2111     eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2112     er_syntax  = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
2113                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
2114                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
2115                  ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2116
2117     /* This assignment is to silence a GCC warning about the variable being used
2118      * uninitialized when in fact it always is.
2119      */
2120     pulse.num_pulse = 0;
2121
2122     global_gain = get_bits(gb, 8);
2123
2124     if (!common_window && !scale_flag) {
2125         ret = decode_ics_info(ac, ics, gb);
2126         if (ret < 0)
2127             goto fail;
2128     }
2129
2130     if ((ret = decode_band_types(ac, sce->band_type,
2131                                  sce->band_type_run_end, gb, ics)) < 0)
2132         goto fail;
2133     if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
2134                                   sce->band_type, sce->band_type_run_end)) < 0)
2135         goto fail;
2136
2137     pulse_present = 0;
2138     if (!scale_flag) {
2139         if (!eld_syntax && (pulse_present = get_bits1(gb))) {
2140             if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2141                 av_log(ac->avctx, AV_LOG_ERROR,
2142                        "Pulse tool not allowed in eight short sequence.\n");
2143                 ret = AVERROR_INVALIDDATA;
2144                 goto fail;
2145             }
2146             if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
2147                 av_log(ac->avctx, AV_LOG_ERROR,
2148                        "Pulse data corrupt or invalid.\n");
2149                 ret = AVERROR_INVALIDDATA;
2150                 goto fail;
2151             }
2152         }
2153         tns->present = get_bits1(gb);
2154         if (tns->present && !er_syntax) {
2155             ret = decode_tns(ac, tns, gb, ics);
2156             if (ret < 0)
2157                 goto fail;
2158         }
2159         if (!eld_syntax && get_bits1(gb)) {
2160             decode_gain_control(sce, gb);
2161             if (!ac->warned_gain_control) {
2162                 avpriv_report_missing_feature(ac->avctx, "Gain control");
2163                 ac->warned_gain_control = 1;
2164             }
2165         }
2166         // I see no textual basis in the spec for this occurring after SSR gain
2167         // control, but this is what both reference and real implmentations do
2168         if (tns->present && er_syntax) {
2169             ret = decode_tns(ac, tns, gb, ics);
2170             if (ret < 0)
2171                 goto fail;
2172         }
2173     }
2174
2175     ret = decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
2176                                     &pulse, ics, sce->band_type);
2177     if (ret < 0)
2178         goto fail;
2179
2180     if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
2181         apply_prediction(ac, sce);
2182
2183     return 0;
2184 fail:
2185     tns->present = 0;
2186     return ret;
2187 }
2188
2189 /**
2190  * Mid/Side stereo decoding; reference: 4.6.8.1.3.
2191  */
2192 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
2193 {
2194     const IndividualChannelStream *ics = &cpe->ch[0].ics;
2195     INTFLOAT *ch0 = cpe->ch[0].coeffs;
2196     INTFLOAT *ch1 = cpe->ch[1].coeffs;
2197     int g, i, group, idx = 0;
2198     const uint16_t *offsets = ics->swb_offset;
2199     for (g = 0; g < ics->num_window_groups; g++) {
2200         for (i = 0; i < ics->max_sfb; i++, idx++) {
2201             if (cpe->ms_mask[idx] &&
2202                 cpe->ch[0].band_type[idx] < NOISE_BT &&
2203                 cpe->ch[1].band_type[idx] < NOISE_BT) {
2204 #if USE_FIXED
2205                 for (group = 0; group < ics->group_len[g]; group++) {
2206                     ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
2207                                                 ch1 + group * 128 + offsets[i],
2208                                                 offsets[i+1] - offsets[i]);
2209 #else
2210                 for (group = 0; group < ics->group_len[g]; group++) {
2211                     ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
2212                                                ch1 + group * 128 + offsets[i],
2213                                                offsets[i+1] - offsets[i]);
2214 #endif /* USE_FIXED */
2215                 }
2216             }
2217         }
2218         ch0 += ics->group_len[g] * 128;
2219         ch1 += ics->group_len[g] * 128;
2220     }
2221 }
2222
2223 /**
2224  * intensity stereo decoding; reference: 4.6.8.2.3
2225  *
2226  * @param   ms_present  Indicates mid/side stereo presence. [0] mask is all 0s;
2227  *                      [1] mask is decoded from bitstream; [2] mask is all 1s;
2228  *                      [3] reserved for scalable AAC
2229  */
2230 static void apply_intensity_stereo(AACContext *ac,
2231                                    ChannelElement *cpe, int ms_present)
2232 {
2233     const IndividualChannelStream *ics = &cpe->ch[1].ics;
2234     SingleChannelElement         *sce1 = &cpe->ch[1];
2235     INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2236     const uint16_t *offsets = ics->swb_offset;
2237     int g, group, i, idx = 0;
2238     int c;
2239     INTFLOAT scale;
2240     for (g = 0; g < ics->num_window_groups; g++) {
2241         for (i = 0; i < ics->max_sfb;) {
2242             if (sce1->band_type[idx] == INTENSITY_BT ||
2243                 sce1->band_type[idx] == INTENSITY_BT2) {
2244                 const int bt_run_end = sce1->band_type_run_end[idx];
2245                 for (; i < bt_run_end; i++, idx++) {
2246                     c = -1 + 2 * (sce1->band_type[idx] - 14);
2247                     if (ms_present)
2248                         c *= 1 - 2 * cpe->ms_mask[idx];
2249                     scale = c * sce1->sf[idx];
2250                     for (group = 0; group < ics->group_len[g]; group++)
2251 #if USE_FIXED
2252                         ac->subband_scale(coef1 + group * 128 + offsets[i],
2253                                       coef0 + group * 128 + offsets[i],
2254                                       scale,
2255                                       23,
2256                                       offsets[i + 1] - offsets[i] ,ac->avctx);
2257 #else
2258                         ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2259                                                     coef0 + group * 128 + offsets[i],
2260                                                     scale,
2261                                                     offsets[i + 1] - offsets[i]);
2262 #endif /* USE_FIXED */
2263                 }
2264             } else {
2265                 int bt_run_end = sce1->band_type_run_end[idx];
2266                 idx += bt_run_end - i;
2267                 i    = bt_run_end;
2268             }
2269         }
2270         coef0 += ics->group_len[g] * 128;
2271         coef1 += ics->group_len[g] * 128;
2272     }
2273 }
2274
2275 /**
2276  * Decode a channel_pair_element; reference: table 4.4.
2277  *
2278  * @return  Returns error status. 0 - OK, !0 - error
2279  */
2280 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2281 {
2282     int i, ret, common_window, ms_present = 0;
2283     int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2284
2285     common_window = eld_syntax || get_bits1(gb);
2286     if (common_window) {
2287         if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2288             return AVERROR_INVALIDDATA;
2289         i = cpe->ch[1].ics.use_kb_window[0];
2290         cpe->ch[1].ics = cpe->ch[0].ics;
2291         cpe->ch[1].ics.use_kb_window[1] = i;
2292         if (cpe->ch[1].ics.predictor_present &&
2293             (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2294             if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2295                 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2296         ms_present = get_bits(gb, 2);
2297         if (ms_present == 3) {
2298             av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2299             return AVERROR_INVALIDDATA;
2300         } else if (ms_present)
2301             decode_mid_side_stereo(cpe, gb, ms_present);
2302     }
2303     if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2304         return ret;
2305     if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2306         return ret;
2307
2308     if (common_window) {
2309         if (ms_present)
2310             apply_mid_side_stereo(ac, cpe);
2311         if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2312             apply_prediction(ac, &cpe->ch[0]);
2313             apply_prediction(ac, &cpe->ch[1]);
2314         }
2315     }
2316
2317     apply_intensity_stereo(ac, cpe, ms_present);
2318     return 0;
2319 }
2320
2321 static const float cce_scale[] = {
2322     1.09050773266525765921, //2^(1/8)
2323     1.18920711500272106672, //2^(1/4)
2324     M_SQRT2,
2325     2,
2326 };
2327
2328 /**
2329  * Decode coupling_channel_element; reference: table 4.8.
2330  *
2331  * @return  Returns error status. 0 - OK, !0 - error
2332  */
2333 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2334 {
2335     int num_gain = 0;
2336     int c, g, sfb, ret;
2337     int sign;
2338     INTFLOAT scale;
2339     SingleChannelElement *sce = &che->ch[0];
2340     ChannelCoupling     *coup = &che->coup;
2341
2342     coup->coupling_point = 2 * get_bits1(gb);
2343     coup->num_coupled = get_bits(gb, 3);
2344     for (c = 0; c <= coup->num_coupled; c++) {
2345         num_gain++;
2346         coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2347         coup->id_select[c] = get_bits(gb, 4);
2348         if (coup->type[c] == TYPE_CPE) {
2349             coup->ch_select[c] = get_bits(gb, 2);
2350             if (coup->ch_select[c] == 3)
2351                 num_gain++;
2352         } else
2353             coup->ch_select[c] = 2;
2354     }
2355     coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2356
2357     sign  = get_bits(gb, 1);
2358 #if USE_FIXED
2359     scale = get_bits(gb, 2);
2360 #else
2361     scale = cce_scale[get_bits(gb, 2)];
2362 #endif
2363
2364     if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2365         return ret;
2366
2367     for (c = 0; c < num_gain; c++) {
2368         int idx  = 0;
2369         int cge  = 1;
2370         int gain = 0;
2371         INTFLOAT gain_cache = FIXR10(1.);
2372         if (c) {
2373             cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2374             gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2375             gain_cache = GET_GAIN(scale, gain);
2376 #if USE_FIXED
2377             if ((abs(gain_cache)-1024) >> 3 > 30)
2378                 return AVERROR(ERANGE);
2379 #endif
2380         }
2381         if (coup->coupling_point == AFTER_IMDCT) {
2382             coup->gain[c][0] = gain_cache;
2383         } else {
2384             for (g = 0; g < sce->ics.num_window_groups; g++) {
2385                 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2386                     if (sce->band_type[idx] != ZERO_BT) {
2387                         if (!cge) {
2388                             int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2389                             if (t) {
2390                                 int s = 1;
2391                                 t = gain += t;
2392                                 if (sign) {
2393                                     s  -= 2 * (t & 0x1);
2394                                     t >>= 1;
2395                                 }
2396                                 gain_cache = GET_GAIN(scale, t) * s;
2397 #if USE_FIXED
2398                                 if ((abs(gain_cache)-1024) >> 3 > 30)
2399                                     return AVERROR(ERANGE);
2400 #endif
2401                             }
2402                         }
2403                         coup->gain[c][idx] = gain_cache;
2404                     }
2405                 }
2406             }
2407         }
2408     }
2409     return 0;
2410 }
2411
2412 /**
2413  * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2414  *
2415  * @return  Returns number of bytes consumed.
2416  */
2417 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2418                                          GetBitContext *gb)
2419 {
2420     int i;
2421     int num_excl_chan = 0;
2422
2423     do {
2424         for (i = 0; i < 7; i++)
2425             che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2426     } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2427
2428     return num_excl_chan / 7;
2429 }
2430
2431 /**
2432  * Decode dynamic range information; reference: table 4.52.
2433  *
2434  * @return  Returns number of bytes consumed.
2435  */
2436 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2437                                 GetBitContext *gb)
2438 {
2439     int n             = 1;
2440     int drc_num_bands = 1;
2441     int i;
2442
2443     /* pce_tag_present? */
2444     if (get_bits1(gb)) {
2445         che_drc->pce_instance_tag  = get_bits(gb, 4);
2446         skip_bits(gb, 4); // tag_reserved_bits
2447         n++;
2448     }
2449
2450     /* excluded_chns_present? */
2451     if (get_bits1(gb)) {
2452         n += decode_drc_channel_exclusions(che_drc, gb);
2453     }
2454
2455     /* drc_bands_present? */
2456     if (get_bits1(gb)) {
2457         che_drc->band_incr            = get_bits(gb, 4);
2458         che_drc->interpolation_scheme = get_bits(gb, 4);
2459         n++;
2460         drc_num_bands += che_drc->band_incr;
2461         for (i = 0; i < drc_num_bands; i++) {
2462             che_drc->band_top[i] = get_bits(gb, 8);
2463             n++;
2464         }
2465     }
2466
2467     /* prog_ref_level_present? */
2468     if (get_bits1(gb)) {
2469         che_drc->prog_ref_level = get_bits(gb, 7);
2470         skip_bits1(gb); // prog_ref_level_reserved_bits
2471         n++;
2472     }
2473
2474     for (i = 0; i < drc_num_bands; i++) {
2475         che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2476         che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2477         n++;
2478     }
2479
2480     return n;
2481 }
2482
2483 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2484     uint8_t buf[256];
2485     int i, major, minor;
2486
2487     if (len < 13+7*8)
2488         goto unknown;
2489
2490     get_bits(gb, 13); len -= 13;
2491
2492     for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2493         buf[i] = get_bits(gb, 8);
2494
2495     buf[i] = 0;
2496     if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2497         av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2498
2499     if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2500         ac->avctx->internal->skip_samples = 1024;
2501     }
2502
2503 unknown:
2504     skip_bits_long(gb, len);
2505
2506     return 0;
2507 }
2508
2509 /**
2510  * Decode extension data (incomplete); reference: table 4.51.
2511  *
2512  * @param   cnt length of TYPE_FIL syntactic element in bytes
2513  *
2514  * @return Returns number of bytes consumed
2515  */
2516 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2517                                     ChannelElement *che, enum RawDataBlockType elem_type)
2518 {
2519     int crc_flag = 0;
2520     int res = cnt;
2521     int type = get_bits(gb, 4);
2522
2523     if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2524         av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2525
2526     switch (type) { // extension type
2527     case EXT_SBR_DATA_CRC:
2528         crc_flag++;
2529     case EXT_SBR_DATA:
2530         if (!che) {
2531             av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2532             return res;
2533         } else if (ac->oc[1].m4ac.frame_length_short) {
2534             if (!ac->warned_960_sbr)
2535               avpriv_report_missing_feature(ac->avctx,
2536                                             "SBR with 960 frame length");
2537             ac->warned_960_sbr = 1;
2538             skip_bits_long(gb, 8 * cnt - 4);
2539             return res;
2540         } else if (!ac->oc[1].m4ac.sbr) {
2541             av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2542             skip_bits_long(gb, 8 * cnt - 4);
2543             return res;
2544         } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2545             av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2546             skip_bits_long(gb, 8 * cnt - 4);
2547             return res;
2548         } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2549             ac->oc[1].m4ac.sbr = 1;
2550             ac->oc[1].m4ac.ps = 1;
2551             ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2552             output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2553                              ac->oc[1].status, 1);
2554         } else {
2555             ac->oc[1].m4ac.sbr = 1;
2556             ac->avctx->profile = FF_PROFILE_AAC_HE;
2557         }
2558         res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2559         break;
2560     case EXT_DYNAMIC_RANGE:
2561         res = decode_dynamic_range(&ac->che_drc, gb);
2562         break;
2563     case EXT_FILL:
2564         decode_fill(ac, gb, 8 * cnt - 4);
2565         break;
2566     case EXT_FILL_DATA:
2567     case EXT_DATA_ELEMENT:
2568     default:
2569         skip_bits_long(gb, 8 * cnt - 4);
2570         break;
2571     };
2572     return res;
2573 }
2574
2575 /**
2576  * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2577  *
2578  * @param   decode  1 if tool is used normally, 0 if tool is used in LTP.
2579  * @param   coef    spectral coefficients
2580  */
2581 static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns,
2582                       IndividualChannelStream *ics, int decode)
2583 {
2584     const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2585     int w, filt, m, i;
2586     int bottom, top, order, start, end, size, inc;
2587     INTFLOAT lpc[TNS_MAX_ORDER];
2588     INTFLOAT tmp[TNS_MAX_ORDER+1];
2589     UINTFLOAT *coef = coef_param;
2590
2591     if(!mmm)
2592         return;
2593
2594     for (w = 0; w < ics->num_windows; w++) {
2595         bottom = ics->num_swb;
2596         for (filt = 0; filt < tns->n_filt[w]; filt++) {
2597             top    = bottom;
2598             bottom = FFMAX(0, top - tns->length[w][filt]);
2599             order  = tns->order[w][filt];
2600             if (order == 0)
2601                 continue;
2602
2603             // tns_decode_coef
2604             AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
2605
2606             start = ics->swb_offset[FFMIN(bottom, mmm)];
2607             end   = ics->swb_offset[FFMIN(   top, mmm)];
2608             if ((size = end - start) <= 0)
2609                 continue;
2610             if (tns->direction[w][filt]) {
2611                 inc = -1;
2612                 start = end - 1;
2613             } else {
2614                 inc = 1;
2615             }
2616             start += w * 128;
2617
2618             if (decode) {
2619                 // ar filter
2620                 for (m = 0; m < size; m++, start += inc)
2621                     for (i = 1; i <= FFMIN(m, order); i++)
2622                         coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]);
2623             } else {
2624                 // ma filter
2625                 for (m = 0; m < size; m++, start += inc) {
2626                     tmp[0] = coef[start];
2627                     for (i = 1; i <= FFMIN(m, order); i++)
2628                         coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
2629                     for (i = order; i > 0; i--)
2630                         tmp[i] = tmp[i - 1];
2631                 }
2632             }
2633         }
2634     }
2635 }
2636
2637 /**
2638  *  Apply windowing and MDCT to obtain the spectral
2639  *  coefficient from the predicted sample by LTP.
2640  */
2641 static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
2642                                    INTFLOAT *in, IndividualChannelStream *ics)
2643 {
2644     const INTFLOAT *lwindow      = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2645     const INTFLOAT *swindow      = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2646     const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2647     const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2648
2649     if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2650         ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
2651     } else {
2652         memset(in, 0, 448 * sizeof(*in));
2653         ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
2654     }
2655     if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2656         ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2657     } else {
2658         ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2659         memset(in + 1024 + 576, 0, 448 * sizeof(*in));
2660     }
2661     ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2662 }
2663
2664 /**
2665  * Apply the long term prediction
2666  */
2667 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2668 {
2669     const LongTermPrediction *ltp = &sce->ics.ltp;
2670     const uint16_t *offsets = sce->ics.swb_offset;
2671     int i, sfb;
2672
2673     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2674         INTFLOAT *predTime = sce->ret;
2675         INTFLOAT *predFreq = ac->buf_mdct;
2676         int16_t num_samples = 2048;
2677
2678         if (ltp->lag < 1024)
2679             num_samples = ltp->lag + 1024;
2680         for (i = 0; i < num_samples; i++)
2681             predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
2682         memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
2683
2684         ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2685
2686         if (sce->tns.present)
2687             ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2688
2689         for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2690             if (ltp->used[sfb])
2691                 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2692                     sce->coeffs[i] += (UINTFLOAT)predFreq[i];
2693     }
2694 }
2695
2696 /**
2697  * Update the LTP buffer for next frame
2698  */
2699 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2700 {
2701     IndividualChannelStream *ics = &sce->ics;
2702     INTFLOAT *saved     = sce->saved;
2703     INTFLOAT *saved_ltp = sce->coeffs;
2704     const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2705     const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2706     int i;
2707
2708     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2709         memcpy(saved_ltp,       saved, 512 * sizeof(*saved_ltp));
2710         memset(saved_ltp + 576, 0,     448 * sizeof(*saved_ltp));
2711         ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2712
2713         for (i = 0; i < 64; i++)
2714             saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2715     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2716         memcpy(saved_ltp,       ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
2717         memset(saved_ltp + 576, 0,                  448 * sizeof(*saved_ltp));
2718         ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
2719
2720         for (i = 0; i < 64; i++)
2721             saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2722     } else { // LONG_STOP or ONLY_LONG
2723         ac->fdsp->vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
2724
2725         for (i = 0; i < 512; i++)
2726             saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
2727     }
2728
2729     memcpy(sce->ltp_state,      sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2730     memcpy(sce->ltp_state+1024, sce->ret,            1024 * sizeof(*sce->ltp_state));
2731     memcpy(sce->ltp_state+2048, saved_ltp,           1024 * sizeof(*sce->ltp_state));
2732 }
2733
2734 /**
2735  * Conduct IMDCT and windowing.
2736  */
2737 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2738 {
2739     IndividualChannelStream *ics = &sce->ics;
2740     INTFLOAT *in    = sce->coeffs;
2741     INTFLOAT *out   = sce->ret;
2742     INTFLOAT *saved = sce->saved;
2743     const INTFLOAT *swindow      = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2744     const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2745     const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2746     INTFLOAT *buf  = ac->buf_mdct;
2747     INTFLOAT *temp = ac->temp;
2748     int i;
2749
2750     // imdct
2751     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2752         for (i = 0; i < 1024; i += 128)
2753             ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2754     } else {
2755         ac->mdct.imdct_half(&ac->mdct, buf, in);
2756 #if USE_FIXED
2757         for (i=0; i<1024; i++)
2758           buf[i] = (buf[i] + 4LL) >> 3;
2759 #endif /* USE_FIXED */
2760     }
2761
2762     /* window overlapping
2763      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2764      * and long to short transitions are considered to be short to short
2765      * transitions. This leaves just two cases (long to long and short to short)
2766      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2767      */
2768     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2769             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2770         ac->fdsp->vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
2771     } else {
2772         memcpy(                         out,               saved,            448 * sizeof(*out));
2773
2774         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2775             ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448,      buf + 0*128, swindow_prev, 64);
2776             ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow,      64);
2777             ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow,      64);
2778             ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow,      64);
2779             ac->fdsp->vector_fmul_window(temp,              buf + 3*128 + 64, buf + 4*128, swindow,      64);
2780             memcpy(                     out + 448 + 4*128, temp, 64 * sizeof(*out));
2781         } else {
2782             ac->fdsp->vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
2783             memcpy(                     out + 576,         buf + 64,         448 * sizeof(*out));
2784         }
2785     }
2786
2787     // buffer update
2788     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2789         memcpy(                     saved,       temp + 64,         64 * sizeof(*saved));
2790         ac->fdsp->vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
2791         ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2792         ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2793         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(*saved));
2794     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2795         memcpy(                     saved,       buf + 512,        448 * sizeof(*saved));
2796         memcpy(                     saved + 448, buf + 7*128 + 64,  64 * sizeof(*saved));
2797     } else { // LONG_STOP or ONLY_LONG
2798         memcpy(                     saved,       buf + 512,        512 * sizeof(*saved));
2799     }
2800 }
2801
2802 /**
2803  * Conduct IMDCT and windowing.
2804  */
2805 static void imdct_and_windowing_960(AACContext *ac, SingleChannelElement *sce)
2806 {
2807 #if !USE_FIXED
2808     IndividualChannelStream *ics = &sce->ics;
2809     INTFLOAT *in    = sce->coeffs;
2810     INTFLOAT *out   = sce->ret;
2811     INTFLOAT *saved = sce->saved;
2812     const INTFLOAT *swindow      = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2813     const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_960) : AAC_RENAME(ff_sine_960);
2814     const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2815     INTFLOAT *buf  = ac->buf_mdct;
2816     INTFLOAT *temp = ac->temp;
2817     int i;
2818
2819     // imdct
2820     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2821         for (i = 0; i < 8; i++)
2822             ac->mdct120->imdct_half(ac->mdct120, buf + i * 120, in + i * 128, 1);
2823     } else {
2824         ac->mdct960->imdct_half(ac->mdct960, buf, in, 1);
2825     }
2826
2827     /* window overlapping
2828      * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2829      * and long to short transitions are considered to be short to short
2830      * transitions. This leaves just two cases (long to long and short to short)
2831      * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2832      */
2833
2834     if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2835         (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2836         ac->fdsp->vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 480);
2837     } else {
2838         memcpy(                          out,               saved,            420 * sizeof(*out));
2839
2840         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2841             ac->fdsp->vector_fmul_window(out + 420 + 0*120, saved + 420,      buf + 0*120, swindow_prev, 60);
2842             ac->fdsp->vector_fmul_window(out + 420 + 1*120, buf + 0*120 + 60, buf + 1*120, swindow,      60);
2843             ac->fdsp->vector_fmul_window(out + 420 + 2*120, buf + 1*120 + 60, buf + 2*120, swindow,      60);
2844             ac->fdsp->vector_fmul_window(out + 420 + 3*120, buf + 2*120 + 60, buf + 3*120, swindow,      60);
2845             ac->fdsp->vector_fmul_window(temp,              buf + 3*120 + 60, buf + 4*120, swindow,      60);
2846             memcpy(                      out + 420 + 4*120, temp, 60 * sizeof(*out));
2847         } else {
2848             ac->fdsp->vector_fmul_window(out + 420,         saved + 420,      buf,         swindow_prev, 60);
2849             memcpy(                      out + 540,         buf + 60,         420 * sizeof(*out));
2850         }
2851     }
2852
2853     // buffer update
2854     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2855         memcpy(                      saved,       temp + 60,         60 * sizeof(*saved));
2856         ac->fdsp->vector_fmul_window(saved + 60,  buf + 4*120 + 60, buf + 5*120, swindow, 60);
2857         ac->fdsp->vector_fmul_window(saved + 180, buf + 5*120 + 60, buf + 6*120, swindow, 60);
2858         ac->fdsp->vector_fmul_window(saved + 300, buf + 6*120 + 60, buf + 7*120, swindow, 60);
2859         memcpy(                      saved + 420, buf + 7*120 + 60,  60 * sizeof(*saved));
2860     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2861         memcpy(                      saved,       buf + 480,        420 * sizeof(*saved));
2862         memcpy(                      saved + 420, buf + 7*120 + 60,  60 * sizeof(*saved));
2863     } else { // LONG_STOP or ONLY_LONG
2864         memcpy(                      saved,       buf + 480,        480 * sizeof(*saved));
2865     }
2866 #endif
2867 }
2868 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2869 {
2870     IndividualChannelStream *ics = &sce->ics;
2871     INTFLOAT *in    = sce->coeffs;
2872     INTFLOAT *out   = sce->ret;
2873     INTFLOAT *saved = sce->saved;
2874     INTFLOAT *buf  = ac->buf_mdct;
2875 #if USE_FIXED
2876     int i;
2877 #endif /* USE_FIXED */
2878
2879     // imdct
2880     ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2881
2882 #if USE_FIXED
2883     for (i = 0; i < 1024; i++)
2884         buf[i] = (buf[i] + 2) >> 2;
2885 #endif /* USE_FIXED */
2886
2887     // window overlapping
2888     if (ics->use_kb_window[1]) {
2889         // AAC LD uses a low overlap sine window instead of a KBD window
2890         memcpy(out, saved, 192 * sizeof(*out));
2891         ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME(ff_sine_128), 64);
2892         memcpy(                     out + 320, buf + 64, 192 * sizeof(*out));
2893     } else {
2894         ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME(ff_sine_512), 256);
2895     }
2896
2897     // buffer update
2898     memcpy(saved, buf + 256, 256 * sizeof(*saved));
2899 }
2900
2901 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2902 {
2903     INTFLOAT *in    = sce->coeffs;
2904     INTFLOAT *out   = sce->ret;
2905     INTFLOAT *saved = sce->saved;
2906     INTFLOAT *buf  = ac->buf_mdct;
2907     int i;
2908     const int n  = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2909     const int n2 = n >> 1;
2910     const int n4 = n >> 2;
2911     const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
2912                                            AAC_RENAME(ff_aac_eld_window_512);
2913
2914     // Inverse transform, mapped to the conventional IMDCT by
2915     // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2916     // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2917     // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2918     // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2919     for (i = 0; i < n2; i+=2) {
2920         INTFLOAT temp;
2921         temp =  in[i    ]; in[i    ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2922         temp = -in[i + 1]; in[i + 1] =  in[n - 2 - i]; in[n - 2 - i] = temp;
2923     }
2924 #if !USE_FIXED
2925     if (n == 480)
2926         ac->mdct480->imdct_half(ac->mdct480, buf, in, 1);
2927     else
2928 #endif
2929         ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2930
2931 #if USE_FIXED
2932     for (i = 0; i < 1024; i++)
2933       buf[i] = (buf[i] + 1) >> 1;
2934 #endif /* USE_FIXED */
2935
2936     for (i = 0; i < n; i+=2) {
2937         buf[i] = -buf[i];
2938     }
2939     // Like with the regular IMDCT at this point we still have the middle half
2940     // of a transform but with even symmetry on the left and odd symmetry on
2941     // the right
2942
2943     // window overlapping
2944     // The spec says to use samples [0..511] but the reference decoder uses
2945     // samples [128..639].
2946     for (i = n4; i < n2; i ++) {
2947         out[i - n4] = AAC_MUL31(   buf[    n2 - 1 - i] , window[i       - n4]) +
2948                       AAC_MUL31( saved[        i + n2] , window[i +   n - n4]) +
2949                       AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
2950                       AAC_MUL31(-saved[  2*n + n2 + i] , window[i + 3*n - n4]);
2951     }
2952     for (i = 0; i < n2; i ++) {
2953         out[n4 + i] = AAC_MUL31(   buf[              i] , window[i + n2       - n4]) +
2954                       AAC_MUL31(-saved[      n - 1 - i] , window[i + n2 +   n - n4]) +
2955                       AAC_MUL31(-saved[          n + i] , window[i + n2 + 2*n - n4]) +
2956                       AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
2957     }
2958     for (i = 0; i < n4; i ++) {
2959         out[n2 + n4 + i] = AAC_MUL31(   buf[    i + n2] , window[i +   n - n4]) +
2960                            AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
2961                            AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
2962     }
2963
2964     // buffer update
2965     memmove(saved + n, saved, 2 * n * sizeof(*saved));
2966     memcpy( saved,       buf,     n * sizeof(*saved));
2967 }
2968
2969 /**
2970  * channel coupling transformation interface
2971  *
2972  * @param   apply_coupling_method   pointer to (in)dependent coupling function
2973  */
2974 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2975                                    enum RawDataBlockType type, int elem_id,
2976                                    enum CouplingPoint coupling_point,
2977                                    void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2978 {
2979     int i, c;
2980
2981     for (i = 0; i < MAX_ELEM_ID; i++) {
2982         ChannelElement *cce = ac->che[TYPE_CCE][i];
2983         int index = 0;
2984
2985         if (cce && cce->coup.coupling_point == coupling_point) {
2986             ChannelCoupling *coup = &cce->coup;
2987
2988             for (c = 0; c <= coup->num_coupled; c++) {
2989                 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2990                     if (coup->ch_select[c] != 1) {
2991                         apply_coupling_method(ac, &cc->ch[0], cce, index);
2992                         if (coup->ch_select[c] != 0)
2993                             index++;
2994                     }
2995                     if (coup->ch_select[c] != 2)
2996                         apply_coupling_method(ac, &cc->ch[1], cce, index++);
2997                 } else
2998                     index += 1 + (coup->ch_select[c] == 3);
2999             }
3000         }
3001     }
3002 }
3003
3004 /**
3005  * Convert spectral data to samples, applying all supported tools as appropriate.
3006  */
3007 static void spectral_to_sample(AACContext *ac, int samples)
3008 {
3009     int i, type;
3010     void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
3011     switch (ac->oc[1].m4ac.object_type) {
3012     case AOT_ER_AAC_LD:
3013         imdct_and_window = imdct_and_windowing_ld;
3014         break;
3015     case AOT_ER_AAC_ELD:
3016         imdct_and_window = imdct_and_windowing_eld;
3017         break;
3018     default:
3019         if (ac->oc[1].m4ac.frame_length_short)
3020             imdct_and_window = imdct_and_windowing_960;
3021         else
3022             imdct_and_window = ac->imdct_and_windowing;
3023     }
3024     for (type = 3; type >= 0; type--) {
3025         for (i = 0; i < MAX_ELEM_ID; i++) {
3026             ChannelElement *che = ac->che[type][i];
3027             if (che && che->present) {
3028                 if (type <= TYPE_CPE)
3029                     apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
3030                 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
3031                     if (che->ch[0].ics.predictor_present) {
3032                         if (che->ch[0].ics.ltp.present)
3033                             ac->apply_ltp(ac, &che->ch[0]);
3034                         if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
3035                             ac->apply_ltp(ac, &che->ch[1]);
3036                     }
3037                 }
3038                 if (che->ch[0].tns.present)
3039                     ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
3040                 if (che->ch[1].tns.present)
3041                     ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
3042                 if (type <= TYPE_CPE)
3043                     apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
3044                 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
3045                     imdct_and_window(ac, &che->ch[0]);
3046                     if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3047                         ac->update_ltp(ac, &che->ch[0]);
3048                     if (type == TYPE_CPE) {
3049                         imdct_and_window(ac, &che->ch[1]);
3050                         if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3051                             ac->update_ltp(ac, &che->ch[1]);
3052                     }
3053                     if (ac->oc[1].m4ac.sbr > 0) {
3054                         AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
3055                     }
3056                 }
3057                 if (type <= TYPE_CCE)
3058                     apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
3059
3060 #if USE_FIXED
3061                 {
3062                     int j;
3063                     /* preparation for resampler */
3064                     for(j = 0; j<samples; j++){
3065                         che->ch[0].ret[j] = (int32_t)av_clip64((int64_t)che->ch[0].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3066                         if(type == TYPE_CPE)
3067                             che->ch[1].ret[j] = (int32_t)av_clip64((int64_t)che->ch[1].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3068                     }
3069                 }
3070 #endif /* USE_FIXED */
3071                 che->present = 0;
3072             } else if (che) {
3073                 av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
3074             }
3075         }
3076     }
3077 }
3078
3079 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
3080 {
3081     int size;
3082     AACADTSHeaderInfo hdr_info;
3083     uint8_t layout_map[MAX_ELEM_ID*4][3];
3084     int layout_map_tags, ret;
3085
3086     size = ff_adts_header_parse(gb, &hdr_info);
3087     if (size > 0) {
3088         if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
3089             // This is 2 for "VLB " audio in NSV files.
3090             // See samples/nsv/vlb_audio.
3091             avpriv_report_missing_feature(ac->avctx,
3092                                           "More than one AAC RDB per ADTS frame");
3093             ac->warned_num_aac_frames = 1;
3094         }
3095         push_output_configuration(ac);
3096         if (hdr_info.chan_config) {
3097             ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
3098             if ((ret = set_default_channel_config(ac, ac->avctx,
3099                                                   layout_map,
3100                                                   &layout_map_tags,
3101                                                   hdr_info.chan_config)) < 0)
3102                 return ret;
3103             if ((ret = output_configure(ac, layout_map, layout_map_tags,
3104                                         FFMAX(ac->oc[1].status,
3105                                               OC_TRIAL_FRAME), 0)) < 0)
3106                 return ret;
3107         } else {
3108             ac->oc[1].m4ac.chan_config = 0;
3109             /**
3110              * dual mono frames in Japanese DTV can have chan_config 0
3111              * WITHOUT specifying PCE.
3112              *  thus, set dual mono as default.
3113              */
3114             if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
3115                 layout_map_tags = 2;
3116                 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
3117                 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
3118                 layout_map[0][1] = 0;
3119                 layout_map[1][1] = 1;
3120                 if (output_configure(ac, layout_map, layout_map_tags,
3121                                      OC_TRIAL_FRAME, 0))
3122                     return -7;
3123             }
3124         }
3125         ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
3126         ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
3127         ac->oc[1].m4ac.object_type     = hdr_info.object_type;
3128         ac->oc[1].m4ac.frame_length_short = 0;
3129         if (ac->oc[0].status != OC_LOCKED ||
3130             ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
3131             ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
3132             ac->oc[1].m4ac.sbr = -1;
3133             ac->oc[1].m4ac.ps  = -1;
3134         }
3135         if (!hdr_info.crc_absent)
3136             skip_bits(gb, 16);
3137     }
3138     return size;
3139 }
3140
3141 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
3142                                int *got_frame_ptr, GetBitContext *gb)
3143 {
3144     AACContext *ac = avctx->priv_data;
3145     const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
3146     ChannelElement *che;
3147     int err, i;
3148     int samples = m4ac->frame_length_short ? 960 : 1024;
3149     int chan_config = m4ac->chan_config;
3150     int aot = m4ac->object_type;
3151
3152     if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
3153         samples >>= 1;
3154
3155     ac->frame = data;
3156
3157     if ((err = frame_configure_elements(avctx)) < 0)
3158         return err;
3159
3160     // The FF_PROFILE_AAC_* defines are all object_type - 1
3161     // This may lead to an undefined profile being signaled
3162     ac->avctx->profile = aot - 1;
3163
3164     ac->tags_mapped = 0;
3165
3166     if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
3167         avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
3168                               chan_config);
3169         return AVERROR_INVALIDDATA;
3170     }
3171     for (i = 0; i < tags_per_config[chan_config]; i++) {
3172         const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
3173         const int elem_id   = aac_channel_layout_map[chan_config-1][i][1];
3174         if (!(che=get_che(ac, elem_type, elem_id))) {
3175             av_log(ac->avctx, AV_LOG_ERROR,
3176                    "channel element %d.%d is not allocated\n",
3177                    elem_type, elem_id);
3178             return AVERROR_INVALIDDATA;
3179         }
3180         che->present = 1;
3181         if (aot != AOT_ER_AAC_ELD)
3182             skip_bits(gb, 4);
3183         switch (elem_type) {
3184         case TYPE_SCE:
3185             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3186             break;
3187         case TYPE_CPE:
3188             err = decode_cpe(ac, gb, che);
3189             break;
3190         case TYPE_LFE:
3191             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3192             break;
3193         }
3194         if (err < 0)
3195             return err;
3196     }
3197
3198     spectral_to_sample(ac, samples);
3199
3200     if (!ac->frame->data[0] && samples) {
3201         av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3202         return AVERROR_INVALIDDATA;
3203     }
3204
3205     ac->frame->nb_samples = samples;
3206     ac->frame->sample_rate = avctx->sample_rate;
3207     *got_frame_ptr = 1;
3208
3209     skip_bits_long(gb, get_bits_left(gb));
3210     return 0;
3211 }
3212
3213 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
3214                                 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
3215 {
3216     AACContext *ac = avctx->priv_data;
3217     ChannelElement *che = NULL, *che_prev = NULL;
3218     enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
3219     int err, elem_id;
3220     int samples = 0, multiplier, audio_found = 0, pce_found = 0;
3221     int is_dmono, sce_count = 0;
3222     int payload_alignment;
3223     uint8_t che_presence[4][MAX_ELEM_ID] = {{0}};
3224
3225     ac->frame = data;
3226
3227     if (show_bits(gb, 12) == 0xfff) {
3228         if ((err = parse_adts_frame_header(ac, gb)) < 0) {
3229             av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
3230             goto fail;
3231         }
3232         if (ac->oc[1].m4ac.sampling_index > 12) {
3233             av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
3234             err = AVERROR_INVALIDDATA;
3235             goto fail;
3236         }
3237     }
3238
3239     if ((err = frame_configure_elements(avctx)) < 0)
3240         goto fail;
3241
3242     // The FF_PROFILE_AAC_* defines are all object_type - 1
3243     // This may lead to an undefined profile being signaled
3244     ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
3245
3246     payload_alignment = get_bits_count(gb);
3247     ac->tags_mapped = 0;
3248     // parse
3249     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
3250         elem_id = get_bits(gb, 4);
3251
3252         if (avctx->debug & FF_DEBUG_STARTCODE)
3253             av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
3254
3255         if (!avctx->channels && elem_type != TYPE_PCE) {
3256             err = AVERROR_INVALIDDATA;
3257             goto fail;
3258         }
3259
3260         if (elem_type < TYPE_DSE) {
3261             if (che_presence[elem_type][elem_id]) {
3262                 int error = che_presence[elem_type][elem_id] > 1;
3263                 av_log(ac->avctx, error ? AV_LOG_ERROR : AV_LOG_DEBUG, "channel element %d.%d duplicate\n",
3264                        elem_type, elem_id);
3265                 if (error) {
3266                     err = AVERROR_INVALIDDATA;
3267                     goto fail;
3268                 }
3269             }
3270             che_presence[elem_type][elem_id]++;
3271
3272             if (!(che=get_che(ac, elem_type, elem_id))) {
3273                 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
3274                        elem_type, elem_id);
3275                 err = AVERROR_INVALIDDATA;
3276                 goto fail;
3277             }
3278             samples = ac->oc[1].m4ac.frame_length_short ? 960 : 1024;
3279             che->present = 1;
3280         }
3281
3282         switch (elem_type) {
3283
3284         case TYPE_SCE:
3285             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3286             audio_found = 1;
3287             sce_count++;
3288             break;
3289
3290         case TYPE_CPE:
3291             err = decode_cpe(ac, gb, che);
3292             audio_found = 1;
3293             break;
3294
3295         case TYPE_CCE:
3296             err = decode_cce(ac, gb, che);
3297             break;
3298
3299         case TYPE_LFE:
3300             err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3301             audio_found = 1;
3302             break;
3303
3304         case TYPE_DSE:
3305             err = skip_data_stream_element(ac, gb);
3306             break;
3307
3308         case TYPE_PCE: {
3309             uint8_t layout_map[MAX_ELEM_ID*4][3] = {{0}};
3310             int tags;
3311
3312             int pushed = push_output_configuration(ac);
3313             if (pce_found && !pushed) {
3314                 err = AVERROR_INVALIDDATA;
3315                 goto fail;
3316             }
3317
3318             tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
3319                               payload_alignment);
3320             if (tags < 0) {
3321                 err = tags;
3322                 break;
3323             }
3324             if (pce_found) {
3325                 av_log(avctx, AV_LOG_ERROR,
3326                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
3327                 pop_output_configuration(ac);
3328             } else {
3329                 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
3330                 if (!err)
3331                     ac->oc[1].m4ac.chan_config = 0;
3332                 pce_found = 1;
3333             }
3334             break;
3335         }
3336
3337         case TYPE_FIL:
3338             if (elem_id == 15)
3339                 elem_id += get_bits(gb, 8) - 1;
3340             if (get_bits_left(gb) < 8 * elem_id) {
3341                     av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3342                     err = AVERROR_INVALIDDATA;
3343                     goto fail;
3344             }
3345             err = 0;
3346             while (elem_id > 0) {
3347                 int ret = decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
3348                 if (ret < 0) {
3349                     err = ret;
3350                     break;
3351                 }
3352                 elem_id -= ret;
3353             }
3354             break;
3355
3356         default:
3357             err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3358             break;
3359         }
3360
3361         if (elem_type < TYPE_DSE) {
3362             che_prev      = che;
3363             che_prev_type = elem_type;
3364         }
3365
3366         if (err)
3367             goto fail;
3368
3369         if (get_bits_left(gb) < 3) {
3370             av_log(avctx, AV_LOG_ERROR, overread_err);
3371             err = AVERROR_INVALIDDATA;
3372             goto fail;
3373         }
3374     }
3375
3376     if (!avctx->channels) {
3377         *got_frame_ptr = 0;
3378         return 0;
3379     }
3380
3381     multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3382     samples <<= multiplier;
3383
3384     spectral_to_sample(ac, samples);
3385
3386     if (ac->oc[1].status && audio_found) {
3387         avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3388         avctx->frame_size = samples;
3389         ac->oc[1].status = OC_LOCKED;
3390     }
3391
3392     if (multiplier)
3393         avctx->internal->skip_samples_multiplier = 2;
3394
3395     if (!ac->frame->data[0] && samples) {
3396         av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3397         err = AVERROR_INVALIDDATA;
3398         goto fail;
3399     }
3400
3401     if (samples) {
3402         ac->frame->nb_samples = samples;
3403         ac->frame->sample_rate = avctx->sample_rate;
3404     } else
3405         av_frame_unref(ac->frame);
3406     *got_frame_ptr = !!samples;
3407
3408     /* for dual-mono audio (SCE + SCE) */
3409     is_dmono = ac->dmono_mode && sce_count == 2 &&
3410                ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
3411     if (is_dmono) {
3412         if (ac->dmono_mode == 1)
3413             ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3414         else if (ac->dmono_mode == 2)
3415             ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3416     }
3417
3418     return 0;
3419 fail:
3420     pop_output_configuration(ac);
3421     return err;
3422 }
3423
3424 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3425                             int *got_frame_ptr, AVPacket *avpkt)
3426 {
3427     AACContext *ac = avctx->priv_data;
3428     const uint8_t *buf = avpkt->data;
3429     int buf_size = avpkt->size;
3430     GetBitContext gb;
3431     int buf_consumed;
3432     int buf_offset;
3433     int err;
3434     int new_extradata_size;
3435     const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3436                                        AV_PKT_DATA_NEW_EXTRADATA,
3437                                        &new_extradata_size);
3438     int jp_dualmono_size;
3439     const uint8_t *jp_dualmono   = av_packet_get_side_data(avpkt,
3440                                        AV_PKT_DATA_JP_DUALMONO,
3441                                        &jp_dualmono_size);
3442
3443     if (new_extradata) {
3444         /* discard previous configuration */
3445         ac->oc[1].status = OC_NONE;
3446         err = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3447                                            new_extradata,
3448                                            new_extradata_size * 8LL, 1);
3449         if (err < 0) {
3450             return err;
3451         }
3452     }
3453
3454     ac->dmono_mode = 0;
3455     if (jp_dualmono && jp_dualmono_size > 0)
3456         ac->dmono_mode =  1 + *jp_dualmono;
3457     if (ac->force_dmono_mode >= 0)
3458         ac->dmono_mode = ac->force_dmono_mode;
3459
3460     if (INT_MAX / 8 <= buf_size)
3461         return AVERROR_INVALIDDATA;
3462
3463     if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)
3464         return err;
3465
3466     switch (ac->oc[1].m4ac.object_type) {
3467     case AOT_ER_AAC_LC:
3468     case AOT_ER_AAC_LTP:
3469     case AOT_ER_AAC_LD:
3470     case AOT_ER_AAC_ELD:
3471         err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3472         break;
3473     default:
3474         err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3475     }
3476     if (err < 0)
3477         return err;
3478
3479     buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3480     for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3481         if (buf[buf_offset])
3482             break;
3483
3484     return buf_size > buf_offset ? buf_consumed : buf_size;
3485 }
3486
3487 static av_cold int aac_decode_close(AVCodecContext *avctx)
3488 {
3489     AACContext *ac = avctx->priv_data;
3490     int i, type;
3491
3492     for (i = 0; i < MAX_ELEM_ID; i++) {
3493         for (type = 0; type < 4; type++) {
3494             if (ac->che[type][i])
3495                 AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][i]->sbr);
3496             av_freep(&ac->che[type][i]);
3497         }
3498     }
3499
3500     ff_mdct_end(&ac->mdct);
3501     ff_mdct_end(&ac->mdct_small);
3502     ff_mdct_end(&ac->mdct_ld);
3503     ff_mdct_end(&ac->mdct_ltp);
3504 #if !USE_FIXED
3505     ff_mdct15_uninit(&ac->mdct120);
3506     ff_mdct15_uninit(&ac->mdct480);
3507     ff_mdct15_uninit(&ac->mdct960);
3508 #endif
3509     av_freep(&ac->fdsp);
3510     return 0;
3511 }
3512
3513 static void aacdec_init(AACContext *c)
3514 {
3515     c->imdct_and_windowing                      = imdct_and_windowing;
3516     c->apply_ltp                                = apply_ltp;
3517     c->apply_tns                                = apply_tns;
3518     c->windowing_and_mdct_ltp                   = windowing_and_mdct_ltp;
3519     c->update_ltp                               = update_ltp;
3520 #if USE_FIXED
3521     c->vector_pow43                             = vector_pow43;
3522     c->subband_scale                            = subband_scale;
3523 #endif
3524
3525 #if !USE_FIXED
3526     if(ARCH_MIPS)
3527         ff_aacdec_init_mips(c);
3528 #endif /* !USE_FIXED */
3529 }
3530 /**
3531  * AVOptions for Japanese DTV specific extensions (ADTS only)
3532  */
3533 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3534 static const AVOption options[] = {
3535     {"dual_mono_mode", "Select the channel to decode for dual mono",
3536      offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3537      AACDEC_FLAGS, "dual_mono_mode"},
3538
3539     {"auto", "autoselection",            0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3540     {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3541     {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3542     {"both", "Select both channels",     0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3543
3544     {NULL},
3545 };
3546
3547 static const AVClass aac_decoder_class = {
3548     .class_name = "AAC decoder",
3549     .item_name  = av_default_item_name,
3550     .option     = options,
3551     .version    = LIBAVUTIL_VERSION_INT,
3552 };