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 * AAC decoder fixed-point implementation
13 * MIPS Technologies, Inc., California.
15 * This file is part of FFmpeg.
17 * FFmpeg is free software; you can redistribute it and/or
18 * modify it under the terms of the GNU Lesser General Public
19 * License as published by the Free Software Foundation; either
20 * version 2.1 of the License, or (at your option) any later version.
22 * FFmpeg is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 * Lesser General Public License for more details.
27 * You should have received a copy of the GNU Lesser General Public
28 * License along with FFmpeg; if not, write to the Free Software
29 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 * @author Oded Shimon ( ods15 ods15 dyndns org )
36 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
38 * AAC decoder fixed-point implementation
39 * @author Stanislav Ocovaj ( stanislav.ocovaj imgtec com )
40 * @author Nedeljko Babic ( nedeljko.babic imgtec com )
47 * N (code in SoC repo) gain control
49 * Y window shapes - standard
50 * N window shapes - Low Delay
51 * Y filterbank - standard
52 * N (code in SoC repo) filterbank - Scalable Sample Rate
53 * Y Temporal Noise Shaping
54 * Y Long Term Prediction
57 * Y frequency domain prediction
58 * Y Perceptual Noise Substitution
60 * N Scalable Inverse AAC Quantization
61 * N Frequency Selective Switch
63 * Y quantization & coding - AAC
64 * N quantization & coding - TwinVQ
65 * N quantization & coding - BSAC
66 * N AAC Error Resilience tools
67 * N Error Resilience payload syntax
68 * N Error Protection tool
70 * N Silence Compression
73 * N Structured Audio tools
74 * N Structured Audio Sample Bank Format
76 * N Harmonic and Individual Lines plus Noise
77 * N Text-To-Speech Interface
78 * Y Spectral Band Replication
79 * Y (not in this code) Layer-1
80 * Y (not in this code) Layer-2
81 * Y (not in this code) Layer-3
82 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
84 * N Direct Stream Transfer
85 * Y (not in fixed point code) Enhanced AAC Low Delay (ER AAC ELD)
87 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
88 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
92 #include "libavutil/thread.h"
94 static VLC vlc_scalefactors;
95 static VLC vlc_spectral[11];
97 static int output_configure(AACContext *ac,
98 uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
99 enum OCStatus oc_type, int get_new_frame);
101 #define overread_err "Input buffer exhausted before END element found\n"
103 static int count_channels(uint8_t (*layout)[3], int tags)
106 for (i = 0; i < tags; i++) {
107 int syn_ele = layout[i][0];
108 int pos = layout[i][2];
109 sum += (1 + (syn_ele == TYPE_CPE)) *
110 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
116 * Check for the channel element in the current channel position configuration.
117 * If it exists, make sure the appropriate element is allocated and map the
118 * channel order to match the internal FFmpeg channel layout.
120 * @param che_pos current channel position configuration
121 * @param type channel element type
122 * @param id channel element id
123 * @param channels count of the number of channels in the configuration
125 * @return Returns error status. 0 - OK, !0 - error
127 static av_cold int che_configure(AACContext *ac,
128 enum ChannelPosition che_pos,
129 int type, int id, int *channels)
131 if (*channels >= MAX_CHANNELS)
132 return AVERROR_INVALIDDATA;
134 if (!ac->che[type][id]) {
135 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
136 return AVERROR(ENOMEM);
137 AAC_RENAME(ff_aac_sbr_ctx_init)(ac, &ac->che[type][id]->sbr, type);
139 if (type != TYPE_CCE) {
140 if (*channels >= MAX_CHANNELS - (type == TYPE_CPE || (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1))) {
141 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
142 return AVERROR_INVALIDDATA;
144 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
145 if (type == TYPE_CPE ||
146 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
147 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
151 if (ac->che[type][id])
152 AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][id]->sbr);
153 av_freep(&ac->che[type][id]);
158 static int frame_configure_elements(AVCodecContext *avctx)
160 AACContext *ac = avctx->priv_data;
161 int type, id, ch, ret;
163 /* set channel pointers to internal buffers by default */
164 for (type = 0; type < 4; type++) {
165 for (id = 0; id < MAX_ELEM_ID; id++) {
166 ChannelElement *che = ac->che[type][id];
168 che->ch[0].ret = che->ch[0].ret_buf;
169 che->ch[1].ret = che->ch[1].ret_buf;
174 /* get output buffer */
175 av_frame_unref(ac->frame);
176 if (!avctx->channels)
179 ac->frame->nb_samples = 2048;
180 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
183 /* map output channel pointers to AVFrame data */
184 for (ch = 0; ch < avctx->channels; ch++) {
185 if (ac->output_element[ch])
186 ac->output_element[ch]->ret = (INTFLOAT *)ac->frame->extended_data[ch];
192 struct elem_to_channel {
193 uint64_t av_position;
196 uint8_t aac_position;
199 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
200 uint8_t (*layout_map)[3], int offset, uint64_t left,
201 uint64_t right, int pos)
203 if (layout_map[offset][0] == TYPE_CPE) {
204 e2c_vec[offset] = (struct elem_to_channel) {
205 .av_position = left | right,
207 .elem_id = layout_map[offset][1],
212 e2c_vec[offset] = (struct elem_to_channel) {
215 .elem_id = layout_map[offset][1],
218 e2c_vec[offset + 1] = (struct elem_to_channel) {
219 .av_position = right,
221 .elem_id = layout_map[offset + 1][1],
228 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
231 int num_pos_channels = 0;
235 for (i = *current; i < tags; i++) {
236 if (layout_map[i][2] != pos)
238 if (layout_map[i][0] == TYPE_CPE) {
240 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
246 num_pos_channels += 2;
254 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
257 return num_pos_channels;
260 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
262 int i, n, total_non_cc_elements;
263 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
264 int num_front_channels, num_side_channels, num_back_channels;
267 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
272 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
273 if (num_front_channels < 0)
276 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
277 if (num_side_channels < 0)
280 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
281 if (num_back_channels < 0)
284 if (num_side_channels == 0 && num_back_channels >= 4) {
285 num_side_channels = 2;
286 num_back_channels -= 2;
290 if (num_front_channels & 1) {
291 e2c_vec[i] = (struct elem_to_channel) {
292 .av_position = AV_CH_FRONT_CENTER,
294 .elem_id = layout_map[i][1],
295 .aac_position = AAC_CHANNEL_FRONT
298 num_front_channels--;
300 if (num_front_channels >= 4) {
301 i += assign_pair(e2c_vec, layout_map, i,
302 AV_CH_FRONT_LEFT_OF_CENTER,
303 AV_CH_FRONT_RIGHT_OF_CENTER,
305 num_front_channels -= 2;
307 if (num_front_channels >= 2) {
308 i += assign_pair(e2c_vec, layout_map, i,
312 num_front_channels -= 2;
314 while (num_front_channels >= 2) {
315 i += assign_pair(e2c_vec, layout_map, i,
319 num_front_channels -= 2;
322 if (num_side_channels >= 2) {
323 i += assign_pair(e2c_vec, layout_map, i,
327 num_side_channels -= 2;
329 while (num_side_channels >= 2) {
330 i += assign_pair(e2c_vec, layout_map, i,
334 num_side_channels -= 2;
337 while (num_back_channels >= 4) {
338 i += assign_pair(e2c_vec, layout_map, i,
342 num_back_channels -= 2;
344 if (num_back_channels >= 2) {
345 i += assign_pair(e2c_vec, layout_map, i,
349 num_back_channels -= 2;
351 if (num_back_channels) {
352 e2c_vec[i] = (struct elem_to_channel) {
353 .av_position = AV_CH_BACK_CENTER,
355 .elem_id = layout_map[i][1],
356 .aac_position = AAC_CHANNEL_BACK
362 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
363 e2c_vec[i] = (struct elem_to_channel) {
364 .av_position = AV_CH_LOW_FREQUENCY,
366 .elem_id = layout_map[i][1],
367 .aac_position = AAC_CHANNEL_LFE
371 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
372 e2c_vec[i] = (struct elem_to_channel) {
373 .av_position = UINT64_MAX,
375 .elem_id = layout_map[i][1],
376 .aac_position = AAC_CHANNEL_LFE
381 // Must choose a stable sort
382 total_non_cc_elements = n = i;
385 for (i = 1; i < n; i++)
386 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
387 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
394 for (i = 0; i < total_non_cc_elements; i++) {
395 layout_map[i][0] = e2c_vec[i].syn_ele;
396 layout_map[i][1] = e2c_vec[i].elem_id;
397 layout_map[i][2] = e2c_vec[i].aac_position;
398 if (e2c_vec[i].av_position != UINT64_MAX) {
399 layout |= e2c_vec[i].av_position;
407 * Save current output configuration if and only if it has been locked.
409 static int push_output_configuration(AACContext *ac) {
412 if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
413 ac->oc[0] = ac->oc[1];
416 ac->oc[1].status = OC_NONE;
421 * Restore the previous output configuration if and only if the current
422 * configuration is unlocked.
424 static void pop_output_configuration(AACContext *ac) {
425 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
426 ac->oc[1] = ac->oc[0];
427 ac->avctx->channels = ac->oc[1].channels;
428 ac->avctx->channel_layout = ac->oc[1].channel_layout;
429 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
430 ac->oc[1].status, 0);
435 * Configure output channel order based on the current program
436 * configuration element.
438 * @return Returns error status. 0 - OK, !0 - error
440 static int output_configure(AACContext *ac,
441 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
442 enum OCStatus oc_type, int get_new_frame)
444 AVCodecContext *avctx = ac->avctx;
445 int i, channels = 0, ret;
447 uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
448 uint8_t type_counts[TYPE_END] = { 0 };
450 if (ac->oc[1].layout_map != layout_map) {
451 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
452 ac->oc[1].layout_map_tags = tags;
454 for (i = 0; i < tags; i++) {
455 int type = layout_map[i][0];
456 int id = layout_map[i][1];
457 id_map[type][id] = type_counts[type]++;
458 if (id_map[type][id] >= MAX_ELEM_ID) {
459 avpriv_request_sample(ac->avctx, "Too large remapped id");
460 return AVERROR_PATCHWELCOME;
463 // Try to sniff a reasonable channel order, otherwise output the
464 // channels in the order the PCE declared them.
465 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
466 layout = sniff_channel_order(layout_map, tags);
467 for (i = 0; i < tags; i++) {
468 int type = layout_map[i][0];
469 int id = layout_map[i][1];
470 int iid = id_map[type][id];
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, iid, &channels);
477 ac->tag_che_map[type][id] = ac->che[type][iid];
479 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
480 if (layout == AV_CH_FRONT_CENTER) {
481 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
487 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 && channel_config < 11) ||
529 channel_config > 12) {
530 av_log(avctx, AV_LOG_ERROR,
531 "invalid default channel configuration (%d)\n",
533 return AVERROR_INVALIDDATA;
535 *tags = tags_per_config[channel_config];
536 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
537 *tags * sizeof(*layout_map));
540 * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
541 * However, at least Nero AAC encoder encodes 7.1 streams using the default
542 * channel config 7, mapping the side channels of the original audio stream
543 * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
544 * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
545 * the incorrect streams as if they were correct (and as the encoder intended).
547 * As actual intended 7.1(wide) streams are very rare, default to assuming a
548 * 7.1 layout was intended.
550 if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT) {
551 av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
552 " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
553 " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
554 layout_map[2][2] = AAC_CHANNEL_SIDE;
560 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
562 /* For PCE based channel configurations map the channels solely based
564 if (!ac->oc[1].m4ac.chan_config) {
565 return ac->tag_che_map[type][elem_id];
567 // Allow single CPE stereo files to be signalled with mono configuration.
568 if (!ac->tags_mapped && type == TYPE_CPE &&
569 ac->oc[1].m4ac.chan_config == 1) {
570 uint8_t layout_map[MAX_ELEM_ID*4][3];
572 push_output_configuration(ac);
574 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
576 if (set_default_channel_config(ac->avctx, layout_map,
577 &layout_map_tags, 2) < 0)
579 if (output_configure(ac, layout_map, layout_map_tags,
580 OC_TRIAL_FRAME, 1) < 0)
583 ac->oc[1].m4ac.chan_config = 2;
584 ac->oc[1].m4ac.ps = 0;
587 if (!ac->tags_mapped && type == TYPE_SCE &&
588 ac->oc[1].m4ac.chan_config == 2) {
589 uint8_t layout_map[MAX_ELEM_ID * 4][3];
591 push_output_configuration(ac);
593 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
595 if (set_default_channel_config(ac->avctx, layout_map,
596 &layout_map_tags, 1) < 0)
598 if (output_configure(ac, layout_map, layout_map_tags,
599 OC_TRIAL_FRAME, 1) < 0)
602 ac->oc[1].m4ac.chan_config = 1;
603 if (ac->oc[1].m4ac.sbr)
604 ac->oc[1].m4ac.ps = -1;
606 /* For indexed channel configurations map the channels solely based
608 switch (ac->oc[1].m4ac.chan_config) {
611 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
613 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
616 if (ac->tags_mapped == 2 &&
617 ac->oc[1].m4ac.chan_config == 11 &&
620 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
623 /* Some streams incorrectly code 5.1 audio as
624 * SCE[0] CPE[0] CPE[1] SCE[1]
626 * SCE[0] CPE[0] CPE[1] LFE[0].
627 * If we seem to have encountered such a stream, transfer
628 * the LFE[0] element to the SCE[1]'s mapping */
629 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
630 if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
631 av_log(ac->avctx, AV_LOG_WARNING,
632 "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
633 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
634 ac->warned_remapping_once++;
637 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
640 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
642 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
645 /* Some streams incorrectly code 4.0 audio as
646 * SCE[0] CPE[0] LFE[0]
648 * SCE[0] CPE[0] SCE[1].
649 * If we seem to have encountered such a stream, transfer
650 * the SCE[1] element to the LFE[0]'s mapping */
651 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
652 if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
653 av_log(ac->avctx, AV_LOG_WARNING,
654 "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
655 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
656 ac->warned_remapping_once++;
659 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
661 if (ac->tags_mapped == 2 &&
662 ac->oc[1].m4ac.chan_config == 4 &&
665 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
669 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
672 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
673 } else if (ac->oc[1].m4ac.chan_config == 2) {
677 if (!ac->tags_mapped && type == TYPE_SCE) {
679 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
687 * Decode an array of 4 bit element IDs, optionally interleaved with a
688 * stereo/mono switching bit.
690 * @param type speaker type/position for these channels
692 static void decode_channel_map(uint8_t layout_map[][3],
693 enum ChannelPosition type,
694 GetBitContext *gb, int n)
697 enum RawDataBlockType syn_ele;
699 case AAC_CHANNEL_FRONT:
700 case AAC_CHANNEL_BACK:
701 case AAC_CHANNEL_SIDE:
702 syn_ele = get_bits1(gb);
708 case AAC_CHANNEL_LFE:
712 // AAC_CHANNEL_OFF has no channel map
715 layout_map[0][0] = syn_ele;
716 layout_map[0][1] = get_bits(gb, 4);
717 layout_map[0][2] = type;
722 static inline void relative_align_get_bits(GetBitContext *gb,
723 int reference_position) {
724 int n = (reference_position - get_bits_count(gb) & 7);
730 * Decode program configuration element; reference: table 4.2.
732 * @return Returns error status. 0 - OK, !0 - error
734 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
735 uint8_t (*layout_map)[3],
736 GetBitContext *gb, int byte_align_ref)
738 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
743 skip_bits(gb, 2); // object_type
745 sampling_index = get_bits(gb, 4);
746 if (m4ac->sampling_index != sampling_index)
747 av_log(avctx, AV_LOG_WARNING,
748 "Sample rate index in program config element does not "
749 "match the sample rate index configured by the container.\n");
751 num_front = get_bits(gb, 4);
752 num_side = get_bits(gb, 4);
753 num_back = get_bits(gb, 4);
754 num_lfe = get_bits(gb, 2);
755 num_assoc_data = get_bits(gb, 3);
756 num_cc = get_bits(gb, 4);
759 skip_bits(gb, 4); // mono_mixdown_tag
761 skip_bits(gb, 4); // stereo_mixdown_tag
764 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
766 if (get_bits_left(gb) < 5 * (num_front + num_side + num_back + num_cc) + 4 *(num_lfe + num_assoc_data + num_cc)) {
767 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
770 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
772 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
774 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
776 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
779 skip_bits_long(gb, 4 * num_assoc_data);
781 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
784 relative_align_get_bits(gb, byte_align_ref);
786 /* comment field, first byte is length */
787 comment_len = get_bits(gb, 8) * 8;
788 if (get_bits_left(gb) < comment_len) {
789 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
790 return AVERROR_INVALIDDATA;
792 skip_bits_long(gb, comment_len);
797 * Decode GA "General Audio" specific configuration; reference: table 4.1.
799 * @param ac pointer to AACContext, may be null
800 * @param avctx pointer to AVCCodecContext, used for logging
802 * @return Returns error status. 0 - OK, !0 - error
804 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
806 int get_bit_alignment,
807 MPEG4AudioConfig *m4ac,
810 int extension_flag, ret, ep_config, res_flags;
811 uint8_t layout_map[MAX_ELEM_ID*4][3];
815 if (get_bits1(gb)) { // frameLengthFlag
816 avpriv_report_missing_feature(avctx, "Fixed point 960/120 MDCT window");
817 return AVERROR_PATCHWELCOME;
819 m4ac->frame_length_short = 0;
821 m4ac->frame_length_short = get_bits1(gb);
822 if (m4ac->frame_length_short && m4ac->sbr == 1) {
823 avpriv_report_missing_feature(avctx, "SBR with 960 frame length");
824 if (ac) ac->warned_960_sbr = 1;
830 if (get_bits1(gb)) // dependsOnCoreCoder
831 skip_bits(gb, 14); // coreCoderDelay
832 extension_flag = get_bits1(gb);
834 if (m4ac->object_type == AOT_AAC_SCALABLE ||
835 m4ac->object_type == AOT_ER_AAC_SCALABLE)
836 skip_bits(gb, 3); // layerNr
838 if (channel_config == 0) {
839 skip_bits(gb, 4); // element_instance_tag
840 tags = decode_pce(avctx, m4ac, layout_map, gb, get_bit_alignment);
844 if ((ret = set_default_channel_config(avctx, layout_map,
845 &tags, channel_config)))
849 if (count_channels(layout_map, tags) > 1) {
851 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
854 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
857 if (extension_flag) {
858 switch (m4ac->object_type) {
860 skip_bits(gb, 5); // numOfSubFrame
861 skip_bits(gb, 11); // layer_length
865 case AOT_ER_AAC_SCALABLE:
867 res_flags = get_bits(gb, 3);
869 avpriv_report_missing_feature(avctx,
870 "AAC data resilience (flags %x)",
872 return AVERROR_PATCHWELCOME;
876 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
878 switch (m4ac->object_type) {
881 case AOT_ER_AAC_SCALABLE:
883 ep_config = get_bits(gb, 2);
885 avpriv_report_missing_feature(avctx,
886 "epConfig %d", ep_config);
887 return AVERROR_PATCHWELCOME;
893 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
895 MPEG4AudioConfig *m4ac,
898 int ret, ep_config, res_flags;
899 uint8_t layout_map[MAX_ELEM_ID*4][3];
901 const int ELDEXT_TERM = 0;
906 if (get_bits1(gb)) { // frameLengthFlag
907 avpriv_request_sample(avctx, "960/120 MDCT window");
908 return AVERROR_PATCHWELCOME;
911 m4ac->frame_length_short = get_bits1(gb);
913 res_flags = get_bits(gb, 3);
915 avpriv_report_missing_feature(avctx,
916 "AAC data resilience (flags %x)",
918 return AVERROR_PATCHWELCOME;
921 if (get_bits1(gb)) { // ldSbrPresentFlag
922 avpriv_report_missing_feature(avctx,
924 return AVERROR_PATCHWELCOME;
927 while (get_bits(gb, 4) != ELDEXT_TERM) {
928 int len = get_bits(gb, 4);
930 len += get_bits(gb, 8);
932 len += get_bits(gb, 16);
933 if (get_bits_left(gb) < len * 8 + 4) {
934 av_log(avctx, AV_LOG_ERROR, overread_err);
935 return AVERROR_INVALIDDATA;
937 skip_bits_long(gb, 8 * len);
940 if ((ret = set_default_channel_config(avctx, layout_map,
941 &tags, channel_config)))
944 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
947 ep_config = get_bits(gb, 2);
949 avpriv_report_missing_feature(avctx,
950 "epConfig %d", ep_config);
951 return AVERROR_PATCHWELCOME;
957 * Decode audio specific configuration; reference: table 1.13.
959 * @param ac pointer to AACContext, may be null
960 * @param avctx pointer to AVCCodecContext, used for logging
961 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
962 * @param gb buffer holding an audio specific config
963 * @param get_bit_alignment relative alignment for byte align operations
964 * @param sync_extension look for an appended sync extension
966 * @return Returns error status or number of consumed bits. <0 - error
968 static int decode_audio_specific_config_gb(AACContext *ac,
969 AVCodecContext *avctx,
970 MPEG4AudioConfig *m4ac,
972 int get_bit_alignment,
976 GetBitContext gbc = *gb;
978 if ((i = ff_mpeg4audio_get_config_gb(m4ac, &gbc, sync_extension)) < 0)
979 return AVERROR_INVALIDDATA;
981 if (m4ac->sampling_index > 12) {
982 av_log(avctx, AV_LOG_ERROR,
983 "invalid sampling rate index %d\n",
984 m4ac->sampling_index);
985 return AVERROR_INVALIDDATA;
987 if (m4ac->object_type == AOT_ER_AAC_LD &&
988 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
989 av_log(avctx, AV_LOG_ERROR,
990 "invalid low delay sampling rate index %d\n",
991 m4ac->sampling_index);
992 return AVERROR_INVALIDDATA;
995 skip_bits_long(gb, i);
997 switch (m4ac->object_type) {
1003 if ((ret = decode_ga_specific_config(ac, avctx, gb, get_bit_alignment,
1004 m4ac, m4ac->chan_config)) < 0)
1007 case AOT_ER_AAC_ELD:
1008 if ((ret = decode_eld_specific_config(ac, avctx, gb,
1009 m4ac, m4ac->chan_config)) < 0)
1013 avpriv_report_missing_feature(avctx,
1014 "Audio object type %s%d",
1015 m4ac->sbr == 1 ? "SBR+" : "",
1017 return AVERROR(ENOSYS);
1021 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1022 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1023 m4ac->sample_rate, m4ac->sbr,
1026 return get_bits_count(gb);
1029 static int decode_audio_specific_config(AACContext *ac,
1030 AVCodecContext *avctx,
1031 MPEG4AudioConfig *m4ac,
1032 const uint8_t *data, int64_t bit_size,
1038 if (bit_size < 0 || bit_size > INT_MAX) {
1039 av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
1040 return AVERROR_INVALIDDATA;
1043 ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
1044 for (i = 0; i < bit_size >> 3; i++)
1045 ff_dlog(avctx, "%02x ", data[i]);
1046 ff_dlog(avctx, "\n");
1048 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
1051 return decode_audio_specific_config_gb(ac, avctx, m4ac, &gb, 0,
1056 * linear congruential pseudorandom number generator
1058 * @param previous_val pointer to the current state of the generator
1060 * @return Returns a 32-bit pseudorandom integer
1062 static av_always_inline int lcg_random(unsigned previous_val)
1064 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1068 static void reset_all_predictors(PredictorState *ps)
1071 for (i = 0; i < MAX_PREDICTORS; i++)
1072 reset_predict_state(&ps[i]);
1075 static int sample_rate_idx (int rate)
1077 if (92017 <= rate) return 0;
1078 else if (75132 <= rate) return 1;
1079 else if (55426 <= rate) return 2;
1080 else if (46009 <= rate) return 3;
1081 else if (37566 <= rate) return 4;
1082 else if (27713 <= rate) return 5;
1083 else if (23004 <= rate) return 6;
1084 else if (18783 <= rate) return 7;
1085 else if (13856 <= rate) return 8;
1086 else if (11502 <= rate) return 9;
1087 else if (9391 <= rate) return 10;
1091 static void reset_predictor_group(PredictorState *ps, int group_num)
1094 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1095 reset_predict_state(&ps[i]);
1098 #define AAC_INIT_VLC_STATIC(num, size) \
1099 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1100 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1101 sizeof(ff_aac_spectral_bits[num][0]), \
1102 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1103 sizeof(ff_aac_spectral_codes[num][0]), \
1106 static void aacdec_init(AACContext *ac);
1108 static av_cold void aac_static_table_init(void)
1110 AAC_INIT_VLC_STATIC( 0, 304);
1111 AAC_INIT_VLC_STATIC( 1, 270);
1112 AAC_INIT_VLC_STATIC( 2, 550);
1113 AAC_INIT_VLC_STATIC( 3, 300);
1114 AAC_INIT_VLC_STATIC( 4, 328);
1115 AAC_INIT_VLC_STATIC( 5, 294);
1116 AAC_INIT_VLC_STATIC( 6, 306);
1117 AAC_INIT_VLC_STATIC( 7, 268);
1118 AAC_INIT_VLC_STATIC( 8, 510);
1119 AAC_INIT_VLC_STATIC( 9, 366);
1120 AAC_INIT_VLC_STATIC(10, 462);
1122 AAC_RENAME(ff_aac_sbr_init)();
1126 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1127 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1128 ff_aac_scalefactor_bits,
1129 sizeof(ff_aac_scalefactor_bits[0]),
1130 sizeof(ff_aac_scalefactor_bits[0]),
1131 ff_aac_scalefactor_code,
1132 sizeof(ff_aac_scalefactor_code[0]),
1133 sizeof(ff_aac_scalefactor_code[0]),
1136 // window initialization
1137 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_1024), 4.0, 1024);
1138 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_128), 6.0, 128);
1140 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_960), 4.0, 960);
1141 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_120), 6.0, 120);
1142 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_960), 960);
1143 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_120), 120);
1145 AAC_RENAME(ff_init_ff_sine_windows)(10);
1146 AAC_RENAME(ff_init_ff_sine_windows)( 9);
1147 AAC_RENAME(ff_init_ff_sine_windows)( 7);
1149 AAC_RENAME(ff_cbrt_tableinit)();
1152 static AVOnce aac_table_init = AV_ONCE_INIT;
1154 static av_cold int aac_decode_init(AVCodecContext *avctx)
1156 AACContext *ac = avctx->priv_data;
1159 ret = ff_thread_once(&aac_table_init, &aac_static_table_init);
1161 return AVERROR_UNKNOWN;
1164 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1168 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1170 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1171 #endif /* USE_FIXED */
1173 if (avctx->extradata_size > 0) {
1174 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1176 avctx->extradata_size * 8LL,
1181 uint8_t layout_map[MAX_ELEM_ID*4][3];
1182 int layout_map_tags;
1184 sr = sample_rate_idx(avctx->sample_rate);
1185 ac->oc[1].m4ac.sampling_index = sr;
1186 ac->oc[1].m4ac.channels = avctx->channels;
1187 ac->oc[1].m4ac.sbr = -1;
1188 ac->oc[1].m4ac.ps = -1;
1190 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1191 if (ff_mpeg4audio_channels[i] == avctx->channels)
1193 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1196 ac->oc[1].m4ac.chan_config = i;
1198 if (ac->oc[1].m4ac.chan_config) {
1199 int ret = set_default_channel_config(avctx, layout_map,
1200 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1202 output_configure(ac, layout_map, layout_map_tags,
1204 else if (avctx->err_recognition & AV_EF_EXPLODE)
1205 return AVERROR_INVALIDDATA;
1209 if (avctx->channels > MAX_CHANNELS) {
1210 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1211 return AVERROR_INVALIDDATA;
1215 ac->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1217 ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1218 #endif /* USE_FIXED */
1220 return AVERROR(ENOMEM);
1223 ac->random_state = 0x1f2e3d4c;
1225 AAC_RENAME_32(ff_mdct_init)(&ac->mdct, 11, 1, 1.0 / RANGE15(1024.0));
1226 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ld, 10, 1, 1.0 / RANGE15(512.0));
1227 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_small, 8, 1, 1.0 / RANGE15(128.0));
1228 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ltp, 11, 0, RANGE15(-2.0));
1230 ret = ff_mdct15_init(&ac->mdct120, 1, 3, 1.0f/(16*1024*120*2));
1233 ret = ff_mdct15_init(&ac->mdct480, 1, 5, 1.0f/(16*1024*960));
1236 ret = ff_mdct15_init(&ac->mdct960, 1, 6, 1.0f/(16*1024*960*2));
1245 * Skip data_stream_element; reference: table 4.10.
1247 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1249 int byte_align = get_bits1(gb);
1250 int count = get_bits(gb, 8);
1252 count += get_bits(gb, 8);
1256 if (get_bits_left(gb) < 8 * count) {
1257 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1258 return AVERROR_INVALIDDATA;
1260 skip_bits_long(gb, 8 * count);
1264 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1268 if (get_bits1(gb)) {
1269 ics->predictor_reset_group = get_bits(gb, 5);
1270 if (ics->predictor_reset_group == 0 ||
1271 ics->predictor_reset_group > 30) {
1272 av_log(ac->avctx, AV_LOG_ERROR,
1273 "Invalid Predictor Reset Group.\n");
1274 return AVERROR_INVALIDDATA;
1277 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1278 ics->prediction_used[sfb] = get_bits1(gb);
1284 * Decode Long Term Prediction data; reference: table 4.xx.
1286 static void decode_ltp(LongTermPrediction *ltp,
1287 GetBitContext *gb, uint8_t max_sfb)
1291 ltp->lag = get_bits(gb, 11);
1292 ltp->coef = ltp_coef[get_bits(gb, 3)];
1293 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1294 ltp->used[sfb] = get_bits1(gb);
1298 * Decode Individual Channel Stream info; reference: table 4.6.
1300 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1303 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1304 const int aot = m4ac->object_type;
1305 const int sampling_index = m4ac->sampling_index;
1306 int ret_fail = AVERROR_INVALIDDATA;
1308 if (aot != AOT_ER_AAC_ELD) {
1309 if (get_bits1(gb)) {
1310 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1311 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1312 return AVERROR_INVALIDDATA;
1314 ics->window_sequence[1] = ics->window_sequence[0];
1315 ics->window_sequence[0] = get_bits(gb, 2);
1316 if (aot == AOT_ER_AAC_LD &&
1317 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1318 av_log(ac->avctx, AV_LOG_ERROR,
1319 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1320 "window sequence %d found.\n", ics->window_sequence[0]);
1321 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1322 return AVERROR_INVALIDDATA;
1324 ics->use_kb_window[1] = ics->use_kb_window[0];
1325 ics->use_kb_window[0] = get_bits1(gb);
1327 ics->num_window_groups = 1;
1328 ics->group_len[0] = 1;
1329 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1331 ics->max_sfb = get_bits(gb, 4);
1332 for (i = 0; i < 7; i++) {
1333 if (get_bits1(gb)) {
1334 ics->group_len[ics->num_window_groups - 1]++;
1336 ics->num_window_groups++;
1337 ics->group_len[ics->num_window_groups - 1] = 1;
1340 ics->num_windows = 8;
1341 if (m4ac->frame_length_short) {
1342 ics->swb_offset = ff_swb_offset_120[sampling_index];
1343 ics->num_swb = ff_aac_num_swb_120[sampling_index];
1345 ics->swb_offset = ff_swb_offset_128[sampling_index];
1346 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1348 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
1349 ics->predictor_present = 0;
1351 ics->max_sfb = get_bits(gb, 6);
1352 ics->num_windows = 1;
1353 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1354 if (m4ac->frame_length_short) {
1355 ics->swb_offset = ff_swb_offset_480[sampling_index];
1356 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1357 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1359 ics->swb_offset = ff_swb_offset_512[sampling_index];
1360 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1361 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1363 if (!ics->num_swb || !ics->swb_offset) {
1364 ret_fail = AVERROR_BUG;
1368 if (m4ac->frame_length_short) {
1369 ics->num_swb = ff_aac_num_swb_960[sampling_index];
1370 ics->swb_offset = ff_swb_offset_960[sampling_index];
1372 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1373 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1375 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1377 if (aot != AOT_ER_AAC_ELD) {
1378 ics->predictor_present = get_bits1(gb);
1379 ics->predictor_reset_group = 0;
1381 if (ics->predictor_present) {
1382 if (aot == AOT_AAC_MAIN) {
1383 if (decode_prediction(ac, ics, gb)) {
1386 } else if (aot == AOT_AAC_LC ||
1387 aot == AOT_ER_AAC_LC) {
1388 av_log(ac->avctx, AV_LOG_ERROR,
1389 "Prediction is not allowed in AAC-LC.\n");
1392 if (aot == AOT_ER_AAC_LD) {
1393 av_log(ac->avctx, AV_LOG_ERROR,
1394 "LTP in ER AAC LD not yet implemented.\n");
1395 ret_fail = AVERROR_PATCHWELCOME;
1398 if ((ics->ltp.present = get_bits(gb, 1)))
1399 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1404 if (ics->max_sfb > ics->num_swb) {
1405 av_log(ac->avctx, AV_LOG_ERROR,
1406 "Number of scalefactor bands in group (%d) "
1407 "exceeds limit (%d).\n",
1408 ics->max_sfb, ics->num_swb);
1419 * Decode band types (section_data payload); reference: table 4.46.
1421 * @param band_type array of the used band type
1422 * @param band_type_run_end array of the last scalefactor band of a band type run
1424 * @return Returns error status. 0 - OK, !0 - error
1426 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1427 int band_type_run_end[120], GetBitContext *gb,
1428 IndividualChannelStream *ics)
1431 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1432 for (g = 0; g < ics->num_window_groups; g++) {
1434 while (k < ics->max_sfb) {
1435 uint8_t sect_end = k;
1437 int sect_band_type = get_bits(gb, 4);
1438 if (sect_band_type == 12) {
1439 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1440 return AVERROR_INVALIDDATA;
1443 sect_len_incr = get_bits(gb, bits);
1444 sect_end += sect_len_incr;
1445 if (get_bits_left(gb) < 0) {
1446 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1447 return AVERROR_INVALIDDATA;
1449 if (sect_end > ics->max_sfb) {
1450 av_log(ac->avctx, AV_LOG_ERROR,
1451 "Number of bands (%d) exceeds limit (%d).\n",
1452 sect_end, ics->max_sfb);
1453 return AVERROR_INVALIDDATA;
1455 } while (sect_len_incr == (1 << bits) - 1);
1456 for (; k < sect_end; k++) {
1457 band_type [idx] = sect_band_type;
1458 band_type_run_end[idx++] = sect_end;
1466 * Decode scalefactors; reference: table 4.47.
1468 * @param global_gain first scalefactor value as scalefactors are differentially coded
1469 * @param band_type array of the used band type
1470 * @param band_type_run_end array of the last scalefactor band of a band type run
1471 * @param sf array of scalefactors or intensity stereo positions
1473 * @return Returns error status. 0 - OK, !0 - error
1475 static int decode_scalefactors(AACContext *ac, INTFLOAT sf[120], GetBitContext *gb,
1476 unsigned int global_gain,
1477 IndividualChannelStream *ics,
1478 enum BandType band_type[120],
1479 int band_type_run_end[120])
1482 int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
1485 for (g = 0; g < ics->num_window_groups; g++) {
1486 for (i = 0; i < ics->max_sfb;) {
1487 int run_end = band_type_run_end[idx];
1488 if (band_type[idx] == ZERO_BT) {
1489 for (; i < run_end; i++, idx++)
1491 } else if ((band_type[idx] == INTENSITY_BT) ||
1492 (band_type[idx] == INTENSITY_BT2)) {
1493 for (; i < run_end; i++, idx++) {
1494 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1495 clipped_offset = av_clip(offset[2], -155, 100);
1496 if (offset[2] != clipped_offset) {
1497 avpriv_request_sample(ac->avctx,
1498 "If you heard an audible artifact, there may be a bug in the decoder. "
1499 "Clipped intensity stereo position (%d -> %d)",
1500 offset[2], clipped_offset);
1503 sf[idx] = 100 - clipped_offset;
1505 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1506 #endif /* USE_FIXED */
1508 } else if (band_type[idx] == NOISE_BT) {
1509 for (; i < run_end; i++, idx++) {
1510 if (noise_flag-- > 0)
1511 offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
1513 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1514 clipped_offset = av_clip(offset[1], -100, 155);
1515 if (offset[1] != clipped_offset) {
1516 avpriv_request_sample(ac->avctx,
1517 "If you heard an audible artifact, there may be a bug in the decoder. "
1518 "Clipped noise gain (%d -> %d)",
1519 offset[1], clipped_offset);
1522 sf[idx] = -(100 + clipped_offset);
1524 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1525 #endif /* USE_FIXED */
1528 for (; i < run_end; i++, idx++) {
1529 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1530 if (offset[0] > 255U) {
1531 av_log(ac->avctx, AV_LOG_ERROR,
1532 "Scalefactor (%d) out of range.\n", offset[0]);
1533 return AVERROR_INVALIDDATA;
1536 sf[idx] = -offset[0];
1538 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1539 #endif /* USE_FIXED */
1548 * Decode pulse data; reference: table 4.7.
1550 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1551 const uint16_t *swb_offset, int num_swb)
1554 pulse->num_pulse = get_bits(gb, 2) + 1;
1555 pulse_swb = get_bits(gb, 6);
1556 if (pulse_swb >= num_swb)
1558 pulse->pos[0] = swb_offset[pulse_swb];
1559 pulse->pos[0] += get_bits(gb, 5);
1560 if (pulse->pos[0] >= swb_offset[num_swb])
1562 pulse->amp[0] = get_bits(gb, 4);
1563 for (i = 1; i < pulse->num_pulse; i++) {
1564 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1565 if (pulse->pos[i] >= swb_offset[num_swb])
1567 pulse->amp[i] = get_bits(gb, 4);
1573 * Decode Temporal Noise Shaping data; reference: table 4.48.
1575 * @return Returns error status. 0 - OK, !0 - error
1577 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1578 GetBitContext *gb, const IndividualChannelStream *ics)
1580 int w, filt, i, coef_len, coef_res, coef_compress;
1581 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1582 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1583 for (w = 0; w < ics->num_windows; w++) {
1584 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1585 coef_res = get_bits1(gb);
1587 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1589 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1591 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1592 av_log(ac->avctx, AV_LOG_ERROR,
1593 "TNS filter order %d is greater than maximum %d.\n",
1594 tns->order[w][filt], tns_max_order);
1595 tns->order[w][filt] = 0;
1596 return AVERROR_INVALIDDATA;
1598 if (tns->order[w][filt]) {
1599 tns->direction[w][filt] = get_bits1(gb);
1600 coef_compress = get_bits1(gb);
1601 coef_len = coef_res + 3 - coef_compress;
1602 tmp2_idx = 2 * coef_compress + coef_res;
1604 for (i = 0; i < tns->order[w][filt]; i++)
1605 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1614 * Decode Mid/Side data; reference: table 4.54.
1616 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1617 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1618 * [3] reserved for scalable AAC
1620 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1624 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1625 if (ms_present == 1) {
1626 for (idx = 0; idx < max_idx; idx++)
1627 cpe->ms_mask[idx] = get_bits1(gb);
1628 } else if (ms_present == 2) {
1629 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1634 * Decode spectral data; reference: table 4.50.
1635 * Dequantize and scale spectral data; reference: 4.6.3.3.
1637 * @param coef array of dequantized, scaled spectral data
1638 * @param sf array of scalefactors or intensity stereo positions
1639 * @param pulse_present set if pulses are present
1640 * @param pulse pointer to pulse data struct
1641 * @param band_type array of the used band type
1643 * @return Returns error status. 0 - OK, !0 - error
1645 static int decode_spectrum_and_dequant(AACContext *ac, INTFLOAT coef[1024],
1646 GetBitContext *gb, const INTFLOAT sf[120],
1647 int pulse_present, const Pulse *pulse,
1648 const IndividualChannelStream *ics,
1649 enum BandType band_type[120])
1651 int i, k, g, idx = 0;
1652 const int c = 1024 / ics->num_windows;
1653 const uint16_t *offsets = ics->swb_offset;
1654 INTFLOAT *coef_base = coef;
1656 for (g = 0; g < ics->num_windows; g++)
1657 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1658 sizeof(INTFLOAT) * (c - offsets[ics->max_sfb]));
1660 for (g = 0; g < ics->num_window_groups; g++) {
1661 unsigned g_len = ics->group_len[g];
1663 for (i = 0; i < ics->max_sfb; i++, idx++) {
1664 const unsigned cbt_m1 = band_type[idx] - 1;
1665 INTFLOAT *cfo = coef + offsets[i];
1666 int off_len = offsets[i + 1] - offsets[i];
1669 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1670 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1671 memset(cfo, 0, off_len * sizeof(*cfo));
1673 } else if (cbt_m1 == NOISE_BT - 1) {
1674 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1677 #endif /* !USE_FIXED */
1678 INTFLOAT band_energy;
1680 for (k = 0; k < off_len; k++) {
1681 ac->random_state = lcg_random(ac->random_state);
1683 cfo[k] = ac->random_state >> 3;
1685 cfo[k] = ac->random_state;
1686 #endif /* USE_FIXED */
1690 band_energy = ac->fdsp->scalarproduct_fixed(cfo, cfo, off_len);
1691 band_energy = fixed_sqrt(band_energy, 31);
1692 noise_scale(cfo, sf[idx], band_energy, off_len);
1694 band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
1695 scale = sf[idx] / sqrtf(band_energy);
1696 ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
1697 #endif /* USE_FIXED */
1701 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1702 #endif /* !USE_FIXED */
1703 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1704 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1705 OPEN_READER(re, gb);
1707 switch (cbt_m1 >> 1) {
1709 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1717 UPDATE_CACHE(re, gb);
1718 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1719 cb_idx = cb_vector_idx[code];
1721 cf = DEC_SQUAD(cf, cb_idx);
1723 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1724 #endif /* USE_FIXED */
1730 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1740 UPDATE_CACHE(re, gb);
1741 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1742 cb_idx = cb_vector_idx[code];
1743 nnz = cb_idx >> 8 & 15;
1744 bits = nnz ? GET_CACHE(re, gb) : 0;
1745 LAST_SKIP_BITS(re, gb, nnz);
1747 cf = DEC_UQUAD(cf, cb_idx, bits);
1749 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1750 #endif /* USE_FIXED */
1756 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1764 UPDATE_CACHE(re, gb);
1765 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1766 cb_idx = cb_vector_idx[code];
1768 cf = DEC_SPAIR(cf, cb_idx);
1770 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1771 #endif /* USE_FIXED */
1778 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1788 UPDATE_CACHE(re, gb);
1789 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1790 cb_idx = cb_vector_idx[code];
1791 nnz = cb_idx >> 8 & 15;
1792 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1793 LAST_SKIP_BITS(re, gb, nnz);
1795 cf = DEC_UPAIR(cf, cb_idx, sign);
1797 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1798 #endif /* USE_FIXED */
1804 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1810 uint32_t *icf = (uint32_t *) cf;
1811 #endif /* USE_FIXED */
1821 UPDATE_CACHE(re, gb);
1822 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1830 cb_idx = cb_vector_idx[code];
1833 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1834 LAST_SKIP_BITS(re, gb, nnz);
1836 for (j = 0; j < 2; j++) {
1840 /* The total length of escape_sequence must be < 22 bits according
1841 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1842 UPDATE_CACHE(re, gb);
1843 b = GET_CACHE(re, gb);
1844 b = 31 - av_log2(~b);
1847 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1848 return AVERROR_INVALIDDATA;
1851 SKIP_BITS(re, gb, b + 1);
1853 n = (1 << b) + SHOW_UBITS(re, gb, b);
1854 LAST_SKIP_BITS(re, gb, b);
1861 *icf++ = ff_cbrt_tab[n] | (bits & 1U<<31);
1862 #endif /* USE_FIXED */
1871 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1872 *icf++ = (bits & 1U<<31) | v;
1873 #endif /* USE_FIXED */
1880 ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1881 #endif /* !USE_FIXED */
1885 CLOSE_READER(re, gb);
1891 if (pulse_present) {
1893 for (i = 0; i < pulse->num_pulse; i++) {
1894 INTFLOAT co = coef_base[ pulse->pos[i] ];
1895 while (offsets[idx + 1] <= pulse->pos[i])
1897 if (band_type[idx] != NOISE_BT && sf[idx]) {
1898 INTFLOAT ico = -pulse->amp[i];
1901 ico = co + (co > 0 ? -ico : ico);
1903 coef_base[ pulse->pos[i] ] = ico;
1907 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1909 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1910 #endif /* USE_FIXED */
1917 for (g = 0; g < ics->num_window_groups; g++) {
1918 unsigned g_len = ics->group_len[g];
1920 for (i = 0; i < ics->max_sfb; i++, idx++) {
1921 const unsigned cbt_m1 = band_type[idx] - 1;
1922 int *cfo = coef + offsets[i];
1923 int off_len = offsets[i + 1] - offsets[i];
1926 if (cbt_m1 < NOISE_BT - 1) {
1927 for (group = 0; group < (int)g_len; group++, cfo+=128) {
1928 ac->vector_pow43(cfo, off_len);
1929 ac->subband_scale(cfo, cfo, sf[idx], 34, off_len);
1935 #endif /* USE_FIXED */
1940 * Apply AAC-Main style frequency domain prediction.
1942 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1946 if (!sce->ics.predictor_initialized) {
1947 reset_all_predictors(sce->predictor_state);
1948 sce->ics.predictor_initialized = 1;
1951 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1953 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1955 for (k = sce->ics.swb_offset[sfb];
1956 k < sce->ics.swb_offset[sfb + 1];
1958 predict(&sce->predictor_state[k], &sce->coeffs[k],
1959 sce->ics.predictor_present &&
1960 sce->ics.prediction_used[sfb]);
1963 if (sce->ics.predictor_reset_group)
1964 reset_predictor_group(sce->predictor_state,
1965 sce->ics.predictor_reset_group);
1967 reset_all_predictors(sce->predictor_state);
1971 * Decode an individual_channel_stream payload; reference: table 4.44.
1973 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1974 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1976 * @return Returns error status. 0 - OK, !0 - error
1978 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1979 GetBitContext *gb, int common_window, int scale_flag)
1982 TemporalNoiseShaping *tns = &sce->tns;
1983 IndividualChannelStream *ics = &sce->ics;
1984 INTFLOAT *out = sce->coeffs;
1985 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
1988 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1989 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1990 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1991 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1992 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1994 /* This assignment is to silence a GCC warning about the variable being used
1995 * uninitialized when in fact it always is.
1997 pulse.num_pulse = 0;
1999 global_gain = get_bits(gb, 8);
2001 if (!common_window && !scale_flag) {
2002 if (decode_ics_info(ac, ics, gb) < 0)
2003 return AVERROR_INVALIDDATA;
2006 if ((ret = decode_band_types(ac, sce->band_type,
2007 sce->band_type_run_end, gb, ics)) < 0)
2009 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
2010 sce->band_type, sce->band_type_run_end)) < 0)
2015 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
2016 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2017 av_log(ac->avctx, AV_LOG_ERROR,
2018 "Pulse tool not allowed in eight short sequence.\n");
2019 return AVERROR_INVALIDDATA;
2021 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
2022 av_log(ac->avctx, AV_LOG_ERROR,
2023 "Pulse data corrupt or invalid.\n");
2024 return AVERROR_INVALIDDATA;
2027 tns->present = get_bits1(gb);
2028 if (tns->present && !er_syntax)
2029 if (decode_tns(ac, tns, gb, ics) < 0)
2030 return AVERROR_INVALIDDATA;
2031 if (!eld_syntax && get_bits1(gb)) {
2032 avpriv_request_sample(ac->avctx, "SSR");
2033 return AVERROR_PATCHWELCOME;
2035 // I see no textual basis in the spec for this occurring after SSR gain
2036 // control, but this is what both reference and real implmentations do
2037 if (tns->present && er_syntax)
2038 if (decode_tns(ac, tns, gb, ics) < 0)
2039 return AVERROR_INVALIDDATA;
2042 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
2043 &pulse, ics, sce->band_type) < 0)
2044 return AVERROR_INVALIDDATA;
2046 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
2047 apply_prediction(ac, sce);
2053 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
2055 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
2057 const IndividualChannelStream *ics = &cpe->ch[0].ics;
2058 INTFLOAT *ch0 = cpe->ch[0].coeffs;
2059 INTFLOAT *ch1 = cpe->ch[1].coeffs;
2060 int g, i, group, idx = 0;
2061 const uint16_t *offsets = ics->swb_offset;
2062 for (g = 0; g < ics->num_window_groups; g++) {
2063 for (i = 0; i < ics->max_sfb; i++, idx++) {
2064 if (cpe->ms_mask[idx] &&
2065 cpe->ch[0].band_type[idx] < NOISE_BT &&
2066 cpe->ch[1].band_type[idx] < NOISE_BT) {
2068 for (group = 0; group < ics->group_len[g]; group++) {
2069 ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
2070 ch1 + group * 128 + offsets[i],
2071 offsets[i+1] - offsets[i]);
2073 for (group = 0; group < ics->group_len[g]; group++) {
2074 ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
2075 ch1 + group * 128 + offsets[i],
2076 offsets[i+1] - offsets[i]);
2077 #endif /* USE_FIXED */
2081 ch0 += ics->group_len[g] * 128;
2082 ch1 += ics->group_len[g] * 128;
2087 * intensity stereo decoding; reference: 4.6.8.2.3
2089 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
2090 * [1] mask is decoded from bitstream; [2] mask is all 1s;
2091 * [3] reserved for scalable AAC
2093 static void apply_intensity_stereo(AACContext *ac,
2094 ChannelElement *cpe, int ms_present)
2096 const IndividualChannelStream *ics = &cpe->ch[1].ics;
2097 SingleChannelElement *sce1 = &cpe->ch[1];
2098 INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2099 const uint16_t *offsets = ics->swb_offset;
2100 int g, group, i, idx = 0;
2103 for (g = 0; g < ics->num_window_groups; g++) {
2104 for (i = 0; i < ics->max_sfb;) {
2105 if (sce1->band_type[idx] == INTENSITY_BT ||
2106 sce1->band_type[idx] == INTENSITY_BT2) {
2107 const int bt_run_end = sce1->band_type_run_end[idx];
2108 for (; i < bt_run_end; i++, idx++) {
2109 c = -1 + 2 * (sce1->band_type[idx] - 14);
2111 c *= 1 - 2 * cpe->ms_mask[idx];
2112 scale = c * sce1->sf[idx];
2113 for (group = 0; group < ics->group_len[g]; group++)
2115 ac->subband_scale(coef1 + group * 128 + offsets[i],
2116 coef0 + group * 128 + offsets[i],
2119 offsets[i + 1] - offsets[i]);
2121 ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2122 coef0 + group * 128 + offsets[i],
2124 offsets[i + 1] - offsets[i]);
2125 #endif /* USE_FIXED */
2128 int bt_run_end = sce1->band_type_run_end[idx];
2129 idx += bt_run_end - i;
2133 coef0 += ics->group_len[g] * 128;
2134 coef1 += ics->group_len[g] * 128;
2139 * Decode a channel_pair_element; reference: table 4.4.
2141 * @return Returns error status. 0 - OK, !0 - error
2143 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2145 int i, ret, common_window, ms_present = 0;
2146 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2148 common_window = eld_syntax || get_bits1(gb);
2149 if (common_window) {
2150 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2151 return AVERROR_INVALIDDATA;
2152 i = cpe->ch[1].ics.use_kb_window[0];
2153 cpe->ch[1].ics = cpe->ch[0].ics;
2154 cpe->ch[1].ics.use_kb_window[1] = i;
2155 if (cpe->ch[1].ics.predictor_present &&
2156 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2157 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2158 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2159 ms_present = get_bits(gb, 2);
2160 if (ms_present == 3) {
2161 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2162 return AVERROR_INVALIDDATA;
2163 } else if (ms_present)
2164 decode_mid_side_stereo(cpe, gb, ms_present);
2166 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2168 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2171 if (common_window) {
2173 apply_mid_side_stereo(ac, cpe);
2174 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2175 apply_prediction(ac, &cpe->ch[0]);
2176 apply_prediction(ac, &cpe->ch[1]);
2180 apply_intensity_stereo(ac, cpe, ms_present);
2184 static const float cce_scale[] = {
2185 1.09050773266525765921, //2^(1/8)
2186 1.18920711500272106672, //2^(1/4)
2192 * Decode coupling_channel_element; reference: table 4.8.
2194 * @return Returns error status. 0 - OK, !0 - error
2196 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2202 SingleChannelElement *sce = &che->ch[0];
2203 ChannelCoupling *coup = &che->coup;
2205 coup->coupling_point = 2 * get_bits1(gb);
2206 coup->num_coupled = get_bits(gb, 3);
2207 for (c = 0; c <= coup->num_coupled; c++) {
2209 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2210 coup->id_select[c] = get_bits(gb, 4);
2211 if (coup->type[c] == TYPE_CPE) {
2212 coup->ch_select[c] = get_bits(gb, 2);
2213 if (coup->ch_select[c] == 3)
2216 coup->ch_select[c] = 2;
2218 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2220 sign = get_bits(gb, 1);
2222 scale = get_bits(gb, 2);
2224 scale = cce_scale[get_bits(gb, 2)];
2227 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2230 for (c = 0; c < num_gain; c++) {
2234 INTFLOAT gain_cache = FIXR10(1.);
2236 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2237 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2238 gain_cache = GET_GAIN(scale, gain);
2240 if ((abs(gain_cache)-1024) >> 3 > 30)
2241 return AVERROR(ERANGE);
2244 if (coup->coupling_point == AFTER_IMDCT) {
2245 coup->gain[c][0] = gain_cache;
2247 for (g = 0; g < sce->ics.num_window_groups; g++) {
2248 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2249 if (sce->band_type[idx] != ZERO_BT) {
2251 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2259 gain_cache = GET_GAIN(scale, t) * s;
2261 if ((abs(gain_cache)-1024) >> 3 > 30)
2262 return AVERROR(ERANGE);
2266 coup->gain[c][idx] = gain_cache;
2276 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2278 * @return Returns number of bytes consumed.
2280 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2284 int num_excl_chan = 0;
2287 for (i = 0; i < 7; i++)
2288 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2289 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2291 return num_excl_chan / 7;
2295 * Decode dynamic range information; reference: table 4.52.
2297 * @return Returns number of bytes consumed.
2299 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2303 int drc_num_bands = 1;
2306 /* pce_tag_present? */
2307 if (get_bits1(gb)) {
2308 che_drc->pce_instance_tag = get_bits(gb, 4);
2309 skip_bits(gb, 4); // tag_reserved_bits
2313 /* excluded_chns_present? */
2314 if (get_bits1(gb)) {
2315 n += decode_drc_channel_exclusions(che_drc, gb);
2318 /* drc_bands_present? */
2319 if (get_bits1(gb)) {
2320 che_drc->band_incr = get_bits(gb, 4);
2321 che_drc->interpolation_scheme = get_bits(gb, 4);
2323 drc_num_bands += che_drc->band_incr;
2324 for (i = 0; i < drc_num_bands; i++) {
2325 che_drc->band_top[i] = get_bits(gb, 8);
2330 /* prog_ref_level_present? */
2331 if (get_bits1(gb)) {
2332 che_drc->prog_ref_level = get_bits(gb, 7);
2333 skip_bits1(gb); // prog_ref_level_reserved_bits
2337 for (i = 0; i < drc_num_bands; i++) {
2338 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2339 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2346 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2348 int i, major, minor;
2353 get_bits(gb, 13); len -= 13;
2355 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2356 buf[i] = get_bits(gb, 8);
2359 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2360 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2362 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2363 ac->avctx->internal->skip_samples = 1024;
2367 skip_bits_long(gb, len);
2373 * Decode extension data (incomplete); reference: table 4.51.
2375 * @param cnt length of TYPE_FIL syntactic element in bytes
2377 * @return Returns number of bytes consumed
2379 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2380 ChannelElement *che, enum RawDataBlockType elem_type)
2384 int type = get_bits(gb, 4);
2386 if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2387 av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2389 switch (type) { // extension type
2390 case EXT_SBR_DATA_CRC:
2394 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2396 } else if (ac->oc[1].m4ac.frame_length_short) {
2397 if (!ac->warned_960_sbr)
2398 avpriv_report_missing_feature(ac->avctx,
2399 "SBR with 960 frame length");
2400 ac->warned_960_sbr = 1;
2401 skip_bits_long(gb, 8 * cnt - 4);
2403 } else if (!ac->oc[1].m4ac.sbr) {
2404 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2405 skip_bits_long(gb, 8 * cnt - 4);
2407 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2408 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2409 skip_bits_long(gb, 8 * cnt - 4);
2411 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2412 ac->oc[1].m4ac.sbr = 1;
2413 ac->oc[1].m4ac.ps = 1;
2414 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2415 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2416 ac->oc[1].status, 1);
2418 ac->oc[1].m4ac.sbr = 1;
2419 ac->avctx->profile = FF_PROFILE_AAC_HE;
2421 res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2423 case EXT_DYNAMIC_RANGE:
2424 res = decode_dynamic_range(&ac->che_drc, gb);
2427 decode_fill(ac, gb, 8 * cnt - 4);
2430 case EXT_DATA_ELEMENT:
2432 skip_bits_long(gb, 8 * cnt - 4);
2439 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2441 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2442 * @param coef spectral coefficients
2444 static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns,
2445 IndividualChannelStream *ics, int decode)
2447 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2449 int bottom, top, order, start, end, size, inc;
2450 INTFLOAT lpc[TNS_MAX_ORDER];
2451 INTFLOAT tmp[TNS_MAX_ORDER+1];
2452 UINTFLOAT *coef = coef_param;
2454 for (w = 0; w < ics->num_windows; w++) {
2455 bottom = ics->num_swb;
2456 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2458 bottom = FFMAX(0, top - tns->length[w][filt]);
2459 order = tns->order[w][filt];
2464 AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
2466 start = ics->swb_offset[FFMIN(bottom, mmm)];
2467 end = ics->swb_offset[FFMIN( top, mmm)];
2468 if ((size = end - start) <= 0)
2470 if (tns->direction[w][filt]) {
2480 for (m = 0; m < size; m++, start += inc)
2481 for (i = 1; i <= FFMIN(m, order); i++)
2482 coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]);
2485 for (m = 0; m < size; m++, start += inc) {
2486 tmp[0] = coef[start];
2487 for (i = 1; i <= FFMIN(m, order); i++)
2488 coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
2489 for (i = order; i > 0; i--)
2490 tmp[i] = tmp[i - 1];
2498 * Apply windowing and MDCT to obtain the spectral
2499 * coefficient from the predicted sample by LTP.
2501 static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
2502 INTFLOAT *in, IndividualChannelStream *ics)
2504 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2505 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2506 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2507 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2509 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2510 ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
2512 memset(in, 0, 448 * sizeof(*in));
2513 ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
2515 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2516 ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2518 ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2519 memset(in + 1024 + 576, 0, 448 * sizeof(*in));
2521 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2525 * Apply the long term prediction
2527 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2529 const LongTermPrediction *ltp = &sce->ics.ltp;
2530 const uint16_t *offsets = sce->ics.swb_offset;
2533 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2534 INTFLOAT *predTime = sce->ret;
2535 INTFLOAT *predFreq = ac->buf_mdct;
2536 int16_t num_samples = 2048;
2538 if (ltp->lag < 1024)
2539 num_samples = ltp->lag + 1024;
2540 for (i = 0; i < num_samples; i++)
2541 predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
2542 memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
2544 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2546 if (sce->tns.present)
2547 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2549 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2551 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2552 sce->coeffs[i] += predFreq[i];
2557 * Update the LTP buffer for next frame
2559 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2561 IndividualChannelStream *ics = &sce->ics;
2562 INTFLOAT *saved = sce->saved;
2563 INTFLOAT *saved_ltp = sce->coeffs;
2564 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2565 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2568 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2569 memcpy(saved_ltp, saved, 512 * sizeof(*saved_ltp));
2570 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2571 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2573 for (i = 0; i < 64; i++)
2574 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2575 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2576 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
2577 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2578 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2580 for (i = 0; i < 64; i++)
2581 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2582 } else { // LONG_STOP or ONLY_LONG
2583 ac->fdsp->vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2585 for (i = 0; i < 512; i++)
2586 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
2589 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2590 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2591 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2595 * Conduct IMDCT and windowing.
2597 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2599 IndividualChannelStream *ics = &sce->ics;
2600 INTFLOAT *in = sce->coeffs;
2601 INTFLOAT *out = sce->ret;
2602 INTFLOAT *saved = sce->saved;
2603 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2604 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2605 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2606 INTFLOAT *buf = ac->buf_mdct;
2607 INTFLOAT *temp = ac->temp;
2611 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2612 for (i = 0; i < 1024; i += 128)
2613 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2615 ac->mdct.imdct_half(&ac->mdct, buf, in);
2617 for (i=0; i<1024; i++)
2618 buf[i] = (buf[i] + 4) >> 3;
2619 #endif /* USE_FIXED */
2622 /* window overlapping
2623 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2624 * and long to short transitions are considered to be short to short
2625 * transitions. This leaves just two cases (long to long and short to short)
2626 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2628 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2629 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2630 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2632 memcpy( out, saved, 448 * sizeof(*out));
2634 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2635 ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2636 ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2637 ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2638 ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2639 ac->fdsp->vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2640 memcpy( out + 448 + 4*128, temp, 64 * sizeof(*out));
2642 ac->fdsp->vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2643 memcpy( out + 576, buf + 64, 448 * sizeof(*out));
2648 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2649 memcpy( saved, temp + 64, 64 * sizeof(*saved));
2650 ac->fdsp->vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2651 ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2652 ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2653 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2654 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2655 memcpy( saved, buf + 512, 448 * sizeof(*saved));
2656 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2657 } else { // LONG_STOP or ONLY_LONG
2658 memcpy( saved, buf + 512, 512 * sizeof(*saved));
2663 * Conduct IMDCT and windowing.
2665 static void imdct_and_windowing_960(AACContext *ac, SingleChannelElement *sce)
2668 IndividualChannelStream *ics = &sce->ics;
2669 INTFLOAT *in = sce->coeffs;
2670 INTFLOAT *out = sce->ret;
2671 INTFLOAT *saved = sce->saved;
2672 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2673 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_960) : AAC_RENAME(ff_sine_960);
2674 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2675 INTFLOAT *buf = ac->buf_mdct;
2676 INTFLOAT *temp = ac->temp;
2680 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2681 for (i = 0; i < 8; i++)
2682 ac->mdct120->imdct_half(ac->mdct120, buf + i * 120, in + i * 128, 1);
2684 ac->mdct960->imdct_half(ac->mdct960, buf, in, 1);
2687 /* window overlapping
2688 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2689 * and long to short transitions are considered to be short to short
2690 * transitions. This leaves just two cases (long to long and short to short)
2691 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2694 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2695 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2696 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 480);
2698 memcpy( out, saved, 420 * sizeof(*out));
2700 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2701 ac->fdsp->vector_fmul_window(out + 420 + 0*120, saved + 420, buf + 0*120, swindow_prev, 60);
2702 ac->fdsp->vector_fmul_window(out + 420 + 1*120, buf + 0*120 + 60, buf + 1*120, swindow, 60);
2703 ac->fdsp->vector_fmul_window(out + 420 + 2*120, buf + 1*120 + 60, buf + 2*120, swindow, 60);
2704 ac->fdsp->vector_fmul_window(out + 420 + 3*120, buf + 2*120 + 60, buf + 3*120, swindow, 60);
2705 ac->fdsp->vector_fmul_window(temp, buf + 3*120 + 60, buf + 4*120, swindow, 60);
2706 memcpy( out + 420 + 4*120, temp, 60 * sizeof(*out));
2708 ac->fdsp->vector_fmul_window(out + 420, saved + 420, buf, swindow_prev, 60);
2709 memcpy( out + 540, buf + 60, 420 * sizeof(*out));
2714 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2715 memcpy( saved, temp + 60, 60 * sizeof(*saved));
2716 ac->fdsp->vector_fmul_window(saved + 60, buf + 4*120 + 60, buf + 5*120, swindow, 60);
2717 ac->fdsp->vector_fmul_window(saved + 180, buf + 5*120 + 60, buf + 6*120, swindow, 60);
2718 ac->fdsp->vector_fmul_window(saved + 300, buf + 6*120 + 60, buf + 7*120, swindow, 60);
2719 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2720 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2721 memcpy( saved, buf + 480, 420 * sizeof(*saved));
2722 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2723 } else { // LONG_STOP or ONLY_LONG
2724 memcpy( saved, buf + 480, 480 * sizeof(*saved));
2728 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2730 IndividualChannelStream *ics = &sce->ics;
2731 INTFLOAT *in = sce->coeffs;
2732 INTFLOAT *out = sce->ret;
2733 INTFLOAT *saved = sce->saved;
2734 INTFLOAT *buf = ac->buf_mdct;
2737 #endif /* USE_FIXED */
2740 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2743 for (i = 0; i < 1024; i++)
2744 buf[i] = (buf[i] + 2) >> 2;
2745 #endif /* USE_FIXED */
2747 // window overlapping
2748 if (ics->use_kb_window[1]) {
2749 // AAC LD uses a low overlap sine window instead of a KBD window
2750 memcpy(out, saved, 192 * sizeof(*out));
2751 ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME(ff_sine_128), 64);
2752 memcpy( out + 320, buf + 64, 192 * sizeof(*out));
2754 ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME(ff_sine_512), 256);
2758 memcpy(saved, buf + 256, 256 * sizeof(*saved));
2761 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2763 INTFLOAT *in = sce->coeffs;
2764 INTFLOAT *out = sce->ret;
2765 INTFLOAT *saved = sce->saved;
2766 INTFLOAT *buf = ac->buf_mdct;
2768 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2769 const int n2 = n >> 1;
2770 const int n4 = n >> 2;
2771 const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
2772 AAC_RENAME(ff_aac_eld_window_512);
2774 // Inverse transform, mapped to the conventional IMDCT by
2775 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2776 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2777 // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2778 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2779 for (i = 0; i < n2; i+=2) {
2781 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2782 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2786 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1);
2789 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2792 for (i = 0; i < 1024; i++)
2793 buf[i] = (buf[i] + 1) >> 1;
2794 #endif /* USE_FIXED */
2796 for (i = 0; i < n; i+=2) {
2799 // Like with the regular IMDCT at this point we still have the middle half
2800 // of a transform but with even symmetry on the left and odd symmetry on
2803 // window overlapping
2804 // The spec says to use samples [0..511] but the reference decoder uses
2805 // samples [128..639].
2806 for (i = n4; i < n2; i ++) {
2807 out[i - n4] = AAC_MUL31( buf[ n2 - 1 - i] , window[i - n4]) +
2808 AAC_MUL31( saved[ i + n2] , window[i + n - n4]) +
2809 AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
2810 AAC_MUL31(-saved[ 2*n + n2 + i] , window[i + 3*n - n4]);
2812 for (i = 0; i < n2; i ++) {
2813 out[n4 + i] = AAC_MUL31( buf[ i] , window[i + n2 - n4]) +
2814 AAC_MUL31(-saved[ n - 1 - i] , window[i + n2 + n - n4]) +
2815 AAC_MUL31(-saved[ n + i] , window[i + n2 + 2*n - n4]) +
2816 AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
2818 for (i = 0; i < n4; i ++) {
2819 out[n2 + n4 + i] = AAC_MUL31( buf[ i + n2] , window[i + n - n4]) +
2820 AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
2821 AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
2825 memmove(saved + n, saved, 2 * n * sizeof(*saved));
2826 memcpy( saved, buf, n * sizeof(*saved));
2830 * channel coupling transformation interface
2832 * @param apply_coupling_method pointer to (in)dependent coupling function
2834 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2835 enum RawDataBlockType type, int elem_id,
2836 enum CouplingPoint coupling_point,
2837 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2841 for (i = 0; i < MAX_ELEM_ID; i++) {
2842 ChannelElement *cce = ac->che[TYPE_CCE][i];
2845 if (cce && cce->coup.coupling_point == coupling_point) {
2846 ChannelCoupling *coup = &cce->coup;
2848 for (c = 0; c <= coup->num_coupled; c++) {
2849 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2850 if (coup->ch_select[c] != 1) {
2851 apply_coupling_method(ac, &cc->ch[0], cce, index);
2852 if (coup->ch_select[c] != 0)
2855 if (coup->ch_select[c] != 2)
2856 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2858 index += 1 + (coup->ch_select[c] == 3);
2865 * Convert spectral data to samples, applying all supported tools as appropriate.
2867 static void spectral_to_sample(AACContext *ac, int samples)
2870 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2871 switch (ac->oc[1].m4ac.object_type) {
2873 imdct_and_window = imdct_and_windowing_ld;
2875 case AOT_ER_AAC_ELD:
2876 imdct_and_window = imdct_and_windowing_eld;
2879 if (ac->oc[1].m4ac.frame_length_short)
2880 imdct_and_window = imdct_and_windowing_960;
2882 imdct_and_window = ac->imdct_and_windowing;
2884 for (type = 3; type >= 0; type--) {
2885 for (i = 0; i < MAX_ELEM_ID; i++) {
2886 ChannelElement *che = ac->che[type][i];
2887 if (che && che->present) {
2888 if (type <= TYPE_CPE)
2889 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
2890 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2891 if (che->ch[0].ics.predictor_present) {
2892 if (che->ch[0].ics.ltp.present)
2893 ac->apply_ltp(ac, &che->ch[0]);
2894 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2895 ac->apply_ltp(ac, &che->ch[1]);
2898 if (che->ch[0].tns.present)
2899 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2900 if (che->ch[1].tns.present)
2901 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2902 if (type <= TYPE_CPE)
2903 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
2904 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2905 imdct_and_window(ac, &che->ch[0]);
2906 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2907 ac->update_ltp(ac, &che->ch[0]);
2908 if (type == TYPE_CPE) {
2909 imdct_and_window(ac, &che->ch[1]);
2910 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2911 ac->update_ltp(ac, &che->ch[1]);
2913 if (ac->oc[1].m4ac.sbr > 0) {
2914 AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2917 if (type <= TYPE_CCE)
2918 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
2923 /* preparation for resampler */
2924 for(j = 0; j<samples; j++){
2925 che->ch[0].ret[j] = (int32_t)av_clip64((int64_t)che->ch[0].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
2926 if(type == TYPE_CPE)
2927 che->ch[1].ret[j] = (int32_t)av_clip64((int64_t)che->ch[1].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
2930 #endif /* USE_FIXED */
2933 av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
2939 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2942 AACADTSHeaderInfo hdr_info;
2943 uint8_t layout_map[MAX_ELEM_ID*4][3];
2944 int layout_map_tags, ret;
2946 size = avpriv_aac_parse_header(gb, &hdr_info);
2948 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2949 // This is 2 for "VLB " audio in NSV files.
2950 // See samples/nsv/vlb_audio.
2951 avpriv_report_missing_feature(ac->avctx,
2952 "More than one AAC RDB per ADTS frame");
2953 ac->warned_num_aac_frames = 1;
2955 push_output_configuration(ac);
2956 if (hdr_info.chan_config) {
2957 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2958 if ((ret = set_default_channel_config(ac->avctx,
2961 hdr_info.chan_config)) < 0)
2963 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2964 FFMAX(ac->oc[1].status,
2965 OC_TRIAL_FRAME), 0)) < 0)
2968 ac->oc[1].m4ac.chan_config = 0;
2970 * dual mono frames in Japanese DTV can have chan_config 0
2971 * WITHOUT specifying PCE.
2972 * thus, set dual mono as default.
2974 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
2975 layout_map_tags = 2;
2976 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
2977 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
2978 layout_map[0][1] = 0;
2979 layout_map[1][1] = 1;
2980 if (output_configure(ac, layout_map, layout_map_tags,
2985 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2986 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2987 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2988 ac->oc[1].m4ac.frame_length_short = 0;
2989 if (ac->oc[0].status != OC_LOCKED ||
2990 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2991 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2992 ac->oc[1].m4ac.sbr = -1;
2993 ac->oc[1].m4ac.ps = -1;
2995 if (!hdr_info.crc_absent)
3001 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
3002 int *got_frame_ptr, GetBitContext *gb)
3004 AACContext *ac = avctx->priv_data;
3005 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
3006 ChannelElement *che;
3008 int samples = m4ac->frame_length_short ? 960 : 1024;
3009 int chan_config = m4ac->chan_config;
3010 int aot = m4ac->object_type;
3012 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
3017 if ((err = frame_configure_elements(avctx)) < 0)
3020 // The FF_PROFILE_AAC_* defines are all object_type - 1
3021 // This may lead to an undefined profile being signaled
3022 ac->avctx->profile = aot - 1;
3024 ac->tags_mapped = 0;
3026 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
3027 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
3029 return AVERROR_INVALIDDATA;
3031 for (i = 0; i < tags_per_config[chan_config]; i++) {
3032 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
3033 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
3034 if (!(che=get_che(ac, elem_type, elem_id))) {
3035 av_log(ac->avctx, AV_LOG_ERROR,
3036 "channel element %d.%d is not allocated\n",
3037 elem_type, elem_id);
3038 return AVERROR_INVALIDDATA;
3041 if (aot != AOT_ER_AAC_ELD)
3043 switch (elem_type) {
3045 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3048 err = decode_cpe(ac, gb, che);
3051 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3058 spectral_to_sample(ac, samples);
3060 if (!ac->frame->data[0] && samples) {
3061 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3062 return AVERROR_INVALIDDATA;
3065 ac->frame->nb_samples = samples;
3066 ac->frame->sample_rate = avctx->sample_rate;
3069 skip_bits_long(gb, get_bits_left(gb));
3073 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
3074 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
3076 AACContext *ac = avctx->priv_data;
3077 ChannelElement *che = NULL, *che_prev = NULL;
3078 enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
3080 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
3081 int is_dmono, sce_count = 0;
3082 int payload_alignment;
3086 if (show_bits(gb, 12) == 0xfff) {
3087 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
3088 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
3091 if (ac->oc[1].m4ac.sampling_index > 12) {
3092 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
3093 err = AVERROR_INVALIDDATA;
3098 if ((err = frame_configure_elements(avctx)) < 0)
3101 // The FF_PROFILE_AAC_* defines are all object_type - 1
3102 // This may lead to an undefined profile being signaled
3103 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
3105 payload_alignment = get_bits_count(gb);
3106 ac->tags_mapped = 0;
3108 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
3109 elem_id = get_bits(gb, 4);
3111 if (avctx->debug & FF_DEBUG_STARTCODE)
3112 av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
3114 if (!avctx->channels && elem_type != TYPE_PCE) {
3115 err = AVERROR_INVALIDDATA;
3119 if (elem_type < TYPE_DSE) {
3120 if (!(che=get_che(ac, elem_type, elem_id))) {
3121 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
3122 elem_type, elem_id);
3123 err = AVERROR_INVALIDDATA;
3126 samples = ac->oc[1].m4ac.frame_length_short ? 960 : 1024;
3130 switch (elem_type) {
3133 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3139 err = decode_cpe(ac, gb, che);
3144 err = decode_cce(ac, gb, che);
3148 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3153 err = skip_data_stream_element(ac, gb);
3157 uint8_t layout_map[MAX_ELEM_ID*4][3];
3160 int pushed = push_output_configuration(ac);
3161 if (pce_found && !pushed) {
3162 err = AVERROR_INVALIDDATA;
3166 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
3173 av_log(avctx, AV_LOG_ERROR,
3174 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
3175 pop_output_configuration(ac);
3177 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
3179 ac->oc[1].m4ac.chan_config = 0;
3187 elem_id += get_bits(gb, 8) - 1;
3188 if (get_bits_left(gb) < 8 * elem_id) {
3189 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3190 err = AVERROR_INVALIDDATA;
3194 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
3195 err = 0; /* FIXME */
3199 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3203 if (elem_type < TYPE_DSE) {
3205 che_prev_type = elem_type;
3211 if (get_bits_left(gb) < 3) {
3212 av_log(avctx, AV_LOG_ERROR, overread_err);
3213 err = AVERROR_INVALIDDATA;
3218 if (!avctx->channels) {
3223 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3224 samples <<= multiplier;
3226 spectral_to_sample(ac, samples);
3228 if (ac->oc[1].status && audio_found) {
3229 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3230 avctx->frame_size = samples;
3231 ac->oc[1].status = OC_LOCKED;
3235 avctx->internal->skip_samples_multiplier = 2;
3237 if (!ac->frame->data[0] && samples) {
3238 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3239 err = AVERROR_INVALIDDATA;
3244 ac->frame->nb_samples = samples;
3245 ac->frame->sample_rate = avctx->sample_rate;
3247 av_frame_unref(ac->frame);
3248 *got_frame_ptr = !!samples;
3250 /* for dual-mono audio (SCE + SCE) */
3251 is_dmono = ac->dmono_mode && sce_count == 2 &&
3252 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
3254 if (ac->dmono_mode == 1)
3255 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3256 else if (ac->dmono_mode == 2)
3257 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3262 pop_output_configuration(ac);
3266 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3267 int *got_frame_ptr, AVPacket *avpkt)
3269 AACContext *ac = avctx->priv_data;
3270 const uint8_t *buf = avpkt->data;
3271 int buf_size = avpkt->size;
3276 int new_extradata_size;
3277 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3278 AV_PKT_DATA_NEW_EXTRADATA,
3279 &new_extradata_size);
3280 int jp_dualmono_size;
3281 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3282 AV_PKT_DATA_JP_DUALMONO,
3285 if (new_extradata && 0) {
3286 av_free(avctx->extradata);
3287 avctx->extradata = av_mallocz(new_extradata_size +
3288 AV_INPUT_BUFFER_PADDING_SIZE);
3289 if (!avctx->extradata)
3290 return AVERROR(ENOMEM);
3291 avctx->extradata_size = new_extradata_size;
3292 memcpy(avctx->extradata, new_extradata, new_extradata_size);
3293 push_output_configuration(ac);
3294 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3296 avctx->extradata_size*8LL, 1) < 0) {
3297 pop_output_configuration(ac);
3298 return AVERROR_INVALIDDATA;
3303 if (jp_dualmono && jp_dualmono_size > 0)
3304 ac->dmono_mode = 1 + *jp_dualmono;
3305 if (ac->force_dmono_mode >= 0)
3306 ac->dmono_mode = ac->force_dmono_mode;
3308 if (INT_MAX / 8 <= buf_size)
3309 return AVERROR_INVALIDDATA;
3311 if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)
3314 switch (ac->oc[1].m4ac.object_type) {
3316 case AOT_ER_AAC_LTP:
3318 case AOT_ER_AAC_ELD:
3319 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3322 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3327 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3328 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3329 if (buf[buf_offset])
3332 return buf_size > buf_offset ? buf_consumed : buf_size;
3335 static av_cold int aac_decode_close(AVCodecContext *avctx)
3337 AACContext *ac = avctx->priv_data;
3340 for (i = 0; i < MAX_ELEM_ID; i++) {
3341 for (type = 0; type < 4; type++) {
3342 if (ac->che[type][i])
3343 AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][i]->sbr);
3344 av_freep(&ac->che[type][i]);
3348 ff_mdct_end(&ac->mdct);
3349 ff_mdct_end(&ac->mdct_small);
3350 ff_mdct_end(&ac->mdct_ld);
3351 ff_mdct_end(&ac->mdct_ltp);
3353 ff_mdct15_uninit(&ac->mdct120);
3354 ff_mdct15_uninit(&ac->mdct480);
3355 ff_mdct15_uninit(&ac->mdct960);
3357 av_freep(&ac->fdsp);
3361 static void aacdec_init(AACContext *c)
3363 c->imdct_and_windowing = imdct_and_windowing;
3364 c->apply_ltp = apply_ltp;
3365 c->apply_tns = apply_tns;
3366 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3367 c->update_ltp = update_ltp;
3369 c->vector_pow43 = vector_pow43;
3370 c->subband_scale = subband_scale;
3375 ff_aacdec_init_mips(c);
3376 #endif /* !USE_FIXED */
3379 * AVOptions for Japanese DTV specific extensions (ADTS only)
3381 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3382 static const AVOption options[] = {
3383 {"dual_mono_mode", "Select the channel to decode for dual mono",
3384 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3385 AACDEC_FLAGS, "dual_mono_mode"},
3387 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3388 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3389 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3390 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3395 static const AVClass aac_decoder_class = {
3396 .class_name = "AAC decoder",
3397 .item_name = av_default_item_name,
3399 .version = LIBAVUTIL_VERSION_INT,