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 * N (code in SoC repo) 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
92 #include "aacdectab.h"
93 #include "cbrt_tablegen.h"
96 #include "mpeg4audio.h"
97 #include "aacadtsdec.h"
105 # include "arm/aac.h"
113 static VLC vlc_scalefactors;
114 static VLC vlc_spectral[11];
116 static const char overread_err[] = "Input buffer exhausted before END element found\n";
118 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
120 // For PCE based channel configurations map the channels solely based on tags.
121 if (!ac->m4ac.chan_config) {
122 return ac->tag_che_map[type][elem_id];
124 // For indexed channel configurations map the channels solely based on position.
125 switch (ac->m4ac.chan_config) {
127 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
129 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
132 /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
133 instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
134 encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
135 if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
137 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
140 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
142 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
145 if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
147 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
151 if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
153 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
154 } else if (ac->m4ac.chan_config == 2) {
158 if (!ac->tags_mapped && type == TYPE_SCE) {
160 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
168 * Check for the channel element in the current channel position configuration.
169 * If it exists, make sure the appropriate element is allocated and map the
170 * channel order to match the internal FFmpeg channel layout.
172 * @param che_pos current channel position configuration
173 * @param type channel element type
174 * @param id channel element id
175 * @param channels count of the number of channels in the configuration
177 * @return Returns error status. 0 - OK, !0 - error
179 static av_cold int che_configure(AACContext *ac,
180 enum ChannelPosition che_pos[4][MAX_ELEM_ID],
184 if (che_pos[type][id]) {
185 if (!ac->che[type][id] && !(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
186 return AVERROR(ENOMEM);
187 ff_aac_sbr_ctx_init(&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]));
253 avctx->channel_layout = 0;
256 avctx->channels = channels;
258 ac->output_configured = oc_type;
264 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
266 * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
267 * @param sce_map mono (Single Channel Element) map
268 * @param type speaker type/position for these channels
270 static void decode_channel_map(enum ChannelPosition *cpe_map,
271 enum ChannelPosition *sce_map,
272 enum ChannelPosition type,
273 GetBitContext *gb, int n)
276 enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
277 map[get_bits(gb, 4)] = type;
282 * Decode program configuration element; reference: table 4.2.
284 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
286 * @return Returns error status. 0 - OK, !0 - error
288 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
289 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
292 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
295 skip_bits(gb, 2); // object_type
297 sampling_index = get_bits(gb, 4);
298 if (m4ac->sampling_index != sampling_index)
299 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");
301 num_front = get_bits(gb, 4);
302 num_side = get_bits(gb, 4);
303 num_back = get_bits(gb, 4);
304 num_lfe = get_bits(gb, 2);
305 num_assoc_data = get_bits(gb, 3);
306 num_cc = get_bits(gb, 4);
309 skip_bits(gb, 4); // mono_mixdown_tag
311 skip_bits(gb, 4); // stereo_mixdown_tag
314 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
316 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
317 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
318 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
319 decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
321 skip_bits_long(gb, 4 * num_assoc_data);
323 decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
327 /* comment field, first byte is length */
328 comment_len = get_bits(gb, 8) * 8;
329 if (get_bits_left(gb) < comment_len) {
330 av_log(avctx, AV_LOG_ERROR, overread_err);
333 skip_bits_long(gb, comment_len);
338 * Set up channel positions based on a default channel configuration
339 * as specified in table 1.17.
341 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
343 * @return Returns error status. 0 - OK, !0 - error
345 static av_cold int set_default_channel_config(AVCodecContext *avctx,
346 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
349 if (channel_config < 1 || channel_config > 7) {
350 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
355 /* default channel configurations:
357 * 1ch : front center (mono)
358 * 2ch : L + R (stereo)
359 * 3ch : front center + L + R
360 * 4ch : front center + L + R + back center
361 * 5ch : front center + L + R + back stereo
362 * 6ch : front center + L + R + back stereo + LFE
363 * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
366 if (channel_config != 2)
367 new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
368 if (channel_config > 1)
369 new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
370 if (channel_config == 4)
371 new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
372 if (channel_config > 4)
373 new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
374 = AAC_CHANNEL_BACK; // back stereo
375 if (channel_config > 5)
376 new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
377 if (channel_config == 7)
378 new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
384 * Decode GA "General Audio" specific configuration; reference: table 4.1.
386 * @param ac pointer to AACContext, may be null
387 * @param avctx pointer to AVCCodecContext, used for logging
389 * @return Returns error status. 0 - OK, !0 - error
391 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
393 MPEG4AudioConfig *m4ac,
396 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
397 int extension_flag, ret;
399 if (get_bits1(gb)) { // frameLengthFlag
400 av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
404 if (get_bits1(gb)) // dependsOnCoreCoder
405 skip_bits(gb, 14); // coreCoderDelay
406 extension_flag = get_bits1(gb);
408 if (m4ac->object_type == AOT_AAC_SCALABLE ||
409 m4ac->object_type == AOT_ER_AAC_SCALABLE)
410 skip_bits(gb, 3); // layerNr
412 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
413 if (channel_config == 0) {
414 skip_bits(gb, 4); // element_instance_tag
415 if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
418 if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
421 if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
424 if (extension_flag) {
425 switch (m4ac->object_type) {
427 skip_bits(gb, 5); // numOfSubFrame
428 skip_bits(gb, 11); // layer_length
432 case AOT_ER_AAC_SCALABLE:
434 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
435 * aacScalefactorDataResilienceFlag
436 * aacSpectralDataResilienceFlag
440 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
446 * Decode audio specific configuration; reference: table 1.13.
448 * @param ac pointer to AACContext, may be null
449 * @param avctx pointer to AVCCodecContext, used for logging
450 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
451 * @param data pointer to AVCodecContext extradata
452 * @param data_size size of AVCCodecContext extradata
454 * @return Returns error status or number of consumed bits. <0 - error
456 static int decode_audio_specific_config(AACContext *ac,
457 AVCodecContext *avctx,
458 MPEG4AudioConfig *m4ac,
459 const uint8_t *data, int data_size)
464 init_get_bits(&gb, data, data_size * 8);
466 if ((i = ff_mpeg4audio_get_config(m4ac, data, data_size)) < 0)
468 if (m4ac->sampling_index > 12) {
469 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
472 if (m4ac->sbr == 1 && m4ac->ps == -1)
475 skip_bits_long(&gb, i);
477 switch (m4ac->object_type) {
480 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
484 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
485 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
489 return get_bits_count(&gb);
493 * linear congruential pseudorandom number generator
495 * @param previous_val pointer to the current state of the generator
497 * @return Returns a 32-bit pseudorandom integer
499 static av_always_inline int lcg_random(int previous_val)
501 return previous_val * 1664525 + 1013904223;
504 static av_always_inline void reset_predict_state(PredictorState *ps)
514 static void reset_all_predictors(PredictorState *ps)
517 for (i = 0; i < MAX_PREDICTORS; i++)
518 reset_predict_state(&ps[i]);
521 static void reset_predictor_group(PredictorState *ps, int group_num)
524 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
525 reset_predict_state(&ps[i]);
528 #define AAC_INIT_VLC_STATIC(num, size) \
529 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
530 ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
531 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
534 static av_cold int aac_decode_init(AVCodecContext *avctx)
536 AACContext *ac = avctx->priv_data;
539 ac->m4ac.sample_rate = avctx->sample_rate;
541 if (avctx->extradata_size > 0) {
542 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
544 avctx->extradata_size) < 0)
548 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
550 AAC_INIT_VLC_STATIC( 0, 304);
551 AAC_INIT_VLC_STATIC( 1, 270);
552 AAC_INIT_VLC_STATIC( 2, 550);
553 AAC_INIT_VLC_STATIC( 3, 300);
554 AAC_INIT_VLC_STATIC( 4, 328);
555 AAC_INIT_VLC_STATIC( 5, 294);
556 AAC_INIT_VLC_STATIC( 6, 306);
557 AAC_INIT_VLC_STATIC( 7, 268);
558 AAC_INIT_VLC_STATIC( 8, 510);
559 AAC_INIT_VLC_STATIC( 9, 366);
560 AAC_INIT_VLC_STATIC(10, 462);
564 dsputil_init(&ac->dsp, avctx);
566 ac->random_state = 0x1f2e3d4c;
568 // -1024 - Compensate wrong IMDCT method.
569 // 32768 - Required to scale values to the correct range for the bias method
570 // for float to int16 conversion.
572 if (ac->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
573 ac->add_bias = 385.0f;
574 ac->sf_scale = 1. / (-1024. * 32768.);
578 ac->sf_scale = 1. / -1024.;
584 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
585 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
586 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
589 ff_mdct_init(&ac->mdct, 11, 1, 1.0);
590 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0);
591 // window initialization
592 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
593 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
594 ff_init_ff_sine_windows(10);
595 ff_init_ff_sine_windows( 7);
603 * Skip data_stream_element; reference: table 4.10.
605 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
607 int byte_align = get_bits1(gb);
608 int count = get_bits(gb, 8);
610 count += get_bits(gb, 8);
614 if (get_bits_left(gb) < 8 * count) {
615 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
618 skip_bits_long(gb, 8 * count);
622 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
627 ics->predictor_reset_group = get_bits(gb, 5);
628 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
629 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
633 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
634 ics->prediction_used[sfb] = get_bits1(gb);
640 * Decode Individual Channel Stream info; reference: table 4.6.
642 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
644 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
645 GetBitContext *gb, int common_window)
648 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
649 memset(ics, 0, sizeof(IndividualChannelStream));
652 ics->window_sequence[1] = ics->window_sequence[0];
653 ics->window_sequence[0] = get_bits(gb, 2);
654 ics->use_kb_window[1] = ics->use_kb_window[0];
655 ics->use_kb_window[0] = get_bits1(gb);
656 ics->num_window_groups = 1;
657 ics->group_len[0] = 1;
658 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
660 ics->max_sfb = get_bits(gb, 4);
661 for (i = 0; i < 7; i++) {
663 ics->group_len[ics->num_window_groups - 1]++;
665 ics->num_window_groups++;
666 ics->group_len[ics->num_window_groups - 1] = 1;
669 ics->num_windows = 8;
670 ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
671 ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
672 ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
673 ics->predictor_present = 0;
675 ics->max_sfb = get_bits(gb, 6);
676 ics->num_windows = 1;
677 ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
678 ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
679 ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
680 ics->predictor_present = get_bits1(gb);
681 ics->predictor_reset_group = 0;
682 if (ics->predictor_present) {
683 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
684 if (decode_prediction(ac, ics, gb)) {
685 memset(ics, 0, sizeof(IndividualChannelStream));
688 } else if (ac->m4ac.object_type == AOT_AAC_LC) {
689 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
690 memset(ics, 0, sizeof(IndividualChannelStream));
693 av_log_missing_feature(ac->avctx, "Predictor bit set but LTP is", 1);
694 memset(ics, 0, sizeof(IndividualChannelStream));
700 if (ics->max_sfb > ics->num_swb) {
701 av_log(ac->avctx, AV_LOG_ERROR,
702 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
703 ics->max_sfb, ics->num_swb);
704 memset(ics, 0, sizeof(IndividualChannelStream));
712 * Decode band types (section_data payload); reference: table 4.46.
714 * @param band_type array of the used band type
715 * @param band_type_run_end array of the last scalefactor band of a band type run
717 * @return Returns error status. 0 - OK, !0 - error
719 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
720 int band_type_run_end[120], GetBitContext *gb,
721 IndividualChannelStream *ics)
724 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
725 for (g = 0; g < ics->num_window_groups; g++) {
727 while (k < ics->max_sfb) {
728 uint8_t sect_end = k;
730 int sect_band_type = get_bits(gb, 4);
731 if (sect_band_type == 12) {
732 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
735 while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
736 sect_end += sect_len_incr;
737 sect_end += sect_len_incr;
738 if (get_bits_left(gb) < 0) {
739 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
742 if (sect_end > ics->max_sfb) {
743 av_log(ac->avctx, AV_LOG_ERROR,
744 "Number of bands (%d) exceeds limit (%d).\n",
745 sect_end, ics->max_sfb);
748 for (; k < sect_end; k++) {
749 band_type [idx] = sect_band_type;
750 band_type_run_end[idx++] = sect_end;
758 * Decode scalefactors; reference: table 4.47.
760 * @param global_gain first scalefactor value as scalefactors are differentially coded
761 * @param band_type array of the used band type
762 * @param band_type_run_end array of the last scalefactor band of a band type run
763 * @param sf array of scalefactors or intensity stereo positions
765 * @return Returns error status. 0 - OK, !0 - error
767 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
768 unsigned int global_gain,
769 IndividualChannelStream *ics,
770 enum BandType band_type[120],
771 int band_type_run_end[120])
773 const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
775 int offset[3] = { global_gain, global_gain - 90, 100 };
777 static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
778 for (g = 0; g < ics->num_window_groups; g++) {
779 for (i = 0; i < ics->max_sfb;) {
780 int run_end = band_type_run_end[idx];
781 if (band_type[idx] == ZERO_BT) {
782 for (; i < run_end; i++, idx++)
784 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
785 for (; i < run_end; i++, idx++) {
786 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
787 if (offset[2] > 255U) {
788 av_log(ac->avctx, AV_LOG_ERROR,
789 "%s (%d) out of range.\n", sf_str[2], offset[2]);
792 sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
794 } else if (band_type[idx] == NOISE_BT) {
795 for (; i < run_end; i++, idx++) {
796 if (noise_flag-- > 0)
797 offset[1] += get_bits(gb, 9) - 256;
799 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
800 if (offset[1] > 255U) {
801 av_log(ac->avctx, AV_LOG_ERROR,
802 "%s (%d) out of range.\n", sf_str[1], offset[1]);
805 sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
808 for (; i < run_end; i++, idx++) {
809 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
810 if (offset[0] > 255U) {
811 av_log(ac->avctx, AV_LOG_ERROR,
812 "%s (%d) out of range.\n", sf_str[0], offset[0]);
815 sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
824 * Decode pulse data; reference: table 4.7.
826 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
827 const uint16_t *swb_offset, int num_swb)
830 pulse->num_pulse = get_bits(gb, 2) + 1;
831 pulse_swb = get_bits(gb, 6);
832 if (pulse_swb >= num_swb)
834 pulse->pos[0] = swb_offset[pulse_swb];
835 pulse->pos[0] += get_bits(gb, 5);
836 if (pulse->pos[0] > 1023)
838 pulse->amp[0] = get_bits(gb, 4);
839 for (i = 1; i < pulse->num_pulse; i++) {
840 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
841 if (pulse->pos[i] > 1023)
843 pulse->amp[i] = get_bits(gb, 4);
849 * Decode Temporal Noise Shaping data; reference: table 4.48.
851 * @return Returns error status. 0 - OK, !0 - error
853 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
854 GetBitContext *gb, const IndividualChannelStream *ics)
856 int w, filt, i, coef_len, coef_res, coef_compress;
857 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
858 const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
859 for (w = 0; w < ics->num_windows; w++) {
860 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
861 coef_res = get_bits1(gb);
863 for (filt = 0; filt < tns->n_filt[w]; filt++) {
865 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
867 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
868 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
869 tns->order[w][filt], tns_max_order);
870 tns->order[w][filt] = 0;
873 if (tns->order[w][filt]) {
874 tns->direction[w][filt] = get_bits1(gb);
875 coef_compress = get_bits1(gb);
876 coef_len = coef_res + 3 - coef_compress;
877 tmp2_idx = 2 * coef_compress + coef_res;
879 for (i = 0; i < tns->order[w][filt]; i++)
880 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
889 * Decode Mid/Side data; reference: table 4.54.
891 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
892 * [1] mask is decoded from bitstream; [2] mask is all 1s;
893 * [3] reserved for scalable AAC
895 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
899 if (ms_present == 1) {
900 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
901 cpe->ms_mask[idx] = get_bits1(gb);
902 } else if (ms_present == 2) {
903 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
908 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
912 *dst++ = v[idx & 15] * s;
913 *dst++ = v[idx>>4 & 15] * s;
919 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
923 *dst++ = v[idx & 3] * s;
924 *dst++ = v[idx>>2 & 3] * s;
925 *dst++ = v[idx>>4 & 3] * s;
926 *dst++ = v[idx>>6 & 3] * s;
932 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
933 unsigned sign, const float *scale)
935 union float754 s0, s1;
937 s0.f = s1.f = *scale;
938 s0.i ^= sign >> 1 << 31;
941 *dst++ = v[idx & 15] * s0.f;
942 *dst++ = v[idx>>4 & 15] * s1.f;
949 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
950 unsigned sign, const float *scale)
952 unsigned nz = idx >> 12;
953 union float754 s = { .f = *scale };
956 t.i = s.i ^ (sign & 1<<31);
957 *dst++ = v[idx & 3] * t.f;
959 sign <<= nz & 1; nz >>= 1;
960 t.i = s.i ^ (sign & 1<<31);
961 *dst++ = v[idx>>2 & 3] * t.f;
963 sign <<= nz & 1; nz >>= 1;
964 t.i = s.i ^ (sign & 1<<31);
965 *dst++ = v[idx>>4 & 3] * t.f;
967 sign <<= nz & 1; nz >>= 1;
968 t.i = s.i ^ (sign & 1<<31);
969 *dst++ = v[idx>>6 & 3] * t.f;
976 * Decode spectral data; reference: table 4.50.
977 * Dequantize and scale spectral data; reference: 4.6.3.3.
979 * @param coef array of dequantized, scaled spectral data
980 * @param sf array of scalefactors or intensity stereo positions
981 * @param pulse_present set if pulses are present
982 * @param pulse pointer to pulse data struct
983 * @param band_type array of the used band type
985 * @return Returns error status. 0 - OK, !0 - error
987 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
988 GetBitContext *gb, const float sf[120],
989 int pulse_present, const Pulse *pulse,
990 const IndividualChannelStream *ics,
991 enum BandType band_type[120])
993 int i, k, g, idx = 0;
994 const int c = 1024 / ics->num_windows;
995 const uint16_t *offsets = ics->swb_offset;
996 float *coef_base = coef;
998 for (g = 0; g < ics->num_windows; g++)
999 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
1001 for (g = 0; g < ics->num_window_groups; g++) {
1002 unsigned g_len = ics->group_len[g];
1004 for (i = 0; i < ics->max_sfb; i++, idx++) {
1005 const unsigned cbt_m1 = band_type[idx] - 1;
1006 float *cfo = coef + offsets[i];
1007 int off_len = offsets[i + 1] - offsets[i];
1010 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1011 for (group = 0; group < g_len; group++, cfo+=128) {
1012 memset(cfo, 0, off_len * sizeof(float));
1014 } else if (cbt_m1 == NOISE_BT - 1) {
1015 for (group = 0; group < g_len; group++, cfo+=128) {
1019 for (k = 0; k < off_len; k++) {
1020 ac->random_state = lcg_random(ac->random_state);
1021 cfo[k] = ac->random_state;
1024 band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1025 scale = sf[idx] / sqrtf(band_energy);
1026 ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1029 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1030 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1031 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1032 OPEN_READER(re, gb);
1034 switch (cbt_m1 >> 1) {
1036 for (group = 0; group < g_len; group++, cfo+=128) {
1044 UPDATE_CACHE(re, gb);
1045 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1046 cb_idx = cb_vector_idx[code];
1047 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1053 for (group = 0; group < g_len; group++, cfo+=128) {
1063 UPDATE_CACHE(re, gb);
1064 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1065 #if MIN_CACHE_BITS < 20
1066 UPDATE_CACHE(re, gb);
1068 cb_idx = cb_vector_idx[code];
1069 nnz = cb_idx >> 8 & 15;
1070 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1071 LAST_SKIP_BITS(re, gb, nnz);
1072 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1078 for (group = 0; group < g_len; group++, cfo+=128) {
1086 UPDATE_CACHE(re, gb);
1087 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1088 cb_idx = cb_vector_idx[code];
1089 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1096 for (group = 0; group < g_len; group++, cfo+=128) {
1106 UPDATE_CACHE(re, gb);
1107 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1108 cb_idx = cb_vector_idx[code];
1109 nnz = cb_idx >> 8 & 15;
1110 sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
1111 LAST_SKIP_BITS(re, gb, nnz);
1112 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1118 for (group = 0; group < g_len; group++, cfo+=128) {
1120 uint32_t *icf = (uint32_t *) cf;
1130 UPDATE_CACHE(re, gb);
1131 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1139 cb_idx = cb_vector_idx[code];
1142 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1143 LAST_SKIP_BITS(re, gb, nnz);
1145 for (j = 0; j < 2; j++) {
1149 /* The total length of escape_sequence must be < 22 bits according
1150 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1151 UPDATE_CACHE(re, gb);
1152 b = GET_CACHE(re, gb);
1153 b = 31 - av_log2(~b);
1156 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1160 #if MIN_CACHE_BITS < 21
1161 LAST_SKIP_BITS(re, gb, b + 1);
1162 UPDATE_CACHE(re, gb);
1164 SKIP_BITS(re, gb, b + 1);
1167 n = (1 << b) + SHOW_UBITS(re, gb, b);
1168 LAST_SKIP_BITS(re, gb, b);
1169 *icf++ = cbrt_tab[n] | (bits & 1<<31);
1172 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1173 *icf++ = (bits & 1<<31) | v;
1180 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1184 CLOSE_READER(re, gb);
1190 if (pulse_present) {
1192 for (i = 0; i < pulse->num_pulse; i++) {
1193 float co = coef_base[ pulse->pos[i] ];
1194 while (offsets[idx + 1] <= pulse->pos[i])
1196 if (band_type[idx] != NOISE_BT && sf[idx]) {
1197 float ico = -pulse->amp[i];
1200 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1202 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1209 static av_always_inline float flt16_round(float pf)
1213 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1217 static av_always_inline float flt16_even(float pf)
1221 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1225 static av_always_inline float flt16_trunc(float pf)
1229 pun.i &= 0xFFFF0000U;
1233 static av_always_inline void predict(PredictorState *ps, float *coef,
1234 float sf_scale, float inv_sf_scale,
1237 const float a = 0.953125; // 61.0 / 64
1238 const float alpha = 0.90625; // 29.0 / 32
1242 float r0 = ps->r0, r1 = ps->r1;
1243 float cor0 = ps->cor0, cor1 = ps->cor1;
1244 float var0 = ps->var0, var1 = ps->var1;
1246 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1247 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1249 pv = flt16_round(k1 * r0 + k2 * r1);
1251 *coef += pv * sf_scale;
1253 e0 = *coef * inv_sf_scale;
1256 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1257 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1258 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1259 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1261 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1262 ps->r0 = flt16_trunc(a * e0);
1266 * Apply AAC-Main style frequency domain prediction.
1268 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1271 float sf_scale = ac->sf_scale, inv_sf_scale = 1 / ac->sf_scale;
1273 if (!sce->ics.predictor_initialized) {
1274 reset_all_predictors(sce->predictor_state);
1275 sce->ics.predictor_initialized = 1;
1278 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1279 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1280 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1281 predict(&sce->predictor_state[k], &sce->coeffs[k],
1282 sf_scale, inv_sf_scale,
1283 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1286 if (sce->ics.predictor_reset_group)
1287 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1289 reset_all_predictors(sce->predictor_state);
1293 * Decode an individual_channel_stream payload; reference: table 4.44.
1295 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1296 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1298 * @return Returns error status. 0 - OK, !0 - error
1300 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1301 GetBitContext *gb, int common_window, int scale_flag)
1304 TemporalNoiseShaping *tns = &sce->tns;
1305 IndividualChannelStream *ics = &sce->ics;
1306 float *out = sce->coeffs;
1307 int global_gain, pulse_present = 0;
1309 /* This assignment is to silence a GCC warning about the variable being used
1310 * uninitialized when in fact it always is.
1312 pulse.num_pulse = 0;
1314 global_gain = get_bits(gb, 8);
1316 if (!common_window && !scale_flag) {
1317 if (decode_ics_info(ac, ics, gb, 0) < 0)
1321 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1323 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1328 if ((pulse_present = get_bits1(gb))) {
1329 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1330 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1333 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1334 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1338 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1340 if (get_bits1(gb)) {
1341 av_log_missing_feature(ac->avctx, "SSR", 1);
1346 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1349 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1350 apply_prediction(ac, sce);
1356 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1358 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1360 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1361 float *ch0 = cpe->ch[0].coeffs;
1362 float *ch1 = cpe->ch[1].coeffs;
1363 int g, i, group, idx = 0;
1364 const uint16_t *offsets = ics->swb_offset;
1365 for (g = 0; g < ics->num_window_groups; g++) {
1366 for (i = 0; i < ics->max_sfb; i++, idx++) {
1367 if (cpe->ms_mask[idx] &&
1368 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1369 for (group = 0; group < ics->group_len[g]; group++) {
1370 ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1371 ch1 + group * 128 + offsets[i],
1372 offsets[i+1] - offsets[i]);
1376 ch0 += ics->group_len[g] * 128;
1377 ch1 += ics->group_len[g] * 128;
1382 * intensity stereo decoding; reference: 4.6.8.2.3
1384 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1385 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1386 * [3] reserved for scalable AAC
1388 static void apply_intensity_stereo(ChannelElement *cpe, int ms_present)
1390 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1391 SingleChannelElement *sce1 = &cpe->ch[1];
1392 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1393 const uint16_t *offsets = ics->swb_offset;
1394 int g, group, i, k, idx = 0;
1397 for (g = 0; g < ics->num_window_groups; g++) {
1398 for (i = 0; i < ics->max_sfb;) {
1399 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1400 const int bt_run_end = sce1->band_type_run_end[idx];
1401 for (; i < bt_run_end; i++, idx++) {
1402 c = -1 + 2 * (sce1->band_type[idx] - 14);
1404 c *= 1 - 2 * cpe->ms_mask[idx];
1405 scale = c * sce1->sf[idx];
1406 for (group = 0; group < ics->group_len[g]; group++)
1407 for (k = offsets[i]; k < offsets[i + 1]; k++)
1408 coef1[group * 128 + k] = scale * coef0[group * 128 + k];
1411 int bt_run_end = sce1->band_type_run_end[idx];
1412 idx += bt_run_end - i;
1416 coef0 += ics->group_len[g] * 128;
1417 coef1 += ics->group_len[g] * 128;
1422 * Decode a channel_pair_element; reference: table 4.4.
1424 * @return Returns error status. 0 - OK, !0 - error
1426 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1428 int i, ret, common_window, ms_present = 0;
1430 common_window = get_bits1(gb);
1431 if (common_window) {
1432 if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
1434 i = cpe->ch[1].ics.use_kb_window[0];
1435 cpe->ch[1].ics = cpe->ch[0].ics;
1436 cpe->ch[1].ics.use_kb_window[1] = i;
1437 ms_present = get_bits(gb, 2);
1438 if (ms_present == 3) {
1439 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1441 } else if (ms_present)
1442 decode_mid_side_stereo(cpe, gb, ms_present);
1444 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1446 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1449 if (common_window) {
1451 apply_mid_side_stereo(ac, cpe);
1452 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1453 apply_prediction(ac, &cpe->ch[0]);
1454 apply_prediction(ac, &cpe->ch[1]);
1458 apply_intensity_stereo(cpe, ms_present);
1462 static const float cce_scale[] = {
1463 1.09050773266525765921, //2^(1/8)
1464 1.18920711500272106672, //2^(1/4)
1470 * Decode coupling_channel_element; reference: table 4.8.
1472 * @return Returns error status. 0 - OK, !0 - error
1474 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1480 SingleChannelElement *sce = &che->ch[0];
1481 ChannelCoupling *coup = &che->coup;
1483 coup->coupling_point = 2 * get_bits1(gb);
1484 coup->num_coupled = get_bits(gb, 3);
1485 for (c = 0; c <= coup->num_coupled; c++) {
1487 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1488 coup->id_select[c] = get_bits(gb, 4);
1489 if (coup->type[c] == TYPE_CPE) {
1490 coup->ch_select[c] = get_bits(gb, 2);
1491 if (coup->ch_select[c] == 3)
1494 coup->ch_select[c] = 2;
1496 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1498 sign = get_bits(gb, 1);
1499 scale = cce_scale[get_bits(gb, 2)];
1501 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1504 for (c = 0; c < num_gain; c++) {
1508 float gain_cache = 1.;
1510 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1511 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1512 gain_cache = powf(scale, -gain);
1514 if (coup->coupling_point == AFTER_IMDCT) {
1515 coup->gain[c][0] = gain_cache;
1517 for (g = 0; g < sce->ics.num_window_groups; g++) {
1518 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1519 if (sce->band_type[idx] != ZERO_BT) {
1521 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1529 gain_cache = powf(scale, -t) * s;
1532 coup->gain[c][idx] = gain_cache;
1542 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1544 * @return Returns number of bytes consumed.
1546 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1550 int num_excl_chan = 0;
1553 for (i = 0; i < 7; i++)
1554 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1555 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1557 return num_excl_chan / 7;
1561 * Decode dynamic range information; reference: table 4.52.
1563 * @param cnt length of TYPE_FIL syntactic element in bytes
1565 * @return Returns number of bytes consumed.
1567 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1568 GetBitContext *gb, int cnt)
1571 int drc_num_bands = 1;
1574 /* pce_tag_present? */
1575 if (get_bits1(gb)) {
1576 che_drc->pce_instance_tag = get_bits(gb, 4);
1577 skip_bits(gb, 4); // tag_reserved_bits
1581 /* excluded_chns_present? */
1582 if (get_bits1(gb)) {
1583 n += decode_drc_channel_exclusions(che_drc, gb);
1586 /* drc_bands_present? */
1587 if (get_bits1(gb)) {
1588 che_drc->band_incr = get_bits(gb, 4);
1589 che_drc->interpolation_scheme = get_bits(gb, 4);
1591 drc_num_bands += che_drc->band_incr;
1592 for (i = 0; i < drc_num_bands; i++) {
1593 che_drc->band_top[i] = get_bits(gb, 8);
1598 /* prog_ref_level_present? */
1599 if (get_bits1(gb)) {
1600 che_drc->prog_ref_level = get_bits(gb, 7);
1601 skip_bits1(gb); // prog_ref_level_reserved_bits
1605 for (i = 0; i < drc_num_bands; i++) {
1606 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1607 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1615 * Decode extension data (incomplete); reference: table 4.51.
1617 * @param cnt length of TYPE_FIL syntactic element in bytes
1619 * @return Returns number of bytes consumed
1621 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1622 ChannelElement *che, enum RawDataBlockType elem_type)
1626 switch (get_bits(gb, 4)) { // extension type
1627 case EXT_SBR_DATA_CRC:
1631 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1633 } else if (!ac->m4ac.sbr) {
1634 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1635 skip_bits_long(gb, 8 * cnt - 4);
1637 } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1638 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1639 skip_bits_long(gb, 8 * cnt - 4);
1641 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1644 output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
1648 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1650 case EXT_DYNAMIC_RANGE:
1651 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1655 case EXT_DATA_ELEMENT:
1657 skip_bits_long(gb, 8 * cnt - 4);
1664 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1666 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1667 * @param coef spectral coefficients
1669 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1670 IndividualChannelStream *ics, int decode)
1672 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1674 int bottom, top, order, start, end, size, inc;
1675 float lpc[TNS_MAX_ORDER];
1677 for (w = 0; w < ics->num_windows; w++) {
1678 bottom = ics->num_swb;
1679 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1681 bottom = FFMAX(0, top - tns->length[w][filt]);
1682 order = tns->order[w][filt];
1687 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1689 start = ics->swb_offset[FFMIN(bottom, mmm)];
1690 end = ics->swb_offset[FFMIN( top, mmm)];
1691 if ((size = end - start) <= 0)
1693 if (tns->direction[w][filt]) {
1702 for (m = 0; m < size; m++, start += inc)
1703 for (i = 1; i <= FFMIN(m, order); i++)
1704 coef[start] -= coef[start - i * inc] * lpc[i - 1];
1710 * Conduct IMDCT and windowing.
1712 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce, float bias)
1714 IndividualChannelStream *ics = &sce->ics;
1715 float *in = sce->coeffs;
1716 float *out = sce->ret;
1717 float *saved = sce->saved;
1718 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1719 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1720 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1721 float *buf = ac->buf_mdct;
1722 float *temp = ac->temp;
1726 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1727 for (i = 0; i < 1024; i += 128)
1728 ff_imdct_half(&ac->mdct_small, buf + i, in + i);
1730 ff_imdct_half(&ac->mdct, buf, in);
1732 /* window overlapping
1733 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1734 * and long to short transitions are considered to be short to short
1735 * transitions. This leaves just two cases (long to long and short to short)
1736 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1738 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
1739 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
1740 ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, bias, 512);
1742 for (i = 0; i < 448; i++)
1743 out[i] = saved[i] + bias;
1745 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1746 ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, bias, 64);
1747 ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, bias, 64);
1748 ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, bias, 64);
1749 ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, bias, 64);
1750 ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, bias, 64);
1751 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
1753 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, bias, 64);
1754 for (i = 576; i < 1024; i++)
1755 out[i] = buf[i-512] + bias;
1760 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1761 for (i = 0; i < 64; i++)
1762 saved[i] = temp[64 + i] - bias;
1763 ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
1764 ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
1765 ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
1766 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1767 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1768 memcpy( saved, buf + 512, 448 * sizeof(float));
1769 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1770 } else { // LONG_STOP or ONLY_LONG
1771 memcpy( saved, buf + 512, 512 * sizeof(float));
1776 * Apply dependent channel coupling (applied before IMDCT).
1778 * @param index index into coupling gain array
1780 static void apply_dependent_coupling(AACContext *ac,
1781 SingleChannelElement *target,
1782 ChannelElement *cce, int index)
1784 IndividualChannelStream *ics = &cce->ch[0].ics;
1785 const uint16_t *offsets = ics->swb_offset;
1786 float *dest = target->coeffs;
1787 const float *src = cce->ch[0].coeffs;
1788 int g, i, group, k, idx = 0;
1789 if (ac->m4ac.object_type == AOT_AAC_LTP) {
1790 av_log(ac->avctx, AV_LOG_ERROR,
1791 "Dependent coupling is not supported together with LTP\n");
1794 for (g = 0; g < ics->num_window_groups; g++) {
1795 for (i = 0; i < ics->max_sfb; i++, idx++) {
1796 if (cce->ch[0].band_type[idx] != ZERO_BT) {
1797 const float gain = cce->coup.gain[index][idx];
1798 for (group = 0; group < ics->group_len[g]; group++) {
1799 for (k = offsets[i]; k < offsets[i + 1]; k++) {
1801 dest[group * 128 + k] += gain * src[group * 128 + k];
1806 dest += ics->group_len[g] * 128;
1807 src += ics->group_len[g] * 128;
1812 * Apply independent channel coupling (applied after IMDCT).
1814 * @param index index into coupling gain array
1816 static void apply_independent_coupling(AACContext *ac,
1817 SingleChannelElement *target,
1818 ChannelElement *cce, int index)
1821 const float gain = cce->coup.gain[index][0];
1822 const float bias = ac->add_bias;
1823 const float *src = cce->ch[0].ret;
1824 float *dest = target->ret;
1825 const int len = 1024 << (ac->m4ac.sbr == 1);
1827 for (i = 0; i < len; i++)
1828 dest[i] += gain * (src[i] - bias);
1832 * channel coupling transformation interface
1834 * @param apply_coupling_method pointer to (in)dependent coupling function
1836 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
1837 enum RawDataBlockType type, int elem_id,
1838 enum CouplingPoint coupling_point,
1839 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
1843 for (i = 0; i < MAX_ELEM_ID; i++) {
1844 ChannelElement *cce = ac->che[TYPE_CCE][i];
1847 if (cce && cce->coup.coupling_point == coupling_point) {
1848 ChannelCoupling *coup = &cce->coup;
1850 for (c = 0; c <= coup->num_coupled; c++) {
1851 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
1852 if (coup->ch_select[c] != 1) {
1853 apply_coupling_method(ac, &cc->ch[0], cce, index);
1854 if (coup->ch_select[c] != 0)
1857 if (coup->ch_select[c] != 2)
1858 apply_coupling_method(ac, &cc->ch[1], cce, index++);
1860 index += 1 + (coup->ch_select[c] == 3);
1867 * Convert spectral data to float samples, applying all supported tools as appropriate.
1869 static void spectral_to_sample(AACContext *ac)
1872 float imdct_bias = (ac->m4ac.sbr <= 0) ? ac->add_bias : 0.0f;
1873 for (type = 3; type >= 0; type--) {
1874 for (i = 0; i < MAX_ELEM_ID; i++) {
1875 ChannelElement *che = ac->che[type][i];
1877 if (type <= TYPE_CPE)
1878 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
1879 if (che->ch[0].tns.present)
1880 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
1881 if (che->ch[1].tns.present)
1882 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
1883 if (type <= TYPE_CPE)
1884 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
1885 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
1886 imdct_and_windowing(ac, &che->ch[0], imdct_bias);
1887 if (type == TYPE_CPE) {
1888 imdct_and_windowing(ac, &che->ch[1], imdct_bias);
1890 if (ac->m4ac.sbr > 0) {
1891 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
1894 if (type <= TYPE_CCE)
1895 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
1901 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
1904 AACADTSHeaderInfo hdr_info;
1906 size = ff_aac_parse_header(gb, &hdr_info);
1908 if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
1909 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1910 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
1911 ac->m4ac.chan_config = hdr_info.chan_config;
1912 if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
1914 if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
1916 } else if (ac->output_configured != OC_LOCKED) {
1917 ac->output_configured = OC_NONE;
1919 if (ac->output_configured != OC_LOCKED) {
1923 ac->m4ac.sample_rate = hdr_info.sample_rate;
1924 ac->m4ac.sampling_index = hdr_info.sampling_index;
1925 ac->m4ac.object_type = hdr_info.object_type;
1926 if (!ac->avctx->sample_rate)
1927 ac->avctx->sample_rate = hdr_info.sample_rate;
1928 if (hdr_info.num_aac_frames == 1) {
1929 if (!hdr_info.crc_absent)
1932 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
1939 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
1940 int *data_size, GetBitContext *gb)
1942 AACContext *ac = avctx->priv_data;
1943 ChannelElement *che = NULL, *che_prev = NULL;
1944 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
1945 int err, elem_id, data_size_tmp;
1946 int samples = 0, multiplier;
1948 if (show_bits(gb, 12) == 0xfff) {
1949 if (parse_adts_frame_header(ac, gb) < 0) {
1950 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
1953 if (ac->m4ac.sampling_index > 12) {
1954 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
1959 ac->tags_mapped = 0;
1961 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
1962 elem_id = get_bits(gb, 4);
1964 if (elem_type < TYPE_DSE) {
1965 if (!(che=get_che(ac, elem_type, elem_id))) {
1966 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
1967 elem_type, elem_id);
1973 switch (elem_type) {
1976 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1980 err = decode_cpe(ac, gb, che);
1984 err = decode_cce(ac, gb, che);
1988 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1992 err = skip_data_stream_element(ac, gb);
1996 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1997 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
1998 if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
2000 if (ac->output_configured > OC_TRIAL_PCE)
2001 av_log(avctx, AV_LOG_ERROR,
2002 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2004 err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
2010 elem_id += get_bits(gb, 8) - 1;
2011 if (get_bits_left(gb) < 8 * elem_id) {
2012 av_log(avctx, AV_LOG_ERROR, overread_err);
2016 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2017 err = 0; /* FIXME */
2021 err = -1; /* should not happen, but keeps compiler happy */
2026 elem_type_prev = elem_type;
2031 if (get_bits_left(gb) < 3) {
2032 av_log(avctx, AV_LOG_ERROR, overread_err);
2037 spectral_to_sample(ac);
2039 multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2040 samples <<= multiplier;
2041 if (ac->output_configured < OC_LOCKED) {
2042 avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2043 avctx->frame_size = samples;
2046 data_size_tmp = samples * avctx->channels * sizeof(int16_t);
2047 if (*data_size < data_size_tmp) {
2048 av_log(avctx, AV_LOG_ERROR,
2049 "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
2050 *data_size, data_size_tmp);
2053 *data_size = data_size_tmp;
2056 ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avctx->channels);
2058 if (ac->output_configured)
2059 ac->output_configured = OC_LOCKED;
2064 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2065 int *data_size, AVPacket *avpkt)
2067 const uint8_t *buf = avpkt->data;
2068 int buf_size = avpkt->size;
2074 init_get_bits(&gb, buf, buf_size * 8);
2076 if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
2079 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2080 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2081 if (buf[buf_offset])
2084 return buf_size > buf_offset ? buf_consumed : buf_size;
2087 static av_cold int aac_decode_close(AVCodecContext *avctx)
2089 AACContext *ac = avctx->priv_data;
2092 for (i = 0; i < MAX_ELEM_ID; i++) {
2093 for (type = 0; type < 4; type++) {
2094 if (ac->che[type][i])
2095 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2096 av_freep(&ac->che[type][i]);
2100 ff_mdct_end(&ac->mdct);
2101 ff_mdct_end(&ac->mdct_small);
2106 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2108 struct LATMContext {
2109 AACContext aac_ctx; ///< containing AACContext
2110 int initialized; ///< initilized after a valid extradata was seen
2113 int audio_mux_version_A; ///< LATM syntax version
2114 int frame_length_type; ///< 0/1 variable/fixed frame length
2115 int frame_length; ///< frame length for fixed frame length
2118 static inline uint32_t latm_get_value(GetBitContext *b)
2120 int length = get_bits(b, 2);
2122 return get_bits_long(b, (length+1)*8);
2125 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2128 AVCodecContext *avctx = latmctx->aac_ctx.avctx;
2129 MPEG4AudioConfig m4ac;
2130 int config_start_bit = get_bits_count(gb);
2131 int bits_consumed, esize;
2133 if (config_start_bit % 8) {
2134 av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2135 "config not byte aligned.\n", 1);
2136 return AVERROR_INVALIDDATA;
2139 decode_audio_specific_config(NULL, avctx, &m4ac,
2140 gb->buffer + (config_start_bit / 8),
2141 get_bits_left(gb) / 8);
2143 if (bits_consumed < 0)
2144 return AVERROR_INVALIDDATA;
2146 esize = (bits_consumed+7) / 8;
2148 if (avctx->extradata_size <= esize) {
2149 av_free(avctx->extradata);
2150 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2151 if (!avctx->extradata)
2152 return AVERROR(ENOMEM);
2155 avctx->extradata_size = esize;
2156 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2157 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2159 skip_bits_long(gb, bits_consumed);
2162 return bits_consumed;
2165 static int read_stream_mux_config(struct LATMContext *latmctx,
2168 int ret, audio_mux_version = get_bits(gb, 1);
2170 latmctx->audio_mux_version_A = 0;
2171 if (audio_mux_version)
2172 latmctx->audio_mux_version_A = get_bits(gb, 1);
2174 if (!latmctx->audio_mux_version_A) {
2176 if (audio_mux_version)
2177 latm_get_value(gb); // taraFullness
2179 skip_bits(gb, 1); // allStreamSameTimeFraming
2180 skip_bits(gb, 6); // numSubFrames
2182 if (get_bits(gb, 4)) { // numPrograms
2183 av_log_missing_feature(latmctx->aac_ctx.avctx,
2184 "multiple programs are not supported\n", 1);
2185 return AVERROR_PATCHWELCOME;
2188 // for each program (which there is only on in DVB)
2190 // for each layer (which there is only on in DVB)
2191 if (get_bits(gb, 3)) { // numLayer
2192 av_log_missing_feature(latmctx->aac_ctx.avctx,
2193 "multiple layers are not supported\n", 1);
2194 return AVERROR_PATCHWELCOME;
2197 // for all but first stream: use_same_config = get_bits(gb, 1);
2198 if (!audio_mux_version) {
2199 if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2202 int ascLen = latm_get_value(gb);
2203 if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2206 skip_bits_long(gb, ascLen);
2209 latmctx->frame_length_type = get_bits(gb, 3);
2210 switch (latmctx->frame_length_type) {
2212 skip_bits(gb, 8); // latmBufferFullness
2215 latmctx->frame_length = get_bits(gb, 9);
2220 skip_bits(gb, 6); // CELP frame length table index
2224 skip_bits(gb, 1); // HVXC frame length table index
2228 if (get_bits(gb, 1)) { // other data
2229 if (audio_mux_version) {
2230 latm_get_value(gb); // other_data_bits
2234 esc = get_bits(gb, 1);
2240 if (get_bits(gb, 1)) // crc present
2241 skip_bits(gb, 8); // config_crc
2247 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2251 if (ctx->frame_length_type == 0) {
2252 int mux_slot_length = 0;
2254 tmp = get_bits(gb, 8);
2255 mux_slot_length += tmp;
2256 } while (tmp == 255);
2257 return mux_slot_length;
2258 } else if (ctx->frame_length_type == 1) {
2259 return ctx->frame_length;
2260 } else if (ctx->frame_length_type == 3 ||
2261 ctx->frame_length_type == 5 ||
2262 ctx->frame_length_type == 7) {
2263 skip_bits(gb, 2); // mux_slot_length_coded
2268 static int read_audio_mux_element(struct LATMContext *latmctx,
2272 uint8_t use_same_mux = get_bits(gb, 1);
2273 if (!use_same_mux) {
2274 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2276 } else if (!latmctx->aac_ctx.avctx->extradata) {
2277 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2278 "no decoder config found\n");
2279 return AVERROR(EAGAIN);
2281 if (latmctx->audio_mux_version_A == 0) {
2282 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2283 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2284 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2285 return AVERROR_INVALIDDATA;
2286 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2287 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2288 "frame length mismatch %d << %d\n",
2289 mux_slot_length_bytes * 8, get_bits_left(gb));
2290 return AVERROR_INVALIDDATA;
2297 static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,
2300 struct LATMContext *latmctx = avctx->priv_data;
2304 if (avpkt->size == 0)
2307 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2309 // check for LOAS sync word
2310 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2311 return AVERROR_INVALIDDATA;
2313 muxlength = get_bits(&gb, 13) + 3;
2314 // not enough data, the parser should have sorted this
2315 if (muxlength > avpkt->size)
2316 return AVERROR_INVALIDDATA;
2318 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2321 if (!latmctx->initialized) {
2322 if (!avctx->extradata) {
2326 if ((err = aac_decode_init(avctx)) < 0)
2328 latmctx->initialized = 1;
2332 if (show_bits(&gb, 12) == 0xfff) {
2333 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2334 "ADTS header detected, probably as result of configuration "
2336 return AVERROR_INVALIDDATA;
2339 if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)
2345 av_cold static int latm_decode_init(AVCodecContext *avctx)
2347 struct LATMContext *latmctx = avctx->priv_data;
2350 ret = aac_decode_init(avctx);
2352 if (avctx->extradata_size > 0) {
2353 latmctx->initialized = !ret;
2355 latmctx->initialized = 0;
2362 AVCodec aac_decoder = {
2371 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2372 .sample_fmts = (const enum AVSampleFormat[]) {
2373 AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
2375 .channel_layouts = aac_channel_layout,
2379 Note: This decoder filter is intended to decode LATM streams transferred
2380 in MPEG transport streams which only contain one program.
2381 To do a more complex LATM demuxing a separate LATM demuxer should be used.
2383 AVCodec aac_latm_decoder = {
2385 .type = CODEC_TYPE_AUDIO,
2386 .id = CODEC_ID_AAC_LATM,
2387 .priv_data_size = sizeof(struct LATMContext),
2388 .init = latm_decode_init,
2389 .close = aac_decode_close,
2390 .decode = latm_decode_frame,
2391 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2392 .sample_fmts = (const enum AVSampleFormat[]) {
2393 AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
2395 .channel_layouts = aac_channel_layout,