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) {
643 layout_map[2][2] = AAC_CHANNEL_SIDE;
645 if (!ac || !ac->warned_71_wide++) {
646 av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
647 " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
648 " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
655 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
657 /* For PCE based channel configurations map the channels solely based
659 if (!ac->oc[1].m4ac.chan_config) {
660 return ac->tag_che_map[type][elem_id];
662 // Allow single CPE stereo files to be signalled with mono configuration.
663 if (!ac->tags_mapped && type == TYPE_CPE &&
664 ac->oc[1].m4ac.chan_config == 1) {
665 uint8_t layout_map[MAX_ELEM_ID*4][3];
667 push_output_configuration(ac);
669 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
671 if (set_default_channel_config(ac, ac->avctx, layout_map,
672 &layout_map_tags, 2) < 0)
674 if (output_configure(ac, layout_map, layout_map_tags,
675 OC_TRIAL_FRAME, 1) < 0)
678 ac->oc[1].m4ac.chan_config = 2;
679 ac->oc[1].m4ac.ps = 0;
682 if (!ac->tags_mapped && type == TYPE_SCE &&
683 ac->oc[1].m4ac.chan_config == 2) {
684 uint8_t layout_map[MAX_ELEM_ID * 4][3];
686 push_output_configuration(ac);
688 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
690 if (set_default_channel_config(ac, ac->avctx, layout_map,
691 &layout_map_tags, 1) < 0)
693 if (output_configure(ac, layout_map, layout_map_tags,
694 OC_TRIAL_FRAME, 1) < 0)
697 ac->oc[1].m4ac.chan_config = 1;
698 if (ac->oc[1].m4ac.sbr)
699 ac->oc[1].m4ac.ps = -1;
701 /* For indexed channel configurations map the channels solely based
703 switch (ac->oc[1].m4ac.chan_config) {
705 if (ac->tags_mapped > 3 && ((type == TYPE_CPE && elem_id < 8) ||
706 (type == TYPE_SCE && elem_id < 6) ||
707 (type == TYPE_LFE && elem_id < 2))) {
709 return ac->tag_che_map[type][elem_id] = ac->che[type][elem_id];
713 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
715 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
718 if (ac->tags_mapped == 2 &&
719 ac->oc[1].m4ac.chan_config == 11 &&
722 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
725 /* Some streams incorrectly code 5.1 audio as
726 * SCE[0] CPE[0] CPE[1] SCE[1]
728 * SCE[0] CPE[0] CPE[1] LFE[0].
729 * If we seem to have encountered such a stream, transfer
730 * the LFE[0] element to the SCE[1]'s mapping */
731 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
732 if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
733 av_log(ac->avctx, AV_LOG_WARNING,
734 "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
735 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
736 ac->warned_remapping_once++;
739 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
742 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
744 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
747 /* Some streams incorrectly code 4.0 audio as
748 * SCE[0] CPE[0] LFE[0]
750 * SCE[0] CPE[0] SCE[1].
751 * If we seem to have encountered such a stream, transfer
752 * the SCE[1] element to the LFE[0]'s mapping */
753 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
754 if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
755 av_log(ac->avctx, AV_LOG_WARNING,
756 "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
757 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
758 ac->warned_remapping_once++;
761 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
763 if (ac->tags_mapped == 2 &&
764 ac->oc[1].m4ac.chan_config == 4 &&
767 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
771 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
774 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
775 } else if (ac->oc[1].m4ac.chan_config == 2) {
779 if (!ac->tags_mapped && type == TYPE_SCE) {
781 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
789 * Decode an array of 4 bit element IDs, optionally interleaved with a
790 * stereo/mono switching bit.
792 * @param type speaker type/position for these channels
794 static void decode_channel_map(uint8_t layout_map[][3],
795 enum ChannelPosition type,
796 GetBitContext *gb, int n)
799 enum RawDataBlockType syn_ele;
801 case AAC_CHANNEL_FRONT:
802 case AAC_CHANNEL_BACK:
803 case AAC_CHANNEL_SIDE:
804 syn_ele = get_bits1(gb);
810 case AAC_CHANNEL_LFE:
814 // AAC_CHANNEL_OFF has no channel map
817 layout_map[0][0] = syn_ele;
818 layout_map[0][1] = get_bits(gb, 4);
819 layout_map[0][2] = type;
824 static inline void relative_align_get_bits(GetBitContext *gb,
825 int reference_position) {
826 int n = (reference_position - get_bits_count(gb) & 7);
832 * Decode program configuration element; reference: table 4.2.
834 * @return Returns error status. 0 - OK, !0 - error
836 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
837 uint8_t (*layout_map)[3],
838 GetBitContext *gb, int byte_align_ref)
840 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
845 skip_bits(gb, 2); // object_type
847 sampling_index = get_bits(gb, 4);
848 if (m4ac->sampling_index != sampling_index)
849 av_log(avctx, AV_LOG_WARNING,
850 "Sample rate index in program config element does not "
851 "match the sample rate index configured by the container.\n");
853 num_front = get_bits(gb, 4);
854 num_side = get_bits(gb, 4);
855 num_back = get_bits(gb, 4);
856 num_lfe = get_bits(gb, 2);
857 num_assoc_data = get_bits(gb, 3);
858 num_cc = get_bits(gb, 4);
861 skip_bits(gb, 4); // mono_mixdown_tag
863 skip_bits(gb, 4); // stereo_mixdown_tag
866 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
868 if (get_bits_left(gb) < 5 * (num_front + num_side + num_back + num_cc) + 4 *(num_lfe + num_assoc_data + num_cc)) {
869 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
872 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
874 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
876 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
878 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
881 skip_bits_long(gb, 4 * num_assoc_data);
883 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
886 relative_align_get_bits(gb, byte_align_ref);
888 /* comment field, first byte is length */
889 comment_len = get_bits(gb, 8) * 8;
890 if (get_bits_left(gb) < comment_len) {
891 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
892 return AVERROR_INVALIDDATA;
894 skip_bits_long(gb, comment_len);
899 * Decode GA "General Audio" specific configuration; reference: table 4.1.
901 * @param ac pointer to AACContext, may be null
902 * @param avctx pointer to AVCCodecContext, used for logging
904 * @return Returns error status. 0 - OK, !0 - error
906 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
908 int get_bit_alignment,
909 MPEG4AudioConfig *m4ac,
912 int extension_flag, ret, ep_config, res_flags;
913 uint8_t layout_map[MAX_ELEM_ID*4][3];
917 if (get_bits1(gb)) { // frameLengthFlag
918 avpriv_report_missing_feature(avctx, "Fixed point 960/120 MDCT window");
919 return AVERROR_PATCHWELCOME;
921 m4ac->frame_length_short = 0;
923 m4ac->frame_length_short = get_bits1(gb);
924 if (m4ac->frame_length_short && m4ac->sbr == 1) {
925 avpriv_report_missing_feature(avctx, "SBR with 960 frame length");
926 if (ac) ac->warned_960_sbr = 1;
932 if (get_bits1(gb)) // dependsOnCoreCoder
933 skip_bits(gb, 14); // coreCoderDelay
934 extension_flag = get_bits1(gb);
936 if (m4ac->object_type == AOT_AAC_SCALABLE ||
937 m4ac->object_type == AOT_ER_AAC_SCALABLE)
938 skip_bits(gb, 3); // layerNr
940 if (channel_config == 0) {
941 skip_bits(gb, 4); // element_instance_tag
942 tags = decode_pce(avctx, m4ac, layout_map, gb, get_bit_alignment);
946 if ((ret = set_default_channel_config(ac, avctx, layout_map,
947 &tags, channel_config)))
951 if (count_channels(layout_map, tags) > 1) {
953 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
956 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
959 if (extension_flag) {
960 switch (m4ac->object_type) {
962 skip_bits(gb, 5); // numOfSubFrame
963 skip_bits(gb, 11); // layer_length
967 case AOT_ER_AAC_SCALABLE:
969 res_flags = get_bits(gb, 3);
971 avpriv_report_missing_feature(avctx,
972 "AAC data resilience (flags %x)",
974 return AVERROR_PATCHWELCOME;
978 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
980 switch (m4ac->object_type) {
983 case AOT_ER_AAC_SCALABLE:
985 ep_config = get_bits(gb, 2);
987 avpriv_report_missing_feature(avctx,
988 "epConfig %d", ep_config);
989 return AVERROR_PATCHWELCOME;
995 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
997 MPEG4AudioConfig *m4ac,
1000 int ret, ep_config, res_flags;
1001 uint8_t layout_map[MAX_ELEM_ID*4][3];
1003 const int ELDEXT_TERM = 0;
1008 if (get_bits1(gb)) { // frameLengthFlag
1009 avpriv_request_sample(avctx, "960/120 MDCT window");
1010 return AVERROR_PATCHWELCOME;
1013 m4ac->frame_length_short = get_bits1(gb);
1015 res_flags = get_bits(gb, 3);
1017 avpriv_report_missing_feature(avctx,
1018 "AAC data resilience (flags %x)",
1020 return AVERROR_PATCHWELCOME;
1023 if (get_bits1(gb)) { // ldSbrPresentFlag
1024 avpriv_report_missing_feature(avctx,
1026 return AVERROR_PATCHWELCOME;
1029 while (get_bits(gb, 4) != ELDEXT_TERM) {
1030 int len = get_bits(gb, 4);
1032 len += get_bits(gb, 8);
1033 if (len == 15 + 255)
1034 len += get_bits(gb, 16);
1035 if (get_bits_left(gb) < len * 8 + 4) {
1036 av_log(avctx, AV_LOG_ERROR, overread_err);
1037 return AVERROR_INVALIDDATA;
1039 skip_bits_long(gb, 8 * len);
1042 if ((ret = set_default_channel_config(ac, avctx, layout_map,
1043 &tags, channel_config)))
1046 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
1049 ep_config = get_bits(gb, 2);
1051 avpriv_report_missing_feature(avctx,
1052 "epConfig %d", ep_config);
1053 return AVERROR_PATCHWELCOME;
1059 * Decode audio specific configuration; reference: table 1.13.
1061 * @param ac pointer to AACContext, may be null
1062 * @param avctx pointer to AVCCodecContext, used for logging
1063 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
1064 * @param gb buffer holding an audio specific config
1065 * @param get_bit_alignment relative alignment for byte align operations
1066 * @param sync_extension look for an appended sync extension
1068 * @return Returns error status or number of consumed bits. <0 - error
1070 static int decode_audio_specific_config_gb(AACContext *ac,
1071 AVCodecContext *avctx,
1072 MPEG4AudioConfig *m4ac,
1074 int get_bit_alignment,
1078 GetBitContext gbc = *gb;
1080 if ((i = ff_mpeg4audio_get_config_gb(m4ac, &gbc, sync_extension, avctx)) < 0)
1081 return AVERROR_INVALIDDATA;
1083 if (m4ac->sampling_index > 12) {
1084 av_log(avctx, AV_LOG_ERROR,
1085 "invalid sampling rate index %d\n",
1086 m4ac->sampling_index);
1087 return AVERROR_INVALIDDATA;
1089 if (m4ac->object_type == AOT_ER_AAC_LD &&
1090 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
1091 av_log(avctx, AV_LOG_ERROR,
1092 "invalid low delay sampling rate index %d\n",
1093 m4ac->sampling_index);
1094 return AVERROR_INVALIDDATA;
1097 skip_bits_long(gb, i);
1099 switch (m4ac->object_type) {
1106 if ((ret = decode_ga_specific_config(ac, avctx, gb, get_bit_alignment,
1107 m4ac, m4ac->chan_config)) < 0)
1110 case AOT_ER_AAC_ELD:
1111 if ((ret = decode_eld_specific_config(ac, avctx, gb,
1112 m4ac, m4ac->chan_config)) < 0)
1116 avpriv_report_missing_feature(avctx,
1117 "Audio object type %s%d",
1118 m4ac->sbr == 1 ? "SBR+" : "",
1120 return AVERROR(ENOSYS);
1124 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1125 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1126 m4ac->sample_rate, m4ac->sbr,
1129 return get_bits_count(gb);
1132 static int decode_audio_specific_config(AACContext *ac,
1133 AVCodecContext *avctx,
1134 MPEG4AudioConfig *m4ac,
1135 const uint8_t *data, int64_t bit_size,
1141 if (bit_size < 0 || bit_size > INT_MAX) {
1142 av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
1143 return AVERROR_INVALIDDATA;
1146 ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
1147 for (i = 0; i < bit_size >> 3; i++)
1148 ff_dlog(avctx, "%02x ", data[i]);
1149 ff_dlog(avctx, "\n");
1151 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
1154 return decode_audio_specific_config_gb(ac, avctx, m4ac, &gb, 0,
1159 * linear congruential pseudorandom number generator
1161 * @param previous_val pointer to the current state of the generator
1163 * @return Returns a 32-bit pseudorandom integer
1165 static av_always_inline int lcg_random(unsigned previous_val)
1167 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1171 static void reset_all_predictors(PredictorState *ps)
1174 for (i = 0; i < MAX_PREDICTORS; i++)
1175 reset_predict_state(&ps[i]);
1178 static int sample_rate_idx (int rate)
1180 if (92017 <= rate) return 0;
1181 else if (75132 <= rate) return 1;
1182 else if (55426 <= rate) return 2;
1183 else if (46009 <= rate) return 3;
1184 else if (37566 <= rate) return 4;
1185 else if (27713 <= rate) return 5;
1186 else if (23004 <= rate) return 6;
1187 else if (18783 <= rate) return 7;
1188 else if (13856 <= rate) return 8;
1189 else if (11502 <= rate) return 9;
1190 else if (9391 <= rate) return 10;
1194 static void reset_predictor_group(PredictorState *ps, int group_num)
1197 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1198 reset_predict_state(&ps[i]);
1201 static void aacdec_init(AACContext *ac);
1203 static av_cold void aac_static_table_init(void)
1205 static VLC_TYPE vlc_buf[304 + 270 + 550 + 300 + 328 +
1206 294 + 306 + 268 + 510 + 366 + 462][2];
1207 for (unsigned i = 0, offset = 0; i < 11; i++) {
1208 vlc_spectral[i].table = &vlc_buf[offset];
1209 vlc_spectral[i].table_allocated = FF_ARRAY_ELEMS(vlc_buf) - offset;
1210 ff_init_vlc_sparse(&vlc_spectral[i], 8, ff_aac_spectral_sizes[i],
1211 ff_aac_spectral_bits[i], sizeof(ff_aac_spectral_bits[i][0]),
1212 sizeof(ff_aac_spectral_bits[i][0]),
1213 ff_aac_spectral_codes[i], sizeof(ff_aac_spectral_codes[i][0]),
1214 sizeof(ff_aac_spectral_codes[i][0]),
1215 ff_aac_codebook_vector_idx[i], sizeof(ff_aac_codebook_vector_idx[i][0]),
1216 sizeof(ff_aac_codebook_vector_idx[i][0]),
1217 INIT_VLC_STATIC_OVERLONG);
1218 offset += vlc_spectral[i].table_size;
1221 AAC_RENAME(ff_aac_sbr_init)();
1225 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1226 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1227 ff_aac_scalefactor_bits,
1228 sizeof(ff_aac_scalefactor_bits[0]),
1229 sizeof(ff_aac_scalefactor_bits[0]),
1230 ff_aac_scalefactor_code,
1231 sizeof(ff_aac_scalefactor_code[0]),
1232 sizeof(ff_aac_scalefactor_code[0]),
1235 // window initialization
1237 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(aac_kbd_long_960), 4.0, 960);
1238 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(aac_kbd_short_120), 6.0, 120);
1239 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(sine_960), 960);
1240 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(sine_120), 120);
1241 AAC_RENAME(ff_init_ff_sine_windows)(9);
1242 ff_aac_float_common_init();
1244 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME2(aac_kbd_long_1024), 4.0, 1024);
1245 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME2(aac_kbd_short_128), 6.0, 128);
1246 init_sine_windows_fixed();
1249 AAC_RENAME(ff_cbrt_tableinit)();
1252 static AVOnce aac_table_init = AV_ONCE_INIT;
1254 static av_cold int aac_decode_init(AVCodecContext *avctx)
1256 AACContext *ac = avctx->priv_data;
1259 if (avctx->sample_rate > 96000)
1260 return AVERROR_INVALIDDATA;
1262 ret = ff_thread_once(&aac_table_init, &aac_static_table_init);
1264 return AVERROR_UNKNOWN;
1267 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1271 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1273 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1274 #endif /* USE_FIXED */
1276 if (avctx->extradata_size > 0) {
1277 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1279 avctx->extradata_size * 8LL,
1284 uint8_t layout_map[MAX_ELEM_ID*4][3];
1285 int layout_map_tags;
1287 sr = sample_rate_idx(avctx->sample_rate);
1288 ac->oc[1].m4ac.sampling_index = sr;
1289 ac->oc[1].m4ac.channels = avctx->channels;
1290 ac->oc[1].m4ac.sbr = -1;
1291 ac->oc[1].m4ac.ps = -1;
1293 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1294 if (ff_mpeg4audio_channels[i] == avctx->channels)
1296 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1299 ac->oc[1].m4ac.chan_config = i;
1301 if (ac->oc[1].m4ac.chan_config) {
1302 int ret = set_default_channel_config(ac, avctx, layout_map,
1303 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1305 output_configure(ac, layout_map, layout_map_tags,
1307 else if (avctx->err_recognition & AV_EF_EXPLODE)
1308 return AVERROR_INVALIDDATA;
1312 if (avctx->channels > MAX_CHANNELS) {
1313 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1314 return AVERROR_INVALIDDATA;
1318 ac->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1320 ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1321 #endif /* USE_FIXED */
1323 return AVERROR(ENOMEM);
1326 ac->random_state = 0x1f2e3d4c;
1328 AAC_RENAME_32(ff_mdct_init)(&ac->mdct, 11, 1, 1.0 / RANGE15(1024.0));
1329 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ld, 10, 1, 1.0 / RANGE15(512.0));
1330 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_small, 8, 1, 1.0 / RANGE15(128.0));
1331 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ltp, 11, 0, RANGE15(-2.0));
1333 ret = ff_mdct15_init(&ac->mdct120, 1, 3, 1.0f/(16*1024*120*2));
1336 ret = ff_mdct15_init(&ac->mdct480, 1, 5, 1.0f/(16*1024*960));
1339 ret = ff_mdct15_init(&ac->mdct960, 1, 6, 1.0f/(16*1024*960*2));
1348 * Skip data_stream_element; reference: table 4.10.
1350 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1352 int byte_align = get_bits1(gb);
1353 int count = get_bits(gb, 8);
1355 count += get_bits(gb, 8);
1359 if (get_bits_left(gb) < 8 * count) {
1360 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1361 return AVERROR_INVALIDDATA;
1363 skip_bits_long(gb, 8 * count);
1367 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1371 if (get_bits1(gb)) {
1372 ics->predictor_reset_group = get_bits(gb, 5);
1373 if (ics->predictor_reset_group == 0 ||
1374 ics->predictor_reset_group > 30) {
1375 av_log(ac->avctx, AV_LOG_ERROR,
1376 "Invalid Predictor Reset Group.\n");
1377 return AVERROR_INVALIDDATA;
1380 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1381 ics->prediction_used[sfb] = get_bits1(gb);
1387 * Decode Long Term Prediction data; reference: table 4.xx.
1389 static void decode_ltp(LongTermPrediction *ltp,
1390 GetBitContext *gb, uint8_t max_sfb)
1394 ltp->lag = get_bits(gb, 11);
1395 ltp->coef = ltp_coef[get_bits(gb, 3)];
1396 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1397 ltp->used[sfb] = get_bits1(gb);
1401 * Decode Individual Channel Stream info; reference: table 4.6.
1403 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1406 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1407 const int aot = m4ac->object_type;
1408 const int sampling_index = m4ac->sampling_index;
1409 int ret_fail = AVERROR_INVALIDDATA;
1411 if (aot != AOT_ER_AAC_ELD) {
1412 if (get_bits1(gb)) {
1413 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1414 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1415 return AVERROR_INVALIDDATA;
1417 ics->window_sequence[1] = ics->window_sequence[0];
1418 ics->window_sequence[0] = get_bits(gb, 2);
1419 if (aot == AOT_ER_AAC_LD &&
1420 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1421 av_log(ac->avctx, AV_LOG_ERROR,
1422 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1423 "window sequence %d found.\n", ics->window_sequence[0]);
1424 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1425 return AVERROR_INVALIDDATA;
1427 ics->use_kb_window[1] = ics->use_kb_window[0];
1428 ics->use_kb_window[0] = get_bits1(gb);
1430 ics->num_window_groups = 1;
1431 ics->group_len[0] = 1;
1432 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1434 ics->max_sfb = get_bits(gb, 4);
1435 for (i = 0; i < 7; i++) {
1436 if (get_bits1(gb)) {
1437 ics->group_len[ics->num_window_groups - 1]++;
1439 ics->num_window_groups++;
1440 ics->group_len[ics->num_window_groups - 1] = 1;
1443 ics->num_windows = 8;
1444 if (m4ac->frame_length_short) {
1445 ics->swb_offset = ff_swb_offset_120[sampling_index];
1446 ics->num_swb = ff_aac_num_swb_120[sampling_index];
1448 ics->swb_offset = ff_swb_offset_128[sampling_index];
1449 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1451 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
1452 ics->predictor_present = 0;
1454 ics->max_sfb = get_bits(gb, 6);
1455 ics->num_windows = 1;
1456 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1457 if (m4ac->frame_length_short) {
1458 ics->swb_offset = ff_swb_offset_480[sampling_index];
1459 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1460 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1462 ics->swb_offset = ff_swb_offset_512[sampling_index];
1463 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1464 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1466 if (!ics->num_swb || !ics->swb_offset) {
1467 ret_fail = AVERROR_BUG;
1471 if (m4ac->frame_length_short) {
1472 ics->num_swb = ff_aac_num_swb_960[sampling_index];
1473 ics->swb_offset = ff_swb_offset_960[sampling_index];
1475 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1476 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1478 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1480 if (aot != AOT_ER_AAC_ELD) {
1481 ics->predictor_present = get_bits1(gb);
1482 ics->predictor_reset_group = 0;
1484 if (ics->predictor_present) {
1485 if (aot == AOT_AAC_MAIN) {
1486 if (decode_prediction(ac, ics, gb)) {
1489 } else if (aot == AOT_AAC_LC ||
1490 aot == AOT_ER_AAC_LC) {
1491 av_log(ac->avctx, AV_LOG_ERROR,
1492 "Prediction is not allowed in AAC-LC.\n");
1495 if (aot == AOT_ER_AAC_LD) {
1496 av_log(ac->avctx, AV_LOG_ERROR,
1497 "LTP in ER AAC LD not yet implemented.\n");
1498 ret_fail = AVERROR_PATCHWELCOME;
1501 if ((ics->ltp.present = get_bits(gb, 1)))
1502 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1507 if (ics->max_sfb > ics->num_swb) {
1508 av_log(ac->avctx, AV_LOG_ERROR,
1509 "Number of scalefactor bands in group (%d) "
1510 "exceeds limit (%d).\n",
1511 ics->max_sfb, ics->num_swb);
1522 * Decode band types (section_data payload); reference: table 4.46.
1524 * @param band_type array of the used band type
1525 * @param band_type_run_end array of the last scalefactor band of a band type run
1527 * @return Returns error status. 0 - OK, !0 - error
1529 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1530 int band_type_run_end[120], GetBitContext *gb,
1531 IndividualChannelStream *ics)
1534 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1535 for (g = 0; g < ics->num_window_groups; g++) {
1537 while (k < ics->max_sfb) {
1538 uint8_t sect_end = k;
1540 int sect_band_type = get_bits(gb, 4);
1541 if (sect_band_type == 12) {
1542 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1543 return AVERROR_INVALIDDATA;
1546 sect_len_incr = get_bits(gb, bits);
1547 sect_end += sect_len_incr;
1548 if (get_bits_left(gb) < 0) {
1549 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1550 return AVERROR_INVALIDDATA;
1552 if (sect_end > ics->max_sfb) {
1553 av_log(ac->avctx, AV_LOG_ERROR,
1554 "Number of bands (%d) exceeds limit (%d).\n",
1555 sect_end, ics->max_sfb);
1556 return AVERROR_INVALIDDATA;
1558 } while (sect_len_incr == (1 << bits) - 1);
1559 for (; k < sect_end; k++) {
1560 band_type [idx] = sect_band_type;
1561 band_type_run_end[idx++] = sect_end;
1569 * Decode scalefactors; reference: table 4.47.
1571 * @param global_gain first scalefactor value as scalefactors are differentially coded
1572 * @param band_type array of the used band type
1573 * @param band_type_run_end array of the last scalefactor band of a band type run
1574 * @param sf array of scalefactors or intensity stereo positions
1576 * @return Returns error status. 0 - OK, !0 - error
1578 static int decode_scalefactors(AACContext *ac, INTFLOAT sf[120], GetBitContext *gb,
1579 unsigned int global_gain,
1580 IndividualChannelStream *ics,
1581 enum BandType band_type[120],
1582 int band_type_run_end[120])
1585 int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
1588 for (g = 0; g < ics->num_window_groups; g++) {
1589 for (i = 0; i < ics->max_sfb;) {
1590 int run_end = band_type_run_end[idx];
1591 if (band_type[idx] == ZERO_BT) {
1592 for (; i < run_end; i++, idx++)
1594 } else if ((band_type[idx] == INTENSITY_BT) ||
1595 (band_type[idx] == INTENSITY_BT2)) {
1596 for (; i < run_end; i++, idx++) {
1597 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1598 clipped_offset = av_clip(offset[2], -155, 100);
1599 if (offset[2] != clipped_offset) {
1600 avpriv_request_sample(ac->avctx,
1601 "If you heard an audible artifact, there may be a bug in the decoder. "
1602 "Clipped intensity stereo position (%d -> %d)",
1603 offset[2], clipped_offset);
1606 sf[idx] = 100 - clipped_offset;
1608 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1609 #endif /* USE_FIXED */
1611 } else if (band_type[idx] == NOISE_BT) {
1612 for (; i < run_end; i++, idx++) {
1613 if (noise_flag-- > 0)
1614 offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
1616 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1617 clipped_offset = av_clip(offset[1], -100, 155);
1618 if (offset[1] != clipped_offset) {
1619 avpriv_request_sample(ac->avctx,
1620 "If you heard an audible artifact, there may be a bug in the decoder. "
1621 "Clipped noise gain (%d -> %d)",
1622 offset[1], clipped_offset);
1625 sf[idx] = -(100 + clipped_offset);
1627 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1628 #endif /* USE_FIXED */
1631 for (; i < run_end; i++, idx++) {
1632 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1633 if (offset[0] > 255U) {
1634 av_log(ac->avctx, AV_LOG_ERROR,
1635 "Scalefactor (%d) out of range.\n", offset[0]);
1636 return AVERROR_INVALIDDATA;
1639 sf[idx] = -offset[0];
1641 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1642 #endif /* USE_FIXED */
1651 * Decode pulse data; reference: table 4.7.
1653 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1654 const uint16_t *swb_offset, int num_swb)
1657 pulse->num_pulse = get_bits(gb, 2) + 1;
1658 pulse_swb = get_bits(gb, 6);
1659 if (pulse_swb >= num_swb)
1661 pulse->pos[0] = swb_offset[pulse_swb];
1662 pulse->pos[0] += get_bits(gb, 5);
1663 if (pulse->pos[0] >= swb_offset[num_swb])
1665 pulse->amp[0] = get_bits(gb, 4);
1666 for (i = 1; i < pulse->num_pulse; i++) {
1667 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1668 if (pulse->pos[i] >= swb_offset[num_swb])
1670 pulse->amp[i] = get_bits(gb, 4);
1676 * Decode Temporal Noise Shaping data; reference: table 4.48.
1678 * @return Returns error status. 0 - OK, !0 - error
1680 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1681 GetBitContext *gb, const IndividualChannelStream *ics)
1683 int w, filt, i, coef_len, coef_res, coef_compress;
1684 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1685 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1686 for (w = 0; w < ics->num_windows; w++) {
1687 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1688 coef_res = get_bits1(gb);
1690 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1692 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1694 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1695 av_log(ac->avctx, AV_LOG_ERROR,
1696 "TNS filter order %d is greater than maximum %d.\n",
1697 tns->order[w][filt], tns_max_order);
1698 tns->order[w][filt] = 0;
1699 return AVERROR_INVALIDDATA;
1701 if (tns->order[w][filt]) {
1702 tns->direction[w][filt] = get_bits1(gb);
1703 coef_compress = get_bits1(gb);
1704 coef_len = coef_res + 3 - coef_compress;
1705 tmp2_idx = 2 * coef_compress + coef_res;
1707 for (i = 0; i < tns->order[w][filt]; i++)
1708 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1717 * Decode Mid/Side data; reference: table 4.54.
1719 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1720 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1721 * [3] reserved for scalable AAC
1723 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1727 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1728 if (ms_present == 1) {
1729 for (idx = 0; idx < max_idx; idx++)
1730 cpe->ms_mask[idx] = get_bits1(gb);
1731 } else if (ms_present == 2) {
1732 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1737 * Decode spectral data; reference: table 4.50.
1738 * Dequantize and scale spectral data; reference: 4.6.3.3.
1740 * @param coef array of dequantized, scaled spectral data
1741 * @param sf array of scalefactors or intensity stereo positions
1742 * @param pulse_present set if pulses are present
1743 * @param pulse pointer to pulse data struct
1744 * @param band_type array of the used band type
1746 * @return Returns error status. 0 - OK, !0 - error
1748 static int decode_spectrum_and_dequant(AACContext *ac, INTFLOAT coef[1024],
1749 GetBitContext *gb, const INTFLOAT sf[120],
1750 int pulse_present, const Pulse *pulse,
1751 const IndividualChannelStream *ics,
1752 enum BandType band_type[120])
1754 int i, k, g, idx = 0;
1755 const int c = 1024 / ics->num_windows;
1756 const uint16_t *offsets = ics->swb_offset;
1757 INTFLOAT *coef_base = coef;
1759 for (g = 0; g < ics->num_windows; g++)
1760 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1761 sizeof(INTFLOAT) * (c - offsets[ics->max_sfb]));
1763 for (g = 0; g < ics->num_window_groups; g++) {
1764 unsigned g_len = ics->group_len[g];
1766 for (i = 0; i < ics->max_sfb; i++, idx++) {
1767 const unsigned cbt_m1 = band_type[idx] - 1;
1768 INTFLOAT *cfo = coef + offsets[i];
1769 int off_len = offsets[i + 1] - offsets[i];
1772 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1773 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1774 memset(cfo, 0, off_len * sizeof(*cfo));
1776 } else if (cbt_m1 == NOISE_BT - 1) {
1777 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1778 INTFLOAT band_energy;
1780 for (k = 0; k < off_len; k++) {
1781 ac->random_state = lcg_random(ac->random_state);
1782 cfo[k] = ac->random_state >> 3;
1785 band_energy = ac->fdsp->scalarproduct_fixed(cfo, cfo, off_len);
1786 band_energy = fixed_sqrt(band_energy, 31);
1787 noise_scale(cfo, sf[idx], band_energy, off_len);
1791 for (k = 0; k < off_len; k++) {
1792 ac->random_state = lcg_random(ac->random_state);
1793 cfo[k] = ac->random_state;
1796 band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
1797 scale = sf[idx] / sqrtf(band_energy);
1798 ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
1799 #endif /* USE_FIXED */
1803 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1804 #endif /* !USE_FIXED */
1805 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1806 OPEN_READER(re, gb);
1808 switch (cbt_m1 >> 1) {
1810 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1818 UPDATE_CACHE(re, gb);
1819 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1822 cf = DEC_SQUAD(cf, cb_idx);
1824 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1825 #endif /* USE_FIXED */
1831 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1841 UPDATE_CACHE(re, gb);
1842 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1844 nnz = cb_idx >> 8 & 15;
1845 bits = nnz ? GET_CACHE(re, gb) : 0;
1846 LAST_SKIP_BITS(re, gb, nnz);
1848 cf = DEC_UQUAD(cf, cb_idx, bits);
1850 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1851 #endif /* USE_FIXED */
1857 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1865 UPDATE_CACHE(re, gb);
1866 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1869 cf = DEC_SPAIR(cf, cb_idx);
1871 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1872 #endif /* USE_FIXED */
1879 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1889 UPDATE_CACHE(re, gb);
1890 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1892 nnz = cb_idx >> 8 & 15;
1893 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1894 LAST_SKIP_BITS(re, gb, nnz);
1896 cf = DEC_UPAIR(cf, cb_idx, sign);
1898 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1899 #endif /* USE_FIXED */
1905 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1911 uint32_t *icf = (uint32_t *) cf;
1912 #endif /* USE_FIXED */
1922 UPDATE_CACHE(re, gb);
1923 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1926 if (cb_idx == 0x0000) {
1934 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1935 LAST_SKIP_BITS(re, gb, nnz);
1937 for (j = 0; j < 2; j++) {
1941 /* The total length of escape_sequence must be < 22 bits according
1942 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1943 UPDATE_CACHE(re, gb);
1944 b = GET_CACHE(re, gb);
1945 b = 31 - av_log2(~b);
1948 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1949 return AVERROR_INVALIDDATA;
1952 SKIP_BITS(re, gb, b + 1);
1954 n = (1 << b) + SHOW_UBITS(re, gb, b);
1955 LAST_SKIP_BITS(re, gb, b);
1962 *icf++ = ff_cbrt_tab[n] | (bits & 1U<<31);
1963 #endif /* USE_FIXED */
1972 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1973 *icf++ = (bits & 1U<<31) | v;
1974 #endif /* USE_FIXED */
1981 ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1982 #endif /* !USE_FIXED */
1986 CLOSE_READER(re, gb);
1992 if (pulse_present) {
1994 for (i = 0; i < pulse->num_pulse; i++) {
1995 INTFLOAT co = coef_base[ pulse->pos[i] ];
1996 while (offsets[idx + 1] <= pulse->pos[i])
1998 if (band_type[idx] != NOISE_BT && sf[idx]) {
1999 INTFLOAT ico = -pulse->amp[i];
2002 ico = co + (co > 0 ? -ico : ico);
2004 coef_base[ pulse->pos[i] ] = ico;
2008 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
2010 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
2011 #endif /* USE_FIXED */
2018 for (g = 0; g < ics->num_window_groups; g++) {
2019 unsigned g_len = ics->group_len[g];
2021 for (i = 0; i < ics->max_sfb; i++, idx++) {
2022 const unsigned cbt_m1 = band_type[idx] - 1;
2023 int *cfo = coef + offsets[i];
2024 int off_len = offsets[i + 1] - offsets[i];
2027 if (cbt_m1 < NOISE_BT - 1) {
2028 for (group = 0; group < (int)g_len; group++, cfo+=128) {
2029 ac->vector_pow43(cfo, off_len);
2030 ac->subband_scale(cfo, cfo, sf[idx], 34, off_len, ac->avctx);
2036 #endif /* USE_FIXED */
2041 * Apply AAC-Main style frequency domain prediction.
2043 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
2047 if (!sce->ics.predictor_initialized) {
2048 reset_all_predictors(sce->predictor_state);
2049 sce->ics.predictor_initialized = 1;
2052 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2054 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
2056 for (k = sce->ics.swb_offset[sfb];
2057 k < sce->ics.swb_offset[sfb + 1];
2059 predict(&sce->predictor_state[k], &sce->coeffs[k],
2060 sce->ics.predictor_present &&
2061 sce->ics.prediction_used[sfb]);
2064 if (sce->ics.predictor_reset_group)
2065 reset_predictor_group(sce->predictor_state,
2066 sce->ics.predictor_reset_group);
2068 reset_all_predictors(sce->predictor_state);
2071 static void decode_gain_control(SingleChannelElement * sce, GetBitContext * gb)
2073 // wd_num, wd_test, aloc_size
2074 static const uint8_t gain_mode[4][3] = {
2075 {1, 0, 5}, // ONLY_LONG_SEQUENCE = 0,
2076 {2, 1, 2}, // LONG_START_SEQUENCE,
2077 {8, 0, 2}, // EIGHT_SHORT_SEQUENCE,
2078 {2, 1, 5}, // LONG_STOP_SEQUENCE
2081 const int mode = sce->ics.window_sequence[0];
2084 // FIXME: Store the gain control data on |sce| and do something with it.
2085 uint8_t max_band = get_bits(gb, 2);
2086 for (bd = 0; bd < max_band; bd++) {
2087 for (wd = 0; wd < gain_mode[mode][0]; wd++) {
2088 uint8_t adjust_num = get_bits(gb, 3);
2089 for (ad = 0; ad < adjust_num; ad++) {
2090 skip_bits(gb, 4 + ((wd == 0 && gain_mode[mode][1])
2092 : gain_mode[mode][2]));
2099 * Decode an individual_channel_stream payload; reference: table 4.44.
2101 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
2102 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
2104 * @return Returns error status. 0 - OK, !0 - error
2106 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
2107 GetBitContext *gb, int common_window, int scale_flag)
2110 TemporalNoiseShaping *tns = &sce->tns;
2111 IndividualChannelStream *ics = &sce->ics;
2112 INTFLOAT *out = sce->coeffs;
2113 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
2116 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2117 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
2118 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
2119 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
2120 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2122 /* This assignment is to silence a GCC warning about the variable being used
2123 * uninitialized when in fact it always is.
2125 pulse.num_pulse = 0;
2127 global_gain = get_bits(gb, 8);
2129 if (!common_window && !scale_flag) {
2130 ret = decode_ics_info(ac, ics, gb);
2135 if ((ret = decode_band_types(ac, sce->band_type,
2136 sce->band_type_run_end, gb, ics)) < 0)
2138 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
2139 sce->band_type, sce->band_type_run_end)) < 0)
2144 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
2145 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2146 av_log(ac->avctx, AV_LOG_ERROR,
2147 "Pulse tool not allowed in eight short sequence.\n");
2148 ret = AVERROR_INVALIDDATA;
2151 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
2152 av_log(ac->avctx, AV_LOG_ERROR,
2153 "Pulse data corrupt or invalid.\n");
2154 ret = AVERROR_INVALIDDATA;
2158 tns->present = get_bits1(gb);
2159 if (tns->present && !er_syntax) {
2160 ret = decode_tns(ac, tns, gb, ics);
2164 if (!eld_syntax && get_bits1(gb)) {
2165 decode_gain_control(sce, gb);
2166 if (!ac->warned_gain_control) {
2167 avpriv_report_missing_feature(ac->avctx, "Gain control");
2168 ac->warned_gain_control = 1;
2171 // I see no textual basis in the spec for this occurring after SSR gain
2172 // control, but this is what both reference and real implmentations do
2173 if (tns->present && er_syntax) {
2174 ret = decode_tns(ac, tns, gb, ics);
2180 ret = decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
2181 &pulse, ics, sce->band_type);
2185 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
2186 apply_prediction(ac, sce);
2195 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
2197 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
2199 const IndividualChannelStream *ics = &cpe->ch[0].ics;
2200 INTFLOAT *ch0 = cpe->ch[0].coeffs;
2201 INTFLOAT *ch1 = cpe->ch[1].coeffs;
2202 int g, i, group, idx = 0;
2203 const uint16_t *offsets = ics->swb_offset;
2204 for (g = 0; g < ics->num_window_groups; g++) {
2205 for (i = 0; i < ics->max_sfb; i++, idx++) {
2206 if (cpe->ms_mask[idx] &&
2207 cpe->ch[0].band_type[idx] < NOISE_BT &&
2208 cpe->ch[1].band_type[idx] < NOISE_BT) {
2210 for (group = 0; group < ics->group_len[g]; group++) {
2211 ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
2212 ch1 + group * 128 + offsets[i],
2213 offsets[i+1] - offsets[i]);
2215 for (group = 0; group < ics->group_len[g]; group++) {
2216 ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
2217 ch1 + group * 128 + offsets[i],
2218 offsets[i+1] - offsets[i]);
2219 #endif /* USE_FIXED */
2223 ch0 += ics->group_len[g] * 128;
2224 ch1 += ics->group_len[g] * 128;
2229 * intensity stereo decoding; reference: 4.6.8.2.3
2231 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
2232 * [1] mask is decoded from bitstream; [2] mask is all 1s;
2233 * [3] reserved for scalable AAC
2235 static void apply_intensity_stereo(AACContext *ac,
2236 ChannelElement *cpe, int ms_present)
2238 const IndividualChannelStream *ics = &cpe->ch[1].ics;
2239 SingleChannelElement *sce1 = &cpe->ch[1];
2240 INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2241 const uint16_t *offsets = ics->swb_offset;
2242 int g, group, i, idx = 0;
2245 for (g = 0; g < ics->num_window_groups; g++) {
2246 for (i = 0; i < ics->max_sfb;) {
2247 if (sce1->band_type[idx] == INTENSITY_BT ||
2248 sce1->band_type[idx] == INTENSITY_BT2) {
2249 const int bt_run_end = sce1->band_type_run_end[idx];
2250 for (; i < bt_run_end; i++, idx++) {
2251 c = -1 + 2 * (sce1->band_type[idx] - 14);
2253 c *= 1 - 2 * cpe->ms_mask[idx];
2254 scale = c * sce1->sf[idx];
2255 for (group = 0; group < ics->group_len[g]; group++)
2257 ac->subband_scale(coef1 + group * 128 + offsets[i],
2258 coef0 + group * 128 + offsets[i],
2261 offsets[i + 1] - offsets[i] ,ac->avctx);
2263 ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2264 coef0 + group * 128 + offsets[i],
2266 offsets[i + 1] - offsets[i]);
2267 #endif /* USE_FIXED */
2270 int bt_run_end = sce1->band_type_run_end[idx];
2271 idx += bt_run_end - i;
2275 coef0 += ics->group_len[g] * 128;
2276 coef1 += ics->group_len[g] * 128;
2281 * Decode a channel_pair_element; reference: table 4.4.
2283 * @return Returns error status. 0 - OK, !0 - error
2285 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2287 int i, ret, common_window, ms_present = 0;
2288 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2290 common_window = eld_syntax || get_bits1(gb);
2291 if (common_window) {
2292 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2293 return AVERROR_INVALIDDATA;
2294 i = cpe->ch[1].ics.use_kb_window[0];
2295 cpe->ch[1].ics = cpe->ch[0].ics;
2296 cpe->ch[1].ics.use_kb_window[1] = i;
2297 if (cpe->ch[1].ics.predictor_present &&
2298 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2299 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2300 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2301 ms_present = get_bits(gb, 2);
2302 if (ms_present == 3) {
2303 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2304 return AVERROR_INVALIDDATA;
2305 } else if (ms_present)
2306 decode_mid_side_stereo(cpe, gb, ms_present);
2308 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2310 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2313 if (common_window) {
2315 apply_mid_side_stereo(ac, cpe);
2316 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2317 apply_prediction(ac, &cpe->ch[0]);
2318 apply_prediction(ac, &cpe->ch[1]);
2322 apply_intensity_stereo(ac, cpe, ms_present);
2326 static const float cce_scale[] = {
2327 1.09050773266525765921, //2^(1/8)
2328 1.18920711500272106672, //2^(1/4)
2334 * Decode coupling_channel_element; reference: table 4.8.
2336 * @return Returns error status. 0 - OK, !0 - error
2338 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2344 SingleChannelElement *sce = &che->ch[0];
2345 ChannelCoupling *coup = &che->coup;
2347 coup->coupling_point = 2 * get_bits1(gb);
2348 coup->num_coupled = get_bits(gb, 3);
2349 for (c = 0; c <= coup->num_coupled; c++) {
2351 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2352 coup->id_select[c] = get_bits(gb, 4);
2353 if (coup->type[c] == TYPE_CPE) {
2354 coup->ch_select[c] = get_bits(gb, 2);
2355 if (coup->ch_select[c] == 3)
2358 coup->ch_select[c] = 2;
2360 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2362 sign = get_bits(gb, 1);
2364 scale = get_bits(gb, 2);
2366 scale = cce_scale[get_bits(gb, 2)];
2369 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2372 for (c = 0; c < num_gain; c++) {
2376 INTFLOAT gain_cache = FIXR10(1.);
2378 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2379 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2380 gain_cache = GET_GAIN(scale, gain);
2382 if ((abs(gain_cache)-1024) >> 3 > 30)
2383 return AVERROR(ERANGE);
2386 if (coup->coupling_point == AFTER_IMDCT) {
2387 coup->gain[c][0] = gain_cache;
2389 for (g = 0; g < sce->ics.num_window_groups; g++) {
2390 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2391 if (sce->band_type[idx] != ZERO_BT) {
2393 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2401 gain_cache = GET_GAIN(scale, t) * s;
2403 if ((abs(gain_cache)-1024) >> 3 > 30)
2404 return AVERROR(ERANGE);
2408 coup->gain[c][idx] = gain_cache;
2418 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2420 * @return Returns number of bytes consumed.
2422 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2426 int num_excl_chan = 0;
2429 for (i = 0; i < 7; i++)
2430 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2431 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2433 return num_excl_chan / 7;
2437 * Decode dynamic range information; reference: table 4.52.
2439 * @return Returns number of bytes consumed.
2441 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2445 int drc_num_bands = 1;
2448 /* pce_tag_present? */
2449 if (get_bits1(gb)) {
2450 che_drc->pce_instance_tag = get_bits(gb, 4);
2451 skip_bits(gb, 4); // tag_reserved_bits
2455 /* excluded_chns_present? */
2456 if (get_bits1(gb)) {
2457 n += decode_drc_channel_exclusions(che_drc, gb);
2460 /* drc_bands_present? */
2461 if (get_bits1(gb)) {
2462 che_drc->band_incr = get_bits(gb, 4);
2463 che_drc->interpolation_scheme = get_bits(gb, 4);
2465 drc_num_bands += che_drc->band_incr;
2466 for (i = 0; i < drc_num_bands; i++) {
2467 che_drc->band_top[i] = get_bits(gb, 8);
2472 /* prog_ref_level_present? */
2473 if (get_bits1(gb)) {
2474 che_drc->prog_ref_level = get_bits(gb, 7);
2475 skip_bits1(gb); // prog_ref_level_reserved_bits
2479 for (i = 0; i < drc_num_bands; i++) {
2480 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2481 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2488 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2490 int i, major, minor;
2495 get_bits(gb, 13); len -= 13;
2497 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2498 buf[i] = get_bits(gb, 8);
2501 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2502 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2504 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2505 ac->avctx->internal->skip_samples = 1024;
2509 skip_bits_long(gb, len);
2515 * Decode extension data (incomplete); reference: table 4.51.
2517 * @param cnt length of TYPE_FIL syntactic element in bytes
2519 * @return Returns number of bytes consumed
2521 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2522 ChannelElement *che, enum RawDataBlockType elem_type)
2526 int type = get_bits(gb, 4);
2528 if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2529 av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2531 switch (type) { // extension type
2532 case EXT_SBR_DATA_CRC:
2536 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2538 } else if (ac->oc[1].m4ac.frame_length_short) {
2539 if (!ac->warned_960_sbr)
2540 avpriv_report_missing_feature(ac->avctx,
2541 "SBR with 960 frame length");
2542 ac->warned_960_sbr = 1;
2543 skip_bits_long(gb, 8 * cnt - 4);
2545 } else if (!ac->oc[1].m4ac.sbr) {
2546 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2547 skip_bits_long(gb, 8 * cnt - 4);
2549 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2550 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2551 skip_bits_long(gb, 8 * cnt - 4);
2553 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2554 ac->oc[1].m4ac.sbr = 1;
2555 ac->oc[1].m4ac.ps = 1;
2556 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2557 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2558 ac->oc[1].status, 1);
2560 ac->oc[1].m4ac.sbr = 1;
2561 ac->avctx->profile = FF_PROFILE_AAC_HE;
2563 res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2565 case EXT_DYNAMIC_RANGE:
2566 res = decode_dynamic_range(&ac->che_drc, gb);
2569 decode_fill(ac, gb, 8 * cnt - 4);
2572 case EXT_DATA_ELEMENT:
2574 skip_bits_long(gb, 8 * cnt - 4);
2581 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2583 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2584 * @param coef spectral coefficients
2586 static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns,
2587 IndividualChannelStream *ics, int decode)
2589 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2591 int bottom, top, order, start, end, size, inc;
2592 INTFLOAT lpc[TNS_MAX_ORDER];
2593 INTFLOAT tmp[TNS_MAX_ORDER+1];
2594 UINTFLOAT *coef = coef_param;
2599 for (w = 0; w < ics->num_windows; w++) {
2600 bottom = ics->num_swb;
2601 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2603 bottom = FFMAX(0, top - tns->length[w][filt]);
2604 order = tns->order[w][filt];
2609 AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
2611 start = ics->swb_offset[FFMIN(bottom, mmm)];
2612 end = ics->swb_offset[FFMIN( top, mmm)];
2613 if ((size = end - start) <= 0)
2615 if (tns->direction[w][filt]) {
2625 for (m = 0; m < size; m++, start += inc)
2626 for (i = 1; i <= FFMIN(m, order); i++)
2627 coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]);
2630 for (m = 0; m < size; m++, start += inc) {
2631 tmp[0] = coef[start];
2632 for (i = 1; i <= FFMIN(m, order); i++)
2633 coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
2634 for (i = order; i > 0; i--)
2635 tmp[i] = tmp[i - 1];
2643 * Apply windowing and MDCT to obtain the spectral
2644 * coefficient from the predicted sample by LTP.
2646 static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
2647 INTFLOAT *in, IndividualChannelStream *ics)
2649 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME2(aac_kbd_long_1024) : AAC_RENAME2(sine_1024);
2650 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME2(aac_kbd_short_128) : AAC_RENAME2(sine_128);
2651 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME2(aac_kbd_long_1024) : AAC_RENAME2(sine_1024);
2652 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME2(aac_kbd_short_128) : AAC_RENAME2(sine_128);
2654 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2655 ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
2657 memset(in, 0, 448 * sizeof(*in));
2658 ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
2660 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2661 ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2663 ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2664 memset(in + 1024 + 576, 0, 448 * sizeof(*in));
2666 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2670 * Apply the long term prediction
2672 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2674 const LongTermPrediction *ltp = &sce->ics.ltp;
2675 const uint16_t *offsets = sce->ics.swb_offset;
2678 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2679 INTFLOAT *predTime = sce->ret;
2680 INTFLOAT *predFreq = ac->buf_mdct;
2681 int16_t num_samples = 2048;
2683 if (ltp->lag < 1024)
2684 num_samples = ltp->lag + 1024;
2685 for (i = 0; i < num_samples; i++)
2686 predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
2687 memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
2689 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2691 if (sce->tns.present)
2692 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2694 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2696 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2697 sce->coeffs[i] += (UINTFLOAT)predFreq[i];
2702 * Update the LTP buffer for next frame
2704 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2706 IndividualChannelStream *ics = &sce->ics;
2707 INTFLOAT *saved = sce->saved;
2708 INTFLOAT *saved_ltp = sce->coeffs;
2709 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME2(aac_kbd_long_1024) : AAC_RENAME2(sine_1024);
2710 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME2(aac_kbd_short_128) : AAC_RENAME2(sine_128);
2713 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2714 memcpy(saved_ltp, saved, 512 * sizeof(*saved_ltp));
2715 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2716 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2718 for (i = 0; i < 64; i++)
2719 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2720 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2721 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
2722 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2723 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2725 for (i = 0; i < 64; i++)
2726 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2727 } else { // LONG_STOP or ONLY_LONG
2728 ac->fdsp->vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2730 for (i = 0; i < 512; i++)
2731 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
2734 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2735 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2736 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2740 * Conduct IMDCT and windowing.
2742 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2744 IndividualChannelStream *ics = &sce->ics;
2745 INTFLOAT *in = sce->coeffs;
2746 INTFLOAT *out = sce->ret;
2747 INTFLOAT *saved = sce->saved;
2748 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME2(aac_kbd_short_128) : AAC_RENAME2(sine_128);
2749 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME2(aac_kbd_long_1024) : AAC_RENAME2(sine_1024);
2750 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME2(aac_kbd_short_128) : AAC_RENAME2(sine_128);
2751 INTFLOAT *buf = ac->buf_mdct;
2752 INTFLOAT *temp = ac->temp;
2756 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2757 for (i = 0; i < 1024; i += 128)
2758 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2760 ac->mdct.imdct_half(&ac->mdct, buf, in);
2762 for (i=0; i<1024; i++)
2763 buf[i] = (buf[i] + 4LL) >> 3;
2764 #endif /* USE_FIXED */
2767 /* window overlapping
2768 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2769 * and long to short transitions are considered to be short to short
2770 * transitions. This leaves just two cases (long to long and short to short)
2771 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2773 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2774 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2775 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2777 memcpy( out, saved, 448 * sizeof(*out));
2779 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2780 ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2781 ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2782 ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2783 ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2784 ac->fdsp->vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2785 memcpy( out + 448 + 4*128, temp, 64 * sizeof(*out));
2787 ac->fdsp->vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2788 memcpy( out + 576, buf + 64, 448 * sizeof(*out));
2793 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2794 memcpy( saved, temp + 64, 64 * sizeof(*saved));
2795 ac->fdsp->vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2796 ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2797 ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2798 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2799 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2800 memcpy( saved, buf + 512, 448 * sizeof(*saved));
2801 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2802 } else { // LONG_STOP or ONLY_LONG
2803 memcpy( saved, buf + 512, 512 * sizeof(*saved));
2808 * Conduct IMDCT and windowing.
2810 static void imdct_and_windowing_960(AACContext *ac, SingleChannelElement *sce)
2813 IndividualChannelStream *ics = &sce->ics;
2814 INTFLOAT *in = sce->coeffs;
2815 INTFLOAT *out = sce->ret;
2816 INTFLOAT *saved = sce->saved;
2817 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(aac_kbd_short_120) : AAC_RENAME(sine_120);
2818 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(aac_kbd_long_960) : AAC_RENAME(sine_960);
2819 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(aac_kbd_short_120) : AAC_RENAME(sine_120);
2820 INTFLOAT *buf = ac->buf_mdct;
2821 INTFLOAT *temp = ac->temp;
2825 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2826 for (i = 0; i < 8; i++)
2827 ac->mdct120->imdct_half(ac->mdct120, buf + i * 120, in + i * 128, 1);
2829 ac->mdct960->imdct_half(ac->mdct960, buf, in, 1);
2832 /* window overlapping
2833 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2834 * and long to short transitions are considered to be short to short
2835 * transitions. This leaves just two cases (long to long and short to short)
2836 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2839 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2840 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2841 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 480);
2843 memcpy( out, saved, 420 * sizeof(*out));
2845 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2846 ac->fdsp->vector_fmul_window(out + 420 + 0*120, saved + 420, buf + 0*120, swindow_prev, 60);
2847 ac->fdsp->vector_fmul_window(out + 420 + 1*120, buf + 0*120 + 60, buf + 1*120, swindow, 60);
2848 ac->fdsp->vector_fmul_window(out + 420 + 2*120, buf + 1*120 + 60, buf + 2*120, swindow, 60);
2849 ac->fdsp->vector_fmul_window(out + 420 + 3*120, buf + 2*120 + 60, buf + 3*120, swindow, 60);
2850 ac->fdsp->vector_fmul_window(temp, buf + 3*120 + 60, buf + 4*120, swindow, 60);
2851 memcpy( out + 420 + 4*120, temp, 60 * sizeof(*out));
2853 ac->fdsp->vector_fmul_window(out + 420, saved + 420, buf, swindow_prev, 60);
2854 memcpy( out + 540, buf + 60, 420 * sizeof(*out));
2859 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2860 memcpy( saved, temp + 60, 60 * sizeof(*saved));
2861 ac->fdsp->vector_fmul_window(saved + 60, buf + 4*120 + 60, buf + 5*120, swindow, 60);
2862 ac->fdsp->vector_fmul_window(saved + 180, buf + 5*120 + 60, buf + 6*120, swindow, 60);
2863 ac->fdsp->vector_fmul_window(saved + 300, buf + 6*120 + 60, buf + 7*120, swindow, 60);
2864 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2865 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2866 memcpy( saved, buf + 480, 420 * sizeof(*saved));
2867 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2868 } else { // LONG_STOP or ONLY_LONG
2869 memcpy( saved, buf + 480, 480 * sizeof(*saved));
2873 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2875 IndividualChannelStream *ics = &sce->ics;
2876 INTFLOAT *in = sce->coeffs;
2877 INTFLOAT *out = sce->ret;
2878 INTFLOAT *saved = sce->saved;
2879 INTFLOAT *buf = ac->buf_mdct;
2882 #endif /* USE_FIXED */
2885 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2888 for (i = 0; i < 1024; i++)
2889 buf[i] = (buf[i] + 2) >> 2;
2890 #endif /* USE_FIXED */
2892 // window overlapping
2893 if (ics->use_kb_window[1]) {
2894 // AAC LD uses a low overlap sine window instead of a KBD window
2895 memcpy(out, saved, 192 * sizeof(*out));
2896 ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME2(sine_128), 64);
2897 memcpy( out + 320, buf + 64, 192 * sizeof(*out));
2899 ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME2(sine_512), 256);
2903 memcpy(saved, buf + 256, 256 * sizeof(*saved));
2906 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2908 UINTFLOAT *in = sce->coeffs;
2909 INTFLOAT *out = sce->ret;
2910 INTFLOAT *saved = sce->saved;
2911 INTFLOAT *buf = ac->buf_mdct;
2913 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2914 const int n2 = n >> 1;
2915 const int n4 = n >> 2;
2916 const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
2917 AAC_RENAME(ff_aac_eld_window_512);
2919 // Inverse transform, mapped to the conventional IMDCT by
2920 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2921 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2922 // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2923 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2924 for (i = 0; i < n2; i+=2) {
2926 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2927 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2931 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1);
2934 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2937 for (i = 0; i < 1024; i++)
2938 buf[i] = (buf[i] + 1) >> 1;
2939 #endif /* USE_FIXED */
2941 for (i = 0; i < n; i+=2) {
2944 // Like with the regular IMDCT at this point we still have the middle half
2945 // of a transform but with even symmetry on the left and odd symmetry on
2948 // window overlapping
2949 // The spec says to use samples [0..511] but the reference decoder uses
2950 // samples [128..639].
2951 for (i = n4; i < n2; i ++) {
2952 out[i - n4] = AAC_MUL31( buf[ n2 - 1 - i] , window[i - n4]) +
2953 AAC_MUL31( saved[ i + n2] , window[i + n - n4]) +
2954 AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
2955 AAC_MUL31(-saved[ 2*n + n2 + i] , window[i + 3*n - n4]);
2957 for (i = 0; i < n2; i ++) {
2958 out[n4 + i] = AAC_MUL31( buf[ i] , window[i + n2 - n4]) +
2959 AAC_MUL31(-saved[ n - 1 - i] , window[i + n2 + n - n4]) +
2960 AAC_MUL31(-saved[ n + i] , window[i + n2 + 2*n - n4]) +
2961 AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
2963 for (i = 0; i < n4; i ++) {
2964 out[n2 + n4 + i] = AAC_MUL31( buf[ i + n2] , window[i + n - n4]) +
2965 AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
2966 AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
2970 memmove(saved + n, saved, 2 * n * sizeof(*saved));
2971 memcpy( saved, buf, n * sizeof(*saved));
2975 * channel coupling transformation interface
2977 * @param apply_coupling_method pointer to (in)dependent coupling function
2979 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2980 enum RawDataBlockType type, int elem_id,
2981 enum CouplingPoint coupling_point,
2982 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2986 for (i = 0; i < MAX_ELEM_ID; i++) {
2987 ChannelElement *cce = ac->che[TYPE_CCE][i];
2990 if (cce && cce->coup.coupling_point == coupling_point) {
2991 ChannelCoupling *coup = &cce->coup;
2993 for (c = 0; c <= coup->num_coupled; c++) {
2994 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2995 if (coup->ch_select[c] != 1) {
2996 apply_coupling_method(ac, &cc->ch[0], cce, index);
2997 if (coup->ch_select[c] != 0)
3000 if (coup->ch_select[c] != 2)
3001 apply_coupling_method(ac, &cc->ch[1], cce, index++);
3003 index += 1 + (coup->ch_select[c] == 3);
3010 * Convert spectral data to samples, applying all supported tools as appropriate.
3012 static void spectral_to_sample(AACContext *ac, int samples)
3015 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
3016 switch (ac->oc[1].m4ac.object_type) {
3018 imdct_and_window = imdct_and_windowing_ld;
3020 case AOT_ER_AAC_ELD:
3021 imdct_and_window = imdct_and_windowing_eld;
3024 if (ac->oc[1].m4ac.frame_length_short)
3025 imdct_and_window = imdct_and_windowing_960;
3027 imdct_and_window = ac->imdct_and_windowing;
3029 for (type = 3; type >= 0; type--) {
3030 for (i = 0; i < MAX_ELEM_ID; i++) {
3031 ChannelElement *che = ac->che[type][i];
3032 if (che && che->present) {
3033 if (type <= TYPE_CPE)
3034 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
3035 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
3036 if (che->ch[0].ics.predictor_present) {
3037 if (che->ch[0].ics.ltp.present)
3038 ac->apply_ltp(ac, &che->ch[0]);
3039 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
3040 ac->apply_ltp(ac, &che->ch[1]);
3043 if (che->ch[0].tns.present)
3044 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
3045 if (che->ch[1].tns.present)
3046 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
3047 if (type <= TYPE_CPE)
3048 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
3049 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
3050 imdct_and_window(ac, &che->ch[0]);
3051 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3052 ac->update_ltp(ac, &che->ch[0]);
3053 if (type == TYPE_CPE) {
3054 imdct_and_window(ac, &che->ch[1]);
3055 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3056 ac->update_ltp(ac, &che->ch[1]);
3058 if (ac->oc[1].m4ac.sbr > 0) {
3059 AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
3062 if (type <= TYPE_CCE)
3063 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
3068 /* preparation for resampler */
3069 for(j = 0; j<samples; j++){
3070 che->ch[0].ret[j] = (int32_t)av_clip64((int64_t)che->ch[0].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3071 if(type == TYPE_CPE)
3072 che->ch[1].ret[j] = (int32_t)av_clip64((int64_t)che->ch[1].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3075 #endif /* USE_FIXED */
3078 av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
3084 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
3087 AACADTSHeaderInfo hdr_info;
3088 uint8_t layout_map[MAX_ELEM_ID*4][3];
3089 int layout_map_tags, ret;
3091 size = ff_adts_header_parse(gb, &hdr_info);
3093 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
3094 // This is 2 for "VLB " audio in NSV files.
3095 // See samples/nsv/vlb_audio.
3096 avpriv_report_missing_feature(ac->avctx,
3097 "More than one AAC RDB per ADTS frame");
3098 ac->warned_num_aac_frames = 1;
3100 push_output_configuration(ac);
3101 if (hdr_info.chan_config) {
3102 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
3103 if ((ret = set_default_channel_config(ac, ac->avctx,
3106 hdr_info.chan_config)) < 0)
3108 if ((ret = output_configure(ac, layout_map, layout_map_tags,
3109 FFMAX(ac->oc[1].status,
3110 OC_TRIAL_FRAME), 0)) < 0)
3113 ac->oc[1].m4ac.chan_config = 0;
3115 * dual mono frames in Japanese DTV can have chan_config 0
3116 * WITHOUT specifying PCE.
3117 * thus, set dual mono as default.
3119 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
3120 layout_map_tags = 2;
3121 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
3122 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
3123 layout_map[0][1] = 0;
3124 layout_map[1][1] = 1;
3125 if (output_configure(ac, layout_map, layout_map_tags,
3130 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
3131 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
3132 ac->oc[1].m4ac.object_type = hdr_info.object_type;
3133 ac->oc[1].m4ac.frame_length_short = 0;
3134 if (ac->oc[0].status != OC_LOCKED ||
3135 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
3136 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
3137 ac->oc[1].m4ac.sbr = -1;
3138 ac->oc[1].m4ac.ps = -1;
3140 if (!hdr_info.crc_absent)
3146 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
3147 int *got_frame_ptr, GetBitContext *gb)
3149 AACContext *ac = avctx->priv_data;
3150 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
3151 ChannelElement *che;
3153 int samples = m4ac->frame_length_short ? 960 : 1024;
3154 int chan_config = m4ac->chan_config;
3155 int aot = m4ac->object_type;
3157 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
3162 if ((err = frame_configure_elements(avctx)) < 0)
3165 // The FF_PROFILE_AAC_* defines are all object_type - 1
3166 // This may lead to an undefined profile being signaled
3167 ac->avctx->profile = aot - 1;
3169 ac->tags_mapped = 0;
3171 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
3172 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
3174 return AVERROR_INVALIDDATA;
3176 for (i = 0; i < tags_per_config[chan_config]; i++) {
3177 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
3178 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
3179 if (!(che=get_che(ac, elem_type, elem_id))) {
3180 av_log(ac->avctx, AV_LOG_ERROR,
3181 "channel element %d.%d is not allocated\n",
3182 elem_type, elem_id);
3183 return AVERROR_INVALIDDATA;
3186 if (aot != AOT_ER_AAC_ELD)
3188 switch (elem_type) {
3190 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3193 err = decode_cpe(ac, gb, che);
3196 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3203 spectral_to_sample(ac, samples);
3205 if (!ac->frame->data[0] && samples) {
3206 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3207 return AVERROR_INVALIDDATA;
3210 ac->frame->nb_samples = samples;
3211 ac->frame->sample_rate = avctx->sample_rate;
3214 skip_bits_long(gb, get_bits_left(gb));
3218 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
3219 int *got_frame_ptr, GetBitContext *gb,
3220 const AVPacket *avpkt)
3222 AACContext *ac = avctx->priv_data;
3223 ChannelElement *che = NULL, *che_prev = NULL;
3224 enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
3226 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
3227 int is_dmono, sce_count = 0;
3228 int payload_alignment;
3229 uint8_t che_presence[4][MAX_ELEM_ID] = {{0}};
3233 if (show_bits(gb, 12) == 0xfff) {
3234 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
3235 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
3238 if (ac->oc[1].m4ac.sampling_index > 12) {
3239 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
3240 err = AVERROR_INVALIDDATA;
3245 if ((err = frame_configure_elements(avctx)) < 0)
3248 // The FF_PROFILE_AAC_* defines are all object_type - 1
3249 // This may lead to an undefined profile being signaled
3250 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
3252 payload_alignment = get_bits_count(gb);
3253 ac->tags_mapped = 0;
3255 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
3256 elem_id = get_bits(gb, 4);
3258 if (avctx->debug & FF_DEBUG_STARTCODE)
3259 av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
3261 if (!avctx->channels && elem_type != TYPE_PCE) {
3262 err = AVERROR_INVALIDDATA;
3266 if (elem_type < TYPE_DSE) {
3267 if (che_presence[elem_type][elem_id]) {
3268 int error = che_presence[elem_type][elem_id] > 1;
3269 av_log(ac->avctx, error ? AV_LOG_ERROR : AV_LOG_DEBUG, "channel element %d.%d duplicate\n",
3270 elem_type, elem_id);
3272 err = AVERROR_INVALIDDATA;
3276 che_presence[elem_type][elem_id]++;
3278 if (!(che=get_che(ac, elem_type, elem_id))) {
3279 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
3280 elem_type, elem_id);
3281 err = AVERROR_INVALIDDATA;
3284 samples = ac->oc[1].m4ac.frame_length_short ? 960 : 1024;
3288 switch (elem_type) {
3291 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3297 err = decode_cpe(ac, gb, che);
3302 err = decode_cce(ac, gb, che);
3306 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3311 err = skip_data_stream_element(ac, gb);
3315 uint8_t layout_map[MAX_ELEM_ID*4][3] = {{0}};
3318 int pushed = push_output_configuration(ac);
3319 if (pce_found && !pushed) {
3320 err = AVERROR_INVALIDDATA;
3324 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
3331 av_log(avctx, AV_LOG_ERROR,
3332 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
3333 pop_output_configuration(ac);
3335 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
3337 ac->oc[1].m4ac.chan_config = 0;
3345 elem_id += get_bits(gb, 8) - 1;
3346 if (get_bits_left(gb) < 8 * elem_id) {
3347 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3348 err = AVERROR_INVALIDDATA;
3352 while (elem_id > 0) {
3353 int ret = decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
3363 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3367 if (elem_type < TYPE_DSE) {
3369 che_prev_type = elem_type;
3375 if (get_bits_left(gb) < 3) {
3376 av_log(avctx, AV_LOG_ERROR, overread_err);
3377 err = AVERROR_INVALIDDATA;
3382 if (!avctx->channels) {
3387 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3388 samples <<= multiplier;
3390 spectral_to_sample(ac, samples);
3392 if (ac->oc[1].status && audio_found) {
3393 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3394 avctx->frame_size = samples;
3395 ac->oc[1].status = OC_LOCKED;
3399 avctx->internal->skip_samples_multiplier = 2;
3401 if (!ac->frame->data[0] && samples) {
3402 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3403 err = AVERROR_INVALIDDATA;
3408 ac->frame->nb_samples = samples;
3409 ac->frame->sample_rate = avctx->sample_rate;
3411 av_frame_unref(ac->frame);
3412 *got_frame_ptr = !!samples;
3414 /* for dual-mono audio (SCE + SCE) */
3415 is_dmono = ac->dmono_mode && sce_count == 2 &&
3416 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
3418 if (ac->dmono_mode == 1)
3419 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3420 else if (ac->dmono_mode == 2)
3421 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3426 pop_output_configuration(ac);
3430 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3431 int *got_frame_ptr, AVPacket *avpkt)
3433 AACContext *ac = avctx->priv_data;
3434 const uint8_t *buf = avpkt->data;
3435 int buf_size = avpkt->size;
3440 buffer_size_t new_extradata_size;
3441 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3442 AV_PKT_DATA_NEW_EXTRADATA,
3443 &new_extradata_size);
3444 buffer_size_t jp_dualmono_size;
3445 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3446 AV_PKT_DATA_JP_DUALMONO,
3449 if (new_extradata) {
3450 /* discard previous configuration */
3451 ac->oc[1].status = OC_NONE;
3452 err = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3454 new_extradata_size * 8LL, 1);
3461 if (jp_dualmono && jp_dualmono_size > 0)
3462 ac->dmono_mode = 1 + *jp_dualmono;
3463 if (ac->force_dmono_mode >= 0)
3464 ac->dmono_mode = ac->force_dmono_mode;
3466 if (INT_MAX / 8 <= buf_size)
3467 return AVERROR_INVALIDDATA;
3469 if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)
3472 switch (ac->oc[1].m4ac.object_type) {
3474 case AOT_ER_AAC_LTP:
3476 case AOT_ER_AAC_ELD:
3477 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3480 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3485 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3486 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3487 if (buf[buf_offset])
3490 return buf_size > buf_offset ? buf_consumed : buf_size;
3493 static av_cold int aac_decode_close(AVCodecContext *avctx)
3495 AACContext *ac = avctx->priv_data;
3498 for (i = 0; i < MAX_ELEM_ID; i++) {
3499 for (type = 0; type < 4; type++) {
3500 if (ac->che[type][i])
3501 AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][i]->sbr);
3502 av_freep(&ac->che[type][i]);
3506 ff_mdct_end(&ac->mdct);
3507 ff_mdct_end(&ac->mdct_small);
3508 ff_mdct_end(&ac->mdct_ld);
3509 ff_mdct_end(&ac->mdct_ltp);
3511 ff_mdct15_uninit(&ac->mdct120);
3512 ff_mdct15_uninit(&ac->mdct480);
3513 ff_mdct15_uninit(&ac->mdct960);
3515 av_freep(&ac->fdsp);
3519 static void aacdec_init(AACContext *c)
3521 c->imdct_and_windowing = imdct_and_windowing;
3522 c->apply_ltp = apply_ltp;
3523 c->apply_tns = apply_tns;
3524 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3525 c->update_ltp = update_ltp;
3527 c->vector_pow43 = vector_pow43;
3528 c->subband_scale = subband_scale;
3533 ff_aacdec_init_mips(c);
3534 #endif /* !USE_FIXED */
3537 * AVOptions for Japanese DTV specific extensions (ADTS only)
3539 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3540 static const AVOption options[] = {
3541 {"dual_mono_mode", "Select the channel to decode for dual mono",
3542 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3543 AACDEC_FLAGS, "dual_mono_mode"},
3545 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3546 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3547 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3548 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3553 static const AVClass aac_decoder_class = {
3554 .class_name = "AAC decoder",
3555 .item_name = av_default_item_name,
3557 .version = LIBAVUTIL_VERSION_INT,