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-libav@jannau.net>
10 * This file is part of FFmpeg.
12 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 FFmpeg 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 if (layout) avctx->channel_layout = layout;
388 avctx->channels = channels;
389 ac->output_configured = oc_type;
394 static void flush(AVCodecContext *avctx)
396 AACContext *ac= avctx->priv_data;
399 for (type = 3; type >= 0; type--) {
400 for (i = 0; i < MAX_ELEM_ID; i++) {
401 ChannelElement *che = ac->che[type][i];
403 for (j = 0; j <= 1; j++) {
404 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
412 * Set up channel positions based on a default channel configuration
413 * as specified in table 1.17.
415 * @return Returns error status. 0 - OK, !0 - error
417 static av_cold int set_default_channel_config(AVCodecContext *avctx,
418 uint8_t (*layout_map)[3],
422 if (channel_config < 1 || channel_config > 7) {
423 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
427 *tags = tags_per_config[channel_config];
428 memcpy(layout_map, aac_channel_layout_map[channel_config-1], *tags * sizeof(*layout_map));
432 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
434 // For PCE based channel configurations map the channels solely based on tags.
435 if (!ac->m4ac.chan_config) {
436 return ac->tag_che_map[type][elem_id];
438 // Allow single CPE stereo files to be signalled with mono configuration.
439 if (!ac->tags_mapped && type == TYPE_CPE && ac->m4ac.chan_config == 1) {
440 uint8_t layout_map[MAX_ELEM_ID*4][3];
443 if (set_default_channel_config(ac->avctx, layout_map, &layout_map_tags,
446 if (output_configure(ac, layout_map, layout_map_tags,
447 2, OC_TRIAL_FRAME) < 0)
450 ac->m4ac.chan_config = 2;
452 // For indexed channel configurations map the channels solely based on position.
453 switch (ac->m4ac.chan_config) {
455 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
457 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
460 /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
461 instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
462 encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
463 if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
465 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
468 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
470 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
473 if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
475 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
479 if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
481 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
482 } else if (ac->m4ac.chan_config == 2) {
486 if (!ac->tags_mapped && type == TYPE_SCE) {
488 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
496 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
498 * @param type speaker type/position for these channels
500 static void decode_channel_map(uint8_t layout_map[][3],
501 enum ChannelPosition type,
502 GetBitContext *gb, int n)
505 enum RawDataBlockType syn_ele;
507 case AAC_CHANNEL_FRONT:
508 case AAC_CHANNEL_BACK:
509 case AAC_CHANNEL_SIDE:
510 syn_ele = get_bits1(gb);
516 case AAC_CHANNEL_LFE:
520 layout_map[0][0] = syn_ele;
521 layout_map[0][1] = get_bits(gb, 4);
522 layout_map[0][2] = type;
528 * Decode program configuration element; reference: table 4.2.
530 * @return Returns error status. 0 - OK, !0 - error
532 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
533 uint8_t (*layout_map)[3],
536 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
540 skip_bits(gb, 2); // object_type
542 sampling_index = get_bits(gb, 4);
543 if (m4ac->sampling_index != sampling_index)
544 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");
546 num_front = get_bits(gb, 4);
547 num_side = get_bits(gb, 4);
548 num_back = get_bits(gb, 4);
549 num_lfe = get_bits(gb, 2);
550 num_assoc_data = get_bits(gb, 3);
551 num_cc = get_bits(gb, 4);
554 skip_bits(gb, 4); // mono_mixdown_tag
556 skip_bits(gb, 4); // stereo_mixdown_tag
559 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
561 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
562 av_log(avctx, AV_LOG_ERROR, overread_err);
565 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
567 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
569 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
571 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
574 skip_bits_long(gb, 4 * num_assoc_data);
576 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
581 /* comment field, first byte is length */
582 comment_len = get_bits(gb, 8) * 8;
583 if (get_bits_left(gb) < comment_len) {
584 av_log(avctx, AV_LOG_ERROR, overread_err);
587 skip_bits_long(gb, comment_len);
592 * Decode GA "General Audio" specific configuration; reference: table 4.1.
594 * @param ac pointer to AACContext, may be null
595 * @param avctx pointer to AVCCodecContext, used for logging
597 * @return Returns error status. 0 - OK, !0 - error
599 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
601 MPEG4AudioConfig *m4ac,
604 int extension_flag, ret;
605 uint8_t layout_map[MAX_ELEM_ID*4][3];
608 if (get_bits1(gb)) { // frameLengthFlag
609 av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
613 if (get_bits1(gb)) // dependsOnCoreCoder
614 skip_bits(gb, 14); // coreCoderDelay
615 extension_flag = get_bits1(gb);
617 if (m4ac->object_type == AOT_AAC_SCALABLE ||
618 m4ac->object_type == AOT_ER_AAC_SCALABLE)
619 skip_bits(gb, 3); // layerNr
621 if (channel_config == 0) {
622 skip_bits(gb, 4); // element_instance_tag
623 tags = decode_pce(avctx, m4ac, layout_map, gb);
627 if ((ret = set_default_channel_config(avctx, layout_map, &tags, channel_config)))
631 if (count_channels(layout_map, tags) > 1) {
633 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
636 if (ac && (ret = output_configure(ac, layout_map, tags,
637 channel_config, OC_GLOBAL_HDR)))
640 if (extension_flag) {
641 switch (m4ac->object_type) {
643 skip_bits(gb, 5); // numOfSubFrame
644 skip_bits(gb, 11); // layer_length
648 case AOT_ER_AAC_SCALABLE:
650 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
651 * aacScalefactorDataResilienceFlag
652 * aacSpectralDataResilienceFlag
656 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
662 * Decode audio specific configuration; reference: table 1.13.
664 * @param ac pointer to AACContext, may be null
665 * @param avctx pointer to AVCCodecContext, used for logging
666 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
667 * @param data pointer to buffer holding an audio specific config
668 * @param bit_size size of audio specific config or data in bits
669 * @param sync_extension look for an appended sync extension
671 * @return Returns error status or number of consumed bits. <0 - error
673 static int decode_audio_specific_config(AACContext *ac,
674 AVCodecContext *avctx,
675 MPEG4AudioConfig *m4ac,
676 const uint8_t *data, int bit_size,
682 av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
683 for (i = 0; i < avctx->extradata_size; i++)
684 av_dlog(avctx, "%02x ", avctx->extradata[i]);
685 av_dlog(avctx, "\n");
687 init_get_bits(&gb, data, bit_size);
689 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
691 if (m4ac->sampling_index > 12) {
692 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
696 skip_bits_long(&gb, i);
698 switch (m4ac->object_type) {
702 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
706 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
707 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
711 av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
712 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
713 m4ac->sample_rate, m4ac->sbr, m4ac->ps);
715 return get_bits_count(&gb);
719 * linear congruential pseudorandom number generator
721 * @param previous_val pointer to the current state of the generator
723 * @return Returns a 32-bit pseudorandom integer
725 static av_always_inline int lcg_random(int previous_val)
727 return previous_val * 1664525 + 1013904223;
730 static av_always_inline void reset_predict_state(PredictorState *ps)
740 static void reset_all_predictors(PredictorState *ps)
743 for (i = 0; i < MAX_PREDICTORS; i++)
744 reset_predict_state(&ps[i]);
747 static int sample_rate_idx (int rate)
749 if (92017 <= rate) return 0;
750 else if (75132 <= rate) return 1;
751 else if (55426 <= rate) return 2;
752 else if (46009 <= rate) return 3;
753 else if (37566 <= rate) return 4;
754 else if (27713 <= rate) return 5;
755 else if (23004 <= rate) return 6;
756 else if (18783 <= rate) return 7;
757 else if (13856 <= rate) return 8;
758 else if (11502 <= rate) return 9;
759 else if (9391 <= rate) return 10;
763 static void reset_predictor_group(PredictorState *ps, int group_num)
766 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
767 reset_predict_state(&ps[i]);
770 #define AAC_INIT_VLC_STATIC(num, size) \
771 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
772 ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
773 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
776 static av_cold int aac_decode_init(AVCodecContext *avctx)
778 AACContext *ac = avctx->priv_data;
779 float output_scale_factor;
782 ac->m4ac.sample_rate = avctx->sample_rate;
784 if (avctx->extradata_size > 0) {
785 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
787 avctx->extradata_size*8, 1) < 0)
791 uint8_t layout_map[MAX_ELEM_ID*4][3];
794 sr = sample_rate_idx(avctx->sample_rate);
795 ac->m4ac.sampling_index = sr;
796 ac->m4ac.channels = avctx->channels;
800 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
801 if (ff_mpeg4audio_channels[i] == avctx->channels)
803 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
806 ac->m4ac.chan_config = i;
808 if (ac->m4ac.chan_config) {
809 int ret = set_default_channel_config(avctx, layout_map,
810 &layout_map_tags, ac->m4ac.chan_config);
812 output_configure(ac, layout_map, layout_map_tags,
813 ac->m4ac.chan_config, OC_GLOBAL_HDR);
814 else if (avctx->err_recognition & AV_EF_EXPLODE)
815 return AVERROR_INVALIDDATA;
819 if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
820 avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
821 output_scale_factor = 1.0 / 32768.0;
823 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
824 output_scale_factor = 1.0;
827 AAC_INIT_VLC_STATIC( 0, 304);
828 AAC_INIT_VLC_STATIC( 1, 270);
829 AAC_INIT_VLC_STATIC( 2, 550);
830 AAC_INIT_VLC_STATIC( 3, 300);
831 AAC_INIT_VLC_STATIC( 4, 328);
832 AAC_INIT_VLC_STATIC( 5, 294);
833 AAC_INIT_VLC_STATIC( 6, 306);
834 AAC_INIT_VLC_STATIC( 7, 268);
835 AAC_INIT_VLC_STATIC( 8, 510);
836 AAC_INIT_VLC_STATIC( 9, 366);
837 AAC_INIT_VLC_STATIC(10, 462);
841 ff_dsputil_init(&ac->dsp, avctx);
842 ff_fmt_convert_init(&ac->fmt_conv, avctx);
844 ac->random_state = 0x1f2e3d4c;
848 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
849 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
850 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
853 ff_mdct_init(&ac->mdct, 11, 1, output_scale_factor/1024.0);
854 ff_mdct_init(&ac->mdct_small, 8, 1, output_scale_factor/128.0);
855 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0/output_scale_factor);
856 // window initialization
857 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
858 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
859 ff_init_ff_sine_windows(10);
860 ff_init_ff_sine_windows( 7);
864 avcodec_get_frame_defaults(&ac->frame);
865 avctx->coded_frame = &ac->frame;
871 * Skip data_stream_element; reference: table 4.10.
873 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
875 int byte_align = get_bits1(gb);
876 int count = get_bits(gb, 8);
878 count += get_bits(gb, 8);
882 if (get_bits_left(gb) < 8 * count) {
883 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
886 skip_bits_long(gb, 8 * count);
890 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
895 ics->predictor_reset_group = get_bits(gb, 5);
896 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
897 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
901 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
902 ics->prediction_used[sfb] = get_bits1(gb);
908 * Decode Long Term Prediction data; reference: table 4.xx.
910 static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
911 GetBitContext *gb, uint8_t max_sfb)
915 ltp->lag = get_bits(gb, 11);
916 ltp->coef = ltp_coef[get_bits(gb, 3)];
917 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
918 ltp->used[sfb] = get_bits1(gb);
922 * Decode Individual Channel Stream info; reference: table 4.6.
924 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
928 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
929 return AVERROR_INVALIDDATA;
931 ics->window_sequence[1] = ics->window_sequence[0];
932 ics->window_sequence[0] = get_bits(gb, 2);
933 ics->use_kb_window[1] = ics->use_kb_window[0];
934 ics->use_kb_window[0] = get_bits1(gb);
935 ics->num_window_groups = 1;
936 ics->group_len[0] = 1;
937 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
939 ics->max_sfb = get_bits(gb, 4);
940 for (i = 0; i < 7; i++) {
942 ics->group_len[ics->num_window_groups - 1]++;
944 ics->num_window_groups++;
945 ics->group_len[ics->num_window_groups - 1] = 1;
948 ics->num_windows = 8;
949 ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
950 ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
951 ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
952 ics->predictor_present = 0;
954 ics->max_sfb = get_bits(gb, 6);
955 ics->num_windows = 1;
956 ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
957 ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
958 ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
959 ics->predictor_present = get_bits1(gb);
960 ics->predictor_reset_group = 0;
961 if (ics->predictor_present) {
962 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
963 if (decode_prediction(ac, ics, gb)) {
964 return AVERROR_INVALIDDATA;
966 } else if (ac->m4ac.object_type == AOT_AAC_LC) {
967 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
968 return AVERROR_INVALIDDATA;
970 if ((ics->ltp.present = get_bits(gb, 1)))
971 decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
976 if (ics->max_sfb > ics->num_swb) {
977 av_log(ac->avctx, AV_LOG_ERROR,
978 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
979 ics->max_sfb, ics->num_swb);
980 return AVERROR_INVALIDDATA;
987 * Decode band types (section_data payload); reference: table 4.46.
989 * @param band_type array of the used band type
990 * @param band_type_run_end array of the last scalefactor band of a band type run
992 * @return Returns error status. 0 - OK, !0 - error
994 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
995 int band_type_run_end[120], GetBitContext *gb,
996 IndividualChannelStream *ics)
999 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1000 for (g = 0; g < ics->num_window_groups; g++) {
1002 while (k < ics->max_sfb) {
1003 uint8_t sect_end = k;
1005 int sect_band_type = get_bits(gb, 4);
1006 if (sect_band_type == 12) {
1007 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1011 sect_len_incr = get_bits(gb, bits);
1012 sect_end += sect_len_incr;
1013 if (get_bits_left(gb) < 0) {
1014 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1017 if (sect_end > ics->max_sfb) {
1018 av_log(ac->avctx, AV_LOG_ERROR,
1019 "Number of bands (%d) exceeds limit (%d).\n",
1020 sect_end, ics->max_sfb);
1023 } while (sect_len_incr == (1 << bits) - 1);
1024 for (; k < sect_end; k++) {
1025 band_type [idx] = sect_band_type;
1026 band_type_run_end[idx++] = sect_end;
1034 * Decode scalefactors; reference: table 4.47.
1036 * @param global_gain first scalefactor value as scalefactors are differentially coded
1037 * @param band_type array of the used band type
1038 * @param band_type_run_end array of the last scalefactor band of a band type run
1039 * @param sf array of scalefactors or intensity stereo positions
1041 * @return Returns error status. 0 - OK, !0 - error
1043 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1044 unsigned int global_gain,
1045 IndividualChannelStream *ics,
1046 enum BandType band_type[120],
1047 int band_type_run_end[120])
1050 int offset[3] = { global_gain, global_gain - 90, 0 };
1053 for (g = 0; g < ics->num_window_groups; g++) {
1054 for (i = 0; i < ics->max_sfb;) {
1055 int run_end = band_type_run_end[idx];
1056 if (band_type[idx] == ZERO_BT) {
1057 for (; i < run_end; i++, idx++)
1059 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
1060 for (; i < run_end; i++, idx++) {
1061 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1062 clipped_offset = av_clip(offset[2], -155, 100);
1063 if (offset[2] != clipped_offset) {
1064 av_log_ask_for_sample(ac->avctx, "Intensity stereo "
1065 "position clipped (%d -> %d).\nIf you heard an "
1066 "audible artifact, there may be a bug in the "
1067 "decoder. ", offset[2], clipped_offset);
1069 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1071 } else if (band_type[idx] == NOISE_BT) {
1072 for (; i < run_end; i++, idx++) {
1073 if (noise_flag-- > 0)
1074 offset[1] += get_bits(gb, 9) - 256;
1076 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1077 clipped_offset = av_clip(offset[1], -100, 155);
1078 if (offset[1] != clipped_offset) {
1079 av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
1080 "(%d -> %d).\nIf you heard an audible "
1081 "artifact, there may be a bug in the decoder. ",
1082 offset[1], clipped_offset);
1084 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1087 for (; i < run_end; i++, idx++) {
1088 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1089 if (offset[0] > 255U) {
1090 av_log(ac->avctx, AV_LOG_ERROR,
1091 "Scalefactor (%d) out of range.\n", offset[0]);
1094 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1103 * Decode pulse data; reference: table 4.7.
1105 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1106 const uint16_t *swb_offset, int num_swb)
1109 pulse->num_pulse = get_bits(gb, 2) + 1;
1110 pulse_swb = get_bits(gb, 6);
1111 if (pulse_swb >= num_swb)
1113 pulse->pos[0] = swb_offset[pulse_swb];
1114 pulse->pos[0] += get_bits(gb, 5);
1115 if (pulse->pos[0] > 1023)
1117 pulse->amp[0] = get_bits(gb, 4);
1118 for (i = 1; i < pulse->num_pulse; i++) {
1119 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1120 if (pulse->pos[i] > 1023)
1122 pulse->amp[i] = get_bits(gb, 4);
1128 * Decode Temporal Noise Shaping data; reference: table 4.48.
1130 * @return Returns error status. 0 - OK, !0 - error
1132 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1133 GetBitContext *gb, const IndividualChannelStream *ics)
1135 int w, filt, i, coef_len, coef_res, coef_compress;
1136 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1137 const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1138 for (w = 0; w < ics->num_windows; w++) {
1139 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1140 coef_res = get_bits1(gb);
1142 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1144 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1146 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1147 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
1148 tns->order[w][filt], tns_max_order);
1149 tns->order[w][filt] = 0;
1152 if (tns->order[w][filt]) {
1153 tns->direction[w][filt] = get_bits1(gb);
1154 coef_compress = get_bits1(gb);
1155 coef_len = coef_res + 3 - coef_compress;
1156 tmp2_idx = 2 * coef_compress + coef_res;
1158 for (i = 0; i < tns->order[w][filt]; i++)
1159 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1168 * Decode Mid/Side data; reference: table 4.54.
1170 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1171 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1172 * [3] reserved for scalable AAC
1174 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1178 if (ms_present == 1) {
1179 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
1180 cpe->ms_mask[idx] = get_bits1(gb);
1181 } else if (ms_present == 2) {
1182 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
1187 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1191 *dst++ = v[idx & 15] * s;
1192 *dst++ = v[idx>>4 & 15] * s;
1198 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1202 *dst++ = v[idx & 3] * s;
1203 *dst++ = v[idx>>2 & 3] * s;
1204 *dst++ = v[idx>>4 & 3] * s;
1205 *dst++ = v[idx>>6 & 3] * s;
1211 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1212 unsigned sign, const float *scale)
1214 union av_intfloat32 s0, s1;
1216 s0.f = s1.f = *scale;
1217 s0.i ^= sign >> 1 << 31;
1220 *dst++ = v[idx & 15] * s0.f;
1221 *dst++ = v[idx>>4 & 15] * s1.f;
1228 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1229 unsigned sign, const float *scale)
1231 unsigned nz = idx >> 12;
1232 union av_intfloat32 s = { .f = *scale };
1233 union av_intfloat32 t;
1235 t.i = s.i ^ (sign & 1U<<31);
1236 *dst++ = v[idx & 3] * t.f;
1238 sign <<= nz & 1; nz >>= 1;
1239 t.i = s.i ^ (sign & 1U<<31);
1240 *dst++ = v[idx>>2 & 3] * t.f;
1242 sign <<= nz & 1; nz >>= 1;
1243 t.i = s.i ^ (sign & 1U<<31);
1244 *dst++ = v[idx>>4 & 3] * t.f;
1246 sign <<= nz & 1; nz >>= 1;
1247 t.i = s.i ^ (sign & 1U<<31);
1248 *dst++ = v[idx>>6 & 3] * t.f;
1255 * Decode spectral data; reference: table 4.50.
1256 * Dequantize and scale spectral data; reference: 4.6.3.3.
1258 * @param coef array of dequantized, scaled spectral data
1259 * @param sf array of scalefactors or intensity stereo positions
1260 * @param pulse_present set if pulses are present
1261 * @param pulse pointer to pulse data struct
1262 * @param band_type array of the used band type
1264 * @return Returns error status. 0 - OK, !0 - error
1266 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1267 GetBitContext *gb, const float sf[120],
1268 int pulse_present, const Pulse *pulse,
1269 const IndividualChannelStream *ics,
1270 enum BandType band_type[120])
1272 int i, k, g, idx = 0;
1273 const int c = 1024 / ics->num_windows;
1274 const uint16_t *offsets = ics->swb_offset;
1275 float *coef_base = coef;
1277 for (g = 0; g < ics->num_windows; g++)
1278 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1280 for (g = 0; g < ics->num_window_groups; g++) {
1281 unsigned g_len = ics->group_len[g];
1283 for (i = 0; i < ics->max_sfb; i++, idx++) {
1284 const unsigned cbt_m1 = band_type[idx] - 1;
1285 float *cfo = coef + offsets[i];
1286 int off_len = offsets[i + 1] - offsets[i];
1289 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1290 for (group = 0; group < g_len; group++, cfo+=128) {
1291 memset(cfo, 0, off_len * sizeof(float));
1293 } else if (cbt_m1 == NOISE_BT - 1) {
1294 for (group = 0; group < g_len; group++, cfo+=128) {
1298 for (k = 0; k < off_len; k++) {
1299 ac->random_state = lcg_random(ac->random_state);
1300 cfo[k] = ac->random_state;
1303 band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1304 scale = sf[idx] / sqrtf(band_energy);
1305 ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1308 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1309 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1310 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1311 OPEN_READER(re, gb);
1313 switch (cbt_m1 >> 1) {
1315 for (group = 0; group < g_len; group++, cfo+=128) {
1323 UPDATE_CACHE(re, gb);
1324 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1325 cb_idx = cb_vector_idx[code];
1326 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1332 for (group = 0; group < g_len; group++, cfo+=128) {
1342 UPDATE_CACHE(re, gb);
1343 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1344 cb_idx = cb_vector_idx[code];
1345 nnz = cb_idx >> 8 & 15;
1346 bits = nnz ? GET_CACHE(re, gb) : 0;
1347 LAST_SKIP_BITS(re, gb, nnz);
1348 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1354 for (group = 0; group < g_len; group++, cfo+=128) {
1362 UPDATE_CACHE(re, gb);
1363 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1364 cb_idx = cb_vector_idx[code];
1365 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1372 for (group = 0; group < g_len; group++, cfo+=128) {
1382 UPDATE_CACHE(re, gb);
1383 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1384 cb_idx = cb_vector_idx[code];
1385 nnz = cb_idx >> 8 & 15;
1386 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1387 LAST_SKIP_BITS(re, gb, nnz);
1388 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1394 for (group = 0; group < g_len; group++, cfo+=128) {
1396 uint32_t *icf = (uint32_t *) cf;
1406 UPDATE_CACHE(re, gb);
1407 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1415 cb_idx = cb_vector_idx[code];
1418 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1419 LAST_SKIP_BITS(re, gb, nnz);
1421 for (j = 0; j < 2; j++) {
1425 /* The total length of escape_sequence must be < 22 bits according
1426 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1427 UPDATE_CACHE(re, gb);
1428 b = GET_CACHE(re, gb);
1429 b = 31 - av_log2(~b);
1432 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1436 SKIP_BITS(re, gb, b + 1);
1438 n = (1 << b) + SHOW_UBITS(re, gb, b);
1439 LAST_SKIP_BITS(re, gb, b);
1440 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1443 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1444 *icf++ = (bits & 1U<<31) | v;
1451 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1455 CLOSE_READER(re, gb);
1461 if (pulse_present) {
1463 for (i = 0; i < pulse->num_pulse; i++) {
1464 float co = coef_base[ pulse->pos[i] ];
1465 while (offsets[idx + 1] <= pulse->pos[i])
1467 if (band_type[idx] != NOISE_BT && sf[idx]) {
1468 float ico = -pulse->amp[i];
1471 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1473 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1480 static av_always_inline float flt16_round(float pf)
1482 union av_intfloat32 tmp;
1484 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1488 static av_always_inline float flt16_even(float pf)
1490 union av_intfloat32 tmp;
1492 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1496 static av_always_inline float flt16_trunc(float pf)
1498 union av_intfloat32 pun;
1500 pun.i &= 0xFFFF0000U;
1504 static av_always_inline void predict(PredictorState *ps, float *coef,
1507 const float a = 0.953125; // 61.0 / 64
1508 const float alpha = 0.90625; // 29.0 / 32
1512 float r0 = ps->r0, r1 = ps->r1;
1513 float cor0 = ps->cor0, cor1 = ps->cor1;
1514 float var0 = ps->var0, var1 = ps->var1;
1516 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1517 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1519 pv = flt16_round(k1 * r0 + k2 * r1);
1526 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1527 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1528 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1529 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1531 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1532 ps->r0 = flt16_trunc(a * e0);
1536 * Apply AAC-Main style frequency domain prediction.
1538 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1542 if (!sce->ics.predictor_initialized) {
1543 reset_all_predictors(sce->predictor_state);
1544 sce->ics.predictor_initialized = 1;
1547 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1548 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1549 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1550 predict(&sce->predictor_state[k], &sce->coeffs[k],
1551 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1554 if (sce->ics.predictor_reset_group)
1555 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1557 reset_all_predictors(sce->predictor_state);
1561 * Decode an individual_channel_stream payload; reference: table 4.44.
1563 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1564 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1566 * @return Returns error status. 0 - OK, !0 - error
1568 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1569 GetBitContext *gb, int common_window, int scale_flag)
1572 TemporalNoiseShaping *tns = &sce->tns;
1573 IndividualChannelStream *ics = &sce->ics;
1574 float *out = sce->coeffs;
1575 int global_gain, pulse_present = 0;
1577 /* This assignment is to silence a GCC warning about the variable being used
1578 * uninitialized when in fact it always is.
1580 pulse.num_pulse = 0;
1582 global_gain = get_bits(gb, 8);
1584 if (!common_window && !scale_flag) {
1585 if (decode_ics_info(ac, ics, gb) < 0)
1586 return AVERROR_INVALIDDATA;
1589 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1591 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1596 if ((pulse_present = get_bits1(gb))) {
1597 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1598 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1601 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1602 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1606 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1608 if (get_bits1(gb)) {
1609 av_log_missing_feature(ac->avctx, "SSR", 1);
1614 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1617 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1618 apply_prediction(ac, sce);
1624 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1626 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1628 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1629 float *ch0 = cpe->ch[0].coeffs;
1630 float *ch1 = cpe->ch[1].coeffs;
1631 int g, i, group, idx = 0;
1632 const uint16_t *offsets = ics->swb_offset;
1633 for (g = 0; g < ics->num_window_groups; g++) {
1634 for (i = 0; i < ics->max_sfb; i++, idx++) {
1635 if (cpe->ms_mask[idx] &&
1636 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1637 for (group = 0; group < ics->group_len[g]; group++) {
1638 ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1639 ch1 + group * 128 + offsets[i],
1640 offsets[i+1] - offsets[i]);
1644 ch0 += ics->group_len[g] * 128;
1645 ch1 += ics->group_len[g] * 128;
1650 * intensity stereo decoding; reference: 4.6.8.2.3
1652 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1653 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1654 * [3] reserved for scalable AAC
1656 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
1658 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1659 SingleChannelElement *sce1 = &cpe->ch[1];
1660 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1661 const uint16_t *offsets = ics->swb_offset;
1662 int g, group, i, idx = 0;
1665 for (g = 0; g < ics->num_window_groups; g++) {
1666 for (i = 0; i < ics->max_sfb;) {
1667 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1668 const int bt_run_end = sce1->band_type_run_end[idx];
1669 for (; i < bt_run_end; i++, idx++) {
1670 c = -1 + 2 * (sce1->band_type[idx] - 14);
1672 c *= 1 - 2 * cpe->ms_mask[idx];
1673 scale = c * sce1->sf[idx];
1674 for (group = 0; group < ics->group_len[g]; group++)
1675 ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1676 coef0 + group * 128 + offsets[i],
1678 offsets[i + 1] - offsets[i]);
1681 int bt_run_end = sce1->band_type_run_end[idx];
1682 idx += bt_run_end - i;
1686 coef0 += ics->group_len[g] * 128;
1687 coef1 += ics->group_len[g] * 128;
1692 * Decode a channel_pair_element; reference: table 4.4.
1694 * @return Returns error status. 0 - OK, !0 - error
1696 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1698 int i, ret, common_window, ms_present = 0;
1700 common_window = get_bits1(gb);
1701 if (common_window) {
1702 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1703 return AVERROR_INVALIDDATA;
1704 i = cpe->ch[1].ics.use_kb_window[0];
1705 cpe->ch[1].ics = cpe->ch[0].ics;
1706 cpe->ch[1].ics.use_kb_window[1] = i;
1707 if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
1708 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1709 decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1710 ms_present = get_bits(gb, 2);
1711 if (ms_present == 3) {
1712 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1714 } else if (ms_present)
1715 decode_mid_side_stereo(cpe, gb, ms_present);
1717 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1719 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1722 if (common_window) {
1724 apply_mid_side_stereo(ac, cpe);
1725 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1726 apply_prediction(ac, &cpe->ch[0]);
1727 apply_prediction(ac, &cpe->ch[1]);
1731 apply_intensity_stereo(ac, cpe, ms_present);
1735 static const float cce_scale[] = {
1736 1.09050773266525765921, //2^(1/8)
1737 1.18920711500272106672, //2^(1/4)
1743 * Decode coupling_channel_element; reference: table 4.8.
1745 * @return Returns error status. 0 - OK, !0 - error
1747 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1753 SingleChannelElement *sce = &che->ch[0];
1754 ChannelCoupling *coup = &che->coup;
1756 coup->coupling_point = 2 * get_bits1(gb);
1757 coup->num_coupled = get_bits(gb, 3);
1758 for (c = 0; c <= coup->num_coupled; c++) {
1760 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1761 coup->id_select[c] = get_bits(gb, 4);
1762 if (coup->type[c] == TYPE_CPE) {
1763 coup->ch_select[c] = get_bits(gb, 2);
1764 if (coup->ch_select[c] == 3)
1767 coup->ch_select[c] = 2;
1769 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1771 sign = get_bits(gb, 1);
1772 scale = cce_scale[get_bits(gb, 2)];
1774 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1777 for (c = 0; c < num_gain; c++) {
1781 float gain_cache = 1.;
1783 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1784 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1785 gain_cache = powf(scale, -gain);
1787 if (coup->coupling_point == AFTER_IMDCT) {
1788 coup->gain[c][0] = gain_cache;
1790 for (g = 0; g < sce->ics.num_window_groups; g++) {
1791 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1792 if (sce->band_type[idx] != ZERO_BT) {
1794 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1802 gain_cache = powf(scale, -t) * s;
1805 coup->gain[c][idx] = gain_cache;
1815 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1817 * @return Returns number of bytes consumed.
1819 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1823 int num_excl_chan = 0;
1826 for (i = 0; i < 7; i++)
1827 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1828 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1830 return num_excl_chan / 7;
1834 * Decode dynamic range information; reference: table 4.52.
1836 * @param cnt length of TYPE_FIL syntactic element in bytes
1838 * @return Returns number of bytes consumed.
1840 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1841 GetBitContext *gb, int cnt)
1844 int drc_num_bands = 1;
1847 /* pce_tag_present? */
1848 if (get_bits1(gb)) {
1849 che_drc->pce_instance_tag = get_bits(gb, 4);
1850 skip_bits(gb, 4); // tag_reserved_bits
1854 /* excluded_chns_present? */
1855 if (get_bits1(gb)) {
1856 n += decode_drc_channel_exclusions(che_drc, gb);
1859 /* drc_bands_present? */
1860 if (get_bits1(gb)) {
1861 che_drc->band_incr = get_bits(gb, 4);
1862 che_drc->interpolation_scheme = get_bits(gb, 4);
1864 drc_num_bands += che_drc->band_incr;
1865 for (i = 0; i < drc_num_bands; i++) {
1866 che_drc->band_top[i] = get_bits(gb, 8);
1871 /* prog_ref_level_present? */
1872 if (get_bits1(gb)) {
1873 che_drc->prog_ref_level = get_bits(gb, 7);
1874 skip_bits1(gb); // prog_ref_level_reserved_bits
1878 for (i = 0; i < drc_num_bands; i++) {
1879 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1880 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1888 * Decode extension data (incomplete); reference: table 4.51.
1890 * @param cnt length of TYPE_FIL syntactic element in bytes
1892 * @return Returns number of bytes consumed
1894 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1895 ChannelElement *che, enum RawDataBlockType elem_type)
1899 switch (get_bits(gb, 4)) { // extension type
1900 case EXT_SBR_DATA_CRC:
1904 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1906 } else if (!ac->m4ac.sbr) {
1907 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1908 skip_bits_long(gb, 8 * cnt - 4);
1910 } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1911 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1912 skip_bits_long(gb, 8 * cnt - 4);
1914 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1917 output_configure(ac, ac->layout_map, ac->layout_map_tags,
1918 ac->m4ac.chan_config, ac->output_configured);
1922 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1924 case EXT_DYNAMIC_RANGE:
1925 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1929 case EXT_DATA_ELEMENT:
1931 skip_bits_long(gb, 8 * cnt - 4);
1938 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1940 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1941 * @param coef spectral coefficients
1943 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1944 IndividualChannelStream *ics, int decode)
1946 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1948 int bottom, top, order, start, end, size, inc;
1949 float lpc[TNS_MAX_ORDER];
1950 float tmp[TNS_MAX_ORDER];
1952 for (w = 0; w < ics->num_windows; w++) {
1953 bottom = ics->num_swb;
1954 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1956 bottom = FFMAX(0, top - tns->length[w][filt]);
1957 order = tns->order[w][filt];
1962 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1964 start = ics->swb_offset[FFMIN(bottom, mmm)];
1965 end = ics->swb_offset[FFMIN( top, mmm)];
1966 if ((size = end - start) <= 0)
1968 if (tns->direction[w][filt]) {
1978 for (m = 0; m < size; m++, start += inc)
1979 for (i = 1; i <= FFMIN(m, order); i++)
1980 coef[start] -= coef[start - i * inc] * lpc[i - 1];
1983 for (m = 0; m < size; m++, start += inc) {
1984 tmp[0] = coef[start];
1985 for (i = 1; i <= FFMIN(m, order); i++)
1986 coef[start] += tmp[i] * lpc[i - 1];
1987 for (i = order; i > 0; i--)
1988 tmp[i] = tmp[i - 1];
1996 * Apply windowing and MDCT to obtain the spectral
1997 * coefficient from the predicted sample by LTP.
1999 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2000 float *in, IndividualChannelStream *ics)
2002 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2003 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2004 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2005 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2007 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2008 ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
2010 memset(in, 0, 448 * sizeof(float));
2011 ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2013 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2014 ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2016 ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2017 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2019 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2023 * Apply the long term prediction
2025 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2027 const LongTermPrediction *ltp = &sce->ics.ltp;
2028 const uint16_t *offsets = sce->ics.swb_offset;
2031 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2032 float *predTime = sce->ret;
2033 float *predFreq = ac->buf_mdct;
2034 int16_t num_samples = 2048;
2036 if (ltp->lag < 1024)
2037 num_samples = ltp->lag + 1024;
2038 for (i = 0; i < num_samples; i++)
2039 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2040 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2042 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2044 if (sce->tns.present)
2045 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2047 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2049 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2050 sce->coeffs[i] += predFreq[i];
2055 * Update the LTP buffer for next frame
2057 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2059 IndividualChannelStream *ics = &sce->ics;
2060 float *saved = sce->saved;
2061 float *saved_ltp = sce->coeffs;
2062 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2063 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2066 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2067 memcpy(saved_ltp, saved, 512 * sizeof(float));
2068 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2069 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2070 for (i = 0; i < 64; i++)
2071 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2072 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2073 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2074 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2075 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2076 for (i = 0; i < 64; i++)
2077 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2078 } else { // LONG_STOP or ONLY_LONG
2079 ac->dsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2080 for (i = 0; i < 512; i++)
2081 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2084 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2085 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2086 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2090 * Conduct IMDCT and windowing.
2092 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2094 IndividualChannelStream *ics = &sce->ics;
2095 float *in = sce->coeffs;
2096 float *out = sce->ret;
2097 float *saved = sce->saved;
2098 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2099 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2100 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2101 float *buf = ac->buf_mdct;
2102 float *temp = ac->temp;
2106 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2107 for (i = 0; i < 1024; i += 128)
2108 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2110 ac->mdct.imdct_half(&ac->mdct, buf, in);
2112 /* window overlapping
2113 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2114 * and long to short transitions are considered to be short to short
2115 * transitions. This leaves just two cases (long to long and short to short)
2116 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2118 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2119 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2120 ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2122 memcpy( out, saved, 448 * sizeof(float));
2124 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2125 ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2126 ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2127 ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2128 ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2129 ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2130 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2132 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2133 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2138 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2139 memcpy( saved, temp + 64, 64 * sizeof(float));
2140 ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2141 ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2142 ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2143 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2144 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2145 memcpy( saved, buf + 512, 448 * sizeof(float));
2146 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2147 } else { // LONG_STOP or ONLY_LONG
2148 memcpy( saved, buf + 512, 512 * sizeof(float));
2153 * Apply dependent channel coupling (applied before IMDCT).
2155 * @param index index into coupling gain array
2157 static void apply_dependent_coupling(AACContext *ac,
2158 SingleChannelElement *target,
2159 ChannelElement *cce, int index)
2161 IndividualChannelStream *ics = &cce->ch[0].ics;
2162 const uint16_t *offsets = ics->swb_offset;
2163 float *dest = target->coeffs;
2164 const float *src = cce->ch[0].coeffs;
2165 int g, i, group, k, idx = 0;
2166 if (ac->m4ac.object_type == AOT_AAC_LTP) {
2167 av_log(ac->avctx, AV_LOG_ERROR,
2168 "Dependent coupling is not supported together with LTP\n");
2171 for (g = 0; g < ics->num_window_groups; g++) {
2172 for (i = 0; i < ics->max_sfb; i++, idx++) {
2173 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2174 const float gain = cce->coup.gain[index][idx];
2175 for (group = 0; group < ics->group_len[g]; group++) {
2176 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2178 dest[group * 128 + k] += gain * src[group * 128 + k];
2183 dest += ics->group_len[g] * 128;
2184 src += ics->group_len[g] * 128;
2189 * Apply independent channel coupling (applied after IMDCT).
2191 * @param index index into coupling gain array
2193 static void apply_independent_coupling(AACContext *ac,
2194 SingleChannelElement *target,
2195 ChannelElement *cce, int index)
2198 const float gain = cce->coup.gain[index][0];
2199 const float *src = cce->ch[0].ret;
2200 float *dest = target->ret;
2201 const int len = 1024 << (ac->m4ac.sbr == 1);
2203 for (i = 0; i < len; i++)
2204 dest[i] += gain * src[i];
2208 * channel coupling transformation interface
2210 * @param apply_coupling_method pointer to (in)dependent coupling function
2212 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2213 enum RawDataBlockType type, int elem_id,
2214 enum CouplingPoint coupling_point,
2215 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2219 for (i = 0; i < MAX_ELEM_ID; i++) {
2220 ChannelElement *cce = ac->che[TYPE_CCE][i];
2223 if (cce && cce->coup.coupling_point == coupling_point) {
2224 ChannelCoupling *coup = &cce->coup;
2226 for (c = 0; c <= coup->num_coupled; c++) {
2227 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2228 if (coup->ch_select[c] != 1) {
2229 apply_coupling_method(ac, &cc->ch[0], cce, index);
2230 if (coup->ch_select[c] != 0)
2233 if (coup->ch_select[c] != 2)
2234 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2236 index += 1 + (coup->ch_select[c] == 3);
2243 * Convert spectral data to float samples, applying all supported tools as appropriate.
2245 static void spectral_to_sample(AACContext *ac)
2248 for (type = 3; type >= 0; type--) {
2249 for (i = 0; i < MAX_ELEM_ID; i++) {
2250 ChannelElement *che = ac->che[type][i];
2252 if (type <= TYPE_CPE)
2253 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2254 if (ac->m4ac.object_type == AOT_AAC_LTP) {
2255 if (che->ch[0].ics.predictor_present) {
2256 if (che->ch[0].ics.ltp.present)
2257 apply_ltp(ac, &che->ch[0]);
2258 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2259 apply_ltp(ac, &che->ch[1]);
2262 if (che->ch[0].tns.present)
2263 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2264 if (che->ch[1].tns.present)
2265 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2266 if (type <= TYPE_CPE)
2267 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2268 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2269 imdct_and_windowing(ac, &che->ch[0]);
2270 if (ac->m4ac.object_type == AOT_AAC_LTP)
2271 update_ltp(ac, &che->ch[0]);
2272 if (type == TYPE_CPE) {
2273 imdct_and_windowing(ac, &che->ch[1]);
2274 if (ac->m4ac.object_type == AOT_AAC_LTP)
2275 update_ltp(ac, &che->ch[1]);
2277 if (ac->m4ac.sbr > 0) {
2278 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2281 if (type <= TYPE_CCE)
2282 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2288 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2291 AACADTSHeaderInfo hdr_info;
2292 uint8_t layout_map[MAX_ELEM_ID*4][3];
2293 int layout_map_tags;
2295 size = avpriv_aac_parse_header(gb, &hdr_info);
2297 if (hdr_info.chan_config) {
2298 ac->m4ac.chan_config = hdr_info.chan_config;
2299 if (set_default_channel_config(ac->avctx, layout_map,
2300 &layout_map_tags, hdr_info.chan_config))
2302 if (output_configure(ac, layout_map, layout_map_tags,
2303 hdr_info.chan_config,
2304 FFMAX(ac->output_configured, OC_TRIAL_FRAME)))
2306 } else if (ac->output_configured != OC_LOCKED) {
2307 ac->m4ac.chan_config = 0;
2308 ac->output_configured = OC_NONE;
2310 if (ac->output_configured != OC_LOCKED) {
2313 ac->m4ac.sample_rate = hdr_info.sample_rate;
2314 ac->m4ac.sampling_index = hdr_info.sampling_index;
2315 ac->m4ac.object_type = hdr_info.object_type;
2317 if (!ac->avctx->sample_rate)
2318 ac->avctx->sample_rate = hdr_info.sample_rate;
2319 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2320 // This is 2 for "VLB " audio in NSV files.
2321 // See samples/nsv/vlb_audio.
2322 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
2323 ac->warned_num_aac_frames = 1;
2325 if (!hdr_info.crc_absent)
2331 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2332 int *got_frame_ptr, GetBitContext *gb)
2334 AACContext *ac = avctx->priv_data;
2335 ChannelElement *che = NULL, *che_prev = NULL;
2336 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2338 int samples = 0, multiplier, audio_found = 0;
2340 if (show_bits(gb, 12) == 0xfff) {
2341 if (parse_adts_frame_header(ac, gb) < 0) {
2342 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2345 if (ac->m4ac.sampling_index > 12) {
2346 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
2351 ac->tags_mapped = 0;
2353 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2354 elem_id = get_bits(gb, 4);
2356 if (elem_type < TYPE_DSE) {
2357 if (!(che=get_che(ac, elem_type, elem_id))) {
2358 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2359 elem_type, elem_id);
2365 switch (elem_type) {
2368 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2373 err = decode_cpe(ac, gb, che);
2378 err = decode_cce(ac, gb, che);
2382 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2387 err = skip_data_stream_element(ac, gb);
2391 uint8_t layout_map[MAX_ELEM_ID*4][3];
2393 tags = decode_pce(avctx, &ac->m4ac, layout_map, gb);
2398 if (ac->output_configured > OC_TRIAL_PCE)
2399 av_log(avctx, AV_LOG_INFO,
2400 "Evaluating a further program_config_element.\n");
2401 err = output_configure(ac, layout_map, tags, 0, OC_TRIAL_PCE);
2403 ac->m4ac.chan_config = 0;
2409 elem_id += get_bits(gb, 8) - 1;
2410 if (get_bits_left(gb) < 8 * elem_id) {
2411 av_log(avctx, AV_LOG_ERROR, overread_err);
2415 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2416 err = 0; /* FIXME */
2420 err = -1; /* should not happen, but keeps compiler happy */
2425 elem_type_prev = elem_type;
2430 if (get_bits_left(gb) < 3) {
2431 av_log(avctx, AV_LOG_ERROR, overread_err);
2436 spectral_to_sample(ac);
2438 multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2439 samples <<= multiplier;
2440 if (ac->output_configured < OC_LOCKED) {
2441 avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2442 avctx->frame_size = samples;
2446 /* get output buffer */
2447 ac->frame.nb_samples = samples;
2448 if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
2449 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2453 if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
2454 ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
2455 (const float **)ac->output_data,
2456 samples, avctx->channels);
2458 ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2459 (const float **)ac->output_data,
2460 samples, avctx->channels);
2462 *(AVFrame *)data = ac->frame;
2464 *got_frame_ptr = !!samples;
2466 if (ac->output_configured && audio_found)
2467 ac->output_configured = OC_LOCKED;
2472 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2473 int *got_frame_ptr, AVPacket *avpkt)
2475 AACContext *ac = avctx->priv_data;
2476 const uint8_t *buf = avpkt->data;
2477 int buf_size = avpkt->size;
2482 int new_extradata_size;
2483 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2484 AV_PKT_DATA_NEW_EXTRADATA,
2485 &new_extradata_size);
2487 if (new_extradata) {
2488 av_free(avctx->extradata);
2489 avctx->extradata = av_mallocz(new_extradata_size +
2490 FF_INPUT_BUFFER_PADDING_SIZE);
2491 if (!avctx->extradata)
2492 return AVERROR(ENOMEM);
2493 avctx->extradata_size = new_extradata_size;
2494 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2495 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
2497 avctx->extradata_size*8, 1) < 0)
2498 return AVERROR_INVALIDDATA;
2501 init_get_bits(&gb, buf, buf_size * 8);
2503 if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
2506 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2507 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2508 if (buf[buf_offset])
2511 return buf_size > buf_offset ? buf_consumed : buf_size;
2514 static av_cold int aac_decode_close(AVCodecContext *avctx)
2516 AACContext *ac = avctx->priv_data;
2519 for (i = 0; i < MAX_ELEM_ID; i++) {
2520 for (type = 0; type < 4; type++) {
2521 if (ac->che[type][i])
2522 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2523 av_freep(&ac->che[type][i]);
2527 ff_mdct_end(&ac->mdct);
2528 ff_mdct_end(&ac->mdct_small);
2529 ff_mdct_end(&ac->mdct_ltp);
2534 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2536 struct LATMContext {
2537 AACContext aac_ctx; ///< containing AACContext
2538 int initialized; ///< initilized after a valid extradata was seen
2541 int audio_mux_version_A; ///< LATM syntax version
2542 int frame_length_type; ///< 0/1 variable/fixed frame length
2543 int frame_length; ///< frame length for fixed frame length
2546 static inline uint32_t latm_get_value(GetBitContext *b)
2548 int length = get_bits(b, 2);
2550 return get_bits_long(b, (length+1)*8);
2553 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2554 GetBitContext *gb, int asclen)
2556 AACContext *ac = &latmctx->aac_ctx;
2557 AVCodecContext *avctx = ac->avctx;
2558 MPEG4AudioConfig m4ac = {0};
2559 int config_start_bit = get_bits_count(gb);
2560 int sync_extension = 0;
2561 int bits_consumed, esize;
2565 asclen = FFMIN(asclen, get_bits_left(gb));
2567 asclen = get_bits_left(gb);
2569 if (config_start_bit % 8) {
2570 av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2571 "config not byte aligned.\n", 1);
2572 return AVERROR_INVALIDDATA;
2575 return AVERROR_INVALIDDATA;
2576 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2577 gb->buffer + (config_start_bit / 8),
2578 asclen, sync_extension);
2580 if (bits_consumed < 0)
2581 return AVERROR_INVALIDDATA;
2583 if (ac->m4ac.sample_rate != m4ac.sample_rate ||
2584 ac->m4ac.chan_config != m4ac.chan_config) {
2586 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2587 latmctx->initialized = 0;
2589 esize = (bits_consumed+7) / 8;
2591 if (avctx->extradata_size < esize) {
2592 av_free(avctx->extradata);
2593 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2594 if (!avctx->extradata)
2595 return AVERROR(ENOMEM);
2598 avctx->extradata_size = esize;
2599 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2600 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2602 skip_bits_long(gb, bits_consumed);
2604 return bits_consumed;
2607 static int read_stream_mux_config(struct LATMContext *latmctx,
2610 int ret, audio_mux_version = get_bits(gb, 1);
2612 latmctx->audio_mux_version_A = 0;
2613 if (audio_mux_version)
2614 latmctx->audio_mux_version_A = get_bits(gb, 1);
2616 if (!latmctx->audio_mux_version_A) {
2618 if (audio_mux_version)
2619 latm_get_value(gb); // taraFullness
2621 skip_bits(gb, 1); // allStreamSameTimeFraming
2622 skip_bits(gb, 6); // numSubFrames
2624 if (get_bits(gb, 4)) { // numPrograms
2625 av_log_missing_feature(latmctx->aac_ctx.avctx,
2626 "multiple programs are not supported\n", 1);
2627 return AVERROR_PATCHWELCOME;
2630 // for each program (which there is only on in DVB)
2632 // for each layer (which there is only on in DVB)
2633 if (get_bits(gb, 3)) { // numLayer
2634 av_log_missing_feature(latmctx->aac_ctx.avctx,
2635 "multiple layers are not supported\n", 1);
2636 return AVERROR_PATCHWELCOME;
2639 // for all but first stream: use_same_config = get_bits(gb, 1);
2640 if (!audio_mux_version) {
2641 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2644 int ascLen = latm_get_value(gb);
2645 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2648 skip_bits_long(gb, ascLen);
2651 latmctx->frame_length_type = get_bits(gb, 3);
2652 switch (latmctx->frame_length_type) {
2654 skip_bits(gb, 8); // latmBufferFullness
2657 latmctx->frame_length = get_bits(gb, 9);
2662 skip_bits(gb, 6); // CELP frame length table index
2666 skip_bits(gb, 1); // HVXC frame length table index
2670 if (get_bits(gb, 1)) { // other data
2671 if (audio_mux_version) {
2672 latm_get_value(gb); // other_data_bits
2676 esc = get_bits(gb, 1);
2682 if (get_bits(gb, 1)) // crc present
2683 skip_bits(gb, 8); // config_crc
2689 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2693 if (ctx->frame_length_type == 0) {
2694 int mux_slot_length = 0;
2696 tmp = get_bits(gb, 8);
2697 mux_slot_length += tmp;
2698 } while (tmp == 255);
2699 return mux_slot_length;
2700 } else if (ctx->frame_length_type == 1) {
2701 return ctx->frame_length;
2702 } else if (ctx->frame_length_type == 3 ||
2703 ctx->frame_length_type == 5 ||
2704 ctx->frame_length_type == 7) {
2705 skip_bits(gb, 2); // mux_slot_length_coded
2710 static int read_audio_mux_element(struct LATMContext *latmctx,
2714 uint8_t use_same_mux = get_bits(gb, 1);
2715 if (!use_same_mux) {
2716 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2718 } else if (!latmctx->aac_ctx.avctx->extradata) {
2719 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2720 "no decoder config found\n");
2721 return AVERROR(EAGAIN);
2723 if (latmctx->audio_mux_version_A == 0) {
2724 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2725 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2726 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2727 return AVERROR_INVALIDDATA;
2728 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2729 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2730 "frame length mismatch %d << %d\n",
2731 mux_slot_length_bytes * 8, get_bits_left(gb));
2732 return AVERROR_INVALIDDATA;
2739 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2740 int *got_frame_ptr, AVPacket *avpkt)
2742 struct LATMContext *latmctx = avctx->priv_data;
2746 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2748 // check for LOAS sync word
2749 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2750 return AVERROR_INVALIDDATA;
2752 muxlength = get_bits(&gb, 13) + 3;
2753 // not enough data, the parser should have sorted this
2754 if (muxlength > avpkt->size)
2755 return AVERROR_INVALIDDATA;
2757 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2760 if (!latmctx->initialized) {
2761 if (!avctx->extradata) {
2765 if ((err = decode_audio_specific_config(
2766 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.m4ac,
2767 avctx->extradata, avctx->extradata_size*8, 1)) < 0)
2769 latmctx->initialized = 1;
2773 if (show_bits(&gb, 12) == 0xfff) {
2774 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2775 "ADTS header detected, probably as result of configuration "
2777 return AVERROR_INVALIDDATA;
2780 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2786 av_cold static int latm_decode_init(AVCodecContext *avctx)
2788 struct LATMContext *latmctx = avctx->priv_data;
2789 int ret = aac_decode_init(avctx);
2791 if (avctx->extradata_size > 0)
2792 latmctx->initialized = !ret;
2798 AVCodec ff_aac_decoder = {
2800 .type = AVMEDIA_TYPE_AUDIO,
2802 .priv_data_size = sizeof(AACContext),
2803 .init = aac_decode_init,
2804 .close = aac_decode_close,
2805 .decode = aac_decode_frame,
2806 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2807 .sample_fmts = (const enum AVSampleFormat[]) {
2808 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2810 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2811 .channel_layouts = aac_channel_layout,
2815 Note: This decoder filter is intended to decode LATM streams transferred
2816 in MPEG transport streams which only contain one program.
2817 To do a more complex LATM demuxing a separate LATM demuxer should be used.
2819 AVCodec ff_aac_latm_decoder = {
2821 .type = AVMEDIA_TYPE_AUDIO,
2822 .id = CODEC_ID_AAC_LATM,
2823 .priv_data_size = sizeof(struct LATMContext),
2824 .init = latm_decode_init,
2825 .close = aac_decode_close,
2826 .decode = latm_decode_frame,
2827 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2828 .sample_fmts = (const enum AVSampleFormat[]) {
2829 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2831 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2832 .channel_layouts = aac_channel_layout,