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-ffmpeg@jannau.net>
10 * This file is part of FFmpeg.
12 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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
88 #include "fmtconvert.h"
95 #include "aacdectab.h"
96 #include "cbrt_tablegen.h"
99 #include "mpeg4audio.h"
100 #include "aacadtsdec.h"
108 # include "arm/aac.h"
116 static VLC vlc_scalefactors;
117 static VLC vlc_spectral[11];
119 static const char overread_err[] = "Input buffer exhausted before END element found\n";
121 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
123 // For PCE based channel configurations map the channels solely based on tags.
124 if (!ac->m4ac.chan_config) {
125 return ac->tag_che_map[type][elem_id];
127 // For indexed channel configurations map the channels solely based on position.
128 switch (ac->m4ac.chan_config) {
130 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
132 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
135 /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
136 instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
137 encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
138 if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
140 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
143 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
145 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
148 if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
150 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
154 if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
156 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
157 } else if (ac->m4ac.chan_config == 2) {
161 if (!ac->tags_mapped && type == TYPE_SCE) {
163 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
171 * Check for the channel element in the current channel position configuration.
172 * If it exists, make sure the appropriate element is allocated and map the
173 * channel order to match the internal FFmpeg channel layout.
175 * @param che_pos current channel position configuration
176 * @param type channel element type
177 * @param id channel element id
178 * @param channels count of the number of channels in the configuration
180 * @return Returns error status. 0 - OK, !0 - error
182 static av_cold int che_configure(AACContext *ac,
183 enum ChannelPosition che_pos[4][MAX_ELEM_ID],
184 int type, int id, int *channels)
186 if (che_pos[type][id]) {
187 if (!ac->che[type][id]) {
188 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
189 return AVERROR(ENOMEM);
190 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
192 if (type != TYPE_CCE) {
193 ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
194 if (type == TYPE_CPE ||
195 (type == TYPE_SCE && ac->m4ac.ps == 1)) {
196 ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
200 if (ac->che[type][id])
201 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
202 av_freep(&ac->che[type][id]);
208 * Configure output channel order based on the current program configuration element.
210 * @param che_pos current channel position configuration
211 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
213 * @return Returns error status. 0 - OK, !0 - error
215 static av_cold int output_configure(AACContext *ac,
216 enum ChannelPosition che_pos[4][MAX_ELEM_ID],
217 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
218 int channel_config, enum OCStatus oc_type)
220 AVCodecContext *avctx = ac->avctx;
221 int i, type, channels = 0, ret;
223 if (new_che_pos != che_pos)
224 memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
226 if (channel_config) {
227 for (i = 0; i < tags_per_config[channel_config]; i++) {
228 if ((ret = che_configure(ac, che_pos,
229 aac_channel_layout_map[channel_config - 1][i][0],
230 aac_channel_layout_map[channel_config - 1][i][1],
235 memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
237 avctx->channel_layout = aac_channel_layout[channel_config - 1];
239 /* Allocate or free elements depending on if they are in the
240 * current program configuration.
242 * Set up default 1:1 output mapping.
244 * For a 5.1 stream the output order will be:
245 * [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
248 for (i = 0; i < MAX_ELEM_ID; i++) {
249 for (type = 0; type < 4; type++) {
250 if ((ret = che_configure(ac, che_pos, type, i, &channels)))
255 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
258 avctx->channels = channels;
260 ac->output_configured = oc_type;
265 static void flush(AVCodecContext *avctx)
267 AACContext *ac= avctx->priv_data;
270 for (type = 3; type >= 0; type--) {
271 for (i = 0; i < MAX_ELEM_ID; i++) {
272 ChannelElement *che = ac->che[type][i];
274 for (j = 0; j <= 1; j++) {
275 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
283 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
285 * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
286 * @param sce_map mono (Single Channel Element) map
287 * @param type speaker type/position for these channels
289 static void decode_channel_map(enum ChannelPosition *cpe_map,
290 enum ChannelPosition *sce_map,
291 enum ChannelPosition type,
292 GetBitContext *gb, int n)
295 enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
296 map[get_bits(gb, 4)] = type;
301 * Decode program configuration element; reference: table 4.2.
303 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
305 * @return Returns error status. 0 - OK, !0 - error
307 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
308 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
311 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
314 skip_bits(gb, 2); // object_type
316 sampling_index = get_bits(gb, 4);
317 if (m4ac->sampling_index != sampling_index)
318 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");
320 num_front = get_bits(gb, 4);
321 num_side = get_bits(gb, 4);
322 num_back = get_bits(gb, 4);
323 num_lfe = get_bits(gb, 2);
324 num_assoc_data = get_bits(gb, 3);
325 num_cc = get_bits(gb, 4);
328 skip_bits(gb, 4); // mono_mixdown_tag
330 skip_bits(gb, 4); // stereo_mixdown_tag
333 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
335 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
336 av_log(avctx, AV_LOG_ERROR, overread_err);
339 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
340 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
341 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
342 decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
344 skip_bits_long(gb, 4 * num_assoc_data);
346 decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
350 /* comment field, first byte is length */
351 comment_len = get_bits(gb, 8) * 8;
352 if (get_bits_left(gb) < comment_len) {
353 av_log(avctx, AV_LOG_ERROR, overread_err);
356 skip_bits_long(gb, comment_len);
361 * Set up channel positions based on a default channel configuration
362 * as specified in table 1.17.
364 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
366 * @return Returns error status. 0 - OK, !0 - error
368 static av_cold int set_default_channel_config(AVCodecContext *avctx,
369 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
372 if (channel_config < 1 || channel_config > 7) {
373 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
378 /* default channel configurations:
380 * 1ch : front center (mono)
381 * 2ch : L + R (stereo)
382 * 3ch : front center + L + R
383 * 4ch : front center + L + R + back center
384 * 5ch : front center + L + R + back stereo
385 * 6ch : front center + L + R + back stereo + LFE
386 * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
389 if (channel_config != 2)
390 new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
391 if (channel_config > 1)
392 new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
393 if (channel_config == 4)
394 new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
395 if (channel_config > 4)
396 new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
397 = AAC_CHANNEL_BACK; // back stereo
398 if (channel_config > 5)
399 new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
400 if (channel_config == 7)
401 new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
407 * Decode GA "General Audio" specific configuration; reference: table 4.1.
409 * @param ac pointer to AACContext, may be null
410 * @param avctx pointer to AVCCodecContext, used for logging
412 * @return Returns error status. 0 - OK, !0 - error
414 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
416 MPEG4AudioConfig *m4ac,
419 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
420 int extension_flag, ret;
422 if (get_bits1(gb)) { // frameLengthFlag
423 av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
427 if (get_bits1(gb)) // dependsOnCoreCoder
428 skip_bits(gb, 14); // coreCoderDelay
429 extension_flag = get_bits1(gb);
431 if (m4ac->object_type == AOT_AAC_SCALABLE ||
432 m4ac->object_type == AOT_ER_AAC_SCALABLE)
433 skip_bits(gb, 3); // layerNr
435 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
436 if (channel_config == 0) {
437 skip_bits(gb, 4); // element_instance_tag
438 if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
441 if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
444 if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
447 if (extension_flag) {
448 switch (m4ac->object_type) {
450 skip_bits(gb, 5); // numOfSubFrame
451 skip_bits(gb, 11); // layer_length
455 case AOT_ER_AAC_SCALABLE:
457 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
458 * aacScalefactorDataResilienceFlag
459 * aacSpectralDataResilienceFlag
463 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
469 * Decode audio specific configuration; reference: table 1.13.
471 * @param ac pointer to AACContext, may be null
472 * @param avctx pointer to AVCCodecContext, used for logging
473 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
474 * @param data pointer to buffer holding an audio specific config
475 * @param bit_size size of audio specific config or data in bits
476 * @param sync_extension look for an appended sync extension
478 * @return Returns error status or number of consumed bits. <0 - error
480 static int decode_audio_specific_config(AACContext *ac,
481 AVCodecContext *avctx,
482 MPEG4AudioConfig *m4ac,
483 const uint8_t *data, int bit_size,
489 av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
490 for (i = 0; i < avctx->extradata_size; i++)
491 av_dlog(avctx, "%02x ", avctx->extradata[i]);
492 av_dlog(avctx, "\n");
494 init_get_bits(&gb, data, bit_size);
496 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
498 if (m4ac->sampling_index > 12) {
499 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
502 if (m4ac->sbr == 1 && m4ac->ps == -1)
505 skip_bits_long(&gb, i);
507 switch (m4ac->object_type) {
511 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
515 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
516 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
520 av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
521 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
522 m4ac->sample_rate, m4ac->sbr, m4ac->ps);
524 return get_bits_count(&gb);
528 * linear congruential pseudorandom number generator
530 * @param previous_val pointer to the current state of the generator
532 * @return Returns a 32-bit pseudorandom integer
534 static av_always_inline int lcg_random(int previous_val)
536 return previous_val * 1664525 + 1013904223;
539 static av_always_inline void reset_predict_state(PredictorState *ps)
549 static void reset_all_predictors(PredictorState *ps)
552 for (i = 0; i < MAX_PREDICTORS; i++)
553 reset_predict_state(&ps[i]);
556 static int sample_rate_idx (int rate)
558 if (92017 <= rate) return 0;
559 else if (75132 <= rate) return 1;
560 else if (55426 <= rate) return 2;
561 else if (46009 <= rate) return 3;
562 else if (37566 <= rate) return 4;
563 else if (27713 <= rate) return 5;
564 else if (23004 <= rate) return 6;
565 else if (18783 <= rate) return 7;
566 else if (13856 <= rate) return 8;
567 else if (11502 <= rate) return 9;
568 else if (9391 <= rate) return 10;
572 static void reset_predictor_group(PredictorState *ps, int group_num)
575 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
576 reset_predict_state(&ps[i]);
579 #define AAC_INIT_VLC_STATIC(num, size) \
580 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
581 ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
582 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
585 static av_cold int aac_decode_init(AVCodecContext *avctx)
587 AACContext *ac = avctx->priv_data;
588 float output_scale_factor;
591 ac->m4ac.sample_rate = avctx->sample_rate;
593 if (avctx->extradata_size > 0) {
594 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
596 avctx->extradata_size*8, 1) < 0)
600 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
602 sr = sample_rate_idx(avctx->sample_rate);
603 ac->m4ac.sampling_index = sr;
604 ac->m4ac.channels = avctx->channels;
608 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
609 if (ff_mpeg4audio_channels[i] == avctx->channels)
611 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
614 ac->m4ac.chan_config = i;
616 if (ac->m4ac.chan_config) {
617 int ret = set_default_channel_config(avctx, new_che_pos, ac->m4ac.chan_config);
619 output_configure(ac, ac->che_pos, new_che_pos, ac->m4ac.chan_config, OC_GLOBAL_HDR);
620 else if (avctx->err_recognition & AV_EF_EXPLODE)
621 return AVERROR_INVALIDDATA;
625 if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
626 avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
627 output_scale_factor = 1.0 / 32768.0;
629 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
630 output_scale_factor = 1.0;
633 AAC_INIT_VLC_STATIC( 0, 304);
634 AAC_INIT_VLC_STATIC( 1, 270);
635 AAC_INIT_VLC_STATIC( 2, 550);
636 AAC_INIT_VLC_STATIC( 3, 300);
637 AAC_INIT_VLC_STATIC( 4, 328);
638 AAC_INIT_VLC_STATIC( 5, 294);
639 AAC_INIT_VLC_STATIC( 6, 306);
640 AAC_INIT_VLC_STATIC( 7, 268);
641 AAC_INIT_VLC_STATIC( 8, 510);
642 AAC_INIT_VLC_STATIC( 9, 366);
643 AAC_INIT_VLC_STATIC(10, 462);
647 dsputil_init(&ac->dsp, avctx);
648 ff_fmt_convert_init(&ac->fmt_conv, avctx);
650 ac->random_state = 0x1f2e3d4c;
654 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
655 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
656 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
659 ff_mdct_init(&ac->mdct, 11, 1, output_scale_factor/1024.0);
660 ff_mdct_init(&ac->mdct_small, 8, 1, output_scale_factor/128.0);
661 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0/output_scale_factor);
662 // window initialization
663 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
664 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
665 ff_init_ff_sine_windows(10);
666 ff_init_ff_sine_windows( 7);
670 avcodec_get_frame_defaults(&ac->frame);
671 avctx->coded_frame = &ac->frame;
677 * Skip data_stream_element; reference: table 4.10.
679 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
681 int byte_align = get_bits1(gb);
682 int count = get_bits(gb, 8);
684 count += get_bits(gb, 8);
688 if (get_bits_left(gb) < 8 * count) {
689 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
692 skip_bits_long(gb, 8 * count);
696 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
701 ics->predictor_reset_group = get_bits(gb, 5);
702 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
703 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
707 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
708 ics->prediction_used[sfb] = get_bits1(gb);
714 * Decode Long Term Prediction data; reference: table 4.xx.
716 static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
717 GetBitContext *gb, uint8_t max_sfb)
721 ltp->lag = get_bits(gb, 11);
722 ltp->coef = ltp_coef[get_bits(gb, 3)];
723 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
724 ltp->used[sfb] = get_bits1(gb);
728 * Decode Individual Channel Stream info; reference: table 4.6.
730 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
732 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
733 GetBitContext *gb, int common_window)
736 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
737 memset(ics, 0, sizeof(IndividualChannelStream));
740 ics->window_sequence[1] = ics->window_sequence[0];
741 ics->window_sequence[0] = get_bits(gb, 2);
742 ics->use_kb_window[1] = ics->use_kb_window[0];
743 ics->use_kb_window[0] = get_bits1(gb);
744 ics->num_window_groups = 1;
745 ics->group_len[0] = 1;
746 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
748 ics->max_sfb = get_bits(gb, 4);
749 for (i = 0; i < 7; i++) {
751 ics->group_len[ics->num_window_groups - 1]++;
753 ics->num_window_groups++;
754 ics->group_len[ics->num_window_groups - 1] = 1;
757 ics->num_windows = 8;
758 ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
759 ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
760 ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
761 ics->predictor_present = 0;
763 ics->max_sfb = get_bits(gb, 6);
764 ics->num_windows = 1;
765 ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
766 ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
767 ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
768 ics->predictor_present = get_bits1(gb);
769 ics->predictor_reset_group = 0;
770 if (ics->predictor_present) {
771 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
772 if (decode_prediction(ac, ics, gb)) {
773 memset(ics, 0, sizeof(IndividualChannelStream));
776 } else if (ac->m4ac.object_type == AOT_AAC_LC) {
777 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
778 memset(ics, 0, sizeof(IndividualChannelStream));
781 if ((ics->ltp.present = get_bits(gb, 1)))
782 decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
787 if (ics->max_sfb > ics->num_swb) {
788 av_log(ac->avctx, AV_LOG_ERROR,
789 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
790 ics->max_sfb, ics->num_swb);
791 memset(ics, 0, sizeof(IndividualChannelStream));
799 * Decode band types (section_data payload); reference: table 4.46.
801 * @param band_type array of the used band type
802 * @param band_type_run_end array of the last scalefactor band of a band type run
804 * @return Returns error status. 0 - OK, !0 - error
806 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
807 int band_type_run_end[120], GetBitContext *gb,
808 IndividualChannelStream *ics)
811 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
812 for (g = 0; g < ics->num_window_groups; g++) {
814 while (k < ics->max_sfb) {
815 uint8_t sect_end = k;
817 int sect_band_type = get_bits(gb, 4);
818 if (sect_band_type == 12) {
819 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
822 while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
823 sect_end += sect_len_incr;
824 sect_end += sect_len_incr;
825 if (get_bits_left(gb) < 0) {
826 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
829 if (sect_end > ics->max_sfb) {
830 av_log(ac->avctx, AV_LOG_ERROR,
831 "Number of bands (%d) exceeds limit (%d).\n",
832 sect_end, ics->max_sfb);
835 for (; k < sect_end; k++) {
836 band_type [idx] = sect_band_type;
837 band_type_run_end[idx++] = sect_end;
845 * Decode scalefactors; reference: table 4.47.
847 * @param global_gain first scalefactor value as scalefactors are differentially coded
848 * @param band_type array of the used band type
849 * @param band_type_run_end array of the last scalefactor band of a band type run
850 * @param sf array of scalefactors or intensity stereo positions
852 * @return Returns error status. 0 - OK, !0 - error
854 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
855 unsigned int global_gain,
856 IndividualChannelStream *ics,
857 enum BandType band_type[120],
858 int band_type_run_end[120])
861 int offset[3] = { global_gain, global_gain - 90, 0 };
864 static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
865 for (g = 0; g < ics->num_window_groups; g++) {
866 for (i = 0; i < ics->max_sfb;) {
867 int run_end = band_type_run_end[idx];
868 if (band_type[idx] == ZERO_BT) {
869 for (; i < run_end; i++, idx++)
871 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
872 for (; i < run_end; i++, idx++) {
873 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
874 clipped_offset = av_clip(offset[2], -155, 100);
875 if (offset[2] != clipped_offset) {
876 av_log_ask_for_sample(ac->avctx, "Intensity stereo "
877 "position clipped (%d -> %d).\nIf you heard an "
878 "audible artifact, there may be a bug in the "
879 "decoder. ", offset[2], clipped_offset);
881 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
883 } else if (band_type[idx] == NOISE_BT) {
884 for (; i < run_end; i++, idx++) {
885 if (noise_flag-- > 0)
886 offset[1] += get_bits(gb, 9) - 256;
888 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
889 clipped_offset = av_clip(offset[1], -100, 155);
890 if (offset[1] != clipped_offset) {
891 av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
892 "(%d -> %d).\nIf you heard an audible "
893 "artifact, there may be a bug in the decoder. ",
894 offset[1], clipped_offset);
896 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
899 for (; i < run_end; i++, idx++) {
900 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
901 if (offset[0] > 255U) {
902 av_log(ac->avctx, AV_LOG_ERROR,
903 "%s (%d) out of range.\n", sf_str[0], offset[0]);
906 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
915 * Decode pulse data; reference: table 4.7.
917 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
918 const uint16_t *swb_offset, int num_swb)
921 pulse->num_pulse = get_bits(gb, 2) + 1;
922 pulse_swb = get_bits(gb, 6);
923 if (pulse_swb >= num_swb)
925 pulse->pos[0] = swb_offset[pulse_swb];
926 pulse->pos[0] += get_bits(gb, 5);
927 if (pulse->pos[0] > 1023)
929 pulse->amp[0] = get_bits(gb, 4);
930 for (i = 1; i < pulse->num_pulse; i++) {
931 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
932 if (pulse->pos[i] > 1023)
934 pulse->amp[i] = get_bits(gb, 4);
940 * Decode Temporal Noise Shaping data; reference: table 4.48.
942 * @return Returns error status. 0 - OK, !0 - error
944 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
945 GetBitContext *gb, const IndividualChannelStream *ics)
947 int w, filt, i, coef_len, coef_res, coef_compress;
948 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
949 const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
950 for (w = 0; w < ics->num_windows; w++) {
951 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
952 coef_res = get_bits1(gb);
954 for (filt = 0; filt < tns->n_filt[w]; filt++) {
956 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
958 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
959 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
960 tns->order[w][filt], tns_max_order);
961 tns->order[w][filt] = 0;
964 if (tns->order[w][filt]) {
965 tns->direction[w][filt] = get_bits1(gb);
966 coef_compress = get_bits1(gb);
967 coef_len = coef_res + 3 - coef_compress;
968 tmp2_idx = 2 * coef_compress + coef_res;
970 for (i = 0; i < tns->order[w][filt]; i++)
971 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
980 * Decode Mid/Side data; reference: table 4.54.
982 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
983 * [1] mask is decoded from bitstream; [2] mask is all 1s;
984 * [3] reserved for scalable AAC
986 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
990 if (ms_present == 1) {
991 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
992 cpe->ms_mask[idx] = get_bits1(gb);
993 } else if (ms_present == 2) {
994 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
999 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1003 *dst++ = v[idx & 15] * s;
1004 *dst++ = v[idx>>4 & 15] * s;
1010 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1014 *dst++ = v[idx & 3] * s;
1015 *dst++ = v[idx>>2 & 3] * s;
1016 *dst++ = v[idx>>4 & 3] * s;
1017 *dst++ = v[idx>>6 & 3] * s;
1023 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1024 unsigned sign, const float *scale)
1026 union float754 s0, s1;
1028 s0.f = s1.f = *scale;
1029 s0.i ^= sign >> 1 << 31;
1032 *dst++ = v[idx & 15] * s0.f;
1033 *dst++ = v[idx>>4 & 15] * s1.f;
1040 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1041 unsigned sign, const float *scale)
1043 unsigned nz = idx >> 12;
1044 union float754 s = { .f = *scale };
1047 t.i = s.i ^ (sign & 1U<<31);
1048 *dst++ = v[idx & 3] * t.f;
1050 sign <<= nz & 1; nz >>= 1;
1051 t.i = s.i ^ (sign & 1U<<31);
1052 *dst++ = v[idx>>2 & 3] * t.f;
1054 sign <<= nz & 1; nz >>= 1;
1055 t.i = s.i ^ (sign & 1U<<31);
1056 *dst++ = v[idx>>4 & 3] * t.f;
1058 sign <<= nz & 1; nz >>= 1;
1059 t.i = s.i ^ (sign & 1U<<31);
1060 *dst++ = v[idx>>6 & 3] * t.f;
1067 * Decode spectral data; reference: table 4.50.
1068 * Dequantize and scale spectral data; reference: 4.6.3.3.
1070 * @param coef array of dequantized, scaled spectral data
1071 * @param sf array of scalefactors or intensity stereo positions
1072 * @param pulse_present set if pulses are present
1073 * @param pulse pointer to pulse data struct
1074 * @param band_type array of the used band type
1076 * @return Returns error status. 0 - OK, !0 - error
1078 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1079 GetBitContext *gb, const float sf[120],
1080 int pulse_present, const Pulse *pulse,
1081 const IndividualChannelStream *ics,
1082 enum BandType band_type[120])
1084 int i, k, g, idx = 0;
1085 const int c = 1024 / ics->num_windows;
1086 const uint16_t *offsets = ics->swb_offset;
1087 float *coef_base = coef;
1089 for (g = 0; g < ics->num_windows; g++)
1090 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1092 for (g = 0; g < ics->num_window_groups; g++) {
1093 unsigned g_len = ics->group_len[g];
1095 for (i = 0; i < ics->max_sfb; i++, idx++) {
1096 const unsigned cbt_m1 = band_type[idx] - 1;
1097 float *cfo = coef + offsets[i];
1098 int off_len = offsets[i + 1] - offsets[i];
1101 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1102 for (group = 0; group < g_len; group++, cfo+=128) {
1103 memset(cfo, 0, off_len * sizeof(float));
1105 } else if (cbt_m1 == NOISE_BT - 1) {
1106 for (group = 0; group < g_len; group++, cfo+=128) {
1110 for (k = 0; k < off_len; k++) {
1111 ac->random_state = lcg_random(ac->random_state);
1112 cfo[k] = ac->random_state;
1115 band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1116 scale = sf[idx] / sqrtf(band_energy);
1117 ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1120 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1121 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1122 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1123 OPEN_READER(re, gb);
1125 switch (cbt_m1 >> 1) {
1127 for (group = 0; group < g_len; group++, cfo+=128) {
1135 UPDATE_CACHE(re, gb);
1136 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1137 cb_idx = cb_vector_idx[code];
1138 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1144 for (group = 0; group < g_len; group++, cfo+=128) {
1154 UPDATE_CACHE(re, gb);
1155 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1156 cb_idx = cb_vector_idx[code];
1157 nnz = cb_idx >> 8 & 15;
1158 bits = nnz ? GET_CACHE(re, gb) : 0;
1159 LAST_SKIP_BITS(re, gb, nnz);
1160 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1166 for (group = 0; group < g_len; group++, cfo+=128) {
1174 UPDATE_CACHE(re, gb);
1175 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1176 cb_idx = cb_vector_idx[code];
1177 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1184 for (group = 0; group < g_len; group++, cfo+=128) {
1194 UPDATE_CACHE(re, gb);
1195 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1196 cb_idx = cb_vector_idx[code];
1197 nnz = cb_idx >> 8 & 15;
1198 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1199 LAST_SKIP_BITS(re, gb, nnz);
1200 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1206 for (group = 0; group < g_len; group++, cfo+=128) {
1208 uint32_t *icf = (uint32_t *) cf;
1218 UPDATE_CACHE(re, gb);
1219 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1227 cb_idx = cb_vector_idx[code];
1230 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1231 LAST_SKIP_BITS(re, gb, nnz);
1233 for (j = 0; j < 2; j++) {
1237 /* The total length of escape_sequence must be < 22 bits according
1238 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1239 UPDATE_CACHE(re, gb);
1240 b = GET_CACHE(re, gb);
1241 b = 31 - av_log2(~b);
1244 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1248 SKIP_BITS(re, gb, b + 1);
1250 n = (1 << b) + SHOW_UBITS(re, gb, b);
1251 LAST_SKIP_BITS(re, gb, b);
1252 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1255 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1256 *icf++ = (bits & 1U<<31) | v;
1263 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1267 CLOSE_READER(re, gb);
1273 if (pulse_present) {
1275 for (i = 0; i < pulse->num_pulse; i++) {
1276 float co = coef_base[ pulse->pos[i] ];
1277 while (offsets[idx + 1] <= pulse->pos[i])
1279 if (band_type[idx] != NOISE_BT && sf[idx]) {
1280 float ico = -pulse->amp[i];
1283 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1285 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1292 static av_always_inline float flt16_round(float pf)
1296 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1300 static av_always_inline float flt16_even(float pf)
1304 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1308 static av_always_inline float flt16_trunc(float pf)
1312 pun.i &= 0xFFFF0000U;
1316 static av_always_inline void predict(PredictorState *ps, float *coef,
1319 const float a = 0.953125; // 61.0 / 64
1320 const float alpha = 0.90625; // 29.0 / 32
1324 float r0 = ps->r0, r1 = ps->r1;
1325 float cor0 = ps->cor0, cor1 = ps->cor1;
1326 float var0 = ps->var0, var1 = ps->var1;
1328 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1329 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1331 pv = flt16_round(k1 * r0 + k2 * r1);
1338 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1339 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1340 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1341 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1343 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1344 ps->r0 = flt16_trunc(a * e0);
1348 * Apply AAC-Main style frequency domain prediction.
1350 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1354 if (!sce->ics.predictor_initialized) {
1355 reset_all_predictors(sce->predictor_state);
1356 sce->ics.predictor_initialized = 1;
1359 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1360 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1361 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1362 predict(&sce->predictor_state[k], &sce->coeffs[k],
1363 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1366 if (sce->ics.predictor_reset_group)
1367 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1369 reset_all_predictors(sce->predictor_state);
1373 * Decode an individual_channel_stream payload; reference: table 4.44.
1375 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1376 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1378 * @return Returns error status. 0 - OK, !0 - error
1380 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1381 GetBitContext *gb, int common_window, int scale_flag)
1384 TemporalNoiseShaping *tns = &sce->tns;
1385 IndividualChannelStream *ics = &sce->ics;
1386 float *out = sce->coeffs;
1387 int global_gain, pulse_present = 0;
1389 /* This assignment is to silence a GCC warning about the variable being used
1390 * uninitialized when in fact it always is.
1392 pulse.num_pulse = 0;
1394 global_gain = get_bits(gb, 8);
1396 if (!common_window && !scale_flag) {
1397 if (decode_ics_info(ac, ics, gb, 0) < 0)
1401 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1403 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1408 if ((pulse_present = get_bits1(gb))) {
1409 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1410 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1413 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1414 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1418 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1420 if (get_bits1(gb)) {
1421 av_log_missing_feature(ac->avctx, "SSR", 1);
1426 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1429 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1430 apply_prediction(ac, sce);
1436 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1438 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1440 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1441 float *ch0 = cpe->ch[0].coeffs;
1442 float *ch1 = cpe->ch[1].coeffs;
1443 int g, i, group, idx = 0;
1444 const uint16_t *offsets = ics->swb_offset;
1445 for (g = 0; g < ics->num_window_groups; g++) {
1446 for (i = 0; i < ics->max_sfb; i++, idx++) {
1447 if (cpe->ms_mask[idx] &&
1448 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1449 for (group = 0; group < ics->group_len[g]; group++) {
1450 ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1451 ch1 + group * 128 + offsets[i],
1452 offsets[i+1] - offsets[i]);
1456 ch0 += ics->group_len[g] * 128;
1457 ch1 += ics->group_len[g] * 128;
1462 * intensity stereo decoding; reference: 4.6.8.2.3
1464 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1465 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1466 * [3] reserved for scalable AAC
1468 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
1470 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1471 SingleChannelElement *sce1 = &cpe->ch[1];
1472 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1473 const uint16_t *offsets = ics->swb_offset;
1474 int g, group, i, idx = 0;
1477 for (g = 0; g < ics->num_window_groups; g++) {
1478 for (i = 0; i < ics->max_sfb;) {
1479 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1480 const int bt_run_end = sce1->band_type_run_end[idx];
1481 for (; i < bt_run_end; i++, idx++) {
1482 c = -1 + 2 * (sce1->band_type[idx] - 14);
1484 c *= 1 - 2 * cpe->ms_mask[idx];
1485 scale = c * sce1->sf[idx];
1486 for (group = 0; group < ics->group_len[g]; group++)
1487 ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1488 coef0 + group * 128 + offsets[i],
1490 offsets[i + 1] - offsets[i]);
1493 int bt_run_end = sce1->band_type_run_end[idx];
1494 idx += bt_run_end - i;
1498 coef0 += ics->group_len[g] * 128;
1499 coef1 += ics->group_len[g] * 128;
1504 * Decode a channel_pair_element; reference: table 4.4.
1506 * @return Returns error status. 0 - OK, !0 - error
1508 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1510 int i, ret, common_window, ms_present = 0;
1512 common_window = get_bits1(gb);
1513 if (common_window) {
1514 if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
1516 i = cpe->ch[1].ics.use_kb_window[0];
1517 cpe->ch[1].ics = cpe->ch[0].ics;
1518 cpe->ch[1].ics.use_kb_window[1] = i;
1519 if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
1520 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1521 decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1522 ms_present = get_bits(gb, 2);
1523 if (ms_present == 3) {
1524 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1526 } else if (ms_present)
1527 decode_mid_side_stereo(cpe, gb, ms_present);
1529 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1531 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1534 if (common_window) {
1536 apply_mid_side_stereo(ac, cpe);
1537 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1538 apply_prediction(ac, &cpe->ch[0]);
1539 apply_prediction(ac, &cpe->ch[1]);
1543 apply_intensity_stereo(ac, cpe, ms_present);
1547 static const float cce_scale[] = {
1548 1.09050773266525765921, //2^(1/8)
1549 1.18920711500272106672, //2^(1/4)
1555 * Decode coupling_channel_element; reference: table 4.8.
1557 * @return Returns error status. 0 - OK, !0 - error
1559 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1565 SingleChannelElement *sce = &che->ch[0];
1566 ChannelCoupling *coup = &che->coup;
1568 coup->coupling_point = 2 * get_bits1(gb);
1569 coup->num_coupled = get_bits(gb, 3);
1570 for (c = 0; c <= coup->num_coupled; c++) {
1572 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1573 coup->id_select[c] = get_bits(gb, 4);
1574 if (coup->type[c] == TYPE_CPE) {
1575 coup->ch_select[c] = get_bits(gb, 2);
1576 if (coup->ch_select[c] == 3)
1579 coup->ch_select[c] = 2;
1581 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1583 sign = get_bits(gb, 1);
1584 scale = cce_scale[get_bits(gb, 2)];
1586 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1589 for (c = 0; c < num_gain; c++) {
1593 float gain_cache = 1.;
1595 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1596 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1597 gain_cache = powf(scale, -gain);
1599 if (coup->coupling_point == AFTER_IMDCT) {
1600 coup->gain[c][0] = gain_cache;
1602 for (g = 0; g < sce->ics.num_window_groups; g++) {
1603 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1604 if (sce->band_type[idx] != ZERO_BT) {
1606 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1614 gain_cache = powf(scale, -t) * s;
1617 coup->gain[c][idx] = gain_cache;
1627 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1629 * @return Returns number of bytes consumed.
1631 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1635 int num_excl_chan = 0;
1638 for (i = 0; i < 7; i++)
1639 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1640 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1642 return num_excl_chan / 7;
1646 * Decode dynamic range information; reference: table 4.52.
1648 * @param cnt length of TYPE_FIL syntactic element in bytes
1650 * @return Returns number of bytes consumed.
1652 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1653 GetBitContext *gb, int cnt)
1656 int drc_num_bands = 1;
1659 /* pce_tag_present? */
1660 if (get_bits1(gb)) {
1661 che_drc->pce_instance_tag = get_bits(gb, 4);
1662 skip_bits(gb, 4); // tag_reserved_bits
1666 /* excluded_chns_present? */
1667 if (get_bits1(gb)) {
1668 n += decode_drc_channel_exclusions(che_drc, gb);
1671 /* drc_bands_present? */
1672 if (get_bits1(gb)) {
1673 che_drc->band_incr = get_bits(gb, 4);
1674 che_drc->interpolation_scheme = get_bits(gb, 4);
1676 drc_num_bands += che_drc->band_incr;
1677 for (i = 0; i < drc_num_bands; i++) {
1678 che_drc->band_top[i] = get_bits(gb, 8);
1683 /* prog_ref_level_present? */
1684 if (get_bits1(gb)) {
1685 che_drc->prog_ref_level = get_bits(gb, 7);
1686 skip_bits1(gb); // prog_ref_level_reserved_bits
1690 for (i = 0; i < drc_num_bands; i++) {
1691 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1692 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1700 * Decode extension data (incomplete); reference: table 4.51.
1702 * @param cnt length of TYPE_FIL syntactic element in bytes
1704 * @return Returns number of bytes consumed
1706 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1707 ChannelElement *che, enum RawDataBlockType elem_type)
1711 switch (get_bits(gb, 4)) { // extension type
1712 case EXT_SBR_DATA_CRC:
1716 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1718 } else if (!ac->m4ac.sbr) {
1719 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1720 skip_bits_long(gb, 8 * cnt - 4);
1722 } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1723 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1724 skip_bits_long(gb, 8 * cnt - 4);
1726 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1729 output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
1733 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1735 case EXT_DYNAMIC_RANGE:
1736 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1740 case EXT_DATA_ELEMENT:
1742 skip_bits_long(gb, 8 * cnt - 4);
1749 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1751 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1752 * @param coef spectral coefficients
1754 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1755 IndividualChannelStream *ics, int decode)
1757 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1759 int bottom, top, order, start, end, size, inc;
1760 float lpc[TNS_MAX_ORDER];
1761 float tmp[TNS_MAX_ORDER];
1763 for (w = 0; w < ics->num_windows; w++) {
1764 bottom = ics->num_swb;
1765 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1767 bottom = FFMAX(0, top - tns->length[w][filt]);
1768 order = tns->order[w][filt];
1773 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1775 start = ics->swb_offset[FFMIN(bottom, mmm)];
1776 end = ics->swb_offset[FFMIN( top, mmm)];
1777 if ((size = end - start) <= 0)
1779 if (tns->direction[w][filt]) {
1789 for (m = 0; m < size; m++, start += inc)
1790 for (i = 1; i <= FFMIN(m, order); i++)
1791 coef[start] -= coef[start - i * inc] * lpc[i - 1];
1794 for (m = 0; m < size; m++, start += inc) {
1795 tmp[0] = coef[start];
1796 for (i = 1; i <= FFMIN(m, order); i++)
1797 coef[start] += tmp[i] * lpc[i - 1];
1798 for (i = order; i > 0; i--)
1799 tmp[i] = tmp[i - 1];
1807 * Apply windowing and MDCT to obtain the spectral
1808 * coefficient from the predicted sample by LTP.
1810 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
1811 float *in, IndividualChannelStream *ics)
1813 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1814 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1815 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1816 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1818 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
1819 ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
1821 memset(in, 0, 448 * sizeof(float));
1822 ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
1824 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
1825 ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
1827 ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
1828 memset(in + 1024 + 576, 0, 448 * sizeof(float));
1830 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
1834 * Apply the long term prediction
1836 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
1838 const LongTermPrediction *ltp = &sce->ics.ltp;
1839 const uint16_t *offsets = sce->ics.swb_offset;
1842 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1843 float *predTime = sce->ret;
1844 float *predFreq = ac->buf_mdct;
1845 int16_t num_samples = 2048;
1847 if (ltp->lag < 1024)
1848 num_samples = ltp->lag + 1024;
1849 for (i = 0; i < num_samples; i++)
1850 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
1851 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
1853 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
1855 if (sce->tns.present)
1856 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
1858 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
1860 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
1861 sce->coeffs[i] += predFreq[i];
1866 * Update the LTP buffer for next frame
1868 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
1870 IndividualChannelStream *ics = &sce->ics;
1871 float *saved = sce->saved;
1872 float *saved_ltp = sce->coeffs;
1873 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1874 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1877 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1878 memcpy(saved_ltp, saved, 512 * sizeof(float));
1879 memset(saved_ltp + 576, 0, 448 * sizeof(float));
1880 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1881 for (i = 0; i < 64; i++)
1882 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
1883 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1884 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
1885 memset(saved_ltp + 576, 0, 448 * sizeof(float));
1886 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1887 for (i = 0; i < 64; i++)
1888 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
1889 } else { // LONG_STOP or ONLY_LONG
1890 ac->dsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
1891 for (i = 0; i < 512; i++)
1892 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
1895 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
1896 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
1897 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
1901 * Conduct IMDCT and windowing.
1903 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
1905 IndividualChannelStream *ics = &sce->ics;
1906 float *in = sce->coeffs;
1907 float *out = sce->ret;
1908 float *saved = sce->saved;
1909 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1910 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1911 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1912 float *buf = ac->buf_mdct;
1913 float *temp = ac->temp;
1917 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1918 for (i = 0; i < 1024; i += 128)
1919 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
1921 ac->mdct.imdct_half(&ac->mdct, buf, in);
1923 /* window overlapping
1924 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1925 * and long to short transitions are considered to be short to short
1926 * transitions. This leaves just two cases (long to long and short to short)
1927 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1929 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
1930 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
1931 ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
1933 memcpy( out, saved, 448 * sizeof(float));
1935 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1936 ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
1937 ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
1938 ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
1939 ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
1940 ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
1941 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
1943 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
1944 memcpy( out + 576, buf + 64, 448 * sizeof(float));
1949 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1950 memcpy( saved, temp + 64, 64 * sizeof(float));
1951 ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
1952 ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
1953 ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
1954 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1955 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1956 memcpy( saved, buf + 512, 448 * sizeof(float));
1957 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1958 } else { // LONG_STOP or ONLY_LONG
1959 memcpy( saved, buf + 512, 512 * sizeof(float));
1964 * Apply dependent channel coupling (applied before IMDCT).
1966 * @param index index into coupling gain array
1968 static void apply_dependent_coupling(AACContext *ac,
1969 SingleChannelElement *target,
1970 ChannelElement *cce, int index)
1972 IndividualChannelStream *ics = &cce->ch[0].ics;
1973 const uint16_t *offsets = ics->swb_offset;
1974 float *dest = target->coeffs;
1975 const float *src = cce->ch[0].coeffs;
1976 int g, i, group, k, idx = 0;
1977 if (ac->m4ac.object_type == AOT_AAC_LTP) {
1978 av_log(ac->avctx, AV_LOG_ERROR,
1979 "Dependent coupling is not supported together with LTP\n");
1982 for (g = 0; g < ics->num_window_groups; g++) {
1983 for (i = 0; i < ics->max_sfb; i++, idx++) {
1984 if (cce->ch[0].band_type[idx] != ZERO_BT) {
1985 const float gain = cce->coup.gain[index][idx];
1986 for (group = 0; group < ics->group_len[g]; group++) {
1987 for (k = offsets[i]; k < offsets[i + 1]; k++) {
1989 dest[group * 128 + k] += gain * src[group * 128 + k];
1994 dest += ics->group_len[g] * 128;
1995 src += ics->group_len[g] * 128;
2000 * Apply independent channel coupling (applied after IMDCT).
2002 * @param index index into coupling gain array
2004 static void apply_independent_coupling(AACContext *ac,
2005 SingleChannelElement *target,
2006 ChannelElement *cce, int index)
2009 const float gain = cce->coup.gain[index][0];
2010 const float *src = cce->ch[0].ret;
2011 float *dest = target->ret;
2012 const int len = 1024 << (ac->m4ac.sbr == 1);
2014 for (i = 0; i < len; i++)
2015 dest[i] += gain * src[i];
2019 * channel coupling transformation interface
2021 * @param apply_coupling_method pointer to (in)dependent coupling function
2023 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2024 enum RawDataBlockType type, int elem_id,
2025 enum CouplingPoint coupling_point,
2026 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2030 for (i = 0; i < MAX_ELEM_ID; i++) {
2031 ChannelElement *cce = ac->che[TYPE_CCE][i];
2034 if (cce && cce->coup.coupling_point == coupling_point) {
2035 ChannelCoupling *coup = &cce->coup;
2037 for (c = 0; c <= coup->num_coupled; c++) {
2038 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2039 if (coup->ch_select[c] != 1) {
2040 apply_coupling_method(ac, &cc->ch[0], cce, index);
2041 if (coup->ch_select[c] != 0)
2044 if (coup->ch_select[c] != 2)
2045 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2047 index += 1 + (coup->ch_select[c] == 3);
2054 * Convert spectral data to float samples, applying all supported tools as appropriate.
2056 static void spectral_to_sample(AACContext *ac)
2059 for (type = 3; type >= 0; type--) {
2060 for (i = 0; i < MAX_ELEM_ID; i++) {
2061 ChannelElement *che = ac->che[type][i];
2063 if (type <= TYPE_CPE)
2064 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2065 if (ac->m4ac.object_type == AOT_AAC_LTP) {
2066 if (che->ch[0].ics.predictor_present) {
2067 if (che->ch[0].ics.ltp.present)
2068 apply_ltp(ac, &che->ch[0]);
2069 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2070 apply_ltp(ac, &che->ch[1]);
2073 if (che->ch[0].tns.present)
2074 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2075 if (che->ch[1].tns.present)
2076 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2077 if (type <= TYPE_CPE)
2078 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2079 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2080 imdct_and_windowing(ac, &che->ch[0]);
2081 if (ac->m4ac.object_type == AOT_AAC_LTP)
2082 update_ltp(ac, &che->ch[0]);
2083 if (type == TYPE_CPE) {
2084 imdct_and_windowing(ac, &che->ch[1]);
2085 if (ac->m4ac.object_type == AOT_AAC_LTP)
2086 update_ltp(ac, &che->ch[1]);
2088 if (ac->m4ac.sbr > 0) {
2089 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2092 if (type <= TYPE_CCE)
2093 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2099 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2102 AACADTSHeaderInfo hdr_info;
2104 size = avpriv_aac_parse_header(gb, &hdr_info);
2106 if (hdr_info.chan_config && (hdr_info.chan_config!=ac->m4ac.chan_config || ac->m4ac.sample_rate!=hdr_info.sample_rate)) {
2107 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2108 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2109 ac->m4ac.chan_config = hdr_info.chan_config;
2110 if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
2112 if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config,
2113 FFMAX(ac->output_configured, OC_TRIAL_FRAME)))
2115 } else if (ac->output_configured != OC_LOCKED) {
2116 ac->m4ac.chan_config = 0;
2117 ac->output_configured = OC_NONE;
2119 if (ac->output_configured != OC_LOCKED) {
2122 ac->m4ac.sample_rate = hdr_info.sample_rate;
2123 ac->m4ac.sampling_index = hdr_info.sampling_index;
2124 ac->m4ac.object_type = hdr_info.object_type;
2126 if (!ac->avctx->sample_rate)
2127 ac->avctx->sample_rate = hdr_info.sample_rate;
2128 if (hdr_info.num_aac_frames == 1) {
2129 if (!hdr_info.crc_absent)
2132 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
2139 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2140 int *got_frame_ptr, GetBitContext *gb)
2142 AACContext *ac = avctx->priv_data;
2143 ChannelElement *che = NULL, *che_prev = NULL;
2144 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2146 int samples = 0, multiplier, audio_found = 0;
2148 if (show_bits(gb, 12) == 0xfff) {
2149 if (parse_adts_frame_header(ac, gb) < 0) {
2150 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2153 if (ac->m4ac.sampling_index > 12) {
2154 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
2159 ac->tags_mapped = 0;
2161 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2162 elem_id = get_bits(gb, 4);
2164 if (elem_type < TYPE_DSE) {
2165 if (!ac->tags_mapped && elem_type == TYPE_CPE && ac->m4ac.chan_config==1) {
2166 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID]= {0};
2167 ac->m4ac.chan_config=2;
2169 if (set_default_channel_config(ac->avctx, new_che_pos, 2)<0)
2171 if (output_configure(ac, ac->che_pos, new_che_pos, 2, OC_TRIAL_FRAME)<0)
2174 if (!(che=get_che(ac, elem_type, elem_id))) {
2175 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2176 elem_type, elem_id);
2182 switch (elem_type) {
2185 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2190 err = decode_cpe(ac, gb, che);
2195 err = decode_cce(ac, gb, che);
2199 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2204 err = skip_data_stream_element(ac, gb);
2208 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2209 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2210 if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
2212 if (ac->output_configured > OC_TRIAL_PCE)
2213 av_log(avctx, AV_LOG_ERROR,
2214 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2216 err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
2222 elem_id += get_bits(gb, 8) - 1;
2223 if (get_bits_left(gb) < 8 * elem_id) {
2224 av_log(avctx, AV_LOG_ERROR, overread_err);
2228 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2229 err = 0; /* FIXME */
2233 err = -1; /* should not happen, but keeps compiler happy */
2238 elem_type_prev = elem_type;
2243 if (get_bits_left(gb) < 3) {
2244 av_log(avctx, AV_LOG_ERROR, overread_err);
2249 spectral_to_sample(ac);
2251 multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2252 samples <<= multiplier;
2253 if (ac->output_configured < OC_LOCKED) {
2254 avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2255 avctx->frame_size = samples;
2259 /* get output buffer */
2260 ac->frame.nb_samples = samples;
2261 if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
2262 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2266 if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
2267 ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
2268 (const float **)ac->output_data,
2269 samples, avctx->channels);
2271 ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2272 (const float **)ac->output_data,
2273 samples, avctx->channels);
2275 *(AVFrame *)data = ac->frame;
2277 *got_frame_ptr = !!samples;
2279 if (ac->output_configured && audio_found)
2280 ac->output_configured = OC_LOCKED;
2285 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2286 int *got_frame_ptr, AVPacket *avpkt)
2288 const uint8_t *buf = avpkt->data;
2289 int buf_size = avpkt->size;
2295 init_get_bits(&gb, buf, buf_size * 8);
2297 if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
2300 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2301 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2302 if (buf[buf_offset])
2305 return buf_size > buf_offset ? buf_consumed : buf_size;
2308 static av_cold int aac_decode_close(AVCodecContext *avctx)
2310 AACContext *ac = avctx->priv_data;
2313 for (i = 0; i < MAX_ELEM_ID; i++) {
2314 for (type = 0; type < 4; type++) {
2315 if (ac->che[type][i])
2316 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2317 av_freep(&ac->che[type][i]);
2321 ff_mdct_end(&ac->mdct);
2322 ff_mdct_end(&ac->mdct_small);
2323 ff_mdct_end(&ac->mdct_ltp);
2328 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2330 struct LATMContext {
2331 AACContext aac_ctx; ///< containing AACContext
2332 int initialized; ///< initilized after a valid extradata was seen
2335 int audio_mux_version_A; ///< LATM syntax version
2336 int frame_length_type; ///< 0/1 variable/fixed frame length
2337 int frame_length; ///< frame length for fixed frame length
2340 static inline uint32_t latm_get_value(GetBitContext *b)
2342 int length = get_bits(b, 2);
2344 return get_bits_long(b, (length+1)*8);
2347 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2348 GetBitContext *gb, int asclen)
2350 AACContext *ac = &latmctx->aac_ctx;
2351 AVCodecContext *avctx = ac->avctx;
2352 MPEG4AudioConfig m4ac = {0};
2353 int config_start_bit = get_bits_count(gb);
2354 int sync_extension = 0;
2355 int bits_consumed, esize;
2359 asclen = FFMIN(asclen, get_bits_left(gb));
2361 asclen = get_bits_left(gb);
2363 if (config_start_bit % 8) {
2364 av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2365 "config not byte aligned.\n", 1);
2366 return AVERROR_INVALIDDATA;
2368 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2369 gb->buffer + (config_start_bit / 8),
2370 asclen, sync_extension);
2372 if (bits_consumed < 0)
2373 return AVERROR_INVALIDDATA;
2375 if (ac->m4ac.sample_rate != m4ac.sample_rate ||
2376 ac->m4ac.chan_config != m4ac.chan_config) {
2378 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2379 latmctx->initialized = 0;
2381 esize = (bits_consumed+7) / 8;
2383 if (avctx->extradata_size < esize) {
2384 av_free(avctx->extradata);
2385 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2386 if (!avctx->extradata)
2387 return AVERROR(ENOMEM);
2390 avctx->extradata_size = esize;
2391 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2392 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2394 skip_bits_long(gb, bits_consumed);
2396 return bits_consumed;
2399 static int read_stream_mux_config(struct LATMContext *latmctx,
2402 int ret, audio_mux_version = get_bits(gb, 1);
2404 latmctx->audio_mux_version_A = 0;
2405 if (audio_mux_version)
2406 latmctx->audio_mux_version_A = get_bits(gb, 1);
2408 if (!latmctx->audio_mux_version_A) {
2410 if (audio_mux_version)
2411 latm_get_value(gb); // taraFullness
2413 skip_bits(gb, 1); // allStreamSameTimeFraming
2414 skip_bits(gb, 6); // numSubFrames
2416 if (get_bits(gb, 4)) { // numPrograms
2417 av_log_missing_feature(latmctx->aac_ctx.avctx,
2418 "multiple programs are not supported\n", 1);
2419 return AVERROR_PATCHWELCOME;
2422 // for each program (which there is only on in DVB)
2424 // for each layer (which there is only on in DVB)
2425 if (get_bits(gb, 3)) { // numLayer
2426 av_log_missing_feature(latmctx->aac_ctx.avctx,
2427 "multiple layers are not supported\n", 1);
2428 return AVERROR_PATCHWELCOME;
2431 // for all but first stream: use_same_config = get_bits(gb, 1);
2432 if (!audio_mux_version) {
2433 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2436 int ascLen = latm_get_value(gb);
2437 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2440 skip_bits_long(gb, ascLen);
2443 latmctx->frame_length_type = get_bits(gb, 3);
2444 switch (latmctx->frame_length_type) {
2446 skip_bits(gb, 8); // latmBufferFullness
2449 latmctx->frame_length = get_bits(gb, 9);
2454 skip_bits(gb, 6); // CELP frame length table index
2458 skip_bits(gb, 1); // HVXC frame length table index
2462 if (get_bits(gb, 1)) { // other data
2463 if (audio_mux_version) {
2464 latm_get_value(gb); // other_data_bits
2468 esc = get_bits(gb, 1);
2474 if (get_bits(gb, 1)) // crc present
2475 skip_bits(gb, 8); // config_crc
2481 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2485 if (ctx->frame_length_type == 0) {
2486 int mux_slot_length = 0;
2488 tmp = get_bits(gb, 8);
2489 mux_slot_length += tmp;
2490 } while (tmp == 255);
2491 return mux_slot_length;
2492 } else if (ctx->frame_length_type == 1) {
2493 return ctx->frame_length;
2494 } else if (ctx->frame_length_type == 3 ||
2495 ctx->frame_length_type == 5 ||
2496 ctx->frame_length_type == 7) {
2497 skip_bits(gb, 2); // mux_slot_length_coded
2502 static int read_audio_mux_element(struct LATMContext *latmctx,
2506 uint8_t use_same_mux = get_bits(gb, 1);
2507 if (!use_same_mux) {
2508 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2510 } else if (!latmctx->aac_ctx.avctx->extradata) {
2511 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2512 "no decoder config found\n");
2513 return AVERROR(EAGAIN);
2515 if (latmctx->audio_mux_version_A == 0) {
2516 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2517 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2518 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2519 return AVERROR_INVALIDDATA;
2520 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2521 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2522 "frame length mismatch %d << %d\n",
2523 mux_slot_length_bytes * 8, get_bits_left(gb));
2524 return AVERROR_INVALIDDATA;
2531 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2532 int *got_frame_ptr, AVPacket *avpkt)
2534 struct LATMContext *latmctx = avctx->priv_data;
2538 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2540 // check for LOAS sync word
2541 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2542 return AVERROR_INVALIDDATA;
2544 muxlength = get_bits(&gb, 13) + 3;
2545 // not enough data, the parser should have sorted this
2546 if (muxlength > avpkt->size)
2547 return AVERROR_INVALIDDATA;
2549 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2552 if (!latmctx->initialized) {
2553 if (!avctx->extradata) {
2557 if ((err = decode_audio_specific_config(
2558 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.m4ac,
2559 avctx->extradata, avctx->extradata_size*8, 1)) < 0)
2561 latmctx->initialized = 1;
2565 if (show_bits(&gb, 12) == 0xfff) {
2566 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2567 "ADTS header detected, probably as result of configuration "
2569 return AVERROR_INVALIDDATA;
2572 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2578 av_cold static int latm_decode_init(AVCodecContext *avctx)
2580 struct LATMContext *latmctx = avctx->priv_data;
2581 int ret = aac_decode_init(avctx);
2583 if (avctx->extradata_size > 0)
2584 latmctx->initialized = !ret;
2590 AVCodec ff_aac_decoder = {
2592 .type = AVMEDIA_TYPE_AUDIO,
2594 .priv_data_size = sizeof(AACContext),
2595 .init = aac_decode_init,
2596 .close = aac_decode_close,
2597 .decode = aac_decode_frame,
2598 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2599 .sample_fmts = (const enum AVSampleFormat[]) {
2600 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2602 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2603 .channel_layouts = aac_channel_layout,
2607 Note: This decoder filter is intended to decode LATM streams transferred
2608 in MPEG transport streams which only contain one program.
2609 To do a more complex LATM demuxing a separate LATM demuxer should be used.
2611 AVCodec ff_aac_latm_decoder = {
2613 .type = AVMEDIA_TYPE_AUDIO,
2614 .id = CODEC_ID_AAC_LATM,
2615 .priv_data_size = sizeof(struct LATMContext),
2616 .init = latm_decode_init,
2617 .close = aac_decode_close,
2618 .decode = latm_decode_frame,
2619 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2620 .sample_fmts = (const enum AVSampleFormat[]) {
2621 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2623 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2624 .channel_layouts = aac_channel_layout,