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, uint64_t *layout)
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],
210 if (e2c_vec[offset].av_position != UINT64_MAX)
211 *layout |= e2c_vec[offset].av_position;
215 e2c_vec[offset] = (struct elem_to_channel) {
218 .elem_id = layout_map[offset][1],
221 e2c_vec[offset + 1] = (struct elem_to_channel) {
222 .av_position = right,
224 .elem_id = layout_map[offset + 1][1],
227 if (left != UINT64_MAX)
230 if (right != UINT64_MAX)
237 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
240 int num_pos_channels = 0;
244 for (i = *current; i < tags; i++) {
245 if (layout_map[i][2] != pos)
247 if (layout_map[i][0] == TYPE_CPE) {
249 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
255 num_pos_channels += 2;
263 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
266 return num_pos_channels;
269 #define PREFIX_FOR_22POINT2 (AV_CH_LAYOUT_7POINT1_WIDE_BACK|AV_CH_BACK_CENTER|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT|AV_CH_LOW_FREQUENCY_2)
270 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
272 int i, n, total_non_cc_elements;
273 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
274 int num_front_channels, num_side_channels, num_back_channels;
277 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
282 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
283 if (num_front_channels < 0)
286 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
287 if (num_side_channels < 0)
290 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
291 if (num_back_channels < 0)
294 if (num_side_channels == 0 && num_back_channels >= 4) {
295 num_side_channels = 2;
296 num_back_channels -= 2;
300 if (num_front_channels & 1) {
301 e2c_vec[i] = (struct elem_to_channel) {
302 .av_position = AV_CH_FRONT_CENTER,
304 .elem_id = layout_map[i][1],
305 .aac_position = AAC_CHANNEL_FRONT
307 layout |= e2c_vec[i].av_position;
309 num_front_channels--;
311 if (num_front_channels >= 4) {
312 i += assign_pair(e2c_vec, layout_map, i,
313 AV_CH_FRONT_LEFT_OF_CENTER,
314 AV_CH_FRONT_RIGHT_OF_CENTER,
315 AAC_CHANNEL_FRONT, &layout);
316 num_front_channels -= 2;
318 if (num_front_channels >= 2) {
319 i += assign_pair(e2c_vec, layout_map, i,
322 AAC_CHANNEL_FRONT, &layout);
323 num_front_channels -= 2;
325 while (num_front_channels >= 2) {
326 i += assign_pair(e2c_vec, layout_map, i,
329 AAC_CHANNEL_FRONT, &layout);
330 num_front_channels -= 2;
333 if (num_side_channels >= 2) {
334 i += assign_pair(e2c_vec, layout_map, i,
337 AAC_CHANNEL_FRONT, &layout);
338 num_side_channels -= 2;
340 while (num_side_channels >= 2) {
341 i += assign_pair(e2c_vec, layout_map, i,
344 AAC_CHANNEL_SIDE, &layout);
345 num_side_channels -= 2;
348 while (num_back_channels >= 4) {
349 i += assign_pair(e2c_vec, layout_map, i,
352 AAC_CHANNEL_BACK, &layout);
353 num_back_channels -= 2;
355 if (num_back_channels >= 2) {
356 i += assign_pair(e2c_vec, layout_map, i,
359 AAC_CHANNEL_BACK, &layout);
360 num_back_channels -= 2;
362 if (num_back_channels) {
363 e2c_vec[i] = (struct elem_to_channel) {
364 .av_position = AV_CH_BACK_CENTER,
366 .elem_id = layout_map[i][1],
367 .aac_position = AAC_CHANNEL_BACK
369 layout |= e2c_vec[i].av_position;
374 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
375 e2c_vec[i] = (struct elem_to_channel) {
376 .av_position = AV_CH_LOW_FREQUENCY,
378 .elem_id = layout_map[i][1],
379 .aac_position = AAC_CHANNEL_LFE
381 layout |= e2c_vec[i].av_position;
384 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
385 e2c_vec[i] = (struct elem_to_channel) {
386 .av_position = AV_CH_LOW_FREQUENCY_2,
388 .elem_id = layout_map[i][1],
389 .aac_position = AAC_CHANNEL_LFE
391 layout |= e2c_vec[i].av_position;
394 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
395 e2c_vec[i] = (struct elem_to_channel) {
396 .av_position = UINT64_MAX,
398 .elem_id = layout_map[i][1],
399 .aac_position = AAC_CHANNEL_LFE
404 // The previous checks would end up at 8 at this point for 22.2
405 if (layout == PREFIX_FOR_22POINT2 && tags == 16 && i == 8) {
406 const uint8_t (*reference_layout_map)[3] = aac_channel_layout_map[12];
407 for (int j = 0; j < tags; j++) {
408 if (layout_map[j][0] != reference_layout_map[j][0] ||
409 layout_map[j][2] != reference_layout_map[j][2])
410 goto end_of_layout_definition;
413 e2c_vec[i] = (struct elem_to_channel) {
414 .av_position = AV_CH_TOP_FRONT_CENTER,
415 .syn_ele = layout_map[i][0],
416 .elem_id = layout_map[i][1],
417 .aac_position = layout_map[i][2]
418 }; layout |= e2c_vec[i].av_position; i++;
419 i += assign_pair(e2c_vec, layout_map, i,
420 AV_CH_TOP_FRONT_LEFT,
421 AV_CH_TOP_FRONT_RIGHT,
424 i += assign_pair(e2c_vec, layout_map, i,
426 AV_CH_TOP_SIDE_RIGHT,
429 e2c_vec[i] = (struct elem_to_channel) {
430 .av_position = AV_CH_TOP_CENTER,
431 .syn_ele = layout_map[i][0],
432 .elem_id = layout_map[i][1],
433 .aac_position = layout_map[i][2]
434 }; layout |= e2c_vec[i].av_position; i++;
435 i += assign_pair(e2c_vec, layout_map, i,
437 AV_CH_TOP_BACK_RIGHT,
440 e2c_vec[i] = (struct elem_to_channel) {
441 .av_position = AV_CH_TOP_BACK_CENTER,
442 .syn_ele = layout_map[i][0],
443 .elem_id = layout_map[i][1],
444 .aac_position = layout_map[i][2]
445 }; layout |= e2c_vec[i].av_position; i++;
446 e2c_vec[i] = (struct elem_to_channel) {
447 .av_position = AV_CH_BOTTOM_FRONT_CENTER,
448 .syn_ele = layout_map[i][0],
449 .elem_id = layout_map[i][1],
450 .aac_position = layout_map[i][2]
451 }; layout |= e2c_vec[i].av_position; i++;
452 i += assign_pair(e2c_vec, layout_map, i,
453 AV_CH_BOTTOM_FRONT_LEFT,
454 AV_CH_BOTTOM_FRONT_RIGHT,
459 end_of_layout_definition:
461 total_non_cc_elements = n = i;
463 if (layout == AV_CH_LAYOUT_22POINT2) {
464 // For 22.2 reorder the result as needed
465 FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[0]); // FL & FR first (final), FC third
466 FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[1]); // FC second (final), FLc & FRc third
467 FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[2]); // LFE1 third (final), FLc & FRc seventh
468 FFSWAP(struct elem_to_channel, e2c_vec[4], e2c_vec[3]); // BL & BR fourth (final), SiL & SiR fifth
469 FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[4]); // FLc & FRc fifth (final), SiL & SiR seventh
470 FFSWAP(struct elem_to_channel, e2c_vec[7], e2c_vec[6]); // LFE2 seventh (final), SiL & SiR eight (final)
471 FFSWAP(struct elem_to_channel, e2c_vec[9], e2c_vec[8]); // TpFL & TpFR ninth (final), TFC tenth (final)
472 FFSWAP(struct elem_to_channel, e2c_vec[11], e2c_vec[10]); // TC eleventh (final), TpSiL & TpSiR twelth
473 FFSWAP(struct elem_to_channel, e2c_vec[12], e2c_vec[11]); // TpBL & TpBR twelth (final), TpSiL & TpSiR thirteenth (final)
475 // For everything else, utilize the AV channel position define as a
479 for (i = 1; i < n; i++)
480 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
481 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
489 for (i = 0; i < total_non_cc_elements; i++) {
490 layout_map[i][0] = e2c_vec[i].syn_ele;
491 layout_map[i][1] = e2c_vec[i].elem_id;
492 layout_map[i][2] = e2c_vec[i].aac_position;
499 * Save current output configuration if and only if it has been locked.
501 static int push_output_configuration(AACContext *ac) {
504 if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
505 ac->oc[0] = ac->oc[1];
508 ac->oc[1].status = OC_NONE;
513 * Restore the previous output configuration if and only if the current
514 * configuration is unlocked.
516 static void pop_output_configuration(AACContext *ac) {
517 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
518 ac->oc[1] = ac->oc[0];
519 ac->avctx->channels = ac->oc[1].channels;
520 ac->avctx->channel_layout = ac->oc[1].channel_layout;
521 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
522 ac->oc[1].status, 0);
527 * Configure output channel order based on the current program
528 * configuration element.
530 * @return Returns error status. 0 - OK, !0 - error
532 static int output_configure(AACContext *ac,
533 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
534 enum OCStatus oc_type, int get_new_frame)
536 AVCodecContext *avctx = ac->avctx;
537 int i, channels = 0, ret;
539 uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
540 uint8_t type_counts[TYPE_END] = { 0 };
542 if (ac->oc[1].layout_map != layout_map) {
543 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
544 ac->oc[1].layout_map_tags = tags;
546 for (i = 0; i < tags; i++) {
547 int type = layout_map[i][0];
548 int id = layout_map[i][1];
549 id_map[type][id] = type_counts[type]++;
550 if (id_map[type][id] >= MAX_ELEM_ID) {
551 avpriv_request_sample(ac->avctx, "Too large remapped id");
552 return AVERROR_PATCHWELCOME;
555 // Try to sniff a reasonable channel order, otherwise output the
556 // channels in the order the PCE declared them.
557 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
558 layout = sniff_channel_order(layout_map, tags);
559 for (i = 0; i < tags; i++) {
560 int type = layout_map[i][0];
561 int id = layout_map[i][1];
562 int iid = id_map[type][id];
563 int position = layout_map[i][2];
564 // Allocate or free elements depending on if they are in the
565 // current program configuration.
566 ret = che_configure(ac, position, type, iid, &channels);
569 ac->tag_che_map[type][id] = ac->che[type][iid];
571 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
572 if (layout == AV_CH_FRONT_CENTER) {
573 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
579 if (layout) avctx->channel_layout = layout;
580 ac->oc[1].channel_layout = layout;
581 avctx->channels = ac->oc[1].channels = channels;
582 ac->oc[1].status = oc_type;
585 if ((ret = frame_configure_elements(ac->avctx)) < 0)
592 static void flush(AVCodecContext *avctx)
594 AACContext *ac= avctx->priv_data;
597 for (type = 3; type >= 0; type--) {
598 for (i = 0; i < MAX_ELEM_ID; i++) {
599 ChannelElement *che = ac->che[type][i];
601 for (j = 0; j <= 1; j++) {
602 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
610 * Set up channel positions based on a default channel configuration
611 * as specified in table 1.17.
613 * @return Returns error status. 0 - OK, !0 - error
615 static int set_default_channel_config(AACContext *ac, AVCodecContext *avctx,
616 uint8_t (*layout_map)[3],
620 if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
621 channel_config > 13) {
622 av_log(avctx, AV_LOG_ERROR,
623 "invalid default channel configuration (%d)\n",
625 return AVERROR_INVALIDDATA;
627 *tags = tags_per_config[channel_config];
628 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
629 *tags * sizeof(*layout_map));
632 * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
633 * However, at least Nero AAC encoder encodes 7.1 streams using the default
634 * channel config 7, mapping the side channels of the original audio stream
635 * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
636 * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
637 * the incorrect streams as if they were correct (and as the encoder intended).
639 * As actual intended 7.1(wide) streams are very rare, default to assuming a
640 * 7.1 layout was intended.
642 if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT && (!ac || !ac->warned_71_wide++)) {
643 av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
644 " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
645 " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
646 layout_map[2][2] = AAC_CHANNEL_SIDE;
652 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
654 /* For PCE based channel configurations map the channels solely based
656 if (!ac->oc[1].m4ac.chan_config) {
657 return ac->tag_che_map[type][elem_id];
659 // Allow single CPE stereo files to be signalled with mono configuration.
660 if (!ac->tags_mapped && type == TYPE_CPE &&
661 ac->oc[1].m4ac.chan_config == 1) {
662 uint8_t layout_map[MAX_ELEM_ID*4][3];
664 push_output_configuration(ac);
666 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
668 if (set_default_channel_config(ac, ac->avctx, layout_map,
669 &layout_map_tags, 2) < 0)
671 if (output_configure(ac, layout_map, layout_map_tags,
672 OC_TRIAL_FRAME, 1) < 0)
675 ac->oc[1].m4ac.chan_config = 2;
676 ac->oc[1].m4ac.ps = 0;
679 if (!ac->tags_mapped && type == TYPE_SCE &&
680 ac->oc[1].m4ac.chan_config == 2) {
681 uint8_t layout_map[MAX_ELEM_ID * 4][3];
683 push_output_configuration(ac);
685 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
687 if (set_default_channel_config(ac, ac->avctx, layout_map,
688 &layout_map_tags, 1) < 0)
690 if (output_configure(ac, layout_map, layout_map_tags,
691 OC_TRIAL_FRAME, 1) < 0)
694 ac->oc[1].m4ac.chan_config = 1;
695 if (ac->oc[1].m4ac.sbr)
696 ac->oc[1].m4ac.ps = -1;
698 /* For indexed channel configurations map the channels solely based
700 switch (ac->oc[1].m4ac.chan_config) {
702 if (ac->tags_mapped > 3 && ((type == TYPE_CPE && elem_id < 8) ||
703 (type == TYPE_SCE && elem_id < 6) ||
704 (type == TYPE_LFE && elem_id < 2))) {
706 return ac->tag_che_map[type][elem_id] = ac->che[type][elem_id];
710 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
712 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
715 if (ac->tags_mapped == 2 &&
716 ac->oc[1].m4ac.chan_config == 11 &&
719 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
722 /* Some streams incorrectly code 5.1 audio as
723 * SCE[0] CPE[0] CPE[1] SCE[1]
725 * SCE[0] CPE[0] CPE[1] LFE[0].
726 * If we seem to have encountered such a stream, transfer
727 * the LFE[0] element to the SCE[1]'s mapping */
728 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
729 if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
730 av_log(ac->avctx, AV_LOG_WARNING,
731 "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
732 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
733 ac->warned_remapping_once++;
736 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
739 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
741 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
744 /* Some streams incorrectly code 4.0 audio as
745 * SCE[0] CPE[0] LFE[0]
747 * SCE[0] CPE[0] SCE[1].
748 * If we seem to have encountered such a stream, transfer
749 * the SCE[1] element to the LFE[0]'s mapping */
750 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
751 if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
752 av_log(ac->avctx, AV_LOG_WARNING,
753 "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
754 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
755 ac->warned_remapping_once++;
758 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
760 if (ac->tags_mapped == 2 &&
761 ac->oc[1].m4ac.chan_config == 4 &&
764 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
768 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
771 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
772 } else if (ac->oc[1].m4ac.chan_config == 2) {
776 if (!ac->tags_mapped && type == TYPE_SCE) {
778 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
786 * Decode an array of 4 bit element IDs, optionally interleaved with a
787 * stereo/mono switching bit.
789 * @param type speaker type/position for these channels
791 static void decode_channel_map(uint8_t layout_map[][3],
792 enum ChannelPosition type,
793 GetBitContext *gb, int n)
796 enum RawDataBlockType syn_ele;
798 case AAC_CHANNEL_FRONT:
799 case AAC_CHANNEL_BACK:
800 case AAC_CHANNEL_SIDE:
801 syn_ele = get_bits1(gb);
807 case AAC_CHANNEL_LFE:
811 // AAC_CHANNEL_OFF has no channel map
814 layout_map[0][0] = syn_ele;
815 layout_map[0][1] = get_bits(gb, 4);
816 layout_map[0][2] = type;
821 static inline void relative_align_get_bits(GetBitContext *gb,
822 int reference_position) {
823 int n = (reference_position - get_bits_count(gb) & 7);
829 * Decode program configuration element; reference: table 4.2.
831 * @return Returns error status. 0 - OK, !0 - error
833 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
834 uint8_t (*layout_map)[3],
835 GetBitContext *gb, int byte_align_ref)
837 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
842 skip_bits(gb, 2); // object_type
844 sampling_index = get_bits(gb, 4);
845 if (m4ac->sampling_index != sampling_index)
846 av_log(avctx, AV_LOG_WARNING,
847 "Sample rate index in program config element does not "
848 "match the sample rate index configured by the container.\n");
850 num_front = get_bits(gb, 4);
851 num_side = get_bits(gb, 4);
852 num_back = get_bits(gb, 4);
853 num_lfe = get_bits(gb, 2);
854 num_assoc_data = get_bits(gb, 3);
855 num_cc = get_bits(gb, 4);
858 skip_bits(gb, 4); // mono_mixdown_tag
860 skip_bits(gb, 4); // stereo_mixdown_tag
863 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
865 if (get_bits_left(gb) < 5 * (num_front + num_side + num_back + num_cc) + 4 *(num_lfe + num_assoc_data + num_cc)) {
866 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
869 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
871 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
873 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
875 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
878 skip_bits_long(gb, 4 * num_assoc_data);
880 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
883 relative_align_get_bits(gb, byte_align_ref);
885 /* comment field, first byte is length */
886 comment_len = get_bits(gb, 8) * 8;
887 if (get_bits_left(gb) < comment_len) {
888 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
889 return AVERROR_INVALIDDATA;
891 skip_bits_long(gb, comment_len);
896 * Decode GA "General Audio" specific configuration; reference: table 4.1.
898 * @param ac pointer to AACContext, may be null
899 * @param avctx pointer to AVCCodecContext, used for logging
901 * @return Returns error status. 0 - OK, !0 - error
903 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
905 int get_bit_alignment,
906 MPEG4AudioConfig *m4ac,
909 int extension_flag, ret, ep_config, res_flags;
910 uint8_t layout_map[MAX_ELEM_ID*4][3];
914 if (get_bits1(gb)) { // frameLengthFlag
915 avpriv_report_missing_feature(avctx, "Fixed point 960/120 MDCT window");
916 return AVERROR_PATCHWELCOME;
918 m4ac->frame_length_short = 0;
920 m4ac->frame_length_short = get_bits1(gb);
921 if (m4ac->frame_length_short && m4ac->sbr == 1) {
922 avpriv_report_missing_feature(avctx, "SBR with 960 frame length");
923 if (ac) ac->warned_960_sbr = 1;
929 if (get_bits1(gb)) // dependsOnCoreCoder
930 skip_bits(gb, 14); // coreCoderDelay
931 extension_flag = get_bits1(gb);
933 if (m4ac->object_type == AOT_AAC_SCALABLE ||
934 m4ac->object_type == AOT_ER_AAC_SCALABLE)
935 skip_bits(gb, 3); // layerNr
937 if (channel_config == 0) {
938 skip_bits(gb, 4); // element_instance_tag
939 tags = decode_pce(avctx, m4ac, layout_map, gb, get_bit_alignment);
943 if ((ret = set_default_channel_config(ac, avctx, layout_map,
944 &tags, channel_config)))
948 if (count_channels(layout_map, tags) > 1) {
950 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
953 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
956 if (extension_flag) {
957 switch (m4ac->object_type) {
959 skip_bits(gb, 5); // numOfSubFrame
960 skip_bits(gb, 11); // layer_length
964 case AOT_ER_AAC_SCALABLE:
966 res_flags = get_bits(gb, 3);
968 avpriv_report_missing_feature(avctx,
969 "AAC data resilience (flags %x)",
971 return AVERROR_PATCHWELCOME;
975 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
977 switch (m4ac->object_type) {
980 case AOT_ER_AAC_SCALABLE:
982 ep_config = get_bits(gb, 2);
984 avpriv_report_missing_feature(avctx,
985 "epConfig %d", ep_config);
986 return AVERROR_PATCHWELCOME;
992 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
994 MPEG4AudioConfig *m4ac,
997 int ret, ep_config, res_flags;
998 uint8_t layout_map[MAX_ELEM_ID*4][3];
1000 const int ELDEXT_TERM = 0;
1005 if (get_bits1(gb)) { // frameLengthFlag
1006 avpriv_request_sample(avctx, "960/120 MDCT window");
1007 return AVERROR_PATCHWELCOME;
1010 m4ac->frame_length_short = get_bits1(gb);
1012 res_flags = get_bits(gb, 3);
1014 avpriv_report_missing_feature(avctx,
1015 "AAC data resilience (flags %x)",
1017 return AVERROR_PATCHWELCOME;
1020 if (get_bits1(gb)) { // ldSbrPresentFlag
1021 avpriv_report_missing_feature(avctx,
1023 return AVERROR_PATCHWELCOME;
1026 while (get_bits(gb, 4) != ELDEXT_TERM) {
1027 int len = get_bits(gb, 4);
1029 len += get_bits(gb, 8);
1030 if (len == 15 + 255)
1031 len += get_bits(gb, 16);
1032 if (get_bits_left(gb) < len * 8 + 4) {
1033 av_log(avctx, AV_LOG_ERROR, overread_err);
1034 return AVERROR_INVALIDDATA;
1036 skip_bits_long(gb, 8 * len);
1039 if ((ret = set_default_channel_config(ac, avctx, layout_map,
1040 &tags, channel_config)))
1043 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
1046 ep_config = get_bits(gb, 2);
1048 avpriv_report_missing_feature(avctx,
1049 "epConfig %d", ep_config);
1050 return AVERROR_PATCHWELCOME;
1056 * Decode audio specific configuration; reference: table 1.13.
1058 * @param ac pointer to AACContext, may be null
1059 * @param avctx pointer to AVCCodecContext, used for logging
1060 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
1061 * @param gb buffer holding an audio specific config
1062 * @param get_bit_alignment relative alignment for byte align operations
1063 * @param sync_extension look for an appended sync extension
1065 * @return Returns error status or number of consumed bits. <0 - error
1067 static int decode_audio_specific_config_gb(AACContext *ac,
1068 AVCodecContext *avctx,
1069 MPEG4AudioConfig *m4ac,
1071 int get_bit_alignment,
1075 GetBitContext gbc = *gb;
1077 if ((i = ff_mpeg4audio_get_config_gb(m4ac, &gbc, sync_extension, avctx)) < 0)
1078 return AVERROR_INVALIDDATA;
1080 if (m4ac->sampling_index > 12) {
1081 av_log(avctx, AV_LOG_ERROR,
1082 "invalid sampling rate index %d\n",
1083 m4ac->sampling_index);
1084 return AVERROR_INVALIDDATA;
1086 if (m4ac->object_type == AOT_ER_AAC_LD &&
1087 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
1088 av_log(avctx, AV_LOG_ERROR,
1089 "invalid low delay sampling rate index %d\n",
1090 m4ac->sampling_index);
1091 return AVERROR_INVALIDDATA;
1094 skip_bits_long(gb, i);
1096 switch (m4ac->object_type) {
1103 if ((ret = decode_ga_specific_config(ac, avctx, gb, get_bit_alignment,
1104 m4ac, m4ac->chan_config)) < 0)
1107 case AOT_ER_AAC_ELD:
1108 if ((ret = decode_eld_specific_config(ac, avctx, gb,
1109 m4ac, m4ac->chan_config)) < 0)
1113 avpriv_report_missing_feature(avctx,
1114 "Audio object type %s%d",
1115 m4ac->sbr == 1 ? "SBR+" : "",
1117 return AVERROR(ENOSYS);
1121 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1122 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1123 m4ac->sample_rate, m4ac->sbr,
1126 return get_bits_count(gb);
1129 static int decode_audio_specific_config(AACContext *ac,
1130 AVCodecContext *avctx,
1131 MPEG4AudioConfig *m4ac,
1132 const uint8_t *data, int64_t bit_size,
1138 if (bit_size < 0 || bit_size > INT_MAX) {
1139 av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
1140 return AVERROR_INVALIDDATA;
1143 ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
1144 for (i = 0; i < bit_size >> 3; i++)
1145 ff_dlog(avctx, "%02x ", data[i]);
1146 ff_dlog(avctx, "\n");
1148 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
1151 return decode_audio_specific_config_gb(ac, avctx, m4ac, &gb, 0,
1156 * linear congruential pseudorandom number generator
1158 * @param previous_val pointer to the current state of the generator
1160 * @return Returns a 32-bit pseudorandom integer
1162 static av_always_inline int lcg_random(unsigned previous_val)
1164 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1168 static void reset_all_predictors(PredictorState *ps)
1171 for (i = 0; i < MAX_PREDICTORS; i++)
1172 reset_predict_state(&ps[i]);
1175 static int sample_rate_idx (int rate)
1177 if (92017 <= rate) return 0;
1178 else if (75132 <= rate) return 1;
1179 else if (55426 <= rate) return 2;
1180 else if (46009 <= rate) return 3;
1181 else if (37566 <= rate) return 4;
1182 else if (27713 <= rate) return 5;
1183 else if (23004 <= rate) return 6;
1184 else if (18783 <= rate) return 7;
1185 else if (13856 <= rate) return 8;
1186 else if (11502 <= rate) return 9;
1187 else if (9391 <= rate) return 10;
1191 static void reset_predictor_group(PredictorState *ps, int group_num)
1194 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1195 reset_predict_state(&ps[i]);
1198 static void aacdec_init(AACContext *ac);
1200 static av_cold void aac_static_table_init(void)
1202 static VLC_TYPE vlc_buf[304 + 270 + 550 + 300 + 328 +
1203 294 + 306 + 268 + 510 + 366 + 462][2];
1204 for (unsigned i = 0, offset = 0; i < 11; i++) {
1205 vlc_spectral[i].table = &vlc_buf[offset];
1206 vlc_spectral[i].table_allocated = FF_ARRAY_ELEMS(vlc_buf) - offset;
1207 ff_init_vlc_sparse(&vlc_spectral[i], 8, ff_aac_spectral_sizes[i],
1208 ff_aac_spectral_bits[i], sizeof(ff_aac_spectral_bits[i][0]),
1209 sizeof(ff_aac_spectral_bits[i][0]),
1210 ff_aac_spectral_codes[i], sizeof(ff_aac_spectral_codes[i][0]),
1211 sizeof(ff_aac_spectral_codes[i][0]),
1212 ff_aac_codebook_vector_idx[i], sizeof(ff_aac_codebook_vector_idx[i][0]),
1213 sizeof(ff_aac_codebook_vector_idx[i][0]),
1214 INIT_VLC_STATIC_OVERLONG);
1215 offset += vlc_spectral[i].table_size;
1218 AAC_RENAME(ff_aac_sbr_init)();
1222 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1223 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1224 ff_aac_scalefactor_bits,
1225 sizeof(ff_aac_scalefactor_bits[0]),
1226 sizeof(ff_aac_scalefactor_bits[0]),
1227 ff_aac_scalefactor_code,
1228 sizeof(ff_aac_scalefactor_code[0]),
1229 sizeof(ff_aac_scalefactor_code[0]),
1232 // window initialization
1233 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_1024), 4.0, 1024);
1234 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_128), 6.0, 128);
1236 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_960), 4.0, 960);
1237 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_120), 6.0, 120);
1238 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_960), 960);
1239 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_120), 120);
1241 AAC_RENAME(ff_init_ff_sine_windows)(10);
1242 AAC_RENAME(ff_init_ff_sine_windows)( 9);
1243 AAC_RENAME(ff_init_ff_sine_windows)( 7);
1245 AAC_RENAME(ff_cbrt_tableinit)();
1248 static AVOnce aac_table_init = AV_ONCE_INIT;
1250 static av_cold int aac_decode_init(AVCodecContext *avctx)
1252 AACContext *ac = avctx->priv_data;
1255 if (avctx->sample_rate > 96000)
1256 return AVERROR_INVALIDDATA;
1258 ret = ff_thread_once(&aac_table_init, &aac_static_table_init);
1260 return AVERROR_UNKNOWN;
1263 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1267 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1269 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1270 #endif /* USE_FIXED */
1272 if (avctx->extradata_size > 0) {
1273 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1275 avctx->extradata_size * 8LL,
1280 uint8_t layout_map[MAX_ELEM_ID*4][3];
1281 int layout_map_tags;
1283 sr = sample_rate_idx(avctx->sample_rate);
1284 ac->oc[1].m4ac.sampling_index = sr;
1285 ac->oc[1].m4ac.channels = avctx->channels;
1286 ac->oc[1].m4ac.sbr = -1;
1287 ac->oc[1].m4ac.ps = -1;
1289 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1290 if (ff_mpeg4audio_channels[i] == avctx->channels)
1292 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1295 ac->oc[1].m4ac.chan_config = i;
1297 if (ac->oc[1].m4ac.chan_config) {
1298 int ret = set_default_channel_config(ac, avctx, layout_map,
1299 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1301 output_configure(ac, layout_map, layout_map_tags,
1303 else if (avctx->err_recognition & AV_EF_EXPLODE)
1304 return AVERROR_INVALIDDATA;
1308 if (avctx->channels > MAX_CHANNELS) {
1309 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1310 return AVERROR_INVALIDDATA;
1314 ac->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1316 ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1317 #endif /* USE_FIXED */
1319 return AVERROR(ENOMEM);
1322 ac->random_state = 0x1f2e3d4c;
1324 AAC_RENAME_32(ff_mdct_init)(&ac->mdct, 11, 1, 1.0 / RANGE15(1024.0));
1325 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ld, 10, 1, 1.0 / RANGE15(512.0));
1326 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_small, 8, 1, 1.0 / RANGE15(128.0));
1327 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ltp, 11, 0, RANGE15(-2.0));
1329 ret = ff_mdct15_init(&ac->mdct120, 1, 3, 1.0f/(16*1024*120*2));
1332 ret = ff_mdct15_init(&ac->mdct480, 1, 5, 1.0f/(16*1024*960));
1335 ret = ff_mdct15_init(&ac->mdct960, 1, 6, 1.0f/(16*1024*960*2));
1344 * Skip data_stream_element; reference: table 4.10.
1346 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1348 int byte_align = get_bits1(gb);
1349 int count = get_bits(gb, 8);
1351 count += get_bits(gb, 8);
1355 if (get_bits_left(gb) < 8 * count) {
1356 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1357 return AVERROR_INVALIDDATA;
1359 skip_bits_long(gb, 8 * count);
1363 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1367 if (get_bits1(gb)) {
1368 ics->predictor_reset_group = get_bits(gb, 5);
1369 if (ics->predictor_reset_group == 0 ||
1370 ics->predictor_reset_group > 30) {
1371 av_log(ac->avctx, AV_LOG_ERROR,
1372 "Invalid Predictor Reset Group.\n");
1373 return AVERROR_INVALIDDATA;
1376 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1377 ics->prediction_used[sfb] = get_bits1(gb);
1383 * Decode Long Term Prediction data; reference: table 4.xx.
1385 static void decode_ltp(LongTermPrediction *ltp,
1386 GetBitContext *gb, uint8_t max_sfb)
1390 ltp->lag = get_bits(gb, 11);
1391 ltp->coef = ltp_coef[get_bits(gb, 3)];
1392 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1393 ltp->used[sfb] = get_bits1(gb);
1397 * Decode Individual Channel Stream info; reference: table 4.6.
1399 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1402 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1403 const int aot = m4ac->object_type;
1404 const int sampling_index = m4ac->sampling_index;
1405 int ret_fail = AVERROR_INVALIDDATA;
1407 if (aot != AOT_ER_AAC_ELD) {
1408 if (get_bits1(gb)) {
1409 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1410 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1411 return AVERROR_INVALIDDATA;
1413 ics->window_sequence[1] = ics->window_sequence[0];
1414 ics->window_sequence[0] = get_bits(gb, 2);
1415 if (aot == AOT_ER_AAC_LD &&
1416 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1417 av_log(ac->avctx, AV_LOG_ERROR,
1418 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1419 "window sequence %d found.\n", ics->window_sequence[0]);
1420 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1421 return AVERROR_INVALIDDATA;
1423 ics->use_kb_window[1] = ics->use_kb_window[0];
1424 ics->use_kb_window[0] = get_bits1(gb);
1426 ics->num_window_groups = 1;
1427 ics->group_len[0] = 1;
1428 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1430 ics->max_sfb = get_bits(gb, 4);
1431 for (i = 0; i < 7; i++) {
1432 if (get_bits1(gb)) {
1433 ics->group_len[ics->num_window_groups - 1]++;
1435 ics->num_window_groups++;
1436 ics->group_len[ics->num_window_groups - 1] = 1;
1439 ics->num_windows = 8;
1440 if (m4ac->frame_length_short) {
1441 ics->swb_offset = ff_swb_offset_120[sampling_index];
1442 ics->num_swb = ff_aac_num_swb_120[sampling_index];
1444 ics->swb_offset = ff_swb_offset_128[sampling_index];
1445 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1447 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
1448 ics->predictor_present = 0;
1450 ics->max_sfb = get_bits(gb, 6);
1451 ics->num_windows = 1;
1452 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1453 if (m4ac->frame_length_short) {
1454 ics->swb_offset = ff_swb_offset_480[sampling_index];
1455 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1456 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1458 ics->swb_offset = ff_swb_offset_512[sampling_index];
1459 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1460 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1462 if (!ics->num_swb || !ics->swb_offset) {
1463 ret_fail = AVERROR_BUG;
1467 if (m4ac->frame_length_short) {
1468 ics->num_swb = ff_aac_num_swb_960[sampling_index];
1469 ics->swb_offset = ff_swb_offset_960[sampling_index];
1471 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1472 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1474 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1476 if (aot != AOT_ER_AAC_ELD) {
1477 ics->predictor_present = get_bits1(gb);
1478 ics->predictor_reset_group = 0;
1480 if (ics->predictor_present) {
1481 if (aot == AOT_AAC_MAIN) {
1482 if (decode_prediction(ac, ics, gb)) {
1485 } else if (aot == AOT_AAC_LC ||
1486 aot == AOT_ER_AAC_LC) {
1487 av_log(ac->avctx, AV_LOG_ERROR,
1488 "Prediction is not allowed in AAC-LC.\n");
1491 if (aot == AOT_ER_AAC_LD) {
1492 av_log(ac->avctx, AV_LOG_ERROR,
1493 "LTP in ER AAC LD not yet implemented.\n");
1494 ret_fail = AVERROR_PATCHWELCOME;
1497 if ((ics->ltp.present = get_bits(gb, 1)))
1498 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1503 if (ics->max_sfb > ics->num_swb) {
1504 av_log(ac->avctx, AV_LOG_ERROR,
1505 "Number of scalefactor bands in group (%d) "
1506 "exceeds limit (%d).\n",
1507 ics->max_sfb, ics->num_swb);
1518 * Decode band types (section_data payload); reference: table 4.46.
1520 * @param band_type array of the used band type
1521 * @param band_type_run_end array of the last scalefactor band of a band type run
1523 * @return Returns error status. 0 - OK, !0 - error
1525 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1526 int band_type_run_end[120], GetBitContext *gb,
1527 IndividualChannelStream *ics)
1530 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1531 for (g = 0; g < ics->num_window_groups; g++) {
1533 while (k < ics->max_sfb) {
1534 uint8_t sect_end = k;
1536 int sect_band_type = get_bits(gb, 4);
1537 if (sect_band_type == 12) {
1538 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1539 return AVERROR_INVALIDDATA;
1542 sect_len_incr = get_bits(gb, bits);
1543 sect_end += sect_len_incr;
1544 if (get_bits_left(gb) < 0) {
1545 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1546 return AVERROR_INVALIDDATA;
1548 if (sect_end > ics->max_sfb) {
1549 av_log(ac->avctx, AV_LOG_ERROR,
1550 "Number of bands (%d) exceeds limit (%d).\n",
1551 sect_end, ics->max_sfb);
1552 return AVERROR_INVALIDDATA;
1554 } while (sect_len_incr == (1 << bits) - 1);
1555 for (; k < sect_end; k++) {
1556 band_type [idx] = sect_band_type;
1557 band_type_run_end[idx++] = sect_end;
1565 * Decode scalefactors; reference: table 4.47.
1567 * @param global_gain first scalefactor value as scalefactors are differentially coded
1568 * @param band_type array of the used band type
1569 * @param band_type_run_end array of the last scalefactor band of a band type run
1570 * @param sf array of scalefactors or intensity stereo positions
1572 * @return Returns error status. 0 - OK, !0 - error
1574 static int decode_scalefactors(AACContext *ac, INTFLOAT sf[120], GetBitContext *gb,
1575 unsigned int global_gain,
1576 IndividualChannelStream *ics,
1577 enum BandType band_type[120],
1578 int band_type_run_end[120])
1581 int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
1584 for (g = 0; g < ics->num_window_groups; g++) {
1585 for (i = 0; i < ics->max_sfb;) {
1586 int run_end = band_type_run_end[idx];
1587 if (band_type[idx] == ZERO_BT) {
1588 for (; i < run_end; i++, idx++)
1590 } else if ((band_type[idx] == INTENSITY_BT) ||
1591 (band_type[idx] == INTENSITY_BT2)) {
1592 for (; i < run_end; i++, idx++) {
1593 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1594 clipped_offset = av_clip(offset[2], -155, 100);
1595 if (offset[2] != clipped_offset) {
1596 avpriv_request_sample(ac->avctx,
1597 "If you heard an audible artifact, there may be a bug in the decoder. "
1598 "Clipped intensity stereo position (%d -> %d)",
1599 offset[2], clipped_offset);
1602 sf[idx] = 100 - clipped_offset;
1604 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1605 #endif /* USE_FIXED */
1607 } else if (band_type[idx] == NOISE_BT) {
1608 for (; i < run_end; i++, idx++) {
1609 if (noise_flag-- > 0)
1610 offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
1612 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1613 clipped_offset = av_clip(offset[1], -100, 155);
1614 if (offset[1] != clipped_offset) {
1615 avpriv_request_sample(ac->avctx,
1616 "If you heard an audible artifact, there may be a bug in the decoder. "
1617 "Clipped noise gain (%d -> %d)",
1618 offset[1], clipped_offset);
1621 sf[idx] = -(100 + clipped_offset);
1623 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1624 #endif /* USE_FIXED */
1627 for (; i < run_end; i++, idx++) {
1628 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1629 if (offset[0] > 255U) {
1630 av_log(ac->avctx, AV_LOG_ERROR,
1631 "Scalefactor (%d) out of range.\n", offset[0]);
1632 return AVERROR_INVALIDDATA;
1635 sf[idx] = -offset[0];
1637 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1638 #endif /* USE_FIXED */
1647 * Decode pulse data; reference: table 4.7.
1649 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1650 const uint16_t *swb_offset, int num_swb)
1653 pulse->num_pulse = get_bits(gb, 2) + 1;
1654 pulse_swb = get_bits(gb, 6);
1655 if (pulse_swb >= num_swb)
1657 pulse->pos[0] = swb_offset[pulse_swb];
1658 pulse->pos[0] += get_bits(gb, 5);
1659 if (pulse->pos[0] >= swb_offset[num_swb])
1661 pulse->amp[0] = get_bits(gb, 4);
1662 for (i = 1; i < pulse->num_pulse; i++) {
1663 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1664 if (pulse->pos[i] >= swb_offset[num_swb])
1666 pulse->amp[i] = get_bits(gb, 4);
1672 * Decode Temporal Noise Shaping data; reference: table 4.48.
1674 * @return Returns error status. 0 - OK, !0 - error
1676 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1677 GetBitContext *gb, const IndividualChannelStream *ics)
1679 int w, filt, i, coef_len, coef_res, coef_compress;
1680 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1681 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1682 for (w = 0; w < ics->num_windows; w++) {
1683 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1684 coef_res = get_bits1(gb);
1686 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1688 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1690 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1691 av_log(ac->avctx, AV_LOG_ERROR,
1692 "TNS filter order %d is greater than maximum %d.\n",
1693 tns->order[w][filt], tns_max_order);
1694 tns->order[w][filt] = 0;
1695 return AVERROR_INVALIDDATA;
1697 if (tns->order[w][filt]) {
1698 tns->direction[w][filt] = get_bits1(gb);
1699 coef_compress = get_bits1(gb);
1700 coef_len = coef_res + 3 - coef_compress;
1701 tmp2_idx = 2 * coef_compress + coef_res;
1703 for (i = 0; i < tns->order[w][filt]; i++)
1704 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1713 * Decode Mid/Side data; reference: table 4.54.
1715 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1716 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1717 * [3] reserved for scalable AAC
1719 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1723 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1724 if (ms_present == 1) {
1725 for (idx = 0; idx < max_idx; idx++)
1726 cpe->ms_mask[idx] = get_bits1(gb);
1727 } else if (ms_present == 2) {
1728 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1733 * Decode spectral data; reference: table 4.50.
1734 * Dequantize and scale spectral data; reference: 4.6.3.3.
1736 * @param coef array of dequantized, scaled spectral data
1737 * @param sf array of scalefactors or intensity stereo positions
1738 * @param pulse_present set if pulses are present
1739 * @param pulse pointer to pulse data struct
1740 * @param band_type array of the used band type
1742 * @return Returns error status. 0 - OK, !0 - error
1744 static int decode_spectrum_and_dequant(AACContext *ac, INTFLOAT coef[1024],
1745 GetBitContext *gb, const INTFLOAT sf[120],
1746 int pulse_present, const Pulse *pulse,
1747 const IndividualChannelStream *ics,
1748 enum BandType band_type[120])
1750 int i, k, g, idx = 0;
1751 const int c = 1024 / ics->num_windows;
1752 const uint16_t *offsets = ics->swb_offset;
1753 INTFLOAT *coef_base = coef;
1755 for (g = 0; g < ics->num_windows; g++)
1756 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1757 sizeof(INTFLOAT) * (c - offsets[ics->max_sfb]));
1759 for (g = 0; g < ics->num_window_groups; g++) {
1760 unsigned g_len = ics->group_len[g];
1762 for (i = 0; i < ics->max_sfb; i++, idx++) {
1763 const unsigned cbt_m1 = band_type[idx] - 1;
1764 INTFLOAT *cfo = coef + offsets[i];
1765 int off_len = offsets[i + 1] - offsets[i];
1768 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1769 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1770 memset(cfo, 0, off_len * sizeof(*cfo));
1772 } else if (cbt_m1 == NOISE_BT - 1) {
1773 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1774 INTFLOAT band_energy;
1776 for (k = 0; k < off_len; k++) {
1777 ac->random_state = lcg_random(ac->random_state);
1778 cfo[k] = ac->random_state >> 3;
1781 band_energy = ac->fdsp->scalarproduct_fixed(cfo, cfo, off_len);
1782 band_energy = fixed_sqrt(band_energy, 31);
1783 noise_scale(cfo, sf[idx], band_energy, off_len);
1787 for (k = 0; k < off_len; k++) {
1788 ac->random_state = lcg_random(ac->random_state);
1789 cfo[k] = ac->random_state;
1792 band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
1793 scale = sf[idx] / sqrtf(band_energy);
1794 ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
1795 #endif /* USE_FIXED */
1799 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1800 #endif /* !USE_FIXED */
1801 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1802 OPEN_READER(re, gb);
1804 switch (cbt_m1 >> 1) {
1806 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1814 UPDATE_CACHE(re, gb);
1815 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1818 cf = DEC_SQUAD(cf, cb_idx);
1820 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1821 #endif /* USE_FIXED */
1827 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1837 UPDATE_CACHE(re, gb);
1838 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1840 nnz = cb_idx >> 8 & 15;
1841 bits = nnz ? GET_CACHE(re, gb) : 0;
1842 LAST_SKIP_BITS(re, gb, nnz);
1844 cf = DEC_UQUAD(cf, cb_idx, bits);
1846 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1847 #endif /* USE_FIXED */
1853 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1861 UPDATE_CACHE(re, gb);
1862 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1865 cf = DEC_SPAIR(cf, cb_idx);
1867 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1868 #endif /* USE_FIXED */
1875 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1885 UPDATE_CACHE(re, gb);
1886 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1888 nnz = cb_idx >> 8 & 15;
1889 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1890 LAST_SKIP_BITS(re, gb, nnz);
1892 cf = DEC_UPAIR(cf, cb_idx, sign);
1894 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1895 #endif /* USE_FIXED */
1901 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1907 uint32_t *icf = (uint32_t *) cf;
1908 #endif /* USE_FIXED */
1918 UPDATE_CACHE(re, gb);
1919 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1922 if (cb_idx == 0x0000) {
1930 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1931 LAST_SKIP_BITS(re, gb, nnz);
1933 for (j = 0; j < 2; j++) {
1937 /* The total length of escape_sequence must be < 22 bits according
1938 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1939 UPDATE_CACHE(re, gb);
1940 b = GET_CACHE(re, gb);
1941 b = 31 - av_log2(~b);
1944 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1945 return AVERROR_INVALIDDATA;
1948 SKIP_BITS(re, gb, b + 1);
1950 n = (1 << b) + SHOW_UBITS(re, gb, b);
1951 LAST_SKIP_BITS(re, gb, b);
1958 *icf++ = ff_cbrt_tab[n] | (bits & 1U<<31);
1959 #endif /* USE_FIXED */
1968 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1969 *icf++ = (bits & 1U<<31) | v;
1970 #endif /* USE_FIXED */
1977 ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1978 #endif /* !USE_FIXED */
1982 CLOSE_READER(re, gb);
1988 if (pulse_present) {
1990 for (i = 0; i < pulse->num_pulse; i++) {
1991 INTFLOAT co = coef_base[ pulse->pos[i] ];
1992 while (offsets[idx + 1] <= pulse->pos[i])
1994 if (band_type[idx] != NOISE_BT && sf[idx]) {
1995 INTFLOAT ico = -pulse->amp[i];
1998 ico = co + (co > 0 ? -ico : ico);
2000 coef_base[ pulse->pos[i] ] = ico;
2004 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
2006 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
2007 #endif /* USE_FIXED */
2014 for (g = 0; g < ics->num_window_groups; g++) {
2015 unsigned g_len = ics->group_len[g];
2017 for (i = 0; i < ics->max_sfb; i++, idx++) {
2018 const unsigned cbt_m1 = band_type[idx] - 1;
2019 int *cfo = coef + offsets[i];
2020 int off_len = offsets[i + 1] - offsets[i];
2023 if (cbt_m1 < NOISE_BT - 1) {
2024 for (group = 0; group < (int)g_len; group++, cfo+=128) {
2025 ac->vector_pow43(cfo, off_len);
2026 ac->subband_scale(cfo, cfo, sf[idx], 34, off_len, ac->avctx);
2032 #endif /* USE_FIXED */
2037 * Apply AAC-Main style frequency domain prediction.
2039 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
2043 if (!sce->ics.predictor_initialized) {
2044 reset_all_predictors(sce->predictor_state);
2045 sce->ics.predictor_initialized = 1;
2048 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2050 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
2052 for (k = sce->ics.swb_offset[sfb];
2053 k < sce->ics.swb_offset[sfb + 1];
2055 predict(&sce->predictor_state[k], &sce->coeffs[k],
2056 sce->ics.predictor_present &&
2057 sce->ics.prediction_used[sfb]);
2060 if (sce->ics.predictor_reset_group)
2061 reset_predictor_group(sce->predictor_state,
2062 sce->ics.predictor_reset_group);
2064 reset_all_predictors(sce->predictor_state);
2067 static void decode_gain_control(SingleChannelElement * sce, GetBitContext * gb)
2069 // wd_num, wd_test, aloc_size
2070 static const uint8_t gain_mode[4][3] = {
2071 {1, 0, 5}, // ONLY_LONG_SEQUENCE = 0,
2072 {2, 1, 2}, // LONG_START_SEQUENCE,
2073 {8, 0, 2}, // EIGHT_SHORT_SEQUENCE,
2074 {2, 1, 5}, // LONG_STOP_SEQUENCE
2077 const int mode = sce->ics.window_sequence[0];
2080 // FIXME: Store the gain control data on |sce| and do something with it.
2081 uint8_t max_band = get_bits(gb, 2);
2082 for (bd = 0; bd < max_band; bd++) {
2083 for (wd = 0; wd < gain_mode[mode][0]; wd++) {
2084 uint8_t adjust_num = get_bits(gb, 3);
2085 for (ad = 0; ad < adjust_num; ad++) {
2086 skip_bits(gb, 4 + ((wd == 0 && gain_mode[mode][1])
2088 : gain_mode[mode][2]));
2095 * Decode an individual_channel_stream payload; reference: table 4.44.
2097 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
2098 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
2100 * @return Returns error status. 0 - OK, !0 - error
2102 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
2103 GetBitContext *gb, int common_window, int scale_flag)
2106 TemporalNoiseShaping *tns = &sce->tns;
2107 IndividualChannelStream *ics = &sce->ics;
2108 INTFLOAT *out = sce->coeffs;
2109 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
2112 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2113 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
2114 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
2115 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
2116 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2118 /* This assignment is to silence a GCC warning about the variable being used
2119 * uninitialized when in fact it always is.
2121 pulse.num_pulse = 0;
2123 global_gain = get_bits(gb, 8);
2125 if (!common_window && !scale_flag) {
2126 ret = decode_ics_info(ac, ics, gb);
2131 if ((ret = decode_band_types(ac, sce->band_type,
2132 sce->band_type_run_end, gb, ics)) < 0)
2134 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
2135 sce->band_type, sce->band_type_run_end)) < 0)
2140 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
2141 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2142 av_log(ac->avctx, AV_LOG_ERROR,
2143 "Pulse tool not allowed in eight short sequence.\n");
2144 ret = AVERROR_INVALIDDATA;
2147 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
2148 av_log(ac->avctx, AV_LOG_ERROR,
2149 "Pulse data corrupt or invalid.\n");
2150 ret = AVERROR_INVALIDDATA;
2154 tns->present = get_bits1(gb);
2155 if (tns->present && !er_syntax) {
2156 ret = decode_tns(ac, tns, gb, ics);
2160 if (!eld_syntax && get_bits1(gb)) {
2161 decode_gain_control(sce, gb);
2162 if (!ac->warned_gain_control) {
2163 avpriv_report_missing_feature(ac->avctx, "Gain control");
2164 ac->warned_gain_control = 1;
2167 // I see no textual basis in the spec for this occurring after SSR gain
2168 // control, but this is what both reference and real implmentations do
2169 if (tns->present && er_syntax) {
2170 ret = decode_tns(ac, tns, gb, ics);
2176 ret = decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
2177 &pulse, ics, sce->band_type);
2181 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
2182 apply_prediction(ac, sce);
2191 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
2193 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
2195 const IndividualChannelStream *ics = &cpe->ch[0].ics;
2196 INTFLOAT *ch0 = cpe->ch[0].coeffs;
2197 INTFLOAT *ch1 = cpe->ch[1].coeffs;
2198 int g, i, group, idx = 0;
2199 const uint16_t *offsets = ics->swb_offset;
2200 for (g = 0; g < ics->num_window_groups; g++) {
2201 for (i = 0; i < ics->max_sfb; i++, idx++) {
2202 if (cpe->ms_mask[idx] &&
2203 cpe->ch[0].band_type[idx] < NOISE_BT &&
2204 cpe->ch[1].band_type[idx] < NOISE_BT) {
2206 for (group = 0; group < ics->group_len[g]; group++) {
2207 ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
2208 ch1 + group * 128 + offsets[i],
2209 offsets[i+1] - offsets[i]);
2211 for (group = 0; group < ics->group_len[g]; group++) {
2212 ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
2213 ch1 + group * 128 + offsets[i],
2214 offsets[i+1] - offsets[i]);
2215 #endif /* USE_FIXED */
2219 ch0 += ics->group_len[g] * 128;
2220 ch1 += ics->group_len[g] * 128;
2225 * intensity stereo decoding; reference: 4.6.8.2.3
2227 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
2228 * [1] mask is decoded from bitstream; [2] mask is all 1s;
2229 * [3] reserved for scalable AAC
2231 static void apply_intensity_stereo(AACContext *ac,
2232 ChannelElement *cpe, int ms_present)
2234 const IndividualChannelStream *ics = &cpe->ch[1].ics;
2235 SingleChannelElement *sce1 = &cpe->ch[1];
2236 INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2237 const uint16_t *offsets = ics->swb_offset;
2238 int g, group, i, idx = 0;
2241 for (g = 0; g < ics->num_window_groups; g++) {
2242 for (i = 0; i < ics->max_sfb;) {
2243 if (sce1->band_type[idx] == INTENSITY_BT ||
2244 sce1->band_type[idx] == INTENSITY_BT2) {
2245 const int bt_run_end = sce1->band_type_run_end[idx];
2246 for (; i < bt_run_end; i++, idx++) {
2247 c = -1 + 2 * (sce1->band_type[idx] - 14);
2249 c *= 1 - 2 * cpe->ms_mask[idx];
2250 scale = c * sce1->sf[idx];
2251 for (group = 0; group < ics->group_len[g]; group++)
2253 ac->subband_scale(coef1 + group * 128 + offsets[i],
2254 coef0 + group * 128 + offsets[i],
2257 offsets[i + 1] - offsets[i] ,ac->avctx);
2259 ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2260 coef0 + group * 128 + offsets[i],
2262 offsets[i + 1] - offsets[i]);
2263 #endif /* USE_FIXED */
2266 int bt_run_end = sce1->band_type_run_end[idx];
2267 idx += bt_run_end - i;
2271 coef0 += ics->group_len[g] * 128;
2272 coef1 += ics->group_len[g] * 128;
2277 * Decode a channel_pair_element; reference: table 4.4.
2279 * @return Returns error status. 0 - OK, !0 - error
2281 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2283 int i, ret, common_window, ms_present = 0;
2284 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2286 common_window = eld_syntax || get_bits1(gb);
2287 if (common_window) {
2288 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2289 return AVERROR_INVALIDDATA;
2290 i = cpe->ch[1].ics.use_kb_window[0];
2291 cpe->ch[1].ics = cpe->ch[0].ics;
2292 cpe->ch[1].ics.use_kb_window[1] = i;
2293 if (cpe->ch[1].ics.predictor_present &&
2294 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2295 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2296 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2297 ms_present = get_bits(gb, 2);
2298 if (ms_present == 3) {
2299 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2300 return AVERROR_INVALIDDATA;
2301 } else if (ms_present)
2302 decode_mid_side_stereo(cpe, gb, ms_present);
2304 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2306 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2309 if (common_window) {
2311 apply_mid_side_stereo(ac, cpe);
2312 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2313 apply_prediction(ac, &cpe->ch[0]);
2314 apply_prediction(ac, &cpe->ch[1]);
2318 apply_intensity_stereo(ac, cpe, ms_present);
2322 static const float cce_scale[] = {
2323 1.09050773266525765921, //2^(1/8)
2324 1.18920711500272106672, //2^(1/4)
2330 * Decode coupling_channel_element; reference: table 4.8.
2332 * @return Returns error status. 0 - OK, !0 - error
2334 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2340 SingleChannelElement *sce = &che->ch[0];
2341 ChannelCoupling *coup = &che->coup;
2343 coup->coupling_point = 2 * get_bits1(gb);
2344 coup->num_coupled = get_bits(gb, 3);
2345 for (c = 0; c <= coup->num_coupled; c++) {
2347 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2348 coup->id_select[c] = get_bits(gb, 4);
2349 if (coup->type[c] == TYPE_CPE) {
2350 coup->ch_select[c] = get_bits(gb, 2);
2351 if (coup->ch_select[c] == 3)
2354 coup->ch_select[c] = 2;
2356 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2358 sign = get_bits(gb, 1);
2360 scale = get_bits(gb, 2);
2362 scale = cce_scale[get_bits(gb, 2)];
2365 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2368 for (c = 0; c < num_gain; c++) {
2372 INTFLOAT gain_cache = FIXR10(1.);
2374 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2375 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2376 gain_cache = GET_GAIN(scale, gain);
2378 if ((abs(gain_cache)-1024) >> 3 > 30)
2379 return AVERROR(ERANGE);
2382 if (coup->coupling_point == AFTER_IMDCT) {
2383 coup->gain[c][0] = gain_cache;
2385 for (g = 0; g < sce->ics.num_window_groups; g++) {
2386 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2387 if (sce->band_type[idx] != ZERO_BT) {
2389 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2397 gain_cache = GET_GAIN(scale, t) * s;
2399 if ((abs(gain_cache)-1024) >> 3 > 30)
2400 return AVERROR(ERANGE);
2404 coup->gain[c][idx] = gain_cache;
2414 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2416 * @return Returns number of bytes consumed.
2418 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2422 int num_excl_chan = 0;
2425 for (i = 0; i < 7; i++)
2426 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2427 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2429 return num_excl_chan / 7;
2433 * Decode dynamic range information; reference: table 4.52.
2435 * @return Returns number of bytes consumed.
2437 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2441 int drc_num_bands = 1;
2444 /* pce_tag_present? */
2445 if (get_bits1(gb)) {
2446 che_drc->pce_instance_tag = get_bits(gb, 4);
2447 skip_bits(gb, 4); // tag_reserved_bits
2451 /* excluded_chns_present? */
2452 if (get_bits1(gb)) {
2453 n += decode_drc_channel_exclusions(che_drc, gb);
2456 /* drc_bands_present? */
2457 if (get_bits1(gb)) {
2458 che_drc->band_incr = get_bits(gb, 4);
2459 che_drc->interpolation_scheme = get_bits(gb, 4);
2461 drc_num_bands += che_drc->band_incr;
2462 for (i = 0; i < drc_num_bands; i++) {
2463 che_drc->band_top[i] = get_bits(gb, 8);
2468 /* prog_ref_level_present? */
2469 if (get_bits1(gb)) {
2470 che_drc->prog_ref_level = get_bits(gb, 7);
2471 skip_bits1(gb); // prog_ref_level_reserved_bits
2475 for (i = 0; i < drc_num_bands; i++) {
2476 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2477 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2484 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2486 int i, major, minor;
2491 get_bits(gb, 13); len -= 13;
2493 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2494 buf[i] = get_bits(gb, 8);
2497 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2498 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2500 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2501 ac->avctx->internal->skip_samples = 1024;
2505 skip_bits_long(gb, len);
2511 * Decode extension data (incomplete); reference: table 4.51.
2513 * @param cnt length of TYPE_FIL syntactic element in bytes
2515 * @return Returns number of bytes consumed
2517 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2518 ChannelElement *che, enum RawDataBlockType elem_type)
2522 int type = get_bits(gb, 4);
2524 if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2525 av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2527 switch (type) { // extension type
2528 case EXT_SBR_DATA_CRC:
2532 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2534 } else if (ac->oc[1].m4ac.frame_length_short) {
2535 if (!ac->warned_960_sbr)
2536 avpriv_report_missing_feature(ac->avctx,
2537 "SBR with 960 frame length");
2538 ac->warned_960_sbr = 1;
2539 skip_bits_long(gb, 8 * cnt - 4);
2541 } else if (!ac->oc[1].m4ac.sbr) {
2542 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2543 skip_bits_long(gb, 8 * cnt - 4);
2545 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2546 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2547 skip_bits_long(gb, 8 * cnt - 4);
2549 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2550 ac->oc[1].m4ac.sbr = 1;
2551 ac->oc[1].m4ac.ps = 1;
2552 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2553 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2554 ac->oc[1].status, 1);
2556 ac->oc[1].m4ac.sbr = 1;
2557 ac->avctx->profile = FF_PROFILE_AAC_HE;
2559 res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2561 case EXT_DYNAMIC_RANGE:
2562 res = decode_dynamic_range(&ac->che_drc, gb);
2565 decode_fill(ac, gb, 8 * cnt - 4);
2568 case EXT_DATA_ELEMENT:
2570 skip_bits_long(gb, 8 * cnt - 4);
2577 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2579 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2580 * @param coef spectral coefficients
2582 static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns,
2583 IndividualChannelStream *ics, int decode)
2585 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2587 int bottom, top, order, start, end, size, inc;
2588 INTFLOAT lpc[TNS_MAX_ORDER];
2589 INTFLOAT tmp[TNS_MAX_ORDER+1];
2590 UINTFLOAT *coef = coef_param;
2595 for (w = 0; w < ics->num_windows; w++) {
2596 bottom = ics->num_swb;
2597 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2599 bottom = FFMAX(0, top - tns->length[w][filt]);
2600 order = tns->order[w][filt];
2605 AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
2607 start = ics->swb_offset[FFMIN(bottom, mmm)];
2608 end = ics->swb_offset[FFMIN( top, mmm)];
2609 if ((size = end - start) <= 0)
2611 if (tns->direction[w][filt]) {
2621 for (m = 0; m < size; m++, start += inc)
2622 for (i = 1; i <= FFMIN(m, order); i++)
2623 coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]);
2626 for (m = 0; m < size; m++, start += inc) {
2627 tmp[0] = coef[start];
2628 for (i = 1; i <= FFMIN(m, order); i++)
2629 coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
2630 for (i = order; i > 0; i--)
2631 tmp[i] = tmp[i - 1];
2639 * Apply windowing and MDCT to obtain the spectral
2640 * coefficient from the predicted sample by LTP.
2642 static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
2643 INTFLOAT *in, IndividualChannelStream *ics)
2645 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2646 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2647 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2648 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2650 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2651 ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
2653 memset(in, 0, 448 * sizeof(*in));
2654 ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
2656 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2657 ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2659 ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2660 memset(in + 1024 + 576, 0, 448 * sizeof(*in));
2662 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2666 * Apply the long term prediction
2668 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2670 const LongTermPrediction *ltp = &sce->ics.ltp;
2671 const uint16_t *offsets = sce->ics.swb_offset;
2674 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2675 INTFLOAT *predTime = sce->ret;
2676 INTFLOAT *predFreq = ac->buf_mdct;
2677 int16_t num_samples = 2048;
2679 if (ltp->lag < 1024)
2680 num_samples = ltp->lag + 1024;
2681 for (i = 0; i < num_samples; i++)
2682 predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
2683 memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
2685 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2687 if (sce->tns.present)
2688 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2690 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2692 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2693 sce->coeffs[i] += (UINTFLOAT)predFreq[i];
2698 * Update the LTP buffer for next frame
2700 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2702 IndividualChannelStream *ics = &sce->ics;
2703 INTFLOAT *saved = sce->saved;
2704 INTFLOAT *saved_ltp = sce->coeffs;
2705 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2706 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2709 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2710 memcpy(saved_ltp, saved, 512 * sizeof(*saved_ltp));
2711 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2712 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2714 for (i = 0; i < 64; i++)
2715 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2716 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2717 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
2718 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2719 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2721 for (i = 0; i < 64; i++)
2722 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2723 } else { // LONG_STOP or ONLY_LONG
2724 ac->fdsp->vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2726 for (i = 0; i < 512; i++)
2727 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
2730 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2731 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2732 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2736 * Conduct IMDCT and windowing.
2738 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2740 IndividualChannelStream *ics = &sce->ics;
2741 INTFLOAT *in = sce->coeffs;
2742 INTFLOAT *out = sce->ret;
2743 INTFLOAT *saved = sce->saved;
2744 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2745 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2746 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2747 INTFLOAT *buf = ac->buf_mdct;
2748 INTFLOAT *temp = ac->temp;
2752 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2753 for (i = 0; i < 1024; i += 128)
2754 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2756 ac->mdct.imdct_half(&ac->mdct, buf, in);
2758 for (i=0; i<1024; i++)
2759 buf[i] = (buf[i] + 4LL) >> 3;
2760 #endif /* USE_FIXED */
2763 /* window overlapping
2764 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2765 * and long to short transitions are considered to be short to short
2766 * transitions. This leaves just two cases (long to long and short to short)
2767 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2769 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2770 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2771 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2773 memcpy( out, saved, 448 * sizeof(*out));
2775 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2776 ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2777 ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2778 ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2779 ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2780 ac->fdsp->vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2781 memcpy( out + 448 + 4*128, temp, 64 * sizeof(*out));
2783 ac->fdsp->vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2784 memcpy( out + 576, buf + 64, 448 * sizeof(*out));
2789 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2790 memcpy( saved, temp + 64, 64 * sizeof(*saved));
2791 ac->fdsp->vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2792 ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2793 ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2794 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2795 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2796 memcpy( saved, buf + 512, 448 * sizeof(*saved));
2797 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2798 } else { // LONG_STOP or ONLY_LONG
2799 memcpy( saved, buf + 512, 512 * sizeof(*saved));
2804 * Conduct IMDCT and windowing.
2806 static void imdct_and_windowing_960(AACContext *ac, SingleChannelElement *sce)
2809 IndividualChannelStream *ics = &sce->ics;
2810 INTFLOAT *in = sce->coeffs;
2811 INTFLOAT *out = sce->ret;
2812 INTFLOAT *saved = sce->saved;
2813 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2814 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_960) : AAC_RENAME(ff_sine_960);
2815 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2816 INTFLOAT *buf = ac->buf_mdct;
2817 INTFLOAT *temp = ac->temp;
2821 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2822 for (i = 0; i < 8; i++)
2823 ac->mdct120->imdct_half(ac->mdct120, buf + i * 120, in + i * 128, 1);
2825 ac->mdct960->imdct_half(ac->mdct960, buf, in, 1);
2828 /* window overlapping
2829 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2830 * and long to short transitions are considered to be short to short
2831 * transitions. This leaves just two cases (long to long and short to short)
2832 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2835 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2836 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2837 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 480);
2839 memcpy( out, saved, 420 * sizeof(*out));
2841 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2842 ac->fdsp->vector_fmul_window(out + 420 + 0*120, saved + 420, buf + 0*120, swindow_prev, 60);
2843 ac->fdsp->vector_fmul_window(out + 420 + 1*120, buf + 0*120 + 60, buf + 1*120, swindow, 60);
2844 ac->fdsp->vector_fmul_window(out + 420 + 2*120, buf + 1*120 + 60, buf + 2*120, swindow, 60);
2845 ac->fdsp->vector_fmul_window(out + 420 + 3*120, buf + 2*120 + 60, buf + 3*120, swindow, 60);
2846 ac->fdsp->vector_fmul_window(temp, buf + 3*120 + 60, buf + 4*120, swindow, 60);
2847 memcpy( out + 420 + 4*120, temp, 60 * sizeof(*out));
2849 ac->fdsp->vector_fmul_window(out + 420, saved + 420, buf, swindow_prev, 60);
2850 memcpy( out + 540, buf + 60, 420 * sizeof(*out));
2855 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2856 memcpy( saved, temp + 60, 60 * sizeof(*saved));
2857 ac->fdsp->vector_fmul_window(saved + 60, buf + 4*120 + 60, buf + 5*120, swindow, 60);
2858 ac->fdsp->vector_fmul_window(saved + 180, buf + 5*120 + 60, buf + 6*120, swindow, 60);
2859 ac->fdsp->vector_fmul_window(saved + 300, buf + 6*120 + 60, buf + 7*120, swindow, 60);
2860 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2861 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2862 memcpy( saved, buf + 480, 420 * sizeof(*saved));
2863 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2864 } else { // LONG_STOP or ONLY_LONG
2865 memcpy( saved, buf + 480, 480 * sizeof(*saved));
2869 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2871 IndividualChannelStream *ics = &sce->ics;
2872 INTFLOAT *in = sce->coeffs;
2873 INTFLOAT *out = sce->ret;
2874 INTFLOAT *saved = sce->saved;
2875 INTFLOAT *buf = ac->buf_mdct;
2878 #endif /* USE_FIXED */
2881 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2884 for (i = 0; i < 1024; i++)
2885 buf[i] = (buf[i] + 2) >> 2;
2886 #endif /* USE_FIXED */
2888 // window overlapping
2889 if (ics->use_kb_window[1]) {
2890 // AAC LD uses a low overlap sine window instead of a KBD window
2891 memcpy(out, saved, 192 * sizeof(*out));
2892 ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME(ff_sine_128), 64);
2893 memcpy( out + 320, buf + 64, 192 * sizeof(*out));
2895 ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME(ff_sine_512), 256);
2899 memcpy(saved, buf + 256, 256 * sizeof(*saved));
2902 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2904 INTFLOAT *in = sce->coeffs;
2905 INTFLOAT *out = sce->ret;
2906 INTFLOAT *saved = sce->saved;
2907 INTFLOAT *buf = ac->buf_mdct;
2909 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2910 const int n2 = n >> 1;
2911 const int n4 = n >> 2;
2912 const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
2913 AAC_RENAME(ff_aac_eld_window_512);
2915 // Inverse transform, mapped to the conventional IMDCT by
2916 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2917 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2918 // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2919 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2920 for (i = 0; i < n2; i+=2) {
2922 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2923 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2927 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1);
2930 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2933 for (i = 0; i < 1024; i++)
2934 buf[i] = (buf[i] + 1) >> 1;
2935 #endif /* USE_FIXED */
2937 for (i = 0; i < n; i+=2) {
2940 // Like with the regular IMDCT at this point we still have the middle half
2941 // of a transform but with even symmetry on the left and odd symmetry on
2944 // window overlapping
2945 // The spec says to use samples [0..511] but the reference decoder uses
2946 // samples [128..639].
2947 for (i = n4; i < n2; i ++) {
2948 out[i - n4] = AAC_MUL31( buf[ n2 - 1 - i] , window[i - n4]) +
2949 AAC_MUL31( saved[ i + n2] , window[i + n - n4]) +
2950 AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
2951 AAC_MUL31(-saved[ 2*n + n2 + i] , window[i + 3*n - n4]);
2953 for (i = 0; i < n2; i ++) {
2954 out[n4 + i] = AAC_MUL31( buf[ i] , window[i + n2 - n4]) +
2955 AAC_MUL31(-saved[ n - 1 - i] , window[i + n2 + n - n4]) +
2956 AAC_MUL31(-saved[ n + i] , window[i + n2 + 2*n - n4]) +
2957 AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
2959 for (i = 0; i < n4; i ++) {
2960 out[n2 + n4 + i] = AAC_MUL31( buf[ i + n2] , window[i + n - n4]) +
2961 AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
2962 AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
2966 memmove(saved + n, saved, 2 * n * sizeof(*saved));
2967 memcpy( saved, buf, n * sizeof(*saved));
2971 * channel coupling transformation interface
2973 * @param apply_coupling_method pointer to (in)dependent coupling function
2975 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2976 enum RawDataBlockType type, int elem_id,
2977 enum CouplingPoint coupling_point,
2978 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2982 for (i = 0; i < MAX_ELEM_ID; i++) {
2983 ChannelElement *cce = ac->che[TYPE_CCE][i];
2986 if (cce && cce->coup.coupling_point == coupling_point) {
2987 ChannelCoupling *coup = &cce->coup;
2989 for (c = 0; c <= coup->num_coupled; c++) {
2990 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2991 if (coup->ch_select[c] != 1) {
2992 apply_coupling_method(ac, &cc->ch[0], cce, index);
2993 if (coup->ch_select[c] != 0)
2996 if (coup->ch_select[c] != 2)
2997 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2999 index += 1 + (coup->ch_select[c] == 3);
3006 * Convert spectral data to samples, applying all supported tools as appropriate.
3008 static void spectral_to_sample(AACContext *ac, int samples)
3011 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
3012 switch (ac->oc[1].m4ac.object_type) {
3014 imdct_and_window = imdct_and_windowing_ld;
3016 case AOT_ER_AAC_ELD:
3017 imdct_and_window = imdct_and_windowing_eld;
3020 if (ac->oc[1].m4ac.frame_length_short)
3021 imdct_and_window = imdct_and_windowing_960;
3023 imdct_and_window = ac->imdct_and_windowing;
3025 for (type = 3; type >= 0; type--) {
3026 for (i = 0; i < MAX_ELEM_ID; i++) {
3027 ChannelElement *che = ac->che[type][i];
3028 if (che && che->present) {
3029 if (type <= TYPE_CPE)
3030 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
3031 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
3032 if (che->ch[0].ics.predictor_present) {
3033 if (che->ch[0].ics.ltp.present)
3034 ac->apply_ltp(ac, &che->ch[0]);
3035 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
3036 ac->apply_ltp(ac, &che->ch[1]);
3039 if (che->ch[0].tns.present)
3040 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
3041 if (che->ch[1].tns.present)
3042 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
3043 if (type <= TYPE_CPE)
3044 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
3045 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
3046 imdct_and_window(ac, &che->ch[0]);
3047 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3048 ac->update_ltp(ac, &che->ch[0]);
3049 if (type == TYPE_CPE) {
3050 imdct_and_window(ac, &che->ch[1]);
3051 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3052 ac->update_ltp(ac, &che->ch[1]);
3054 if (ac->oc[1].m4ac.sbr > 0) {
3055 AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
3058 if (type <= TYPE_CCE)
3059 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
3064 /* preparation for resampler */
3065 for(j = 0; j<samples; j++){
3066 che->ch[0].ret[j] = (int32_t)av_clip64((int64_t)che->ch[0].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3067 if(type == TYPE_CPE)
3068 che->ch[1].ret[j] = (int32_t)av_clip64((int64_t)che->ch[1].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3071 #endif /* USE_FIXED */
3074 av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
3080 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
3083 AACADTSHeaderInfo hdr_info;
3084 uint8_t layout_map[MAX_ELEM_ID*4][3];
3085 int layout_map_tags, ret;
3087 size = ff_adts_header_parse(gb, &hdr_info);
3089 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
3090 // This is 2 for "VLB " audio in NSV files.
3091 // See samples/nsv/vlb_audio.
3092 avpriv_report_missing_feature(ac->avctx,
3093 "More than one AAC RDB per ADTS frame");
3094 ac->warned_num_aac_frames = 1;
3096 push_output_configuration(ac);
3097 if (hdr_info.chan_config) {
3098 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
3099 if ((ret = set_default_channel_config(ac, ac->avctx,
3102 hdr_info.chan_config)) < 0)
3104 if ((ret = output_configure(ac, layout_map, layout_map_tags,
3105 FFMAX(ac->oc[1].status,
3106 OC_TRIAL_FRAME), 0)) < 0)
3109 ac->oc[1].m4ac.chan_config = 0;
3111 * dual mono frames in Japanese DTV can have chan_config 0
3112 * WITHOUT specifying PCE.
3113 * thus, set dual mono as default.
3115 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
3116 layout_map_tags = 2;
3117 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
3118 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
3119 layout_map[0][1] = 0;
3120 layout_map[1][1] = 1;
3121 if (output_configure(ac, layout_map, layout_map_tags,
3126 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
3127 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
3128 ac->oc[1].m4ac.object_type = hdr_info.object_type;
3129 ac->oc[1].m4ac.frame_length_short = 0;
3130 if (ac->oc[0].status != OC_LOCKED ||
3131 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
3132 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
3133 ac->oc[1].m4ac.sbr = -1;
3134 ac->oc[1].m4ac.ps = -1;
3136 if (!hdr_info.crc_absent)
3142 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
3143 int *got_frame_ptr, GetBitContext *gb)
3145 AACContext *ac = avctx->priv_data;
3146 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
3147 ChannelElement *che;
3149 int samples = m4ac->frame_length_short ? 960 : 1024;
3150 int chan_config = m4ac->chan_config;
3151 int aot = m4ac->object_type;
3153 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
3158 if ((err = frame_configure_elements(avctx)) < 0)
3161 // The FF_PROFILE_AAC_* defines are all object_type - 1
3162 // This may lead to an undefined profile being signaled
3163 ac->avctx->profile = aot - 1;
3165 ac->tags_mapped = 0;
3167 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
3168 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
3170 return AVERROR_INVALIDDATA;
3172 for (i = 0; i < tags_per_config[chan_config]; i++) {
3173 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
3174 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
3175 if (!(che=get_che(ac, elem_type, elem_id))) {
3176 av_log(ac->avctx, AV_LOG_ERROR,
3177 "channel element %d.%d is not allocated\n",
3178 elem_type, elem_id);
3179 return AVERROR_INVALIDDATA;
3182 if (aot != AOT_ER_AAC_ELD)
3184 switch (elem_type) {
3186 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3189 err = decode_cpe(ac, gb, che);
3192 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3199 spectral_to_sample(ac, samples);
3201 if (!ac->frame->data[0] && samples) {
3202 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3203 return AVERROR_INVALIDDATA;
3206 ac->frame->nb_samples = samples;
3207 ac->frame->sample_rate = avctx->sample_rate;
3210 skip_bits_long(gb, get_bits_left(gb));
3214 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
3215 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
3217 AACContext *ac = avctx->priv_data;
3218 ChannelElement *che = NULL, *che_prev = NULL;
3219 enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
3221 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
3222 int is_dmono, sce_count = 0;
3223 int payload_alignment;
3224 uint8_t che_presence[4][MAX_ELEM_ID] = {{0}};
3228 if (show_bits(gb, 12) == 0xfff) {
3229 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
3230 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
3233 if (ac->oc[1].m4ac.sampling_index > 12) {
3234 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
3235 err = AVERROR_INVALIDDATA;
3240 if ((err = frame_configure_elements(avctx)) < 0)
3243 // The FF_PROFILE_AAC_* defines are all object_type - 1
3244 // This may lead to an undefined profile being signaled
3245 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
3247 payload_alignment = get_bits_count(gb);
3248 ac->tags_mapped = 0;
3250 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
3251 elem_id = get_bits(gb, 4);
3253 if (avctx->debug & FF_DEBUG_STARTCODE)
3254 av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
3256 if (!avctx->channels && elem_type != TYPE_PCE) {
3257 err = AVERROR_INVALIDDATA;
3261 if (elem_type < TYPE_DSE) {
3262 if (che_presence[elem_type][elem_id]) {
3263 int error = che_presence[elem_type][elem_id] > 1;
3264 av_log(ac->avctx, error ? AV_LOG_ERROR : AV_LOG_DEBUG, "channel element %d.%d duplicate\n",
3265 elem_type, elem_id);
3267 err = AVERROR_INVALIDDATA;
3271 che_presence[elem_type][elem_id]++;
3273 if (!(che=get_che(ac, elem_type, elem_id))) {
3274 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
3275 elem_type, elem_id);
3276 err = AVERROR_INVALIDDATA;
3279 samples = ac->oc[1].m4ac.frame_length_short ? 960 : 1024;
3283 switch (elem_type) {
3286 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3292 err = decode_cpe(ac, gb, che);
3297 err = decode_cce(ac, gb, che);
3301 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3306 err = skip_data_stream_element(ac, gb);
3310 uint8_t layout_map[MAX_ELEM_ID*4][3] = {{0}};
3313 int pushed = push_output_configuration(ac);
3314 if (pce_found && !pushed) {
3315 err = AVERROR_INVALIDDATA;
3319 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
3326 av_log(avctx, AV_LOG_ERROR,
3327 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
3328 pop_output_configuration(ac);
3330 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
3332 ac->oc[1].m4ac.chan_config = 0;
3340 elem_id += get_bits(gb, 8) - 1;
3341 if (get_bits_left(gb) < 8 * elem_id) {
3342 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3343 err = AVERROR_INVALIDDATA;
3347 while (elem_id > 0) {
3348 int ret = decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
3358 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3362 if (elem_type < TYPE_DSE) {
3364 che_prev_type = elem_type;
3370 if (get_bits_left(gb) < 3) {
3371 av_log(avctx, AV_LOG_ERROR, overread_err);
3372 err = AVERROR_INVALIDDATA;
3377 if (!avctx->channels) {
3382 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3383 samples <<= multiplier;
3385 spectral_to_sample(ac, samples);
3387 if (ac->oc[1].status && audio_found) {
3388 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3389 avctx->frame_size = samples;
3390 ac->oc[1].status = OC_LOCKED;
3394 avctx->internal->skip_samples_multiplier = 2;
3396 if (!ac->frame->data[0] && samples) {
3397 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3398 err = AVERROR_INVALIDDATA;
3403 ac->frame->nb_samples = samples;
3404 ac->frame->sample_rate = avctx->sample_rate;
3406 av_frame_unref(ac->frame);
3407 *got_frame_ptr = !!samples;
3409 /* for dual-mono audio (SCE + SCE) */
3410 is_dmono = ac->dmono_mode && sce_count == 2 &&
3411 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
3413 if (ac->dmono_mode == 1)
3414 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3415 else if (ac->dmono_mode == 2)
3416 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3421 pop_output_configuration(ac);
3425 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3426 int *got_frame_ptr, AVPacket *avpkt)
3428 AACContext *ac = avctx->priv_data;
3429 const uint8_t *buf = avpkt->data;
3430 int buf_size = avpkt->size;
3435 int new_extradata_size;
3436 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3437 AV_PKT_DATA_NEW_EXTRADATA,
3438 &new_extradata_size);
3439 int jp_dualmono_size;
3440 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3441 AV_PKT_DATA_JP_DUALMONO,
3444 if (new_extradata) {
3445 /* discard previous configuration */
3446 ac->oc[1].status = OC_NONE;
3447 err = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3449 new_extradata_size * 8LL, 1);
3456 if (jp_dualmono && jp_dualmono_size > 0)
3457 ac->dmono_mode = 1 + *jp_dualmono;
3458 if (ac->force_dmono_mode >= 0)
3459 ac->dmono_mode = ac->force_dmono_mode;
3461 if (INT_MAX / 8 <= buf_size)
3462 return AVERROR_INVALIDDATA;
3464 if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)
3467 switch (ac->oc[1].m4ac.object_type) {
3469 case AOT_ER_AAC_LTP:
3471 case AOT_ER_AAC_ELD:
3472 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3475 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3480 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3481 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3482 if (buf[buf_offset])
3485 return buf_size > buf_offset ? buf_consumed : buf_size;
3488 static av_cold int aac_decode_close(AVCodecContext *avctx)
3490 AACContext *ac = avctx->priv_data;
3493 for (i = 0; i < MAX_ELEM_ID; i++) {
3494 for (type = 0; type < 4; type++) {
3495 if (ac->che[type][i])
3496 AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][i]->sbr);
3497 av_freep(&ac->che[type][i]);
3501 ff_mdct_end(&ac->mdct);
3502 ff_mdct_end(&ac->mdct_small);
3503 ff_mdct_end(&ac->mdct_ld);
3504 ff_mdct_end(&ac->mdct_ltp);
3506 ff_mdct15_uninit(&ac->mdct120);
3507 ff_mdct15_uninit(&ac->mdct480);
3508 ff_mdct15_uninit(&ac->mdct960);
3510 av_freep(&ac->fdsp);
3514 static void aacdec_init(AACContext *c)
3516 c->imdct_and_windowing = imdct_and_windowing;
3517 c->apply_ltp = apply_ltp;
3518 c->apply_tns = apply_tns;
3519 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3520 c->update_ltp = update_ltp;
3522 c->vector_pow43 = vector_pow43;
3523 c->subband_scale = subband_scale;
3528 ff_aacdec_init_mips(c);
3529 #endif /* !USE_FIXED */
3532 * AVOptions for Japanese DTV specific extensions (ADTS only)
3534 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3535 static const AVOption options[] = {
3536 {"dual_mono_mode", "Select the channel to decode for dual mono",
3537 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3538 AACDEC_FLAGS, "dual_mono_mode"},
3540 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3541 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3542 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3543 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3548 static const AVClass aac_decoder_class = {
3549 .class_name = "AAC decoder",
3550 .item_name = av_default_item_name,
3552 .version = LIBAVUTIL_VERSION_INT,