3 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
7 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8 * Copyright (c) 2010 Janne Grunau <janne-libav@jannau.net>
10 * This file is part of Libav.
12 * Libav is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * Libav is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with Libav; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 * @author Oded Shimon ( ods15 ods15 dyndns org )
31 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
38 * N (code in SoC repo) gain control
40 * Y window shapes - standard
41 * N window shapes - Low Delay
42 * Y filterbank - standard
43 * N (code in SoC repo) filterbank - Scalable Sample Rate
44 * Y Temporal Noise Shaping
45 * Y Long Term Prediction
48 * Y frequency domain prediction
49 * Y Perceptual Noise Substitution
51 * N Scalable Inverse AAC Quantization
52 * N Frequency Selective Switch
54 * Y quantization & coding - AAC
55 * N quantization & coding - TwinVQ
56 * N quantization & coding - BSAC
57 * N AAC Error Resilience tools
58 * N Error Resilience payload syntax
59 * N Error Protection tool
61 * N Silence Compression
64 * N Structured Audio tools
65 * N Structured Audio Sample Bank Format
67 * N Harmonic and Individual Lines plus Noise
68 * N Text-To-Speech Interface
69 * Y Spectral Band Replication
70 * Y (not in this code) Layer-1
71 * Y (not in this code) Layer-2
72 * Y (not in this code) Layer-3
73 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
75 * N Direct Stream Transfer
77 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
82 #include "libavutil/float_dsp.h"
87 #include "fmtconvert.h"
94 #include "aacdectab.h"
95 #include "cbrt_tablegen.h"
98 #include "mpeg4audio.h"
99 #include "aacadtsdec.h"
100 #include "libavutil/intfloat.h"
108 # include "arm/aac.h"
111 static VLC vlc_scalefactors;
112 static VLC vlc_spectral[11];
114 static const char overread_err[] = "Input buffer exhausted before END element found\n";
116 static int count_channels(uint8_t (*layout)[3], int tags)
119 for (i = 0; i < tags; i++) {
120 int syn_ele = layout[i][0];
121 int pos = layout[i][2];
122 sum += (1 + (syn_ele == TYPE_CPE)) *
123 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
129 * Check for the channel element in the current channel position configuration.
130 * If it exists, make sure the appropriate element is allocated and map the
131 * channel order to match the internal Libav channel layout.
133 * @param che_pos current channel position configuration
134 * @param type channel element type
135 * @param id channel element id
136 * @param channels count of the number of channels in the configuration
138 * @return Returns error status. 0 - OK, !0 - error
140 static av_cold int che_configure(AACContext *ac,
141 enum ChannelPosition che_pos,
142 int type, int id, int *channels)
145 if (!ac->che[type][id]) {
146 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
147 return AVERROR(ENOMEM);
148 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
150 if (type != TYPE_CCE) {
151 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
152 if (type == TYPE_CPE ||
153 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
154 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
158 if (ac->che[type][id])
159 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
160 av_freep(&ac->che[type][id]);
165 static int frame_configure_elements(AVCodecContext *avctx)
167 AACContext *ac = avctx->priv_data;
168 int type, id, ch, ret;
170 /* set channel pointers to internal buffers by default */
171 for (type = 0; type < 4; type++) {
172 for (id = 0; id < MAX_ELEM_ID; id++) {
173 ChannelElement *che = ac->che[type][id];
175 che->ch[0].ret = che->ch[0].ret_buf;
176 che->ch[1].ret = che->ch[1].ret_buf;
181 /* get output buffer */
182 av_frame_unref(ac->frame);
183 ac->frame->nb_samples = 2048;
184 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0) {
185 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
189 /* map output channel pointers to AVFrame data */
190 for (ch = 0; ch < avctx->channels; ch++) {
191 if (ac->output_element[ch])
192 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
198 struct elem_to_channel {
199 uint64_t av_position;
202 uint8_t aac_position;
205 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
206 uint8_t (*layout_map)[3], int offset, uint64_t left,
207 uint64_t right, int pos)
209 if (layout_map[offset][0] == TYPE_CPE) {
210 e2c_vec[offset] = (struct elem_to_channel) {
211 .av_position = left | right, .syn_ele = TYPE_CPE,
212 .elem_id = layout_map[offset ][1], .aac_position = pos };
215 e2c_vec[offset] = (struct elem_to_channel) {
216 .av_position = left, .syn_ele = TYPE_SCE,
217 .elem_id = layout_map[offset ][1], .aac_position = pos };
218 e2c_vec[offset + 1] = (struct elem_to_channel) {
219 .av_position = right, .syn_ele = TYPE_SCE,
220 .elem_id = layout_map[offset + 1][1], .aac_position = pos };
225 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos, int *current) {
226 int num_pos_channels = 0;
230 for (i = *current; i < tags; i++) {
231 if (layout_map[i][2] != pos)
233 if (layout_map[i][0] == TYPE_CPE) {
235 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
241 num_pos_channels += 2;
249 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
252 return num_pos_channels;
255 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
257 int i, n, total_non_cc_elements;
258 struct elem_to_channel e2c_vec[4*MAX_ELEM_ID] = {{ 0 }};
259 int num_front_channels, num_side_channels, num_back_channels;
262 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
267 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
268 if (num_front_channels < 0)
271 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
272 if (num_side_channels < 0)
275 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
276 if (num_back_channels < 0)
280 if (num_front_channels & 1) {
281 e2c_vec[i] = (struct elem_to_channel) {
282 .av_position = AV_CH_FRONT_CENTER, .syn_ele = TYPE_SCE,
283 .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_FRONT };
285 num_front_channels--;
287 if (num_front_channels >= 4) {
288 i += assign_pair(e2c_vec, layout_map, i,
289 AV_CH_FRONT_LEFT_OF_CENTER,
290 AV_CH_FRONT_RIGHT_OF_CENTER,
292 num_front_channels -= 2;
294 if (num_front_channels >= 2) {
295 i += assign_pair(e2c_vec, layout_map, i,
299 num_front_channels -= 2;
301 while (num_front_channels >= 2) {
302 i += assign_pair(e2c_vec, layout_map, i,
306 num_front_channels -= 2;
309 if (num_side_channels >= 2) {
310 i += assign_pair(e2c_vec, layout_map, i,
314 num_side_channels -= 2;
316 while (num_side_channels >= 2) {
317 i += assign_pair(e2c_vec, layout_map, i,
321 num_side_channels -= 2;
324 while (num_back_channels >= 4) {
325 i += assign_pair(e2c_vec, layout_map, i,
329 num_back_channels -= 2;
331 if (num_back_channels >= 2) {
332 i += assign_pair(e2c_vec, layout_map, i,
336 num_back_channels -= 2;
338 if (num_back_channels) {
339 e2c_vec[i] = (struct elem_to_channel) {
340 .av_position = AV_CH_BACK_CENTER, .syn_ele = TYPE_SCE,
341 .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_BACK };
346 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
347 e2c_vec[i] = (struct elem_to_channel) {
348 .av_position = AV_CH_LOW_FREQUENCY, .syn_ele = TYPE_LFE,
349 .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_LFE };
352 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
353 e2c_vec[i] = (struct elem_to_channel) {
354 .av_position = UINT64_MAX, .syn_ele = TYPE_LFE,
355 .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_LFE };
359 // Must choose a stable sort
360 total_non_cc_elements = n = i;
363 for (i = 1; i < n; i++) {
364 if (e2c_vec[i-1].av_position > e2c_vec[i].av_position) {
365 FFSWAP(struct elem_to_channel, e2c_vec[i-1], e2c_vec[i]);
373 for (i = 0; i < total_non_cc_elements; i++) {
374 layout_map[i][0] = e2c_vec[i].syn_ele;
375 layout_map[i][1] = e2c_vec[i].elem_id;
376 layout_map[i][2] = e2c_vec[i].aac_position;
377 if (e2c_vec[i].av_position != UINT64_MAX) {
378 layout |= e2c_vec[i].av_position;
386 * Save current output configuration if and only if it has been locked.
388 static void push_output_configuration(AACContext *ac) {
389 if (ac->oc[1].status == OC_LOCKED) {
390 ac->oc[0] = ac->oc[1];
392 ac->oc[1].status = OC_NONE;
396 * Restore the previous output configuration if and only if the current
397 * configuration is unlocked.
399 static void pop_output_configuration(AACContext *ac) {
400 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
401 ac->oc[1] = ac->oc[0];
402 ac->avctx->channels = ac->oc[1].channels;
403 ac->avctx->channel_layout = ac->oc[1].channel_layout;
408 * Configure output channel order based on the current program configuration element.
410 * @return Returns error status. 0 - OK, !0 - error
412 static int output_configure(AACContext *ac,
413 uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
414 enum OCStatus oc_type, int get_new_frame)
416 AVCodecContext *avctx = ac->avctx;
417 int i, channels = 0, ret;
420 if (ac->oc[1].layout_map != layout_map) {
421 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
422 ac->oc[1].layout_map_tags = tags;
425 // Try to sniff a reasonable channel order, otherwise output the
426 // channels in the order the PCE declared them.
427 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
428 layout = sniff_channel_order(layout_map, tags);
429 for (i = 0; i < tags; i++) {
430 int type = layout_map[i][0];
431 int id = layout_map[i][1];
432 int position = layout_map[i][2];
433 // Allocate or free elements depending on if they are in the
434 // current program configuration.
435 ret = che_configure(ac, position, type, id, &channels);
439 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
440 if (layout == AV_CH_FRONT_CENTER) {
441 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
447 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
448 avctx->channel_layout = ac->oc[1].channel_layout = layout;
449 avctx->channels = ac->oc[1].channels = channels;
450 ac->oc[1].status = oc_type;
453 if ((ret = frame_configure_elements(ac->avctx)) < 0)
461 * Set up channel positions based on a default channel configuration
462 * as specified in table 1.17.
464 * @return Returns error status. 0 - OK, !0 - error
466 static int set_default_channel_config(AVCodecContext *avctx,
467 uint8_t (*layout_map)[3],
471 if (channel_config < 1 || channel_config > 7) {
472 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
476 *tags = tags_per_config[channel_config];
477 memcpy(layout_map, aac_channel_layout_map[channel_config-1], *tags * sizeof(*layout_map));
481 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
483 // For PCE based channel configurations map the channels solely based on tags.
484 if (!ac->oc[1].m4ac.chan_config) {
485 return ac->tag_che_map[type][elem_id];
487 // Allow single CPE stereo files to be signalled with mono configuration.
488 if (!ac->tags_mapped && type == TYPE_CPE && ac->oc[1].m4ac.chan_config == 1) {
489 uint8_t layout_map[MAX_ELEM_ID*4][3];
491 push_output_configuration(ac);
493 if (set_default_channel_config(ac->avctx, layout_map, &layout_map_tags,
496 if (output_configure(ac, layout_map, layout_map_tags,
497 OC_TRIAL_FRAME, 1) < 0)
500 ac->oc[1].m4ac.chan_config = 2;
501 ac->oc[1].m4ac.ps = 0;
504 if (!ac->tags_mapped && type == TYPE_SCE && ac->oc[1].m4ac.chan_config == 2) {
505 uint8_t layout_map[MAX_ELEM_ID*4][3];
507 push_output_configuration(ac);
509 if (set_default_channel_config(ac->avctx, layout_map, &layout_map_tags,
512 if (output_configure(ac, layout_map, layout_map_tags,
513 OC_TRIAL_FRAME, 1) < 0)
516 ac->oc[1].m4ac.chan_config = 1;
517 if (ac->oc[1].m4ac.sbr)
518 ac->oc[1].m4ac.ps = -1;
520 // For indexed channel configurations map the channels solely based on position.
521 switch (ac->oc[1].m4ac.chan_config) {
523 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
525 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
528 /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
529 instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
530 encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
531 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
533 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
536 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
538 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
541 if (ac->tags_mapped == 2 && ac->oc[1].m4ac.chan_config == 4 && type == TYPE_SCE) {
543 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
547 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) && type == TYPE_CPE) {
549 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
550 } else if (ac->oc[1].m4ac.chan_config == 2) {
554 if (!ac->tags_mapped && type == TYPE_SCE) {
556 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
564 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
566 * @param type speaker type/position for these channels
568 static void decode_channel_map(uint8_t layout_map[][3],
569 enum ChannelPosition type,
570 GetBitContext *gb, int n)
573 enum RawDataBlockType syn_ele;
575 case AAC_CHANNEL_FRONT:
576 case AAC_CHANNEL_BACK:
577 case AAC_CHANNEL_SIDE:
578 syn_ele = get_bits1(gb);
584 case AAC_CHANNEL_LFE:
588 layout_map[0][0] = syn_ele;
589 layout_map[0][1] = get_bits(gb, 4);
590 layout_map[0][2] = type;
596 * Decode program configuration element; reference: table 4.2.
598 * @return Returns error status. 0 - OK, !0 - error
600 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
601 uint8_t (*layout_map)[3],
604 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
608 skip_bits(gb, 2); // object_type
610 sampling_index = get_bits(gb, 4);
611 if (m4ac->sampling_index != sampling_index)
612 av_log(avctx, AV_LOG_WARNING, "Sample rate index in program config element does not match the sample rate index configured by the container.\n");
614 num_front = get_bits(gb, 4);
615 num_side = get_bits(gb, 4);
616 num_back = get_bits(gb, 4);
617 num_lfe = get_bits(gb, 2);
618 num_assoc_data = get_bits(gb, 3);
619 num_cc = get_bits(gb, 4);
622 skip_bits(gb, 4); // mono_mixdown_tag
624 skip_bits(gb, 4); // stereo_mixdown_tag
627 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
629 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
631 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
633 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
635 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
638 skip_bits_long(gb, 4 * num_assoc_data);
640 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
645 /* comment field, first byte is length */
646 comment_len = get_bits(gb, 8) * 8;
647 if (get_bits_left(gb) < comment_len) {
648 av_log(avctx, AV_LOG_ERROR, overread_err);
651 skip_bits_long(gb, comment_len);
656 * Decode GA "General Audio" specific configuration; reference: table 4.1.
658 * @param ac pointer to AACContext, may be null
659 * @param avctx pointer to AVCCodecContext, used for logging
661 * @return Returns error status. 0 - OK, !0 - error
663 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
665 MPEG4AudioConfig *m4ac,
668 int extension_flag, ret;
669 uint8_t layout_map[MAX_ELEM_ID*4][3];
672 if (get_bits1(gb)) { // frameLengthFlag
673 avpriv_request_sample(avctx, "960/120 MDCT window");
674 return AVERROR_PATCHWELCOME;
677 if (get_bits1(gb)) // dependsOnCoreCoder
678 skip_bits(gb, 14); // coreCoderDelay
679 extension_flag = get_bits1(gb);
681 if (m4ac->object_type == AOT_AAC_SCALABLE ||
682 m4ac->object_type == AOT_ER_AAC_SCALABLE)
683 skip_bits(gb, 3); // layerNr
685 if (channel_config == 0) {
686 skip_bits(gb, 4); // element_instance_tag
687 tags = decode_pce(avctx, m4ac, layout_map, gb);
691 if ((ret = set_default_channel_config(avctx, layout_map, &tags, channel_config)))
695 if (count_channels(layout_map, tags) > 1) {
697 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
700 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
703 if (extension_flag) {
704 switch (m4ac->object_type) {
706 skip_bits(gb, 5); // numOfSubFrame
707 skip_bits(gb, 11); // layer_length
711 case AOT_ER_AAC_SCALABLE:
713 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
714 * aacScalefactorDataResilienceFlag
715 * aacSpectralDataResilienceFlag
719 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
725 * Decode audio specific configuration; reference: table 1.13.
727 * @param ac pointer to AACContext, may be null
728 * @param avctx pointer to AVCCodecContext, used for logging
729 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
730 * @param data pointer to buffer holding an audio specific config
731 * @param bit_size size of audio specific config or data in bits
732 * @param sync_extension look for an appended sync extension
734 * @return Returns error status or number of consumed bits. <0 - error
736 static int decode_audio_specific_config(AACContext *ac,
737 AVCodecContext *avctx,
738 MPEG4AudioConfig *m4ac,
739 const uint8_t *data, int bit_size,
745 av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
746 for (i = 0; i < avctx->extradata_size; i++)
747 av_dlog(avctx, "%02x ", avctx->extradata[i]);
748 av_dlog(avctx, "\n");
750 init_get_bits(&gb, data, bit_size);
752 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
754 if (m4ac->sampling_index > 12) {
755 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
759 skip_bits_long(&gb, i);
761 switch (m4ac->object_type) {
765 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
769 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
770 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
774 av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
775 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
776 m4ac->sample_rate, m4ac->sbr, m4ac->ps);
778 return get_bits_count(&gb);
782 * linear congruential pseudorandom number generator
784 * @param previous_val pointer to the current state of the generator
786 * @return Returns a 32-bit pseudorandom integer
788 static av_always_inline int lcg_random(int previous_val)
790 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
794 static av_always_inline void reset_predict_state(PredictorState *ps)
804 static void reset_all_predictors(PredictorState *ps)
807 for (i = 0; i < MAX_PREDICTORS; i++)
808 reset_predict_state(&ps[i]);
811 static int sample_rate_idx (int rate)
813 if (92017 <= rate) return 0;
814 else if (75132 <= rate) return 1;
815 else if (55426 <= rate) return 2;
816 else if (46009 <= rate) return 3;
817 else if (37566 <= rate) return 4;
818 else if (27713 <= rate) return 5;
819 else if (23004 <= rate) return 6;
820 else if (18783 <= rate) return 7;
821 else if (13856 <= rate) return 8;
822 else if (11502 <= rate) return 9;
823 else if (9391 <= rate) return 10;
827 static void reset_predictor_group(PredictorState *ps, int group_num)
830 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
831 reset_predict_state(&ps[i]);
834 #define AAC_INIT_VLC_STATIC(num, size) \
835 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
836 ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
837 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
840 static av_cold int aac_decode_init(AVCodecContext *avctx)
842 AACContext *ac = avctx->priv_data;
845 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
847 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
849 if (avctx->extradata_size > 0) {
850 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
852 avctx->extradata_size*8, 1) < 0)
856 uint8_t layout_map[MAX_ELEM_ID*4][3];
859 sr = sample_rate_idx(avctx->sample_rate);
860 ac->oc[1].m4ac.sampling_index = sr;
861 ac->oc[1].m4ac.channels = avctx->channels;
862 ac->oc[1].m4ac.sbr = -1;
863 ac->oc[1].m4ac.ps = -1;
865 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
866 if (ff_mpeg4audio_channels[i] == avctx->channels)
868 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
871 ac->oc[1].m4ac.chan_config = i;
873 if (ac->oc[1].m4ac.chan_config) {
874 int ret = set_default_channel_config(avctx, layout_map,
875 &layout_map_tags, ac->oc[1].m4ac.chan_config);
877 output_configure(ac, layout_map, layout_map_tags,
879 else if (avctx->err_recognition & AV_EF_EXPLODE)
880 return AVERROR_INVALIDDATA;
884 AAC_INIT_VLC_STATIC( 0, 304);
885 AAC_INIT_VLC_STATIC( 1, 270);
886 AAC_INIT_VLC_STATIC( 2, 550);
887 AAC_INIT_VLC_STATIC( 3, 300);
888 AAC_INIT_VLC_STATIC( 4, 328);
889 AAC_INIT_VLC_STATIC( 5, 294);
890 AAC_INIT_VLC_STATIC( 6, 306);
891 AAC_INIT_VLC_STATIC( 7, 268);
892 AAC_INIT_VLC_STATIC( 8, 510);
893 AAC_INIT_VLC_STATIC( 9, 366);
894 AAC_INIT_VLC_STATIC(10, 462);
898 ff_fmt_convert_init(&ac->fmt_conv, avctx);
899 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
901 ac->random_state = 0x1f2e3d4c;
905 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
906 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
907 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
910 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
911 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
912 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
913 // window initialization
914 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
915 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
916 ff_init_ff_sine_windows(10);
917 ff_init_ff_sine_windows( 7);
925 * Skip data_stream_element; reference: table 4.10.
927 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
929 int byte_align = get_bits1(gb);
930 int count = get_bits(gb, 8);
932 count += get_bits(gb, 8);
936 if (get_bits_left(gb) < 8 * count) {
937 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
940 skip_bits_long(gb, 8 * count);
944 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
949 ics->predictor_reset_group = get_bits(gb, 5);
950 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
951 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
955 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
956 ics->prediction_used[sfb] = get_bits1(gb);
962 * Decode Long Term Prediction data; reference: table 4.xx.
964 static void decode_ltp(LongTermPrediction *ltp,
965 GetBitContext *gb, uint8_t max_sfb)
969 ltp->lag = get_bits(gb, 11);
970 ltp->coef = ltp_coef[get_bits(gb, 3)];
971 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
972 ltp->used[sfb] = get_bits1(gb);
976 * Decode Individual Channel Stream info; reference: table 4.6.
978 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
982 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
983 return AVERROR_INVALIDDATA;
985 ics->window_sequence[1] = ics->window_sequence[0];
986 ics->window_sequence[0] = get_bits(gb, 2);
987 ics->use_kb_window[1] = ics->use_kb_window[0];
988 ics->use_kb_window[0] = get_bits1(gb);
989 ics->num_window_groups = 1;
990 ics->group_len[0] = 1;
991 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
993 ics->max_sfb = get_bits(gb, 4);
994 for (i = 0; i < 7; i++) {
996 ics->group_len[ics->num_window_groups - 1]++;
998 ics->num_window_groups++;
999 ics->group_len[ics->num_window_groups - 1] = 1;
1002 ics->num_windows = 8;
1003 ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1004 ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1005 ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1006 ics->predictor_present = 0;
1008 ics->max_sfb = get_bits(gb, 6);
1009 ics->num_windows = 1;
1010 ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1011 ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1012 ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1013 ics->predictor_present = get_bits1(gb);
1014 ics->predictor_reset_group = 0;
1015 if (ics->predictor_present) {
1016 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1017 if (decode_prediction(ac, ics, gb)) {
1018 return AVERROR_INVALIDDATA;
1020 } else if (ac->oc[1].m4ac.object_type == AOT_AAC_LC) {
1021 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
1022 return AVERROR_INVALIDDATA;
1024 if ((ics->ltp.present = get_bits(gb, 1)))
1025 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1030 if (ics->max_sfb > ics->num_swb) {
1031 av_log(ac->avctx, AV_LOG_ERROR,
1032 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
1033 ics->max_sfb, ics->num_swb);
1034 return AVERROR_INVALIDDATA;
1041 * Decode band types (section_data payload); reference: table 4.46.
1043 * @param band_type array of the used band type
1044 * @param band_type_run_end array of the last scalefactor band of a band type run
1046 * @return Returns error status. 0 - OK, !0 - error
1048 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1049 int band_type_run_end[120], GetBitContext *gb,
1050 IndividualChannelStream *ics)
1053 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1054 for (g = 0; g < ics->num_window_groups; g++) {
1056 while (k < ics->max_sfb) {
1057 uint8_t sect_end = k;
1059 int sect_band_type = get_bits(gb, 4);
1060 if (sect_band_type == 12) {
1061 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1065 sect_len_incr = get_bits(gb, bits);
1066 sect_end += sect_len_incr;
1067 if (get_bits_left(gb) < 0) {
1068 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1071 if (sect_end > ics->max_sfb) {
1072 av_log(ac->avctx, AV_LOG_ERROR,
1073 "Number of bands (%d) exceeds limit (%d).\n",
1074 sect_end, ics->max_sfb);
1077 } while (sect_len_incr == (1 << bits) - 1);
1078 for (; k < sect_end; k++) {
1079 band_type [idx] = sect_band_type;
1080 band_type_run_end[idx++] = sect_end;
1088 * Decode scalefactors; reference: table 4.47.
1090 * @param global_gain first scalefactor value as scalefactors are differentially coded
1091 * @param band_type array of the used band type
1092 * @param band_type_run_end array of the last scalefactor band of a band type run
1093 * @param sf array of scalefactors or intensity stereo positions
1095 * @return Returns error status. 0 - OK, !0 - error
1097 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1098 unsigned int global_gain,
1099 IndividualChannelStream *ics,
1100 enum BandType band_type[120],
1101 int band_type_run_end[120])
1104 int offset[3] = { global_gain, global_gain - 90, 0 };
1107 for (g = 0; g < ics->num_window_groups; g++) {
1108 for (i = 0; i < ics->max_sfb;) {
1109 int run_end = band_type_run_end[idx];
1110 if (band_type[idx] == ZERO_BT) {
1111 for (; i < run_end; i++, idx++)
1113 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
1114 for (; i < run_end; i++, idx++) {
1115 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1116 clipped_offset = av_clip(offset[2], -155, 100);
1117 if (offset[2] != clipped_offset) {
1118 avpriv_request_sample(ac->avctx,
1119 "If you heard an audible artifact, there may be a bug in the decoder. "
1120 "Clipped intensity stereo position (%d -> %d)",
1121 offset[2], clipped_offset);
1123 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1125 } else if (band_type[idx] == NOISE_BT) {
1126 for (; i < run_end; i++, idx++) {
1127 if (noise_flag-- > 0)
1128 offset[1] += get_bits(gb, 9) - 256;
1130 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1131 clipped_offset = av_clip(offset[1], -100, 155);
1132 if (offset[1] != clipped_offset) {
1133 avpriv_request_sample(ac->avctx,
1134 "If you heard an audible artifact, there may be a bug in the decoder. "
1135 "Clipped noise gain (%d -> %d)",
1136 offset[1], clipped_offset);
1138 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1141 for (; i < run_end; i++, idx++) {
1142 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1143 if (offset[0] > 255U) {
1144 av_log(ac->avctx, AV_LOG_ERROR,
1145 "Scalefactor (%d) out of range.\n", offset[0]);
1148 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1157 * Decode pulse data; reference: table 4.7.
1159 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1160 const uint16_t *swb_offset, int num_swb)
1163 pulse->num_pulse = get_bits(gb, 2) + 1;
1164 pulse_swb = get_bits(gb, 6);
1165 if (pulse_swb >= num_swb)
1167 pulse->pos[0] = swb_offset[pulse_swb];
1168 pulse->pos[0] += get_bits(gb, 5);
1169 if (pulse->pos[0] > 1023)
1171 pulse->amp[0] = get_bits(gb, 4);
1172 for (i = 1; i < pulse->num_pulse; i++) {
1173 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1174 if (pulse->pos[i] > 1023)
1176 pulse->amp[i] = get_bits(gb, 4);
1182 * Decode Temporal Noise Shaping data; reference: table 4.48.
1184 * @return Returns error status. 0 - OK, !0 - error
1186 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1187 GetBitContext *gb, const IndividualChannelStream *ics)
1189 int w, filt, i, coef_len, coef_res, coef_compress;
1190 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1191 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1192 for (w = 0; w < ics->num_windows; w++) {
1193 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1194 coef_res = get_bits1(gb);
1196 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1198 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1200 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1201 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
1202 tns->order[w][filt], tns_max_order);
1203 tns->order[w][filt] = 0;
1206 if (tns->order[w][filt]) {
1207 tns->direction[w][filt] = get_bits1(gb);
1208 coef_compress = get_bits1(gb);
1209 coef_len = coef_res + 3 - coef_compress;
1210 tmp2_idx = 2 * coef_compress + coef_res;
1212 for (i = 0; i < tns->order[w][filt]; i++)
1213 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1222 * Decode Mid/Side data; reference: table 4.54.
1224 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1225 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1226 * [3] reserved for scalable AAC
1228 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1232 if (ms_present == 1) {
1233 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
1234 cpe->ms_mask[idx] = get_bits1(gb);
1235 } else if (ms_present == 2) {
1236 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
1241 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1245 *dst++ = v[idx & 15] * s;
1246 *dst++ = v[idx>>4 & 15] * s;
1252 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1256 *dst++ = v[idx & 3] * s;
1257 *dst++ = v[idx>>2 & 3] * s;
1258 *dst++ = v[idx>>4 & 3] * s;
1259 *dst++ = v[idx>>6 & 3] * s;
1265 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1266 unsigned sign, const float *scale)
1268 union av_intfloat32 s0, s1;
1270 s0.f = s1.f = *scale;
1271 s0.i ^= sign >> 1 << 31;
1274 *dst++ = v[idx & 15] * s0.f;
1275 *dst++ = v[idx>>4 & 15] * s1.f;
1282 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1283 unsigned sign, const float *scale)
1285 unsigned nz = idx >> 12;
1286 union av_intfloat32 s = { .f = *scale };
1287 union av_intfloat32 t;
1289 t.i = s.i ^ (sign & 1U<<31);
1290 *dst++ = v[idx & 3] * t.f;
1292 sign <<= nz & 1; nz >>= 1;
1293 t.i = s.i ^ (sign & 1U<<31);
1294 *dst++ = v[idx>>2 & 3] * t.f;
1296 sign <<= nz & 1; nz >>= 1;
1297 t.i = s.i ^ (sign & 1U<<31);
1298 *dst++ = v[idx>>4 & 3] * t.f;
1301 t.i = s.i ^ (sign & 1U<<31);
1302 *dst++ = v[idx>>6 & 3] * t.f;
1309 * Decode spectral data; reference: table 4.50.
1310 * Dequantize and scale spectral data; reference: 4.6.3.3.
1312 * @param coef array of dequantized, scaled spectral data
1313 * @param sf array of scalefactors or intensity stereo positions
1314 * @param pulse_present set if pulses are present
1315 * @param pulse pointer to pulse data struct
1316 * @param band_type array of the used band type
1318 * @return Returns error status. 0 - OK, !0 - error
1320 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1321 GetBitContext *gb, const float sf[120],
1322 int pulse_present, const Pulse *pulse,
1323 const IndividualChannelStream *ics,
1324 enum BandType band_type[120])
1326 int i, k, g, idx = 0;
1327 const int c = 1024 / ics->num_windows;
1328 const uint16_t *offsets = ics->swb_offset;
1329 float *coef_base = coef;
1331 for (g = 0; g < ics->num_windows; g++)
1332 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1334 for (g = 0; g < ics->num_window_groups; g++) {
1335 unsigned g_len = ics->group_len[g];
1337 for (i = 0; i < ics->max_sfb; i++, idx++) {
1338 const unsigned cbt_m1 = band_type[idx] - 1;
1339 float *cfo = coef + offsets[i];
1340 int off_len = offsets[i + 1] - offsets[i];
1343 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1344 for (group = 0; group < g_len; group++, cfo+=128) {
1345 memset(cfo, 0, off_len * sizeof(float));
1347 } else if (cbt_m1 == NOISE_BT - 1) {
1348 for (group = 0; group < g_len; group++, cfo+=128) {
1352 for (k = 0; k < off_len; k++) {
1353 ac->random_state = lcg_random(ac->random_state);
1354 cfo[k] = ac->random_state;
1357 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1358 scale = sf[idx] / sqrtf(band_energy);
1359 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1362 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1363 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1364 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1365 OPEN_READER(re, gb);
1367 switch (cbt_m1 >> 1) {
1369 for (group = 0; group < g_len; group++, cfo+=128) {
1377 UPDATE_CACHE(re, gb);
1378 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1379 cb_idx = cb_vector_idx[code];
1380 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1386 for (group = 0; group < g_len; group++, cfo+=128) {
1396 UPDATE_CACHE(re, gb);
1397 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1398 cb_idx = cb_vector_idx[code];
1399 nnz = cb_idx >> 8 & 15;
1400 bits = nnz ? GET_CACHE(re, gb) : 0;
1401 LAST_SKIP_BITS(re, gb, nnz);
1402 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1408 for (group = 0; group < g_len; group++, cfo+=128) {
1416 UPDATE_CACHE(re, gb);
1417 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1418 cb_idx = cb_vector_idx[code];
1419 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1426 for (group = 0; group < g_len; group++, cfo+=128) {
1436 UPDATE_CACHE(re, gb);
1437 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1438 cb_idx = cb_vector_idx[code];
1439 nnz = cb_idx >> 8 & 15;
1440 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1441 LAST_SKIP_BITS(re, gb, nnz);
1442 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1448 for (group = 0; group < g_len; group++, cfo+=128) {
1450 uint32_t *icf = (uint32_t *) cf;
1460 UPDATE_CACHE(re, gb);
1461 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1469 cb_idx = cb_vector_idx[code];
1472 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1473 LAST_SKIP_BITS(re, gb, nnz);
1475 for (j = 0; j < 2; j++) {
1479 /* The total length of escape_sequence must be < 22 bits according
1480 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1481 UPDATE_CACHE(re, gb);
1482 b = GET_CACHE(re, gb);
1483 b = 31 - av_log2(~b);
1486 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1490 SKIP_BITS(re, gb, b + 1);
1492 n = (1 << b) + SHOW_UBITS(re, gb, b);
1493 LAST_SKIP_BITS(re, gb, b);
1494 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1497 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1498 *icf++ = (bits & 1U<<31) | v;
1505 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1509 CLOSE_READER(re, gb);
1515 if (pulse_present) {
1517 for (i = 0; i < pulse->num_pulse; i++) {
1518 float co = coef_base[ pulse->pos[i] ];
1519 while (offsets[idx + 1] <= pulse->pos[i])
1521 if (band_type[idx] != NOISE_BT && sf[idx]) {
1522 float ico = -pulse->amp[i];
1525 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1527 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1534 static av_always_inline float flt16_round(float pf)
1536 union av_intfloat32 tmp;
1538 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1542 static av_always_inline float flt16_even(float pf)
1544 union av_intfloat32 tmp;
1546 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1550 static av_always_inline float flt16_trunc(float pf)
1552 union av_intfloat32 pun;
1554 pun.i &= 0xFFFF0000U;
1558 static av_always_inline void predict(PredictorState *ps, float *coef,
1561 const float a = 0.953125; // 61.0 / 64
1562 const float alpha = 0.90625; // 29.0 / 32
1566 float r0 = ps->r0, r1 = ps->r1;
1567 float cor0 = ps->cor0, cor1 = ps->cor1;
1568 float var0 = ps->var0, var1 = ps->var1;
1570 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1571 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1573 pv = flt16_round(k1 * r0 + k2 * r1);
1580 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1581 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1582 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1583 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1585 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1586 ps->r0 = flt16_trunc(a * e0);
1590 * Apply AAC-Main style frequency domain prediction.
1592 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1596 if (!sce->ics.predictor_initialized) {
1597 reset_all_predictors(sce->predictor_state);
1598 sce->ics.predictor_initialized = 1;
1601 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1602 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]; sfb++) {
1603 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1604 predict(&sce->predictor_state[k], &sce->coeffs[k],
1605 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1608 if (sce->ics.predictor_reset_group)
1609 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1611 reset_all_predictors(sce->predictor_state);
1615 * Decode an individual_channel_stream payload; reference: table 4.44.
1617 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1618 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1620 * @return Returns error status. 0 - OK, !0 - error
1622 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1623 GetBitContext *gb, int common_window, int scale_flag)
1626 TemporalNoiseShaping *tns = &sce->tns;
1627 IndividualChannelStream *ics = &sce->ics;
1628 float *out = sce->coeffs;
1629 int global_gain, pulse_present = 0;
1631 /* This assignment is to silence a GCC warning about the variable being used
1632 * uninitialized when in fact it always is.
1634 pulse.num_pulse = 0;
1636 global_gain = get_bits(gb, 8);
1638 if (!common_window && !scale_flag) {
1639 if (decode_ics_info(ac, ics, gb) < 0)
1640 return AVERROR_INVALIDDATA;
1643 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1645 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1650 if ((pulse_present = get_bits1(gb))) {
1651 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1652 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1655 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1656 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1660 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1662 if (get_bits1(gb)) {
1663 avpriv_request_sample(ac->avctx, "SSR");
1664 return AVERROR_PATCHWELCOME;
1668 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1671 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1672 apply_prediction(ac, sce);
1678 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1680 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1682 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1683 float *ch0 = cpe->ch[0].coeffs;
1684 float *ch1 = cpe->ch[1].coeffs;
1685 int g, i, group, idx = 0;
1686 const uint16_t *offsets = ics->swb_offset;
1687 for (g = 0; g < ics->num_window_groups; g++) {
1688 for (i = 0; i < ics->max_sfb; i++, idx++) {
1689 if (cpe->ms_mask[idx] &&
1690 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1691 for (group = 0; group < ics->group_len[g]; group++) {
1692 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1693 ch1 + group * 128 + offsets[i],
1694 offsets[i+1] - offsets[i]);
1698 ch0 += ics->group_len[g] * 128;
1699 ch1 += ics->group_len[g] * 128;
1704 * intensity stereo decoding; reference: 4.6.8.2.3
1706 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1707 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1708 * [3] reserved for scalable AAC
1710 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
1712 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1713 SingleChannelElement *sce1 = &cpe->ch[1];
1714 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1715 const uint16_t *offsets = ics->swb_offset;
1716 int g, group, i, idx = 0;
1719 for (g = 0; g < ics->num_window_groups; g++) {
1720 for (i = 0; i < ics->max_sfb;) {
1721 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1722 const int bt_run_end = sce1->band_type_run_end[idx];
1723 for (; i < bt_run_end; i++, idx++) {
1724 c = -1 + 2 * (sce1->band_type[idx] - 14);
1726 c *= 1 - 2 * cpe->ms_mask[idx];
1727 scale = c * sce1->sf[idx];
1728 for (group = 0; group < ics->group_len[g]; group++)
1729 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1730 coef0 + group * 128 + offsets[i],
1732 offsets[i + 1] - offsets[i]);
1735 int bt_run_end = sce1->band_type_run_end[idx];
1736 idx += bt_run_end - i;
1740 coef0 += ics->group_len[g] * 128;
1741 coef1 += ics->group_len[g] * 128;
1746 * Decode a channel_pair_element; reference: table 4.4.
1748 * @return Returns error status. 0 - OK, !0 - error
1750 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1752 int i, ret, common_window, ms_present = 0;
1754 common_window = get_bits1(gb);
1755 if (common_window) {
1756 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1757 return AVERROR_INVALIDDATA;
1758 i = cpe->ch[1].ics.use_kb_window[0];
1759 cpe->ch[1].ics = cpe->ch[0].ics;
1760 cpe->ch[1].ics.use_kb_window[1] = i;
1761 if (cpe->ch[1].ics.predictor_present && (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1762 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1763 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1764 ms_present = get_bits(gb, 2);
1765 if (ms_present == 3) {
1766 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1768 } else if (ms_present)
1769 decode_mid_side_stereo(cpe, gb, ms_present);
1771 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1773 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1776 if (common_window) {
1778 apply_mid_side_stereo(ac, cpe);
1779 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1780 apply_prediction(ac, &cpe->ch[0]);
1781 apply_prediction(ac, &cpe->ch[1]);
1785 apply_intensity_stereo(ac, cpe, ms_present);
1789 static const float cce_scale[] = {
1790 1.09050773266525765921, //2^(1/8)
1791 1.18920711500272106672, //2^(1/4)
1797 * Decode coupling_channel_element; reference: table 4.8.
1799 * @return Returns error status. 0 - OK, !0 - error
1801 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1807 SingleChannelElement *sce = &che->ch[0];
1808 ChannelCoupling *coup = &che->coup;
1810 coup->coupling_point = 2 * get_bits1(gb);
1811 coup->num_coupled = get_bits(gb, 3);
1812 for (c = 0; c <= coup->num_coupled; c++) {
1814 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1815 coup->id_select[c] = get_bits(gb, 4);
1816 if (coup->type[c] == TYPE_CPE) {
1817 coup->ch_select[c] = get_bits(gb, 2);
1818 if (coup->ch_select[c] == 3)
1821 coup->ch_select[c] = 2;
1823 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1825 sign = get_bits(gb, 1);
1826 scale = cce_scale[get_bits(gb, 2)];
1828 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1831 for (c = 0; c < num_gain; c++) {
1835 float gain_cache = 1.;
1837 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1838 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1839 gain_cache = powf(scale, -gain);
1841 if (coup->coupling_point == AFTER_IMDCT) {
1842 coup->gain[c][0] = gain_cache;
1844 for (g = 0; g < sce->ics.num_window_groups; g++) {
1845 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1846 if (sce->band_type[idx] != ZERO_BT) {
1848 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1856 gain_cache = powf(scale, -t) * s;
1859 coup->gain[c][idx] = gain_cache;
1869 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1871 * @return Returns number of bytes consumed.
1873 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1877 int num_excl_chan = 0;
1880 for (i = 0; i < 7; i++)
1881 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1882 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1884 return num_excl_chan / 7;
1888 * Decode dynamic range information; reference: table 4.52.
1890 * @return Returns number of bytes consumed.
1892 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1896 int drc_num_bands = 1;
1899 /* pce_tag_present? */
1900 if (get_bits1(gb)) {
1901 che_drc->pce_instance_tag = get_bits(gb, 4);
1902 skip_bits(gb, 4); // tag_reserved_bits
1906 /* excluded_chns_present? */
1907 if (get_bits1(gb)) {
1908 n += decode_drc_channel_exclusions(che_drc, gb);
1911 /* drc_bands_present? */
1912 if (get_bits1(gb)) {
1913 che_drc->band_incr = get_bits(gb, 4);
1914 che_drc->interpolation_scheme = get_bits(gb, 4);
1916 drc_num_bands += che_drc->band_incr;
1917 for (i = 0; i < drc_num_bands; i++) {
1918 che_drc->band_top[i] = get_bits(gb, 8);
1923 /* prog_ref_level_present? */
1924 if (get_bits1(gb)) {
1925 che_drc->prog_ref_level = get_bits(gb, 7);
1926 skip_bits1(gb); // prog_ref_level_reserved_bits
1930 for (i = 0; i < drc_num_bands; i++) {
1931 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1932 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1940 * Decode extension data (incomplete); reference: table 4.51.
1942 * @param cnt length of TYPE_FIL syntactic element in bytes
1944 * @return Returns number of bytes consumed
1946 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1947 ChannelElement *che, enum RawDataBlockType elem_type)
1951 switch (get_bits(gb, 4)) { // extension type
1952 case EXT_SBR_DATA_CRC:
1956 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1958 } else if (!ac->oc[1].m4ac.sbr) {
1959 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1960 skip_bits_long(gb, 8 * cnt - 4);
1962 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
1963 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1964 skip_bits_long(gb, 8 * cnt - 4);
1966 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
1967 ac->oc[1].m4ac.sbr = 1;
1968 ac->oc[1].m4ac.ps = 1;
1969 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
1970 ac->oc[1].status, 1);
1972 ac->oc[1].m4ac.sbr = 1;
1974 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1976 case EXT_DYNAMIC_RANGE:
1977 res = decode_dynamic_range(&ac->che_drc, gb);
1981 case EXT_DATA_ELEMENT:
1983 skip_bits_long(gb, 8 * cnt - 4);
1990 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1992 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1993 * @param coef spectral coefficients
1995 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1996 IndividualChannelStream *ics, int decode)
1998 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2000 int bottom, top, order, start, end, size, inc;
2001 float lpc[TNS_MAX_ORDER];
2002 float tmp[TNS_MAX_ORDER + 1];
2004 for (w = 0; w < ics->num_windows; w++) {
2005 bottom = ics->num_swb;
2006 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2008 bottom = FFMAX(0, top - tns->length[w][filt]);
2009 order = tns->order[w][filt];
2014 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2016 start = ics->swb_offset[FFMIN(bottom, mmm)];
2017 end = ics->swb_offset[FFMIN( top, mmm)];
2018 if ((size = end - start) <= 0)
2020 if (tns->direction[w][filt]) {
2030 for (m = 0; m < size; m++, start += inc)
2031 for (i = 1; i <= FFMIN(m, order); i++)
2032 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2035 for (m = 0; m < size; m++, start += inc) {
2036 tmp[0] = coef[start];
2037 for (i = 1; i <= FFMIN(m, order); i++)
2038 coef[start] += tmp[i] * lpc[i - 1];
2039 for (i = order; i > 0; i--)
2040 tmp[i] = tmp[i - 1];
2048 * Apply windowing and MDCT to obtain the spectral
2049 * coefficient from the predicted sample by LTP.
2051 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2052 float *in, IndividualChannelStream *ics)
2054 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2055 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2056 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2057 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2059 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2060 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2062 memset(in, 0, 448 * sizeof(float));
2063 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2065 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2066 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2068 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2069 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2071 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2075 * Apply the long term prediction
2077 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2079 const LongTermPrediction *ltp = &sce->ics.ltp;
2080 const uint16_t *offsets = sce->ics.swb_offset;
2083 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2084 float *predTime = sce->ret;
2085 float *predFreq = ac->buf_mdct;
2086 int16_t num_samples = 2048;
2088 if (ltp->lag < 1024)
2089 num_samples = ltp->lag + 1024;
2090 for (i = 0; i < num_samples; i++)
2091 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2092 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2094 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2096 if (sce->tns.present)
2097 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2099 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2101 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2102 sce->coeffs[i] += predFreq[i];
2107 * Update the LTP buffer for next frame
2109 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2111 IndividualChannelStream *ics = &sce->ics;
2112 float *saved = sce->saved;
2113 float *saved_ltp = sce->coeffs;
2114 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2115 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2118 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2119 memcpy(saved_ltp, saved, 512 * sizeof(float));
2120 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2121 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2122 for (i = 0; i < 64; i++)
2123 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2124 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2125 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2126 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2127 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2128 for (i = 0; i < 64; i++)
2129 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2130 } else { // LONG_STOP or ONLY_LONG
2131 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2132 for (i = 0; i < 512; i++)
2133 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2136 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2137 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2138 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2142 * Conduct IMDCT and windowing.
2144 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2146 IndividualChannelStream *ics = &sce->ics;
2147 float *in = sce->coeffs;
2148 float *out = sce->ret;
2149 float *saved = sce->saved;
2150 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2151 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2152 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2153 float *buf = ac->buf_mdct;
2154 float *temp = ac->temp;
2158 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2159 for (i = 0; i < 1024; i += 128)
2160 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2162 ac->mdct.imdct_half(&ac->mdct, buf, in);
2164 /* window overlapping
2165 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2166 * and long to short transitions are considered to be short to short
2167 * transitions. This leaves just two cases (long to long and short to short)
2168 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2170 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2171 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2172 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2174 memcpy( out, saved, 448 * sizeof(float));
2176 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2177 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2178 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2179 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2180 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2181 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2182 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2184 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2185 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2190 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2191 memcpy( saved, temp + 64, 64 * sizeof(float));
2192 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2193 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2194 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2195 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2196 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2197 memcpy( saved, buf + 512, 448 * sizeof(float));
2198 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2199 } else { // LONG_STOP or ONLY_LONG
2200 memcpy( saved, buf + 512, 512 * sizeof(float));
2205 * Apply dependent channel coupling (applied before IMDCT).
2207 * @param index index into coupling gain array
2209 static void apply_dependent_coupling(AACContext *ac,
2210 SingleChannelElement *target,
2211 ChannelElement *cce, int index)
2213 IndividualChannelStream *ics = &cce->ch[0].ics;
2214 const uint16_t *offsets = ics->swb_offset;
2215 float *dest = target->coeffs;
2216 const float *src = cce->ch[0].coeffs;
2217 int g, i, group, k, idx = 0;
2218 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2219 av_log(ac->avctx, AV_LOG_ERROR,
2220 "Dependent coupling is not supported together with LTP\n");
2223 for (g = 0; g < ics->num_window_groups; g++) {
2224 for (i = 0; i < ics->max_sfb; i++, idx++) {
2225 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2226 const float gain = cce->coup.gain[index][idx];
2227 for (group = 0; group < ics->group_len[g]; group++) {
2228 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2230 dest[group * 128 + k] += gain * src[group * 128 + k];
2235 dest += ics->group_len[g] * 128;
2236 src += ics->group_len[g] * 128;
2241 * Apply independent channel coupling (applied after IMDCT).
2243 * @param index index into coupling gain array
2245 static void apply_independent_coupling(AACContext *ac,
2246 SingleChannelElement *target,
2247 ChannelElement *cce, int index)
2250 const float gain = cce->coup.gain[index][0];
2251 const float *src = cce->ch[0].ret;
2252 float *dest = target->ret;
2253 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2255 for (i = 0; i < len; i++)
2256 dest[i] += gain * src[i];
2260 * channel coupling transformation interface
2262 * @param apply_coupling_method pointer to (in)dependent coupling function
2264 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2265 enum RawDataBlockType type, int elem_id,
2266 enum CouplingPoint coupling_point,
2267 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2271 for (i = 0; i < MAX_ELEM_ID; i++) {
2272 ChannelElement *cce = ac->che[TYPE_CCE][i];
2275 if (cce && cce->coup.coupling_point == coupling_point) {
2276 ChannelCoupling *coup = &cce->coup;
2278 for (c = 0; c <= coup->num_coupled; c++) {
2279 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2280 if (coup->ch_select[c] != 1) {
2281 apply_coupling_method(ac, &cc->ch[0], cce, index);
2282 if (coup->ch_select[c] != 0)
2285 if (coup->ch_select[c] != 2)
2286 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2288 index += 1 + (coup->ch_select[c] == 3);
2295 * Convert spectral data to float samples, applying all supported tools as appropriate.
2297 static void spectral_to_sample(AACContext *ac)
2300 for (type = 3; type >= 0; type--) {
2301 for (i = 0; i < MAX_ELEM_ID; i++) {
2302 ChannelElement *che = ac->che[type][i];
2304 if (type <= TYPE_CPE)
2305 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2306 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2307 if (che->ch[0].ics.predictor_present) {
2308 if (che->ch[0].ics.ltp.present)
2309 apply_ltp(ac, &che->ch[0]);
2310 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2311 apply_ltp(ac, &che->ch[1]);
2314 if (che->ch[0].tns.present)
2315 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2316 if (che->ch[1].tns.present)
2317 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2318 if (type <= TYPE_CPE)
2319 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2320 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2321 imdct_and_windowing(ac, &che->ch[0]);
2322 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2323 update_ltp(ac, &che->ch[0]);
2324 if (type == TYPE_CPE) {
2325 imdct_and_windowing(ac, &che->ch[1]);
2326 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2327 update_ltp(ac, &che->ch[1]);
2329 if (ac->oc[1].m4ac.sbr > 0) {
2330 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2333 if (type <= TYPE_CCE)
2334 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2340 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2343 AACADTSHeaderInfo hdr_info;
2344 uint8_t layout_map[MAX_ELEM_ID*4][3];
2345 int layout_map_tags;
2347 size = avpriv_aac_parse_header(gb, &hdr_info);
2349 if (hdr_info.num_aac_frames != 1) {
2350 avpriv_report_missing_feature(ac->avctx,
2351 "More than one AAC RDB per ADTS frame");
2352 return AVERROR_PATCHWELCOME;
2354 push_output_configuration(ac);
2355 if (hdr_info.chan_config) {
2356 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2357 if (set_default_channel_config(ac->avctx, layout_map,
2358 &layout_map_tags, hdr_info.chan_config))
2360 if (output_configure(ac, layout_map, layout_map_tags,
2361 FFMAX(ac->oc[1].status, OC_TRIAL_FRAME), 0))
2364 ac->oc[1].m4ac.chan_config = 0;
2366 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2367 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2368 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2369 if (ac->oc[0].status != OC_LOCKED ||
2370 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2371 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2372 ac->oc[1].m4ac.sbr = -1;
2373 ac->oc[1].m4ac.ps = -1;
2375 if (!hdr_info.crc_absent)
2381 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2382 int *got_frame_ptr, GetBitContext *gb)
2384 AACContext *ac = avctx->priv_data;
2385 ChannelElement *che = NULL, *che_prev = NULL;
2386 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2388 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2392 if (show_bits(gb, 12) == 0xfff) {
2393 if (parse_adts_frame_header(ac, gb) < 0) {
2394 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2398 if (ac->oc[1].m4ac.sampling_index > 12) {
2399 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2405 if (frame_configure_elements(avctx) < 0) {
2410 ac->tags_mapped = 0;
2412 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2413 elem_id = get_bits(gb, 4);
2415 if (elem_type < TYPE_DSE) {
2416 if (!(che=get_che(ac, elem_type, elem_id))) {
2417 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2418 elem_type, elem_id);
2425 switch (elem_type) {
2428 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2433 err = decode_cpe(ac, gb, che);
2438 err = decode_cce(ac, gb, che);
2442 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2447 err = skip_data_stream_element(ac, gb);
2451 uint8_t layout_map[MAX_ELEM_ID*4][3];
2453 push_output_configuration(ac);
2454 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2460 av_log(avctx, AV_LOG_ERROR,
2461 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2462 pop_output_configuration(ac);
2464 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2472 elem_id += get_bits(gb, 8) - 1;
2473 if (get_bits_left(gb) < 8 * elem_id) {
2474 av_log(avctx, AV_LOG_ERROR, overread_err);
2479 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2480 err = 0; /* FIXME */
2484 err = -1; /* should not happen, but keeps compiler happy */
2489 elem_type_prev = elem_type;
2494 if (get_bits_left(gb) < 3) {
2495 av_log(avctx, AV_LOG_ERROR, overread_err);
2501 spectral_to_sample(ac);
2503 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2504 samples <<= multiplier;
2507 ac->frame->nb_samples = samples;
2508 *got_frame_ptr = !!samples;
2510 if (ac->oc[1].status && audio_found) {
2511 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2512 avctx->frame_size = samples;
2513 ac->oc[1].status = OC_LOCKED;
2518 pop_output_configuration(ac);
2522 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2523 int *got_frame_ptr, AVPacket *avpkt)
2525 AACContext *ac = avctx->priv_data;
2526 const uint8_t *buf = avpkt->data;
2527 int buf_size = avpkt->size;
2532 int new_extradata_size;
2533 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2534 AV_PKT_DATA_NEW_EXTRADATA,
2535 &new_extradata_size);
2537 if (new_extradata) {
2538 av_free(avctx->extradata);
2539 avctx->extradata = av_mallocz(new_extradata_size +
2540 FF_INPUT_BUFFER_PADDING_SIZE);
2541 if (!avctx->extradata)
2542 return AVERROR(ENOMEM);
2543 avctx->extradata_size = new_extradata_size;
2544 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2545 push_output_configuration(ac);
2546 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2548 avctx->extradata_size*8, 1) < 0) {
2549 pop_output_configuration(ac);
2550 return AVERROR_INVALIDDATA;
2554 init_get_bits(&gb, buf, buf_size * 8);
2556 if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
2559 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2560 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2561 if (buf[buf_offset])
2564 return buf_size > buf_offset ? buf_consumed : buf_size;
2567 static av_cold int aac_decode_close(AVCodecContext *avctx)
2569 AACContext *ac = avctx->priv_data;
2572 for (i = 0; i < MAX_ELEM_ID; i++) {
2573 for (type = 0; type < 4; type++) {
2574 if (ac->che[type][i])
2575 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2576 av_freep(&ac->che[type][i]);
2580 ff_mdct_end(&ac->mdct);
2581 ff_mdct_end(&ac->mdct_small);
2582 ff_mdct_end(&ac->mdct_ltp);
2587 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2589 struct LATMContext {
2590 AACContext aac_ctx; ///< containing AACContext
2591 int initialized; ///< initilized after a valid extradata was seen
2594 int audio_mux_version_A; ///< LATM syntax version
2595 int frame_length_type; ///< 0/1 variable/fixed frame length
2596 int frame_length; ///< frame length for fixed frame length
2599 static inline uint32_t latm_get_value(GetBitContext *b)
2601 int length = get_bits(b, 2);
2603 return get_bits_long(b, (length+1)*8);
2606 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2607 GetBitContext *gb, int asclen)
2609 AACContext *ac = &latmctx->aac_ctx;
2610 AVCodecContext *avctx = ac->avctx;
2611 MPEG4AudioConfig m4ac = { 0 };
2612 int config_start_bit = get_bits_count(gb);
2613 int sync_extension = 0;
2614 int bits_consumed, esize;
2618 asclen = FFMIN(asclen, get_bits_left(gb));
2620 asclen = get_bits_left(gb);
2622 if (config_start_bit % 8) {
2623 avpriv_request_sample(latmctx->aac_ctx.avctx,
2624 "Non-byte-aligned audio-specific config");
2625 return AVERROR_PATCHWELCOME;
2628 return AVERROR_INVALIDDATA;
2629 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2630 gb->buffer + (config_start_bit / 8),
2631 asclen, sync_extension);
2633 if (bits_consumed < 0)
2634 return AVERROR_INVALIDDATA;
2636 if (ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
2637 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
2639 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2640 latmctx->initialized = 0;
2642 esize = (bits_consumed+7) / 8;
2644 if (avctx->extradata_size < esize) {
2645 av_free(avctx->extradata);
2646 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2647 if (!avctx->extradata)
2648 return AVERROR(ENOMEM);
2651 avctx->extradata_size = esize;
2652 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2653 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2655 skip_bits_long(gb, bits_consumed);
2657 return bits_consumed;
2660 static int read_stream_mux_config(struct LATMContext *latmctx,
2663 int ret, audio_mux_version = get_bits(gb, 1);
2665 latmctx->audio_mux_version_A = 0;
2666 if (audio_mux_version)
2667 latmctx->audio_mux_version_A = get_bits(gb, 1);
2669 if (!latmctx->audio_mux_version_A) {
2671 if (audio_mux_version)
2672 latm_get_value(gb); // taraFullness
2674 skip_bits(gb, 1); // allStreamSameTimeFraming
2675 skip_bits(gb, 6); // numSubFrames
2677 if (get_bits(gb, 4)) { // numPrograms
2678 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
2679 return AVERROR_PATCHWELCOME;
2682 // for each program (which there is only on in DVB)
2684 // for each layer (which there is only on in DVB)
2685 if (get_bits(gb, 3)) { // numLayer
2686 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
2687 return AVERROR_PATCHWELCOME;
2690 // for all but first stream: use_same_config = get_bits(gb, 1);
2691 if (!audio_mux_version) {
2692 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2695 int ascLen = latm_get_value(gb);
2696 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2699 skip_bits_long(gb, ascLen);
2702 latmctx->frame_length_type = get_bits(gb, 3);
2703 switch (latmctx->frame_length_type) {
2705 skip_bits(gb, 8); // latmBufferFullness
2708 latmctx->frame_length = get_bits(gb, 9);
2713 skip_bits(gb, 6); // CELP frame length table index
2717 skip_bits(gb, 1); // HVXC frame length table index
2721 if (get_bits(gb, 1)) { // other data
2722 if (audio_mux_version) {
2723 latm_get_value(gb); // other_data_bits
2727 esc = get_bits(gb, 1);
2733 if (get_bits(gb, 1)) // crc present
2734 skip_bits(gb, 8); // config_crc
2740 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2744 if (ctx->frame_length_type == 0) {
2745 int mux_slot_length = 0;
2747 tmp = get_bits(gb, 8);
2748 mux_slot_length += tmp;
2749 } while (tmp == 255);
2750 return mux_slot_length;
2751 } else if (ctx->frame_length_type == 1) {
2752 return ctx->frame_length;
2753 } else if (ctx->frame_length_type == 3 ||
2754 ctx->frame_length_type == 5 ||
2755 ctx->frame_length_type == 7) {
2756 skip_bits(gb, 2); // mux_slot_length_coded
2761 static int read_audio_mux_element(struct LATMContext *latmctx,
2765 uint8_t use_same_mux = get_bits(gb, 1);
2766 if (!use_same_mux) {
2767 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2769 } else if (!latmctx->aac_ctx.avctx->extradata) {
2770 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2771 "no decoder config found\n");
2772 return AVERROR(EAGAIN);
2774 if (latmctx->audio_mux_version_A == 0) {
2775 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2776 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2777 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2778 return AVERROR_INVALIDDATA;
2779 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2780 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2781 "frame length mismatch %d << %d\n",
2782 mux_slot_length_bytes * 8, get_bits_left(gb));
2783 return AVERROR_INVALIDDATA;
2790 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2791 int *got_frame_ptr, AVPacket *avpkt)
2793 struct LATMContext *latmctx = avctx->priv_data;
2797 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2799 // check for LOAS sync word
2800 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2801 return AVERROR_INVALIDDATA;
2803 muxlength = get_bits(&gb, 13) + 3;
2804 // not enough data, the parser should have sorted this
2805 if (muxlength > avpkt->size)
2806 return AVERROR_INVALIDDATA;
2808 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2811 if (!latmctx->initialized) {
2812 if (!avctx->extradata) {
2816 push_output_configuration(&latmctx->aac_ctx);
2817 if ((err = decode_audio_specific_config(
2818 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
2819 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
2820 pop_output_configuration(&latmctx->aac_ctx);
2823 latmctx->initialized = 1;
2827 if (show_bits(&gb, 12) == 0xfff) {
2828 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2829 "ADTS header detected, probably as result of configuration "
2831 return AVERROR_INVALIDDATA;
2834 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2840 static av_cold int latm_decode_init(AVCodecContext *avctx)
2842 struct LATMContext *latmctx = avctx->priv_data;
2843 int ret = aac_decode_init(avctx);
2845 if (avctx->extradata_size > 0)
2846 latmctx->initialized = !ret;
2852 AVCodec ff_aac_decoder = {
2854 .type = AVMEDIA_TYPE_AUDIO,
2855 .id = AV_CODEC_ID_AAC,
2856 .priv_data_size = sizeof(AACContext),
2857 .init = aac_decode_init,
2858 .close = aac_decode_close,
2859 .decode = aac_decode_frame,
2860 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
2861 .sample_fmts = (const enum AVSampleFormat[]) {
2862 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
2864 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2865 .channel_layouts = aac_channel_layout,
2869 Note: This decoder filter is intended to decode LATM streams transferred
2870 in MPEG transport streams which only contain one program.
2871 To do a more complex LATM demuxing a separate LATM demuxer should be used.
2873 AVCodec ff_aac_latm_decoder = {
2875 .type = AVMEDIA_TYPE_AUDIO,
2876 .id = AV_CODEC_ID_AAC_LATM,
2877 .priv_data_size = sizeof(struct LATMContext),
2878 .init = latm_decode_init,
2879 .close = aac_decode_close,
2880 .decode = latm_decode_frame,
2881 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
2882 .sample_fmts = (const enum AVSampleFormat[]) {
2883 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
2885 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2886 .channel_layouts = aac_channel_layout,