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
82 #include "libavutil/float_dsp.h"
83 #include "libavutil/opt.h"
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"
111 # include "mips/aacdec_mips.h"
114 static VLC vlc_scalefactors;
115 static VLC vlc_spectral[11];
117 static int output_configure(AACContext *ac,
118 uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
119 enum OCStatus oc_type, int get_new_frame);
121 #define overread_err "Input buffer exhausted before END element found\n"
123 static int count_channels(uint8_t (*layout)[3], int tags)
126 for (i = 0; i < tags; i++) {
127 int syn_ele = layout[i][0];
128 int pos = layout[i][2];
129 sum += (1 + (syn_ele == TYPE_CPE)) *
130 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
136 * Check for the channel element in the current channel position configuration.
137 * If it exists, make sure the appropriate element is allocated and map the
138 * channel order to match the internal FFmpeg channel layout.
140 * @param che_pos current channel position configuration
141 * @param type channel element type
142 * @param id channel element id
143 * @param channels count of the number of channels in the configuration
145 * @return Returns error status. 0 - OK, !0 - error
147 static av_cold int che_configure(AACContext *ac,
148 enum ChannelPosition che_pos,
149 int type, int id, int *channels)
151 if (*channels >= MAX_CHANNELS)
152 return AVERROR_INVALIDDATA;
154 if (!ac->che[type][id]) {
155 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
156 return AVERROR(ENOMEM);
157 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
159 if (type != TYPE_CCE) {
160 if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
161 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
162 return AVERROR_INVALIDDATA;
164 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
165 if (type == TYPE_CPE ||
166 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
167 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
171 if (ac->che[type][id])
172 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
173 av_freep(&ac->che[type][id]);
178 static int frame_configure_elements(AVCodecContext *avctx)
180 AACContext *ac = avctx->priv_data;
181 int type, id, ch, ret;
183 /* set channel pointers to internal buffers by default */
184 for (type = 0; type < 4; type++) {
185 for (id = 0; id < MAX_ELEM_ID; id++) {
186 ChannelElement *che = ac->che[type][id];
188 che->ch[0].ret = che->ch[0].ret_buf;
189 che->ch[1].ret = che->ch[1].ret_buf;
194 /* get output buffer */
195 av_frame_unref(ac->frame);
196 ac->frame->nb_samples = 2048;
197 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
200 /* map output channel pointers to AVFrame data */
201 for (ch = 0; ch < avctx->channels; ch++) {
202 if (ac->output_element[ch])
203 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
209 struct elem_to_channel {
210 uint64_t av_position;
213 uint8_t aac_position;
216 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
217 uint8_t (*layout_map)[3], int offset, uint64_t left,
218 uint64_t right, int pos)
220 if (layout_map[offset][0] == TYPE_CPE) {
221 e2c_vec[offset] = (struct elem_to_channel) {
222 .av_position = left | right,
224 .elem_id = layout_map[offset][1],
229 e2c_vec[offset] = (struct elem_to_channel) {
232 .elem_id = layout_map[offset][1],
235 e2c_vec[offset + 1] = (struct elem_to_channel) {
236 .av_position = right,
238 .elem_id = layout_map[offset + 1][1],
245 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
248 int num_pos_channels = 0;
252 for (i = *current; i < tags; i++) {
253 if (layout_map[i][2] != pos)
255 if (layout_map[i][0] == TYPE_CPE) {
257 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
263 num_pos_channels += 2;
271 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
274 return num_pos_channels;
277 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
279 int i, n, total_non_cc_elements;
280 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
281 int num_front_channels, num_side_channels, num_back_channels;
284 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
289 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
290 if (num_front_channels < 0)
293 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
294 if (num_side_channels < 0)
297 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
298 if (num_back_channels < 0)
302 if (num_front_channels & 1) {
303 e2c_vec[i] = (struct elem_to_channel) {
304 .av_position = AV_CH_FRONT_CENTER,
306 .elem_id = layout_map[i][1],
307 .aac_position = AAC_CHANNEL_FRONT
310 num_front_channels--;
312 if (num_front_channels >= 4) {
313 i += assign_pair(e2c_vec, layout_map, i,
314 AV_CH_FRONT_LEFT_OF_CENTER,
315 AV_CH_FRONT_RIGHT_OF_CENTER,
317 num_front_channels -= 2;
319 if (num_front_channels >= 2) {
320 i += assign_pair(e2c_vec, layout_map, i,
324 num_front_channels -= 2;
326 while (num_front_channels >= 2) {
327 i += assign_pair(e2c_vec, layout_map, i,
331 num_front_channels -= 2;
334 if (num_side_channels >= 2) {
335 i += assign_pair(e2c_vec, layout_map, i,
339 num_side_channels -= 2;
341 while (num_side_channels >= 2) {
342 i += assign_pair(e2c_vec, layout_map, i,
346 num_side_channels -= 2;
349 while (num_back_channels >= 4) {
350 i += assign_pair(e2c_vec, layout_map, i,
354 num_back_channels -= 2;
356 if (num_back_channels >= 2) {
357 i += assign_pair(e2c_vec, layout_map, i,
361 num_back_channels -= 2;
363 if (num_back_channels) {
364 e2c_vec[i] = (struct elem_to_channel) {
365 .av_position = AV_CH_BACK_CENTER,
367 .elem_id = layout_map[i][1],
368 .aac_position = AAC_CHANNEL_BACK
374 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
375 e2c_vec[i] = (struct elem_to_channel) {
376 .av_position = AV_CH_LOW_FREQUENCY,
378 .elem_id = layout_map[i][1],
379 .aac_position = AAC_CHANNEL_LFE
383 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
384 e2c_vec[i] = (struct elem_to_channel) {
385 .av_position = UINT64_MAX,
387 .elem_id = layout_map[i][1],
388 .aac_position = AAC_CHANNEL_LFE
393 // Must choose a stable sort
394 total_non_cc_elements = n = i;
397 for (i = 1; i < n; i++)
398 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
399 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
406 for (i = 0; i < total_non_cc_elements; i++) {
407 layout_map[i][0] = e2c_vec[i].syn_ele;
408 layout_map[i][1] = e2c_vec[i].elem_id;
409 layout_map[i][2] = e2c_vec[i].aac_position;
410 if (e2c_vec[i].av_position != UINT64_MAX) {
411 layout |= e2c_vec[i].av_position;
419 * Save current output configuration if and only if it has been locked.
421 static void push_output_configuration(AACContext *ac) {
422 if (ac->oc[1].status == OC_LOCKED) {
423 ac->oc[0] = ac->oc[1];
425 ac->oc[1].status = OC_NONE;
429 * Restore the previous output configuration if and only if the current
430 * configuration is unlocked.
432 static void pop_output_configuration(AACContext *ac) {
433 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
434 ac->oc[1] = ac->oc[0];
435 ac->avctx->channels = ac->oc[1].channels;
436 ac->avctx->channel_layout = ac->oc[1].channel_layout;
437 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
438 ac->oc[1].status, 0);
443 * Configure output channel order based on the current program
444 * configuration element.
446 * @return Returns error status. 0 - OK, !0 - error
448 static int output_configure(AACContext *ac,
449 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
450 enum OCStatus oc_type, int get_new_frame)
452 AVCodecContext *avctx = ac->avctx;
453 int i, channels = 0, ret;
456 if (ac->oc[1].layout_map != layout_map) {
457 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
458 ac->oc[1].layout_map_tags = tags;
461 // Try to sniff a reasonable channel order, otherwise output the
462 // channels in the order the PCE declared them.
463 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
464 layout = sniff_channel_order(layout_map, tags);
465 for (i = 0; i < tags; i++) {
466 int type = layout_map[i][0];
467 int id = layout_map[i][1];
468 int position = layout_map[i][2];
469 // Allocate or free elements depending on if they are in the
470 // current program configuration.
471 ret = che_configure(ac, position, type, id, &channels);
475 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
476 if (layout == AV_CH_FRONT_CENTER) {
477 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
483 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
484 if (layout) avctx->channel_layout = layout;
485 ac->oc[1].channel_layout = layout;
486 avctx->channels = ac->oc[1].channels = channels;
487 ac->oc[1].status = oc_type;
490 if ((ret = frame_configure_elements(ac->avctx)) < 0)
497 static void flush(AVCodecContext *avctx)
499 AACContext *ac= avctx->priv_data;
502 for (type = 3; type >= 0; type--) {
503 for (i = 0; i < MAX_ELEM_ID; i++) {
504 ChannelElement *che = ac->che[type][i];
506 for (j = 0; j <= 1; j++) {
507 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
515 * Set up channel positions based on a default channel configuration
516 * as specified in table 1.17.
518 * @return Returns error status. 0 - OK, !0 - error
520 static int set_default_channel_config(AVCodecContext *avctx,
521 uint8_t (*layout_map)[3],
525 if (channel_config < 1 || channel_config > 7) {
526 av_log(avctx, AV_LOG_ERROR,
527 "invalid default channel configuration (%d)\n",
529 return AVERROR_INVALIDDATA;
531 *tags = tags_per_config[channel_config];
532 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
533 *tags * sizeof(*layout_map));
537 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
539 /* For PCE based channel configurations map the channels solely based
541 if (!ac->oc[1].m4ac.chan_config) {
542 return ac->tag_che_map[type][elem_id];
544 // Allow single CPE stereo files to be signalled with mono configuration.
545 if (!ac->tags_mapped && type == TYPE_CPE &&
546 ac->oc[1].m4ac.chan_config == 1) {
547 uint8_t layout_map[MAX_ELEM_ID*4][3];
549 push_output_configuration(ac);
551 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
553 if (set_default_channel_config(ac->avctx, layout_map,
554 &layout_map_tags, 2) < 0)
556 if (output_configure(ac, layout_map, layout_map_tags,
557 OC_TRIAL_FRAME, 1) < 0)
560 ac->oc[1].m4ac.chan_config = 2;
561 ac->oc[1].m4ac.ps = 0;
564 if (!ac->tags_mapped && type == TYPE_SCE &&
565 ac->oc[1].m4ac.chan_config == 2) {
566 uint8_t layout_map[MAX_ELEM_ID * 4][3];
568 push_output_configuration(ac);
570 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
572 if (set_default_channel_config(ac->avctx, layout_map,
573 &layout_map_tags, 1) < 0)
575 if (output_configure(ac, layout_map, layout_map_tags,
576 OC_TRIAL_FRAME, 1) < 0)
579 ac->oc[1].m4ac.chan_config = 1;
580 if (ac->oc[1].m4ac.sbr)
581 ac->oc[1].m4ac.ps = -1;
583 /* For indexed channel configurations map the channels solely based
585 switch (ac->oc[1].m4ac.chan_config) {
587 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
589 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
592 /* Some streams incorrectly code 5.1 audio as
593 * SCE[0] CPE[0] CPE[1] SCE[1]
595 * SCE[0] CPE[0] CPE[1] LFE[0].
596 * If we seem to have encountered such a stream, transfer
597 * the LFE[0] element to the SCE[1]'s mapping */
598 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
600 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
603 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
605 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
608 if (ac->tags_mapped == 2 &&
609 ac->oc[1].m4ac.chan_config == 4 &&
612 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
616 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
619 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
620 } else if (ac->oc[1].m4ac.chan_config == 2) {
624 if (!ac->tags_mapped && type == TYPE_SCE) {
626 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
634 * Decode an array of 4 bit element IDs, optionally interleaved with a
635 * stereo/mono switching bit.
637 * @param type speaker type/position for these channels
639 static void decode_channel_map(uint8_t layout_map[][3],
640 enum ChannelPosition type,
641 GetBitContext *gb, int n)
644 enum RawDataBlockType syn_ele;
646 case AAC_CHANNEL_FRONT:
647 case AAC_CHANNEL_BACK:
648 case AAC_CHANNEL_SIDE:
649 syn_ele = get_bits1(gb);
655 case AAC_CHANNEL_LFE:
661 layout_map[0][0] = syn_ele;
662 layout_map[0][1] = get_bits(gb, 4);
663 layout_map[0][2] = type;
669 * Decode program configuration element; reference: table 4.2.
671 * @return Returns error status. 0 - OK, !0 - error
673 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
674 uint8_t (*layout_map)[3],
677 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
682 skip_bits(gb, 2); // object_type
684 sampling_index = get_bits(gb, 4);
685 if (m4ac->sampling_index != sampling_index)
686 av_log(avctx, AV_LOG_WARNING,
687 "Sample rate index in program config element does not "
688 "match the sample rate index configured by the container.\n");
690 num_front = get_bits(gb, 4);
691 num_side = get_bits(gb, 4);
692 num_back = get_bits(gb, 4);
693 num_lfe = get_bits(gb, 2);
694 num_assoc_data = get_bits(gb, 3);
695 num_cc = get_bits(gb, 4);
698 skip_bits(gb, 4); // mono_mixdown_tag
700 skip_bits(gb, 4); // stereo_mixdown_tag
703 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
705 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
706 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
709 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
711 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
713 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
715 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
718 skip_bits_long(gb, 4 * num_assoc_data);
720 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
725 /* comment field, first byte is length */
726 comment_len = get_bits(gb, 8) * 8;
727 if (get_bits_left(gb) < comment_len) {
728 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
729 return AVERROR_INVALIDDATA;
731 skip_bits_long(gb, comment_len);
736 * Decode GA "General Audio" specific configuration; reference: table 4.1.
738 * @param ac pointer to AACContext, may be null
739 * @param avctx pointer to AVCCodecContext, used for logging
741 * @return Returns error status. 0 - OK, !0 - error
743 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
745 MPEG4AudioConfig *m4ac,
748 int extension_flag, ret, ep_config, res_flags;
749 uint8_t layout_map[MAX_ELEM_ID*4][3];
752 if (get_bits1(gb)) { // frameLengthFlag
753 avpriv_request_sample(avctx, "960/120 MDCT window");
754 return AVERROR_PATCHWELCOME;
757 if (get_bits1(gb)) // dependsOnCoreCoder
758 skip_bits(gb, 14); // coreCoderDelay
759 extension_flag = get_bits1(gb);
761 if (m4ac->object_type == AOT_AAC_SCALABLE ||
762 m4ac->object_type == AOT_ER_AAC_SCALABLE)
763 skip_bits(gb, 3); // layerNr
765 if (channel_config == 0) {
766 skip_bits(gb, 4); // element_instance_tag
767 tags = decode_pce(avctx, m4ac, layout_map, gb);
771 if ((ret = set_default_channel_config(avctx, layout_map,
772 &tags, channel_config)))
776 if (count_channels(layout_map, tags) > 1) {
778 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
781 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
784 if (extension_flag) {
785 switch (m4ac->object_type) {
787 skip_bits(gb, 5); // numOfSubFrame
788 skip_bits(gb, 11); // layer_length
792 case AOT_ER_AAC_SCALABLE:
794 res_flags = get_bits(gb, 3);
796 avpriv_report_missing_feature(avctx, AV_LOG_ERROR,
797 "AAC data resilience (flags %x)",
799 return AVERROR_PATCHWELCOME;
803 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
805 switch (m4ac->object_type) {
808 case AOT_ER_AAC_SCALABLE:
810 ep_config = get_bits(gb, 2);
812 avpriv_report_missing_feature(avctx, AV_LOG_ERROR,
813 "epConfig %d", ep_config);
814 return AVERROR_PATCHWELCOME;
821 * Decode audio specific configuration; reference: table 1.13.
823 * @param ac pointer to AACContext, may be null
824 * @param avctx pointer to AVCCodecContext, used for logging
825 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
826 * @param data pointer to buffer holding an audio specific config
827 * @param bit_size size of audio specific config or data in bits
828 * @param sync_extension look for an appended sync extension
830 * @return Returns error status or number of consumed bits. <0 - error
832 static int decode_audio_specific_config(AACContext *ac,
833 AVCodecContext *avctx,
834 MPEG4AudioConfig *m4ac,
835 const uint8_t *data, int bit_size,
841 av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
842 for (i = 0; i < bit_size >> 3; i++)
843 av_dlog(avctx, "%02x ", data[i]);
844 av_dlog(avctx, "\n");
846 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
849 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
850 sync_extension)) < 0)
851 return AVERROR_INVALIDDATA;
852 if (m4ac->sampling_index > 12) {
853 av_log(avctx, AV_LOG_ERROR,
854 "invalid sampling rate index %d\n",
855 m4ac->sampling_index);
856 return AVERROR_INVALIDDATA;
858 if (m4ac->object_type == AOT_ER_AAC_LD &&
859 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
860 av_log(avctx, AV_LOG_ERROR,
861 "invalid low delay sampling rate index %d\n",
862 m4ac->sampling_index);
863 return AVERROR_INVALIDDATA;
866 skip_bits_long(&gb, i);
868 switch (m4ac->object_type) {
874 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
875 m4ac, m4ac->chan_config)) < 0)
879 avpriv_report_missing_feature(avctx, AV_LOG_ERROR,
880 "Audio object type %s%d",
881 m4ac->sbr == 1 ? "SBR+" : "",
883 return AVERROR(ENOSYS);
887 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
888 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
889 m4ac->sample_rate, m4ac->sbr,
892 return get_bits_count(&gb);
896 * linear congruential pseudorandom number generator
898 * @param previous_val pointer to the current state of the generator
900 * @return Returns a 32-bit pseudorandom integer
902 static av_always_inline int lcg_random(unsigned previous_val)
904 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
908 static av_always_inline void reset_predict_state(PredictorState *ps)
918 static void reset_all_predictors(PredictorState *ps)
921 for (i = 0; i < MAX_PREDICTORS; i++)
922 reset_predict_state(&ps[i]);
925 static int sample_rate_idx (int rate)
927 if (92017 <= rate) return 0;
928 else if (75132 <= rate) return 1;
929 else if (55426 <= rate) return 2;
930 else if (46009 <= rate) return 3;
931 else if (37566 <= rate) return 4;
932 else if (27713 <= rate) return 5;
933 else if (23004 <= rate) return 6;
934 else if (18783 <= rate) return 7;
935 else if (13856 <= rate) return 8;
936 else if (11502 <= rate) return 9;
937 else if (9391 <= rate) return 10;
941 static void reset_predictor_group(PredictorState *ps, int group_num)
944 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
945 reset_predict_state(&ps[i]);
948 #define AAC_INIT_VLC_STATIC(num, size) \
949 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
950 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
951 sizeof(ff_aac_spectral_bits[num][0]), \
952 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
953 sizeof(ff_aac_spectral_codes[num][0]), \
956 static void aacdec_init(AACContext *ac);
958 static av_cold int aac_decode_init(AVCodecContext *avctx)
960 AACContext *ac = avctx->priv_data;
964 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
968 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
970 if (avctx->extradata_size > 0) {
971 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
973 avctx->extradata_size * 8,
978 uint8_t layout_map[MAX_ELEM_ID*4][3];
981 sr = sample_rate_idx(avctx->sample_rate);
982 ac->oc[1].m4ac.sampling_index = sr;
983 ac->oc[1].m4ac.channels = avctx->channels;
984 ac->oc[1].m4ac.sbr = -1;
985 ac->oc[1].m4ac.ps = -1;
987 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
988 if (ff_mpeg4audio_channels[i] == avctx->channels)
990 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
993 ac->oc[1].m4ac.chan_config = i;
995 if (ac->oc[1].m4ac.chan_config) {
996 int ret = set_default_channel_config(avctx, layout_map,
997 &layout_map_tags, ac->oc[1].m4ac.chan_config);
999 output_configure(ac, layout_map, layout_map_tags,
1001 else if (avctx->err_recognition & AV_EF_EXPLODE)
1002 return AVERROR_INVALIDDATA;
1006 if (avctx->channels > MAX_CHANNELS) {
1007 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1008 return AVERROR_INVALIDDATA;
1011 AAC_INIT_VLC_STATIC( 0, 304);
1012 AAC_INIT_VLC_STATIC( 1, 270);
1013 AAC_INIT_VLC_STATIC( 2, 550);
1014 AAC_INIT_VLC_STATIC( 3, 300);
1015 AAC_INIT_VLC_STATIC( 4, 328);
1016 AAC_INIT_VLC_STATIC( 5, 294);
1017 AAC_INIT_VLC_STATIC( 6, 306);
1018 AAC_INIT_VLC_STATIC( 7, 268);
1019 AAC_INIT_VLC_STATIC( 8, 510);
1020 AAC_INIT_VLC_STATIC( 9, 366);
1021 AAC_INIT_VLC_STATIC(10, 462);
1025 ff_fmt_convert_init(&ac->fmt_conv, avctx);
1026 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
1028 ac->random_state = 0x1f2e3d4c;
1032 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1033 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1034 ff_aac_scalefactor_bits,
1035 sizeof(ff_aac_scalefactor_bits[0]),
1036 sizeof(ff_aac_scalefactor_bits[0]),
1037 ff_aac_scalefactor_code,
1038 sizeof(ff_aac_scalefactor_code[0]),
1039 sizeof(ff_aac_scalefactor_code[0]),
1042 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1043 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1044 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1045 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1046 // window initialization
1047 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1048 ff_kbd_window_init(ff_aac_kbd_long_512, 4.0, 512);
1049 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1050 ff_init_ff_sine_windows(10);
1051 ff_init_ff_sine_windows( 9);
1052 ff_init_ff_sine_windows( 7);
1060 * Skip data_stream_element; reference: table 4.10.
1062 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1064 int byte_align = get_bits1(gb);
1065 int count = get_bits(gb, 8);
1067 count += get_bits(gb, 8);
1071 if (get_bits_left(gb) < 8 * count) {
1072 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1073 return AVERROR_INVALIDDATA;
1075 skip_bits_long(gb, 8 * count);
1079 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1083 if (get_bits1(gb)) {
1084 ics->predictor_reset_group = get_bits(gb, 5);
1085 if (ics->predictor_reset_group == 0 ||
1086 ics->predictor_reset_group > 30) {
1087 av_log(ac->avctx, AV_LOG_ERROR,
1088 "Invalid Predictor Reset Group.\n");
1089 return AVERROR_INVALIDDATA;
1092 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1093 ics->prediction_used[sfb] = get_bits1(gb);
1099 * Decode Long Term Prediction data; reference: table 4.xx.
1101 static void decode_ltp(LongTermPrediction *ltp,
1102 GetBitContext *gb, uint8_t max_sfb)
1106 ltp->lag = get_bits(gb, 11);
1107 ltp->coef = ltp_coef[get_bits(gb, 3)];
1108 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1109 ltp->used[sfb] = get_bits1(gb);
1113 * Decode Individual Channel Stream info; reference: table 4.6.
1115 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1118 if (get_bits1(gb)) {
1119 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1120 return AVERROR_INVALIDDATA;
1122 ics->window_sequence[1] = ics->window_sequence[0];
1123 ics->window_sequence[0] = get_bits(gb, 2);
1124 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD &&
1125 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1126 av_log(ac->avctx, AV_LOG_ERROR,
1127 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1128 "window sequence %d found.\n", ics->window_sequence[0]);
1129 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1130 return AVERROR_INVALIDDATA;
1132 ics->use_kb_window[1] = ics->use_kb_window[0];
1133 ics->use_kb_window[0] = get_bits1(gb);
1134 ics->num_window_groups = 1;
1135 ics->group_len[0] = 1;
1136 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1138 ics->max_sfb = get_bits(gb, 4);
1139 for (i = 0; i < 7; i++) {
1140 if (get_bits1(gb)) {
1141 ics->group_len[ics->num_window_groups - 1]++;
1143 ics->num_window_groups++;
1144 ics->group_len[ics->num_window_groups - 1] = 1;
1147 ics->num_windows = 8;
1148 ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1149 ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1150 ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1151 ics->predictor_present = 0;
1153 ics->max_sfb = get_bits(gb, 6);
1154 ics->num_windows = 1;
1155 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD) {
1156 ics->swb_offset = ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];
1157 ics->num_swb = ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];
1158 if (!ics->num_swb || !ics->swb_offset)
1161 ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1162 ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1164 ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1165 ics->predictor_present = get_bits1(gb);
1166 ics->predictor_reset_group = 0;
1167 if (ics->predictor_present) {
1168 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1169 if (decode_prediction(ac, ics, gb)) {
1172 } else if (ac->oc[1].m4ac.object_type == AOT_AAC_LC ||
1173 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC) {
1174 av_log(ac->avctx, AV_LOG_ERROR,
1175 "Prediction is not allowed in AAC-LC.\n");
1178 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD) {
1179 av_log(ac->avctx, AV_LOG_ERROR,
1180 "LTP in ER AAC LD not yet implemented.\n");
1181 return AVERROR_PATCHWELCOME;
1183 if ((ics->ltp.present = get_bits(gb, 1)))
1184 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1189 if (ics->max_sfb > ics->num_swb) {
1190 av_log(ac->avctx, AV_LOG_ERROR,
1191 "Number of scalefactor bands in group (%d) "
1192 "exceeds limit (%d).\n",
1193 ics->max_sfb, ics->num_swb);
1200 return AVERROR_INVALIDDATA;
1204 * Decode band types (section_data payload); reference: table 4.46.
1206 * @param band_type array of the used band type
1207 * @param band_type_run_end array of the last scalefactor band of a band type run
1209 * @return Returns error status. 0 - OK, !0 - error
1211 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1212 int band_type_run_end[120], GetBitContext *gb,
1213 IndividualChannelStream *ics)
1216 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1217 for (g = 0; g < ics->num_window_groups; g++) {
1219 while (k < ics->max_sfb) {
1220 uint8_t sect_end = k;
1222 int sect_band_type = get_bits(gb, 4);
1223 if (sect_band_type == 12) {
1224 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1225 return AVERROR_INVALIDDATA;
1228 sect_len_incr = get_bits(gb, bits);
1229 sect_end += sect_len_incr;
1230 if (get_bits_left(gb) < 0) {
1231 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1232 return AVERROR_INVALIDDATA;
1234 if (sect_end > ics->max_sfb) {
1235 av_log(ac->avctx, AV_LOG_ERROR,
1236 "Number of bands (%d) exceeds limit (%d).\n",
1237 sect_end, ics->max_sfb);
1238 return AVERROR_INVALIDDATA;
1240 } while (sect_len_incr == (1 << bits) - 1);
1241 for (; k < sect_end; k++) {
1242 band_type [idx] = sect_band_type;
1243 band_type_run_end[idx++] = sect_end;
1251 * Decode scalefactors; reference: table 4.47.
1253 * @param global_gain first scalefactor value as scalefactors are differentially coded
1254 * @param band_type array of the used band type
1255 * @param band_type_run_end array of the last scalefactor band of a band type run
1256 * @param sf array of scalefactors or intensity stereo positions
1258 * @return Returns error status. 0 - OK, !0 - error
1260 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1261 unsigned int global_gain,
1262 IndividualChannelStream *ics,
1263 enum BandType band_type[120],
1264 int band_type_run_end[120])
1267 int offset[3] = { global_gain, global_gain - 90, 0 };
1270 for (g = 0; g < ics->num_window_groups; g++) {
1271 for (i = 0; i < ics->max_sfb;) {
1272 int run_end = band_type_run_end[idx];
1273 if (band_type[idx] == ZERO_BT) {
1274 for (; i < run_end; i++, idx++)
1276 } else if ((band_type[idx] == INTENSITY_BT) ||
1277 (band_type[idx] == INTENSITY_BT2)) {
1278 for (; i < run_end; i++, idx++) {
1279 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1280 clipped_offset = av_clip(offset[2], -155, 100);
1281 if (offset[2] != clipped_offset) {
1282 avpriv_request_sample(ac->avctx,
1283 "If you heard an audible artifact, there may be a bug in the decoder. "
1284 "Clipped intensity stereo position (%d -> %d)",
1285 offset[2], clipped_offset);
1287 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1289 } else if (band_type[idx] == NOISE_BT) {
1290 for (; i < run_end; i++, idx++) {
1291 if (noise_flag-- > 0)
1292 offset[1] += get_bits(gb, 9) - 256;
1294 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1295 clipped_offset = av_clip(offset[1], -100, 155);
1296 if (offset[1] != clipped_offset) {
1297 avpriv_request_sample(ac->avctx,
1298 "If you heard an audible artifact, there may be a bug in the decoder. "
1299 "Clipped noise gain (%d -> %d)",
1300 offset[1], clipped_offset);
1302 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1305 for (; i < run_end; i++, idx++) {
1306 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1307 if (offset[0] > 255U) {
1308 av_log(ac->avctx, AV_LOG_ERROR,
1309 "Scalefactor (%d) out of range.\n", offset[0]);
1310 return AVERROR_INVALIDDATA;
1312 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1321 * Decode pulse data; reference: table 4.7.
1323 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1324 const uint16_t *swb_offset, int num_swb)
1327 pulse->num_pulse = get_bits(gb, 2) + 1;
1328 pulse_swb = get_bits(gb, 6);
1329 if (pulse_swb >= num_swb)
1331 pulse->pos[0] = swb_offset[pulse_swb];
1332 pulse->pos[0] += get_bits(gb, 5);
1333 if (pulse->pos[0] > 1023)
1335 pulse->amp[0] = get_bits(gb, 4);
1336 for (i = 1; i < pulse->num_pulse; i++) {
1337 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1338 if (pulse->pos[i] > 1023)
1340 pulse->amp[i] = get_bits(gb, 4);
1346 * Decode Temporal Noise Shaping data; reference: table 4.48.
1348 * @return Returns error status. 0 - OK, !0 - error
1350 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1351 GetBitContext *gb, const IndividualChannelStream *ics)
1353 int w, filt, i, coef_len, coef_res, coef_compress;
1354 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1355 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1356 for (w = 0; w < ics->num_windows; w++) {
1357 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1358 coef_res = get_bits1(gb);
1360 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1362 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1364 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1365 av_log(ac->avctx, AV_LOG_ERROR,
1366 "TNS filter order %d is greater than maximum %d.\n",
1367 tns->order[w][filt], tns_max_order);
1368 tns->order[w][filt] = 0;
1369 return AVERROR_INVALIDDATA;
1371 if (tns->order[w][filt]) {
1372 tns->direction[w][filt] = get_bits1(gb);
1373 coef_compress = get_bits1(gb);
1374 coef_len = coef_res + 3 - coef_compress;
1375 tmp2_idx = 2 * coef_compress + coef_res;
1377 for (i = 0; i < tns->order[w][filt]; i++)
1378 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1387 * Decode Mid/Side data; reference: table 4.54.
1389 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1390 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1391 * [3] reserved for scalable AAC
1393 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1397 if (ms_present == 1) {
1399 idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1401 cpe->ms_mask[idx] = get_bits1(gb);
1402 } else if (ms_present == 2) {
1403 memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1408 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1412 *dst++ = v[idx & 15] * s;
1413 *dst++ = v[idx>>4 & 15] * s;
1419 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1423 *dst++ = v[idx & 3] * s;
1424 *dst++ = v[idx>>2 & 3] * s;
1425 *dst++ = v[idx>>4 & 3] * s;
1426 *dst++ = v[idx>>6 & 3] * s;
1432 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1433 unsigned sign, const float *scale)
1435 union av_intfloat32 s0, s1;
1437 s0.f = s1.f = *scale;
1438 s0.i ^= sign >> 1 << 31;
1441 *dst++ = v[idx & 15] * s0.f;
1442 *dst++ = v[idx>>4 & 15] * s1.f;
1449 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1450 unsigned sign, const float *scale)
1452 unsigned nz = idx >> 12;
1453 union av_intfloat32 s = { .f = *scale };
1454 union av_intfloat32 t;
1456 t.i = s.i ^ (sign & 1U<<31);
1457 *dst++ = v[idx & 3] * t.f;
1459 sign <<= nz & 1; nz >>= 1;
1460 t.i = s.i ^ (sign & 1U<<31);
1461 *dst++ = v[idx>>2 & 3] * t.f;
1463 sign <<= nz & 1; nz >>= 1;
1464 t.i = s.i ^ (sign & 1U<<31);
1465 *dst++ = v[idx>>4 & 3] * t.f;
1468 t.i = s.i ^ (sign & 1U<<31);
1469 *dst++ = v[idx>>6 & 3] * t.f;
1476 * Decode spectral data; reference: table 4.50.
1477 * Dequantize and scale spectral data; reference: 4.6.3.3.
1479 * @param coef array of dequantized, scaled spectral data
1480 * @param sf array of scalefactors or intensity stereo positions
1481 * @param pulse_present set if pulses are present
1482 * @param pulse pointer to pulse data struct
1483 * @param band_type array of the used band type
1485 * @return Returns error status. 0 - OK, !0 - error
1487 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1488 GetBitContext *gb, const float sf[120],
1489 int pulse_present, const Pulse *pulse,
1490 const IndividualChannelStream *ics,
1491 enum BandType band_type[120])
1493 int i, k, g, idx = 0;
1494 const int c = 1024 / ics->num_windows;
1495 const uint16_t *offsets = ics->swb_offset;
1496 float *coef_base = coef;
1498 for (g = 0; g < ics->num_windows; g++)
1499 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1500 sizeof(float) * (c - offsets[ics->max_sfb]));
1502 for (g = 0; g < ics->num_window_groups; g++) {
1503 unsigned g_len = ics->group_len[g];
1505 for (i = 0; i < ics->max_sfb; i++, idx++) {
1506 const unsigned cbt_m1 = band_type[idx] - 1;
1507 float *cfo = coef + offsets[i];
1508 int off_len = offsets[i + 1] - offsets[i];
1511 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1512 for (group = 0; group < g_len; group++, cfo+=128) {
1513 memset(cfo, 0, off_len * sizeof(float));
1515 } else if (cbt_m1 == NOISE_BT - 1) {
1516 for (group = 0; group < g_len; group++, cfo+=128) {
1520 for (k = 0; k < off_len; k++) {
1521 ac->random_state = lcg_random(ac->random_state);
1522 cfo[k] = ac->random_state;
1525 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1526 scale = sf[idx] / sqrtf(band_energy);
1527 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1530 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1531 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1532 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1533 OPEN_READER(re, gb);
1535 switch (cbt_m1 >> 1) {
1537 for (group = 0; group < g_len; group++, cfo+=128) {
1545 UPDATE_CACHE(re, gb);
1546 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1547 cb_idx = cb_vector_idx[code];
1548 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1554 for (group = 0; group < g_len; group++, cfo+=128) {
1564 UPDATE_CACHE(re, gb);
1565 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1566 cb_idx = cb_vector_idx[code];
1567 nnz = cb_idx >> 8 & 15;
1568 bits = nnz ? GET_CACHE(re, gb) : 0;
1569 LAST_SKIP_BITS(re, gb, nnz);
1570 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1576 for (group = 0; group < g_len; group++, cfo+=128) {
1584 UPDATE_CACHE(re, gb);
1585 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1586 cb_idx = cb_vector_idx[code];
1587 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1594 for (group = 0; group < g_len; group++, cfo+=128) {
1604 UPDATE_CACHE(re, gb);
1605 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1606 cb_idx = cb_vector_idx[code];
1607 nnz = cb_idx >> 8 & 15;
1608 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1609 LAST_SKIP_BITS(re, gb, nnz);
1610 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1616 for (group = 0; group < g_len; group++, cfo+=128) {
1618 uint32_t *icf = (uint32_t *) cf;
1628 UPDATE_CACHE(re, gb);
1629 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1637 cb_idx = cb_vector_idx[code];
1640 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1641 LAST_SKIP_BITS(re, gb, nnz);
1643 for (j = 0; j < 2; j++) {
1647 /* The total length of escape_sequence must be < 22 bits according
1648 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1649 UPDATE_CACHE(re, gb);
1650 b = GET_CACHE(re, gb);
1651 b = 31 - av_log2(~b);
1654 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1655 return AVERROR_INVALIDDATA;
1658 SKIP_BITS(re, gb, b + 1);
1660 n = (1 << b) + SHOW_UBITS(re, gb, b);
1661 LAST_SKIP_BITS(re, gb, b);
1662 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1665 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1666 *icf++ = (bits & 1U<<31) | v;
1673 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1677 CLOSE_READER(re, gb);
1683 if (pulse_present) {
1685 for (i = 0; i < pulse->num_pulse; i++) {
1686 float co = coef_base[ pulse->pos[i] ];
1687 while (offsets[idx + 1] <= pulse->pos[i])
1689 if (band_type[idx] != NOISE_BT && sf[idx]) {
1690 float ico = -pulse->amp[i];
1693 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1695 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1702 static av_always_inline float flt16_round(float pf)
1704 union av_intfloat32 tmp;
1706 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1710 static av_always_inline float flt16_even(float pf)
1712 union av_intfloat32 tmp;
1714 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1718 static av_always_inline float flt16_trunc(float pf)
1720 union av_intfloat32 pun;
1722 pun.i &= 0xFFFF0000U;
1726 static av_always_inline void predict(PredictorState *ps, float *coef,
1729 const float a = 0.953125; // 61.0 / 64
1730 const float alpha = 0.90625; // 29.0 / 32
1734 float r0 = ps->r0, r1 = ps->r1;
1735 float cor0 = ps->cor0, cor1 = ps->cor1;
1736 float var0 = ps->var0, var1 = ps->var1;
1738 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1739 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1741 pv = flt16_round(k1 * r0 + k2 * r1);
1748 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1749 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1750 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1751 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1753 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1754 ps->r0 = flt16_trunc(a * e0);
1758 * Apply AAC-Main style frequency domain prediction.
1760 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1764 if (!sce->ics.predictor_initialized) {
1765 reset_all_predictors(sce->predictor_state);
1766 sce->ics.predictor_initialized = 1;
1769 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1771 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1773 for (k = sce->ics.swb_offset[sfb];
1774 k < sce->ics.swb_offset[sfb + 1];
1776 predict(&sce->predictor_state[k], &sce->coeffs[k],
1777 sce->ics.predictor_present &&
1778 sce->ics.prediction_used[sfb]);
1781 if (sce->ics.predictor_reset_group)
1782 reset_predictor_group(sce->predictor_state,
1783 sce->ics.predictor_reset_group);
1785 reset_all_predictors(sce->predictor_state);
1789 * Decode an individual_channel_stream payload; reference: table 4.44.
1791 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1792 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1794 * @return Returns error status. 0 - OK, !0 - error
1796 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1797 GetBitContext *gb, int common_window, int scale_flag)
1800 TemporalNoiseShaping *tns = &sce->tns;
1801 IndividualChannelStream *ics = &sce->ics;
1802 float *out = sce->coeffs;
1803 int global_gain, er_syntax, pulse_present = 0;
1806 /* This assignment is to silence a GCC warning about the variable being used
1807 * uninitialized when in fact it always is.
1809 pulse.num_pulse = 0;
1811 global_gain = get_bits(gb, 8);
1813 if (!common_window && !scale_flag) {
1814 if (decode_ics_info(ac, ics, gb) < 0)
1815 return AVERROR_INVALIDDATA;
1818 if ((ret = decode_band_types(ac, sce->band_type,
1819 sce->band_type_run_end, gb, ics)) < 0)
1821 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1822 sce->band_type, sce->band_type_run_end)) < 0)
1826 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1827 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1828 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD;
1830 if ((pulse_present = get_bits1(gb))) {
1831 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1832 av_log(ac->avctx, AV_LOG_ERROR,
1833 "Pulse tool not allowed in eight short sequence.\n");
1834 return AVERROR_INVALIDDATA;
1836 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1837 av_log(ac->avctx, AV_LOG_ERROR,
1838 "Pulse data corrupt or invalid.\n");
1839 return AVERROR_INVALIDDATA;
1842 tns->present = get_bits1(gb);
1843 if (tns->present && !er_syntax)
1844 if (decode_tns(ac, tns, gb, ics) < 0)
1845 return AVERROR_INVALIDDATA;
1846 if (get_bits1(gb)) {
1847 avpriv_request_sample(ac->avctx, "SSR");
1848 return AVERROR_PATCHWELCOME;
1850 // I see no textual basis in the spec for this occuring after SSR gain
1851 // control, but this is what both reference and real implmentations do
1852 if (tns->present && er_syntax)
1853 if (decode_tns(ac, tns, gb, ics) < 0)
1854 return AVERROR_INVALIDDATA;
1857 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1858 &pulse, ics, sce->band_type) < 0)
1859 return AVERROR_INVALIDDATA;
1861 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1862 apply_prediction(ac, sce);
1868 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1870 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1872 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1873 float *ch0 = cpe->ch[0].coeffs;
1874 float *ch1 = cpe->ch[1].coeffs;
1875 int g, i, group, idx = 0;
1876 const uint16_t *offsets = ics->swb_offset;
1877 for (g = 0; g < ics->num_window_groups; g++) {
1878 for (i = 0; i < ics->max_sfb; i++, idx++) {
1879 if (cpe->ms_mask[idx] &&
1880 cpe->ch[0].band_type[idx] < NOISE_BT &&
1881 cpe->ch[1].band_type[idx] < NOISE_BT) {
1882 for (group = 0; group < ics->group_len[g]; group++) {
1883 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1884 ch1 + group * 128 + offsets[i],
1885 offsets[i+1] - offsets[i]);
1889 ch0 += ics->group_len[g] * 128;
1890 ch1 += ics->group_len[g] * 128;
1895 * intensity stereo decoding; reference: 4.6.8.2.3
1897 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1898 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1899 * [3] reserved for scalable AAC
1901 static void apply_intensity_stereo(AACContext *ac,
1902 ChannelElement *cpe, int ms_present)
1904 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1905 SingleChannelElement *sce1 = &cpe->ch[1];
1906 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1907 const uint16_t *offsets = ics->swb_offset;
1908 int g, group, i, idx = 0;
1911 for (g = 0; g < ics->num_window_groups; g++) {
1912 for (i = 0; i < ics->max_sfb;) {
1913 if (sce1->band_type[idx] == INTENSITY_BT ||
1914 sce1->band_type[idx] == INTENSITY_BT2) {
1915 const int bt_run_end = sce1->band_type_run_end[idx];
1916 for (; i < bt_run_end; i++, idx++) {
1917 c = -1 + 2 * (sce1->band_type[idx] - 14);
1919 c *= 1 - 2 * cpe->ms_mask[idx];
1920 scale = c * sce1->sf[idx];
1921 for (group = 0; group < ics->group_len[g]; group++)
1922 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1923 coef0 + group * 128 + offsets[i],
1925 offsets[i + 1] - offsets[i]);
1928 int bt_run_end = sce1->band_type_run_end[idx];
1929 idx += bt_run_end - i;
1933 coef0 += ics->group_len[g] * 128;
1934 coef1 += ics->group_len[g] * 128;
1939 * Decode a channel_pair_element; reference: table 4.4.
1941 * @return Returns error status. 0 - OK, !0 - error
1943 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1945 int i, ret, common_window, ms_present = 0;
1947 common_window = get_bits1(gb);
1948 if (common_window) {
1949 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1950 return AVERROR_INVALIDDATA;
1951 i = cpe->ch[1].ics.use_kb_window[0];
1952 cpe->ch[1].ics = cpe->ch[0].ics;
1953 cpe->ch[1].ics.use_kb_window[1] = i;
1954 if (cpe->ch[1].ics.predictor_present &&
1955 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1956 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1957 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1958 ms_present = get_bits(gb, 2);
1959 if (ms_present == 3) {
1960 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1961 return AVERROR_INVALIDDATA;
1962 } else if (ms_present)
1963 decode_mid_side_stereo(cpe, gb, ms_present);
1965 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1967 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1970 if (common_window) {
1972 apply_mid_side_stereo(ac, cpe);
1973 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1974 apply_prediction(ac, &cpe->ch[0]);
1975 apply_prediction(ac, &cpe->ch[1]);
1979 apply_intensity_stereo(ac, cpe, ms_present);
1983 static const float cce_scale[] = {
1984 1.09050773266525765921, //2^(1/8)
1985 1.18920711500272106672, //2^(1/4)
1991 * Decode coupling_channel_element; reference: table 4.8.
1993 * @return Returns error status. 0 - OK, !0 - error
1995 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2001 SingleChannelElement *sce = &che->ch[0];
2002 ChannelCoupling *coup = &che->coup;
2004 coup->coupling_point = 2 * get_bits1(gb);
2005 coup->num_coupled = get_bits(gb, 3);
2006 for (c = 0; c <= coup->num_coupled; c++) {
2008 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2009 coup->id_select[c] = get_bits(gb, 4);
2010 if (coup->type[c] == TYPE_CPE) {
2011 coup->ch_select[c] = get_bits(gb, 2);
2012 if (coup->ch_select[c] == 3)
2015 coup->ch_select[c] = 2;
2017 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2019 sign = get_bits(gb, 1);
2020 scale = cce_scale[get_bits(gb, 2)];
2022 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2025 for (c = 0; c < num_gain; c++) {
2029 float gain_cache = 1.0;
2031 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2032 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2033 gain_cache = powf(scale, -gain);
2035 if (coup->coupling_point == AFTER_IMDCT) {
2036 coup->gain[c][0] = gain_cache;
2038 for (g = 0; g < sce->ics.num_window_groups; g++) {
2039 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2040 if (sce->band_type[idx] != ZERO_BT) {
2042 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2050 gain_cache = powf(scale, -t) * s;
2053 coup->gain[c][idx] = gain_cache;
2063 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2065 * @return Returns number of bytes consumed.
2067 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2071 int num_excl_chan = 0;
2074 for (i = 0; i < 7; i++)
2075 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2076 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2078 return num_excl_chan / 7;
2082 * Decode dynamic range information; reference: table 4.52.
2084 * @return Returns number of bytes consumed.
2086 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2090 int drc_num_bands = 1;
2093 /* pce_tag_present? */
2094 if (get_bits1(gb)) {
2095 che_drc->pce_instance_tag = get_bits(gb, 4);
2096 skip_bits(gb, 4); // tag_reserved_bits
2100 /* excluded_chns_present? */
2101 if (get_bits1(gb)) {
2102 n += decode_drc_channel_exclusions(che_drc, gb);
2105 /* drc_bands_present? */
2106 if (get_bits1(gb)) {
2107 che_drc->band_incr = get_bits(gb, 4);
2108 che_drc->interpolation_scheme = get_bits(gb, 4);
2110 drc_num_bands += che_drc->band_incr;
2111 for (i = 0; i < drc_num_bands; i++) {
2112 che_drc->band_top[i] = get_bits(gb, 8);
2117 /* prog_ref_level_present? */
2118 if (get_bits1(gb)) {
2119 che_drc->prog_ref_level = get_bits(gb, 7);
2120 skip_bits1(gb); // prog_ref_level_reserved_bits
2124 for (i = 0; i < drc_num_bands; i++) {
2125 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2126 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2133 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2135 int i, major, minor;
2140 get_bits(gb, 13); len -= 13;
2142 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2143 buf[i] = get_bits(gb, 8);
2146 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2147 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2149 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2150 ac->avctx->internal->skip_samples = 1024;
2154 skip_bits_long(gb, len);
2160 * Decode extension data (incomplete); reference: table 4.51.
2162 * @param cnt length of TYPE_FIL syntactic element in bytes
2164 * @return Returns number of bytes consumed
2166 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2167 ChannelElement *che, enum RawDataBlockType elem_type)
2171 switch (get_bits(gb, 4)) { // extension type
2172 case EXT_SBR_DATA_CRC:
2176 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2178 } else if (!ac->oc[1].m4ac.sbr) {
2179 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2180 skip_bits_long(gb, 8 * cnt - 4);
2182 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2183 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2184 skip_bits_long(gb, 8 * cnt - 4);
2186 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2187 ac->oc[1].m4ac.sbr = 1;
2188 ac->oc[1].m4ac.ps = 1;
2189 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2190 ac->oc[1].status, 1);
2192 ac->oc[1].m4ac.sbr = 1;
2194 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2196 case EXT_DYNAMIC_RANGE:
2197 res = decode_dynamic_range(&ac->che_drc, gb);
2200 decode_fill(ac, gb, 8 * cnt - 4);
2203 case EXT_DATA_ELEMENT:
2205 skip_bits_long(gb, 8 * cnt - 4);
2212 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2214 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2215 * @param coef spectral coefficients
2217 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2218 IndividualChannelStream *ics, int decode)
2220 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2222 int bottom, top, order, start, end, size, inc;
2223 float lpc[TNS_MAX_ORDER];
2224 float tmp[TNS_MAX_ORDER+1];
2226 for (w = 0; w < ics->num_windows; w++) {
2227 bottom = ics->num_swb;
2228 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2230 bottom = FFMAX(0, top - tns->length[w][filt]);
2231 order = tns->order[w][filt];
2236 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2238 start = ics->swb_offset[FFMIN(bottom, mmm)];
2239 end = ics->swb_offset[FFMIN( top, mmm)];
2240 if ((size = end - start) <= 0)
2242 if (tns->direction[w][filt]) {
2252 for (m = 0; m < size; m++, start += inc)
2253 for (i = 1; i <= FFMIN(m, order); i++)
2254 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2257 for (m = 0; m < size; m++, start += inc) {
2258 tmp[0] = coef[start];
2259 for (i = 1; i <= FFMIN(m, order); i++)
2260 coef[start] += tmp[i] * lpc[i - 1];
2261 for (i = order; i > 0; i--)
2262 tmp[i] = tmp[i - 1];
2270 * Apply windowing and MDCT to obtain the spectral
2271 * coefficient from the predicted sample by LTP.
2273 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2274 float *in, IndividualChannelStream *ics)
2276 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2277 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2278 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2279 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2281 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2282 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2284 memset(in, 0, 448 * sizeof(float));
2285 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2287 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2288 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2290 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2291 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2293 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2297 * Apply the long term prediction
2299 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2301 const LongTermPrediction *ltp = &sce->ics.ltp;
2302 const uint16_t *offsets = sce->ics.swb_offset;
2305 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2306 float *predTime = sce->ret;
2307 float *predFreq = ac->buf_mdct;
2308 int16_t num_samples = 2048;
2310 if (ltp->lag < 1024)
2311 num_samples = ltp->lag + 1024;
2312 for (i = 0; i < num_samples; i++)
2313 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2314 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2316 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2318 if (sce->tns.present)
2319 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2321 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2323 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2324 sce->coeffs[i] += predFreq[i];
2329 * Update the LTP buffer for next frame
2331 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2333 IndividualChannelStream *ics = &sce->ics;
2334 float *saved = sce->saved;
2335 float *saved_ltp = sce->coeffs;
2336 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2337 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2340 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2341 memcpy(saved_ltp, saved, 512 * sizeof(float));
2342 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2343 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2344 for (i = 0; i < 64; i++)
2345 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2346 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2347 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2348 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2349 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2350 for (i = 0; i < 64; i++)
2351 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2352 } else { // LONG_STOP or ONLY_LONG
2353 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2354 for (i = 0; i < 512; i++)
2355 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2358 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2359 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2360 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2364 * Conduct IMDCT and windowing.
2366 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2368 IndividualChannelStream *ics = &sce->ics;
2369 float *in = sce->coeffs;
2370 float *out = sce->ret;
2371 float *saved = sce->saved;
2372 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2373 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2374 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2375 float *buf = ac->buf_mdct;
2376 float *temp = ac->temp;
2380 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2381 for (i = 0; i < 1024; i += 128)
2382 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2384 ac->mdct.imdct_half(&ac->mdct, buf, in);
2386 /* window overlapping
2387 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2388 * and long to short transitions are considered to be short to short
2389 * transitions. This leaves just two cases (long to long and short to short)
2390 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2392 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2393 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2394 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2396 memcpy( out, saved, 448 * sizeof(float));
2398 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2399 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2400 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2401 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2402 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2403 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2404 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2406 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2407 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2412 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2413 memcpy( saved, temp + 64, 64 * sizeof(float));
2414 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2415 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2416 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2417 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2418 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2419 memcpy( saved, buf + 512, 448 * sizeof(float));
2420 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2421 } else { // LONG_STOP or ONLY_LONG
2422 memcpy( saved, buf + 512, 512 * sizeof(float));
2426 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2428 IndividualChannelStream *ics = &sce->ics;
2429 float *in = sce->coeffs;
2430 float *out = sce->ret;
2431 float *saved = sce->saved;
2432 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_512 : ff_sine_512;
2433 float *buf = ac->buf_mdct;
2436 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2438 // window overlapping
2439 ac->fdsp.vector_fmul_window(out, saved, buf, lwindow_prev, 256);
2442 memcpy(saved, buf + 256, 256 * sizeof(float));
2446 * Apply dependent channel coupling (applied before IMDCT).
2448 * @param index index into coupling gain array
2450 static void apply_dependent_coupling(AACContext *ac,
2451 SingleChannelElement *target,
2452 ChannelElement *cce, int index)
2454 IndividualChannelStream *ics = &cce->ch[0].ics;
2455 const uint16_t *offsets = ics->swb_offset;
2456 float *dest = target->coeffs;
2457 const float *src = cce->ch[0].coeffs;
2458 int g, i, group, k, idx = 0;
2459 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2460 av_log(ac->avctx, AV_LOG_ERROR,
2461 "Dependent coupling is not supported together with LTP\n");
2464 for (g = 0; g < ics->num_window_groups; g++) {
2465 for (i = 0; i < ics->max_sfb; i++, idx++) {
2466 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2467 const float gain = cce->coup.gain[index][idx];
2468 for (group = 0; group < ics->group_len[g]; group++) {
2469 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2471 dest[group * 128 + k] += gain * src[group * 128 + k];
2476 dest += ics->group_len[g] * 128;
2477 src += ics->group_len[g] * 128;
2482 * Apply independent channel coupling (applied after IMDCT).
2484 * @param index index into coupling gain array
2486 static void apply_independent_coupling(AACContext *ac,
2487 SingleChannelElement *target,
2488 ChannelElement *cce, int index)
2491 const float gain = cce->coup.gain[index][0];
2492 const float *src = cce->ch[0].ret;
2493 float *dest = target->ret;
2494 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2496 for (i = 0; i < len; i++)
2497 dest[i] += gain * src[i];
2501 * channel coupling transformation interface
2503 * @param apply_coupling_method pointer to (in)dependent coupling function
2505 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2506 enum RawDataBlockType type, int elem_id,
2507 enum CouplingPoint coupling_point,
2508 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2512 for (i = 0; i < MAX_ELEM_ID; i++) {
2513 ChannelElement *cce = ac->che[TYPE_CCE][i];
2516 if (cce && cce->coup.coupling_point == coupling_point) {
2517 ChannelCoupling *coup = &cce->coup;
2519 for (c = 0; c <= coup->num_coupled; c++) {
2520 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2521 if (coup->ch_select[c] != 1) {
2522 apply_coupling_method(ac, &cc->ch[0], cce, index);
2523 if (coup->ch_select[c] != 0)
2526 if (coup->ch_select[c] != 2)
2527 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2529 index += 1 + (coup->ch_select[c] == 3);
2536 * Convert spectral data to float samples, applying all supported tools as appropriate.
2538 static void spectral_to_sample(AACContext *ac)
2541 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2542 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD)
2543 imdct_and_window = imdct_and_windowing_ld;
2545 imdct_and_window = ac->imdct_and_windowing;
2546 for (type = 3; type >= 0; type--) {
2547 for (i = 0; i < MAX_ELEM_ID; i++) {
2548 ChannelElement *che = ac->che[type][i];
2550 if (type <= TYPE_CPE)
2551 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2552 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2553 if (che->ch[0].ics.predictor_present) {
2554 if (che->ch[0].ics.ltp.present)
2555 ac->apply_ltp(ac, &che->ch[0]);
2556 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2557 ac->apply_ltp(ac, &che->ch[1]);
2560 if (che->ch[0].tns.present)
2561 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2562 if (che->ch[1].tns.present)
2563 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2564 if (type <= TYPE_CPE)
2565 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2566 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2567 imdct_and_window(ac, &che->ch[0]);
2568 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2569 ac->update_ltp(ac, &che->ch[0]);
2570 if (type == TYPE_CPE) {
2571 imdct_and_window(ac, &che->ch[1]);
2572 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2573 ac->update_ltp(ac, &che->ch[1]);
2575 if (ac->oc[1].m4ac.sbr > 0) {
2576 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2579 if (type <= TYPE_CCE)
2580 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2586 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2589 AACADTSHeaderInfo hdr_info;
2590 uint8_t layout_map[MAX_ELEM_ID*4][3];
2591 int layout_map_tags, ret;
2593 size = avpriv_aac_parse_header(gb, &hdr_info);
2595 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2596 // This is 2 for "VLB " audio in NSV files.
2597 // See samples/nsv/vlb_audio.
2598 avpriv_report_missing_feature(ac->avctx,
2599 "More than one AAC RDB per ADTS frame");
2600 ac->warned_num_aac_frames = 1;
2602 push_output_configuration(ac);
2603 if (hdr_info.chan_config) {
2604 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2605 if ((ret = set_default_channel_config(ac->avctx,
2608 hdr_info.chan_config)) < 0)
2610 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2611 FFMAX(ac->oc[1].status,
2612 OC_TRIAL_FRAME), 0)) < 0)
2615 ac->oc[1].m4ac.chan_config = 0;
2617 * dual mono frames in Japanese DTV can have chan_config 0
2618 * WITHOUT specifying PCE.
2619 * thus, set dual mono as default.
2621 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2622 layout_map_tags = 2;
2623 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2624 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2625 layout_map[0][1] = 0;
2626 layout_map[1][1] = 1;
2627 if (output_configure(ac, layout_map, layout_map_tags,
2632 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2633 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2634 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2635 if (ac->oc[0].status != OC_LOCKED ||
2636 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2637 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2638 ac->oc[1].m4ac.sbr = -1;
2639 ac->oc[1].m4ac.ps = -1;
2641 if (!hdr_info.crc_absent)
2647 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2648 int *got_frame_ptr, GetBitContext *gb)
2650 AACContext *ac = avctx->priv_data;
2651 ChannelElement *che;
2654 int chan_config = ac->oc[1].m4ac.chan_config;
2656 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD)
2661 if ((err = frame_configure_elements(avctx)) < 0)
2664 ac->tags_mapped = 0;
2666 if (chan_config < 0 || chan_config >= 8) {
2667 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2668 ac->oc[1].m4ac.chan_config);
2669 return AVERROR_INVALIDDATA;
2671 for (i = 0; i < tags_per_config[chan_config]; i++) {
2672 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2673 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2674 if (!(che=get_che(ac, elem_type, elem_id))) {
2675 av_log(ac->avctx, AV_LOG_ERROR,
2676 "channel element %d.%d is not allocated\n",
2677 elem_type, elem_id);
2678 return AVERROR_INVALIDDATA;
2681 switch (elem_type) {
2683 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2686 err = decode_cpe(ac, gb, che);
2689 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2696 spectral_to_sample(ac);
2698 ac->frame->nb_samples = samples;
2701 skip_bits_long(gb, get_bits_left(gb));
2705 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2706 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2708 AACContext *ac = avctx->priv_data;
2709 ChannelElement *che = NULL, *che_prev = NULL;
2710 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2712 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2713 int is_dmono, sce_count = 0;
2717 if (show_bits(gb, 12) == 0xfff) {
2718 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2719 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2722 if (ac->oc[1].m4ac.sampling_index > 12) {
2723 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2724 err = AVERROR_INVALIDDATA;
2729 if ((err = frame_configure_elements(avctx)) < 0)
2732 ac->tags_mapped = 0;
2734 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2735 elem_id = get_bits(gb, 4);
2737 if (elem_type < TYPE_DSE) {
2738 if (!(che=get_che(ac, elem_type, elem_id))) {
2739 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2740 elem_type, elem_id);
2741 err = AVERROR_INVALIDDATA;
2747 switch (elem_type) {
2750 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2756 err = decode_cpe(ac, gb, che);
2761 err = decode_cce(ac, gb, che);
2765 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2770 err = skip_data_stream_element(ac, gb);
2774 uint8_t layout_map[MAX_ELEM_ID*4][3];
2776 push_output_configuration(ac);
2777 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2783 av_log(avctx, AV_LOG_ERROR,
2784 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2786 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2788 ac->oc[1].m4ac.chan_config = 0;
2796 elem_id += get_bits(gb, 8) - 1;
2797 if (get_bits_left(gb) < 8 * elem_id) {
2798 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
2799 err = AVERROR_INVALIDDATA;
2803 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2804 err = 0; /* FIXME */
2808 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2813 elem_type_prev = elem_type;
2818 if (get_bits_left(gb) < 3) {
2819 av_log(avctx, AV_LOG_ERROR, overread_err);
2820 err = AVERROR_INVALIDDATA;
2825 spectral_to_sample(ac);
2827 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2828 samples <<= multiplier;
2829 /* for dual-mono audio (SCE + SCE) */
2830 is_dmono = ac->dmono_mode && sce_count == 2 &&
2831 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
2834 ac->frame->nb_samples = samples;
2836 av_frame_unref(ac->frame);
2837 *got_frame_ptr = !!samples;
2840 if (ac->dmono_mode == 1)
2841 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
2842 else if (ac->dmono_mode == 2)
2843 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
2846 if (ac->oc[1].status && audio_found) {
2847 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2848 avctx->frame_size = samples;
2849 ac->oc[1].status = OC_LOCKED;
2854 const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2855 if (side && side_size>=4)
2856 AV_WL32(side, 2*AV_RL32(side));
2860 pop_output_configuration(ac);
2864 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2865 int *got_frame_ptr, AVPacket *avpkt)
2867 AACContext *ac = avctx->priv_data;
2868 const uint8_t *buf = avpkt->data;
2869 int buf_size = avpkt->size;
2874 int new_extradata_size;
2875 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2876 AV_PKT_DATA_NEW_EXTRADATA,
2877 &new_extradata_size);
2878 int jp_dualmono_size;
2879 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
2880 AV_PKT_DATA_JP_DUALMONO,
2883 if (new_extradata && 0) {
2884 av_free(avctx->extradata);
2885 avctx->extradata = av_mallocz(new_extradata_size +
2886 FF_INPUT_BUFFER_PADDING_SIZE);
2887 if (!avctx->extradata)
2888 return AVERROR(ENOMEM);
2889 avctx->extradata_size = new_extradata_size;
2890 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2891 push_output_configuration(ac);
2892 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2894 avctx->extradata_size*8, 1) < 0) {
2895 pop_output_configuration(ac);
2896 return AVERROR_INVALIDDATA;
2901 if (jp_dualmono && jp_dualmono_size > 0)
2902 ac->dmono_mode = 1 + *jp_dualmono;
2903 if (ac->force_dmono_mode >= 0)
2904 ac->dmono_mode = ac->force_dmono_mode;
2906 if (INT_MAX / 8 <= buf_size)
2907 return AVERROR_INVALIDDATA;
2909 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
2912 switch (ac->oc[1].m4ac.object_type) {
2914 case AOT_ER_AAC_LTP:
2916 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
2919 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
2924 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2925 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2926 if (buf[buf_offset])
2929 return buf_size > buf_offset ? buf_consumed : buf_size;
2932 static av_cold int aac_decode_close(AVCodecContext *avctx)
2934 AACContext *ac = avctx->priv_data;
2937 for (i = 0; i < MAX_ELEM_ID; i++) {
2938 for (type = 0; type < 4; type++) {
2939 if (ac->che[type][i])
2940 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2941 av_freep(&ac->che[type][i]);
2945 ff_mdct_end(&ac->mdct);
2946 ff_mdct_end(&ac->mdct_small);
2947 ff_mdct_end(&ac->mdct_ld);
2948 ff_mdct_end(&ac->mdct_ltp);
2953 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2955 struct LATMContext {
2956 AACContext aac_ctx; ///< containing AACContext
2957 int initialized; ///< initialized after a valid extradata was seen
2960 int audio_mux_version_A; ///< LATM syntax version
2961 int frame_length_type; ///< 0/1 variable/fixed frame length
2962 int frame_length; ///< frame length for fixed frame length
2965 static inline uint32_t latm_get_value(GetBitContext *b)
2967 int length = get_bits(b, 2);
2969 return get_bits_long(b, (length+1)*8);
2972 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2973 GetBitContext *gb, int asclen)
2975 AACContext *ac = &latmctx->aac_ctx;
2976 AVCodecContext *avctx = ac->avctx;
2977 MPEG4AudioConfig m4ac = { 0 };
2978 int config_start_bit = get_bits_count(gb);
2979 int sync_extension = 0;
2980 int bits_consumed, esize;
2984 asclen = FFMIN(asclen, get_bits_left(gb));
2986 asclen = get_bits_left(gb);
2988 if (config_start_bit % 8) {
2989 avpriv_request_sample(latmctx->aac_ctx.avctx,
2990 "Non-byte-aligned audio-specific config");
2991 return AVERROR_PATCHWELCOME;
2994 return AVERROR_INVALIDDATA;
2995 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2996 gb->buffer + (config_start_bit / 8),
2997 asclen, sync_extension);
2999 if (bits_consumed < 0)
3000 return AVERROR_INVALIDDATA;
3002 if (!latmctx->initialized ||
3003 ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3004 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3006 if(latmctx->initialized) {
3007 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3009 av_log(avctx, AV_LOG_DEBUG, "initializing latmctx\n");
3011 latmctx->initialized = 0;
3013 esize = (bits_consumed+7) / 8;
3015 if (avctx->extradata_size < esize) {
3016 av_free(avctx->extradata);
3017 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
3018 if (!avctx->extradata)
3019 return AVERROR(ENOMEM);
3022 avctx->extradata_size = esize;
3023 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3024 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3026 skip_bits_long(gb, bits_consumed);
3028 return bits_consumed;
3031 static int read_stream_mux_config(struct LATMContext *latmctx,
3034 int ret, audio_mux_version = get_bits(gb, 1);
3036 latmctx->audio_mux_version_A = 0;
3037 if (audio_mux_version)
3038 latmctx->audio_mux_version_A = get_bits(gb, 1);
3040 if (!latmctx->audio_mux_version_A) {
3042 if (audio_mux_version)
3043 latm_get_value(gb); // taraFullness
3045 skip_bits(gb, 1); // allStreamSameTimeFraming
3046 skip_bits(gb, 6); // numSubFrames
3048 if (get_bits(gb, 4)) { // numPrograms
3049 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3050 return AVERROR_PATCHWELCOME;
3053 // for each program (which there is only one in DVB)
3055 // for each layer (which there is only one in DVB)
3056 if (get_bits(gb, 3)) { // numLayer
3057 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3058 return AVERROR_PATCHWELCOME;
3061 // for all but first stream: use_same_config = get_bits(gb, 1);
3062 if (!audio_mux_version) {
3063 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3066 int ascLen = latm_get_value(gb);
3067 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3070 skip_bits_long(gb, ascLen);
3073 latmctx->frame_length_type = get_bits(gb, 3);
3074 switch (latmctx->frame_length_type) {
3076 skip_bits(gb, 8); // latmBufferFullness
3079 latmctx->frame_length = get_bits(gb, 9);
3084 skip_bits(gb, 6); // CELP frame length table index
3088 skip_bits(gb, 1); // HVXC frame length table index
3092 if (get_bits(gb, 1)) { // other data
3093 if (audio_mux_version) {
3094 latm_get_value(gb); // other_data_bits
3098 esc = get_bits(gb, 1);
3104 if (get_bits(gb, 1)) // crc present
3105 skip_bits(gb, 8); // config_crc
3111 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3115 if (ctx->frame_length_type == 0) {
3116 int mux_slot_length = 0;
3118 tmp = get_bits(gb, 8);
3119 mux_slot_length += tmp;
3120 } while (tmp == 255);
3121 return mux_slot_length;
3122 } else if (ctx->frame_length_type == 1) {
3123 return ctx->frame_length;
3124 } else if (ctx->frame_length_type == 3 ||
3125 ctx->frame_length_type == 5 ||
3126 ctx->frame_length_type == 7) {
3127 skip_bits(gb, 2); // mux_slot_length_coded
3132 static int read_audio_mux_element(struct LATMContext *latmctx,
3136 uint8_t use_same_mux = get_bits(gb, 1);
3137 if (!use_same_mux) {
3138 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3140 } else if (!latmctx->aac_ctx.avctx->extradata) {
3141 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3142 "no decoder config found\n");
3143 return AVERROR(EAGAIN);
3145 if (latmctx->audio_mux_version_A == 0) {
3146 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3147 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3148 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3149 return AVERROR_INVALIDDATA;
3150 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3151 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3152 "frame length mismatch %d << %d\n",
3153 mux_slot_length_bytes * 8, get_bits_left(gb));
3154 return AVERROR_INVALIDDATA;
3161 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3162 int *got_frame_ptr, AVPacket *avpkt)
3164 struct LATMContext *latmctx = avctx->priv_data;
3168 if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
3171 // check for LOAS sync word
3172 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3173 return AVERROR_INVALIDDATA;
3175 muxlength = get_bits(&gb, 13) + 3;
3176 // not enough data, the parser should have sorted this out
3177 if (muxlength > avpkt->size)
3178 return AVERROR_INVALIDDATA;
3180 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3183 if (!latmctx->initialized) {
3184 if (!avctx->extradata) {
3188 push_output_configuration(&latmctx->aac_ctx);
3189 if ((err = decode_audio_specific_config(
3190 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3191 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3192 pop_output_configuration(&latmctx->aac_ctx);
3195 latmctx->initialized = 1;
3199 if (show_bits(&gb, 12) == 0xfff) {
3200 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3201 "ADTS header detected, probably as result of configuration "
3203 return AVERROR_INVALIDDATA;
3206 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
3212 static av_cold int latm_decode_init(AVCodecContext *avctx)
3214 struct LATMContext *latmctx = avctx->priv_data;
3215 int ret = aac_decode_init(avctx);
3217 if (avctx->extradata_size > 0)
3218 latmctx->initialized = !ret;
3223 static void aacdec_init(AACContext *c)
3225 c->imdct_and_windowing = imdct_and_windowing;
3226 c->apply_ltp = apply_ltp;
3227 c->apply_tns = apply_tns;
3228 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3229 c->update_ltp = update_ltp;
3232 ff_aacdec_init_mips(c);
3235 * AVOptions for Japanese DTV specific extensions (ADTS only)
3237 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3238 static const AVOption options[] = {
3239 {"dual_mono_mode", "Select the channel to decode for dual mono",
3240 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3241 AACDEC_FLAGS, "dual_mono_mode"},
3243 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3244 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3245 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3246 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3251 static const AVClass aac_decoder_class = {
3252 .class_name = "AAC decoder",
3253 .item_name = av_default_item_name,
3255 .version = LIBAVUTIL_VERSION_INT,
3258 AVCodec ff_aac_decoder = {
3260 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3261 .type = AVMEDIA_TYPE_AUDIO,
3262 .id = AV_CODEC_ID_AAC,
3263 .priv_data_size = sizeof(AACContext),
3264 .init = aac_decode_init,
3265 .close = aac_decode_close,
3266 .decode = aac_decode_frame,
3267 .sample_fmts = (const enum AVSampleFormat[]) {
3268 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3270 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3271 .channel_layouts = aac_channel_layout,
3273 .priv_class = &aac_decoder_class,
3277 Note: This decoder filter is intended to decode LATM streams transferred
3278 in MPEG transport streams which only contain one program.
3279 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3281 AVCodec ff_aac_latm_decoder = {
3283 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3284 .type = AVMEDIA_TYPE_AUDIO,
3285 .id = AV_CODEC_ID_AAC_LATM,
3286 .priv_data_size = sizeof(struct LATMContext),
3287 .init = latm_decode_init,
3288 .close = aac_decode_close,
3289 .decode = latm_decode_frame,
3290 .sample_fmts = (const enum AVSampleFormat[]) {
3291 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3293 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3294 .channel_layouts = aac_channel_layout,