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 FFmpeg.
13 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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"
84 #include "libavutil/opt.h"
89 #include "fmtconvert.h"
96 #include "aacdectab.h"
97 #include "cbrt_tablegen.h"
100 #include "mpeg4audio.h"
101 #include "aacadtsdec.h"
102 #include "libavutil/intfloat.h"
110 # include "arm/aac.h"
112 # include "mips/aacdec_mips.h"
115 static VLC vlc_scalefactors;
116 static VLC vlc_spectral[11];
118 static int output_configure(AACContext *ac,
119 uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
120 enum OCStatus oc_type, int get_new_frame);
122 #define overread_err "Input buffer exhausted before END element found\n"
124 static int count_channels(uint8_t (*layout)[3], int tags)
127 for (i = 0; i < tags; i++) {
128 int syn_ele = layout[i][0];
129 int pos = layout[i][2];
130 sum += (1 + (syn_ele == TYPE_CPE)) *
131 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
137 * Check for the channel element in the current channel position configuration.
138 * If it exists, make sure the appropriate element is allocated and map the
139 * channel order to match the internal FFmpeg channel layout.
141 * @param che_pos current channel position configuration
142 * @param type channel element type
143 * @param id channel element id
144 * @param channels count of the number of channels in the configuration
146 * @return Returns error status. 0 - OK, !0 - error
148 static av_cold int che_configure(AACContext *ac,
149 enum ChannelPosition che_pos,
150 int type, int id, int *channels)
152 if (*channels >= MAX_CHANNELS)
153 return AVERROR_INVALIDDATA;
155 if (!ac->che[type][id]) {
156 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
157 return AVERROR(ENOMEM);
158 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
160 if (type != TYPE_CCE) {
161 if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
162 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
163 return AVERROR_INVALIDDATA;
165 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
166 if (type == TYPE_CPE ||
167 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
168 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
172 if (ac->che[type][id])
173 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
174 av_freep(&ac->che[type][id]);
179 static int frame_configure_elements(AVCodecContext *avctx)
181 AACContext *ac = avctx->priv_data;
182 int type, id, ch, ret;
184 /* set channel pointers to internal buffers by default */
185 for (type = 0; type < 4; type++) {
186 for (id = 0; id < MAX_ELEM_ID; id++) {
187 ChannelElement *che = ac->che[type][id];
189 che->ch[0].ret = che->ch[0].ret_buf;
190 che->ch[1].ret = che->ch[1].ret_buf;
195 /* get output buffer */
196 av_frame_unref(ac->frame);
197 if (!avctx->channels)
200 ac->frame->nb_samples = 2048;
201 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
204 /* map output channel pointers to AVFrame data */
205 for (ch = 0; ch < avctx->channels; ch++) {
206 if (ac->output_element[ch])
207 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
213 struct elem_to_channel {
214 uint64_t av_position;
217 uint8_t aac_position;
220 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
221 uint8_t (*layout_map)[3], int offset, uint64_t left,
222 uint64_t right, int pos)
224 if (layout_map[offset][0] == TYPE_CPE) {
225 e2c_vec[offset] = (struct elem_to_channel) {
226 .av_position = left | right,
228 .elem_id = layout_map[offset][1],
233 e2c_vec[offset] = (struct elem_to_channel) {
236 .elem_id = layout_map[offset][1],
239 e2c_vec[offset + 1] = (struct elem_to_channel) {
240 .av_position = right,
242 .elem_id = layout_map[offset + 1][1],
249 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
252 int num_pos_channels = 0;
256 for (i = *current; i < tags; i++) {
257 if (layout_map[i][2] != pos)
259 if (layout_map[i][0] == TYPE_CPE) {
261 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
267 num_pos_channels += 2;
275 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
278 return num_pos_channels;
281 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
283 int i, n, total_non_cc_elements;
284 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
285 int num_front_channels, num_side_channels, num_back_channels;
288 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
293 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
294 if (num_front_channels < 0)
297 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
298 if (num_side_channels < 0)
301 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
302 if (num_back_channels < 0)
306 if (num_front_channels & 1) {
307 e2c_vec[i] = (struct elem_to_channel) {
308 .av_position = AV_CH_FRONT_CENTER,
310 .elem_id = layout_map[i][1],
311 .aac_position = AAC_CHANNEL_FRONT
314 num_front_channels--;
316 if (num_front_channels >= 4) {
317 i += assign_pair(e2c_vec, layout_map, i,
318 AV_CH_FRONT_LEFT_OF_CENTER,
319 AV_CH_FRONT_RIGHT_OF_CENTER,
321 num_front_channels -= 2;
323 if (num_front_channels >= 2) {
324 i += assign_pair(e2c_vec, layout_map, i,
328 num_front_channels -= 2;
330 while (num_front_channels >= 2) {
331 i += assign_pair(e2c_vec, layout_map, i,
335 num_front_channels -= 2;
338 if (num_side_channels >= 2) {
339 i += assign_pair(e2c_vec, layout_map, i,
343 num_side_channels -= 2;
345 while (num_side_channels >= 2) {
346 i += assign_pair(e2c_vec, layout_map, i,
350 num_side_channels -= 2;
353 while (num_back_channels >= 4) {
354 i += assign_pair(e2c_vec, layout_map, i,
358 num_back_channels -= 2;
360 if (num_back_channels >= 2) {
361 i += assign_pair(e2c_vec, layout_map, i,
365 num_back_channels -= 2;
367 if (num_back_channels) {
368 e2c_vec[i] = (struct elem_to_channel) {
369 .av_position = AV_CH_BACK_CENTER,
371 .elem_id = layout_map[i][1],
372 .aac_position = AAC_CHANNEL_BACK
378 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
379 e2c_vec[i] = (struct elem_to_channel) {
380 .av_position = AV_CH_LOW_FREQUENCY,
382 .elem_id = layout_map[i][1],
383 .aac_position = AAC_CHANNEL_LFE
387 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
388 e2c_vec[i] = (struct elem_to_channel) {
389 .av_position = UINT64_MAX,
391 .elem_id = layout_map[i][1],
392 .aac_position = AAC_CHANNEL_LFE
397 // Must choose a stable sort
398 total_non_cc_elements = n = i;
401 for (i = 1; i < n; i++)
402 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
403 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
410 for (i = 0; i < total_non_cc_elements; i++) {
411 layout_map[i][0] = e2c_vec[i].syn_ele;
412 layout_map[i][1] = e2c_vec[i].elem_id;
413 layout_map[i][2] = e2c_vec[i].aac_position;
414 if (e2c_vec[i].av_position != UINT64_MAX) {
415 layout |= e2c_vec[i].av_position;
423 * Save current output configuration if and only if it has been locked.
425 static void push_output_configuration(AACContext *ac) {
426 if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
427 ac->oc[0] = ac->oc[1];
429 ac->oc[1].status = OC_NONE;
433 * Restore the previous output configuration if and only if the current
434 * configuration is unlocked.
436 static void pop_output_configuration(AACContext *ac) {
437 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
438 ac->oc[1] = ac->oc[0];
439 ac->avctx->channels = ac->oc[1].channels;
440 ac->avctx->channel_layout = ac->oc[1].channel_layout;
441 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
442 ac->oc[1].status, 0);
447 * Configure output channel order based on the current program
448 * configuration element.
450 * @return Returns error status. 0 - OK, !0 - error
452 static int output_configure(AACContext *ac,
453 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
454 enum OCStatus oc_type, int get_new_frame)
456 AVCodecContext *avctx = ac->avctx;
457 int i, channels = 0, ret;
460 if (ac->oc[1].layout_map != layout_map) {
461 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
462 ac->oc[1].layout_map_tags = tags;
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 position = layout_map[i][2];
473 // Allocate or free elements depending on if they are in the
474 // current program configuration.
475 ret = che_configure(ac, position, type, id, &channels);
479 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
480 if (layout == AV_CH_FRONT_CENTER) {
481 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
487 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
488 if (layout) avctx->channel_layout = layout;
489 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)
501 static void flush(AVCodecContext *avctx)
503 AACContext *ac= avctx->priv_data;
506 for (type = 3; type >= 0; type--) {
507 for (i = 0; i < MAX_ELEM_ID; i++) {
508 ChannelElement *che = ac->che[type][i];
510 for (j = 0; j <= 1; j++) {
511 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
519 * Set up channel positions based on a default channel configuration
520 * as specified in table 1.17.
522 * @return Returns error status. 0 - OK, !0 - error
524 static int set_default_channel_config(AVCodecContext *avctx,
525 uint8_t (*layout_map)[3],
529 if (channel_config < 1 || channel_config > 7) {
530 av_log(avctx, AV_LOG_ERROR,
531 "invalid default channel configuration (%d)\n",
533 return AVERROR_INVALIDDATA;
535 *tags = tags_per_config[channel_config];
536 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
537 *tags * sizeof(*layout_map));
541 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
543 /* For PCE based channel configurations map the channels solely based
545 if (!ac->oc[1].m4ac.chan_config) {
546 return ac->tag_che_map[type][elem_id];
548 // Allow single CPE stereo files to be signalled with mono configuration.
549 if (!ac->tags_mapped && type == TYPE_CPE &&
550 ac->oc[1].m4ac.chan_config == 1) {
551 uint8_t layout_map[MAX_ELEM_ID*4][3];
553 push_output_configuration(ac);
555 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
557 if (set_default_channel_config(ac->avctx, layout_map,
558 &layout_map_tags, 2) < 0)
560 if (output_configure(ac, layout_map, layout_map_tags,
561 OC_TRIAL_FRAME, 1) < 0)
564 ac->oc[1].m4ac.chan_config = 2;
565 ac->oc[1].m4ac.ps = 0;
568 if (!ac->tags_mapped && type == TYPE_SCE &&
569 ac->oc[1].m4ac.chan_config == 2) {
570 uint8_t layout_map[MAX_ELEM_ID * 4][3];
572 push_output_configuration(ac);
574 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
576 if (set_default_channel_config(ac->avctx, layout_map,
577 &layout_map_tags, 1) < 0)
579 if (output_configure(ac, layout_map, layout_map_tags,
580 OC_TRIAL_FRAME, 1) < 0)
583 ac->oc[1].m4ac.chan_config = 1;
584 if (ac->oc[1].m4ac.sbr)
585 ac->oc[1].m4ac.ps = -1;
587 /* For indexed channel configurations map the channels solely based
589 switch (ac->oc[1].m4ac.chan_config) {
591 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
593 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
596 /* Some streams incorrectly code 5.1 audio as
597 * SCE[0] CPE[0] CPE[1] SCE[1]
599 * SCE[0] CPE[0] CPE[1] LFE[0].
600 * If we seem to have encountered such a stream, transfer
601 * the LFE[0] element to the SCE[1]'s mapping */
602 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
604 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
607 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
609 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
612 if (ac->tags_mapped == 2 &&
613 ac->oc[1].m4ac.chan_config == 4 &&
616 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
620 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
623 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
624 } else if (ac->oc[1].m4ac.chan_config == 2) {
628 if (!ac->tags_mapped && type == TYPE_SCE) {
630 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
638 * Decode an array of 4 bit element IDs, optionally interleaved with a
639 * stereo/mono switching bit.
641 * @param type speaker type/position for these channels
643 static void decode_channel_map(uint8_t layout_map[][3],
644 enum ChannelPosition type,
645 GetBitContext *gb, int n)
648 enum RawDataBlockType syn_ele;
650 case AAC_CHANNEL_FRONT:
651 case AAC_CHANNEL_BACK:
652 case AAC_CHANNEL_SIDE:
653 syn_ele = get_bits1(gb);
659 case AAC_CHANNEL_LFE:
665 layout_map[0][0] = syn_ele;
666 layout_map[0][1] = get_bits(gb, 4);
667 layout_map[0][2] = type;
673 * Decode program configuration element; reference: table 4.2.
675 * @return Returns error status. 0 - OK, !0 - error
677 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
678 uint8_t (*layout_map)[3],
681 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
686 skip_bits(gb, 2); // object_type
688 sampling_index = get_bits(gb, 4);
689 if (m4ac->sampling_index != sampling_index)
690 av_log(avctx, AV_LOG_WARNING,
691 "Sample rate index in program config element does not "
692 "match the sample rate index configured by the container.\n");
694 num_front = get_bits(gb, 4);
695 num_side = get_bits(gb, 4);
696 num_back = get_bits(gb, 4);
697 num_lfe = get_bits(gb, 2);
698 num_assoc_data = get_bits(gb, 3);
699 num_cc = get_bits(gb, 4);
702 skip_bits(gb, 4); // mono_mixdown_tag
704 skip_bits(gb, 4); // stereo_mixdown_tag
707 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
709 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
710 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
713 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
715 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
717 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
719 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
722 skip_bits_long(gb, 4 * num_assoc_data);
724 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
729 /* comment field, first byte is length */
730 comment_len = get_bits(gb, 8) * 8;
731 if (get_bits_left(gb) < comment_len) {
732 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
733 return AVERROR_INVALIDDATA;
735 skip_bits_long(gb, comment_len);
740 * Decode GA "General Audio" specific configuration; reference: table 4.1.
742 * @param ac pointer to AACContext, may be null
743 * @param avctx pointer to AVCCodecContext, used for logging
745 * @return Returns error status. 0 - OK, !0 - error
747 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
749 MPEG4AudioConfig *m4ac,
752 int extension_flag, ret, ep_config, res_flags;
753 uint8_t layout_map[MAX_ELEM_ID*4][3];
756 if (get_bits1(gb)) { // frameLengthFlag
757 avpriv_request_sample(avctx, "960/120 MDCT window");
758 return AVERROR_PATCHWELCOME;
761 if (get_bits1(gb)) // dependsOnCoreCoder
762 skip_bits(gb, 14); // coreCoderDelay
763 extension_flag = get_bits1(gb);
765 if (m4ac->object_type == AOT_AAC_SCALABLE ||
766 m4ac->object_type == AOT_ER_AAC_SCALABLE)
767 skip_bits(gb, 3); // layerNr
769 if (channel_config == 0) {
770 skip_bits(gb, 4); // element_instance_tag
771 tags = decode_pce(avctx, m4ac, layout_map, gb);
775 if ((ret = set_default_channel_config(avctx, layout_map,
776 &tags, channel_config)))
780 if (count_channels(layout_map, tags) > 1) {
782 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
785 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
788 if (extension_flag) {
789 switch (m4ac->object_type) {
791 skip_bits(gb, 5); // numOfSubFrame
792 skip_bits(gb, 11); // layer_length
796 case AOT_ER_AAC_SCALABLE:
798 res_flags = get_bits(gb, 3);
800 avpriv_report_missing_feature(avctx,
801 "AAC data resilience (flags %x)",
803 return AVERROR_PATCHWELCOME;
807 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
809 switch (m4ac->object_type) {
812 case AOT_ER_AAC_SCALABLE:
814 ep_config = get_bits(gb, 2);
816 avpriv_report_missing_feature(avctx,
817 "epConfig %d", ep_config);
818 return AVERROR_PATCHWELCOME;
824 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
826 MPEG4AudioConfig *m4ac,
829 int ret, ep_config, res_flags;
830 uint8_t layout_map[MAX_ELEM_ID*4][3];
832 const int ELDEXT_TERM = 0;
837 if (get_bits1(gb)) { // frameLengthFlag
838 avpriv_request_sample(avctx, "960/120 MDCT window");
839 return AVERROR_PATCHWELCOME;
842 res_flags = get_bits(gb, 3);
844 avpriv_report_missing_feature(avctx,
845 "AAC data resilience (flags %x)",
847 return AVERROR_PATCHWELCOME;
850 if (get_bits1(gb)) { // ldSbrPresentFlag
851 avpriv_report_missing_feature(avctx,
853 return AVERROR_PATCHWELCOME;
856 while (get_bits(gb, 4) != ELDEXT_TERM) {
857 int len = get_bits(gb, 4);
859 len += get_bits(gb, 8);
861 len += get_bits(gb, 16);
862 if (get_bits_left(gb) < len * 8 + 4) {
863 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
864 return AVERROR_INVALIDDATA;
866 skip_bits_long(gb, 8 * len);
869 if ((ret = set_default_channel_config(avctx, layout_map,
870 &tags, channel_config)))
873 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
876 ep_config = get_bits(gb, 2);
878 avpriv_report_missing_feature(avctx,
879 "epConfig %d", ep_config);
880 return AVERROR_PATCHWELCOME;
886 * Decode audio specific configuration; reference: table 1.13.
888 * @param ac pointer to AACContext, may be null
889 * @param avctx pointer to AVCCodecContext, used for logging
890 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
891 * @param data pointer to buffer holding an audio specific config
892 * @param bit_size size of audio specific config or data in bits
893 * @param sync_extension look for an appended sync extension
895 * @return Returns error status or number of consumed bits. <0 - error
897 static int decode_audio_specific_config(AACContext *ac,
898 AVCodecContext *avctx,
899 MPEG4AudioConfig *m4ac,
900 const uint8_t *data, int bit_size,
906 av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
907 for (i = 0; i < bit_size >> 3; i++)
908 av_dlog(avctx, "%02x ", data[i]);
909 av_dlog(avctx, "\n");
911 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
914 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
915 sync_extension)) < 0)
916 return AVERROR_INVALIDDATA;
917 if (m4ac->sampling_index > 12) {
918 av_log(avctx, AV_LOG_ERROR,
919 "invalid sampling rate index %d\n",
920 m4ac->sampling_index);
921 return AVERROR_INVALIDDATA;
923 if (m4ac->object_type == AOT_ER_AAC_LD &&
924 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
925 av_log(avctx, AV_LOG_ERROR,
926 "invalid low delay sampling rate index %d\n",
927 m4ac->sampling_index);
928 return AVERROR_INVALIDDATA;
931 skip_bits_long(&gb, i);
933 switch (m4ac->object_type) {
939 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
940 m4ac, m4ac->chan_config)) < 0)
944 if ((ret = decode_eld_specific_config(ac, avctx, &gb,
945 m4ac, m4ac->chan_config)) < 0)
949 avpriv_report_missing_feature(avctx,
950 "Audio object type %s%d",
951 m4ac->sbr == 1 ? "SBR+" : "",
953 return AVERROR(ENOSYS);
957 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
958 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
959 m4ac->sample_rate, m4ac->sbr,
962 return get_bits_count(&gb);
966 * linear congruential pseudorandom number generator
968 * @param previous_val pointer to the current state of the generator
970 * @return Returns a 32-bit pseudorandom integer
972 static av_always_inline int lcg_random(unsigned previous_val)
974 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
978 static av_always_inline void reset_predict_state(PredictorState *ps)
988 static void reset_all_predictors(PredictorState *ps)
991 for (i = 0; i < MAX_PREDICTORS; i++)
992 reset_predict_state(&ps[i]);
995 static int sample_rate_idx (int rate)
997 if (92017 <= rate) return 0;
998 else if (75132 <= rate) return 1;
999 else if (55426 <= rate) return 2;
1000 else if (46009 <= rate) return 3;
1001 else if (37566 <= rate) return 4;
1002 else if (27713 <= rate) return 5;
1003 else if (23004 <= rate) return 6;
1004 else if (18783 <= rate) return 7;
1005 else if (13856 <= rate) return 8;
1006 else if (11502 <= rate) return 9;
1007 else if (9391 <= rate) return 10;
1011 static void reset_predictor_group(PredictorState *ps, int group_num)
1014 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1015 reset_predict_state(&ps[i]);
1018 #define AAC_INIT_VLC_STATIC(num, size) \
1019 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1020 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1021 sizeof(ff_aac_spectral_bits[num][0]), \
1022 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1023 sizeof(ff_aac_spectral_codes[num][0]), \
1026 static void aacdec_init(AACContext *ac);
1028 static av_cold int aac_decode_init(AVCodecContext *avctx)
1030 AACContext *ac = avctx->priv_data;
1034 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1038 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1040 if (avctx->extradata_size > 0) {
1041 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1043 avctx->extradata_size * 8,
1048 uint8_t layout_map[MAX_ELEM_ID*4][3];
1049 int layout_map_tags;
1051 sr = sample_rate_idx(avctx->sample_rate);
1052 ac->oc[1].m4ac.sampling_index = sr;
1053 ac->oc[1].m4ac.channels = avctx->channels;
1054 ac->oc[1].m4ac.sbr = -1;
1055 ac->oc[1].m4ac.ps = -1;
1057 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1058 if (ff_mpeg4audio_channels[i] == avctx->channels)
1060 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1063 ac->oc[1].m4ac.chan_config = i;
1065 if (ac->oc[1].m4ac.chan_config) {
1066 int ret = set_default_channel_config(avctx, layout_map,
1067 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1069 output_configure(ac, layout_map, layout_map_tags,
1071 else if (avctx->err_recognition & AV_EF_EXPLODE)
1072 return AVERROR_INVALIDDATA;
1076 if (avctx->channels > MAX_CHANNELS) {
1077 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1078 return AVERROR_INVALIDDATA;
1081 AAC_INIT_VLC_STATIC( 0, 304);
1082 AAC_INIT_VLC_STATIC( 1, 270);
1083 AAC_INIT_VLC_STATIC( 2, 550);
1084 AAC_INIT_VLC_STATIC( 3, 300);
1085 AAC_INIT_VLC_STATIC( 4, 328);
1086 AAC_INIT_VLC_STATIC( 5, 294);
1087 AAC_INIT_VLC_STATIC( 6, 306);
1088 AAC_INIT_VLC_STATIC( 7, 268);
1089 AAC_INIT_VLC_STATIC( 8, 510);
1090 AAC_INIT_VLC_STATIC( 9, 366);
1091 AAC_INIT_VLC_STATIC(10, 462);
1095 ff_fmt_convert_init(&ac->fmt_conv, avctx);
1096 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
1098 ac->random_state = 0x1f2e3d4c;
1102 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1103 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1104 ff_aac_scalefactor_bits,
1105 sizeof(ff_aac_scalefactor_bits[0]),
1106 sizeof(ff_aac_scalefactor_bits[0]),
1107 ff_aac_scalefactor_code,
1108 sizeof(ff_aac_scalefactor_code[0]),
1109 sizeof(ff_aac_scalefactor_code[0]),
1112 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1113 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1114 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1115 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1116 // window initialization
1117 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1118 ff_kbd_window_init(ff_aac_kbd_long_512, 4.0, 512);
1119 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1120 ff_init_ff_sine_windows(10);
1121 ff_init_ff_sine_windows( 9);
1122 ff_init_ff_sine_windows( 7);
1130 * Skip data_stream_element; reference: table 4.10.
1132 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1134 int byte_align = get_bits1(gb);
1135 int count = get_bits(gb, 8);
1137 count += get_bits(gb, 8);
1141 if (get_bits_left(gb) < 8 * count) {
1142 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1143 return AVERROR_INVALIDDATA;
1145 skip_bits_long(gb, 8 * count);
1149 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1153 if (get_bits1(gb)) {
1154 ics->predictor_reset_group = get_bits(gb, 5);
1155 if (ics->predictor_reset_group == 0 ||
1156 ics->predictor_reset_group > 30) {
1157 av_log(ac->avctx, AV_LOG_ERROR,
1158 "Invalid Predictor Reset Group.\n");
1159 return AVERROR_INVALIDDATA;
1162 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1163 ics->prediction_used[sfb] = get_bits1(gb);
1169 * Decode Long Term Prediction data; reference: table 4.xx.
1171 static void decode_ltp(LongTermPrediction *ltp,
1172 GetBitContext *gb, uint8_t max_sfb)
1176 ltp->lag = get_bits(gb, 11);
1177 ltp->coef = ltp_coef[get_bits(gb, 3)];
1178 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1179 ltp->used[sfb] = get_bits1(gb);
1183 * Decode Individual Channel Stream info; reference: table 4.6.
1185 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1188 int aot = ac->oc[1].m4ac.object_type;
1189 if (aot != AOT_ER_AAC_ELD) {
1190 if (get_bits1(gb)) {
1191 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1192 return AVERROR_INVALIDDATA;
1194 ics->window_sequence[1] = ics->window_sequence[0];
1195 ics->window_sequence[0] = get_bits(gb, 2);
1196 if (aot == AOT_ER_AAC_LD &&
1197 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1198 av_log(ac->avctx, AV_LOG_ERROR,
1199 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1200 "window sequence %d found.\n", ics->window_sequence[0]);
1201 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1202 return AVERROR_INVALIDDATA;
1204 ics->use_kb_window[1] = ics->use_kb_window[0];
1205 ics->use_kb_window[0] = get_bits1(gb);
1207 ics->num_window_groups = 1;
1208 ics->group_len[0] = 1;
1209 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1211 ics->max_sfb = get_bits(gb, 4);
1212 for (i = 0; i < 7; i++) {
1213 if (get_bits1(gb)) {
1214 ics->group_len[ics->num_window_groups - 1]++;
1216 ics->num_window_groups++;
1217 ics->group_len[ics->num_window_groups - 1] = 1;
1220 ics->num_windows = 8;
1221 ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1222 ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1223 ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1224 ics->predictor_present = 0;
1226 ics->max_sfb = get_bits(gb, 6);
1227 ics->num_windows = 1;
1228 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1229 ics->swb_offset = ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];
1230 ics->num_swb = ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];
1231 if (!ics->num_swb || !ics->swb_offset)
1234 ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1235 ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1237 ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1238 if (aot != AOT_ER_AAC_ELD) {
1239 ics->predictor_present = get_bits1(gb);
1240 ics->predictor_reset_group = 0;
1242 if (ics->predictor_present) {
1243 if (aot == AOT_AAC_MAIN) {
1244 if (decode_prediction(ac, ics, gb)) {
1247 } else if (aot == AOT_AAC_LC ||
1248 aot == AOT_ER_AAC_LC) {
1249 av_log(ac->avctx, AV_LOG_ERROR,
1250 "Prediction is not allowed in AAC-LC.\n");
1253 if (aot == AOT_ER_AAC_LD) {
1254 av_log(ac->avctx, AV_LOG_ERROR,
1255 "LTP in ER AAC LD not yet implemented.\n");
1256 return AVERROR_PATCHWELCOME;
1258 if ((ics->ltp.present = get_bits(gb, 1)))
1259 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1264 if (ics->max_sfb > ics->num_swb) {
1265 av_log(ac->avctx, AV_LOG_ERROR,
1266 "Number of scalefactor bands in group (%d) "
1267 "exceeds limit (%d).\n",
1268 ics->max_sfb, ics->num_swb);
1275 return AVERROR_INVALIDDATA;
1279 * Decode band types (section_data payload); reference: table 4.46.
1281 * @param band_type array of the used band type
1282 * @param band_type_run_end array of the last scalefactor band of a band type run
1284 * @return Returns error status. 0 - OK, !0 - error
1286 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1287 int band_type_run_end[120], GetBitContext *gb,
1288 IndividualChannelStream *ics)
1291 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1292 for (g = 0; g < ics->num_window_groups; g++) {
1294 while (k < ics->max_sfb) {
1295 uint8_t sect_end = k;
1297 int sect_band_type = get_bits(gb, 4);
1298 if (sect_band_type == 12) {
1299 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1300 return AVERROR_INVALIDDATA;
1303 sect_len_incr = get_bits(gb, bits);
1304 sect_end += sect_len_incr;
1305 if (get_bits_left(gb) < 0) {
1306 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1307 return AVERROR_INVALIDDATA;
1309 if (sect_end > ics->max_sfb) {
1310 av_log(ac->avctx, AV_LOG_ERROR,
1311 "Number of bands (%d) exceeds limit (%d).\n",
1312 sect_end, ics->max_sfb);
1313 return AVERROR_INVALIDDATA;
1315 } while (sect_len_incr == (1 << bits) - 1);
1316 for (; k < sect_end; k++) {
1317 band_type [idx] = sect_band_type;
1318 band_type_run_end[idx++] = sect_end;
1326 * Decode scalefactors; reference: table 4.47.
1328 * @param global_gain first scalefactor value as scalefactors are differentially coded
1329 * @param band_type array of the used band type
1330 * @param band_type_run_end array of the last scalefactor band of a band type run
1331 * @param sf array of scalefactors or intensity stereo positions
1333 * @return Returns error status. 0 - OK, !0 - error
1335 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1336 unsigned int global_gain,
1337 IndividualChannelStream *ics,
1338 enum BandType band_type[120],
1339 int band_type_run_end[120])
1342 int offset[3] = { global_gain, global_gain - 90, 0 };
1345 for (g = 0; g < ics->num_window_groups; g++) {
1346 for (i = 0; i < ics->max_sfb;) {
1347 int run_end = band_type_run_end[idx];
1348 if (band_type[idx] == ZERO_BT) {
1349 for (; i < run_end; i++, idx++)
1351 } else if ((band_type[idx] == INTENSITY_BT) ||
1352 (band_type[idx] == INTENSITY_BT2)) {
1353 for (; i < run_end; i++, idx++) {
1354 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1355 clipped_offset = av_clip(offset[2], -155, 100);
1356 if (offset[2] != clipped_offset) {
1357 avpriv_request_sample(ac->avctx,
1358 "If you heard an audible artifact, there may be a bug in the decoder. "
1359 "Clipped intensity stereo position (%d -> %d)",
1360 offset[2], clipped_offset);
1362 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1364 } else if (band_type[idx] == NOISE_BT) {
1365 for (; i < run_end; i++, idx++) {
1366 if (noise_flag-- > 0)
1367 offset[1] += get_bits(gb, 9) - 256;
1369 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1370 clipped_offset = av_clip(offset[1], -100, 155);
1371 if (offset[1] != clipped_offset) {
1372 avpriv_request_sample(ac->avctx,
1373 "If you heard an audible artifact, there may be a bug in the decoder. "
1374 "Clipped noise gain (%d -> %d)",
1375 offset[1], clipped_offset);
1377 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1380 for (; i < run_end; i++, idx++) {
1381 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1382 if (offset[0] > 255U) {
1383 av_log(ac->avctx, AV_LOG_ERROR,
1384 "Scalefactor (%d) out of range.\n", offset[0]);
1385 return AVERROR_INVALIDDATA;
1387 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1396 * Decode pulse data; reference: table 4.7.
1398 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1399 const uint16_t *swb_offset, int num_swb)
1402 pulse->num_pulse = get_bits(gb, 2) + 1;
1403 pulse_swb = get_bits(gb, 6);
1404 if (pulse_swb >= num_swb)
1406 pulse->pos[0] = swb_offset[pulse_swb];
1407 pulse->pos[0] += get_bits(gb, 5);
1408 if (pulse->pos[0] >= swb_offset[num_swb])
1410 pulse->amp[0] = get_bits(gb, 4);
1411 for (i = 1; i < pulse->num_pulse; i++) {
1412 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1413 if (pulse->pos[i] >= swb_offset[num_swb])
1415 pulse->amp[i] = get_bits(gb, 4);
1421 * Decode Temporal Noise Shaping data; reference: table 4.48.
1423 * @return Returns error status. 0 - OK, !0 - error
1425 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1426 GetBitContext *gb, const IndividualChannelStream *ics)
1428 int w, filt, i, coef_len, coef_res, coef_compress;
1429 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1430 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1431 for (w = 0; w < ics->num_windows; w++) {
1432 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1433 coef_res = get_bits1(gb);
1435 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1437 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1439 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1440 av_log(ac->avctx, AV_LOG_ERROR,
1441 "TNS filter order %d is greater than maximum %d.\n",
1442 tns->order[w][filt], tns_max_order);
1443 tns->order[w][filt] = 0;
1444 return AVERROR_INVALIDDATA;
1446 if (tns->order[w][filt]) {
1447 tns->direction[w][filt] = get_bits1(gb);
1448 coef_compress = get_bits1(gb);
1449 coef_len = coef_res + 3 - coef_compress;
1450 tmp2_idx = 2 * coef_compress + coef_res;
1452 for (i = 0; i < tns->order[w][filt]; i++)
1453 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1462 * Decode Mid/Side data; reference: table 4.54.
1464 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1465 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1466 * [3] reserved for scalable AAC
1468 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1472 if (ms_present == 1) {
1474 idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1476 cpe->ms_mask[idx] = get_bits1(gb);
1477 } else if (ms_present == 2) {
1478 memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1483 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1487 *dst++ = v[idx & 15] * s;
1488 *dst++ = v[idx>>4 & 15] * s;
1494 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1498 *dst++ = v[idx & 3] * s;
1499 *dst++ = v[idx>>2 & 3] * s;
1500 *dst++ = v[idx>>4 & 3] * s;
1501 *dst++ = v[idx>>6 & 3] * s;
1507 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1508 unsigned sign, const float *scale)
1510 union av_intfloat32 s0, s1;
1512 s0.f = s1.f = *scale;
1513 s0.i ^= sign >> 1 << 31;
1516 *dst++ = v[idx & 15] * s0.f;
1517 *dst++ = v[idx>>4 & 15] * s1.f;
1524 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1525 unsigned sign, const float *scale)
1527 unsigned nz = idx >> 12;
1528 union av_intfloat32 s = { .f = *scale };
1529 union av_intfloat32 t;
1531 t.i = s.i ^ (sign & 1U<<31);
1532 *dst++ = v[idx & 3] * t.f;
1534 sign <<= nz & 1; nz >>= 1;
1535 t.i = s.i ^ (sign & 1U<<31);
1536 *dst++ = v[idx>>2 & 3] * t.f;
1538 sign <<= nz & 1; nz >>= 1;
1539 t.i = s.i ^ (sign & 1U<<31);
1540 *dst++ = v[idx>>4 & 3] * t.f;
1543 t.i = s.i ^ (sign & 1U<<31);
1544 *dst++ = v[idx>>6 & 3] * t.f;
1551 * Decode spectral data; reference: table 4.50.
1552 * Dequantize and scale spectral data; reference: 4.6.3.3.
1554 * @param coef array of dequantized, scaled spectral data
1555 * @param sf array of scalefactors or intensity stereo positions
1556 * @param pulse_present set if pulses are present
1557 * @param pulse pointer to pulse data struct
1558 * @param band_type array of the used band type
1560 * @return Returns error status. 0 - OK, !0 - error
1562 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1563 GetBitContext *gb, const float sf[120],
1564 int pulse_present, const Pulse *pulse,
1565 const IndividualChannelStream *ics,
1566 enum BandType band_type[120])
1568 int i, k, g, idx = 0;
1569 const int c = 1024 / ics->num_windows;
1570 const uint16_t *offsets = ics->swb_offset;
1571 float *coef_base = coef;
1573 for (g = 0; g < ics->num_windows; g++)
1574 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1575 sizeof(float) * (c - offsets[ics->max_sfb]));
1577 for (g = 0; g < ics->num_window_groups; g++) {
1578 unsigned g_len = ics->group_len[g];
1580 for (i = 0; i < ics->max_sfb; i++, idx++) {
1581 const unsigned cbt_m1 = band_type[idx] - 1;
1582 float *cfo = coef + offsets[i];
1583 int off_len = offsets[i + 1] - offsets[i];
1586 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1587 for (group = 0; group < g_len; group++, cfo+=128) {
1588 memset(cfo, 0, off_len * sizeof(float));
1590 } else if (cbt_m1 == NOISE_BT - 1) {
1591 for (group = 0; group < g_len; group++, cfo+=128) {
1595 for (k = 0; k < off_len; k++) {
1596 ac->random_state = lcg_random(ac->random_state);
1597 cfo[k] = ac->random_state;
1600 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1601 scale = sf[idx] / sqrtf(band_energy);
1602 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1605 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1606 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1607 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1608 OPEN_READER(re, gb);
1610 switch (cbt_m1 >> 1) {
1612 for (group = 0; group < g_len; group++, cfo+=128) {
1620 UPDATE_CACHE(re, gb);
1621 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1622 cb_idx = cb_vector_idx[code];
1623 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1629 for (group = 0; group < g_len; group++, cfo+=128) {
1639 UPDATE_CACHE(re, gb);
1640 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1641 cb_idx = cb_vector_idx[code];
1642 nnz = cb_idx >> 8 & 15;
1643 bits = nnz ? GET_CACHE(re, gb) : 0;
1644 LAST_SKIP_BITS(re, gb, nnz);
1645 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1651 for (group = 0; group < g_len; group++, cfo+=128) {
1659 UPDATE_CACHE(re, gb);
1660 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1661 cb_idx = cb_vector_idx[code];
1662 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1669 for (group = 0; group < g_len; group++, cfo+=128) {
1679 UPDATE_CACHE(re, gb);
1680 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1681 cb_idx = cb_vector_idx[code];
1682 nnz = cb_idx >> 8 & 15;
1683 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1684 LAST_SKIP_BITS(re, gb, nnz);
1685 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1691 for (group = 0; group < g_len; group++, cfo+=128) {
1693 uint32_t *icf = (uint32_t *) cf;
1703 UPDATE_CACHE(re, gb);
1704 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1712 cb_idx = cb_vector_idx[code];
1715 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1716 LAST_SKIP_BITS(re, gb, nnz);
1718 for (j = 0; j < 2; j++) {
1722 /* The total length of escape_sequence must be < 22 bits according
1723 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1724 UPDATE_CACHE(re, gb);
1725 b = GET_CACHE(re, gb);
1726 b = 31 - av_log2(~b);
1729 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1730 return AVERROR_INVALIDDATA;
1733 SKIP_BITS(re, gb, b + 1);
1735 n = (1 << b) + SHOW_UBITS(re, gb, b);
1736 LAST_SKIP_BITS(re, gb, b);
1737 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1740 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1741 *icf++ = (bits & 1U<<31) | v;
1748 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1752 CLOSE_READER(re, gb);
1758 if (pulse_present) {
1760 for (i = 0; i < pulse->num_pulse; i++) {
1761 float co = coef_base[ pulse->pos[i] ];
1762 while (offsets[idx + 1] <= pulse->pos[i])
1764 if (band_type[idx] != NOISE_BT && sf[idx]) {
1765 float ico = -pulse->amp[i];
1768 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1770 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1777 static av_always_inline float flt16_round(float pf)
1779 union av_intfloat32 tmp;
1781 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1785 static av_always_inline float flt16_even(float pf)
1787 union av_intfloat32 tmp;
1789 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1793 static av_always_inline float flt16_trunc(float pf)
1795 union av_intfloat32 pun;
1797 pun.i &= 0xFFFF0000U;
1801 static av_always_inline void predict(PredictorState *ps, float *coef,
1804 const float a = 0.953125; // 61.0 / 64
1805 const float alpha = 0.90625; // 29.0 / 32
1809 float r0 = ps->r0, r1 = ps->r1;
1810 float cor0 = ps->cor0, cor1 = ps->cor1;
1811 float var0 = ps->var0, var1 = ps->var1;
1813 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1814 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1816 pv = flt16_round(k1 * r0 + k2 * r1);
1823 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1824 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1825 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1826 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1828 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1829 ps->r0 = flt16_trunc(a * e0);
1833 * Apply AAC-Main style frequency domain prediction.
1835 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1839 if (!sce->ics.predictor_initialized) {
1840 reset_all_predictors(sce->predictor_state);
1841 sce->ics.predictor_initialized = 1;
1844 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1846 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1848 for (k = sce->ics.swb_offset[sfb];
1849 k < sce->ics.swb_offset[sfb + 1];
1851 predict(&sce->predictor_state[k], &sce->coeffs[k],
1852 sce->ics.predictor_present &&
1853 sce->ics.prediction_used[sfb]);
1856 if (sce->ics.predictor_reset_group)
1857 reset_predictor_group(sce->predictor_state,
1858 sce->ics.predictor_reset_group);
1860 reset_all_predictors(sce->predictor_state);
1864 * Decode an individual_channel_stream payload; reference: table 4.44.
1866 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1867 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1869 * @return Returns error status. 0 - OK, !0 - error
1871 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1872 GetBitContext *gb, int common_window, int scale_flag)
1875 TemporalNoiseShaping *tns = &sce->tns;
1876 IndividualChannelStream *ics = &sce->ics;
1877 float *out = sce->coeffs;
1878 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1881 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1882 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1883 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1884 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1885 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1887 /* This assignment is to silence a GCC warning about the variable being used
1888 * uninitialized when in fact it always is.
1890 pulse.num_pulse = 0;
1892 global_gain = get_bits(gb, 8);
1894 if (!common_window && !scale_flag) {
1895 if (decode_ics_info(ac, ics, gb) < 0)
1896 return AVERROR_INVALIDDATA;
1899 if ((ret = decode_band_types(ac, sce->band_type,
1900 sce->band_type_run_end, gb, ics)) < 0)
1902 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1903 sce->band_type, sce->band_type_run_end)) < 0)
1908 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1909 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1910 av_log(ac->avctx, AV_LOG_ERROR,
1911 "Pulse tool not allowed in eight short sequence.\n");
1912 return AVERROR_INVALIDDATA;
1914 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1915 av_log(ac->avctx, AV_LOG_ERROR,
1916 "Pulse data corrupt or invalid.\n");
1917 return AVERROR_INVALIDDATA;
1920 tns->present = get_bits1(gb);
1921 if (tns->present && !er_syntax)
1922 if (decode_tns(ac, tns, gb, ics) < 0)
1923 return AVERROR_INVALIDDATA;
1924 if (!eld_syntax && get_bits1(gb)) {
1925 avpriv_request_sample(ac->avctx, "SSR");
1926 return AVERROR_PATCHWELCOME;
1928 // I see no textual basis in the spec for this occuring after SSR gain
1929 // control, but this is what both reference and real implmentations do
1930 if (tns->present && er_syntax)
1931 if (decode_tns(ac, tns, gb, ics) < 0)
1932 return AVERROR_INVALIDDATA;
1935 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1936 &pulse, ics, sce->band_type) < 0)
1937 return AVERROR_INVALIDDATA;
1939 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1940 apply_prediction(ac, sce);
1946 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1948 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1950 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1951 float *ch0 = cpe->ch[0].coeffs;
1952 float *ch1 = cpe->ch[1].coeffs;
1953 int g, i, group, idx = 0;
1954 const uint16_t *offsets = ics->swb_offset;
1955 for (g = 0; g < ics->num_window_groups; g++) {
1956 for (i = 0; i < ics->max_sfb; i++, idx++) {
1957 if (cpe->ms_mask[idx] &&
1958 cpe->ch[0].band_type[idx] < NOISE_BT &&
1959 cpe->ch[1].band_type[idx] < NOISE_BT) {
1960 for (group = 0; group < ics->group_len[g]; group++) {
1961 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1962 ch1 + group * 128 + offsets[i],
1963 offsets[i+1] - offsets[i]);
1967 ch0 += ics->group_len[g] * 128;
1968 ch1 += ics->group_len[g] * 128;
1973 * intensity stereo decoding; reference: 4.6.8.2.3
1975 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1976 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1977 * [3] reserved for scalable AAC
1979 static void apply_intensity_stereo(AACContext *ac,
1980 ChannelElement *cpe, int ms_present)
1982 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1983 SingleChannelElement *sce1 = &cpe->ch[1];
1984 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1985 const uint16_t *offsets = ics->swb_offset;
1986 int g, group, i, idx = 0;
1989 for (g = 0; g < ics->num_window_groups; g++) {
1990 for (i = 0; i < ics->max_sfb;) {
1991 if (sce1->band_type[idx] == INTENSITY_BT ||
1992 sce1->band_type[idx] == INTENSITY_BT2) {
1993 const int bt_run_end = sce1->band_type_run_end[idx];
1994 for (; i < bt_run_end; i++, idx++) {
1995 c = -1 + 2 * (sce1->band_type[idx] - 14);
1997 c *= 1 - 2 * cpe->ms_mask[idx];
1998 scale = c * sce1->sf[idx];
1999 for (group = 0; group < ics->group_len[g]; group++)
2000 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2001 coef0 + group * 128 + offsets[i],
2003 offsets[i + 1] - offsets[i]);
2006 int bt_run_end = sce1->band_type_run_end[idx];
2007 idx += bt_run_end - i;
2011 coef0 += ics->group_len[g] * 128;
2012 coef1 += ics->group_len[g] * 128;
2017 * Decode a channel_pair_element; reference: table 4.4.
2019 * @return Returns error status. 0 - OK, !0 - error
2021 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2023 int i, ret, common_window, ms_present = 0;
2024 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2026 common_window = eld_syntax || get_bits1(gb);
2027 if (common_window) {
2028 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2029 return AVERROR_INVALIDDATA;
2030 i = cpe->ch[1].ics.use_kb_window[0];
2031 cpe->ch[1].ics = cpe->ch[0].ics;
2032 cpe->ch[1].ics.use_kb_window[1] = i;
2033 if (cpe->ch[1].ics.predictor_present &&
2034 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2035 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2036 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2037 ms_present = get_bits(gb, 2);
2038 if (ms_present == 3) {
2039 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2040 return AVERROR_INVALIDDATA;
2041 } else if (ms_present)
2042 decode_mid_side_stereo(cpe, gb, ms_present);
2044 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2046 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2049 if (common_window) {
2051 apply_mid_side_stereo(ac, cpe);
2052 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2053 apply_prediction(ac, &cpe->ch[0]);
2054 apply_prediction(ac, &cpe->ch[1]);
2058 apply_intensity_stereo(ac, cpe, ms_present);
2062 static const float cce_scale[] = {
2063 1.09050773266525765921, //2^(1/8)
2064 1.18920711500272106672, //2^(1/4)
2070 * Decode coupling_channel_element; reference: table 4.8.
2072 * @return Returns error status. 0 - OK, !0 - error
2074 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2080 SingleChannelElement *sce = &che->ch[0];
2081 ChannelCoupling *coup = &che->coup;
2083 coup->coupling_point = 2 * get_bits1(gb);
2084 coup->num_coupled = get_bits(gb, 3);
2085 for (c = 0; c <= coup->num_coupled; c++) {
2087 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2088 coup->id_select[c] = get_bits(gb, 4);
2089 if (coup->type[c] == TYPE_CPE) {
2090 coup->ch_select[c] = get_bits(gb, 2);
2091 if (coup->ch_select[c] == 3)
2094 coup->ch_select[c] = 2;
2096 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2098 sign = get_bits(gb, 1);
2099 scale = cce_scale[get_bits(gb, 2)];
2101 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2104 for (c = 0; c < num_gain; c++) {
2108 float gain_cache = 1.0;
2110 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2111 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2112 gain_cache = powf(scale, -gain);
2114 if (coup->coupling_point == AFTER_IMDCT) {
2115 coup->gain[c][0] = gain_cache;
2117 for (g = 0; g < sce->ics.num_window_groups; g++) {
2118 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2119 if (sce->band_type[idx] != ZERO_BT) {
2121 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2129 gain_cache = powf(scale, -t) * s;
2132 coup->gain[c][idx] = gain_cache;
2142 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2144 * @return Returns number of bytes consumed.
2146 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2150 int num_excl_chan = 0;
2153 for (i = 0; i < 7; i++)
2154 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2155 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2157 return num_excl_chan / 7;
2161 * Decode dynamic range information; reference: table 4.52.
2163 * @return Returns number of bytes consumed.
2165 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2169 int drc_num_bands = 1;
2172 /* pce_tag_present? */
2173 if (get_bits1(gb)) {
2174 che_drc->pce_instance_tag = get_bits(gb, 4);
2175 skip_bits(gb, 4); // tag_reserved_bits
2179 /* excluded_chns_present? */
2180 if (get_bits1(gb)) {
2181 n += decode_drc_channel_exclusions(che_drc, gb);
2184 /* drc_bands_present? */
2185 if (get_bits1(gb)) {
2186 che_drc->band_incr = get_bits(gb, 4);
2187 che_drc->interpolation_scheme = get_bits(gb, 4);
2189 drc_num_bands += che_drc->band_incr;
2190 for (i = 0; i < drc_num_bands; i++) {
2191 che_drc->band_top[i] = get_bits(gb, 8);
2196 /* prog_ref_level_present? */
2197 if (get_bits1(gb)) {
2198 che_drc->prog_ref_level = get_bits(gb, 7);
2199 skip_bits1(gb); // prog_ref_level_reserved_bits
2203 for (i = 0; i < drc_num_bands; i++) {
2204 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2205 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2212 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2214 int i, major, minor;
2219 get_bits(gb, 13); len -= 13;
2221 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2222 buf[i] = get_bits(gb, 8);
2225 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2226 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2228 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2229 ac->avctx->internal->skip_samples = 1024;
2233 skip_bits_long(gb, len);
2239 * Decode extension data (incomplete); reference: table 4.51.
2241 * @param cnt length of TYPE_FIL syntactic element in bytes
2243 * @return Returns number of bytes consumed
2245 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2246 ChannelElement *che, enum RawDataBlockType elem_type)
2250 switch (get_bits(gb, 4)) { // extension type
2251 case EXT_SBR_DATA_CRC:
2255 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2257 } else if (!ac->oc[1].m4ac.sbr) {
2258 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2259 skip_bits_long(gb, 8 * cnt - 4);
2261 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2262 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2263 skip_bits_long(gb, 8 * cnt - 4);
2265 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2266 ac->oc[1].m4ac.sbr = 1;
2267 ac->oc[1].m4ac.ps = 1;
2268 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2269 ac->oc[1].status, 1);
2271 ac->oc[1].m4ac.sbr = 1;
2273 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2275 case EXT_DYNAMIC_RANGE:
2276 res = decode_dynamic_range(&ac->che_drc, gb);
2279 decode_fill(ac, gb, 8 * cnt - 4);
2282 case EXT_DATA_ELEMENT:
2284 skip_bits_long(gb, 8 * cnt - 4);
2291 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2293 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2294 * @param coef spectral coefficients
2296 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2297 IndividualChannelStream *ics, int decode)
2299 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2301 int bottom, top, order, start, end, size, inc;
2302 float lpc[TNS_MAX_ORDER];
2303 float tmp[TNS_MAX_ORDER+1];
2305 for (w = 0; w < ics->num_windows; w++) {
2306 bottom = ics->num_swb;
2307 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2309 bottom = FFMAX(0, top - tns->length[w][filt]);
2310 order = tns->order[w][filt];
2315 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2317 start = ics->swb_offset[FFMIN(bottom, mmm)];
2318 end = ics->swb_offset[FFMIN( top, mmm)];
2319 if ((size = end - start) <= 0)
2321 if (tns->direction[w][filt]) {
2331 for (m = 0; m < size; m++, start += inc)
2332 for (i = 1; i <= FFMIN(m, order); i++)
2333 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2336 for (m = 0; m < size; m++, start += inc) {
2337 tmp[0] = coef[start];
2338 for (i = 1; i <= FFMIN(m, order); i++)
2339 coef[start] += tmp[i] * lpc[i - 1];
2340 for (i = order; i > 0; i--)
2341 tmp[i] = tmp[i - 1];
2349 * Apply windowing and MDCT to obtain the spectral
2350 * coefficient from the predicted sample by LTP.
2352 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2353 float *in, IndividualChannelStream *ics)
2355 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2356 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2357 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2358 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2360 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2361 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2363 memset(in, 0, 448 * sizeof(float));
2364 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2366 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2367 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2369 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2370 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2372 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2376 * Apply the long term prediction
2378 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2380 const LongTermPrediction *ltp = &sce->ics.ltp;
2381 const uint16_t *offsets = sce->ics.swb_offset;
2384 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2385 float *predTime = sce->ret;
2386 float *predFreq = ac->buf_mdct;
2387 int16_t num_samples = 2048;
2389 if (ltp->lag < 1024)
2390 num_samples = ltp->lag + 1024;
2391 for (i = 0; i < num_samples; i++)
2392 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2393 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2395 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2397 if (sce->tns.present)
2398 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2400 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2402 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2403 sce->coeffs[i] += predFreq[i];
2408 * Update the LTP buffer for next frame
2410 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2412 IndividualChannelStream *ics = &sce->ics;
2413 float *saved = sce->saved;
2414 float *saved_ltp = sce->coeffs;
2415 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2416 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2419 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2420 memcpy(saved_ltp, saved, 512 * sizeof(float));
2421 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2422 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2423 for (i = 0; i < 64; i++)
2424 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2425 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2426 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2427 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2428 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2429 for (i = 0; i < 64; i++)
2430 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2431 } else { // LONG_STOP or ONLY_LONG
2432 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2433 for (i = 0; i < 512; i++)
2434 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2437 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2438 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2439 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2443 * Conduct IMDCT and windowing.
2445 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2447 IndividualChannelStream *ics = &sce->ics;
2448 float *in = sce->coeffs;
2449 float *out = sce->ret;
2450 float *saved = sce->saved;
2451 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2452 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2453 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2454 float *buf = ac->buf_mdct;
2455 float *temp = ac->temp;
2459 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2460 for (i = 0; i < 1024; i += 128)
2461 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2463 ac->mdct.imdct_half(&ac->mdct, buf, in);
2465 /* window overlapping
2466 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2467 * and long to short transitions are considered to be short to short
2468 * transitions. This leaves just two cases (long to long and short to short)
2469 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2471 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2472 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2473 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2475 memcpy( out, saved, 448 * sizeof(float));
2477 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2478 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2479 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2480 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2481 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2482 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2483 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2485 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2486 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2491 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2492 memcpy( saved, temp + 64, 64 * sizeof(float));
2493 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2494 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2495 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2496 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2497 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2498 memcpy( saved, buf + 512, 448 * sizeof(float));
2499 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2500 } else { // LONG_STOP or ONLY_LONG
2501 memcpy( saved, buf + 512, 512 * sizeof(float));
2505 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2507 IndividualChannelStream *ics = &sce->ics;
2508 float *in = sce->coeffs;
2509 float *out = sce->ret;
2510 float *saved = sce->saved;
2511 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_512 : ff_sine_512;
2512 float *buf = ac->buf_mdct;
2515 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2517 // window overlapping
2518 ac->fdsp.vector_fmul_window(out, saved, buf, lwindow_prev, 256);
2521 memcpy(saved, buf + 256, 256 * sizeof(float));
2524 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2526 float *in = sce->coeffs;
2527 float *out = sce->ret;
2528 float *saved = sce->saved;
2529 const float *const window = ff_aac_eld_window;
2530 float *buf = ac->buf_mdct;
2533 const int n2 = n >> 1;
2534 const int n4 = n >> 2;
2536 // Inverse transform, mapped to the conventional IMDCT by
2537 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2538 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2539 // Audio, Language and Image Processing, 2008. ICALIP 2008. International Conference on
2540 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2541 for (i = 0; i < n2; i+=2) {
2543 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2544 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2546 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2547 for (i = 0; i < n; i+=2) {
2550 // Like with the regular IMDCT at this point we still have the middle half
2551 // of a transform but with even symmetry on the left and odd symmetry on
2554 // window overlapping
2555 // The spec says to use samples [0..511] but the reference decoder uses
2556 // samples [128..639].
2557 for (i = n4; i < n2; i ++) {
2558 out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2559 saved[ i + n2] * window[i + n - n4] +
2560 -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2561 -saved[2*n + n2 + i] * window[i + 3*n - n4];
2563 for (i = 0; i < n2; i ++) {
2564 out[n4 + i] = buf[i] * window[i + n2 - n4] +
2565 -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2566 -saved[ n + i] * window[i + n2 + 2*n - n4] +
2567 saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2569 for (i = 0; i < n4; i ++) {
2570 out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2571 -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2572 -saved[ n + n2 + i] * window[i + 3*n - n4];
2576 memmove(saved + n, saved, 2 * n * sizeof(float));
2577 memcpy( saved, buf, n * sizeof(float));
2581 * Apply dependent channel coupling (applied before IMDCT).
2583 * @param index index into coupling gain array
2585 static void apply_dependent_coupling(AACContext *ac,
2586 SingleChannelElement *target,
2587 ChannelElement *cce, int index)
2589 IndividualChannelStream *ics = &cce->ch[0].ics;
2590 const uint16_t *offsets = ics->swb_offset;
2591 float *dest = target->coeffs;
2592 const float *src = cce->ch[0].coeffs;
2593 int g, i, group, k, idx = 0;
2594 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2595 av_log(ac->avctx, AV_LOG_ERROR,
2596 "Dependent coupling is not supported together with LTP\n");
2599 for (g = 0; g < ics->num_window_groups; g++) {
2600 for (i = 0; i < ics->max_sfb; i++, idx++) {
2601 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2602 const float gain = cce->coup.gain[index][idx];
2603 for (group = 0; group < ics->group_len[g]; group++) {
2604 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2606 dest[group * 128 + k] += gain * src[group * 128 + k];
2611 dest += ics->group_len[g] * 128;
2612 src += ics->group_len[g] * 128;
2617 * Apply independent channel coupling (applied after IMDCT).
2619 * @param index index into coupling gain array
2621 static void apply_independent_coupling(AACContext *ac,
2622 SingleChannelElement *target,
2623 ChannelElement *cce, int index)
2626 const float gain = cce->coup.gain[index][0];
2627 const float *src = cce->ch[0].ret;
2628 float *dest = target->ret;
2629 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2631 for (i = 0; i < len; i++)
2632 dest[i] += gain * src[i];
2636 * channel coupling transformation interface
2638 * @param apply_coupling_method pointer to (in)dependent coupling function
2640 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2641 enum RawDataBlockType type, int elem_id,
2642 enum CouplingPoint coupling_point,
2643 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2647 for (i = 0; i < MAX_ELEM_ID; i++) {
2648 ChannelElement *cce = ac->che[TYPE_CCE][i];
2651 if (cce && cce->coup.coupling_point == coupling_point) {
2652 ChannelCoupling *coup = &cce->coup;
2654 for (c = 0; c <= coup->num_coupled; c++) {
2655 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2656 if (coup->ch_select[c] != 1) {
2657 apply_coupling_method(ac, &cc->ch[0], cce, index);
2658 if (coup->ch_select[c] != 0)
2661 if (coup->ch_select[c] != 2)
2662 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2664 index += 1 + (coup->ch_select[c] == 3);
2671 * Convert spectral data to float samples, applying all supported tools as appropriate.
2673 static void spectral_to_sample(AACContext *ac)
2676 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2677 switch (ac->oc[1].m4ac.object_type) {
2679 imdct_and_window = imdct_and_windowing_ld;
2681 case AOT_ER_AAC_ELD:
2682 imdct_and_window = imdct_and_windowing_eld;
2685 imdct_and_window = ac->imdct_and_windowing;
2687 for (type = 3; type >= 0; type--) {
2688 for (i = 0; i < MAX_ELEM_ID; i++) {
2689 ChannelElement *che = ac->che[type][i];
2691 if (type <= TYPE_CPE)
2692 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2693 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2694 if (che->ch[0].ics.predictor_present) {
2695 if (che->ch[0].ics.ltp.present)
2696 ac->apply_ltp(ac, &che->ch[0]);
2697 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2698 ac->apply_ltp(ac, &che->ch[1]);
2701 if (che->ch[0].tns.present)
2702 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2703 if (che->ch[1].tns.present)
2704 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2705 if (type <= TYPE_CPE)
2706 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2707 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2708 imdct_and_window(ac, &che->ch[0]);
2709 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2710 ac->update_ltp(ac, &che->ch[0]);
2711 if (type == TYPE_CPE) {
2712 imdct_and_window(ac, &che->ch[1]);
2713 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2714 ac->update_ltp(ac, &che->ch[1]);
2716 if (ac->oc[1].m4ac.sbr > 0) {
2717 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2720 if (type <= TYPE_CCE)
2721 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2727 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2730 AACADTSHeaderInfo hdr_info;
2731 uint8_t layout_map[MAX_ELEM_ID*4][3];
2732 int layout_map_tags, ret;
2734 size = avpriv_aac_parse_header(gb, &hdr_info);
2736 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2737 // This is 2 for "VLB " audio in NSV files.
2738 // See samples/nsv/vlb_audio.
2739 avpriv_report_missing_feature(ac->avctx,
2740 "More than one AAC RDB per ADTS frame");
2741 ac->warned_num_aac_frames = 1;
2743 push_output_configuration(ac);
2744 if (hdr_info.chan_config) {
2745 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2746 if ((ret = set_default_channel_config(ac->avctx,
2749 hdr_info.chan_config)) < 0)
2751 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2752 FFMAX(ac->oc[1].status,
2753 OC_TRIAL_FRAME), 0)) < 0)
2756 ac->oc[1].m4ac.chan_config = 0;
2758 * dual mono frames in Japanese DTV can have chan_config 0
2759 * WITHOUT specifying PCE.
2760 * thus, set dual mono as default.
2762 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2763 layout_map_tags = 2;
2764 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2765 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2766 layout_map[0][1] = 0;
2767 layout_map[1][1] = 1;
2768 if (output_configure(ac, layout_map, layout_map_tags,
2773 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2774 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2775 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2776 if (ac->oc[0].status != OC_LOCKED ||
2777 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2778 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2779 ac->oc[1].m4ac.sbr = -1;
2780 ac->oc[1].m4ac.ps = -1;
2782 if (!hdr_info.crc_absent)
2788 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2789 int *got_frame_ptr, GetBitContext *gb)
2791 AACContext *ac = avctx->priv_data;
2792 ChannelElement *che;
2795 int chan_config = ac->oc[1].m4ac.chan_config;
2796 int aot = ac->oc[1].m4ac.object_type;
2798 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2803 if ((err = frame_configure_elements(avctx)) < 0)
2806 ac->tags_mapped = 0;
2808 if (chan_config < 0 || chan_config >= 8) {
2809 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2810 ac->oc[1].m4ac.chan_config);
2811 return AVERROR_INVALIDDATA;
2813 for (i = 0; i < tags_per_config[chan_config]; i++) {
2814 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2815 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2816 if (!(che=get_che(ac, elem_type, elem_id))) {
2817 av_log(ac->avctx, AV_LOG_ERROR,
2818 "channel element %d.%d is not allocated\n",
2819 elem_type, elem_id);
2820 return AVERROR_INVALIDDATA;
2822 if (aot != AOT_ER_AAC_ELD)
2824 switch (elem_type) {
2826 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2829 err = decode_cpe(ac, gb, che);
2832 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2839 spectral_to_sample(ac);
2841 ac->frame->nb_samples = samples;
2844 skip_bits_long(gb, get_bits_left(gb));
2848 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2849 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2851 AACContext *ac = avctx->priv_data;
2852 ChannelElement *che = NULL, *che_prev = NULL;
2853 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2855 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2856 int is_dmono, sce_count = 0;
2860 if (show_bits(gb, 12) == 0xfff) {
2861 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2862 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2865 if (ac->oc[1].m4ac.sampling_index > 12) {
2866 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2867 err = AVERROR_INVALIDDATA;
2872 if ((err = frame_configure_elements(avctx)) < 0)
2875 ac->tags_mapped = 0;
2877 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2878 elem_id = get_bits(gb, 4);
2880 if (elem_type < TYPE_DSE) {
2881 if (!(che=get_che(ac, elem_type, elem_id))) {
2882 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2883 elem_type, elem_id);
2884 err = AVERROR_INVALIDDATA;
2890 switch (elem_type) {
2893 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2899 err = decode_cpe(ac, gb, che);
2904 err = decode_cce(ac, gb, che);
2908 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2913 err = skip_data_stream_element(ac, gb);
2917 uint8_t layout_map[MAX_ELEM_ID*4][3];
2919 push_output_configuration(ac);
2920 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2926 av_log(avctx, AV_LOG_ERROR,
2927 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2929 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2931 ac->oc[1].m4ac.chan_config = 0;
2939 elem_id += get_bits(gb, 8) - 1;
2940 if (get_bits_left(gb) < 8 * elem_id) {
2941 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
2942 err = AVERROR_INVALIDDATA;
2946 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2947 err = 0; /* FIXME */
2951 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2956 elem_type_prev = elem_type;
2961 if (get_bits_left(gb) < 3) {
2962 av_log(avctx, AV_LOG_ERROR, overread_err);
2963 err = AVERROR_INVALIDDATA;
2968 spectral_to_sample(ac);
2970 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2971 samples <<= multiplier;
2972 /* for dual-mono audio (SCE + SCE) */
2973 is_dmono = ac->dmono_mode && sce_count == 2 &&
2974 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
2977 ac->frame->nb_samples = samples;
2979 av_frame_unref(ac->frame);
2980 *got_frame_ptr = !!samples;
2983 if (ac->dmono_mode == 1)
2984 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
2985 else if (ac->dmono_mode == 2)
2986 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
2989 if (ac->oc[1].status && audio_found) {
2990 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2991 avctx->frame_size = samples;
2992 ac->oc[1].status = OC_LOCKED;
2997 const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2998 if (side && side_size>=4)
2999 AV_WL32(side, 2*AV_RL32(side));
3003 pop_output_configuration(ac);
3007 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3008 int *got_frame_ptr, AVPacket *avpkt)
3010 AACContext *ac = avctx->priv_data;
3011 const uint8_t *buf = avpkt->data;
3012 int buf_size = avpkt->size;
3017 int new_extradata_size;
3018 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3019 AV_PKT_DATA_NEW_EXTRADATA,
3020 &new_extradata_size);
3021 int jp_dualmono_size;
3022 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3023 AV_PKT_DATA_JP_DUALMONO,
3026 if (new_extradata && 0) {
3027 av_free(avctx->extradata);
3028 avctx->extradata = av_mallocz(new_extradata_size +
3029 FF_INPUT_BUFFER_PADDING_SIZE);
3030 if (!avctx->extradata)
3031 return AVERROR(ENOMEM);
3032 avctx->extradata_size = new_extradata_size;
3033 memcpy(avctx->extradata, new_extradata, new_extradata_size);
3034 push_output_configuration(ac);
3035 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3037 avctx->extradata_size*8, 1) < 0) {
3038 pop_output_configuration(ac);
3039 return AVERROR_INVALIDDATA;
3044 if (jp_dualmono && jp_dualmono_size > 0)
3045 ac->dmono_mode = 1 + *jp_dualmono;
3046 if (ac->force_dmono_mode >= 0)
3047 ac->dmono_mode = ac->force_dmono_mode;
3049 if (INT_MAX / 8 <= buf_size)
3050 return AVERROR_INVALIDDATA;
3052 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3055 switch (ac->oc[1].m4ac.object_type) {
3057 case AOT_ER_AAC_LTP:
3059 case AOT_ER_AAC_ELD:
3060 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3063 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3068 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3069 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3070 if (buf[buf_offset])
3073 return buf_size > buf_offset ? buf_consumed : buf_size;
3076 static av_cold int aac_decode_close(AVCodecContext *avctx)
3078 AACContext *ac = avctx->priv_data;
3081 for (i = 0; i < MAX_ELEM_ID; i++) {
3082 for (type = 0; type < 4; type++) {
3083 if (ac->che[type][i])
3084 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3085 av_freep(&ac->che[type][i]);
3089 ff_mdct_end(&ac->mdct);
3090 ff_mdct_end(&ac->mdct_small);
3091 ff_mdct_end(&ac->mdct_ld);
3092 ff_mdct_end(&ac->mdct_ltp);
3097 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
3099 struct LATMContext {
3100 AACContext aac_ctx; ///< containing AACContext
3101 int initialized; ///< initialized after a valid extradata was seen
3104 int audio_mux_version_A; ///< LATM syntax version
3105 int frame_length_type; ///< 0/1 variable/fixed frame length
3106 int frame_length; ///< frame length for fixed frame length
3109 static inline uint32_t latm_get_value(GetBitContext *b)
3111 int length = get_bits(b, 2);
3113 return get_bits_long(b, (length+1)*8);
3116 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
3117 GetBitContext *gb, int asclen)
3119 AACContext *ac = &latmctx->aac_ctx;
3120 AVCodecContext *avctx = ac->avctx;
3121 MPEG4AudioConfig m4ac = { 0 };
3122 int config_start_bit = get_bits_count(gb);
3123 int sync_extension = 0;
3124 int bits_consumed, esize;
3128 asclen = FFMIN(asclen, get_bits_left(gb));
3130 asclen = get_bits_left(gb);
3132 if (config_start_bit % 8) {
3133 avpriv_request_sample(latmctx->aac_ctx.avctx,
3134 "Non-byte-aligned audio-specific config");
3135 return AVERROR_PATCHWELCOME;
3138 return AVERROR_INVALIDDATA;
3139 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3140 gb->buffer + (config_start_bit / 8),
3141 asclen, sync_extension);
3143 if (bits_consumed < 0)
3144 return AVERROR_INVALIDDATA;
3146 if (!latmctx->initialized ||
3147 ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3148 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3150 if(latmctx->initialized) {
3151 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3153 av_log(avctx, AV_LOG_DEBUG, "initializing latmctx\n");
3155 latmctx->initialized = 0;
3157 esize = (bits_consumed+7) / 8;
3159 if (avctx->extradata_size < esize) {
3160 av_free(avctx->extradata);
3161 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
3162 if (!avctx->extradata)
3163 return AVERROR(ENOMEM);
3166 avctx->extradata_size = esize;
3167 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3168 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3170 skip_bits_long(gb, bits_consumed);
3172 return bits_consumed;
3175 static int read_stream_mux_config(struct LATMContext *latmctx,
3178 int ret, audio_mux_version = get_bits(gb, 1);
3180 latmctx->audio_mux_version_A = 0;
3181 if (audio_mux_version)
3182 latmctx->audio_mux_version_A = get_bits(gb, 1);
3184 if (!latmctx->audio_mux_version_A) {
3186 if (audio_mux_version)
3187 latm_get_value(gb); // taraFullness
3189 skip_bits(gb, 1); // allStreamSameTimeFraming
3190 skip_bits(gb, 6); // numSubFrames
3192 if (get_bits(gb, 4)) { // numPrograms
3193 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3194 return AVERROR_PATCHWELCOME;
3197 // for each program (which there is only one in DVB)
3199 // for each layer (which there is only one in DVB)
3200 if (get_bits(gb, 3)) { // numLayer
3201 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3202 return AVERROR_PATCHWELCOME;
3205 // for all but first stream: use_same_config = get_bits(gb, 1);
3206 if (!audio_mux_version) {
3207 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3210 int ascLen = latm_get_value(gb);
3211 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3214 skip_bits_long(gb, ascLen);
3217 latmctx->frame_length_type = get_bits(gb, 3);
3218 switch (latmctx->frame_length_type) {
3220 skip_bits(gb, 8); // latmBufferFullness
3223 latmctx->frame_length = get_bits(gb, 9);
3228 skip_bits(gb, 6); // CELP frame length table index
3232 skip_bits(gb, 1); // HVXC frame length table index
3236 if (get_bits(gb, 1)) { // other data
3237 if (audio_mux_version) {
3238 latm_get_value(gb); // other_data_bits
3242 esc = get_bits(gb, 1);
3248 if (get_bits(gb, 1)) // crc present
3249 skip_bits(gb, 8); // config_crc
3255 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3259 if (ctx->frame_length_type == 0) {
3260 int mux_slot_length = 0;
3262 tmp = get_bits(gb, 8);
3263 mux_slot_length += tmp;
3264 } while (tmp == 255);
3265 return mux_slot_length;
3266 } else if (ctx->frame_length_type == 1) {
3267 return ctx->frame_length;
3268 } else if (ctx->frame_length_type == 3 ||
3269 ctx->frame_length_type == 5 ||
3270 ctx->frame_length_type == 7) {
3271 skip_bits(gb, 2); // mux_slot_length_coded
3276 static int read_audio_mux_element(struct LATMContext *latmctx,
3280 uint8_t use_same_mux = get_bits(gb, 1);
3281 if (!use_same_mux) {
3282 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3284 } else if (!latmctx->aac_ctx.avctx->extradata) {
3285 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3286 "no decoder config found\n");
3287 return AVERROR(EAGAIN);
3289 if (latmctx->audio_mux_version_A == 0) {
3290 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3291 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3292 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3293 return AVERROR_INVALIDDATA;
3294 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3295 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3296 "frame length mismatch %d << %d\n",
3297 mux_slot_length_bytes * 8, get_bits_left(gb));
3298 return AVERROR_INVALIDDATA;
3305 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3306 int *got_frame_ptr, AVPacket *avpkt)
3308 struct LATMContext *latmctx = avctx->priv_data;
3312 if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
3315 // check for LOAS sync word
3316 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3317 return AVERROR_INVALIDDATA;
3319 muxlength = get_bits(&gb, 13) + 3;
3320 // not enough data, the parser should have sorted this out
3321 if (muxlength > avpkt->size)
3322 return AVERROR_INVALIDDATA;
3324 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3327 if (!latmctx->initialized) {
3328 if (!avctx->extradata) {
3332 push_output_configuration(&latmctx->aac_ctx);
3333 if ((err = decode_audio_specific_config(
3334 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3335 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3336 pop_output_configuration(&latmctx->aac_ctx);
3339 latmctx->initialized = 1;
3343 if (show_bits(&gb, 12) == 0xfff) {
3344 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3345 "ADTS header detected, probably as result of configuration "
3347 return AVERROR_INVALIDDATA;
3350 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
3356 static av_cold int latm_decode_init(AVCodecContext *avctx)
3358 struct LATMContext *latmctx = avctx->priv_data;
3359 int ret = aac_decode_init(avctx);
3361 if (avctx->extradata_size > 0)
3362 latmctx->initialized = !ret;
3367 static void aacdec_init(AACContext *c)
3369 c->imdct_and_windowing = imdct_and_windowing;
3370 c->apply_ltp = apply_ltp;
3371 c->apply_tns = apply_tns;
3372 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3373 c->update_ltp = update_ltp;
3376 ff_aacdec_init_mips(c);
3379 * AVOptions for Japanese DTV specific extensions (ADTS only)
3381 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3382 static const AVOption options[] = {
3383 {"dual_mono_mode", "Select the channel to decode for dual mono",
3384 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3385 AACDEC_FLAGS, "dual_mono_mode"},
3387 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3388 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3389 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3390 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3395 static const AVClass aac_decoder_class = {
3396 .class_name = "AAC decoder",
3397 .item_name = av_default_item_name,
3399 .version = LIBAVUTIL_VERSION_INT,
3402 AVCodec ff_aac_decoder = {
3404 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3405 .type = AVMEDIA_TYPE_AUDIO,
3406 .id = AV_CODEC_ID_AAC,
3407 .priv_data_size = sizeof(AACContext),
3408 .init = aac_decode_init,
3409 .close = aac_decode_close,
3410 .decode = aac_decode_frame,
3411 .sample_fmts = (const enum AVSampleFormat[]) {
3412 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3414 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3415 .channel_layouts = aac_channel_layout,
3417 .priv_class = &aac_decoder_class,
3421 Note: This decoder filter is intended to decode LATM streams transferred
3422 in MPEG transport streams which only contain one program.
3423 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3425 AVCodec ff_aac_latm_decoder = {
3427 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3428 .type = AVMEDIA_TYPE_AUDIO,
3429 .id = AV_CODEC_ID_AAC_LATM,
3430 .priv_data_size = sizeof(struct LATMContext),
3431 .init = latm_decode_init,
3432 .close = aac_decode_close,
3433 .decode = latm_decode_frame,
3434 .sample_fmts = (const enum AVSampleFormat[]) {
3435 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3437 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3438 .channel_layouts = aac_channel_layout,