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