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 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
271 int i, n, total_non_cc_elements;
272 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
273 int num_front_channels, num_side_channels, num_back_channels;
276 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
281 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
282 if (num_front_channels < 0)
285 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
286 if (num_side_channels < 0)
289 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
290 if (num_back_channels < 0)
293 if (num_side_channels == 0 && num_back_channels >= 4) {
294 num_side_channels = 2;
295 num_back_channels -= 2;
299 if (num_front_channels & 1) {
300 e2c_vec[i] = (struct elem_to_channel) {
301 .av_position = AV_CH_FRONT_CENTER,
303 .elem_id = layout_map[i][1],
304 .aac_position = AAC_CHANNEL_FRONT
306 layout |= e2c_vec[i].av_position;
308 num_front_channels--;
310 if (num_front_channels >= 4) {
311 i += assign_pair(e2c_vec, layout_map, i,
312 AV_CH_FRONT_LEFT_OF_CENTER,
313 AV_CH_FRONT_RIGHT_OF_CENTER,
314 AAC_CHANNEL_FRONT, &layout);
315 num_front_channels -= 2;
317 if (num_front_channels >= 2) {
318 i += assign_pair(e2c_vec, layout_map, i,
321 AAC_CHANNEL_FRONT, &layout);
322 num_front_channels -= 2;
324 while (num_front_channels >= 2) {
325 i += assign_pair(e2c_vec, layout_map, i,
328 AAC_CHANNEL_FRONT, &layout);
329 num_front_channels -= 2;
332 if (num_side_channels >= 2) {
333 i += assign_pair(e2c_vec, layout_map, i,
336 AAC_CHANNEL_FRONT, &layout);
337 num_side_channels -= 2;
339 while (num_side_channels >= 2) {
340 i += assign_pair(e2c_vec, layout_map, i,
343 AAC_CHANNEL_SIDE, &layout);
344 num_side_channels -= 2;
347 while (num_back_channels >= 4) {
348 i += assign_pair(e2c_vec, layout_map, i,
351 AAC_CHANNEL_BACK, &layout);
352 num_back_channels -= 2;
354 if (num_back_channels >= 2) {
355 i += assign_pair(e2c_vec, layout_map, i,
358 AAC_CHANNEL_BACK, &layout);
359 num_back_channels -= 2;
361 if (num_back_channels) {
362 e2c_vec[i] = (struct elem_to_channel) {
363 .av_position = AV_CH_BACK_CENTER,
365 .elem_id = layout_map[i][1],
366 .aac_position = AAC_CHANNEL_BACK
368 layout |= e2c_vec[i].av_position;
373 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
374 e2c_vec[i] = (struct elem_to_channel) {
375 .av_position = AV_CH_LOW_FREQUENCY,
377 .elem_id = layout_map[i][1],
378 .aac_position = AAC_CHANNEL_LFE
380 layout |= e2c_vec[i].av_position;
383 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
384 e2c_vec[i] = (struct elem_to_channel) {
385 .av_position = AV_CH_LOW_FREQUENCY_2,
387 .elem_id = layout_map[i][1],
388 .aac_position = AAC_CHANNEL_LFE
390 layout |= e2c_vec[i].av_position;
393 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
394 e2c_vec[i] = (struct elem_to_channel) {
395 .av_position = UINT64_MAX,
397 .elem_id = layout_map[i][1],
398 .aac_position = AAC_CHANNEL_LFE
403 // The previous checks would end up at 8 at this point for 22.2
404 if (tags == 16 && i == 8) {
405 e2c_vec[i] = (struct elem_to_channel) {
406 .av_position = AV_CH_TOP_FRONT_CENTER,
407 .syn_ele = layout_map[i][0],
408 .elem_id = layout_map[i][1],
409 .aac_position = layout_map[i][2]
410 }; layout |= e2c_vec[i].av_position; i++;
411 i += assign_pair(e2c_vec, layout_map, i,
412 AV_CH_TOP_FRONT_LEFT,
413 AV_CH_TOP_FRONT_RIGHT,
416 i += assign_pair(e2c_vec, layout_map, i,
418 AV_CH_TOP_SIDE_RIGHT,
421 e2c_vec[i] = (struct elem_to_channel) {
422 .av_position = AV_CH_TOP_CENTER,
423 .syn_ele = layout_map[i][0],
424 .elem_id = layout_map[i][1],
425 .aac_position = layout_map[i][2]
426 }; layout |= e2c_vec[i].av_position; i++;
427 i += assign_pair(e2c_vec, layout_map, i,
429 AV_CH_TOP_BACK_RIGHT,
432 e2c_vec[i] = (struct elem_to_channel) {
433 .av_position = AV_CH_TOP_BACK_CENTER,
434 .syn_ele = layout_map[i][0],
435 .elem_id = layout_map[i][1],
436 .aac_position = layout_map[i][2]
437 }; layout |= e2c_vec[i].av_position; i++;
438 e2c_vec[i] = (struct elem_to_channel) {
439 .av_position = AV_CH_BOTTOM_FRONT_CENTER,
440 .syn_ele = layout_map[i][0],
441 .elem_id = layout_map[i][1],
442 .aac_position = layout_map[i][2]
443 }; layout |= e2c_vec[i].av_position; i++;
444 i += assign_pair(e2c_vec, layout_map, i,
445 AV_CH_BOTTOM_FRONT_LEFT,
446 AV_CH_BOTTOM_FRONT_RIGHT,
451 total_non_cc_elements = n = i;
453 if (tags == 16 && total_non_cc_elements == 16) {
454 // For 22.2 reorder the result as needed
455 FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[0]); // FL & FR first (final), FC third
456 FFSWAP(struct elem_to_channel, e2c_vec[2], e2c_vec[1]); // FC second (final), FLc & FRc third
457 FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[2]); // LFE1 third (final), FLc & FRc seventh
458 FFSWAP(struct elem_to_channel, e2c_vec[4], e2c_vec[3]); // BL & BR fourth (final), SiL & SiR fifth
459 FFSWAP(struct elem_to_channel, e2c_vec[6], e2c_vec[4]); // FLc & FRc fifth (final), SiL & SiR seventh
460 FFSWAP(struct elem_to_channel, e2c_vec[7], e2c_vec[6]); // LFE2 seventh (final), SiL & SiR eight (final)
461 FFSWAP(struct elem_to_channel, e2c_vec[9], e2c_vec[8]); // TpFL & TpFR ninth (final), TFC tenth (final)
462 FFSWAP(struct elem_to_channel, e2c_vec[11], e2c_vec[10]); // TC eleventh (final), TpSiL & TpSiR twelth
463 FFSWAP(struct elem_to_channel, e2c_vec[12], e2c_vec[11]); // TpBL & TpBR twelth (final), TpSiL & TpSiR thirteenth (final)
465 // For everything else, utilize the AV channel position define as a
469 for (i = 1; i < n; i++)
470 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
471 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
479 for (i = 0; i < total_non_cc_elements; i++) {
480 layout_map[i][0] = e2c_vec[i].syn_ele;
481 layout_map[i][1] = e2c_vec[i].elem_id;
482 layout_map[i][2] = e2c_vec[i].aac_position;
489 * Save current output configuration if and only if it has been locked.
491 static int push_output_configuration(AACContext *ac) {
494 if (ac->oc[1].status == OC_LOCKED || ac->oc[0].status == OC_NONE) {
495 ac->oc[0] = ac->oc[1];
498 ac->oc[1].status = OC_NONE;
503 * Restore the previous output configuration if and only if the current
504 * configuration is unlocked.
506 static void pop_output_configuration(AACContext *ac) {
507 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
508 ac->oc[1] = ac->oc[0];
509 ac->avctx->channels = ac->oc[1].channels;
510 ac->avctx->channel_layout = ac->oc[1].channel_layout;
511 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
512 ac->oc[1].status, 0);
517 * Configure output channel order based on the current program
518 * configuration element.
520 * @return Returns error status. 0 - OK, !0 - error
522 static int output_configure(AACContext *ac,
523 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
524 enum OCStatus oc_type, int get_new_frame)
526 AVCodecContext *avctx = ac->avctx;
527 int i, channels = 0, ret;
529 uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
530 uint8_t type_counts[TYPE_END] = { 0 };
532 if (ac->oc[1].layout_map != layout_map) {
533 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
534 ac->oc[1].layout_map_tags = tags;
536 for (i = 0; i < tags; i++) {
537 int type = layout_map[i][0];
538 int id = layout_map[i][1];
539 id_map[type][id] = type_counts[type]++;
540 if (id_map[type][id] >= MAX_ELEM_ID) {
541 avpriv_request_sample(ac->avctx, "Too large remapped id");
542 return AVERROR_PATCHWELCOME;
545 // Try to sniff a reasonable channel order, otherwise output the
546 // channels in the order the PCE declared them.
547 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
548 layout = sniff_channel_order(layout_map, tags);
549 for (i = 0; i < tags; i++) {
550 int type = layout_map[i][0];
551 int id = layout_map[i][1];
552 int iid = id_map[type][id];
553 int position = layout_map[i][2];
554 // Allocate or free elements depending on if they are in the
555 // current program configuration.
556 ret = che_configure(ac, position, type, iid, &channels);
559 ac->tag_che_map[type][id] = ac->che[type][iid];
561 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
562 if (layout == AV_CH_FRONT_CENTER) {
563 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
569 if (layout) avctx->channel_layout = layout;
570 ac->oc[1].channel_layout = layout;
571 avctx->channels = ac->oc[1].channels = channels;
572 ac->oc[1].status = oc_type;
575 if ((ret = frame_configure_elements(ac->avctx)) < 0)
582 static void flush(AVCodecContext *avctx)
584 AACContext *ac= avctx->priv_data;
587 for (type = 3; type >= 0; type--) {
588 for (i = 0; i < MAX_ELEM_ID; i++) {
589 ChannelElement *che = ac->che[type][i];
591 for (j = 0; j <= 1; j++) {
592 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
600 * Set up channel positions based on a default channel configuration
601 * as specified in table 1.17.
603 * @return Returns error status. 0 - OK, !0 - error
605 static int set_default_channel_config(AACContext *ac, AVCodecContext *avctx,
606 uint8_t (*layout_map)[3],
610 if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
611 channel_config > 13) {
612 av_log(avctx, AV_LOG_ERROR,
613 "invalid default channel configuration (%d)\n",
615 return AVERROR_INVALIDDATA;
617 *tags = tags_per_config[channel_config];
618 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
619 *tags * sizeof(*layout_map));
622 * AAC specification has 7.1(wide) as a default layout for 8-channel streams.
623 * However, at least Nero AAC encoder encodes 7.1 streams using the default
624 * channel config 7, mapping the side channels of the original audio stream
625 * to the second AAC_CHANNEL_FRONT pair in the AAC stream. Similarly, e.g. FAAD
626 * decodes the second AAC_CHANNEL_FRONT pair as side channels, therefore decoding
627 * the incorrect streams as if they were correct (and as the encoder intended).
629 * As actual intended 7.1(wide) streams are very rare, default to assuming a
630 * 7.1 layout was intended.
632 if (channel_config == 7 && avctx->strict_std_compliance < FF_COMPLIANCE_STRICT && (!ac || !ac->warned_71_wide++)) {
633 av_log(avctx, AV_LOG_INFO, "Assuming an incorrectly encoded 7.1 channel layout"
634 " instead of a spec-compliant 7.1(wide) layout, use -strict %d to decode"
635 " according to the specification instead.\n", FF_COMPLIANCE_STRICT);
636 layout_map[2][2] = AAC_CHANNEL_SIDE;
642 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
644 /* For PCE based channel configurations map the channels solely based
646 if (!ac->oc[1].m4ac.chan_config) {
647 return ac->tag_che_map[type][elem_id];
649 // Allow single CPE stereo files to be signalled with mono configuration.
650 if (!ac->tags_mapped && type == TYPE_CPE &&
651 ac->oc[1].m4ac.chan_config == 1) {
652 uint8_t layout_map[MAX_ELEM_ID*4][3];
654 push_output_configuration(ac);
656 av_log(ac->avctx, AV_LOG_DEBUG, "mono with CPE\n");
658 if (set_default_channel_config(ac, ac->avctx, layout_map,
659 &layout_map_tags, 2) < 0)
661 if (output_configure(ac, layout_map, layout_map_tags,
662 OC_TRIAL_FRAME, 1) < 0)
665 ac->oc[1].m4ac.chan_config = 2;
666 ac->oc[1].m4ac.ps = 0;
669 if (!ac->tags_mapped && type == TYPE_SCE &&
670 ac->oc[1].m4ac.chan_config == 2) {
671 uint8_t layout_map[MAX_ELEM_ID * 4][3];
673 push_output_configuration(ac);
675 av_log(ac->avctx, AV_LOG_DEBUG, "stereo with SCE\n");
677 if (set_default_channel_config(ac, ac->avctx, layout_map,
678 &layout_map_tags, 1) < 0)
680 if (output_configure(ac, layout_map, layout_map_tags,
681 OC_TRIAL_FRAME, 1) < 0)
684 ac->oc[1].m4ac.chan_config = 1;
685 if (ac->oc[1].m4ac.sbr)
686 ac->oc[1].m4ac.ps = -1;
688 /* For indexed channel configurations map the channels solely based
690 switch (ac->oc[1].m4ac.chan_config) {
692 if (ac->tags_mapped > 3 && ((type == TYPE_CPE && elem_id < 8) ||
693 (type == TYPE_SCE && elem_id < 6) ||
694 (type == TYPE_LFE && elem_id < 2))) {
696 return ac->tag_che_map[type][elem_id] = ac->che[type][elem_id];
700 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
702 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
705 if (ac->tags_mapped == 2 &&
706 ac->oc[1].m4ac.chan_config == 11 &&
709 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
712 /* Some streams incorrectly code 5.1 audio as
713 * SCE[0] CPE[0] CPE[1] SCE[1]
715 * SCE[0] CPE[0] CPE[1] LFE[0].
716 * If we seem to have encountered such a stream, transfer
717 * the LFE[0] element to the SCE[1]'s mapping */
718 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
719 if (!ac->warned_remapping_once && (type != TYPE_LFE || elem_id != 0)) {
720 av_log(ac->avctx, AV_LOG_WARNING,
721 "This stream seems to incorrectly report its last channel as %s[%d], mapping to LFE[0]\n",
722 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
723 ac->warned_remapping_once++;
726 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
729 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
731 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
734 /* Some streams incorrectly code 4.0 audio as
735 * SCE[0] CPE[0] LFE[0]
737 * SCE[0] CPE[0] SCE[1].
738 * If we seem to have encountered such a stream, transfer
739 * the SCE[1] element to the LFE[0]'s mapping */
740 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
741 if (!ac->warned_remapping_once && (type != TYPE_SCE || elem_id != 1)) {
742 av_log(ac->avctx, AV_LOG_WARNING,
743 "This stream seems to incorrectly report its last channel as %s[%d], mapping to SCE[1]\n",
744 type == TYPE_SCE ? "SCE" : "LFE", elem_id);
745 ac->warned_remapping_once++;
748 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_SCE][1];
750 if (ac->tags_mapped == 2 &&
751 ac->oc[1].m4ac.chan_config == 4 &&
754 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
758 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
761 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
762 } else if (ac->oc[1].m4ac.chan_config == 2) {
766 if (!ac->tags_mapped && type == TYPE_SCE) {
768 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
776 * Decode an array of 4 bit element IDs, optionally interleaved with a
777 * stereo/mono switching bit.
779 * @param type speaker type/position for these channels
781 static void decode_channel_map(uint8_t layout_map[][3],
782 enum ChannelPosition type,
783 GetBitContext *gb, int n)
786 enum RawDataBlockType syn_ele;
788 case AAC_CHANNEL_FRONT:
789 case AAC_CHANNEL_BACK:
790 case AAC_CHANNEL_SIDE:
791 syn_ele = get_bits1(gb);
797 case AAC_CHANNEL_LFE:
801 // AAC_CHANNEL_OFF has no channel map
804 layout_map[0][0] = syn_ele;
805 layout_map[0][1] = get_bits(gb, 4);
806 layout_map[0][2] = type;
811 static inline void relative_align_get_bits(GetBitContext *gb,
812 int reference_position) {
813 int n = (reference_position - get_bits_count(gb) & 7);
819 * Decode program configuration element; reference: table 4.2.
821 * @return Returns error status. 0 - OK, !0 - error
823 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
824 uint8_t (*layout_map)[3],
825 GetBitContext *gb, int byte_align_ref)
827 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
832 skip_bits(gb, 2); // object_type
834 sampling_index = get_bits(gb, 4);
835 if (m4ac->sampling_index != sampling_index)
836 av_log(avctx, AV_LOG_WARNING,
837 "Sample rate index in program config element does not "
838 "match the sample rate index configured by the container.\n");
840 num_front = get_bits(gb, 4);
841 num_side = get_bits(gb, 4);
842 num_back = get_bits(gb, 4);
843 num_lfe = get_bits(gb, 2);
844 num_assoc_data = get_bits(gb, 3);
845 num_cc = get_bits(gb, 4);
848 skip_bits(gb, 4); // mono_mixdown_tag
850 skip_bits(gb, 4); // stereo_mixdown_tag
853 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
855 if (get_bits_left(gb) < 5 * (num_front + num_side + num_back + num_cc) + 4 *(num_lfe + num_assoc_data + num_cc)) {
856 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
859 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
861 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
863 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
865 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
868 skip_bits_long(gb, 4 * num_assoc_data);
870 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
873 relative_align_get_bits(gb, byte_align_ref);
875 /* comment field, first byte is length */
876 comment_len = get_bits(gb, 8) * 8;
877 if (get_bits_left(gb) < comment_len) {
878 av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err);
879 return AVERROR_INVALIDDATA;
881 skip_bits_long(gb, comment_len);
886 * Decode GA "General Audio" specific configuration; reference: table 4.1.
888 * @param ac pointer to AACContext, may be null
889 * @param avctx pointer to AVCCodecContext, used for logging
891 * @return Returns error status. 0 - OK, !0 - error
893 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
895 int get_bit_alignment,
896 MPEG4AudioConfig *m4ac,
899 int extension_flag, ret, ep_config, res_flags;
900 uint8_t layout_map[MAX_ELEM_ID*4][3];
904 if (get_bits1(gb)) { // frameLengthFlag
905 avpriv_report_missing_feature(avctx, "Fixed point 960/120 MDCT window");
906 return AVERROR_PATCHWELCOME;
908 m4ac->frame_length_short = 0;
910 m4ac->frame_length_short = get_bits1(gb);
911 if (m4ac->frame_length_short && m4ac->sbr == 1) {
912 avpriv_report_missing_feature(avctx, "SBR with 960 frame length");
913 if (ac) ac->warned_960_sbr = 1;
919 if (get_bits1(gb)) // dependsOnCoreCoder
920 skip_bits(gb, 14); // coreCoderDelay
921 extension_flag = get_bits1(gb);
923 if (m4ac->object_type == AOT_AAC_SCALABLE ||
924 m4ac->object_type == AOT_ER_AAC_SCALABLE)
925 skip_bits(gb, 3); // layerNr
927 if (channel_config == 0) {
928 skip_bits(gb, 4); // element_instance_tag
929 tags = decode_pce(avctx, m4ac, layout_map, gb, get_bit_alignment);
933 if ((ret = set_default_channel_config(ac, avctx, layout_map,
934 &tags, channel_config)))
938 if (count_channels(layout_map, tags) > 1) {
940 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
943 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
946 if (extension_flag) {
947 switch (m4ac->object_type) {
949 skip_bits(gb, 5); // numOfSubFrame
950 skip_bits(gb, 11); // layer_length
954 case AOT_ER_AAC_SCALABLE:
956 res_flags = get_bits(gb, 3);
958 avpriv_report_missing_feature(avctx,
959 "AAC data resilience (flags %x)",
961 return AVERROR_PATCHWELCOME;
965 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
967 switch (m4ac->object_type) {
970 case AOT_ER_AAC_SCALABLE:
972 ep_config = get_bits(gb, 2);
974 avpriv_report_missing_feature(avctx,
975 "epConfig %d", ep_config);
976 return AVERROR_PATCHWELCOME;
982 static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
984 MPEG4AudioConfig *m4ac,
987 int ret, ep_config, res_flags;
988 uint8_t layout_map[MAX_ELEM_ID*4][3];
990 const int ELDEXT_TERM = 0;
995 if (get_bits1(gb)) { // frameLengthFlag
996 avpriv_request_sample(avctx, "960/120 MDCT window");
997 return AVERROR_PATCHWELCOME;
1000 m4ac->frame_length_short = get_bits1(gb);
1002 res_flags = get_bits(gb, 3);
1004 avpriv_report_missing_feature(avctx,
1005 "AAC data resilience (flags %x)",
1007 return AVERROR_PATCHWELCOME;
1010 if (get_bits1(gb)) { // ldSbrPresentFlag
1011 avpriv_report_missing_feature(avctx,
1013 return AVERROR_PATCHWELCOME;
1016 while (get_bits(gb, 4) != ELDEXT_TERM) {
1017 int len = get_bits(gb, 4);
1019 len += get_bits(gb, 8);
1020 if (len == 15 + 255)
1021 len += get_bits(gb, 16);
1022 if (get_bits_left(gb) < len * 8 + 4) {
1023 av_log(avctx, AV_LOG_ERROR, overread_err);
1024 return AVERROR_INVALIDDATA;
1026 skip_bits_long(gb, 8 * len);
1029 if ((ret = set_default_channel_config(ac, avctx, layout_map,
1030 &tags, channel_config)))
1033 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
1036 ep_config = get_bits(gb, 2);
1038 avpriv_report_missing_feature(avctx,
1039 "epConfig %d", ep_config);
1040 return AVERROR_PATCHWELCOME;
1046 * Decode audio specific configuration; reference: table 1.13.
1048 * @param ac pointer to AACContext, may be null
1049 * @param avctx pointer to AVCCodecContext, used for logging
1050 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
1051 * @param gb buffer holding an audio specific config
1052 * @param get_bit_alignment relative alignment for byte align operations
1053 * @param sync_extension look for an appended sync extension
1055 * @return Returns error status or number of consumed bits. <0 - error
1057 static int decode_audio_specific_config_gb(AACContext *ac,
1058 AVCodecContext *avctx,
1059 MPEG4AudioConfig *m4ac,
1061 int get_bit_alignment,
1065 GetBitContext gbc = *gb;
1067 if ((i = ff_mpeg4audio_get_config_gb(m4ac, &gbc, sync_extension, avctx)) < 0)
1068 return AVERROR_INVALIDDATA;
1070 if (m4ac->sampling_index > 12) {
1071 av_log(avctx, AV_LOG_ERROR,
1072 "invalid sampling rate index %d\n",
1073 m4ac->sampling_index);
1074 return AVERROR_INVALIDDATA;
1076 if (m4ac->object_type == AOT_ER_AAC_LD &&
1077 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
1078 av_log(avctx, AV_LOG_ERROR,
1079 "invalid low delay sampling rate index %d\n",
1080 m4ac->sampling_index);
1081 return AVERROR_INVALIDDATA;
1084 skip_bits_long(gb, i);
1086 switch (m4ac->object_type) {
1093 if ((ret = decode_ga_specific_config(ac, avctx, gb, get_bit_alignment,
1094 m4ac, m4ac->chan_config)) < 0)
1097 case AOT_ER_AAC_ELD:
1098 if ((ret = decode_eld_specific_config(ac, avctx, gb,
1099 m4ac, m4ac->chan_config)) < 0)
1103 avpriv_report_missing_feature(avctx,
1104 "Audio object type %s%d",
1105 m4ac->sbr == 1 ? "SBR+" : "",
1107 return AVERROR(ENOSYS);
1111 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
1112 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
1113 m4ac->sample_rate, m4ac->sbr,
1116 return get_bits_count(gb);
1119 static int decode_audio_specific_config(AACContext *ac,
1120 AVCodecContext *avctx,
1121 MPEG4AudioConfig *m4ac,
1122 const uint8_t *data, int64_t bit_size,
1128 if (bit_size < 0 || bit_size > INT_MAX) {
1129 av_log(avctx, AV_LOG_ERROR, "Audio specific config size is invalid\n");
1130 return AVERROR_INVALIDDATA;
1133 ff_dlog(avctx, "audio specific config size %d\n", (int)bit_size >> 3);
1134 for (i = 0; i < bit_size >> 3; i++)
1135 ff_dlog(avctx, "%02x ", data[i]);
1136 ff_dlog(avctx, "\n");
1138 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
1141 return decode_audio_specific_config_gb(ac, avctx, m4ac, &gb, 0,
1146 * linear congruential pseudorandom number generator
1148 * @param previous_val pointer to the current state of the generator
1150 * @return Returns a 32-bit pseudorandom integer
1152 static av_always_inline int lcg_random(unsigned previous_val)
1154 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
1158 static void reset_all_predictors(PredictorState *ps)
1161 for (i = 0; i < MAX_PREDICTORS; i++)
1162 reset_predict_state(&ps[i]);
1165 static int sample_rate_idx (int rate)
1167 if (92017 <= rate) return 0;
1168 else if (75132 <= rate) return 1;
1169 else if (55426 <= rate) return 2;
1170 else if (46009 <= rate) return 3;
1171 else if (37566 <= rate) return 4;
1172 else if (27713 <= rate) return 5;
1173 else if (23004 <= rate) return 6;
1174 else if (18783 <= rate) return 7;
1175 else if (13856 <= rate) return 8;
1176 else if (11502 <= rate) return 9;
1177 else if (9391 <= rate) return 10;
1181 static void reset_predictor_group(PredictorState *ps, int group_num)
1184 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
1185 reset_predict_state(&ps[i]);
1188 #define AAC_INIT_VLC_STATIC(num, size) \
1189 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1190 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1191 sizeof(ff_aac_spectral_bits[num][0]), \
1192 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1193 sizeof(ff_aac_spectral_codes[num][0]), \
1196 static void aacdec_init(AACContext *ac);
1198 static av_cold void aac_static_table_init(void)
1200 AAC_INIT_VLC_STATIC( 0, 304);
1201 AAC_INIT_VLC_STATIC( 1, 270);
1202 AAC_INIT_VLC_STATIC( 2, 550);
1203 AAC_INIT_VLC_STATIC( 3, 300);
1204 AAC_INIT_VLC_STATIC( 4, 328);
1205 AAC_INIT_VLC_STATIC( 5, 294);
1206 AAC_INIT_VLC_STATIC( 6, 306);
1207 AAC_INIT_VLC_STATIC( 7, 268);
1208 AAC_INIT_VLC_STATIC( 8, 510);
1209 AAC_INIT_VLC_STATIC( 9, 366);
1210 AAC_INIT_VLC_STATIC(10, 462);
1212 AAC_RENAME(ff_aac_sbr_init)();
1216 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1217 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1218 ff_aac_scalefactor_bits,
1219 sizeof(ff_aac_scalefactor_bits[0]),
1220 sizeof(ff_aac_scalefactor_bits[0]),
1221 ff_aac_scalefactor_code,
1222 sizeof(ff_aac_scalefactor_code[0]),
1223 sizeof(ff_aac_scalefactor_code[0]),
1226 // window initialization
1227 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_1024), 4.0, 1024);
1228 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_128), 6.0, 128);
1230 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_long_960), 4.0, 960);
1231 AAC_RENAME(ff_kbd_window_init)(AAC_RENAME(ff_aac_kbd_short_120), 6.0, 120);
1232 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_960), 960);
1233 AAC_RENAME(ff_sine_window_init)(AAC_RENAME(ff_sine_120), 120);
1235 AAC_RENAME(ff_init_ff_sine_windows)(10);
1236 AAC_RENAME(ff_init_ff_sine_windows)( 9);
1237 AAC_RENAME(ff_init_ff_sine_windows)( 7);
1239 AAC_RENAME(ff_cbrt_tableinit)();
1242 static AVOnce aac_table_init = AV_ONCE_INIT;
1244 static av_cold int aac_decode_init(AVCodecContext *avctx)
1246 AACContext *ac = avctx->priv_data;
1249 if (avctx->sample_rate > 96000)
1250 return AVERROR_INVALIDDATA;
1252 ret = ff_thread_once(&aac_table_init, &aac_static_table_init);
1254 return AVERROR_UNKNOWN;
1257 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
1261 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1263 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1264 #endif /* USE_FIXED */
1266 if (avctx->extradata_size > 0) {
1267 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1269 avctx->extradata_size * 8LL,
1274 uint8_t layout_map[MAX_ELEM_ID*4][3];
1275 int layout_map_tags;
1277 sr = sample_rate_idx(avctx->sample_rate);
1278 ac->oc[1].m4ac.sampling_index = sr;
1279 ac->oc[1].m4ac.channels = avctx->channels;
1280 ac->oc[1].m4ac.sbr = -1;
1281 ac->oc[1].m4ac.ps = -1;
1283 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1284 if (ff_mpeg4audio_channels[i] == avctx->channels)
1286 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1289 ac->oc[1].m4ac.chan_config = i;
1291 if (ac->oc[1].m4ac.chan_config) {
1292 int ret = set_default_channel_config(ac, avctx, layout_map,
1293 &layout_map_tags, ac->oc[1].m4ac.chan_config);
1295 output_configure(ac, layout_map, layout_map_tags,
1297 else if (avctx->err_recognition & AV_EF_EXPLODE)
1298 return AVERROR_INVALIDDATA;
1302 if (avctx->channels > MAX_CHANNELS) {
1303 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
1304 return AVERROR_INVALIDDATA;
1308 ac->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1310 ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1311 #endif /* USE_FIXED */
1313 return AVERROR(ENOMEM);
1316 ac->random_state = 0x1f2e3d4c;
1318 AAC_RENAME_32(ff_mdct_init)(&ac->mdct, 11, 1, 1.0 / RANGE15(1024.0));
1319 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ld, 10, 1, 1.0 / RANGE15(512.0));
1320 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_small, 8, 1, 1.0 / RANGE15(128.0));
1321 AAC_RENAME_32(ff_mdct_init)(&ac->mdct_ltp, 11, 0, RANGE15(-2.0));
1323 ret = ff_mdct15_init(&ac->mdct120, 1, 3, 1.0f/(16*1024*120*2));
1326 ret = ff_mdct15_init(&ac->mdct480, 1, 5, 1.0f/(16*1024*960));
1329 ret = ff_mdct15_init(&ac->mdct960, 1, 6, 1.0f/(16*1024*960*2));
1338 * Skip data_stream_element; reference: table 4.10.
1340 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1342 int byte_align = get_bits1(gb);
1343 int count = get_bits(gb, 8);
1345 count += get_bits(gb, 8);
1349 if (get_bits_left(gb) < 8 * count) {
1350 av_log(ac->avctx, AV_LOG_ERROR, "skip_data_stream_element: "overread_err);
1351 return AVERROR_INVALIDDATA;
1353 skip_bits_long(gb, 8 * count);
1357 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1361 if (get_bits1(gb)) {
1362 ics->predictor_reset_group = get_bits(gb, 5);
1363 if (ics->predictor_reset_group == 0 ||
1364 ics->predictor_reset_group > 30) {
1365 av_log(ac->avctx, AV_LOG_ERROR,
1366 "Invalid Predictor Reset Group.\n");
1367 return AVERROR_INVALIDDATA;
1370 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1371 ics->prediction_used[sfb] = get_bits1(gb);
1377 * Decode Long Term Prediction data; reference: table 4.xx.
1379 static void decode_ltp(LongTermPrediction *ltp,
1380 GetBitContext *gb, uint8_t max_sfb)
1384 ltp->lag = get_bits(gb, 11);
1385 ltp->coef = ltp_coef[get_bits(gb, 3)];
1386 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1387 ltp->used[sfb] = get_bits1(gb);
1391 * Decode Individual Channel Stream info; reference: table 4.6.
1393 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1396 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1397 const int aot = m4ac->object_type;
1398 const int sampling_index = m4ac->sampling_index;
1399 int ret_fail = AVERROR_INVALIDDATA;
1401 if (aot != AOT_ER_AAC_ELD) {
1402 if (get_bits1(gb)) {
1403 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1404 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1405 return AVERROR_INVALIDDATA;
1407 ics->window_sequence[1] = ics->window_sequence[0];
1408 ics->window_sequence[0] = get_bits(gb, 2);
1409 if (aot == AOT_ER_AAC_LD &&
1410 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1411 av_log(ac->avctx, AV_LOG_ERROR,
1412 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1413 "window sequence %d found.\n", ics->window_sequence[0]);
1414 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1415 return AVERROR_INVALIDDATA;
1417 ics->use_kb_window[1] = ics->use_kb_window[0];
1418 ics->use_kb_window[0] = get_bits1(gb);
1420 ics->num_window_groups = 1;
1421 ics->group_len[0] = 1;
1422 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1424 ics->max_sfb = get_bits(gb, 4);
1425 for (i = 0; i < 7; i++) {
1426 if (get_bits1(gb)) {
1427 ics->group_len[ics->num_window_groups - 1]++;
1429 ics->num_window_groups++;
1430 ics->group_len[ics->num_window_groups - 1] = 1;
1433 ics->num_windows = 8;
1434 if (m4ac->frame_length_short) {
1435 ics->swb_offset = ff_swb_offset_120[sampling_index];
1436 ics->num_swb = ff_aac_num_swb_120[sampling_index];
1438 ics->swb_offset = ff_swb_offset_128[sampling_index];
1439 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1441 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
1442 ics->predictor_present = 0;
1444 ics->max_sfb = get_bits(gb, 6);
1445 ics->num_windows = 1;
1446 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
1447 if (m4ac->frame_length_short) {
1448 ics->swb_offset = ff_swb_offset_480[sampling_index];
1449 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1450 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1452 ics->swb_offset = ff_swb_offset_512[sampling_index];
1453 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1454 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1456 if (!ics->num_swb || !ics->swb_offset) {
1457 ret_fail = AVERROR_BUG;
1461 if (m4ac->frame_length_short) {
1462 ics->num_swb = ff_aac_num_swb_960[sampling_index];
1463 ics->swb_offset = ff_swb_offset_960[sampling_index];
1465 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1466 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1468 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1470 if (aot != AOT_ER_AAC_ELD) {
1471 ics->predictor_present = get_bits1(gb);
1472 ics->predictor_reset_group = 0;
1474 if (ics->predictor_present) {
1475 if (aot == AOT_AAC_MAIN) {
1476 if (decode_prediction(ac, ics, gb)) {
1479 } else if (aot == AOT_AAC_LC ||
1480 aot == AOT_ER_AAC_LC) {
1481 av_log(ac->avctx, AV_LOG_ERROR,
1482 "Prediction is not allowed in AAC-LC.\n");
1485 if (aot == AOT_ER_AAC_LD) {
1486 av_log(ac->avctx, AV_LOG_ERROR,
1487 "LTP in ER AAC LD not yet implemented.\n");
1488 ret_fail = AVERROR_PATCHWELCOME;
1491 if ((ics->ltp.present = get_bits(gb, 1)))
1492 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1497 if (ics->max_sfb > ics->num_swb) {
1498 av_log(ac->avctx, AV_LOG_ERROR,
1499 "Number of scalefactor bands in group (%d) "
1500 "exceeds limit (%d).\n",
1501 ics->max_sfb, ics->num_swb);
1512 * Decode band types (section_data payload); reference: table 4.46.
1514 * @param band_type array of the used band type
1515 * @param band_type_run_end array of the last scalefactor band of a band type run
1517 * @return Returns error status. 0 - OK, !0 - error
1519 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1520 int band_type_run_end[120], GetBitContext *gb,
1521 IndividualChannelStream *ics)
1524 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1525 for (g = 0; g < ics->num_window_groups; g++) {
1527 while (k < ics->max_sfb) {
1528 uint8_t sect_end = k;
1530 int sect_band_type = get_bits(gb, 4);
1531 if (sect_band_type == 12) {
1532 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1533 return AVERROR_INVALIDDATA;
1536 sect_len_incr = get_bits(gb, bits);
1537 sect_end += sect_len_incr;
1538 if (get_bits_left(gb) < 0) {
1539 av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
1540 return AVERROR_INVALIDDATA;
1542 if (sect_end > ics->max_sfb) {
1543 av_log(ac->avctx, AV_LOG_ERROR,
1544 "Number of bands (%d) exceeds limit (%d).\n",
1545 sect_end, ics->max_sfb);
1546 return AVERROR_INVALIDDATA;
1548 } while (sect_len_incr == (1 << bits) - 1);
1549 for (; k < sect_end; k++) {
1550 band_type [idx] = sect_band_type;
1551 band_type_run_end[idx++] = sect_end;
1559 * Decode scalefactors; reference: table 4.47.
1561 * @param global_gain first scalefactor value as scalefactors are differentially coded
1562 * @param band_type array of the used band type
1563 * @param band_type_run_end array of the last scalefactor band of a band type run
1564 * @param sf array of scalefactors or intensity stereo positions
1566 * @return Returns error status. 0 - OK, !0 - error
1568 static int decode_scalefactors(AACContext *ac, INTFLOAT sf[120], GetBitContext *gb,
1569 unsigned int global_gain,
1570 IndividualChannelStream *ics,
1571 enum BandType band_type[120],
1572 int band_type_run_end[120])
1575 int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
1578 for (g = 0; g < ics->num_window_groups; g++) {
1579 for (i = 0; i < ics->max_sfb;) {
1580 int run_end = band_type_run_end[idx];
1581 if (band_type[idx] == ZERO_BT) {
1582 for (; i < run_end; i++, idx++)
1584 } else if ((band_type[idx] == INTENSITY_BT) ||
1585 (band_type[idx] == INTENSITY_BT2)) {
1586 for (; i < run_end; i++, idx++) {
1587 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1588 clipped_offset = av_clip(offset[2], -155, 100);
1589 if (offset[2] != clipped_offset) {
1590 avpriv_request_sample(ac->avctx,
1591 "If you heard an audible artifact, there may be a bug in the decoder. "
1592 "Clipped intensity stereo position (%d -> %d)",
1593 offset[2], clipped_offset);
1596 sf[idx] = 100 - clipped_offset;
1598 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1599 #endif /* USE_FIXED */
1601 } else if (band_type[idx] == NOISE_BT) {
1602 for (; i < run_end; i++, idx++) {
1603 if (noise_flag-- > 0)
1604 offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
1606 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1607 clipped_offset = av_clip(offset[1], -100, 155);
1608 if (offset[1] != clipped_offset) {
1609 avpriv_request_sample(ac->avctx,
1610 "If you heard an audible artifact, there may be a bug in the decoder. "
1611 "Clipped noise gain (%d -> %d)",
1612 offset[1], clipped_offset);
1615 sf[idx] = -(100 + clipped_offset);
1617 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1618 #endif /* USE_FIXED */
1621 for (; i < run_end; i++, idx++) {
1622 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
1623 if (offset[0] > 255U) {
1624 av_log(ac->avctx, AV_LOG_ERROR,
1625 "Scalefactor (%d) out of range.\n", offset[0]);
1626 return AVERROR_INVALIDDATA;
1629 sf[idx] = -offset[0];
1631 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1632 #endif /* USE_FIXED */
1641 * Decode pulse data; reference: table 4.7.
1643 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1644 const uint16_t *swb_offset, int num_swb)
1647 pulse->num_pulse = get_bits(gb, 2) + 1;
1648 pulse_swb = get_bits(gb, 6);
1649 if (pulse_swb >= num_swb)
1651 pulse->pos[0] = swb_offset[pulse_swb];
1652 pulse->pos[0] += get_bits(gb, 5);
1653 if (pulse->pos[0] >= swb_offset[num_swb])
1655 pulse->amp[0] = get_bits(gb, 4);
1656 for (i = 1; i < pulse->num_pulse; i++) {
1657 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1658 if (pulse->pos[i] >= swb_offset[num_swb])
1660 pulse->amp[i] = get_bits(gb, 4);
1666 * Decode Temporal Noise Shaping data; reference: table 4.48.
1668 * @return Returns error status. 0 - OK, !0 - error
1670 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1671 GetBitContext *gb, const IndividualChannelStream *ics)
1673 int w, filt, i, coef_len, coef_res, coef_compress;
1674 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1675 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1676 for (w = 0; w < ics->num_windows; w++) {
1677 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1678 coef_res = get_bits1(gb);
1680 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1682 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1684 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1685 av_log(ac->avctx, AV_LOG_ERROR,
1686 "TNS filter order %d is greater than maximum %d.\n",
1687 tns->order[w][filt], tns_max_order);
1688 tns->order[w][filt] = 0;
1689 return AVERROR_INVALIDDATA;
1691 if (tns->order[w][filt]) {
1692 tns->direction[w][filt] = get_bits1(gb);
1693 coef_compress = get_bits1(gb);
1694 coef_len = coef_res + 3 - coef_compress;
1695 tmp2_idx = 2 * coef_compress + coef_res;
1697 for (i = 0; i < tns->order[w][filt]; i++)
1698 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1707 * Decode Mid/Side data; reference: table 4.54.
1709 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1710 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1711 * [3] reserved for scalable AAC
1713 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1717 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1718 if (ms_present == 1) {
1719 for (idx = 0; idx < max_idx; idx++)
1720 cpe->ms_mask[idx] = get_bits1(gb);
1721 } else if (ms_present == 2) {
1722 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
1727 * Decode spectral data; reference: table 4.50.
1728 * Dequantize and scale spectral data; reference: 4.6.3.3.
1730 * @param coef array of dequantized, scaled spectral data
1731 * @param sf array of scalefactors or intensity stereo positions
1732 * @param pulse_present set if pulses are present
1733 * @param pulse pointer to pulse data struct
1734 * @param band_type array of the used band type
1736 * @return Returns error status. 0 - OK, !0 - error
1738 static int decode_spectrum_and_dequant(AACContext *ac, INTFLOAT coef[1024],
1739 GetBitContext *gb, const INTFLOAT sf[120],
1740 int pulse_present, const Pulse *pulse,
1741 const IndividualChannelStream *ics,
1742 enum BandType band_type[120])
1744 int i, k, g, idx = 0;
1745 const int c = 1024 / ics->num_windows;
1746 const uint16_t *offsets = ics->swb_offset;
1747 INTFLOAT *coef_base = coef;
1749 for (g = 0; g < ics->num_windows; g++)
1750 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1751 sizeof(INTFLOAT) * (c - offsets[ics->max_sfb]));
1753 for (g = 0; g < ics->num_window_groups; g++) {
1754 unsigned g_len = ics->group_len[g];
1756 for (i = 0; i < ics->max_sfb; i++, idx++) {
1757 const unsigned cbt_m1 = band_type[idx] - 1;
1758 INTFLOAT *cfo = coef + offsets[i];
1759 int off_len = offsets[i + 1] - offsets[i];
1762 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1763 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1764 memset(cfo, 0, off_len * sizeof(*cfo));
1766 } else if (cbt_m1 == NOISE_BT - 1) {
1767 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1768 INTFLOAT band_energy;
1770 for (k = 0; k < off_len; k++) {
1771 ac->random_state = lcg_random(ac->random_state);
1772 cfo[k] = ac->random_state >> 3;
1775 band_energy = ac->fdsp->scalarproduct_fixed(cfo, cfo, off_len);
1776 band_energy = fixed_sqrt(band_energy, 31);
1777 noise_scale(cfo, sf[idx], band_energy, off_len);
1781 for (k = 0; k < off_len; k++) {
1782 ac->random_state = lcg_random(ac->random_state);
1783 cfo[k] = ac->random_state;
1786 band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
1787 scale = sf[idx] / sqrtf(band_energy);
1788 ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
1789 #endif /* USE_FIXED */
1793 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1794 #endif /* !USE_FIXED */
1795 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1796 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1797 OPEN_READER(re, gb);
1799 switch (cbt_m1 >> 1) {
1801 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1809 UPDATE_CACHE(re, gb);
1810 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1811 cb_idx = cb_vector_idx[code];
1813 cf = DEC_SQUAD(cf, cb_idx);
1815 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1816 #endif /* USE_FIXED */
1822 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1832 UPDATE_CACHE(re, gb);
1833 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1834 cb_idx = cb_vector_idx[code];
1835 nnz = cb_idx >> 8 & 15;
1836 bits = nnz ? GET_CACHE(re, gb) : 0;
1837 LAST_SKIP_BITS(re, gb, nnz);
1839 cf = DEC_UQUAD(cf, cb_idx, bits);
1841 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1842 #endif /* USE_FIXED */
1848 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1856 UPDATE_CACHE(re, gb);
1857 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1858 cb_idx = cb_vector_idx[code];
1860 cf = DEC_SPAIR(cf, cb_idx);
1862 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1863 #endif /* USE_FIXED */
1870 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1880 UPDATE_CACHE(re, gb);
1881 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1882 cb_idx = cb_vector_idx[code];
1883 nnz = cb_idx >> 8 & 15;
1884 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1885 LAST_SKIP_BITS(re, gb, nnz);
1887 cf = DEC_UPAIR(cf, cb_idx, sign);
1889 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1890 #endif /* USE_FIXED */
1896 for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
1902 uint32_t *icf = (uint32_t *) cf;
1903 #endif /* USE_FIXED */
1913 UPDATE_CACHE(re, gb);
1914 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1922 cb_idx = cb_vector_idx[code];
1925 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1926 LAST_SKIP_BITS(re, gb, nnz);
1928 for (j = 0; j < 2; j++) {
1932 /* The total length of escape_sequence must be < 22 bits according
1933 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1934 UPDATE_CACHE(re, gb);
1935 b = GET_CACHE(re, gb);
1936 b = 31 - av_log2(~b);
1939 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1940 return AVERROR_INVALIDDATA;
1943 SKIP_BITS(re, gb, b + 1);
1945 n = (1 << b) + SHOW_UBITS(re, gb, b);
1946 LAST_SKIP_BITS(re, gb, b);
1953 *icf++ = ff_cbrt_tab[n] | (bits & 1U<<31);
1954 #endif /* USE_FIXED */
1963 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1964 *icf++ = (bits & 1U<<31) | v;
1965 #endif /* USE_FIXED */
1972 ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1973 #endif /* !USE_FIXED */
1977 CLOSE_READER(re, gb);
1983 if (pulse_present) {
1985 for (i = 0; i < pulse->num_pulse; i++) {
1986 INTFLOAT co = coef_base[ pulse->pos[i] ];
1987 while (offsets[idx + 1] <= pulse->pos[i])
1989 if (band_type[idx] != NOISE_BT && sf[idx]) {
1990 INTFLOAT ico = -pulse->amp[i];
1993 ico = co + (co > 0 ? -ico : ico);
1995 coef_base[ pulse->pos[i] ] = ico;
1999 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
2001 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
2002 #endif /* USE_FIXED */
2009 for (g = 0; g < ics->num_window_groups; g++) {
2010 unsigned g_len = ics->group_len[g];
2012 for (i = 0; i < ics->max_sfb; i++, idx++) {
2013 const unsigned cbt_m1 = band_type[idx] - 1;
2014 int *cfo = coef + offsets[i];
2015 int off_len = offsets[i + 1] - offsets[i];
2018 if (cbt_m1 < NOISE_BT - 1) {
2019 for (group = 0; group < (int)g_len; group++, cfo+=128) {
2020 ac->vector_pow43(cfo, off_len);
2021 ac->subband_scale(cfo, cfo, sf[idx], 34, off_len, ac->avctx);
2027 #endif /* USE_FIXED */
2032 * Apply AAC-Main style frequency domain prediction.
2034 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
2038 if (!sce->ics.predictor_initialized) {
2039 reset_all_predictors(sce->predictor_state);
2040 sce->ics.predictor_initialized = 1;
2043 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2045 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
2047 for (k = sce->ics.swb_offset[sfb];
2048 k < sce->ics.swb_offset[sfb + 1];
2050 predict(&sce->predictor_state[k], &sce->coeffs[k],
2051 sce->ics.predictor_present &&
2052 sce->ics.prediction_used[sfb]);
2055 if (sce->ics.predictor_reset_group)
2056 reset_predictor_group(sce->predictor_state,
2057 sce->ics.predictor_reset_group);
2059 reset_all_predictors(sce->predictor_state);
2062 static void decode_gain_control(SingleChannelElement * sce, GetBitContext * gb)
2064 // wd_num, wd_test, aloc_size
2065 static const uint8_t gain_mode[4][3] = {
2066 {1, 0, 5}, // ONLY_LONG_SEQUENCE = 0,
2067 {2, 1, 2}, // LONG_START_SEQUENCE,
2068 {8, 0, 2}, // EIGHT_SHORT_SEQUENCE,
2069 {2, 1, 5}, // LONG_STOP_SEQUENCE
2072 const int mode = sce->ics.window_sequence[0];
2075 // FIXME: Store the gain control data on |sce| and do something with it.
2076 uint8_t max_band = get_bits(gb, 2);
2077 for (bd = 0; bd < max_band; bd++) {
2078 for (wd = 0; wd < gain_mode[mode][0]; wd++) {
2079 uint8_t adjust_num = get_bits(gb, 3);
2080 for (ad = 0; ad < adjust_num; ad++) {
2081 skip_bits(gb, 4 + ((wd == 0 && gain_mode[mode][1])
2083 : gain_mode[mode][2]));
2090 * Decode an individual_channel_stream payload; reference: table 4.44.
2092 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
2093 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
2095 * @return Returns error status. 0 - OK, !0 - error
2097 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
2098 GetBitContext *gb, int common_window, int scale_flag)
2101 TemporalNoiseShaping *tns = &sce->tns;
2102 IndividualChannelStream *ics = &sce->ics;
2103 INTFLOAT *out = sce->coeffs;
2104 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
2107 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2108 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
2109 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
2110 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
2111 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2113 /* This assignment is to silence a GCC warning about the variable being used
2114 * uninitialized when in fact it always is.
2116 pulse.num_pulse = 0;
2118 global_gain = get_bits(gb, 8);
2120 if (!common_window && !scale_flag) {
2121 ret = decode_ics_info(ac, ics, gb);
2126 if ((ret = decode_band_types(ac, sce->band_type,
2127 sce->band_type_run_end, gb, ics)) < 0)
2129 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
2130 sce->band_type, sce->band_type_run_end)) < 0)
2135 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
2136 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2137 av_log(ac->avctx, AV_LOG_ERROR,
2138 "Pulse tool not allowed in eight short sequence.\n");
2139 ret = AVERROR_INVALIDDATA;
2142 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
2143 av_log(ac->avctx, AV_LOG_ERROR,
2144 "Pulse data corrupt or invalid.\n");
2145 ret = AVERROR_INVALIDDATA;
2149 tns->present = get_bits1(gb);
2150 if (tns->present && !er_syntax) {
2151 ret = decode_tns(ac, tns, gb, ics);
2155 if (!eld_syntax && get_bits1(gb)) {
2156 decode_gain_control(sce, gb);
2157 if (!ac->warned_gain_control) {
2158 avpriv_report_missing_feature(ac->avctx, "Gain control");
2159 ac->warned_gain_control = 1;
2162 // I see no textual basis in the spec for this occurring after SSR gain
2163 // control, but this is what both reference and real implmentations do
2164 if (tns->present && er_syntax) {
2165 ret = decode_tns(ac, tns, gb, ics);
2171 ret = decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
2172 &pulse, ics, sce->band_type);
2176 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
2177 apply_prediction(ac, sce);
2186 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
2188 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
2190 const IndividualChannelStream *ics = &cpe->ch[0].ics;
2191 INTFLOAT *ch0 = cpe->ch[0].coeffs;
2192 INTFLOAT *ch1 = cpe->ch[1].coeffs;
2193 int g, i, group, idx = 0;
2194 const uint16_t *offsets = ics->swb_offset;
2195 for (g = 0; g < ics->num_window_groups; g++) {
2196 for (i = 0; i < ics->max_sfb; i++, idx++) {
2197 if (cpe->ms_mask[idx] &&
2198 cpe->ch[0].band_type[idx] < NOISE_BT &&
2199 cpe->ch[1].band_type[idx] < NOISE_BT) {
2201 for (group = 0; group < ics->group_len[g]; group++) {
2202 ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
2203 ch1 + group * 128 + offsets[i],
2204 offsets[i+1] - offsets[i]);
2206 for (group = 0; group < ics->group_len[g]; group++) {
2207 ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
2208 ch1 + group * 128 + offsets[i],
2209 offsets[i+1] - offsets[i]);
2210 #endif /* USE_FIXED */
2214 ch0 += ics->group_len[g] * 128;
2215 ch1 += ics->group_len[g] * 128;
2220 * intensity stereo decoding; reference: 4.6.8.2.3
2222 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
2223 * [1] mask is decoded from bitstream; [2] mask is all 1s;
2224 * [3] reserved for scalable AAC
2226 static void apply_intensity_stereo(AACContext *ac,
2227 ChannelElement *cpe, int ms_present)
2229 const IndividualChannelStream *ics = &cpe->ch[1].ics;
2230 SingleChannelElement *sce1 = &cpe->ch[1];
2231 INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
2232 const uint16_t *offsets = ics->swb_offset;
2233 int g, group, i, idx = 0;
2236 for (g = 0; g < ics->num_window_groups; g++) {
2237 for (i = 0; i < ics->max_sfb;) {
2238 if (sce1->band_type[idx] == INTENSITY_BT ||
2239 sce1->band_type[idx] == INTENSITY_BT2) {
2240 const int bt_run_end = sce1->band_type_run_end[idx];
2241 for (; i < bt_run_end; i++, idx++) {
2242 c = -1 + 2 * (sce1->band_type[idx] - 14);
2244 c *= 1 - 2 * cpe->ms_mask[idx];
2245 scale = c * sce1->sf[idx];
2246 for (group = 0; group < ics->group_len[g]; group++)
2248 ac->subband_scale(coef1 + group * 128 + offsets[i],
2249 coef0 + group * 128 + offsets[i],
2252 offsets[i + 1] - offsets[i] ,ac->avctx);
2254 ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
2255 coef0 + group * 128 + offsets[i],
2257 offsets[i + 1] - offsets[i]);
2258 #endif /* USE_FIXED */
2261 int bt_run_end = sce1->band_type_run_end[idx];
2262 idx += bt_run_end - i;
2266 coef0 += ics->group_len[g] * 128;
2267 coef1 += ics->group_len[g] * 128;
2272 * Decode a channel_pair_element; reference: table 4.4.
2274 * @return Returns error status. 0 - OK, !0 - error
2276 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2278 int i, ret, common_window, ms_present = 0;
2279 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
2281 common_window = eld_syntax || get_bits1(gb);
2282 if (common_window) {
2283 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2284 return AVERROR_INVALIDDATA;
2285 i = cpe->ch[1].ics.use_kb_window[0];
2286 cpe->ch[1].ics = cpe->ch[0].ics;
2287 cpe->ch[1].ics.use_kb_window[1] = i;
2288 if (cpe->ch[1].ics.predictor_present &&
2289 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
2290 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
2291 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
2292 ms_present = get_bits(gb, 2);
2293 if (ms_present == 3) {
2294 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
2295 return AVERROR_INVALIDDATA;
2296 } else if (ms_present)
2297 decode_mid_side_stereo(cpe, gb, ms_present);
2299 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2301 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2304 if (common_window) {
2306 apply_mid_side_stereo(ac, cpe);
2307 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
2308 apply_prediction(ac, &cpe->ch[0]);
2309 apply_prediction(ac, &cpe->ch[1]);
2313 apply_intensity_stereo(ac, cpe, ms_present);
2317 static const float cce_scale[] = {
2318 1.09050773266525765921, //2^(1/8)
2319 1.18920711500272106672, //2^(1/4)
2325 * Decode coupling_channel_element; reference: table 4.8.
2327 * @return Returns error status. 0 - OK, !0 - error
2329 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2335 SingleChannelElement *sce = &che->ch[0];
2336 ChannelCoupling *coup = &che->coup;
2338 coup->coupling_point = 2 * get_bits1(gb);
2339 coup->num_coupled = get_bits(gb, 3);
2340 for (c = 0; c <= coup->num_coupled; c++) {
2342 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2343 coup->id_select[c] = get_bits(gb, 4);
2344 if (coup->type[c] == TYPE_CPE) {
2345 coup->ch_select[c] = get_bits(gb, 2);
2346 if (coup->ch_select[c] == 3)
2349 coup->ch_select[c] = 2;
2351 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
2353 sign = get_bits(gb, 1);
2355 scale = get_bits(gb, 2);
2357 scale = cce_scale[get_bits(gb, 2)];
2360 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2363 for (c = 0; c < num_gain; c++) {
2367 INTFLOAT gain_cache = FIXR10(1.);
2369 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2370 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
2371 gain_cache = GET_GAIN(scale, gain);
2373 if ((abs(gain_cache)-1024) >> 3 > 30)
2374 return AVERROR(ERANGE);
2377 if (coup->coupling_point == AFTER_IMDCT) {
2378 coup->gain[c][0] = gain_cache;
2380 for (g = 0; g < sce->ics.num_window_groups; g++) {
2381 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2382 if (sce->band_type[idx] != ZERO_BT) {
2384 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2392 gain_cache = GET_GAIN(scale, t) * s;
2394 if ((abs(gain_cache)-1024) >> 3 > 30)
2395 return AVERROR(ERANGE);
2399 coup->gain[c][idx] = gain_cache;
2409 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2411 * @return Returns number of bytes consumed.
2413 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2417 int num_excl_chan = 0;
2420 for (i = 0; i < 7; i++)
2421 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2422 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2424 return num_excl_chan / 7;
2428 * Decode dynamic range information; reference: table 4.52.
2430 * @return Returns number of bytes consumed.
2432 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2436 int drc_num_bands = 1;
2439 /* pce_tag_present? */
2440 if (get_bits1(gb)) {
2441 che_drc->pce_instance_tag = get_bits(gb, 4);
2442 skip_bits(gb, 4); // tag_reserved_bits
2446 /* excluded_chns_present? */
2447 if (get_bits1(gb)) {
2448 n += decode_drc_channel_exclusions(che_drc, gb);
2451 /* drc_bands_present? */
2452 if (get_bits1(gb)) {
2453 che_drc->band_incr = get_bits(gb, 4);
2454 che_drc->interpolation_scheme = get_bits(gb, 4);
2456 drc_num_bands += che_drc->band_incr;
2457 for (i = 0; i < drc_num_bands; i++) {
2458 che_drc->band_top[i] = get_bits(gb, 8);
2463 /* prog_ref_level_present? */
2464 if (get_bits1(gb)) {
2465 che_drc->prog_ref_level = get_bits(gb, 7);
2466 skip_bits1(gb); // prog_ref_level_reserved_bits
2470 for (i = 0; i < drc_num_bands; i++) {
2471 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2472 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2479 static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
2481 int i, major, minor;
2486 get_bits(gb, 13); len -= 13;
2488 for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
2489 buf[i] = get_bits(gb, 8);
2492 if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
2493 av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
2495 if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
2496 ac->avctx->internal->skip_samples = 1024;
2500 skip_bits_long(gb, len);
2506 * Decode extension data (incomplete); reference: table 4.51.
2508 * @param cnt length of TYPE_FIL syntactic element in bytes
2510 * @return Returns number of bytes consumed
2512 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2513 ChannelElement *che, enum RawDataBlockType elem_type)
2517 int type = get_bits(gb, 4);
2519 if (ac->avctx->debug & FF_DEBUG_STARTCODE)
2520 av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
2522 switch (type) { // extension type
2523 case EXT_SBR_DATA_CRC:
2527 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2529 } else if (ac->oc[1].m4ac.frame_length_short) {
2530 if (!ac->warned_960_sbr)
2531 avpriv_report_missing_feature(ac->avctx,
2532 "SBR with 960 frame length");
2533 ac->warned_960_sbr = 1;
2534 skip_bits_long(gb, 8 * cnt - 4);
2536 } else if (!ac->oc[1].m4ac.sbr) {
2537 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2538 skip_bits_long(gb, 8 * cnt - 4);
2540 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2541 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2542 skip_bits_long(gb, 8 * cnt - 4);
2544 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2545 ac->oc[1].m4ac.sbr = 1;
2546 ac->oc[1].m4ac.ps = 1;
2547 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
2548 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2549 ac->oc[1].status, 1);
2551 ac->oc[1].m4ac.sbr = 1;
2552 ac->avctx->profile = FF_PROFILE_AAC_HE;
2554 res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2556 case EXT_DYNAMIC_RANGE:
2557 res = decode_dynamic_range(&ac->che_drc, gb);
2560 decode_fill(ac, gb, 8 * cnt - 4);
2563 case EXT_DATA_ELEMENT:
2565 skip_bits_long(gb, 8 * cnt - 4);
2572 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2574 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2575 * @param coef spectral coefficients
2577 static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns,
2578 IndividualChannelStream *ics, int decode)
2580 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2582 int bottom, top, order, start, end, size, inc;
2583 INTFLOAT lpc[TNS_MAX_ORDER];
2584 INTFLOAT tmp[TNS_MAX_ORDER+1];
2585 UINTFLOAT *coef = coef_param;
2590 for (w = 0; w < ics->num_windows; w++) {
2591 bottom = ics->num_swb;
2592 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2594 bottom = FFMAX(0, top - tns->length[w][filt]);
2595 order = tns->order[w][filt];
2600 AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
2602 start = ics->swb_offset[FFMIN(bottom, mmm)];
2603 end = ics->swb_offset[FFMIN( top, mmm)];
2604 if ((size = end - start) <= 0)
2606 if (tns->direction[w][filt]) {
2616 for (m = 0; m < size; m++, start += inc)
2617 for (i = 1; i <= FFMIN(m, order); i++)
2618 coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]);
2621 for (m = 0; m < size; m++, start += inc) {
2622 tmp[0] = coef[start];
2623 for (i = 1; i <= FFMIN(m, order); i++)
2624 coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
2625 for (i = order; i > 0; i--)
2626 tmp[i] = tmp[i - 1];
2634 * Apply windowing and MDCT to obtain the spectral
2635 * coefficient from the predicted sample by LTP.
2637 static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
2638 INTFLOAT *in, IndividualChannelStream *ics)
2640 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2641 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2642 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2643 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2645 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2646 ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
2648 memset(in, 0, 448 * sizeof(*in));
2649 ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
2651 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2652 ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2654 ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2655 memset(in + 1024 + 576, 0, 448 * sizeof(*in));
2657 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2661 * Apply the long term prediction
2663 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2665 const LongTermPrediction *ltp = &sce->ics.ltp;
2666 const uint16_t *offsets = sce->ics.swb_offset;
2669 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2670 INTFLOAT *predTime = sce->ret;
2671 INTFLOAT *predFreq = ac->buf_mdct;
2672 int16_t num_samples = 2048;
2674 if (ltp->lag < 1024)
2675 num_samples = ltp->lag + 1024;
2676 for (i = 0; i < num_samples; i++)
2677 predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
2678 memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
2680 ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2682 if (sce->tns.present)
2683 ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2685 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2687 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2688 sce->coeffs[i] += (UINTFLOAT)predFreq[i];
2693 * Update the LTP buffer for next frame
2695 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2697 IndividualChannelStream *ics = &sce->ics;
2698 INTFLOAT *saved = sce->saved;
2699 INTFLOAT *saved_ltp = sce->coeffs;
2700 const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2701 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2704 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2705 memcpy(saved_ltp, saved, 512 * sizeof(*saved_ltp));
2706 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2707 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2709 for (i = 0; i < 64; i++)
2710 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2711 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2712 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
2713 memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
2714 ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2716 for (i = 0; i < 64; i++)
2717 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
2718 } else { // LONG_STOP or ONLY_LONG
2719 ac->fdsp->vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2721 for (i = 0; i < 512; i++)
2722 saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
2725 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2726 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2727 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2731 * Conduct IMDCT and windowing.
2733 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2735 IndividualChannelStream *ics = &sce->ics;
2736 INTFLOAT *in = sce->coeffs;
2737 INTFLOAT *out = sce->ret;
2738 INTFLOAT *saved = sce->saved;
2739 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2740 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
2741 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
2742 INTFLOAT *buf = ac->buf_mdct;
2743 INTFLOAT *temp = ac->temp;
2747 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2748 for (i = 0; i < 1024; i += 128)
2749 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2751 ac->mdct.imdct_half(&ac->mdct, buf, in);
2753 for (i=0; i<1024; i++)
2754 buf[i] = (buf[i] + 4LL) >> 3;
2755 #endif /* USE_FIXED */
2758 /* window overlapping
2759 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2760 * and long to short transitions are considered to be short to short
2761 * transitions. This leaves just two cases (long to long and short to short)
2762 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2764 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2765 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2766 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2768 memcpy( out, saved, 448 * sizeof(*out));
2770 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2771 ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2772 ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2773 ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2774 ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2775 ac->fdsp->vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2776 memcpy( out + 448 + 4*128, temp, 64 * sizeof(*out));
2778 ac->fdsp->vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2779 memcpy( out + 576, buf + 64, 448 * sizeof(*out));
2784 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2785 memcpy( saved, temp + 64, 64 * sizeof(*saved));
2786 ac->fdsp->vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2787 ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2788 ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2789 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2790 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2791 memcpy( saved, buf + 512, 448 * sizeof(*saved));
2792 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
2793 } else { // LONG_STOP or ONLY_LONG
2794 memcpy( saved, buf + 512, 512 * sizeof(*saved));
2799 * Conduct IMDCT and windowing.
2801 static void imdct_and_windowing_960(AACContext *ac, SingleChannelElement *sce)
2804 IndividualChannelStream *ics = &sce->ics;
2805 INTFLOAT *in = sce->coeffs;
2806 INTFLOAT *out = sce->ret;
2807 INTFLOAT *saved = sce->saved;
2808 const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2809 const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_960) : AAC_RENAME(ff_sine_960);
2810 const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_120) : AAC_RENAME(ff_sine_120);
2811 INTFLOAT *buf = ac->buf_mdct;
2812 INTFLOAT *temp = ac->temp;
2816 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2817 for (i = 0; i < 8; i++)
2818 ac->mdct120->imdct_half(ac->mdct120, buf + i * 120, in + i * 128, 1);
2820 ac->mdct960->imdct_half(ac->mdct960, buf, in, 1);
2823 /* window overlapping
2824 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2825 * and long to short transitions are considered to be short to short
2826 * transitions. This leaves just two cases (long to long and short to short)
2827 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2830 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2831 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2832 ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 480);
2834 memcpy( out, saved, 420 * sizeof(*out));
2836 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2837 ac->fdsp->vector_fmul_window(out + 420 + 0*120, saved + 420, buf + 0*120, swindow_prev, 60);
2838 ac->fdsp->vector_fmul_window(out + 420 + 1*120, buf + 0*120 + 60, buf + 1*120, swindow, 60);
2839 ac->fdsp->vector_fmul_window(out + 420 + 2*120, buf + 1*120 + 60, buf + 2*120, swindow, 60);
2840 ac->fdsp->vector_fmul_window(out + 420 + 3*120, buf + 2*120 + 60, buf + 3*120, swindow, 60);
2841 ac->fdsp->vector_fmul_window(temp, buf + 3*120 + 60, buf + 4*120, swindow, 60);
2842 memcpy( out + 420 + 4*120, temp, 60 * sizeof(*out));
2844 ac->fdsp->vector_fmul_window(out + 420, saved + 420, buf, swindow_prev, 60);
2845 memcpy( out + 540, buf + 60, 420 * sizeof(*out));
2850 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2851 memcpy( saved, temp + 60, 60 * sizeof(*saved));
2852 ac->fdsp->vector_fmul_window(saved + 60, buf + 4*120 + 60, buf + 5*120, swindow, 60);
2853 ac->fdsp->vector_fmul_window(saved + 180, buf + 5*120 + 60, buf + 6*120, swindow, 60);
2854 ac->fdsp->vector_fmul_window(saved + 300, buf + 6*120 + 60, buf + 7*120, swindow, 60);
2855 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2856 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2857 memcpy( saved, buf + 480, 420 * sizeof(*saved));
2858 memcpy( saved + 420, buf + 7*120 + 60, 60 * sizeof(*saved));
2859 } else { // LONG_STOP or ONLY_LONG
2860 memcpy( saved, buf + 480, 480 * sizeof(*saved));
2864 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2866 IndividualChannelStream *ics = &sce->ics;
2867 INTFLOAT *in = sce->coeffs;
2868 INTFLOAT *out = sce->ret;
2869 INTFLOAT *saved = sce->saved;
2870 INTFLOAT *buf = ac->buf_mdct;
2873 #endif /* USE_FIXED */
2876 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2879 for (i = 0; i < 1024; i++)
2880 buf[i] = (buf[i] + 2) >> 2;
2881 #endif /* USE_FIXED */
2883 // window overlapping
2884 if (ics->use_kb_window[1]) {
2885 // AAC LD uses a low overlap sine window instead of a KBD window
2886 memcpy(out, saved, 192 * sizeof(*out));
2887 ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME(ff_sine_128), 64);
2888 memcpy( out + 320, buf + 64, 192 * sizeof(*out));
2890 ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME(ff_sine_512), 256);
2894 memcpy(saved, buf + 256, 256 * sizeof(*saved));
2897 static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2899 INTFLOAT *in = sce->coeffs;
2900 INTFLOAT *out = sce->ret;
2901 INTFLOAT *saved = sce->saved;
2902 INTFLOAT *buf = ac->buf_mdct;
2904 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
2905 const int n2 = n >> 1;
2906 const int n4 = n >> 2;
2907 const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
2908 AAC_RENAME(ff_aac_eld_window_512);
2910 // Inverse transform, mapped to the conventional IMDCT by
2911 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2912 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2913 // International Conference on Audio, Language and Image Processing, ICALIP 2008.
2914 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2915 for (i = 0; i < n2; i+=2) {
2917 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2918 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2922 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1);
2925 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2928 for (i = 0; i < 1024; i++)
2929 buf[i] = (buf[i] + 1) >> 1;
2930 #endif /* USE_FIXED */
2932 for (i = 0; i < n; i+=2) {
2935 // Like with the regular IMDCT at this point we still have the middle half
2936 // of a transform but with even symmetry on the left and odd symmetry on
2939 // window overlapping
2940 // The spec says to use samples [0..511] but the reference decoder uses
2941 // samples [128..639].
2942 for (i = n4; i < n2; i ++) {
2943 out[i - n4] = AAC_MUL31( buf[ n2 - 1 - i] , window[i - n4]) +
2944 AAC_MUL31( saved[ i + n2] , window[i + n - n4]) +
2945 AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
2946 AAC_MUL31(-saved[ 2*n + n2 + i] , window[i + 3*n - n4]);
2948 for (i = 0; i < n2; i ++) {
2949 out[n4 + i] = AAC_MUL31( buf[ i] , window[i + n2 - n4]) +
2950 AAC_MUL31(-saved[ n - 1 - i] , window[i + n2 + n - n4]) +
2951 AAC_MUL31(-saved[ n + i] , window[i + n2 + 2*n - n4]) +
2952 AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
2954 for (i = 0; i < n4; i ++) {
2955 out[n2 + n4 + i] = AAC_MUL31( buf[ i + n2] , window[i + n - n4]) +
2956 AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
2957 AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
2961 memmove(saved + n, saved, 2 * n * sizeof(*saved));
2962 memcpy( saved, buf, n * sizeof(*saved));
2966 * channel coupling transformation interface
2968 * @param apply_coupling_method pointer to (in)dependent coupling function
2970 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2971 enum RawDataBlockType type, int elem_id,
2972 enum CouplingPoint coupling_point,
2973 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2977 for (i = 0; i < MAX_ELEM_ID; i++) {
2978 ChannelElement *cce = ac->che[TYPE_CCE][i];
2981 if (cce && cce->coup.coupling_point == coupling_point) {
2982 ChannelCoupling *coup = &cce->coup;
2984 for (c = 0; c <= coup->num_coupled; c++) {
2985 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2986 if (coup->ch_select[c] != 1) {
2987 apply_coupling_method(ac, &cc->ch[0], cce, index);
2988 if (coup->ch_select[c] != 0)
2991 if (coup->ch_select[c] != 2)
2992 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2994 index += 1 + (coup->ch_select[c] == 3);
3001 * Convert spectral data to samples, applying all supported tools as appropriate.
3003 static void spectral_to_sample(AACContext *ac, int samples)
3006 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
3007 switch (ac->oc[1].m4ac.object_type) {
3009 imdct_and_window = imdct_and_windowing_ld;
3011 case AOT_ER_AAC_ELD:
3012 imdct_and_window = imdct_and_windowing_eld;
3015 if (ac->oc[1].m4ac.frame_length_short)
3016 imdct_and_window = imdct_and_windowing_960;
3018 imdct_and_window = ac->imdct_and_windowing;
3020 for (type = 3; type >= 0; type--) {
3021 for (i = 0; i < MAX_ELEM_ID; i++) {
3022 ChannelElement *che = ac->che[type][i];
3023 if (che && che->present) {
3024 if (type <= TYPE_CPE)
3025 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
3026 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
3027 if (che->ch[0].ics.predictor_present) {
3028 if (che->ch[0].ics.ltp.present)
3029 ac->apply_ltp(ac, &che->ch[0]);
3030 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
3031 ac->apply_ltp(ac, &che->ch[1]);
3034 if (che->ch[0].tns.present)
3035 ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
3036 if (che->ch[1].tns.present)
3037 ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
3038 if (type <= TYPE_CPE)
3039 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
3040 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
3041 imdct_and_window(ac, &che->ch[0]);
3042 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3043 ac->update_ltp(ac, &che->ch[0]);
3044 if (type == TYPE_CPE) {
3045 imdct_and_window(ac, &che->ch[1]);
3046 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
3047 ac->update_ltp(ac, &che->ch[1]);
3049 if (ac->oc[1].m4ac.sbr > 0) {
3050 AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
3053 if (type <= TYPE_CCE)
3054 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
3059 /* preparation for resampler */
3060 for(j = 0; j<samples; j++){
3061 che->ch[0].ret[j] = (int32_t)av_clip64((int64_t)che->ch[0].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3062 if(type == TYPE_CPE)
3063 che->ch[1].ret[j] = (int32_t)av_clip64((int64_t)che->ch[1].ret[j]*128, INT32_MIN, INT32_MAX-0x8000)+0x8000;
3066 #endif /* USE_FIXED */
3069 av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
3075 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
3078 AACADTSHeaderInfo hdr_info;
3079 uint8_t layout_map[MAX_ELEM_ID*4][3];
3080 int layout_map_tags, ret;
3082 size = ff_adts_header_parse(gb, &hdr_info);
3084 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
3085 // This is 2 for "VLB " audio in NSV files.
3086 // See samples/nsv/vlb_audio.
3087 avpriv_report_missing_feature(ac->avctx,
3088 "More than one AAC RDB per ADTS frame");
3089 ac->warned_num_aac_frames = 1;
3091 push_output_configuration(ac);
3092 if (hdr_info.chan_config) {
3093 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
3094 if ((ret = set_default_channel_config(ac, ac->avctx,
3097 hdr_info.chan_config)) < 0)
3099 if ((ret = output_configure(ac, layout_map, layout_map_tags,
3100 FFMAX(ac->oc[1].status,
3101 OC_TRIAL_FRAME), 0)) < 0)
3104 ac->oc[1].m4ac.chan_config = 0;
3106 * dual mono frames in Japanese DTV can have chan_config 0
3107 * WITHOUT specifying PCE.
3108 * thus, set dual mono as default.
3110 if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
3111 layout_map_tags = 2;
3112 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
3113 layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
3114 layout_map[0][1] = 0;
3115 layout_map[1][1] = 1;
3116 if (output_configure(ac, layout_map, layout_map_tags,
3121 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
3122 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
3123 ac->oc[1].m4ac.object_type = hdr_info.object_type;
3124 ac->oc[1].m4ac.frame_length_short = 0;
3125 if (ac->oc[0].status != OC_LOCKED ||
3126 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
3127 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
3128 ac->oc[1].m4ac.sbr = -1;
3129 ac->oc[1].m4ac.ps = -1;
3131 if (!hdr_info.crc_absent)
3137 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
3138 int *got_frame_ptr, GetBitContext *gb)
3140 AACContext *ac = avctx->priv_data;
3141 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
3142 ChannelElement *che;
3144 int samples = m4ac->frame_length_short ? 960 : 1024;
3145 int chan_config = m4ac->chan_config;
3146 int aot = m4ac->object_type;
3148 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
3153 if ((err = frame_configure_elements(avctx)) < 0)
3156 // The FF_PROFILE_AAC_* defines are all object_type - 1
3157 // This may lead to an undefined profile being signaled
3158 ac->avctx->profile = aot - 1;
3160 ac->tags_mapped = 0;
3162 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
3163 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
3165 return AVERROR_INVALIDDATA;
3167 for (i = 0; i < tags_per_config[chan_config]; i++) {
3168 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
3169 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
3170 if (!(che=get_che(ac, elem_type, elem_id))) {
3171 av_log(ac->avctx, AV_LOG_ERROR,
3172 "channel element %d.%d is not allocated\n",
3173 elem_type, elem_id);
3174 return AVERROR_INVALIDDATA;
3177 if (aot != AOT_ER_AAC_ELD)
3179 switch (elem_type) {
3181 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3184 err = decode_cpe(ac, gb, che);
3187 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3194 spectral_to_sample(ac, samples);
3196 if (!ac->frame->data[0] && samples) {
3197 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3198 return AVERROR_INVALIDDATA;
3201 ac->frame->nb_samples = samples;
3202 ac->frame->sample_rate = avctx->sample_rate;
3205 skip_bits_long(gb, get_bits_left(gb));
3209 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
3210 int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
3212 AACContext *ac = avctx->priv_data;
3213 ChannelElement *che = NULL, *che_prev = NULL;
3214 enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
3216 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
3217 int is_dmono, sce_count = 0;
3218 int payload_alignment;
3219 uint8_t che_presence[4][MAX_ELEM_ID] = {{0}};
3223 if (show_bits(gb, 12) == 0xfff) {
3224 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
3225 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
3228 if (ac->oc[1].m4ac.sampling_index > 12) {
3229 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
3230 err = AVERROR_INVALIDDATA;
3235 if ((err = frame_configure_elements(avctx)) < 0)
3238 // The FF_PROFILE_AAC_* defines are all object_type - 1
3239 // This may lead to an undefined profile being signaled
3240 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
3242 payload_alignment = get_bits_count(gb);
3243 ac->tags_mapped = 0;
3245 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
3246 elem_id = get_bits(gb, 4);
3248 if (avctx->debug & FF_DEBUG_STARTCODE)
3249 av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
3251 if (!avctx->channels && elem_type != TYPE_PCE) {
3252 err = AVERROR_INVALIDDATA;
3256 if (elem_type < TYPE_DSE) {
3257 if (che_presence[elem_type][elem_id]) {
3258 int error = che_presence[elem_type][elem_id] > 1;
3259 av_log(ac->avctx, error ? AV_LOG_ERROR : AV_LOG_DEBUG, "channel element %d.%d duplicate\n",
3260 elem_type, elem_id);
3262 err = AVERROR_INVALIDDATA;
3266 che_presence[elem_type][elem_id]++;
3268 if (!(che=get_che(ac, elem_type, elem_id))) {
3269 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
3270 elem_type, elem_id);
3271 err = AVERROR_INVALIDDATA;
3274 samples = ac->oc[1].m4ac.frame_length_short ? 960 : 1024;
3278 switch (elem_type) {
3281 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3287 err = decode_cpe(ac, gb, che);
3292 err = decode_cce(ac, gb, che);
3296 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
3301 err = skip_data_stream_element(ac, gb);
3305 uint8_t layout_map[MAX_ELEM_ID*4][3];
3308 int pushed = push_output_configuration(ac);
3309 if (pce_found && !pushed) {
3310 err = AVERROR_INVALIDDATA;
3314 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
3321 av_log(avctx, AV_LOG_ERROR,
3322 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
3323 pop_output_configuration(ac);
3325 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
3327 ac->oc[1].m4ac.chan_config = 0;
3335 elem_id += get_bits(gb, 8) - 1;
3336 if (get_bits_left(gb) < 8 * elem_id) {
3337 av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
3338 err = AVERROR_INVALIDDATA;
3342 while (elem_id > 0) {
3343 int ret = decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
3353 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
3357 if (elem_type < TYPE_DSE) {
3359 che_prev_type = elem_type;
3365 if (get_bits_left(gb) < 3) {
3366 av_log(avctx, AV_LOG_ERROR, overread_err);
3367 err = AVERROR_INVALIDDATA;
3372 if (!avctx->channels) {
3377 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
3378 samples <<= multiplier;
3380 spectral_to_sample(ac, samples);
3382 if (ac->oc[1].status && audio_found) {
3383 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
3384 avctx->frame_size = samples;
3385 ac->oc[1].status = OC_LOCKED;
3389 avctx->internal->skip_samples_multiplier = 2;
3391 if (!ac->frame->data[0] && samples) {
3392 av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
3393 err = AVERROR_INVALIDDATA;
3398 ac->frame->nb_samples = samples;
3399 ac->frame->sample_rate = avctx->sample_rate;
3401 av_frame_unref(ac->frame);
3402 *got_frame_ptr = !!samples;
3404 /* for dual-mono audio (SCE + SCE) */
3405 is_dmono = ac->dmono_mode && sce_count == 2 &&
3406 ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
3408 if (ac->dmono_mode == 1)
3409 ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
3410 else if (ac->dmono_mode == 2)
3411 ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
3416 pop_output_configuration(ac);
3420 static int aac_decode_frame(AVCodecContext *avctx, void *data,
3421 int *got_frame_ptr, AVPacket *avpkt)
3423 AACContext *ac = avctx->priv_data;
3424 const uint8_t *buf = avpkt->data;
3425 int buf_size = avpkt->size;
3430 int new_extradata_size;
3431 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
3432 AV_PKT_DATA_NEW_EXTRADATA,
3433 &new_extradata_size);
3434 int jp_dualmono_size;
3435 const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
3436 AV_PKT_DATA_JP_DUALMONO,
3439 if (new_extradata) {
3440 /* discard previous configuration */
3441 ac->oc[1].status = OC_NONE;
3442 err = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
3444 new_extradata_size * 8LL, 1);
3451 if (jp_dualmono && jp_dualmono_size > 0)
3452 ac->dmono_mode = 1 + *jp_dualmono;
3453 if (ac->force_dmono_mode >= 0)
3454 ac->dmono_mode = ac->force_dmono_mode;
3456 if (INT_MAX / 8 <= buf_size)
3457 return AVERROR_INVALIDDATA;
3459 if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)
3462 switch (ac->oc[1].m4ac.object_type) {
3464 case AOT_ER_AAC_LTP:
3466 case AOT_ER_AAC_ELD:
3467 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3470 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
3475 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
3476 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3477 if (buf[buf_offset])
3480 return buf_size > buf_offset ? buf_consumed : buf_size;
3483 static av_cold int aac_decode_close(AVCodecContext *avctx)
3485 AACContext *ac = avctx->priv_data;
3488 for (i = 0; i < MAX_ELEM_ID; i++) {
3489 for (type = 0; type < 4; type++) {
3490 if (ac->che[type][i])
3491 AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][i]->sbr);
3492 av_freep(&ac->che[type][i]);
3496 ff_mdct_end(&ac->mdct);
3497 ff_mdct_end(&ac->mdct_small);
3498 ff_mdct_end(&ac->mdct_ld);
3499 ff_mdct_end(&ac->mdct_ltp);
3501 ff_mdct15_uninit(&ac->mdct120);
3502 ff_mdct15_uninit(&ac->mdct480);
3503 ff_mdct15_uninit(&ac->mdct960);
3505 av_freep(&ac->fdsp);
3509 static void aacdec_init(AACContext *c)
3511 c->imdct_and_windowing = imdct_and_windowing;
3512 c->apply_ltp = apply_ltp;
3513 c->apply_tns = apply_tns;
3514 c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
3515 c->update_ltp = update_ltp;
3517 c->vector_pow43 = vector_pow43;
3518 c->subband_scale = subband_scale;
3523 ff_aacdec_init_mips(c);
3524 #endif /* !USE_FIXED */
3527 * AVOptions for Japanese DTV specific extensions (ADTS only)
3529 #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
3530 static const AVOption options[] = {
3531 {"dual_mono_mode", "Select the channel to decode for dual mono",
3532 offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
3533 AACDEC_FLAGS, "dual_mono_mode"},
3535 {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3536 {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3537 {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3538 {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
3543 static const AVClass aac_decoder_class = {
3544 .class_name = "AAC decoder",
3545 .item_name = av_default_item_name,
3547 .version = LIBAVUTIL_VERSION_INT,