3 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
7 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8 * Copyright (c) 2010 Janne Grunau <janne-ffmpeg@jannau.net>
10 * This file is part of Libav.
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.
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.
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
30 * @author Oded Shimon ( ods15 ods15 dyndns org )
31 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
38 * N (code in SoC repo) gain control
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
48 * Y frequency domain prediction
49 * Y Perceptual Noise Substitution
51 * N Scalable Inverse AAC Quantization
52 * N Frequency Selective Switch
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
61 * N Silence Compression
64 * N Structured Audio tools
65 * N Structured Audio Sample Bank Format
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)
75 * N Direct Stream Transfer
77 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
88 #include "fmtconvert.h"
95 #include "aacdectab.h"
96 #include "cbrt_tablegen.h"
99 #include "mpeg4audio.h"
100 #include "aacadtsdec.h"
101 #include "libavutil/intfloat.h"
109 # include "arm/aac.h"
112 static VLC vlc_scalefactors;
113 static VLC vlc_spectral[11];
115 static const char overread_err[] = "Input buffer exhausted before END element found\n";
117 static int count_channels(uint8_t (*layout)[3], int tags)
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);
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.
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
139 * @return Returns error status. 0 - OK, !0 - error
141 static av_cold int che_configure(AACContext *ac,
142 enum ChannelPosition che_pos,
143 int type, int id, int *channels)
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);
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;
159 if (ac->che[type][id])
160 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
161 av_freep(&ac->che[type][id]);
166 struct elem_to_channel {
167 uint64_t av_position;
170 uint8_t aac_position;
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)
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 };
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 };
193 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos, int *current) {
194 int num_pos_channels = 0;
198 for (i = *current; i < tags; i++) {
199 if (layout_map[i][2] != pos)
201 if (layout_map[i][0] == TYPE_CPE) {
203 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
209 num_pos_channels += 2;
217 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
220 return num_pos_channels;
223 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
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;
230 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
235 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
236 if (num_front_channels < 0)
239 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
240 if (num_side_channels < 0)
243 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
244 if (num_back_channels < 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 };
253 num_front_channels--;
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,
260 num_front_channels -= 2;
262 if (num_front_channels >= 2) {
263 i += assign_pair(e2c_vec, layout_map, i, tags,
267 num_front_channels -= 2;
269 while (num_front_channels >= 2) {
270 i += assign_pair(e2c_vec, layout_map, i, tags,
274 num_front_channels -= 2;
277 if (num_side_channels >= 2) {
278 i += assign_pair(e2c_vec, layout_map, i, tags,
282 num_side_channels -= 2;
284 while (num_side_channels >= 2) {
285 i += assign_pair(e2c_vec, layout_map, i, tags,
289 num_side_channels -= 2;
292 while (num_back_channels >= 4) {
293 i += assign_pair(e2c_vec, layout_map, i, tags,
297 num_back_channels -= 2;
299 if (num_back_channels >= 2) {
300 i += assign_pair(e2c_vec, layout_map, i, tags,
304 num_back_channels -= 2;
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 };
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 };
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 };
327 // Must choose a stable sort
328 total_non_cc_elements = n = i;
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]);
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;
354 * Configure output channel order based on the current program configuration element.
356 * @return Returns error status. 0 - OK, !0 - error
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)
362 AVCodecContext *avctx = ac->avctx;
363 int i, channels = 0, ret;
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;
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);
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;
395 * Set up channel positions based on a default channel configuration
396 * as specified in table 1.17.
398 * @return Returns error status. 0 - OK, !0 - error
400 static av_cold int set_default_channel_config(AVCodecContext *avctx,
401 uint8_t (*layout_map)[3],
405 if (channel_config < 1 || channel_config > 7) {
406 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
410 *tags = tags_per_config[channel_config];
411 memcpy(layout_map, aac_channel_layout_map[channel_config-1], *tags * sizeof(*layout_map));
415 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
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];
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];
426 if (set_default_channel_config(ac->avctx, layout_map, &layout_map_tags,
429 if (output_configure(ac, layout_map, layout_map_tags,
430 2, OC_TRIAL_FRAME) < 0)
433 ac->m4ac.chan_config = 2;
435 // For indexed channel configurations map the channels solely based on position.
436 switch (ac->m4ac.chan_config) {
438 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
440 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
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)) {
448 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
451 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
453 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
456 if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
458 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
462 if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
464 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
465 } else if (ac->m4ac.chan_config == 2) {
469 if (!ac->tags_mapped && type == TYPE_SCE) {
471 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
479 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
481 * @param type speaker type/position for these channels
483 static void decode_channel_map(uint8_t layout_map[][3],
484 enum ChannelPosition type,
485 GetBitContext *gb, int n)
488 enum RawDataBlockType syn_ele;
490 case AAC_CHANNEL_FRONT:
491 case AAC_CHANNEL_BACK:
492 case AAC_CHANNEL_SIDE:
493 syn_ele = get_bits1(gb);
499 case AAC_CHANNEL_LFE:
503 layout_map[0][0] = syn_ele;
504 layout_map[0][1] = get_bits(gb, 4);
505 layout_map[0][2] = type;
511 * Decode program configuration element; reference: table 4.2.
513 * @return Returns error status. 0 - OK, !0 - error
515 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
516 uint8_t (*layout_map)[3],
519 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
523 skip_bits(gb, 2); // object_type
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");
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);
537 skip_bits(gb, 4); // mono_mixdown_tag
539 skip_bits(gb, 4); // stereo_mixdown_tag
542 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
544 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
546 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
548 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
550 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
553 skip_bits_long(gb, 4 * num_assoc_data);
555 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
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);
566 skip_bits_long(gb, comment_len);
571 * Decode GA "General Audio" specific configuration; reference: table 4.1.
573 * @param ac pointer to AACContext, may be null
574 * @param avctx pointer to AVCCodecContext, used for logging
576 * @return Returns error status. 0 - OK, !0 - error
578 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
580 MPEG4AudioConfig *m4ac,
583 int extension_flag, ret;
584 uint8_t layout_map[MAX_ELEM_ID*4][3];
587 if (get_bits1(gb)) { // frameLengthFlag
588 av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
592 if (get_bits1(gb)) // dependsOnCoreCoder
593 skip_bits(gb, 14); // coreCoderDelay
594 extension_flag = get_bits1(gb);
596 if (m4ac->object_type == AOT_AAC_SCALABLE ||
597 m4ac->object_type == AOT_ER_AAC_SCALABLE)
598 skip_bits(gb, 3); // layerNr
600 if (channel_config == 0) {
601 skip_bits(gb, 4); // element_instance_tag
602 tags = decode_pce(avctx, m4ac, layout_map, gb);
606 if ((ret = set_default_channel_config(avctx, layout_map, &tags, channel_config)))
610 if (count_channels(layout_map, tags) > 1) {
612 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
615 if (ac && (ret = output_configure(ac, layout_map, tags,
616 channel_config, OC_GLOBAL_HDR)))
619 if (extension_flag) {
620 switch (m4ac->object_type) {
622 skip_bits(gb, 5); // numOfSubFrame
623 skip_bits(gb, 11); // layer_length
627 case AOT_ER_AAC_SCALABLE:
629 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
630 * aacScalefactorDataResilienceFlag
631 * aacSpectralDataResilienceFlag
635 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
641 * Decode audio specific configuration; reference: table 1.13.
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
650 * @return Returns error status or number of consumed bits. <0 - error
652 static int decode_audio_specific_config(AACContext *ac,
653 AVCodecContext *avctx,
654 MPEG4AudioConfig *m4ac,
655 const uint8_t *data, int bit_size,
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");
666 init_get_bits(&gb, data, bit_size);
668 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
670 if (m4ac->sampling_index > 12) {
671 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
675 skip_bits_long(&gb, i);
677 switch (m4ac->object_type) {
681 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
685 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
686 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
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);
694 return get_bits_count(&gb);
698 * linear congruential pseudorandom number generator
700 * @param previous_val pointer to the current state of the generator
702 * @return Returns a 32-bit pseudorandom integer
704 static av_always_inline int lcg_random(int previous_val)
706 return previous_val * 1664525 + 1013904223;
709 static av_always_inline void reset_predict_state(PredictorState *ps)
719 static void reset_all_predictors(PredictorState *ps)
722 for (i = 0; i < MAX_PREDICTORS; i++)
723 reset_predict_state(&ps[i]);
726 static int sample_rate_idx (int rate)
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;
742 static void reset_predictor_group(PredictorState *ps, int group_num)
745 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
746 reset_predict_state(&ps[i]);
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]), \
755 static av_cold int aac_decode_init(AVCodecContext *avctx)
757 AACContext *ac = avctx->priv_data;
758 float output_scale_factor;
761 ac->m4ac.sample_rate = avctx->sample_rate;
763 if (avctx->extradata_size > 0) {
764 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
766 avctx->extradata_size*8, 1) < 0)
770 uint8_t layout_map[MAX_ELEM_ID*4][3];
773 sr = sample_rate_idx(avctx->sample_rate);
774 ac->m4ac.sampling_index = sr;
775 ac->m4ac.channels = avctx->channels;
779 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
780 if (ff_mpeg4audio_channels[i] == avctx->channels)
782 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
785 ac->m4ac.chan_config = i;
787 if (ac->m4ac.chan_config) {
788 int ret = set_default_channel_config(avctx, layout_map,
789 &layout_map_tags, ac->m4ac.chan_config);
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;
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;
802 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
803 output_scale_factor = 1.0;
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);
820 ff_dsputil_init(&ac->dsp, avctx);
821 ff_fmt_convert_init(&ac->fmt_conv, avctx);
823 ac->random_state = 0x1f2e3d4c;
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]),
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);
843 avcodec_get_frame_defaults(&ac->frame);
844 avctx->coded_frame = &ac->frame;
850 * Skip data_stream_element; reference: table 4.10.
852 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
854 int byte_align = get_bits1(gb);
855 int count = get_bits(gb, 8);
857 count += get_bits(gb, 8);
861 if (get_bits_left(gb) < 8 * count) {
862 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
865 skip_bits_long(gb, 8 * count);
869 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
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");
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);
887 * Decode Long Term Prediction data; reference: table 4.xx.
889 static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
890 GetBitContext *gb, uint8_t max_sfb)
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);
901 * Decode Individual Channel Stream info; reference: table 4.6.
903 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
907 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
908 return AVERROR_INVALIDDATA;
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) {
918 ics->max_sfb = get_bits(gb, 4);
919 for (i = 0; i < 7; i++) {
921 ics->group_len[ics->num_window_groups - 1]++;
923 ics->num_window_groups++;
924 ics->group_len[ics->num_window_groups - 1] = 1;
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;
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;
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;
949 if ((ics->ltp.present = get_bits(gb, 1)))
950 decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
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;
966 * Decode band types (section_data payload); reference: table 4.46.
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
971 * @return Returns error status. 0 - OK, !0 - error
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)
978 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
979 for (g = 0; g < ics->num_window_groups; g++) {
981 while (k < ics->max_sfb) {
982 uint8_t sect_end = k;
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");
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);
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);
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;
1013 * Decode scalefactors; reference: table 4.47.
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
1020 * @return Returns error status. 0 - OK, !0 - error
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])
1029 int offset[3] = { global_gain, global_gain - 90, 0 };
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++)
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);
1048 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
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;
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);
1063 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
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]);
1073 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1082 * Decode pulse data; reference: table 4.7.
1084 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1085 const uint16_t *swb_offset, int num_swb)
1088 pulse->num_pulse = get_bits(gb, 2) + 1;
1089 pulse_swb = get_bits(gb, 6);
1090 if (pulse_swb >= num_swb)
1092 pulse->pos[0] = swb_offset[pulse_swb];
1093 pulse->pos[0] += get_bits(gb, 5);
1094 if (pulse->pos[0] > 1023)
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)
1101 pulse->amp[i] = get_bits(gb, 4);
1107 * Decode Temporal Noise Shaping data; reference: table 4.48.
1109 * @return Returns error status. 0 - OK, !0 - error
1111 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1112 GetBitContext *gb, const IndividualChannelStream *ics)
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);
1121 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1123 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
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;
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;
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)];
1147 * Decode Mid/Side data; reference: table 4.54.
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
1153 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
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]));
1166 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1170 *dst++ = v[idx & 15] * s;
1171 *dst++ = v[idx>>4 & 15] * s;
1177 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
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;
1190 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1191 unsigned sign, const float *scale)
1193 union av_intfloat32 s0, s1;
1195 s0.f = s1.f = *scale;
1196 s0.i ^= sign >> 1 << 31;
1199 *dst++ = v[idx & 15] * s0.f;
1200 *dst++ = v[idx>>4 & 15] * s1.f;
1207 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1208 unsigned sign, const float *scale)
1210 unsigned nz = idx >> 12;
1211 union av_intfloat32 s = { .f = *scale };
1212 union av_intfloat32 t;
1214 t.i = s.i ^ (sign & 1U<<31);
1215 *dst++ = v[idx & 3] * t.f;
1217 sign <<= nz & 1; nz >>= 1;
1218 t.i = s.i ^ (sign & 1U<<31);
1219 *dst++ = v[idx>>2 & 3] * t.f;
1221 sign <<= nz & 1; nz >>= 1;
1222 t.i = s.i ^ (sign & 1U<<31);
1223 *dst++ = v[idx>>4 & 3] * t.f;
1225 sign <<= nz & 1; nz >>= 1;
1226 t.i = s.i ^ (sign & 1U<<31);
1227 *dst++ = v[idx>>6 & 3] * t.f;
1234 * Decode spectral data; reference: table 4.50.
1235 * Dequantize and scale spectral data; reference: 4.6.3.3.
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
1243 * @return Returns error status. 0 - OK, !0 - error
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])
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;
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]));
1259 for (g = 0; g < ics->num_window_groups; g++) {
1260 unsigned g_len = ics->group_len[g];
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];
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));
1272 } else if (cbt_m1 == NOISE_BT - 1) {
1273 for (group = 0; group < g_len; group++, cfo+=128) {
1277 for (k = 0; k < off_len; k++) {
1278 ac->random_state = lcg_random(ac->random_state);
1279 cfo[k] = ac->random_state;
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);
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);
1292 switch (cbt_m1 >> 1) {
1294 for (group = 0; group < g_len; group++, cfo+=128) {
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);
1311 for (group = 0; group < g_len; group++, cfo+=128) {
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);
1333 for (group = 0; group < g_len; group++, cfo+=128) {
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);
1351 for (group = 0; group < g_len; group++, cfo+=128) {
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);
1373 for (group = 0; group < g_len; group++, cfo+=128) {
1375 uint32_t *icf = (uint32_t *) cf;
1385 UPDATE_CACHE(re, gb);
1386 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1394 cb_idx = cb_vector_idx[code];
1397 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1398 LAST_SKIP_BITS(re, gb, nnz);
1400 for (j = 0; j < 2; j++) {
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);
1411 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1415 SKIP_BITS(re, gb, b + 1);
1417 n = (1 << b) + SHOW_UBITS(re, gb, b);
1418 LAST_SKIP_BITS(re, gb, b);
1419 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1422 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1423 *icf++ = (bits & 1U<<31) | v;
1430 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1434 CLOSE_READER(re, gb);
1440 if (pulse_present) {
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])
1446 if (band_type[idx] != NOISE_BT && sf[idx]) {
1447 float ico = -pulse->amp[i];
1450 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1452 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1459 static av_always_inline float flt16_round(float pf)
1461 union av_intfloat32 tmp;
1463 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1467 static av_always_inline float flt16_even(float pf)
1469 union av_intfloat32 tmp;
1471 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1475 static av_always_inline float flt16_trunc(float pf)
1477 union av_intfloat32 pun;
1479 pun.i &= 0xFFFF0000U;
1483 static av_always_inline void predict(PredictorState *ps, float *coef,
1486 const float a = 0.953125; // 61.0 / 64
1487 const float alpha = 0.90625; // 29.0 / 32
1491 float r0 = ps->r0, r1 = ps->r1;
1492 float cor0 = ps->cor0, cor1 = ps->cor1;
1493 float var0 = ps->var0, var1 = ps->var1;
1495 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1496 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1498 pv = flt16_round(k1 * r0 + k2 * r1);
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));
1510 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1511 ps->r0 = flt16_trunc(a * e0);
1515 * Apply AAC-Main style frequency domain prediction.
1517 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1521 if (!sce->ics.predictor_initialized) {
1522 reset_all_predictors(sce->predictor_state);
1523 sce->ics.predictor_initialized = 1;
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]);
1533 if (sce->ics.predictor_reset_group)
1534 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1536 reset_all_predictors(sce->predictor_state);
1540 * Decode an individual_channel_stream payload; reference: table 4.44.
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.)
1545 * @return Returns error status. 0 - OK, !0 - error
1547 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1548 GetBitContext *gb, int common_window, int scale_flag)
1551 TemporalNoiseShaping *tns = &sce->tns;
1552 IndividualChannelStream *ics = &sce->ics;
1553 float *out = sce->coeffs;
1554 int global_gain, pulse_present = 0;
1556 /* This assignment is to silence a GCC warning about the variable being used
1557 * uninitialized when in fact it always is.
1559 pulse.num_pulse = 0;
1561 global_gain = get_bits(gb, 8);
1563 if (!common_window && !scale_flag) {
1564 if (decode_ics_info(ac, ics, gb) < 0)
1565 return AVERROR_INVALIDDATA;
1568 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1570 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
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");
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");
1585 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1587 if (get_bits1(gb)) {
1588 av_log_missing_feature(ac->avctx, "SSR", 1);
1593 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1596 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1597 apply_prediction(ac, sce);
1603 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1605 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
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]);
1623 ch0 += ics->group_len[g] * 128;
1624 ch1 += ics->group_len[g] * 128;
1629 * intensity stereo decoding; reference: 4.6.8.2.3
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
1635 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
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;
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);
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],
1657 offsets[i + 1] - offsets[i]);
1660 int bt_run_end = sce1->band_type_run_end[idx];
1661 idx += bt_run_end - i;
1665 coef0 += ics->group_len[g] * 128;
1666 coef1 += ics->group_len[g] * 128;
1671 * Decode a channel_pair_element; reference: table 4.4.
1673 * @return Returns error status. 0 - OK, !0 - error
1675 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1677 int i, ret, common_window, ms_present = 0;
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");
1693 } else if (ms_present)
1694 decode_mid_side_stereo(cpe, gb, ms_present);
1696 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1698 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1701 if (common_window) {
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]);
1710 apply_intensity_stereo(ac, cpe, ms_present);
1714 static const float cce_scale[] = {
1715 1.09050773266525765921, //2^(1/8)
1716 1.18920711500272106672, //2^(1/4)
1722 * Decode coupling_channel_element; reference: table 4.8.
1724 * @return Returns error status. 0 - OK, !0 - error
1726 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1732 SingleChannelElement *sce = &che->ch[0];
1733 ChannelCoupling *coup = &che->coup;
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++) {
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)
1746 coup->ch_select[c] = 2;
1748 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1750 sign = get_bits(gb, 1);
1751 scale = cce_scale[get_bits(gb, 2)];
1753 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1756 for (c = 0; c < num_gain; c++) {
1760 float gain_cache = 1.;
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);
1766 if (coup->coupling_point == AFTER_IMDCT) {
1767 coup->gain[c][0] = gain_cache;
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) {
1773 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1781 gain_cache = powf(scale, -t) * s;
1784 coup->gain[c][idx] = gain_cache;
1794 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1796 * @return Returns number of bytes consumed.
1798 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1802 int num_excl_chan = 0;
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));
1809 return num_excl_chan / 7;
1813 * Decode dynamic range information; reference: table 4.52.
1815 * @param cnt length of TYPE_FIL syntactic element in bytes
1817 * @return Returns number of bytes consumed.
1819 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1820 GetBitContext *gb, int cnt)
1823 int drc_num_bands = 1;
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
1833 /* excluded_chns_present? */
1834 if (get_bits1(gb)) {
1835 n += decode_drc_channel_exclusions(che_drc, gb);
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);
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);
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
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);
1867 * Decode extension data (incomplete); reference: table 4.51.
1869 * @param cnt length of TYPE_FIL syntactic element in bytes
1871 * @return Returns number of bytes consumed
1873 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1874 ChannelElement *che, enum RawDataBlockType elem_type)
1878 switch (get_bits(gb, 4)) { // extension type
1879 case EXT_SBR_DATA_CRC:
1883 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
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);
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);
1893 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1896 output_configure(ac, ac->layout_map, ac->layout_map_tags,
1897 ac->m4ac.chan_config, ac->output_configured);
1901 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1903 case EXT_DYNAMIC_RANGE:
1904 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1908 case EXT_DATA_ELEMENT:
1910 skip_bits_long(gb, 8 * cnt - 4);
1917 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1919 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1920 * @param coef spectral coefficients
1922 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1923 IndividualChannelStream *ics, int decode)
1925 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1927 int bottom, top, order, start, end, size, inc;
1928 float lpc[TNS_MAX_ORDER];
1929 float tmp[TNS_MAX_ORDER];
1931 for (w = 0; w < ics->num_windows; w++) {
1932 bottom = ics->num_swb;
1933 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1935 bottom = FFMAX(0, top - tns->length[w][filt]);
1936 order = tns->order[w][filt];
1941 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1943 start = ics->swb_offset[FFMIN(bottom, mmm)];
1944 end = ics->swb_offset[FFMIN( top, mmm)];
1945 if ((size = end - start) <= 0)
1947 if (tns->direction[w][filt]) {
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];
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];
1975 * Apply windowing and MDCT to obtain the spectral
1976 * coefficient from the predicted sample by LTP.
1978 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
1979 float *in, IndividualChannelStream *ics)
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;
1986 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
1987 ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
1989 memset(in, 0, 448 * sizeof(float));
1990 ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
1992 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
1993 ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
1995 ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
1996 memset(in + 1024 + 576, 0, 448 * sizeof(float));
1998 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2002 * Apply the long term prediction
2004 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2006 const LongTermPrediction *ltp = &sce->ics.ltp;
2007 const uint16_t *offsets = sce->ics.swb_offset;
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;
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));
2021 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2023 if (sce->tns.present)
2024 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2026 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2028 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2029 sce->coeffs[i] += predFreq[i];
2034 * Update the LTP buffer for next frame
2036 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
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;
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];
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));
2069 * Conduct IMDCT and windowing.
2071 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
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;
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);
2089 ac->mdct.imdct_half(&ac->mdct, buf, in);
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.
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);
2101 memcpy( out, saved, 448 * sizeof(float));
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));
2111 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2112 memcpy( out + 576, buf + 64, 448 * sizeof(float));
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));
2132 * Apply dependent channel coupling (applied before IMDCT).
2134 * @param index index into coupling gain array
2136 static void apply_dependent_coupling(AACContext *ac,
2137 SingleChannelElement *target,
2138 ChannelElement *cce, int index)
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");
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++) {
2157 dest[group * 128 + k] += gain * src[group * 128 + k];
2162 dest += ics->group_len[g] * 128;
2163 src += ics->group_len[g] * 128;
2168 * Apply independent channel coupling (applied after IMDCT).
2170 * @param index index into coupling gain array
2172 static void apply_independent_coupling(AACContext *ac,
2173 SingleChannelElement *target,
2174 ChannelElement *cce, int index)
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);
2182 for (i = 0; i < len; i++)
2183 dest[i] += gain * src[i];
2187 * channel coupling transformation interface
2189 * @param apply_coupling_method pointer to (in)dependent coupling function
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))
2198 for (i = 0; i < MAX_ELEM_ID; i++) {
2199 ChannelElement *cce = ac->che[TYPE_CCE][i];
2202 if (cce && cce->coup.coupling_point == coupling_point) {
2203 ChannelCoupling *coup = &cce->coup;
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)
2212 if (coup->ch_select[c] != 2)
2213 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2215 index += 1 + (coup->ch_select[c] == 3);
2222 * Convert spectral data to float samples, applying all supported tools as appropriate.
2224 static void spectral_to_sample(AACContext *ac)
2227 for (type = 3; type >= 0; type--) {
2228 for (i = 0; i < MAX_ELEM_ID; i++) {
2229 ChannelElement *che = ac->che[type][i];
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]);
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]);
2256 if (ac->m4ac.sbr > 0) {
2257 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2260 if (type <= TYPE_CCE)
2261 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2267 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2270 AACADTSHeaderInfo hdr_info;
2271 uint8_t layout_map[MAX_ELEM_ID*4][3];
2272 int layout_map_tags;
2274 size = avpriv_aac_parse_header(gb, &hdr_info);
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))
2281 if (output_configure(ac, layout_map, layout_map_tags,
2282 hdr_info.chan_config,
2283 FFMAX(ac->output_configured, OC_TRIAL_FRAME)))
2285 } else if (ac->output_configured != OC_LOCKED) {
2286 ac->m4ac.chan_config = 0;
2287 ac->output_configured = OC_NONE;
2289 if (ac->output_configured != OC_LOCKED) {
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;
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)
2302 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
2309 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2310 int *got_frame_ptr, GetBitContext *gb)
2312 AACContext *ac = avctx->priv_data;
2313 ChannelElement *che = NULL, *che_prev = NULL;
2314 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2316 int samples = 0, multiplier, audio_found = 0;
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");
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);
2329 ac->tags_mapped = 0;
2331 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2332 elem_id = get_bits(gb, 4);
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);
2343 switch (elem_type) {
2346 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2351 err = decode_cpe(ac, gb, che);
2356 err = decode_cce(ac, gb, che);
2360 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2365 err = skip_data_stream_element(ac, gb);
2369 uint8_t layout_map[MAX_ELEM_ID*4][3];
2371 tags = decode_pce(avctx, &ac->m4ac, layout_map, gb);
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");
2380 err = output_configure(ac, layout_map, tags, 0, OC_TRIAL_PCE);
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);
2392 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2393 err = 0; /* FIXME */
2397 err = -1; /* should not happen, but keeps compiler happy */
2402 elem_type_prev = elem_type;
2407 if (get_bits_left(gb) < 3) {
2408 av_log(avctx, AV_LOG_ERROR, overread_err);
2413 spectral_to_sample(ac);
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;
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");
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);
2435 ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2436 (const float **)ac->output_data,
2437 samples, avctx->channels);
2439 *(AVFrame *)data = ac->frame;
2441 *got_frame_ptr = !!samples;
2443 if (ac->output_configured && audio_found)
2444 ac->output_configured = OC_LOCKED;
2449 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2450 int *got_frame_ptr, AVPacket *avpkt)
2452 AACContext *ac = avctx->priv_data;
2453 const uint8_t *buf = avpkt->data;
2454 int buf_size = avpkt->size;
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);
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,
2474 avctx->extradata_size*8, 1) < 0)
2475 return AVERROR_INVALIDDATA;
2478 init_get_bits(&gb, buf, buf_size * 8);
2480 if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
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])
2488 return buf_size > buf_offset ? buf_consumed : buf_size;
2491 static av_cold int aac_decode_close(AVCodecContext *avctx)
2493 AACContext *ac = avctx->priv_data;
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]);
2504 ff_mdct_end(&ac->mdct);
2505 ff_mdct_end(&ac->mdct_small);
2506 ff_mdct_end(&ac->mdct_ltp);
2511 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2513 struct LATMContext {
2514 AACContext aac_ctx; ///< containing AACContext
2515 int initialized; ///< initilized after a valid extradata was seen
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
2523 static inline uint32_t latm_get_value(GetBitContext *b)
2525 int length = get_bits(b, 2);
2527 return get_bits_long(b, (length+1)*8);
2530 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2531 GetBitContext *gb, int asclen)
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;
2542 asclen = FFMIN(asclen, get_bits_left(gb));
2544 asclen = get_bits_left(gb);
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;
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);
2557 if (bits_consumed < 0)
2558 return AVERROR_INVALIDDATA;
2560 if (ac->m4ac.sample_rate != m4ac.sample_rate ||
2561 ac->m4ac.chan_config != m4ac.chan_config) {
2563 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2564 latmctx->initialized = 0;
2566 esize = (bits_consumed+7) / 8;
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);
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);
2579 skip_bits_long(gb, bits_consumed);
2581 return bits_consumed;
2584 static int read_stream_mux_config(struct LATMContext *latmctx,
2587 int ret, audio_mux_version = get_bits(gb, 1);
2589 latmctx->audio_mux_version_A = 0;
2590 if (audio_mux_version)
2591 latmctx->audio_mux_version_A = get_bits(gb, 1);
2593 if (!latmctx->audio_mux_version_A) {
2595 if (audio_mux_version)
2596 latm_get_value(gb); // taraFullness
2598 skip_bits(gb, 1); // allStreamSameTimeFraming
2599 skip_bits(gb, 6); // numSubFrames
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;
2607 // for each program (which there is only on in DVB)
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;
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)
2621 int ascLen = latm_get_value(gb);
2622 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2625 skip_bits_long(gb, ascLen);
2628 latmctx->frame_length_type = get_bits(gb, 3);
2629 switch (latmctx->frame_length_type) {
2631 skip_bits(gb, 8); // latmBufferFullness
2634 latmctx->frame_length = get_bits(gb, 9);
2639 skip_bits(gb, 6); // CELP frame length table index
2643 skip_bits(gb, 1); // HVXC frame length table index
2647 if (get_bits(gb, 1)) { // other data
2648 if (audio_mux_version) {
2649 latm_get_value(gb); // other_data_bits
2653 esc = get_bits(gb, 1);
2659 if (get_bits(gb, 1)) // crc present
2660 skip_bits(gb, 8); // config_crc
2666 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2670 if (ctx->frame_length_type == 0) {
2671 int mux_slot_length = 0;
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
2687 static int read_audio_mux_element(struct LATMContext *latmctx,
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)
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);
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;
2716 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2717 int *got_frame_ptr, AVPacket *avpkt)
2719 struct LATMContext *latmctx = avctx->priv_data;
2723 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2725 // check for LOAS sync word
2726 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2727 return AVERROR_INVALIDDATA;
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;
2734 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2737 if (!latmctx->initialized) {
2738 if (!avctx->extradata) {
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)
2746 latmctx->initialized = 1;
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 "
2754 return AVERROR_INVALIDDATA;
2757 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2763 av_cold static int latm_decode_init(AVCodecContext *avctx)
2765 struct LATMContext *latmctx = avctx->priv_data;
2766 int ret = aac_decode_init(avctx);
2768 if (avctx->extradata_size > 0)
2769 latmctx->initialized = !ret;
2775 AVCodec ff_aac_decoder = {
2777 .type = AVMEDIA_TYPE_AUDIO,
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
2787 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2788 .channel_layouts = aac_channel_layout,
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.
2796 AVCodec ff_aac_latm_decoder = {
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
2808 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2809 .channel_layouts = aac_channel_layout,