3 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
5 * Copyright (c) 2008-2013 Alex Converse <alex.converse@gmail.com>
8 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
9 * Copyright (c) 2010 Janne Grunau <janne-libav@jannau.net>
11 * This file is part of Libav.
13 * Libav is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2.1 of the License, or (at your option) any later version.
18 * Libav is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with Libav; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 * @author Oded Shimon ( ods15 ods15 dyndns org )
32 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
39 * N (code in SoC repo) gain control
41 * Y window shapes - standard
42 * N window shapes - Low Delay
43 * Y filterbank - standard
44 * N (code in SoC repo) filterbank - Scalable Sample Rate
45 * Y Temporal Noise Shaping
46 * Y Long Term Prediction
49 * Y frequency domain prediction
50 * Y Perceptual Noise Substitution
52 * N Scalable Inverse AAC Quantization
53 * N Frequency Selective Switch
55 * Y quantization & coding - AAC
56 * N quantization & coding - TwinVQ
57 * N quantization & coding - BSAC
58 * N AAC Error Resilience tools
59 * N Error Resilience payload syntax
60 * N Error Protection tool
62 * N Silence Compression
65 * N Structured Audio tools
66 * N Structured Audio Sample Bank Format
68 * N Harmonic and Individual Lines plus Noise
69 * N Text-To-Speech Interface
70 * Y Spectral Band Replication
71 * Y (not in this code) Layer-1
72 * Y (not in this code) Layer-2
73 * Y (not in this code) Layer-3
74 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
76 * N Direct Stream Transfer
78 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
79 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
83 #include "libavutil/float_dsp.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"
110 # include "arm/aac.h"
113 static VLC vlc_scalefactors;
114 static VLC vlc_spectral[11];
116 static const char overread_err[] = "Input buffer exhausted before END element found\n";
118 static int count_channels(uint8_t (*layout)[3], int tags)
121 for (i = 0; i < tags; i++) {
122 int syn_ele = layout[i][0];
123 int pos = layout[i][2];
124 sum += (1 + (syn_ele == TYPE_CPE)) *
125 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
131 * Check for the channel element in the current channel position configuration.
132 * If it exists, make sure the appropriate element is allocated and map the
133 * channel order to match the internal Libav channel layout.
135 * @param che_pos current channel position configuration
136 * @param type channel element type
137 * @param id channel element id
138 * @param channels count of the number of channels in the configuration
140 * @return Returns error status. 0 - OK, !0 - error
142 static av_cold int che_configure(AACContext *ac,
143 enum ChannelPosition che_pos,
144 int type, int id, int *channels)
146 if (*channels >= MAX_CHANNELS)
147 return AVERROR_INVALIDDATA;
149 if (!ac->che[type][id]) {
150 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
151 return AVERROR(ENOMEM);
152 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
154 if (type != TYPE_CCE) {
155 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
156 if (type == TYPE_CPE ||
157 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
158 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
162 if (ac->che[type][id])
163 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
164 av_freep(&ac->che[type][id]);
169 static int frame_configure_elements(AVCodecContext *avctx)
171 AACContext *ac = avctx->priv_data;
172 int type, id, ch, ret;
174 /* set channel pointers to internal buffers by default */
175 for (type = 0; type < 4; type++) {
176 for (id = 0; id < MAX_ELEM_ID; id++) {
177 ChannelElement *che = ac->che[type][id];
179 che->ch[0].ret = che->ch[0].ret_buf;
180 che->ch[1].ret = che->ch[1].ret_buf;
185 /* get output buffer */
186 av_frame_unref(ac->frame);
187 ac->frame->nb_samples = 2048;
188 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0) {
189 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
193 /* map output channel pointers to AVFrame data */
194 for (ch = 0; ch < avctx->channels; ch++) {
195 if (ac->output_element[ch])
196 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
202 struct elem_to_channel {
203 uint64_t av_position;
206 uint8_t aac_position;
209 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
210 uint8_t (*layout_map)[3], int offset, uint64_t left,
211 uint64_t right, int pos)
213 if (layout_map[offset][0] == TYPE_CPE) {
214 e2c_vec[offset] = (struct elem_to_channel) {
215 .av_position = left | right,
217 .elem_id = layout_map[offset][1],
222 e2c_vec[offset] = (struct elem_to_channel) {
225 .elem_id = layout_map[offset][1],
228 e2c_vec[offset + 1] = (struct elem_to_channel) {
229 .av_position = right,
231 .elem_id = layout_map[offset + 1][1],
238 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
241 int num_pos_channels = 0;
245 for (i = *current; i < tags; i++) {
246 if (layout_map[i][2] != pos)
248 if (layout_map[i][0] == TYPE_CPE) {
250 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
256 num_pos_channels += 2;
264 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
267 return num_pos_channels;
270 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
272 int i, n, total_non_cc_elements;
273 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
274 int num_front_channels, num_side_channels, num_back_channels;
277 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
282 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
283 if (num_front_channels < 0)
286 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
287 if (num_side_channels < 0)
290 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
291 if (num_back_channels < 0)
295 if (num_front_channels & 1) {
296 e2c_vec[i] = (struct elem_to_channel) {
297 .av_position = AV_CH_FRONT_CENTER,
299 .elem_id = layout_map[i][1],
300 .aac_position = AAC_CHANNEL_FRONT
303 num_front_channels--;
305 if (num_front_channels >= 4) {
306 i += assign_pair(e2c_vec, layout_map, i,
307 AV_CH_FRONT_LEFT_OF_CENTER,
308 AV_CH_FRONT_RIGHT_OF_CENTER,
310 num_front_channels -= 2;
312 if (num_front_channels >= 2) {
313 i += assign_pair(e2c_vec, layout_map, i,
317 num_front_channels -= 2;
319 while (num_front_channels >= 2) {
320 i += assign_pair(e2c_vec, layout_map, i,
324 num_front_channels -= 2;
327 if (num_side_channels >= 2) {
328 i += assign_pair(e2c_vec, layout_map, i,
332 num_side_channels -= 2;
334 while (num_side_channels >= 2) {
335 i += assign_pair(e2c_vec, layout_map, i,
339 num_side_channels -= 2;
342 while (num_back_channels >= 4) {
343 i += assign_pair(e2c_vec, layout_map, i,
347 num_back_channels -= 2;
349 if (num_back_channels >= 2) {
350 i += assign_pair(e2c_vec, layout_map, i,
354 num_back_channels -= 2;
356 if (num_back_channels) {
357 e2c_vec[i] = (struct elem_to_channel) {
358 .av_position = AV_CH_BACK_CENTER,
360 .elem_id = layout_map[i][1],
361 .aac_position = AAC_CHANNEL_BACK
367 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
368 e2c_vec[i] = (struct elem_to_channel) {
369 .av_position = AV_CH_LOW_FREQUENCY,
371 .elem_id = layout_map[i][1],
372 .aac_position = AAC_CHANNEL_LFE
376 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
377 e2c_vec[i] = (struct elem_to_channel) {
378 .av_position = UINT64_MAX,
380 .elem_id = layout_map[i][1],
381 .aac_position = AAC_CHANNEL_LFE
386 // Must choose a stable sort
387 total_non_cc_elements = n = i;
390 for (i = 1; i < n; i++)
391 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
392 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
399 for (i = 0; i < total_non_cc_elements; i++) {
400 layout_map[i][0] = e2c_vec[i].syn_ele;
401 layout_map[i][1] = e2c_vec[i].elem_id;
402 layout_map[i][2] = e2c_vec[i].aac_position;
403 if (e2c_vec[i].av_position != UINT64_MAX) {
404 layout |= e2c_vec[i].av_position;
412 * Save current output configuration if and only if it has been locked.
414 static void push_output_configuration(AACContext *ac) {
415 if (ac->oc[1].status == OC_LOCKED) {
416 ac->oc[0] = ac->oc[1];
418 ac->oc[1].status = OC_NONE;
422 * Restore the previous output configuration if and only if the current
423 * configuration is unlocked.
425 static void pop_output_configuration(AACContext *ac) {
426 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
427 ac->oc[1] = ac->oc[0];
428 ac->avctx->channels = ac->oc[1].channels;
429 ac->avctx->channel_layout = ac->oc[1].channel_layout;
434 * Configure output channel order based on the current program
435 * configuration element.
437 * @return Returns error status. 0 - OK, !0 - error
439 static int output_configure(AACContext *ac,
440 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
441 enum OCStatus oc_type, int get_new_frame)
443 AVCodecContext *avctx = ac->avctx;
444 int i, channels = 0, ret;
447 if (ac->oc[1].layout_map != layout_map) {
448 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
449 ac->oc[1].layout_map_tags = tags;
452 // Try to sniff a reasonable channel order, otherwise output the
453 // channels in the order the PCE declared them.
454 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
455 layout = sniff_channel_order(layout_map, tags);
456 for (i = 0; i < tags; i++) {
457 int type = layout_map[i][0];
458 int id = layout_map[i][1];
459 int position = layout_map[i][2];
460 // Allocate or free elements depending on if they are in the
461 // current program configuration.
462 ret = che_configure(ac, position, type, id, &channels);
466 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
467 if (layout == AV_CH_FRONT_CENTER) {
468 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
474 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
475 avctx->channel_layout = ac->oc[1].channel_layout = layout;
476 avctx->channels = ac->oc[1].channels = channels;
477 ac->oc[1].status = oc_type;
480 if ((ret = frame_configure_elements(ac->avctx)) < 0)
488 * Set up channel positions based on a default channel configuration
489 * as specified in table 1.17.
491 * @return Returns error status. 0 - OK, !0 - error
493 static int set_default_channel_config(AVCodecContext *avctx,
494 uint8_t (*layout_map)[3],
498 if (channel_config < 1 || channel_config > 7) {
499 av_log(avctx, AV_LOG_ERROR,
500 "invalid default channel configuration (%d)\n",
502 return AVERROR_INVALIDDATA;
504 *tags = tags_per_config[channel_config];
505 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
506 *tags * sizeof(*layout_map));
510 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
512 /* For PCE based channel configurations map the channels solely based
514 if (!ac->oc[1].m4ac.chan_config) {
515 return ac->tag_che_map[type][elem_id];
517 // Allow single CPE stereo files to be signalled with mono configuration.
518 if (!ac->tags_mapped && type == TYPE_CPE &&
519 ac->oc[1].m4ac.chan_config == 1) {
520 uint8_t layout_map[MAX_ELEM_ID*4][3];
522 push_output_configuration(ac);
524 if (set_default_channel_config(ac->avctx, layout_map,
525 &layout_map_tags, 2) < 0)
527 if (output_configure(ac, layout_map, layout_map_tags,
528 OC_TRIAL_FRAME, 1) < 0)
531 ac->oc[1].m4ac.chan_config = 2;
532 ac->oc[1].m4ac.ps = 0;
535 if (!ac->tags_mapped && type == TYPE_SCE &&
536 ac->oc[1].m4ac.chan_config == 2) {
537 uint8_t layout_map[MAX_ELEM_ID * 4][3];
539 push_output_configuration(ac);
541 if (set_default_channel_config(ac->avctx, layout_map,
542 &layout_map_tags, 1) < 0)
544 if (output_configure(ac, layout_map, layout_map_tags,
545 OC_TRIAL_FRAME, 1) < 0)
548 ac->oc[1].m4ac.chan_config = 1;
549 if (ac->oc[1].m4ac.sbr)
550 ac->oc[1].m4ac.ps = -1;
552 /* For indexed channel configurations map the channels solely based
554 switch (ac->oc[1].m4ac.chan_config) {
556 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
558 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
561 /* Some streams incorrectly code 5.1 audio as
562 * SCE[0] CPE[0] CPE[1] SCE[1]
564 * SCE[0] CPE[0] CPE[1] LFE[0].
565 * If we seem to have encountered such a stream, transfer
566 * the LFE[0] element to the SCE[1]'s mapping */
567 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
569 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
572 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
574 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
577 if (ac->tags_mapped == 2 &&
578 ac->oc[1].m4ac.chan_config == 4 &&
581 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
585 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
588 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
589 } else if (ac->oc[1].m4ac.chan_config == 2) {
593 if (!ac->tags_mapped && type == TYPE_SCE) {
595 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
603 * Decode an array of 4 bit element IDs, optionally interleaved with a
604 * stereo/mono switching bit.
606 * @param type speaker type/position for these channels
608 static void decode_channel_map(uint8_t layout_map[][3],
609 enum ChannelPosition type,
610 GetBitContext *gb, int n)
613 enum RawDataBlockType syn_ele;
615 case AAC_CHANNEL_FRONT:
616 case AAC_CHANNEL_BACK:
617 case AAC_CHANNEL_SIDE:
618 syn_ele = get_bits1(gb);
624 case AAC_CHANNEL_LFE:
628 layout_map[0][0] = syn_ele;
629 layout_map[0][1] = get_bits(gb, 4);
630 layout_map[0][2] = type;
636 * Decode program configuration element; reference: table 4.2.
638 * @return Returns error status. 0 - OK, !0 - error
640 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
641 uint8_t (*layout_map)[3],
644 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
649 skip_bits(gb, 2); // object_type
651 sampling_index = get_bits(gb, 4);
652 if (m4ac->sampling_index != sampling_index)
653 av_log(avctx, AV_LOG_WARNING,
654 "Sample rate index in program config element does not "
655 "match the sample rate index configured by the container.\n");
657 num_front = get_bits(gb, 4);
658 num_side = get_bits(gb, 4);
659 num_back = get_bits(gb, 4);
660 num_lfe = get_bits(gb, 2);
661 num_assoc_data = get_bits(gb, 3);
662 num_cc = get_bits(gb, 4);
665 skip_bits(gb, 4); // mono_mixdown_tag
667 skip_bits(gb, 4); // stereo_mixdown_tag
670 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
672 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
674 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
676 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
678 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
681 skip_bits_long(gb, 4 * num_assoc_data);
683 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
688 /* comment field, first byte is length */
689 comment_len = get_bits(gb, 8) * 8;
690 if (get_bits_left(gb) < comment_len) {
691 av_log(avctx, AV_LOG_ERROR, overread_err);
692 return AVERROR_INVALIDDATA;
694 skip_bits_long(gb, comment_len);
699 * Decode GA "General Audio" specific configuration; reference: table 4.1.
701 * @param ac pointer to AACContext, may be null
702 * @param avctx pointer to AVCCodecContext, used for logging
704 * @return Returns error status. 0 - OK, !0 - error
706 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
708 MPEG4AudioConfig *m4ac,
711 int extension_flag, ret, ep_config, res_flags;
712 uint8_t layout_map[MAX_ELEM_ID*4][3];
715 if (get_bits1(gb)) { // frameLengthFlag
716 avpriv_request_sample(avctx, "960/120 MDCT window");
717 return AVERROR_PATCHWELCOME;
720 if (get_bits1(gb)) // dependsOnCoreCoder
721 skip_bits(gb, 14); // coreCoderDelay
722 extension_flag = get_bits1(gb);
724 if (m4ac->object_type == AOT_AAC_SCALABLE ||
725 m4ac->object_type == AOT_ER_AAC_SCALABLE)
726 skip_bits(gb, 3); // layerNr
728 if (channel_config == 0) {
729 skip_bits(gb, 4); // element_instance_tag
730 tags = decode_pce(avctx, m4ac, layout_map, gb);
734 if ((ret = set_default_channel_config(avctx, layout_map,
735 &tags, channel_config)))
739 if (count_channels(layout_map, tags) > 1) {
741 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
744 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
747 if (extension_flag) {
748 switch (m4ac->object_type) {
750 skip_bits(gb, 5); // numOfSubFrame
751 skip_bits(gb, 11); // layer_length
755 case AOT_ER_AAC_SCALABLE:
757 res_flags = get_bits(gb, 3);
759 avpriv_report_missing_feature(avctx,
760 "AAC data resilience (flags %x)",
762 return AVERROR_PATCHWELCOME;
766 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
768 switch (m4ac->object_type) {
771 case AOT_ER_AAC_SCALABLE:
773 ep_config = get_bits(gb, 2);
775 avpriv_report_missing_feature(avctx,
776 "epConfig %d", ep_config);
777 return AVERROR_PATCHWELCOME;
783 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
785 MPEG4AudioConfig *m4ac,
788 int ret, ep_config, res_flags;
789 uint8_t layout_map[MAX_ELEM_ID*4][3];
791 const int ELDEXT_TERM = 0;
796 if (get_bits1(gb)) { // frameLengthFlag
797 avpriv_request_sample(avctx, "960/120 MDCT window");
798 return AVERROR_PATCHWELCOME;
801 res_flags = get_bits(gb, 3);
803 avpriv_report_missing_feature(avctx,
804 "AAC data resilience (flags %x)",
806 return AVERROR_PATCHWELCOME;
809 if (get_bits1(gb)) { // ldSbrPresentFlag
810 avpriv_report_missing_feature(avctx,
812 return AVERROR_PATCHWELCOME;
815 while (get_bits(gb, 4) != ELDEXT_TERM) {
816 int len = get_bits(gb, 4);
818 len += get_bits(gb, 8);
820 len += get_bits(gb, 16);
821 if (get_bits_left(gb) < len * 8 + 4) {
822 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
823 return AVERROR_INVALIDDATA;
825 skip_bits_long(gb, 8 * len);
828 if ((ret = set_default_channel_config(avctx, layout_map,
829 &tags, channel_config)))
832 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
835 ep_config = get_bits(gb, 2);
837 avpriv_report_missing_feature(avctx,
838 "epConfig %d", ep_config);
839 return AVERROR_PATCHWELCOME;
845 * Decode audio specific configuration; reference: table 1.13.
847 * @param ac pointer to AACContext, may be null
848 * @param avctx pointer to AVCCodecContext, used for logging
849 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
850 * @param data pointer to buffer holding an audio specific config
851 * @param bit_size size of audio specific config or data in bits
852 * @param sync_extension look for an appended sync extension
854 * @return Returns error status or number of consumed bits. <0 - error
856 static int decode_audio_specific_config(AACContext *ac,
857 AVCodecContext *avctx,
858 MPEG4AudioConfig *m4ac,
859 const uint8_t *data, int bit_size,
865 av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
866 for (i = 0; i < avctx->extradata_size; i++)
867 av_dlog(avctx, "%02x ", avctx->extradata[i]);
868 av_dlog(avctx, "\n");
870 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
873 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
874 sync_extension)) < 0)
875 return AVERROR_INVALIDDATA;
876 if (m4ac->sampling_index > 12) {
877 av_log(avctx, AV_LOG_ERROR,
878 "invalid sampling rate index %d\n",
879 m4ac->sampling_index);
880 return AVERROR_INVALIDDATA;
882 if (m4ac->object_type == AOT_ER_AAC_LD &&
883 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
884 av_log(avctx, AV_LOG_ERROR,
885 "invalid low delay sampling rate index %d\n",
886 m4ac->sampling_index);
887 return AVERROR_INVALIDDATA;
890 skip_bits_long(&gb, i);
892 switch (m4ac->object_type) {
898 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
899 m4ac, m4ac->chan_config)) < 0)
903 if ((ret = decode_eld_specific_config(ac, avctx, &gb,
904 m4ac, m4ac->chan_config)) < 0)
908 avpriv_report_missing_feature(avctx,
909 "Audio object type %s%d",
910 m4ac->sbr == 1 ? "SBR+" : "",
912 return AVERROR(ENOSYS);
916 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
917 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
918 m4ac->sample_rate, m4ac->sbr,
921 return get_bits_count(&gb);
925 * linear congruential pseudorandom number generator
927 * @param previous_val pointer to the current state of the generator
929 * @return Returns a 32-bit pseudorandom integer
931 static av_always_inline int lcg_random(int previous_val)
933 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
937 static av_always_inline void reset_predict_state(PredictorState *ps)
947 static void reset_all_predictors(PredictorState *ps)
950 for (i = 0; i < MAX_PREDICTORS; i++)
951 reset_predict_state(&ps[i]);
954 static int sample_rate_idx (int rate)
956 if (92017 <= rate) return 0;
957 else if (75132 <= rate) return 1;
958 else if (55426 <= rate) return 2;
959 else if (46009 <= rate) return 3;
960 else if (37566 <= rate) return 4;
961 else if (27713 <= rate) return 5;
962 else if (23004 <= rate) return 6;
963 else if (18783 <= rate) return 7;
964 else if (13856 <= rate) return 8;
965 else if (11502 <= rate) return 9;
966 else if (9391 <= rate) return 10;
970 static void reset_predictor_group(PredictorState *ps, int group_num)
973 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
974 reset_predict_state(&ps[i]);
977 #define AAC_INIT_VLC_STATIC(num, size) \
978 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
979 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
980 sizeof(ff_aac_spectral_bits[num][0]), \
981 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
982 sizeof(ff_aac_spectral_codes[num][0]), \
985 static av_cold int aac_decode_init(AVCodecContext *avctx)
987 AACContext *ac = avctx->priv_data;
991 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
993 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
995 if (avctx->extradata_size > 0) {
996 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
998 avctx->extradata_size * 8,
1003 uint8_t layout_map[MAX_ELEM_ID*4][3];
1004 int layout_map_tags;
1006 sr = sample_rate_idx(avctx->sample_rate);
1007 ac->oc[1].m4ac.sampling_index = sr;
1008 ac->oc[1].m4ac.channels = avctx->channels;
1009 ac->oc[1].m4ac.sbr = -1;
1010 ac->oc[1].m4ac.ps = -1;
1012 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1013 if (ff_mpeg4audio_channels[i] == avctx->channels)
1015 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1018 ac->oc[1].m4ac.chan_config = i;
1020 if (ac->oc[1].m4ac.chan_config) {
1021 int ret = set_default_channel_config(avctx, layout_map,
1022 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1024 output_configure(ac, layout_map, layout_map_tags,
1026 else if (avctx->err_recognition & AV_EF_EXPLODE)
1027 return AVERROR_INVALIDDATA;
1031 AAC_INIT_VLC_STATIC( 0, 304);
1032 AAC_INIT_VLC_STATIC( 1, 270);
1033 AAC_INIT_VLC_STATIC( 2, 550);
1034 AAC_INIT_VLC_STATIC( 3, 300);
1035 AAC_INIT_VLC_STATIC( 4, 328);
1036 AAC_INIT_VLC_STATIC( 5, 294);
1037 AAC_INIT_VLC_STATIC( 6, 306);
1038 AAC_INIT_VLC_STATIC( 7, 268);
1039 AAC_INIT_VLC_STATIC( 8, 510);
1040 AAC_INIT_VLC_STATIC( 9, 366);
1041 AAC_INIT_VLC_STATIC(10, 462);
1045 ff_fmt_convert_init(&ac->fmt_conv, avctx);
1046 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
1048 ac->random_state = 0x1f2e3d4c;
1052 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1053 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1054 ff_aac_scalefactor_bits,
1055 sizeof(ff_aac_scalefactor_bits[0]),
1056 sizeof(ff_aac_scalefactor_bits[0]),
1057 ff_aac_scalefactor_code,
1058 sizeof(ff_aac_scalefactor_code[0]),
1059 sizeof(ff_aac_scalefactor_code[0]),
1062 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1063 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1064 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1065 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1066 // window initialization
1067 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1068 ff_kbd_window_init(ff_aac_kbd_long_512, 4.0, 512);
1069 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1070 ff_init_ff_sine_windows(10);
1071 ff_init_ff_sine_windows( 9);
1072 ff_init_ff_sine_windows( 7);
1080 * Skip data_stream_element; reference: table 4.10.
1082 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1084 int byte_align = get_bits1(gb);
1085 int count = get_bits(gb, 8);
1087 count += get_bits(gb, 8);
1091 if (get_bits_left(gb) < 8 * count) {
1092 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1093 return AVERROR_INVALIDDATA;
1095 skip_bits_long(gb, 8 * count);
1099 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1103 if (get_bits1(gb)) {
1104 ics->predictor_reset_group = get_bits(gb, 5);
1105 if (ics->predictor_reset_group == 0 ||
1106 ics->predictor_reset_group > 30) {
1107 av_log(ac->avctx, AV_LOG_ERROR,
1108 "Invalid Predictor Reset Group.\n");
1109 return AVERROR_INVALIDDATA;
1112 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1113 ics->prediction_used[sfb] = get_bits1(gb);
1119 * Decode Long Term Prediction data; reference: table 4.xx.
1121 static void decode_ltp(LongTermPrediction *ltp,
1122 GetBitContext *gb, uint8_t max_sfb)
1126 ltp->lag = get_bits(gb, 11);
1127 ltp->coef = ltp_coef[get_bits(gb, 3)];
1128 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1129 ltp->used[sfb] = get_bits1(gb);
1133 * Decode Individual Channel Stream info; reference: table 4.6.
1135 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1138 int aot = ac->oc[1].m4ac.object_type;
1139 if (aot != AOT_ER_AAC_ELD) {
1140 if (get_bits1(gb)) {
1141 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1142 return AVERROR_INVALIDDATA;
1144 ics->window_sequence[1] = ics->window_sequence[0];
1145 ics->window_sequence[0] = get_bits(gb, 2);
1146 if (aot == AOT_ER_AAC_LD &&
1147 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1148 av_log(ac->avctx, AV_LOG_ERROR,
1149 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1150 "window sequence %d found.\n", ics->window_sequence[0]);
1151 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1152 return AVERROR_INVALIDDATA;
1154 ics->use_kb_window[1] = ics->use_kb_window[0];
1155 ics->use_kb_window[0] = get_bits1(gb);
1157 ics->num_window_groups = 1;
1158 ics->group_len[0] = 1;
1159 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1161 ics->max_sfb = get_bits(gb, 4);
1162 for (i = 0; i < 7; i++) {
1163 if (get_bits1(gb)) {
1164 ics->group_len[ics->num_window_groups - 1]++;
1166 ics->num_window_groups++;
1167 ics->group_len[ics->num_window_groups - 1] = 1;
1170 ics->num_windows = 8;
1171 ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1172 ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1173 ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1174 ics->predictor_present = 0;
1176 ics->max_sfb = get_bits(gb, 6);
1177 ics->num_windows = 1;
1178 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1179 ics->swb_offset = ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];
1180 ics->num_swb = ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];
1181 ics->tns_max_bands = ff_tns_max_bands_512[ac->oc[1].m4ac.sampling_index];
1182 if (!ics->num_swb || !ics->swb_offset)
1185 ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1186 ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1187 ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1189 if (aot != AOT_ER_AAC_ELD) {
1190 ics->predictor_present = get_bits1(gb);
1191 ics->predictor_reset_group = 0;
1193 if (ics->predictor_present) {
1194 if (aot == AOT_AAC_MAIN) {
1195 if (decode_prediction(ac, ics, gb)) {
1196 return AVERROR_INVALIDDATA;
1198 } else if (aot == AOT_AAC_LC ||
1199 aot == AOT_ER_AAC_LC) {
1200 av_log(ac->avctx, AV_LOG_ERROR,
1201 "Prediction is not allowed in AAC-LC.\n");
1202 return AVERROR_INVALIDDATA;
1204 if (aot == AOT_ER_AAC_LD) {
1205 av_log(ac->avctx, AV_LOG_ERROR,
1206 "LTP in ER AAC LD not yet implemented.\n");
1207 return AVERROR_PATCHWELCOME;
1209 if ((ics->ltp.present = get_bits(gb, 1)))
1210 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1215 if (ics->max_sfb > ics->num_swb) {
1216 av_log(ac->avctx, AV_LOG_ERROR,
1217 "Number of scalefactor bands in group (%d) "
1218 "exceeds limit (%d).\n",
1219 ics->max_sfb, ics->num_swb);
1220 return AVERROR_INVALIDDATA;
1227 * Decode band types (section_data payload); reference: table 4.46.
1229 * @param band_type array of the used band type
1230 * @param band_type_run_end array of the last scalefactor band of a band type run
1232 * @return Returns error status. 0 - OK, !0 - error
1234 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1235 int band_type_run_end[120], GetBitContext *gb,
1236 IndividualChannelStream *ics)
1239 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1240 for (g = 0; g < ics->num_window_groups; g++) {
1242 while (k < ics->max_sfb) {
1243 uint8_t sect_end = k;
1245 int sect_band_type = get_bits(gb, 4);
1246 if (sect_band_type == 12) {
1247 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1248 return AVERROR_INVALIDDATA;
1251 sect_len_incr = get_bits(gb, bits);
1252 sect_end += sect_len_incr;
1253 if (get_bits_left(gb) < 0) {
1254 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1255 return AVERROR_INVALIDDATA;
1257 if (sect_end > ics->max_sfb) {
1258 av_log(ac->avctx, AV_LOG_ERROR,
1259 "Number of bands (%d) exceeds limit (%d).\n",
1260 sect_end, ics->max_sfb);
1261 return AVERROR_INVALIDDATA;
1263 } while (sect_len_incr == (1 << bits) - 1);
1264 for (; k < sect_end; k++) {
1265 band_type [idx] = sect_band_type;
1266 band_type_run_end[idx++] = sect_end;
1274 * Decode scalefactors; reference: table 4.47.
1276 * @param global_gain first scalefactor value as scalefactors are differentially coded
1277 * @param band_type array of the used band type
1278 * @param band_type_run_end array of the last scalefactor band of a band type run
1279 * @param sf array of scalefactors or intensity stereo positions
1281 * @return Returns error status. 0 - OK, !0 - error
1283 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1284 unsigned int global_gain,
1285 IndividualChannelStream *ics,
1286 enum BandType band_type[120],
1287 int band_type_run_end[120])
1290 int offset[3] = { global_gain, global_gain - 90, 0 };
1293 for (g = 0; g < ics->num_window_groups; g++) {
1294 for (i = 0; i < ics->max_sfb;) {
1295 int run_end = band_type_run_end[idx];
1296 if (band_type[idx] == ZERO_BT) {
1297 for (; i < run_end; i++, idx++)
1299 } else if ((band_type[idx] == INTENSITY_BT) ||
1300 (band_type[idx] == INTENSITY_BT2)) {
1301 for (; i < run_end; i++, idx++) {
1302 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1303 clipped_offset = av_clip(offset[2], -155, 100);
1304 if (offset[2] != clipped_offset) {
1305 avpriv_request_sample(ac->avctx,
1306 "If you heard an audible artifact, there may be a bug in the decoder. "
1307 "Clipped intensity stereo position (%d -> %d)",
1308 offset[2], clipped_offset);
1310 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1312 } else if (band_type[idx] == NOISE_BT) {
1313 for (; i < run_end; i++, idx++) {
1314 if (noise_flag-- > 0)
1315 offset[1] += get_bits(gb, 9) - 256;
1317 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1318 clipped_offset = av_clip(offset[1], -100, 155);
1319 if (offset[1] != clipped_offset) {
1320 avpriv_request_sample(ac->avctx,
1321 "If you heard an audible artifact, there may be a bug in the decoder. "
1322 "Clipped noise gain (%d -> %d)",
1323 offset[1], clipped_offset);
1325 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1328 for (; i < run_end; i++, idx++) {
1329 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1330 if (offset[0] > 255U) {
1331 av_log(ac->avctx, AV_LOG_ERROR,
1332 "Scalefactor (%d) out of range.\n", offset[0]);
1333 return AVERROR_INVALIDDATA;
1335 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1344 * Decode pulse data; reference: table 4.7.
1346 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1347 const uint16_t *swb_offset, int num_swb)
1350 pulse->num_pulse = get_bits(gb, 2) + 1;
1351 pulse_swb = get_bits(gb, 6);
1352 if (pulse_swb >= num_swb)
1354 pulse->pos[0] = swb_offset[pulse_swb];
1355 pulse->pos[0] += get_bits(gb, 5);
1356 if (pulse->pos[0] > 1023)
1358 pulse->amp[0] = get_bits(gb, 4);
1359 for (i = 1; i < pulse->num_pulse; i++) {
1360 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1361 if (pulse->pos[i] > 1023)
1363 pulse->amp[i] = get_bits(gb, 4);
1369 * Decode Temporal Noise Shaping data; reference: table 4.48.
1371 * @return Returns error status. 0 - OK, !0 - error
1373 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1374 GetBitContext *gb, const IndividualChannelStream *ics)
1376 int w, filt, i, coef_len, coef_res, coef_compress;
1377 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1378 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1379 for (w = 0; w < ics->num_windows; w++) {
1380 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1381 coef_res = get_bits1(gb);
1383 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1385 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1387 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1388 av_log(ac->avctx, AV_LOG_ERROR,
1389 "TNS filter order %d is greater than maximum %d.\n",
1390 tns->order[w][filt], tns_max_order);
1391 tns->order[w][filt] = 0;
1392 return AVERROR_INVALIDDATA;
1394 if (tns->order[w][filt]) {
1395 tns->direction[w][filt] = get_bits1(gb);
1396 coef_compress = get_bits1(gb);
1397 coef_len = coef_res + 3 - coef_compress;
1398 tmp2_idx = 2 * coef_compress + coef_res;
1400 for (i = 0; i < tns->order[w][filt]; i++)
1401 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1410 * Decode Mid/Side data; reference: table 4.54.
1412 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1413 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1414 * [3] reserved for scalable AAC
1416 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1420 if (ms_present == 1) {
1422 idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1424 cpe->ms_mask[idx] = get_bits1(gb);
1425 } else if (ms_present == 2) {
1426 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
1431 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1435 *dst++ = v[idx & 15] * s;
1436 *dst++ = v[idx>>4 & 15] * s;
1442 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1446 *dst++ = v[idx & 3] * s;
1447 *dst++ = v[idx>>2 & 3] * s;
1448 *dst++ = v[idx>>4 & 3] * s;
1449 *dst++ = v[idx>>6 & 3] * s;
1455 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1456 unsigned sign, const float *scale)
1458 union av_intfloat32 s0, s1;
1460 s0.f = s1.f = *scale;
1461 s0.i ^= sign >> 1 << 31;
1464 *dst++ = v[idx & 15] * s0.f;
1465 *dst++ = v[idx>>4 & 15] * s1.f;
1472 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1473 unsigned sign, const float *scale)
1475 unsigned nz = idx >> 12;
1476 union av_intfloat32 s = { .f = *scale };
1477 union av_intfloat32 t;
1479 t.i = s.i ^ (sign & 1U<<31);
1480 *dst++ = v[idx & 3] * t.f;
1482 sign <<= nz & 1; nz >>= 1;
1483 t.i = s.i ^ (sign & 1U<<31);
1484 *dst++ = v[idx>>2 & 3] * t.f;
1486 sign <<= nz & 1; nz >>= 1;
1487 t.i = s.i ^ (sign & 1U<<31);
1488 *dst++ = v[idx>>4 & 3] * t.f;
1491 t.i = s.i ^ (sign & 1U<<31);
1492 *dst++ = v[idx>>6 & 3] * t.f;
1499 * Decode spectral data; reference: table 4.50.
1500 * Dequantize and scale spectral data; reference: 4.6.3.3.
1502 * @param coef array of dequantized, scaled spectral data
1503 * @param sf array of scalefactors or intensity stereo positions
1504 * @param pulse_present set if pulses are present
1505 * @param pulse pointer to pulse data struct
1506 * @param band_type array of the used band type
1508 * @return Returns error status. 0 - OK, !0 - error
1510 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1511 GetBitContext *gb, const float sf[120],
1512 int pulse_present, const Pulse *pulse,
1513 const IndividualChannelStream *ics,
1514 enum BandType band_type[120])
1516 int i, k, g, idx = 0;
1517 const int c = 1024 / ics->num_windows;
1518 const uint16_t *offsets = ics->swb_offset;
1519 float *coef_base = coef;
1521 for (g = 0; g < ics->num_windows; g++)
1522 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1523 sizeof(float) * (c - offsets[ics->max_sfb]));
1525 for (g = 0; g < ics->num_window_groups; g++) {
1526 unsigned g_len = ics->group_len[g];
1528 for (i = 0; i < ics->max_sfb; i++, idx++) {
1529 const unsigned cbt_m1 = band_type[idx] - 1;
1530 float *cfo = coef + offsets[i];
1531 int off_len = offsets[i + 1] - offsets[i];
1534 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1535 for (group = 0; group < g_len; group++, cfo+=128) {
1536 memset(cfo, 0, off_len * sizeof(float));
1538 } else if (cbt_m1 == NOISE_BT - 1) {
1539 for (group = 0; group < g_len; group++, cfo+=128) {
1543 for (k = 0; k < off_len; k++) {
1544 ac->random_state = lcg_random(ac->random_state);
1545 cfo[k] = ac->random_state;
1548 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1549 scale = sf[idx] / sqrtf(band_energy);
1550 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1553 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1554 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1555 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1556 OPEN_READER(re, gb);
1558 switch (cbt_m1 >> 1) {
1560 for (group = 0; group < g_len; group++, cfo+=128) {
1568 UPDATE_CACHE(re, gb);
1569 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1570 cb_idx = cb_vector_idx[code];
1571 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1577 for (group = 0; group < g_len; group++, cfo+=128) {
1587 UPDATE_CACHE(re, gb);
1588 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1589 cb_idx = cb_vector_idx[code];
1590 nnz = cb_idx >> 8 & 15;
1591 bits = nnz ? GET_CACHE(re, gb) : 0;
1592 LAST_SKIP_BITS(re, gb, nnz);
1593 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1599 for (group = 0; group < g_len; group++, cfo+=128) {
1607 UPDATE_CACHE(re, gb);
1608 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1609 cb_idx = cb_vector_idx[code];
1610 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1617 for (group = 0; group < g_len; group++, cfo+=128) {
1627 UPDATE_CACHE(re, gb);
1628 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1629 cb_idx = cb_vector_idx[code];
1630 nnz = cb_idx >> 8 & 15;
1631 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1632 LAST_SKIP_BITS(re, gb, nnz);
1633 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1639 for (group = 0; group < g_len; group++, cfo+=128) {
1641 uint32_t *icf = (uint32_t *) cf;
1651 UPDATE_CACHE(re, gb);
1652 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1660 cb_idx = cb_vector_idx[code];
1663 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1664 LAST_SKIP_BITS(re, gb, nnz);
1666 for (j = 0; j < 2; j++) {
1670 /* The total length of escape_sequence must be < 22 bits according
1671 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1672 UPDATE_CACHE(re, gb);
1673 b = GET_CACHE(re, gb);
1674 b = 31 - av_log2(~b);
1677 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1678 return AVERROR_INVALIDDATA;
1681 SKIP_BITS(re, gb, b + 1);
1683 n = (1 << b) + SHOW_UBITS(re, gb, b);
1684 LAST_SKIP_BITS(re, gb, b);
1685 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1688 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1689 *icf++ = (bits & 1U<<31) | v;
1696 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1700 CLOSE_READER(re, gb);
1706 if (pulse_present) {
1708 for (i = 0; i < pulse->num_pulse; i++) {
1709 float co = coef_base[ pulse->pos[i] ];
1710 while (offsets[idx + 1] <= pulse->pos[i])
1712 if (band_type[idx] != NOISE_BT && sf[idx]) {
1713 float ico = -pulse->amp[i];
1716 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1718 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1725 static av_always_inline float flt16_round(float pf)
1727 union av_intfloat32 tmp;
1729 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1733 static av_always_inline float flt16_even(float pf)
1735 union av_intfloat32 tmp;
1737 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1741 static av_always_inline float flt16_trunc(float pf)
1743 union av_intfloat32 pun;
1745 pun.i &= 0xFFFF0000U;
1749 static av_always_inline void predict(PredictorState *ps, float *coef,
1752 const float a = 0.953125; // 61.0 / 64
1753 const float alpha = 0.90625; // 29.0 / 32
1757 float r0 = ps->r0, r1 = ps->r1;
1758 float cor0 = ps->cor0, cor1 = ps->cor1;
1759 float var0 = ps->var0, var1 = ps->var1;
1761 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1762 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1764 pv = flt16_round(k1 * r0 + k2 * r1);
1771 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1772 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1773 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1774 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1776 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1777 ps->r0 = flt16_trunc(a * e0);
1781 * Apply AAC-Main style frequency domain prediction.
1783 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1787 if (!sce->ics.predictor_initialized) {
1788 reset_all_predictors(sce->predictor_state);
1789 sce->ics.predictor_initialized = 1;
1792 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1794 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1796 for (k = sce->ics.swb_offset[sfb];
1797 k < sce->ics.swb_offset[sfb + 1];
1799 predict(&sce->predictor_state[k], &sce->coeffs[k],
1800 sce->ics.predictor_present &&
1801 sce->ics.prediction_used[sfb]);
1804 if (sce->ics.predictor_reset_group)
1805 reset_predictor_group(sce->predictor_state,
1806 sce->ics.predictor_reset_group);
1808 reset_all_predictors(sce->predictor_state);
1812 * Decode an individual_channel_stream payload; reference: table 4.44.
1814 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1815 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1817 * @return Returns error status. 0 - OK, !0 - error
1819 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1820 GetBitContext *gb, int common_window, int scale_flag)
1823 TemporalNoiseShaping *tns = &sce->tns;
1824 IndividualChannelStream *ics = &sce->ics;
1825 float *out = sce->coeffs;
1826 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1829 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1830 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1831 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1832 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1833 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1835 /* This assignment is to silence a GCC warning about the variable being used
1836 * uninitialized when in fact it always is.
1838 pulse.num_pulse = 0;
1840 global_gain = get_bits(gb, 8);
1842 if (!common_window && !scale_flag) {
1843 if (decode_ics_info(ac, ics, gb) < 0)
1844 return AVERROR_INVALIDDATA;
1847 if ((ret = decode_band_types(ac, sce->band_type,
1848 sce->band_type_run_end, gb, ics)) < 0)
1850 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1851 sce->band_type, sce->band_type_run_end)) < 0)
1856 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1857 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1858 av_log(ac->avctx, AV_LOG_ERROR,
1859 "Pulse tool not allowed in eight short sequence.\n");
1860 return AVERROR_INVALIDDATA;
1862 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1863 av_log(ac->avctx, AV_LOG_ERROR,
1864 "Pulse data corrupt or invalid.\n");
1865 return AVERROR_INVALIDDATA;
1868 tns->present = get_bits1(gb);
1869 if (tns->present && !er_syntax)
1870 if (decode_tns(ac, tns, gb, ics) < 0)
1871 return AVERROR_INVALIDDATA;
1872 if (!eld_syntax && get_bits1(gb)) {
1873 avpriv_request_sample(ac->avctx, "SSR");
1874 return AVERROR_PATCHWELCOME;
1876 // I see no textual basis in the spec for this occuring after SSR gain
1877 // control, but this is what both reference and real implmentations do
1878 if (tns->present && er_syntax)
1879 if (decode_tns(ac, tns, gb, ics) < 0)
1880 return AVERROR_INVALIDDATA;
1883 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1884 &pulse, ics, sce->band_type) < 0)
1885 return AVERROR_INVALIDDATA;
1887 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1888 apply_prediction(ac, sce);
1894 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1896 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1898 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1899 float *ch0 = cpe->ch[0].coeffs;
1900 float *ch1 = cpe->ch[1].coeffs;
1901 int g, i, group, idx = 0;
1902 const uint16_t *offsets = ics->swb_offset;
1903 for (g = 0; g < ics->num_window_groups; g++) {
1904 for (i = 0; i < ics->max_sfb; i++, idx++) {
1905 if (cpe->ms_mask[idx] &&
1906 cpe->ch[0].band_type[idx] < NOISE_BT &&
1907 cpe->ch[1].band_type[idx] < NOISE_BT) {
1908 for (group = 0; group < ics->group_len[g]; group++) {
1909 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1910 ch1 + group * 128 + offsets[i],
1911 offsets[i+1] - offsets[i]);
1915 ch0 += ics->group_len[g] * 128;
1916 ch1 += ics->group_len[g] * 128;
1921 * intensity stereo decoding; reference: 4.6.8.2.3
1923 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1924 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1925 * [3] reserved for scalable AAC
1927 static void apply_intensity_stereo(AACContext *ac,
1928 ChannelElement *cpe, int ms_present)
1930 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1931 SingleChannelElement *sce1 = &cpe->ch[1];
1932 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1933 const uint16_t *offsets = ics->swb_offset;
1934 int g, group, i, idx = 0;
1937 for (g = 0; g < ics->num_window_groups; g++) {
1938 for (i = 0; i < ics->max_sfb;) {
1939 if (sce1->band_type[idx] == INTENSITY_BT ||
1940 sce1->band_type[idx] == INTENSITY_BT2) {
1941 const int bt_run_end = sce1->band_type_run_end[idx];
1942 for (; i < bt_run_end; i++, idx++) {
1943 c = -1 + 2 * (sce1->band_type[idx] - 14);
1945 c *= 1 - 2 * cpe->ms_mask[idx];
1946 scale = c * sce1->sf[idx];
1947 for (group = 0; group < ics->group_len[g]; group++)
1948 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1949 coef0 + group * 128 + offsets[i],
1951 offsets[i + 1] - offsets[i]);
1954 int bt_run_end = sce1->band_type_run_end[idx];
1955 idx += bt_run_end - i;
1959 coef0 += ics->group_len[g] * 128;
1960 coef1 += ics->group_len[g] * 128;
1965 * Decode a channel_pair_element; reference: table 4.4.
1967 * @return Returns error status. 0 - OK, !0 - error
1969 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1971 int i, ret, common_window, ms_present = 0;
1972 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1974 common_window = eld_syntax || get_bits1(gb);
1975 if (common_window) {
1976 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1977 return AVERROR_INVALIDDATA;
1978 i = cpe->ch[1].ics.use_kb_window[0];
1979 cpe->ch[1].ics = cpe->ch[0].ics;
1980 cpe->ch[1].ics.use_kb_window[1] = i;
1981 if (cpe->ch[1].ics.predictor_present &&
1982 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1983 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1984 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1985 ms_present = get_bits(gb, 2);
1986 if (ms_present == 3) {
1987 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1988 return AVERROR_INVALIDDATA;
1989 } else if (ms_present)
1990 decode_mid_side_stereo(cpe, gb, ms_present);
1992 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1994 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1997 if (common_window) {
1999 apply_mid_side_stereo(ac, cpe);
2000 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2001 apply_prediction(ac, &cpe->ch[0]);
2002 apply_prediction(ac, &cpe->ch[1]);
2006 apply_intensity_stereo(ac, cpe, ms_present);
2010 static const float cce_scale[] = {
2011 1.09050773266525765921, //2^(1/8)
2012 1.18920711500272106672, //2^(1/4)
2018 * Decode coupling_channel_element; reference: table 4.8.
2020 * @return Returns error status. 0 - OK, !0 - error
2022 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2028 SingleChannelElement *sce = &che->ch[0];
2029 ChannelCoupling *coup = &che->coup;
2031 coup->coupling_point = 2 * get_bits1(gb);
2032 coup->num_coupled = get_bits(gb, 3);
2033 for (c = 0; c <= coup->num_coupled; c++) {
2035 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2036 coup->id_select[c] = get_bits(gb, 4);
2037 if (coup->type[c] == TYPE_CPE) {
2038 coup->ch_select[c] = get_bits(gb, 2);
2039 if (coup->ch_select[c] == 3)
2042 coup->ch_select[c] = 2;
2044 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2046 sign = get_bits(gb, 1);
2047 scale = cce_scale[get_bits(gb, 2)];
2049 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2052 for (c = 0; c < num_gain; c++) {
2056 float gain_cache = 1.0;
2058 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2059 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2060 gain_cache = powf(scale, -gain);
2062 if (coup->coupling_point == AFTER_IMDCT) {
2063 coup->gain[c][0] = gain_cache;
2065 for (g = 0; g < sce->ics.num_window_groups; g++) {
2066 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2067 if (sce->band_type[idx] != ZERO_BT) {
2069 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2077 gain_cache = powf(scale, -t) * s;
2080 coup->gain[c][idx] = gain_cache;
2090 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2092 * @return Returns number of bytes consumed.
2094 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2098 int num_excl_chan = 0;
2101 for (i = 0; i < 7; i++)
2102 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2103 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2105 return num_excl_chan / 7;
2109 * Decode dynamic range information; reference: table 4.52.
2111 * @return Returns number of bytes consumed.
2113 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2117 int drc_num_bands = 1;
2120 /* pce_tag_present? */
2121 if (get_bits1(gb)) {
2122 che_drc->pce_instance_tag = get_bits(gb, 4);
2123 skip_bits(gb, 4); // tag_reserved_bits
2127 /* excluded_chns_present? */
2128 if (get_bits1(gb)) {
2129 n += decode_drc_channel_exclusions(che_drc, gb);
2132 /* drc_bands_present? */
2133 if (get_bits1(gb)) {
2134 che_drc->band_incr = get_bits(gb, 4);
2135 che_drc->interpolation_scheme = get_bits(gb, 4);
2137 drc_num_bands += che_drc->band_incr;
2138 for (i = 0; i < drc_num_bands; i++) {
2139 che_drc->band_top[i] = get_bits(gb, 8);
2144 /* prog_ref_level_present? */
2145 if (get_bits1(gb)) {
2146 che_drc->prog_ref_level = get_bits(gb, 7);
2147 skip_bits1(gb); // prog_ref_level_reserved_bits
2151 for (i = 0; i < drc_num_bands; i++) {
2152 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2153 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2161 * Decode extension data (incomplete); reference: table 4.51.
2163 * @param cnt length of TYPE_FIL syntactic element in bytes
2165 * @return Returns number of bytes consumed
2167 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2168 ChannelElement *che, enum RawDataBlockType elem_type)
2172 switch (get_bits(gb, 4)) { // extension type
2173 case EXT_SBR_DATA_CRC:
2177 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2179 } else if (!ac->oc[1].m4ac.sbr) {
2180 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2181 skip_bits_long(gb, 8 * cnt - 4);
2183 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2184 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2185 skip_bits_long(gb, 8 * cnt - 4);
2187 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2188 ac->oc[1].m4ac.sbr = 1;
2189 ac->oc[1].m4ac.ps = 1;
2190 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2191 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2192 ac->oc[1].status, 1);
2194 ac->oc[1].m4ac.sbr = 1;
2195 ac->avctx->profile = FF_PROFILE_AAC_HE;
2197 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2199 case EXT_DYNAMIC_RANGE:
2200 res = decode_dynamic_range(&ac->che_drc, gb);
2204 case EXT_DATA_ELEMENT:
2206 skip_bits_long(gb, 8 * cnt - 4);
2213 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2215 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2216 * @param coef spectral coefficients
2218 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2219 IndividualChannelStream *ics, int decode)
2221 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2223 int bottom, top, order, start, end, size, inc;
2224 float lpc[TNS_MAX_ORDER];
2225 float tmp[TNS_MAX_ORDER + 1];
2227 for (w = 0; w < ics->num_windows; w++) {
2228 bottom = ics->num_swb;
2229 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2231 bottom = FFMAX(0, top - tns->length[w][filt]);
2232 order = tns->order[w][filt];
2237 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2239 start = ics->swb_offset[FFMIN(bottom, mmm)];
2240 end = ics->swb_offset[FFMIN( top, mmm)];
2241 if ((size = end - start) <= 0)
2243 if (tns->direction[w][filt]) {
2253 for (m = 0; m < size; m++, start += inc)
2254 for (i = 1; i <= FFMIN(m, order); i++)
2255 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2258 for (m = 0; m < size; m++, start += inc) {
2259 tmp[0] = coef[start];
2260 for (i = 1; i <= FFMIN(m, order); i++)
2261 coef[start] += tmp[i] * lpc[i - 1];
2262 for (i = order; i > 0; i--)
2263 tmp[i] = tmp[i - 1];
2271 * Apply windowing and MDCT to obtain the spectral
2272 * coefficient from the predicted sample by LTP.
2274 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2275 float *in, IndividualChannelStream *ics)
2277 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2278 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2279 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2280 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2282 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2283 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2285 memset(in, 0, 448 * sizeof(float));
2286 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2288 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2289 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2291 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2292 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2294 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2298 * Apply the long term prediction
2300 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2302 const LongTermPrediction *ltp = &sce->ics.ltp;
2303 const uint16_t *offsets = sce->ics.swb_offset;
2306 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2307 float *predTime = sce->ret;
2308 float *predFreq = ac->buf_mdct;
2309 int16_t num_samples = 2048;
2311 if (ltp->lag < 1024)
2312 num_samples = ltp->lag + 1024;
2313 for (i = 0; i < num_samples; i++)
2314 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2315 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2317 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2319 if (sce->tns.present)
2320 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2322 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2324 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2325 sce->coeffs[i] += predFreq[i];
2330 * Update the LTP buffer for next frame
2332 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2334 IndividualChannelStream *ics = &sce->ics;
2335 float *saved = sce->saved;
2336 float *saved_ltp = sce->coeffs;
2337 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2338 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2341 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2342 memcpy(saved_ltp, saved, 512 * sizeof(float));
2343 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2344 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2345 for (i = 0; i < 64; i++)
2346 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2347 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2348 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2349 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2350 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2351 for (i = 0; i < 64; i++)
2352 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2353 } else { // LONG_STOP or ONLY_LONG
2354 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2355 for (i = 0; i < 512; i++)
2356 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2359 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2360 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2361 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2365 * Conduct IMDCT and windowing.
2367 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2369 IndividualChannelStream *ics = &sce->ics;
2370 float *in = sce->coeffs;
2371 float *out = sce->ret;
2372 float *saved = sce->saved;
2373 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2374 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2375 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2376 float *buf = ac->buf_mdct;
2377 float *temp = ac->temp;
2381 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2382 for (i = 0; i < 1024; i += 128)
2383 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2385 ac->mdct.imdct_half(&ac->mdct, buf, in);
2387 /* window overlapping
2388 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2389 * and long to short transitions are considered to be short to short
2390 * transitions. This leaves just two cases (long to long and short to short)
2391 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2393 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2394 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2395 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2397 memcpy( out, saved, 448 * sizeof(float));
2399 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2400 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2401 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2402 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2403 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2404 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2405 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2407 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2408 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2413 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2414 memcpy( saved, temp + 64, 64 * sizeof(float));
2415 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2416 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2417 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2418 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2419 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2420 memcpy( saved, buf + 512, 448 * sizeof(float));
2421 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2422 } else { // LONG_STOP or ONLY_LONG
2423 memcpy( saved, buf + 512, 512 * sizeof(float));
2427 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2429 IndividualChannelStream *ics = &sce->ics;
2430 float *in = sce->coeffs;
2431 float *out = sce->ret;
2432 float *saved = sce->saved;
2433 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_512 : ff_sine_512;
2434 float *buf = ac->buf_mdct;
2437 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2439 // window overlapping
2440 ac->fdsp.vector_fmul_window(out, saved, buf, lwindow_prev, 256);
2443 memcpy(saved, buf + 256, 256 * sizeof(float));
2446 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2448 float *in = sce->coeffs;
2449 float *out = sce->ret;
2450 float *saved = sce->saved;
2451 const float *const window = ff_aac_eld_window;
2452 float *buf = ac->buf_mdct;
2455 const int n2 = n >> 1;
2456 const int n4 = n >> 2;
2458 // Inverse transform, mapped to the conventional IMDCT by
2459 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2460 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2461 // Audio, Language and Image Processing, 2008. ICALIP 2008. International Conference on
2462 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2463 for (i = 0; i < n2; i+=2) {
2465 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2466 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2468 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2469 for (i = 0; i < n; i+=2) {
2472 // Like with the regular IMDCT at this point we still have the middle half
2473 // of a transform but with even symmetry on the left and odd symmetry on
2476 // window overlapping
2477 // The spec says to use samples [0..511] but the reference decoder uses
2478 // samples [128..639].
2479 for (i = n4; i < n2; i ++) {
2480 out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2481 saved[ i + n2] * window[i + n - n4] +
2482 -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2483 -saved[2*n + n2 + i] * window[i + 3*n - n4];
2485 for (i = 0; i < n2; i ++) {
2486 out[n4 + i] = buf[i] * window[i + n2 - n4] +
2487 -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2488 -saved[ n + i] * window[i + n2 + 2*n - n4] +
2489 saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2491 for (i = 0; i < n4; i ++) {
2492 out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2493 -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2494 -saved[ n + n2 + i] * window[i + 3*n - n4];
2498 memmove(saved + n, saved, 2 * n * sizeof(float));
2499 memcpy( saved, buf, n * sizeof(float));
2503 * Apply dependent channel coupling (applied before IMDCT).
2505 * @param index index into coupling gain array
2507 static void apply_dependent_coupling(AACContext *ac,
2508 SingleChannelElement *target,
2509 ChannelElement *cce, int index)
2511 IndividualChannelStream *ics = &cce->ch[0].ics;
2512 const uint16_t *offsets = ics->swb_offset;
2513 float *dest = target->coeffs;
2514 const float *src = cce->ch[0].coeffs;
2515 int g, i, group, k, idx = 0;
2516 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2517 av_log(ac->avctx, AV_LOG_ERROR,
2518 "Dependent coupling is not supported together with LTP\n");
2521 for (g = 0; g < ics->num_window_groups; g++) {
2522 for (i = 0; i < ics->max_sfb; i++, idx++) {
2523 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2524 const float gain = cce->coup.gain[index][idx];
2525 for (group = 0; group < ics->group_len[g]; group++) {
2526 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2528 dest[group * 128 + k] += gain * src[group * 128 + k];
2533 dest += ics->group_len[g] * 128;
2534 src += ics->group_len[g] * 128;
2539 * Apply independent channel coupling (applied after IMDCT).
2541 * @param index index into coupling gain array
2543 static void apply_independent_coupling(AACContext *ac,
2544 SingleChannelElement *target,
2545 ChannelElement *cce, int index)
2548 const float gain = cce->coup.gain[index][0];
2549 const float *src = cce->ch[0].ret;
2550 float *dest = target->ret;
2551 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2553 for (i = 0; i < len; i++)
2554 dest[i] += gain * src[i];
2558 * channel coupling transformation interface
2560 * @param apply_coupling_method pointer to (in)dependent coupling function
2562 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2563 enum RawDataBlockType type, int elem_id,
2564 enum CouplingPoint coupling_point,
2565 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2569 for (i = 0; i < MAX_ELEM_ID; i++) {
2570 ChannelElement *cce = ac->che[TYPE_CCE][i];
2573 if (cce && cce->coup.coupling_point == coupling_point) {
2574 ChannelCoupling *coup = &cce->coup;
2576 for (c = 0; c <= coup->num_coupled; c++) {
2577 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2578 if (coup->ch_select[c] != 1) {
2579 apply_coupling_method(ac, &cc->ch[0], cce, index);
2580 if (coup->ch_select[c] != 0)
2583 if (coup->ch_select[c] != 2)
2584 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2586 index += 1 + (coup->ch_select[c] == 3);
2593 * Convert spectral data to float samples, applying all supported tools as appropriate.
2595 static void spectral_to_sample(AACContext *ac)
2598 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2599 switch (ac->oc[1].m4ac.object_type) {
2601 imdct_and_window = imdct_and_windowing_ld;
2603 case AOT_ER_AAC_ELD:
2604 imdct_and_window = imdct_and_windowing_eld;
2607 imdct_and_window = imdct_and_windowing;
2609 for (type = 3; type >= 0; type--) {
2610 for (i = 0; i < MAX_ELEM_ID; i++) {
2611 ChannelElement *che = ac->che[type][i];
2613 if (type <= TYPE_CPE)
2614 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2615 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2616 if (che->ch[0].ics.predictor_present) {
2617 if (che->ch[0].ics.ltp.present)
2618 apply_ltp(ac, &che->ch[0]);
2619 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2620 apply_ltp(ac, &che->ch[1]);
2623 if (che->ch[0].tns.present)
2624 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2625 if (che->ch[1].tns.present)
2626 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2627 if (type <= TYPE_CPE)
2628 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2629 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2630 imdct_and_window(ac, &che->ch[0]);
2631 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2632 update_ltp(ac, &che->ch[0]);
2633 if (type == TYPE_CPE) {
2634 imdct_and_window(ac, &che->ch[1]);
2635 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2636 update_ltp(ac, &che->ch[1]);
2638 if (ac->oc[1].m4ac.sbr > 0) {
2639 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2642 if (type <= TYPE_CCE)
2643 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2649 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2652 AACADTSHeaderInfo hdr_info;
2653 uint8_t layout_map[MAX_ELEM_ID*4][3];
2654 int layout_map_tags, ret;
2656 size = avpriv_aac_parse_header(gb, &hdr_info);
2658 if (hdr_info.num_aac_frames != 1) {
2659 avpriv_report_missing_feature(ac->avctx,
2660 "More than one AAC RDB per ADTS frame");
2661 return AVERROR_PATCHWELCOME;
2663 push_output_configuration(ac);
2664 if (hdr_info.chan_config) {
2665 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2666 if ((ret = set_default_channel_config(ac->avctx,
2669 hdr_info.chan_config)) < 0)
2671 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2672 FFMAX(ac->oc[1].status,
2673 OC_TRIAL_FRAME), 0)) < 0)
2676 ac->oc[1].m4ac.chan_config = 0;
2678 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2679 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2680 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2681 if (ac->oc[0].status != OC_LOCKED ||
2682 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2683 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2684 ac->oc[1].m4ac.sbr = -1;
2685 ac->oc[1].m4ac.ps = -1;
2687 if (!hdr_info.crc_absent)
2693 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2694 int *got_frame_ptr, GetBitContext *gb)
2696 AACContext *ac = avctx->priv_data;
2697 ChannelElement *che;
2700 int chan_config = ac->oc[1].m4ac.chan_config;
2701 int aot = ac->oc[1].m4ac.object_type;
2703 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2708 if ((err = frame_configure_elements(avctx)) < 0)
2711 // The FF_PROFILE_AAC_* defines are all object_type - 1
2712 // This may lead to an undefined profile being signaled
2713 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2715 ac->tags_mapped = 0;
2717 if (chan_config < 0 || chan_config >= 8) {
2718 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2719 ac->oc[1].m4ac.chan_config);
2720 return AVERROR_INVALIDDATA;
2722 for (i = 0; i < tags_per_config[chan_config]; i++) {
2723 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2724 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2725 if (!(che=get_che(ac, elem_type, elem_id))) {
2726 av_log(ac->avctx, AV_LOG_ERROR,
2727 "channel element %d.%d is not allocated\n",
2728 elem_type, elem_id);
2729 return AVERROR_INVALIDDATA;
2731 if (aot != AOT_ER_AAC_ELD)
2733 switch (elem_type) {
2735 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2738 err = decode_cpe(ac, gb, che);
2741 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2748 spectral_to_sample(ac);
2750 ac->frame->nb_samples = samples;
2753 skip_bits_long(gb, get_bits_left(gb));
2757 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2758 int *got_frame_ptr, GetBitContext *gb)
2760 AACContext *ac = avctx->priv_data;
2761 ChannelElement *che = NULL, *che_prev = NULL;
2762 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2764 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2768 if (show_bits(gb, 12) == 0xfff) {
2769 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2770 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2773 if (ac->oc[1].m4ac.sampling_index > 12) {
2774 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2775 err = AVERROR_INVALIDDATA;
2780 if ((err = frame_configure_elements(avctx)) < 0)
2783 // The FF_PROFILE_AAC_* defines are all object_type - 1
2784 // This may lead to an undefined profile being signaled
2785 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2787 ac->tags_mapped = 0;
2789 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2790 elem_id = get_bits(gb, 4);
2792 if (elem_type < TYPE_DSE) {
2793 if (!(che=get_che(ac, elem_type, elem_id))) {
2794 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2795 elem_type, elem_id);
2796 err = AVERROR_INVALIDDATA;
2802 switch (elem_type) {
2805 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2810 err = decode_cpe(ac, gb, che);
2815 err = decode_cce(ac, gb, che);
2819 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2824 err = skip_data_stream_element(ac, gb);
2828 uint8_t layout_map[MAX_ELEM_ID*4][3];
2830 push_output_configuration(ac);
2831 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2837 av_log(avctx, AV_LOG_ERROR,
2838 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2839 pop_output_configuration(ac);
2841 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2849 elem_id += get_bits(gb, 8) - 1;
2850 if (get_bits_left(gb) < 8 * elem_id) {
2851 av_log(avctx, AV_LOG_ERROR, overread_err);
2852 err = AVERROR_INVALIDDATA;
2856 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2857 err = 0; /* FIXME */
2861 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2866 elem_type_prev = elem_type;
2871 if (get_bits_left(gb) < 3) {
2872 av_log(avctx, AV_LOG_ERROR, overread_err);
2873 err = AVERROR_INVALIDDATA;
2878 spectral_to_sample(ac);
2880 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2881 samples <<= multiplier;
2884 ac->frame->nb_samples = samples;
2885 *got_frame_ptr = !!samples;
2887 if (ac->oc[1].status && audio_found) {
2888 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2889 avctx->frame_size = samples;
2890 ac->oc[1].status = OC_LOCKED;
2895 pop_output_configuration(ac);
2899 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2900 int *got_frame_ptr, AVPacket *avpkt)
2902 AACContext *ac = avctx->priv_data;
2903 const uint8_t *buf = avpkt->data;
2904 int buf_size = avpkt->size;
2909 int new_extradata_size;
2910 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2911 AV_PKT_DATA_NEW_EXTRADATA,
2912 &new_extradata_size);
2914 if (new_extradata) {
2915 av_free(avctx->extradata);
2916 avctx->extradata = av_mallocz(new_extradata_size +
2917 FF_INPUT_BUFFER_PADDING_SIZE);
2918 if (!avctx->extradata)
2919 return AVERROR(ENOMEM);
2920 avctx->extradata_size = new_extradata_size;
2921 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2922 push_output_configuration(ac);
2923 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2925 avctx->extradata_size*8, 1) < 0) {
2926 pop_output_configuration(ac);
2927 return AVERROR_INVALIDDATA;
2931 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
2934 switch (ac->oc[1].m4ac.object_type) {
2936 case AOT_ER_AAC_LTP:
2938 case AOT_ER_AAC_ELD:
2939 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
2942 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb);
2947 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2948 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2949 if (buf[buf_offset])
2952 return buf_size > buf_offset ? buf_consumed : buf_size;
2955 static av_cold int aac_decode_close(AVCodecContext *avctx)
2957 AACContext *ac = avctx->priv_data;
2960 for (i = 0; i < MAX_ELEM_ID; i++) {
2961 for (type = 0; type < 4; type++) {
2962 if (ac->che[type][i])
2963 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2964 av_freep(&ac->che[type][i]);
2968 ff_mdct_end(&ac->mdct);
2969 ff_mdct_end(&ac->mdct_small);
2970 ff_mdct_end(&ac->mdct_ld);
2971 ff_mdct_end(&ac->mdct_ltp);
2976 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2978 struct LATMContext {
2979 AACContext aac_ctx; ///< containing AACContext
2980 int initialized; ///< initilized after a valid extradata was seen
2983 int audio_mux_version_A; ///< LATM syntax version
2984 int frame_length_type; ///< 0/1 variable/fixed frame length
2985 int frame_length; ///< frame length for fixed frame length
2988 static inline uint32_t latm_get_value(GetBitContext *b)
2990 int length = get_bits(b, 2);
2992 return get_bits_long(b, (length+1)*8);
2995 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2996 GetBitContext *gb, int asclen)
2998 AACContext *ac = &latmctx->aac_ctx;
2999 AVCodecContext *avctx = ac->avctx;
3000 MPEG4AudioConfig m4ac = { 0 };
3001 int config_start_bit = get_bits_count(gb);
3002 int sync_extension = 0;
3003 int bits_consumed, esize;
3007 asclen = FFMIN(asclen, get_bits_left(gb));
3009 asclen = get_bits_left(gb);
3011 if (config_start_bit % 8) {
3012 avpriv_request_sample(latmctx->aac_ctx.avctx,
3013 "Non-byte-aligned audio-specific config");
3014 return AVERROR_PATCHWELCOME;
3017 return AVERROR_INVALIDDATA;
3018 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3019 gb->buffer + (config_start_bit / 8),
3020 asclen, sync_extension);
3022 if (bits_consumed < 0)
3023 return AVERROR_INVALIDDATA;
3025 if (ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3026 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3028 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3029 latmctx->initialized = 0;
3031 esize = (bits_consumed+7) / 8;
3033 if (avctx->extradata_size < esize) {
3034 av_free(avctx->extradata);
3035 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
3036 if (!avctx->extradata)
3037 return AVERROR(ENOMEM);
3040 avctx->extradata_size = esize;
3041 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3042 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3044 skip_bits_long(gb, bits_consumed);
3046 return bits_consumed;
3049 static int read_stream_mux_config(struct LATMContext *latmctx,
3052 int ret, audio_mux_version = get_bits(gb, 1);
3054 latmctx->audio_mux_version_A = 0;
3055 if (audio_mux_version)
3056 latmctx->audio_mux_version_A = get_bits(gb, 1);
3058 if (!latmctx->audio_mux_version_A) {
3060 if (audio_mux_version)
3061 latm_get_value(gb); // taraFullness
3063 skip_bits(gb, 1); // allStreamSameTimeFraming
3064 skip_bits(gb, 6); // numSubFrames
3066 if (get_bits(gb, 4)) { // numPrograms
3067 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3068 return AVERROR_PATCHWELCOME;
3071 // for each program (which there is only on in DVB)
3073 // for each layer (which there is only on in DVB)
3074 if (get_bits(gb, 3)) { // numLayer
3075 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3076 return AVERROR_PATCHWELCOME;
3079 // for all but first stream: use_same_config = get_bits(gb, 1);
3080 if (!audio_mux_version) {
3081 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3084 int ascLen = latm_get_value(gb);
3085 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3088 skip_bits_long(gb, ascLen);
3091 latmctx->frame_length_type = get_bits(gb, 3);
3092 switch (latmctx->frame_length_type) {
3094 skip_bits(gb, 8); // latmBufferFullness
3097 latmctx->frame_length = get_bits(gb, 9);
3102 skip_bits(gb, 6); // CELP frame length table index
3106 skip_bits(gb, 1); // HVXC frame length table index
3110 if (get_bits(gb, 1)) { // other data
3111 if (audio_mux_version) {
3112 latm_get_value(gb); // other_data_bits
3116 esc = get_bits(gb, 1);
3122 if (get_bits(gb, 1)) // crc present
3123 skip_bits(gb, 8); // config_crc
3129 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3133 if (ctx->frame_length_type == 0) {
3134 int mux_slot_length = 0;
3136 tmp = get_bits(gb, 8);
3137 mux_slot_length += tmp;
3138 } while (tmp == 255);
3139 return mux_slot_length;
3140 } else if (ctx->frame_length_type == 1) {
3141 return ctx->frame_length;
3142 } else if (ctx->frame_length_type == 3 ||
3143 ctx->frame_length_type == 5 ||
3144 ctx->frame_length_type == 7) {
3145 skip_bits(gb, 2); // mux_slot_length_coded
3150 static int read_audio_mux_element(struct LATMContext *latmctx,
3154 uint8_t use_same_mux = get_bits(gb, 1);
3155 if (!use_same_mux) {
3156 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3158 } else if (!latmctx->aac_ctx.avctx->extradata) {
3159 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3160 "no decoder config found\n");
3161 return AVERROR(EAGAIN);
3163 if (latmctx->audio_mux_version_A == 0) {
3164 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3165 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3166 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3167 return AVERROR_INVALIDDATA;
3168 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3169 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3170 "frame length mismatch %d << %d\n",
3171 mux_slot_length_bytes * 8, get_bits_left(gb));
3172 return AVERROR_INVALIDDATA;
3179 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3180 int *got_frame_ptr, AVPacket *avpkt)
3182 struct LATMContext *latmctx = avctx->priv_data;
3186 if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
3189 // check for LOAS sync word
3190 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3191 return AVERROR_INVALIDDATA;
3193 muxlength = get_bits(&gb, 13) + 3;
3194 // not enough data, the parser should have sorted this
3195 if (muxlength > avpkt->size)
3196 return AVERROR_INVALIDDATA;
3198 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3201 if (!latmctx->initialized) {
3202 if (!avctx->extradata) {
3206 push_output_configuration(&latmctx->aac_ctx);
3207 if ((err = decode_audio_specific_config(
3208 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3209 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3210 pop_output_configuration(&latmctx->aac_ctx);
3213 latmctx->initialized = 1;
3217 if (show_bits(&gb, 12) == 0xfff) {
3218 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3219 "ADTS header detected, probably as result of configuration "
3221 return AVERROR_INVALIDDATA;
3224 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
3230 static av_cold int latm_decode_init(AVCodecContext *avctx)
3232 struct LATMContext *latmctx = avctx->priv_data;
3233 int ret = aac_decode_init(avctx);
3235 if (avctx->extradata_size > 0)
3236 latmctx->initialized = !ret;
3242 AVCodec ff_aac_decoder = {
3244 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3245 .type = AVMEDIA_TYPE_AUDIO,
3246 .id = AV_CODEC_ID_AAC,
3247 .priv_data_size = sizeof(AACContext),
3248 .init = aac_decode_init,
3249 .close = aac_decode_close,
3250 .decode = aac_decode_frame,
3251 .sample_fmts = (const enum AVSampleFormat[]) {
3252 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3254 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3255 .channel_layouts = aac_channel_layout,
3259 Note: This decoder filter is intended to decode LATM streams transferred
3260 in MPEG transport streams which only contain one program.
3261 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3263 AVCodec ff_aac_latm_decoder = {
3265 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3266 .type = AVMEDIA_TYPE_AUDIO,
3267 .id = AV_CODEC_ID_AAC_LATM,
3268 .priv_data_size = sizeof(struct LATMContext),
3269 .init = latm_decode_init,
3270 .close = aac_decode_close,
3271 .decode = latm_decode_frame,
3272 .sample_fmts = (const enum AVSampleFormat[]) {
3273 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3275 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3276 .channel_layouts = aac_channel_layout,