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 (not in fixed point code) 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 static VLC vlc_scalefactors;
85 static VLC vlc_spectral[11];
87 static int output_configure(AACContext *ac,
88 uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
89 enum OCStatus oc_type, int get_new_frame);
91 #define overread_err "Input buffer exhausted before END element found\n"
93 static int count_channels(uint8_t (*layout)[3], int tags)
96 for (i = 0; i < tags; i++) {
97 int syn_ele = layout[i][0];
98 int pos = layout[i][2];
99 sum += (1 + (syn_ele == TYPE_CPE)) *
100 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
106 * Check for the channel element in the current channel position configuration.
107 * If it exists, make sure the appropriate element is allocated and map the
108 * channel order to match the internal FFmpeg channel layout.
110 * @param che_pos current channel position configuration
111 * @param type channel element type
112 * @param id channel element id
113 * @param channels count of the number of channels in the configuration
115 * @return Returns error status. 0 - OK, !0 - error
117 static av_cold int che_configure(AACContext *ac,
118 enum ChannelPosition che_pos,
119 int type, int id, int *channels)
121 if (*channels >= MAX_CHANNELS)
122 return AVERROR_INVALIDDATA;
124 if (!ac->che[type][id]) {
125 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
126 return AVERROR(ENOMEM);
127 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
129 if (type != TYPE_CCE) {
130 if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
131 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
132 return AVERROR_INVALIDDATA;
134 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
135 if (type == TYPE_CPE ||
136 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
137 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
141 if (ac->che[type][id])
142 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
143 av_freep(&ac->che[type][id]);
148 static int frame_configure_elements(AVCodecContext *avctx)
150 AACContext *ac = avctx->priv_data;
151 int type, id, ch, ret;
153 /* set channel pointers to internal buffers by default */
154 for (type = 0; type < 4; type++) {
155 for (id = 0; id < MAX_ELEM_ID; id++) {
156 ChannelElement *che = ac->che[type][id];
158 che->ch[0].ret = che->ch[0].ret_buf;
159 che->ch[1].ret = che->ch[1].ret_buf;
164 /* get output buffer */
165 av_frame_unref(ac->frame);
166 if (!avctx->channels)
169 ac->frame->nb_samples = 2048;
170 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
173 /* map output channel pointers to AVFrame data */
174 for (ch = 0; ch < avctx->channels; ch++) {
175 if (ac->output_element[ch])
176 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
182 struct elem_to_channel {
183 uint64_t av_position;
186 uint8_t aac_position;
189 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
190 uint8_t (*layout_map)[3], int offset, uint64_t left,
191 uint64_t right, int pos)
193 if (layout_map[offset][0] == TYPE_CPE) {
194 e2c_vec[offset] = (struct elem_to_channel) {
195 .av_position = left | right,
197 .elem_id = layout_map[offset][1],
202 e2c_vec[offset] = (struct elem_to_channel) {
205 .elem_id = layout_map[offset][1],
208 e2c_vec[offset + 1] = (struct elem_to_channel) {
209 .av_position = right,
211 .elem_id = layout_map[offset + 1][1],
218 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
221 int num_pos_channels = 0;
225 for (i = *current; i < tags; i++) {
226 if (layout_map[i][2] != pos)
228 if (layout_map[i][0] == TYPE_CPE) {
230 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
236 num_pos_channels += 2;
244 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
247 return num_pos_channels;
250 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
252 int i, n, total_non_cc_elements;
253 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
254 int num_front_channels, num_side_channels, num_back_channels;
257 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
262 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
263 if (num_front_channels < 0)
266 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
267 if (num_side_channels < 0)
270 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
271 if (num_back_channels < 0)
274 if (num_side_channels == 0 && num_back_channels >= 4) {
275 num_side_channels = 2;
276 num_back_channels -= 2;
280 if (num_front_channels & 1) {
281 e2c_vec[i] = (struct elem_to_channel) {
282 .av_position = AV_CH_FRONT_CENTER,
284 .elem_id = layout_map[i][1],
285 .aac_position = AAC_CHANNEL_FRONT
288 num_front_channels--;
290 if (num_front_channels >= 4) {
291 i += assign_pair(e2c_vec, layout_map, i,
292 AV_CH_FRONT_LEFT_OF_CENTER,
293 AV_CH_FRONT_RIGHT_OF_CENTER,
295 num_front_channels -= 2;
297 if (num_front_channels >= 2) {
298 i += assign_pair(e2c_vec, layout_map, i,
302 num_front_channels -= 2;
304 while (num_front_channels >= 2) {
305 i += assign_pair(e2c_vec, layout_map, i,
309 num_front_channels -= 2;
312 if (num_side_channels >= 2) {
313 i += assign_pair(e2c_vec, layout_map, i,
317 num_side_channels -= 2;
319 while (num_side_channels >= 2) {
320 i += assign_pair(e2c_vec, layout_map, i,
324 num_side_channels -= 2;
327 while (num_back_channels >= 4) {
328 i += assign_pair(e2c_vec, layout_map, i,
332 num_back_channels -= 2;
334 if (num_back_channels >= 2) {
335 i += assign_pair(e2c_vec, layout_map, i,
339 num_back_channels -= 2;
341 if (num_back_channels) {
342 e2c_vec[i] = (struct elem_to_channel) {
343 .av_position = AV_CH_BACK_CENTER,
345 .elem_id = layout_map[i][1],
346 .aac_position = AAC_CHANNEL_BACK
352 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
353 e2c_vec[i] = (struct elem_to_channel) {
354 .av_position = AV_CH_LOW_FREQUENCY,
356 .elem_id = layout_map[i][1],
357 .aac_position = AAC_CHANNEL_LFE
361 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
362 e2c_vec[i] = (struct elem_to_channel) {
363 .av_position = UINT64_MAX,
365 .elem_id = layout_map[i][1],
366 .aac_position = AAC_CHANNEL_LFE
371 // Must choose a stable sort
372 total_non_cc_elements = n = i;
375 for (i = 1; i < n; i++)
376 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
377 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
384 for (i = 0; i < total_non_cc_elements; i++) {
385 layout_map[i][0] = e2c_vec[i].syn_ele;
386 layout_map[i][1] = e2c_vec[i].elem_id;
387 layout_map[i][2] = e2c_vec[i].aac_position;
388 if (e2c_vec[i].av_position != UINT64_MAX) {
389 layout |= e2c_vec[i].av_position;
397 * Save current output configuration if and only if it has been locked.
399 static void push_output_configuration(AACContext *ac) {
400 if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
401 ac->oc[0] = ac->oc[1];
403 ac->oc[1].status = OC_NONE;
407 * Restore the previous output configuration if and only if the current
408 * configuration is unlocked.
410 static void pop_output_configuration(AACContext *ac) {
411 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
412 ac->oc[1] = ac->oc[0];
413 ac->avctx->channels = ac->oc[1].channels;
414 ac->avctx->channel_layout = ac->oc[1].channel_layout;
415 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
416 ac->oc[1].status, 0);
421 * Configure output channel order based on the current program
422 * configuration element.
424 * @return Returns error status. 0 - OK, !0 - error
426 static int output_configure(AACContext *ac,
427 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
428 enum OCStatus oc_type, int get_new_frame)
430 AVCodecContext *avctx = ac->avctx;
431 int i, channels = 0, ret;
433 uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
434 uint8_t type_counts[TYPE_END] = { 0 };
436 if (ac->oc[1].layout_map != layout_map) {
437 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
438 ac->oc[1].layout_map_tags = tags;
440 for (i = 0; i < tags; i++) {
441 int type = layout_map[i][0];
442 int id = layout_map[i][1];
443 id_map[type][id] = type_counts[type]++;
445 // Try to sniff a reasonable channel order, otherwise output the
446 // channels in the order the PCE declared them.
447 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
448 layout = sniff_channel_order(layout_map, tags);
449 for (i = 0; i < tags; i++) {
450 int type = layout_map[i][0];
451 int id = layout_map[i][1];
452 int iid = id_map[type][id];
453 int position = layout_map[i][2];
454 // Allocate or free elements depending on if they are in the
455 // current program configuration.
456 ret = che_configure(ac, position, type, iid, &channels);
459 ac->tag_che_map[type][id] = ac->che[type][iid];
461 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
462 if (layout == AV_CH_FRONT_CENTER) {
463 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
469 if (layout) avctx->channel_layout = layout;
470 ac->oc[1].channel_layout = layout;
471 avctx->channels = ac->oc[1].channels = channels;
472 ac->oc[1].status = oc_type;
475 if ((ret = frame_configure_elements(ac->avctx)) < 0)
482 static void flush(AVCodecContext *avctx)
484 AACContext *ac= avctx->priv_data;
487 for (type = 3; type >= 0; type--) {
488 for (i = 0; i < MAX_ELEM_ID; i++) {
489 ChannelElement *che = ac->che[type][i];
491 for (j = 0; j <= 1; j++) {
492 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
500 * Set up channel positions based on a default channel configuration
501 * as specified in table 1.17.
503 * @return Returns error status. 0 - OK, !0 - error
505 static int set_default_channel_config(AVCodecContext *avctx,
506 uint8_t (*layout_map)[3],
510 if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
511 channel_config > 12) {
512 av_log(avctx, AV_LOG_ERROR,
513 "invalid default channel configuration (%d)\n",
515 return AVERROR_INVALIDDATA;
517 *tags = tags_per_config[channel_config];
518 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
519 *tags * sizeof(*layout_map));
522 * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
523 * However, at least Nero AAC encoder encodes 7.1 streams using the default
524 * channel config 7, mapping the side channels of the original audio stream
525 * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
526 * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
527 * the incorrect streams as if they were correct (and as the encoder intended).
529 * As actual intended 7.1(wide) streams are very rare, default to assuming a
530 * 7.1 layout was intended.
532 if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT) {
533 av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
534 " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
535 " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
536 layout_map[2][2] = AAC_CHANNEL_SIDE;
542 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
544 /* For PCE based channel configurations map the channels solely based
546 if (!ac->oc[1].m4ac.chan_config) {
547 return ac->tag_che_map[type][elem_id];
549 // Allow single CPE stereo files to be signalled with mono configuration.
550 if (!ac->tags_mapped && type == TYPE_CPE &&
551 ac->oc[1].m4ac.chan_config == 1) {
552 uint8_t layout_map[MAX_ELEM_ID*4][3];
554 push_output_configuration(ac);
556 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
558 if (set_default_channel_config(ac->avctx, layout_map,
559 &layout_map_tags, 2) < 0)
561 if (output_configure(ac, layout_map, layout_map_tags,
562 OC_TRIAL_FRAME, 1) < 0)
565 ac->oc[1].m4ac.chan_config = 2;
566 ac->oc[1].m4ac.ps = 0;
569 if (!ac->tags_mapped && type == TYPE_SCE &&
570 ac->oc[1].m4ac.chan_config == 2) {
571 uint8_t layout_map[MAX_ELEM_ID * 4][3];
573 push_output_configuration(ac);
575 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
577 if (set_default_channel_config(ac->avctx, layout_map,
578 &layout_map_tags, 1) < 0)
580 if (output_configure(ac, layout_map, layout_map_tags,
581 OC_TRIAL_FRAME, 1) < 0)
584 ac->oc[1].m4ac.chan_config = 1;
585 if (ac->oc[1].m4ac.sbr)
586 ac->oc[1].m4ac.ps = -1;
588 /* For indexed channel configurations map the channels solely based
590 switch (ac->oc[1].m4ac.chan_config) {
593 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
595 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
598 if (ac->tags_mapped == 2 &&
599 ac->oc[1].m4ac.chan_config == 11 &&
602 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
605 /* Some streams incorrectly code 5.1 audio as
606 * SCE[0] CPE[0] CPE[1] SCE[1]
608 * SCE[0] CPE[0] CPE[1] LFE[0].
609 * If we seem to have encountered such a stream, transfer
610 * the LFE[0] element to the SCE[1]'s mapping */
611 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
612 if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
613 av_log(ac->avctx, AV_LOG_WARNING,
614 "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
615 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
616 ac->warned_remapping_once++;
619 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
622 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
624 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
627 /* Some streams incorrectly code 4.0 audio as
628 * SCE[0] CPE[0] LFE[0]
630 * SCE[0] CPE[0] SCE[1].
631 * If we seem to have encountered such a stream, transfer
632 * the SCE[1] element to the LFE[0]'s mapping */
633 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
634 if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
635 av_log(ac->avctx, AV_LOG_WARNING,
636 "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
637 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
638 ac->warned_remapping_once++;
641 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
643 if (ac->tags_mapped == 2 &&
644 ac->oc[1].m4ac.chan_config == 4 &&
647 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
651 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
654 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
655 } else if (ac->oc[1].m4ac.chan_config == 2) {
659 if (!ac->tags_mapped && type == TYPE_SCE) {
661 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
669 * Decode an array of 4 bit element IDs, optionally interleaved with a
670 * stereo/mono switching bit.
672 * @param type speaker type/position for these channels
674 static void decode_channel_map(uint8_t layout_map[][3],
675 enum ChannelPosition type,
676 GetBitContext *gb, int n)
679 enum RawDataBlockType syn_ele;
681 case AAC_CHANNEL_FRONT:
682 case AAC_CHANNEL_BACK:
683 case AAC_CHANNEL_SIDE:
684 syn_ele = get_bits1(gb);
690 case AAC_CHANNEL_LFE:
694 // AAC_CHANNEL_OFF has no channel map
697 layout_map[0][0] = syn_ele;
698 layout_map[0][1] = get_bits(gb, 4);
699 layout_map[0][2] = type;
705 * Decode program configuration element; reference: table 4.2.
707 * @return Returns error status. 0 - OK, !0 - error
709 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
710 uint8_t (*layout_map)[3],
713 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
718 skip_bits(gb, 2); // object_type
720 sampling_index = get_bits(gb, 4);
721 if (m4ac->sampling_index != sampling_index)
722 av_log(avctx, AV_LOG_WARNING,
723 "Sample rate index in program config element does not "
724 "match the sample rate index configured by the container.\n");
726 num_front = get_bits(gb, 4);
727 num_side = get_bits(gb, 4);
728 num_back = get_bits(gb, 4);
729 num_lfe = get_bits(gb, 2);
730 num_assoc_data = get_bits(gb, 3);
731 num_cc = get_bits(gb, 4);
734 skip_bits(gb, 4); // mono_mixdown_tag
736 skip_bits(gb, 4); // stereo_mixdown_tag
739 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
741 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
742 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
745 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
747 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
749 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
751 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
754 skip_bits_long(gb, 4 * num_assoc_data);
756 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
761 /* comment field, first byte is length */
762 comment_len = get_bits(gb, 8) * 8;
763 if (get_bits_left(gb) < comment_len) {
764 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
765 return AVERROR_INVALIDDATA;
767 skip_bits_long(gb, comment_len);
772 * Decode GA "General Audio" specific configuration; reference: table 4.1.
774 * @param ac pointer to AACContext, may be null
775 * @param avctx pointer to AVCCodecContext, used for logging
777 * @return Returns error status. 0 - OK, !0 - error
779 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
781 MPEG4AudioConfig *m4ac,
784 int extension_flag, ret, ep_config, res_flags;
785 uint8_t layout_map[MAX_ELEM_ID*4][3];
788 if (get_bits1(gb)) { // frameLengthFlag
789 avpriv_request_sample(avctx, "960/120 MDCT window");
790 return AVERROR_PATCHWELCOME;
792 m4ac->frame_length_short = 0;
794 if (get_bits1(gb)) // dependsOnCoreCoder
795 skip_bits(gb, 14); // coreCoderDelay
796 extension_flag = get_bits1(gb);
798 if (m4ac->object_type == AOT_AAC_SCALABLE ||
799 m4ac->object_type == AOT_ER_AAC_SCALABLE)
800 skip_bits(gb, 3); // layerNr
802 if (channel_config == 0) {
803 skip_bits(gb, 4); // element_instance_tag
804 tags = decode_pce(avctx, m4ac, layout_map, gb);
808 if ((ret = set_default_channel_config(avctx, layout_map,
809 &tags, channel_config)))
813 if (count_channels(layout_map, tags) > 1) {
815 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
818 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
821 if (extension_flag) {
822 switch (m4ac->object_type) {
824 skip_bits(gb, 5); // numOfSubFrame
825 skip_bits(gb, 11); // layer_length
829 case AOT_ER_AAC_SCALABLE:
831 res_flags = get_bits(gb, 3);
833 avpriv_report_missing_feature(avctx,
834 "AAC data resilience (flags %x)",
836 return AVERROR_PATCHWELCOME;
840 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
842 switch (m4ac->object_type) {
845 case AOT_ER_AAC_SCALABLE:
847 ep_config = get_bits(gb, 2);
849 avpriv_report_missing_feature(avctx,
850 "epConfig %d", ep_config);
851 return AVERROR_PATCHWELCOME;
857 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
859 MPEG4AudioConfig *m4ac,
862 int ret, ep_config, res_flags;
863 uint8_t layout_map[MAX_ELEM_ID*4][3];
865 const int ELDEXT_TERM = 0;
870 m4ac->frame_length_short = get_bits1(gb);
871 res_flags = get_bits(gb, 3);
873 avpriv_report_missing_feature(avctx,
874 "AAC data resilience (flags %x)",
876 return AVERROR_PATCHWELCOME;
879 if (get_bits1(gb)) { // ldSbrPresentFlag
880 avpriv_report_missing_feature(avctx,
882 return AVERROR_PATCHWELCOME;
885 while (get_bits(gb, 4) != ELDEXT_TERM) {
886 int len = get_bits(gb, 4);
888 len += get_bits(gb, 8);
890 len += get_bits(gb, 16);
891 if (get_bits_left(gb) < len * 8 + 4) {
892 av_log(avctx, AV_LOG_ERROR, overread_err);
893 return AVERROR_INVALIDDATA;
895 skip_bits_long(gb, 8 * len);
898 if ((ret = set_default_channel_config(avctx, layout_map,
899 &tags, channel_config)))
902 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
905 ep_config = get_bits(gb, 2);
907 avpriv_report_missing_feature(avctx,
908 "epConfig %d", ep_config);
909 return AVERROR_PATCHWELCOME;
915 * Decode audio specific configuration; reference: table 1.13.
917 * @param ac pointer to AACContext, may be null
918 * @param avctx pointer to AVCCodecContext, used for logging
919 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
920 * @param data pointer to buffer holding an audio specific config
921 * @param bit_size size of audio specific config or data in bits
922 * @param sync_extension look for an appended sync extension
924 * @return Returns error status or number of consumed bits. <0 - error
926 static int decode_audio_specific_config(AACContext *ac,
927 AVCodecContext *avctx,
928 MPEG4AudioConfig *m4ac,
929 const uint8_t *data, int bit_size,
935 ff_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);
936 for (i = 0; i < bit_size >> 3; i++)
937 ff_dlog(avctx, "%02x ", data[i]);
938 ff_dlog(avctx, "\n");
940 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
943 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
944 sync_extension)) < 0)
945 return AVERROR_INVALIDDATA;
946 if (m4ac->sampling_index > 12) {
947 av_log(avctx, AV_LOG_ERROR,
948 "invalid sampling rate index %d\n",
949 m4ac->sampling_index);
950 return AVERROR_INVALIDDATA;
952 if (m4ac->object_type == AOT_ER_AAC_LD &&
953 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
954 av_log(avctx, AV_LOG_ERROR,
955 "invalid low delay sampling rate index %d\n",
956 m4ac->sampling_index);
957 return AVERROR_INVALIDDATA;
960 skip_bits_long(&gb, i);
962 switch (m4ac->object_type) {
968 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
969 m4ac, m4ac->chan_config)) < 0)
973 if ((ret = decode_eld_specific_config(ac, avctx, &gb,
974 m4ac, m4ac->chan_config)) < 0)
978 avpriv_report_missing_feature(avctx,
979 "Audio object type %s%d",
980 m4ac->sbr == 1 ? "SBR+" : "",
982 return AVERROR(ENOSYS);
986 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
987 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
988 m4ac->sample_rate, m4ac->sbr,
991 return get_bits_count(&gb);
995 * linear congruential pseudorandom number generator
997 * @param previous_val pointer to the current state of the generator
999 * @return Returns a 32-bit pseudorandom integer
1001 static av_always_inline int lcg_random(unsigned previous_val)
1003 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1007 static void reset_all_predictors(PredictorState *ps)
1010 for (i = 0; i < MAX_PREDICTORS; i++)
1011 reset_predict_state(&ps[i]);
1014 static int sample_rate_idx (int rate)
1016 if (92017 <= rate) return 0;
1017 else if (75132 <= rate) return 1;
1018 else if (55426 <= rate) return 2;
1019 else if (46009 <= rate) return 3;
1020 else if (37566 <= rate) return 4;
1021 else if (27713 <= rate) return 5;
1022 else if (23004 <= rate) return 6;
1023 else if (18783 <= rate) return 7;
1024 else if (13856 <= rate) return 8;
1025 else if (11502 <= rate) return 9;
1026 else if (9391 <= rate) return 10;
1030 static void reset_predictor_group(PredictorState *ps, int group_num)
1033 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1034 reset_predict_state(&ps[i]);
1037 #define AAC_INIT_VLC_STATIC(num, size) \
1038 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1039 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1040 sizeof(ff_aac_spectral_bits[num][0]), \
1041 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1042 sizeof(ff_aac_spectral_codes[num][0]), \
1045 static void aacdec_init(AACContext *ac);
1047 static av_cold int aac_decode_init(AVCodecContext *avctx)
1049 AACContext *ac = avctx->priv_data;
1053 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1057 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1059 if (avctx->extradata_size > 0) {
1060 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1062 avctx->extradata_size * 8,
1067 uint8_t layout_map[MAX_ELEM_ID*4][3];
1068 int layout_map_tags;
1070 sr = sample_rate_idx(avctx->sample_rate);
1071 ac->oc[1].m4ac.sampling_index = sr;
1072 ac->oc[1].m4ac.channels = avctx->channels;
1073 ac->oc[1].m4ac.sbr = -1;
1074 ac->oc[1].m4ac.ps = -1;
1076 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1077 if (ff_mpeg4audio_channels[i] == avctx->channels)
1079 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1082 ac->oc[1].m4ac.chan_config = i;
1084 if (ac->oc[1].m4ac.chan_config) {
1085 int ret = set_default_channel_config(avctx, layout_map,
1086 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1088 output_configure(ac, layout_map, layout_map_tags,
1090 else if (avctx->err_recognition & AV_EF_EXPLODE)
1091 return AVERROR_INVALIDDATA;
1095 if (avctx->channels > MAX_CHANNELS) {
1096 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1097 return AVERROR_INVALIDDATA;
1100 AAC_INIT_VLC_STATIC( 0, 304);
1101 AAC_INIT_VLC_STATIC( 1, 270);
1102 AAC_INIT_VLC_STATIC( 2, 550);
1103 AAC_INIT_VLC_STATIC( 3, 300);
1104 AAC_INIT_VLC_STATIC( 4, 328);
1105 AAC_INIT_VLC_STATIC( 5, 294);
1106 AAC_INIT_VLC_STATIC( 6, 306);
1107 AAC_INIT_VLC_STATIC( 7, 268);
1108 AAC_INIT_VLC_STATIC( 8, 510);
1109 AAC_INIT_VLC_STATIC( 9, 366);
1110 AAC_INIT_VLC_STATIC(10, 462);
1114 ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & CODEC_FLAG_BITEXACT);
1116 return AVERROR(ENOMEM);
1119 ac->random_state = 0x1f2e3d4c;
1123 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1124 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1125 ff_aac_scalefactor_bits,
1126 sizeof(ff_aac_scalefactor_bits[0]),
1127 sizeof(ff_aac_scalefactor_bits[0]),
1128 ff_aac_scalefactor_code,
1129 sizeof(ff_aac_scalefactor_code[0]),
1130 sizeof(ff_aac_scalefactor_code[0]),
1133 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1134 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
1135 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1136 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
1137 ret = ff_imdct15_init(&ac->mdct480, 5);
1141 // window initialization
1142 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1143 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1144 ff_init_ff_sine_windows(10);
1145 ff_init_ff_sine_windows( 9);
1146 ff_init_ff_sine_windows( 7);
1154 * Skip data_stream_element; reference: table 4.10.
1156 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1158 int byte_align = get_bits1(gb);
1159 int count = get_bits(gb, 8);
1161 count += get_bits(gb, 8);
1165 if (get_bits_left(gb) < 8 * count) {
1166 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1167 return AVERROR_INVALIDDATA;
1169 skip_bits_long(gb, 8 * count);
1173 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1177 if (get_bits1(gb)) {
1178 ics->predictor_reset_group = get_bits(gb, 5);
1179 if (ics->predictor_reset_group == 0 ||
1180 ics->predictor_reset_group > 30) {
1181 av_log(ac->avctx, AV_LOG_ERROR,
1182 "Invalid Predictor Reset Group.\n");
1183 return AVERROR_INVALIDDATA;
1186 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1187 ics->prediction_used[sfb] = get_bits1(gb);
1193 * Decode Long Term Prediction data; reference: table 4.xx.
1195 static void decode_ltp(LongTermPrediction *ltp,
1196 GetBitContext *gb, uint8_t max_sfb)
1200 ltp->lag = get_bits(gb, 11);
1201 ltp->coef = ltp_coef[get_bits(gb, 3)];
1202 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1203 ltp->used[sfb] = get_bits1(gb);
1207 * Decode Individual Channel Stream info; reference: table 4.6.
1209 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1212 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1213 const int aot = m4ac->object_type;
1214 const int sampling_index = m4ac->sampling_index;
1215 if (aot != AOT_ER_AAC_ELD) {
1216 if (get_bits1(gb)) {
1217 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1218 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1219 return AVERROR_INVALIDDATA;
1221 ics->window_sequence[1] = ics->window_sequence[0];
1222 ics->window_sequence[0] = get_bits(gb, 2);
1223 if (aot == AOT_ER_AAC_LD &&
1224 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1225 av_log(ac->avctx, AV_LOG_ERROR,
1226 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1227 "window sequence %d found.\n", ics->window_sequence[0]);
1228 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1229 return AVERROR_INVALIDDATA;
1231 ics->use_kb_window[1] = ics->use_kb_window[0];
1232 ics->use_kb_window[0] = get_bits1(gb);
1234 ics->num_window_groups = 1;
1235 ics->group_len[0] = 1;
1236 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1238 ics->max_sfb = get_bits(gb, 4);
1239 for (i = 0; i < 7; i++) {
1240 if (get_bits1(gb)) {
1241 ics->group_len[ics->num_window_groups - 1]++;
1243 ics->num_window_groups++;
1244 ics->group_len[ics->num_window_groups - 1] = 1;
1247 ics->num_windows = 8;
1248 ics->swb_offset = ff_swb_offset_128[sampling_index];
1249 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1250 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
1251 ics->predictor_present = 0;
1253 ics->max_sfb = get_bits(gb, 6);
1254 ics->num_windows = 1;
1255 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1256 if (m4ac->frame_length_short) {
1257 ics->swb_offset = ff_swb_offset_480[sampling_index];
1258 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1259 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1261 ics->swb_offset = ff_swb_offset_512[sampling_index];
1262 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1263 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1265 if (!ics->num_swb || !ics->swb_offset)
1268 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1269 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1270 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1272 if (aot != AOT_ER_AAC_ELD) {
1273 ics->predictor_present = get_bits1(gb);
1274 ics->predictor_reset_group = 0;
1276 if (ics->predictor_present) {
1277 if (aot == AOT_AAC_MAIN) {
1278 if (decode_prediction(ac, ics, gb)) {
1281 } else if (aot == AOT_AAC_LC ||
1282 aot == AOT_ER_AAC_LC) {
1283 av_log(ac->avctx, AV_LOG_ERROR,
1284 "Prediction is not allowed in AAC-LC.\n");
1287 if (aot == AOT_ER_AAC_LD) {
1288 av_log(ac->avctx, AV_LOG_ERROR,
1289 "LTP in ER AAC LD not yet implemented.\n");
1290 return AVERROR_PATCHWELCOME;
1292 if ((ics->ltp.present = get_bits(gb, 1)))
1293 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1298 if (ics->max_sfb > ics->num_swb) {
1299 av_log(ac->avctx, AV_LOG_ERROR,
1300 "Number of scalefactor bands in group (%d) "
1301 "exceeds limit (%d).\n",
1302 ics->max_sfb, ics->num_swb);
1309 return AVERROR_INVALIDDATA;
1313 * Decode band types (section_data payload); reference: table 4.46.
1315 * @param band_type array of the used band type
1316 * @param band_type_run_end array of the last scalefactor band of a band type run
1318 * @return Returns error status. 0 - OK, !0 - error
1320 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1321 int band_type_run_end[120], GetBitContext *gb,
1322 IndividualChannelStream *ics)
1325 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1326 for (g = 0; g < ics->num_window_groups; g++) {
1328 while (k < ics->max_sfb) {
1329 uint8_t sect_end = k;
1331 int sect_band_type = get_bits(gb, 4);
1332 if (sect_band_type == 12) {
1333 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1334 return AVERROR_INVALIDDATA;
1337 sect_len_incr = get_bits(gb, bits);
1338 sect_end += sect_len_incr;
1339 if (get_bits_left(gb) < 0) {
1340 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1341 return AVERROR_INVALIDDATA;
1343 if (sect_end > ics->max_sfb) {
1344 av_log(ac->avctx, AV_LOG_ERROR,
1345 "Number of bands (%d) exceeds limit (%d).\n",
1346 sect_end, ics->max_sfb);
1347 return AVERROR_INVALIDDATA;
1349 } while (sect_len_incr == (1 << bits) - 1);
1350 for (; k < sect_end; k++) {
1351 band_type [idx] = sect_band_type;
1352 band_type_run_end[idx++] = sect_end;
1360 * Decode scalefactors; reference: table 4.47.
1362 * @param global_gain first scalefactor value as scalefactors are differentially coded
1363 * @param band_type array of the used band type
1364 * @param band_type_run_end array of the last scalefactor band of a band type run
1365 * @param sf array of scalefactors or intensity stereo positions
1367 * @return Returns error status. 0 - OK, !0 - error
1369 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1370 unsigned int global_gain,
1371 IndividualChannelStream *ics,
1372 enum BandType band_type[120],
1373 int band_type_run_end[120])
1376 int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
1379 for (g = 0; g < ics->num_window_groups; g++) {
1380 for (i = 0; i < ics->max_sfb;) {
1381 int run_end = band_type_run_end[idx];
1382 if (band_type[idx] == ZERO_BT) {
1383 for (; i < run_end; i++, idx++)
1385 } else if ((band_type[idx] == INTENSITY_BT) ||
1386 (band_type[idx] == INTENSITY_BT2)) {
1387 for (; i < run_end; i++, idx++) {
1388 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1389 clipped_offset = av_clip(offset[2], -155, 100);
1390 if (offset[2] != clipped_offset) {
1391 avpriv_request_sample(ac->avctx,
1392 "If you heard an audible artifact, there may be a bug in the decoder. "
1393 "Clipped intensity stereo position (%d -> %d)",
1394 offset[2], clipped_offset);
1396 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1398 } else if (band_type[idx] == NOISE_BT) {
1399 for (; i < run_end; i++, idx++) {
1400 if (noise_flag-- > 0)
1401 offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
1403 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1404 clipped_offset = av_clip(offset[1], -100, 155);
1405 if (offset[1] != clipped_offset) {
1406 avpriv_request_sample(ac->avctx,
1407 "If you heard an audible artifact, there may be a bug in the decoder. "
1408 "Clipped noise gain (%d -> %d)",
1409 offset[1], clipped_offset);
1411 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1414 for (; i < run_end; i++, idx++) {
1415 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1416 if (offset[0] > 255U) {
1417 av_log(ac->avctx, AV_LOG_ERROR,
1418 "Scalefactor (%d) out of range.\n", offset[0]);
1419 return AVERROR_INVALIDDATA;
1421 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1430 * Decode pulse data; reference: table 4.7.
1432 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1433 const uint16_t *swb_offset, int num_swb)
1436 pulse->num_pulse = get_bits(gb, 2) + 1;
1437 pulse_swb = get_bits(gb, 6);
1438 if (pulse_swb >= num_swb)
1440 pulse->pos[0] = swb_offset[pulse_swb];
1441 pulse->pos[0] += get_bits(gb, 5);
1442 if (pulse->pos[0] >= swb_offset[num_swb])
1444 pulse->amp[0] = get_bits(gb, 4);
1445 for (i = 1; i < pulse->num_pulse; i++) {
1446 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1447 if (pulse->pos[i] >= swb_offset[num_swb])
1449 pulse->amp[i] = get_bits(gb, 4);
1455 * Decode Temporal Noise Shaping data; reference: table 4.48.
1457 * @return Returns error status. 0 - OK, !0 - error
1459 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1460 GetBitContext *gb, const IndividualChannelStream *ics)
1462 int w, filt, i, coef_len, coef_res, coef_compress;
1463 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1464 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1465 for (w = 0; w < ics->num_windows; w++) {
1466 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1467 coef_res = get_bits1(gb);
1469 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1471 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1473 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1474 av_log(ac->avctx, AV_LOG_ERROR,
1475 "TNS filter order %d is greater than maximum %d.\n",
1476 tns->order[w][filt], tns_max_order);
1477 tns->order[w][filt] = 0;
1478 return AVERROR_INVALIDDATA;
1480 if (tns->order[w][filt]) {
1481 tns->direction[w][filt] = get_bits1(gb);
1482 coef_compress = get_bits1(gb);
1483 coef_len = coef_res + 3 - coef_compress;
1484 tmp2_idx = 2 * coef_compress + coef_res;
1486 for (i = 0; i < tns->order[w][filt]; i++)
1487 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1496 * Decode Mid/Side data; reference: table 4.54.
1498 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1499 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1500 * [3] reserved for scalable AAC
1502 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1506 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1507 if (ms_present == 1) {
1508 for (idx = 0; idx < max_idx; idx++)
1509 cpe->ms_mask[idx] = get_bits1(gb);
1510 } else if (ms_present == 2) {
1511 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1516 * Decode spectral data; reference: table 4.50.
1517 * Dequantize and scale spectral data; reference: 4.6.3.3.
1519 * @param coef array of dequantized, scaled spectral data
1520 * @param sf array of scalefactors or intensity stereo positions
1521 * @param pulse_present set if pulses are present
1522 * @param pulse pointer to pulse data struct
1523 * @param band_type array of the used band type
1525 * @return Returns error status. 0 - OK, !0 - error
1527 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1528 GetBitContext *gb, const float sf[120],
1529 int pulse_present, const Pulse *pulse,
1530 const IndividualChannelStream *ics,
1531 enum BandType band_type[120])
1533 int i, k, g, idx = 0;
1534 const int c = 1024 / ics->num_windows;
1535 const uint16_t *offsets = ics->swb_offset;
1536 float *coef_base = coef;
1538 for (g = 0; g < ics->num_windows; g++)
1539 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1540 sizeof(float) * (c - offsets[ics->max_sfb]));
1542 for (g = 0; g < ics->num_window_groups; g++) {
1543 unsigned g_len = ics->group_len[g];
1545 for (i = 0; i < ics->max_sfb; i++, idx++) {
1546 const unsigned cbt_m1 = band_type[idx] - 1;
1547 float *cfo = coef + offsets[i];
1548 int off_len = offsets[i + 1] - offsets[i];
1551 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1552 for (group = 0; group < g_len; group++, cfo+=128) {
1553 memset(cfo, 0, off_len * sizeof(float));
1555 } else if (cbt_m1 == NOISE_BT - 1) {
1556 for (group = 0; group < g_len; group++, cfo+=128) {
1560 for (k = 0; k < off_len; k++) {
1561 ac->random_state = lcg_random(ac->random_state);
1562 cfo[k] = ac->random_state;
1565 band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
1566 scale = sf[idx] / sqrtf(band_energy);
1567 ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
1570 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1571 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1572 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1573 OPEN_READER(re, gb);
1575 switch (cbt_m1 >> 1) {
1577 for (group = 0; group < g_len; group++, cfo+=128) {
1585 UPDATE_CACHE(re, gb);
1586 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1587 cb_idx = cb_vector_idx[code];
1588 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1594 for (group = 0; group < g_len; group++, cfo+=128) {
1604 UPDATE_CACHE(re, gb);
1605 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1606 cb_idx = cb_vector_idx[code];
1607 nnz = cb_idx >> 8 & 15;
1608 bits = nnz ? GET_CACHE(re, gb) : 0;
1609 LAST_SKIP_BITS(re, gb, nnz);
1610 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1616 for (group = 0; group < g_len; group++, cfo+=128) {
1624 UPDATE_CACHE(re, gb);
1625 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1626 cb_idx = cb_vector_idx[code];
1627 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1634 for (group = 0; group < g_len; group++, cfo+=128) {
1644 UPDATE_CACHE(re, gb);
1645 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1646 cb_idx = cb_vector_idx[code];
1647 nnz = cb_idx >> 8 & 15;
1648 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1649 LAST_SKIP_BITS(re, gb, nnz);
1650 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1656 for (group = 0; group < g_len; group++, cfo+=128) {
1658 uint32_t *icf = (uint32_t *) cf;
1668 UPDATE_CACHE(re, gb);
1669 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1677 cb_idx = cb_vector_idx[code];
1680 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1681 LAST_SKIP_BITS(re, gb, nnz);
1683 for (j = 0; j < 2; j++) {
1687 /* The total length of escape_sequence must be < 22 bits according
1688 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1689 UPDATE_CACHE(re, gb);
1690 b = GET_CACHE(re, gb);
1691 b = 31 - av_log2(~b);
1694 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1695 return AVERROR_INVALIDDATA;
1698 SKIP_BITS(re, gb, b + 1);
1700 n = (1 << b) + SHOW_UBITS(re, gb, b);
1701 LAST_SKIP_BITS(re, gb, b);
1702 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1705 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1706 *icf++ = (bits & 1U<<31) | v;
1713 ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1717 CLOSE_READER(re, gb);
1723 if (pulse_present) {
1725 for (i = 0; i < pulse->num_pulse; i++) {
1726 float co = coef_base[ pulse->pos[i] ];
1727 while (offsets[idx + 1] <= pulse->pos[i])
1729 if (band_type[idx] != NOISE_BT && sf[idx]) {
1730 float ico = -pulse->amp[i];
1733 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1735 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1743 * Apply AAC-Main style frequency domain prediction.
1745 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1749 if (!sce->ics.predictor_initialized) {
1750 reset_all_predictors(sce->predictor_state);
1751 sce->ics.predictor_initialized = 1;
1754 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1756 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1758 for (k = sce->ics.swb_offset[sfb];
1759 k < sce->ics.swb_offset[sfb + 1];
1761 predict(&sce->predictor_state[k], &sce->coeffs[k],
1762 sce->ics.predictor_present &&
1763 sce->ics.prediction_used[sfb]);
1766 if (sce->ics.predictor_reset_group)
1767 reset_predictor_group(sce->predictor_state,
1768 sce->ics.predictor_reset_group);
1770 reset_all_predictors(sce->predictor_state);
1774 * Decode an individual_channel_stream payload; reference: table 4.44.
1776 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1777 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1779 * @return Returns error status. 0 - OK, !0 - error
1781 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1782 GetBitContext *gb, int common_window, int scale_flag)
1785 TemporalNoiseShaping *tns = &sce->tns;
1786 IndividualChannelStream *ics = &sce->ics;
1787 float *out = sce->coeffs;
1788 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1791 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1792 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1793 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1794 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1795 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1797 /* This assignment is to silence a GCC warning about the variable being used
1798 * uninitialized when in fact it always is.
1800 pulse.num_pulse = 0;
1802 global_gain = get_bits(gb, 8);
1804 if (!common_window && !scale_flag) {
1805 if (decode_ics_info(ac, ics, gb) < 0)
1806 return AVERROR_INVALIDDATA;
1809 if ((ret = decode_band_types(ac, sce->band_type,
1810 sce->band_type_run_end, gb, ics)) < 0)
1812 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1813 sce->band_type, sce->band_type_run_end)) < 0)
1818 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
1819 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1820 av_log(ac->avctx, AV_LOG_ERROR,
1821 "Pulse tool not allowed in eight short sequence.\n");
1822 return AVERROR_INVALIDDATA;
1824 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1825 av_log(ac->avctx, AV_LOG_ERROR,
1826 "Pulse data corrupt or invalid.\n");
1827 return AVERROR_INVALIDDATA;
1830 tns->present = get_bits1(gb);
1831 if (tns->present && !er_syntax)
1832 if (decode_tns(ac, tns, gb, ics) < 0)
1833 return AVERROR_INVALIDDATA;
1834 if (!eld_syntax && get_bits1(gb)) {
1835 avpriv_request_sample(ac->avctx, "SSR");
1836 return AVERROR_PATCHWELCOME;
1838 // I see no textual basis in the spec for this occurring after SSR gain
1839 // control, but this is what both reference and real implmentations do
1840 if (tns->present && er_syntax)
1841 if (decode_tns(ac, tns, gb, ics) < 0)
1842 return AVERROR_INVALIDDATA;
1845 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1846 &pulse, ics, sce->band_type) < 0)
1847 return AVERROR_INVALIDDATA;
1849 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1850 apply_prediction(ac, sce);
1856 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1858 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1860 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1861 float *ch0 = cpe->ch[0].coeffs;
1862 float *ch1 = cpe->ch[1].coeffs;
1863 int g, i, group, idx = 0;
1864 const uint16_t *offsets = ics->swb_offset;
1865 for (g = 0; g < ics->num_window_groups; g++) {
1866 for (i = 0; i < ics->max_sfb; i++, idx++) {
1867 if (cpe->ms_mask[idx] &&
1868 cpe->ch[0].band_type[idx] < NOISE_BT &&
1869 cpe->ch[1].band_type[idx] < NOISE_BT) {
1870 for (group = 0; group < ics->group_len[g]; group++) {
1871 ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
1872 ch1 + group * 128 + offsets[i],
1873 offsets[i+1] - offsets[i]);
1877 ch0 += ics->group_len[g] * 128;
1878 ch1 += ics->group_len[g] * 128;
1883 * intensity stereo decoding; reference: 4.6.8.2.3
1885 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1886 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1887 * [3] reserved for scalable AAC
1889 static void apply_intensity_stereo(AACContext *ac,
1890 ChannelElement *cpe, int ms_present)
1892 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1893 SingleChannelElement *sce1 = &cpe->ch[1];
1894 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1895 const uint16_t *offsets = ics->swb_offset;
1896 int g, group, i, idx = 0;
1899 for (g = 0; g < ics->num_window_groups; g++) {
1900 for (i = 0; i < ics->max_sfb;) {
1901 if (sce1->band_type[idx] == INTENSITY_BT ||
1902 sce1->band_type[idx] == INTENSITY_BT2) {
1903 const int bt_run_end = sce1->band_type_run_end[idx];
1904 for (; i < bt_run_end; i++, idx++) {
1905 c = -1 + 2 * (sce1->band_type[idx] - 14);
1907 c *= 1 - 2 * cpe->ms_mask[idx];
1908 scale = c * sce1->sf[idx];
1909 for (group = 0; group < ics->group_len[g]; group++)
1910 ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1911 coef0 + group * 128 + offsets[i],
1913 offsets[i + 1] - offsets[i]);
1916 int bt_run_end = sce1->band_type_run_end[idx];
1917 idx += bt_run_end - i;
1921 coef0 += ics->group_len[g] * 128;
1922 coef1 += ics->group_len[g] * 128;
1927 * Decode a channel_pair_element; reference: table 4.4.
1929 * @return Returns error status. 0 - OK, !0 - error
1931 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1933 int i, ret, common_window, ms_present = 0;
1934 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1936 common_window = eld_syntax || get_bits1(gb);
1937 if (common_window) {
1938 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1939 return AVERROR_INVALIDDATA;
1940 i = cpe->ch[1].ics.use_kb_window[0];
1941 cpe->ch[1].ics = cpe->ch[0].ics;
1942 cpe->ch[1].ics.use_kb_window[1] = i;
1943 if (cpe->ch[1].ics.predictor_present &&
1944 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1945 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1946 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1947 ms_present = get_bits(gb, 2);
1948 if (ms_present == 3) {
1949 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1950 return AVERROR_INVALIDDATA;
1951 } else if (ms_present)
1952 decode_mid_side_stereo(cpe, gb, ms_present);
1954 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1956 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1959 if (common_window) {
1961 apply_mid_side_stereo(ac, cpe);
1962 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1963 apply_prediction(ac, &cpe->ch[0]);
1964 apply_prediction(ac, &cpe->ch[1]);
1968 apply_intensity_stereo(ac, cpe, ms_present);
1972 static const float cce_scale[] = {
1973 1.09050773266525765921, //2^(1/8)
1974 1.18920711500272106672, //2^(1/4)
1980 * Decode coupling_channel_element; reference: table 4.8.
1982 * @return Returns error status. 0 - OK, !0 - error
1984 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1990 SingleChannelElement *sce = &che->ch[0];
1991 ChannelCoupling *coup = &che->coup;
1993 coup->coupling_point = 2 * get_bits1(gb);
1994 coup->num_coupled = get_bits(gb, 3);
1995 for (c = 0; c <= coup->num_coupled; c++) {
1997 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1998 coup->id_select[c] = get_bits(gb, 4);
1999 if (coup->type[c] == TYPE_CPE) {
2000 coup->ch_select[c] = get_bits(gb, 2);
2001 if (coup->ch_select[c] == 3)
2004 coup->ch_select[c] = 2;
2006 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2008 sign = get_bits(gb, 1);
2009 scale = cce_scale[get_bits(gb, 2)];
2011 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2014 for (c = 0; c < num_gain; c++) {
2018 float gain_cache = 1.0;
2020 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2021 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2022 gain_cache = powf(scale, -gain);
2024 if (coup->coupling_point == AFTER_IMDCT) {
2025 coup->gain[c][0] = gain_cache;
2027 for (g = 0; g < sce->ics.num_window_groups; g++) {
2028 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2029 if (sce->band_type[idx] != ZERO_BT) {
2031 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2039 gain_cache = powf(scale, -t) * s;
2042 coup->gain[c][idx] = gain_cache;
2052 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2054 * @return Returns number of bytes consumed.
2056 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2060 int num_excl_chan = 0;
2063 for (i = 0; i < 7; i++)
2064 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2065 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2067 return num_excl_chan / 7;
2071 * Decode dynamic range information; reference: table 4.52.
2073 * @return Returns number of bytes consumed.
2075 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2079 int drc_num_bands = 1;
2082 /* pce_tag_present? */
2083 if (get_bits1(gb)) {
2084 che_drc->pce_instance_tag = get_bits(gb, 4);
2085 skip_bits(gb, 4); // tag_reserved_bits
2089 /* excluded_chns_present? */
2090 if (get_bits1(gb)) {
2091 n += decode_drc_channel_exclusions(che_drc, gb);
2094 /* drc_bands_present? */
2095 if (get_bits1(gb)) {
2096 che_drc->band_incr = get_bits(gb, 4);
2097 che_drc->interpolation_scheme = get_bits(gb, 4);
2099 drc_num_bands += che_drc->band_incr;
2100 for (i = 0; i < drc_num_bands; i++) {
2101 che_drc->band_top[i] = get_bits(gb, 8);
2106 /* prog_ref_level_present? */
2107 if (get_bits1(gb)) {
2108 che_drc->prog_ref_level = get_bits(gb, 7);
2109 skip_bits1(gb); // prog_ref_level_reserved_bits
2113 for (i = 0; i < drc_num_bands; i++) {
2114 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2115 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2122 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2124 int i, major, minor;
2129 get_bits(gb, 13); len -= 13;
2131 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2132 buf[i] = get_bits(gb, 8);
2135 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2136 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2138 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2139 ac->avctx->internal->skip_samples = 1024;
2143 skip_bits_long(gb, len);
2149 * Decode extension data (incomplete); reference: table 4.51.
2151 * @param cnt length of TYPE_FIL syntactic element in bytes
2153 * @return Returns number of bytes consumed
2155 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2156 ChannelElement *che, enum RawDataBlockType elem_type)
2160 int type = get_bits(gb, 4);
2162 if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2163 av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2165 switch (type) { // extension type
2166 case EXT_SBR_DATA_CRC:
2170 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2172 } else if (!ac->oc[1].m4ac.sbr) {
2173 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2174 skip_bits_long(gb, 8 * cnt - 4);
2176 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2177 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2178 skip_bits_long(gb, 8 * cnt - 4);
2180 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2181 ac->oc[1].m4ac.sbr = 1;
2182 ac->oc[1].m4ac.ps = 1;
2183 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2184 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2185 ac->oc[1].status, 1);
2187 ac->oc[1].m4ac.sbr = 1;
2188 ac->avctx->profile = FF_PROFILE_AAC_HE;
2190 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2192 case EXT_DYNAMIC_RANGE:
2193 res = decode_dynamic_range(&ac->che_drc, gb);
2196 decode_fill(ac, gb, 8 * cnt - 4);
2199 case EXT_DATA_ELEMENT:
2201 skip_bits_long(gb, 8 * cnt - 4);
2208 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2210 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2211 * @param coef spectral coefficients
2213 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2214 IndividualChannelStream *ics, int decode)
2216 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2218 int bottom, top, order, start, end, size, inc;
2219 float lpc[TNS_MAX_ORDER];
2220 float tmp[TNS_MAX_ORDER+1];
2222 for (w = 0; w < ics->num_windows; w++) {
2223 bottom = ics->num_swb;
2224 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2226 bottom = FFMAX(0, top - tns->length[w][filt]);
2227 order = tns->order[w][filt];
2232 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2234 start = ics->swb_offset[FFMIN(bottom, mmm)];
2235 end = ics->swb_offset[FFMIN( top, mmm)];
2236 if ((size = end - start) <= 0)
2238 if (tns->direction[w][filt]) {
2248 for (m = 0; m < size; m++, start += inc)
2249 for (i = 1; i <= FFMIN(m, order); i++)
2250 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2253 for (m = 0; m < size; m++, start += inc) {
2254 tmp[0] = coef[start];
2255 for (i = 1; i <= FFMIN(m, order); i++)
2256 coef[start] += tmp[i] * lpc[i - 1];
2257 for (i = order; i > 0; i--)
2258 tmp[i] = tmp[i - 1];
2266 * Apply windowing and MDCT to obtain the spectral
2267 * coefficient from the predicted sample by LTP.
2269 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2270 float *in, IndividualChannelStream *ics)
2272 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2273 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2274 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2275 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2277 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2278 ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
2280 memset(in, 0, 448 * sizeof(float));
2281 ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
2283 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2284 ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2286 ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2287 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2289 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2293 * Apply the long term prediction
2295 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2297 const LongTermPrediction *ltp = &sce->ics.ltp;
2298 const uint16_t *offsets = sce->ics.swb_offset;
2301 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2302 float *predTime = sce->ret;
2303 float *predFreq = ac->buf_mdct;
2304 int16_t num_samples = 2048;
2306 if (ltp->lag < 1024)
2307 num_samples = ltp->lag + 1024;
2308 for (i = 0; i < num_samples; i++)
2309 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2310 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2312 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2314 if (sce->tns.present)
2315 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2317 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2319 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2320 sce->coeffs[i] += predFreq[i];
2325 * Update the LTP buffer for next frame
2327 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2329 IndividualChannelStream *ics = &sce->ics;
2330 float *saved = sce->saved;
2331 float *saved_ltp = sce->coeffs;
2332 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2333 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2336 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2337 memcpy(saved_ltp, saved, 512 * sizeof(float));
2338 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2339 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2340 for (i = 0; i < 64; i++)
2341 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2342 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2343 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2344 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2345 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2346 for (i = 0; i < 64; i++)
2347 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2348 } else { // LONG_STOP or ONLY_LONG
2349 ac->fdsp->vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2350 for (i = 0; i < 512; i++)
2351 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2354 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2355 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2356 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2360 * Conduct IMDCT and windowing.
2362 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2364 IndividualChannelStream *ics = &sce->ics;
2365 float *in = sce->coeffs;
2366 float *out = sce->ret;
2367 float *saved = sce->saved;
2368 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2369 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2370 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2371 float *buf = ac->buf_mdct;
2372 float *temp = ac->temp;
2376 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2377 for (i = 0; i < 1024; i += 128)
2378 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2380 ac->mdct.imdct_half(&ac->mdct, buf, in);
2382 /* window overlapping
2383 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2384 * and long to short transitions are considered to be short to short
2385 * transitions. This leaves just two cases (long to long and short to short)
2386 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2388 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2389 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2390 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2392 memcpy( out, saved, 448 * sizeof(float));
2394 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2395 ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2396 ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2397 ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2398 ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2399 ac->fdsp->vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2400 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2402 ac->fdsp->vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2403 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2408 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2409 memcpy( saved, temp + 64, 64 * sizeof(float));
2410 ac->fdsp->vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2411 ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2412 ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2413 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2414 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2415 memcpy( saved, buf + 512, 448 * sizeof(float));
2416 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2417 } else { // LONG_STOP or ONLY_LONG
2418 memcpy( saved, buf + 512, 512 * sizeof(float));
2422 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2424 IndividualChannelStream *ics = &sce->ics;
2425 float *in = sce->coeffs;
2426 float *out = sce->ret;
2427 float *saved = sce->saved;
2428 float *buf = ac->buf_mdct;
2431 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2433 // window overlapping
2434 if (ics->use_kb_window[1]) {
2435 // AAC LD uses a low overlap sine window instead of a KBD window
2436 memcpy(out, saved, 192 * sizeof(float));
2437 ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2438 memcpy( out + 320, buf + 64, 192 * sizeof(float));
2440 ac->fdsp->vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2444 memcpy(saved, buf + 256, 256 * sizeof(float));
2447 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2449 float *in = sce->coeffs;
2450 float *out = sce->ret;
2451 float *saved = sce->saved;
2452 float *buf = ac->buf_mdct;
2454 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2455 const int n2 = n >> 1;
2456 const int n4 = n >> 2;
2457 const float *const window = n == 480 ? ff_aac_eld_window_480 :
2458 ff_aac_eld_window_512;
2460 // Inverse transform, mapped to the conventional IMDCT by
2461 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2462 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2463 // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2464 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2465 for (i = 0; i < n2; i+=2) {
2467 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2468 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2471 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
2473 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2474 for (i = 0; i < n; i+=2) {
2477 // Like with the regular IMDCT at this point we still have the middle half
2478 // of a transform but with even symmetry on the left and odd symmetry on
2481 // window overlapping
2482 // The spec says to use samples [0..511] but the reference decoder uses
2483 // samples [128..639].
2484 for (i = n4; i < n2; i ++) {
2485 out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2486 saved[ i + n2] * window[i + n - n4] +
2487 -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2488 -saved[2*n + n2 + i] * window[i + 3*n - n4];
2490 for (i = 0; i < n2; i ++) {
2491 out[n4 + i] = buf[i] * window[i + n2 - n4] +
2492 -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2493 -saved[ n + i] * window[i + n2 + 2*n - n4] +
2494 saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2496 for (i = 0; i < n4; i ++) {
2497 out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2498 -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2499 -saved[ n + n2 + i] * window[i + 3*n - n4];
2503 memmove(saved + n, saved, 2 * n * sizeof(float));
2504 memcpy( saved, buf, n * sizeof(float));
2508 * channel coupling transformation interface
2510 * @param apply_coupling_method pointer to (in)dependent coupling function
2512 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2513 enum RawDataBlockType type, int elem_id,
2514 enum CouplingPoint coupling_point,
2515 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2519 for (i = 0; i < MAX_ELEM_ID; i++) {
2520 ChannelElement *cce = ac->che[TYPE_CCE][i];
2523 if (cce && cce->coup.coupling_point == coupling_point) {
2524 ChannelCoupling *coup = &cce->coup;
2526 for (c = 0; c <= coup->num_coupled; c++) {
2527 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2528 if (coup->ch_select[c] != 1) {
2529 apply_coupling_method(ac, &cc->ch[0], cce, index);
2530 if (coup->ch_select[c] != 0)
2533 if (coup->ch_select[c] != 2)
2534 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2536 index += 1 + (coup->ch_select[c] == 3);
2543 * Convert spectral data to float samples, applying all supported tools as appropriate.
2545 static void spectral_to_sample(AACContext *ac)
2548 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2549 switch (ac->oc[1].m4ac.object_type) {
2551 imdct_and_window = imdct_and_windowing_ld;
2553 case AOT_ER_AAC_ELD:
2554 imdct_and_window = imdct_and_windowing_eld;
2557 imdct_and_window = ac->imdct_and_windowing;
2559 for (type = 3; type >= 0; type--) {
2560 for (i = 0; i < MAX_ELEM_ID; i++) {
2561 ChannelElement *che = ac->che[type][i];
2562 if (che && che->present) {
2563 if (type <= TYPE_CPE)
2564 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2565 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2566 if (che->ch[0].ics.predictor_present) {
2567 if (che->ch[0].ics.ltp.present)
2568 ac->apply_ltp(ac, &che->ch[0]);
2569 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2570 ac->apply_ltp(ac, &che->ch[1]);
2573 if (che->ch[0].tns.present)
2574 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2575 if (che->ch[1].tns.present)
2576 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2577 if (type <= TYPE_CPE)
2578 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2579 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2580 imdct_and_window(ac, &che->ch[0]);
2581 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2582 ac->update_ltp(ac, &che->ch[0]);
2583 if (type == TYPE_CPE) {
2584 imdct_and_window(ac, &che->ch[1]);
2585 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2586 ac->update_ltp(ac, &che->ch[1]);
2588 if (ac->oc[1].m4ac.sbr > 0) {
2589 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2592 if (type <= TYPE_CCE)
2593 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2596 av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
2602 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2605 AACADTSHeaderInfo hdr_info;
2606 uint8_t layout_map[MAX_ELEM_ID*4][3];
2607 int layout_map_tags, ret;
2609 size = avpriv_aac_parse_header(gb, &hdr_info);
2611 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2612 // This is 2 for "VLB " audio in NSV files.
2613 // See samples/nsv/vlb_audio.
2614 avpriv_report_missing_feature(ac->avctx,
2615 "More than one AAC RDB per ADTS frame");
2616 ac->warned_num_aac_frames = 1;
2618 push_output_configuration(ac);
2619 if (hdr_info.chan_config) {
2620 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2621 if ((ret = set_default_channel_config(ac->avctx,
2624 hdr_info.chan_config)) < 0)
2626 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2627 FFMAX(ac->oc[1].status,
2628 OC_TRIAL_FRAME), 0)) < 0)
2631 ac->oc[1].m4ac.chan_config = 0;
2633 * dual mono frames in Japanese DTV can have chan_config 0
2634 * WITHOUT specifying PCE.
2635 * thus, set dual mono as default.
2637 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2638 layout_map_tags = 2;
2639 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2640 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2641 layout_map[0][1] = 0;
2642 layout_map[1][1] = 1;
2643 if (output_configure(ac, layout_map, layout_map_tags,
2648 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2649 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2650 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2651 ac->oc[1].m4ac.frame_length_short = 0;
2652 if (ac->oc[0].status != OC_LOCKED ||
2653 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2654 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2655 ac->oc[1].m4ac.sbr = -1;
2656 ac->oc[1].m4ac.ps = -1;
2658 if (!hdr_info.crc_absent)
2664 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2665 int *got_frame_ptr, GetBitContext *gb)
2667 AACContext *ac = avctx->priv_data;
2668 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
2669 ChannelElement *che;
2671 int samples = m4ac->frame_length_short ? 960 : 1024;
2672 int chan_config = m4ac->chan_config;
2673 int aot = m4ac->object_type;
2675 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
2680 if ((err = frame_configure_elements(avctx)) < 0)
2683 // The FF_PROFILE_AAC_* defines are all object_type - 1
2684 // This may lead to an undefined profile being signaled
2685 ac->avctx->profile = aot - 1;
2687 ac->tags_mapped = 0;
2689 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
2690 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2692 return AVERROR_INVALIDDATA;
2694 for (i = 0; i < tags_per_config[chan_config]; i++) {
2695 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2696 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2697 if (!(che=get_che(ac, elem_type, elem_id))) {
2698 av_log(ac->avctx, AV_LOG_ERROR,
2699 "channel element %d.%d is not allocated\n",
2700 elem_type, elem_id);
2701 return AVERROR_INVALIDDATA;
2704 if (aot != AOT_ER_AAC_ELD)
2706 switch (elem_type) {
2708 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2711 err = decode_cpe(ac, gb, che);
2714 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2721 spectral_to_sample(ac);
2723 ac->frame->nb_samples = samples;
2724 ac->frame->sample_rate = avctx->sample_rate;
2727 skip_bits_long(gb, get_bits_left(gb));
2731 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2732 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
2734 AACContext *ac = avctx->priv_data;
2735 ChannelElement *che = NULL, *che_prev = NULL;
2736 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2738 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2739 int is_dmono, sce_count = 0;
2743 if (show_bits(gb, 12) == 0xfff) {
2744 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2745 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2748 if (ac->oc[1].m4ac.sampling_index > 12) {
2749 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2750 err = AVERROR_INVALIDDATA;
2755 if ((err = frame_configure_elements(avctx)) < 0)
2758 // The FF_PROFILE_AAC_* defines are all object_type - 1
2759 // This may lead to an undefined profile being signaled
2760 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2762 ac->tags_mapped = 0;
2764 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2765 elem_id = get_bits(gb, 4);
2767 if (avctx->debug & FF_DEBUG_STARTCODE)
2768 av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
2770 if (!avctx->channels && elem_type != TYPE_PCE) {
2771 err = AVERROR_INVALIDDATA;
2775 if (elem_type < TYPE_DSE) {
2776 if (!(che=get_che(ac, elem_type, elem_id))) {
2777 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2778 elem_type, elem_id);
2779 err = AVERROR_INVALIDDATA;
2786 switch (elem_type) {
2789 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2795 err = decode_cpe(ac, gb, che);
2800 err = decode_cce(ac, gb, che);
2804 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2809 err = skip_data_stream_element(ac, gb);
2813 uint8_t layout_map[MAX_ELEM_ID*4][3];
2815 push_output_configuration(ac);
2816 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2822 av_log(avctx, AV_LOG_ERROR,
2823 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2825 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2827 ac->oc[1].m4ac.chan_config = 0;
2835 elem_id += get_bits(gb, 8) - 1;
2836 if (get_bits_left(gb) < 8 * elem_id) {
2837 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
2838 err = AVERROR_INVALIDDATA;
2842 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2843 err = 0; /* FIXME */
2847 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2852 elem_type_prev = elem_type;
2857 if (get_bits_left(gb) < 3) {
2858 av_log(avctx, AV_LOG_ERROR, overread_err);
2859 err = AVERROR_INVALIDDATA;
2864 if (!avctx->channels) {
2869 spectral_to_sample(ac);
2871 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2872 samples <<= multiplier;
2874 if (ac->oc[1].status && audio_found) {
2875 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2876 avctx->frame_size = samples;
2877 ac->oc[1].status = OC_LOCKED;
2882 const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2883 if (side && side_size>=4)
2884 AV_WL32(side, 2*AV_RL32(side));
2887 if (!ac->frame->data[0] && samples) {
2888 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
2889 err = AVERROR_INVALIDDATA;
2894 ac->frame->nb_samples = samples;
2895 ac->frame->sample_rate = avctx->sample_rate;
2897 av_frame_unref(ac->frame);
2898 *got_frame_ptr = !!samples;
2900 /* for dual-mono audio (SCE + SCE) */
2901 is_dmono = ac->dmono_mode && sce_count == 2 &&
2902 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
2904 if (ac->dmono_mode == 1)
2905 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
2906 else if (ac->dmono_mode == 2)
2907 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
2912 pop_output_configuration(ac);
2916 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2917 int *got_frame_ptr, AVPacket *avpkt)
2919 AACContext *ac = avctx->priv_data;
2920 const uint8_t *buf = avpkt->data;
2921 int buf_size = avpkt->size;
2926 int new_extradata_size;
2927 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2928 AV_PKT_DATA_NEW_EXTRADATA,
2929 &new_extradata_size);
2930 int jp_dualmono_size;
2931 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
2932 AV_PKT_DATA_JP_DUALMONO,
2935 if (new_extradata && 0) {
2936 av_free(avctx->extradata);
2937 avctx->extradata = av_mallocz(new_extradata_size +
2938 FF_INPUT_BUFFER_PADDING_SIZE);
2939 if (!avctx->extradata)
2940 return AVERROR(ENOMEM);
2941 avctx->extradata_size = new_extradata_size;
2942 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2943 push_output_configuration(ac);
2944 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2946 avctx->extradata_size*8, 1) < 0) {
2947 pop_output_configuration(ac);
2948 return AVERROR_INVALIDDATA;
2953 if (jp_dualmono && jp_dualmono_size > 0)
2954 ac->dmono_mode = 1 + *jp_dualmono;
2955 if (ac->force_dmono_mode >= 0)
2956 ac->dmono_mode = ac->force_dmono_mode;
2958 if (INT_MAX / 8 <= buf_size)
2959 return AVERROR_INVALIDDATA;
2961 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
2964 switch (ac->oc[1].m4ac.object_type) {
2966 case AOT_ER_AAC_LTP:
2968 case AOT_ER_AAC_ELD:
2969 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
2972 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
2977 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2978 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2979 if (buf[buf_offset])
2982 return buf_size > buf_offset ? buf_consumed : buf_size;
2985 static av_cold int aac_decode_close(AVCodecContext *avctx)
2987 AACContext *ac = avctx->priv_data;
2990 for (i = 0; i < MAX_ELEM_ID; i++) {
2991 for (type = 0; type < 4; type++) {
2992 if (ac->che[type][i])
2993 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2994 av_freep(&ac->che[type][i]);
2998 ff_mdct_end(&ac->mdct);
2999 ff_mdct_end(&ac->mdct_small);
3000 ff_mdct_end(&ac->mdct_ld);
3001 ff_mdct_end(&ac->mdct_ltp);
3002 ff_imdct15_uninit(&ac->mdct480);
3003 av_freep(&ac->fdsp);
3007 static void aacdec_init(AACContext *c)
3009 c->imdct_and_windowing = imdct_and_windowing;
3010 c->apply_ltp = apply_ltp;
3011 c->apply_tns = apply_tns;
3012 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3013 c->update_ltp = update_ltp;
3016 ff_aacdec_init_mips(c);
3019 * AVOptions for Japanese DTV specific extensions (ADTS only)
3021 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3022 static const AVOption options[] = {
3023 {"dual_mono_mode", "Select the channel to decode for dual mono",
3024 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3025 AACDEC_FLAGS, "dual_mono_mode"},
3027 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3028 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3029 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3030 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3035 static const AVClass aac_decoder_class = {
3036 .class_name = "AAC decoder",
3037 .item_name = av_default_item_name,
3039 .version = LIBAVUTIL_VERSION_INT,
3042 static const AVProfile profiles[] = {
3043 { FF_PROFILE_AAC_MAIN, "Main" },
3044 { FF_PROFILE_AAC_LOW, "LC" },
3045 { FF_PROFILE_AAC_SSR, "SSR" },
3046 { FF_PROFILE_AAC_LTP, "LTP" },
3047 { FF_PROFILE_AAC_HE, "HE-AAC" },
3048 { FF_PROFILE_AAC_HE_V2, "HE-AACv2" },
3049 { FF_PROFILE_AAC_LD, "LD" },
3050 { FF_PROFILE_AAC_ELD, "ELD" },
3051 { FF_PROFILE_UNKNOWN },