aacdec: pass avctx as logging context for decode_audio_specific_config
[libav.git] / libavcodec / aacdec.c
CommitLineData
71e9a1b8
RS
1/*
2 * AAC decoder
3 * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
4 * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
ba87f080 24 * @file
71e9a1b8
RS
25 * AAC decoder
26 * @author Oded Shimon ( ods15 ods15 dyndns org )
27 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
28 */
29
30/*
31 * supported tools
32 *
33 * Support? Name
34 * N (code in SoC repo) gain control
35 * Y block switching
36 * Y window shapes - standard
37 * N window shapes - Low Delay
38 * Y filterbank - standard
39 * N (code in SoC repo) filterbank - Scalable Sample Rate
40 * Y Temporal Noise Shaping
41 * N (code in SoC repo) Long Term Prediction
42 * Y intensity stereo
43 * Y channel coupling
7633a041 44 * Y frequency domain prediction
71e9a1b8
RS
45 * Y Perceptual Noise Substitution
46 * Y Mid/Side stereo
47 * N Scalable Inverse AAC Quantization
48 * N Frequency Selective Switch
49 * N upsampling filter
50 * Y quantization & coding - AAC
51 * N quantization & coding - TwinVQ
52 * N quantization & coding - BSAC
53 * N AAC Error Resilience tools
54 * N Error Resilience payload syntax
55 * N Error Protection tool
56 * N CELP
57 * N Silence Compression
58 * N HVXC
59 * N HVXC 4kbits/s VR
60 * N Structured Audio tools
61 * N Structured Audio Sample Bank Format
62 * N MIDI
63 * N Harmonic and Individual Lines plus Noise
64 * N Text-To-Speech Interface
ed492b61 65 * Y Spectral Band Replication
71e9a1b8
RS
66 * Y (not in this code) Layer-1
67 * Y (not in this code) Layer-2
68 * Y (not in this code) Layer-3
69 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
a2063901 70 * Y Parametric Stereo
71e9a1b8
RS
71 * N Direct Stream Transfer
72 *
73 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
74 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
75 Parametric Stereo.
76 */
77
78
79#include "avcodec.h"
dbbec0c2 80#include "internal.h"
9106a698 81#include "get_bits.h"
71e9a1b8 82#include "dsputil.h"
1429224b 83#include "fft.h"
1be0fc29 84#include "lpc.h"
71e9a1b8
RS
85
86#include "aac.h"
87#include "aactab.h"
cc0591da 88#include "aacdectab.h"
c26bce10 89#include "cbrt_tablegen.h"
ed492b61
AC
90#include "sbr.h"
91#include "aacsbr.h"
71e9a1b8 92#include "mpeg4audio.h"
3cac899a 93#include "aacadtsdec.h"
71e9a1b8
RS
94
95#include <assert.h>
96#include <errno.h>
97#include <math.h>
98#include <string.h>
99
798339fb
MR
100#if ARCH_ARM
101# include "arm/aac.h"
102#endif
103
577d383b
DB
104union float754 {
105 float f;
106 uint32_t i;
107};
4a39ccb4 108
71e9a1b8
RS
109static VLC vlc_scalefactors;
110static VLC vlc_spectral[11];
111
8d637124
AC
112static const char overread_err[] = "Input buffer exhausted before END element found\n";
113
577d383b
DB
114static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
115{
bb2d8e9f
AC
116 // For PCE based channel configurations map the channels solely based on tags.
117 if (!ac->m4ac.chan_config) {
bb5c0988
AC
118 return ac->tag_che_map[type][elem_id];
119 }
bb2d8e9f 120 // For indexed channel configurations map the channels solely based on position.
bb5c0988 121 switch (ac->m4ac.chan_config) {
577d383b
DB
122 case 7:
123 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
124 ac->tags_mapped++;
125 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
126 }
127 case 6:
128 /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
5d55bb9f
CR
129 instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
130 encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
577d383b
DB
131 if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
132 ac->tags_mapped++;
133 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
134 }
135 case 5:
136 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
137 ac->tags_mapped++;
138 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
139 }
140 case 4:
141 if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
142 ac->tags_mapped++;
143 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
144 }
145 case 3:
146 case 2:
147 if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
148 ac->tags_mapped++;
149 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
150 } else if (ac->m4ac.chan_config == 2) {
bb5c0988 151 return NULL;
577d383b
DB
152 }
153 case 1:
154 if (!ac->tags_mapped && type == TYPE_SCE) {
155 ac->tags_mapped++;
156 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
157 }
158 default:
159 return NULL;
bb5c0988
AC
160 }
161}
162
9cc04edf 163/**
754ff9a7
RS
164 * Check for the channel element in the current channel position configuration.
165 * If it exists, make sure the appropriate element is allocated and map the
166 * channel order to match the internal FFmpeg channel layout.
167 *
168 * @param che_pos current channel position configuration
169 * @param type channel element type
170 * @param id channel element id
171 * @param channels count of the number of channels in the configuration
172 *
173 * @return Returns error status. 0 - OK, !0 - error
174 */
89584458 175static av_cold int che_configure(AACContext *ac,
754ff9a7
RS
176 enum ChannelPosition che_pos[4][MAX_ELEM_ID],
177 int type, int id,
178 int *channels)
179{
180 if (che_pos[type][id]) {
181 if (!ac->che[type][id] && !(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
182 return AVERROR(ENOMEM);
ed492b61 183 ff_aac_sbr_ctx_init(&ac->che[type][id]->sbr);
754ff9a7
RS
184 if (type != TYPE_CCE) {
185 ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
a2063901
AC
186 if (type == TYPE_CPE ||
187 (type == TYPE_SCE && ac->m4ac.ps == 1)) {
754ff9a7
RS
188 ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
189 }
190 }
ed492b61
AC
191 } else {
192 if (ac->che[type][id])
193 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
754ff9a7 194 av_freep(&ac->che[type][id]);
ed492b61 195 }
754ff9a7
RS
196 return 0;
197}
198
199/**
62a57fae
RS
200 * Configure output channel order based on the current program configuration element.
201 *
202 * @param che_pos current channel position configuration
203 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
204 *
205 * @return Returns error status. 0 - OK, !0 - error
206 */
ff98c17c 207static av_cold int output_configure(AACContext *ac,
577d383b
DB
208 enum ChannelPosition che_pos[4][MAX_ELEM_ID],
209 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
981b8fd7 210 int channel_config, enum OCStatus oc_type)
577d383b 211{
dd8871a6 212 AVCodecContext *avctx = ac->avctx;
754ff9a7 213 int i, type, channels = 0, ret;
62a57fae 214
a2063901 215 if (new_che_pos != che_pos)
62a57fae
RS
216 memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
217
e22da6b6
RS
218 if (channel_config) {
219 for (i = 0; i < tags_per_config[channel_config]; i++) {
754ff9a7
RS
220 if ((ret = che_configure(ac, che_pos,
221 aac_channel_layout_map[channel_config - 1][i][0],
222 aac_channel_layout_map[channel_config - 1][i][1],
223 &channels)))
224 return ret;
e22da6b6
RS
225 }
226
227 memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
e22da6b6
RS
228
229 avctx->channel_layout = aac_channel_layout[channel_config - 1];
230 } else {
2309923c
RS
231 /* Allocate or free elements depending on if they are in the
232 * current program configuration.
233 *
234 * Set up default 1:1 output mapping.
235 *
236 * For a 5.1 stream the output order will be:
237 * [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
238 */
239
240 for (i = 0; i < MAX_ELEM_ID; i++) {
241 for (type = 0; type < 4; type++) {
754ff9a7
RS
242 if ((ret = che_configure(ac, che_pos, type, i, &channels)))
243 return ret;
2309923c 244 }
62a57fae 245 }
62a57fae 246
bb5c0988 247 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
e22da6b6
RS
248
249 avctx->channel_layout = 0;
bb5c0988
AC
250 }
251
62a57fae 252 avctx->channels = channels;
bb5c0988 253
981b8fd7 254 ac->output_configured = oc_type;
6308765c 255
62a57fae
RS
256 return 0;
257}
258
259/**
9cc04edf
RS
260 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
261 *
262 * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
263 * @param sce_map mono (Single Channel Element) map
264 * @param type speaker type/position for these channels
265 */
266static void decode_channel_map(enum ChannelPosition *cpe_map,
577d383b
DB
267 enum ChannelPosition *sce_map,
268 enum ChannelPosition type,
269 GetBitContext *gb, int n)
270{
271 while (n--) {
9cc04edf
RS
272 enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
273 map[get_bits(gb, 4)] = type;
274 }
275}
276
277/**
278 * Decode program configuration element; reference: table 4.2.
279 *
280 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
281 *
282 * @return Returns error status. 0 - OK, !0 - error
283 */
6c003e6d
JG
284static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
285 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
577d383b
DB
286 GetBitContext *gb)
287{
99665a21 288 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
8d637124 289 int comment_len;
9cc04edf
RS
290
291 skip_bits(gb, 2); // object_type
292
99665a21 293 sampling_index = get_bits(gb, 4);
6c003e6d
JG
294 if (m4ac->sampling_index != sampling_index)
295 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");
401a9950 296
71e9a1b8
RS
297 num_front = get_bits(gb, 4);
298 num_side = get_bits(gb, 4);
299 num_back = get_bits(gb, 4);
300 num_lfe = get_bits(gb, 2);
301 num_assoc_data = get_bits(gb, 3);
302 num_cc = get_bits(gb, 4);
303
cc0591da
RS
304 if (get_bits1(gb))
305 skip_bits(gb, 4); // mono_mixdown_tag
306 if (get_bits1(gb))
307 skip_bits(gb, 4); // stereo_mixdown_tag
71e9a1b8 308
cc0591da
RS
309 if (get_bits1(gb))
310 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
71e9a1b8 311
cc0591da
RS
312 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
313 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
314 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
315 decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
71e9a1b8
RS
316
317 skip_bits_long(gb, 4 * num_assoc_data);
318
cc0591da 319 decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
71e9a1b8
RS
320
321 align_get_bits(gb);
322
323 /* comment field, first byte is length */
8d637124
AC
324 comment_len = get_bits(gb, 8) * 8;
325 if (get_bits_left(gb) < comment_len) {
6c003e6d 326 av_log(avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
327 return -1;
328 }
329 skip_bits_long(gb, comment_len);
cc0591da
RS
330 return 0;
331}
71e9a1b8 332
9cc04edf
RS
333/**
334 * Set up channel positions based on a default channel configuration
335 * as specified in table 1.17.
336 *
337 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
338 *
339 * @return Returns error status. 0 - OK, !0 - error
340 */
6c003e6d 341static av_cold int set_default_channel_config(AVCodecContext *avctx,
577d383b
DB
342 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
343 int channel_config)
9cc04edf 344{
577d383b 345 if (channel_config < 1 || channel_config > 7) {
6c003e6d 346 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
9cc04edf
RS
347 channel_config);
348 return -1;
349 }
350
351 /* default channel configurations:
352 *
353 * 1ch : front center (mono)
354 * 2ch : L + R (stereo)
355 * 3ch : front center + L + R
356 * 4ch : front center + L + R + back center
357 * 5ch : front center + L + R + back stereo
358 * 6ch : front center + L + R + back stereo + LFE
359 * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
360 */
361
577d383b 362 if (channel_config != 2)
9cc04edf 363 new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
577d383b 364 if (channel_config > 1)
9cc04edf 365 new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
577d383b 366 if (channel_config == 4)
9cc04edf 367 new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
577d383b 368 if (channel_config > 4)
9cc04edf 369 new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
577d383b
DB
370 = AAC_CHANNEL_BACK; // back stereo
371 if (channel_config > 5)
9cc04edf 372 new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
577d383b 373 if (channel_config == 7)
9cc04edf
RS
374 new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
375
376 return 0;
377}
378
62a57fae
RS
379/**
380 * Decode GA "General Audio" specific configuration; reference: table 4.1.
381 *
6c003e6d
JG
382 * @param ac pointer to AACContext, may be null
383 * @param avctx pointer to AVCCodecContext, used for logging
384 *
62a57fae
RS
385 * @return Returns error status. 0 - OK, !0 - error
386 */
6c003e6d
JG
387static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
388 GetBitContext *gb,
37d28953 389 MPEG4AudioConfig *m4ac,
577d383b
DB
390 int channel_config)
391{
62a57fae
RS
392 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
393 int extension_flag, ret;
394
577d383b 395 if (get_bits1(gb)) { // frameLengthFlag
6c003e6d 396 av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
9cc04edf
RS
397 return -1;
398 }
399
400 if (get_bits1(gb)) // dependsOnCoreCoder
401 skip_bits(gb, 14); // coreCoderDelay
402 extension_flag = get_bits1(gb);
403
37d28953
JG
404 if (m4ac->object_type == AOT_AAC_SCALABLE ||
405 m4ac->object_type == AOT_ER_AAC_SCALABLE)
9cc04edf
RS
406 skip_bits(gb, 3); // layerNr
407
408 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
409 if (channel_config == 0) {
410 skip_bits(gb, 4); // element_instance_tag
6c003e6d 411 if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
9cc04edf
RS
412 return ret;
413 } else {
6c003e6d 414 if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
9cc04edf
RS
415 return ret;
416 }
6c003e6d 417 if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
9cc04edf
RS
418 return ret;
419
420 if (extension_flag) {
37d28953 421 switch (m4ac->object_type) {
577d383b
DB
422 case AOT_ER_BSAC:
423 skip_bits(gb, 5); // numOfSubFrame
424 skip_bits(gb, 11); // layer_length
425 break;
426 case AOT_ER_AAC_LC:
427 case AOT_ER_AAC_LTP:
428 case AOT_ER_AAC_SCALABLE:
429 case AOT_ER_AAC_LD:
430 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
9cc04edf
RS
431 * aacScalefactorDataResilienceFlag
432 * aacSpectralDataResilienceFlag
433 */
577d383b 434 break;
9cc04edf
RS
435 }
436 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
437 }
438 return 0;
439}
440
441/**
442 * Decode audio specific configuration; reference: table 1.13.
443 *
6c003e6d
JG
444 * @param ac pointer to AACContext, may be null
445 * @param avctx pointer to AVCCodecContext, used for logging
446 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
9cc04edf
RS
447 * @param data pointer to AVCodecContext extradata
448 * @param data_size size of AVCCodecContext extradata
449 *
be63b4ba 450 * @return Returns error status or number of consumed bits. <0 - error
9cc04edf 451 */
37d28953 452static int decode_audio_specific_config(AACContext *ac,
6c003e6d
JG
453 AVCodecContext *avctx,
454 MPEG4AudioConfig *m4ac,
455 void *data, int data_size)
577d383b 456{
9cc04edf
RS
457 GetBitContext gb;
458 int i;
459
460 init_get_bits(&gb, data, data_size * 8);
461
37d28953 462 if ((i = ff_mpeg4audio_get_config(m4ac, data, data_size)) < 0)
9cc04edf 463 return -1;
37d28953 464 if (m4ac->sampling_index > 12) {
6c003e6d 465 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
9cc04edf
RS
466 return -1;
467 }
37d28953
JG
468 if (m4ac->sbr == 1 && m4ac->ps == -1)
469 m4ac->ps = 1;
9cc04edf
RS
470
471 skip_bits_long(&gb, i);
472
37d28953 473 switch (m4ac->object_type) {
7633a041 474 case AOT_AAC_MAIN:
9cc04edf 475 case AOT_AAC_LC:
6c003e6d 476 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
9cc04edf
RS
477 return -1;
478 break;
479 default:
6c003e6d 480 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
37d28953 481 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
9cc04edf
RS
482 return -1;
483 }
37d28953 484
be63b4ba 485 return get_bits_count(&gb);
9cc04edf
RS
486}
487
62a57fae
RS
488/**
489 * linear congruential pseudorandom number generator
490 *
491 * @param previous_val pointer to the current state of the generator
492 *
493 * @return Returns a 32-bit pseudorandom integer
494 */
577d383b
DB
495static av_always_inline int lcg_random(int previous_val)
496{
62a57fae
RS
497 return previous_val * 1664525 + 1013904223;
498}
499
ab2a3028 500static av_always_inline void reset_predict_state(PredictorState *ps)
577d383b
DB
501{
502 ps->r0 = 0.0f;
503 ps->r1 = 0.0f;
7633a041
AC
504 ps->cor0 = 0.0f;
505 ps->cor1 = 0.0f;
506 ps->var0 = 1.0f;
507 ps->var1 = 1.0f;
508}
509
577d383b
DB
510static void reset_all_predictors(PredictorState *ps)
511{
7633a041
AC
512 int i;
513 for (i = 0; i < MAX_PREDICTORS; i++)
514 reset_predict_state(&ps[i]);
515}
516
577d383b
DB
517static void reset_predictor_group(PredictorState *ps, int group_num)
518{
7633a041 519 int i;
577d383b 520 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
7633a041
AC
521 reset_predict_state(&ps[i]);
522}
523
8e5998f0
AC
524#define AAC_INIT_VLC_STATIC(num, size) \
525 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
526 ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
527 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
528 size);
529
dd8871a6 530static av_cold int aac_decode_init(AVCodecContext *avctx)
577d383b 531{
dd8871a6 532 AACContext *ac = avctx->priv_data;
71e9a1b8 533
dd8871a6
AC
534 ac->avctx = avctx;
535 ac->m4ac.sample_rate = avctx->sample_rate;
71e9a1b8 536
dd8871a6 537 if (avctx->extradata_size > 0) {
6c003e6d
JG
538 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
539 avctx->extradata,
540 avctx->extradata_size) < 0)
158b3912 541 return -1;
158b3912 542 }
cc0591da 543
dd8871a6 544 avctx->sample_fmt = SAMPLE_FMT_S16;
71e9a1b8 545
2ef21b91
MR
546 AAC_INIT_VLC_STATIC( 0, 304);
547 AAC_INIT_VLC_STATIC( 1, 270);
548 AAC_INIT_VLC_STATIC( 2, 550);
549 AAC_INIT_VLC_STATIC( 3, 300);
550 AAC_INIT_VLC_STATIC( 4, 328);
551 AAC_INIT_VLC_STATIC( 5, 294);
552 AAC_INIT_VLC_STATIC( 6, 306);
553 AAC_INIT_VLC_STATIC( 7, 268);
554 AAC_INIT_VLC_STATIC( 8, 510);
555 AAC_INIT_VLC_STATIC( 9, 366);
556 AAC_INIT_VLC_STATIC(10, 462);
71e9a1b8 557
ed492b61
AC
558 ff_aac_sbr_init();
559
dd8871a6 560 dsputil_init(&ac->dsp, avctx);
71e9a1b8 561
9cc04edf
RS
562 ac->random_state = 0x1f2e3d4c;
563
71e9a1b8
RS
564 // -1024 - Compensate wrong IMDCT method.
565 // 32768 - Required to scale values to the correct range for the bias method
566 // for float to int16 conversion.
567
144fec83 568 if (ac->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
577d383b
DB
569 ac->add_bias = 385.0f;
570 ac->sf_scale = 1. / (-1024. * 32768.);
71e9a1b8
RS
571 ac->sf_offset = 0;
572 } else {
577d383b
DB
573 ac->add_bias = 0.0f;
574 ac->sf_scale = 1. / -1024.;
71e9a1b8
RS
575 ac->sf_offset = 60;
576 }
577
e29af818 578 ff_aac_tableinit();
71e9a1b8 579
37d3e066 580 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
577d383b
DB
581 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
582 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
583 352);
71e9a1b8 584
7d485f16
SS
585 ff_mdct_init(&ac->mdct, 11, 1, 1.0);
586 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0);
9ffd5c1c
RS
587 // window initialization
588 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
589 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
14b86070
RD
590 ff_init_ff_sine_windows(10);
591 ff_init_ff_sine_windows( 7);
9ffd5c1c 592
c26bce10 593 cbrt_tableinit();
dc0d86fa 594
71e9a1b8
RS
595 return 0;
596}
597
9cc04edf
RS
598/**
599 * Skip data_stream_element; reference: table 4.10.
600 */
8d637124 601static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
577d383b 602{
71e9a1b8
RS
603 int byte_align = get_bits1(gb);
604 int count = get_bits(gb, 8);
605 if (count == 255)
606 count += get_bits(gb, 8);
607 if (byte_align)
608 align_get_bits(gb);
8d637124
AC
609
610 if (get_bits_left(gb) < 8 * count) {
dd8871a6 611 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
612 return -1;
613 }
71e9a1b8 614 skip_bits_long(gb, 8 * count);
8d637124 615 return 0;
71e9a1b8
RS
616}
617
577d383b
DB
618static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
619 GetBitContext *gb)
620{
7633a041
AC
621 int sfb;
622 if (get_bits1(gb)) {
623 ics->predictor_reset_group = get_bits(gb, 5);
624 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
dd8871a6 625 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
7633a041
AC
626 return -1;
627 }
628 }
629 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
630 ics->prediction_used[sfb] = get_bits1(gb);
631 }
632 return 0;
633}
634
71e9a1b8 635/**
9cc04edf
RS
636 * Decode Individual Channel Stream info; reference: table 4.6.
637 *
638 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
639 */
577d383b
DB
640static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
641 GetBitContext *gb, int common_window)
642{
9cc04edf 643 if (get_bits1(gb)) {
dd8871a6 644 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
9cc04edf
RS
645 memset(ics, 0, sizeof(IndividualChannelStream));
646 return -1;
647 }
648 ics->window_sequence[1] = ics->window_sequence[0];
649 ics->window_sequence[0] = get_bits(gb, 2);
577d383b
DB
650 ics->use_kb_window[1] = ics->use_kb_window[0];
651 ics->use_kb_window[0] = get_bits1(gb);
652 ics->num_window_groups = 1;
653 ics->group_len[0] = 1;
9ffd5c1c
RS
654 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
655 int i;
656 ics->max_sfb = get_bits(gb, 4);
657 for (i = 0; i < 7; i++) {
658 if (get_bits1(gb)) {
577d383b 659 ics->group_len[ics->num_window_groups - 1]++;
9ffd5c1c
RS
660 } else {
661 ics->num_window_groups++;
577d383b 662 ics->group_len[ics->num_window_groups - 1] = 1;
9ffd5c1c
RS
663 }
664 }
577d383b
DB
665 ics->num_windows = 8;
666 ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
667 ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
668 ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
7633a041 669 ics->predictor_present = 0;
9ffd5c1c 670 } else {
577d383b
DB
671 ics->max_sfb = get_bits(gb, 6);
672 ics->num_windows = 1;
673 ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
674 ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
675 ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
676 ics->predictor_present = get_bits1(gb);
7633a041
AC
677 ics->predictor_reset_group = 0;
678 if (ics->predictor_present) {
679 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
680 if (decode_prediction(ac, ics, gb)) {
681 memset(ics, 0, sizeof(IndividualChannelStream));
682 return -1;
683 }
684 } else if (ac->m4ac.object_type == AOT_AAC_LC) {
dd8871a6 685 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
7633a041
AC
686 memset(ics, 0, sizeof(IndividualChannelStream));
687 return -1;
688 } else {
dd8871a6 689 av_log_missing_feature(ac->avctx, "Predictor bit set but LTP is", 1);
8f5aaa6d
RS
690 memset(ics, 0, sizeof(IndividualChannelStream));
691 return -1;
7633a041 692 }
62a57fae
RS
693 }
694 }
695
577d383b 696 if (ics->max_sfb > ics->num_swb) {
dd8871a6 697 av_log(ac->avctx, AV_LOG_ERROR,
577d383b
DB
698 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
699 ics->max_sfb, ics->num_swb);
62a57fae
RS
700 memset(ics, 0, sizeof(IndividualChannelStream));
701 return -1;
702 }
703
9cc04edf
RS
704 return 0;
705}
706
707/**
9cc04edf
RS
708 * Decode band types (section_data payload); reference: table 4.46.
709 *
710 * @param band_type array of the used band type
711 * @param band_type_run_end array of the last scalefactor band of a band type run
712 *
713 * @return Returns error status. 0 - OK, !0 - error
714 */
577d383b
DB
715static int decode_band_types(AACContext *ac, enum BandType band_type[120],
716 int band_type_run_end[120], GetBitContext *gb,
717 IndividualChannelStream *ics)
718{
cc0591da
RS
719 int g, idx = 0;
720 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
721 for (g = 0; g < ics->num_window_groups; g++) {
722 int k = 0;
723 while (k < ics->max_sfb) {
01d19fbc 724 uint8_t sect_end = k;
cc0591da
RS
725 int sect_len_incr;
726 int sect_band_type = get_bits(gb, 4);
727 if (sect_band_type == 12) {
dd8871a6 728 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
cc0591da
RS
729 return -1;
730 }
577d383b 731 while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
01d19fbc
AC
732 sect_end += sect_len_incr;
733 sect_end += sect_len_incr;
c4a90caa 734 if (get_bits_left(gb) < 0) {
dd8871a6 735 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
c4a90caa
AC
736 return -1;
737 }
01d19fbc 738 if (sect_end > ics->max_sfb) {
dd8871a6 739 av_log(ac->avctx, AV_LOG_ERROR,
577d383b 740 "Number of bands (%d) exceeds limit (%d).\n",
01d19fbc 741 sect_end, ics->max_sfb);
cc0591da
RS
742 return -1;
743 }
01d19fbc 744 for (; k < sect_end; k++) {
9ffd5c1c 745 band_type [idx] = sect_band_type;
01d19fbc 746 band_type_run_end[idx++] = sect_end;
9ffd5c1c 747 }
9cc04edf
RS
748 }
749 }
750 return 0;
751}
cc0591da 752
9cc04edf
RS
753/**
754 * Decode scalefactors; reference: table 4.47.
cc0591da 755 *
cc0591da
RS
756 * @param global_gain first scalefactor value as scalefactors are differentially coded
757 * @param band_type array of the used band type
758 * @param band_type_run_end array of the last scalefactor band of a band type run
759 * @param sf array of scalefactors or intensity stereo positions
760 *
761 * @return Returns error status. 0 - OK, !0 - error
762 */
577d383b
DB
763static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
764 unsigned int global_gain,
765 IndividualChannelStream *ics,
766 enum BandType band_type[120],
767 int band_type_run_end[120])
768{
cc0591da
RS
769 const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
770 int g, i, idx = 0;
771 int offset[3] = { global_gain, global_gain - 90, 100 };
772 int noise_flag = 1;
773 static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
cc0591da
RS
774 for (g = 0; g < ics->num_window_groups; g++) {
775 for (i = 0; i < ics->max_sfb;) {
776 int run_end = band_type_run_end[idx];
777 if (band_type[idx] == ZERO_BT) {
577d383b 778 for (; i < run_end; i++, idx++)
cc0591da 779 sf[idx] = 0.;
577d383b
DB
780 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
781 for (; i < run_end; i++, idx++) {
cc0591da 782 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 783 if (offset[2] > 255U) {
dd8871a6 784 av_log(ac->avctx, AV_LOG_ERROR,
577d383b 785 "%s (%d) out of range.\n", sf_str[2], offset[2]);
cc0591da
RS
786 return -1;
787 }
577d383b 788 sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
cc0591da 789 }
577d383b
DB
790 } else if (band_type[idx] == NOISE_BT) {
791 for (; i < run_end; i++, idx++) {
792 if (noise_flag-- > 0)
cc0591da
RS
793 offset[1] += get_bits(gb, 9) - 256;
794 else
795 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 796 if (offset[1] > 255U) {
dd8871a6 797 av_log(ac->avctx, AV_LOG_ERROR,
577d383b 798 "%s (%d) out of range.\n", sf_str[1], offset[1]);
cc0591da
RS
799 return -1;
800 }
577d383b 801 sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
cc0591da 802 }
577d383b
DB
803 } else {
804 for (; i < run_end; i++, idx++) {
cc0591da 805 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 806 if (offset[0] > 255U) {
dd8871a6 807 av_log(ac->avctx, AV_LOG_ERROR,
577d383b 808 "%s (%d) out of range.\n", sf_str[0], offset[0]);
cc0591da
RS
809 return -1;
810 }
811 sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
cc0591da
RS
812 }
813 }
814 }
815 }
816 return 0;
817}
818
819/**
820 * Decode pulse data; reference: table 4.7.
821 */
577d383b
DB
822static int decode_pulses(Pulse *pulse, GetBitContext *gb,
823 const uint16_t *swb_offset, int num_swb)
824{
aac0eda4 825 int i, pulse_swb;
cc0591da 826 pulse->num_pulse = get_bits(gb, 2) + 1;
aac0eda4
AC
827 pulse_swb = get_bits(gb, 6);
828 if (pulse_swb >= num_swb)
829 return -1;
830 pulse->pos[0] = swb_offset[pulse_swb];
408992ba 831 pulse->pos[0] += get_bits(gb, 5);
aac0eda4
AC
832 if (pulse->pos[0] > 1023)
833 return -1;
848a5815
RS
834 pulse->amp[0] = get_bits(gb, 4);
835 for (i = 1; i < pulse->num_pulse; i++) {
577d383b 836 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
aac0eda4
AC
837 if (pulse->pos[i] > 1023)
838 return -1;
848a5815 839 pulse->amp[i] = get_bits(gb, 4);
cc0591da 840 }
aac0eda4 841 return 0;
cc0591da
RS
842}
843
844/**
1dece0d2
RS
845 * Decode Temporal Noise Shaping data; reference: table 4.48.
846 *
847 * @return Returns error status. 0 - OK, !0 - error
848 */
577d383b
DB
849static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
850 GetBitContext *gb, const IndividualChannelStream *ics)
851{
1dece0d2
RS
852 int w, filt, i, coef_len, coef_res, coef_compress;
853 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
854 const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
855 for (w = 0; w < ics->num_windows; w++) {
fbd91d7c 856 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1dece0d2
RS
857 coef_res = get_bits1(gb);
858
65b20b24
RS
859 for (filt = 0; filt < tns->n_filt[w]; filt++) {
860 int tmp2_idx;
577d383b 861 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
65b20b24 862
577d383b 863 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
dd8871a6 864 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
65b20b24
RS
865 tns->order[w][filt], tns_max_order);
866 tns->order[w][filt] = 0;
867 return -1;
868 }
51673647 869 if (tns->order[w][filt]) {
35445d29
RS
870 tns->direction[w][filt] = get_bits1(gb);
871 coef_compress = get_bits1(gb);
872 coef_len = coef_res + 3 - coef_compress;
577d383b 873 tmp2_idx = 2 * coef_compress + coef_res;
1dece0d2 874
35445d29
RS
875 for (i = 0; i < tns->order[w][filt]; i++)
876 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
51673647 877 }
65b20b24 878 }
fbd91d7c 879 }
1dece0d2
RS
880 }
881 return 0;
882}
883
884/**
9cc04edf
RS
885 * Decode Mid/Side data; reference: table 4.54.
886 *
887 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
888 * [1] mask is decoded from bitstream; [2] mask is all 1s;
889 * [3] reserved for scalable AAC
890 */
577d383b
DB
891static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
892 int ms_present)
893{
62a57fae
RS
894 int idx;
895 if (ms_present == 1) {
896 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
897 cpe->ms_mask[idx] = get_bits1(gb);
898 } else if (ms_present == 2) {
899 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
900 }
901}
9cc04edf 902
798339fb 903#ifndef VMUL2
c816d3d0
MR
904static inline float *VMUL2(float *dst, const float *v, unsigned idx,
905 const float *scale)
906{
907 float s = *scale;
908 *dst++ = v[idx & 15] * s;
909 *dst++ = v[idx>>4 & 15] * s;
910 return dst;
911}
798339fb 912#endif
c816d3d0 913
798339fb 914#ifndef VMUL4
c816d3d0
MR
915static inline float *VMUL4(float *dst, const float *v, unsigned idx,
916 const float *scale)
917{
918 float s = *scale;
919 *dst++ = v[idx & 3] * s;
920 *dst++ = v[idx>>2 & 3] * s;
921 *dst++ = v[idx>>4 & 3] * s;
922 *dst++ = v[idx>>6 & 3] * s;
923 return dst;
924}
798339fb 925#endif
c816d3d0 926
798339fb 927#ifndef VMUL2S
c816d3d0
MR
928static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
929 unsigned sign, const float *scale)
930{
931 union float754 s0, s1;
932
933 s0.f = s1.f = *scale;
934 s0.i ^= sign >> 1 << 31;
935 s1.i ^= sign << 31;
936
937 *dst++ = v[idx & 15] * s0.f;
938 *dst++ = v[idx>>4 & 15] * s1.f;
939
940 return dst;
941}
798339fb 942#endif
c816d3d0 943
798339fb 944#ifndef VMUL4S
c816d3d0
MR
945static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
946 unsigned sign, const float *scale)
947{
948 unsigned nz = idx >> 12;
949 union float754 s = { .f = *scale };
950 union float754 t;
951
952 t.i = s.i ^ (sign & 1<<31);
953 *dst++ = v[idx & 3] * t.f;
954
955 sign <<= nz & 1; nz >>= 1;
956 t.i = s.i ^ (sign & 1<<31);
957 *dst++ = v[idx>>2 & 3] * t.f;
958
959 sign <<= nz & 1; nz >>= 1;
960 t.i = s.i ^ (sign & 1<<31);
961 *dst++ = v[idx>>4 & 3] * t.f;
962
963 sign <<= nz & 1; nz >>= 1;
964 t.i = s.i ^ (sign & 1<<31);
965 *dst++ = v[idx>>6 & 3] * t.f;
966
967 return dst;
968}
798339fb 969#endif
c816d3d0 970
9cc04edf 971/**
9ffd5c1c
RS
972 * Decode spectral data; reference: table 4.50.
973 * Dequantize and scale spectral data; reference: 4.6.3.3.
974 *
975 * @param coef array of dequantized, scaled spectral data
976 * @param sf array of scalefactors or intensity stereo positions
977 * @param pulse_present set if pulses are present
978 * @param pulse pointer to pulse data struct
979 * @param band_type array of the used band type
980 *
981 * @return Returns error status. 0 - OK, !0 - error
982 */
577d383b 983static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
3963a17d 984 GetBitContext *gb, const float sf[120],
577d383b
DB
985 int pulse_present, const Pulse *pulse,
986 const IndividualChannelStream *ics,
987 enum BandType band_type[120])
988{
9ffd5c1c 989 int i, k, g, idx = 0;
577d383b
DB
990 const int c = 1024 / ics->num_windows;
991 const uint16_t *offsets = ics->swb_offset;
9ffd5c1c
RS
992 float *coef_base = coef;
993
994 for (g = 0; g < ics->num_windows; g++)
577d383b 995 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
9ffd5c1c
RS
996
997 for (g = 0; g < ics->num_window_groups; g++) {
05f9d8fc
MR
998 unsigned g_len = ics->group_len[g];
999
9ffd5c1c 1000 for (i = 0; i < ics->max_sfb; i++, idx++) {
05f9d8fc
MR
1001 const unsigned cbt_m1 = band_type[idx] - 1;
1002 float *cfo = coef + offsets[i];
1003 int off_len = offsets[i + 1] - offsets[i];
9ffd5c1c 1004 int group;
05f9d8fc
MR
1005
1006 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1007 for (group = 0; group < g_len; group++, cfo+=128) {
1008 memset(cfo, 0, off_len * sizeof(float));
9ffd5c1c 1009 }
05f9d8fc
MR
1010 } else if (cbt_m1 == NOISE_BT - 1) {
1011 for (group = 0; group < g_len; group++, cfo+=128) {
d0ee5021 1012 float scale;
b418a6ca 1013 float band_energy;
42d3fbb3 1014
05f9d8fc 1015 for (k = 0; k < off_len; k++) {
9ffd5c1c 1016 ac->random_state = lcg_random(ac->random_state);
05f9d8fc 1017 cfo[k] = ac->random_state;
d0ee5021 1018 }
42d3fbb3 1019
05f9d8fc 1020 band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
d0ee5021 1021 scale = sf[idx] / sqrtf(band_energy);
05f9d8fc 1022 ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
9ffd5c1c 1023 }
577d383b 1024 } else {
05f9d8fc
MR
1025 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1026 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1027 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
d356a53f 1028 OPEN_READER(re, gb);
c816d3d0 1029
95dff4ac
MR
1030 switch (cbt_m1 >> 1) {
1031 case 0:
1032 for (group = 0; group < g_len; group++, cfo+=128) {
1033 float *cf = cfo;
1034 int len = off_len;
42d3fbb3 1035
c816d3d0 1036 do {
d356a53f 1037 int code;
c816d3d0
MR
1038 unsigned cb_idx;
1039
d356a53f
MR
1040 UPDATE_CACHE(re, gb);
1041 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1042 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1043 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1044 } while (len -= 4);
95dff4ac
MR
1045 }
1046 break;
1047
1048 case 1:
1049 for (group = 0; group < g_len; group++, cfo+=128) {
1050 float *cf = cfo;
1051 int len = off_len;
1052
c816d3d0 1053 do {
d356a53f 1054 int code;
c816d3d0
MR
1055 unsigned nnz;
1056 unsigned cb_idx;
1057 uint32_t bits;
1058
d356a53f
MR
1059 UPDATE_CACHE(re, gb);
1060 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f
MR
1061#if MIN_CACHE_BITS < 20
1062 UPDATE_CACHE(re, gb);
1063#endif
1064 cb_idx = cb_vector_idx[code];
c816d3d0 1065 nnz = cb_idx >> 8 & 15;
d356a53f
MR
1066 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1067 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1068 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1069 } while (len -= 4);
95dff4ac
MR
1070 }
1071 break;
1072
1073 case 2:
1074 for (group = 0; group < g_len; group++, cfo+=128) {
1075 float *cf = cfo;
1076 int len = off_len;
1077
c816d3d0 1078 do {
d356a53f 1079 int code;
c816d3d0
MR
1080 unsigned cb_idx;
1081
d356a53f
MR
1082 UPDATE_CACHE(re, gb);
1083 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1084 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1085 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1086 } while (len -= 2);
95dff4ac
MR
1087 }
1088 break;
1089
1090 case 3:
1091 case 4:
1092 for (group = 0; group < g_len; group++, cfo+=128) {
1093 float *cf = cfo;
1094 int len = off_len;
1095
c816d3d0 1096 do {
d356a53f 1097 int code;
c816d3d0
MR
1098 unsigned nnz;
1099 unsigned cb_idx;
1100 unsigned sign;
1101
d356a53f
MR
1102 UPDATE_CACHE(re, gb);
1103 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1104 cb_idx = cb_vector_idx[code];
c816d3d0 1105 nnz = cb_idx >> 8 & 15;
d356a53f
MR
1106 sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
1107 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1108 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1109 } while (len -= 2);
95dff4ac
MR
1110 }
1111 break;
1112
1113 default:
1114 for (group = 0; group < g_len; group++, cfo+=128) {
1115 float *cf = cfo;
1116 uint32_t *icf = (uint32_t *) cf;
1117 int len = off_len;
1118
05f9d8fc 1119 do {
d356a53f 1120 int code;
c816d3d0
MR
1121 unsigned nzt, nnz;
1122 unsigned cb_idx;
1123 uint32_t bits;
1124 int j;
1125
d356a53f
MR
1126 UPDATE_CACHE(re, gb);
1127 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1128
1129 if (!code) {
05f9d8fc
MR
1130 *icf++ = 0;
1131 *icf++ = 0;
c816d3d0
MR
1132 continue;
1133 }
1134
d356a53f 1135 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1136 nnz = cb_idx >> 12;
1137 nzt = cb_idx >> 8;
d356a53f
MR
1138 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1139 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1140
1141 for (j = 0; j < 2; j++) {
1142 if (nzt & 1<<j) {
d356a53f
MR
1143 uint32_t b;
1144 int n;
c816d3d0
MR
1145 /* The total length of escape_sequence must be < 22 bits according
1146 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
d356a53f
MR
1147 UPDATE_CACHE(re, gb);
1148 b = GET_CACHE(re, gb);
1149 b = 31 - av_log2(~b);
1150
1151 if (b > 8) {
dd8871a6 1152 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
c816d3d0
MR
1153 return -1;
1154 }
d356a53f
MR
1155
1156#if MIN_CACHE_BITS < 21
1157 LAST_SKIP_BITS(re, gb, b + 1);
1158 UPDATE_CACHE(re, gb);
1159#else
1160 SKIP_BITS(re, gb, b + 1);
1161#endif
1162 b += 4;
1163 n = (1 << b) + SHOW_UBITS(re, gb, b);
1164 LAST_SKIP_BITS(re, gb, b);
05f9d8fc 1165 *icf++ = cbrt_tab[n] | (bits & 1<<31);
c816d3d0
MR
1166 bits <<= 1;
1167 } else {
1168 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
05f9d8fc 1169 *icf++ = (bits & 1<<31) | v;
c816d3d0 1170 bits <<= !!v;
e8d5c07b 1171 }
c816d3d0 1172 cb_idx >>= 4;
9ffd5c1c 1173 }
05f9d8fc 1174 } while (len -= 2);
42d3fbb3 1175
05f9d8fc 1176 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
42d3fbb3 1177 }
9ffd5c1c 1178 }
d356a53f
MR
1179
1180 CLOSE_READER(re, gb);
9ffd5c1c
RS
1181 }
1182 }
05f9d8fc 1183 coef += g_len << 7;
9ffd5c1c
RS
1184 }
1185
1186 if (pulse_present) {
51436848 1187 idx = 0;
577d383b
DB
1188 for (i = 0; i < pulse->num_pulse; i++) {
1189 float co = coef_base[ pulse->pos[i] ];
1190 while (offsets[idx + 1] <= pulse->pos[i])
51436848
AC
1191 idx++;
1192 if (band_type[idx] != NOISE_BT && sf[idx]) {
70735a3f
RS
1193 float ico = -pulse->amp[i];
1194 if (co) {
1195 co /= sf[idx];
1196 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1197 }
1198 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
51436848 1199 }
9ffd5c1c
RS
1200 }
1201 }
1202 return 0;
1203}
1204
577d383b
DB
1205static av_always_inline float flt16_round(float pf)
1206{
4a39ccb4
AC
1207 union float754 tmp;
1208 tmp.f = pf;
1209 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1210 return tmp.f;
7633a041
AC
1211}
1212
577d383b
DB
1213static av_always_inline float flt16_even(float pf)
1214{
4a39ccb4
AC
1215 union float754 tmp;
1216 tmp.f = pf;
577d383b 1217 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
4a39ccb4 1218 return tmp.f;
7633a041
AC
1219}
1220
577d383b
DB
1221static av_always_inline float flt16_trunc(float pf)
1222{
4a39ccb4
AC
1223 union float754 pun;
1224 pun.f = pf;
1225 pun.i &= 0xFFFF0000U;
1226 return pun.f;
7633a041
AC
1227}
1228
70c99adb
AC
1229static av_always_inline void predict(PredictorState *ps, float *coef,
1230 float sf_scale, float inv_sf_scale,
577d383b
DB
1231 int output_enable)
1232{
1233 const float a = 0.953125; // 61.0 / 64
1234 const float alpha = 0.90625; // 29.0 / 32
7633a041
AC
1235 float e0, e1;
1236 float pv;
1237 float k1, k2;
81824fe0
AC
1238 float r0 = ps->r0, r1 = ps->r1;
1239 float cor0 = ps->cor0, cor1 = ps->cor1;
1240 float var0 = ps->var0, var1 = ps->var1;
7633a041 1241
81824fe0
AC
1242 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1243 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
7633a041 1244
81824fe0 1245 pv = flt16_round(k1 * r0 + k2 * r1);
7633a041 1246 if (output_enable)
70c99adb 1247 *coef += pv * sf_scale;
7633a041 1248
70c99adb 1249 e0 = *coef * inv_sf_scale;
81824fe0 1250 e1 = e0 - k1 * r0;
7633a041 1251
81824fe0
AC
1252 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1253 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1254 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1255 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
7633a041 1256
81824fe0 1257 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
7633a041
AC
1258 ps->r0 = flt16_trunc(a * e0);
1259}
1260
1261/**
1262 * Apply AAC-Main style frequency domain prediction.
1263 */
577d383b
DB
1264static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1265{
7633a041 1266 int sfb, k;
70c99adb 1267 float sf_scale = ac->sf_scale, inv_sf_scale = 1 / ac->sf_scale;
7633a041
AC
1268
1269 if (!sce->ics.predictor_initialized) {
aab54133 1270 reset_all_predictors(sce->predictor_state);
7633a041
AC
1271 sce->ics.predictor_initialized = 1;
1272 }
1273
1274 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1275 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1276 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
70c99adb
AC
1277 predict(&sce->predictor_state[k], &sce->coeffs[k],
1278 sf_scale, inv_sf_scale,
577d383b 1279 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
7633a041
AC
1280 }
1281 }
1282 if (sce->ics.predictor_reset_group)
aab54133 1283 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
7633a041 1284 } else
aab54133 1285 reset_all_predictors(sce->predictor_state);
7633a041
AC
1286}
1287
9ffd5c1c 1288/**
9cc04edf
RS
1289 * Decode an individual_channel_stream payload; reference: table 4.44.
1290 *
1291 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1292 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1293 *
1294 * @return Returns error status. 0 - OK, !0 - error
1295 */
577d383b
DB
1296static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1297 GetBitContext *gb, int common_window, int scale_flag)
1298{
9cc04edf 1299 Pulse pulse;
577d383b
DB
1300 TemporalNoiseShaping *tns = &sce->tns;
1301 IndividualChannelStream *ics = &sce->ics;
1302 float *out = sce->coeffs;
9cc04edf
RS
1303 int global_gain, pulse_present = 0;
1304
848a5815
RS
1305 /* This assignment is to silence a GCC warning about the variable being used
1306 * uninitialized when in fact it always is.
9cc04edf
RS
1307 */
1308 pulse.num_pulse = 0;
9cc04edf
RS
1309
1310 global_gain = get_bits(gb, 8);
1311
1312 if (!common_window && !scale_flag) {
1313 if (decode_ics_info(ac, ics, gb, 0) < 0)
1314 return -1;
1315 }
1316
1317 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1318 return -1;
1319 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1320 return -1;
1321
1322 pulse_present = 0;
1323 if (!scale_flag) {
1324 if ((pulse_present = get_bits1(gb))) {
1325 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
dd8871a6 1326 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
9cc04edf
RS
1327 return -1;
1328 }
aac0eda4 1329 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
dd8871a6 1330 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
aac0eda4
AC
1331 return -1;
1332 }
9cc04edf
RS
1333 }
1334 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1335 return -1;
1336 if (get_bits1(gb)) {
dd8871a6 1337 av_log_missing_feature(ac->avctx, "SSR", 1);
9cc04edf
RS
1338 return -1;
1339 }
1340 }
1341
848a5815 1342 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
9cc04edf 1343 return -1;
7633a041 1344
577d383b 1345 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
7633a041
AC
1346 apply_prediction(ac, sce);
1347
9cc04edf
RS
1348 return 0;
1349}
1350
1351/**
9ffd5c1c
RS
1352 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1353 */
42d3fbb3 1354static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
577d383b
DB
1355{
1356 const IndividualChannelStream *ics = &cpe->ch[0].ics;
9ffd5c1c
RS
1357 float *ch0 = cpe->ch[0].coeffs;
1358 float *ch1 = cpe->ch[1].coeffs;
42d3fbb3 1359 int g, i, group, idx = 0;
577d383b 1360 const uint16_t *offsets = ics->swb_offset;
9ffd5c1c
RS
1361 for (g = 0; g < ics->num_window_groups; g++) {
1362 for (i = 0; i < ics->max_sfb; i++, idx++) {
1363 if (cpe->ms_mask[idx] &&
577d383b 1364 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
9ffd5c1c 1365 for (group = 0; group < ics->group_len[g]; group++) {
42d3fbb3
MR
1366 ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1367 ch1 + group * 128 + offsets[i],
1368 offsets[i+1] - offsets[i]);
9ffd5c1c
RS
1369 }
1370 }
1371 }
577d383b
DB
1372 ch0 += ics->group_len[g] * 128;
1373 ch1 += ics->group_len[g] * 128;
9ffd5c1c
RS
1374 }
1375}
1376
1377/**
1378 * intensity stereo decoding; reference: 4.6.8.2.3
1379 *
1380 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1381 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1382 * [3] reserved for scalable AAC
1383 */
577d383b
DB
1384static void apply_intensity_stereo(ChannelElement *cpe, int ms_present)
1385{
1386 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1387 SingleChannelElement *sce1 = &cpe->ch[1];
9ffd5c1c 1388 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
577d383b 1389 const uint16_t *offsets = ics->swb_offset;
9ffd5c1c
RS
1390 int g, group, i, k, idx = 0;
1391 int c;
1392 float scale;
1393 for (g = 0; g < ics->num_window_groups; g++) {
1394 for (i = 0; i < ics->max_sfb;) {
1395 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1396 const int bt_run_end = sce1->band_type_run_end[idx];
1397 for (; i < bt_run_end; i++, idx++) {
1398 c = -1 + 2 * (sce1->band_type[idx] - 14);
1399 if (ms_present)
1400 c *= 1 - 2 * cpe->ms_mask[idx];
1401 scale = c * sce1->sf[idx];
1402 for (group = 0; group < ics->group_len[g]; group++)
577d383b
DB
1403 for (k = offsets[i]; k < offsets[i + 1]; k++)
1404 coef1[group * 128 + k] = scale * coef0[group * 128 + k];
9ffd5c1c
RS
1405 }
1406 } else {
1407 int bt_run_end = sce1->band_type_run_end[idx];
1408 idx += bt_run_end - i;
1409 i = bt_run_end;
1410 }
1411 }
577d383b
DB
1412 coef0 += ics->group_len[g] * 128;
1413 coef1 += ics->group_len[g] * 128;
9ffd5c1c
RS
1414 }
1415}
1416
1417/**
9cc04edf
RS
1418 * Decode a channel_pair_element; reference: table 4.4.
1419 *
9cc04edf
RS
1420 * @return Returns error status. 0 - OK, !0 - error
1421 */
577d383b
DB
1422static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1423{
9cc04edf 1424 int i, ret, common_window, ms_present = 0;
9cc04edf 1425
9cc04edf
RS
1426 common_window = get_bits1(gb);
1427 if (common_window) {
1428 if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
1429 return -1;
1430 i = cpe->ch[1].ics.use_kb_window[0];
1431 cpe->ch[1].ics = cpe->ch[0].ics;
1432 cpe->ch[1].ics.use_kb_window[1] = i;
1433 ms_present = get_bits(gb, 2);
577d383b 1434 if (ms_present == 3) {
dd8871a6 1435 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
9cc04edf 1436 return -1;
577d383b 1437 } else if (ms_present)
9cc04edf
RS
1438 decode_mid_side_stereo(cpe, gb, ms_present);
1439 }
1440 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1441 return ret;
1442 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1443 return ret;
1444
aab54133
AC
1445 if (common_window) {
1446 if (ms_present)
42d3fbb3 1447 apply_mid_side_stereo(ac, cpe);
aab54133
AC
1448 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1449 apply_prediction(ac, &cpe->ch[0]);
1450 apply_prediction(ac, &cpe->ch[1]);
1451 }
1452 }
9cc04edf 1453
848a5815 1454 apply_intensity_stereo(cpe, ms_present);
9cc04edf
RS
1455 return 0;
1456}
1457
93c6ff6c
AC
1458static const float cce_scale[] = {
1459 1.09050773266525765921, //2^(1/8)
1460 1.18920711500272106672, //2^(1/4)
1461 M_SQRT2,
1462 2,
1463};
1464
9ffd5c1c
RS
1465/**
1466 * Decode coupling_channel_element; reference: table 4.8.
1467 *
9ffd5c1c
RS
1468 * @return Returns error status. 0 - OK, !0 - error
1469 */
577d383b
DB
1470static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1471{
9ffd5c1c 1472 int num_gain = 0;
341b28c0 1473 int c, g, sfb, ret;
9ffd5c1c
RS
1474 int sign;
1475 float scale;
577d383b
DB
1476 SingleChannelElement *sce = &che->ch[0];
1477 ChannelCoupling *coup = &che->coup;
9ffd5c1c 1478
577d383b 1479 coup->coupling_point = 2 * get_bits1(gb);
62a57fae
RS
1480 coup->num_coupled = get_bits(gb, 3);
1481 for (c = 0; c <= coup->num_coupled; c++) {
1482 num_gain++;
1483 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1484 coup->id_select[c] = get_bits(gb, 4);
1485 if (coup->type[c] == TYPE_CPE) {
1486 coup->ch_select[c] = get_bits(gb, 2);
1487 if (coup->ch_select[c] == 3)
1488 num_gain++;
1489 } else
88de95c2 1490 coup->ch_select[c] = 2;
62a57fae 1491 }
577d383b 1492 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
62a57fae 1493
577d383b 1494 sign = get_bits(gb, 1);
93c6ff6c 1495 scale = cce_scale[get_bits(gb, 2)];
62a57fae
RS
1496
1497 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1498 return ret;
1499
1500 for (c = 0; c < num_gain; c++) {
577d383b
DB
1501 int idx = 0;
1502 int cge = 1;
62a57fae
RS
1503 int gain = 0;
1504 float gain_cache = 1.;
1505 if (c) {
1506 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1507 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
531cfe6e 1508 gain_cache = powf(scale, -gain);
62a57fae 1509 }
f1ade11e
AC
1510 if (coup->coupling_point == AFTER_IMDCT) {
1511 coup->gain[c][0] = gain_cache;
1512 } else {
03b12747
AC
1513 for (g = 0; g < sce->ics.num_window_groups; g++) {
1514 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1515 if (sce->band_type[idx] != ZERO_BT) {
1516 if (!cge) {
1517 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 1518 if (t) {
03b12747
AC
1519 int s = 1;
1520 t = gain += t;
1521 if (sign) {
1522 s -= 2 * (t & 0x1);
1523 t >>= 1;
1524 }
531cfe6e 1525 gain_cache = powf(scale, -t) * s;
62a57fae 1526 }
62a57fae 1527 }
03b12747 1528 coup->gain[c][idx] = gain_cache;
62a57fae 1529 }
62a57fae 1530 }
f80a8ca5
RS
1531 }
1532 }
62a57fae
RS
1533 }
1534 return 0;
1535}
1536
9cc04edf 1537/**
62a57fae
RS
1538 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1539 *
1540 * @return Returns number of bytes consumed.
1541 */
577d383b
DB
1542static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1543 GetBitContext *gb)
1544{
62a57fae
RS
1545 int i;
1546 int num_excl_chan = 0;
1547
1548 do {
1549 for (i = 0; i < 7; i++)
1550 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1551 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1552
1553 return num_excl_chan / 7;
1554}
1555
1556/**
9cc04edf
RS
1557 * Decode dynamic range information; reference: table 4.52.
1558 *
1559 * @param cnt length of TYPE_FIL syntactic element in bytes
1560 *
1561 * @return Returns number of bytes consumed.
1562 */
577d383b
DB
1563static int decode_dynamic_range(DynamicRangeControl *che_drc,
1564 GetBitContext *gb, int cnt)
1565{
1566 int n = 1;
9cc04edf
RS
1567 int drc_num_bands = 1;
1568 int i;
1569
1570 /* pce_tag_present? */
577d383b 1571 if (get_bits1(gb)) {
9cc04edf
RS
1572 che_drc->pce_instance_tag = get_bits(gb, 4);
1573 skip_bits(gb, 4); // tag_reserved_bits
1574 n++;
1575 }
1576
1577 /* excluded_chns_present? */
577d383b 1578 if (get_bits1(gb)) {
9cc04edf
RS
1579 n += decode_drc_channel_exclusions(che_drc, gb);
1580 }
1581
1582 /* drc_bands_present? */
1583 if (get_bits1(gb)) {
1584 che_drc->band_incr = get_bits(gb, 4);
1585 che_drc->interpolation_scheme = get_bits(gb, 4);
1586 n++;
1587 drc_num_bands += che_drc->band_incr;
1588 for (i = 0; i < drc_num_bands; i++) {
1589 che_drc->band_top[i] = get_bits(gb, 8);
1590 n++;
1591 }
1592 }
1593
1594 /* prog_ref_level_present? */
1595 if (get_bits1(gb)) {
1596 che_drc->prog_ref_level = get_bits(gb, 7);
1597 skip_bits1(gb); // prog_ref_level_reserved_bits
1598 n++;
1599 }
1600
1601 for (i = 0; i < drc_num_bands; i++) {
1602 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1603 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1604 n++;
1605 }
1606
1607 return n;
1608}
1609
1610/**
1611 * Decode extension data (incomplete); reference: table 4.51.
1612 *
1613 * @param cnt length of TYPE_FIL syntactic element in bytes
1614 *
1615 * @return Returns number of bytes consumed
1616 */
ed492b61
AC
1617static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1618 ChannelElement *che, enum RawDataBlockType elem_type)
577d383b 1619{
cc0591da
RS
1620 int crc_flag = 0;
1621 int res = cnt;
1622 switch (get_bits(gb, 4)) { // extension type
577d383b
DB
1623 case EXT_SBR_DATA_CRC:
1624 crc_flag++;
1625 case EXT_SBR_DATA:
ed492b61 1626 if (!che) {
dd8871a6 1627 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
ed492b61
AC
1628 return res;
1629 } else if (!ac->m4ac.sbr) {
dd8871a6 1630 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
ed492b61
AC
1631 skip_bits_long(gb, 8 * cnt - 4);
1632 return res;
1633 } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
dd8871a6 1634 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
ed492b61
AC
1635 skip_bits_long(gb, 8 * cnt - 4);
1636 return res;
a2063901
AC
1637 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1638 ac->m4ac.sbr = 1;
1639 ac->m4ac.ps = 1;
1640 output_configure(ac, ac->che_pos, ac->che_pos, ac->m4ac.chan_config, ac->output_configured);
ed492b61
AC
1641 } else {
1642 ac->m4ac.sbr = 1;
1643 }
1644 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
577d383b
DB
1645 break;
1646 case EXT_DYNAMIC_RANGE:
1647 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1648 break;
1649 case EXT_FILL:
1650 case EXT_FILL_DATA:
1651 case EXT_DATA_ELEMENT:
1652 default:
1653 skip_bits_long(gb, 8 * cnt - 4);
1654 break;
cc0591da
RS
1655 };
1656 return res;
1657}
1658
7d8f3de4
RS
1659/**
1660 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1661 *
1662 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1663 * @param coef spectral coefficients
1664 */
577d383b
DB
1665static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1666 IndividualChannelStream *ics, int decode)
1667{
1668 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1098e8d2 1669 int w, filt, m, i;
7d8f3de4
RS
1670 int bottom, top, order, start, end, size, inc;
1671 float lpc[TNS_MAX_ORDER];
1672
1673 for (w = 0; w < ics->num_windows; w++) {
1674 bottom = ics->num_swb;
1675 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1676 top = bottom;
1677 bottom = FFMAX(0, top - tns->length[w][filt]);
1678 order = tns->order[w][filt];
1679 if (order == 0)
1680 continue;
1681
1be0fc29
VS
1682 // tns_decode_coef
1683 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
7d8f3de4 1684
1dece0d2
RS
1685 start = ics->swb_offset[FFMIN(bottom, mmm)];
1686 end = ics->swb_offset[FFMIN( top, mmm)];
1687 if ((size = end - start) <= 0)
1688 continue;
1689 if (tns->direction[w][filt]) {
577d383b
DB
1690 inc = -1;
1691 start = end - 1;
1dece0d2
RS
1692 } else {
1693 inc = 1;
1694 }
1695 start += w * 128;
1696
1697 // ar filter
1698 for (m = 0; m < size; m++, start += inc)
1699 for (i = 1; i <= FFMIN(m, order); i++)
577d383b 1700 coef[start] -= coef[start - i * inc] * lpc[i - 1];
1dece0d2
RS
1701 }
1702 }
1703}
1704
cc0591da 1705/**
9cc04edf
RS
1706 * Conduct IMDCT and windowing.
1707 */
f8a93a20 1708static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce, float bias)
577d383b
DB
1709{
1710 IndividualChannelStream *ics = &sce->ics;
1711 float *in = sce->coeffs;
1712 float *out = sce->ret;
1713 float *saved = sce->saved;
1714 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1715 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1716 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1717 float *buf = ac->buf_mdct;
1718 float *temp = ac->temp;
9cc04edf
RS
1719 int i;
1720
f4990558 1721 // imdct
62a57fae 1722 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
b0f5852a
RS
1723 for (i = 0; i < 1024; i += 128)
1724 ff_imdct_half(&ac->mdct_small, buf + i, in + i);
f4990558 1725 } else
b0f5852a 1726 ff_imdct_half(&ac->mdct, buf, in);
f4990558
RS
1727
1728 /* window overlapping
1729 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1730 * and long to short transitions are considered to be short to short
1731 * transitions. This leaves just two cases (long to long and short to short)
1732 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1733 */
1734 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
577d383b 1735 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
f8a93a20 1736 ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, bias, 512);
f4990558 1737 } else {
db38c386 1738 for (i = 0; i < 448; i++)
f8a93a20 1739 out[i] = saved[i] + bias;
62a57fae 1740
f4990558 1741 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
f8a93a20
AC
1742 ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, bias, 64);
1743 ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, bias, 64);
1744 ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, bias, 64);
1745 ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, bias, 64);
1746 ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, bias, 64);
b0f5852a 1747 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
f4990558 1748 } else {
f8a93a20 1749 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, bias, 64);
db38c386 1750 for (i = 576; i < 1024; i++)
f8a93a20 1751 out[i] = buf[i-512] + bias;
f4990558
RS
1752 }
1753 }
62a57fae 1754
f4990558
RS
1755 // buffer update
1756 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
b0f5852a 1757 for (i = 0; i < 64; i++)
f8a93a20 1758 saved[i] = temp[64 + i] - bias;
b0f5852a
RS
1759 ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
1760 ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
1761 ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
1762 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
f4990558 1763 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
b0f5852a
RS
1764 memcpy( saved, buf + 512, 448 * sizeof(float));
1765 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
f4990558 1766 } else { // LONG_STOP or ONLY_LONG
b0f5852a 1767 memcpy( saved, buf + 512, 512 * sizeof(float));
62a57fae
RS
1768 }
1769}
1770
9cc04edf 1771/**
cc0591da
RS
1772 * Apply dependent channel coupling (applied before IMDCT).
1773 *
1774 * @param index index into coupling gain array
1775 */
577d383b
DB
1776static void apply_dependent_coupling(AACContext *ac,
1777 SingleChannelElement *target,
1778 ChannelElement *cce, int index)
1779{
1780 IndividualChannelStream *ics = &cce->ch[0].ics;
1781 const uint16_t *offsets = ics->swb_offset;
1782 float *dest = target->coeffs;
1783 const float *src = cce->ch[0].coeffs;
cc0591da 1784 int g, i, group, k, idx = 0;
577d383b 1785 if (ac->m4ac.object_type == AOT_AAC_LTP) {
dd8871a6 1786 av_log(ac->avctx, AV_LOG_ERROR,
cc0591da
RS
1787 "Dependent coupling is not supported together with LTP\n");
1788 return;
1789 }
1790 for (g = 0; g < ics->num_window_groups; g++) {
1791 for (i = 0; i < ics->max_sfb; i++, idx++) {
fbdae895 1792 if (cce->ch[0].band_type[idx] != ZERO_BT) {
cfd937b0 1793 const float gain = cce->coup.gain[index][idx];
cc0591da 1794 for (group = 0; group < ics->group_len[g]; group++) {
577d383b 1795 for (k = offsets[i]; k < offsets[i + 1]; k++) {
cc0591da 1796 // XXX dsputil-ize
577d383b 1797 dest[group * 128 + k] += gain * src[group * 128 + k];
cc0591da
RS
1798 }
1799 }
1800 }
1801 }
577d383b
DB
1802 dest += ics->group_len[g] * 128;
1803 src += ics->group_len[g] * 128;
cc0591da
RS
1804 }
1805}
1806
1807/**
1808 * Apply independent channel coupling (applied after IMDCT).
1809 *
1810 * @param index index into coupling gain array
1811 */
577d383b
DB
1812static void apply_independent_coupling(AACContext *ac,
1813 SingleChannelElement *target,
1814 ChannelElement *cce, int index)
1815{
cc0591da 1816 int i;
039821a8
AC
1817 const float gain = cce->coup.gain[index][0];
1818 const float bias = ac->add_bias;
577d383b
DB
1819 const float *src = cce->ch[0].ret;
1820 float *dest = target->ret;
ed492b61 1821 const int len = 1024 << (ac->m4ac.sbr == 1);
039821a8 1822
ed492b61 1823 for (i = 0; i < len; i++)
039821a8 1824 dest[i] += gain * (src[i] - bias);
cc0591da
RS
1825}
1826
9ffd5c1c
RS
1827/**
1828 * channel coupling transformation interface
1829 *
9ffd5c1c
RS
1830 * @param apply_coupling_method pointer to (in)dependent coupling function
1831 */
577d383b
DB
1832static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
1833 enum RawDataBlockType type, int elem_id,
1834 enum CouplingPoint coupling_point,
1835 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
9ffd5c1c 1836{
88de95c2
AC
1837 int i, c;
1838
1839 for (i = 0; i < MAX_ELEM_ID; i++) {
1840 ChannelElement *cce = ac->che[TYPE_CCE][i];
1841 int index = 0;
1842
1843 if (cce && cce->coup.coupling_point == coupling_point) {
577d383b 1844 ChannelCoupling *coup = &cce->coup;
88de95c2
AC
1845
1846 for (c = 0; c <= coup->num_coupled; c++) {
1847 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
1848 if (coup->ch_select[c] != 1) {
1849 apply_coupling_method(ac, &cc->ch[0], cce, index);
1850 if (coup->ch_select[c] != 0)
1851 index++;
1852 }
1853 if (coup->ch_select[c] != 2)
1854 apply_coupling_method(ac, &cc->ch[1], cce, index++);
1855 } else
1856 index += 1 + (coup->ch_select[c] == 3);
9ffd5c1c 1857 }
9ffd5c1c
RS
1858 }
1859 }
1860}
1861
1862/**
1863 * Convert spectral data to float samples, applying all supported tools as appropriate.
1864 */
577d383b
DB
1865static void spectral_to_sample(AACContext *ac)
1866{
b0bc928b 1867 int i, type;
f8a93a20 1868 float imdct_bias = (ac->m4ac.sbr <= 0) ? ac->add_bias : 0.0f;
b0bc928b 1869 for (type = 3; type >= 0; type--) {
88de95c2 1870 for (i = 0; i < MAX_ELEM_ID; i++) {
9ffd5c1c 1871 ChannelElement *che = ac->che[type][i];
577d383b
DB
1872 if (che) {
1873 if (type <= TYPE_CPE)
88de95c2 1874 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
577d383b 1875 if (che->ch[0].tns.present)
9ffd5c1c 1876 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
577d383b 1877 if (che->ch[1].tns.present)
9ffd5c1c 1878 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
577d383b 1879 if (type <= TYPE_CPE)
88de95c2 1880 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
ed492b61 1881 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
f8a93a20 1882 imdct_and_windowing(ac, &che->ch[0], imdct_bias);
d0dedce7
AC
1883 if (type == TYPE_CPE) {
1884 imdct_and_windowing(ac, &che->ch[1], imdct_bias);
1885 }
ca6d3f23
AC
1886 if (ac->m4ac.sbr > 0) {
1887 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
1888 }
ed492b61 1889 }
577d383b 1890 if (type <= TYPE_CCE)
88de95c2 1891 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
62a57fae
RS
1892 }
1893 }
1894 }
1895}
1896
577d383b
DB
1897static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
1898{
158b3912
RS
1899 int size;
1900 AACADTSHeaderInfo hdr_info;
1901
1902 size = ff_aac_parse_header(gb, &hdr_info);
1903 if (size > 0) {
981b8fd7 1904 if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
6308765c
AC
1905 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1906 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
158b3912 1907 ac->m4ac.chan_config = hdr_info.chan_config;
6c003e6d 1908 if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
6308765c 1909 return -7;
981b8fd7 1910 if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
6308765c 1911 return -7;
981b8fd7
AC
1912 } else if (ac->output_configured != OC_LOCKED) {
1913 ac->output_configured = OC_NONE;
6308765c 1914 }
a2063901 1915 if (ac->output_configured != OC_LOCKED) {
38610d92 1916 ac->m4ac.sbr = -1;
a2063901
AC
1917 ac->m4ac.ps = -1;
1918 }
158b3912
RS
1919 ac->m4ac.sample_rate = hdr_info.sample_rate;
1920 ac->m4ac.sampling_index = hdr_info.sampling_index;
1921 ac->m4ac.object_type = hdr_info.object_type;
dd8871a6
AC
1922 if (!ac->avctx->sample_rate)
1923 ac->avctx->sample_rate = hdr_info.sample_rate;
7d87e2ce
AC
1924 if (hdr_info.num_aac_frames == 1) {
1925 if (!hdr_info.crc_absent)
1926 skip_bits(gb, 16);
1927 } else {
dd8871a6 1928 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
7d87e2ce
AC
1929 return -1;
1930 }
51741a82 1931 }
158b3912
RS
1932 return size;
1933}
1934
66a71d98
JG
1935static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
1936 int *data_size, GetBitContext *gb)
577d383b 1937{
dd8871a6 1938 AACContext *ac = avctx->priv_data;
ed492b61 1939 ChannelElement *che = NULL, *che_prev = NULL;
ed492b61 1940 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
62a57fae 1941 int err, elem_id, data_size_tmp;
fda36b59 1942 int samples = 0, multiplier;
62a57fae 1943
66a71d98
JG
1944 if (show_bits(gb, 12) == 0xfff) {
1945 if (parse_adts_frame_header(ac, gb) < 0) {
dd8871a6 1946 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
158b3912
RS
1947 return -1;
1948 }
30272450 1949 if (ac->m4ac.sampling_index > 12) {
dd8871a6 1950 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
f418b861
JM
1951 return -1;
1952 }
158b3912
RS
1953 }
1954
bb2d8e9f 1955 ac->tags_mapped = 0;
62a57fae 1956 // parse
66a71d98
JG
1957 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
1958 elem_id = get_bits(gb, 4);
62a57fae 1959
ed99e54d 1960 if (elem_type < TYPE_DSE) {
d4e355d5
AC
1961 if (!(che=get_che(ac, elem_type, elem_id))) {
1962 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
1963 elem_type, elem_id);
1964 return -1;
1965 }
fda36b59 1966 samples = 1024;
ed99e54d 1967 }
fda36b59 1968
62a57fae
RS
1969 switch (elem_type) {
1970
1971 case TYPE_SCE:
66a71d98 1972 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
62a57fae
RS
1973 break;
1974
1975 case TYPE_CPE:
66a71d98 1976 err = decode_cpe(ac, gb, che);
62a57fae
RS
1977 break;
1978
1979 case TYPE_CCE:
66a71d98 1980 err = decode_cce(ac, gb, che);
62a57fae
RS
1981 break;
1982
1983 case TYPE_LFE:
66a71d98 1984 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
62a57fae
RS
1985 break;
1986
1987 case TYPE_DSE:
66a71d98 1988 err = skip_data_stream_element(ac, gb);
62a57fae
RS
1989 break;
1990
577d383b 1991 case TYPE_PCE: {
62a57fae
RS
1992 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
1993 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
6c003e6d 1994 if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
62a57fae 1995 break;
4e878a18 1996 if (ac->output_configured > OC_TRIAL_PCE)
dd8871a6 1997 av_log(avctx, AV_LOG_ERROR,
6308765c
AC
1998 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
1999 else
981b8fd7 2000 err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
62a57fae
RS
2001 break;
2002 }
2003
2004 case TYPE_FIL:
2005 if (elem_id == 15)
66a71d98
JG
2006 elem_id += get_bits(gb, 8) - 1;
2007 if (get_bits_left(gb) < 8 * elem_id) {
dd8871a6 2008 av_log(avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
2009 return -1;
2010 }
62a57fae 2011 while (elem_id > 0)
66a71d98 2012 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
62a57fae
RS
2013 err = 0; /* FIXME */
2014 break;
2015
2016 default:
2017 err = -1; /* should not happen, but keeps compiler happy */
2018 break;
2019 }
2020
ed492b61
AC
2021 che_prev = che;
2022 elem_type_prev = elem_type;
2023
577d383b 2024 if (err)
62a57fae 2025 return err;
8d637124 2026
66a71d98 2027 if (get_bits_left(gb) < 3) {
dd8871a6 2028 av_log(avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
2029 return -1;
2030 }
62a57fae
RS
2031 }
2032
2033 spectral_to_sample(ac);
2034
ed492b61 2035 multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
54f158bd
AC
2036 samples <<= multiplier;
2037 if (ac->output_configured < OC_LOCKED) {
dd8871a6
AC
2038 avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2039 avctx->frame_size = samples;
54f158bd
AC
2040 }
2041
dd8871a6 2042 data_size_tmp = samples * avctx->channels * sizeof(int16_t);
577d383b 2043 if (*data_size < data_size_tmp) {
dd8871a6 2044 av_log(avctx, AV_LOG_ERROR,
9cc04edf
RS
2045 "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
2046 *data_size, data_size_tmp);
2047 return -1;
2048 }
2049 *data_size = data_size_tmp;
2050
fda36b59 2051 if (samples)
19ed4b86 2052 ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avctx->channels);
9cc04edf 2053
981b8fd7
AC
2054 if (ac->output_configured)
2055 ac->output_configured = OC_LOCKED;
2056
66a71d98
JG
2057 return 0;
2058}
2059
2060static int aac_decode_frame(AVCodecContext *avctx, void *data,
2061 int *data_size, AVPacket *avpkt)
2062{
2063 const uint8_t *buf = avpkt->data;
2064 int buf_size = avpkt->size;
2065 GetBitContext gb;
2066 int buf_consumed;
2067 int buf_offset;
2068 int err;
2069
2070 init_get_bits(&gb, buf, buf_size * 8);
2071
2072 if ((err = aac_decode_frame_int(avctx, data, data_size, &gb)) < 0)
2073 return err;
2074
b5e2bb8c 2075 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
c16d5a6f
AC
2076 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2077 if (buf[buf_offset])
2078 break;
2079
2080 return buf_size > buf_offset ? buf_consumed : buf_size;
9cc04edf
RS
2081}
2082
dd8871a6 2083static av_cold int aac_decode_close(AVCodecContext *avctx)
577d383b 2084{
dd8871a6 2085 AACContext *ac = avctx->priv_data;
9edae4ad 2086 int i, type;
71e9a1b8 2087
cc0591da 2088 for (i = 0; i < MAX_ELEM_ID; i++) {
ed492b61
AC
2089 for (type = 0; type < 4; type++) {
2090 if (ac->che[type][i])
2091 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
9edae4ad 2092 av_freep(&ac->che[type][i]);
ed492b61 2093 }
71e9a1b8
RS
2094 }
2095
2096 ff_mdct_end(&ac->mdct);
2097 ff_mdct_end(&ac->mdct_small);
577d383b 2098 return 0;
71e9a1b8
RS
2099}
2100
2101AVCodec aac_decoder = {
2102 "aac",
72415b2a 2103 AVMEDIA_TYPE_AUDIO,
71e9a1b8
RS
2104 CODEC_ID_AAC,
2105 sizeof(AACContext),
2106 aac_decode_init,
2107 NULL,
2108 aac_decode_close,
2109 aac_decode_frame,
2110 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
b5f09d31 2111 .sample_fmts = (const enum SampleFormat[]) {
577d383b
DB
2112 SAMPLE_FMT_S16,SAMPLE_FMT_NONE
2113 },
e22da6b6 2114 .channel_layouts = aac_channel_layout,
71e9a1b8 2115};