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 // 60 - Required to scale values to the correct range [-32768,32767]
570 // for float to int16 conversion. (1 << (60 / 4)) == 32768
571 ac->sf_scale = 1. / -1024.;
576 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
577 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
578 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
581 ff_mdct_init(&ac->mdct, 11, 1, 1.0);
582 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0);
583 // window initialization
584 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
585 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
586 ff_init_ff_sine_windows(10);
587 ff_init_ff_sine_windows( 7);
595 * Skip data_stream_element; reference: table 4.10.
597 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
599 int byte_align = get_bits1(gb);
600 int count = get_bits(gb, 8);
602 count += get_bits(gb, 8);
606 if (get_bits_left(gb) < 8 * count) {
607 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
610 skip_bits_long(gb, 8 * count);
614 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
619 ics->predictor_reset_group = get_bits(gb, 5);
620 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
621 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
625 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
626 ics->prediction_used[sfb] = get_bits1(gb);
632 * Decode Individual Channel Stream info; reference: table 4.6.
634 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
636 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
637 GetBitContext *gb, int common_window)
640 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
641 memset(ics, 0, sizeof(IndividualChannelStream));
644 ics->window_sequence[1] = ics->window_sequence[0];
645 ics->window_sequence[0] = get_bits(gb, 2);
646 ics->use_kb_window[1] = ics->use_kb_window[0];
647 ics->use_kb_window[0] = get_bits1(gb);
648 ics->num_window_groups = 1;
649 ics->group_len[0] = 1;
650 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
652 ics->max_sfb = get_bits(gb, 4);
653 for (i = 0; i < 7; i++) {
655 ics->group_len[ics->num_window_groups - 1]++;
657 ics->num_window_groups++;
658 ics->group_len[ics->num_window_groups - 1] = 1;
661 ics->num_windows = 8;
662 ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
663 ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
664 ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
665 ics->predictor_present = 0;
667 ics->max_sfb = get_bits(gb, 6);
668 ics->num_windows = 1;
669 ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
670 ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
671 ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
672 ics->predictor_present = get_bits1(gb);
673 ics->predictor_reset_group = 0;
674 if (ics->predictor_present) {
675 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
676 if (decode_prediction(ac, ics, gb)) {
677 memset(ics, 0, sizeof(IndividualChannelStream));
680 } else if (ac->m4ac.object_type == AOT_AAC_LC) {
681 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
682 memset(ics, 0, sizeof(IndividualChannelStream));
685 av_log_missing_feature(ac->avctx, "Predictor bit set but LTP is", 1);
686 memset(ics, 0, sizeof(IndividualChannelStream));
692 if (ics->max_sfb > ics->num_swb) {
693 av_log(ac->avctx, AV_LOG_ERROR,
694 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
695 ics->max_sfb, ics->num_swb);
696 memset(ics, 0, sizeof(IndividualChannelStream));
704 * Decode band types (section_data payload); reference: table 4.46.
706 * @param band_type array of the used band type
707 * @param band_type_run_end array of the last scalefactor band of a band type run
709 * @return Returns error status. 0 - OK, !0 - error
711 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
712 int band_type_run_end[120], GetBitContext *gb,
713 IndividualChannelStream *ics)
716 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
717 for (g = 0; g < ics->num_window_groups; g++) {
719 while (k < ics->max_sfb) {
720 uint8_t sect_end = k;
722 int sect_band_type = get_bits(gb, 4);
723 if (sect_band_type == 12) {
724 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
727 while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
728 sect_end += sect_len_incr;
729 sect_end += sect_len_incr;
730 if (get_bits_left(gb) < 0) {
731 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
734 if (sect_end > ics->max_sfb) {
735 av_log(ac->avctx, AV_LOG_ERROR,
736 "Number of bands (%d) exceeds limit (%d).\n",
737 sect_end, ics->max_sfb);
740 for (; k < sect_end; k++) {
741 band_type [idx] = sect_band_type;
742 band_type_run_end[idx++] = sect_end;
750 * Decode scalefactors; reference: table 4.47.
752 * @param global_gain first scalefactor value as scalefactors are differentially coded
753 * @param band_type array of the used band type
754 * @param band_type_run_end array of the last scalefactor band of a band type run
755 * @param sf array of scalefactors or intensity stereo positions
757 * @return Returns error status. 0 - OK, !0 - error
759 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
760 unsigned int global_gain,
761 IndividualChannelStream *ics,
762 enum BandType band_type[120],
763 int band_type_run_end[120])
765 const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
767 int offset[3] = { global_gain, global_gain - 90, 100 };
769 static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
770 for (g = 0; g < ics->num_window_groups; g++) {
771 for (i = 0; i < ics->max_sfb;) {
772 int run_end = band_type_run_end[idx];
773 if (band_type[idx] == ZERO_BT) {
774 for (; i < run_end; i++, idx++)
776 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
777 for (; i < run_end; i++, idx++) {
778 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
779 if (offset[2] > 255U) {
780 av_log(ac->avctx, AV_LOG_ERROR,
781 "%s (%d) out of range.\n", sf_str[2], offset[2]);
784 sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
786 } else if (band_type[idx] == NOISE_BT) {
787 for (; i < run_end; i++, idx++) {
788 if (noise_flag-- > 0)
789 offset[1] += get_bits(gb, 9) - 256;
791 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
792 if (offset[1] > 255U) {
793 av_log(ac->avctx, AV_LOG_ERROR,
794 "%s (%d) out of range.\n", sf_str[1], offset[1]);
797 sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
800 for (; i < run_end; i++, idx++) {
801 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
802 if (offset[0] > 255U) {
803 av_log(ac->avctx, AV_LOG_ERROR,
804 "%s (%d) out of range.\n", sf_str[0], offset[0]);
807 sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
816 * Decode pulse data; reference: table 4.7.
818 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
819 const uint16_t *swb_offset, int num_swb)
822 pulse->num_pulse = get_bits(gb, 2) + 1;
823 pulse_swb = get_bits(gb, 6);
824 if (pulse_swb >= num_swb)
826 pulse->pos[0] = swb_offset[pulse_swb];
827 pulse->pos[0] += get_bits(gb, 5);
828 if (pulse->pos[0] > 1023)
830 pulse->amp[0] = get_bits(gb, 4);
831 for (i = 1; i < pulse->num_pulse; i++) {
832 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
833 if (pulse->pos[i] > 1023)
835 pulse->amp[i] = get_bits(gb, 4);
841 * Decode Temporal Noise Shaping data; reference: table 4.48.
843 * @return Returns error status. 0 - OK, !0 - error
845 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
846 GetBitContext *gb, const IndividualChannelStream *ics)
848 int w, filt, i, coef_len, coef_res, coef_compress;
849 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
850 const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
851 for (w = 0; w < ics->num_windows; w++) {
852 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
853 coef_res = get_bits1(gb);
855 for (filt = 0; filt < tns->n_filt[w]; filt++) {
857 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
859 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
860 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
861 tns->order[w][filt], tns_max_order);
862 tns->order[w][filt] = 0;
865 if (tns->order[w][filt]) {
866 tns->direction[w][filt] = get_bits1(gb);
867 coef_compress = get_bits1(gb);
868 coef_len = coef_res + 3 - coef_compress;
869 tmp2_idx = 2 * coef_compress + coef_res;
871 for (i = 0; i < tns->order[w][filt]; i++)
872 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
881 * Decode Mid/Side data; reference: table 4.54.
883 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
884 * [1] mask is decoded from bitstream; [2] mask is all 1s;
885 * [3] reserved for scalable AAC
887 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
891 if (ms_present == 1) {
892 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
893 cpe->ms_mask[idx] = get_bits1(gb);
894 } else if (ms_present == 2) {
895 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
900 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
904 *dst++ = v[idx & 15] * s;
905 *dst++ = v[idx>>4 & 15] * s;
911 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
915 *dst++ = v[idx & 3] * s;
916 *dst++ = v[idx>>2 & 3] * s;
917 *dst++ = v[idx>>4 & 3] * s;
918 *dst++ = v[idx>>6 & 3] * s;
924 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
925 unsigned sign, const float *scale)
927 union float754 s0, s1;
929 s0.f = s1.f = *scale;
930 s0.i ^= sign >> 1 << 31;
933 *dst++ = v[idx & 15] * s0.f;
934 *dst++ = v[idx>>4 & 15] * s1.f;
941 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
942 unsigned sign, const float *scale)
944 unsigned nz = idx >> 12;
945 union float754 s = { .f = *scale };
948 t.i = s.i ^ (sign & 1<<31);
949 *dst++ = v[idx & 3] * t.f;
951 sign <<= nz & 1; nz >>= 1;
952 t.i = s.i ^ (sign & 1<<31);
953 *dst++ = v[idx>>2 & 3] * t.f;
955 sign <<= nz & 1; nz >>= 1;
956 t.i = s.i ^ (sign & 1<<31);
957 *dst++ = v[idx>>4 & 3] * t.f;
959 sign <<= nz & 1; nz >>= 1;
960 t.i = s.i ^ (sign & 1<<31);
961 *dst++ = v[idx>>6 & 3] * t.f;
968 * Decode spectral data; reference: table 4.50.
969 * Dequantize and scale spectral data; reference: 4.6.3.3.
971 * @param coef array of dequantized, scaled spectral data
972 * @param sf array of scalefactors or intensity stereo positions
973 * @param pulse_present set if pulses are present
974 * @param pulse pointer to pulse data struct
975 * @param band_type array of the used band type
977 * @return Returns error status. 0 - OK, !0 - error
979 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
980 GetBitContext *gb, const float sf[120],
981 int pulse_present, const Pulse *pulse,
982 const IndividualChannelStream *ics,
983 enum BandType band_type[120])
985 int i, k, g, idx = 0;
986 const int c = 1024 / ics->num_windows;
987 const uint16_t *offsets = ics->swb_offset;
988 float *coef_base = coef;
990 for (g = 0; g < ics->num_windows; g++)
991 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
993 for (g = 0; g < ics->num_window_groups; g++) {
994 unsigned g_len = ics->group_len[g];
996 for (i = 0; i < ics->max_sfb; i++, idx++) {
997 const unsigned cbt_m1 = band_type[idx] - 1;
998 float *cfo = coef + offsets[i];
999 int off_len = offsets[i + 1] - offsets[i];
1002 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1003 for (group = 0; group < g_len; group++, cfo+=128) {
1004 memset(cfo, 0, off_len * sizeof(float));
1006 } else if (cbt_m1 == NOISE_BT - 1) {
1007 for (group = 0; group < g_len; group++, cfo+=128) {
1011 for (k = 0; k < off_len; k++) {
1012 ac->random_state = lcg_random(ac->random_state);
1013 cfo[k] = ac->random_state;
1016 band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
1017 scale = sf[idx] / sqrtf(band_energy);
1018 ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1021 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1022 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1023 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1024 OPEN_READER(re, gb);
1026 switch (cbt_m1 >> 1) {
1028 for (group = 0; group < g_len; group++, cfo+=128) {
1036 UPDATE_CACHE(re, gb);
1037 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1038 cb_idx = cb_vector_idx[code];
1039 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1045 for (group = 0; group < g_len; group++, cfo+=128) {
1055 UPDATE_CACHE(re, gb);
1056 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1057 cb_idx = cb_vector_idx[code];
1058 nnz = cb_idx >> 8 & 15;
1059 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1060 LAST_SKIP_BITS(re, gb, nnz);
1061 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1067 for (group = 0; group < g_len; group++, cfo+=128) {
1075 UPDATE_CACHE(re, gb);
1076 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1077 cb_idx = cb_vector_idx[code];
1078 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1085 for (group = 0; group < g_len; group++, cfo+=128) {
1095 UPDATE_CACHE(re, gb);
1096 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1097 cb_idx = cb_vector_idx[code];
1098 nnz = cb_idx >> 8 & 15;
1099 sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
1100 LAST_SKIP_BITS(re, gb, nnz);
1101 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1107 for (group = 0; group < g_len; group++, cfo+=128) {
1109 uint32_t *icf = (uint32_t *) cf;
1119 UPDATE_CACHE(re, gb);
1120 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1128 cb_idx = cb_vector_idx[code];
1131 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1132 LAST_SKIP_BITS(re, gb, nnz);
1134 for (j = 0; j < 2; j++) {
1138 /* The total length of escape_sequence must be < 22 bits according
1139 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1140 UPDATE_CACHE(re, gb);
1141 b = GET_CACHE(re, gb);
1142 b = 31 - av_log2(~b);
1145 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1149 SKIP_BITS(re, gb, b + 1);
1151 n = (1 << b) + SHOW_UBITS(re, gb, b);
1152 LAST_SKIP_BITS(re, gb, b);
1153 *icf++ = cbrt_tab[n] | (bits & 1<<31);
1156 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1157 *icf++ = (bits & 1<<31) | v;
1164 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1168 CLOSE_READER(re, gb);
1174 if (pulse_present) {
1176 for (i = 0; i < pulse->num_pulse; i++) {
1177 float co = coef_base[ pulse->pos[i] ];
1178 while (offsets[idx + 1] <= pulse->pos[i])
1180 if (band_type[idx] != NOISE_BT && sf[idx]) {
1181 float ico = -pulse->amp[i];
1184 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1186 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1193 static av_always_inline float flt16_round(float pf)
1197 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1201 static av_always_inline float flt16_even(float pf)
1205 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1209 static av_always_inline float flt16_trunc(float pf)
1213 pun.i &= 0xFFFF0000U;
1217 static av_always_inline void predict(PredictorState *ps, float *coef,
1218 float sf_scale, float inv_sf_scale,
1221 const float a = 0.953125; // 61.0 / 64
1222 const float alpha = 0.90625; // 29.0 / 32
1226 float r0 = ps->r0, r1 = ps->r1;
1227 float cor0 = ps->cor0, cor1 = ps->cor1;
1228 float var0 = ps->var0, var1 = ps->var1;
1230 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1231 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1233 pv = flt16_round(k1 * r0 + k2 * r1);
1235 *coef += pv * sf_scale;
1237 e0 = *coef * inv_sf_scale;
1240 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1241 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1242 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1243 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1245 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1246 ps->r0 = flt16_trunc(a * e0);
1250 * Apply AAC-Main style frequency domain prediction.
1252 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1255 float sf_scale = ac->sf_scale, inv_sf_scale = 1 / ac->sf_scale;
1257 if (!sce->ics.predictor_initialized) {
1258 reset_all_predictors(sce->predictor_state);
1259 sce->ics.predictor_initialized = 1;
1262 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1263 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1264 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
1265 predict(&sce->predictor_state[k], &sce->coeffs[k],
1266 sf_scale, inv_sf_scale,
1267 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
1270 if (sce->ics.predictor_reset_group)
1271 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
1273 reset_all_predictors(sce->predictor_state);
1277 * Decode an individual_channel_stream payload; reference: table 4.44.
1279 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1280 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1282 * @return Returns error status. 0 - OK, !0 - error
1284 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1285 GetBitContext *gb, int common_window, int scale_flag)
1288 TemporalNoiseShaping *tns = &sce->tns;
1289 IndividualChannelStream *ics = &sce->ics;
1290 float *out = sce->coeffs;
1291 int global_gain, pulse_present = 0;
1293 /* This assignment is to silence a GCC warning about the variable being used
1294 * uninitialized when in fact it always is.
1296 pulse.num_pulse = 0;
1298 global_gain = get_bits(gb, 8);
1300 if (!common_window && !scale_flag) {
1301 if (decode_ics_info(ac, ics, gb, 0) < 0)
1305 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1307 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1312 if ((pulse_present = get_bits1(gb))) {
1313 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1314 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
1317 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1318 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
1322 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1324 if (get_bits1(gb)) {
1325 av_log_missing_feature(ac->avctx, "SSR", 1);
1330 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
1333 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
1334 apply_prediction(ac, sce);
1340 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1342 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1344 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1345 float *ch0 = cpe->ch[0].coeffs;
1346 float *ch1 = cpe->ch[1].coeffs;
1347 int g, i, group, idx = 0;
1348 const uint16_t *offsets = ics->swb_offset;
1349 for (g = 0; g < ics->num_window_groups; g++) {
1350 for (i = 0; i < ics->max_sfb; i++, idx++) {
1351 if (cpe->ms_mask[idx] &&
1352 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
1353 for (group = 0; group < ics->group_len[g]; group++) {
1354 ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1355 ch1 + group * 128 + offsets[i],
1356 offsets[i+1] - offsets[i]);
1360 ch0 += ics->group_len[g] * 128;
1361 ch1 += ics->group_len[g] * 128;
1366 * intensity stereo decoding; reference: 4.6.8.2.3
1368 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1369 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1370 * [3] reserved for scalable AAC
1372 static void apply_intensity_stereo(ChannelElement *cpe, int ms_present)
1374 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1375 SingleChannelElement *sce1 = &cpe->ch[1];
1376 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1377 const uint16_t *offsets = ics->swb_offset;
1378 int g, group, i, k, idx = 0;
1381 for (g = 0; g < ics->num_window_groups; g++) {
1382 for (i = 0; i < ics->max_sfb;) {
1383 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1384 const int bt_run_end = sce1->band_type_run_end[idx];
1385 for (; i < bt_run_end; i++, idx++) {
1386 c = -1 + 2 * (sce1->band_type[idx] - 14);
1388 c *= 1 - 2 * cpe->ms_mask[idx];
1389 scale = c * sce1->sf[idx];
1390 for (group = 0; group < ics->group_len[g]; group++)
1391 for (k = offsets[i]; k < offsets[i + 1]; k++)
1392 coef1[group * 128 + k] = scale * coef0[group * 128 + k];
1395 int bt_run_end = sce1->band_type_run_end[idx];
1396 idx += bt_run_end - i;
1400 coef0 += ics->group_len[g] * 128;
1401 coef1 += ics->group_len[g] * 128;
1406 * Decode a channel_pair_element; reference: table 4.4.
1408 * @return Returns error status. 0 - OK, !0 - error
1410 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1412 int i, ret, common_window, ms_present = 0;
1414 common_window = get_bits1(gb);
1415 if (common_window) {
1416 if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
1418 i = cpe->ch[1].ics.use_kb_window[0];
1419 cpe->ch[1].ics = cpe->ch[0].ics;
1420 cpe->ch[1].ics.use_kb_window[1] = i;
1421 ms_present = get_bits(gb, 2);
1422 if (ms_present == 3) {
1423 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1425 } else if (ms_present)
1426 decode_mid_side_stereo(cpe, gb, ms_present);
1428 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1430 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1433 if (common_window) {
1435 apply_mid_side_stereo(ac, cpe);
1436 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1437 apply_prediction(ac, &cpe->ch[0]);
1438 apply_prediction(ac, &cpe->ch[1]);
1442 apply_intensity_stereo(cpe, ms_present);
1446 static const float cce_scale[] = {
1447 1.09050773266525765921, //2^(1/8)
1448 1.18920711500272106672, //2^(1/4)
1454 * Decode coupling_channel_element; reference: table 4.8.
1456 * @return Returns error status. 0 - OK, !0 - error
1458 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1464 SingleChannelElement *sce = &che->ch[0];
1465 ChannelCoupling *coup = &che->coup;
1467 coup->coupling_point = 2 * get_bits1(gb);
1468 coup->num_coupled = get_bits(gb, 3);
1469 for (c = 0; c <= coup->num_coupled; c++) {
1471 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1472 coup->id_select[c] = get_bits(gb, 4);
1473 if (coup->type[c] == TYPE_CPE) {
1474 coup->ch_select[c] = get_bits(gb, 2);
1475 if (coup->ch_select[c] == 3)
1478 coup->ch_select[c] = 2;
1480 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1482 sign = get_bits(gb, 1);
1483 scale = cce_scale[get_bits(gb, 2)];
1485 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1488 for (c = 0; c < num_gain; c++) {
1492 float gain_cache = 1.;
1494 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1495 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1496 gain_cache = powf(scale, -gain);
1498 if (coup->coupling_point == AFTER_IMDCT) {
1499 coup->gain[c][0] = gain_cache;
1501 for (g = 0; g < sce->ics.num_window_groups; g++) {
1502 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1503 if (sce->band_type[idx] != ZERO_BT) {
1505 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1513 gain_cache = powf(scale, -t) * s;
1516 coup->gain[c][idx] = gain_cache;
1526 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1528 * @return Returns number of bytes consumed.
1530 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1534 int num_excl_chan = 0;
1537 for (i = 0; i < 7; i++)
1538 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1539 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1541 return num_excl_chan / 7;
1545 * Decode dynamic range information; reference: table 4.52.
1547 * @param cnt length of TYPE_FIL syntactic element in bytes
1549 * @return Returns number of bytes consumed.
1551 static int decode_dynamic_range(DynamicRangeControl *che_drc,
1552 GetBitContext *gb, int cnt)
1555 int drc_num_bands = 1;
1558 /* pce_tag_present? */
1559 if (get_bits1(gb)) {
1560 che_drc->pce_instance_tag = get_bits(gb, 4);
1561 skip_bits(gb, 4); // tag_reserved_bits
1565 /* excluded_chns_present? */
1566 if (get_bits1(gb)) {
1567 n += decode_drc_channel_exclusions(che_drc, gb);
1570 /* drc_bands_present? */
1571 if (get_bits1(gb)) {
1572 che_drc->band_incr = get_bits(gb, 4);
1573 che_drc->interpolation_scheme = get_bits(gb, 4);
1575 drc_num_bands += che_drc->band_incr;
1576 for (i = 0; i < drc_num_bands; i++) {
1577 che_drc->band_top[i] = get_bits(gb, 8);
1582 /* prog_ref_level_present? */
1583 if (get_bits1(gb)) {
1584 che_drc->prog_ref_level = get_bits(gb, 7);
1585 skip_bits1(gb); // prog_ref_level_reserved_bits
1589 for (i = 0; i < drc_num_bands; i++) {
1590 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1591 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1599 * Decode extension data (incomplete); reference: table 4.51.
1601 * @param cnt length of TYPE_FIL syntactic element in bytes
1603 * @return Returns number of bytes consumed
1605 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1606 ChannelElement *che, enum RawDataBlockType elem_type)
1610 switch (get_bits(gb, 4)) { // extension type
1611 case EXT_SBR_DATA_CRC:
1615 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
1617 } else if (!ac->m4ac.sbr) {
1618 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
1619 skip_bits_long(gb, 8 * cnt - 4);
1621 } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
1622 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
1623 skip_bits_long(gb, 8 * cnt - 4);
1625 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1628 output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
1632 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
1634 case EXT_DYNAMIC_RANGE:
1635 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1639 case EXT_DATA_ELEMENT:
1641 skip_bits_long(gb, 8 * cnt - 4);
1648 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1650 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1651 * @param coef spectral coefficients
1653 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1654 IndividualChannelStream *ics, int decode)
1656 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1658 int bottom, top, order, start, end, size, inc;
1659 float lpc[TNS_MAX_ORDER];
1661 for (w = 0; w < ics->num_windows; w++) {
1662 bottom = ics->num_swb;
1663 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1665 bottom = FFMAX(0, top - tns->length[w][filt]);
1666 order = tns->order[w][filt];
1671 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
1673 start = ics->swb_offset[FFMIN(bottom, mmm)];
1674 end = ics->swb_offset[FFMIN( top, mmm)];
1675 if ((size = end - start) <= 0)
1677 if (tns->direction[w][filt]) {
1686 for (m = 0; m < size; m++, start += inc)
1687 for (i = 1; i <= FFMIN(m, order); i++)
1688 coef[start] -= coef[start - i * inc] * lpc[i - 1];
1694 * Conduct IMDCT and windowing.
1696 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
1698 IndividualChannelStream *ics = &sce->ics;
1699 float *in = sce->coeffs;
1700 float *out = sce->ret;
1701 float *saved = sce->saved;
1702 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1703 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1704 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1705 float *buf = ac->buf_mdct;
1706 float *temp = ac->temp;
1710 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1711 for (i = 0; i < 1024; i += 128)
1712 ff_imdct_half(&ac->mdct_small, buf + i, in + i);
1714 ff_imdct_half(&ac->mdct, buf, in);
1716 /* window overlapping
1717 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1718 * and long to short transitions are considered to be short to short
1719 * transitions. This leaves just two cases (long to long and short to short)
1720 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1722 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
1723 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
1724 ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, 0, 512);
1726 for (i = 0; i < 448; i++)
1729 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1730 ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 0, 64);
1731 ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 0, 64);
1732 ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 0, 64);
1733 ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 0, 64);
1734 ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 0, 64);
1735 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
1737 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 0, 64);
1738 for (i = 576; i < 1024; i++)
1739 out[i] = buf[i-512];
1744 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1745 for (i = 0; i < 64; i++)
1746 saved[i] = temp[64 + i];
1747 ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
1748 ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
1749 ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
1750 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1751 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1752 memcpy( saved, buf + 512, 448 * sizeof(float));
1753 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
1754 } else { // LONG_STOP or ONLY_LONG
1755 memcpy( saved, buf + 512, 512 * sizeof(float));
1760 * Apply dependent channel coupling (applied before IMDCT).
1762 * @param index index into coupling gain array
1764 static void apply_dependent_coupling(AACContext *ac,
1765 SingleChannelElement *target,
1766 ChannelElement *cce, int index)
1768 IndividualChannelStream *ics = &cce->ch[0].ics;
1769 const uint16_t *offsets = ics->swb_offset;
1770 float *dest = target->coeffs;
1771 const float *src = cce->ch[0].coeffs;
1772 int g, i, group, k, idx = 0;
1773 if (ac->m4ac.object_type == AOT_AAC_LTP) {
1774 av_log(ac->avctx, AV_LOG_ERROR,
1775 "Dependent coupling is not supported together with LTP\n");
1778 for (g = 0; g < ics->num_window_groups; g++) {
1779 for (i = 0; i < ics->max_sfb; i++, idx++) {
1780 if (cce->ch[0].band_type[idx] != ZERO_BT) {
1781 const float gain = cce->coup.gain[index][idx];
1782 for (group = 0; group < ics->group_len[g]; group++) {
1783 for (k = offsets[i]; k < offsets[i + 1]; k++) {
1785 dest[group * 128 + k] += gain * src[group * 128 + k];
1790 dest += ics->group_len[g] * 128;
1791 src += ics->group_len[g] * 128;
1796 * Apply independent channel coupling (applied after IMDCT).
1798 * @param index index into coupling gain array
1800 static void apply_independent_coupling(AACContext *ac,
1801 SingleChannelElement *target,
1802 ChannelElement *cce, int index)
1805 const float gain = cce->coup.gain[index][0];
1806 const float *src = cce->ch[0].ret;
1807 float *dest = target->ret;
1808 const int len = 1024 << (ac->m4ac.sbr == 1);
1810 for (i = 0; i < len; i++)
1811 dest[i] += gain * src[i];
1815 * channel coupling transformation interface
1817 * @param apply_coupling_method pointer to (in)dependent coupling function
1819 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
1820 enum RawDataBlockType type, int elem_id,
1821 enum CouplingPoint coupling_point,
1822 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
1826 for (i = 0; i < MAX_ELEM_ID; i++) {
1827 ChannelElement *cce = ac->che[TYPE_CCE][i];
1830 if (cce && cce->coup.coupling_point == coupling_point) {
1831 ChannelCoupling *coup = &cce->coup;
1833 for (c = 0; c <= coup->num_coupled; c++) {
1834 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
1835 if (coup->ch_select[c] != 1) {
1836 apply_coupling_method(ac, &cc->ch[0], cce, index);
1837 if (coup->ch_select[c] != 0)
1840 if (coup->ch_select[c] != 2)
1841 apply_coupling_method(ac, &cc->ch[1], cce, index++);
1843 index += 1 + (coup->ch_select[c] == 3);
1850 * Convert spectral data to float samples, applying all supported tools as appropriate.
1852 static void spectral_to_sample(AACContext *ac)
1855 for (type = 3; type >= 0; type--) {
1856 for (i = 0; i < MAX_ELEM_ID; i++) {
1857 ChannelElement *che = ac->che[type][i];
1859 if (type <= TYPE_CPE)
1860 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
1861 if (che->ch[0].tns.present)
1862 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
1863 if (che->ch[1].tns.present)
1864 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
1865 if (type <= TYPE_CPE)
1866 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
1867 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
1868 imdct_and_windowing(ac, &che->ch[0]);
1869 if (type == TYPE_CPE) {
1870 imdct_and_windowing(ac, &che->ch[1]);
1872 if (ac->m4ac.sbr > 0) {
1873 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
1876 if (type <= TYPE_CCE)
1877 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
1883 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
1886 AACADTSHeaderInfo hdr_info;
1888 size = ff_aac_parse_header(gb, &hdr_info);
1890 if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
1891 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1892 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
1893 ac->m4ac.chan_config = hdr_info.chan_config;
1894 if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
1896 if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
1898 } else if (ac->output_configured != OC_LOCKED) {
1899 ac->output_configured = OC_NONE;
1901 if (ac->output_configured != OC_LOCKED) {
1905 ac->m4ac.sample_rate = hdr_info.sample_rate;
1906 ac->m4ac.sampling_index = hdr_info.sampling_index;
1907 ac->m4ac.object_type = hdr_info.object_type;
1908 if (!ac->avctx->sample_rate)
1909 ac->avctx->sample_rate = hdr_info.sample_rate;
1910 if (hdr_info.num_aac_frames == 1) {
1911 if (!hdr_info.crc_absent)
1914 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
1921 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
1922 int *data_size, GetBitContext *gb)
1924 AACContext *ac = avctx->priv_data;
1925 ChannelElement *che = NULL, *che_prev = NULL;
1926 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
1927 int err, elem_id, data_size_tmp;
1928 int samples = 0, multiplier;
1930 if (show_bits(gb, 12) == 0xfff) {
1931 if (parse_adts_frame_header(ac, gb) < 0) {
1932 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
1935 if (ac->m4ac.sampling_index > 12) {
1936 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
1941 ac->tags_mapped = 0;
1943 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
1944 elem_id = get_bits(gb, 4);
1946 if (elem_type < TYPE_DSE) {
1947 if (!(che=get_che(ac, elem_type, elem_id))) {
1948 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
1949 elem_type, elem_id);
1955 switch (elem_type) {
1958 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1962 err = decode_cpe(ac, gb, che);
1966 err = decode_cce(ac, gb, che);
1970 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
1974 err = skip_data_stream_element(ac, gb);
1978 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1979 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
1980 if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
1982 if (ac->output_configured > OC_TRIAL_PCE)
1983 av_log(avctx, AV_LOG_ERROR,
1984 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
1986 err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
1992 elem_id += get_bits(gb, 8) - 1;
1993 if (get_bits_left(gb) < 8 * elem_id) {
1994 av_log(avctx, AV_LOG_ERROR, overread_err);
1998 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
1999 err = 0; /* FIXME */
2003 err = -1; /* should not happen, but keeps compiler happy */
2008 elem_type_prev = elem_type;
2013 if (get_bits_left(gb) < 3) {
2014 av_log(avctx, AV_LOG_ERROR, overread_err);
2019 spectral_to_sample(ac);
2021 multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
2022 samples <<= multiplier;
2023 if (ac->output_configured < OC_LOCKED) {
2024 avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2025 avctx->frame_size = samples;
2028 data_size_tmp = samples * avctx->channels * sizeof(int16_t);
2029 if (*data_size < data_size_tmp) {
2030 av_log(avctx, AV_LOG_ERROR,
2031 "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
2032 *data_size, data_size_tmp);
2035 *data_size = data_size_tmp;
2038 ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avctx->channels);
2040 if (ac->output_configured)
2041 ac->output_configured = OC_LOCKED;
2046 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2047 int *data_size, AVPacket *avpkt)
2049 const uint8_t *buf = avpkt->data;
2050 int buf_size = avpkt->size;
2056 init_get_bits(&gb, buf, buf_size * 8);
2058 if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
2061 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2062 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2063 if (buf[buf_offset])
2066 return buf_size > buf_offset ? buf_consumed : buf_size;
2069 static av_cold int aac_decode_close(AVCodecContext *avctx)
2071 AACContext *ac = avctx->priv_data;
2074 for (i = 0; i < MAX_ELEM_ID; i++) {
2075 for (type = 0; type < 4; type++) {
2076 if (ac->che[type][i])
2077 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2078 av_freep(&ac->che[type][i]);
2082 ff_mdct_end(&ac->mdct);
2083 ff_mdct_end(&ac->mdct_small);
2088 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2090 struct LATMContext {
2091 AACContext aac_ctx; ///< containing AACContext
2092 int initialized; ///< initilized after a valid extradata was seen
2095 int audio_mux_version_A; ///< LATM syntax version
2096 int frame_length_type; ///< 0/1 variable/fixed frame length
2097 int frame_length; ///< frame length for fixed frame length
2100 static inline uint32_t latm_get_value(GetBitContext *b)
2102 int length = get_bits(b, 2);
2104 return get_bits_long(b, (length+1)*8);
2107 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2110 AVCodecContext *avctx = latmctx->aac_ctx.avctx;
2111 MPEG4AudioConfig m4ac;
2112 int config_start_bit = get_bits_count(gb);
2113 int bits_consumed, esize;
2115 if (config_start_bit % 8) {
2116 av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2117 "config not byte aligned.\n", 1);
2118 return AVERROR_INVALIDDATA;
2121 decode_audio_specific_config(NULL, avctx, &m4ac,
2122 gb->buffer + (config_start_bit / 8),
2123 get_bits_left(gb) / 8);
2125 if (bits_consumed < 0)
2126 return AVERROR_INVALIDDATA;
2128 esize = (bits_consumed+7) / 8;
2130 if (avctx->extradata_size <= esize) {
2131 av_free(avctx->extradata);
2132 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2133 if (!avctx->extradata)
2134 return AVERROR(ENOMEM);
2137 avctx->extradata_size = esize;
2138 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2139 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2141 skip_bits_long(gb, bits_consumed);
2144 return bits_consumed;
2147 static int read_stream_mux_config(struct LATMContext *latmctx,
2150 int ret, audio_mux_version = get_bits(gb, 1);
2152 latmctx->audio_mux_version_A = 0;
2153 if (audio_mux_version)
2154 latmctx->audio_mux_version_A = get_bits(gb, 1);
2156 if (!latmctx->audio_mux_version_A) {
2158 if (audio_mux_version)
2159 latm_get_value(gb); // taraFullness
2161 skip_bits(gb, 1); // allStreamSameTimeFraming
2162 skip_bits(gb, 6); // numSubFrames
2164 if (get_bits(gb, 4)) { // numPrograms
2165 av_log_missing_feature(latmctx->aac_ctx.avctx,
2166 "multiple programs are not supported\n", 1);
2167 return AVERROR_PATCHWELCOME;
2170 // for each program (which there is only on in DVB)
2172 // for each layer (which there is only on in DVB)
2173 if (get_bits(gb, 3)) { // numLayer
2174 av_log_missing_feature(latmctx->aac_ctx.avctx,
2175 "multiple layers are not supported\n", 1);
2176 return AVERROR_PATCHWELCOME;
2179 // for all but first stream: use_same_config = get_bits(gb, 1);
2180 if (!audio_mux_version) {
2181 if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2184 int ascLen = latm_get_value(gb);
2185 if ((ret = latm_decode_audio_specific_config(latmctx, gb)) < 0)
2188 skip_bits_long(gb, ascLen);
2191 latmctx->frame_length_type = get_bits(gb, 3);
2192 switch (latmctx->frame_length_type) {
2194 skip_bits(gb, 8); // latmBufferFullness
2197 latmctx->frame_length = get_bits(gb, 9);
2202 skip_bits(gb, 6); // CELP frame length table index
2206 skip_bits(gb, 1); // HVXC frame length table index
2210 if (get_bits(gb, 1)) { // other data
2211 if (audio_mux_version) {
2212 latm_get_value(gb); // other_data_bits
2216 esc = get_bits(gb, 1);
2222 if (get_bits(gb, 1)) // crc present
2223 skip_bits(gb, 8); // config_crc
2229 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2233 if (ctx->frame_length_type == 0) {
2234 int mux_slot_length = 0;
2236 tmp = get_bits(gb, 8);
2237 mux_slot_length += tmp;
2238 } while (tmp == 255);
2239 return mux_slot_length;
2240 } else if (ctx->frame_length_type == 1) {
2241 return ctx->frame_length;
2242 } else if (ctx->frame_length_type == 3 ||
2243 ctx->frame_length_type == 5 ||
2244 ctx->frame_length_type == 7) {
2245 skip_bits(gb, 2); // mux_slot_length_coded
2250 static int read_audio_mux_element(struct LATMContext *latmctx,
2254 uint8_t use_same_mux = get_bits(gb, 1);
2255 if (!use_same_mux) {
2256 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2258 } else if (!latmctx->aac_ctx.avctx->extradata) {
2259 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2260 "no decoder config found\n");
2261 return AVERROR(EAGAIN);
2263 if (latmctx->audio_mux_version_A == 0) {
2264 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2265 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2266 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2267 return AVERROR_INVALIDDATA;
2268 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2269 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2270 "frame length mismatch %d << %d\n",
2271 mux_slot_length_bytes * 8, get_bits_left(gb));
2272 return AVERROR_INVALIDDATA;
2279 static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,
2282 struct LATMContext *latmctx = avctx->priv_data;
2286 if (avpkt->size == 0)
2289 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2291 // check for LOAS sync word
2292 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2293 return AVERROR_INVALIDDATA;
2295 muxlength = get_bits(&gb, 13) + 3;
2296 // not enough data, the parser should have sorted this
2297 if (muxlength > avpkt->size)
2298 return AVERROR_INVALIDDATA;
2300 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2303 if (!latmctx->initialized) {
2304 if (!avctx->extradata) {
2308 if ((err = aac_decode_init(avctx)) < 0)
2310 latmctx->initialized = 1;
2314 if (show_bits(&gb, 12) == 0xfff) {
2315 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2316 "ADTS header detected, probably as result of configuration "
2318 return AVERROR_INVALIDDATA;
2321 if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)
2327 av_cold static int latm_decode_init(AVCodecContext *avctx)
2329 struct LATMContext *latmctx = avctx->priv_data;
2332 ret = aac_decode_init(avctx);
2334 if (avctx->extradata_size > 0) {
2335 latmctx->initialized = !ret;
2337 latmctx->initialized = 0;
2344 AVCodec ff_aac_decoder = {
2353 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
2354 .sample_fmts = (const enum AVSampleFormat[]) {
2355 AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
2357 .channel_layouts = aac_channel_layout,
2361 Note: This decoder filter is intended to decode LATM streams transferred
2362 in MPEG transport streams which only contain one program.
2363 To do a more complex LATM demuxing a separate LATM demuxer should be used.
2365 AVCodec ff_aac_latm_decoder = {
2367 .type = CODEC_TYPE_AUDIO,
2368 .id = CODEC_ID_AAC_LATM,
2369 .priv_data_size = sizeof(struct LATMContext),
2370 .init = latm_decode_init,
2371 .close = aac_decode_close,
2372 .decode = latm_decode_frame,
2373 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
2374 .sample_fmts = (const enum AVSampleFormat[]) {
2375 AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE
2377 .channel_layouts = aac_channel_layout,