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"
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)
147 if (!ac->che[type][id]) {
148 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
149 return AVERROR(ENOMEM);
150 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
152 if (type != TYPE_CCE) {
153 if (*channels >= MAX_CHANNELS - 2)
154 return AVERROR_INVALIDDATA;
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)
294 if (num_side_channels == 0 && num_back_channels >= 4) {
295 num_side_channels = 2;
296 num_back_channels -= 2;
300 if (num_front_channels & 1) {
301 e2c_vec[i] = (struct elem_to_channel) {
302 .av_position = AV_CH_FRONT_CENTER,
304 .elem_id = layout_map[i][1],
305 .aac_position = AAC_CHANNEL_FRONT
308 num_front_channels--;
310 if (num_front_channels >= 4) {
311 i += assign_pair(e2c_vec, layout_map, i,
312 AV_CH_FRONT_LEFT_OF_CENTER,
313 AV_CH_FRONT_RIGHT_OF_CENTER,
315 num_front_channels -= 2;
317 if (num_front_channels >= 2) {
318 i += assign_pair(e2c_vec, layout_map, i,
322 num_front_channels -= 2;
324 while (num_front_channels >= 2) {
325 i += assign_pair(e2c_vec, layout_map, i,
329 num_front_channels -= 2;
332 if (num_side_channels >= 2) {
333 i += assign_pair(e2c_vec, layout_map, i,
337 num_side_channels -= 2;
339 while (num_side_channels >= 2) {
340 i += assign_pair(e2c_vec, layout_map, i,
344 num_side_channels -= 2;
347 while (num_back_channels >= 4) {
348 i += assign_pair(e2c_vec, layout_map, i,
352 num_back_channels -= 2;
354 if (num_back_channels >= 2) {
355 i += assign_pair(e2c_vec, layout_map, i,
359 num_back_channels -= 2;
361 if (num_back_channels) {
362 e2c_vec[i] = (struct elem_to_channel) {
363 .av_position = AV_CH_BACK_CENTER,
365 .elem_id = layout_map[i][1],
366 .aac_position = AAC_CHANNEL_BACK
372 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
373 e2c_vec[i] = (struct elem_to_channel) {
374 .av_position = AV_CH_LOW_FREQUENCY,
376 .elem_id = layout_map[i][1],
377 .aac_position = AAC_CHANNEL_LFE
381 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
382 e2c_vec[i] = (struct elem_to_channel) {
383 .av_position = UINT64_MAX,
385 .elem_id = layout_map[i][1],
386 .aac_position = AAC_CHANNEL_LFE
391 // Must choose a stable sort
392 total_non_cc_elements = n = i;
395 for (i = 1; i < n; i++)
396 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
397 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
404 for (i = 0; i < total_non_cc_elements; i++) {
405 layout_map[i][0] = e2c_vec[i].syn_ele;
406 layout_map[i][1] = e2c_vec[i].elem_id;
407 layout_map[i][2] = e2c_vec[i].aac_position;
408 if (e2c_vec[i].av_position != UINT64_MAX) {
409 layout |= e2c_vec[i].av_position;
417 * Save current output configuration if and only if it has been locked.
419 static void push_output_configuration(AACContext *ac) {
420 if (ac->oc[1].status == OC_LOCKED) {
421 ac->oc[0] = ac->oc[1];
423 ac->oc[1].status = OC_NONE;
427 * Restore the previous output configuration if and only if the current
428 * configuration is unlocked.
430 static void pop_output_configuration(AACContext *ac) {
431 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
432 ac->oc[1] = ac->oc[0];
433 ac->avctx->channels = ac->oc[1].channels;
434 ac->avctx->channel_layout = ac->oc[1].channel_layout;
439 * Configure output channel order based on the current program
440 * configuration element.
442 * @return Returns error status. 0 - OK, !0 - error
444 static int output_configure(AACContext *ac,
445 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
446 enum OCStatus oc_type, int get_new_frame)
448 AVCodecContext *avctx = ac->avctx;
449 int i, channels = 0, ret;
451 uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
452 uint8_t type_counts[TYPE_END] = { 0 };
454 if (ac->oc[1].layout_map != layout_map) {
455 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
456 ac->oc[1].layout_map_tags = tags;
458 for (i = 0; i < tags; i++) {
459 int type = layout_map[i][0];
460 int id = layout_map[i][1];
461 id_map[type][id] = type_counts[type]++;
463 // Try to sniff a reasonable channel order, otherwise output the
464 // channels in the order the PCE declared them.
465 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
466 layout = sniff_channel_order(layout_map, tags);
467 for (i = 0; i < tags; i++) {
468 int type = layout_map[i][0];
469 int id = layout_map[i][1];
470 int iid = id_map[type][id];
471 int position = layout_map[i][2];
472 // Allocate or free elements depending on if they are in the
473 // current program configuration.
474 ret = che_configure(ac, position, type, iid, &channels);
477 ac->tag_che_map[type][id] = ac->che[type][iid];
479 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
480 if (layout == AV_CH_FRONT_CENTER) {
481 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
487 avctx->channel_layout = ac->oc[1].channel_layout = layout;
488 avctx->channels = ac->oc[1].channels = channels;
489 ac->oc[1].status = oc_type;
492 if ((ret = frame_configure_elements(ac->avctx)) < 0)
500 * Set up channel positions based on a default channel configuration
501 * as specified in table 1.17.
503 * @return Returns error status. 0 - OK, !0 - error
505 static int set_default_channel_config(AVCodecContext *avctx,
506 uint8_t (*layout_map)[3],
510 if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
511 channel_config > 12) {
512 av_log(avctx, AV_LOG_ERROR,
513 "invalid default channel configuration (%d)\n",
515 return AVERROR_INVALIDDATA;
517 *tags = tags_per_config[channel_config];
518 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
519 *tags * sizeof(*layout_map));
523 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
525 /* For PCE based channel configurations map the channels solely based
527 if (!ac->oc[1].m4ac.chan_config) {
528 return ac->tag_che_map[type][elem_id];
530 // Allow single CPE stereo files to be signalled with mono configuration.
531 if (!ac->tags_mapped && type == TYPE_CPE &&
532 ac->oc[1].m4ac.chan_config == 1) {
533 uint8_t layout_map[MAX_ELEM_ID*4][3];
535 push_output_configuration(ac);
537 if (set_default_channel_config(ac->avctx, layout_map,
538 &layout_map_tags, 2) < 0)
540 if (output_configure(ac, layout_map, layout_map_tags,
541 OC_TRIAL_FRAME, 1) < 0)
544 ac->oc[1].m4ac.chan_config = 2;
545 ac->oc[1].m4ac.ps = 0;
548 if (!ac->tags_mapped && type == TYPE_SCE &&
549 ac->oc[1].m4ac.chan_config == 2) {
550 uint8_t layout_map[MAX_ELEM_ID * 4][3];
552 push_output_configuration(ac);
554 if (set_default_channel_config(ac->avctx, layout_map,
555 &layout_map_tags, 1) < 0)
557 if (output_configure(ac, layout_map, layout_map_tags,
558 OC_TRIAL_FRAME, 1) < 0)
561 ac->oc[1].m4ac.chan_config = 1;
562 if (ac->oc[1].m4ac.sbr)
563 ac->oc[1].m4ac.ps = -1;
565 /* For indexed channel configurations map the channels solely based
567 switch (ac->oc[1].m4ac.chan_config) {
570 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
572 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
575 if (ac->tags_mapped == 2 &&
576 ac->oc[1].m4ac.chan_config == 11 &&
579 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
582 /* Some streams incorrectly code 5.1 audio as
583 * SCE[0] CPE[0] CPE[1] SCE[1]
585 * SCE[0] CPE[0] CPE[1] LFE[0].
586 * If we seem to have encountered such a stream, transfer
587 * the LFE[0] element to the SCE[1]'s mapping */
588 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
590 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
593 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
595 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
598 if (ac->tags_mapped == 2 &&
599 ac->oc[1].m4ac.chan_config == 4 &&
602 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
606 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
609 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
610 } else if (ac->oc[1].m4ac.chan_config == 2) {
614 if (!ac->tags_mapped && type == TYPE_SCE) {
616 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
624 * Decode an array of 4 bit element IDs, optionally interleaved with a
625 * stereo/mono switching bit.
627 * @param type speaker type/position for these channels
629 static void decode_channel_map(uint8_t layout_map[][3],
630 enum ChannelPosition type,
631 GetBitContext *gb, int n)
634 enum RawDataBlockType syn_ele;
636 case AAC_CHANNEL_FRONT:
637 case AAC_CHANNEL_BACK:
638 case AAC_CHANNEL_SIDE:
639 syn_ele = get_bits1(gb);
645 case AAC_CHANNEL_LFE:
649 // AAC_CHANNEL_OFF has no channel map
652 layout_map[0][0] = syn_ele;
653 layout_map[0][1] = get_bits(gb, 4);
654 layout_map[0][2] = type;
660 * Decode program configuration element; reference: table 4.2.
662 * @return Returns error status. 0 - OK, !0 - error
664 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
665 uint8_t (*layout_map)[3],
668 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
673 skip_bits(gb, 2); // object_type
675 sampling_index = get_bits(gb, 4);
676 if (m4ac->sampling_index != sampling_index)
677 av_log(avctx, AV_LOG_WARNING,
678 "Sample rate index in program config element does not "
679 "match the sample rate index configured by the container.\n");
681 num_front = get_bits(gb, 4);
682 num_side = get_bits(gb, 4);
683 num_back = get_bits(gb, 4);
684 num_lfe = get_bits(gb, 2);
685 num_assoc_data = get_bits(gb, 3);
686 num_cc = get_bits(gb, 4);
689 skip_bits(gb, 4); // mono_mixdown_tag
691 skip_bits(gb, 4); // stereo_mixdown_tag
694 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
696 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
698 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
700 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
702 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
705 skip_bits_long(gb, 4 * num_assoc_data);
707 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
712 /* comment field, first byte is length */
713 comment_len = get_bits(gb, 8) * 8;
714 if (get_bits_left(gb) < comment_len) {
715 av_log(avctx, AV_LOG_ERROR, overread_err);
716 return AVERROR_INVALIDDATA;
718 skip_bits_long(gb, comment_len);
723 * Decode GA "General Audio" specific configuration; reference: table 4.1.
725 * @param ac pointer to AACContext, may be null
726 * @param avctx pointer to AVCCodecContext, used for logging
728 * @return Returns error status. 0 - OK, !0 - error
730 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
732 MPEG4AudioConfig *m4ac,
735 int extension_flag, ret, ep_config, res_flags;
736 uint8_t layout_map[MAX_ELEM_ID*4][3];
739 if (get_bits1(gb)) { // frameLengthFlag
740 avpriv_request_sample(avctx, "960/120 MDCT window");
741 return AVERROR_PATCHWELCOME;
743 m4ac->frame_length_short = 0;
745 if (get_bits1(gb)) // dependsOnCoreCoder
746 skip_bits(gb, 14); // coreCoderDelay
747 extension_flag = get_bits1(gb);
749 if (m4ac->object_type == AOT_AAC_SCALABLE ||
750 m4ac->object_type == AOT_ER_AAC_SCALABLE)
751 skip_bits(gb, 3); // layerNr
753 if (channel_config == 0) {
754 skip_bits(gb, 4); // element_instance_tag
755 tags = decode_pce(avctx, m4ac, layout_map, gb);
759 if ((ret = set_default_channel_config(avctx, layout_map,
760 &tags, channel_config)))
764 if (count_channels(layout_map, tags) > 1) {
766 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
769 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
772 if (extension_flag) {
773 switch (m4ac->object_type) {
775 skip_bits(gb, 5); // numOfSubFrame
776 skip_bits(gb, 11); // layer_length
780 case AOT_ER_AAC_SCALABLE:
782 res_flags = get_bits(gb, 3);
784 avpriv_report_missing_feature(avctx,
785 "AAC data resilience (flags %x)",
787 return AVERROR_PATCHWELCOME;
791 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
793 switch (m4ac->object_type) {
796 case AOT_ER_AAC_SCALABLE:
798 ep_config = get_bits(gb, 2);
800 avpriv_report_missing_feature(avctx,
801 "epConfig %d", ep_config);
802 return AVERROR_PATCHWELCOME;
808 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
810 MPEG4AudioConfig *m4ac,
813 int ret, ep_config, res_flags;
814 uint8_t layout_map[MAX_ELEM_ID*4][3];
816 const int ELDEXT_TERM = 0;
821 m4ac->frame_length_short = get_bits1(gb);
822 res_flags = get_bits(gb, 3);
824 avpriv_report_missing_feature(avctx,
825 "AAC data resilience (flags %x)",
827 return AVERROR_PATCHWELCOME;
830 if (get_bits1(gb)) { // ldSbrPresentFlag
831 avpriv_report_missing_feature(avctx,
833 return AVERROR_PATCHWELCOME;
836 while (get_bits(gb, 4) != ELDEXT_TERM) {
837 int len = get_bits(gb, 4);
839 len += get_bits(gb, 8);
841 len += get_bits(gb, 16);
842 if (get_bits_left(gb) < len * 8 + 4) {
843 av_log(avctx, AV_LOG_ERROR, overread_err);
844 return AVERROR_INVALIDDATA;
846 skip_bits_long(gb, 8 * len);
849 if ((ret = set_default_channel_config(avctx, layout_map,
850 &tags, channel_config)))
853 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
856 ep_config = get_bits(gb, 2);
858 avpriv_report_missing_feature(avctx,
859 "epConfig %d", ep_config);
860 return AVERROR_PATCHWELCOME;
866 * Decode audio specific configuration; reference: table 1.13.
868 * @param ac pointer to AACContext, may be null
869 * @param avctx pointer to AVCCodecContext, used for logging
870 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
871 * @param data pointer to buffer holding an audio specific config
872 * @param bit_size size of audio specific config or data in bits
873 * @param sync_extension look for an appended sync extension
875 * @return Returns error status or number of consumed bits. <0 - error
877 static int decode_audio_specific_config(AACContext *ac,
878 AVCodecContext *avctx,
879 MPEG4AudioConfig *m4ac,
880 const uint8_t *data, int bit_size,
886 ff_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
887 for (i = 0; i < avctx->extradata_size; i++)
888 ff_dlog(avctx, "%02x ", avctx->extradata[i]);
889 ff_dlog(avctx, "\n");
891 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
894 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
895 sync_extension)) < 0)
896 return AVERROR_INVALIDDATA;
897 if (m4ac->sampling_index > 12) {
898 av_log(avctx, AV_LOG_ERROR,
899 "invalid sampling rate index %d\n",
900 m4ac->sampling_index);
901 return AVERROR_INVALIDDATA;
903 if (m4ac->object_type == AOT_ER_AAC_LD &&
904 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
905 av_log(avctx, AV_LOG_ERROR,
906 "invalid low delay sampling rate index %d\n",
907 m4ac->sampling_index);
908 return AVERROR_INVALIDDATA;
911 skip_bits_long(&gb, i);
913 switch (m4ac->object_type) {
919 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
920 m4ac, m4ac->chan_config)) < 0)
924 if ((ret = decode_eld_specific_config(ac, avctx, &gb,
925 m4ac, m4ac->chan_config)) < 0)
929 avpriv_report_missing_feature(avctx,
930 "Audio object type %s%d",
931 m4ac->sbr == 1 ? "SBR+" : "",
933 return AVERROR(ENOSYS);
937 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
938 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
939 m4ac->sample_rate, m4ac->sbr,
942 return get_bits_count(&gb);
946 * linear congruential pseudorandom number generator
948 * @param previous_val pointer to the current state of the generator
950 * @return Returns a 32-bit pseudorandom integer
952 static av_always_inline int lcg_random(int previous_val)
954 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
958 static av_always_inline void reset_predict_state(PredictorState *ps)
968 static void reset_all_predictors(PredictorState *ps)
971 for (i = 0; i < MAX_PREDICTORS; i++)
972 reset_predict_state(&ps[i]);
975 static int sample_rate_idx (int rate)
977 if (92017 <= rate) return 0;
978 else if (75132 <= rate) return 1;
979 else if (55426 <= rate) return 2;
980 else if (46009 <= rate) return 3;
981 else if (37566 <= rate) return 4;
982 else if (27713 <= rate) return 5;
983 else if (23004 <= rate) return 6;
984 else if (18783 <= rate) return 7;
985 else if (13856 <= rate) return 8;
986 else if (11502 <= rate) return 9;
987 else if (9391 <= rate) return 10;
991 static void reset_predictor_group(PredictorState *ps, int group_num)
994 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
995 reset_predict_state(&ps[i]);
998 #define AAC_INIT_VLC_STATIC(num, size) \
999 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1000 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1001 sizeof(ff_aac_spectral_bits[num][0]), \
1002 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1003 sizeof(ff_aac_spectral_codes[num][0]), \
1006 static av_cold int aac_decode_init(AVCodecContext *avctx)
1008 AACContext *ac = avctx->priv_data;
1012 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1014 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1016 if (avctx->extradata_size > 0) {
1017 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1019 avctx->extradata_size * 8,
1024 uint8_t layout_map[MAX_ELEM_ID*4][3];
1025 int layout_map_tags;
1027 sr = sample_rate_idx(avctx->sample_rate);
1028 ac->oc[1].m4ac.sampling_index = sr;
1029 ac->oc[1].m4ac.channels = avctx->channels;
1030 ac->oc[1].m4ac.sbr = -1;
1031 ac->oc[1].m4ac.ps = -1;
1033 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1034 if (ff_mpeg4audio_channels[i] == avctx->channels)
1036 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1039 ac->oc[1].m4ac.chan_config = i;
1041 if (ac->oc[1].m4ac.chan_config) {
1042 int ret = set_default_channel_config(avctx, layout_map,
1043 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1045 output_configure(ac, layout_map, layout_map_tags,
1047 else if (avctx->err_recognition & AV_EF_EXPLODE)
1048 return AVERROR_INVALIDDATA;
1052 AAC_INIT_VLC_STATIC( 0, 304);
1053 AAC_INIT_VLC_STATIC( 1, 270);
1054 AAC_INIT_VLC_STATIC( 2, 550);
1055 AAC_INIT_VLC_STATIC( 3, 300);
1056 AAC_INIT_VLC_STATIC( 4, 328);
1057 AAC_INIT_VLC_STATIC( 5, 294);
1058 AAC_INIT_VLC_STATIC( 6, 306);
1059 AAC_INIT_VLC_STATIC( 7, 268);
1060 AAC_INIT_VLC_STATIC( 8, 510);
1061 AAC_INIT_VLC_STATIC( 9, 366);
1062 AAC_INIT_VLC_STATIC(10, 462);
1066 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
1068 ac->random_state = 0x1f2e3d4c;
1072 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1073 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1074 ff_aac_scalefactor_bits,
1075 sizeof(ff_aac_scalefactor_bits[0]),
1076 sizeof(ff_aac_scalefactor_bits[0]),
1077 ff_aac_scalefactor_code,
1078 sizeof(ff_aac_scalefactor_code[0]),
1079 sizeof(ff_aac_scalefactor_code[0]),
1082 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1083 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1084 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1085 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1086 ret = ff_imdct15_init(&ac->mdct480, 5);
1090 // window initialization
1091 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1092 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1093 ff_init_ff_sine_windows(10);
1094 ff_init_ff_sine_windows( 9);
1095 ff_init_ff_sine_windows( 7);
1103 * Skip data_stream_element; reference: table 4.10.
1105 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1107 int byte_align = get_bits1(gb);
1108 int count = get_bits(gb, 8);
1110 count += get_bits(gb, 8);
1114 if (get_bits_left(gb) < 8 * count) {
1115 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1116 return AVERROR_INVALIDDATA;
1118 skip_bits_long(gb, 8 * count);
1122 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1126 if (get_bits1(gb)) {
1127 ics->predictor_reset_group = get_bits(gb, 5);
1128 if (ics->predictor_reset_group == 0 ||
1129 ics->predictor_reset_group > 30) {
1130 av_log(ac->avctx, AV_LOG_ERROR,
1131 "Invalid Predictor Reset Group.\n");
1132 return AVERROR_INVALIDDATA;
1135 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1136 ics->prediction_used[sfb] = get_bits1(gb);
1142 * Decode Long Term Prediction data; reference: table 4.xx.
1144 static void decode_ltp(LongTermPrediction *ltp,
1145 GetBitContext *gb, uint8_t max_sfb)
1149 ltp->lag = get_bits(gb, 11);
1150 ltp->coef = ltp_coef[get_bits(gb, 3)];
1151 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1152 ltp->used[sfb] = get_bits1(gb);
1156 * Decode Individual Channel Stream info; reference: table 4.6.
1158 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1161 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1162 const int aot = m4ac->object_type;
1163 const int sampling_index = m4ac->sampling_index;
1164 if (aot != AOT_ER_AAC_ELD) {
1165 if (get_bits1(gb)) {
1166 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1167 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1168 return AVERROR_INVALIDDATA;
1170 ics->window_sequence[1] = ics->window_sequence[0];
1171 ics->window_sequence[0] = get_bits(gb, 2);
1172 if (aot == AOT_ER_AAC_LD &&
1173 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1174 av_log(ac->avctx, AV_LOG_ERROR,
1175 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1176 "window sequence %d found.\n", ics->window_sequence[0]);
1177 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1178 return AVERROR_INVALIDDATA;
1180 ics->use_kb_window[1] = ics->use_kb_window[0];
1181 ics->use_kb_window[0] = get_bits1(gb);
1183 ics->num_window_groups = 1;
1184 ics->group_len[0] = 1;
1185 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1187 ics->max_sfb = get_bits(gb, 4);
1188 for (i = 0; i < 7; i++) {
1189 if (get_bits1(gb)) {
1190 ics->group_len[ics->num_window_groups - 1]++;
1192 ics->num_window_groups++;
1193 ics->group_len[ics->num_window_groups - 1] = 1;
1196 ics->num_windows = 8;
1197 ics->swb_offset = ff_swb_offset_128[sampling_index];
1198 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1199 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
1200 ics->predictor_present = 0;
1202 ics->max_sfb = get_bits(gb, 6);
1203 ics->num_windows = 1;
1204 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1205 if (m4ac->frame_length_short) {
1206 ics->swb_offset = ff_swb_offset_480[sampling_index];
1207 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1208 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1210 ics->swb_offset = ff_swb_offset_512[sampling_index];
1211 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1212 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1214 if (!ics->num_swb || !ics->swb_offset)
1217 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1218 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1219 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1221 if (aot != AOT_ER_AAC_ELD) {
1222 ics->predictor_present = get_bits1(gb);
1223 ics->predictor_reset_group = 0;
1225 if (ics->predictor_present) {
1226 if (aot == AOT_AAC_MAIN) {
1227 if (decode_prediction(ac, ics, gb)) {
1228 return AVERROR_INVALIDDATA;
1230 } else if (aot == AOT_AAC_LC ||
1231 aot == AOT_ER_AAC_LC) {
1232 av_log(ac->avctx, AV_LOG_ERROR,
1233 "Prediction is not allowed in AAC-LC.\n");
1234 return AVERROR_INVALIDDATA;
1236 if (aot == AOT_ER_AAC_LD) {
1237 av_log(ac->avctx, AV_LOG_ERROR,
1238 "LTP in ER AAC LD not yet implemented.\n");
1239 return AVERROR_PATCHWELCOME;
1241 if ((ics->ltp.present = get_bits(gb, 1)))
1242 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1247 if (ics->max_sfb > ics->num_swb) {
1248 av_log(ac->avctx, AV_LOG_ERROR,
1249 "Number of scalefactor bands in group (%d) "
1250 "exceeds limit (%d).\n",
1251 ics->max_sfb, ics->num_swb);
1252 return AVERROR_INVALIDDATA;
1259 * Decode band types (section_data payload); reference: table 4.46.
1261 * @param band_type array of the used band type
1262 * @param band_type_run_end array of the last scalefactor band of a band type run
1264 * @return Returns error status. 0 - OK, !0 - error
1266 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1267 int band_type_run_end[120], GetBitContext *gb,
1268 IndividualChannelStream *ics)
1271 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1272 for (g = 0; g < ics->num_window_groups; g++) {
1274 while (k < ics->max_sfb) {
1275 uint8_t sect_end = k;
1277 int sect_band_type = get_bits(gb, 4);
1278 if (sect_band_type == 12) {
1279 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1280 return AVERROR_INVALIDDATA;
1283 sect_len_incr = get_bits(gb, bits);
1284 sect_end += sect_len_incr;
1285 if (get_bits_left(gb) < 0) {
1286 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1287 return AVERROR_INVALIDDATA;
1289 if (sect_end > ics->max_sfb) {
1290 av_log(ac->avctx, AV_LOG_ERROR,
1291 "Number of bands (%d) exceeds limit (%d).\n",
1292 sect_end, ics->max_sfb);
1293 return AVERROR_INVALIDDATA;
1295 } while (sect_len_incr == (1 << bits) - 1);
1296 for (; k < sect_end; k++) {
1297 band_type [idx] = sect_band_type;
1298 band_type_run_end[idx++] = sect_end;
1306 * Decode scalefactors; reference: table 4.47.
1308 * @param global_gain first scalefactor value as scalefactors are differentially coded
1309 * @param band_type array of the used band type
1310 * @param band_type_run_end array of the last scalefactor band of a band type run
1311 * @param sf array of scalefactors or intensity stereo positions
1313 * @return Returns error status. 0 - OK, !0 - error
1315 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1316 unsigned int global_gain,
1317 IndividualChannelStream *ics,
1318 enum BandType band_type[120],
1319 int band_type_run_end[120])
1322 int offset[3] = { global_gain, global_gain - 90, 0 };
1325 for (g = 0; g < ics->num_window_groups; g++) {
1326 for (i = 0; i < ics->max_sfb;) {
1327 int run_end = band_type_run_end[idx];
1328 if (band_type[idx] == ZERO_BT) {
1329 for (; i < run_end; i++, idx++)
1331 } else if ((band_type[idx] == INTENSITY_BT) ||
1332 (band_type[idx] == INTENSITY_BT2)) {
1333 for (; i < run_end; i++, idx++) {
1334 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1335 clipped_offset = av_clip(offset[2], -155, 100);
1336 if (offset[2] != clipped_offset) {
1337 avpriv_request_sample(ac->avctx,
1338 "If you heard an audible artifact, there may be a bug in the decoder. "
1339 "Clipped intensity stereo position (%d -> %d)",
1340 offset[2], clipped_offset);
1342 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1344 } else if (band_type[idx] == NOISE_BT) {
1345 for (; i < run_end; i++, idx++) {
1346 if (noise_flag-- > 0)
1347 offset[1] += get_bits(gb, 9) - 256;
1349 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1350 clipped_offset = av_clip(offset[1], -100, 155);
1351 if (offset[1] != clipped_offset) {
1352 avpriv_request_sample(ac->avctx,
1353 "If you heard an audible artifact, there may be a bug in the decoder. "
1354 "Clipped noise gain (%d -> %d)",
1355 offset[1], clipped_offset);
1357 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1360 for (; i < run_end; i++, idx++) {
1361 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1362 if (offset[0] > 255U) {
1363 av_log(ac->avctx, AV_LOG_ERROR,
1364 "Scalefactor (%d) out of range.\n", offset[0]);
1365 return AVERROR_INVALIDDATA;
1367 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1376 * Decode pulse data; reference: table 4.7.
1378 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1379 const uint16_t *swb_offset, int num_swb)
1382 pulse->num_pulse = get_bits(gb, 2) + 1;
1383 pulse_swb = get_bits(gb, 6);
1384 if (pulse_swb >= num_swb)
1386 pulse->pos[0] = swb_offset[pulse_swb];
1387 pulse->pos[0] += get_bits(gb, 5);
1388 if (pulse->pos[0] > 1023)
1390 pulse->amp[0] = get_bits(gb, 4);
1391 for (i = 1; i < pulse->num_pulse; i++) {
1392 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1393 if (pulse->pos[i] > 1023)
1395 pulse->amp[i] = get_bits(gb, 4);
1401 * Decode Temporal Noise Shaping data; reference: table 4.48.
1403 * @return Returns error status. 0 - OK, !0 - error
1405 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1406 GetBitContext *gb, const IndividualChannelStream *ics)
1408 int w, filt, i, coef_len, coef_res, coef_compress;
1409 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1410 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1411 for (w = 0; w < ics->num_windows; w++) {
1412 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1413 coef_res = get_bits1(gb);
1415 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1417 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1419 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1420 av_log(ac->avctx, AV_LOG_ERROR,
1421 "TNS filter order %d is greater than maximum %d.\n",
1422 tns->order[w][filt], tns_max_order);
1423 tns->order[w][filt] = 0;
1424 return AVERROR_INVALIDDATA;
1426 if (tns->order[w][filt]) {
1427 tns->direction[w][filt] = get_bits1(gb);
1428 coef_compress = get_bits1(gb);
1429 coef_len = coef_res + 3 - coef_compress;
1430 tmp2_idx = 2 * coef_compress + coef_res;
1432 for (i = 0; i < tns->order[w][filt]; i++)
1433 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1442 * Decode Mid/Side data; reference: table 4.54.
1444 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1445 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1446 * [3] reserved for scalable AAC
1448 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1452 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1453 if (ms_present == 1) {
1454 for (idx = 0; idx < max_idx; idx++)
1455 cpe->ms_mask[idx] = get_bits1(gb);
1456 } else if (ms_present == 2) {
1457 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1462 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1466 *dst++ = v[idx & 15] * s;
1467 *dst++ = v[idx>>4 & 15] * s;
1473 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1477 *dst++ = v[idx & 3] * s;
1478 *dst++ = v[idx>>2 & 3] * s;
1479 *dst++ = v[idx>>4 & 3] * s;
1480 *dst++ = v[idx>>6 & 3] * s;
1486 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1487 unsigned sign, const float *scale)
1489 union av_intfloat32 s0, s1;
1491 s0.f = s1.f = *scale;
1492 s0.i ^= sign >> 1 << 31;
1495 *dst++ = v[idx & 15] * s0.f;
1496 *dst++ = v[idx>>4 & 15] * s1.f;
1503 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1504 unsigned sign, const float *scale)
1506 unsigned nz = idx >> 12;
1507 union av_intfloat32 s = { .f = *scale };
1508 union av_intfloat32 t;
1510 t.i = s.i ^ (sign & 1U<<31);
1511 *dst++ = v[idx & 3] * t.f;
1513 sign <<= nz & 1; nz >>= 1;
1514 t.i = s.i ^ (sign & 1U<<31);
1515 *dst++ = v[idx>>2 & 3] * t.f;
1517 sign <<= nz & 1; nz >>= 1;
1518 t.i = s.i ^ (sign & 1U<<31);
1519 *dst++ = v[idx>>4 & 3] * t.f;
1522 t.i = s.i ^ (sign & 1U<<31);
1523 *dst++ = v[idx>>6 & 3] * t.f;
1530 * Decode spectral data; reference: table 4.50.
1531 * Dequantize and scale spectral data; reference: 4.6.3.3.
1533 * @param coef array of dequantized, scaled spectral data
1534 * @param sf array of scalefactors or intensity stereo positions
1535 * @param pulse_present set if pulses are present
1536 * @param pulse pointer to pulse data struct
1537 * @param band_type array of the used band type
1539 * @return Returns error status. 0 - OK, !0 - error
1541 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1542 GetBitContext *gb, const float sf[120],
1543 int pulse_present, const Pulse *pulse,
1544 const IndividualChannelStream *ics,
1545 enum BandType band_type[120])
1547 int i, k, g, idx = 0;
1548 const int c = 1024 / ics->num_windows;
1549 const uint16_t *offsets = ics->swb_offset;
1550 float *coef_base = coef;
1552 for (g = 0; g < ics->num_windows; g++)
1553 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1554 sizeof(float) * (c - offsets[ics->max_sfb]));
1556 for (g = 0; g < ics->num_window_groups; g++) {
1557 unsigned g_len = ics->group_len[g];
1559 for (i = 0; i < ics->max_sfb; i++, idx++) {
1560 const unsigned cbt_m1 = band_type[idx] - 1;
1561 float *cfo = coef + offsets[i];
1562 int off_len = offsets[i + 1] - offsets[i];
1565 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1566 for (group = 0; group < g_len; group++, cfo+=128) {
1567 memset(cfo, 0, off_len * sizeof(float));
1569 } else if (cbt_m1 == NOISE_BT - 1) {
1570 for (group = 0; group < g_len; group++, cfo+=128) {
1574 for (k = 0; k < off_len; k++) {
1575 ac->random_state = lcg_random(ac->random_state);
1576 cfo[k] = ac->random_state;
1579 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1580 scale = sf[idx] / sqrtf(band_energy);
1581 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1584 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1585 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1586 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1587 OPEN_READER(re, gb);
1589 switch (cbt_m1 >> 1) {
1591 for (group = 0; group < g_len; group++, cfo+=128) {
1599 UPDATE_CACHE(re, gb);
1600 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1601 cb_idx = cb_vector_idx[code];
1602 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1608 for (group = 0; group < g_len; group++, cfo+=128) {
1618 UPDATE_CACHE(re, gb);
1619 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1620 cb_idx = cb_vector_idx[code];
1621 nnz = cb_idx >> 8 & 15;
1622 bits = nnz ? GET_CACHE(re, gb) : 0;
1623 LAST_SKIP_BITS(re, gb, nnz);
1624 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1630 for (group = 0; group < g_len; group++, cfo+=128) {
1638 UPDATE_CACHE(re, gb);
1639 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1640 cb_idx = cb_vector_idx[code];
1641 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1648 for (group = 0; group < g_len; group++, cfo+=128) {
1658 UPDATE_CACHE(re, gb);
1659 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1660 cb_idx = cb_vector_idx[code];
1661 nnz = cb_idx >> 8 & 15;
1662 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1663 LAST_SKIP_BITS(re, gb, nnz);
1664 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1670 for (group = 0; group < g_len; group++, cfo+=128) {
1672 uint32_t *icf = (uint32_t *) cf;
1682 UPDATE_CACHE(re, gb);
1683 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1691 cb_idx = cb_vector_idx[code];
1694 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1695 LAST_SKIP_BITS(re, gb, nnz);
1697 for (j = 0; j < 2; j++) {
1701 /* The total length of escape_sequence must be < 22 bits according
1702 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1703 UPDATE_CACHE(re, gb);
1704 b = GET_CACHE(re, gb);
1705 b = 31 - av_log2(~b);
1708 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1709 return AVERROR_INVALIDDATA;
1712 SKIP_BITS(re, gb, b + 1);
1714 n = (1 << b) + SHOW_UBITS(re, gb, b);
1715 LAST_SKIP_BITS(re, gb, b);
1716 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1719 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1720 *icf++ = (bits & 1U<<31) | v;
1727 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1731 CLOSE_READER(re, gb);
1737 if (pulse_present) {
1739 for (i = 0; i < pulse->num_pulse; i++) {
1740 float co = coef_base[ pulse->pos[i] ];
1741 while (offsets[idx + 1] <= pulse->pos[i])
1743 if (band_type[idx] != NOISE_BT && sf[idx]) {
1744 float ico = -pulse->amp[i];
1747 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1749 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1756 static av_always_inline float flt16_round(float pf)
1758 union av_intfloat32 tmp;
1760 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1764 static av_always_inline float flt16_even(float pf)
1766 union av_intfloat32 tmp;
1768 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1772 static av_always_inline float flt16_trunc(float pf)
1774 union av_intfloat32 pun;
1776 pun.i &= 0xFFFF0000U;
1780 static av_always_inline void predict(PredictorState *ps, float *coef,
1783 const float a = 0.953125; // 61.0 / 64
1784 const float alpha = 0.90625; // 29.0 / 32
1788 float r0 = ps->r0, r1 = ps->r1;
1789 float cor0 = ps->cor0, cor1 = ps->cor1;
1790 float var0 = ps->var0, var1 = ps->var1;
1792 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1793 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1795 pv = flt16_round(k1 * r0 + k2 * r1);
1802 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1803 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1804 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1805 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1807 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1808 ps->r0 = flt16_trunc(a * e0);
1812 * Apply AAC-Main style frequency domain prediction.
1814 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1818 if (!sce->ics.predictor_initialized) {
1819 reset_all_predictors(sce->predictor_state);
1820 sce->ics.predictor_initialized = 1;
1823 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1825 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1827 for (k = sce->ics.swb_offset[sfb];
1828 k < sce->ics.swb_offset[sfb + 1];
1830 predict(&sce->predictor_state[k], &sce->coeffs[k],
1831 sce->ics.predictor_present &&
1832 sce->ics.prediction_used[sfb]);
1835 if (sce->ics.predictor_reset_group)
1836 reset_predictor_group(sce->predictor_state,
1837 sce->ics.predictor_reset_group);
1839 reset_all_predictors(sce->predictor_state);
1843 * Decode an individual_channel_stream payload; reference: table 4.44.
1845 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1846 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1848 * @return Returns error status. 0 - OK, !0 - error
1850 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1851 GetBitContext *gb, int common_window, int scale_flag)
1854 TemporalNoiseShaping *tns = &sce->tns;
1855 IndividualChannelStream *ics = &sce->ics;
1856 float *out = sce->coeffs;
1857 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1860 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1861 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1862 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1863 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1864 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1866 /* This assignment is to silence a GCC warning about the variable being used
1867 * uninitialized when in fact it always is.
1869 pulse.num_pulse = 0;
1871 global_gain = get_bits(gb, 8);
1873 if (!common_window && !scale_flag) {
1874 if (decode_ics_info(ac, ics, gb) < 0)
1875 return AVERROR_INVALIDDATA;
1878 if ((ret = decode_band_types(ac, sce->band_type,
1879 sce->band_type_run_end, gb, ics)) < 0)
1881 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1882 sce->band_type, sce->band_type_run_end)) < 0)
1887 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1888 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1889 av_log(ac->avctx, AV_LOG_ERROR,
1890 "Pulse tool not allowed in eight short sequence.\n");
1891 return AVERROR_INVALIDDATA;
1893 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1894 av_log(ac->avctx, AV_LOG_ERROR,
1895 "Pulse data corrupt or invalid.\n");
1896 return AVERROR_INVALIDDATA;
1899 tns->present = get_bits1(gb);
1900 if (tns->present && !er_syntax)
1901 if (decode_tns(ac, tns, gb, ics) < 0)
1902 return AVERROR_INVALIDDATA;
1903 if (!eld_syntax && get_bits1(gb)) {
1904 avpriv_request_sample(ac->avctx, "SSR");
1905 return AVERROR_PATCHWELCOME;
1907 // I see no textual basis in the spec for this occuring after SSR gain
1908 // control, but this is what both reference and real implmentations do
1909 if (tns->present && er_syntax)
1910 if (decode_tns(ac, tns, gb, ics) < 0)
1911 return AVERROR_INVALIDDATA;
1914 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1915 &pulse, ics, sce->band_type) < 0)
1916 return AVERROR_INVALIDDATA;
1918 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1919 apply_prediction(ac, sce);
1925 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1927 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1929 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1930 float *ch0 = cpe->ch[0].coeffs;
1931 float *ch1 = cpe->ch[1].coeffs;
1932 int g, i, group, idx = 0;
1933 const uint16_t *offsets = ics->swb_offset;
1934 for (g = 0; g < ics->num_window_groups; g++) {
1935 for (i = 0; i < ics->max_sfb; i++, idx++) {
1936 if (cpe->ms_mask[idx] &&
1937 cpe->ch[0].band_type[idx] < NOISE_BT &&
1938 cpe->ch[1].band_type[idx] < NOISE_BT) {
1939 for (group = 0; group < ics->group_len[g]; group++) {
1940 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1941 ch1 + group * 128 + offsets[i],
1942 offsets[i+1] - offsets[i]);
1946 ch0 += ics->group_len[g] * 128;
1947 ch1 += ics->group_len[g] * 128;
1952 * intensity stereo decoding; reference: 4.6.8.2.3
1954 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1955 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1956 * [3] reserved for scalable AAC
1958 static void apply_intensity_stereo(AACContext *ac,
1959 ChannelElement *cpe, int ms_present)
1961 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1962 SingleChannelElement *sce1 = &cpe->ch[1];
1963 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1964 const uint16_t *offsets = ics->swb_offset;
1965 int g, group, i, idx = 0;
1968 for (g = 0; g < ics->num_window_groups; g++) {
1969 for (i = 0; i < ics->max_sfb;) {
1970 if (sce1->band_type[idx] == INTENSITY_BT ||
1971 sce1->band_type[idx] == INTENSITY_BT2) {
1972 const int bt_run_end = sce1->band_type_run_end[idx];
1973 for (; i < bt_run_end; i++, idx++) {
1974 c = -1 + 2 * (sce1->band_type[idx] - 14);
1976 c *= 1 - 2 * cpe->ms_mask[idx];
1977 scale = c * sce1->sf[idx];
1978 for (group = 0; group < ics->group_len[g]; group++)
1979 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1980 coef0 + group * 128 + offsets[i],
1982 offsets[i + 1] - offsets[i]);
1985 int bt_run_end = sce1->band_type_run_end[idx];
1986 idx += bt_run_end - i;
1990 coef0 += ics->group_len[g] * 128;
1991 coef1 += ics->group_len[g] * 128;
1996 * Decode a channel_pair_element; reference: table 4.4.
1998 * @return Returns error status. 0 - OK, !0 - error
2000 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2002 int i, ret, common_window, ms_present = 0;
2003 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2005 common_window = eld_syntax || get_bits1(gb);
2006 if (common_window) {
2007 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2008 return AVERROR_INVALIDDATA;
2009 i = cpe->ch[1].ics.use_kb_window[0];
2010 cpe->ch[1].ics = cpe->ch[0].ics;
2011 cpe->ch[1].ics.use_kb_window[1] = i;
2012 if (cpe->ch[1].ics.predictor_present &&
2013 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2014 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2015 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2016 ms_present = get_bits(gb, 2);
2017 if (ms_present == 3) {
2018 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2019 return AVERROR_INVALIDDATA;
2020 } else if (ms_present)
2021 decode_mid_side_stereo(cpe, gb, ms_present);
2023 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2025 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2028 if (common_window) {
2030 apply_mid_side_stereo(ac, cpe);
2031 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2032 apply_prediction(ac, &cpe->ch[0]);
2033 apply_prediction(ac, &cpe->ch[1]);
2037 apply_intensity_stereo(ac, cpe, ms_present);
2041 static const float cce_scale[] = {
2042 1.09050773266525765921, //2^(1/8)
2043 1.18920711500272106672, //2^(1/4)
2049 * Decode coupling_channel_element; reference: table 4.8.
2051 * @return Returns error status. 0 - OK, !0 - error
2053 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2059 SingleChannelElement *sce = &che->ch[0];
2060 ChannelCoupling *coup = &che->coup;
2062 coup->coupling_point = 2 * get_bits1(gb);
2063 coup->num_coupled = get_bits(gb, 3);
2064 for (c = 0; c <= coup->num_coupled; c++) {
2066 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2067 coup->id_select[c] = get_bits(gb, 4);
2068 if (coup->type[c] == TYPE_CPE) {
2069 coup->ch_select[c] = get_bits(gb, 2);
2070 if (coup->ch_select[c] == 3)
2073 coup->ch_select[c] = 2;
2075 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2077 sign = get_bits(gb, 1);
2078 scale = cce_scale[get_bits(gb, 2)];
2080 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2083 for (c = 0; c < num_gain; c++) {
2087 float gain_cache = 1.0;
2089 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2090 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2091 gain_cache = powf(scale, -gain);
2093 if (coup->coupling_point == AFTER_IMDCT) {
2094 coup->gain[c][0] = gain_cache;
2096 for (g = 0; g < sce->ics.num_window_groups; g++) {
2097 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2098 if (sce->band_type[idx] != ZERO_BT) {
2100 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2108 gain_cache = powf(scale, -t) * s;
2111 coup->gain[c][idx] = gain_cache;
2121 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2123 * @return Returns number of bytes consumed.
2125 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2129 int num_excl_chan = 0;
2132 for (i = 0; i < 7; i++)
2133 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2134 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2136 return num_excl_chan / 7;
2140 * Decode dynamic range information; reference: table 4.52.
2142 * @return Returns number of bytes consumed.
2144 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2148 int drc_num_bands = 1;
2151 /* pce_tag_present? */
2152 if (get_bits1(gb)) {
2153 che_drc->pce_instance_tag = get_bits(gb, 4);
2154 skip_bits(gb, 4); // tag_reserved_bits
2158 /* excluded_chns_present? */
2159 if (get_bits1(gb)) {
2160 n += decode_drc_channel_exclusions(che_drc, gb);
2163 /* drc_bands_present? */
2164 if (get_bits1(gb)) {
2165 che_drc->band_incr = get_bits(gb, 4);
2166 che_drc->interpolation_scheme = get_bits(gb, 4);
2168 drc_num_bands += che_drc->band_incr;
2169 for (i = 0; i < drc_num_bands; i++) {
2170 che_drc->band_top[i] = get_bits(gb, 8);
2175 /* prog_ref_level_present? */
2176 if (get_bits1(gb)) {
2177 che_drc->prog_ref_level = get_bits(gb, 7);
2178 skip_bits1(gb); // prog_ref_level_reserved_bits
2182 for (i = 0; i < drc_num_bands; i++) {
2183 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2184 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2192 * Decode extension data (incomplete); reference: table 4.51.
2194 * @param cnt length of TYPE_FIL syntactic element in bytes
2196 * @return Returns number of bytes consumed
2198 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2199 ChannelElement *che, enum RawDataBlockType elem_type)
2203 switch (get_bits(gb, 4)) { // extension type
2204 case EXT_SBR_DATA_CRC:
2208 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2210 } else if (!ac->oc[1].m4ac.sbr) {
2211 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2212 skip_bits_long(gb, 8 * cnt - 4);
2214 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2215 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2216 skip_bits_long(gb, 8 * cnt - 4);
2218 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2219 ac->oc[1].m4ac.sbr = 1;
2220 ac->oc[1].m4ac.ps = 1;
2221 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2222 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2223 ac->oc[1].status, 1);
2225 ac->oc[1].m4ac.sbr = 1;
2226 ac->avctx->profile = FF_PROFILE_AAC_HE;
2228 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2230 case EXT_DYNAMIC_RANGE:
2231 res = decode_dynamic_range(&ac->che_drc, gb);
2235 case EXT_DATA_ELEMENT:
2237 skip_bits_long(gb, 8 * cnt - 4);
2244 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2246 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2247 * @param coef spectral coefficients
2249 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2250 IndividualChannelStream *ics, int decode)
2252 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2254 int bottom, top, order, start, end, size, inc;
2255 float lpc[TNS_MAX_ORDER];
2256 float tmp[TNS_MAX_ORDER + 1];
2258 for (w = 0; w < ics->num_windows; w++) {
2259 bottom = ics->num_swb;
2260 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2262 bottom = FFMAX(0, top - tns->length[w][filt]);
2263 order = tns->order[w][filt];
2268 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2270 start = ics->swb_offset[FFMIN(bottom, mmm)];
2271 end = ics->swb_offset[FFMIN( top, mmm)];
2272 if ((size = end - start) <= 0)
2274 if (tns->direction[w][filt]) {
2284 for (m = 0; m < size; m++, start += inc)
2285 for (i = 1; i <= FFMIN(m, order); i++)
2286 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2289 for (m = 0; m < size; m++, start += inc) {
2290 tmp[0] = coef[start];
2291 for (i = 1; i <= FFMIN(m, order); i++)
2292 coef[start] += tmp[i] * lpc[i - 1];
2293 for (i = order; i > 0; i--)
2294 tmp[i] = tmp[i - 1];
2302 * Apply windowing and MDCT to obtain the spectral
2303 * coefficient from the predicted sample by LTP.
2305 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2306 float *in, IndividualChannelStream *ics)
2308 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2309 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2310 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2311 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2313 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2314 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2316 memset(in, 0, 448 * sizeof(float));
2317 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2319 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2320 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2322 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2323 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2325 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2329 * Apply the long term prediction
2331 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2333 const LongTermPrediction *ltp = &sce->ics.ltp;
2334 const uint16_t *offsets = sce->ics.swb_offset;
2337 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2338 float *predTime = sce->ret;
2339 float *predFreq = ac->buf_mdct;
2340 int16_t num_samples = 2048;
2342 if (ltp->lag < 1024)
2343 num_samples = ltp->lag + 1024;
2344 for (i = 0; i < num_samples; i++)
2345 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2346 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2348 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2350 if (sce->tns.present)
2351 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2353 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2355 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2356 sce->coeffs[i] += predFreq[i];
2361 * Update the LTP buffer for next frame
2363 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2365 IndividualChannelStream *ics = &sce->ics;
2366 float *saved = sce->saved;
2367 float *saved_ltp = sce->coeffs;
2368 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2369 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2372 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2373 memcpy(saved_ltp, saved, 512 * sizeof(float));
2374 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2375 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2376 for (i = 0; i < 64; i++)
2377 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2378 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2379 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2380 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2381 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2382 for (i = 0; i < 64; i++)
2383 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2384 } else { // LONG_STOP or ONLY_LONG
2385 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2386 for (i = 0; i < 512; i++)
2387 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2390 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2391 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2392 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2396 * Conduct IMDCT and windowing.
2398 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2400 IndividualChannelStream *ics = &sce->ics;
2401 float *in = sce->coeffs;
2402 float *out = sce->ret;
2403 float *saved = sce->saved;
2404 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2405 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2406 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2407 float *buf = ac->buf_mdct;
2408 float *temp = ac->temp;
2412 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2413 for (i = 0; i < 1024; i += 128)
2414 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2416 ac->mdct.imdct_half(&ac->mdct, buf, in);
2418 /* window overlapping
2419 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2420 * and long to short transitions are considered to be short to short
2421 * transitions. This leaves just two cases (long to long and short to short)
2422 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2424 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2425 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2426 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2428 memcpy( out, saved, 448 * sizeof(float));
2430 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2431 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2432 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2433 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2434 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2435 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2436 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2438 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2439 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2444 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2445 memcpy( saved, temp + 64, 64 * sizeof(float));
2446 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2447 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2448 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2449 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2450 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2451 memcpy( saved, buf + 512, 448 * sizeof(float));
2452 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2453 } else { // LONG_STOP or ONLY_LONG
2454 memcpy( saved, buf + 512, 512 * sizeof(float));
2458 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2460 IndividualChannelStream *ics = &sce->ics;
2461 float *in = sce->coeffs;
2462 float *out = sce->ret;
2463 float *saved = sce->saved;
2464 float *buf = ac->buf_mdct;
2467 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2469 // window overlapping
2470 if (ics->use_kb_window[1]) {
2471 // AAC LD uses a low overlap sine window instead of a KBD window
2472 memcpy(out, saved, 192 * sizeof(float));
2473 ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2474 memcpy( out + 320, buf + 64, 192 * sizeof(float));
2476 ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2480 memcpy(saved, buf + 256, 256 * sizeof(float));
2483 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2485 float *in = sce->coeffs;
2486 float *out = sce->ret;
2487 float *saved = sce->saved;
2488 float *buf = ac->buf_mdct;
2490 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2491 const int n2 = n >> 1;
2492 const int n4 = n >> 2;
2493 const float *const window = n == 480 ? ff_aac_eld_window_480 :
2494 ff_aac_eld_window_512;
2496 // Inverse transform, mapped to the conventional IMDCT by
2497 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2498 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2499 // Audio, Language and Image Processing, 2008. ICALIP 2008. International Conference on
2500 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2501 for (i = 0; i < n2; i+=2) {
2503 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2504 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2507 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
2509 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2510 for (i = 0; i < n; i+=2) {
2513 // Like with the regular IMDCT at this point we still have the middle half
2514 // of a transform but with even symmetry on the left and odd symmetry on
2517 // window overlapping
2518 // The spec says to use samples [0..511] but the reference decoder uses
2519 // samples [128..639].
2520 for (i = n4; i < n2; i ++) {
2521 out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2522 saved[ i + n2] * window[i + n - n4] +
2523 -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2524 -saved[2*n + n2 + i] * window[i + 3*n - n4];
2526 for (i = 0; i < n2; i ++) {
2527 out[n4 + i] = buf[i] * window[i + n2 - n4] +
2528 -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2529 -saved[ n + i] * window[i + n2 + 2*n - n4] +
2530 saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2532 for (i = 0; i < n4; i ++) {
2533 out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2534 -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2535 -saved[ n + n2 + i] * window[i + 3*n - n4];
2539 memmove(saved + n, saved, 2 * n * sizeof(float));
2540 memcpy( saved, buf, n * sizeof(float));
2544 * Apply dependent channel coupling (applied before IMDCT).
2546 * @param index index into coupling gain array
2548 static void apply_dependent_coupling(AACContext *ac,
2549 SingleChannelElement *target,
2550 ChannelElement *cce, int index)
2552 IndividualChannelStream *ics = &cce->ch[0].ics;
2553 const uint16_t *offsets = ics->swb_offset;
2554 float *dest = target->coeffs;
2555 const float *src = cce->ch[0].coeffs;
2556 int g, i, group, k, idx = 0;
2557 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2558 av_log(ac->avctx, AV_LOG_ERROR,
2559 "Dependent coupling is not supported together with LTP\n");
2562 for (g = 0; g < ics->num_window_groups; g++) {
2563 for (i = 0; i < ics->max_sfb; i++, idx++) {
2564 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2565 const float gain = cce->coup.gain[index][idx];
2566 for (group = 0; group < ics->group_len[g]; group++) {
2567 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2569 dest[group * 128 + k] += gain * src[group * 128 + k];
2574 dest += ics->group_len[g] * 128;
2575 src += ics->group_len[g] * 128;
2580 * Apply independent channel coupling (applied after IMDCT).
2582 * @param index index into coupling gain array
2584 static void apply_independent_coupling(AACContext *ac,
2585 SingleChannelElement *target,
2586 ChannelElement *cce, int index)
2589 const float gain = cce->coup.gain[index][0];
2590 const float *src = cce->ch[0].ret;
2591 float *dest = target->ret;
2592 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2594 for (i = 0; i < len; i++)
2595 dest[i] += gain * src[i];
2599 * channel coupling transformation interface
2601 * @param apply_coupling_method pointer to (in)dependent coupling function
2603 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2604 enum RawDataBlockType type, int elem_id,
2605 enum CouplingPoint coupling_point,
2606 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2610 for (i = 0; i < MAX_ELEM_ID; i++) {
2611 ChannelElement *cce = ac->che[TYPE_CCE][i];
2614 if (cce && cce->coup.coupling_point == coupling_point) {
2615 ChannelCoupling *coup = &cce->coup;
2617 for (c = 0; c <= coup->num_coupled; c++) {
2618 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2619 if (coup->ch_select[c] != 1) {
2620 apply_coupling_method(ac, &cc->ch[0], cce, index);
2621 if (coup->ch_select[c] != 0)
2624 if (coup->ch_select[c] != 2)
2625 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2627 index += 1 + (coup->ch_select[c] == 3);
2634 * Convert spectral data to float samples, applying all supported tools as appropriate.
2636 static void spectral_to_sample(AACContext *ac)
2639 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2640 switch (ac->oc[1].m4ac.object_type) {
2642 imdct_and_window = imdct_and_windowing_ld;
2644 case AOT_ER_AAC_ELD:
2645 imdct_and_window = imdct_and_windowing_eld;
2648 imdct_and_window = imdct_and_windowing;
2650 for (type = 3; type >= 0; type--) {
2651 for (i = 0; i < MAX_ELEM_ID; i++) {
2652 ChannelElement *che = ac->che[type][i];
2654 if (type <= TYPE_CPE)
2655 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2656 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2657 if (che->ch[0].ics.predictor_present) {
2658 if (che->ch[0].ics.ltp.present)
2659 apply_ltp(ac, &che->ch[0]);
2660 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2661 apply_ltp(ac, &che->ch[1]);
2664 if (che->ch[0].tns.present)
2665 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2666 if (che->ch[1].tns.present)
2667 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2668 if (type <= TYPE_CPE)
2669 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2670 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2671 imdct_and_window(ac, &che->ch[0]);
2672 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2673 update_ltp(ac, &che->ch[0]);
2674 if (type == TYPE_CPE) {
2675 imdct_and_window(ac, &che->ch[1]);
2676 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2677 update_ltp(ac, &che->ch[1]);
2679 if (ac->oc[1].m4ac.sbr > 0) {
2680 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2683 if (type <= TYPE_CCE)
2684 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2690 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2693 AACADTSHeaderInfo hdr_info;
2694 uint8_t layout_map[MAX_ELEM_ID*4][3];
2695 int layout_map_tags, ret;
2697 size = avpriv_aac_parse_header(gb, &hdr_info);
2699 if (hdr_info.num_aac_frames != 1) {
2700 avpriv_report_missing_feature(ac->avctx,
2701 "More than one AAC RDB per ADTS frame");
2702 return AVERROR_PATCHWELCOME;
2704 push_output_configuration(ac);
2705 if (hdr_info.chan_config) {
2706 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2707 if ((ret = set_default_channel_config(ac->avctx,
2710 hdr_info.chan_config)) < 0)
2712 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2713 FFMAX(ac->oc[1].status,
2714 OC_TRIAL_FRAME), 0)) < 0)
2717 ac->oc[1].m4ac.chan_config = 0;
2719 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2720 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2721 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2722 ac->oc[1].m4ac.frame_length_short = 0;
2723 if (ac->oc[0].status != OC_LOCKED ||
2724 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2725 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2726 ac->oc[1].m4ac.sbr = -1;
2727 ac->oc[1].m4ac.ps = -1;
2729 if (!hdr_info.crc_absent)
2735 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2736 int *got_frame_ptr, GetBitContext *gb)
2738 AACContext *ac = avctx->priv_data;
2739 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
2740 ChannelElement *che;
2742 int samples = m4ac->frame_length_short ? 960 : 1024;
2743 int chan_config = m4ac->chan_config;
2744 int aot = m4ac->object_type;
2746 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2751 if ((err = frame_configure_elements(avctx)) < 0)
2754 // The FF_PROFILE_AAC_* defines are all object_type - 1
2755 // This may lead to an undefined profile being signaled
2756 ac->avctx->profile = aot - 1;
2758 ac->tags_mapped = 0;
2760 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
2761 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2763 return AVERROR_INVALIDDATA;
2765 for (i = 0; i < tags_per_config[chan_config]; i++) {
2766 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2767 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2768 if (!(che=get_che(ac, elem_type, elem_id))) {
2769 av_log(ac->avctx, AV_LOG_ERROR,
2770 "channel element %d.%d is not allocated\n",
2771 elem_type, elem_id);
2772 return AVERROR_INVALIDDATA;
2774 if (aot != AOT_ER_AAC_ELD)
2776 switch (elem_type) {
2778 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2781 err = decode_cpe(ac, gb, che);
2784 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2791 spectral_to_sample(ac);
2793 ac->frame->nb_samples = samples;
2794 ac->frame->sample_rate = avctx->sample_rate;
2797 skip_bits_long(gb, get_bits_left(gb));
2801 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2802 int *got_frame_ptr, GetBitContext *gb)
2804 AACContext *ac = avctx->priv_data;
2805 ChannelElement *che = NULL, *che_prev = NULL;
2806 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2808 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2812 if (show_bits(gb, 12) == 0xfff) {
2813 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2814 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2817 if (ac->oc[1].m4ac.sampling_index > 12) {
2818 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2819 err = AVERROR_INVALIDDATA;
2824 if (avctx->channels)
2825 if ((err = frame_configure_elements(avctx)) < 0)
2828 // The FF_PROFILE_AAC_* defines are all object_type - 1
2829 // This may lead to an undefined profile being signaled
2830 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2832 ac->tags_mapped = 0;
2834 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2835 elem_id = get_bits(gb, 4);
2837 if (!avctx->channels && elem_type != TYPE_PCE)
2840 if (elem_type < TYPE_DSE) {
2841 if (!(che=get_che(ac, elem_type, elem_id))) {
2842 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2843 elem_type, elem_id);
2844 err = AVERROR_INVALIDDATA;
2850 switch (elem_type) {
2853 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2858 err = decode_cpe(ac, gb, che);
2863 err = decode_cce(ac, gb, che);
2867 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2872 err = skip_data_stream_element(ac, gb);
2876 uint8_t layout_map[MAX_ELEM_ID*4][3];
2878 push_output_configuration(ac);
2879 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2885 av_log(avctx, AV_LOG_ERROR,
2886 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2887 pop_output_configuration(ac);
2889 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2897 elem_id += get_bits(gb, 8) - 1;
2898 if (get_bits_left(gb) < 8 * elem_id) {
2899 av_log(avctx, AV_LOG_ERROR, overread_err);
2900 err = AVERROR_INVALIDDATA;
2904 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2905 err = 0; /* FIXME */
2909 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2914 elem_type_prev = elem_type;
2919 if (get_bits_left(gb) < 3) {
2920 av_log(avctx, AV_LOG_ERROR, overread_err);
2921 err = AVERROR_INVALIDDATA;
2926 if (!avctx->channels) {
2931 spectral_to_sample(ac);
2933 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2934 samples <<= multiplier;
2936 if (ac->oc[1].status && audio_found) {
2937 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2938 avctx->frame_size = samples;
2939 ac->oc[1].status = OC_LOCKED;
2943 ac->frame->nb_samples = samples;
2944 ac->frame->sample_rate = avctx->sample_rate;
2946 *got_frame_ptr = !!samples;
2950 pop_output_configuration(ac);
2954 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2955 int *got_frame_ptr, AVPacket *avpkt)
2957 AACContext *ac = avctx->priv_data;
2958 const uint8_t *buf = avpkt->data;
2959 int buf_size = avpkt->size;
2964 int new_extradata_size;
2965 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2966 AV_PKT_DATA_NEW_EXTRADATA,
2967 &new_extradata_size);
2969 if (new_extradata) {
2970 av_free(avctx->extradata);
2971 avctx->extradata = av_mallocz(new_extradata_size +
2972 FF_INPUT_BUFFER_PADDING_SIZE);
2973 if (!avctx->extradata)
2974 return AVERROR(ENOMEM);
2975 avctx->extradata_size = new_extradata_size;
2976 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2977 push_output_configuration(ac);
2978 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2980 avctx->extradata_size*8, 1) < 0) {
2981 pop_output_configuration(ac);
2982 return AVERROR_INVALIDDATA;
2986 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
2989 switch (ac->oc[1].m4ac.object_type) {
2991 case AOT_ER_AAC_LTP:
2993 case AOT_ER_AAC_ELD:
2994 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
2997 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb);
3002 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3003 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3004 if (buf[buf_offset])
3007 return buf_size > buf_offset ? buf_consumed : buf_size;
3010 static av_cold int aac_decode_close(AVCodecContext *avctx)
3012 AACContext *ac = avctx->priv_data;
3015 for (i = 0; i < MAX_ELEM_ID; i++) {
3016 for (type = 0; type < 4; type++) {
3017 if (ac->che[type][i])
3018 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3019 av_freep(&ac->che[type][i]);
3023 ff_mdct_end(&ac->mdct);
3024 ff_mdct_end(&ac->mdct_small);
3025 ff_mdct_end(&ac->mdct_ld);
3026 ff_mdct_end(&ac->mdct_ltp);
3027 ff_imdct15_uninit(&ac->mdct480);
3032 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
3034 struct LATMContext {
3035 AACContext aac_ctx; ///< containing AACContext
3036 int initialized; ///< initilized after a valid extradata was seen
3039 int audio_mux_version_A; ///< LATM syntax version
3040 int frame_length_type; ///< 0/1 variable/fixed frame length
3041 int frame_length; ///< frame length for fixed frame length
3044 static inline uint32_t latm_get_value(GetBitContext *b)
3046 int length = get_bits(b, 2);
3048 return get_bits_long(b, (length+1)*8);
3051 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
3052 GetBitContext *gb, int asclen)
3054 AACContext *ac = &latmctx->aac_ctx;
3055 AVCodecContext *avctx = ac->avctx;
3056 MPEG4AudioConfig m4ac = { 0 };
3057 int config_start_bit = get_bits_count(gb);
3058 int sync_extension = 0;
3059 int bits_consumed, esize;
3063 asclen = FFMIN(asclen, get_bits_left(gb));
3065 asclen = get_bits_left(gb);
3067 if (config_start_bit % 8) {
3068 avpriv_request_sample(latmctx->aac_ctx.avctx,
3069 "Non-byte-aligned audio-specific config");
3070 return AVERROR_PATCHWELCOME;
3073 return AVERROR_INVALIDDATA;
3074 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3075 gb->buffer + (config_start_bit / 8),
3076 asclen, sync_extension);
3078 if (bits_consumed < 0)
3079 return AVERROR_INVALIDDATA;
3081 if (!latmctx->initialized ||
3082 ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3083 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3085 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3086 latmctx->initialized = 0;
3088 esize = (bits_consumed+7) / 8;
3090 if (avctx->extradata_size < esize) {
3091 av_free(avctx->extradata);
3092 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
3093 if (!avctx->extradata)
3094 return AVERROR(ENOMEM);
3097 avctx->extradata_size = esize;
3098 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3099 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3101 skip_bits_long(gb, bits_consumed);
3103 return bits_consumed;
3106 static int read_stream_mux_config(struct LATMContext *latmctx,
3109 int ret, audio_mux_version = get_bits(gb, 1);
3111 latmctx->audio_mux_version_A = 0;
3112 if (audio_mux_version)
3113 latmctx->audio_mux_version_A = get_bits(gb, 1);
3115 if (!latmctx->audio_mux_version_A) {
3117 if (audio_mux_version)
3118 latm_get_value(gb); // taraFullness
3120 skip_bits(gb, 1); // allStreamSameTimeFraming
3121 skip_bits(gb, 6); // numSubFrames
3123 if (get_bits(gb, 4)) { // numPrograms
3124 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3125 return AVERROR_PATCHWELCOME;
3128 // for each program (which there is only on in DVB)
3130 // for each layer (which there is only on in DVB)
3131 if (get_bits(gb, 3)) { // numLayer
3132 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3133 return AVERROR_PATCHWELCOME;
3136 // for all but first stream: use_same_config = get_bits(gb, 1);
3137 if (!audio_mux_version) {
3138 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3141 int ascLen = latm_get_value(gb);
3142 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3145 skip_bits_long(gb, ascLen);
3148 latmctx->frame_length_type = get_bits(gb, 3);
3149 switch (latmctx->frame_length_type) {
3151 skip_bits(gb, 8); // latmBufferFullness
3154 latmctx->frame_length = get_bits(gb, 9);
3159 skip_bits(gb, 6); // CELP frame length table index
3163 skip_bits(gb, 1); // HVXC frame length table index
3167 if (get_bits(gb, 1)) { // other data
3168 if (audio_mux_version) {
3169 latm_get_value(gb); // other_data_bits
3173 esc = get_bits(gb, 1);
3179 if (get_bits(gb, 1)) // crc present
3180 skip_bits(gb, 8); // config_crc
3186 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3190 if (ctx->frame_length_type == 0) {
3191 int mux_slot_length = 0;
3193 tmp = get_bits(gb, 8);
3194 mux_slot_length += tmp;
3195 } while (tmp == 255);
3196 return mux_slot_length;
3197 } else if (ctx->frame_length_type == 1) {
3198 return ctx->frame_length;
3199 } else if (ctx->frame_length_type == 3 ||
3200 ctx->frame_length_type == 5 ||
3201 ctx->frame_length_type == 7) {
3202 skip_bits(gb, 2); // mux_slot_length_coded
3207 static int read_audio_mux_element(struct LATMContext *latmctx,
3211 uint8_t use_same_mux = get_bits(gb, 1);
3212 if (!use_same_mux) {
3213 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3215 } else if (!latmctx->aac_ctx.avctx->extradata) {
3216 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3217 "no decoder config found\n");
3218 return AVERROR(EAGAIN);
3220 if (latmctx->audio_mux_version_A == 0) {
3221 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3222 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3223 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3224 return AVERROR_INVALIDDATA;
3225 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3226 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3227 "frame length mismatch %d << %d\n",
3228 mux_slot_length_bytes * 8, get_bits_left(gb));
3229 return AVERROR_INVALIDDATA;
3236 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3237 int *got_frame_ptr, AVPacket *avpkt)
3239 struct LATMContext *latmctx = avctx->priv_data;
3243 if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
3246 // check for LOAS sync word
3247 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3248 return AVERROR_INVALIDDATA;
3250 muxlength = get_bits(&gb, 13) + 3;
3251 // not enough data, the parser should have sorted this
3252 if (muxlength > avpkt->size)
3253 return AVERROR_INVALIDDATA;
3255 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3258 if (!latmctx->initialized) {
3259 if (!avctx->extradata) {
3263 push_output_configuration(&latmctx->aac_ctx);
3264 if ((err = decode_audio_specific_config(
3265 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3266 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3267 pop_output_configuration(&latmctx->aac_ctx);
3270 latmctx->initialized = 1;
3274 if (show_bits(&gb, 12) == 0xfff) {
3275 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3276 "ADTS header detected, probably as result of configuration "
3278 return AVERROR_INVALIDDATA;
3281 switch (latmctx->aac_ctx.oc[1].m4ac.object_type) {
3283 case AOT_ER_AAC_LTP:
3285 case AOT_ER_AAC_ELD:
3286 err = aac_decode_er_frame(avctx, out, got_frame_ptr, &gb);
3289 err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb);
3297 static av_cold int latm_decode_init(AVCodecContext *avctx)
3299 struct LATMContext *latmctx = avctx->priv_data;
3300 int ret = aac_decode_init(avctx);
3302 if (avctx->extradata_size > 0)
3303 latmctx->initialized = !ret;
3309 AVCodec ff_aac_decoder = {
3311 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3312 .type = AVMEDIA_TYPE_AUDIO,
3313 .id = AV_CODEC_ID_AAC,
3314 .priv_data_size = sizeof(AACContext),
3315 .init = aac_decode_init,
3316 .close = aac_decode_close,
3317 .decode = aac_decode_frame,
3318 .sample_fmts = (const enum AVSampleFormat[]) {
3319 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3321 .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
3322 .channel_layouts = aac_channel_layout,
3326 Note: This decoder filter is intended to decode LATM streams transferred
3327 in MPEG transport streams which only contain one program.
3328 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3330 AVCodec ff_aac_latm_decoder = {
3332 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3333 .type = AVMEDIA_TYPE_AUDIO,
3334 .id = AV_CODEC_ID_AAC_LATM,
3335 .priv_data_size = sizeof(struct LATMContext),
3336 .init = latm_decode_init,
3337 .close = aac_decode_close,
3338 .decode = latm_decode_frame,
3339 .sample_fmts = (const enum AVSampleFormat[]) {
3340 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3342 .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
3343 .channel_layouts = aac_channel_layout,