3 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
7 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8 * Copyright (c) 2010 Janne Grunau <janne-libav@jannau.net>
10 * This file is part of FFmpeg.
12 * FFmpeg is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * FFmpeg is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with FFmpeg; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 * @author Oded Shimon ( ods15 ods15 dyndns org )
31 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
38 * N (code in SoC repo) gain control
40 * Y window shapes - standard
41 * N window shapes - Low Delay
42 * Y filterbank - standard
43 * N (code in SoC repo) filterbank - Scalable Sample Rate
44 * Y Temporal Noise Shaping
45 * Y Long Term Prediction
48 * Y frequency domain prediction
49 * Y Perceptual Noise Substitution
51 * N Scalable Inverse AAC Quantization
52 * N Frequency Selective Switch
54 * Y quantization & coding - AAC
55 * N quantization & coding - TwinVQ
56 * N quantization & coding - BSAC
57 * N AAC Error Resilience tools
58 * N Error Resilience payload syntax
59 * N Error Protection tool
61 * N Silence Compression
64 * N Structured Audio tools
65 * N Structured Audio Sample Bank Format
67 * N Harmonic and Individual Lines plus Noise
68 * N Text-To-Speech Interface
69 * Y Spectral Band Replication
70 * Y (not in this code) Layer-1
71 * Y (not in this code) Layer-2
72 * Y (not in this code) Layer-3
73 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
75 * N Direct Stream Transfer
77 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
82 #include "libavutil/float_dsp.h"
83 #include "libavutil/opt.h"
88 #include "fmtconvert.h"
95 #include "aacdectab.h"
96 #include "cbrt_tablegen.h"
99 #include "mpeg4audio.h"
100 #include "aacadtsdec.h"
101 #include "libavutil/intfloat.h"
109 # include "arm/aac.h"
111 # include "mips/aacdec_mips.h"
114 static VLC vlc_scalefactors;
115 static VLC vlc_spectral[11];
117 static int output_configure(AACContext *ac,
118 uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
119 enum OCStatus oc_type, int get_new_frame);
121 #define overread_err "Input buffer exhausted before END element found\n"
123 static int count_channels(uint8_t (*layout)[3], int tags)
126 for (i = 0; i < tags; i++) {
127 int syn_ele = layout[i][0];
128 int pos = layout[i][2];
129 sum += (1 + (syn_ele == TYPE_CPE)) *
130 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
136 * Check for the channel element in the current channel position configuration.
137 * If it exists, make sure the appropriate element is allocated and map the
138 * channel order to match the internal FFmpeg channel layout.
140 * @param che_pos current channel position configuration
141 * @param type channel element type
142 * @param id channel element id
143 * @param channels count of the number of channels in the configuration
145 * @return Returns error status. 0 - OK, !0 - error
147 static av_cold int che_configure(AACContext *ac,
148 enum ChannelPosition che_pos,
149 int type, int id, int *channels)
151 if (*channels >= MAX_CHANNELS)
152 return AVERROR_INVALIDDATA;
154 if (!ac->che[type][id]) {
155 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
156 return AVERROR(ENOMEM);
157 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
159 if (type != TYPE_CCE) {
160 if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
161 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
162 return AVERROR_INVALIDDATA;
164 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
165 if (type == TYPE_CPE ||
166 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
167 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
171 if (ac->che[type][id])
172 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
173 av_freep(&ac->che[type][id]);
178 static int frame_configure_elements(AVCodecContext *avctx)
180 AACContext *ac = avctx->priv_data;
181 int type, id, ch, ret;
183 /* set channel pointers to internal buffers by default */
184 for (type = 0; type < 4; type++) {
185 for (id = 0; id < MAX_ELEM_ID; id++) {
186 ChannelElement *che = ac->che[type][id];
188 che->ch[0].ret = che->ch[0].ret_buf;
189 che->ch[1].ret = che->ch[1].ret_buf;
194 /* get output buffer */
195 av_frame_unref(ac->frame);
196 ac->frame->nb_samples = 2048;
197 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
200 /* map output channel pointers to AVFrame data */
201 for (ch = 0; ch < avctx->channels; ch++) {
202 if (ac->output_element[ch])
203 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
209 struct elem_to_channel {
210 uint64_t av_position;
213 uint8_t aac_position;
216 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
217 uint8_t (*layout_map)[3], int offset, uint64_t left,
218 uint64_t right, int pos)
220 if (layout_map[offset][0] == TYPE_CPE) {
221 e2c_vec[offset] = (struct elem_to_channel) {
222 .av_position = left | right,
224 .elem_id = layout_map[offset][1],
229 e2c_vec[offset] = (struct elem_to_channel) {
232 .elem_id = layout_map[offset][1],
235 e2c_vec[offset + 1] = (struct elem_to_channel) {
236 .av_position = right,
238 .elem_id = layout_map[offset + 1][1],
245 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
248 int num_pos_channels = 0;
252 for (i = *current; i < tags; i++) {
253 if (layout_map[i][2] != pos)
255 if (layout_map[i][0] == TYPE_CPE) {
257 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
263 num_pos_channels += 2;
271 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
274 return num_pos_channels;
277 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
279 int i, n, total_non_cc_elements;
280 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
281 int num_front_channels, num_side_channels, num_back_channels;
284 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
289 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
290 if (num_front_channels < 0)
293 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
294 if (num_side_channels < 0)
297 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
298 if (num_back_channels < 0)
302 if (num_front_channels & 1) {
303 e2c_vec[i] = (struct elem_to_channel) {
304 .av_position = AV_CH_FRONT_CENTER,
306 .elem_id = layout_map[i][1],
307 .aac_position = AAC_CHANNEL_FRONT
310 num_front_channels--;
312 if (num_front_channels >= 4) {
313 i += assign_pair(e2c_vec, layout_map, i,
314 AV_CH_FRONT_LEFT_OF_CENTER,
315 AV_CH_FRONT_RIGHT_OF_CENTER,
317 num_front_channels -= 2;
319 if (num_front_channels >= 2) {
320 i += assign_pair(e2c_vec, layout_map, i,
324 num_front_channels -= 2;
326 while (num_front_channels >= 2) {
327 i += assign_pair(e2c_vec, layout_map, i,
331 num_front_channels -= 2;
334 if (num_side_channels >= 2) {
335 i += assign_pair(e2c_vec, layout_map, i,
339 num_side_channels -= 2;
341 while (num_side_channels >= 2) {
342 i += assign_pair(e2c_vec, layout_map, i,
346 num_side_channels -= 2;
349 while (num_back_channels >= 4) {
350 i += assign_pair(e2c_vec, layout_map, i,
354 num_back_channels -= 2;
356 if (num_back_channels >= 2) {
357 i += assign_pair(e2c_vec, layout_map, i,
361 num_back_channels -= 2;
363 if (num_back_channels) {
364 e2c_vec[i] = (struct elem_to_channel) {
365 .av_position = AV_CH_BACK_CENTER,
367 .elem_id = layout_map[i][1],
368 .aac_position = AAC_CHANNEL_BACK
374 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
375 e2c_vec[i] = (struct elem_to_channel) {
376 .av_position = AV_CH_LOW_FREQUENCY,
378 .elem_id = layout_map[i][1],
379 .aac_position = AAC_CHANNEL_LFE
383 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
384 e2c_vec[i] = (struct elem_to_channel) {
385 .av_position = UINT64_MAX,
387 .elem_id = layout_map[i][1],
388 .aac_position = AAC_CHANNEL_LFE
393 // Must choose a stable sort
394 total_non_cc_elements = n = i;
397 for (i = 1; i < n; i++)
398 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
399 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
406 for (i = 0; i < total_non_cc_elements; i++) {
407 layout_map[i][0] = e2c_vec[i].syn_ele;
408 layout_map[i][1] = e2c_vec[i].elem_id;
409 layout_map[i][2] = e2c_vec[i].aac_position;
410 if (e2c_vec[i].av_position != UINT64_MAX) {
411 layout |= e2c_vec[i].av_position;
419 * Save current output configuration if and only if it has been locked.
421 static void push_output_configuration(AACContext *ac) {
422 if (ac->oc[1].status == OC_LOCKED) {
423 ac->oc[0] = ac->oc[1];
425 ac->oc[1].status = OC_NONE;
429 * Restore the previous output configuration if and only if the current
430 * configuration is unlocked.
432 static void pop_output_configuration(AACContext *ac) {
433 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
434 ac->oc[1] = ac->oc[0];
435 ac->avctx->channels = ac->oc[1].channels;
436 ac->avctx->channel_layout = ac->oc[1].channel_layout;
437 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
438 ac->oc[1].status, 0);
443 * Configure output channel order based on the current program
444 * configuration element.
446 * @return Returns error status. 0 - OK, !0 - error
448 static int output_configure(AACContext *ac,
449 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
450 enum OCStatus oc_type, int get_new_frame)
452 AVCodecContext *avctx = ac->avctx;
453 int i, channels = 0, ret;
456 if (ac->oc[1].layout_map != layout_map) {
457 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
458 ac->oc[1].layout_map_tags = tags;
461 // Try to sniff a reasonable channel order, otherwise output the
462 // channels in the order the PCE declared them.
463 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
464 layout = sniff_channel_order(layout_map, tags);
465 for (i = 0; i < tags; i++) {
466 int type = layout_map[i][0];
467 int id = layout_map[i][1];
468 int position = layout_map[i][2];
469 // Allocate or free elements depending on if they are in the
470 // current program configuration.
471 ret = che_configure(ac, position, type, id, &channels);
475 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
476 if (layout == AV_CH_FRONT_CENTER) {
477 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
483 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
484 if (layout) avctx->channel_layout = layout;
485 ac->oc[1].channel_layout = layout;
486 avctx->channels = ac->oc[1].channels = channels;
487 ac->oc[1].status = oc_type;
490 if ((ret = frame_configure_elements(ac->avctx)) < 0)
497 static void flush(AVCodecContext *avctx)
499 AACContext *ac= avctx->priv_data;
502 for (type = 3; type >= 0; type--) {
503 for (i = 0; i < MAX_ELEM_ID; i++) {
504 ChannelElement *che = ac->che[type][i];
506 for (j = 0; j <= 1; j++) {
507 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
515 * Set up channel positions based on a default channel configuration
516 * as specified in table 1.17.
518 * @return Returns error status. 0 - OK, !0 - error
520 static int set_default_channel_config(AVCodecContext *avctx,
521 uint8_t (*layout_map)[3],
525 if (channel_config < 1 || channel_config > 7) {
526 av_log(avctx, AV_LOG_ERROR,
527 "invalid default channel configuration (%d)\n",
531 *tags = tags_per_config[channel_config];
532 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
533 *tags * sizeof(*layout_map));
537 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
539 /* For PCE based channel configurations map the channels solely based
541 if (!ac->oc[1].m4ac.chan_config) {
542 return ac->tag_che_map[type][elem_id];
544 // Allow single CPE stereo files to be signalled with mono configuration.
545 if (!ac->tags_mapped && type == TYPE_CPE &&
546 ac->oc[1].m4ac.chan_config == 1) {
547 uint8_t layout_map[MAX_ELEM_ID*4][3];
549 push_output_configuration(ac);
551 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
553 if (set_default_channel_config(ac->avctx, layout_map,
554 &layout_map_tags, 2) < 0)
556 if (output_configure(ac, layout_map, layout_map_tags,
557 OC_TRIAL_FRAME, 1) < 0)
560 ac->oc[1].m4ac.chan_config = 2;
561 ac->oc[1].m4ac.ps = 0;
564 if (!ac->tags_mapped && type == TYPE_SCE &&
565 ac->oc[1].m4ac.chan_config == 2) {
566 uint8_t layout_map[MAX_ELEM_ID * 4][3];
568 push_output_configuration(ac);
570 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
572 if (set_default_channel_config(ac->avctx, layout_map,
573 &layout_map_tags, 1) < 0)
575 if (output_configure(ac, layout_map, layout_map_tags,
576 OC_TRIAL_FRAME, 1) < 0)
579 ac->oc[1].m4ac.chan_config = 1;
580 if (ac->oc[1].m4ac.sbr)
581 ac->oc[1].m4ac.ps = -1;
583 /* For indexed channel configurations map the channels solely based
585 switch (ac->oc[1].m4ac.chan_config) {
587 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
589 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
592 /* Some streams incorrectly code 5.1 audio as
593 * SCE[0] CPE[0] CPE[1] SCE[1]
595 * SCE[0] CPE[0] CPE[1] LFE[0].
596 * If we seem to have encountered such a stream, transfer
597 * the LFE[0] element to the SCE[1]'s mapping */
598 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
600 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
603 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
605 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
608 if (ac->tags_mapped == 2 &&
609 ac->oc[1].m4ac.chan_config == 4 &&
612 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
616 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
619 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
620 } else if (ac->oc[1].m4ac.chan_config == 2) {
624 if (!ac->tags_mapped && type == TYPE_SCE) {
626 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
634 * Decode an array of 4 bit element IDs, optionally interleaved with a
635 * stereo/mono switching bit.
637 * @param type speaker type/position for these channels
639 static void decode_channel_map(uint8_t layout_map[][3],
640 enum ChannelPosition type,
641 GetBitContext *gb, int n)
644 enum RawDataBlockType syn_ele;
646 case AAC_CHANNEL_FRONT:
647 case AAC_CHANNEL_BACK:
648 case AAC_CHANNEL_SIDE:
649 syn_ele = get_bits1(gb);
655 case AAC_CHANNEL_LFE:
661 layout_map[0][0] = syn_ele;
662 layout_map[0][1] = get_bits(gb, 4);
663 layout_map[0][2] = type;
669 * Decode program configuration element; reference: table 4.2.
671 * @return Returns error status. 0 - OK, !0 - error
673 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
674 uint8_t (*layout_map)[3],
677 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
682 skip_bits(gb, 2); // object_type
684 sampling_index = get_bits(gb, 4);
685 if (m4ac->sampling_index != sampling_index)
686 av_log(avctx, AV_LOG_WARNING,
687 "Sample rate index in program config element does not "
688 "match the sample rate index configured by the container.\n");
690 num_front = get_bits(gb, 4);
691 num_side = get_bits(gb, 4);
692 num_back = get_bits(gb, 4);
693 num_lfe = get_bits(gb, 2);
694 num_assoc_data = get_bits(gb, 3);
695 num_cc = get_bits(gb, 4);
698 skip_bits(gb, 4); // mono_mixdown_tag
700 skip_bits(gb, 4); // stereo_mixdown_tag
703 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
705 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
706 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
709 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
711 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
713 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
715 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
718 skip_bits_long(gb, 4 * num_assoc_data);
720 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
725 /* comment field, first byte is length */
726 comment_len = get_bits(gb, 8) * 8;
727 if (get_bits_left(gb) < comment_len) {
728 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
731 skip_bits_long(gb, comment_len);
736 * Decode GA "General Audio" specific configuration; reference: table 4.1.
738 * @param ac pointer to AACContext, may be null
739 * @param avctx pointer to AVCCodecContext, used for logging
741 * @return Returns error status. 0 - OK, !0 - error
743 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
745 MPEG4AudioConfig *m4ac,
748 int extension_flag, ret;
749 uint8_t layout_map[MAX_ELEM_ID*4][3];
752 if (get_bits1(gb)) { // frameLengthFlag
753 avpriv_request_sample(avctx, "960/120 MDCT window");
754 return AVERROR_PATCHWELCOME;
757 if (get_bits1(gb)) // dependsOnCoreCoder
758 skip_bits(gb, 14); // coreCoderDelay
759 extension_flag = get_bits1(gb);
761 if (m4ac->object_type == AOT_AAC_SCALABLE ||
762 m4ac->object_type == AOT_ER_AAC_SCALABLE)
763 skip_bits(gb, 3); // layerNr
765 if (channel_config == 0) {
766 skip_bits(gb, 4); // element_instance_tag
767 tags = decode_pce(avctx, m4ac, layout_map, gb);
771 if ((ret = set_default_channel_config(avctx, layout_map,
772 &tags, channel_config)))
776 if (count_channels(layout_map, tags) > 1) {
778 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
781 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
784 if (extension_flag) {
785 switch (m4ac->object_type) {
787 skip_bits(gb, 5); // numOfSubFrame
788 skip_bits(gb, 11); // layer_length
792 case AOT_ER_AAC_SCALABLE:
794 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
795 * aacScalefactorDataResilienceFlag
796 * aacSpectralDataResilienceFlag
800 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
806 * Decode audio specific configuration; reference: table 1.13.
808 * @param ac pointer to AACContext, may be null
809 * @param avctx pointer to AVCCodecContext, used for logging
810 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
811 * @param data pointer to buffer holding an audio specific config
812 * @param bit_size size of audio specific config or data in bits
813 * @param sync_extension look for an appended sync extension
815 * @return Returns error status or number of consumed bits. <0 - error
817 static int decode_audio_specific_config(AACContext *ac,
818 AVCodecContext *avctx,
819 MPEG4AudioConfig *m4ac,
820 const uint8_t *data, int bit_size,
827 av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
828 for (i = 0; i < bit_size >> 3; i++)
829 av_dlog(avctx, "%02x ", data[i]);
830 av_dlog(avctx, "\n");
832 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
835 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
836 sync_extension)) < 0)
838 if (m4ac->sampling_index > 12) {
839 av_log(avctx, AV_LOG_ERROR,
840 "invalid sampling rate index %d\n",
841 m4ac->sampling_index);
845 skip_bits_long(&gb, i);
847 switch (m4ac->object_type) {
851 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
855 av_log(avctx, AV_LOG_ERROR,
856 "Audio object type %s%d is not supported.\n",
857 m4ac->sbr == 1 ? "SBR+" : "",
863 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
864 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
865 m4ac->sample_rate, m4ac->sbr,
868 return get_bits_count(&gb);
872 * linear congruential pseudorandom number generator
874 * @param previous_val pointer to the current state of the generator
876 * @return Returns a 32-bit pseudorandom integer
878 static av_always_inline int lcg_random(unsigned previous_val)
880 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
884 static av_always_inline void reset_predict_state(PredictorState *ps)
894 static void reset_all_predictors(PredictorState *ps)
897 for (i = 0; i < MAX_PREDICTORS; i++)
898 reset_predict_state(&ps[i]);
901 static int sample_rate_idx (int rate)
903 if (92017 <= rate) return 0;
904 else if (75132 <= rate) return 1;
905 else if (55426 <= rate) return 2;
906 else if (46009 <= rate) return 3;
907 else if (37566 <= rate) return 4;
908 else if (27713 <= rate) return 5;
909 else if (23004 <= rate) return 6;
910 else if (18783 <= rate) return 7;
911 else if (13856 <= rate) return 8;
912 else if (11502 <= rate) return 9;
913 else if (9391 <= rate) return 10;
917 static void reset_predictor_group(PredictorState *ps, int group_num)
920 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
921 reset_predict_state(&ps[i]);
924 #define AAC_INIT_VLC_STATIC(num, size) \
925 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
926 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
927 sizeof(ff_aac_spectral_bits[num][0]), \
928 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
929 sizeof(ff_aac_spectral_codes[num][0]), \
932 static void aacdec_init(AACContext *ac);
934 static av_cold int aac_decode_init(AVCodecContext *avctx)
936 AACContext *ac = avctx->priv_data;
939 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
943 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
945 if (avctx->extradata_size > 0) {
946 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
948 avctx->extradata_size * 8, 1) < 0)
952 uint8_t layout_map[MAX_ELEM_ID*4][3];
955 sr = sample_rate_idx(avctx->sample_rate);
956 ac->oc[1].m4ac.sampling_index = sr;
957 ac->oc[1].m4ac.channels = avctx->channels;
958 ac->oc[1].m4ac.sbr = -1;
959 ac->oc[1].m4ac.ps = -1;
961 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
962 if (ff_mpeg4audio_channels[i] == avctx->channels)
964 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
967 ac->oc[1].m4ac.chan_config = i;
969 if (ac->oc[1].m4ac.chan_config) {
970 int ret = set_default_channel_config(avctx, layout_map,
971 &layout_map_tags, ac->oc[1].m4ac.chan_config);
973 output_configure(ac, layout_map, layout_map_tags,
975 else if (avctx->err_recognition & AV_EF_EXPLODE)
976 return AVERROR_INVALIDDATA;
980 if (avctx->channels > MAX_CHANNELS) {
981 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
982 return AVERROR_INVALIDDATA;
985 AAC_INIT_VLC_STATIC( 0, 304);
986 AAC_INIT_VLC_STATIC( 1, 270);
987 AAC_INIT_VLC_STATIC( 2, 550);
988 AAC_INIT_VLC_STATIC( 3, 300);
989 AAC_INIT_VLC_STATIC( 4, 328);
990 AAC_INIT_VLC_STATIC( 5, 294);
991 AAC_INIT_VLC_STATIC( 6, 306);
992 AAC_INIT_VLC_STATIC( 7, 268);
993 AAC_INIT_VLC_STATIC( 8, 510);
994 AAC_INIT_VLC_STATIC( 9, 366);
995 AAC_INIT_VLC_STATIC(10, 462);
999 ff_fmt_convert_init(&ac->fmt_conv, avctx);
1000 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
1002 ac->random_state = 0x1f2e3d4c;
1006 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1007 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1008 ff_aac_scalefactor_bits,
1009 sizeof(ff_aac_scalefactor_bits[0]),
1010 sizeof(ff_aac_scalefactor_bits[0]),
1011 ff_aac_scalefactor_code,
1012 sizeof(ff_aac_scalefactor_code[0]),
1013 sizeof(ff_aac_scalefactor_code[0]),
1016 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1017 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1018 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1019 // window initialization
1020 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1021 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1022 ff_init_ff_sine_windows(10);
1023 ff_init_ff_sine_windows( 7);
1031 * Skip data_stream_element; reference: table 4.10.
1033 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1035 int byte_align = get_bits1(gb);
1036 int count = get_bits(gb, 8);
1038 count += get_bits(gb, 8);
1042 if (get_bits_left(gb) < 8 * count) {
1043 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1046 skip_bits_long(gb, 8 * count);
1050 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1054 if (get_bits1(gb)) {
1055 ics->predictor_reset_group = get_bits(gb, 5);
1056 if (ics->predictor_reset_group == 0 ||
1057 ics->predictor_reset_group > 30) {
1058 av_log(ac->avctx, AV_LOG_ERROR,
1059 "Invalid Predictor Reset Group.\n");
1063 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1064 ics->prediction_used[sfb] = get_bits1(gb);
1070 * Decode Long Term Prediction data; reference: table 4.xx.
1072 static void decode_ltp(LongTermPrediction *ltp,
1073 GetBitContext *gb, uint8_t max_sfb)
1077 ltp->lag = get_bits(gb, 11);
1078 ltp->coef = ltp_coef[get_bits(gb, 3)];
1079 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1080 ltp->used[sfb] = get_bits1(gb);
1084 * Decode Individual Channel Stream info; reference: table 4.6.
1086 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1089 if (get_bits1(gb)) {
1090 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1091 return AVERROR_INVALIDDATA;
1093 ics->window_sequence[1] = ics->window_sequence[0];
1094 ics->window_sequence[0] = get_bits(gb, 2);
1095 ics->use_kb_window[1] = ics->use_kb_window[0];
1096 ics->use_kb_window[0] = get_bits1(gb);
1097 ics->num_window_groups = 1;
1098 ics->group_len[0] = 1;
1099 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1101 ics->max_sfb = get_bits(gb, 4);
1102 for (i = 0; i < 7; i++) {
1103 if (get_bits1(gb)) {
1104 ics->group_len[ics->num_window_groups - 1]++;
1106 ics->num_window_groups++;
1107 ics->group_len[ics->num_window_groups - 1] = 1;
1110 ics->num_windows = 8;
1111 ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1112 ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1113 ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1114 ics->predictor_present = 0;
1116 ics->max_sfb = get_bits(gb, 6);
1117 ics->num_windows = 1;
1118 ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1119 ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1120 ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1121 ics->predictor_present = get_bits1(gb);
1122 ics->predictor_reset_group = 0;
1123 if (ics->predictor_present) {
1124 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1125 if (decode_prediction(ac, ics, gb)) {
1128 } else if (ac->oc[1].m4ac.object_type == AOT_AAC_LC) {
1129 av_log(ac->avctx, AV_LOG_ERROR,
1130 "Prediction is not allowed in AAC-LC.\n");
1133 if ((ics->ltp.present = get_bits(gb, 1)))
1134 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1139 if (ics->max_sfb > ics->num_swb) {
1140 av_log(ac->avctx, AV_LOG_ERROR,
1141 "Number of scalefactor bands in group (%d) "
1142 "exceeds limit (%d).\n",
1143 ics->max_sfb, ics->num_swb);
1150 return AVERROR_INVALIDDATA;
1154 * Decode band types (section_data payload); reference: table 4.46.
1156 * @param band_type array of the used band type
1157 * @param band_type_run_end array of the last scalefactor band of a band type run
1159 * @return Returns error status. 0 - OK, !0 - error
1161 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1162 int band_type_run_end[120], GetBitContext *gb,
1163 IndividualChannelStream *ics)
1166 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1167 for (g = 0; g < ics->num_window_groups; g++) {
1169 while (k < ics->max_sfb) {
1170 uint8_t sect_end = k;
1172 int sect_band_type = get_bits(gb, 4);
1173 if (sect_band_type == 12) {
1174 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1178 sect_len_incr = get_bits(gb, bits);
1179 sect_end += sect_len_incr;
1180 if (get_bits_left(gb) < 0) {
1181 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1184 if (sect_end > ics->max_sfb) {
1185 av_log(ac->avctx, AV_LOG_ERROR,
1186 "Number of bands (%d) exceeds limit (%d).\n",
1187 sect_end, ics->max_sfb);
1190 } while (sect_len_incr == (1 << bits) - 1);
1191 for (; k < sect_end; k++) {
1192 band_type [idx] = sect_band_type;
1193 band_type_run_end[idx++] = sect_end;
1201 * Decode scalefactors; reference: table 4.47.
1203 * @param global_gain first scalefactor value as scalefactors are differentially coded
1204 * @param band_type array of the used band type
1205 * @param band_type_run_end array of the last scalefactor band of a band type run
1206 * @param sf array of scalefactors or intensity stereo positions
1208 * @return Returns error status. 0 - OK, !0 - error
1210 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1211 unsigned int global_gain,
1212 IndividualChannelStream *ics,
1213 enum BandType band_type[120],
1214 int band_type_run_end[120])
1217 int offset[3] = { global_gain, global_gain - 90, 0 };
1220 for (g = 0; g < ics->num_window_groups; g++) {
1221 for (i = 0; i < ics->max_sfb;) {
1222 int run_end = band_type_run_end[idx];
1223 if (band_type[idx] == ZERO_BT) {
1224 for (; i < run_end; i++, idx++)
1226 } else if ((band_type[idx] == INTENSITY_BT) ||
1227 (band_type[idx] == INTENSITY_BT2)) {
1228 for (; i < run_end; i++, idx++) {
1229 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1230 clipped_offset = av_clip(offset[2], -155, 100);
1231 if (offset[2] != clipped_offset) {
1232 avpriv_request_sample(ac->avctx,
1233 "If you heard an audible artifact, there may be a bug in the decoder. "
1234 "Clipped intensity stereo position (%d -> %d)",
1235 offset[2], clipped_offset);
1237 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1239 } else if (band_type[idx] == NOISE_BT) {
1240 for (; i < run_end; i++, idx++) {
1241 if (noise_flag-- > 0)
1242 offset[1] += get_bits(gb, 9) - 256;
1244 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1245 clipped_offset = av_clip(offset[1], -100, 155);
1246 if (offset[1] != clipped_offset) {
1247 avpriv_request_sample(ac->avctx,
1248 "If you heard an audible artifact, there may be a bug in the decoder. "
1249 "Clipped noise gain (%d -> %d)",
1250 offset[1], clipped_offset);
1252 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1255 for (; i < run_end; i++, idx++) {
1256 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1257 if (offset[0] > 255U) {
1258 av_log(ac->avctx, AV_LOG_ERROR,
1259 "Scalefactor (%d) out of range.\n", offset[0]);
1262 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1271 * Decode pulse data; reference: table 4.7.
1273 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1274 const uint16_t *swb_offset, int num_swb)
1277 pulse->num_pulse = get_bits(gb, 2) + 1;
1278 pulse_swb = get_bits(gb, 6);
1279 if (pulse_swb >= num_swb)
1281 pulse->pos[0] = swb_offset[pulse_swb];
1282 pulse->pos[0] += get_bits(gb, 5);
1283 if (pulse->pos[0] > 1023)
1285 pulse->amp[0] = get_bits(gb, 4);
1286 for (i = 1; i < pulse->num_pulse; i++) {
1287 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1288 if (pulse->pos[i] > 1023)
1290 pulse->amp[i] = get_bits(gb, 4);
1296 * Decode Temporal Noise Shaping data; reference: table 4.48.
1298 * @return Returns error status. 0 - OK, !0 - error
1300 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1301 GetBitContext *gb, const IndividualChannelStream *ics)
1303 int w, filt, i, coef_len, coef_res, coef_compress;
1304 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1305 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1306 for (w = 0; w < ics->num_windows; w++) {
1307 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1308 coef_res = get_bits1(gb);
1310 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1312 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1314 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1315 av_log(ac->avctx, AV_LOG_ERROR,
1316 "TNS filter order %d is greater than maximum %d.\n",
1317 tns->order[w][filt], tns_max_order);
1318 tns->order[w][filt] = 0;
1321 if (tns->order[w][filt]) {
1322 tns->direction[w][filt] = get_bits1(gb);
1323 coef_compress = get_bits1(gb);
1324 coef_len = coef_res + 3 - coef_compress;
1325 tmp2_idx = 2 * coef_compress + coef_res;
1327 for (i = 0; i < tns->order[w][filt]; i++)
1328 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1337 * Decode Mid/Side data; reference: table 4.54.
1339 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1340 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1341 * [3] reserved for scalable AAC
1343 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1347 if (ms_present == 1) {
1349 idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1351 cpe->ms_mask[idx] = get_bits1(gb);
1352 } else if (ms_present == 2) {
1353 memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1358 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1362 *dst++ = v[idx & 15] * s;
1363 *dst++ = v[idx>>4 & 15] * s;
1369 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1373 *dst++ = v[idx & 3] * s;
1374 *dst++ = v[idx>>2 & 3] * s;
1375 *dst++ = v[idx>>4 & 3] * s;
1376 *dst++ = v[idx>>6 & 3] * s;
1382 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1383 unsigned sign, const float *scale)
1385 union av_intfloat32 s0, s1;
1387 s0.f = s1.f = *scale;
1388 s0.i ^= sign >> 1 << 31;
1391 *dst++ = v[idx & 15] * s0.f;
1392 *dst++ = v[idx>>4 & 15] * s1.f;
1399 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1400 unsigned sign, const float *scale)
1402 unsigned nz = idx >> 12;
1403 union av_intfloat32 s = { .f = *scale };
1404 union av_intfloat32 t;
1406 t.i = s.i ^ (sign & 1U<<31);
1407 *dst++ = v[idx & 3] * t.f;
1409 sign <<= nz & 1; nz >>= 1;
1410 t.i = s.i ^ (sign & 1U<<31);
1411 *dst++ = v[idx>>2 & 3] * t.f;
1413 sign <<= nz & 1; nz >>= 1;
1414 t.i = s.i ^ (sign & 1U<<31);
1415 *dst++ = v[idx>>4 & 3] * t.f;
1418 t.i = s.i ^ (sign & 1U<<31);
1419 *dst++ = v[idx>>6 & 3] * t.f;
1426 * Decode spectral data; reference: table 4.50.
1427 * Dequantize and scale spectral data; reference: 4.6.3.3.
1429 * @param coef array of dequantized, scaled spectral data
1430 * @param sf array of scalefactors or intensity stereo positions
1431 * @param pulse_present set if pulses are present
1432 * @param pulse pointer to pulse data struct
1433 * @param band_type array of the used band type
1435 * @return Returns error status. 0 - OK, !0 - error
1437 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1438 GetBitContext *gb, const float sf[120],
1439 int pulse_present, const Pulse *pulse,
1440 const IndividualChannelStream *ics,
1441 enum BandType band_type[120])
1443 int i, k, g, idx = 0;
1444 const int c = 1024 / ics->num_windows;
1445 const uint16_t *offsets = ics->swb_offset;
1446 float *coef_base = coef;
1448 for (g = 0; g < ics->num_windows; g++)
1449 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1450 sizeof(float) * (c - offsets[ics->max_sfb]));
1452 for (g = 0; g < ics->num_window_groups; g++) {
1453 unsigned g_len = ics->group_len[g];
1455 for (i = 0; i < ics->max_sfb; i++, idx++) {
1456 const unsigned cbt_m1 = band_type[idx] - 1;
1457 float *cfo = coef + offsets[i];
1458 int off_len = offsets[i + 1] - offsets[i];
1461 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1462 for (group = 0; group < g_len; group++, cfo+=128) {
1463 memset(cfo, 0, off_len * sizeof(float));
1465 } else if (cbt_m1 == NOISE_BT - 1) {
1466 for (group = 0; group < g_len; group++, cfo+=128) {
1470 for (k = 0; k < off_len; k++) {
1471 ac->random_state = lcg_random(ac->random_state);
1472 cfo[k] = ac->random_state;
1475 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1476 scale = sf[idx] / sqrtf(band_energy);
1477 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1480 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1481 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1482 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1483 OPEN_READER(re, gb);
1485 switch (cbt_m1 >> 1) {
1487 for (group = 0; group < g_len; group++, cfo+=128) {
1495 UPDATE_CACHE(re, gb);
1496 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1497 cb_idx = cb_vector_idx[code];
1498 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1504 for (group = 0; group < g_len; group++, cfo+=128) {
1514 UPDATE_CACHE(re, gb);
1515 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1516 cb_idx = cb_vector_idx[code];
1517 nnz = cb_idx >> 8 & 15;
1518 bits = nnz ? GET_CACHE(re, gb) : 0;
1519 LAST_SKIP_BITS(re, gb, nnz);
1520 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1526 for (group = 0; group < g_len; group++, cfo+=128) {
1534 UPDATE_CACHE(re, gb);
1535 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1536 cb_idx = cb_vector_idx[code];
1537 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1544 for (group = 0; group < g_len; group++, cfo+=128) {
1554 UPDATE_CACHE(re, gb);
1555 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1556 cb_idx = cb_vector_idx[code];
1557 nnz = cb_idx >> 8 & 15;
1558 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1559 LAST_SKIP_BITS(re, gb, nnz);
1560 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1566 for (group = 0; group < g_len; group++, cfo+=128) {
1568 uint32_t *icf = (uint32_t *) cf;
1578 UPDATE_CACHE(re, gb);
1579 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1587 cb_idx = cb_vector_idx[code];
1590 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1591 LAST_SKIP_BITS(re, gb, nnz);
1593 for (j = 0; j < 2; j++) {
1597 /* The total length of escape_sequence must be < 22 bits according
1598 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1599 UPDATE_CACHE(re, gb);
1600 b = GET_CACHE(re, gb);
1601 b = 31 - av_log2(~b);
1604 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1608 SKIP_BITS(re, gb, b + 1);
1610 n = (1 << b) + SHOW_UBITS(re, gb, b);
1611 LAST_SKIP_BITS(re, gb, b);
1612 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1615 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1616 *icf++ = (bits & 1U<<31) | v;
1623 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1627 CLOSE_READER(re, gb);
1633 if (pulse_present) {
1635 for (i = 0; i < pulse->num_pulse; i++) {
1636 float co = coef_base[ pulse->pos[i] ];
1637 while (offsets[idx + 1] <= pulse->pos[i])
1639 if (band_type[idx] != NOISE_BT && sf[idx]) {
1640 float ico = -pulse->amp[i];
1643 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1645 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1652 static av_always_inline float flt16_round(float pf)
1654 union av_intfloat32 tmp;
1656 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1660 static av_always_inline float flt16_even(float pf)
1662 union av_intfloat32 tmp;
1664 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1668 static av_always_inline float flt16_trunc(float pf)
1670 union av_intfloat32 pun;
1672 pun.i &= 0xFFFF0000U;
1676 static av_always_inline void predict(PredictorState *ps, float *coef,
1679 const float a = 0.953125; // 61.0 / 64
1680 const float alpha = 0.90625; // 29.0 / 32
1684 float r0 = ps->r0, r1 = ps->r1;
1685 float cor0 = ps->cor0, cor1 = ps->cor1;
1686 float var0 = ps->var0, var1 = ps->var1;
1688 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1689 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1691 pv = flt16_round(k1 * r0 + k2 * r1);
1698 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1699 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1700 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1701 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1703 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1704 ps->r0 = flt16_trunc(a * e0);
1708 * Apply AAC-Main style frequency domain prediction.
1710 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1714 if (!sce->ics.predictor_initialized) {
1715 reset_all_predictors(sce->predictor_state);
1716 sce->ics.predictor_initialized = 1;
1719 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1721 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1723 for (k = sce->ics.swb_offset[sfb];
1724 k < sce->ics.swb_offset[sfb + 1];
1726 predict(&sce->predictor_state[k], &sce->coeffs[k],
1727 sce->ics.predictor_present &&
1728 sce->ics.prediction_used[sfb]);
1731 if (sce->ics.predictor_reset_group)
1732 reset_predictor_group(sce->predictor_state,
1733 sce->ics.predictor_reset_group);
1735 reset_all_predictors(sce->predictor_state);
1739 * Decode an individual_channel_stream payload; reference: table 4.44.
1741 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1742 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1744 * @return Returns error status. 0 - OK, !0 - error
1746 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1747 GetBitContext *gb, int common_window, int scale_flag)
1750 TemporalNoiseShaping *tns = &sce->tns;
1751 IndividualChannelStream *ics = &sce->ics;
1752 float *out = sce->coeffs;
1753 int global_gain, pulse_present = 0;
1755 /* This assignment is to silence a GCC warning about the variable being used
1756 * uninitialized when in fact it always is.
1758 pulse.num_pulse = 0;
1760 global_gain = get_bits(gb, 8);
1762 if (!common_window && !scale_flag) {
1763 if (decode_ics_info(ac, ics, gb) < 0)
1764 return AVERROR_INVALIDDATA;
1767 if (decode_band_types(ac, sce->band_type,
1768 sce->band_type_run_end, gb, ics) < 0)
1770 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1771 sce->band_type, sce->band_type_run_end) < 0)
1776 if ((pulse_present = get_bits1(gb))) {
1777 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1778 av_log(ac->avctx, AV_LOG_ERROR,
1779 "Pulse tool not allowed in eight short sequence.\n");
1782 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1783 av_log(ac->avctx, AV_LOG_ERROR,
1784 "Pulse data corrupt or invalid.\n");
1788 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1790 if (get_bits1(gb)) {
1791 avpriv_request_sample(ac->avctx, "SSR");
1792 return AVERROR_PATCHWELCOME;
1796 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1797 &pulse, ics, sce->band_type) < 0)
1800 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1801 apply_prediction(ac, sce);
1807 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1809 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1811 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1812 float *ch0 = cpe->ch[0].coeffs;
1813 float *ch1 = cpe->ch[1].coeffs;
1814 int g, i, group, idx = 0;
1815 const uint16_t *offsets = ics->swb_offset;
1816 for (g = 0; g < ics->num_window_groups; g++) {
1817 for (i = 0; i < ics->max_sfb; i++, idx++) {
1818 if (cpe->ms_mask[idx] &&
1819 cpe->ch[0].band_type[idx] < NOISE_BT &&
1820 cpe->ch[1].band_type[idx] < NOISE_BT) {
1821 for (group = 0; group < ics->group_len[g]; group++) {
1822 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1823 ch1 + group * 128 + offsets[i],
1824 offsets[i+1] - offsets[i]);
1828 ch0 += ics->group_len[g] * 128;
1829 ch1 += ics->group_len[g] * 128;
1834 * intensity stereo decoding; reference: 4.6.8.2.3
1836 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1837 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1838 * [3] reserved for scalable AAC
1840 static void apply_intensity_stereo(AACContext *ac,
1841 ChannelElement *cpe, int ms_present)
1843 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1844 SingleChannelElement *sce1 = &cpe->ch[1];
1845 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1846 const uint16_t *offsets = ics->swb_offset;
1847 int g, group, i, idx = 0;
1850 for (g = 0; g < ics->num_window_groups; g++) {
1851 for (i = 0; i < ics->max_sfb;) {
1852 if (sce1->band_type[idx] == INTENSITY_BT ||
1853 sce1->band_type[idx] == INTENSITY_BT2) {
1854 const int bt_run_end = sce1->band_type_run_end[idx];
1855 for (; i < bt_run_end; i++, idx++) {
1856 c = -1 + 2 * (sce1->band_type[idx] - 14);
1858 c *= 1 - 2 * cpe->ms_mask[idx];
1859 scale = c * sce1->sf[idx];
1860 for (group = 0; group < ics->group_len[g]; group++)
1861 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1862 coef0 + group * 128 + offsets[i],
1864 offsets[i + 1] - offsets[i]);
1867 int bt_run_end = sce1->band_type_run_end[idx];
1868 idx += bt_run_end - i;
1872 coef0 += ics->group_len[g] * 128;
1873 coef1 += ics->group_len[g] * 128;
1878 * Decode a channel_pair_element; reference: table 4.4.
1880 * @return Returns error status. 0 - OK, !0 - error
1882 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1884 int i, ret, common_window, ms_present = 0;
1886 common_window = get_bits1(gb);
1887 if (common_window) {
1888 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1889 return AVERROR_INVALIDDATA;
1890 i = cpe->ch[1].ics.use_kb_window[0];
1891 cpe->ch[1].ics = cpe->ch[0].ics;
1892 cpe->ch[1].ics.use_kb_window[1] = i;
1893 if (cpe->ch[1].ics.predictor_present &&
1894 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1895 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1896 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1897 ms_present = get_bits(gb, 2);
1898 if (ms_present == 3) {
1899 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1901 } else if (ms_present)
1902 decode_mid_side_stereo(cpe, gb, ms_present);
1904 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1906 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1909 if (common_window) {
1911 apply_mid_side_stereo(ac, cpe);
1912 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1913 apply_prediction(ac, &cpe->ch[0]);
1914 apply_prediction(ac, &cpe->ch[1]);
1918 apply_intensity_stereo(ac, cpe, ms_present);
1922 static const float cce_scale[] = {
1923 1.09050773266525765921, //2^(1/8)
1924 1.18920711500272106672, //2^(1/4)
1930 * Decode coupling_channel_element; reference: table 4.8.
1932 * @return Returns error status. 0 - OK, !0 - error
1934 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1940 SingleChannelElement *sce = &che->ch[0];
1941 ChannelCoupling *coup = &che->coup;
1943 coup->coupling_point = 2 * get_bits1(gb);
1944 coup->num_coupled = get_bits(gb, 3);
1945 for (c = 0; c <= coup->num_coupled; c++) {
1947 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1948 coup->id_select[c] = get_bits(gb, 4);
1949 if (coup->type[c] == TYPE_CPE) {
1950 coup->ch_select[c] = get_bits(gb, 2);
1951 if (coup->ch_select[c] == 3)
1954 coup->ch_select[c] = 2;
1956 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1958 sign = get_bits(gb, 1);
1959 scale = cce_scale[get_bits(gb, 2)];
1961 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1964 for (c = 0; c < num_gain; c++) {
1968 float gain_cache = 1.;
1970 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1971 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1972 gain_cache = powf(scale, -gain);
1974 if (coup->coupling_point == AFTER_IMDCT) {
1975 coup->gain[c][0] = gain_cache;
1977 for (g = 0; g < sce->ics.num_window_groups; g++) {
1978 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1979 if (sce->band_type[idx] != ZERO_BT) {
1981 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1989 gain_cache = powf(scale, -t) * s;
1992 coup->gain[c][idx] = gain_cache;
2002 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2004 * @return Returns number of bytes consumed.
2006 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2010 int num_excl_chan = 0;
2013 for (i = 0; i < 7; i++)
2014 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2015 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2017 return num_excl_chan / 7;
2021 * Decode dynamic range information; reference: table 4.52.
2023 * @return Returns number of bytes consumed.
2025 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2029 int drc_num_bands = 1;
2032 /* pce_tag_present? */
2033 if (get_bits1(gb)) {
2034 che_drc->pce_instance_tag = get_bits(gb, 4);
2035 skip_bits(gb, 4); // tag_reserved_bits
2039 /* excluded_chns_present? */
2040 if (get_bits1(gb)) {
2041 n += decode_drc_channel_exclusions(che_drc, gb);
2044 /* drc_bands_present? */
2045 if (get_bits1(gb)) {
2046 che_drc->band_incr = get_bits(gb, 4);
2047 che_drc->interpolation_scheme = get_bits(gb, 4);
2049 drc_num_bands += che_drc->band_incr;
2050 for (i = 0; i < drc_num_bands; i++) {
2051 che_drc->band_top[i] = get_bits(gb, 8);
2056 /* prog_ref_level_present? */
2057 if (get_bits1(gb)) {
2058 che_drc->prog_ref_level = get_bits(gb, 7);
2059 skip_bits1(gb); // prog_ref_level_reserved_bits
2063 for (i = 0; i < drc_num_bands; i++) {
2064 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2065 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2072 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2074 int i, major, minor;
2079 get_bits(gb, 13); len -= 13;
2081 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2082 buf[i] = get_bits(gb, 8);
2085 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2086 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2088 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2089 ac->avctx->internal->skip_samples = 1024;
2093 skip_bits_long(gb, len);
2099 * Decode extension data (incomplete); reference: table 4.51.
2101 * @param cnt length of TYPE_FIL syntactic element in bytes
2103 * @return Returns number of bytes consumed
2105 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2106 ChannelElement *che, enum RawDataBlockType elem_type)
2110 switch (get_bits(gb, 4)) { // extension type
2111 case EXT_SBR_DATA_CRC:
2115 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2117 } else if (!ac->oc[1].m4ac.sbr) {
2118 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2119 skip_bits_long(gb, 8 * cnt - 4);
2121 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2122 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2123 skip_bits_long(gb, 8 * cnt - 4);
2125 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2126 ac->oc[1].m4ac.sbr = 1;
2127 ac->oc[1].m4ac.ps = 1;
2128 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2129 ac->oc[1].status, 1);
2131 ac->oc[1].m4ac.sbr = 1;
2133 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2135 case EXT_DYNAMIC_RANGE:
2136 res = decode_dynamic_range(&ac->che_drc, gb);
2139 decode_fill(ac, gb, 8 * cnt - 4);
2142 case EXT_DATA_ELEMENT:
2144 skip_bits_long(gb, 8 * cnt - 4);
2151 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2153 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2154 * @param coef spectral coefficients
2156 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2157 IndividualChannelStream *ics, int decode)
2159 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2161 int bottom, top, order, start, end, size, inc;
2162 float lpc[TNS_MAX_ORDER];
2163 float tmp[TNS_MAX_ORDER+1];
2165 for (w = 0; w < ics->num_windows; w++) {
2166 bottom = ics->num_swb;
2167 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2169 bottom = FFMAX(0, top - tns->length[w][filt]);
2170 order = tns->order[w][filt];
2175 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2177 start = ics->swb_offset[FFMIN(bottom, mmm)];
2178 end = ics->swb_offset[FFMIN( top, mmm)];
2179 if ((size = end - start) <= 0)
2181 if (tns->direction[w][filt]) {
2191 for (m = 0; m < size; m++, start += inc)
2192 for (i = 1; i <= FFMIN(m, order); i++)
2193 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2196 for (m = 0; m < size; m++, start += inc) {
2197 tmp[0] = coef[start];
2198 for (i = 1; i <= FFMIN(m, order); i++)
2199 coef[start] += tmp[i] * lpc[i - 1];
2200 for (i = order; i > 0; i--)
2201 tmp[i] = tmp[i - 1];
2209 * Apply windowing and MDCT to obtain the spectral
2210 * coefficient from the predicted sample by LTP.
2212 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2213 float *in, IndividualChannelStream *ics)
2215 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2216 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2217 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2218 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2220 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2221 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2223 memset(in, 0, 448 * sizeof(float));
2224 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2226 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2227 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2229 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2230 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2232 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2236 * Apply the long term prediction
2238 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2240 const LongTermPrediction *ltp = &sce->ics.ltp;
2241 const uint16_t *offsets = sce->ics.swb_offset;
2244 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2245 float *predTime = sce->ret;
2246 float *predFreq = ac->buf_mdct;
2247 int16_t num_samples = 2048;
2249 if (ltp->lag < 1024)
2250 num_samples = ltp->lag + 1024;
2251 for (i = 0; i < num_samples; i++)
2252 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2253 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2255 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2257 if (sce->tns.present)
2258 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2260 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2262 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2263 sce->coeffs[i] += predFreq[i];
2268 * Update the LTP buffer for next frame
2270 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2272 IndividualChannelStream *ics = &sce->ics;
2273 float *saved = sce->saved;
2274 float *saved_ltp = sce->coeffs;
2275 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2276 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2279 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2280 memcpy(saved_ltp, saved, 512 * sizeof(float));
2281 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2282 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2283 for (i = 0; i < 64; i++)
2284 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2285 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2286 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2287 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2288 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2289 for (i = 0; i < 64; i++)
2290 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2291 } else { // LONG_STOP or ONLY_LONG
2292 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2293 for (i = 0; i < 512; i++)
2294 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2297 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2298 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2299 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2303 * Conduct IMDCT and windowing.
2305 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2307 IndividualChannelStream *ics = &sce->ics;
2308 float *in = sce->coeffs;
2309 float *out = sce->ret;
2310 float *saved = sce->saved;
2311 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2312 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2313 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2314 float *buf = ac->buf_mdct;
2315 float *temp = ac->temp;
2319 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2320 for (i = 0; i < 1024; i += 128)
2321 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2323 ac->mdct.imdct_half(&ac->mdct, buf, in);
2325 /* window overlapping
2326 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2327 * and long to short transitions are considered to be short to short
2328 * transitions. This leaves just two cases (long to long and short to short)
2329 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2331 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2332 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2333 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2335 memcpy( out, saved, 448 * sizeof(float));
2337 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2338 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2339 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2340 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2341 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2342 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2343 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2345 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2346 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2351 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2352 memcpy( saved, temp + 64, 64 * sizeof(float));
2353 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2354 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2355 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2356 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2357 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2358 memcpy( saved, buf + 512, 448 * sizeof(float));
2359 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2360 } else { // LONG_STOP or ONLY_LONG
2361 memcpy( saved, buf + 512, 512 * sizeof(float));
2366 * Apply dependent channel coupling (applied before IMDCT).
2368 * @param index index into coupling gain array
2370 static void apply_dependent_coupling(AACContext *ac,
2371 SingleChannelElement *target,
2372 ChannelElement *cce, int index)
2374 IndividualChannelStream *ics = &cce->ch[0].ics;
2375 const uint16_t *offsets = ics->swb_offset;
2376 float *dest = target->coeffs;
2377 const float *src = cce->ch[0].coeffs;
2378 int g, i, group, k, idx = 0;
2379 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2380 av_log(ac->avctx, AV_LOG_ERROR,
2381 "Dependent coupling is not supported together with LTP\n");
2384 for (g = 0; g < ics->num_window_groups; g++) {
2385 for (i = 0; i < ics->max_sfb; i++, idx++) {
2386 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2387 const float gain = cce->coup.gain[index][idx];
2388 for (group = 0; group < ics->group_len[g]; group++) {
2389 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2391 dest[group * 128 + k] += gain * src[group * 128 + k];
2396 dest += ics->group_len[g] * 128;
2397 src += ics->group_len[g] * 128;
2402 * Apply independent channel coupling (applied after IMDCT).
2404 * @param index index into coupling gain array
2406 static void apply_independent_coupling(AACContext *ac,
2407 SingleChannelElement *target,
2408 ChannelElement *cce, int index)
2411 const float gain = cce->coup.gain[index][0];
2412 const float *src = cce->ch[0].ret;
2413 float *dest = target->ret;
2414 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2416 for (i = 0; i < len; i++)
2417 dest[i] += gain * src[i];
2421 * channel coupling transformation interface
2423 * @param apply_coupling_method pointer to (in)dependent coupling function
2425 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2426 enum RawDataBlockType type, int elem_id,
2427 enum CouplingPoint coupling_point,
2428 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2432 for (i = 0; i < MAX_ELEM_ID; i++) {
2433 ChannelElement *cce = ac->che[TYPE_CCE][i];
2436 if (cce && cce->coup.coupling_point == coupling_point) {
2437 ChannelCoupling *coup = &cce->coup;
2439 for (c = 0; c <= coup->num_coupled; c++) {
2440 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2441 if (coup->ch_select[c] != 1) {
2442 apply_coupling_method(ac, &cc->ch[0], cce, index);
2443 if (coup->ch_select[c] != 0)
2446 if (coup->ch_select[c] != 2)
2447 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2449 index += 1 + (coup->ch_select[c] == 3);
2456 * Convert spectral data to float samples, applying all supported tools as appropriate.
2458 static void spectral_to_sample(AACContext *ac)
2461 for (type = 3; type >= 0; type--) {
2462 for (i = 0; i < MAX_ELEM_ID; i++) {
2463 ChannelElement *che = ac->che[type][i];
2465 if (type <= TYPE_CPE)
2466 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2467 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2468 if (che->ch[0].ics.predictor_present) {
2469 if (che->ch[0].ics.ltp.present)
2470 ac->apply_ltp(ac, &che->ch[0]);
2471 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2472 ac->apply_ltp(ac, &che->ch[1]);
2475 if (che->ch[0].tns.present)
2476 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2477 if (che->ch[1].tns.present)
2478 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2479 if (type <= TYPE_CPE)
2480 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2481 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2482 ac->imdct_and_windowing(ac, &che->ch[0]);
2483 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2484 ac->update_ltp(ac, &che->ch[0]);
2485 if (type == TYPE_CPE) {
2486 ac->imdct_and_windowing(ac, &che->ch[1]);
2487 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2488 ac->update_ltp(ac, &che->ch[1]);
2490 if (ac->oc[1].m4ac.sbr > 0) {
2491 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2494 if (type <= TYPE_CCE)
2495 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2501 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2504 AACADTSHeaderInfo hdr_info;
2505 uint8_t layout_map[MAX_ELEM_ID*4][3];
2506 int layout_map_tags;
2508 size = avpriv_aac_parse_header(gb, &hdr_info);
2510 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2511 // This is 2 for "VLB " audio in NSV files.
2512 // See samples/nsv/vlb_audio.
2513 avpriv_report_missing_feature(ac->avctx,
2514 "More than one AAC RDB per ADTS frame");
2515 ac->warned_num_aac_frames = 1;
2517 push_output_configuration(ac);
2518 if (hdr_info.chan_config) {
2519 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2520 if (set_default_channel_config(ac->avctx, layout_map,
2521 &layout_map_tags, hdr_info.chan_config))
2523 if (output_configure(ac, layout_map, layout_map_tags,
2524 FFMAX(ac->oc[1].status, OC_TRIAL_FRAME), 0))
2527 ac->oc[1].m4ac.chan_config = 0;
2529 * dual mono frames in Japanese DTV can have chan_config 0
2530 * WITHOUT specifying PCE.
2531 * thus, set dual mono as default.
2533 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2534 layout_map_tags = 2;
2535 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2536 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2537 layout_map[0][1] = 0;
2538 layout_map[1][1] = 1;
2539 if (output_configure(ac, layout_map, layout_map_tags,
2544 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2545 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2546 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2547 if (ac->oc[0].status != OC_LOCKED ||
2548 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2549 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2550 ac->oc[1].m4ac.sbr = -1;
2551 ac->oc[1].m4ac.ps = -1;
2553 if (!hdr_info.crc_absent)
2559 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2560 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2562 AACContext *ac = avctx->priv_data;
2563 ChannelElement *che = NULL, *che_prev = NULL;
2564 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2566 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2567 int is_dmono, sce_count = 0;
2571 if (show_bits(gb, 12) == 0xfff) {
2572 if (parse_adts_frame_header(ac, gb) < 0) {
2573 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2577 if (ac->oc[1].m4ac.sampling_index > 12) {
2578 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2584 if (frame_configure_elements(avctx) < 0) {
2589 ac->tags_mapped = 0;
2591 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2592 elem_id = get_bits(gb, 4);
2594 if (elem_type < TYPE_DSE) {
2595 if (!(che=get_che(ac, elem_type, elem_id))) {
2596 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2597 elem_type, elem_id);
2604 switch (elem_type) {
2607 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2613 err = decode_cpe(ac, gb, che);
2618 err = decode_cce(ac, gb, che);
2622 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2627 err = skip_data_stream_element(ac, gb);
2631 uint8_t layout_map[MAX_ELEM_ID*4][3];
2633 push_output_configuration(ac);
2634 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2640 av_log(avctx, AV_LOG_ERROR,
2641 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2643 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2645 ac->oc[1].m4ac.chan_config = 0;
2653 elem_id += get_bits(gb, 8) - 1;
2654 if (get_bits_left(gb) < 8 * elem_id) {
2655 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
2660 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2661 err = 0; /* FIXME */
2665 err = -1; /* should not happen, but keeps compiler happy */
2670 elem_type_prev = elem_type;
2675 if (get_bits_left(gb) < 3) {
2676 av_log(avctx, AV_LOG_ERROR, overread_err);
2682 spectral_to_sample(ac);
2684 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2685 samples <<= multiplier;
2686 /* for dual-mono audio (SCE + SCE) */
2687 is_dmono = ac->dmono_mode && sce_count == 2 &&
2688 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
2691 ac->frame->nb_samples = samples;
2693 av_frame_unref(ac->frame);
2694 *got_frame_ptr = !!samples;
2697 if (ac->dmono_mode == 1)
2698 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
2699 else if (ac->dmono_mode == 2)
2700 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
2703 if (ac->oc[1].status && audio_found) {
2704 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2705 avctx->frame_size = samples;
2706 ac->oc[1].status = OC_LOCKED;
2711 const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2712 if (side && side_size>=4)
2713 AV_WL32(side, 2*AV_RL32(side));
2717 pop_output_configuration(ac);
2721 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2722 int *got_frame_ptr, AVPacket *avpkt)
2724 AACContext *ac = avctx->priv_data;
2725 const uint8_t *buf = avpkt->data;
2726 int buf_size = avpkt->size;
2731 int new_extradata_size;
2732 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2733 AV_PKT_DATA_NEW_EXTRADATA,
2734 &new_extradata_size);
2735 int jp_dualmono_size;
2736 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
2737 AV_PKT_DATA_JP_DUALMONO,
2740 if (new_extradata && 0) {
2741 av_free(avctx->extradata);
2742 avctx->extradata = av_mallocz(new_extradata_size +
2743 FF_INPUT_BUFFER_PADDING_SIZE);
2744 if (!avctx->extradata)
2745 return AVERROR(ENOMEM);
2746 avctx->extradata_size = new_extradata_size;
2747 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2748 push_output_configuration(ac);
2749 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2751 avctx->extradata_size*8, 1) < 0) {
2752 pop_output_configuration(ac);
2753 return AVERROR_INVALIDDATA;
2758 if (jp_dualmono && jp_dualmono_size > 0)
2759 ac->dmono_mode = 1 + *jp_dualmono;
2760 if (ac->force_dmono_mode >= 0)
2761 ac->dmono_mode = ac->force_dmono_mode;
2763 if (INT_MAX / 8 <= buf_size)
2764 return AVERROR_INVALIDDATA;
2766 init_get_bits(&gb, buf, buf_size * 8);
2768 if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt)) < 0)
2771 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2772 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2773 if (buf[buf_offset])
2776 return buf_size > buf_offset ? buf_consumed : buf_size;
2779 static av_cold int aac_decode_close(AVCodecContext *avctx)
2781 AACContext *ac = avctx->priv_data;
2784 for (i = 0; i < MAX_ELEM_ID; i++) {
2785 for (type = 0; type < 4; type++) {
2786 if (ac->che[type][i])
2787 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2788 av_freep(&ac->che[type][i]);
2792 ff_mdct_end(&ac->mdct);
2793 ff_mdct_end(&ac->mdct_small);
2794 ff_mdct_end(&ac->mdct_ltp);
2799 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2801 struct LATMContext {
2802 AACContext aac_ctx; ///< containing AACContext
2803 int initialized; ///< initialized after a valid extradata was seen
2806 int audio_mux_version_A; ///< LATM syntax version
2807 int frame_length_type; ///< 0/1 variable/fixed frame length
2808 int frame_length; ///< frame length for fixed frame length
2811 static inline uint32_t latm_get_value(GetBitContext *b)
2813 int length = get_bits(b, 2);
2815 return get_bits_long(b, (length+1)*8);
2818 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2819 GetBitContext *gb, int asclen)
2821 AACContext *ac = &latmctx->aac_ctx;
2822 AVCodecContext *avctx = ac->avctx;
2823 MPEG4AudioConfig m4ac = { 0 };
2824 int config_start_bit = get_bits_count(gb);
2825 int sync_extension = 0;
2826 int bits_consumed, esize;
2830 asclen = FFMIN(asclen, get_bits_left(gb));
2832 asclen = get_bits_left(gb);
2834 if (config_start_bit % 8) {
2835 avpriv_request_sample(latmctx->aac_ctx.avctx,
2836 "Non-byte-aligned audio-specific config");
2837 return AVERROR_PATCHWELCOME;
2840 return AVERROR_INVALIDDATA;
2841 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2842 gb->buffer + (config_start_bit / 8),
2843 asclen, sync_extension);
2845 if (bits_consumed < 0)
2846 return AVERROR_INVALIDDATA;
2848 if (!latmctx->initialized ||
2849 ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
2850 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
2852 if(latmctx->initialized) {
2853 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2855 av_log(avctx, AV_LOG_DEBUG, "initializing latmctx\n");
2857 latmctx->initialized = 0;
2859 esize = (bits_consumed+7) / 8;
2861 if (avctx->extradata_size < esize) {
2862 av_free(avctx->extradata);
2863 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2864 if (!avctx->extradata)
2865 return AVERROR(ENOMEM);
2868 avctx->extradata_size = esize;
2869 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2870 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2872 skip_bits_long(gb, bits_consumed);
2874 return bits_consumed;
2877 static int read_stream_mux_config(struct LATMContext *latmctx,
2880 int ret, audio_mux_version = get_bits(gb, 1);
2882 latmctx->audio_mux_version_A = 0;
2883 if (audio_mux_version)
2884 latmctx->audio_mux_version_A = get_bits(gb, 1);
2886 if (!latmctx->audio_mux_version_A) {
2888 if (audio_mux_version)
2889 latm_get_value(gb); // taraFullness
2891 skip_bits(gb, 1); // allStreamSameTimeFraming
2892 skip_bits(gb, 6); // numSubFrames
2894 if (get_bits(gb, 4)) { // numPrograms
2895 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
2896 return AVERROR_PATCHWELCOME;
2899 // for each program (which there is only one in DVB)
2901 // for each layer (which there is only one in DVB)
2902 if (get_bits(gb, 3)) { // numLayer
2903 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
2904 return AVERROR_PATCHWELCOME;
2907 // for all but first stream: use_same_config = get_bits(gb, 1);
2908 if (!audio_mux_version) {
2909 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2912 int ascLen = latm_get_value(gb);
2913 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2916 skip_bits_long(gb, ascLen);
2919 latmctx->frame_length_type = get_bits(gb, 3);
2920 switch (latmctx->frame_length_type) {
2922 skip_bits(gb, 8); // latmBufferFullness
2925 latmctx->frame_length = get_bits(gb, 9);
2930 skip_bits(gb, 6); // CELP frame length table index
2934 skip_bits(gb, 1); // HVXC frame length table index
2938 if (get_bits(gb, 1)) { // other data
2939 if (audio_mux_version) {
2940 latm_get_value(gb); // other_data_bits
2944 esc = get_bits(gb, 1);
2950 if (get_bits(gb, 1)) // crc present
2951 skip_bits(gb, 8); // config_crc
2957 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2961 if (ctx->frame_length_type == 0) {
2962 int mux_slot_length = 0;
2964 tmp = get_bits(gb, 8);
2965 mux_slot_length += tmp;
2966 } while (tmp == 255);
2967 return mux_slot_length;
2968 } else if (ctx->frame_length_type == 1) {
2969 return ctx->frame_length;
2970 } else if (ctx->frame_length_type == 3 ||
2971 ctx->frame_length_type == 5 ||
2972 ctx->frame_length_type == 7) {
2973 skip_bits(gb, 2); // mux_slot_length_coded
2978 static int read_audio_mux_element(struct LATMContext *latmctx,
2982 uint8_t use_same_mux = get_bits(gb, 1);
2983 if (!use_same_mux) {
2984 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2986 } else if (!latmctx->aac_ctx.avctx->extradata) {
2987 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2988 "no decoder config found\n");
2989 return AVERROR(EAGAIN);
2991 if (latmctx->audio_mux_version_A == 0) {
2992 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2993 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2994 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2995 return AVERROR_INVALIDDATA;
2996 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2997 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2998 "frame length mismatch %d << %d\n",
2999 mux_slot_length_bytes * 8, get_bits_left(gb));
3000 return AVERROR_INVALIDDATA;
3007 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3008 int *got_frame_ptr, AVPacket *avpkt)
3010 struct LATMContext *latmctx = avctx->priv_data;
3014 if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
3017 // check for LOAS sync word
3018 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3019 return AVERROR_INVALIDDATA;
3021 muxlength = get_bits(&gb, 13) + 3;
3022 // not enough data, the parser should have sorted this out
3023 if (muxlength > avpkt->size)
3024 return AVERROR_INVALIDDATA;
3026 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3029 if (!latmctx->initialized) {
3030 if (!avctx->extradata) {
3034 push_output_configuration(&latmctx->aac_ctx);
3035 if ((err = decode_audio_specific_config(
3036 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3037 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3038 pop_output_configuration(&latmctx->aac_ctx);
3041 latmctx->initialized = 1;
3045 if (show_bits(&gb, 12) == 0xfff) {
3046 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3047 "ADTS header detected, probably as result of configuration "
3049 return AVERROR_INVALIDDATA;
3052 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
3058 static av_cold int latm_decode_init(AVCodecContext *avctx)
3060 struct LATMContext *latmctx = avctx->priv_data;
3061 int ret = aac_decode_init(avctx);
3063 if (avctx->extradata_size > 0)
3064 latmctx->initialized = !ret;
3069 static void aacdec_init(AACContext *c)
3071 c->imdct_and_windowing = imdct_and_windowing;
3072 c->apply_ltp = apply_ltp;
3073 c->apply_tns = apply_tns;
3074 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3075 c->update_ltp = update_ltp;
3078 ff_aacdec_init_mips(c);
3081 * AVOptions for Japanese DTV specific extensions (ADTS only)
3083 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3084 static const AVOption options[] = {
3085 {"dual_mono_mode", "Select the channel to decode for dual mono",
3086 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3087 AACDEC_FLAGS, "dual_mono_mode"},
3089 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3090 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3091 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3092 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3097 static const AVClass aac_decoder_class = {
3098 .class_name = "AAC decoder",
3099 .item_name = av_default_item_name,
3101 .version = LIBAVUTIL_VERSION_INT,
3104 AVCodec ff_aac_decoder = {
3106 .type = AVMEDIA_TYPE_AUDIO,
3107 .id = AV_CODEC_ID_AAC,
3108 .priv_data_size = sizeof(AACContext),
3109 .init = aac_decode_init,
3110 .close = aac_decode_close,
3111 .decode = aac_decode_frame,
3112 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3113 .sample_fmts = (const enum AVSampleFormat[]) {
3114 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3116 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3117 .channel_layouts = aac_channel_layout,
3119 .priv_class = &aac_decoder_class,
3123 Note: This decoder filter is intended to decode LATM streams transferred
3124 in MPEG transport streams which only contain one program.
3125 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3127 AVCodec ff_aac_latm_decoder = {
3129 .type = AVMEDIA_TYPE_AUDIO,
3130 .id = AV_CODEC_ID_AAC_LATM,
3131 .priv_data_size = sizeof(struct LATMContext),
3132 .init = latm_decode_init,
3133 .close = aac_decode_close,
3134 .decode = latm_decode_frame,
3135 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3136 .sample_fmts = (const enum AVSampleFormat[]) {
3137 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3139 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3140 .channel_layouts = aac_channel_layout,