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 #include "libavutil/thread.h"
115 static VLC vlc_scalefactors;
116 static VLC vlc_spectral[11];
118 static const char overread_err[] = "Input buffer exhausted before END element found\n";
120 static int count_channels(uint8_t (*layout)[3], int tags)
123 for (i = 0; i < tags; i++) {
124 int syn_ele = layout[i][0];
125 int pos = layout[i][2];
126 sum += (1 + (syn_ele == TYPE_CPE)) *
127 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
133 * Check for the channel element in the current channel position configuration.
134 * If it exists, make sure the appropriate element is allocated and map the
135 * channel order to match the internal Libav channel layout.
137 * @param che_pos current channel position configuration
138 * @param type channel element type
139 * @param id channel element id
140 * @param channels count of the number of channels in the configuration
142 * @return Returns error status. 0 - OK, !0 - error
144 static av_cold int che_configure(AACContext *ac,
145 enum ChannelPosition che_pos,
146 int type, int id, int *channels)
149 if (!ac->che[type][id]) {
150 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
151 return AVERROR(ENOMEM);
152 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
154 if (type != TYPE_CCE) {
155 if (*channels >= MAX_CHANNELS - 2)
156 return AVERROR_INVALIDDATA;
157 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
158 if (type == TYPE_CPE ||
159 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
160 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
164 if (ac->che[type][id])
165 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
166 av_freep(&ac->che[type][id]);
171 static int frame_configure_elements(AVCodecContext *avctx)
173 AACContext *ac = avctx->priv_data;
174 int type, id, ch, ret;
176 /* set channel pointers to internal buffers by default */
177 for (type = 0; type < 4; type++) {
178 for (id = 0; id < MAX_ELEM_ID; id++) {
179 ChannelElement *che = ac->che[type][id];
181 che->ch[0].ret = che->ch[0].ret_buf;
182 che->ch[1].ret = che->ch[1].ret_buf;
187 /* get output buffer */
188 av_frame_unref(ac->frame);
189 ac->frame->nb_samples = 2048;
190 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0) {
191 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
195 /* map output channel pointers to AVFrame data */
196 for (ch = 0; ch < avctx->channels; ch++) {
197 if (ac->output_element[ch])
198 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
204 struct elem_to_channel {
205 uint64_t av_position;
208 uint8_t aac_position;
211 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
212 uint8_t (*layout_map)[3], int offset, uint64_t left,
213 uint64_t right, int pos)
215 if (layout_map[offset][0] == TYPE_CPE) {
216 e2c_vec[offset] = (struct elem_to_channel) {
217 .av_position = left | right,
219 .elem_id = layout_map[offset][1],
224 e2c_vec[offset] = (struct elem_to_channel) {
227 .elem_id = layout_map[offset][1],
230 e2c_vec[offset + 1] = (struct elem_to_channel) {
231 .av_position = right,
233 .elem_id = layout_map[offset + 1][1],
240 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
243 int num_pos_channels = 0;
247 for (i = *current; i < tags; i++) {
248 if (layout_map[i][2] != pos)
250 if (layout_map[i][0] == TYPE_CPE) {
252 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
258 num_pos_channels += 2;
266 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
269 return num_pos_channels;
272 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
274 int i, n, total_non_cc_elements;
275 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
276 int num_front_channels, num_side_channels, num_back_channels;
279 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
284 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
285 if (num_front_channels < 0)
288 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
289 if (num_side_channels < 0)
292 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
293 if (num_back_channels < 0)
296 if (num_side_channels == 0 && num_back_channels >= 4) {
297 num_side_channels = 2;
298 num_back_channels -= 2;
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;
441 * Configure output channel order based on the current program
442 * configuration element.
444 * @return Returns error status. 0 - OK, !0 - error
446 static int output_configure(AACContext *ac,
447 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
448 enum OCStatus oc_type, int get_new_frame)
450 AVCodecContext *avctx = ac->avctx;
451 int i, channels = 0, ret;
453 uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
454 uint8_t type_counts[TYPE_END] = { 0 };
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;
460 for (i = 0; i < tags; i++) {
461 int type = layout_map[i][0];
462 int id = layout_map[i][1];
463 id_map[type][id] = type_counts[type]++;
465 // Try to sniff a reasonable channel order, otherwise output the
466 // channels in the order the PCE declared them.
467 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
468 layout = sniff_channel_order(layout_map, tags);
469 for (i = 0; i < tags; i++) {
470 int type = layout_map[i][0];
471 int id = layout_map[i][1];
472 int iid = id_map[type][id];
473 int position = layout_map[i][2];
474 // Allocate or free elements depending on if they are in the
475 // current program configuration.
476 ret = che_configure(ac, position, type, iid, &channels);
479 ac->tag_che_map[type][id] = ac->che[type][iid];
481 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
482 if (layout == AV_CH_FRONT_CENTER) {
483 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
489 avctx->channel_layout = ac->oc[1].channel_layout = layout;
490 avctx->channels = ac->oc[1].channels = channels;
491 ac->oc[1].status = oc_type;
494 if ((ret = frame_configure_elements(ac->avctx)) < 0)
502 * Set up channel positions based on a default channel configuration
503 * as specified in table 1.17.
505 * @return Returns error status. 0 - OK, !0 - error
507 static int set_default_channel_config(AVCodecContext *avctx,
508 uint8_t (*layout_map)[3],
512 if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
513 channel_config > 12) {
514 av_log(avctx, AV_LOG_ERROR,
515 "invalid default channel configuration (%d)\n",
517 return AVERROR_INVALIDDATA;
519 *tags = tags_per_config[channel_config];
520 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
521 *tags * sizeof(*layout_map));
525 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
527 /* For PCE based channel configurations map the channels solely based
529 if (!ac->oc[1].m4ac.chan_config) {
530 return ac->tag_che_map[type][elem_id];
532 // Allow single CPE stereo files to be signalled with mono configuration.
533 if (!ac->tags_mapped && type == TYPE_CPE &&
534 ac->oc[1].m4ac.chan_config == 1) {
535 uint8_t layout_map[MAX_ELEM_ID*4][3];
537 push_output_configuration(ac);
539 if (set_default_channel_config(ac->avctx, layout_map,
540 &layout_map_tags, 2) < 0)
542 if (output_configure(ac, layout_map, layout_map_tags,
543 OC_TRIAL_FRAME, 1) < 0)
546 ac->oc[1].m4ac.chan_config = 2;
547 ac->oc[1].m4ac.ps = 0;
550 if (!ac->tags_mapped && type == TYPE_SCE &&
551 ac->oc[1].m4ac.chan_config == 2) {
552 uint8_t layout_map[MAX_ELEM_ID * 4][3];
554 push_output_configuration(ac);
556 if (set_default_channel_config(ac->avctx, layout_map,
557 &layout_map_tags, 1) < 0)
559 if (output_configure(ac, layout_map, layout_map_tags,
560 OC_TRIAL_FRAME, 1) < 0)
563 ac->oc[1].m4ac.chan_config = 1;
564 if (ac->oc[1].m4ac.sbr)
565 ac->oc[1].m4ac.ps = -1;
567 /* For indexed channel configurations map the channels solely based
569 switch (ac->oc[1].m4ac.chan_config) {
572 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
574 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
577 if (ac->tags_mapped == 2 &&
578 ac->oc[1].m4ac.chan_config == 11 &&
581 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
584 /* Some streams incorrectly code 5.1 audio as
585 * SCE[0] CPE[0] CPE[1] SCE[1]
587 * SCE[0] CPE[0] CPE[1] LFE[0].
588 * If we seem to have encountered such a stream, transfer
589 * the LFE[0] element to the SCE[1]'s mapping */
590 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
592 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
595 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
597 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
600 if (ac->tags_mapped == 2 &&
601 ac->oc[1].m4ac.chan_config == 4 &&
604 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
608 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
611 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
612 } else if (ac->oc[1].m4ac.chan_config == 2) {
616 if (!ac->tags_mapped && type == TYPE_SCE) {
618 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
626 * Decode an array of 4 bit element IDs, optionally interleaved with a
627 * stereo/mono switching bit.
629 * @param type speaker type/position for these channels
631 static void decode_channel_map(uint8_t layout_map[][3],
632 enum ChannelPosition type,
633 GetBitContext *gb, int n)
636 enum RawDataBlockType syn_ele;
638 case AAC_CHANNEL_FRONT:
639 case AAC_CHANNEL_BACK:
640 case AAC_CHANNEL_SIDE:
641 syn_ele = get_bits1(gb);
647 case AAC_CHANNEL_LFE:
651 // AAC_CHANNEL_OFF has no channel map
654 layout_map[0][0] = syn_ele;
655 layout_map[0][1] = get_bits(gb, 4);
656 layout_map[0][2] = type;
662 * Decode program configuration element; reference: table 4.2.
664 * @return Returns error status. 0 - OK, !0 - error
666 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
667 uint8_t (*layout_map)[3],
670 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
675 skip_bits(gb, 2); // object_type
677 sampling_index = get_bits(gb, 4);
678 if (m4ac->sampling_index != sampling_index)
679 av_log(avctx, AV_LOG_WARNING,
680 "Sample rate index in program config element does not "
681 "match the sample rate index configured by the container.\n");
683 num_front = get_bits(gb, 4);
684 num_side = get_bits(gb, 4);
685 num_back = get_bits(gb, 4);
686 num_lfe = get_bits(gb, 2);
687 num_assoc_data = get_bits(gb, 3);
688 num_cc = get_bits(gb, 4);
691 skip_bits(gb, 4); // mono_mixdown_tag
693 skip_bits(gb, 4); // stereo_mixdown_tag
696 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
698 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
700 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
702 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
704 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
707 skip_bits_long(gb, 4 * num_assoc_data);
709 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
714 /* comment field, first byte is length */
715 comment_len = get_bits(gb, 8) * 8;
716 if (get_bits_left(gb) < comment_len) {
717 av_log(avctx, AV_LOG_ERROR, overread_err);
718 return AVERROR_INVALIDDATA;
720 skip_bits_long(gb, comment_len);
725 * Decode GA "General Audio" specific configuration; reference: table 4.1.
727 * @param ac pointer to AACContext, may be null
728 * @param avctx pointer to AVCCodecContext, used for logging
730 * @return Returns error status. 0 - OK, !0 - error
732 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
734 MPEG4AudioConfig *m4ac,
737 int extension_flag, ret, ep_config, res_flags;
738 uint8_t layout_map[MAX_ELEM_ID*4][3];
741 if (get_bits1(gb)) { // frameLengthFlag
742 avpriv_request_sample(avctx, "960/120 MDCT window");
743 return AVERROR_PATCHWELCOME;
745 m4ac->frame_length_short = 0;
747 if (get_bits1(gb)) // dependsOnCoreCoder
748 skip_bits(gb, 14); // coreCoderDelay
749 extension_flag = get_bits1(gb);
751 if (m4ac->object_type == AOT_AAC_SCALABLE ||
752 m4ac->object_type == AOT_ER_AAC_SCALABLE)
753 skip_bits(gb, 3); // layerNr
755 if (channel_config == 0) {
756 skip_bits(gb, 4); // element_instance_tag
757 tags = decode_pce(avctx, m4ac, layout_map, gb);
761 if ((ret = set_default_channel_config(avctx, layout_map,
762 &tags, channel_config)))
766 if (count_channels(layout_map, tags) > 1) {
768 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
771 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
774 if (extension_flag) {
775 switch (m4ac->object_type) {
777 skip_bits(gb, 5); // numOfSubFrame
778 skip_bits(gb, 11); // layer_length
782 case AOT_ER_AAC_SCALABLE:
784 res_flags = get_bits(gb, 3);
786 avpriv_report_missing_feature(avctx,
787 "AAC data resilience (flags %x)",
789 return AVERROR_PATCHWELCOME;
793 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
795 switch (m4ac->object_type) {
798 case AOT_ER_AAC_SCALABLE:
800 ep_config = get_bits(gb, 2);
802 avpriv_report_missing_feature(avctx,
803 "epConfig %d", ep_config);
804 return AVERROR_PATCHWELCOME;
810 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
812 MPEG4AudioConfig *m4ac,
815 int ret, ep_config, res_flags;
816 uint8_t layout_map[MAX_ELEM_ID*4][3];
818 const int ELDEXT_TERM = 0;
823 m4ac->frame_length_short = get_bits1(gb);
824 res_flags = get_bits(gb, 3);
826 avpriv_report_missing_feature(avctx,
827 "AAC data resilience (flags %x)",
829 return AVERROR_PATCHWELCOME;
832 if (get_bits1(gb)) { // ldSbrPresentFlag
833 avpriv_report_missing_feature(avctx,
835 return AVERROR_PATCHWELCOME;
838 while (get_bits(gb, 4) != ELDEXT_TERM) {
839 int len = get_bits(gb, 4);
841 len += get_bits(gb, 8);
843 len += get_bits(gb, 16);
844 if (get_bits_left(gb) < len * 8 + 4) {
845 av_log(avctx, AV_LOG_ERROR, overread_err);
846 return AVERROR_INVALIDDATA;
848 skip_bits_long(gb, 8 * len);
851 if ((ret = set_default_channel_config(avctx, layout_map,
852 &tags, channel_config)))
855 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
858 ep_config = get_bits(gb, 2);
860 avpriv_report_missing_feature(avctx,
861 "epConfig %d", ep_config);
862 return AVERROR_PATCHWELCOME;
868 * Decode audio specific configuration; reference: table 1.13.
870 * @param ac pointer to AACContext, may be null
871 * @param avctx pointer to AVCCodecContext, used for logging
872 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
873 * @param data pointer to buffer holding an audio specific config
874 * @param bit_size size of audio specific config or data in bits
875 * @param sync_extension look for an appended sync extension
877 * @return Returns error status or number of consumed bits. <0 - error
879 static int decode_audio_specific_config(AACContext *ac,
880 AVCodecContext *avctx,
881 MPEG4AudioConfig *m4ac,
882 const uint8_t *data, int bit_size,
888 ff_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
889 for (i = 0; i < avctx->extradata_size; i++)
890 ff_dlog(avctx, "%02x ", avctx->extradata[i]);
891 ff_dlog(avctx, "\n");
893 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
896 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
897 sync_extension)) < 0)
898 return AVERROR_INVALIDDATA;
899 if (m4ac->sampling_index > 12) {
900 av_log(avctx, AV_LOG_ERROR,
901 "invalid sampling rate index %d\n",
902 m4ac->sampling_index);
903 return AVERROR_INVALIDDATA;
905 if (m4ac->object_type == AOT_ER_AAC_LD &&
906 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
907 av_log(avctx, AV_LOG_ERROR,
908 "invalid low delay sampling rate index %d\n",
909 m4ac->sampling_index);
910 return AVERROR_INVALIDDATA;
913 skip_bits_long(&gb, i);
915 switch (m4ac->object_type) {
921 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
922 m4ac, m4ac->chan_config)) < 0)
926 if ((ret = decode_eld_specific_config(ac, avctx, &gb,
927 m4ac, m4ac->chan_config)) < 0)
931 avpriv_report_missing_feature(avctx,
932 "Audio object type %s%d",
933 m4ac->sbr == 1 ? "SBR+" : "",
935 return AVERROR(ENOSYS);
939 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
940 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
941 m4ac->sample_rate, m4ac->sbr,
944 return get_bits_count(&gb);
948 * linear congruential pseudorandom number generator
950 * @param previous_val pointer to the current state of the generator
952 * @return Returns a 32-bit pseudorandom integer
954 static av_always_inline int lcg_random(int previous_val)
956 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
960 static av_always_inline void reset_predict_state(PredictorState *ps)
970 static void reset_all_predictors(PredictorState *ps)
973 for (i = 0; i < MAX_PREDICTORS; i++)
974 reset_predict_state(&ps[i]);
977 static int sample_rate_idx (int rate)
979 if (92017 <= rate) return 0;
980 else if (75132 <= rate) return 1;
981 else if (55426 <= rate) return 2;
982 else if (46009 <= rate) return 3;
983 else if (37566 <= rate) return 4;
984 else if (27713 <= rate) return 5;
985 else if (23004 <= rate) return 6;
986 else if (18783 <= rate) return 7;
987 else if (13856 <= rate) return 8;
988 else if (11502 <= rate) return 9;
989 else if (9391 <= rate) return 10;
993 static void reset_predictor_group(PredictorState *ps, int group_num)
996 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
997 reset_predict_state(&ps[i]);
1000 #define AAC_INIT_VLC_STATIC(num, size) \
1001 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1002 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1003 sizeof(ff_aac_spectral_bits[num][0]), \
1004 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1005 sizeof(ff_aac_spectral_codes[num][0]), \
1008 static av_cold void aac_static_table_init(void)
1010 AAC_INIT_VLC_STATIC( 0, 304);
1011 AAC_INIT_VLC_STATIC( 1, 270);
1012 AAC_INIT_VLC_STATIC( 2, 550);
1013 AAC_INIT_VLC_STATIC( 3, 300);
1014 AAC_INIT_VLC_STATIC( 4, 328);
1015 AAC_INIT_VLC_STATIC( 5, 294);
1016 AAC_INIT_VLC_STATIC( 6, 306);
1017 AAC_INIT_VLC_STATIC( 7, 268);
1018 AAC_INIT_VLC_STATIC( 8, 510);
1019 AAC_INIT_VLC_STATIC( 9, 366);
1020 AAC_INIT_VLC_STATIC(10, 462);
1026 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1027 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1028 ff_aac_scalefactor_bits,
1029 sizeof(ff_aac_scalefactor_bits[0]),
1030 sizeof(ff_aac_scalefactor_bits[0]),
1031 ff_aac_scalefactor_code,
1032 sizeof(ff_aac_scalefactor_code[0]),
1033 sizeof(ff_aac_scalefactor_code[0]),
1037 // window initialization
1038 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1039 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1040 ff_init_ff_sine_windows(10);
1041 ff_init_ff_sine_windows( 9);
1042 ff_init_ff_sine_windows( 7);
1047 static AVOnce aac_init = AV_ONCE_INIT;
1049 static av_cold int aac_decode_init(AVCodecContext *avctx)
1051 AACContext *ac = avctx->priv_data;
1054 ret = ff_thread_once(&aac_init, &aac_static_table_init);
1056 return AVERROR_UNKNOWN;
1059 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1061 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1063 if (avctx->extradata_size > 0) {
1064 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1066 avctx->extradata_size * 8,
1071 uint8_t layout_map[MAX_ELEM_ID*4][3];
1072 int layout_map_tags;
1074 sr = sample_rate_idx(avctx->sample_rate);
1075 ac->oc[1].m4ac.sampling_index = sr;
1076 ac->oc[1].m4ac.channels = avctx->channels;
1077 ac->oc[1].m4ac.sbr = -1;
1078 ac->oc[1].m4ac.ps = -1;
1080 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1081 if (ff_mpeg4audio_channels[i] == avctx->channels)
1083 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1086 ac->oc[1].m4ac.chan_config = i;
1088 if (ac->oc[1].m4ac.chan_config) {
1089 int ret = set_default_channel_config(avctx, layout_map,
1090 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1092 output_configure(ac, layout_map, layout_map_tags,
1094 else if (avctx->err_recognition & AV_EF_EXPLODE)
1095 return AVERROR_INVALIDDATA;
1099 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
1101 ac->random_state = 0x1f2e3d4c;
1103 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1104 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1105 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1106 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1107 ret = ff_imdct15_init(&ac->mdct480, 5);
1115 * Skip data_stream_element; reference: table 4.10.
1117 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1119 int byte_align = get_bits1(gb);
1120 int count = get_bits(gb, 8);
1122 count += get_bits(gb, 8);
1126 if (get_bits_left(gb) < 8 * count) {
1127 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1128 return AVERROR_INVALIDDATA;
1130 skip_bits_long(gb, 8 * count);
1134 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1138 if (get_bits1(gb)) {
1139 ics->predictor_reset_group = get_bits(gb, 5);
1140 if (ics->predictor_reset_group == 0 ||
1141 ics->predictor_reset_group > 30) {
1142 av_log(ac->avctx, AV_LOG_ERROR,
1143 "Invalid Predictor Reset Group.\n");
1144 return AVERROR_INVALIDDATA;
1147 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1148 ics->prediction_used[sfb] = get_bits1(gb);
1154 * Decode Long Term Prediction data; reference: table 4.xx.
1156 static void decode_ltp(LongTermPrediction *ltp,
1157 GetBitContext *gb, uint8_t max_sfb)
1161 ltp->lag = get_bits(gb, 11);
1162 ltp->coef = ltp_coef[get_bits(gb, 3)];
1163 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1164 ltp->used[sfb] = get_bits1(gb);
1168 * Decode Individual Channel Stream info; reference: table 4.6.
1170 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1173 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1174 const int aot = m4ac->object_type;
1175 const int sampling_index = m4ac->sampling_index;
1176 if (aot != AOT_ER_AAC_ELD) {
1177 if (get_bits1(gb)) {
1178 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1179 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1180 return AVERROR_INVALIDDATA;
1182 ics->window_sequence[1] = ics->window_sequence[0];
1183 ics->window_sequence[0] = get_bits(gb, 2);
1184 if (aot == AOT_ER_AAC_LD &&
1185 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1186 av_log(ac->avctx, AV_LOG_ERROR,
1187 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1188 "window sequence %d found.\n", ics->window_sequence[0]);
1189 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1190 return AVERROR_INVALIDDATA;
1192 ics->use_kb_window[1] = ics->use_kb_window[0];
1193 ics->use_kb_window[0] = get_bits1(gb);
1195 ics->num_window_groups = 1;
1196 ics->group_len[0] = 1;
1197 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1199 ics->max_sfb = get_bits(gb, 4);
1200 for (i = 0; i < 7; i++) {
1201 if (get_bits1(gb)) {
1202 ics->group_len[ics->num_window_groups - 1]++;
1204 ics->num_window_groups++;
1205 ics->group_len[ics->num_window_groups - 1] = 1;
1208 ics->num_windows = 8;
1209 ics->swb_offset = ff_swb_offset_128[sampling_index];
1210 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1211 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
1212 ics->predictor_present = 0;
1214 ics->max_sfb = get_bits(gb, 6);
1215 ics->num_windows = 1;
1216 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1217 if (m4ac->frame_length_short) {
1218 ics->swb_offset = ff_swb_offset_480[sampling_index];
1219 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1220 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1222 ics->swb_offset = ff_swb_offset_512[sampling_index];
1223 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1224 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1226 if (!ics->num_swb || !ics->swb_offset)
1229 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1230 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1231 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1233 if (aot != AOT_ER_AAC_ELD) {
1234 ics->predictor_present = get_bits1(gb);
1235 ics->predictor_reset_group = 0;
1237 if (ics->predictor_present) {
1238 if (aot == AOT_AAC_MAIN) {
1239 if (decode_prediction(ac, ics, gb)) {
1240 return AVERROR_INVALIDDATA;
1242 } else if (aot == AOT_AAC_LC ||
1243 aot == AOT_ER_AAC_LC) {
1244 av_log(ac->avctx, AV_LOG_ERROR,
1245 "Prediction is not allowed in AAC-LC.\n");
1246 return AVERROR_INVALIDDATA;
1248 if (aot == AOT_ER_AAC_LD) {
1249 av_log(ac->avctx, AV_LOG_ERROR,
1250 "LTP in ER AAC LD not yet implemented.\n");
1251 return AVERROR_PATCHWELCOME;
1253 if ((ics->ltp.present = get_bits(gb, 1)))
1254 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1259 if (ics->max_sfb > ics->num_swb) {
1260 av_log(ac->avctx, AV_LOG_ERROR,
1261 "Number of scalefactor bands in group (%d) "
1262 "exceeds limit (%d).\n",
1263 ics->max_sfb, ics->num_swb);
1264 return AVERROR_INVALIDDATA;
1271 * Decode band types (section_data payload); reference: table 4.46.
1273 * @param band_type array of the used band type
1274 * @param band_type_run_end array of the last scalefactor band of a band type run
1276 * @return Returns error status. 0 - OK, !0 - error
1278 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1279 int band_type_run_end[120], GetBitContext *gb,
1280 IndividualChannelStream *ics)
1283 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1284 for (g = 0; g < ics->num_window_groups; g++) {
1286 while (k < ics->max_sfb) {
1287 uint8_t sect_end = k;
1289 int sect_band_type = get_bits(gb, 4);
1290 if (sect_band_type == 12) {
1291 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1292 return AVERROR_INVALIDDATA;
1295 sect_len_incr = get_bits(gb, bits);
1296 sect_end += sect_len_incr;
1297 if (get_bits_left(gb) < 0) {
1298 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1299 return AVERROR_INVALIDDATA;
1301 if (sect_end > ics->max_sfb) {
1302 av_log(ac->avctx, AV_LOG_ERROR,
1303 "Number of bands (%d) exceeds limit (%d).\n",
1304 sect_end, ics->max_sfb);
1305 return AVERROR_INVALIDDATA;
1307 } while (sect_len_incr == (1 << bits) - 1);
1308 for (; k < sect_end; k++) {
1309 band_type [idx] = sect_band_type;
1310 band_type_run_end[idx++] = sect_end;
1318 * Decode scalefactors; reference: table 4.47.
1320 * @param global_gain first scalefactor value as scalefactors are differentially coded
1321 * @param band_type array of the used band type
1322 * @param band_type_run_end array of the last scalefactor band of a band type run
1323 * @param sf array of scalefactors or intensity stereo positions
1325 * @return Returns error status. 0 - OK, !0 - error
1327 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1328 unsigned int global_gain,
1329 IndividualChannelStream *ics,
1330 enum BandType band_type[120],
1331 int band_type_run_end[120])
1334 int offset[3] = { global_gain, global_gain - 90, 0 };
1337 for (g = 0; g < ics->num_window_groups; g++) {
1338 for (i = 0; i < ics->max_sfb;) {
1339 int run_end = band_type_run_end[idx];
1340 if (band_type[idx] == ZERO_BT) {
1341 for (; i < run_end; i++, idx++)
1343 } else if ((band_type[idx] == INTENSITY_BT) ||
1344 (band_type[idx] == INTENSITY_BT2)) {
1345 for (; i < run_end; i++, idx++) {
1346 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1347 clipped_offset = av_clip(offset[2], -155, 100);
1348 if (offset[2] != clipped_offset) {
1349 avpriv_request_sample(ac->avctx,
1350 "If you heard an audible artifact, there may be a bug in the decoder. "
1351 "Clipped intensity stereo position (%d -> %d)",
1352 offset[2], clipped_offset);
1354 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1356 } else if (band_type[idx] == NOISE_BT) {
1357 for (; i < run_end; i++, idx++) {
1358 if (noise_flag-- > 0)
1359 offset[1] += get_bits(gb, 9) - 256;
1361 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1362 clipped_offset = av_clip(offset[1], -100, 155);
1363 if (offset[1] != clipped_offset) {
1364 avpriv_request_sample(ac->avctx,
1365 "If you heard an audible artifact, there may be a bug in the decoder. "
1366 "Clipped noise gain (%d -> %d)",
1367 offset[1], clipped_offset);
1369 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1372 for (; i < run_end; i++, idx++) {
1373 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1374 if (offset[0] > 255U) {
1375 av_log(ac->avctx, AV_LOG_ERROR,
1376 "Scalefactor (%d) out of range.\n", offset[0]);
1377 return AVERROR_INVALIDDATA;
1379 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1388 * Decode pulse data; reference: table 4.7.
1390 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1391 const uint16_t *swb_offset, int num_swb)
1394 pulse->num_pulse = get_bits(gb, 2) + 1;
1395 pulse_swb = get_bits(gb, 6);
1396 if (pulse_swb >= num_swb)
1398 pulse->pos[0] = swb_offset[pulse_swb];
1399 pulse->pos[0] += get_bits(gb, 5);
1400 if (pulse->pos[0] > 1023)
1402 pulse->amp[0] = get_bits(gb, 4);
1403 for (i = 1; i < pulse->num_pulse; i++) {
1404 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1405 if (pulse->pos[i] > 1023)
1407 pulse->amp[i] = get_bits(gb, 4);
1413 * Decode Temporal Noise Shaping data; reference: table 4.48.
1415 * @return Returns error status. 0 - OK, !0 - error
1417 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1418 GetBitContext *gb, const IndividualChannelStream *ics)
1420 int w, filt, i, coef_len, coef_res, coef_compress;
1421 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1422 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1423 for (w = 0; w < ics->num_windows; w++) {
1424 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1425 coef_res = get_bits1(gb);
1427 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1429 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1431 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1432 av_log(ac->avctx, AV_LOG_ERROR,
1433 "TNS filter order %d is greater than maximum %d.\n",
1434 tns->order[w][filt], tns_max_order);
1435 tns->order[w][filt] = 0;
1436 return AVERROR_INVALIDDATA;
1438 if (tns->order[w][filt]) {
1439 tns->direction[w][filt] = get_bits1(gb);
1440 coef_compress = get_bits1(gb);
1441 coef_len = coef_res + 3 - coef_compress;
1442 tmp2_idx = 2 * coef_compress + coef_res;
1444 for (i = 0; i < tns->order[w][filt]; i++)
1445 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1454 * Decode Mid/Side data; reference: table 4.54.
1456 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1457 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1458 * [3] reserved for scalable AAC
1460 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1464 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1465 if (ms_present == 1) {
1466 for (idx = 0; idx < max_idx; idx++)
1467 cpe->ms_mask[idx] = get_bits1(gb);
1468 } else if (ms_present == 2) {
1469 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1474 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1478 *dst++ = v[idx & 15] * s;
1479 *dst++ = v[idx>>4 & 15] * s;
1485 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1489 *dst++ = v[idx & 3] * s;
1490 *dst++ = v[idx>>2 & 3] * s;
1491 *dst++ = v[idx>>4 & 3] * s;
1492 *dst++ = v[idx>>6 & 3] * s;
1498 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1499 unsigned sign, const float *scale)
1501 union av_intfloat32 s0, s1;
1503 s0.f = s1.f = *scale;
1504 s0.i ^= sign >> 1 << 31;
1507 *dst++ = v[idx & 15] * s0.f;
1508 *dst++ = v[idx>>4 & 15] * s1.f;
1515 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1516 unsigned sign, const float *scale)
1518 unsigned nz = idx >> 12;
1519 union av_intfloat32 s = { .f = *scale };
1520 union av_intfloat32 t;
1522 t.i = s.i ^ (sign & 1U<<31);
1523 *dst++ = v[idx & 3] * t.f;
1525 sign <<= nz & 1; nz >>= 1;
1526 t.i = s.i ^ (sign & 1U<<31);
1527 *dst++ = v[idx>>2 & 3] * t.f;
1529 sign <<= nz & 1; nz >>= 1;
1530 t.i = s.i ^ (sign & 1U<<31);
1531 *dst++ = v[idx>>4 & 3] * t.f;
1534 t.i = s.i ^ (sign & 1U<<31);
1535 *dst++ = v[idx>>6 & 3] * t.f;
1542 * Decode spectral data; reference: table 4.50.
1543 * Dequantize and scale spectral data; reference: 4.6.3.3.
1545 * @param coef array of dequantized, scaled spectral data
1546 * @param sf array of scalefactors or intensity stereo positions
1547 * @param pulse_present set if pulses are present
1548 * @param pulse pointer to pulse data struct
1549 * @param band_type array of the used band type
1551 * @return Returns error status. 0 - OK, !0 - error
1553 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1554 GetBitContext *gb, const float sf[120],
1555 int pulse_present, const Pulse *pulse,
1556 const IndividualChannelStream *ics,
1557 enum BandType band_type[120])
1559 int i, k, g, idx = 0;
1560 const int c = 1024 / ics->num_windows;
1561 const uint16_t *offsets = ics->swb_offset;
1562 float *coef_base = coef;
1564 for (g = 0; g < ics->num_windows; g++)
1565 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1566 sizeof(float) * (c - offsets[ics->max_sfb]));
1568 for (g = 0; g < ics->num_window_groups; g++) {
1569 unsigned g_len = ics->group_len[g];
1571 for (i = 0; i < ics->max_sfb; i++, idx++) {
1572 const unsigned cbt_m1 = band_type[idx] - 1;
1573 float *cfo = coef + offsets[i];
1574 int off_len = offsets[i + 1] - offsets[i];
1577 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1578 for (group = 0; group < g_len; group++, cfo+=128) {
1579 memset(cfo, 0, off_len * sizeof(float));
1581 } else if (cbt_m1 == NOISE_BT - 1) {
1582 for (group = 0; group < g_len; group++, cfo+=128) {
1586 for (k = 0; k < off_len; k++) {
1587 ac->random_state = lcg_random(ac->random_state);
1588 cfo[k] = ac->random_state;
1591 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1592 scale = sf[idx] / sqrtf(band_energy);
1593 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1596 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1597 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1598 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1599 OPEN_READER(re, gb);
1601 switch (cbt_m1 >> 1) {
1603 for (group = 0; group < g_len; group++, cfo+=128) {
1611 UPDATE_CACHE(re, gb);
1612 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1613 cb_idx = cb_vector_idx[code];
1614 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1620 for (group = 0; group < g_len; group++, cfo+=128) {
1630 UPDATE_CACHE(re, gb);
1631 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1632 cb_idx = cb_vector_idx[code];
1633 nnz = cb_idx >> 8 & 15;
1634 bits = nnz ? GET_CACHE(re, gb) : 0;
1635 LAST_SKIP_BITS(re, gb, nnz);
1636 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1642 for (group = 0; group < g_len; group++, cfo+=128) {
1650 UPDATE_CACHE(re, gb);
1651 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1652 cb_idx = cb_vector_idx[code];
1653 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1660 for (group = 0; group < g_len; group++, cfo+=128) {
1670 UPDATE_CACHE(re, gb);
1671 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1672 cb_idx = cb_vector_idx[code];
1673 nnz = cb_idx >> 8 & 15;
1674 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1675 LAST_SKIP_BITS(re, gb, nnz);
1676 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1682 for (group = 0; group < g_len; group++, cfo+=128) {
1684 uint32_t *icf = (uint32_t *) cf;
1694 UPDATE_CACHE(re, gb);
1695 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1703 cb_idx = cb_vector_idx[code];
1706 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1707 LAST_SKIP_BITS(re, gb, nnz);
1709 for (j = 0; j < 2; j++) {
1713 /* The total length of escape_sequence must be < 22 bits according
1714 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1715 UPDATE_CACHE(re, gb);
1716 b = GET_CACHE(re, gb);
1717 b = 31 - av_log2(~b);
1720 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1721 return AVERROR_INVALIDDATA;
1724 SKIP_BITS(re, gb, b + 1);
1726 n = (1 << b) + SHOW_UBITS(re, gb, b);
1727 LAST_SKIP_BITS(re, gb, b);
1728 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1731 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1732 *icf++ = (bits & 1U<<31) | v;
1739 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1743 CLOSE_READER(re, gb);
1749 if (pulse_present) {
1751 for (i = 0; i < pulse->num_pulse; i++) {
1752 float co = coef_base[ pulse->pos[i] ];
1753 while (offsets[idx + 1] <= pulse->pos[i])
1755 if (band_type[idx] != NOISE_BT && sf[idx]) {
1756 float ico = -pulse->amp[i];
1759 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1761 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1768 static av_always_inline float flt16_round(float pf)
1770 union av_intfloat32 tmp;
1772 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1776 static av_always_inline float flt16_even(float pf)
1778 union av_intfloat32 tmp;
1780 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1784 static av_always_inline float flt16_trunc(float pf)
1786 union av_intfloat32 pun;
1788 pun.i &= 0xFFFF0000U;
1792 static av_always_inline void predict(PredictorState *ps, float *coef,
1795 const float a = 0.953125; // 61.0 / 64
1796 const float alpha = 0.90625; // 29.0 / 32
1800 float r0 = ps->r0, r1 = ps->r1;
1801 float cor0 = ps->cor0, cor1 = ps->cor1;
1802 float var0 = ps->var0, var1 = ps->var1;
1804 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1805 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1807 pv = flt16_round(k1 * r0 + k2 * r1);
1814 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1815 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1816 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1817 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1819 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1820 ps->r0 = flt16_trunc(a * e0);
1824 * Apply AAC-Main style frequency domain prediction.
1826 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1830 if (!sce->ics.predictor_initialized) {
1831 reset_all_predictors(sce->predictor_state);
1832 sce->ics.predictor_initialized = 1;
1835 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1837 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1839 for (k = sce->ics.swb_offset[sfb];
1840 k < sce->ics.swb_offset[sfb + 1];
1842 predict(&sce->predictor_state[k], &sce->coeffs[k],
1843 sce->ics.predictor_present &&
1844 sce->ics.prediction_used[sfb]);
1847 if (sce->ics.predictor_reset_group)
1848 reset_predictor_group(sce->predictor_state,
1849 sce->ics.predictor_reset_group);
1851 reset_all_predictors(sce->predictor_state);
1855 * Decode an individual_channel_stream payload; reference: table 4.44.
1857 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1858 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1860 * @return Returns error status. 0 - OK, !0 - error
1862 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1863 GetBitContext *gb, int common_window, int scale_flag)
1866 TemporalNoiseShaping *tns = &sce->tns;
1867 IndividualChannelStream *ics = &sce->ics;
1868 float *out = sce->coeffs;
1869 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1872 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1873 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1874 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1875 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1876 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1878 /* This assignment is to silence a GCC warning about the variable being used
1879 * uninitialized when in fact it always is.
1881 pulse.num_pulse = 0;
1883 global_gain = get_bits(gb, 8);
1885 if (!common_window && !scale_flag) {
1886 if (decode_ics_info(ac, ics, gb) < 0)
1887 return AVERROR_INVALIDDATA;
1890 if ((ret = decode_band_types(ac, sce->band_type,
1891 sce->band_type_run_end, gb, ics)) < 0)
1893 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1894 sce->band_type, sce->band_type_run_end)) < 0)
1899 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1900 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1901 av_log(ac->avctx, AV_LOG_ERROR,
1902 "Pulse tool not allowed in eight short sequence.\n");
1903 return AVERROR_INVALIDDATA;
1905 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1906 av_log(ac->avctx, AV_LOG_ERROR,
1907 "Pulse data corrupt or invalid.\n");
1908 return AVERROR_INVALIDDATA;
1911 tns->present = get_bits1(gb);
1912 if (tns->present && !er_syntax)
1913 if (decode_tns(ac, tns, gb, ics) < 0)
1914 return AVERROR_INVALIDDATA;
1915 if (!eld_syntax && get_bits1(gb)) {
1916 avpriv_request_sample(ac->avctx, "SSR");
1917 return AVERROR_PATCHWELCOME;
1919 // I see no textual basis in the spec for this occurring after SSR gain
1920 // control, but this is what both reference and real implementations do
1921 if (tns->present && er_syntax)
1922 if (decode_tns(ac, tns, gb, ics) < 0)
1923 return AVERROR_INVALIDDATA;
1926 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1927 &pulse, ics, sce->band_type) < 0)
1928 return AVERROR_INVALIDDATA;
1930 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1931 apply_prediction(ac, sce);
1937 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1939 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1941 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1942 float *ch0 = cpe->ch[0].coeffs;
1943 float *ch1 = cpe->ch[1].coeffs;
1944 int g, i, group, idx = 0;
1945 const uint16_t *offsets = ics->swb_offset;
1946 for (g = 0; g < ics->num_window_groups; g++) {
1947 for (i = 0; i < ics->max_sfb; i++, idx++) {
1948 if (cpe->ms_mask[idx] &&
1949 cpe->ch[0].band_type[idx] < NOISE_BT &&
1950 cpe->ch[1].band_type[idx] < NOISE_BT) {
1951 for (group = 0; group < ics->group_len[g]; group++) {
1952 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1953 ch1 + group * 128 + offsets[i],
1954 offsets[i+1] - offsets[i]);
1958 ch0 += ics->group_len[g] * 128;
1959 ch1 += ics->group_len[g] * 128;
1964 * intensity stereo decoding; reference: 4.6.8.2.3
1966 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1967 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1968 * [3] reserved for scalable AAC
1970 static void apply_intensity_stereo(AACContext *ac,
1971 ChannelElement *cpe, int ms_present)
1973 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1974 SingleChannelElement *sce1 = &cpe->ch[1];
1975 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1976 const uint16_t *offsets = ics->swb_offset;
1977 int g, group, i, idx = 0;
1980 for (g = 0; g < ics->num_window_groups; g++) {
1981 for (i = 0; i < ics->max_sfb;) {
1982 if (sce1->band_type[idx] == INTENSITY_BT ||
1983 sce1->band_type[idx] == INTENSITY_BT2) {
1984 const int bt_run_end = sce1->band_type_run_end[idx];
1985 for (; i < bt_run_end; i++, idx++) {
1986 c = -1 + 2 * (sce1->band_type[idx] - 14);
1988 c *= 1 - 2 * cpe->ms_mask[idx];
1989 scale = c * sce1->sf[idx];
1990 for (group = 0; group < ics->group_len[g]; group++)
1991 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1992 coef0 + group * 128 + offsets[i],
1994 offsets[i + 1] - offsets[i]);
1997 int bt_run_end = sce1->band_type_run_end[idx];
1998 idx += bt_run_end - i;
2002 coef0 += ics->group_len[g] * 128;
2003 coef1 += ics->group_len[g] * 128;
2008 * Decode a channel_pair_element; reference: table 4.4.
2010 * @return Returns error status. 0 - OK, !0 - error
2012 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2014 int i, ret, common_window, ms_present = 0;
2015 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2017 common_window = eld_syntax || get_bits1(gb);
2018 if (common_window) {
2019 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2020 return AVERROR_INVALIDDATA;
2021 i = cpe->ch[1].ics.use_kb_window[0];
2022 cpe->ch[1].ics = cpe->ch[0].ics;
2023 cpe->ch[1].ics.use_kb_window[1] = i;
2024 if (cpe->ch[1].ics.predictor_present &&
2025 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2026 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2027 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2028 ms_present = get_bits(gb, 2);
2029 if (ms_present == 3) {
2030 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2031 return AVERROR_INVALIDDATA;
2032 } else if (ms_present)
2033 decode_mid_side_stereo(cpe, gb, ms_present);
2035 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2037 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2040 if (common_window) {
2042 apply_mid_side_stereo(ac, cpe);
2043 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2044 apply_prediction(ac, &cpe->ch[0]);
2045 apply_prediction(ac, &cpe->ch[1]);
2049 apply_intensity_stereo(ac, cpe, ms_present);
2053 static const float cce_scale[] = {
2054 1.09050773266525765921, //2^(1/8)
2055 1.18920711500272106672, //2^(1/4)
2061 * Decode coupling_channel_element; reference: table 4.8.
2063 * @return Returns error status. 0 - OK, !0 - error
2065 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2071 SingleChannelElement *sce = &che->ch[0];
2072 ChannelCoupling *coup = &che->coup;
2074 coup->coupling_point = 2 * get_bits1(gb);
2075 coup->num_coupled = get_bits(gb, 3);
2076 for (c = 0; c <= coup->num_coupled; c++) {
2078 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2079 coup->id_select[c] = get_bits(gb, 4);
2080 if (coup->type[c] == TYPE_CPE) {
2081 coup->ch_select[c] = get_bits(gb, 2);
2082 if (coup->ch_select[c] == 3)
2085 coup->ch_select[c] = 2;
2087 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2089 sign = get_bits(gb, 1);
2090 scale = cce_scale[get_bits(gb, 2)];
2092 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2095 for (c = 0; c < num_gain; c++) {
2099 float gain_cache = 1.0;
2101 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2102 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2103 gain_cache = powf(scale, -gain);
2105 if (coup->coupling_point == AFTER_IMDCT) {
2106 coup->gain[c][0] = gain_cache;
2108 for (g = 0; g < sce->ics.num_window_groups; g++) {
2109 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2110 if (sce->band_type[idx] != ZERO_BT) {
2112 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2120 gain_cache = powf(scale, -t) * s;
2123 coup->gain[c][idx] = gain_cache;
2133 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2135 * @return Returns number of bytes consumed.
2137 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2141 int num_excl_chan = 0;
2144 for (i = 0; i < 7; i++)
2145 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2146 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2148 return num_excl_chan / 7;
2152 * Decode dynamic range information; reference: table 4.52.
2154 * @return Returns number of bytes consumed.
2156 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2160 int drc_num_bands = 1;
2163 /* pce_tag_present? */
2164 if (get_bits1(gb)) {
2165 che_drc->pce_instance_tag = get_bits(gb, 4);
2166 skip_bits(gb, 4); // tag_reserved_bits
2170 /* excluded_chns_present? */
2171 if (get_bits1(gb)) {
2172 n += decode_drc_channel_exclusions(che_drc, gb);
2175 /* drc_bands_present? */
2176 if (get_bits1(gb)) {
2177 che_drc->band_incr = get_bits(gb, 4);
2178 che_drc->interpolation_scheme = get_bits(gb, 4);
2180 drc_num_bands += che_drc->band_incr;
2181 for (i = 0; i < drc_num_bands; i++) {
2182 che_drc->band_top[i] = get_bits(gb, 8);
2187 /* prog_ref_level_present? */
2188 if (get_bits1(gb)) {
2189 che_drc->prog_ref_level = get_bits(gb, 7);
2190 skip_bits1(gb); // prog_ref_level_reserved_bits
2194 for (i = 0; i < drc_num_bands; i++) {
2195 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2196 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2204 * Decode extension data (incomplete); reference: table 4.51.
2206 * @param cnt length of TYPE_FIL syntactic element in bytes
2208 * @return Returns number of bytes consumed
2210 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2211 ChannelElement *che, enum RawDataBlockType elem_type)
2215 switch (get_bits(gb, 4)) { // extension type
2216 case EXT_SBR_DATA_CRC:
2220 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2222 } else if (!ac->oc[1].m4ac.sbr) {
2223 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2224 skip_bits_long(gb, 8 * cnt - 4);
2226 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2227 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2228 skip_bits_long(gb, 8 * cnt - 4);
2230 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2231 ac->oc[1].m4ac.sbr = 1;
2232 ac->oc[1].m4ac.ps = 1;
2233 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2234 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2235 ac->oc[1].status, 1);
2237 ac->oc[1].m4ac.sbr = 1;
2238 ac->avctx->profile = FF_PROFILE_AAC_HE;
2240 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2242 case EXT_DYNAMIC_RANGE:
2243 res = decode_dynamic_range(&ac->che_drc, gb);
2247 case EXT_DATA_ELEMENT:
2249 skip_bits_long(gb, 8 * cnt - 4);
2256 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2258 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2259 * @param coef spectral coefficients
2261 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2262 IndividualChannelStream *ics, int decode)
2264 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2266 int bottom, top, order, start, end, size, inc;
2267 float lpc[TNS_MAX_ORDER];
2268 float tmp[TNS_MAX_ORDER + 1];
2270 for (w = 0; w < ics->num_windows; w++) {
2271 bottom = ics->num_swb;
2272 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2274 bottom = FFMAX(0, top - tns->length[w][filt]);
2275 order = tns->order[w][filt];
2280 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2282 start = ics->swb_offset[FFMIN(bottom, mmm)];
2283 end = ics->swb_offset[FFMIN( top, mmm)];
2284 if ((size = end - start) <= 0)
2286 if (tns->direction[w][filt]) {
2296 for (m = 0; m < size; m++, start += inc)
2297 for (i = 1; i <= FFMIN(m, order); i++)
2298 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2301 for (m = 0; m < size; m++, start += inc) {
2302 tmp[0] = coef[start];
2303 for (i = 1; i <= FFMIN(m, order); i++)
2304 coef[start] += tmp[i] * lpc[i - 1];
2305 for (i = order; i > 0; i--)
2306 tmp[i] = tmp[i - 1];
2314 * Apply windowing and MDCT to obtain the spectral
2315 * coefficient from the predicted sample by LTP.
2317 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2318 float *in, IndividualChannelStream *ics)
2320 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2321 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2322 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2323 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2325 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2326 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2328 memset(in, 0, 448 * sizeof(float));
2329 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2331 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2332 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2334 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2335 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2337 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2341 * Apply the long term prediction
2343 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2345 const LongTermPrediction *ltp = &sce->ics.ltp;
2346 const uint16_t *offsets = sce->ics.swb_offset;
2349 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2350 float *predTime = sce->ret;
2351 float *predFreq = ac->buf_mdct;
2352 int16_t num_samples = 2048;
2354 if (ltp->lag < 1024)
2355 num_samples = ltp->lag + 1024;
2356 for (i = 0; i < num_samples; i++)
2357 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2358 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2360 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2362 if (sce->tns.present)
2363 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2365 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2367 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2368 sce->coeffs[i] += predFreq[i];
2373 * Update the LTP buffer for next frame
2375 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2377 IndividualChannelStream *ics = &sce->ics;
2378 float *saved = sce->saved;
2379 float *saved_ltp = sce->coeffs;
2380 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2381 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2384 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2385 memcpy(saved_ltp, saved, 512 * sizeof(float));
2386 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2387 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2388 for (i = 0; i < 64; i++)
2389 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2390 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2391 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2392 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2393 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2394 for (i = 0; i < 64; i++)
2395 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2396 } else { // LONG_STOP or ONLY_LONG
2397 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2398 for (i = 0; i < 512; i++)
2399 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2402 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2403 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2404 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2408 * Conduct IMDCT and windowing.
2410 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2412 IndividualChannelStream *ics = &sce->ics;
2413 float *in = sce->coeffs;
2414 float *out = sce->ret;
2415 float *saved = sce->saved;
2416 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2417 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2418 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2419 float *buf = ac->buf_mdct;
2420 float *temp = ac->temp;
2424 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2425 for (i = 0; i < 1024; i += 128)
2426 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2428 ac->mdct.imdct_half(&ac->mdct, buf, in);
2430 /* window overlapping
2431 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2432 * and long to short transitions are considered to be short to short
2433 * transitions. This leaves just two cases (long to long and short to short)
2434 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2436 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2437 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2438 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2440 memcpy( out, saved, 448 * sizeof(float));
2442 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2443 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2444 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2445 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2446 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2447 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2448 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2450 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2451 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2456 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2457 memcpy( saved, temp + 64, 64 * sizeof(float));
2458 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2459 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2460 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2461 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2462 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2463 memcpy( saved, buf + 512, 448 * sizeof(float));
2464 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2465 } else { // LONG_STOP or ONLY_LONG
2466 memcpy( saved, buf + 512, 512 * sizeof(float));
2470 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2472 IndividualChannelStream *ics = &sce->ics;
2473 float *in = sce->coeffs;
2474 float *out = sce->ret;
2475 float *saved = sce->saved;
2476 float *buf = ac->buf_mdct;
2479 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2481 // window overlapping
2482 if (ics->use_kb_window[1]) {
2483 // AAC LD uses a low overlap sine window instead of a KBD window
2484 memcpy(out, saved, 192 * sizeof(float));
2485 ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2486 memcpy( out + 320, buf + 64, 192 * sizeof(float));
2488 ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2492 memcpy(saved, buf + 256, 256 * sizeof(float));
2495 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2497 float *in = sce->coeffs;
2498 float *out = sce->ret;
2499 float *saved = sce->saved;
2500 float *buf = ac->buf_mdct;
2502 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2503 const int n2 = n >> 1;
2504 const int n4 = n >> 2;
2505 const float *const window = n == 480 ? ff_aac_eld_window_480 :
2506 ff_aac_eld_window_512;
2508 // Inverse transform, mapped to the conventional IMDCT by
2509 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2510 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2511 // Audio, Language and Image Processing, 2008. ICALIP 2008. International Conference on
2512 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2513 for (i = 0; i < n2; i+=2) {
2515 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2516 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2519 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
2521 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2522 for (i = 0; i < n; i+=2) {
2525 // Like with the regular IMDCT at this point we still have the middle half
2526 // of a transform but with even symmetry on the left and odd symmetry on
2529 // window overlapping
2530 // The spec says to use samples [0..511] but the reference decoder uses
2531 // samples [128..639].
2532 for (i = n4; i < n2; i ++) {
2533 out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2534 saved[ i + n2] * window[i + n - n4] +
2535 -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2536 -saved[2*n + n2 + i] * window[i + 3*n - n4];
2538 for (i = 0; i < n2; i ++) {
2539 out[n4 + i] = buf[i] * window[i + n2 - n4] +
2540 -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2541 -saved[ n + i] * window[i + n2 + 2*n - n4] +
2542 saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2544 for (i = 0; i < n4; i ++) {
2545 out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2546 -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2547 -saved[ n + n2 + i] * window[i + 3*n - n4];
2551 memmove(saved + n, saved, 2 * n * sizeof(float));
2552 memcpy( saved, buf, n * sizeof(float));
2556 * Apply dependent channel coupling (applied before IMDCT).
2558 * @param index index into coupling gain array
2560 static void apply_dependent_coupling(AACContext *ac,
2561 SingleChannelElement *target,
2562 ChannelElement *cce, int index)
2564 IndividualChannelStream *ics = &cce->ch[0].ics;
2565 const uint16_t *offsets = ics->swb_offset;
2566 float *dest = target->coeffs;
2567 const float *src = cce->ch[0].coeffs;
2568 int g, i, group, k, idx = 0;
2569 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2570 av_log(ac->avctx, AV_LOG_ERROR,
2571 "Dependent coupling is not supported together with LTP\n");
2574 for (g = 0; g < ics->num_window_groups; g++) {
2575 for (i = 0; i < ics->max_sfb; i++, idx++) {
2576 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2577 const float gain = cce->coup.gain[index][idx];
2578 for (group = 0; group < ics->group_len[g]; group++) {
2579 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2581 dest[group * 128 + k] += gain * src[group * 128 + k];
2586 dest += ics->group_len[g] * 128;
2587 src += ics->group_len[g] * 128;
2592 * Apply independent channel coupling (applied after IMDCT).
2594 * @param index index into coupling gain array
2596 static void apply_independent_coupling(AACContext *ac,
2597 SingleChannelElement *target,
2598 ChannelElement *cce, int index)
2601 const float gain = cce->coup.gain[index][0];
2602 const float *src = cce->ch[0].ret;
2603 float *dest = target->ret;
2604 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2606 for (i = 0; i < len; i++)
2607 dest[i] += gain * src[i];
2611 * channel coupling transformation interface
2613 * @param apply_coupling_method pointer to (in)dependent coupling function
2615 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2616 enum RawDataBlockType type, int elem_id,
2617 enum CouplingPoint coupling_point,
2618 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2622 for (i = 0; i < MAX_ELEM_ID; i++) {
2623 ChannelElement *cce = ac->che[TYPE_CCE][i];
2626 if (cce && cce->coup.coupling_point == coupling_point) {
2627 ChannelCoupling *coup = &cce->coup;
2629 for (c = 0; c <= coup->num_coupled; c++) {
2630 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2631 if (coup->ch_select[c] != 1) {
2632 apply_coupling_method(ac, &cc->ch[0], cce, index);
2633 if (coup->ch_select[c] != 0)
2636 if (coup->ch_select[c] != 2)
2637 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2639 index += 1 + (coup->ch_select[c] == 3);
2646 * Convert spectral data to float samples, applying all supported tools as appropriate.
2648 static void spectral_to_sample(AACContext *ac)
2651 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2652 switch (ac->oc[1].m4ac.object_type) {
2654 imdct_and_window = imdct_and_windowing_ld;
2656 case AOT_ER_AAC_ELD:
2657 imdct_and_window = imdct_and_windowing_eld;
2660 imdct_and_window = imdct_and_windowing;
2662 for (type = 3; type >= 0; type--) {
2663 for (i = 0; i < MAX_ELEM_ID; i++) {
2664 ChannelElement *che = ac->che[type][i];
2666 if (type <= TYPE_CPE)
2667 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2668 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2669 if (che->ch[0].ics.predictor_present) {
2670 if (che->ch[0].ics.ltp.present)
2671 apply_ltp(ac, &che->ch[0]);
2672 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2673 apply_ltp(ac, &che->ch[1]);
2676 if (che->ch[0].tns.present)
2677 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2678 if (che->ch[1].tns.present)
2679 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2680 if (type <= TYPE_CPE)
2681 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2682 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2683 imdct_and_window(ac, &che->ch[0]);
2684 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2685 update_ltp(ac, &che->ch[0]);
2686 if (type == TYPE_CPE) {
2687 imdct_and_window(ac, &che->ch[1]);
2688 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2689 update_ltp(ac, &che->ch[1]);
2691 if (ac->oc[1].m4ac.sbr > 0) {
2692 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2695 if (type <= TYPE_CCE)
2696 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2702 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2705 AACADTSHeaderInfo hdr_info;
2706 uint8_t layout_map[MAX_ELEM_ID*4][3];
2707 int layout_map_tags, ret;
2709 size = avpriv_aac_parse_header(gb, &hdr_info);
2711 if (hdr_info.num_aac_frames != 1) {
2712 avpriv_report_missing_feature(ac->avctx,
2713 "More than one AAC RDB per ADTS frame");
2714 return AVERROR_PATCHWELCOME;
2716 push_output_configuration(ac);
2717 if (hdr_info.chan_config) {
2718 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2719 if ((ret = set_default_channel_config(ac->avctx,
2722 hdr_info.chan_config)) < 0)
2724 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2725 FFMAX(ac->oc[1].status,
2726 OC_TRIAL_FRAME), 0)) < 0)
2729 ac->oc[1].m4ac.chan_config = 0;
2731 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2732 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2733 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2734 ac->oc[1].m4ac.frame_length_short = 0;
2735 if (ac->oc[0].status != OC_LOCKED ||
2736 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2737 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2738 ac->oc[1].m4ac.sbr = -1;
2739 ac->oc[1].m4ac.ps = -1;
2741 if (!hdr_info.crc_absent)
2747 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2748 int *got_frame_ptr, GetBitContext *gb)
2750 AACContext *ac = avctx->priv_data;
2751 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
2752 ChannelElement *che;
2754 int samples = m4ac->frame_length_short ? 960 : 1024;
2755 int chan_config = m4ac->chan_config;
2756 int aot = m4ac->object_type;
2758 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2763 if ((err = frame_configure_elements(avctx)) < 0)
2766 // The FF_PROFILE_AAC_* defines are all object_type - 1
2767 // This may lead to an undefined profile being signaled
2768 ac->avctx->profile = aot - 1;
2770 ac->tags_mapped = 0;
2772 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
2773 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2775 return AVERROR_INVALIDDATA;
2777 for (i = 0; i < tags_per_config[chan_config]; i++) {
2778 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2779 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2780 if (!(che=get_che(ac, elem_type, elem_id))) {
2781 av_log(ac->avctx, AV_LOG_ERROR,
2782 "channel element %d.%d is not allocated\n",
2783 elem_type, elem_id);
2784 return AVERROR_INVALIDDATA;
2786 if (aot != AOT_ER_AAC_ELD)
2788 switch (elem_type) {
2790 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2793 err = decode_cpe(ac, gb, che);
2796 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2803 spectral_to_sample(ac);
2805 ac->frame->nb_samples = samples;
2806 ac->frame->sample_rate = avctx->sample_rate;
2809 skip_bits_long(gb, get_bits_left(gb));
2813 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2814 int *got_frame_ptr, GetBitContext *gb)
2816 AACContext *ac = avctx->priv_data;
2817 ChannelElement *che = NULL, *che_prev = NULL;
2818 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2820 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2824 if (show_bits(gb, 12) == 0xfff) {
2825 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2826 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2829 if (ac->oc[1].m4ac.sampling_index > 12) {
2830 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2831 err = AVERROR_INVALIDDATA;
2836 if (avctx->channels)
2837 if ((err = frame_configure_elements(avctx)) < 0)
2840 // The FF_PROFILE_AAC_* defines are all object_type - 1
2841 // This may lead to an undefined profile being signaled
2842 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2844 ac->tags_mapped = 0;
2846 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2847 elem_id = get_bits(gb, 4);
2849 if (!avctx->channels && elem_type != TYPE_PCE) {
2850 err = AVERROR_INVALIDDATA;
2854 if (elem_type < TYPE_DSE) {
2855 if (!(che=get_che(ac, elem_type, elem_id))) {
2856 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2857 elem_type, elem_id);
2858 err = AVERROR_INVALIDDATA;
2864 switch (elem_type) {
2867 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2872 err = decode_cpe(ac, gb, che);
2877 err = decode_cce(ac, gb, che);
2881 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2886 err = skip_data_stream_element(ac, gb);
2890 uint8_t layout_map[MAX_ELEM_ID*4][3];
2892 push_output_configuration(ac);
2893 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2899 av_log(avctx, AV_LOG_ERROR,
2900 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2901 pop_output_configuration(ac);
2903 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2911 elem_id += get_bits(gb, 8) - 1;
2912 if (get_bits_left(gb) < 8 * elem_id) {
2913 av_log(avctx, AV_LOG_ERROR, overread_err);
2914 err = AVERROR_INVALIDDATA;
2918 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2919 err = 0; /* FIXME */
2923 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2928 elem_type_prev = elem_type;
2933 if (get_bits_left(gb) < 3) {
2934 av_log(avctx, AV_LOG_ERROR, overread_err);
2935 err = AVERROR_INVALIDDATA;
2940 if (!avctx->channels) {
2945 spectral_to_sample(ac);
2947 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2948 samples <<= multiplier;
2950 if (ac->oc[1].status && audio_found) {
2951 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2952 avctx->frame_size = samples;
2953 ac->oc[1].status = OC_LOCKED;
2957 ac->frame->nb_samples = samples;
2958 ac->frame->sample_rate = avctx->sample_rate;
2960 *got_frame_ptr = !!samples;
2964 pop_output_configuration(ac);
2968 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2969 int *got_frame_ptr, AVPacket *avpkt)
2971 AACContext *ac = avctx->priv_data;
2972 const uint8_t *buf = avpkt->data;
2973 int buf_size = avpkt->size;
2978 int new_extradata_size;
2979 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2980 AV_PKT_DATA_NEW_EXTRADATA,
2981 &new_extradata_size);
2983 if (new_extradata) {
2984 av_free(avctx->extradata);
2985 avctx->extradata = av_mallocz(new_extradata_size +
2986 AV_INPUT_BUFFER_PADDING_SIZE);
2987 if (!avctx->extradata)
2988 return AVERROR(ENOMEM);
2989 avctx->extradata_size = new_extradata_size;
2990 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2991 push_output_configuration(ac);
2992 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2994 avctx->extradata_size*8, 1) < 0) {
2995 pop_output_configuration(ac);
2996 return AVERROR_INVALIDDATA;
3000 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3003 switch (ac->oc[1].m4ac.object_type) {
3005 case AOT_ER_AAC_LTP:
3007 case AOT_ER_AAC_ELD:
3008 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3011 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb);
3016 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3017 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3018 if (buf[buf_offset])
3021 return buf_size > buf_offset ? buf_consumed : buf_size;
3024 static av_cold int aac_decode_close(AVCodecContext *avctx)
3026 AACContext *ac = avctx->priv_data;
3029 for (i = 0; i < MAX_ELEM_ID; i++) {
3030 for (type = 0; type < 4; type++) {
3031 if (ac->che[type][i])
3032 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3033 av_freep(&ac->che[type][i]);
3037 ff_mdct_end(&ac->mdct);
3038 ff_mdct_end(&ac->mdct_small);
3039 ff_mdct_end(&ac->mdct_ld);
3040 ff_mdct_end(&ac->mdct_ltp);
3041 ff_imdct15_uninit(&ac->mdct480);
3046 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
3048 struct LATMContext {
3049 AACContext aac_ctx; ///< containing AACContext
3050 int initialized; ///< initialized after a valid extradata was seen
3053 int audio_mux_version_A; ///< LATM syntax version
3054 int frame_length_type; ///< 0/1 variable/fixed frame length
3055 int frame_length; ///< frame length for fixed frame length
3058 static inline uint32_t latm_get_value(GetBitContext *b)
3060 int length = get_bits(b, 2);
3062 return get_bits_long(b, (length+1)*8);
3065 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
3066 GetBitContext *gb, int asclen)
3068 AACContext *ac = &latmctx->aac_ctx;
3069 AVCodecContext *avctx = ac->avctx;
3070 MPEG4AudioConfig m4ac = { 0 };
3071 int config_start_bit = get_bits_count(gb);
3072 int sync_extension = 0;
3073 int bits_consumed, esize;
3077 asclen = FFMIN(asclen, get_bits_left(gb));
3079 asclen = get_bits_left(gb);
3081 if (config_start_bit % 8) {
3082 avpriv_request_sample(latmctx->aac_ctx.avctx,
3083 "Non-byte-aligned audio-specific config");
3084 return AVERROR_PATCHWELCOME;
3087 return AVERROR_INVALIDDATA;
3088 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3089 gb->buffer + (config_start_bit / 8),
3090 asclen, sync_extension);
3092 if (bits_consumed < 0)
3093 return AVERROR_INVALIDDATA;
3095 if (!latmctx->initialized ||
3096 ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3097 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3099 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3100 latmctx->initialized = 0;
3102 esize = (bits_consumed+7) / 8;
3104 if (avctx->extradata_size < esize) {
3105 av_free(avctx->extradata);
3106 avctx->extradata = av_malloc(esize + AV_INPUT_BUFFER_PADDING_SIZE);
3107 if (!avctx->extradata)
3108 return AVERROR(ENOMEM);
3111 avctx->extradata_size = esize;
3112 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3113 memset(avctx->extradata+esize, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3115 skip_bits_long(gb, bits_consumed);
3117 return bits_consumed;
3120 static int read_stream_mux_config(struct LATMContext *latmctx,
3123 int ret, audio_mux_version = get_bits(gb, 1);
3125 latmctx->audio_mux_version_A = 0;
3126 if (audio_mux_version)
3127 latmctx->audio_mux_version_A = get_bits(gb, 1);
3129 if (!latmctx->audio_mux_version_A) {
3131 if (audio_mux_version)
3132 latm_get_value(gb); // taraFullness
3134 skip_bits(gb, 1); // allStreamSameTimeFraming
3135 skip_bits(gb, 6); // numSubFrames
3137 if (get_bits(gb, 4)) { // numPrograms
3138 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3139 return AVERROR_PATCHWELCOME;
3142 // for each program (which there is only on in DVB)
3144 // for each layer (which there is only on in DVB)
3145 if (get_bits(gb, 3)) { // numLayer
3146 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3147 return AVERROR_PATCHWELCOME;
3150 // for all but first stream: use_same_config = get_bits(gb, 1);
3151 if (!audio_mux_version) {
3152 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3155 int ascLen = latm_get_value(gb);
3156 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3159 skip_bits_long(gb, ascLen);
3162 latmctx->frame_length_type = get_bits(gb, 3);
3163 switch (latmctx->frame_length_type) {
3165 skip_bits(gb, 8); // latmBufferFullness
3168 latmctx->frame_length = get_bits(gb, 9);
3173 skip_bits(gb, 6); // CELP frame length table index
3177 skip_bits(gb, 1); // HVXC frame length table index
3181 if (get_bits(gb, 1)) { // other data
3182 if (audio_mux_version) {
3183 latm_get_value(gb); // other_data_bits
3187 esc = get_bits(gb, 1);
3193 if (get_bits(gb, 1)) // crc present
3194 skip_bits(gb, 8); // config_crc
3200 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3204 if (ctx->frame_length_type == 0) {
3205 int mux_slot_length = 0;
3207 tmp = get_bits(gb, 8);
3208 mux_slot_length += tmp;
3209 } while (tmp == 255);
3210 return mux_slot_length;
3211 } else if (ctx->frame_length_type == 1) {
3212 return ctx->frame_length;
3213 } else if (ctx->frame_length_type == 3 ||
3214 ctx->frame_length_type == 5 ||
3215 ctx->frame_length_type == 7) {
3216 skip_bits(gb, 2); // mux_slot_length_coded
3221 static int read_audio_mux_element(struct LATMContext *latmctx,
3225 uint8_t use_same_mux = get_bits(gb, 1);
3226 if (!use_same_mux) {
3227 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3229 } else if (!latmctx->aac_ctx.avctx->extradata) {
3230 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3231 "no decoder config found\n");
3232 return AVERROR(EAGAIN);
3234 if (latmctx->audio_mux_version_A == 0) {
3235 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3236 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3237 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3238 return AVERROR_INVALIDDATA;
3239 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3240 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3241 "frame length mismatch %d << %d\n",
3242 mux_slot_length_bytes * 8, get_bits_left(gb));
3243 return AVERROR_INVALIDDATA;
3250 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3251 int *got_frame_ptr, AVPacket *avpkt)
3253 struct LATMContext *latmctx = avctx->priv_data;
3257 if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
3260 // check for LOAS sync word
3261 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3262 return AVERROR_INVALIDDATA;
3264 muxlength = get_bits(&gb, 13) + 3;
3265 // not enough data, the parser should have sorted this
3266 if (muxlength > avpkt->size)
3267 return AVERROR_INVALIDDATA;
3269 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3272 if (!latmctx->initialized) {
3273 if (!avctx->extradata) {
3277 push_output_configuration(&latmctx->aac_ctx);
3278 if ((err = decode_audio_specific_config(
3279 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3280 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3281 pop_output_configuration(&latmctx->aac_ctx);
3284 latmctx->initialized = 1;
3288 if (show_bits(&gb, 12) == 0xfff) {
3289 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3290 "ADTS header detected, probably as result of configuration "
3292 return AVERROR_INVALIDDATA;
3295 switch (latmctx->aac_ctx.oc[1].m4ac.object_type) {
3297 case AOT_ER_AAC_LTP:
3299 case AOT_ER_AAC_ELD:
3300 err = aac_decode_er_frame(avctx, out, got_frame_ptr, &gb);
3303 err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb);
3311 static av_cold int latm_decode_init(AVCodecContext *avctx)
3313 struct LATMContext *latmctx = avctx->priv_data;
3314 int ret = aac_decode_init(avctx);
3316 if (avctx->extradata_size > 0)
3317 latmctx->initialized = !ret;
3323 AVCodec ff_aac_decoder = {
3325 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3326 .type = AVMEDIA_TYPE_AUDIO,
3327 .id = AV_CODEC_ID_AAC,
3328 .priv_data_size = sizeof(AACContext),
3329 .init = aac_decode_init,
3330 .close = aac_decode_close,
3331 .decode = aac_decode_frame,
3332 .sample_fmts = (const enum AVSampleFormat[]) {
3333 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3335 .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
3336 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
3337 .channel_layouts = aac_channel_layout,
3341 Note: This decoder filter is intended to decode LATM streams transferred
3342 in MPEG transport streams which only contain one program.
3343 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3345 AVCodec ff_aac_latm_decoder = {
3347 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3348 .type = AVMEDIA_TYPE_AUDIO,
3349 .id = AV_CODEC_ID_AAC_LATM,
3350 .priv_data_size = sizeof(struct LATMContext),
3351 .init = latm_decode_init,
3352 .close = aac_decode_close,
3353 .decode = latm_decode_frame,
3354 .sample_fmts = (const enum AVSampleFormat[]) {
3355 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3357 .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
3358 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
3359 .channel_layouts = aac_channel_layout,