libavcodec: Don't do av_free(av_malloc(0)) for bitstream filters
[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 *
136e19e1
JG
6 * AAC LATM decoder
7 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
8 * Copyright (c) 2010 Janne Grunau <janne-ffmpeg@jannau.net>
9 *
2912e87a 10 * This file is part of Libav.
71e9a1b8 11 *
2912e87a 12 * Libav is free software; you can redistribute it and/or
71e9a1b8
RS
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.
16 *
2912e87a 17 * Libav is distributed in the hope that it will be useful,
71e9a1b8
RS
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.
21 *
22 * You should have received a copy of the GNU Lesser General Public
2912e87a 23 * License along with Libav; if not, write to the Free Software
71e9a1b8
RS
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 */
26
27/**
ba87f080 28 * @file
71e9a1b8
RS
29 * AAC decoder
30 * @author Oded Shimon ( ods15 ods15 dyndns org )
31 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
32 */
33
34/*
35 * supported tools
36 *
37 * Support? Name
38 * N (code in SoC repo) gain control
39 * Y block switching
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
ead15f1d 45 * Y Long Term Prediction
71e9a1b8
RS
46 * Y intensity stereo
47 * Y channel coupling
7633a041 48 * Y frequency domain prediction
71e9a1b8
RS
49 * Y Perceptual Noise Substitution
50 * Y Mid/Side stereo
51 * N Scalable Inverse AAC Quantization
52 * N Frequency Selective Switch
53 * N upsampling filter
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
60 * N CELP
61 * N Silence Compression
62 * N HVXC
63 * N HVXC 4kbits/s VR
64 * N Structured Audio tools
65 * N Structured Audio Sample Bank Format
66 * N MIDI
67 * N Harmonic and Individual Lines plus Noise
68 * N Text-To-Speech Interface
ed492b61 69 * Y Spectral Band Replication
71e9a1b8
RS
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)
a2063901 74 * Y Parametric Stereo
71e9a1b8
RS
75 * N Direct Stream Transfer
76 *
77 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
78 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
79 Parametric Stereo.
80 */
81
82
83#include "avcodec.h"
dbbec0c2 84#include "internal.h"
9106a698 85#include "get_bits.h"
71e9a1b8 86#include "dsputil.h"
1429224b 87#include "fft.h"
c73d99e6 88#include "fmtconvert.h"
1be0fc29 89#include "lpc.h"
a45fbda9 90#include "kbdwin.h"
4538729a 91#include "sinewin.h"
71e9a1b8
RS
92
93#include "aac.h"
94#include "aactab.h"
cc0591da 95#include "aacdectab.h"
c26bce10 96#include "cbrt_tablegen.h"
ed492b61
AC
97#include "sbr.h"
98#include "aacsbr.h"
71e9a1b8 99#include "mpeg4audio.h"
3cac899a 100#include "aacadtsdec.h"
5cd56e19 101#include "libavutil/intfloat.h"
71e9a1b8
RS
102
103#include <assert.h>
104#include <errno.h>
105#include <math.h>
106#include <string.h>
107
798339fb
MR
108#if ARCH_ARM
109# include "arm/aac.h"
110#endif
111
71e9a1b8
RS
112static VLC vlc_scalefactors;
113static VLC vlc_spectral[11];
114
8d637124
AC
115static const char overread_err[] = "Input buffer exhausted before END element found\n";
116
577d383b
DB
117static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
118{
bb2d8e9f
AC
119 // For PCE based channel configurations map the channels solely based on tags.
120 if (!ac->m4ac.chan_config) {
bb5c0988
AC
121 return ac->tag_che_map[type][elem_id];
122 }
bb2d8e9f 123 // For indexed channel configurations map the channels solely based on position.
bb5c0988 124 switch (ac->m4ac.chan_config) {
577d383b
DB
125 case 7:
126 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
127 ac->tags_mapped++;
128 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
129 }
130 case 6:
131 /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
5d55bb9f
CR
132 instead of SCE[0] CPE[0] CPE[1] LFE[0]. If we seem to have
133 encountered such a stream, transfer the LFE[0] element to the SCE[1]'s mapping */
577d383b
DB
134 if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
135 ac->tags_mapped++;
136 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
137 }
138 case 5:
139 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
140 ac->tags_mapped++;
141 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
142 }
143 case 4:
144 if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
145 ac->tags_mapped++;
146 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
147 }
148 case 3:
149 case 2:
150 if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
151 ac->tags_mapped++;
152 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
153 } else if (ac->m4ac.chan_config == 2) {
bb5c0988 154 return NULL;
577d383b
DB
155 }
156 case 1:
157 if (!ac->tags_mapped && type == TYPE_SCE) {
158 ac->tags_mapped++;
159 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
160 }
161 default:
162 return NULL;
bb5c0988
AC
163 }
164}
165
4acd43a2
AC
166static int count_channels(enum ChannelPosition che_pos[4][MAX_ELEM_ID])
167{
168 int i, type, sum = 0;
169 for (i = 0; i < MAX_ELEM_ID; i++) {
170 for (type = 0; type < 4; type++) {
171 sum += (1 + (type == TYPE_CPE)) *
172 (che_pos[type][i] != AAC_CHANNEL_OFF &&
173 che_pos[type][i] != AAC_CHANNEL_CC);
174 }
175 }
176 return sum;
177}
178
9cc04edf 179/**
754ff9a7
RS
180 * Check for the channel element in the current channel position configuration.
181 * If it exists, make sure the appropriate element is allocated and map the
2912e87a 182 * channel order to match the internal Libav channel layout.
754ff9a7
RS
183 *
184 * @param che_pos current channel position configuration
185 * @param type channel element type
186 * @param id channel element id
187 * @param channels count of the number of channels in the configuration
188 *
189 * @return Returns error status. 0 - OK, !0 - error
190 */
89584458 191static av_cold int che_configure(AACContext *ac,
e600a1e4 192 enum ChannelPosition che_pos,
9978ed7d 193 int type, int id, int *channels)
754ff9a7 194{
e600a1e4 195 if (che_pos) {
80e36425
JG
196 if (!ac->che[type][id]) {
197 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
198 return AVERROR(ENOMEM);
199 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
200 }
754ff9a7
RS
201 if (type != TYPE_CCE) {
202 ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
a2063901
AC
203 if (type == TYPE_CPE ||
204 (type == TYPE_SCE && ac->m4ac.ps == 1)) {
754ff9a7
RS
205 ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
206 }
207 }
ed492b61
AC
208 } else {
209 if (ac->che[type][id])
210 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
754ff9a7 211 av_freep(&ac->che[type][id]);
ed492b61 212 }
754ff9a7
RS
213 return 0;
214}
215
216/**
62a57fae
RS
217 * Configure output channel order based on the current program configuration element.
218 *
219 * @param che_pos current channel position configuration
220 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
221 *
222 * @return Returns error status. 0 - OK, !0 - error
223 */
ff98c17c 224static av_cold int output_configure(AACContext *ac,
9978ed7d
YHL
225 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
226 int channel_config, enum OCStatus oc_type)
577d383b 227{
dd8871a6 228 AVCodecContext *avctx = ac->avctx;
754ff9a7 229 int i, type, channels = 0, ret;
62a57fae 230
e600a1e4
AC
231 if (new_che_pos)
232 memcpy(ac->che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
62a57fae 233
e22da6b6
RS
234 if (channel_config) {
235 for (i = 0; i < tags_per_config[channel_config]; i++) {
e600a1e4
AC
236 int id = aac_channel_layout_map[channel_config - 1][i][1];
237 type = aac_channel_layout_map[channel_config - 1][i][0];
238 if ((ret = che_configure(ac, ac->che_pos[type][id],
239 type, id, &channels)))
754ff9a7 240 return ret;
e22da6b6
RS
241 }
242
9978ed7d 243 memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
e22da6b6
RS
244
245 avctx->channel_layout = aac_channel_layout[channel_config - 1];
246 } else {
2309923c
RS
247 /* Allocate or free elements depending on if they are in the
248 * current program configuration.
249 *
250 * Set up default 1:1 output mapping.
2309923c
RS
251 */
252
253 for (i = 0; i < MAX_ELEM_ID; i++) {
254 for (type = 0; type < 4; type++) {
e600a1e4
AC
255 if ((ret = che_configure(ac, ac->che_pos[type][i],
256 type, i, &channels)))
754ff9a7 257 return ret;
2309923c 258 }
62a57fae 259 }
62a57fae 260
bb5c0988 261 memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
e22da6b6
RS
262
263 avctx->channel_layout = 0;
bb5c0988
AC
264 }
265
62a57fae 266 avctx->channels = channels;
bb5c0988 267
981b8fd7 268 ac->output_configured = oc_type;
6308765c 269
62a57fae
RS
270 return 0;
271}
272
273/**
9cc04edf
RS
274 * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
275 *
276 * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
277 * @param sce_map mono (Single Channel Element) map
278 * @param type speaker type/position for these channels
279 */
280static void decode_channel_map(enum ChannelPosition *cpe_map,
577d383b
DB
281 enum ChannelPosition *sce_map,
282 enum ChannelPosition type,
283 GetBitContext *gb, int n)
284{
285 while (n--) {
9cc04edf
RS
286 enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
287 map[get_bits(gb, 4)] = type;
288 }
289}
290
291/**
292 * Decode program configuration element; reference: table 4.2.
293 *
294 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
295 *
296 * @return Returns error status. 0 - OK, !0 - error
297 */
6c003e6d
JG
298static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
299 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
577d383b
DB
300 GetBitContext *gb)
301{
99665a21 302 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
8d637124 303 int comment_len;
9cc04edf
RS
304
305 skip_bits(gb, 2); // object_type
306
99665a21 307 sampling_index = get_bits(gb, 4);
6c003e6d
JG
308 if (m4ac->sampling_index != sampling_index)
309 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 310
71e9a1b8
RS
311 num_front = get_bits(gb, 4);
312 num_side = get_bits(gb, 4);
313 num_back = get_bits(gb, 4);
314 num_lfe = get_bits(gb, 2);
315 num_assoc_data = get_bits(gb, 3);
316 num_cc = get_bits(gb, 4);
317
cc0591da
RS
318 if (get_bits1(gb))
319 skip_bits(gb, 4); // mono_mixdown_tag
320 if (get_bits1(gb))
321 skip_bits(gb, 4); // stereo_mixdown_tag
71e9a1b8 322
cc0591da
RS
323 if (get_bits1(gb))
324 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
71e9a1b8 325
cc0591da
RS
326 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
327 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
328 decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
329 decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
71e9a1b8
RS
330
331 skip_bits_long(gb, 4 * num_assoc_data);
332
cc0591da 333 decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
71e9a1b8
RS
334
335 align_get_bits(gb);
336
337 /* comment field, first byte is length */
8d637124
AC
338 comment_len = get_bits(gb, 8) * 8;
339 if (get_bits_left(gb) < comment_len) {
6c003e6d 340 av_log(avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
341 return -1;
342 }
343 skip_bits_long(gb, comment_len);
cc0591da
RS
344 return 0;
345}
71e9a1b8 346
9cc04edf
RS
347/**
348 * Set up channel positions based on a default channel configuration
349 * as specified in table 1.17.
350 *
351 * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
352 *
353 * @return Returns error status. 0 - OK, !0 - error
354 */
6c003e6d 355static av_cold int set_default_channel_config(AVCodecContext *avctx,
9978ed7d
YHL
356 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
357 int channel_config)
9cc04edf 358{
577d383b 359 if (channel_config < 1 || channel_config > 7) {
6c003e6d 360 av_log(avctx, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
9cc04edf
RS
361 channel_config);
362 return -1;
363 }
364
365 /* default channel configurations:
366 *
367 * 1ch : front center (mono)
368 * 2ch : L + R (stereo)
369 * 3ch : front center + L + R
370 * 4ch : front center + L + R + back center
371 * 5ch : front center + L + R + back stereo
372 * 6ch : front center + L + R + back stereo + LFE
373 * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
374 */
375
577d383b 376 if (channel_config != 2)
9cc04edf 377 new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
577d383b 378 if (channel_config > 1)
9cc04edf 379 new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
577d383b 380 if (channel_config == 4)
9cc04edf 381 new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
577d383b 382 if (channel_config > 4)
9cc04edf 383 new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
577d383b
DB
384 = AAC_CHANNEL_BACK; // back stereo
385 if (channel_config > 5)
9cc04edf 386 new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
577d383b 387 if (channel_config == 7)
9cc04edf
RS
388 new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
389
390 return 0;
391}
392
62a57fae
RS
393/**
394 * Decode GA "General Audio" specific configuration; reference: table 4.1.
395 *
6c003e6d
JG
396 * @param ac pointer to AACContext, may be null
397 * @param avctx pointer to AVCCodecContext, used for logging
398 *
62a57fae
RS
399 * @return Returns error status. 0 - OK, !0 - error
400 */
6c003e6d
JG
401static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
402 GetBitContext *gb,
37d28953 403 MPEG4AudioConfig *m4ac,
577d383b
DB
404 int channel_config)
405{
62a57fae
RS
406 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
407 int extension_flag, ret;
408
577d383b 409 if (get_bits1(gb)) { // frameLengthFlag
6c003e6d 410 av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
9cc04edf
RS
411 return -1;
412 }
413
414 if (get_bits1(gb)) // dependsOnCoreCoder
415 skip_bits(gb, 14); // coreCoderDelay
416 extension_flag = get_bits1(gb);
417
37d28953
JG
418 if (m4ac->object_type == AOT_AAC_SCALABLE ||
419 m4ac->object_type == AOT_ER_AAC_SCALABLE)
9cc04edf
RS
420 skip_bits(gb, 3); // layerNr
421
422 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
423 if (channel_config == 0) {
424 skip_bits(gb, 4); // element_instance_tag
6c003e6d 425 if ((ret = decode_pce(avctx, m4ac, new_che_pos, gb)))
9cc04edf
RS
426 return ret;
427 } else {
6c003e6d 428 if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
9cc04edf
RS
429 return ret;
430 }
4acd43a2
AC
431
432 if (count_channels(new_che_pos) > 1) {
433 m4ac->ps = 0;
434 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
435 m4ac->ps = 1;
436
e600a1e4 437 if (ac && (ret = output_configure(ac, new_che_pos, channel_config, OC_GLOBAL_HDR)))
9cc04edf
RS
438 return ret;
439
440 if (extension_flag) {
37d28953 441 switch (m4ac->object_type) {
577d383b
DB
442 case AOT_ER_BSAC:
443 skip_bits(gb, 5); // numOfSubFrame
444 skip_bits(gb, 11); // layer_length
445 break;
446 case AOT_ER_AAC_LC:
447 case AOT_ER_AAC_LTP:
448 case AOT_ER_AAC_SCALABLE:
449 case AOT_ER_AAC_LD:
450 skip_bits(gb, 3); /* aacSectionDataResilienceFlag
9cc04edf
RS
451 * aacScalefactorDataResilienceFlag
452 * aacSpectralDataResilienceFlag
453 */
577d383b 454 break;
9cc04edf
RS
455 }
456 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
457 }
458 return 0;
459}
460
461/**
462 * Decode audio specific configuration; reference: table 1.13.
463 *
6c003e6d
JG
464 * @param ac pointer to AACContext, may be null
465 * @param avctx pointer to AVCCodecContext, used for logging
466 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
fd095539
JG
467 * @param data pointer to buffer holding an audio specific config
468 * @param bit_size size of audio specific config or data in bits
469 * @param sync_extension look for an appended sync extension
9cc04edf 470 *
be63b4ba 471 * @return Returns error status or number of consumed bits. <0 - error
9cc04edf 472 */
37d28953 473static int decode_audio_specific_config(AACContext *ac,
6c003e6d
JG
474 AVCodecContext *avctx,
475 MPEG4AudioConfig *m4ac,
fd095539
JG
476 const uint8_t *data, int bit_size,
477 int sync_extension)
577d383b 478{
9cc04edf
RS
479 GetBitContext gb;
480 int i;
481
785c4418
AC
482 av_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
483 for (i = 0; i < avctx->extradata_size; i++)
484 av_dlog(avctx, "%02x ", avctx->extradata[i]);
485 av_dlog(avctx, "\n");
486
fd095539 487 init_get_bits(&gb, data, bit_size);
9cc04edf 488
fd095539 489 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size, sync_extension)) < 0)
9cc04edf 490 return -1;
37d28953 491 if (m4ac->sampling_index > 12) {
6c003e6d 492 av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
9cc04edf
RS
493 return -1;
494 }
495
496 skip_bits_long(&gb, i);
497
37d28953 498 switch (m4ac->object_type) {
7633a041 499 case AOT_AAC_MAIN:
9cc04edf 500 case AOT_AAC_LC:
ead15f1d 501 case AOT_AAC_LTP:
6c003e6d 502 if (decode_ga_specific_config(ac, avctx, &gb, m4ac, m4ac->chan_config))
9cc04edf
RS
503 return -1;
504 break;
505 default:
6c003e6d 506 av_log(avctx, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
37d28953 507 m4ac->sbr == 1? "SBR+" : "", m4ac->object_type);
9cc04edf
RS
508 return -1;
509 }
37d28953 510
785c4418
AC
511 av_dlog(avctx, "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
512 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
513 m4ac->sample_rate, m4ac->sbr, m4ac->ps);
514
be63b4ba 515 return get_bits_count(&gb);
9cc04edf
RS
516}
517
62a57fae
RS
518/**
519 * linear congruential pseudorandom number generator
520 *
521 * @param previous_val pointer to the current state of the generator
522 *
523 * @return Returns a 32-bit pseudorandom integer
524 */
577d383b
DB
525static av_always_inline int lcg_random(int previous_val)
526{
62a57fae
RS
527 return previous_val * 1664525 + 1013904223;
528}
529
ab2a3028 530static av_always_inline void reset_predict_state(PredictorState *ps)
577d383b
DB
531{
532 ps->r0 = 0.0f;
533 ps->r1 = 0.0f;
7633a041
AC
534 ps->cor0 = 0.0f;
535 ps->cor1 = 0.0f;
536 ps->var0 = 1.0f;
537 ps->var1 = 1.0f;
538}
539
577d383b
DB
540static void reset_all_predictors(PredictorState *ps)
541{
7633a041
AC
542 int i;
543 for (i = 0; i < MAX_PREDICTORS; i++)
544 reset_predict_state(&ps[i]);
545}
546
dafaef2f
BL
547static int sample_rate_idx (int rate)
548{
549 if (92017 <= rate) return 0;
550 else if (75132 <= rate) return 1;
551 else if (55426 <= rate) return 2;
552 else if (46009 <= rate) return 3;
553 else if (37566 <= rate) return 4;
554 else if (27713 <= rate) return 5;
555 else if (23004 <= rate) return 6;
556 else if (18783 <= rate) return 7;
557 else if (13856 <= rate) return 8;
558 else if (11502 <= rate) return 9;
559 else if (9391 <= rate) return 10;
560 else return 11;
561}
562
577d383b
DB
563static void reset_predictor_group(PredictorState *ps, int group_num)
564{
7633a041 565 int i;
577d383b 566 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
7633a041
AC
567 reset_predict_state(&ps[i]);
568}
569
8e5998f0
AC
570#define AAC_INIT_VLC_STATIC(num, size) \
571 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
572 ff_aac_spectral_bits[num], sizeof( ff_aac_spectral_bits[num][0]), sizeof( ff_aac_spectral_bits[num][0]), \
573 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), sizeof(ff_aac_spectral_codes[num][0]), \
574 size);
575
dd8871a6 576static av_cold int aac_decode_init(AVCodecContext *avctx)
577d383b 577{
dd8871a6 578 AACContext *ac = avctx->priv_data;
9aa8193a 579 float output_scale_factor;
71e9a1b8 580
dd8871a6
AC
581 ac->avctx = avctx;
582 ac->m4ac.sample_rate = avctx->sample_rate;
71e9a1b8 583
dd8871a6 584 if (avctx->extradata_size > 0) {
6c003e6d
JG
585 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
586 avctx->extradata,
fd095539 587 avctx->extradata_size*8, 1) < 0)
158b3912 588 return -1;
dafaef2f
BL
589 } else {
590 int sr, i;
591 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
592
593 sr = sample_rate_idx(avctx->sample_rate);
594 ac->m4ac.sampling_index = sr;
595 ac->m4ac.channels = avctx->channels;
06d37fed
AC
596 ac->m4ac.sbr = -1;
597 ac->m4ac.ps = -1;
dafaef2f
BL
598
599 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
600 if (ff_mpeg4audio_channels[i] == avctx->channels)
601 break;
602 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
603 i = 0;
604 }
605 ac->m4ac.chan_config = i;
606
607 if (ac->m4ac.chan_config) {
94d47382
AC
608 int ret = set_default_channel_config(avctx, new_che_pos, ac->m4ac.chan_config);
609 if (!ret)
e600a1e4 610 output_configure(ac, new_che_pos, ac->m4ac.chan_config, OC_GLOBAL_HDR);
9abc9873 611 else if (avctx->err_recognition & AV_EF_EXPLODE)
94d47382 612 return AVERROR_INVALIDDATA;
dafaef2f 613 }
158b3912 614 }
cc0591da 615
9aa8193a
JR
616 if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
617 avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
618 output_scale_factor = 1.0 / 32768.0;
619 } else {
620 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
621 output_scale_factor = 1.0;
622 }
71e9a1b8 623
2ef21b91
MR
624 AAC_INIT_VLC_STATIC( 0, 304);
625 AAC_INIT_VLC_STATIC( 1, 270);
626 AAC_INIT_VLC_STATIC( 2, 550);
627 AAC_INIT_VLC_STATIC( 3, 300);
628 AAC_INIT_VLC_STATIC( 4, 328);
629 AAC_INIT_VLC_STATIC( 5, 294);
630 AAC_INIT_VLC_STATIC( 6, 306);
631 AAC_INIT_VLC_STATIC( 7, 268);
632 AAC_INIT_VLC_STATIC( 8, 510);
633 AAC_INIT_VLC_STATIC( 9, 366);
634 AAC_INIT_VLC_STATIC(10, 462);
71e9a1b8 635
ed492b61
AC
636 ff_aac_sbr_init();
637
dd8871a6 638 dsputil_init(&ac->dsp, avctx);
c73d99e6 639 ff_fmt_convert_init(&ac->fmt_conv, avctx);
71e9a1b8 640
9cc04edf
RS
641 ac->random_state = 0x1f2e3d4c;
642
e29af818 643 ff_aac_tableinit();
71e9a1b8 644
37d3e066 645 INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
577d383b
DB
646 ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
647 ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
648 352);
71e9a1b8 649
9aa8193a
JR
650 ff_mdct_init(&ac->mdct, 11, 1, output_scale_factor/1024.0);
651 ff_mdct_init(&ac->mdct_small, 8, 1, output_scale_factor/128.0);
652 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0/output_scale_factor);
9ffd5c1c
RS
653 // window initialization
654 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
655 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
14b86070
RD
656 ff_init_ff_sine_windows(10);
657 ff_init_ff_sine_windows( 7);
9ffd5c1c 658
c26bce10 659 cbrt_tableinit();
dc0d86fa 660
0eea2129
JR
661 avcodec_get_frame_defaults(&ac->frame);
662 avctx->coded_frame = &ac->frame;
663
71e9a1b8
RS
664 return 0;
665}
666
9cc04edf
RS
667/**
668 * Skip data_stream_element; reference: table 4.10.
669 */
8d637124 670static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
577d383b 671{
71e9a1b8
RS
672 int byte_align = get_bits1(gb);
673 int count = get_bits(gb, 8);
674 if (count == 255)
675 count += get_bits(gb, 8);
676 if (byte_align)
677 align_get_bits(gb);
8d637124
AC
678
679 if (get_bits_left(gb) < 8 * count) {
dd8871a6 680 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
681 return -1;
682 }
71e9a1b8 683 skip_bits_long(gb, 8 * count);
8d637124 684 return 0;
71e9a1b8
RS
685}
686
577d383b
DB
687static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
688 GetBitContext *gb)
689{
7633a041
AC
690 int sfb;
691 if (get_bits1(gb)) {
692 ics->predictor_reset_group = get_bits(gb, 5);
693 if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
dd8871a6 694 av_log(ac->avctx, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
7633a041
AC
695 return -1;
696 }
697 }
698 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
699 ics->prediction_used[sfb] = get_bits1(gb);
700 }
701 return 0;
702}
703
71e9a1b8 704/**
ead15f1d
YHL
705 * Decode Long Term Prediction data; reference: table 4.xx.
706 */
707static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
708 GetBitContext *gb, uint8_t max_sfb)
709{
710 int sfb;
711
712 ltp->lag = get_bits(gb, 11);
767848d7 713 ltp->coef = ltp_coef[get_bits(gb, 3)];
ead15f1d
YHL
714 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
715 ltp->used[sfb] = get_bits1(gb);
716}
717
718/**
9cc04edf 719 * Decode Individual Channel Stream info; reference: table 4.6.
9cc04edf 720 */
577d383b 721static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
021914e2 722 GetBitContext *gb)
577d383b 723{
9cc04edf 724 if (get_bits1(gb)) {
dd8871a6 725 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
021914e2 726 return AVERROR_INVALIDDATA;
9cc04edf
RS
727 }
728 ics->window_sequence[1] = ics->window_sequence[0];
729 ics->window_sequence[0] = get_bits(gb, 2);
577d383b
DB
730 ics->use_kb_window[1] = ics->use_kb_window[0];
731 ics->use_kb_window[0] = get_bits1(gb);
732 ics->num_window_groups = 1;
733 ics->group_len[0] = 1;
9ffd5c1c
RS
734 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
735 int i;
736 ics->max_sfb = get_bits(gb, 4);
737 for (i = 0; i < 7; i++) {
738 if (get_bits1(gb)) {
577d383b 739 ics->group_len[ics->num_window_groups - 1]++;
9ffd5c1c
RS
740 } else {
741 ics->num_window_groups++;
577d383b 742 ics->group_len[ics->num_window_groups - 1] = 1;
9ffd5c1c
RS
743 }
744 }
577d383b
DB
745 ics->num_windows = 8;
746 ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
747 ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
748 ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
7633a041 749 ics->predictor_present = 0;
9ffd5c1c 750 } else {
577d383b
DB
751 ics->max_sfb = get_bits(gb, 6);
752 ics->num_windows = 1;
753 ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
754 ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
755 ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
756 ics->predictor_present = get_bits1(gb);
7633a041
AC
757 ics->predictor_reset_group = 0;
758 if (ics->predictor_present) {
759 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
760 if (decode_prediction(ac, ics, gb)) {
021914e2 761 return AVERROR_INVALIDDATA;
7633a041
AC
762 }
763 } else if (ac->m4ac.object_type == AOT_AAC_LC) {
dd8871a6 764 av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
021914e2 765 return AVERROR_INVALIDDATA;
7633a041 766 } else {
ead15f1d
YHL
767 if ((ics->ltp.present = get_bits(gb, 1)))
768 decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
7633a041 769 }
62a57fae
RS
770 }
771 }
772
577d383b 773 if (ics->max_sfb > ics->num_swb) {
dd8871a6 774 av_log(ac->avctx, AV_LOG_ERROR,
577d383b
DB
775 "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
776 ics->max_sfb, ics->num_swb);
021914e2 777 return AVERROR_INVALIDDATA;
62a57fae
RS
778 }
779
9cc04edf
RS
780 return 0;
781}
782
783/**
9cc04edf
RS
784 * Decode band types (section_data payload); reference: table 4.46.
785 *
786 * @param band_type array of the used band type
787 * @param band_type_run_end array of the last scalefactor band of a band type run
788 *
789 * @return Returns error status. 0 - OK, !0 - error
790 */
577d383b
DB
791static int decode_band_types(AACContext *ac, enum BandType band_type[120],
792 int band_type_run_end[120], GetBitContext *gb,
793 IndividualChannelStream *ics)
794{
cc0591da
RS
795 int g, idx = 0;
796 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
797 for (g = 0; g < ics->num_window_groups; g++) {
798 int k = 0;
799 while (k < ics->max_sfb) {
01d19fbc 800 uint8_t sect_end = k;
cc0591da
RS
801 int sect_len_incr;
802 int sect_band_type = get_bits(gb, 4);
803 if (sect_band_type == 12) {
dd8871a6 804 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
cc0591da
RS
805 return -1;
806 }
577d383b 807 while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
01d19fbc
AC
808 sect_end += sect_len_incr;
809 sect_end += sect_len_incr;
c4a90caa 810 if (get_bits_left(gb) < 0) {
dd8871a6 811 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
c4a90caa
AC
812 return -1;
813 }
01d19fbc 814 if (sect_end > ics->max_sfb) {
dd8871a6 815 av_log(ac->avctx, AV_LOG_ERROR,
577d383b 816 "Number of bands (%d) exceeds limit (%d).\n",
01d19fbc 817 sect_end, ics->max_sfb);
cc0591da
RS
818 return -1;
819 }
01d19fbc 820 for (; k < sect_end; k++) {
9ffd5c1c 821 band_type [idx] = sect_band_type;
01d19fbc 822 band_type_run_end[idx++] = sect_end;
9ffd5c1c 823 }
9cc04edf
RS
824 }
825 }
826 return 0;
827}
cc0591da 828
9cc04edf
RS
829/**
830 * Decode scalefactors; reference: table 4.47.
cc0591da 831 *
cc0591da
RS
832 * @param global_gain first scalefactor value as scalefactors are differentially coded
833 * @param band_type array of the used band type
834 * @param band_type_run_end array of the last scalefactor band of a band type run
835 * @param sf array of scalefactors or intensity stereo positions
836 *
837 * @return Returns error status. 0 - OK, !0 - error
838 */
577d383b
DB
839static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
840 unsigned int global_gain,
841 IndividualChannelStream *ics,
842 enum BandType band_type[120],
843 int band_type_run_end[120])
844{
cc0591da 845 int g, i, idx = 0;
e4744b59
AC
846 int offset[3] = { global_gain, global_gain - 90, 0 };
847 int clipped_offset;
cc0591da
RS
848 int noise_flag = 1;
849 static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
cc0591da
RS
850 for (g = 0; g < ics->num_window_groups; g++) {
851 for (i = 0; i < ics->max_sfb;) {
852 int run_end = band_type_run_end[idx];
853 if (band_type[idx] == ZERO_BT) {
577d383b 854 for (; i < run_end; i++, idx++)
cc0591da 855 sf[idx] = 0.;
577d383b
DB
856 } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
857 for (; i < run_end; i++, idx++) {
cc0591da 858 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
e4744b59
AC
859 clipped_offset = av_clip(offset[2], -155, 100);
860 if (offset[2] != clipped_offset) {
861 av_log_ask_for_sample(ac->avctx, "Intensity stereo "
862 "position clipped (%d -> %d).\nIf you heard an "
863 "audible artifact, there may be a bug in the "
864 "decoder. ", offset[2], clipped_offset);
cc0591da 865 }
d70fa4c4 866 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
cc0591da 867 }
577d383b
DB
868 } else if (band_type[idx] == NOISE_BT) {
869 for (; i < run_end; i++, idx++) {
870 if (noise_flag-- > 0)
cc0591da
RS
871 offset[1] += get_bits(gb, 9) - 256;
872 else
873 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
e4744b59 874 clipped_offset = av_clip(offset[1], -100, 155);
cef7d701 875 if (offset[1] != clipped_offset) {
e4744b59
AC
876 av_log_ask_for_sample(ac->avctx, "Noise gain clipped "
877 "(%d -> %d).\nIf you heard an audible "
878 "artifact, there may be a bug in the decoder. ",
879 offset[1], clipped_offset);
cc0591da 880 }
767848d7 881 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
cc0591da 882 }
577d383b
DB
883 } else {
884 for (; i < run_end; i++, idx++) {
cc0591da 885 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 886 if (offset[0] > 255U) {
dd8871a6 887 av_log(ac->avctx, AV_LOG_ERROR,
577d383b 888 "%s (%d) out of range.\n", sf_str[0], offset[0]);
cc0591da
RS
889 return -1;
890 }
767848d7 891 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
cc0591da
RS
892 }
893 }
894 }
895 }
896 return 0;
897}
898
899/**
900 * Decode pulse data; reference: table 4.7.
901 */
577d383b
DB
902static int decode_pulses(Pulse *pulse, GetBitContext *gb,
903 const uint16_t *swb_offset, int num_swb)
904{
aac0eda4 905 int i, pulse_swb;
cc0591da 906 pulse->num_pulse = get_bits(gb, 2) + 1;
aac0eda4
AC
907 pulse_swb = get_bits(gb, 6);
908 if (pulse_swb >= num_swb)
909 return -1;
910 pulse->pos[0] = swb_offset[pulse_swb];
408992ba 911 pulse->pos[0] += get_bits(gb, 5);
aac0eda4
AC
912 if (pulse->pos[0] > 1023)
913 return -1;
848a5815
RS
914 pulse->amp[0] = get_bits(gb, 4);
915 for (i = 1; i < pulse->num_pulse; i++) {
577d383b 916 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
aac0eda4
AC
917 if (pulse->pos[i] > 1023)
918 return -1;
848a5815 919 pulse->amp[i] = get_bits(gb, 4);
cc0591da 920 }
aac0eda4 921 return 0;
cc0591da
RS
922}
923
924/**
1dece0d2
RS
925 * Decode Temporal Noise Shaping data; reference: table 4.48.
926 *
927 * @return Returns error status. 0 - OK, !0 - error
928 */
577d383b
DB
929static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
930 GetBitContext *gb, const IndividualChannelStream *ics)
931{
1dece0d2
RS
932 int w, filt, i, coef_len, coef_res, coef_compress;
933 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
934 const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
935 for (w = 0; w < ics->num_windows; w++) {
fbd91d7c 936 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1dece0d2
RS
937 coef_res = get_bits1(gb);
938
65b20b24
RS
939 for (filt = 0; filt < tns->n_filt[w]; filt++) {
940 int tmp2_idx;
577d383b 941 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
65b20b24 942
577d383b 943 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
dd8871a6 944 av_log(ac->avctx, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
65b20b24
RS
945 tns->order[w][filt], tns_max_order);
946 tns->order[w][filt] = 0;
947 return -1;
948 }
51673647 949 if (tns->order[w][filt]) {
35445d29
RS
950 tns->direction[w][filt] = get_bits1(gb);
951 coef_compress = get_bits1(gb);
952 coef_len = coef_res + 3 - coef_compress;
577d383b 953 tmp2_idx = 2 * coef_compress + coef_res;
1dece0d2 954
35445d29
RS
955 for (i = 0; i < tns->order[w][filt]; i++)
956 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
51673647 957 }
65b20b24 958 }
fbd91d7c 959 }
1dece0d2
RS
960 }
961 return 0;
962}
963
964/**
9cc04edf
RS
965 * Decode Mid/Side data; reference: table 4.54.
966 *
967 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
968 * [1] mask is decoded from bitstream; [2] mask is all 1s;
969 * [3] reserved for scalable AAC
970 */
577d383b
DB
971static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
972 int ms_present)
973{
62a57fae
RS
974 int idx;
975 if (ms_present == 1) {
976 for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
977 cpe->ms_mask[idx] = get_bits1(gb);
978 } else if (ms_present == 2) {
979 memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
980 }
981}
9cc04edf 982
798339fb 983#ifndef VMUL2
c816d3d0
MR
984static inline float *VMUL2(float *dst, const float *v, unsigned idx,
985 const float *scale)
986{
987 float s = *scale;
988 *dst++ = v[idx & 15] * s;
989 *dst++ = v[idx>>4 & 15] * s;
990 return dst;
991}
798339fb 992#endif
c816d3d0 993
798339fb 994#ifndef VMUL4
c816d3d0
MR
995static inline float *VMUL4(float *dst, const float *v, unsigned idx,
996 const float *scale)
997{
998 float s = *scale;
999 *dst++ = v[idx & 3] * s;
1000 *dst++ = v[idx>>2 & 3] * s;
1001 *dst++ = v[idx>>4 & 3] * s;
1002 *dst++ = v[idx>>6 & 3] * s;
1003 return dst;
1004}
798339fb 1005#endif
c816d3d0 1006
798339fb 1007#ifndef VMUL2S
c816d3d0
MR
1008static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1009 unsigned sign, const float *scale)
1010{
5cd56e19 1011 union av_intfloat32 s0, s1;
c816d3d0
MR
1012
1013 s0.f = s1.f = *scale;
1014 s0.i ^= sign >> 1 << 31;
1015 s1.i ^= sign << 31;
1016
1017 *dst++ = v[idx & 15] * s0.f;
1018 *dst++ = v[idx>>4 & 15] * s1.f;
1019
1020 return dst;
1021}
798339fb 1022#endif
c816d3d0 1023
798339fb 1024#ifndef VMUL4S
c816d3d0
MR
1025static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1026 unsigned sign, const float *scale)
1027{
1028 unsigned nz = idx >> 12;
5cd56e19
AC
1029 union av_intfloat32 s = { .f = *scale };
1030 union av_intfloat32 t;
c816d3d0 1031
187a5379 1032 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1033 *dst++ = v[idx & 3] * t.f;
1034
1035 sign <<= nz & 1; nz >>= 1;
187a5379 1036 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1037 *dst++ = v[idx>>2 & 3] * t.f;
1038
1039 sign <<= nz & 1; nz >>= 1;
187a5379 1040 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1041 *dst++ = v[idx>>4 & 3] * t.f;
1042
1043 sign <<= nz & 1; nz >>= 1;
187a5379 1044 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1045 *dst++ = v[idx>>6 & 3] * t.f;
1046
1047 return dst;
1048}
798339fb 1049#endif
c816d3d0 1050
9cc04edf 1051/**
9ffd5c1c
RS
1052 * Decode spectral data; reference: table 4.50.
1053 * Dequantize and scale spectral data; reference: 4.6.3.3.
1054 *
1055 * @param coef array of dequantized, scaled spectral data
1056 * @param sf array of scalefactors or intensity stereo positions
1057 * @param pulse_present set if pulses are present
1058 * @param pulse pointer to pulse data struct
1059 * @param band_type array of the used band type
1060 *
1061 * @return Returns error status. 0 - OK, !0 - error
1062 */
577d383b 1063static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
3963a17d 1064 GetBitContext *gb, const float sf[120],
577d383b
DB
1065 int pulse_present, const Pulse *pulse,
1066 const IndividualChannelStream *ics,
1067 enum BandType band_type[120])
1068{
9ffd5c1c 1069 int i, k, g, idx = 0;
577d383b
DB
1070 const int c = 1024 / ics->num_windows;
1071 const uint16_t *offsets = ics->swb_offset;
9ffd5c1c
RS
1072 float *coef_base = coef;
1073
1074 for (g = 0; g < ics->num_windows; g++)
577d383b 1075 memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
9ffd5c1c
RS
1076
1077 for (g = 0; g < ics->num_window_groups; g++) {
05f9d8fc
MR
1078 unsigned g_len = ics->group_len[g];
1079
9ffd5c1c 1080 for (i = 0; i < ics->max_sfb; i++, idx++) {
05f9d8fc
MR
1081 const unsigned cbt_m1 = band_type[idx] - 1;
1082 float *cfo = coef + offsets[i];
1083 int off_len = offsets[i + 1] - offsets[i];
9ffd5c1c 1084 int group;
05f9d8fc
MR
1085
1086 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1087 for (group = 0; group < g_len; group++, cfo+=128) {
1088 memset(cfo, 0, off_len * sizeof(float));
9ffd5c1c 1089 }
05f9d8fc
MR
1090 } else if (cbt_m1 == NOISE_BT - 1) {
1091 for (group = 0; group < g_len; group++, cfo+=128) {
d0ee5021 1092 float scale;
b418a6ca 1093 float band_energy;
42d3fbb3 1094
05f9d8fc 1095 for (k = 0; k < off_len; k++) {
9ffd5c1c 1096 ac->random_state = lcg_random(ac->random_state);
05f9d8fc 1097 cfo[k] = ac->random_state;
d0ee5021 1098 }
42d3fbb3 1099
05f9d8fc 1100 band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
d0ee5021 1101 scale = sf[idx] / sqrtf(band_energy);
05f9d8fc 1102 ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
9ffd5c1c 1103 }
577d383b 1104 } else {
05f9d8fc
MR
1105 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1106 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1107 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
d356a53f 1108 OPEN_READER(re, gb);
c816d3d0 1109
95dff4ac
MR
1110 switch (cbt_m1 >> 1) {
1111 case 0:
1112 for (group = 0; group < g_len; group++, cfo+=128) {
1113 float *cf = cfo;
1114 int len = off_len;
42d3fbb3 1115
c816d3d0 1116 do {
d356a53f 1117 int code;
c816d3d0
MR
1118 unsigned cb_idx;
1119
d356a53f
MR
1120 UPDATE_CACHE(re, gb);
1121 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1122 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1123 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1124 } while (len -= 4);
95dff4ac
MR
1125 }
1126 break;
1127
1128 case 1:
1129 for (group = 0; group < g_len; group++, cfo+=128) {
1130 float *cf = cfo;
1131 int len = off_len;
1132
c816d3d0 1133 do {
d356a53f 1134 int code;
c816d3d0
MR
1135 unsigned nnz;
1136 unsigned cb_idx;
1137 uint32_t bits;
1138
d356a53f
MR
1139 UPDATE_CACHE(re, gb);
1140 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1141 cb_idx = cb_vector_idx[code];
c816d3d0 1142 nnz = cb_idx >> 8 & 15;
d1229430 1143 bits = nnz ? GET_CACHE(re, gb) : 0;
d356a53f 1144 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1145 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1146 } while (len -= 4);
95dff4ac
MR
1147 }
1148 break;
1149
1150 case 2:
1151 for (group = 0; group < g_len; group++, cfo+=128) {
1152 float *cf = cfo;
1153 int len = off_len;
1154
c816d3d0 1155 do {
d356a53f 1156 int code;
c816d3d0
MR
1157 unsigned cb_idx;
1158
d356a53f
MR
1159 UPDATE_CACHE(re, gb);
1160 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1161 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1162 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1163 } while (len -= 2);
95dff4ac
MR
1164 }
1165 break;
1166
1167 case 3:
1168 case 4:
1169 for (group = 0; group < g_len; group++, cfo+=128) {
1170 float *cf = cfo;
1171 int len = off_len;
1172
c816d3d0 1173 do {
d356a53f 1174 int code;
c816d3d0
MR
1175 unsigned nnz;
1176 unsigned cb_idx;
1177 unsigned sign;
1178
d356a53f
MR
1179 UPDATE_CACHE(re, gb);
1180 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1181 cb_idx = cb_vector_idx[code];
c816d3d0 1182 nnz = cb_idx >> 8 & 15;
d1229430 1183 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
d356a53f 1184 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1185 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1186 } while (len -= 2);
95dff4ac
MR
1187 }
1188 break;
1189
1190 default:
1191 for (group = 0; group < g_len; group++, cfo+=128) {
1192 float *cf = cfo;
1193 uint32_t *icf = (uint32_t *) cf;
1194 int len = off_len;
1195
05f9d8fc 1196 do {
d356a53f 1197 int code;
c816d3d0
MR
1198 unsigned nzt, nnz;
1199 unsigned cb_idx;
1200 uint32_t bits;
1201 int j;
1202
d356a53f
MR
1203 UPDATE_CACHE(re, gb);
1204 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1205
1206 if (!code) {
05f9d8fc
MR
1207 *icf++ = 0;
1208 *icf++ = 0;
c816d3d0
MR
1209 continue;
1210 }
1211
d356a53f 1212 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1213 nnz = cb_idx >> 12;
1214 nzt = cb_idx >> 8;
d356a53f
MR
1215 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1216 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1217
1218 for (j = 0; j < 2; j++) {
1219 if (nzt & 1<<j) {
d356a53f
MR
1220 uint32_t b;
1221 int n;
c816d3d0
MR
1222 /* The total length of escape_sequence must be < 22 bits according
1223 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
d356a53f
MR
1224 UPDATE_CACHE(re, gb);
1225 b = GET_CACHE(re, gb);
1226 b = 31 - av_log2(~b);
1227
1228 if (b > 8) {
dd8871a6 1229 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
c816d3d0
MR
1230 return -1;
1231 }
d356a53f 1232
d356a53f 1233 SKIP_BITS(re, gb, b + 1);
d356a53f
MR
1234 b += 4;
1235 n = (1 << b) + SHOW_UBITS(re, gb, b);
1236 LAST_SKIP_BITS(re, gb, b);
187a5379 1237 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
c816d3d0
MR
1238 bits <<= 1;
1239 } else {
1240 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
187a5379 1241 *icf++ = (bits & 1U<<31) | v;
c816d3d0 1242 bits <<= !!v;
e8d5c07b 1243 }
c816d3d0 1244 cb_idx >>= 4;
9ffd5c1c 1245 }
05f9d8fc 1246 } while (len -= 2);
42d3fbb3 1247
05f9d8fc 1248 ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
42d3fbb3 1249 }
9ffd5c1c 1250 }
d356a53f
MR
1251
1252 CLOSE_READER(re, gb);
9ffd5c1c
RS
1253 }
1254 }
05f9d8fc 1255 coef += g_len << 7;
9ffd5c1c
RS
1256 }
1257
1258 if (pulse_present) {
51436848 1259 idx = 0;
577d383b
DB
1260 for (i = 0; i < pulse->num_pulse; i++) {
1261 float co = coef_base[ pulse->pos[i] ];
1262 while (offsets[idx + 1] <= pulse->pos[i])
51436848
AC
1263 idx++;
1264 if (band_type[idx] != NOISE_BT && sf[idx]) {
70735a3f
RS
1265 float ico = -pulse->amp[i];
1266 if (co) {
1267 co /= sf[idx];
1268 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1269 }
1270 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
51436848 1271 }
9ffd5c1c
RS
1272 }
1273 }
1274 return 0;
1275}
1276
577d383b
DB
1277static av_always_inline float flt16_round(float pf)
1278{
5cd56e19 1279 union av_intfloat32 tmp;
4a39ccb4
AC
1280 tmp.f = pf;
1281 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1282 return tmp.f;
7633a041
AC
1283}
1284
577d383b
DB
1285static av_always_inline float flt16_even(float pf)
1286{
5cd56e19 1287 union av_intfloat32 tmp;
4a39ccb4 1288 tmp.f = pf;
577d383b 1289 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
4a39ccb4 1290 return tmp.f;
7633a041
AC
1291}
1292
577d383b
DB
1293static av_always_inline float flt16_trunc(float pf)
1294{
5cd56e19 1295 union av_intfloat32 pun;
4a39ccb4
AC
1296 pun.f = pf;
1297 pun.i &= 0xFFFF0000U;
1298 return pun.f;
7633a041
AC
1299}
1300
70c99adb 1301static av_always_inline void predict(PredictorState *ps, float *coef,
9978ed7d 1302 int output_enable)
577d383b
DB
1303{
1304 const float a = 0.953125; // 61.0 / 64
1305 const float alpha = 0.90625; // 29.0 / 32
7633a041
AC
1306 float e0, e1;
1307 float pv;
1308 float k1, k2;
81824fe0
AC
1309 float r0 = ps->r0, r1 = ps->r1;
1310 float cor0 = ps->cor0, cor1 = ps->cor1;
1311 float var0 = ps->var0, var1 = ps->var1;
7633a041 1312
81824fe0
AC
1313 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1314 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
7633a041 1315
81824fe0 1316 pv = flt16_round(k1 * r0 + k2 * r1);
7633a041 1317 if (output_enable)
767848d7 1318 *coef += pv;
7633a041 1319
767848d7 1320 e0 = *coef;
81824fe0 1321 e1 = e0 - k1 * r0;
7633a041 1322
81824fe0
AC
1323 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1324 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1325 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1326 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
7633a041 1327
81824fe0 1328 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
7633a041
AC
1329 ps->r0 = flt16_trunc(a * e0);
1330}
1331
1332/**
1333 * Apply AAC-Main style frequency domain prediction.
1334 */
577d383b
DB
1335static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1336{
7633a041
AC
1337 int sfb, k;
1338
1339 if (!sce->ics.predictor_initialized) {
aab54133 1340 reset_all_predictors(sce->predictor_state);
7633a041
AC
1341 sce->ics.predictor_initialized = 1;
1342 }
1343
1344 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
1345 for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
1346 for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
70c99adb 1347 predict(&sce->predictor_state[k], &sce->coeffs[k],
577d383b 1348 sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
7633a041
AC
1349 }
1350 }
1351 if (sce->ics.predictor_reset_group)
aab54133 1352 reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
7633a041 1353 } else
aab54133 1354 reset_all_predictors(sce->predictor_state);
7633a041
AC
1355}
1356
9ffd5c1c 1357/**
9cc04edf
RS
1358 * Decode an individual_channel_stream payload; reference: table 4.44.
1359 *
1360 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1361 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1362 *
1363 * @return Returns error status. 0 - OK, !0 - error
1364 */
577d383b
DB
1365static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1366 GetBitContext *gb, int common_window, int scale_flag)
1367{
9cc04edf 1368 Pulse pulse;
577d383b
DB
1369 TemporalNoiseShaping *tns = &sce->tns;
1370 IndividualChannelStream *ics = &sce->ics;
1371 float *out = sce->coeffs;
9cc04edf
RS
1372 int global_gain, pulse_present = 0;
1373
848a5815
RS
1374 /* This assignment is to silence a GCC warning about the variable being used
1375 * uninitialized when in fact it always is.
9cc04edf
RS
1376 */
1377 pulse.num_pulse = 0;
9cc04edf
RS
1378
1379 global_gain = get_bits(gb, 8);
1380
1381 if (!common_window && !scale_flag) {
021914e2
AC
1382 if (decode_ics_info(ac, ics, gb) < 0)
1383 return AVERROR_INVALIDDATA;
9cc04edf
RS
1384 }
1385
1386 if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
1387 return -1;
1388 if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
1389 return -1;
1390
1391 pulse_present = 0;
1392 if (!scale_flag) {
1393 if ((pulse_present = get_bits1(gb))) {
1394 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
dd8871a6 1395 av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
9cc04edf
RS
1396 return -1;
1397 }
aac0eda4 1398 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
dd8871a6 1399 av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
aac0eda4
AC
1400 return -1;
1401 }
9cc04edf
RS
1402 }
1403 if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
1404 return -1;
1405 if (get_bits1(gb)) {
dd8871a6 1406 av_log_missing_feature(ac->avctx, "SSR", 1);
9cc04edf
RS
1407 return -1;
1408 }
1409 }
1410
848a5815 1411 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
9cc04edf 1412 return -1;
7633a041 1413
577d383b 1414 if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
7633a041
AC
1415 apply_prediction(ac, sce);
1416
9cc04edf
RS
1417 return 0;
1418}
1419
1420/**
9ffd5c1c
RS
1421 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1422 */
42d3fbb3 1423static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
577d383b
DB
1424{
1425 const IndividualChannelStream *ics = &cpe->ch[0].ics;
9ffd5c1c
RS
1426 float *ch0 = cpe->ch[0].coeffs;
1427 float *ch1 = cpe->ch[1].coeffs;
42d3fbb3 1428 int g, i, group, idx = 0;
577d383b 1429 const uint16_t *offsets = ics->swb_offset;
9ffd5c1c
RS
1430 for (g = 0; g < ics->num_window_groups; g++) {
1431 for (i = 0; i < ics->max_sfb; i++, idx++) {
1432 if (cpe->ms_mask[idx] &&
577d383b 1433 cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
9ffd5c1c 1434 for (group = 0; group < ics->group_len[g]; group++) {
42d3fbb3
MR
1435 ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
1436 ch1 + group * 128 + offsets[i],
1437 offsets[i+1] - offsets[i]);
9ffd5c1c
RS
1438 }
1439 }
1440 }
577d383b
DB
1441 ch0 += ics->group_len[g] * 128;
1442 ch1 += ics->group_len[g] * 128;
9ffd5c1c
RS
1443 }
1444}
1445
1446/**
1447 * intensity stereo decoding; reference: 4.6.8.2.3
1448 *
1449 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1450 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1451 * [3] reserved for scalable AAC
1452 */
9707f84f 1453static void apply_intensity_stereo(AACContext *ac, ChannelElement *cpe, int ms_present)
577d383b
DB
1454{
1455 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1456 SingleChannelElement *sce1 = &cpe->ch[1];
9ffd5c1c 1457 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
577d383b 1458 const uint16_t *offsets = ics->swb_offset;
9707f84f 1459 int g, group, i, idx = 0;
9ffd5c1c
RS
1460 int c;
1461 float scale;
1462 for (g = 0; g < ics->num_window_groups; g++) {
1463 for (i = 0; i < ics->max_sfb;) {
1464 if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
1465 const int bt_run_end = sce1->band_type_run_end[idx];
1466 for (; i < bt_run_end; i++, idx++) {
1467 c = -1 + 2 * (sce1->band_type[idx] - 14);
1468 if (ms_present)
1469 c *= 1 - 2 * cpe->ms_mask[idx];
1470 scale = c * sce1->sf[idx];
1471 for (group = 0; group < ics->group_len[g]; group++)
9707f84f
YHL
1472 ac->dsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1473 coef0 + group * 128 + offsets[i],
1474 scale,
1475 offsets[i + 1] - offsets[i]);
9ffd5c1c
RS
1476 }
1477 } else {
1478 int bt_run_end = sce1->band_type_run_end[idx];
1479 idx += bt_run_end - i;
1480 i = bt_run_end;
1481 }
1482 }
577d383b
DB
1483 coef0 += ics->group_len[g] * 128;
1484 coef1 += ics->group_len[g] * 128;
9ffd5c1c
RS
1485 }
1486}
1487
1488/**
9cc04edf
RS
1489 * Decode a channel_pair_element; reference: table 4.4.
1490 *
9cc04edf
RS
1491 * @return Returns error status. 0 - OK, !0 - error
1492 */
577d383b
DB
1493static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
1494{
9cc04edf 1495 int i, ret, common_window, ms_present = 0;
9cc04edf 1496
9cc04edf
RS
1497 common_window = get_bits1(gb);
1498 if (common_window) {
021914e2
AC
1499 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
1500 return AVERROR_INVALIDDATA;
9cc04edf
RS
1501 i = cpe->ch[1].ics.use_kb_window[0];
1502 cpe->ch[1].ics = cpe->ch[0].ics;
1503 cpe->ch[1].ics.use_kb_window[1] = i;
ead15f1d
YHL
1504 if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != AOT_AAC_MAIN))
1505 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
1506 decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
9cc04edf 1507 ms_present = get_bits(gb, 2);
577d383b 1508 if (ms_present == 3) {
dd8871a6 1509 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
9cc04edf 1510 return -1;
577d383b 1511 } else if (ms_present)
9cc04edf
RS
1512 decode_mid_side_stereo(cpe, gb, ms_present);
1513 }
1514 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
1515 return ret;
1516 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
1517 return ret;
1518
aab54133
AC
1519 if (common_window) {
1520 if (ms_present)
42d3fbb3 1521 apply_mid_side_stereo(ac, cpe);
aab54133
AC
1522 if (ac->m4ac.object_type == AOT_AAC_MAIN) {
1523 apply_prediction(ac, &cpe->ch[0]);
1524 apply_prediction(ac, &cpe->ch[1]);
1525 }
1526 }
9cc04edf 1527
9707f84f 1528 apply_intensity_stereo(ac, cpe, ms_present);
9cc04edf
RS
1529 return 0;
1530}
1531
93c6ff6c
AC
1532static const float cce_scale[] = {
1533 1.09050773266525765921, //2^(1/8)
1534 1.18920711500272106672, //2^(1/4)
1535 M_SQRT2,
1536 2,
1537};
1538
9ffd5c1c
RS
1539/**
1540 * Decode coupling_channel_element; reference: table 4.8.
1541 *
9ffd5c1c
RS
1542 * @return Returns error status. 0 - OK, !0 - error
1543 */
577d383b
DB
1544static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
1545{
9ffd5c1c 1546 int num_gain = 0;
341b28c0 1547 int c, g, sfb, ret;
9ffd5c1c
RS
1548 int sign;
1549 float scale;
577d383b
DB
1550 SingleChannelElement *sce = &che->ch[0];
1551 ChannelCoupling *coup = &che->coup;
9ffd5c1c 1552
577d383b 1553 coup->coupling_point = 2 * get_bits1(gb);
62a57fae
RS
1554 coup->num_coupled = get_bits(gb, 3);
1555 for (c = 0; c <= coup->num_coupled; c++) {
1556 num_gain++;
1557 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
1558 coup->id_select[c] = get_bits(gb, 4);
1559 if (coup->type[c] == TYPE_CPE) {
1560 coup->ch_select[c] = get_bits(gb, 2);
1561 if (coup->ch_select[c] == 3)
1562 num_gain++;
1563 } else
88de95c2 1564 coup->ch_select[c] = 2;
62a57fae 1565 }
577d383b 1566 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
62a57fae 1567
577d383b 1568 sign = get_bits(gb, 1);
93c6ff6c 1569 scale = cce_scale[get_bits(gb, 2)];
62a57fae
RS
1570
1571 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
1572 return ret;
1573
1574 for (c = 0; c < num_gain; c++) {
577d383b
DB
1575 int idx = 0;
1576 int cge = 1;
62a57fae
RS
1577 int gain = 0;
1578 float gain_cache = 1.;
1579 if (c) {
1580 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
1581 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
531cfe6e 1582 gain_cache = powf(scale, -gain);
62a57fae 1583 }
f1ade11e
AC
1584 if (coup->coupling_point == AFTER_IMDCT) {
1585 coup->gain[c][0] = gain_cache;
1586 } else {
03b12747
AC
1587 for (g = 0; g < sce->ics.num_window_groups; g++) {
1588 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
1589 if (sce->band_type[idx] != ZERO_BT) {
1590 if (!cge) {
1591 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 1592 if (t) {
03b12747
AC
1593 int s = 1;
1594 t = gain += t;
1595 if (sign) {
1596 s -= 2 * (t & 0x1);
1597 t >>= 1;
1598 }
531cfe6e 1599 gain_cache = powf(scale, -t) * s;
62a57fae 1600 }
62a57fae 1601 }
03b12747 1602 coup->gain[c][idx] = gain_cache;
62a57fae 1603 }
62a57fae 1604 }
f80a8ca5
RS
1605 }
1606 }
62a57fae
RS
1607 }
1608 return 0;
1609}
1610
9cc04edf 1611/**
62a57fae
RS
1612 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
1613 *
1614 * @return Returns number of bytes consumed.
1615 */
577d383b
DB
1616static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
1617 GetBitContext *gb)
1618{
62a57fae
RS
1619 int i;
1620 int num_excl_chan = 0;
1621
1622 do {
1623 for (i = 0; i < 7; i++)
1624 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
1625 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
1626
1627 return num_excl_chan / 7;
1628}
1629
1630/**
9cc04edf
RS
1631 * Decode dynamic range information; reference: table 4.52.
1632 *
1633 * @param cnt length of TYPE_FIL syntactic element in bytes
1634 *
1635 * @return Returns number of bytes consumed.
1636 */
577d383b
DB
1637static int decode_dynamic_range(DynamicRangeControl *che_drc,
1638 GetBitContext *gb, int cnt)
1639{
1640 int n = 1;
9cc04edf
RS
1641 int drc_num_bands = 1;
1642 int i;
1643
1644 /* pce_tag_present? */
577d383b 1645 if (get_bits1(gb)) {
9cc04edf
RS
1646 che_drc->pce_instance_tag = get_bits(gb, 4);
1647 skip_bits(gb, 4); // tag_reserved_bits
1648 n++;
1649 }
1650
1651 /* excluded_chns_present? */
577d383b 1652 if (get_bits1(gb)) {
9cc04edf
RS
1653 n += decode_drc_channel_exclusions(che_drc, gb);
1654 }
1655
1656 /* drc_bands_present? */
1657 if (get_bits1(gb)) {
1658 che_drc->band_incr = get_bits(gb, 4);
1659 che_drc->interpolation_scheme = get_bits(gb, 4);
1660 n++;
1661 drc_num_bands += che_drc->band_incr;
1662 for (i = 0; i < drc_num_bands; i++) {
1663 che_drc->band_top[i] = get_bits(gb, 8);
1664 n++;
1665 }
1666 }
1667
1668 /* prog_ref_level_present? */
1669 if (get_bits1(gb)) {
1670 che_drc->prog_ref_level = get_bits(gb, 7);
1671 skip_bits1(gb); // prog_ref_level_reserved_bits
1672 n++;
1673 }
1674
1675 for (i = 0; i < drc_num_bands; i++) {
1676 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
1677 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
1678 n++;
1679 }
1680
1681 return n;
1682}
1683
1684/**
1685 * Decode extension data (incomplete); reference: table 4.51.
1686 *
1687 * @param cnt length of TYPE_FIL syntactic element in bytes
1688 *
1689 * @return Returns number of bytes consumed
1690 */
ed492b61
AC
1691static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
1692 ChannelElement *che, enum RawDataBlockType elem_type)
577d383b 1693{
cc0591da
RS
1694 int crc_flag = 0;
1695 int res = cnt;
1696 switch (get_bits(gb, 4)) { // extension type
577d383b
DB
1697 case EXT_SBR_DATA_CRC:
1698 crc_flag++;
1699 case EXT_SBR_DATA:
ed492b61 1700 if (!che) {
dd8871a6 1701 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
ed492b61
AC
1702 return res;
1703 } else if (!ac->m4ac.sbr) {
dd8871a6 1704 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
ed492b61
AC
1705 skip_bits_long(gb, 8 * cnt - 4);
1706 return res;
1707 } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
dd8871a6 1708 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
ed492b61
AC
1709 skip_bits_long(gb, 8 * cnt - 4);
1710 return res;
a2063901
AC
1711 } else if (ac->m4ac.ps == -1 && ac->output_configured < OC_LOCKED && ac->avctx->channels == 1) {
1712 ac->m4ac.sbr = 1;
1713 ac->m4ac.ps = 1;
e600a1e4 1714 output_configure(ac, NULL, ac->m4ac.chan_config, ac->output_configured);
ed492b61
AC
1715 } else {
1716 ac->m4ac.sbr = 1;
1717 }
1718 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
577d383b
DB
1719 break;
1720 case EXT_DYNAMIC_RANGE:
1721 res = decode_dynamic_range(&ac->che_drc, gb, cnt);
1722 break;
1723 case EXT_FILL:
1724 case EXT_FILL_DATA:
1725 case EXT_DATA_ELEMENT:
1726 default:
1727 skip_bits_long(gb, 8 * cnt - 4);
1728 break;
cc0591da
RS
1729 };
1730 return res;
1731}
1732
7d8f3de4
RS
1733/**
1734 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
1735 *
1736 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
1737 * @param coef spectral coefficients
1738 */
577d383b
DB
1739static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
1740 IndividualChannelStream *ics, int decode)
1741{
1742 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1098e8d2 1743 int w, filt, m, i;
7d8f3de4
RS
1744 int bottom, top, order, start, end, size, inc;
1745 float lpc[TNS_MAX_ORDER];
ead15f1d 1746 float tmp[TNS_MAX_ORDER];
7d8f3de4
RS
1747
1748 for (w = 0; w < ics->num_windows; w++) {
1749 bottom = ics->num_swb;
1750 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1751 top = bottom;
1752 bottom = FFMAX(0, top - tns->length[w][filt]);
1753 order = tns->order[w][filt];
1754 if (order == 0)
1755 continue;
1756
1be0fc29
VS
1757 // tns_decode_coef
1758 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
7d8f3de4 1759
1dece0d2
RS
1760 start = ics->swb_offset[FFMIN(bottom, mmm)];
1761 end = ics->swb_offset[FFMIN( top, mmm)];
1762 if ((size = end - start) <= 0)
1763 continue;
1764 if (tns->direction[w][filt]) {
577d383b
DB
1765 inc = -1;
1766 start = end - 1;
1dece0d2
RS
1767 } else {
1768 inc = 1;
1769 }
1770 start += w * 128;
1771
ead15f1d
YHL
1772 if (decode) {
1773 // ar filter
1774 for (m = 0; m < size; m++, start += inc)
1775 for (i = 1; i <= FFMIN(m, order); i++)
1776 coef[start] -= coef[start - i * inc] * lpc[i - 1];
1777 } else {
1778 // ma filter
1779 for (m = 0; m < size; m++, start += inc) {
1780 tmp[0] = coef[start];
1781 for (i = 1; i <= FFMIN(m, order); i++)
1782 coef[start] += tmp[i] * lpc[i - 1];
1783 for (i = order; i > 0; i--)
1784 tmp[i] = tmp[i - 1];
1785 }
1786 }
1dece0d2
RS
1787 }
1788 }
1789}
1790
cc0591da 1791/**
ead15f1d
YHL
1792 * Apply windowing and MDCT to obtain the spectral
1793 * coefficient from the predicted sample by LTP.
1794 */
1795static void windowing_and_mdct_ltp(AACContext *ac, float *out,
1796 float *in, IndividualChannelStream *ics)
1797{
1798 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1799 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1800 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1801 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1802
1803 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
1804 ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);
1805 } else {
1806 memset(in, 0, 448 * sizeof(float));
1807 ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
ead15f1d
YHL
1808 }
1809 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
1810 ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
1811 } else {
ead15f1d
YHL
1812 ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
1813 memset(in + 1024 + 576, 0, 448 * sizeof(float));
1814 }
26f548bb 1815 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
ead15f1d
YHL
1816}
1817
1818/**
1819 * Apply the long term prediction
1820 */
1821static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
1822{
1823 const LongTermPrediction *ltp = &sce->ics.ltp;
1824 const uint16_t *offsets = sce->ics.swb_offset;
1825 int i, sfb;
1826
1827 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
e22910b2
YHL
1828 float *predTime = sce->ret;
1829 float *predFreq = ac->buf_mdct;
ead15f1d
YHL
1830 int16_t num_samples = 2048;
1831
1832 if (ltp->lag < 1024)
1833 num_samples = ltp->lag + 1024;
1834 for (i = 0; i < num_samples; i++)
1835 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
1836 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
1837
1838 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
1839
1840 if (sce->tns.present)
1841 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
1842
1843 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
1844 if (ltp->used[sfb])
1845 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
1846 sce->coeffs[i] += predFreq[i];
1847 }
1848}
1849
1850/**
1851 * Update the LTP buffer for next frame
1852 */
1853static void update_ltp(AACContext *ac, SingleChannelElement *sce)
1854{
1855 IndividualChannelStream *ics = &sce->ics;
1856 float *saved = sce->saved;
1857 float *saved_ltp = sce->coeffs;
1858 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1859 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1860 int i;
1861
ead15f1d
YHL
1862 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1863 memcpy(saved_ltp, saved, 512 * sizeof(float));
1864 memset(saved_ltp + 576, 0, 448 * sizeof(float));
e22910b2
YHL
1865 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1866 for (i = 0; i < 64; i++)
1867 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
ead15f1d
YHL
1868 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
1869 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
1870 memset(saved_ltp + 576, 0, 448 * sizeof(float));
e22910b2
YHL
1871 ac->dsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
1872 for (i = 0; i < 64; i++)
1873 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
ead15f1d 1874 } else { // LONG_STOP or ONLY_LONG
e22910b2
YHL
1875 ac->dsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
1876 for (i = 0; i < 512; i++)
1877 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
ead15f1d
YHL
1878 }
1879
033a4a94
JR
1880 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
1881 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
1882 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
ead15f1d
YHL
1883}
1884
1885/**
9cc04edf
RS
1886 * Conduct IMDCT and windowing.
1887 */
9d06d7bc 1888static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
577d383b
DB
1889{
1890 IndividualChannelStream *ics = &sce->ics;
1891 float *in = sce->coeffs;
1892 float *out = sce->ret;
1893 float *saved = sce->saved;
1894 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
1895 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
1896 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
1897 float *buf = ac->buf_mdct;
1898 float *temp = ac->temp;
9cc04edf
RS
1899 int i;
1900
f4990558 1901 // imdct
62a57fae 1902 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
b0f5852a 1903 for (i = 0; i < 1024; i += 128)
26f548bb 1904 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
f4990558 1905 } else
26f548bb 1906 ac->mdct.imdct_half(&ac->mdct, buf, in);
f4990558
RS
1907
1908 /* window overlapping
1909 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
1910 * and long to short transitions are considered to be short to short
1911 * transitions. This leaves just two cases (long to long and short to short)
1912 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
1913 */
1914 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
577d383b 1915 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
80ba1ddb 1916 ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
f4990558 1917 } else {
e5c82df8 1918 memcpy( out, saved, 448 * sizeof(float));
62a57fae 1919
f4990558 1920 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
80ba1ddb
JR
1921 ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
1922 ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
1923 ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
1924 ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
1925 ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
b0f5852a 1926 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
f4990558 1927 } else {
80ba1ddb 1928 ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
e5c82df8 1929 memcpy( out + 576, buf + 64, 448 * sizeof(float));
f4990558
RS
1930 }
1931 }
62a57fae 1932
f4990558
RS
1933 // buffer update
1934 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
e5c82df8 1935 memcpy( saved, temp + 64, 64 * sizeof(float));
80ba1ddb
JR
1936 ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
1937 ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
1938 ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
b0f5852a 1939 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
f4990558 1940 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
b0f5852a
RS
1941 memcpy( saved, buf + 512, 448 * sizeof(float));
1942 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
f4990558 1943 } else { // LONG_STOP or ONLY_LONG
b0f5852a 1944 memcpy( saved, buf + 512, 512 * sizeof(float));
62a57fae
RS
1945 }
1946}
1947
9cc04edf 1948/**
cc0591da
RS
1949 * Apply dependent channel coupling (applied before IMDCT).
1950 *
1951 * @param index index into coupling gain array
1952 */
577d383b
DB
1953static void apply_dependent_coupling(AACContext *ac,
1954 SingleChannelElement *target,
1955 ChannelElement *cce, int index)
1956{
1957 IndividualChannelStream *ics = &cce->ch[0].ics;
1958 const uint16_t *offsets = ics->swb_offset;
1959 float *dest = target->coeffs;
1960 const float *src = cce->ch[0].coeffs;
cc0591da 1961 int g, i, group, k, idx = 0;
577d383b 1962 if (ac->m4ac.object_type == AOT_AAC_LTP) {
dd8871a6 1963 av_log(ac->avctx, AV_LOG_ERROR,
cc0591da
RS
1964 "Dependent coupling is not supported together with LTP\n");
1965 return;
1966 }
1967 for (g = 0; g < ics->num_window_groups; g++) {
1968 for (i = 0; i < ics->max_sfb; i++, idx++) {
fbdae895 1969 if (cce->ch[0].band_type[idx] != ZERO_BT) {
cfd937b0 1970 const float gain = cce->coup.gain[index][idx];
cc0591da 1971 for (group = 0; group < ics->group_len[g]; group++) {
577d383b 1972 for (k = offsets[i]; k < offsets[i + 1]; k++) {
cc0591da 1973 // XXX dsputil-ize
577d383b 1974 dest[group * 128 + k] += gain * src[group * 128 + k];
cc0591da
RS
1975 }
1976 }
1977 }
1978 }
577d383b
DB
1979 dest += ics->group_len[g] * 128;
1980 src += ics->group_len[g] * 128;
cc0591da
RS
1981 }
1982}
1983
1984/**
1985 * Apply independent channel coupling (applied after IMDCT).
1986 *
1987 * @param index index into coupling gain array
1988 */
577d383b
DB
1989static void apply_independent_coupling(AACContext *ac,
1990 SingleChannelElement *target,
1991 ChannelElement *cce, int index)
1992{
cc0591da 1993 int i;
039821a8 1994 const float gain = cce->coup.gain[index][0];
577d383b
DB
1995 const float *src = cce->ch[0].ret;
1996 float *dest = target->ret;
ed492b61 1997 const int len = 1024 << (ac->m4ac.sbr == 1);
039821a8 1998
ed492b61 1999 for (i = 0; i < len; i++)
9d06d7bc 2000 dest[i] += gain * src[i];
cc0591da
RS
2001}
2002
9ffd5c1c
RS
2003/**
2004 * channel coupling transformation interface
2005 *
9ffd5c1c
RS
2006 * @param apply_coupling_method pointer to (in)dependent coupling function
2007 */
577d383b
DB
2008static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2009 enum RawDataBlockType type, int elem_id,
2010 enum CouplingPoint coupling_point,
2011 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
9ffd5c1c 2012{
88de95c2
AC
2013 int i, c;
2014
2015 for (i = 0; i < MAX_ELEM_ID; i++) {
2016 ChannelElement *cce = ac->che[TYPE_CCE][i];
2017 int index = 0;
2018
2019 if (cce && cce->coup.coupling_point == coupling_point) {
577d383b 2020 ChannelCoupling *coup = &cce->coup;
88de95c2
AC
2021
2022 for (c = 0; c <= coup->num_coupled; c++) {
2023 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2024 if (coup->ch_select[c] != 1) {
2025 apply_coupling_method(ac, &cc->ch[0], cce, index);
2026 if (coup->ch_select[c] != 0)
2027 index++;
2028 }
2029 if (coup->ch_select[c] != 2)
2030 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2031 } else
2032 index += 1 + (coup->ch_select[c] == 3);
9ffd5c1c 2033 }
9ffd5c1c
RS
2034 }
2035 }
2036}
2037
2038/**
2039 * Convert spectral data to float samples, applying all supported tools as appropriate.
2040 */
577d383b
DB
2041static void spectral_to_sample(AACContext *ac)
2042{
b0bc928b
CEH
2043 int i, type;
2044 for (type = 3; type >= 0; type--) {
88de95c2 2045 for (i = 0; i < MAX_ELEM_ID; i++) {
9ffd5c1c 2046 ChannelElement *che = ac->che[type][i];
577d383b
DB
2047 if (che) {
2048 if (type <= TYPE_CPE)
88de95c2 2049 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
ead15f1d
YHL
2050 if (ac->m4ac.object_type == AOT_AAC_LTP) {
2051 if (che->ch[0].ics.predictor_present) {
2052 if (che->ch[0].ics.ltp.present)
2053 apply_ltp(ac, &che->ch[0]);
2054 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2055 apply_ltp(ac, &che->ch[1]);
2056 }
2057 }
577d383b 2058 if (che->ch[0].tns.present)
9ffd5c1c 2059 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
577d383b 2060 if (che->ch[1].tns.present)
9ffd5c1c 2061 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
577d383b 2062 if (type <= TYPE_CPE)
88de95c2 2063 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
ed492b61 2064 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
9d06d7bc 2065 imdct_and_windowing(ac, &che->ch[0]);
ead15f1d
YHL
2066 if (ac->m4ac.object_type == AOT_AAC_LTP)
2067 update_ltp(ac, &che->ch[0]);
d0dedce7 2068 if (type == TYPE_CPE) {
9d06d7bc 2069 imdct_and_windowing(ac, &che->ch[1]);
ead15f1d
YHL
2070 if (ac->m4ac.object_type == AOT_AAC_LTP)
2071 update_ltp(ac, &che->ch[1]);
d0dedce7 2072 }
ca6d3f23
AC
2073 if (ac->m4ac.sbr > 0) {
2074 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2075 }
ed492b61 2076 }
577d383b 2077 if (type <= TYPE_CCE)
88de95c2 2078 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
62a57fae
RS
2079 }
2080 }
2081 }
2082}
2083
577d383b
DB
2084static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2085{
158b3912
RS
2086 int size;
2087 AACADTSHeaderInfo hdr_info;
2088
73ae27e1 2089 size = avpriv_aac_parse_header(gb, &hdr_info);
158b3912 2090 if (size > 0) {
bc2dd367 2091 if (hdr_info.chan_config) {
6308765c
AC
2092 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2093 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
158b3912 2094 ac->m4ac.chan_config = hdr_info.chan_config;
6c003e6d 2095 if (set_default_channel_config(ac->avctx, new_che_pos, hdr_info.chan_config))
6308765c 2096 return -7;
e600a1e4 2097 if (output_configure(ac, new_che_pos, hdr_info.chan_config,
963f6855 2098 FFMAX(ac->output_configured, OC_TRIAL_FRAME)))
6308765c 2099 return -7;
981b8fd7 2100 } else if (ac->output_configured != OC_LOCKED) {
dafaef2f 2101 ac->m4ac.chan_config = 0;
981b8fd7 2102 ac->output_configured = OC_NONE;
6308765c 2103 }
a2063901 2104 if (ac->output_configured != OC_LOCKED) {
38610d92 2105 ac->m4ac.sbr = -1;
a2063901 2106 ac->m4ac.ps = -1;
44920d04
AC
2107 ac->m4ac.sample_rate = hdr_info.sample_rate;
2108 ac->m4ac.sampling_index = hdr_info.sampling_index;
2109 ac->m4ac.object_type = hdr_info.object_type;
a2063901 2110 }
dd8871a6
AC
2111 if (!ac->avctx->sample_rate)
2112 ac->avctx->sample_rate = hdr_info.sample_rate;
7d87e2ce
AC
2113 if (hdr_info.num_aac_frames == 1) {
2114 if (!hdr_info.crc_absent)
2115 skip_bits(gb, 16);
2116 } else {
dd8871a6 2117 av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
7d87e2ce
AC
2118 return -1;
2119 }
51741a82 2120 }
158b3912
RS
2121 return size;
2122}
2123
66a71d98 2124static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
0eea2129 2125 int *got_frame_ptr, GetBitContext *gb)
577d383b 2126{
dd8871a6 2127 AACContext *ac = avctx->priv_data;
ed492b61 2128 ChannelElement *che = NULL, *che_prev = NULL;
ed492b61 2129 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
0eea2129 2130 int err, elem_id;
d8425ed4 2131 int samples = 0, multiplier, audio_found = 0;
62a57fae 2132
66a71d98
JG
2133 if (show_bits(gb, 12) == 0xfff) {
2134 if (parse_adts_frame_header(ac, gb) < 0) {
dd8871a6 2135 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
158b3912
RS
2136 return -1;
2137 }
30272450 2138 if (ac->m4ac.sampling_index > 12) {
dd8871a6 2139 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
f418b861
JM
2140 return -1;
2141 }
158b3912
RS
2142 }
2143
bb2d8e9f 2144 ac->tags_mapped = 0;
62a57fae 2145 // parse
66a71d98
JG
2146 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2147 elem_id = get_bits(gb, 4);
62a57fae 2148
ed99e54d 2149 if (elem_type < TYPE_DSE) {
d4e355d5
AC
2150 if (!(che=get_che(ac, elem_type, elem_id))) {
2151 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2152 elem_type, elem_id);
2153 return -1;
2154 }
fda36b59 2155 samples = 1024;
ed99e54d 2156 }
fda36b59 2157
62a57fae
RS
2158 switch (elem_type) {
2159
2160 case TYPE_SCE:
66a71d98 2161 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
d8425ed4 2162 audio_found = 1;
62a57fae
RS
2163 break;
2164
2165 case TYPE_CPE:
66a71d98 2166 err = decode_cpe(ac, gb, che);
d8425ed4 2167 audio_found = 1;
62a57fae
RS
2168 break;
2169
2170 case TYPE_CCE:
66a71d98 2171 err = decode_cce(ac, gb, che);
62a57fae
RS
2172 break;
2173
2174 case TYPE_LFE:
66a71d98 2175 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
d8425ed4 2176 audio_found = 1;
62a57fae
RS
2177 break;
2178
2179 case TYPE_DSE:
66a71d98 2180 err = skip_data_stream_element(ac, gb);
62a57fae
RS
2181 break;
2182
577d383b 2183 case TYPE_PCE: {
62a57fae
RS
2184 enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
2185 memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
6c003e6d 2186 if ((err = decode_pce(avctx, &ac->m4ac, new_che_pos, gb)))
62a57fae 2187 break;
4e878a18 2188 if (ac->output_configured > OC_TRIAL_PCE)
dd8871a6 2189 av_log(avctx, AV_LOG_ERROR,
6308765c
AC
2190 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
2191 else
e600a1e4 2192 err = output_configure(ac, new_che_pos, 0, OC_TRIAL_PCE);
62a57fae
RS
2193 break;
2194 }
2195
2196 case TYPE_FIL:
2197 if (elem_id == 15)
66a71d98
JG
2198 elem_id += get_bits(gb, 8) - 1;
2199 if (get_bits_left(gb) < 8 * elem_id) {
dd8871a6 2200 av_log(avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
2201 return -1;
2202 }
62a57fae 2203 while (elem_id > 0)
66a71d98 2204 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
62a57fae
RS
2205 err = 0; /* FIXME */
2206 break;
2207
2208 default:
2209 err = -1; /* should not happen, but keeps compiler happy */
2210 break;
2211 }
2212
ed492b61
AC
2213 che_prev = che;
2214 elem_type_prev = elem_type;
2215
577d383b 2216 if (err)
62a57fae 2217 return err;
8d637124 2218
66a71d98 2219 if (get_bits_left(gb) < 3) {
dd8871a6 2220 av_log(avctx, AV_LOG_ERROR, overread_err);
8d637124
AC
2221 return -1;
2222 }
62a57fae
RS
2223 }
2224
2225 spectral_to_sample(ac);
2226
ed492b61 2227 multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
54f158bd
AC
2228 samples <<= multiplier;
2229 if (ac->output_configured < OC_LOCKED) {
dd8871a6
AC
2230 avctx->sample_rate = ac->m4ac.sample_rate << multiplier;
2231 avctx->frame_size = samples;
54f158bd
AC
2232 }
2233
9aa8193a 2234 if (samples) {
0eea2129
JR
2235 /* get output buffer */
2236 ac->frame.nb_samples = samples;
2237 if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
2238 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2239 return err;
2240 }
2241
9aa8193a 2242 if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
0eea2129
JR
2243 ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
2244 (const float **)ac->output_data,
9aa8193a
JR
2245 samples, avctx->channels);
2246 else
0eea2129
JR
2247 ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
2248 (const float **)ac->output_data,
9aa8193a 2249 samples, avctx->channels);
0eea2129
JR
2250
2251 *(AVFrame *)data = ac->frame;
9aa8193a 2252 }
0eea2129 2253 *got_frame_ptr = !!samples;
9cc04edf 2254
d8425ed4 2255 if (ac->output_configured && audio_found)
981b8fd7
AC
2256 ac->output_configured = OC_LOCKED;
2257
66a71d98
JG
2258 return 0;
2259}
2260
2261static int aac_decode_frame(AVCodecContext *avctx, void *data,
0eea2129 2262 int *got_frame_ptr, AVPacket *avpkt)
66a71d98 2263{
132846b0 2264 AACContext *ac = avctx->priv_data;
66a71d98
JG
2265 const uint8_t *buf = avpkt->data;
2266 int buf_size = avpkt->size;
2267 GetBitContext gb;
2268 int buf_consumed;
2269 int buf_offset;
2270 int err;
132846b0
MS
2271 int new_extradata_size;
2272 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2273 AV_PKT_DATA_NEW_EXTRADATA,
2274 &new_extradata_size);
2275
2276 if (new_extradata) {
2277 av_free(avctx->extradata);
2278 avctx->extradata = av_mallocz(new_extradata_size +
2279 FF_INPUT_BUFFER_PADDING_SIZE);
2280 if (!avctx->extradata)
2281 return AVERROR(ENOMEM);
2282 avctx->extradata_size = new_extradata_size;
2283 memcpy(avctx->extradata, new_extradata, new_extradata_size);
2284 if (decode_audio_specific_config(ac, ac->avctx, &ac->m4ac,
2285 avctx->extradata,
2286 avctx->extradata_size*8, 1) < 0)
2287 return AVERROR_INVALIDDATA;
2288 }
66a71d98
JG
2289
2290 init_get_bits(&gb, buf, buf_size * 8);
2291
0eea2129 2292 if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)
66a71d98
JG
2293 return err;
2294
b5e2bb8c 2295 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
c16d5a6f
AC
2296 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
2297 if (buf[buf_offset])
2298 break;
2299
2300 return buf_size > buf_offset ? buf_consumed : buf_size;
9cc04edf
RS
2301}
2302
dd8871a6 2303static av_cold int aac_decode_close(AVCodecContext *avctx)
577d383b 2304{
dd8871a6 2305 AACContext *ac = avctx->priv_data;
9edae4ad 2306 int i, type;
71e9a1b8 2307
cc0591da 2308 for (i = 0; i < MAX_ELEM_ID; i++) {
ed492b61
AC
2309 for (type = 0; type < 4; type++) {
2310 if (ac->che[type][i])
2311 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
9edae4ad 2312 av_freep(&ac->che[type][i]);
ed492b61 2313 }
71e9a1b8
RS
2314 }
2315
2316 ff_mdct_end(&ac->mdct);
2317 ff_mdct_end(&ac->mdct_small);
ead15f1d 2318 ff_mdct_end(&ac->mdct_ltp);
577d383b 2319 return 0;
71e9a1b8
RS
2320}
2321
136e19e1
JG
2322
2323#define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
2324
2325struct LATMContext {
2326 AACContext aac_ctx; ///< containing AACContext
2327 int initialized; ///< initilized after a valid extradata was seen
2328
2329 // parser data
2330 int audio_mux_version_A; ///< LATM syntax version
2331 int frame_length_type; ///< 0/1 variable/fixed frame length
2332 int frame_length; ///< frame length for fixed frame length
2333};
2334
2335static inline uint32_t latm_get_value(GetBitContext *b)
2336{
2337 int length = get_bits(b, 2);
2338
2339 return get_bits_long(b, (length+1)*8);
2340}
2341
2342static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
fd095539 2343 GetBitContext *gb, int asclen)
136e19e1 2344{
d268b79e
JG
2345 AACContext *ac = &latmctx->aac_ctx;
2346 AVCodecContext *avctx = ac->avctx;
2347 MPEG4AudioConfig m4ac = {0};
fd095539
JG
2348 int config_start_bit = get_bits_count(gb);
2349 int sync_extension = 0;
2350 int bits_consumed, esize;
2351
2352 if (asclen) {
2353 sync_extension = 1;
2354 asclen = FFMIN(asclen, get_bits_left(gb));
2355 } else
2356 asclen = get_bits_left(gb);
136e19e1
JG
2357
2358 if (config_start_bit % 8) {
2359 av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
2360 "config not byte aligned.\n", 1);
2361 return AVERROR_INVALIDDATA;
d268b79e 2362 }
b5fc571e
AC
2363 if (asclen <= 0)
2364 return AVERROR_INVALIDDATA;
d268b79e 2365 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
136e19e1 2366 gb->buffer + (config_start_bit / 8),
fd095539 2367 asclen, sync_extension);
136e19e1 2368
d268b79e
JG
2369 if (bits_consumed < 0)
2370 return AVERROR_INVALIDDATA;
2371
2372 if (ac->m4ac.sample_rate != m4ac.sample_rate ||
2373 ac->m4ac.chan_config != m4ac.chan_config) {
2374
2375 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
2376 latmctx->initialized = 0;
136e19e1
JG
2377
2378 esize = (bits_consumed+7) / 8;
2379
d268b79e 2380 if (avctx->extradata_size < esize) {
136e19e1
JG
2381 av_free(avctx->extradata);
2382 avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);
2383 if (!avctx->extradata)
2384 return AVERROR(ENOMEM);
2385 }
2386
2387 avctx->extradata_size = esize;
2388 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
2389 memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2390 }
d268b79e 2391 skip_bits_long(gb, bits_consumed);
136e19e1
JG
2392
2393 return bits_consumed;
2394}
2395
2396static int read_stream_mux_config(struct LATMContext *latmctx,
2397 GetBitContext *gb)
2398{
2399 int ret, audio_mux_version = get_bits(gb, 1);
2400
2401 latmctx->audio_mux_version_A = 0;
2402 if (audio_mux_version)
2403 latmctx->audio_mux_version_A = get_bits(gb, 1);
2404
2405 if (!latmctx->audio_mux_version_A) {
2406
2407 if (audio_mux_version)
2408 latm_get_value(gb); // taraFullness
2409
2410 skip_bits(gb, 1); // allStreamSameTimeFraming
2411 skip_bits(gb, 6); // numSubFrames
2412 // numPrograms
2413 if (get_bits(gb, 4)) { // numPrograms
2414 av_log_missing_feature(latmctx->aac_ctx.avctx,
2415 "multiple programs are not supported\n", 1);
2416 return AVERROR_PATCHWELCOME;
2417 }
2418
2419 // for each program (which there is only on in DVB)
2420
2421 // for each layer (which there is only on in DVB)
2422 if (get_bits(gb, 3)) { // numLayer
2423 av_log_missing_feature(latmctx->aac_ctx.avctx,
2424 "multiple layers are not supported\n", 1);
2425 return AVERROR_PATCHWELCOME;
2426 }
2427
2428 // for all but first stream: use_same_config = get_bits(gb, 1);
2429 if (!audio_mux_version) {
fd095539 2430 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
136e19e1
JG
2431 return ret;
2432 } else {
2433 int ascLen = latm_get_value(gb);
fd095539 2434 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
136e19e1
JG
2435 return ret;
2436 ascLen -= ret;
2437 skip_bits_long(gb, ascLen);
2438 }
2439
2440 latmctx->frame_length_type = get_bits(gb, 3);
2441 switch (latmctx->frame_length_type) {
2442 case 0:
2443 skip_bits(gb, 8); // latmBufferFullness
2444 break;
2445 case 1:
2446 latmctx->frame_length = get_bits(gb, 9);
2447 break;
2448 case 3:
2449 case 4:
2450 case 5:
2451 skip_bits(gb, 6); // CELP frame length table index
2452 break;
2453 case 6:
2454 case 7:
2455 skip_bits(gb, 1); // HVXC frame length table index
2456 break;
2457 }
2458
2459 if (get_bits(gb, 1)) { // other data
2460 if (audio_mux_version) {
2461 latm_get_value(gb); // other_data_bits
2462 } else {
2463 int esc;
2464 do {
2465 esc = get_bits(gb, 1);
2466 skip_bits(gb, 8);
2467 } while (esc);
2468 }
2469 }
2470
2471 if (get_bits(gb, 1)) // crc present
2472 skip_bits(gb, 8); // config_crc
2473 }
2474
2475 return 0;
2476}
2477
2478static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
2479{
2480 uint8_t tmp;
2481
2482 if (ctx->frame_length_type == 0) {
2483 int mux_slot_length = 0;
2484 do {
2485 tmp = get_bits(gb, 8);
2486 mux_slot_length += tmp;
2487 } while (tmp == 255);
2488 return mux_slot_length;
2489 } else if (ctx->frame_length_type == 1) {
2490 return ctx->frame_length;
2491 } else if (ctx->frame_length_type == 3 ||
2492 ctx->frame_length_type == 5 ||
2493 ctx->frame_length_type == 7) {
2494 skip_bits(gb, 2); // mux_slot_length_coded
2495 }
2496 return 0;
2497}
2498
2499static int read_audio_mux_element(struct LATMContext *latmctx,
2500 GetBitContext *gb)
2501{
2502 int err;
2503 uint8_t use_same_mux = get_bits(gb, 1);
2504 if (!use_same_mux) {
2505 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
2506 return err;
2507 } else if (!latmctx->aac_ctx.avctx->extradata) {
2508 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
2509 "no decoder config found\n");
2510 return AVERROR(EAGAIN);
2511 }
2512 if (latmctx->audio_mux_version_A == 0) {
2513 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
2514 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
2515 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
2516 return AVERROR_INVALIDDATA;
2517 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
2518 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2519 "frame length mismatch %d << %d\n",
2520 mux_slot_length_bytes * 8, get_bits_left(gb));
2521 return AVERROR_INVALIDDATA;
2522 }
2523 }
2524 return 0;
2525}
2526
2527
0eea2129
JR
2528static int latm_decode_frame(AVCodecContext *avctx, void *out,
2529 int *got_frame_ptr, AVPacket *avpkt)
136e19e1
JG
2530{
2531 struct LATMContext *latmctx = avctx->priv_data;
2532 int muxlength, err;
2533 GetBitContext gb;
2534
136e19e1
JG
2535 init_get_bits(&gb, avpkt->data, avpkt->size * 8);
2536
2537 // check for LOAS sync word
2538 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
2539 return AVERROR_INVALIDDATA;
2540
ebb7f7de 2541 muxlength = get_bits(&gb, 13) + 3;
136e19e1 2542 // not enough data, the parser should have sorted this
ebb7f7de 2543 if (muxlength > avpkt->size)
136e19e1
JG
2544 return AVERROR_INVALIDDATA;
2545
2546 if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
2547 return err;
2548
2549 if (!latmctx->initialized) {
2550 if (!avctx->extradata) {
0eea2129 2551 *got_frame_ptr = 0;
136e19e1
JG
2552 return avpkt->size;
2553 } else {
785f876c
JG
2554 if ((err = decode_audio_specific_config(
2555 &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.m4ac,
fd095539 2556 avctx->extradata, avctx->extradata_size*8, 1)) < 0)
136e19e1
JG
2557 return err;
2558 latmctx->initialized = 1;
2559 }
2560 }
2561
2562 if (show_bits(&gb, 12) == 0xfff) {
2563 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
2564 "ADTS header detected, probably as result of configuration "
2565 "misparsing\n");
2566 return AVERROR_INVALIDDATA;
2567 }
2568
0eea2129 2569 if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb)) < 0)
136e19e1
JG
2570 return err;
2571
2572 return muxlength;
2573}
2574
2575av_cold static int latm_decode_init(AVCodecContext *avctx)
2576{
2577 struct LATMContext *latmctx = avctx->priv_data;
28287045 2578 int ret = aac_decode_init(avctx);
136e19e1 2579
28287045 2580 if (avctx->extradata_size > 0)
136e19e1 2581 latmctx->initialized = !ret;
136e19e1
JG
2582
2583 return ret;
2584}
2585
2586
d36beb3f 2587AVCodec ff_aac_decoder = {
ec6402b7
AK
2588 .name = "aac",
2589 .type = AVMEDIA_TYPE_AUDIO,
2590 .id = CODEC_ID_AAC,
2591 .priv_data_size = sizeof(AACContext),
2592 .init = aac_decode_init,
2593 .close = aac_decode_close,
2594 .decode = aac_decode_frame,
71e9a1b8 2595 .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
5d6e4c16 2596 .sample_fmts = (const enum AVSampleFormat[]) {
9aa8193a 2597 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
577d383b 2598 },
0eea2129 2599 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
e22da6b6 2600 .channel_layouts = aac_channel_layout,
71e9a1b8 2601};
136e19e1
JG
2602
2603/*
2604 Note: This decoder filter is intended to decode LATM streams transferred
2605 in MPEG transport streams which only contain one program.
2606 To do a more complex LATM demuxing a separate LATM demuxer should be used.
2607*/
d36beb3f 2608AVCodec ff_aac_latm_decoder = {
136e19e1 2609 .name = "aac_latm",
b2ed95ec 2610 .type = AVMEDIA_TYPE_AUDIO,
136e19e1
JG
2611 .id = CODEC_ID_AAC_LATM,
2612 .priv_data_size = sizeof(struct LATMContext),
2613 .init = latm_decode_init,
2614 .close = aac_decode_close,
2615 .decode = latm_decode_frame,
2616 .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Codec LATM syntax)"),
5d6e4c16 2617 .sample_fmts = (const enum AVSampleFormat[]) {
9aa8193a 2618 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
136e19e1 2619 },
0eea2129 2620 .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
136e19e1
JG
2621 .channel_layouts = aac_channel_layout,
2622};