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