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"
101 #include "libavutil/intfloat.h"
109 # include "arm/aac.h"
112 static VLC vlc_scalefactors;
113 static VLC vlc_spectral[11];
115 static const char overread_err[] = "Input buffer exhausted before END element found\n";
117 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
119 // For PCE based channel configurations map the channels solely based on tags.
120 if (!ac->m4ac.chan_config) {
121 return ac->tag_che_map[type][elem_id];
123 // For indexed channel configurations map the channels solely based on position.
124 switch (ac->m4ac.chan_config) {
126 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
128 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
131 /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
132 instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
133 encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
134 if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
136 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
139 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
141 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
144 if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
146 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
150 if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
152 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
153 } else if (ac->m4ac.chan_config == 2) {
157 if (!ac->tags_mapped && type == TYPE_SCE) {
159 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
167 * Check for the channel element in the current channel position configuration.
168 * If it exists, make sure the appropriate element is allocated and map the
169 * channel order to match the internal FFmpeg channel layout.
171 * @param che_pos current channel position configuration
172 * @param type channel element type
173 * @param id channel element id
174 * @param channels count of the number of channels in the configuration
176 * @return Returns error status. 0 - OK, !0 - error
178 static av_cold int che_configure(AACContext *ac,
179 enum ChannelPosition che_pos[4][MAX_ELEM_ID],
180 int type, int id, int *channels)
182 if (che_pos[type][id]) {
183 if (!ac->che[type][id]) {
184 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
185 return AVERROR(ENOMEM);
186 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
188 if (type != TYPE_CCE) {
189 ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
190 if (type == TYPE_CPE ||
191 (type == TYPE_SCE && ac->m4ac.ps == 1)) {
192 ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
196 if (ac->che[type][id])
197 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
198 av_freep(&ac->che[type][id]);
204 * Configure output channel order based on the current program configuration element.
206 * @param che_pos current channel position configuration
207 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
209 * @return Returns error status. 0 - OK, !0 - error
211 static av_cold int output_configure(AACContext *ac,
212 enum ChannelPosition che_pos[4][MAX_ELEM_ID],
213 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
214 int channel_config, enum OCStatus oc_type)
216 AVCodecContext *avctx = ac->avctx;
217 int i, type, channels = 0, ret;
219 if (new_che_pos != che_pos)
220 memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
222 if (channel_config) {
223 for (i = 0; i < tags_per_config[channel_config]; i++) {
224 if ((ret = che_configure(ac, che_pos,
225 aac_channel_layout_map[channel_config - 1][i][0],
226 aac_channel_layout_map[channel_config - 1][i][1],
231 memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
233 avctx->channel_layout = aac_channel_layout[channel_config - 1];
235 /* Allocate or free elements depending on if they are in the
236 * current program configuration.
238 * Set up default 1:1 output mapping.
240 * For a 5.1 stream the output order will be:
241 * [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
244 for (i = 0; i < MAX_ELEM_ID; i++) {
245 for (type = 0; type < 4; type++) {
246 if ((ret = che_configure(ac, che_pos, type, i, &channels)))
251 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
254 avctx->channels = channels;
256 ac->output_configured = oc_type;
261 static void flush(AVCodecContext *avctx)
263 AACContext *ac= avctx->priv_data;
266 for (type = 3; type >= 0; type--) {
267 for (i = 0; i < MAX_ELEM_ID; i++) {
268 ChannelElement *che = ac->che[type][i];
270 for (j = 0; j <= 1; j++) {
271 memset(che->ch[j].saved, 0, sizeof(che->ch[j].saved));
279 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
281 * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
282 * @param sce_map mono (Single Channel Element) map
283 * @param type speaker type/position for these channels
285 static void decode_channel_map(enum ChannelPosition *cpe_map,
286 enum ChannelPosition *sce_map,
287 enum ChannelPosition type,
288 GetBitContext *gb, int n)
291 enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
292 map[get_bits(gb, 4)] = type;
297 * Decode program configuration element; reference: table 4.2.
299 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
301 * @return Returns error status. 0 - OK, !0 - error
303 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
304 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
307 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
310 skip_bits(gb, 2); // object_type
312 sampling_index = get_bits(gb, 4);
313 if (m4ac->sampling_index != sampling_index)
314 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");
316 num_front = get_bits(gb, 4);
317 num_side = get_bits(gb, 4);
318 num_back = get_bits(gb, 4);
319 num_lfe = get_bits(gb, 2);
320 num_assoc_data = get_bits(gb, 3);
321 num_cc = get_bits(gb, 4);
324 skip_bits(gb, 4); // mono_mixdown_tag
326 skip_bits(gb, 4); // stereo_mixdown_tag
329 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
331 if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) {
332 av_log(avctx, AV_LOG_ERROR, overread_err);
335 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
336 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
337 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
338 decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
340 skip_bits_long(gb, 4 * num_assoc_data);
342 decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
346 /* comment field, first byte is length */
347 comment_len = get_bits(gb, 8) * 8;
348 if (get_bits_left(gb) < comment_len) {
349 av_log(avctx, AV_LOG_ERROR, overread_err);
352 skip_bits_long(gb, comment_len);
357 * Set up channel positions based on a default channel configuration
358 * as specified in table 1.17.
360 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
362 * @return Returns error status. 0 - OK, !0 - error
364 static av_cold int set_default_channel_config(AVCodecContext *avctx,
365 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
368 if (channel_config < 1 || channel_config > 7) {
369 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
374 /* default channel configurations:
376 * 1ch : front center (mono)
377 * 2ch : L + R (stereo)
378 * 3ch : front center + L + R
379 * 4ch : front center + L + R + back center
380 * 5ch : front center + L + R + back stereo
381 * 6ch : front center + L + R + back stereo + LFE
382 * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
385 if (channel_config != 2)
386 new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
387 if (channel_config > 1)
388 new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
389 if (channel_config == 4)
390 new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
391 if (channel_config > 4)
392 new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
393 = AAC_CHANNEL_BACK; // back stereo
394 if (channel_config > 5)
395 new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
396 if (channel_config == 7)
397 new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
403 * Decode GA "General Audio" specific configuration; reference: table 4.1.
405 * @param ac pointer to AACContext, may be null
406 * @param avctx pointer to AVCCodecContext, used for logging
408 * @return Returns error status. 0 - OK, !0 - error
410 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
412 MPEG4AudioConfig *m4ac,
415 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
416 int extension_flag, ret;
418 if (get_bits1(gb)) { // frameLengthFlag
419 av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
423 if (get_bits1(gb)) // dependsOnCoreCoder
424 skip_bits(gb, 14); // coreCoderDelay
425 extension_flag = get_bits1(gb);
427 if (m4ac->object_type == AOT_AAC_SCALABLE ||
428 m4ac->object_type == AOT_ER_AAC_SCALABLE)
429 skip_bits(gb, 3); // layerNr
431 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
432 if (channel_config == 0) {
433 skip_bits(gb, 4); // element_instance_tag
434 if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
437 if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
440 if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
443 if (extension_flag) {
444 switch (m4ac->object_type) {
446 skip_bits(gb, 5); // numOfSubFrame
447 skip_bits(gb, 11); // layer_length
451 case AOT_ER_AAC_SCALABLE:
453 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
454 * aacScalefactorDataResilienceFlag
455 * aacSpectralDataResilienceFlag
459 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
465 * Decode audio specific configuration; reference: table 1.13.
467 * @param ac pointer to AACContext, may be null
468 * @param avctx pointer to AVCCodecContext, used for logging
469 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
470 * @param data pointer to buffer holding an audio specific config
471 * @param bit_size size of audio specific config or data in bits
472 * @param sync_extension look for an appended sync extension
474 * @return Returns error status or number of consumed bits. <0 - error
476 static int decode_audio_specific_config(AACContext *ac,
477 AVCodecContext *avctx,
478 MPEG4AudioConfig *m4ac,
479 const uint8_t *data, int bit_size,
485 av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
486 for (i = 0; i < avctx->extradata_size; i++)
487 av_dlog(avctx, "%02x ", avctx->extradata[i]);
488 av_dlog(avctx, "\n");
490 init_get_bits(&gb, data, bit_size);
492 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
494 if (m4ac->sampling_index > 12) {
495 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
498 if (m4ac->sbr == 1 && m4ac->ps == -1)
501 skip_bits_long(&gb, i);
503 switch (m4ac->object_type) {
507 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
511 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
512 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
516 av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
517 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
518 m4ac->sample_rate, m4ac->sbr, m4ac->ps);
520 return get_bits_count(&gb);
524 * linear congruential pseudorandom number generator
526 * @param previous_val pointer to the current state of the generator
528 * @return Returns a 32-bit pseudorandom integer
530 static av_always_inline int lcg_random(int previous_val)
532 return previous_val * 1664525 + 1013904223;
535 static av_always_inline void reset_predict_state(PredictorState *ps)
545 static void reset_all_predictors(PredictorState *ps)
548 for (i = 0; i < MAX_PREDICTORS; i++)
549 reset_predict_state(&ps[i]);
552 static int sample_rate_idx (int rate)
554 if (92017 <= rate) return 0;
555 else if (75132 <= rate) return 1;
556 else if (55426 <= rate) return 2;
557 else if (46009 <= rate) return 3;
558 else if (37566 <= rate) return 4;
559 else if (27713 <= rate) return 5;
560 else if (23004 <= rate) return 6;
561 else if (18783 <= rate) return 7;
562 else if (13856 <= rate) return 8;
563 else if (11502 <= rate) return 9;
564 else if (9391 <= rate) return 10;
568 static void reset_predictor_group(PredictorState *ps, int group_num)
571 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
572 reset_predict_state(&ps[i]);
575 #define AAC_INIT_VLC_STATIC(num, size) \
576 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
577 ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
578 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
581 static av_cold int aac_decode_init(AVCodecContext *avctx)
583 AACContext *ac = avctx->priv_data;
584 float output_scale_factor;
587 ac->m4ac.sample_rate = avctx->sample_rate;
589 if (avctx->extradata_size > 0) {
590 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
592 avctx->extradata_size*8, 1) < 0)
596 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
598 sr = sample_rate_idx(avctx->sample_rate);
599 ac->m4ac.sampling_index = sr;
600 ac->m4ac.channels = avctx->channels;
604 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
605 if (ff_mpeg4audio_channels[i] == avctx->channels)
607 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
610 ac->m4ac.chan_config = i;
612 if (ac->m4ac.chan_config) {
613 int ret = set_default_channel_config(avctx, new_che_pos, ac->m4ac.chan_config);
615 output_configure(ac, ac->che_pos, new_che_pos, ac->m4ac.chan_config, OC_GLOBAL_HDR);
616 else if (avctx->err_recognition & AV_EF_EXPLODE)
617 return AVERROR_INVALIDDATA;
621 if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
622 avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
623 output_scale_factor = 1.0 / 32768.0;
625 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
626 output_scale_factor = 1.0;
629 AAC_INIT_VLC_STATIC( 0, 304);
630 AAC_INIT_VLC_STATIC( 1, 270);
631 AAC_INIT_VLC_STATIC( 2, 550);
632 AAC_INIT_VLC_STATIC( 3, 300);
633 AAC_INIT_VLC_STATIC( 4, 328);
634 AAC_INIT_VLC_STATIC( 5, 294);
635 AAC_INIT_VLC_STATIC( 6, 306);
636 AAC_INIT_VLC_STATIC( 7, 268);
637 AAC_INIT_VLC_STATIC( 8, 510);
638 AAC_INIT_VLC_STATIC( 9, 366);
639 AAC_INIT_VLC_STATIC(10, 462);
643 dsputil_init(&ac->dsp, avctx);
644 ff_fmt_convert_init(&ac->fmt_conv, avctx);
646 ac->random_state = 0x1f2e3d4c;
650 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
651 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
652 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
655 ff_mdct_init(&ac->mdct, 11, 1, output_scale_factor/1024.0);
656 ff_mdct_init(&ac->mdct_small, 8, 1, output_scale_factor/128.0);
657 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0/output_scale_factor);
658 // window initialization
659 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
660 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
661 ff_init_ff_sine_windows(10);
662 ff_init_ff_sine_windows( 7);
666 avcodec_get_frame_defaults(&ac->frame);
667 avctx->coded_frame = &ac->frame;
673 * Skip data_stream_element; reference: table 4.10.
675 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
677 int byte_align = get_bits1(gb);
678 int count = get_bits(gb, 8);
680 count += get_bits(gb, 8);
684 if (get_bits_left(gb) < 8 * count) {
685 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
688 skip_bits_long(gb, 8 * count);
692 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
697 ics->predictor_reset_group = get_bits(gb, 5);
698 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
699 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
703 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
704 ics->prediction_used[sfb] = get_bits1(gb);
710 * Decode Long Term Prediction data; reference: table 4.xx.
712 static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
713 GetBitContext *gb, uint8_t max_sfb)
717 ltp->lag = get_bits(gb, 11);
718 ltp->coef = ltp_coef[get_bits(gb, 3)];
719 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
720 ltp->used[sfb] = get_bits1(gb);
724 * Decode Individual Channel Stream info; reference: table 4.6.
726 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
728 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
729 GetBitContext *gb, int common_window)
732 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
733 memset(ics, 0, sizeof(IndividualChannelStream));
736 ics->window_sequence[1] = ics->window_sequence[0];
737 ics->window_sequence[0] = get_bits(gb, 2);
738 ics->use_kb_window[1] = ics->use_kb_window[0];
739 ics->use_kb_window[0] = get_bits1(gb);
740 ics->num_window_groups = 1;
741 ics->group_len[0] = 1;
742 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
744 ics->max_sfb = get_bits(gb, 4);
745 for (i = 0; i < 7; i++) {
747 ics->group_len[ics->num_window_groups - 1]++;
749 ics->num_window_groups++;
750 ics->group_len[ics->num_window_groups - 1] = 1;
753 ics->num_windows = 8;
754 ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
755 ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
756 ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
757 ics->predictor_present = 0;
759 ics->max_sfb = get_bits(gb, 6);
760 ics->num_windows = 1;
761 ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
762 ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
763 ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
764 ics->predictor_present = get_bits1(gb);
765 ics->predictor_reset_group = 0;
766 if (ics->predictor_present) {
767 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
768 if (decode_prediction(ac, ics, gb)) {
769 memset(ics, 0, sizeof(IndividualChannelStream));
772 } else if (ac->m4ac.object_type == AOT_AAC_LC) {
773 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
774 memset(ics, 0, sizeof(IndividualChannelStream));
777 if ((ics->ltp.present = get_bits(gb, 1)))
778 decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
783 if (ics->max_sfb > ics->num_swb) {
784 av_log(ac->avctx, AV_LOG_ERROR,
785 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
786 ics->max_sfb, ics->num_swb);
787 memset(ics, 0, sizeof(IndividualChannelStream));
795 * Decode band types (section_data payload); reference: table 4.46.
797 * @param band_type array of the used band type
798 * @param band_type_run_end array of the last scalefactor band of a band type run
800 * @return Returns error status. 0 - OK, !0 - error
802 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
803 int band_type_run_end[120], GetBitContext *gb,
804 IndividualChannelStream *ics)
807 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
808 for (g = 0; g < ics->num_window_groups; g++) {
810 while (k < ics->max_sfb) {
811 uint8_t sect_end = k;
813 int sect_band_type = get_bits(gb, 4);
814 if (sect_band_type == 12) {
815 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
818 while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
819 sect_end += sect_len_incr;
820 sect_end += sect_len_incr;
821 if (get_bits_left(gb) < 0) {
822 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
825 if (sect_end > ics->max_sfb) {
826 av_log(ac->avctx, AV_LOG_ERROR,
827 "Number of bands (%d) exceeds limit (%d).\n",
828 sect_end, ics->max_sfb);
831 for (; k < sect_end; k++) {
832 band_type [idx] = sect_band_type;
833 band_type_run_end[idx++] = sect_end;
841 * Decode scalefactors; reference: table 4.47.
843 * @param global_gain first scalefactor value as scalefactors are differentially coded
844 * @param band_type array of the used band type
845 * @param band_type_run_end array of the last scalefactor band of a band type run
846 * @param sf array of scalefactors or intensity stereo positions
848 * @return Returns error status. 0 - OK, !0 - error
850 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
851 unsigned int global_gain,
852 IndividualChannelStream *ics,
853 enum BandType band_type[120],
854 int band_type_run_end[120])
857 int offset[3] = { global_gain, global_gain - 90, 0 };
860 static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
861 for (g = 0; g < ics->num_window_groups; g++) {
862 for (i = 0; i < ics->max_sfb;) {
863 int run_end = band_type_run_end[idx];
864 if (band_type[idx] == ZERO_BT) {
865 for (; i < run_end; i++, idx++)
867 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
868 for (; i < run_end; i++, idx++) {
869 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
870 clipped_offset = av_clip(offset[2], -155, 100);
871 if (offset[2] != clipped_offset) {
872 av_log_ask_for_sample(ac->avctx, "Intensity stereo "
873 "position clipped (%d -> %d).\nIf you heard an "
874 "audible artifact, there may be a bug in the "
875 "decoder. ", offset[2], clipped_offset);
877 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
879 } else if (band_type[idx] == NOISE_BT) {
880 for (; i < run_end; i++, idx++) {
881 if (noise_flag-- > 0)
882 offset[1] += get_bits(gb, 9) - 256;
884 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
885 clipped_offset = av_clip(offset[1], -100, 155);
886 if (offset[1] != clipped_offset) {
887 av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
888 "(%d -> %d).\nIf you heard an audible "
889 "artifact, there may be a bug in the decoder. ",
890 offset[1], clipped_offset);
892 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
895 for (; i < run_end; i++, idx++) {
896 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
897 if (offset[0] > 255U) {
898 av_log(ac->avctx, AV_LOG_ERROR,
899 "%s (%d) out of range.\n", sf_str[0], offset[0]);
902 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
911 * Decode pulse data; reference: table 4.7.
913 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
914 const uint16_t *swb_offset, int num_swb)
917 pulse->num_pulse = get_bits(gb, 2) + 1;
918 pulse_swb = get_bits(gb, 6);
919 if (pulse_swb >= num_swb)
921 pulse->pos[0] = swb_offset[pulse_swb];
922 pulse->pos[0] += get_bits(gb, 5);
923 if (pulse->pos[0] > 1023)
925 pulse->amp[0] = get_bits(gb, 4);
926 for (i = 1; i < pulse->num_pulse; i++) {
927 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
928 if (pulse->pos[i] > 1023)
930 pulse->amp[i] = get_bits(gb, 4);
936 * Decode Temporal Noise Shaping data; reference: table 4.48.
938 * @return Returns error status. 0 - OK, !0 - error
940 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
941 GetBitContext *gb, const IndividualChannelStream *ics)
943 int w, filt, i, coef_len, coef_res, coef_compress;
944 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
945 const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
946 for (w = 0; w < ics->num_windows; w++) {
947 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
948 coef_res = get_bits1(gb);
950 for (filt = 0; filt < tns->n_filt[w]; filt++) {
952 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
954 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
955 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
956 tns->order[w][filt], tns_max_order);
957 tns->order[w][filt] = 0;
960 if (tns->order[w][filt]) {
961 tns->direction[w][filt] = get_bits1(gb);
962 coef_compress = get_bits1(gb);
963 coef_len = coef_res + 3 - coef_compress;
964 tmp2_idx = 2 * coef_compress + coef_res;
966 for (i = 0; i < tns->order[w][filt]; i++)
967 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
976 * Decode Mid/Side data; reference: table 4.54.
978 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
979 * [1] mask is decoded from bitstream; [2] mask is all 1s;
980 * [3] reserved for scalable AAC
982 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
986 if (ms_present == 1) {
987 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
988 cpe->ms_mask[idx] = get_bits1(gb);
989 } else if (ms_present == 2) {
990 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
995 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
999 *dst++ = v[idx & 15] * s;
1000 *dst++ = v[idx>>4 & 15] * s;
1006 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1010 *dst++ = v[idx & 3] * s;
1011 *dst++ = v[idx>>2 & 3] * s;
1012 *dst++ = v[idx>>4 & 3] * s;
1013 *dst++ = v[idx>>6 & 3] * s;
1019 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1020 unsigned sign, const float *scale)
1022 union av_intfloat32 s0, s1;
1024 s0.f = s1.f = *scale;
1025 s0.i ^= sign >> 1 << 31;
1028 *dst++ = v[idx & 15] * s0.f;
1029 *dst++ = v[idx>>4 & 15] * s1.f;
1036 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1037 unsigned sign, const float *scale)
1039 unsigned nz = idx >> 12;
1040 union av_intfloat32 s = { .f = *scale };
1041 union av_intfloat32 t;
1043 t.i = s.i ^ (sign & 1U<<31);
1044 *dst++ = v[idx & 3] * t.f;
1046 sign <<= nz & 1; nz >>= 1;
1047 t.i = s.i ^ (sign & 1U<<31);
1048 *dst++ = v[idx>>2 & 3] * t.f;
1050 sign <<= nz & 1; nz >>= 1;
1051 t.i = s.i ^ (sign & 1U<<31);
1052 *dst++ = v[idx>>4 & 3] * t.f;
1054 sign <<= nz & 1; nz >>= 1;
1055 t.i = s.i ^ (sign & 1U<<31);
1056 *dst++ = v[idx>>6 & 3] * t.f;
1063 * Decode spectral data; reference: table 4.50.
1064 * Dequantize and scale spectral data; reference: 4.6.3.3.
1066 * @param coef array of dequantized, scaled spectral data
1067 * @param sf array of scalefactors or intensity stereo positions
1068 * @param pulse_present set if pulses are present
1069 * @param pulse pointer to pulse data struct
1070 * @param band_type array of the used band type
1072 * @return Returns error status. 0 - OK, !0 - error
1074 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1075 GetBitContext *gb, const float sf[120],
1076 int pulse_present, const Pulse *pulse,
1077 const IndividualChannelStream *ics,
1078 enum BandType band_type[120])
1080 int i, k, g, idx = 0;
1081 const int c = 1024 / ics->num_windows;
1082 const uint16_t *offsets = ics->swb_offset;
1083 float *coef_base = coef;
1085 for (g = 0; g < ics->num_windows; g++)
1086 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1088 for (g = 0; g < ics->num_window_groups; g++) {
1089 unsigned g_len = ics->group_len[g];
1091 for (i = 0; i < ics->max_sfb; i++, idx++) {
1092 const unsigned cbt_m1 = band_type[idx] - 1;
1093 float *cfo = coef + offsets[i];
1094 int off_len = offsets[i + 1] - offsets[i];
1097 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1098 for (group = 0; group < g_len; group++, cfo+=128) {
1099 memset(cfo, 0, off_len * sizeof(float));
1101 } else if (cbt_m1 == NOISE_BT - 1) {
1102 for (group = 0; group < g_len; group++, cfo+=128) {
1106 for (k = 0; k < off_len; k++) {
1107 ac->random_state = lcg_random(ac->random_state);
1108 cfo[k] = ac->random_state;
1111 band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1112 scale = sf[idx] / sqrtf(band_energy);
1113 ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1116 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1117 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1118 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1119 OPEN_READER(re, gb);
1121 switch (cbt_m1 >> 1) {
1123 for (group = 0; group < g_len; group++, cfo+=128) {
1131 UPDATE_CACHE(re, gb);
1132 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1133 cb_idx = cb_vector_idx[code];
1134 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1140 for (group = 0; group < g_len; group++, cfo+=128) {
1150 UPDATE_CACHE(re, gb);
1151 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1152 cb_idx = cb_vector_idx[code];
1153 nnz = cb_idx >> 8 & 15;
1154 bits = nnz ? GET_CACHE(re, gb) : 0;
1155 LAST_SKIP_BITS(re, gb, nnz);
1156 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1162 for (group = 0; group < g_len; group++, cfo+=128) {
1170 UPDATE_CACHE(re, gb);
1171 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1172 cb_idx = cb_vector_idx[code];
1173 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1180 for (group = 0; group < g_len; group++, cfo+=128) {
1190 UPDATE_CACHE(re, gb);
1191 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1192 cb_idx = cb_vector_idx[code];
1193 nnz = cb_idx >> 8 & 15;
1194 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1195 LAST_SKIP_BITS(re, gb, nnz);
1196 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1202 for (group = 0; group < g_len; group++, cfo+=128) {
1204 uint32_t *icf = (uint32_t *) cf;
1214 UPDATE_CACHE(re, gb);
1215 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1223 cb_idx = cb_vector_idx[code];
1226 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1227 LAST_SKIP_BITS(re, gb, nnz);
1229 for (j = 0; j < 2; j++) {
1233 /* The total length of escape_sequence must be < 22 bits according
1234 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1235 UPDATE_CACHE(re, gb);
1236 b = GET_CACHE(re, gb);
1237 b = 31 - av_log2(~b);
1240 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1244 SKIP_BITS(re, gb, b + 1);
1246 n = (1 << b) + SHOW_UBITS(re, gb, b);
1247 LAST_SKIP_BITS(re, gb, b);
1248 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1251 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1252 *icf++ = (bits & 1U<<31) | v;
1259 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1263 CLOSE_READER(re, gb);
1269 if (pulse_present) {
1271 for (i = 0; i < pulse->num_pulse; i++) {
1272 float co = coef_base[ pulse->pos[i] ];
1273 while (offsets[idx + 1] <= pulse->pos[i])
1275 if (band_type[idx] != NOISE_BT && sf[idx]) {
1276 float ico = -pulse->amp[i];
1279 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1281 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1288 static av_always_inline float flt16_round(float pf)
1290 union av_intfloat32 tmp;
1292 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1296 static av_always_inline float flt16_even(float pf)
1298 union av_intfloat32 tmp;
1300 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1304 static av_always_inline float flt16_trunc(float pf)
1306 union av_intfloat32 pun;
1308 pun.i &= 0xFFFF0000U;
1312 static av_always_inline void predict(PredictorState *ps, float *coef,
1315 const float a = 0.953125; // 61.0 / 64
1316 const float alpha = 0.90625; // 29.0 / 32
1320 float r0 = ps->r0, r1 = ps->r1;
1321 float cor0 = ps->cor0, cor1 = ps->cor1;
1322 float var0 = ps->var0, var1 = ps->var1;
1324 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1325 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1327 pv = flt16_round(k1 * r0 + k2 * r1);
1334 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1335 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1336 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1337 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1339 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1340 ps->r0 = flt16_trunc(a * e0);
1344 * Apply AAC-Main style frequency domain prediction.
1346 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1350 if (!sce->ics.predictor_initialized) {
1351 reset_all_predictors(sce->predictor_state);
1352 sce->ics.predictor_initialized = 1;
1355 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1356 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1357 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1358 predict(&sce->predictor_state[k], &sce->coeffs[k],
1359 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1362 if (sce->ics.predictor_reset_group)
1363 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1365 reset_all_predictors(sce->predictor_state);
1369 * Decode an individual_channel_stream payload; reference: table 4.44.
1371 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1372 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1374 * @return Returns error status. 0 - OK, !0 - error
1376 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1377 GetBitContext *gb, int common_window, int scale_flag)
1380 TemporalNoiseShaping *tns = &sce->tns;
1381 IndividualChannelStream *ics = &sce->ics;
1382 float *out = sce->coeffs;
1383 int global_gain, pulse_present = 0;
1385 /* This assignment is to silence a GCC warning about the variable being used
1386 * uninitialized when in fact it always is.
1388 pulse.num_pulse = 0;
1390 global_gain = get_bits(gb, 8);
1392 if (!common_window && !scale_flag) {
1393 if (decode_ics_info(ac, ics, gb, 0) < 0)
1397 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1399 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1404 if ((pulse_present = get_bits1(gb))) {
1405 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1406 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1409 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1410 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1414 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1416 if (get_bits1(gb)) {
1417 av_log_missing_feature(ac->avctx, "SSR", 1);
1422 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1425 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1426 apply_prediction(ac, sce);
1432 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1434 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1436 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1437 float *ch0 = cpe->ch[0].coeffs;
1438 float *ch1 = cpe->ch[1].coeffs;
1439 int g, i, group, idx = 0;
1440 const uint16_t *offsets = ics->swb_offset;
1441 for (g = 0; g < ics->num_window_groups; g++) {
1442 for (i = 0; i < ics->max_sfb; i++, idx++) {
1443 if (cpe->ms_mask[idx] &&
1444 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1445 for (group = 0; group < ics->group_len[g]; group++) {
1446 ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1447 ch1 + group * 128 + offsets[i],
1448 offsets[i+1] - offsets[i]);
1452 ch0 += ics->group_len[g] * 128;
1453 ch1 += ics->group_len[g] * 128;
1458 * intensity stereo decoding; reference: 4.6.8.2.3
1460 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1461 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1462 * [3] reserved for scalable AAC
1464 static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
1466 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1467 SingleChannelElement *sce1 = &cpe->ch[1];
1468 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1469 const uint16_t *offsets = ics->swb_offset;
1470 int g, group, i, idx = 0;
1473 for (g = 0; g < ics->num_window_groups; g++) {
1474 for (i = 0; i < ics->max_sfb;) {
1475 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1476 const int bt_run_end = sce1->band_type_run_end[idx];
1477 for (; i < bt_run_end; i++, idx++) {
1478 c = -1 + 2 * (sce1->band_type[idx] - 14);
1480 c *= 1 - 2 * cpe->ms_mask[idx];
1481 scale = c * sce1->sf[idx];
1482 for (group = 0; group < ics->group_len[g]; group++)
1483 ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1484 coef0 + group * 128 + offsets[i],
1486 offsets[i + 1] - offsets[i]);
1489 int bt_run_end = sce1->band_type_run_end[idx];
1490 idx += bt_run_end - i;
1494 coef0 += ics->group_len[g] * 128;
1495 coef1 += ics->group_len[g] * 128;
1500 * Decode a channel_pair_element; reference: table 4.4.
1502 * @return Returns error status. 0 - OK, !0 - error
1504 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1506 int i, ret, common_window, ms_present = 0;
1508 common_window = get_bits1(gb);
1509 if (common_window) {
1510 if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
1512 i = cpe->ch[1].ics.use_kb_window[0];
1513 cpe->ch[1].ics = cpe->ch[0].ics;
1514 cpe->ch[1].ics.use_kb_window[1] = i;
1515 if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
1516 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1517 decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1518 ms_present = get_bits(gb, 2);
1519 if (ms_present == 3) {
1520 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1522 } else if (ms_present)
1523 decode_mid_side_stereo(cpe, gb, ms_present);
1525 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1527 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1530 if (common_window) {
1532 apply_mid_side_stereo(ac, cpe);
1533 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1534 apply_prediction(ac, &cpe->ch[0]);
1535 apply_prediction(ac, &cpe->ch[1]);
1539 apply_intensity_stereo(ac, cpe, ms_present);
1543 static const float cce_scale[] = {
1544 1.09050773266525765921, //2^(1/8)
1545 1.18920711500272106672, //2^(1/4)
1551 * Decode coupling_channel_element; reference: table 4.8.
1553 * @return Returns error status. 0 - OK, !0 - error
1555 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1561 SingleChannelElement *sce = &che->ch[0];
1562 ChannelCoupling *coup = &che->coup;
1564 coup->coupling_point = 2 * get_bits1(gb);
1565 coup->num_coupled = get_bits(gb, 3);
1566 for (c = 0; c <= coup->num_coupled; c++) {
1568 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1569 coup->id_select[c] = get_bits(gb, 4);
1570 if (coup->type[c] == TYPE_CPE) {
1571 coup->ch_select[c] = get_bits(gb, 2);
1572 if (coup->ch_select[c] == 3)
1575 coup->ch_select[c] = 2;
1577 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1579 sign = get_bits(gb, 1);
1580 scale = cce_scale[get_bits(gb, 2)];
1582 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1585 for (c = 0; c < num_gain; c++) {
1589 float gain_cache = 1.;
1591 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1592 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1593 gain_cache = powf(scale, -gain);
1595 if (coup->coupling_point == AFTER_IMDCT) {
1596 coup->gain[c][0] = gain_cache;
1598 for (g = 0; g < sce->ics.num_window_groups; g++) {
1599 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1600 if (sce->band_type[idx] != ZERO_BT) {
1602 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1610 gain_cache = powf(scale, -t) * s;
1613 coup->gain[c][idx] = gain_cache;
1623 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1625 * @return Returns number of bytes consumed.
1627 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1631 int num_excl_chan = 0;
1634 for (i = 0; i < 7; i++)
1635 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1636 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1638 return num_excl_chan / 7;
1642 * Decode dynamic range information; reference: table 4.52.
1644 * @param cnt length of TYPE_FIL syntactic element in bytes
1646 * @return Returns number of bytes consumed.
1648 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1649 GetBitContext *gb, int cnt)
1652 int drc_num_bands = 1;
1655 /* pce_tag_present? */
1656 if (get_bits1(gb)) {
1657 che_drc->pce_instance_tag = get_bits(gb, 4);
1658 skip_bits(gb, 4); // tag_reserved_bits
1662 /* excluded_chns_present? */
1663 if (get_bits1(gb)) {
1664 n += decode_drc_channel_exclusions(che_drc, gb);
1667 /* drc_bands_present? */
1668 if (get_bits1(gb)) {
1669 che_drc->band_incr = get_bits(gb, 4);
1670 che_drc->interpolation_scheme = get_bits(gb, 4);
1672 drc_num_bands += che_drc->band_incr;
1673 for (i = 0; i < drc_num_bands; i++) {
1674 che_drc->band_top[i] = get_bits(gb, 8);
1679 /* prog_ref_level_present? */
1680 if (get_bits1(gb)) {
1681 che_drc->prog_ref_level = get_bits(gb, 7);
1682 skip_bits1(gb); // prog_ref_level_reserved_bits
1686 for (i = 0; i < drc_num_bands; i++) {
1687 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1688 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1696 * Decode extension data (incomplete); reference: table 4.51.
1698 * @param cnt length of TYPE_FIL syntactic element in bytes
1700 * @return Returns number of bytes consumed
1702 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1703 ChannelElement *che, enum RawDataBlockType elem_type)
1707 switch (get_bits(gb, 4)) { // extension type
1708 case EXT_SBR_DATA_CRC:
1712 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1714 } else if (!ac->m4ac.sbr) {
1715 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1716 skip_bits_long(gb, 8 * cnt - 4);
1718 } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1719 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1720 skip_bits_long(gb, 8 * cnt - 4);
1722 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1725 output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
1729 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1731 case EXT_DYNAMIC_RANGE:
1732 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1736 case EXT_DATA_ELEMENT:
1738 skip_bits_long(gb, 8 * cnt - 4);
1745 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1747 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1748 * @param coef spectral coefficients
1750 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1751 IndividualChannelStream *ics, int decode)
1753 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1755 int bottom, top, order, start, end, size, inc;
1756 float lpc[TNS_MAX_ORDER];
1757 float tmp[TNS_MAX_ORDER];
1759 for (w = 0; w < ics->num_windows; w++) {
1760 bottom = ics->num_swb;
1761 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1763 bottom = FFMAX(0, top - tns->length[w][filt]);
1764 order = tns->order[w][filt];
1769 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1771 start = ics->swb_offset[FFMIN(bottom, mmm)];
1772 end = ics->swb_offset[FFMIN( top, mmm)];
1773 if ((size = end - start) <= 0)
1775 if (tns->direction[w][filt]) {
1785 for (m = 0; m < size; m++, start += inc)
1786 for (i = 1; i <= FFMIN(m, order); i++)
1787 coef[start] -= coef[start - i * inc] * lpc[i - 1];
1790 for (m = 0; m < size; m++, start += inc) {
1791 tmp[0] = coef[start];
1792 for (i = 1; i <= FFMIN(m, order); i++)
1793 coef[start] += tmp[i] * lpc[i - 1];
1794 for (i = order; i > 0; i--)
1795 tmp[i] = tmp[i - 1];
1803 * Apply windowing and MDCT to obtain the spectral
1804 * coefficient from the predicted sample by LTP.
1806 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
1807 float *in, IndividualChannelStream *ics)
1809 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1810 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1811 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1812 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1814 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
1815 ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
1817 memset(in, 0, 448 * sizeof(float));
1818 ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
1820 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
1821 ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
1823 ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
1824 memset(in + 1024 + 576, 0, 448 * sizeof(float));
1826 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
1830 * Apply the long term prediction
1832 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
1834 const LongTermPrediction *ltp = &sce->ics.ltp;
1835 const uint16_t *offsets = sce->ics.swb_offset;
1838 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1839 float *predTime = sce->ret;
1840 float *predFreq = ac->buf_mdct;
1841 int16_t num_samples = 2048;
1843 if (ltp->lag < 1024)
1844 num_samples = ltp->lag + 1024;
1845 for (i = 0; i < num_samples; i++)
1846 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
1847 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
1849 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
1851 if (sce->tns.present)
1852 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
1854 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
1856 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
1857 sce->coeffs[i] += predFreq[i];
1862 * Update the LTP buffer for next frame
1864 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
1866 IndividualChannelStream *ics = &sce->ics;
1867 float *saved = sce->saved;
1868 float *saved_ltp = sce->coeffs;
1869 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1870 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1873 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1874 memcpy(saved_ltp, saved, 512 * sizeof(float));
1875 memset(saved_ltp + 576, 0, 448 * sizeof(float));
1876 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1877 for (i = 0; i < 64; i++)
1878 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
1879 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1880 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
1881 memset(saved_ltp + 576, 0, 448 * sizeof(float));
1882 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1883 for (i = 0; i < 64; i++)
1884 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
1885 } else { // LONG_STOP or ONLY_LONG
1886 ac->dsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
1887 for (i = 0; i < 512; i++)
1888 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
1891 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
1892 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
1893 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
1897 * Conduct IMDCT and windowing.
1899 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
1901 IndividualChannelStream *ics = &sce->ics;
1902 float *in = sce->coeffs;
1903 float *out = sce->ret;
1904 float *saved = sce->saved;
1905 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1906 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1907 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1908 float *buf = ac->buf_mdct;
1909 float *temp = ac->temp;
1913 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1914 for (i = 0; i < 1024; i += 128)
1915 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
1917 ac->mdct.imdct_half(&ac->mdct, buf, in);
1919 /* window overlapping
1920 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1921 * and long to short transitions are considered to be short to short
1922 * transitions. This leaves just two cases (long to long and short to short)
1923 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1925 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
1926 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
1927 ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
1929 memcpy( out, saved, 448 * sizeof(float));
1931 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1932 ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
1933 ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
1934 ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
1935 ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
1936 ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
1937 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
1939 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
1940 memcpy( out + 576, buf + 64, 448 * sizeof(float));
1945 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1946 memcpy( saved, temp + 64, 64 * sizeof(float));
1947 ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
1948 ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
1949 ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
1950 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1951 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1952 memcpy( saved, buf + 512, 448 * sizeof(float));
1953 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1954 } else { // LONG_STOP or ONLY_LONG
1955 memcpy( saved, buf + 512, 512 * sizeof(float));
1960 * Apply dependent channel coupling (applied before IMDCT).
1962 * @param index index into coupling gain array
1964 static void apply_dependent_coupling(AACContext *ac,
1965 SingleChannelElement *target,
1966 ChannelElement *cce, int index)
1968 IndividualChannelStream *ics = &cce->ch[0].ics;
1969 const uint16_t *offsets = ics->swb_offset;
1970 float *dest = target->coeffs;
1971 const float *src = cce->ch[0].coeffs;
1972 int g, i, group, k, idx = 0;
1973 if (ac->m4ac.object_type == AOT_AAC_LTP) {
1974 av_log(ac->avctx, AV_LOG_ERROR,
1975 "Dependent coupling is not supported together with LTP\n");
1978 for (g = 0; g < ics->num_window_groups; g++) {
1979 for (i = 0; i < ics->max_sfb; i++, idx++) {
1980 if (cce->ch[0].band_type[idx] != ZERO_BT) {
1981 const float gain = cce->coup.gain[index][idx];
1982 for (group = 0; group < ics->group_len[g]; group++) {
1983 for (k = offsets[i]; k < offsets[i + 1]; k++) {
1985 dest[group * 128 + k] += gain * src[group * 128 + k];
1990 dest += ics->group_len[g] * 128;
1991 src += ics->group_len[g] * 128;
1996 * Apply independent channel coupling (applied after IMDCT).
1998 * @param index index into coupling gain array
2000 static void apply_independent_coupling(AACContext *ac,
2001 SingleChannelElement *target,
2002 ChannelElement *cce, int index)
2005 const float gain = cce->coup.gain[index][0];
2006 const float *src = cce->ch[0].ret;
2007 float *dest = target->ret;
2008 const int len = 1024 << (ac->m4ac.sbr == 1);
2010 for (i = 0; i < len; i++)
2011 dest[i] += gain * src[i];
2015 * channel coupling transformation interface
2017 * @param apply_coupling_method pointer to (in)dependent coupling function
2019 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2020 enum RawDataBlockType type, int elem_id,
2021 enum CouplingPoint coupling_point,
2022 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2026 for (i = 0; i < MAX_ELEM_ID; i++) {
2027 ChannelElement *cce = ac->che[TYPE_CCE][i];
2030 if (cce && cce->coup.coupling_point == coupling_point) {
2031 ChannelCoupling *coup = &cce->coup;
2033 for (c = 0; c <= coup->num_coupled; c++) {
2034 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2035 if (coup->ch_select[c] != 1) {
2036 apply_coupling_method(ac, &cc->ch[0], cce, index);
2037 if (coup->ch_select[c] != 0)
2040 if (coup->ch_select[c] != 2)
2041 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2043 index += 1 + (coup->ch_select[c] == 3);
2050 * Convert spectral data to float samples, applying all supported tools as appropriate.
2052 static void spectral_to_sample(AACContext *ac)
2055 for (type = 3; type >= 0; type--) {
2056 for (i = 0; i < MAX_ELEM_ID; i++) {
2057 ChannelElement *che = ac->che[type][i];
2059 if (type <= TYPE_CPE)
2060 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2061 if (ac->m4ac.object_type == AOT_AAC_LTP) {
2062 if (che->ch[0].ics.predictor_present) {
2063 if (che->ch[0].ics.ltp.present)
2064 apply_ltp(ac, &che->ch[0]);
2065 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2066 apply_ltp(ac, &che->ch[1]);
2069 if (che->ch[0].tns.present)
2070 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2071 if (che->ch[1].tns.present)
2072 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2073 if (type <= TYPE_CPE)
2074 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2075 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2076 imdct_and_windowing(ac, &che->ch[0]);
2077 if (ac->m4ac.object_type == AOT_AAC_LTP)
2078 update_ltp(ac, &che->ch[0]);
2079 if (type == TYPE_CPE) {
2080 imdct_and_windowing(ac, &che->ch[1]);
2081 if (ac->m4ac.object_type == AOT_AAC_LTP)
2082 update_ltp(ac, &che->ch[1]);
2084 if (ac->m4ac.sbr > 0) {
2085 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2088 if (type <= TYPE_CCE)
2089 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2095 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2098 AACADTSHeaderInfo hdr_info;
2100 size = avpriv_aac_parse_header(gb, &hdr_info);
2102 if (hdr_info.chan_config && (hdr_info.chan_config!=ac->m4ac.chan_config || ac->m4ac.sample_rate!=hdr_info.sample_rate)) {
2103 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2104 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2105 ac->m4ac.chan_config = hdr_info.chan_config;
2106 if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
2108 if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config,
2109 FFMAX(ac->output_configured, OC_TRIAL_FRAME)))
2111 } else if (ac->output_configured != OC_LOCKED) {
2112 ac->m4ac.chan_config = 0;
2113 ac->output_configured = OC_NONE;
2115 if (ac->output_configured != OC_LOCKED) {
2118 ac->m4ac.sample_rate = hdr_info.sample_rate;
2119 ac->m4ac.sampling_index = hdr_info.sampling_index;
2120 ac->m4ac.object_type = hdr_info.object_type;
2122 if (!ac->avctx->sample_rate)
2123 ac->avctx->sample_rate = hdr_info.sample_rate;
2124 if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
2125 // This is 2 for "VLB " audio in NSV files.
2126 // See samples/nsv/vlb_audio.
2127 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
2128 ac->warned_num_aac_frames = 1;
2130 if (!hdr_info.crc_absent)
2136 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2137 int *got_frame_ptr, GetBitContext *gb)
2139 AACContext *ac = avctx->priv_data;
2140 ChannelElement *che = NULL, *che_prev = NULL;
2141 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2143 int samples = 0, multiplier, audio_found = 0;
2145 if (show_bits(gb, 12) == 0xfff) {
2146 if (parse_adts_frame_header(ac, gb) < 0) {
2147 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2150 if (ac->m4ac.sampling_index > 12) {
2151 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
2156 ac->tags_mapped = 0;
2158 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2159 elem_id = get_bits(gb, 4);
2161 if (elem_type < TYPE_DSE) {
2162 if (!ac->tags_mapped && elem_type == TYPE_CPE && ac->m4ac.chan_config==1) {
2163 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID]= {0};
2164 ac->m4ac.chan_config=2;
2166 if (set_default_channel_config(ac->avctx, new_che_pos, 2)<0)
2168 if (output_configure(ac, ac->che_pos, new_che_pos, 2, OC_TRIAL_FRAME)<0)
2171 if (!(che=get_che(ac, elem_type, elem_id))) {
2172 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2173 elem_type, elem_id);
2179 switch (elem_type) {
2182 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2187 err = decode_cpe(ac, gb, che);
2192 err = decode_cce(ac, gb, che);
2196 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2201 err = skip_data_stream_element(ac, gb);
2205 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2206 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
2207 if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
2209 if (ac->output_configured > OC_TRIAL_PCE)
2210 av_log(avctx, AV_LOG_ERROR,
2211 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2213 err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
2219 elem_id += get_bits(gb, 8) - 1;
2220 if (get_bits_left(gb) < 8 * elem_id) {
2221 av_log(avctx, AV_LOG_ERROR, overread_err);
2225 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2226 err = 0; /* FIXME */
2230 err = -1; /* should not happen, but keeps compiler happy */
2235 elem_type_prev = elem_type;
2240 if (get_bits_left(gb) < 3) {
2241 av_log(avctx, AV_LOG_ERROR, overread_err);
2246 spectral_to_sample(ac);
2248 multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2249 samples <<= multiplier;
2250 if (ac->output_configured < OC_LOCKED) {
2251 avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2252 avctx->frame_size = samples;
2256 /* get output buffer */
2257 ac->frame.nb_samples = samples;
2258 if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
2259 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2263 if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
2264 ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
2265 (const float **)ac->output_data,
2266 samples, avctx->channels);
2268 ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2269 (const float **)ac->output_data,
2270 samples, avctx->channels);
2272 *(AVFrame *)data = ac->frame;
2274 *got_frame_ptr = !!samples;
2276 if (ac->output_configured && audio_found)
2277 ac->output_configured = OC_LOCKED;
2282 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2283 int *got_frame_ptr, AVPacket *avpkt)
2285 const uint8_t *buf = avpkt->data;
2286 int buf_size = avpkt->size;
2292 init_get_bits(&gb, buf, buf_size * 8);
2294 if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
2297 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2298 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2299 if (buf[buf_offset])
2302 return buf_size > buf_offset ? buf_consumed : buf_size;
2305 static av_cold int aac_decode_close(AVCodecContext *avctx)
2307 AACContext *ac = avctx->priv_data;
2310 for (i = 0; i < MAX_ELEM_ID; i++) {
2311 for (type = 0; type < 4; type++) {
2312 if (ac->che[type][i])
2313 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2314 av_freep(&ac->che[type][i]);
2318 ff_mdct_end(&ac->mdct);
2319 ff_mdct_end(&ac->mdct_small);
2320 ff_mdct_end(&ac->mdct_ltp);
2325 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2327 struct LATMContext {
2328 AACContext aac_ctx; ///< containing AACContext
2329 int initialized; ///< initilized after a valid extradata was seen
2332 int audio_mux_version_A; ///< LATM syntax version
2333 int frame_length_type; ///< 0/1 variable/fixed frame length
2334 int frame_length; ///< frame length for fixed frame length
2337 static inline uint32_t latm_get_value(GetBitContext *b)
2339 int length = get_bits(b, 2);
2341 return get_bits_long(b, (length+1)*8);
2344 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2345 GetBitContext *gb, int asclen)
2347 AACContext *ac = &latmctx->aac_ctx;
2348 AVCodecContext *avctx = ac->avctx;
2349 MPEG4AudioConfig m4ac = {0};
2350 int config_start_bit = get_bits_count(gb);
2351 int sync_extension = 0;
2352 int bits_consumed, esize;
2356 asclen = FFMIN(asclen, get_bits_left(gb));
2358 asclen = get_bits_left(gb);
2360 if (config_start_bit % 8) {
2361 av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2362 "config not byte aligned.\n", 1);
2363 return AVERROR_INVALIDDATA;
2365 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2366 gb->buffer + (config_start_bit / 8),
2367 asclen, sync_extension);
2369 if (bits_consumed < 0)
2370 return AVERROR_INVALIDDATA;
2372 if (ac->m4ac.sample_rate != m4ac.sample_rate ||
2373 ac->m4ac.chan_config != m4ac.chan_config) {
2375 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2376 latmctx->initialized = 0;
2378 esize = (bits_consumed+7) / 8;
2380 if (avctx->extradata_size < esize) {
2381 av_free(avctx->extradata);
2382 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2383 if (!avctx->extradata)
2384 return AVERROR(ENOMEM);
2387 avctx->extradata_size = esize;
2388 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2389 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2391 skip_bits_long(gb, bits_consumed);
2393 return bits_consumed;
2396 static int read_stream_mux_config(struct LATMContext *latmctx,
2399 int ret, audio_mux_version = get_bits(gb, 1);
2401 latmctx->audio_mux_version_A = 0;
2402 if (audio_mux_version)
2403 latmctx->audio_mux_version_A = get_bits(gb, 1);
2405 if (!latmctx->audio_mux_version_A) {
2407 if (audio_mux_version)
2408 latm_get_value(gb); // taraFullness
2410 skip_bits(gb, 1); // allStreamSameTimeFraming
2411 skip_bits(gb, 6); // numSubFrames
2413 if (get_bits(gb, 4)) { // numPrograms
2414 av_log_missing_feature(latmctx->aac_ctx.avctx,
2415 "multiple programs are not supported\n", 1);
2416 return AVERROR_PATCHWELCOME;
2419 // for each program (which there is only on in DVB)
2421 // for each layer (which there is only on in DVB)
2422 if (get_bits(gb, 3)) { // numLayer
2423 av_log_missing_feature(latmctx->aac_ctx.avctx,
2424 "multiple layers are not supported\n", 1);
2425 return AVERROR_PATCHWELCOME;
2428 // for all but first stream: use_same_config = get_bits(gb, 1);
2429 if (!audio_mux_version) {
2430 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2433 int ascLen = latm_get_value(gb);
2434 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2437 skip_bits_long(gb, ascLen);
2440 latmctx->frame_length_type = get_bits(gb, 3);
2441 switch (latmctx->frame_length_type) {
2443 skip_bits(gb, 8); // latmBufferFullness
2446 latmctx->frame_length = get_bits(gb, 9);
2451 skip_bits(gb, 6); // CELP frame length table index
2455 skip_bits(gb, 1); // HVXC frame length table index
2459 if (get_bits(gb, 1)) { // other data
2460 if (audio_mux_version) {
2461 latm_get_value(gb); // other_data_bits
2465 esc = get_bits(gb, 1);
2471 if (get_bits(gb, 1)) // crc present
2472 skip_bits(gb, 8); // config_crc
2478 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2482 if (ctx->frame_length_type == 0) {
2483 int mux_slot_length = 0;
2485 tmp = get_bits(gb, 8);
2486 mux_slot_length += tmp;
2487 } while (tmp == 255);
2488 return mux_slot_length;
2489 } else if (ctx->frame_length_type == 1) {
2490 return ctx->frame_length;
2491 } else if (ctx->frame_length_type == 3 ||
2492 ctx->frame_length_type == 5 ||
2493 ctx->frame_length_type == 7) {
2494 skip_bits(gb, 2); // mux_slot_length_coded
2499 static int read_audio_mux_element(struct LATMContext *latmctx,
2503 uint8_t use_same_mux = get_bits(gb, 1);
2504 if (!use_same_mux) {
2505 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2507 } else if (!latmctx->aac_ctx.avctx->extradata) {
2508 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2509 "no decoder config found\n");
2510 return AVERROR(EAGAIN);
2512 if (latmctx->audio_mux_version_A == 0) {
2513 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2514 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2515 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2516 return AVERROR_INVALIDDATA;
2517 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2518 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2519 "frame length mismatch %d << %d\n",
2520 mux_slot_length_bytes * 8, get_bits_left(gb));
2521 return AVERROR_INVALIDDATA;
2528 static int latm_decode_frame(AVCodecContext *avctx, void *out,
2529 int *got_frame_ptr, AVPacket *avpkt)
2531 struct LATMContext *latmctx = avctx->priv_data;
2535 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2537 // check for LOAS sync word
2538 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2539 return AVERROR_INVALIDDATA;
2541 muxlength = get_bits(&gb, 13) + 3;
2542 // not enough data, the parser should have sorted this
2543 if (muxlength > avpkt->size)
2544 return AVERROR_INVALIDDATA;
2546 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2549 if (!latmctx->initialized) {
2550 if (!avctx->extradata) {
2554 if ((err = decode_audio_specific_config(
2555 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.m4ac,
2556 avctx->extradata, avctx->extradata_size*8, 1)) < 0)
2558 latmctx->initialized = 1;
2562 if (show_bits(&gb, 12) == 0xfff) {
2563 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2564 "ADTS header detected, probably as result of configuration "
2566 return AVERROR_INVALIDDATA;
2569 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
2575 av_cold static int latm_decode_init(AVCodecContext *avctx)
2577 struct LATMContext *latmctx = avctx->priv_data;
2578 int ret = aac_decode_init(avctx);
2580 if (avctx->extradata_size > 0)
2581 latmctx->initialized = !ret;
2587 AVCodec ff_aac_decoder = {
2589 .type = AVMEDIA_TYPE_AUDIO,
2591 .priv_data_size = sizeof(AACContext),
2592 .init = aac_decode_init,
2593 .close = aac_decode_close,
2594 .decode = aac_decode_frame,
2595 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2596 .sample_fmts = (const enum AVSampleFormat[]) {
2597 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2599 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2600 .channel_layouts = aac_channel_layout,
2604 Note: This decoder filter is intended to decode LATM streams transferred
2605 in MPEG transport streams which only contain one program.
2606 To do a more complex LATM demuxing a separate LATM demuxer should be used.
2608 AVCodec ff_aac_latm_decoder = {
2610 .type = AVMEDIA_TYPE_AUDIO,
2611 .id = CODEC_ID_AAC_LATM,
2612 .priv_data_size = sizeof(struct LATMContext),
2613 .init = latm_decode_init,
2614 .close = aac_decode_close,
2615 .decode = latm_decode_frame,
2616 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2617 .sample_fmts = (const enum AVSampleFormat[]) {
2618 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
2620 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
2621 .channel_layouts = aac_channel_layout,