3 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
7 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8 * Copyright (c) 2010 Janne Grunau <janne-libav@jannau.net>
10 * This file is part of Libav.
12 * Libav is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * Libav is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with Libav; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 * @author Oded Shimon ( ods15 ods15 dyndns org )
31 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
38 * N (code in SoC repo) gain control
40 * Y window shapes - standard
41 * N window shapes - Low Delay
42 * Y filterbank - standard
43 * N (code in SoC repo) filterbank - Scalable Sample Rate
44 * Y Temporal Noise Shaping
45 * Y Long Term Prediction
48 * Y frequency domain prediction
49 * Y Perceptual Noise Substitution
51 * N Scalable Inverse AAC Quantization
52 * N Frequency Selective Switch
54 * Y quantization & coding - AAC
55 * N quantization & coding - TwinVQ
56 * N quantization & coding - BSAC
57 * N AAC Error Resilience tools
58 * N Error Resilience payload syntax
59 * N Error Protection tool
61 * N Silence Compression
64 * N Structured Audio tools
65 * N Structured Audio Sample Bank Format
67 * N Harmonic and Individual Lines plus Noise
68 * N Text-To-Speech Interface
69 * Y Spectral Band Replication
70 * Y (not in this code) Layer-1
71 * Y (not in this code) Layer-2
72 * Y (not in this code) Layer-3
73 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
75 * N Direct Stream Transfer
77 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
82 #include "libavutil/float_dsp.h"
87 #include "fmtconvert.h"
94 #include "aacdectab.h"
95 #include "cbrt_tablegen.h"
98 #include "mpeg4audio.h"
99 #include "aacadtsdec.h"
100 #include "libavutil/intfloat.h"
108 # include "arm/aac.h"
111 static VLC vlc_scalefactors;
112 static VLC vlc_spectral[11];
114 static const char overread_err[] = "Input buffer exhausted before END element found\n";
116 static int count_channels(uint8_t (*layout)[3], int tags)
119 for (i = 0; i < tags; i++) {
120 int syn_ele = layout[i][0];
121 int pos = layout[i][2];
122 sum += (1 + (syn_ele == TYPE_CPE)) *
123 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
129 * Check for the channel element in the current channel position configuration.
130 * If it exists, make sure the appropriate element is allocated and map the
131 * channel order to match the internal Libav channel layout.
133 * @param che_pos current channel position configuration
134 * @param type channel element type
135 * @param id channel element id
136 * @param channels count of the number of channels in the configuration
138 * @return Returns error status. 0 - OK, !0 - error
140 static av_cold int che_configure(AACContext *ac,
141 enum ChannelPosition che_pos,
142 int type, int id, int *channels)
144 if (*channels >= MAX_CHANNELS)
145 return AVERROR_INVALIDDATA;
147 if (!ac->che[type][id]) {
148 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
149 return AVERROR(ENOMEM);
150 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
152 if (type != TYPE_CCE) {
153 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
154 if (type == TYPE_CPE ||
155 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
156 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
160 if (ac->che[type][id])
161 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
162 av_freep(&ac->che[type][id]);
167 static int frame_configure_elements(AVCodecContext *avctx)
169 AACContext *ac = avctx->priv_data;
170 int type, id, ch, ret;
172 /* set channel pointers to internal buffers by default */
173 for (type = 0; type < 4; type++) {
174 for (id = 0; id < MAX_ELEM_ID; id++) {
175 ChannelElement *che = ac->che[type][id];
177 che->ch[0].ret = che->ch[0].ret_buf;
178 che->ch[1].ret = che->ch[1].ret_buf;
183 /* get output buffer */
184 av_frame_unref(ac->frame);
185 ac->frame->nb_samples = 2048;
186 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0) {
187 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
191 /* map output channel pointers to AVFrame data */
192 for (ch = 0; ch < avctx->channels; ch++) {
193 if (ac->output_element[ch])
194 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
200 struct elem_to_channel {
201 uint64_t av_position;
204 uint8_t aac_position;
207 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
208 uint8_t (*layout_map)[3], int offset, uint64_t left,
209 uint64_t right, int pos)
211 if (layout_map[offset][0] == TYPE_CPE) {
212 e2c_vec[offset] = (struct elem_to_channel) {
213 .av_position = left | right,
215 .elem_id = layout_map[offset][1],
220 e2c_vec[offset] = (struct elem_to_channel) {
223 .elem_id = layout_map[offset][1],
226 e2c_vec[offset + 1] = (struct elem_to_channel) {
227 .av_position = right,
229 .elem_id = layout_map[offset + 1][1],
236 static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
239 int num_pos_channels = 0;
243 for (i = *current; i < tags; i++) {
244 if (layout_map[i][2] != pos)
246 if (layout_map[i][0] == TYPE_CPE) {
248 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
254 num_pos_channels += 2;
262 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
265 return num_pos_channels;
268 static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
270 int i, n, total_non_cc_elements;
271 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
272 int num_front_channels, num_side_channels, num_back_channels;
275 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
280 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
281 if (num_front_channels < 0)
284 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
285 if (num_side_channels < 0)
288 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
289 if (num_back_channels < 0)
293 if (num_front_channels & 1) {
294 e2c_vec[i] = (struct elem_to_channel) {
295 .av_position = AV_CH_FRONT_CENTER,
297 .elem_id = layout_map[i][1],
298 .aac_position = AAC_CHANNEL_FRONT
301 num_front_channels--;
303 if (num_front_channels >= 4) {
304 i += assign_pair(e2c_vec, layout_map, i,
305 AV_CH_FRONT_LEFT_OF_CENTER,
306 AV_CH_FRONT_RIGHT_OF_CENTER,
308 num_front_channels -= 2;
310 if (num_front_channels >= 2) {
311 i += assign_pair(e2c_vec, layout_map, i,
315 num_front_channels -= 2;
317 while (num_front_channels >= 2) {
318 i += assign_pair(e2c_vec, layout_map, i,
322 num_front_channels -= 2;
325 if (num_side_channels >= 2) {
326 i += assign_pair(e2c_vec, layout_map, i,
330 num_side_channels -= 2;
332 while (num_side_channels >= 2) {
333 i += assign_pair(e2c_vec, layout_map, i,
337 num_side_channels -= 2;
340 while (num_back_channels >= 4) {
341 i += assign_pair(e2c_vec, layout_map, i,
345 num_back_channels -= 2;
347 if (num_back_channels >= 2) {
348 i += assign_pair(e2c_vec, layout_map, i,
352 num_back_channels -= 2;
354 if (num_back_channels) {
355 e2c_vec[i] = (struct elem_to_channel) {
356 .av_position = AV_CH_BACK_CENTER,
358 .elem_id = layout_map[i][1],
359 .aac_position = AAC_CHANNEL_BACK
365 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
366 e2c_vec[i] = (struct elem_to_channel) {
367 .av_position = AV_CH_LOW_FREQUENCY,
369 .elem_id = layout_map[i][1],
370 .aac_position = AAC_CHANNEL_LFE
374 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
375 e2c_vec[i] = (struct elem_to_channel) {
376 .av_position = UINT64_MAX,
378 .elem_id = layout_map[i][1],
379 .aac_position = AAC_CHANNEL_LFE
384 // Must choose a stable sort
385 total_non_cc_elements = n = i;
388 for (i = 1; i < n; i++)
389 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
390 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
397 for (i = 0; i < total_non_cc_elements; i++) {
398 layout_map[i][0] = e2c_vec[i].syn_ele;
399 layout_map[i][1] = e2c_vec[i].elem_id;
400 layout_map[i][2] = e2c_vec[i].aac_position;
401 if (e2c_vec[i].av_position != UINT64_MAX) {
402 layout |= e2c_vec[i].av_position;
410 * Save current output configuration if and only if it has been locked.
412 static void push_output_configuration(AACContext *ac) {
413 if (ac->oc[1].status == OC_LOCKED) {
414 ac->oc[0] = ac->oc[1];
416 ac->oc[1].status = OC_NONE;
420 * Restore the previous output configuration if and only if the current
421 * configuration is unlocked.
423 static void pop_output_configuration(AACContext *ac) {
424 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
425 ac->oc[1] = ac->oc[0];
426 ac->avctx->channels = ac->oc[1].channels;
427 ac->avctx->channel_layout = ac->oc[1].channel_layout;
432 * Configure output channel order based on the current program
433 * configuration element.
435 * @return Returns error status. 0 - OK, !0 - error
437 static int output_configure(AACContext *ac,
438 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
439 enum OCStatus oc_type, int get_new_frame)
441 AVCodecContext *avctx = ac->avctx;
442 int i, channels = 0, ret;
445 if (ac->oc[1].layout_map != layout_map) {
446 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
447 ac->oc[1].layout_map_tags = tags;
450 // Try to sniff a reasonable channel order, otherwise output the
451 // channels in the order the PCE declared them.
452 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
453 layout = sniff_channel_order(layout_map, tags);
454 for (i = 0; i < tags; i++) {
455 int type = layout_map[i][0];
456 int id = layout_map[i][1];
457 int position = layout_map[i][2];
458 // Allocate or free elements depending on if they are in the
459 // current program configuration.
460 ret = che_configure(ac, position, type, id, &channels);
464 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
465 if (layout == AV_CH_FRONT_CENTER) {
466 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
472 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
473 avctx->channel_layout = ac->oc[1].channel_layout = layout;
474 avctx->channels = ac->oc[1].channels = channels;
475 ac->oc[1].status = oc_type;
478 if ((ret = frame_configure_elements(ac->avctx)) < 0)
486 * Set up channel positions based on a default channel configuration
487 * as specified in table 1.17.
489 * @return Returns error status. 0 - OK, !0 - error
491 static int set_default_channel_config(AVCodecContext *avctx,
492 uint8_t (*layout_map)[3],
496 if (channel_config < 1 || channel_config > 7) {
497 av_log(avctx, AV_LOG_ERROR,
498 "invalid default channel configuration (%d)\n",
500 return AVERROR_INVALIDDATA;
502 *tags = tags_per_config[channel_config];
503 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
504 *tags * sizeof(*layout_map));
508 static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
510 /* For PCE based channel configurations map the channels solely based
512 if (!ac->oc[1].m4ac.chan_config) {
513 return ac->tag_che_map[type][elem_id];
515 // Allow single CPE stereo files to be signalled with mono configuration.
516 if (!ac->tags_mapped && type == TYPE_CPE &&
517 ac->oc[1].m4ac.chan_config == 1) {
518 uint8_t layout_map[MAX_ELEM_ID*4][3];
520 push_output_configuration(ac);
522 if (set_default_channel_config(ac->avctx, layout_map,
523 &layout_map_tags, 2) < 0)
525 if (output_configure(ac, layout_map, layout_map_tags,
526 OC_TRIAL_FRAME, 1) < 0)
529 ac->oc[1].m4ac.chan_config = 2;
530 ac->oc[1].m4ac.ps = 0;
533 if (!ac->tags_mapped && type == TYPE_SCE &&
534 ac->oc[1].m4ac.chan_config == 2) {
535 uint8_t layout_map[MAX_ELEM_ID * 4][3];
537 push_output_configuration(ac);
539 if (set_default_channel_config(ac->avctx, layout_map,
540 &layout_map_tags, 1) < 0)
542 if (output_configure(ac, layout_map, layout_map_tags,
543 OC_TRIAL_FRAME, 1) < 0)
546 ac->oc[1].m4ac.chan_config = 1;
547 if (ac->oc[1].m4ac.sbr)
548 ac->oc[1].m4ac.ps = -1;
550 /* For indexed channel configurations map the channels solely based
552 switch (ac->oc[1].m4ac.chan_config) {
554 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
556 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
559 /* Some streams incorrectly code 5.1 audio as
560 * SCE[0] CPE[0] CPE[1] SCE[1]
562 * SCE[0] CPE[0] CPE[1] LFE[0].
563 * If we seem to have encountered such a stream, transfer
564 * the LFE[0] element to the SCE[1]'s mapping */
565 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
567 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
570 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
572 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
575 if (ac->tags_mapped == 2 &&
576 ac->oc[1].m4ac.chan_config == 4 &&
579 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
583 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
586 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
587 } else if (ac->oc[1].m4ac.chan_config == 2) {
591 if (!ac->tags_mapped && type == TYPE_SCE) {
593 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
601 * Decode an array of 4 bit element IDs, optionally interleaved with a
602 * stereo/mono switching bit.
604 * @param type speaker type/position for these channels
606 static void decode_channel_map(uint8_t layout_map[][3],
607 enum ChannelPosition type,
608 GetBitContext *gb, int n)
611 enum RawDataBlockType syn_ele;
613 case AAC_CHANNEL_FRONT:
614 case AAC_CHANNEL_BACK:
615 case AAC_CHANNEL_SIDE:
616 syn_ele = get_bits1(gb);
622 case AAC_CHANNEL_LFE:
626 layout_map[0][0] = syn_ele;
627 layout_map[0][1] = get_bits(gb, 4);
628 layout_map[0][2] = type;
634 * Decode program configuration element; reference: table 4.2.
636 * @return Returns error status. 0 - OK, !0 - error
638 static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
639 uint8_t (*layout_map)[3],
642 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
647 skip_bits(gb, 2); // object_type
649 sampling_index = get_bits(gb, 4);
650 if (m4ac->sampling_index != sampling_index)
651 av_log(avctx, AV_LOG_WARNING,
652 "Sample rate index in program config element does not "
653 "match the sample rate index configured by the container.\n");
655 num_front = get_bits(gb, 4);
656 num_side = get_bits(gb, 4);
657 num_back = get_bits(gb, 4);
658 num_lfe = get_bits(gb, 2);
659 num_assoc_data = get_bits(gb, 3);
660 num_cc = get_bits(gb, 4);
663 skip_bits(gb, 4); // mono_mixdown_tag
665 skip_bits(gb, 4); // stereo_mixdown_tag
668 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
670 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
672 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
674 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
676 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
679 skip_bits_long(gb, 4 * num_assoc_data);
681 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
686 /* comment field, first byte is length */
687 comment_len = get_bits(gb, 8) * 8;
688 if (get_bits_left(gb) < comment_len) {
689 av_log(avctx, AV_LOG_ERROR, overread_err);
690 return AVERROR_INVALIDDATA;
692 skip_bits_long(gb, comment_len);
697 * Decode GA "General Audio" specific configuration; reference: table 4.1.
699 * @param ac pointer to AACContext, may be null
700 * @param avctx pointer to AVCCodecContext, used for logging
702 * @return Returns error status. 0 - OK, !0 - error
704 static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
706 MPEG4AudioConfig *m4ac,
709 int extension_flag, ret, ep_config, res_flags;
710 uint8_t layout_map[MAX_ELEM_ID*4][3];
713 if (get_bits1(gb)) { // frameLengthFlag
714 avpriv_request_sample(avctx, "960/120 MDCT window");
715 return AVERROR_PATCHWELCOME;
718 if (get_bits1(gb)) // dependsOnCoreCoder
719 skip_bits(gb, 14); // coreCoderDelay
720 extension_flag = get_bits1(gb);
722 if (m4ac->object_type == AOT_AAC_SCALABLE ||
723 m4ac->object_type == AOT_ER_AAC_SCALABLE)
724 skip_bits(gb, 3); // layerNr
726 if (channel_config == 0) {
727 skip_bits(gb, 4); // element_instance_tag
728 tags = decode_pce(avctx, m4ac, layout_map, gb);
732 if ((ret = set_default_channel_config(avctx, layout_map,
733 &tags, channel_config)))
737 if (count_channels(layout_map, tags) > 1) {
739 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
742 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
745 if (extension_flag) {
746 switch (m4ac->object_type) {
748 skip_bits(gb, 5); // numOfSubFrame
749 skip_bits(gb, 11); // layer_length
753 case AOT_ER_AAC_SCALABLE:
755 res_flags = get_bits(gb, 3);
757 av_log(avctx, AV_LOG_ERROR,
758 "AAC data resilience not supported (flags %x)\n",
760 return AVERROR_PATCHWELCOME;
764 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
766 switch (m4ac->object_type) {
769 case AOT_ER_AAC_SCALABLE:
771 ep_config = get_bits(gb, 2);
773 av_log(avctx, AV_LOG_ERROR,
774 "epConfig %d is not supported.\n",
776 return AVERROR_PATCHWELCOME;
783 * Decode audio specific configuration; reference: table 1.13.
785 * @param ac pointer to AACContext, may be null
786 * @param avctx pointer to AVCCodecContext, used for logging
787 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
788 * @param data pointer to buffer holding an audio specific config
789 * @param bit_size size of audio specific config or data in bits
790 * @param sync_extension look for an appended sync extension
792 * @return Returns error status or number of consumed bits. <0 - error
794 static int decode_audio_specific_config(AACContext *ac,
795 AVCodecContext *avctx,
796 MPEG4AudioConfig *m4ac,
797 const uint8_t *data, int bit_size,
803 av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
804 for (i = 0; i < avctx->extradata_size; i++)
805 av_dlog(avctx, "%02x ", avctx->extradata[i]);
806 av_dlog(avctx, "\n");
808 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
811 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
812 sync_extension)) < 0)
813 return AVERROR_INVALIDDATA;
814 if (m4ac->sampling_index > 12) {
815 av_log(avctx, AV_LOG_ERROR,
816 "invalid sampling rate index %d\n",
817 m4ac->sampling_index);
818 return AVERROR_INVALIDDATA;
820 if (m4ac->object_type == AOT_ER_AAC_LD &&
821 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
822 av_log(avctx, AV_LOG_ERROR,
823 "invalid low delay sampling rate index %d\n",
824 m4ac->sampling_index);
825 return AVERROR_INVALIDDATA;
828 skip_bits_long(&gb, i);
830 switch (m4ac->object_type) {
836 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
837 m4ac, m4ac->chan_config)) < 0)
841 av_log(avctx, AV_LOG_ERROR,
842 "Audio object type %s%d is not supported.\n",
843 m4ac->sbr == 1 ? "SBR+" : "",
845 return AVERROR(ENOSYS);
849 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
850 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
851 m4ac->sample_rate, m4ac->sbr,
854 return get_bits_count(&gb);
858 * linear congruential pseudorandom number generator
860 * @param previous_val pointer to the current state of the generator
862 * @return Returns a 32-bit pseudorandom integer
864 static av_always_inline int lcg_random(int previous_val)
866 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
870 static av_always_inline void reset_predict_state(PredictorState *ps)
880 static void reset_all_predictors(PredictorState *ps)
883 for (i = 0; i < MAX_PREDICTORS; i++)
884 reset_predict_state(&ps[i]);
887 static int sample_rate_idx (int rate)
889 if (92017 <= rate) return 0;
890 else if (75132 <= rate) return 1;
891 else if (55426 <= rate) return 2;
892 else if (46009 <= rate) return 3;
893 else if (37566 <= rate) return 4;
894 else if (27713 <= rate) return 5;
895 else if (23004 <= rate) return 6;
896 else if (18783 <= rate) return 7;
897 else if (13856 <= rate) return 8;
898 else if (11502 <= rate) return 9;
899 else if (9391 <= rate) return 10;
903 static void reset_predictor_group(PredictorState *ps, int group_num)
906 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
907 reset_predict_state(&ps[i]);
910 #define AAC_INIT_VLC_STATIC(num, size) \
911 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
912 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
913 sizeof(ff_aac_spectral_bits[num][0]), \
914 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
915 sizeof(ff_aac_spectral_codes[num][0]), \
918 static av_cold int aac_decode_init(AVCodecContext *avctx)
920 AACContext *ac = avctx->priv_data;
924 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
926 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
928 if (avctx->extradata_size > 0) {
929 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
931 avctx->extradata_size * 8,
936 uint8_t layout_map[MAX_ELEM_ID*4][3];
939 sr = sample_rate_idx(avctx->sample_rate);
940 ac->oc[1].m4ac.sampling_index = sr;
941 ac->oc[1].m4ac.channels = avctx->channels;
942 ac->oc[1].m4ac.sbr = -1;
943 ac->oc[1].m4ac.ps = -1;
945 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
946 if (ff_mpeg4audio_channels[i] == avctx->channels)
948 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
951 ac->oc[1].m4ac.chan_config = i;
953 if (ac->oc[1].m4ac.chan_config) {
954 int ret = set_default_channel_config(avctx, layout_map,
955 &layout_map_tags, ac->oc[1].m4ac.chan_config);
957 output_configure(ac, layout_map, layout_map_tags,
959 else if (avctx->err_recognition & AV_EF_EXPLODE)
960 return AVERROR_INVALIDDATA;
964 AAC_INIT_VLC_STATIC( 0, 304);
965 AAC_INIT_VLC_STATIC( 1, 270);
966 AAC_INIT_VLC_STATIC( 2, 550);
967 AAC_INIT_VLC_STATIC( 3, 300);
968 AAC_INIT_VLC_STATIC( 4, 328);
969 AAC_INIT_VLC_STATIC( 5, 294);
970 AAC_INIT_VLC_STATIC( 6, 306);
971 AAC_INIT_VLC_STATIC( 7, 268);
972 AAC_INIT_VLC_STATIC( 8, 510);
973 AAC_INIT_VLC_STATIC( 9, 366);
974 AAC_INIT_VLC_STATIC(10, 462);
978 ff_fmt_convert_init(&ac->fmt_conv, avctx);
979 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
981 ac->random_state = 0x1f2e3d4c;
985 INIT_VLC_STATIC(&vlc_scalefactors, 7,
986 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
987 ff_aac_scalefactor_bits,
988 sizeof(ff_aac_scalefactor_bits[0]),
989 sizeof(ff_aac_scalefactor_bits[0]),
990 ff_aac_scalefactor_code,
991 sizeof(ff_aac_scalefactor_code[0]),
992 sizeof(ff_aac_scalefactor_code[0]),
995 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
996 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
997 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
998 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
999 // window initialization
1000 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1001 ff_kbd_window_init(ff_aac_kbd_long_512, 4.0, 512);
1002 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1003 ff_init_ff_sine_windows(10);
1004 ff_init_ff_sine_windows( 9);
1005 ff_init_ff_sine_windows( 7);
1013 * Skip data_stream_element; reference: table 4.10.
1015 static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
1017 int byte_align = get_bits1(gb);
1018 int count = get_bits(gb, 8);
1020 count += get_bits(gb, 8);
1024 if (get_bits_left(gb) < 8 * count) {
1025 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1026 return AVERROR_INVALIDDATA;
1028 skip_bits_long(gb, 8 * count);
1032 static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1036 if (get_bits1(gb)) {
1037 ics->predictor_reset_group = get_bits(gb, 5);
1038 if (ics->predictor_reset_group == 0 ||
1039 ics->predictor_reset_group > 30) {
1040 av_log(ac->avctx, AV_LOG_ERROR,
1041 "Invalid Predictor Reset Group.\n");
1042 return AVERROR_INVALIDDATA;
1045 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
1046 ics->prediction_used[sfb] = get_bits1(gb);
1052 * Decode Long Term Prediction data; reference: table 4.xx.
1054 static void decode_ltp(LongTermPrediction *ltp,
1055 GetBitContext *gb, uint8_t max_sfb)
1059 ltp->lag = get_bits(gb, 11);
1060 ltp->coef = ltp_coef[get_bits(gb, 3)];
1061 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1062 ltp->used[sfb] = get_bits1(gb);
1066 * Decode Individual Channel Stream info; reference: table 4.6.
1068 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
1071 if (get_bits1(gb)) {
1072 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
1073 return AVERROR_INVALIDDATA;
1075 ics->window_sequence[1] = ics->window_sequence[0];
1076 ics->window_sequence[0] = get_bits(gb, 2);
1077 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD &&
1078 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1079 av_log(ac->avctx, AV_LOG_ERROR,
1080 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1081 "window sequence %d found.\n", ics->window_sequence[0]);
1082 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1083 return AVERROR_INVALIDDATA;
1085 ics->use_kb_window[1] = ics->use_kb_window[0];
1086 ics->use_kb_window[0] = get_bits1(gb);
1087 ics->num_window_groups = 1;
1088 ics->group_len[0] = 1;
1089 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1091 ics->max_sfb = get_bits(gb, 4);
1092 for (i = 0; i < 7; i++) {
1093 if (get_bits1(gb)) {
1094 ics->group_len[ics->num_window_groups - 1]++;
1096 ics->num_window_groups++;
1097 ics->group_len[ics->num_window_groups - 1] = 1;
1100 ics->num_windows = 8;
1101 ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
1102 ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
1103 ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
1104 ics->predictor_present = 0;
1106 ics->max_sfb = get_bits(gb, 6);
1107 ics->num_windows = 1;
1108 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD) {
1109 ics->swb_offset = ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];
1110 ics->num_swb = ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];
1111 if (!ics->num_swb || !ics->swb_offset)
1114 ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
1115 ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
1117 ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
1118 ics->predictor_present = get_bits1(gb);
1119 ics->predictor_reset_group = 0;
1120 if (ics->predictor_present) {
1121 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1122 if (decode_prediction(ac, ics, gb)) {
1123 return AVERROR_INVALIDDATA;
1125 } else if (ac->oc[1].m4ac.object_type == AOT_AAC_LC ||
1126 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC) {
1127 av_log(ac->avctx, AV_LOG_ERROR,
1128 "Prediction is not allowed in AAC-LC.\n");
1129 return AVERROR_INVALIDDATA;
1131 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD) {
1132 av_log(ac->avctx, AV_LOG_ERROR,
1133 "LTP in ER AAC LD not yet implemented.\n");
1134 return AVERROR_PATCHWELCOME;
1136 if ((ics->ltp.present = get_bits(gb, 1)))
1137 decode_ltp(&ics->ltp, gb, ics->max_sfb);
1142 if (ics->max_sfb > ics->num_swb) {
1143 av_log(ac->avctx, AV_LOG_ERROR,
1144 "Number of scalefactor bands in group (%d) "
1145 "exceeds limit (%d).\n",
1146 ics->max_sfb, ics->num_swb);
1147 return AVERROR_INVALIDDATA;
1154 * Decode band types (section_data payload); reference: table 4.46.
1156 * @param band_type array of the used band type
1157 * @param band_type_run_end array of the last scalefactor band of a band type run
1159 * @return Returns error status. 0 - OK, !0 - error
1161 static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1162 int band_type_run_end[120], GetBitContext *gb,
1163 IndividualChannelStream *ics)
1166 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1167 for (g = 0; g < ics->num_window_groups; g++) {
1169 while (k < ics->max_sfb) {
1170 uint8_t sect_end = k;
1172 int sect_band_type = get_bits(gb, 4);
1173 if (sect_band_type == 12) {
1174 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
1175 return AVERROR_INVALIDDATA;
1178 sect_len_incr = get_bits(gb, bits);
1179 sect_end += sect_len_incr;
1180 if (get_bits_left(gb) < 0) {
1181 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
1182 return AVERROR_INVALIDDATA;
1184 if (sect_end > ics->max_sfb) {
1185 av_log(ac->avctx, AV_LOG_ERROR,
1186 "Number of bands (%d) exceeds limit (%d).\n",
1187 sect_end, ics->max_sfb);
1188 return AVERROR_INVALIDDATA;
1190 } while (sect_len_incr == (1 << bits) - 1);
1191 for (; k < sect_end; k++) {
1192 band_type [idx] = sect_band_type;
1193 band_type_run_end[idx++] = sect_end;
1201 * Decode scalefactors; reference: table 4.47.
1203 * @param global_gain first scalefactor value as scalefactors are differentially coded
1204 * @param band_type array of the used band type
1205 * @param band_type_run_end array of the last scalefactor band of a band type run
1206 * @param sf array of scalefactors or intensity stereo positions
1208 * @return Returns error status. 0 - OK, !0 - error
1210 static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1211 unsigned int global_gain,
1212 IndividualChannelStream *ics,
1213 enum BandType band_type[120],
1214 int band_type_run_end[120])
1217 int offset[3] = { global_gain, global_gain - 90, 0 };
1220 for (g = 0; g < ics->num_window_groups; g++) {
1221 for (i = 0; i < ics->max_sfb;) {
1222 int run_end = band_type_run_end[idx];
1223 if (band_type[idx] == ZERO_BT) {
1224 for (; i < run_end; i++, idx++)
1226 } else if ((band_type[idx] == INTENSITY_BT) ||
1227 (band_type[idx] == INTENSITY_BT2)) {
1228 for (; i < run_end; i++, idx++) {
1229 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1230 clipped_offset = av_clip(offset[2], -155, 100);
1231 if (offset[2] != clipped_offset) {
1232 avpriv_request_sample(ac->avctx,
1233 "If you heard an audible artifact, there may be a bug in the decoder. "
1234 "Clipped intensity stereo position (%d -> %d)",
1235 offset[2], clipped_offset);
1237 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
1239 } else if (band_type[idx] == NOISE_BT) {
1240 for (; i < run_end; i++, idx++) {
1241 if (noise_flag-- > 0)
1242 offset[1] += get_bits(gb, 9) - 256;
1244 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1245 clipped_offset = av_clip(offset[1], -100, 155);
1246 if (offset[1] != clipped_offset) {
1247 avpriv_request_sample(ac->avctx,
1248 "If you heard an audible artifact, there may be a bug in the decoder. "
1249 "Clipped noise gain (%d -> %d)",
1250 offset[1], clipped_offset);
1252 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
1255 for (; i < run_end; i++, idx++) {
1256 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
1257 if (offset[0] > 255U) {
1258 av_log(ac->avctx, AV_LOG_ERROR,
1259 "Scalefactor (%d) out of range.\n", offset[0]);
1260 return AVERROR_INVALIDDATA;
1262 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
1271 * Decode pulse data; reference: table 4.7.
1273 static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1274 const uint16_t *swb_offset, int num_swb)
1277 pulse->num_pulse = get_bits(gb, 2) + 1;
1278 pulse_swb = get_bits(gb, 6);
1279 if (pulse_swb >= num_swb)
1281 pulse->pos[0] = swb_offset[pulse_swb];
1282 pulse->pos[0] += get_bits(gb, 5);
1283 if (pulse->pos[0] > 1023)
1285 pulse->amp[0] = get_bits(gb, 4);
1286 for (i = 1; i < pulse->num_pulse; i++) {
1287 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
1288 if (pulse->pos[i] > 1023)
1290 pulse->amp[i] = get_bits(gb, 4);
1296 * Decode Temporal Noise Shaping data; reference: table 4.48.
1298 * @return Returns error status. 0 - OK, !0 - error
1300 static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1301 GetBitContext *gb, const IndividualChannelStream *ics)
1303 int w, filt, i, coef_len, coef_res, coef_compress;
1304 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
1305 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1306 for (w = 0; w < ics->num_windows; w++) {
1307 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1308 coef_res = get_bits1(gb);
1310 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1312 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
1314 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
1315 av_log(ac->avctx, AV_LOG_ERROR,
1316 "TNS filter order %d is greater than maximum %d.\n",
1317 tns->order[w][filt], tns_max_order);
1318 tns->order[w][filt] = 0;
1319 return AVERROR_INVALIDDATA;
1321 if (tns->order[w][filt]) {
1322 tns->direction[w][filt] = get_bits1(gb);
1323 coef_compress = get_bits1(gb);
1324 coef_len = coef_res + 3 - coef_compress;
1325 tmp2_idx = 2 * coef_compress + coef_res;
1327 for (i = 0; i < tns->order[w][filt]; i++)
1328 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
1337 * Decode Mid/Side data; reference: table 4.54.
1339 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1340 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1341 * [3] reserved for scalable AAC
1343 static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1347 if (ms_present == 1) {
1349 idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
1351 cpe->ms_mask[idx] = get_bits1(gb);
1352 } else if (ms_present == 2) {
1353 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
1358 static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1362 *dst++ = v[idx & 15] * s;
1363 *dst++ = v[idx>>4 & 15] * s;
1369 static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1373 *dst++ = v[idx & 3] * s;
1374 *dst++ = v[idx>>2 & 3] * s;
1375 *dst++ = v[idx>>4 & 3] * s;
1376 *dst++ = v[idx>>6 & 3] * s;
1382 static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1383 unsigned sign, const float *scale)
1385 union av_intfloat32 s0, s1;
1387 s0.f = s1.f = *scale;
1388 s0.i ^= sign >> 1 << 31;
1391 *dst++ = v[idx & 15] * s0.f;
1392 *dst++ = v[idx>>4 & 15] * s1.f;
1399 static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1400 unsigned sign, const float *scale)
1402 unsigned nz = idx >> 12;
1403 union av_intfloat32 s = { .f = *scale };
1404 union av_intfloat32 t;
1406 t.i = s.i ^ (sign & 1U<<31);
1407 *dst++ = v[idx & 3] * t.f;
1409 sign <<= nz & 1; nz >>= 1;
1410 t.i = s.i ^ (sign & 1U<<31);
1411 *dst++ = v[idx>>2 & 3] * t.f;
1413 sign <<= nz & 1; nz >>= 1;
1414 t.i = s.i ^ (sign & 1U<<31);
1415 *dst++ = v[idx>>4 & 3] * t.f;
1418 t.i = s.i ^ (sign & 1U<<31);
1419 *dst++ = v[idx>>6 & 3] * t.f;
1426 * Decode spectral data; reference: table 4.50.
1427 * Dequantize and scale spectral data; reference: 4.6.3.3.
1429 * @param coef array of dequantized, scaled spectral data
1430 * @param sf array of scalefactors or intensity stereo positions
1431 * @param pulse_present set if pulses are present
1432 * @param pulse pointer to pulse data struct
1433 * @param band_type array of the used band type
1435 * @return Returns error status. 0 - OK, !0 - error
1437 static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
1438 GetBitContext *gb, const float sf[120],
1439 int pulse_present, const Pulse *pulse,
1440 const IndividualChannelStream *ics,
1441 enum BandType band_type[120])
1443 int i, k, g, idx = 0;
1444 const int c = 1024 / ics->num_windows;
1445 const uint16_t *offsets = ics->swb_offset;
1446 float *coef_base = coef;
1448 for (g = 0; g < ics->num_windows; g++)
1449 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1450 sizeof(float) * (c - offsets[ics->max_sfb]));
1452 for (g = 0; g < ics->num_window_groups; g++) {
1453 unsigned g_len = ics->group_len[g];
1455 for (i = 0; i < ics->max_sfb; i++, idx++) {
1456 const unsigned cbt_m1 = band_type[idx] - 1;
1457 float *cfo = coef + offsets[i];
1458 int off_len = offsets[i + 1] - offsets[i];
1461 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1462 for (group = 0; group < g_len; group++, cfo+=128) {
1463 memset(cfo, 0, off_len * sizeof(float));
1465 } else if (cbt_m1 == NOISE_BT - 1) {
1466 for (group = 0; group < g_len; group++, cfo+=128) {
1470 for (k = 0; k < off_len; k++) {
1471 ac->random_state = lcg_random(ac->random_state);
1472 cfo[k] = ac->random_state;
1475 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
1476 scale = sf[idx] / sqrtf(band_energy);
1477 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
1480 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1481 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1482 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
1483 OPEN_READER(re, gb);
1485 switch (cbt_m1 >> 1) {
1487 for (group = 0; group < g_len; group++, cfo+=128) {
1495 UPDATE_CACHE(re, gb);
1496 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1497 cb_idx = cb_vector_idx[code];
1498 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1504 for (group = 0; group < g_len; group++, cfo+=128) {
1514 UPDATE_CACHE(re, gb);
1515 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1516 cb_idx = cb_vector_idx[code];
1517 nnz = cb_idx >> 8 & 15;
1518 bits = nnz ? GET_CACHE(re, gb) : 0;
1519 LAST_SKIP_BITS(re, gb, nnz);
1520 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1526 for (group = 0; group < g_len; group++, cfo+=128) {
1534 UPDATE_CACHE(re, gb);
1535 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1536 cb_idx = cb_vector_idx[code];
1537 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1544 for (group = 0; group < g_len; group++, cfo+=128) {
1554 UPDATE_CACHE(re, gb);
1555 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1556 cb_idx = cb_vector_idx[code];
1557 nnz = cb_idx >> 8 & 15;
1558 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
1559 LAST_SKIP_BITS(re, gb, nnz);
1560 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1566 for (group = 0; group < g_len; group++, cfo+=128) {
1568 uint32_t *icf = (uint32_t *) cf;
1578 UPDATE_CACHE(re, gb);
1579 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1587 cb_idx = cb_vector_idx[code];
1590 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1591 LAST_SKIP_BITS(re, gb, nnz);
1593 for (j = 0; j < 2; j++) {
1597 /* The total length of escape_sequence must be < 22 bits according
1598 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
1599 UPDATE_CACHE(re, gb);
1600 b = GET_CACHE(re, gb);
1601 b = 31 - av_log2(~b);
1604 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
1605 return AVERROR_INVALIDDATA;
1608 SKIP_BITS(re, gb, b + 1);
1610 n = (1 << b) + SHOW_UBITS(re, gb, b);
1611 LAST_SKIP_BITS(re, gb, b);
1612 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
1615 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
1616 *icf++ = (bits & 1U<<31) | v;
1623 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
1627 CLOSE_READER(re, gb);
1633 if (pulse_present) {
1635 for (i = 0; i < pulse->num_pulse; i++) {
1636 float co = coef_base[ pulse->pos[i] ];
1637 while (offsets[idx + 1] <= pulse->pos[i])
1639 if (band_type[idx] != NOISE_BT && sf[idx]) {
1640 float ico = -pulse->amp[i];
1643 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1645 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
1652 static av_always_inline float flt16_round(float pf)
1654 union av_intfloat32 tmp;
1656 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1660 static av_always_inline float flt16_even(float pf)
1662 union av_intfloat32 tmp;
1664 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
1668 static av_always_inline float flt16_trunc(float pf)
1670 union av_intfloat32 pun;
1672 pun.i &= 0xFFFF0000U;
1676 static av_always_inline void predict(PredictorState *ps, float *coef,
1679 const float a = 0.953125; // 61.0 / 64
1680 const float alpha = 0.90625; // 29.0 / 32
1684 float r0 = ps->r0, r1 = ps->r1;
1685 float cor0 = ps->cor0, cor1 = ps->cor1;
1686 float var0 = ps->var0, var1 = ps->var1;
1688 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1689 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
1691 pv = flt16_round(k1 * r0 + k2 * r1);
1698 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1699 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1700 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1701 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
1703 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
1704 ps->r0 = flt16_trunc(a * e0);
1708 * Apply AAC-Main style frequency domain prediction.
1710 static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1714 if (!sce->ics.predictor_initialized) {
1715 reset_all_predictors(sce->predictor_state);
1716 sce->ics.predictor_initialized = 1;
1719 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1721 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1723 for (k = sce->ics.swb_offset[sfb];
1724 k < sce->ics.swb_offset[sfb + 1];
1726 predict(&sce->predictor_state[k], &sce->coeffs[k],
1727 sce->ics.predictor_present &&
1728 sce->ics.prediction_used[sfb]);
1731 if (sce->ics.predictor_reset_group)
1732 reset_predictor_group(sce->predictor_state,
1733 sce->ics.predictor_reset_group);
1735 reset_all_predictors(sce->predictor_state);
1739 * Decode an individual_channel_stream payload; reference: table 4.44.
1741 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1742 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1744 * @return Returns error status. 0 - OK, !0 - error
1746 static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1747 GetBitContext *gb, int common_window, int scale_flag)
1750 TemporalNoiseShaping *tns = &sce->tns;
1751 IndividualChannelStream *ics = &sce->ics;
1752 float *out = sce->coeffs;
1753 int global_gain, er_syntax, pulse_present = 0;
1756 /* This assignment is to silence a GCC warning about the variable being used
1757 * uninitialized when in fact it always is.
1759 pulse.num_pulse = 0;
1761 global_gain = get_bits(gb, 8);
1763 if (!common_window && !scale_flag) {
1764 if (decode_ics_info(ac, ics, gb) < 0)
1765 return AVERROR_INVALIDDATA;
1768 if ((ret = decode_band_types(ac, sce->band_type,
1769 sce->band_type_run_end, gb, ics)) < 0)
1771 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1772 sce->band_type, sce->band_type_run_end)) < 0)
1776 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1777 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1778 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD;
1780 if ((pulse_present = get_bits1(gb))) {
1781 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1782 av_log(ac->avctx, AV_LOG_ERROR,
1783 "Pulse tool not allowed in eight short sequence.\n");
1784 return AVERROR_INVALIDDATA;
1786 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
1787 av_log(ac->avctx, AV_LOG_ERROR,
1788 "Pulse data corrupt or invalid.\n");
1789 return AVERROR_INVALIDDATA;
1792 tns->present = get_bits1(gb);
1793 if (tns->present && !er_syntax)
1794 if (decode_tns(ac, tns, gb, ics) < 0)
1795 return AVERROR_INVALIDDATA;
1796 if (get_bits1(gb)) {
1797 avpriv_request_sample(ac->avctx, "SSR");
1798 return AVERROR_PATCHWELCOME;
1800 // I see no textual basis in the spec for this occuring after SSR gain
1801 // control, but this is what both reference and real implmentations do
1802 if (tns->present && er_syntax)
1803 if (decode_tns(ac, tns, gb, ics) < 0)
1804 return AVERROR_INVALIDDATA;
1807 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1808 &pulse, ics, sce->band_type) < 0)
1809 return AVERROR_INVALIDDATA;
1811 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
1812 apply_prediction(ac, sce);
1818 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1820 static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
1822 const IndividualChannelStream *ics = &cpe->ch[0].ics;
1823 float *ch0 = cpe->ch[0].coeffs;
1824 float *ch1 = cpe->ch[1].coeffs;
1825 int g, i, group, idx = 0;
1826 const uint16_t *offsets = ics->swb_offset;
1827 for (g = 0; g < ics->num_window_groups; g++) {
1828 for (i = 0; i < ics->max_sfb; i++, idx++) {
1829 if (cpe->ms_mask[idx] &&
1830 cpe->ch[0].band_type[idx] < NOISE_BT &&
1831 cpe->ch[1].band_type[idx] < NOISE_BT) {
1832 for (group = 0; group < ics->group_len[g]; group++) {
1833 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1834 ch1 + group * 128 + offsets[i],
1835 offsets[i+1] - offsets[i]);
1839 ch0 += ics->group_len[g] * 128;
1840 ch1 += ics->group_len[g] * 128;
1845 * intensity stereo decoding; reference: 4.6.8.2.3
1847 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1848 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1849 * [3] reserved for scalable AAC
1851 static void apply_intensity_stereo(AACContext *ac,
1852 ChannelElement *cpe, int ms_present)
1854 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1855 SingleChannelElement *sce1 = &cpe->ch[1];
1856 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
1857 const uint16_t *offsets = ics->swb_offset;
1858 int g, group, i, idx = 0;
1861 for (g = 0; g < ics->num_window_groups; g++) {
1862 for (i = 0; i < ics->max_sfb;) {
1863 if (sce1->band_type[idx] == INTENSITY_BT ||
1864 sce1->band_type[idx] == INTENSITY_BT2) {
1865 const int bt_run_end = sce1->band_type_run_end[idx];
1866 for (; i < bt_run_end; i++, idx++) {
1867 c = -1 + 2 * (sce1->band_type[idx] - 14);
1869 c *= 1 - 2 * cpe->ms_mask[idx];
1870 scale = c * sce1->sf[idx];
1871 for (group = 0; group < ics->group_len[g]; group++)
1872 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1873 coef0 + group * 128 + offsets[i],
1875 offsets[i + 1] - offsets[i]);
1878 int bt_run_end = sce1->band_type_run_end[idx];
1879 idx += bt_run_end - i;
1883 coef0 += ics->group_len[g] * 128;
1884 coef1 += ics->group_len[g] * 128;
1889 * Decode a channel_pair_element; reference: table 4.4.
1891 * @return Returns error status. 0 - OK, !0 - error
1893 static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1895 int i, ret, common_window, ms_present = 0;
1897 common_window = get_bits1(gb);
1898 if (common_window) {
1899 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1900 return AVERROR_INVALIDDATA;
1901 i = cpe->ch[1].ics.use_kb_window[0];
1902 cpe->ch[1].ics = cpe->ch[0].ics;
1903 cpe->ch[1].ics.use_kb_window[1] = i;
1904 if (cpe->ch[1].ics.predictor_present &&
1905 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
1906 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1907 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
1908 ms_present = get_bits(gb, 2);
1909 if (ms_present == 3) {
1910 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
1911 return AVERROR_INVALIDDATA;
1912 } else if (ms_present)
1913 decode_mid_side_stereo(cpe, gb, ms_present);
1915 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1917 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1920 if (common_window) {
1922 apply_mid_side_stereo(ac, cpe);
1923 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
1924 apply_prediction(ac, &cpe->ch[0]);
1925 apply_prediction(ac, &cpe->ch[1]);
1929 apply_intensity_stereo(ac, cpe, ms_present);
1933 static const float cce_scale[] = {
1934 1.09050773266525765921, //2^(1/8)
1935 1.18920711500272106672, //2^(1/4)
1941 * Decode coupling_channel_element; reference: table 4.8.
1943 * @return Returns error status. 0 - OK, !0 - error
1945 static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1951 SingleChannelElement *sce = &che->ch[0];
1952 ChannelCoupling *coup = &che->coup;
1954 coup->coupling_point = 2 * get_bits1(gb);
1955 coup->num_coupled = get_bits(gb, 3);
1956 for (c = 0; c <= coup->num_coupled; c++) {
1958 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1959 coup->id_select[c] = get_bits(gb, 4);
1960 if (coup->type[c] == TYPE_CPE) {
1961 coup->ch_select[c] = get_bits(gb, 2);
1962 if (coup->ch_select[c] == 3)
1965 coup->ch_select[c] = 2;
1967 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
1969 sign = get_bits(gb, 1);
1970 scale = cce_scale[get_bits(gb, 2)];
1972 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1975 for (c = 0; c < num_gain; c++) {
1979 float gain_cache = 1.0;
1981 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1982 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
1983 gain_cache = powf(scale, -gain);
1985 if (coup->coupling_point == AFTER_IMDCT) {
1986 coup->gain[c][0] = gain_cache;
1988 for (g = 0; g < sce->ics.num_window_groups; g++) {
1989 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1990 if (sce->band_type[idx] != ZERO_BT) {
1992 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
2000 gain_cache = powf(scale, -t) * s;
2003 coup->gain[c][idx] = gain_cache;
2013 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2015 * @return Returns number of bytes consumed.
2017 static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2021 int num_excl_chan = 0;
2024 for (i = 0; i < 7; i++)
2025 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2026 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2028 return num_excl_chan / 7;
2032 * Decode dynamic range information; reference: table 4.52.
2034 * @return Returns number of bytes consumed.
2036 static int decode_dynamic_range(DynamicRangeControl *che_drc,
2040 int drc_num_bands = 1;
2043 /* pce_tag_present? */
2044 if (get_bits1(gb)) {
2045 che_drc->pce_instance_tag = get_bits(gb, 4);
2046 skip_bits(gb, 4); // tag_reserved_bits
2050 /* excluded_chns_present? */
2051 if (get_bits1(gb)) {
2052 n += decode_drc_channel_exclusions(che_drc, gb);
2055 /* drc_bands_present? */
2056 if (get_bits1(gb)) {
2057 che_drc->band_incr = get_bits(gb, 4);
2058 che_drc->interpolation_scheme = get_bits(gb, 4);
2060 drc_num_bands += che_drc->band_incr;
2061 for (i = 0; i < drc_num_bands; i++) {
2062 che_drc->band_top[i] = get_bits(gb, 8);
2067 /* prog_ref_level_present? */
2068 if (get_bits1(gb)) {
2069 che_drc->prog_ref_level = get_bits(gb, 7);
2070 skip_bits1(gb); // prog_ref_level_reserved_bits
2074 for (i = 0; i < drc_num_bands; i++) {
2075 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2076 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2084 * Decode extension data (incomplete); reference: table 4.51.
2086 * @param cnt length of TYPE_FIL syntactic element in bytes
2088 * @return Returns number of bytes consumed
2090 static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2091 ChannelElement *che, enum RawDataBlockType elem_type)
2095 switch (get_bits(gb, 4)) { // extension type
2096 case EXT_SBR_DATA_CRC:
2100 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
2102 } else if (!ac->oc[1].m4ac.sbr) {
2103 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
2104 skip_bits_long(gb, 8 * cnt - 4);
2106 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
2107 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
2108 skip_bits_long(gb, 8 * cnt - 4);
2110 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2111 ac->oc[1].m4ac.sbr = 1;
2112 ac->oc[1].m4ac.ps = 1;
2113 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
2114 ac->oc[1].status, 1);
2116 ac->oc[1].m4ac.sbr = 1;
2118 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
2120 case EXT_DYNAMIC_RANGE:
2121 res = decode_dynamic_range(&ac->che_drc, gb);
2125 case EXT_DATA_ELEMENT:
2127 skip_bits_long(gb, 8 * cnt - 4);
2134 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2136 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2137 * @param coef spectral coefficients
2139 static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2140 IndividualChannelStream *ics, int decode)
2142 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
2144 int bottom, top, order, start, end, size, inc;
2145 float lpc[TNS_MAX_ORDER];
2146 float tmp[TNS_MAX_ORDER + 1];
2148 for (w = 0; w < ics->num_windows; w++) {
2149 bottom = ics->num_swb;
2150 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2152 bottom = FFMAX(0, top - tns->length[w][filt]);
2153 order = tns->order[w][filt];
2158 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
2160 start = ics->swb_offset[FFMIN(bottom, mmm)];
2161 end = ics->swb_offset[FFMIN( top, mmm)];
2162 if ((size = end - start) <= 0)
2164 if (tns->direction[w][filt]) {
2174 for (m = 0; m < size; m++, start += inc)
2175 for (i = 1; i <= FFMIN(m, order); i++)
2176 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2179 for (m = 0; m < size; m++, start += inc) {
2180 tmp[0] = coef[start];
2181 for (i = 1; i <= FFMIN(m, order); i++)
2182 coef[start] += tmp[i] * lpc[i - 1];
2183 for (i = order; i > 0; i--)
2184 tmp[i] = tmp[i - 1];
2192 * Apply windowing and MDCT to obtain the spectral
2193 * coefficient from the predicted sample by LTP.
2195 static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2196 float *in, IndividualChannelStream *ics)
2198 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2199 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2200 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2201 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2203 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
2204 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
2206 memset(in, 0, 448 * sizeof(float));
2207 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
2209 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
2210 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
2212 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
2213 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2215 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
2219 * Apply the long term prediction
2221 static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2223 const LongTermPrediction *ltp = &sce->ics.ltp;
2224 const uint16_t *offsets = sce->ics.swb_offset;
2227 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
2228 float *predTime = sce->ret;
2229 float *predFreq = ac->buf_mdct;
2230 int16_t num_samples = 2048;
2232 if (ltp->lag < 1024)
2233 num_samples = ltp->lag + 1024;
2234 for (i = 0; i < num_samples; i++)
2235 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2236 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2238 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2240 if (sce->tns.present)
2241 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2243 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2245 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2246 sce->coeffs[i] += predFreq[i];
2251 * Update the LTP buffer for next frame
2253 static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2255 IndividualChannelStream *ics = &sce->ics;
2256 float *saved = sce->saved;
2257 float *saved_ltp = sce->coeffs;
2258 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2259 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2262 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2263 memcpy(saved_ltp, saved, 512 * sizeof(float));
2264 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2265 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2266 for (i = 0; i < 64; i++)
2267 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2268 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2269 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2270 memset(saved_ltp + 576, 0, 448 * sizeof(float));
2271 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
2272 for (i = 0; i < 64; i++)
2273 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
2274 } else { // LONG_STOP or ONLY_LONG
2275 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
2276 for (i = 0; i < 512; i++)
2277 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
2280 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2281 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2282 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
2286 * Conduct IMDCT and windowing.
2288 static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
2290 IndividualChannelStream *ics = &sce->ics;
2291 float *in = sce->coeffs;
2292 float *out = sce->ret;
2293 float *saved = sce->saved;
2294 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2295 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2296 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2297 float *buf = ac->buf_mdct;
2298 float *temp = ac->temp;
2302 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2303 for (i = 0; i < 1024; i += 128)
2304 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
2306 ac->mdct.imdct_half(&ac->mdct, buf, in);
2308 /* window overlapping
2309 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2310 * and long to short transitions are considered to be short to short
2311 * transitions. This leaves just two cases (long to long and short to short)
2312 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2314 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
2315 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
2316 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
2318 memcpy( out, saved, 448 * sizeof(float));
2320 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2321 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2322 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2323 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2324 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2325 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2326 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
2328 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2329 memcpy( out + 576, buf + 64, 448 * sizeof(float));
2334 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2335 memcpy( saved, temp + 64, 64 * sizeof(float));
2336 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2337 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2338 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2339 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2340 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2341 memcpy( saved, buf + 512, 448 * sizeof(float));
2342 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
2343 } else { // LONG_STOP or ONLY_LONG
2344 memcpy( saved, buf + 512, 512 * sizeof(float));
2348 static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2350 IndividualChannelStream *ics = &sce->ics;
2351 float *in = sce->coeffs;
2352 float *out = sce->ret;
2353 float *saved = sce->saved;
2354 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_512 : ff_sine_512;
2355 float *buf = ac->buf_mdct;
2358 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2360 // window overlapping
2361 ac->fdsp.vector_fmul_window(out, saved, buf, lwindow_prev, 256);
2364 memcpy(saved, buf + 256, 256 * sizeof(float));
2368 * Apply dependent channel coupling (applied before IMDCT).
2370 * @param index index into coupling gain array
2372 static void apply_dependent_coupling(AACContext *ac,
2373 SingleChannelElement *target,
2374 ChannelElement *cce, int index)
2376 IndividualChannelStream *ics = &cce->ch[0].ics;
2377 const uint16_t *offsets = ics->swb_offset;
2378 float *dest = target->coeffs;
2379 const float *src = cce->ch[0].coeffs;
2380 int g, i, group, k, idx = 0;
2381 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2382 av_log(ac->avctx, AV_LOG_ERROR,
2383 "Dependent coupling is not supported together with LTP\n");
2386 for (g = 0; g < ics->num_window_groups; g++) {
2387 for (i = 0; i < ics->max_sfb; i++, idx++) {
2388 if (cce->ch[0].band_type[idx] != ZERO_BT) {
2389 const float gain = cce->coup.gain[index][idx];
2390 for (group = 0; group < ics->group_len[g]; group++) {
2391 for (k = offsets[i]; k < offsets[i + 1]; k++) {
2393 dest[group * 128 + k] += gain * src[group * 128 + k];
2398 dest += ics->group_len[g] * 128;
2399 src += ics->group_len[g] * 128;
2404 * Apply independent channel coupling (applied after IMDCT).
2406 * @param index index into coupling gain array
2408 static void apply_independent_coupling(AACContext *ac,
2409 SingleChannelElement *target,
2410 ChannelElement *cce, int index)
2413 const float gain = cce->coup.gain[index][0];
2414 const float *src = cce->ch[0].ret;
2415 float *dest = target->ret;
2416 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
2418 for (i = 0; i < len; i++)
2419 dest[i] += gain * src[i];
2423 * channel coupling transformation interface
2425 * @param apply_coupling_method pointer to (in)dependent coupling function
2427 static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2428 enum RawDataBlockType type, int elem_id,
2429 enum CouplingPoint coupling_point,
2430 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
2434 for (i = 0; i < MAX_ELEM_ID; i++) {
2435 ChannelElement *cce = ac->che[TYPE_CCE][i];
2438 if (cce && cce->coup.coupling_point == coupling_point) {
2439 ChannelCoupling *coup = &cce->coup;
2441 for (c = 0; c <= coup->num_coupled; c++) {
2442 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2443 if (coup->ch_select[c] != 1) {
2444 apply_coupling_method(ac, &cc->ch[0], cce, index);
2445 if (coup->ch_select[c] != 0)
2448 if (coup->ch_select[c] != 2)
2449 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2451 index += 1 + (coup->ch_select[c] == 3);
2458 * Convert spectral data to float samples, applying all supported tools as appropriate.
2460 static void spectral_to_sample(AACContext *ac)
2463 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
2464 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD)
2465 imdct_and_window = imdct_and_windowing_ld;
2467 imdct_and_window = imdct_and_windowing;
2468 for (type = 3; type >= 0; type--) {
2469 for (i = 0; i < MAX_ELEM_ID; i++) {
2470 ChannelElement *che = ac->che[type][i];
2472 if (type <= TYPE_CPE)
2473 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
2474 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
2475 if (che->ch[0].ics.predictor_present) {
2476 if (che->ch[0].ics.ltp.present)
2477 apply_ltp(ac, &che->ch[0]);
2478 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2479 apply_ltp(ac, &che->ch[1]);
2482 if (che->ch[0].tns.present)
2483 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
2484 if (che->ch[1].tns.present)
2485 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
2486 if (type <= TYPE_CPE)
2487 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
2488 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
2489 imdct_and_window(ac, &che->ch[0]);
2490 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2491 update_ltp(ac, &che->ch[0]);
2492 if (type == TYPE_CPE) {
2493 imdct_and_window(ac, &che->ch[1]);
2494 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
2495 update_ltp(ac, &che->ch[1]);
2497 if (ac->oc[1].m4ac.sbr > 0) {
2498 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2501 if (type <= TYPE_CCE)
2502 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
2508 static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2511 AACADTSHeaderInfo hdr_info;
2512 uint8_t layout_map[MAX_ELEM_ID*4][3];
2513 int layout_map_tags, ret;
2515 size = avpriv_aac_parse_header(gb, &hdr_info);
2517 if (hdr_info.num_aac_frames != 1) {
2518 avpriv_report_missing_feature(ac->avctx,
2519 "More than one AAC RDB per ADTS frame");
2520 return AVERROR_PATCHWELCOME;
2522 push_output_configuration(ac);
2523 if (hdr_info.chan_config) {
2524 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
2525 if ((ret = set_default_channel_config(ac->avctx,
2528 hdr_info.chan_config)) < 0)
2530 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2531 FFMAX(ac->oc[1].status,
2532 OC_TRIAL_FRAME), 0)) < 0)
2535 ac->oc[1].m4ac.chan_config = 0;
2537 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2538 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2539 ac->oc[1].m4ac.object_type = hdr_info.object_type;
2540 if (ac->oc[0].status != OC_LOCKED ||
2541 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2542 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2543 ac->oc[1].m4ac.sbr = -1;
2544 ac->oc[1].m4ac.ps = -1;
2546 if (!hdr_info.crc_absent)
2552 static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2553 int *got_frame_ptr, GetBitContext *gb)
2555 AACContext *ac = avctx->priv_data;
2556 ChannelElement *che;
2559 int chan_config = ac->oc[1].m4ac.chan_config;
2561 if (ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD)
2566 if ((err = frame_configure_elements(avctx)) < 0)
2569 ac->tags_mapped = 0;
2571 if (chan_config < 0 || chan_config >= 8) {
2572 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
2573 ac->oc[1].m4ac.chan_config);
2574 return AVERROR_INVALIDDATA;
2576 for (i = 0; i < tags_per_config[chan_config]; i++) {
2577 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2578 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2579 if (!(che=get_che(ac, elem_type, elem_id))) {
2580 av_log(ac->avctx, AV_LOG_ERROR,
2581 "channel element %d.%d is not allocated\n",
2582 elem_type, elem_id);
2583 return AVERROR_INVALIDDATA;
2586 switch (elem_type) {
2588 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2591 err = decode_cpe(ac, gb, che);
2594 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2601 spectral_to_sample(ac);
2603 ac->frame->nb_samples = samples;
2606 skip_bits_long(gb, get_bits_left(gb));
2610 static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
2611 int *got_frame_ptr, GetBitContext *gb)
2613 AACContext *ac = avctx->priv_data;
2614 ChannelElement *che = NULL, *che_prev = NULL;
2615 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
2617 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
2621 if (show_bits(gb, 12) == 0xfff) {
2622 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
2623 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
2626 if (ac->oc[1].m4ac.sampling_index > 12) {
2627 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
2628 err = AVERROR_INVALIDDATA;
2633 if ((err = frame_configure_elements(avctx)) < 0)
2636 ac->tags_mapped = 0;
2638 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2639 elem_id = get_bits(gb, 4);
2641 if (elem_type < TYPE_DSE) {
2642 if (!(che=get_che(ac, elem_type, elem_id))) {
2643 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2644 elem_type, elem_id);
2645 err = AVERROR_INVALIDDATA;
2651 switch (elem_type) {
2654 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2659 err = decode_cpe(ac, gb, che);
2664 err = decode_cce(ac, gb, che);
2668 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2673 err = skip_data_stream_element(ac, gb);
2677 uint8_t layout_map[MAX_ELEM_ID*4][3];
2679 push_output_configuration(ac);
2680 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
2686 av_log(avctx, AV_LOG_ERROR,
2687 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2688 pop_output_configuration(ac);
2690 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
2698 elem_id += get_bits(gb, 8) - 1;
2699 if (get_bits_left(gb) < 8 * elem_id) {
2700 av_log(avctx, AV_LOG_ERROR, overread_err);
2701 err = AVERROR_INVALIDDATA;
2705 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
2706 err = 0; /* FIXME */
2710 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
2715 elem_type_prev = elem_type;
2720 if (get_bits_left(gb) < 3) {
2721 av_log(avctx, AV_LOG_ERROR, overread_err);
2722 err = AVERROR_INVALIDDATA;
2727 spectral_to_sample(ac);
2729 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
2730 samples <<= multiplier;
2733 ac->frame->nb_samples = samples;
2734 *got_frame_ptr = !!samples;
2736 if (ac->oc[1].status && audio_found) {
2737 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2738 avctx->frame_size = samples;
2739 ac->oc[1].status = OC_LOCKED;
2744 pop_output_configuration(ac);
2748 static int aac_decode_frame(AVCodecContext *avctx, void *data,
2749 int *got_frame_ptr, AVPacket *avpkt)
2751 AACContext *ac = avctx->priv_data;
2752 const uint8_t *buf = avpkt->data;
2753 int buf_size = avpkt->size;
2758 int new_extradata_size;
2759 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2760 AV_PKT_DATA_NEW_EXTRADATA,
2761 &new_extradata_size);
2763 if (new_extradata) {
2764 av_free(avctx->extradata);
2765 avctx->extradata = av_mallocz(new_extradata_size +
2766 FF_INPUT_BUFFER_PADDING_SIZE);
2767 if (!avctx->extradata)
2768 return AVERROR(ENOMEM);
2769 avctx->extradata_size = new_extradata_size;
2770 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2771 push_output_configuration(ac);
2772 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
2774 avctx->extradata_size*8, 1) < 0) {
2775 pop_output_configuration(ac);
2776 return AVERROR_INVALIDDATA;
2780 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
2783 switch (ac->oc[1].m4ac.object_type) {
2785 case AOT_ER_AAC_LTP:
2787 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
2790 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb);
2795 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
2796 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2797 if (buf[buf_offset])
2800 return buf_size > buf_offset ? buf_consumed : buf_size;
2803 static av_cold int aac_decode_close(AVCodecContext *avctx)
2805 AACContext *ac = avctx->priv_data;
2808 for (i = 0; i < MAX_ELEM_ID; i++) {
2809 for (type = 0; type < 4; type++) {
2810 if (ac->che[type][i])
2811 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
2812 av_freep(&ac->che[type][i]);
2816 ff_mdct_end(&ac->mdct);
2817 ff_mdct_end(&ac->mdct_small);
2818 ff_mdct_end(&ac->mdct_ld);
2819 ff_mdct_end(&ac->mdct_ltp);
2824 #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2826 struct LATMContext {
2827 AACContext aac_ctx; ///< containing AACContext
2828 int initialized; ///< initilized after a valid extradata was seen
2831 int audio_mux_version_A; ///< LATM syntax version
2832 int frame_length_type; ///< 0/1 variable/fixed frame length
2833 int frame_length; ///< frame length for fixed frame length
2836 static inline uint32_t latm_get_value(GetBitContext *b)
2838 int length = get_bits(b, 2);
2840 return get_bits_long(b, (length+1)*8);
2843 static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
2844 GetBitContext *gb, int asclen)
2846 AACContext *ac = &latmctx->aac_ctx;
2847 AVCodecContext *avctx = ac->avctx;
2848 MPEG4AudioConfig m4ac = { 0 };
2849 int config_start_bit = get_bits_count(gb);
2850 int sync_extension = 0;
2851 int bits_consumed, esize;
2855 asclen = FFMIN(asclen, get_bits_left(gb));
2857 asclen = get_bits_left(gb);
2859 if (config_start_bit % 8) {
2860 avpriv_request_sample(latmctx->aac_ctx.avctx,
2861 "Non-byte-aligned audio-specific config");
2862 return AVERROR_PATCHWELCOME;
2865 return AVERROR_INVALIDDATA;
2866 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
2867 gb->buffer + (config_start_bit / 8),
2868 asclen, sync_extension);
2870 if (bits_consumed < 0)
2871 return AVERROR_INVALIDDATA;
2873 if (ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
2874 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
2876 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2877 latmctx->initialized = 0;
2879 esize = (bits_consumed+7) / 8;
2881 if (avctx->extradata_size < esize) {
2882 av_free(avctx->extradata);
2883 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2884 if (!avctx->extradata)
2885 return AVERROR(ENOMEM);
2888 avctx->extradata_size = esize;
2889 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2890 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2892 skip_bits_long(gb, bits_consumed);
2894 return bits_consumed;
2897 static int read_stream_mux_config(struct LATMContext *latmctx,
2900 int ret, audio_mux_version = get_bits(gb, 1);
2902 latmctx->audio_mux_version_A = 0;
2903 if (audio_mux_version)
2904 latmctx->audio_mux_version_A = get_bits(gb, 1);
2906 if (!latmctx->audio_mux_version_A) {
2908 if (audio_mux_version)
2909 latm_get_value(gb); // taraFullness
2911 skip_bits(gb, 1); // allStreamSameTimeFraming
2912 skip_bits(gb, 6); // numSubFrames
2914 if (get_bits(gb, 4)) { // numPrograms
2915 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
2916 return AVERROR_PATCHWELCOME;
2919 // for each program (which there is only on in DVB)
2921 // for each layer (which there is only on in DVB)
2922 if (get_bits(gb, 3)) { // numLayer
2923 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
2924 return AVERROR_PATCHWELCOME;
2927 // for all but first stream: use_same_config = get_bits(gb, 1);
2928 if (!audio_mux_version) {
2929 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
2932 int ascLen = latm_get_value(gb);
2933 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
2936 skip_bits_long(gb, ascLen);
2939 latmctx->frame_length_type = get_bits(gb, 3);
2940 switch (latmctx->frame_length_type) {
2942 skip_bits(gb, 8); // latmBufferFullness
2945 latmctx->frame_length = get_bits(gb, 9);
2950 skip_bits(gb, 6); // CELP frame length table index
2954 skip_bits(gb, 1); // HVXC frame length table index
2958 if (get_bits(gb, 1)) { // other data
2959 if (audio_mux_version) {
2960 latm_get_value(gb); // other_data_bits
2964 esc = get_bits(gb, 1);
2970 if (get_bits(gb, 1)) // crc present
2971 skip_bits(gb, 8); // config_crc
2977 static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2981 if (ctx->frame_length_type == 0) {
2982 int mux_slot_length = 0;
2984 tmp = get_bits(gb, 8);
2985 mux_slot_length += tmp;
2986 } while (tmp == 255);
2987 return mux_slot_length;
2988 } else if (ctx->frame_length_type == 1) {
2989 return ctx->frame_length;
2990 } else if (ctx->frame_length_type == 3 ||
2991 ctx->frame_length_type == 5 ||
2992 ctx->frame_length_type == 7) {
2993 skip_bits(gb, 2); // mux_slot_length_coded
2998 static int read_audio_mux_element(struct LATMContext *latmctx,
3002 uint8_t use_same_mux = get_bits(gb, 1);
3003 if (!use_same_mux) {
3004 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3006 } else if (!latmctx->aac_ctx.avctx->extradata) {
3007 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3008 "no decoder config found\n");
3009 return AVERROR(EAGAIN);
3011 if (latmctx->audio_mux_version_A == 0) {
3012 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3013 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3014 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3015 return AVERROR_INVALIDDATA;
3016 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3017 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3018 "frame length mismatch %d << %d\n",
3019 mux_slot_length_bytes * 8, get_bits_left(gb));
3020 return AVERROR_INVALIDDATA;
3027 static int latm_decode_frame(AVCodecContext *avctx, void *out,
3028 int *got_frame_ptr, AVPacket *avpkt)
3030 struct LATMContext *latmctx = avctx->priv_data;
3034 if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
3037 // check for LOAS sync word
3038 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3039 return AVERROR_INVALIDDATA;
3041 muxlength = get_bits(&gb, 13) + 3;
3042 // not enough data, the parser should have sorted this
3043 if (muxlength > avpkt->size)
3044 return AVERROR_INVALIDDATA;
3046 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
3049 if (!latmctx->initialized) {
3050 if (!avctx->extradata) {
3054 push_output_configuration(&latmctx->aac_ctx);
3055 if ((err = decode_audio_specific_config(
3056 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
3057 avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
3058 pop_output_configuration(&latmctx->aac_ctx);
3061 latmctx->initialized = 1;
3065 if (show_bits(&gb, 12) == 0xfff) {
3066 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3067 "ADTS header detected, probably as result of configuration "
3069 return AVERROR_INVALIDDATA;
3072 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
3078 static av_cold int latm_decode_init(AVCodecContext *avctx)
3080 struct LATMContext *latmctx = avctx->priv_data;
3081 int ret = aac_decode_init(avctx);
3083 if (avctx->extradata_size > 0)
3084 latmctx->initialized = !ret;
3090 AVCodec ff_aac_decoder = {
3092 .type = AVMEDIA_TYPE_AUDIO,
3093 .id = AV_CODEC_ID_AAC,
3094 .priv_data_size = sizeof(AACContext),
3095 .init = aac_decode_init,
3096 .close = aac_decode_close,
3097 .decode = aac_decode_frame,
3098 .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
3099 .sample_fmts = (const enum AVSampleFormat[]) {
3100 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3102 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3103 .channel_layouts = aac_channel_layout,
3107 Note: This decoder filter is intended to decode LATM streams transferred
3108 in MPEG transport streams which only contain one program.
3109 To do a more complex LATM demuxing a separate LATM demuxer should be used.
3111 AVCodec ff_aac_latm_decoder = {
3113 .type = AVMEDIA_TYPE_AUDIO,
3114 .id = AV_CODEC_ID_AAC_LATM,
3115 .priv_data_size = sizeof(struct LATMContext),
3116 .init = latm_decode_init,
3117 .close = aac_decode_close,
3118 .decode = latm_decode_frame,
3119 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
3120 .sample_fmts = (const enum AVSampleFormat[]) {
3121 AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
3123 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
3124 .channel_layouts = aac_channel_layout,