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
77 * Y Enhanced AAC Low Delay (ER AAC ELD)
79 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
80 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
84 #include "libavutil/float_dsp.h"
85 #include "libavutil/opt.h"
90 #include "fmtconvert.h"
97 #include "aacdectab.h"
98 #include "cbrt_tablegen.h"
101 #include "mpeg4audio.h"
102 #include "aacadtsdec.h"
103 #include "libavutil/intfloat.h"
112 # include "arm/aac.h"
114 # include "mips/aacdec_mips.h"
117 static VLC vlc_scalefactors;
118 static VLC vlc_spectral[11];
120 static int output_configure(AACContext *ac,
121 uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
122 enum OCStatus oc_type, int get_new_frame);
124 #define overread_err "Input buffer exhausted before END element found\n"
126 static int count_channels(uint8_t (*layout)[3], int tags)
129 for (i = 0; i < tags; i++) {
130 int syn_ele = layout[i][0];
131 int pos = layout[i][2];
132 sum += (1 + (syn_ele == TYPE_CPE)) *
133 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
139 * Check for the channel element in the current channel position configuration.
140 * If it exists, make sure the appropriate element is allocated and map the
141 * channel order to match the internal FFmpeg channel layout.
143 * @param che_pos current channel position configuration
144 * @param type channel element type
145 * @param id channel element id
146 * @param channels count of the number of channels in the configuration
148 * @return Returns error status. 0 - OK, !0 - error
150 static av_cold int che_configure(AACContext *ac,
151 enum ChannelPosition che_pos,
152 int type, int id, int *channels)
154 if (*channels >= MAX_CHANNELS)
155 return AVERROR_INVALIDDATA;
157 if (!ac->che[type][id]) {
158 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
159 return AVERROR(ENOMEM);
160 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
162 if (type != TYPE_CCE) {
163 if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
164 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
165 return AVERROR_INVALIDDATA;
167 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
168 if (type == TYPE_CPE ||
169 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
170 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
174 if (ac->che[type][id])
175 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
176 av_freep(&ac->che[type][id]);
181 static int frame_configure_elements(AVCodecContext *avctx)
183 AACContext *ac = avctx->priv_data;
184 int type, id, ch, ret;
186 /* set channel pointers to internal buffers by default */
187 for (type = 0; type < 4; type++) {
188 for (id = 0; id < MAX_ELEM_ID; id++) {
189 ChannelElement *che = ac->che[type][id];
191 che->ch[0].ret = che->ch[0].ret_buf;
192 che->ch[1].ret = che->ch[1].ret_buf;
197 /* get output buffer */
198 av_frame_unref(ac->frame);
199 ac->frame->nb_samples = 2048;
200 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
203 /* map output channel pointers to AVFrame data */
204 for (ch = 0; ch < avctx->channels; ch++) {
205 if (ac->output_element[ch])
206 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
212 struct elem_to_channel {
213 uint64_t av_position;
216 uint8_t aac_position;
219 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
220 uint8_t (*layout_map)[3], int offset, uint64_t left,
221 uint64_t right, int pos)
223 if (layout_map[offset][0] == TYPE_CPE) {
224 e2c_vec[offset] = (struct elem_to_channel) {
225 .av_position = left | right,
227 .elem_id = layout_map[offset][1],
232 e2c_vec[offset] = (struct elem_to_channel) {
235 .elem_id = layout_map[offset][1],
238 e2c_vec[offset + 1] = (struct elem_to_channel) {
239 .av_position = right,
241 .elem_id = layout_map[offset + 1][1],
248 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
251 int num_pos_channels = 0;
255 for (i = *current; i < tags; i++) {
256 if (layout_map[i][2] != pos)
258 if (layout_map[i][0] == TYPE_CPE) {
260 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
266 num_pos_channels += 2;
274 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
277 return num_pos_channels;
280 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
282 int i, n, total_non_cc_elements;
283 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
284 int num_front_channels, num_side_channels, num_back_channels;
287 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
292 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
293 if (num_front_channels < 0)
296 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
297 if (num_side_channels < 0)
300 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
301 if (num_back_channels < 0)
305 if (num_front_channels & 1) {
306 e2c_vec[i] = (struct elem_to_channel) {
307 .av_position = AV_CH_FRONT_CENTER,
309 .elem_id = layout_map[i][1],
310 .aac_position = AAC_CHANNEL_FRONT
313 num_front_channels--;
315 if (num_front_channels >= 4) {
316 i += assign_pair(e2c_vec, layout_map, i,
317 AV_CH_FRONT_LEFT_OF_CENTER,
318 AV_CH_FRONT_RIGHT_OF_CENTER,
320 num_front_channels -= 2;
322 if (num_front_channels >= 2) {
323 i += assign_pair(e2c_vec, layout_map, i,
327 num_front_channels -= 2;
329 while (num_front_channels >= 2) {
330 i += assign_pair(e2c_vec, layout_map, i,
334 num_front_channels -= 2;
337 if (num_side_channels >= 2) {
338 i += assign_pair(e2c_vec, layout_map, i,
342 num_side_channels -= 2;
344 while (num_side_channels >= 2) {
345 i += assign_pair(e2c_vec, layout_map, i,
349 num_side_channels -= 2;
352 while (num_back_channels >= 4) {
353 i += assign_pair(e2c_vec, layout_map, i,
357 num_back_channels -= 2;
359 if (num_back_channels >= 2) {
360 i += assign_pair(e2c_vec, layout_map, i,
364 num_back_channels -= 2;
366 if (num_back_channels) {
367 e2c_vec[i] = (struct elem_to_channel) {
368 .av_position = AV_CH_BACK_CENTER,
370 .elem_id = layout_map[i][1],
371 .aac_position = AAC_CHANNEL_BACK
377 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
378 e2c_vec[i] = (struct elem_to_channel) {
379 .av_position = AV_CH_LOW_FREQUENCY,
381 .elem_id = layout_map[i][1],
382 .aac_position = AAC_CHANNEL_LFE
386 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
387 e2c_vec[i] = (struct elem_to_channel) {
388 .av_position = UINT64_MAX,
390 .elem_id = layout_map[i][1],
391 .aac_position = AAC_CHANNEL_LFE
396 // Must choose a stable sort
397 total_non_cc_elements = n = i;
400 for (i = 1; i < n; i++)
401 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
402 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
409 for (i = 0; i < total_non_cc_elements; i++) {
410 layout_map[i][0] = e2c_vec[i].syn_ele;
411 layout_map[i][1] = e2c_vec[i].elem_id;
412 layout_map[i][2] = e2c_vec[i].aac_position;
413 if (e2c_vec[i].av_position != UINT64_MAX) {
414 layout |= e2c_vec[i].av_position;
422 * Save current output configuration if and only if it has been locked.
424 static void push_output_configuration(AACContext *ac) {
425 if (ac->oc[1].status == OC_LOCKED) {
426 ac->oc[0] = ac->oc[1];
428 ac->oc[1].status = OC_NONE;
432 * Restore the previous output configuration if and only if the current
433 * configuration is unlocked.
435 static void pop_output_configuration(AACContext *ac) {
436 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
437 ac->oc[1] = ac->oc[0];
438 ac->avctx->channels = ac->oc[1].channels;
439 ac->avctx->channel_layout = ac->oc[1].channel_layout;
440 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
441 ac->oc[1].status, 0);
446 * Configure output channel order based on the current program
447 * configuration element.
449 * @return Returns error status. 0 - OK, !0 - error
451 static int output_configure(AACContext *ac,
452 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
453 enum OCStatus oc_type, int get_new_frame)
455 AVCodecContext *avctx = ac->avctx;
456 int i, channels = 0, ret;
459 if (ac->oc[1].layout_map != layout_map) {
460 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
461 ac->oc[1].layout_map_tags = tags;
464 // Try to sniff a reasonable channel order, otherwise output the
465 // channels in the order the PCE declared them.
466 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
467 layout = sniff_channel_order(layout_map, tags);
468 for (i = 0; i < tags; i++) {
469 int type = layout_map[i][0];
470 int id = layout_map[i][1];
471 int position = layout_map[i][2];
472 // Allocate or free elements depending on if they are in the
473 // current program configuration.
474 ret = che_configure(ac, position, type, id, &channels);
478 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
479 if (layout == AV_CH_FRONT_CENTER) {
480 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
486 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
487 if (layout) avctx->channel_layout = layout;
488 ac->oc[1].channel_layout = layout;
489 avctx->channels = ac->oc[1].channels = channels;
490 ac->oc[1].status = oc_type;
493 if ((ret = frame_configure_elements(ac->avctx)) < 0)
500 static void flush(AVCodecContext *avctx)
502 AACContext *ac= avctx->priv_data;
505 for (type = 3; type >= 0; type--) {
506 for (i = 0; i < MAX_ELEM_ID; i++) {
507 ChannelElement *che = ac->che[type][i];
509 for (j = 0; j <= 1; j++) {
510 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
518 * Set up channel positions based on a default channel configuration
519 * as specified in table 1.17.
521 * @return Returns error status. 0 - OK, !0 - error
523 static int set_default_channel_config(AVCodecContext *avctx,
524 uint8_t (*layout_map)[3],
528 if (channel_config < 1 || channel_config > 7) {
529 av_log(avctx, AV_LOG_ERROR,
530 "invalid default channel configuration (%d)\n",
532 return AVERROR_INVALIDDATA;
534 *tags = tags_per_config[channel_config];
535 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
536 *tags * sizeof(*layout_map));
539 * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
540 * However, at least Nero AAC encoder encodes 7.1 streams using the default
541 * channel config 7, mapping the side channels of the original audio stream
542 * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
543 * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
544 * the incorrect streams as if they were correct (and as the encoder intended).
546 * As actual intended 7.1(wide) streams are very rare, default to assuming a
547 * 7.1 layout was intended.
549 if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT) {
550 av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
551 " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
552 " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
553 layout_map[2][2] = AAC_CHANNEL_SIDE;
559 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
561 /* For PCE based channel configurations map the channels solely based
563 if (!ac->oc[1].m4ac.chan_config) {
564 return ac->tag_che_map[type][elem_id];
566 // Allow single CPE stereo files to be signalled with mono configuration.
567 if (!ac->tags_mapped && type == TYPE_CPE &&
568 ac->oc[1].m4ac.chan_config == 1) {
569 uint8_t layout_map[MAX_ELEM_ID*4][3];
571 push_output_configuration(ac);
573 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
575 if (set_default_channel_config(ac->avctx, layout_map,
576 &layout_map_tags, 2) < 0)
578 if (output_configure(ac, layout_map, layout_map_tags,
579 OC_TRIAL_FRAME, 1) < 0)
582 ac->oc[1].m4ac.chan_config = 2;
583 ac->oc[1].m4ac.ps = 0;
586 if (!ac->tags_mapped && type == TYPE_SCE &&
587 ac->oc[1].m4ac.chan_config == 2) {
588 uint8_t layout_map[MAX_ELEM_ID * 4][3];
590 push_output_configuration(ac);
592 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
594 if (set_default_channel_config(ac->avctx, layout_map,
595 &layout_map_tags, 1) < 0)
597 if (output_configure(ac, layout_map, layout_map_tags,
598 OC_TRIAL_FRAME, 1) < 0)
601 ac->oc[1].m4ac.chan_config = 1;
602 if (ac->oc[1].m4ac.sbr)
603 ac->oc[1].m4ac.ps = -1;
605 /* For indexed channel configurations map the channels solely based
607 switch (ac->oc[1].m4ac.chan_config) {
609 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
611 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
614 /* Some streams incorrectly code 5.1 audio as
615 * SCE[0] CPE[0] CPE[1] SCE[1]
617 * SCE[0] CPE[0] CPE[1] LFE[0].
618 * If we seem to have encountered such a stream, transfer
619 * the LFE[0] element to the SCE[1]'s mapping */
620 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
622 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
625 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
627 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
630 if (ac->tags_mapped == 2 &&
631 ac->oc[1].m4ac.chan_config == 4 &&
634 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
638 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
641 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
642 } else if (ac->oc[1].m4ac.chan_config == 2) {
646 if (!ac->tags_mapped && type == TYPE_SCE) {
648 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
656 * Decode an array of 4 bit element IDs, optionally interleaved with a
657 * stereo/mono switching bit.
659 * @param type speaker type/position for these channels
661 static void decode_channel_map(uint8_t layout_map[][3],
662 enum ChannelPosition type,
663 GetBitContext *gb, int n)
666 enum RawDataBlockType syn_ele;
668 case AAC_CHANNEL_FRONT:
669 case AAC_CHANNEL_BACK:
670 case AAC_CHANNEL_SIDE:
671 syn_ele = get_bits1(gb);
677 case AAC_CHANNEL_LFE:
683 layout_map[0][0] = syn_ele;
684 layout_map[0][1] = get_bits(gb, 4);
685 layout_map[0][2] = type;
691 * Decode program configuration element; reference: table 4.2.
693 * @return Returns error status. 0 - OK, !0 - error
695 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
696 uint8_t (*layout_map)[3],
699 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
704 skip_bits(gb, 2); // object_type
706 sampling_index = get_bits(gb, 4);
707 if (m4ac->sampling_index != sampling_index)
708 av_log(avctx, AV_LOG_WARNING,
709 "Sample rate index in program config element does not "
710 "match the sample rate index configured by the container.\n");
712 num_front = get_bits(gb, 4);
713 num_side = get_bits(gb, 4);
714 num_back = get_bits(gb, 4);
715 num_lfe = get_bits(gb, 2);
716 num_assoc_data = get_bits(gb, 3);
717 num_cc = get_bits(gb, 4);
720 skip_bits(gb, 4); // mono_mixdown_tag
722 skip_bits(gb, 4); // stereo_mixdown_tag
725 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
727 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
728 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
731 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
733 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
735 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
737 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
740 skip_bits_long(gb, 4 * num_assoc_data);
742 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
747 /* comment field, first byte is length */
748 comment_len = get_bits(gb, 8) * 8;
749 if (get_bits_left(gb) < comment_len) {
750 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
751 return AVERROR_INVALIDDATA;
753 skip_bits_long(gb, comment_len);
758 * Decode GA "General Audio" specific configuration; reference: table 4.1.
760 * @param ac pointer to AACContext, may be null
761 * @param avctx pointer to AVCCodecContext, used for logging
763 * @return Returns error status. 0 - OK, !0 - error
765 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
767 MPEG4AudioConfig *m4ac,
770 int extension_flag, ret, ep_config, res_flags;
771 uint8_t layout_map[MAX_ELEM_ID*4][3];
774 if (get_bits1(gb)) { // frameLengthFlag
775 avpriv_request_sample(avctx, "960/120 MDCT window");
776 return AVERROR_PATCHWELCOME;
779 if (get_bits1(gb)) // dependsOnCoreCoder
780 skip_bits(gb, 14); // coreCoderDelay
781 extension_flag = get_bits1(gb);
783 if (m4ac->object_type == AOT_AAC_SCALABLE ||
784 m4ac->object_type == AOT_ER_AAC_SCALABLE)
785 skip_bits(gb, 3); // layerNr
787 if (channel_config == 0) {
788 skip_bits(gb, 4); // element_instance_tag
789 tags = decode_pce(avctx, m4ac, layout_map, gb);
793 if ((ret = set_default_channel_config(avctx, layout_map,
794 &tags, channel_config)))
798 if (count_channels(layout_map, tags) > 1) {
800 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
803 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
806 if (extension_flag) {
807 switch (m4ac->object_type) {
809 skip_bits(gb, 5); // numOfSubFrame
810 skip_bits(gb, 11); // layer_length
814 case AOT_ER_AAC_SCALABLE:
816 res_flags = get_bits(gb, 3);
818 avpriv_report_missing_feature(avctx,
819 "AAC data resilience (flags %x)",
821 return AVERROR_PATCHWELCOME;
825 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
827 switch (m4ac->object_type) {
830 case AOT_ER_AAC_SCALABLE:
832 ep_config = get_bits(gb, 2);
834 avpriv_report_missing_feature(avctx,
835 "epConfig %d", ep_config);
836 return AVERROR_PATCHWELCOME;
842 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
844 MPEG4AudioConfig *m4ac,
847 int ret, ep_config, res_flags;
848 uint8_t layout_map[MAX_ELEM_ID*4][3];
850 const int ELDEXT_TERM = 0;
855 if (get_bits1(gb)) { // frameLengthFlag
856 avpriv_request_sample(avctx, "960/120 MDCT window");
857 return AVERROR_PATCHWELCOME;
860 res_flags = get_bits(gb, 3);
862 avpriv_report_missing_feature(avctx,
863 "AAC data resilience (flags %x)",
865 return AVERROR_PATCHWELCOME;
868 if (get_bits1(gb)) { // ldSbrPresentFlag
869 avpriv_report_missing_feature(avctx,
871 return AVERROR_PATCHWELCOME;
874 while (get_bits(gb, 4) != ELDEXT_TERM) {
875 int len = get_bits(gb, 4);
877 len += get_bits(gb, 8);
879 len += get_bits(gb, 16);
880 if (get_bits_left(gb) < len * 8 + 4) {
881 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
882 return AVERROR_INVALIDDATA;
884 skip_bits_long(gb, 8 * len);
887 if ((ret = set_default_channel_config(avctx, layout_map,
888 &tags, channel_config)))
891 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
894 ep_config = get_bits(gb, 2);
896 avpriv_report_missing_feature(avctx,
897 "epConfig %d", ep_config);
898 return AVERROR_PATCHWELCOME;
904 * Decode audio specific configuration; reference: table 1.13.
906 * @param ac pointer to AACContext, may be null
907 * @param avctx pointer to AVCCodecContext, used for logging
908 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
909 * @param data pointer to buffer holding an audio specific config
910 * @param bit_size size of audio specific config or data in bits
911 * @param sync_extension look for an appended sync extension
913 * @return Returns error status or number of consumed bits. <0 - error
915 static int decode_audio_specific_config(AACContext *ac,
916 AVCodecContext *avctx,
917 MPEG4AudioConfig *m4ac,
918 const uint8_t *data, int bit_size,
924 av_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
925 for (i = 0; i < bit_size >> 3; i++)
926 av_dlog(avctx, "%02x ", data[i]);
927 av_dlog(avctx, "\n");
929 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
932 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
933 sync_extension)) < 0)
934 return AVERROR_INVALIDDATA;
935 if (m4ac->sampling_index > 12) {
936 av_log(avctx, AV_LOG_ERROR,
937 "invalid sampling rate index %d\n",
938 m4ac->sampling_index);
939 return AVERROR_INVALIDDATA;
941 if (m4ac->object_type == AOT_ER_AAC_LD &&
942 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
943 av_log(avctx, AV_LOG_ERROR,
944 "invalid low delay sampling rate index %d\n",
945 m4ac->sampling_index);
946 return AVERROR_INVALIDDATA;
949 skip_bits_long(&gb, i);
951 switch (m4ac->object_type) {
957 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
958 m4ac, m4ac->chan_config)) < 0)
962 if ((ret = decode_eld_specific_config(ac, avctx, &gb,
963 m4ac, m4ac->chan_config)) < 0)
967 avpriv_report_missing_feature(avctx,
968 "Audio object type %s%d",
969 m4ac->sbr == 1 ? "SBR+" : "",
971 return AVERROR(ENOSYS);
975 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
976 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
977 m4ac->sample_rate, m4ac->sbr,
980 return get_bits_count(&gb);
984 * linear congruential pseudorandom number generator
986 * @param previous_val pointer to the current state of the generator
988 * @return Returns a 32-bit pseudorandom integer
990 static av_always_inline int lcg_random(unsigned previous_val)
992 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
996 static av_always_inline void reset_predict_state(PredictorState *ps)
1006 static void reset_all_predictors(PredictorState *ps)
1009 for (i = 0; i < MAX_PREDICTORS; i++)
1010 reset_predict_state(&ps[i]);
1013 static int sample_rate_idx (int rate)
1015 if (92017 <= rate) return 0;
1016 else if (75132 <= rate) return 1;
1017 else if (55426 <= rate) return 2;
1018 else if (46009 <= rate) return 3;
1019 else if (37566 <= rate) return 4;
1020 else if (27713 <= rate) return 5;
1021 else if (23004 <= rate) return 6;
1022 else if (18783 <= rate) return 7;
1023 else if (13856 <= rate) return 8;
1024 else if (11502 <= rate) return 9;
1025 else if (9391 <= rate) return 10;
1029 static void reset_predictor_group(PredictorState *ps, int group_num)
1032 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1033 reset_predict_state(&ps[i]);
1036 #define AAC_INIT_VLC_STATIC(num, size) \
1037 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1038 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1039 sizeof(ff_aac_spectral_bits[num][0]), \
1040 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1041 sizeof(ff_aac_spectral_codes[num][0]), \
1044 static void aacdec_init(AACContext *ac);
1046 static av_cold int aac_decode_init(AVCodecContext *avctx)
1048 AACContext *ac = avctx->priv_data;
1052 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1056 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1058 if (avctx->extradata_size > 0) {
1059 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1061 avctx->extradata_size * 8,
1066 uint8_t layout_map[MAX_ELEM_ID*4][3];
1067 int layout_map_tags;
1069 sr = sample_rate_idx(avctx->sample_rate);
1070 ac->oc[1].m4ac.sampling_index = sr;
1071 ac->oc[1].m4ac.channels = avctx->channels;
1072 ac->oc[1].m4ac.sbr = -1;
1073 ac->oc[1].m4ac.ps = -1;
1075 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1076 if (ff_mpeg4audio_channels[i] == avctx->channels)
1078 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1081 ac->oc[1].m4ac.chan_config = i;
1083 if (ac->oc[1].m4ac.chan_config) {
1084 int ret = set_default_channel_config(avctx, layout_map,
1085 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1087 output_configure(ac, layout_map, layout_map_tags,
1089 else if (avctx->err_recognition & AV_EF_EXPLODE)
1090 return AVERROR_INVALIDDATA;
1094 if (avctx->channels > MAX_CHANNELS) {
1095 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1096 return AVERROR_INVALIDDATA;
1099 AAC_INIT_VLC_STATIC( 0, 304);
1100 AAC_INIT_VLC_STATIC( 1, 270);
1101 AAC_INIT_VLC_STATIC( 2, 550);
1102 AAC_INIT_VLC_STATIC( 3, 300);
1103 AAC_INIT_VLC_STATIC( 4, 328);
1104 AAC_INIT_VLC_STATIC( 5, 294);
1105 AAC_INIT_VLC_STATIC( 6, 306);
1106 AAC_INIT_VLC_STATIC( 7, 268);
1107 AAC_INIT_VLC_STATIC( 8, 510);
1108 AAC_INIT_VLC_STATIC( 9, 366);
1109 AAC_INIT_VLC_STATIC(10, 462);
1113 ff_fmt_convert_init(&ac->fmt_conv, avctx);
1114 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
1116 ac->random_state = 0x1f2e3d4c;
1120 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1121 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1122 ff_aac_scalefactor_bits,
1123 sizeof(ff_aac_scalefactor_bits[0]),
1124 sizeof(ff_aac_scalefactor_bits[0]),
1125 ff_aac_scalefactor_code,
1126 sizeof(ff_aac_scalefactor_code[0]),
1127 sizeof(ff_aac_scalefactor_code[0]),
1130 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1131 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1132 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1133 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1134 // window initialization
1135 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1136 ff_kbd_window_init(ff_aac_kbd_long_512, 4.0, 512);
1137 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1138 ff_init_ff_sine_windows(10);
1139 ff_init_ff_sine_windows( 9);
1140 ff_init_ff_sine_windows( 7);
1148 * Skip data_stream_element; reference: table 4.10.
1150 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1152 int byte_align = get_bits1(gb);
1153 int count = get_bits(gb, 8);
1155 count += get_bits(gb, 8);
1159 if (get_bits_left(gb) < 8 * count) {
1160 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1161 return AVERROR_INVALIDDATA;
1163 skip_bits_long(gb, 8 * count);
1167 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1171 if (get_bits1(gb)) {
1172 ics->predictor_reset_group = get_bits(gb, 5);
1173 if (ics->predictor_reset_group == 0 ||
1174 ics->predictor_reset_group > 30) {
1175 av_log(ac->avctx, AV_LOG_ERROR,
1176 "Invalid Predictor Reset Group.\n");
1177 return AVERROR_INVALIDDATA;
1180 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1181 ics->prediction_used[sfb] = get_bits1(gb);
1187 * Decode Long Term Prediction data; reference: table 4.xx.
1189 static void decode_ltp(LongTermPrediction *ltp,
1190 GetBitContext *gb, uint8_t max_sfb)
1194 ltp->lag = get_bits(gb, 11);
1195 ltp->coef = ltp_coef[get_bits(gb, 3)];
1196 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1197 ltp->used[sfb] = get_bits1(gb);
1201 * Decode Individual Channel Stream info; reference: table 4.6.
1203 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1206 int aot = ac->oc[1].m4ac.object_type;
1207 if (aot != AOT_ER_AAC_ELD) {
1208 if (get_bits1(gb)) {
1209 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1210 return AVERROR_INVALIDDATA;
1212 ics->window_sequence[1] = ics->window_sequence[0];
1213 ics->window_sequence[0] = get_bits(gb, 2);
1214 if (aot == AOT_ER_AAC_LD &&
1215 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1216 av_log(ac->avctx, AV_LOG_ERROR,
1217 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1218 "window sequence %d found.\n", ics->window_sequence[0]);
1219 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1220 return AVERROR_INVALIDDATA;
1222 ics->use_kb_window[1] = ics->use_kb_window[0];
1223 ics->use_kb_window[0] = get_bits1(gb);
1225 ics->num_window_groups = 1;
1226 ics->group_len[0] = 1;
1227 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1229 ics->max_sfb = get_bits(gb, 4);
1230 for (i = 0; i < 7; i++) {
1231 if (get_bits1(gb)) {
1232 ics->group_len[ics->num_window_groups - 1]++;
1234 ics->num_window_groups++;
1235 ics->group_len[ics->num_window_groups - 1] = 1;
1238 ics->num_windows = 8;
1239 ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1240 ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1241 ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1242 ics->predictor_present = 0;
1244 ics->max_sfb = get_bits(gb, 6);
1245 ics->num_windows = 1;
1246 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1247 ics->swb_offset = ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];
1248 ics->num_swb = ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];
1249 if (!ics->num_swb || !ics->swb_offset)
1252 ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1253 ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1255 ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1256 if (aot != AOT_ER_AAC_ELD) {
1257 ics->predictor_present = get_bits1(gb);
1258 ics->predictor_reset_group = 0;
1260 if (ics->predictor_present) {
1261 if (aot == AOT_AAC_MAIN) {
1262 if (decode_prediction(ac, ics, gb)) {
1265 } else if (aot == AOT_AAC_LC ||
1266 aot == AOT_ER_AAC_LC) {
1267 av_log(ac->avctx, AV_LOG_ERROR,
1268 "Prediction is not allowed in AAC-LC.\n");
1271 if (aot == AOT_ER_AAC_LD) {
1272 av_log(ac->avctx, AV_LOG_ERROR,
1273 "LTP in ER AAC LD not yet implemented.\n");
1274 return AVERROR_PATCHWELCOME;
1276 if ((ics->ltp.present = get_bits(gb, 1)))
1277 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1282 if (ics->max_sfb > ics->num_swb) {
1283 av_log(ac->avctx, AV_LOG_ERROR,
1284 "Number of scalefactor bands in group (%d) "
1285 "exceeds limit (%d).\n",
1286 ics->max_sfb, ics->num_swb);
1293 return AVERROR_INVALIDDATA;
1297 * Decode band types (section_data payload); reference: table 4.46.
1299 * @param band_type array of the used band type
1300 * @param band_type_run_end array of the last scalefactor band of a band type run
1302 * @return Returns error status. 0 - OK, !0 - error
1304 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1305 int band_type_run_end[120], GetBitContext *gb,
1306 IndividualChannelStream *ics)
1309 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1310 for (g = 0; g < ics->num_window_groups; g++) {
1312 while (k < ics->max_sfb) {
1313 uint8_t sect_end = k;
1315 int sect_band_type = get_bits(gb, 4);
1316 if (sect_band_type == 12) {
1317 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1318 return AVERROR_INVALIDDATA;
1321 sect_len_incr = get_bits(gb, bits);
1322 sect_end += sect_len_incr;
1323 if (get_bits_left(gb) < 0) {
1324 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1325 return AVERROR_INVALIDDATA;
1327 if (sect_end > ics->max_sfb) {
1328 av_log(ac->avctx, AV_LOG_ERROR,
1329 "Number of bands (%d) exceeds limit (%d).\n",
1330 sect_end, ics->max_sfb);
1331 return AVERROR_INVALIDDATA;
1333 } while (sect_len_incr == (1 << bits) - 1);
1334 for (; k < sect_end; k++) {
1335 band_type [idx] = sect_band_type;
1336 band_type_run_end[idx++] = sect_end;
1344 * Decode scalefactors; reference: table 4.47.
1346 * @param global_gain first scalefactor value as scalefactors are differentially coded
1347 * @param band_type array of the used band type
1348 * @param band_type_run_end array of the last scalefactor band of a band type run
1349 * @param sf array of scalefactors or intensity stereo positions
1351 * @return Returns error status. 0 - OK, !0 - error
1353 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1354 unsigned int global_gain,
1355 IndividualChannelStream *ics,
1356 enum BandType band_type[120],
1357 int band_type_run_end[120])
1360 int offset[3] = { global_gain, global_gain - 90, 0 };
1363 for (g = 0; g < ics->num_window_groups; g++) {
1364 for (i = 0; i < ics->max_sfb;) {
1365 int run_end = band_type_run_end[idx];
1366 if (band_type[idx] == ZERO_BT) {
1367 for (; i < run_end; i++, idx++)
1369 } else if ((band_type[idx] == INTENSITY_BT) ||
1370 (band_type[idx] == INTENSITY_BT2)) {
1371 for (; i < run_end; i++, idx++) {
1372 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1373 clipped_offset = av_clip(offset[2], -155, 100);
1374 if (offset[2] != clipped_offset) {
1375 avpriv_request_sample(ac->avctx,
1376 "If you heard an audible artifact, there may be a bug in the decoder. "
1377 "Clipped intensity stereo position (%d -> %d)",
1378 offset[2], clipped_offset);
1380 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1382 } else if (band_type[idx] == NOISE_BT) {
1383 for (; i < run_end; i++, idx++) {
1384 if (noise_flag-- > 0)
1385 offset[1] += get_bits(gb, 9) - 256;
1387 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1388 clipped_offset = av_clip(offset[1], -100, 155);
1389 if (offset[1] != clipped_offset) {
1390 avpriv_request_sample(ac->avctx,
1391 "If you heard an audible artifact, there may be a bug in the decoder. "
1392 "Clipped noise gain (%d -> %d)",
1393 offset[1], clipped_offset);
1395 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1398 for (; i < run_end; i++, idx++) {
1399 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1400 if (offset[0] > 255U) {
1401 av_log(ac->avctx, AV_LOG_ERROR,
1402 "Scalefactor (%d) out of range.\n", offset[0]);
1403 return AVERROR_INVALIDDATA;
1405 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1414 * Decode pulse data; reference: table 4.7.
1416 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1417 const uint16_t *swb_offset, int num_swb)
1420 pulse->num_pulse = get_bits(gb, 2) + 1;
1421 pulse_swb = get_bits(gb, 6);
1422 if (pulse_swb >= num_swb)
1424 pulse->pos[0] = swb_offset[pulse_swb];
1425 pulse->pos[0] += get_bits(gb, 5);
1426 if (pulse->pos[0] > 1023)
1428 pulse->amp[0] = get_bits(gb, 4);
1429 for (i = 1; i < pulse->num_pulse; i++) {
1430 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1431 if (pulse->pos[i] > 1023)
1433 pulse->amp[i] = get_bits(gb, 4);
1439 * Decode Temporal Noise Shaping data; reference: table 4.48.
1441 * @return Returns error status. 0 - OK, !0 - error
1443 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1444 GetBitContext *gb, const IndividualChannelStream *ics)
1446 int w, filt, i, coef_len, coef_res, coef_compress;
1447 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1448 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1449 for (w = 0; w < ics->num_windows; w++) {
1450 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1451 coef_res = get_bits1(gb);
1453 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1455 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1457 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1458 av_log(ac->avctx, AV_LOG_ERROR,
1459 "TNS filter order %d is greater than maximum %d.\n",
1460 tns->order[w][filt], tns_max_order);
1461 tns->order[w][filt] = 0;
1462 return AVERROR_INVALIDDATA;
1464 if (tns->order[w][filt]) {
1465 tns->direction[w][filt] = get_bits1(gb);
1466 coef_compress = get_bits1(gb);
1467 coef_len = coef_res + 3 - coef_compress;
1468 tmp2_idx = 2 * coef_compress + coef_res;
1470 for (i = 0; i < tns->order[w][filt]; i++)
1471 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1480 * Decode Mid/Side data; reference: table 4.54.
1482 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1483 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1484 * [3] reserved for scalable AAC
1486 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1490 if (ms_present == 1) {
1492 idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1494 cpe->ms_mask[idx] = get_bits1(gb);
1495 } else if (ms_present == 2) {
1496 memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
1501 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1505 *dst++ = v[idx & 15] * s;
1506 *dst++ = v[idx>>4 & 15] * s;
1512 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1516 *dst++ = v[idx & 3] * s;
1517 *dst++ = v[idx>>2 & 3] * s;
1518 *dst++ = v[idx>>4 & 3] * s;
1519 *dst++ = v[idx>>6 & 3] * s;
1525 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1526 unsigned sign, const float *scale)
1528 union av_intfloat32 s0, s1;
1530 s0.f = s1.f = *scale;
1531 s0.i ^= sign >> 1 << 31;
1534 *dst++ = v[idx & 15] * s0.f;
1535 *dst++ = v[idx>>4 & 15] * s1.f;
1542 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1543 unsigned sign, const float *scale)
1545 unsigned nz = idx >> 12;
1546 union av_intfloat32 s = { .f = *scale };
1547 union av_intfloat32 t;
1549 t.i = s.i ^ (sign & 1U<<31);
1550 *dst++ = v[idx & 3] * t.f;
1552 sign <<= nz & 1; nz >>= 1;
1553 t.i = s.i ^ (sign & 1U<<31);
1554 *dst++ = v[idx>>2 & 3] * t.f;
1556 sign <<= nz & 1; nz >>= 1;
1557 t.i = s.i ^ (sign & 1U<<31);
1558 *dst++ = v[idx>>4 & 3] * t.f;
1561 t.i = s.i ^ (sign & 1U<<31);
1562 *dst++ = v[idx>>6 & 3] * t.f;
1569 * Decode spectral data; reference: table 4.50.
1570 * Dequantize and scale spectral data; reference: 4.6.3.3.
1572 * @param coef array of dequantized, scaled spectral data
1573 * @param sf array of scalefactors or intensity stereo positions
1574 * @param pulse_present set if pulses are present
1575 * @param pulse pointer to pulse data struct
1576 * @param band_type array of the used band type
1578 * @return Returns error status. 0 - OK, !0 - error
1580 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1581 GetBitContext *gb, const float sf[120],
1582 int pulse_present, const Pulse *pulse,
1583 const IndividualChannelStream *ics,
1584 enum BandType band_type[120])
1586 int i, k, g, idx = 0;
1587 const int c = 1024 / ics->num_windows;
1588 const uint16_t *offsets = ics->swb_offset;
1589 float *coef_base = coef;
1591 for (g = 0; g < ics->num_windows; g++)
1592 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1593 sizeof(float) * (c - offsets[ics->max_sfb]));
1595 for (g = 0; g < ics->num_window_groups; g++) {
1596 unsigned g_len = ics->group_len[g];
1598 for (i = 0; i < ics->max_sfb; i++, idx++) {
1599 const unsigned cbt_m1 = band_type[idx] - 1;
1600 float *cfo = coef + offsets[i];
1601 int off_len = offsets[i + 1] - offsets[i];
1604 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1605 for (group = 0; group < g_len; group++, cfo+=128) {
1606 memset(cfo, 0, off_len * sizeof(float));
1608 } else if (cbt_m1 == NOISE_BT - 1) {
1609 for (group = 0; group < g_len; group++, cfo+=128) {
1613 for (k = 0; k < off_len; k++) {
1614 ac->random_state = lcg_random(ac->random_state);
1615 cfo[k] = ac->random_state;
1618 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1619 scale = sf[idx] / sqrtf(band_energy);
1620 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1623 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1624 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1625 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1626 OPEN_READER(re, gb);
1628 switch (cbt_m1 >> 1) {
1630 for (group = 0; group < g_len; group++, cfo+=128) {
1638 UPDATE_CACHE(re, gb);
1639 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1640 cb_idx = cb_vector_idx[code];
1641 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1647 for (group = 0; group < g_len; group++, cfo+=128) {
1657 UPDATE_CACHE(re, gb);
1658 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1659 cb_idx = cb_vector_idx[code];
1660 nnz = cb_idx >> 8 & 15;
1661 bits = nnz ? GET_CACHE(re, gb) : 0;
1662 LAST_SKIP_BITS(re, gb, nnz);
1663 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1669 for (group = 0; group < g_len; group++, cfo+=128) {
1677 UPDATE_CACHE(re, gb);
1678 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1679 cb_idx = cb_vector_idx[code];
1680 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1687 for (group = 0; group < g_len; group++, cfo+=128) {
1697 UPDATE_CACHE(re, gb);
1698 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1699 cb_idx = cb_vector_idx[code];
1700 nnz = cb_idx >> 8 & 15;
1701 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1702 LAST_SKIP_BITS(re, gb, nnz);
1703 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1709 for (group = 0; group < g_len; group++, cfo+=128) {
1711 uint32_t *icf = (uint32_t *) cf;
1721 UPDATE_CACHE(re, gb);
1722 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1730 cb_idx = cb_vector_idx[code];
1733 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1734 LAST_SKIP_BITS(re, gb, nnz);
1736 for (j = 0; j < 2; j++) {
1740 /* The total length of escape_sequence must be < 22 bits according
1741 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1742 UPDATE_CACHE(re, gb);
1743 b = GET_CACHE(re, gb);
1744 b = 31 - av_log2(~b);
1747 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1748 return AVERROR_INVALIDDATA;
1751 SKIP_BITS(re, gb, b + 1);
1753 n = (1 << b) + SHOW_UBITS(re, gb, b);
1754 LAST_SKIP_BITS(re, gb, b);
1755 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1758 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1759 *icf++ = (bits & 1U<<31) | v;
1766 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1770 CLOSE_READER(re, gb);
1776 if (pulse_present) {
1778 for (i = 0; i < pulse->num_pulse; i++) {
1779 float co = coef_base[ pulse->pos[i] ];
1780 while (offsets[idx + 1] <= pulse->pos[i])
1782 if (band_type[idx] != NOISE_BT && sf[idx]) {
1783 float ico = -pulse->amp[i];
1786 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1788 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1795 static av_always_inline float flt16_round(float pf)
1797 union av_intfloat32 tmp;
1799 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1803 static av_always_inline float flt16_even(float pf)
1805 union av_intfloat32 tmp;
1807 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1811 static av_always_inline float flt16_trunc(float pf)
1813 union av_intfloat32 pun;
1815 pun.i &= 0xFFFF0000U;
1819 static av_always_inline void predict(PredictorState *ps, float *coef,
1822 const float a = 0.953125; // 61.0 / 64
1823 const float alpha = 0.90625; // 29.0 / 32
1827 float r0 = ps->r0, r1 = ps->r1;
1828 float cor0 = ps->cor0, cor1 = ps->cor1;
1829 float var0 = ps->var0, var1 = ps->var1;
1831 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1832 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1834 pv = flt16_round(k1 * r0 + k2 * r1);
1841 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1842 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1843 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1844 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1846 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1847 ps->r0 = flt16_trunc(a * e0);
1851 * Apply AAC-Main style frequency domain prediction.
1853 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1857 if (!sce->ics.predictor_initialized) {
1858 reset_all_predictors(sce->predictor_state);
1859 sce->ics.predictor_initialized = 1;
1862 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1864 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1866 for (k = sce->ics.swb_offset[sfb];
1867 k < sce->ics.swb_offset[sfb + 1];
1869 predict(&sce->predictor_state[k], &sce->coeffs[k],
1870 sce->ics.predictor_present &&
1871 sce->ics.prediction_used[sfb]);
1874 if (sce->ics.predictor_reset_group)
1875 reset_predictor_group(sce->predictor_state,
1876 sce->ics.predictor_reset_group);
1878 reset_all_predictors(sce->predictor_state);
1882 * Decode an individual_channel_stream payload; reference: table 4.44.
1884 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1885 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1887 * @return Returns error status. 0 - OK, !0 - error
1889 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1890 GetBitContext *gb, int common_window, int scale_flag)
1893 TemporalNoiseShaping *tns = &sce->tns;
1894 IndividualChannelStream *ics = &sce->ics;
1895 float *out = sce->coeffs;
1896 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1899 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1900 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1901 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1902 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1903 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1905 /* This assignment is to silence a GCC warning about the variable being used
1906 * uninitialized when in fact it always is.
1908 pulse.num_pulse = 0;
1910 global_gain = get_bits(gb, 8);
1912 if (!common_window && !scale_flag) {
1913 if (decode_ics_info(ac, ics, gb) < 0)
1914 return AVERROR_INVALIDDATA;
1917 if ((ret = decode_band_types(ac, sce->band_type,
1918 sce->band_type_run_end, gb, ics)) < 0)
1920 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1921 sce->band_type, sce->band_type_run_end)) < 0)
1926 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1927 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1928 av_log(ac->avctx, AV_LOG_ERROR,
1929 "Pulse tool not allowed in eight short sequence.\n");
1930 return AVERROR_INVALIDDATA;
1932 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1933 av_log(ac->avctx, AV_LOG_ERROR,
1934 "Pulse data corrupt or invalid.\n");
1935 return AVERROR_INVALIDDATA;
1938 tns->present = get_bits1(gb);
1939 if (tns->present && !er_syntax)
1940 if (decode_tns(ac, tns, gb, ics) < 0)
1941 return AVERROR_INVALIDDATA;
1942 if (!eld_syntax && get_bits1(gb)) {
1943 avpriv_request_sample(ac->avctx, "SSR");
1944 return AVERROR_PATCHWELCOME;
1946 // I see no textual basis in the spec for this occuring after SSR gain
1947 // control, but this is what both reference and real implmentations do
1948 if (tns->present && er_syntax)
1949 if (decode_tns(ac, tns, gb, ics) < 0)
1950 return AVERROR_INVALIDDATA;
1953 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1954 &pulse, ics, sce->band_type) < 0)
1955 return AVERROR_INVALIDDATA;
1957 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1958 apply_prediction(ac, sce);
1964 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1966 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1968 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1969 float *ch0 = cpe->ch[0].coeffs;
1970 float *ch1 = cpe->ch[1].coeffs;
1971 int g, i, group, idx = 0;
1972 const uint16_t *offsets = ics->swb_offset;
1973 for (g = 0; g < ics->num_window_groups; g++) {
1974 for (i = 0; i < ics->max_sfb; i++, idx++) {
1975 if (cpe->ms_mask[idx] &&
1976 cpe->ch[0].band_type[idx] < NOISE_BT &&
1977 cpe->ch[1].band_type[idx] < NOISE_BT) {
1978 for (group = 0; group < ics->group_len[g]; group++) {
1979 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1980 ch1 + group * 128 + offsets[i],
1981 offsets[i+1] - offsets[i]);
1985 ch0 += ics->group_len[g] * 128;
1986 ch1 += ics->group_len[g] * 128;
1991 * intensity stereo decoding; reference: 4.6.8.2.3
1993 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1994 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1995 * [3] reserved for scalable AAC
1997 static void apply_intensity_stereo(AACContext *ac,
1998 ChannelElement *cpe, int ms_present)
2000 const IndividualChannelStream *ics = &cpe->ch[1].ics;
2001 SingleChannelElement *sce1 = &cpe->ch[1];
2002 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2003 const uint16_t *offsets = ics->swb_offset;
2004 int g, group, i, idx = 0;
2007 for (g = 0; g < ics->num_window_groups; g++) {
2008 for (i = 0; i < ics->max_sfb;) {
2009 if (sce1->band_type[idx] == INTENSITY_BT ||
2010 sce1->band_type[idx] == INTENSITY_BT2) {
2011 const int bt_run_end = sce1->band_type_run_end[idx];
2012 for (; i < bt_run_end; i++, idx++) {
2013 c = -1 + 2 * (sce1->band_type[idx] - 14);
2015 c *= 1 - 2 * cpe->ms_mask[idx];
2016 scale = c * sce1->sf[idx];
2017 for (group = 0; group < ics->group_len[g]; group++)
2018 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2019 coef0 + group * 128 + offsets[i],
2021 offsets[i + 1] - offsets[i]);
2024 int bt_run_end = sce1->band_type_run_end[idx];
2025 idx += bt_run_end - i;
2029 coef0 += ics->group_len[g] * 128;
2030 coef1 += ics->group_len[g] * 128;
2035 * Decode a channel_pair_element; reference: table 4.4.
2037 * @return Returns error status. 0 - OK, !0 - error
2039 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2041 int i, ret, common_window, ms_present = 0;
2042 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2044 common_window = eld_syntax || get_bits1(gb);
2045 if (common_window) {
2046 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2047 return AVERROR_INVALIDDATA;
2048 i = cpe->ch[1].ics.use_kb_window[0];
2049 cpe->ch[1].ics = cpe->ch[0].ics;
2050 cpe->ch[1].ics.use_kb_window[1] = i;
2051 if (cpe->ch[1].ics.predictor_present &&
2052 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2053 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2054 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2055 ms_present = get_bits(gb, 2);
2056 if (ms_present == 3) {
2057 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2058 return AVERROR_INVALIDDATA;
2059 } else if (ms_present)
2060 decode_mid_side_stereo(cpe, gb, ms_present);
2062 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2064 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2067 if (common_window) {
2069 apply_mid_side_stereo(ac, cpe);
2070 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2071 apply_prediction(ac, &cpe->ch[0]);
2072 apply_prediction(ac, &cpe->ch[1]);
2076 apply_intensity_stereo(ac, cpe, ms_present);
2080 static const float cce_scale[] = {
2081 1.09050773266525765921, //2^(1/8)
2082 1.18920711500272106672, //2^(1/4)
2088 * Decode coupling_channel_element; reference: table 4.8.
2090 * @return Returns error status. 0 - OK, !0 - error
2092 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2098 SingleChannelElement *sce = &che->ch[0];
2099 ChannelCoupling *coup = &che->coup;
2101 coup->coupling_point = 2 * get_bits1(gb);
2102 coup->num_coupled = get_bits(gb, 3);
2103 for (c = 0; c <= coup->num_coupled; c++) {
2105 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2106 coup->id_select[c] = get_bits(gb, 4);
2107 if (coup->type[c] == TYPE_CPE) {
2108 coup->ch_select[c] = get_bits(gb, 2);
2109 if (coup->ch_select[c] == 3)
2112 coup->ch_select[c] = 2;
2114 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2116 sign = get_bits(gb, 1);
2117 scale = cce_scale[get_bits(gb, 2)];
2119 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2122 for (c = 0; c < num_gain; c++) {
2126 float gain_cache = 1.0;
2128 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2129 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2130 gain_cache = powf(scale, -gain);
2132 if (coup->coupling_point == AFTER_IMDCT) {
2133 coup->gain[c][0] = gain_cache;
2135 for (g = 0; g < sce->ics.num_window_groups; g++) {
2136 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2137 if (sce->band_type[idx] != ZERO_BT) {
2139 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2147 gain_cache = powf(scale, -t) * s;
2150 coup->gain[c][idx] = gain_cache;
2160 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2162 * @return Returns number of bytes consumed.
2164 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2168 int num_excl_chan = 0;
2171 for (i = 0; i < 7; i++)
2172 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2173 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2175 return num_excl_chan / 7;
2179 * Decode dynamic range information; reference: table 4.52.
2181 * @return Returns number of bytes consumed.
2183 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2187 int drc_num_bands = 1;
2190 /* pce_tag_present? */
2191 if (get_bits1(gb)) {
2192 che_drc->pce_instance_tag = get_bits(gb, 4);
2193 skip_bits(gb, 4); // tag_reserved_bits
2197 /* excluded_chns_present? */
2198 if (get_bits1(gb)) {
2199 n += decode_drc_channel_exclusions(che_drc, gb);
2202 /* drc_bands_present? */
2203 if (get_bits1(gb)) {
2204 che_drc->band_incr = get_bits(gb, 4);
2205 che_drc->interpolation_scheme = get_bits(gb, 4);
2207 drc_num_bands += che_drc->band_incr;
2208 for (i = 0; i < drc_num_bands; i++) {
2209 che_drc->band_top[i] = get_bits(gb, 8);
2214 /* prog_ref_level_present? */
2215 if (get_bits1(gb)) {
2216 che_drc->prog_ref_level = get_bits(gb, 7);
2217 skip_bits1(gb); // prog_ref_level_reserved_bits
2221 for (i = 0; i < drc_num_bands; i++) {
2222 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2223 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2230 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2232 int i, major, minor;
2237 get_bits(gb, 13); len -= 13;
2239 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2240 buf[i] = get_bits(gb, 8);
2243 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2244 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2246 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2247 ac->avctx->internal->skip_samples = 1024;
2251 skip_bits_long(gb, len);
2257 * Decode extension data (incomplete); reference: table 4.51.
2259 * @param cnt length of TYPE_FIL syntactic element in bytes
2261 * @return Returns number of bytes consumed
2263 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2264 ChannelElement *che, enum RawDataBlockType elem_type)
2268 switch (get_bits(gb, 4)) { // extension type
2269 case EXT_SBR_DATA_CRC:
2273 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2275 } else if (!ac->oc[1].m4ac.sbr) {
2276 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2277 skip_bits_long(gb, 8 * cnt - 4);
2279 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2280 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2281 skip_bits_long(gb, 8 * cnt - 4);
2283 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2284 ac->oc[1].m4ac.sbr = 1;
2285 ac->oc[1].m4ac.ps = 1;
2286 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2287 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2288 ac->oc[1].status, 1);
2290 ac->oc[1].m4ac.sbr = 1;
2291 ac->avctx->profile = FF_PROFILE_AAC_HE;
2293 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2295 case EXT_DYNAMIC_RANGE:
2296 res = decode_dynamic_range(&ac->che_drc, gb);
2299 decode_fill(ac, gb, 8 * cnt - 4);
2302 case EXT_DATA_ELEMENT:
2304 skip_bits_long(gb, 8 * cnt - 4);
2311 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2313 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2314 * @param coef spectral coefficients
2316 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2317 IndividualChannelStream *ics, int decode)
2319 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2321 int bottom, top, order, start, end, size, inc;
2322 float lpc[TNS_MAX_ORDER];
2323 float tmp[TNS_MAX_ORDER+1];
2325 for (w = 0; w < ics->num_windows; w++) {
2326 bottom = ics->num_swb;
2327 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2329 bottom = FFMAX(0, top - tns->length[w][filt]);
2330 order = tns->order[w][filt];
2335 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2337 start = ics->swb_offset[FFMIN(bottom, mmm)];
2338 end = ics->swb_offset[FFMIN( top, mmm)];
2339 if ((size = end - start) <= 0)
2341 if (tns->direction[w][filt]) {
2351 for (m = 0; m < size; m++, start += inc)
2352 for (i = 1; i <= FFMIN(m, order); i++)
2353 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2356 for (m = 0; m < size; m++, start += inc) {
2357 tmp[0] = coef[start];
2358 for (i = 1; i <= FFMIN(m, order); i++)
2359 coef[start] += tmp[i] * lpc[i - 1];
2360 for (i = order; i > 0; i--)
2361 tmp[i] = tmp[i - 1];
2369 * Apply windowing and MDCT to obtain the spectral
2370 * coefficient from the predicted sample by LTP.
2372 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2373 float *in, IndividualChannelStream *ics)
2375 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2376 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2377 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2378 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2380 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2381 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2383 memset(in, 0, 448 * sizeof(float));
2384 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2386 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2387 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2389 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2390 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2392 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2396 * Apply the long term prediction
2398 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2400 const LongTermPrediction *ltp = &sce->ics.ltp;
2401 const uint16_t *offsets = sce->ics.swb_offset;
2404 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2405 float *predTime = sce->ret;
2406 float *predFreq = ac->buf_mdct;
2407 int16_t num_samples = 2048;
2409 if (ltp->lag < 1024)
2410 num_samples = ltp->lag + 1024;
2411 for (i = 0; i < num_samples; i++)
2412 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2413 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2415 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2417 if (sce->tns.present)
2418 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2420 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2422 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2423 sce->coeffs[i] += predFreq[i];
2428 * Update the LTP buffer for next frame
2430 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2432 IndividualChannelStream *ics = &sce->ics;
2433 float *saved = sce->saved;
2434 float *saved_ltp = sce->coeffs;
2435 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2436 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2439 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2440 memcpy(saved_ltp, saved, 512 * sizeof(float));
2441 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2442 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2443 for (i = 0; i < 64; i++)
2444 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2445 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2446 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2447 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2448 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2449 for (i = 0; i < 64; i++)
2450 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2451 } else { // LONG_STOP or ONLY_LONG
2452 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2453 for (i = 0; i < 512; i++)
2454 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2457 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2458 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2459 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2463 * Conduct IMDCT and windowing.
2465 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2467 IndividualChannelStream *ics = &sce->ics;
2468 float *in = sce->coeffs;
2469 float *out = sce->ret;
2470 float *saved = sce->saved;
2471 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2472 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2473 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2474 float *buf = ac->buf_mdct;
2475 float *temp = ac->temp;
2479 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2480 for (i = 0; i < 1024; i += 128)
2481 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2483 ac->mdct.imdct_half(&ac->mdct, buf, in);
2485 /* window overlapping
2486 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2487 * and long to short transitions are considered to be short to short
2488 * transitions. This leaves just two cases (long to long and short to short)
2489 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2491 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2492 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2493 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2495 memcpy( out, saved, 448 * sizeof(float));
2497 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2498 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2499 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2500 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2501 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2502 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2503 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2505 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2506 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2511 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2512 memcpy( saved, temp + 64, 64 * sizeof(float));
2513 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2514 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2515 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2516 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2517 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2518 memcpy( saved, buf + 512, 448 * sizeof(float));
2519 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2520 } else { // LONG_STOP or ONLY_LONG
2521 memcpy( saved, buf + 512, 512 * sizeof(float));
2525 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2527 IndividualChannelStream *ics = &sce->ics;
2528 float *in = sce->coeffs;
2529 float *out = sce->ret;
2530 float *saved = sce->saved;
2531 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_512 : ff_sine_512;
2532 float *buf = ac->buf_mdct;
2535 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2537 // window overlapping
2538 ac->fdsp.vector_fmul_window(out, saved, buf, lwindow_prev, 256);
2541 memcpy(saved, buf + 256, 256 * sizeof(float));
2544 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2546 float *in = sce->coeffs;
2547 float *out = sce->ret;
2548 float *saved = sce->saved;
2549 const float *const window = ff_aac_eld_window;
2550 float *buf = ac->buf_mdct;
2553 const int n2 = n >> 1;
2554 const int n4 = n >> 2;
2556 // Inverse transform, mapped to the conventional IMDCT by
2557 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2558 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2559 // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2560 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2561 for (i = 0; i < n2; i+=2) {
2563 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2564 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2566 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2567 for (i = 0; i < n; i+=2) {
2570 // Like with the regular IMDCT at this point we still have the middle half
2571 // of a transform but with even symmetry on the left and odd symmetry on
2574 // window overlapping
2575 // The spec says to use samples [0..511] but the reference decoder uses
2576 // samples [128..639].
2577 for (i = n4; i < n2; i ++) {
2578 out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2579 saved[ i + n2] * window[i + n - n4] +
2580 -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2581 -saved[2*n + n2 + i] * window[i + 3*n - n4];
2583 for (i = 0; i < n2; i ++) {
2584 out[n4 + i] = buf[i] * window[i + n2 - n4] +
2585 -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2586 -saved[ n + i] * window[i + n2 + 2*n - n4] +
2587 saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2589 for (i = 0; i < n4; i ++) {
2590 out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2591 -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2592 -saved[ n + n2 + i] * window[i + 3*n - n4];
2596 memmove(saved + n, saved, 2 * n * sizeof(float));
2597 memcpy( saved, buf, n * sizeof(float));
2601 * Apply dependent channel coupling (applied before IMDCT).
2603 * @param index index into coupling gain array
2605 static void apply_dependent_coupling(AACContext *ac,
2606 SingleChannelElement *target,
2607 ChannelElement *cce, int index)
2609 IndividualChannelStream *ics = &cce->ch[0].ics;
2610 const uint16_t *offsets = ics->swb_offset;
2611 float *dest = target->coeffs;
2612 const float *src = cce->ch[0].coeffs;
2613 int g, i, group, k, idx = 0;
2614 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2615 av_log(ac->avctx, AV_LOG_ERROR,
2616 "Dependent coupling is not supported together with LTP\n");
2619 for (g = 0; g < ics->num_window_groups; g++) {
2620 for (i = 0; i < ics->max_sfb; i++, idx++) {
2621 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2622 const float gain = cce->coup.gain[index][idx];
2623 for (group = 0; group < ics->group_len[g]; group++) {
2624 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2626 dest[group * 128 + k] += gain * src[group * 128 + k];
2631 dest += ics->group_len[g] * 128;
2632 src += ics->group_len[g] * 128;
2637 * Apply independent channel coupling (applied after IMDCT).
2639 * @param index index into coupling gain array
2641 static void apply_independent_coupling(AACContext *ac,
2642 SingleChannelElement *target,
2643 ChannelElement *cce, int index)
2646 const float gain = cce->coup.gain[index][0];
2647 const float *src = cce->ch[0].ret;
2648 float *dest = target->ret;
2649 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2651 for (i = 0; i < len; i++)
2652 dest[i] += gain * src[i];
2656 * channel coupling transformation interface
2658 * @param apply_coupling_method pointer to (in)dependent coupling function
2660 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2661 enum RawDataBlockType type, int elem_id,
2662 enum CouplingPoint coupling_point,
2663 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2667 for (i = 0; i < MAX_ELEM_ID; i++) {
2668 ChannelElement *cce = ac->che[TYPE_CCE][i];
2671 if (cce && cce->coup.coupling_point == coupling_point) {
2672 ChannelCoupling *coup = &cce->coup;
2674 for (c = 0; c <= coup->num_coupled; c++) {
2675 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2676 if (coup->ch_select[c] != 1) {
2677 apply_coupling_method(ac, &cc->ch[0], cce, index);
2678 if (coup->ch_select[c] != 0)
2681 if (coup->ch_select[c] != 2)
2682 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2684 index += 1 + (coup->ch_select[c] == 3);
2691 * Convert spectral data to float samples, applying all supported tools as appropriate.
2693 static void spectral_to_sample(AACContext *ac)
2696 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2697 switch (ac->oc[1].m4ac.object_type) {
2699 imdct_and_window = imdct_and_windowing_ld;
2701 case AOT_ER_AAC_ELD:
2702 imdct_and_window = imdct_and_windowing_eld;
2705 imdct_and_window = ac->imdct_and_windowing;
2707 for (type = 3; type >= 0; type--) {
2708 for (i = 0; i < MAX_ELEM_ID; i++) {
2709 ChannelElement *che = ac->che[type][i];
2711 if (type <= TYPE_CPE)
2712 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2713 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2714 if (che->ch[0].ics.predictor_present) {
2715 if (che->ch[0].ics.ltp.present)
2716 ac->apply_ltp(ac, &che->ch[0]);
2717 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2718 ac->apply_ltp(ac, &che->ch[1]);
2721 if (che->ch[0].tns.present)
2722 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2723 if (che->ch[1].tns.present)
2724 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2725 if (type <= TYPE_CPE)
2726 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2727 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2728 imdct_and_window(ac, &che->ch[0]);
2729 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2730 ac->update_ltp(ac, &che->ch[0]);
2731 if (type == TYPE_CPE) {
2732 imdct_and_window(ac, &che->ch[1]);
2733 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2734 ac->update_ltp(ac, &che->ch[1]);
2736 if (ac->oc[1].m4ac.sbr > 0) {
2737 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2740 if (type <= TYPE_CCE)
2741 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2747 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2750 AACADTSHeaderInfo hdr_info;
2751 uint8_t layout_map[MAX_ELEM_ID*4][3];
2752 int layout_map_tags, ret;
2754 size = avpriv_aac_parse_header(gb, &hdr_info);
2756 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2757 // This is 2 for "VLB " audio in NSV files.
2758 // See samples/nsv/vlb_audio.
2759 avpriv_report_missing_feature(ac->avctx,
2760 "More than one AAC RDB per ADTS frame");
2761 ac->warned_num_aac_frames = 1;
2763 push_output_configuration(ac);
2764 if (hdr_info.chan_config) {
2765 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2766 if ((ret = set_default_channel_config(ac->avctx,
2769 hdr_info.chan_config)) < 0)
2771 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2772 FFMAX(ac->oc[1].status,
2773 OC_TRIAL_FRAME), 0)) < 0)
2776 ac->oc[1].m4ac.chan_config = 0;
2778 * dual mono frames in Japanese DTV can have chan_config 0
2779 * WITHOUT specifying PCE.
2780 * thus, set dual mono as default.
2782 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2783 layout_map_tags = 2;
2784 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2785 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2786 layout_map[0][1] = 0;
2787 layout_map[1][1] = 1;
2788 if (output_configure(ac, layout_map, layout_map_tags,
2793 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2794 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2795 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2796 if (ac->oc[0].status != OC_LOCKED ||
2797 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2798 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2799 ac->oc[1].m4ac.sbr = -1;
2800 ac->oc[1].m4ac.ps = -1;
2802 if (!hdr_info.crc_absent)
2808 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2809 int *got_frame_ptr, GetBitContext *gb)
2811 AACContext *ac = avctx->priv_data;
2812 ChannelElement *che;
2815 int chan_config = ac->oc[1].m4ac.chan_config;
2816 int aot = ac->oc[1].m4ac.object_type;
2818 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2823 if ((err = frame_configure_elements(avctx)) < 0)
2826 // The FF_PROFILE_AAC_* defines are all object_type - 1
2827 // This may lead to an undefined profile being signaled
2828 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2830 ac->tags_mapped = 0;
2832 if (chan_config < 0 || chan_config >= 8) {
2833 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2834 ac->oc[1].m4ac.chan_config);
2835 return AVERROR_INVALIDDATA;
2837 for (i = 0; i < tags_per_config[chan_config]; i++) {
2838 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2839 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2840 if (!(che=get_che(ac, elem_type, elem_id))) {
2841 av_log(ac->avctx, AV_LOG_ERROR,
2842 "channel element %d.%d is not allocated\n",
2843 elem_type, elem_id);
2844 return AVERROR_INVALIDDATA;
2846 if (aot != AOT_ER_AAC_ELD)
2848 switch (elem_type) {
2850 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2853 err = decode_cpe(ac, gb, che);
2856 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2863 spectral_to_sample(ac);
2865 ac->frame->nb_samples = samples;
2868 skip_bits_long(gb, get_bits_left(gb));
2872 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2873 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2875 AACContext *ac = avctx->priv_data;
2876 ChannelElement *che = NULL, *che_prev = NULL;
2877 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2879 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2880 int is_dmono, sce_count = 0;
2884 if (show_bits(gb, 12) == 0xfff) {
2885 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2886 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2889 if (ac->oc[1].m4ac.sampling_index > 12) {
2890 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2891 err = AVERROR_INVALIDDATA;
2896 if ((err = frame_configure_elements(avctx)) < 0)
2899 // The FF_PROFILE_AAC_* defines are all object_type - 1
2900 // This may lead to an undefined profile being signaled
2901 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2903 ac->tags_mapped = 0;
2905 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2906 elem_id = get_bits(gb, 4);
2908 if (elem_type < TYPE_DSE) {
2909 if (!(che=get_che(ac, elem_type, elem_id))) {
2910 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2911 elem_type, elem_id);
2912 err = AVERROR_INVALIDDATA;
2918 switch (elem_type) {
2921 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2927 err = decode_cpe(ac, gb, che);
2932 err = decode_cce(ac, gb, che);
2936 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2941 err = skip_data_stream_element(ac, gb);
2945 uint8_t layout_map[MAX_ELEM_ID*4][3];
2947 push_output_configuration(ac);
2948 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2954 av_log(avctx, AV_LOG_ERROR,
2955 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2957 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2959 ac->oc[1].m4ac.chan_config = 0;
2967 elem_id += get_bits(gb, 8) - 1;
2968 if (get_bits_left(gb) < 8 * elem_id) {
2969 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
2970 err = AVERROR_INVALIDDATA;
2974 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2975 err = 0; /* FIXME */
2979 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2984 elem_type_prev = elem_type;
2989 if (get_bits_left(gb) < 3) {
2990 av_log(avctx, AV_LOG_ERROR, overread_err);
2991 err = AVERROR_INVALIDDATA;
2996 spectral_to_sample(ac);
2998 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2999 samples <<= multiplier;
3000 /* for dual-mono audio (SCE + SCE) */
3001 is_dmono = ac->dmono_mode && sce_count == 2 &&
3002 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
3005 ac->frame->nb_samples = samples;
3007 av_frame_unref(ac->frame);
3008 *got_frame_ptr = !!samples;
3011 if (ac->dmono_mode == 1)
3012 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3013 else if (ac->dmono_mode == 2)
3014 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3017 if (ac->oc[1].status && audio_found) {
3018 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3019 avctx->frame_size = samples;
3020 ac->oc[1].status = OC_LOCKED;
3025 const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
3026 if (side && side_size>=4)
3027 AV_WL32(side, 2*AV_RL32(side));
3031 pop_output_configuration(ac);
3035 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3036 int *got_frame_ptr, AVPacket *avpkt)
3038 AACContext *ac = avctx->priv_data;
3039 const uint8_t *buf = avpkt->data;
3040 int buf_size = avpkt->size;
3045 int new_extradata_size;
3046 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3047 AV_PKT_DATA_NEW_EXTRADATA,
3048 &new_extradata_size);
3049 int jp_dualmono_size;
3050 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3051 AV_PKT_DATA_JP_DUALMONO,
3054 if (new_extradata && 0) {
3055 av_free(avctx->extradata);
3056 avctx->extradata = av_mallocz(new_extradata_size +
3057 FF_INPUT_BUFFER_PADDING_SIZE);
3058 if (!avctx->extradata)
3059 return AVERROR(ENOMEM);
3060 avctx->extradata_size = new_extradata_size;
3061 memcpy(avctx->extradata, new_extradata, new_extradata_size);
3062 push_output_configuration(ac);
3063 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3065 avctx->extradata_size*8, 1) < 0) {
3066 pop_output_configuration(ac);
3067 return AVERROR_INVALIDDATA;
3072 if (jp_dualmono && jp_dualmono_size > 0)
3073 ac->dmono_mode = 1 + *jp_dualmono;
3074 if (ac->force_dmono_mode >= 0)
3075 ac->dmono_mode = ac->force_dmono_mode;
3077 if (INT_MAX / 8 <= buf_size)
3078 return AVERROR_INVALIDDATA;
3080 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3083 switch (ac->oc[1].m4ac.object_type) {
3085 case AOT_ER_AAC_LTP:
3087 case AOT_ER_AAC_ELD:
3088 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3091 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3096 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3097 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3098 if (buf[buf_offset])
3101 return buf_size > buf_offset ? buf_consumed : buf_size;
3104 static av_cold int aac_decode_close(AVCodecContext *avctx)
3106 AACContext *ac = avctx->priv_data;
3109 for (i = 0; i < MAX_ELEM_ID; i++) {
3110 for (type = 0; type < 4; type++) {
3111 if (ac->che[type][i])
3112 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
3113 av_freep(&ac->che[type][i]);
3117 ff_mdct_end(&ac->mdct);
3118 ff_mdct_end(&ac->mdct_small);
3119 ff_mdct_end(&ac->mdct_ld);
3120 ff_mdct_end(&ac->mdct_ltp);
3125 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
3127 struct LATMContext {
3128 AACContext aac_ctx; ///< containing AACContext
3129 int initialized; ///< initialized after a valid extradata was seen
3132 int audio_mux_version_A; ///< LATM syntax version
3133 int frame_length_type; ///< 0/1 variable/fixed frame length
3134 int frame_length; ///< frame length for fixed frame length
3137 static inline uint32_t latm_get_value(GetBitContext *b)
3139 int length = get_bits(b, 2);
3141 return get_bits_long(b, (length+1)*8);
3144 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
3145 GetBitContext *gb, int asclen)
3147 AACContext *ac = &latmctx->aac_ctx;
3148 AVCodecContext *avctx = ac->avctx;
3149 MPEG4AudioConfig m4ac = { 0 };
3150 int config_start_bit = get_bits_count(gb);
3151 int sync_extension = 0;
3152 int bits_consumed, esize;
3156 asclen = FFMIN(asclen, get_bits_left(gb));
3158 asclen = get_bits_left(gb);
3160 if (config_start_bit % 8) {
3161 avpriv_request_sample(latmctx->aac_ctx.avctx,
3162 "Non-byte-aligned audio-specific config");
3163 return AVERROR_PATCHWELCOME;
3166 return AVERROR_INVALIDDATA;
3167 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
3168 gb->buffer + (config_start_bit / 8),
3169 asclen, sync_extension);
3171 if (bits_consumed < 0)
3172 return AVERROR_INVALIDDATA;
3174 if (!latmctx->initialized ||
3175 ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
3176 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
3178 if(latmctx->initialized) {
3179 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3181 av_log(avctx, AV_LOG_DEBUG, "initializing latmctx\n");
3183 latmctx->initialized = 0;
3185 esize = (bits_consumed+7) / 8;
3187 if (avctx->extradata_size < esize) {
3188 av_free(avctx->extradata);
3189 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
3190 if (!avctx->extradata)
3191 return AVERROR(ENOMEM);
3194 avctx->extradata_size = esize;
3195 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
3196 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
3198 skip_bits_long(gb, bits_consumed);
3200 return bits_consumed;
3203 static int read_stream_mux_config(struct LATMContext *latmctx,
3206 int ret, audio_mux_version = get_bits(gb, 1);
3208 latmctx->audio_mux_version_A = 0;
3209 if (audio_mux_version)
3210 latmctx->audio_mux_version_A = get_bits(gb, 1);
3212 if (!latmctx->audio_mux_version_A) {
3214 if (audio_mux_version)
3215 latm_get_value(gb); // taraFullness
3217 skip_bits(gb, 1); // allStreamSameTimeFraming
3218 skip_bits(gb, 6); // numSubFrames
3220 if (get_bits(gb, 4)) { // numPrograms
3221 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
3222 return AVERROR_PATCHWELCOME;
3225 // for each program (which there is only one in DVB)
3227 // for each layer (which there is only one in DVB)
3228 if (get_bits(gb, 3)) { // numLayer
3229 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
3230 return AVERROR_PATCHWELCOME;
3233 // for all but first stream: use_same_config = get_bits(gb, 1);
3234 if (!audio_mux_version) {
3235 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
3238 int ascLen = latm_get_value(gb);
3239 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
3242 skip_bits_long(gb, ascLen);
3245 latmctx->frame_length_type = get_bits(gb, 3);
3246 switch (latmctx->frame_length_type) {
3248 skip_bits(gb, 8); // latmBufferFullness
3251 latmctx->frame_length = get_bits(gb, 9);
3256 skip_bits(gb, 6); // CELP frame length table index
3260 skip_bits(gb, 1); // HVXC frame length table index
3264 if (get_bits(gb, 1)) { // other data
3265 if (audio_mux_version) {
3266 latm_get_value(gb); // other_data_bits
3270 esc = get_bits(gb, 1);
3276 if (get_bits(gb, 1)) // crc present
3277 skip_bits(gb, 8); // config_crc
3283 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3287 if (ctx->frame_length_type == 0) {
3288 int mux_slot_length = 0;
3290 tmp = get_bits(gb, 8);
3291 mux_slot_length += tmp;
3292 } while (tmp == 255);
3293 return mux_slot_length;
3294 } else if (ctx->frame_length_type == 1) {
3295 return ctx->frame_length;
3296 } else if (ctx->frame_length_type == 3 ||
3297 ctx->frame_length_type == 5 ||
3298 ctx->frame_length_type == 7) {
3299 skip_bits(gb, 2); // mux_slot_length_coded
3304 static int read_audio_mux_element(struct LATMContext *latmctx,
3308 uint8_t use_same_mux = get_bits(gb, 1);
3309 if (!use_same_mux) {
3310 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3312 } else if (!latmctx->aac_ctx.avctx->extradata) {
3313 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3314 "no decoder config found\n");
3315 return AVERROR(EAGAIN);
3317 if (latmctx->audio_mux_version_A == 0) {
3318 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3319 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3320 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3321 return AVERROR_INVALIDDATA;
3322 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3323 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3324 "frame length mismatch %d << %d\n",
3325 mux_slot_length_bytes * 8, get_bits_left(gb));
3326 return AVERROR_INVALIDDATA;
3333 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3334 int *got_frame_ptr, AVPacket *avpkt)
3336 struct LATMContext *latmctx = avctx->priv_data;
3340 if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
3343 // check for LOAS sync word
3344 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3345 return AVERROR_INVALIDDATA;
3347 muxlength = get_bits(&gb, 13) + 3;
3348 // not enough data, the parser should have sorted this out
3349 if (muxlength > avpkt->size)
3350 return AVERROR_INVALIDDATA;
3352 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3355 if (!latmctx->initialized) {
3356 if (!avctx->extradata) {
3360 push_output_configuration(&latmctx->aac_ctx);
3361 if ((err = decode_audio_specific_config(
3362 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3363 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3364 pop_output_configuration(&latmctx->aac_ctx);
3367 latmctx->initialized = 1;
3371 if (show_bits(&gb, 12) == 0xfff) {
3372 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3373 "ADTS header detected, probably as result of configuration "
3375 return AVERROR_INVALIDDATA;
3378 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
3384 static av_cold int latm_decode_init(AVCodecContext *avctx)
3386 struct LATMContext *latmctx = avctx->priv_data;
3387 int ret = aac_decode_init(avctx);
3389 if (avctx->extradata_size > 0)
3390 latmctx->initialized = !ret;
3395 static void aacdec_init(AACContext *c)
3397 c->imdct_and_windowing = imdct_and_windowing;
3398 c->apply_ltp = apply_ltp;
3399 c->apply_tns = apply_tns;
3400 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3401 c->update_ltp = update_ltp;
3404 ff_aacdec_init_mips(c);
3407 * AVOptions for Japanese DTV specific extensions (ADTS only)
3409 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3410 static const AVOption options[] = {
3411 {"dual_mono_mode", "Select the channel to decode for dual mono",
3412 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3413 AACDEC_FLAGS, "dual_mono_mode"},
3415 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3416 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3417 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3418 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3423 static const AVClass aac_decoder_class = {
3424 .class_name = "AAC decoder",
3425 .item_name = av_default_item_name,
3427 .version = LIBAVUTIL_VERSION_INT,
3430 AVCodec ff_aac_decoder = {
3432 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3433 .type = AVMEDIA_TYPE_AUDIO,
3434 .id = AV_CODEC_ID_AAC,
3435 .priv_data_size = sizeof(AACContext),
3436 .init = aac_decode_init,
3437 .close = aac_decode_close,
3438 .decode = aac_decode_frame,
3439 .sample_fmts = (const enum AVSampleFormat[]) {
3440 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3442 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3443 .channel_layouts = aac_channel_layout,
3445 .priv_class = &aac_decoder_class,
3449 Note: This decoder filter is intended to decode LATM streams transferred
3450 in MPEG transport streams which only contain one program.
3451 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3453 AVCodec ff_aac_latm_decoder = {
3455 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3456 .type = AVMEDIA_TYPE_AUDIO,
3457 .id = AV_CODEC_ID_AAC_LATM,
3458 .priv_data_size = sizeof(struct LATMContext),
3459 .init = latm_decode_init,
3460 .close = aac_decode_close,
3461 .decode = latm_decode_frame,
3462 .sample_fmts = (const enum AVSampleFormat[]) {
3463 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3465 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3466 .channel_layouts = aac_channel_layout,