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