lavc: make sure not to return EAGAIN from codecs
[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 )
b3be41ca 5 * Copyright (c) 2008-2013 Alex Converse <alex.converse@gmail.com>
71e9a1b8 6 *
136e19e1
JG
7 * AAC LATM decoder
8 * Copyright (c) 2008-2010 Paul Kendall <paul@kcbbs.gen.nz>
f36d5c14 9 * Copyright (c) 2010 Janne Grunau <janne-libav@jannau.net>
136e19e1 10 *
2912e87a 11 * This file is part of Libav.
71e9a1b8 12 *
2912e87a 13 * Libav is free software; you can redistribute it and/or
71e9a1b8
RS
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2.1 of the License, or (at your option) any later version.
17 *
2912e87a 18 * Libav is distributed in the hope that it will be useful,
71e9a1b8
RS
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
22 *
23 * You should have received a copy of the GNU Lesser General Public
2912e87a 24 * License along with Libav; if not, write to the Free Software
71e9a1b8
RS
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 */
27
28/**
ba87f080 29 * @file
71e9a1b8
RS
30 * AAC decoder
31 * @author Oded Shimon ( ods15 ods15 dyndns org )
32 * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
33 */
34
35/*
36 * supported tools
37 *
38 * Support? Name
39 * N (code in SoC repo) gain control
40 * Y block switching
41 * Y window shapes - standard
42 * N window shapes - Low Delay
43 * Y filterbank - standard
44 * N (code in SoC repo) filterbank - Scalable Sample Rate
45 * Y Temporal Noise Shaping
ead15f1d 46 * Y Long Term Prediction
71e9a1b8
RS
47 * Y intensity stereo
48 * Y channel coupling
7633a041 49 * Y frequency domain prediction
71e9a1b8
RS
50 * Y Perceptual Noise Substitution
51 * Y Mid/Side stereo
52 * N Scalable Inverse AAC Quantization
53 * N Frequency Selective Switch
54 * N upsampling filter
55 * Y quantization & coding - AAC
56 * N quantization & coding - TwinVQ
57 * N quantization & coding - BSAC
58 * N AAC Error Resilience tools
59 * N Error Resilience payload syntax
60 * N Error Protection tool
61 * N CELP
62 * N Silence Compression
63 * N HVXC
64 * N HVXC 4kbits/s VR
65 * N Structured Audio tools
66 * N Structured Audio Sample Bank Format
67 * N MIDI
68 * N Harmonic and Individual Lines plus Noise
69 * N Text-To-Speech Interface
ed492b61 70 * Y Spectral Band Replication
71e9a1b8
RS
71 * Y (not in this code) Layer-1
72 * Y (not in this code) Layer-2
73 * Y (not in this code) Layer-3
74 * N SinuSoidal Coding (Transient, Sinusoid, Noise)
a2063901 75 * Y Parametric Stereo
71e9a1b8
RS
76 * N Direct Stream Transfer
77 *
78 * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
79 * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
80 Parametric Stereo.
81 */
82
d5a7229b 83#include "libavutil/float_dsp.h"
71e9a1b8 84#include "avcodec.h"
dbbec0c2 85#include "internal.h"
9106a698 86#include "get_bits.h"
1429224b 87#include "fft.h"
d615187f 88#include "imdct15.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>
8f8bc923 106#include <stdint.h>
71e9a1b8
RS
107#include <string.h>
108
798339fb
MR
109#if ARCH_ARM
110# include "arm/aac.h"
111#endif
112
504e3f75
DB
113#include "libavutil/thread.h"
114
71e9a1b8
RS
115static VLC vlc_scalefactors;
116static VLC vlc_spectral[11];
117
8d637124
AC
118static const char overread_err[] = "Input buffer exhausted before END element found\n";
119
37bed6ff 120static int count_channels(uint8_t (*layout)[3], int tags)
4acd43a2 121{
37bed6ff
AC
122 int i, sum = 0;
123 for (i = 0; i < tags; i++) {
124 int syn_ele = layout[i][0];
125 int pos = layout[i][2];
126 sum += (1 + (syn_ele == TYPE_CPE)) *
127 (pos != AAC_CHANNEL_OFF && pos != AAC_CHANNEL_CC);
4acd43a2
AC
128 }
129 return sum;
130}
131
9cc04edf 132/**
754ff9a7
RS
133 * Check for the channel element in the current channel position configuration.
134 * If it exists, make sure the appropriate element is allocated and map the
2912e87a 135 * channel order to match the internal Libav channel layout.
754ff9a7
RS
136 *
137 * @param che_pos current channel position configuration
138 * @param type channel element type
139 * @param id channel element id
140 * @param channels count of the number of channels in the configuration
141 *
142 * @return Returns error status. 0 - OK, !0 - error
143 */
89584458 144static av_cold int che_configure(AACContext *ac,
e600a1e4 145 enum ChannelPosition che_pos,
9978ed7d 146 int type, int id, int *channels)
754ff9a7 147{
e600a1e4 148 if (che_pos) {
80e36425
JG
149 if (!ac->che[type][id]) {
150 if (!(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
151 return AVERROR(ENOMEM);
152 ff_aac_sbr_ctx_init(ac, &ac->che[type][id]->sbr);
153 }
754ff9a7 154 if (type != TYPE_CCE) {
b99ca863
VG
155 if (*channels >= MAX_CHANNELS - 2)
156 return AVERROR_INVALIDDATA;
3d3cf674 157 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
a2063901 158 if (type == TYPE_CPE ||
9fb7e146 159 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
3d3cf674 160 ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
754ff9a7
RS
161 }
162 }
ed492b61
AC
163 } else {
164 if (ac->che[type][id])
165 ff_aac_sbr_ctx_close(&ac->che[type][id]->sbr);
754ff9a7 166 av_freep(&ac->che[type][id]);
ed492b61 167 }
754ff9a7
RS
168 return 0;
169}
170
3d3cf674
JR
171static int frame_configure_elements(AVCodecContext *avctx)
172{
173 AACContext *ac = avctx->priv_data;
174 int type, id, ch, ret;
175
176 /* set channel pointers to internal buffers by default */
177 for (type = 0; type < 4; type++) {
178 for (id = 0; id < MAX_ELEM_ID; id++) {
179 ChannelElement *che = ac->che[type][id];
180 if (che) {
181 che->ch[0].ret = che->ch[0].ret_buf;
182 che->ch[1].ret = che->ch[1].ret_buf;
183 }
184 }
185 }
186
187 /* get output buffer */
759001c5 188 av_frame_unref(ac->frame);
ffd21230 189 ac->frame->nb_samples = 2048;
759001c5 190 if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0) {
3d3cf674
JR
191 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
192 return ret;
193 }
194
195 /* map output channel pointers to AVFrame data */
196 for (ch = 0; ch < avctx->channels; ch++) {
197 if (ac->output_element[ch])
ffd21230 198 ac->output_element[ch]->ret = (float *)ac->frame->extended_data[ch];
3d3cf674
JR
199 }
200
201 return 0;
202}
203
37bed6ff
AC
204struct elem_to_channel {
205 uint64_t av_position;
206 uint8_t syn_ele;
207 uint8_t elem_id;
208 uint8_t aac_position;
209};
210
211static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
5707af8d 212 uint8_t (*layout_map)[3], int offset, uint64_t left,
6d8629aa 213 uint64_t right, int pos)
37bed6ff
AC
214{
215 if (layout_map[offset][0] == TYPE_CPE) {
216 e2c_vec[offset] = (struct elem_to_channel) {
6d8629aa
LB
217 .av_position = left | right,
218 .syn_ele = TYPE_CPE,
219 .elem_id = layout_map[offset][1],
220 .aac_position = pos
221 };
37bed6ff
AC
222 return 1;
223 } else {
6d8629aa
LB
224 e2c_vec[offset] = (struct elem_to_channel) {
225 .av_position = left,
226 .syn_ele = TYPE_SCE,
227 .elem_id = layout_map[offset][1],
228 .aac_position = pos
229 };
37bed6ff 230 e2c_vec[offset + 1] = (struct elem_to_channel) {
6d8629aa
LB
231 .av_position = right,
232 .syn_ele = TYPE_SCE,
233 .elem_id = layout_map[offset + 1][1],
234 .aac_position = pos
235 };
37bed6ff
AC
236 return 2;
237 }
238}
239
6d8629aa
LB
240static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos,
241 int *current)
242{
37bed6ff 243 int num_pos_channels = 0;
6d8629aa
LB
244 int first_cpe = 0;
245 int sce_parity = 0;
37bed6ff
AC
246 int i;
247 for (i = *current; i < tags; i++) {
248 if (layout_map[i][2] != pos)
249 break;
250 if (layout_map[i][0] == TYPE_CPE) {
251 if (sce_parity) {
744dd1d3 252 if (pos == AAC_CHANNEL_FRONT && !first_cpe) {
37bed6ff
AC
253 sce_parity = 0;
254 } else {
255 return -1;
256 }
257 }
258 num_pos_channels += 2;
6d8629aa 259 first_cpe = 1;
37bed6ff
AC
260 } else {
261 num_pos_channels++;
262 sce_parity ^= 1;
263 }
264 }
265 if (sce_parity &&
266 ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))
6d8629aa 267 return -1;
37bed6ff
AC
268 *current = i;
269 return num_pos_channels;
270}
271
272static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)
273{
274 int i, n, total_non_cc_elements;
6d8629aa 275 struct elem_to_channel e2c_vec[4 * MAX_ELEM_ID] = { { 0 } };
37bed6ff
AC
276 int num_front_channels, num_side_channels, num_back_channels;
277 uint64_t layout;
278
d53fe096
MN
279 if (FF_ARRAY_ELEMS(e2c_vec) < tags)
280 return 0;
281
37bed6ff
AC
282 i = 0;
283 num_front_channels =
284 count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);
285 if (num_front_channels < 0)
286 return 0;
287 num_side_channels =
288 count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);
289 if (num_side_channels < 0)
290 return 0;
291 num_back_channels =
292 count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);
293 if (num_back_channels < 0)
294 return 0;
295
677c804a 296 if (num_side_channels == 0 && num_back_channels >= 4) {
297 num_side_channels = 2;
298 num_back_channels -= 2;
299 }
300
37bed6ff
AC
301 i = 0;
302 if (num_front_channels & 1) {
303 e2c_vec[i] = (struct elem_to_channel) {
6d8629aa
LB
304 .av_position = AV_CH_FRONT_CENTER,
305 .syn_ele = TYPE_SCE,
306 .elem_id = layout_map[i][1],
307 .aac_position = AAC_CHANNEL_FRONT
308 };
37bed6ff
AC
309 i++;
310 num_front_channels--;
311 }
312 if (num_front_channels >= 4) {
5707af8d 313 i += assign_pair(e2c_vec, layout_map, i,
37bed6ff
AC
314 AV_CH_FRONT_LEFT_OF_CENTER,
315 AV_CH_FRONT_RIGHT_OF_CENTER,
316 AAC_CHANNEL_FRONT);
317 num_front_channels -= 2;
318 }
319 if (num_front_channels >= 2) {
5707af8d 320 i += assign_pair(e2c_vec, layout_map, i,
37bed6ff
AC
321 AV_CH_FRONT_LEFT,
322 AV_CH_FRONT_RIGHT,
323 AAC_CHANNEL_FRONT);
324 num_front_channels -= 2;
325 }
326 while (num_front_channels >= 2) {
5707af8d 327 i += assign_pair(e2c_vec, layout_map, i,
37bed6ff
AC
328 UINT64_MAX,
329 UINT64_MAX,
330 AAC_CHANNEL_FRONT);
331 num_front_channels -= 2;
332 }
333
334 if (num_side_channels >= 2) {
5707af8d 335 i += assign_pair(e2c_vec, layout_map, i,
37bed6ff
AC
336 AV_CH_SIDE_LEFT,
337 AV_CH_SIDE_RIGHT,
338 AAC_CHANNEL_FRONT);
339 num_side_channels -= 2;
340 }
341 while (num_side_channels >= 2) {
5707af8d 342 i += assign_pair(e2c_vec, layout_map, i,
37bed6ff
AC
343 UINT64_MAX,
344 UINT64_MAX,
345 AAC_CHANNEL_SIDE);
346 num_side_channels -= 2;
347 }
348
349 while (num_back_channels >= 4) {
5707af8d 350 i += assign_pair(e2c_vec, layout_map, i,
37bed6ff
AC
351 UINT64_MAX,
352 UINT64_MAX,
353 AAC_CHANNEL_BACK);
354 num_back_channels -= 2;
355 }
356 if (num_back_channels >= 2) {
5707af8d 357 i += assign_pair(e2c_vec, layout_map, i,
37bed6ff
AC
358 AV_CH_BACK_LEFT,
359 AV_CH_BACK_RIGHT,
360 AAC_CHANNEL_BACK);
361 num_back_channels -= 2;
362 }
363 if (num_back_channels) {
364 e2c_vec[i] = (struct elem_to_channel) {
6d8629aa
LB
365 .av_position = AV_CH_BACK_CENTER,
366 .syn_ele = TYPE_SCE,
367 .elem_id = layout_map[i][1],
368 .aac_position = AAC_CHANNEL_BACK
369 };
37bed6ff
AC
370 i++;
371 num_back_channels--;
372 }
373
374 if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
375 e2c_vec[i] = (struct elem_to_channel) {
6d8629aa
LB
376 .av_position = AV_CH_LOW_FREQUENCY,
377 .syn_ele = TYPE_LFE,
378 .elem_id = layout_map[i][1],
379 .aac_position = AAC_CHANNEL_LFE
380 };
37bed6ff
AC
381 i++;
382 }
383 while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {
384 e2c_vec[i] = (struct elem_to_channel) {
6d8629aa
LB
385 .av_position = UINT64_MAX,
386 .syn_ele = TYPE_LFE,
387 .elem_id = layout_map[i][1],
388 .aac_position = AAC_CHANNEL_LFE
389 };
37bed6ff
AC
390 i++;
391 }
392
393 // Must choose a stable sort
394 total_non_cc_elements = n = i;
395 do {
396 int next_n = 0;
6d8629aa
LB
397 for (i = 1; i < n; i++)
398 if (e2c_vec[i - 1].av_position > e2c_vec[i].av_position) {
399 FFSWAP(struct elem_to_channel, e2c_vec[i - 1], e2c_vec[i]);
37bed6ff
AC
400 next_n = i;
401 }
37bed6ff
AC
402 n = next_n;
403 } while (n > 0);
404
405 layout = 0;
406 for (i = 0; i < total_non_cc_elements; i++) {
407 layout_map[i][0] = e2c_vec[i].syn_ele;
408 layout_map[i][1] = e2c_vec[i].elem_id;
409 layout_map[i][2] = e2c_vec[i].aac_position;
410 if (e2c_vec[i].av_position != UINT64_MAX) {
411 layout |= e2c_vec[i].av_position;
412 }
413 }
414
415 return layout;
416}
417
754ff9a7 418/**
9fb7e146
AC
419 * Save current output configuration if and only if it has been locked.
420 */
421static void push_output_configuration(AACContext *ac) {
422 if (ac->oc[1].status == OC_LOCKED) {
423 ac->oc[0] = ac->oc[1];
424 }
425 ac->oc[1].status = OC_NONE;
426}
427
428/**
429 * Restore the previous output configuration if and only if the current
430 * configuration is unlocked.
431 */
432static void pop_output_configuration(AACContext *ac) {
122d5c52 433 if (ac->oc[1].status != OC_LOCKED && ac->oc[0].status != OC_NONE) {
9fb7e146
AC
434 ac->oc[1] = ac->oc[0];
435 ac->avctx->channels = ac->oc[1].channels;
43886eae 436 ac->avctx->channel_layout = ac->oc[1].channel_layout;
9fb7e146
AC
437 }
438}
439
440/**
6d8629aa
LB
441 * Configure output channel order based on the current program
442 * configuration element.
62a57fae 443 *
62a57fae
RS
444 * @return Returns error status. 0 - OK, !0 - error
445 */
9fb7e146 446static int output_configure(AACContext *ac,
6d8629aa 447 uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,
3d3cf674 448 enum OCStatus oc_type, int get_new_frame)
577d383b 449{
dd8871a6 450 AVCodecContext *avctx = ac->avctx;
37bed6ff 451 int i, channels = 0, ret;
7b050258 452 uint64_t layout = 0;
0289f812 453 uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};
454 uint8_t type_counts[TYPE_END] = { 0 };
62a57fae 455
9fb7e146
AC
456 if (ac->oc[1].layout_map != layout_map) {
457 memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));
458 ac->oc[1].layout_map_tags = tags;
37bed6ff 459 }
0289f812 460 for (i = 0; i < tags; i++) {
461 int type = layout_map[i][0];
462 int id = layout_map[i][1];
463 id_map[type][id] = type_counts[type]++;
464 }
7b050258
AC
465 // Try to sniff a reasonable channel order, otherwise output the
466 // channels in the order the PCE declared them.
467 if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)
468 layout = sniff_channel_order(layout_map, tags);
469 for (i = 0; i < tags; i++) {
470 int type = layout_map[i][0];
471 int id = layout_map[i][1];
0289f812 472 int iid = id_map[type][id];
7b050258
AC
473 int position = layout_map[i][2];
474 // Allocate or free elements depending on if they are in the
475 // current program configuration.
0289f812 476 ret = che_configure(ac, position, type, iid, &channels);
7b050258
AC
477 if (ret < 0)
478 return ret;
0289f812 479 ac->tag_che_map[type][id] = ac->che[type][iid];
bb5c0988 480 }
7eacd70f
AC
481 if (ac->oc[1].m4ac.ps == 1 && channels == 2) {
482 if (layout == AV_CH_FRONT_CENTER) {
483 layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;
484 } else {
485 layout = 0;
486 }
487 }
bb5c0988 488
9fb7e146 489 avctx->channel_layout = ac->oc[1].channel_layout = layout;
6d8629aa 490 avctx->channels = ac->oc[1].channels = channels;
9fb7e146 491 ac->oc[1].status = oc_type;
6308765c 492
3d3cf674
JR
493 if (get_new_frame) {
494 if ((ret = frame_configure_elements(ac->avctx)) < 0)
495 return ret;
496 }
497
62a57fae
RS
498 return 0;
499}
500
501/**
2564f6e6
AC
502 * Set up channel positions based on a default channel configuration
503 * as specified in table 1.17.
504 *
505 * @return Returns error status. 0 - OK, !0 - error
506 */
9fb7e146 507static int set_default_channel_config(AVCodecContext *avctx,
6d8629aa
LB
508 uint8_t (*layout_map)[3],
509 int *tags,
510 int channel_config)
2564f6e6 511{
a188108e
SD
512 if (channel_config < 1 || (channel_config > 7 && channel_config < 11) ||
513 channel_config > 12) {
6d8629aa
LB
514 av_log(avctx, AV_LOG_ERROR,
515 "invalid default channel configuration (%d)\n",
2564f6e6 516 channel_config);
07c52e2c 517 return AVERROR_INVALIDDATA;
2564f6e6
AC
518 }
519 *tags = tags_per_config[channel_config];
6d8629aa
LB
520 memcpy(layout_map, aac_channel_layout_map[channel_config - 1],
521 *tags * sizeof(*layout_map));
2564f6e6
AC
522 return 0;
523}
524
525static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
526{
6d8629aa
LB
527 /* For PCE based channel configurations map the channels solely based
528 * on tags. */
9fb7e146 529 if (!ac->oc[1].m4ac.chan_config) {
2564f6e6
AC
530 return ac->tag_che_map[type][elem_id];
531 }
956fb91e 532 // Allow single CPE stereo files to be signalled with mono configuration.
6d8629aa
LB
533 if (!ac->tags_mapped && type == TYPE_CPE &&
534 ac->oc[1].m4ac.chan_config == 1) {
956fb91e
MN
535 uint8_t layout_map[MAX_ELEM_ID*4][3];
536 int layout_map_tags;
9fb7e146 537 push_output_configuration(ac);
956fb91e 538
6d8629aa
LB
539 if (set_default_channel_config(ac->avctx, layout_map,
540 &layout_map_tags, 2) < 0)
956fb91e
MN
541 return NULL;
542 if (output_configure(ac, layout_map, layout_map_tags,
3d3cf674 543 OC_TRIAL_FRAME, 1) < 0)
956fb91e
MN
544 return NULL;
545
9fb7e146 546 ac->oc[1].m4ac.chan_config = 2;
79c8e29a 547 ac->oc[1].m4ac.ps = 0;
9fb7e146
AC
548 }
549 // And vice-versa
6d8629aa
LB
550 if (!ac->tags_mapped && type == TYPE_SCE &&
551 ac->oc[1].m4ac.chan_config == 2) {
552 uint8_t layout_map[MAX_ELEM_ID * 4][3];
9fb7e146
AC
553 int layout_map_tags;
554 push_output_configuration(ac);
555
6d8629aa
LB
556 if (set_default_channel_config(ac->avctx, layout_map,
557 &layout_map_tags, 1) < 0)
9fb7e146
AC
558 return NULL;
559 if (output_configure(ac, layout_map, layout_map_tags,
3d3cf674 560 OC_TRIAL_FRAME, 1) < 0)
9fb7e146
AC
561 return NULL;
562
563 ac->oc[1].m4ac.chan_config = 1;
79c8e29a
AC
564 if (ac->oc[1].m4ac.sbr)
565 ac->oc[1].m4ac.ps = -1;
956fb91e 566 }
6d8629aa
LB
567 /* For indexed channel configurations map the channels solely based
568 * on position. */
9fb7e146 569 switch (ac->oc[1].m4ac.chan_config) {
a188108e 570 case 12:
2564f6e6
AC
571 case 7:
572 if (ac->tags_mapped == 3 && type == TYPE_CPE) {
573 ac->tags_mapped++;
574 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
575 }
a188108e
SD
576 case 11:
577 if (ac->tags_mapped == 2 &&
578 ac->oc[1].m4ac.chan_config == 11 &&
579 type == TYPE_SCE) {
580 ac->tags_mapped++;
581 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
582 }
2564f6e6 583 case 6:
6d8629aa
LB
584 /* Some streams incorrectly code 5.1 audio as
585 * SCE[0] CPE[0] CPE[1] SCE[1]
586 * instead of
587 * SCE[0] CPE[0] CPE[1] LFE[0].
588 * If we seem to have encountered such a stream, transfer
589 * the LFE[0] element to the SCE[1]'s mapping */
9fb7e146 590 if (ac->tags_mapped == tags_per_config[ac->oc[1].m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
2564f6e6
AC
591 ac->tags_mapped++;
592 return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
593 }
594 case 5:
595 if (ac->tags_mapped == 2 && type == TYPE_CPE) {
596 ac->tags_mapped++;
597 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
598 }
599 case 4:
6d8629aa
LB
600 if (ac->tags_mapped == 2 &&
601 ac->oc[1].m4ac.chan_config == 4 &&
602 type == TYPE_SCE) {
2564f6e6
AC
603 ac->tags_mapped++;
604 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
605 }
606 case 3:
607 case 2:
6d8629aa
LB
608 if (ac->tags_mapped == (ac->oc[1].m4ac.chan_config != 2) &&
609 type == TYPE_CPE) {
2564f6e6
AC
610 ac->tags_mapped++;
611 return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
9fb7e146 612 } else if (ac->oc[1].m4ac.chan_config == 2) {
2564f6e6
AC
613 return NULL;
614 }
615 case 1:
616 if (!ac->tags_mapped && type == TYPE_SCE) {
617 ac->tags_mapped++;
618 return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
619 }
620 default:
621 return NULL;
622 }
623}
624
625/**
6d8629aa
LB
626 * Decode an array of 4 bit element IDs, optionally interleaved with a
627 * stereo/mono switching bit.
9cc04edf 628 *
9cc04edf
RS
629 * @param type speaker type/position for these channels
630 */
37bed6ff 631static void decode_channel_map(uint8_t layout_map[][3],
577d383b
DB
632 enum ChannelPosition type,
633 GetBitContext *gb, int n)
634{
635 while (n--) {
37bed6ff
AC
636 enum RawDataBlockType syn_ele;
637 switch (type) {
638 case AAC_CHANNEL_FRONT:
639 case AAC_CHANNEL_BACK:
640 case AAC_CHANNEL_SIDE:
641 syn_ele = get_bits1(gb);
642 break;
643 case AAC_CHANNEL_CC:
644 skip_bits1(gb);
645 syn_ele = TYPE_CCE;
646 break;
647 case AAC_CHANNEL_LFE:
648 syn_ele = TYPE_LFE;
649 break;
77ab341c
VG
650 default:
651 // AAC_CHANNEL_OFF has no channel map
652 return;
37bed6ff
AC
653 }
654 layout_map[0][0] = syn_ele;
655 layout_map[0][1] = get_bits(gb, 4);
656 layout_map[0][2] = type;
657 layout_map++;
9cc04edf
RS
658 }
659}
660
661/**
662 * Decode program configuration element; reference: table 4.2.
663 *
9cc04edf
RS
664 * @return Returns error status. 0 - OK, !0 - error
665 */
6c003e6d 666static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac,
37bed6ff 667 uint8_t (*layout_map)[3],
577d383b
DB
668 GetBitContext *gb)
669{
6d8629aa
LB
670 int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
671 int sampling_index;
8d637124 672 int comment_len;
37bed6ff 673 int tags;
9cc04edf
RS
674
675 skip_bits(gb, 2); // object_type
676
99665a21 677 sampling_index = get_bits(gb, 4);
6c003e6d 678 if (m4ac->sampling_index != sampling_index)
6d8629aa
LB
679 av_log(avctx, AV_LOG_WARNING,
680 "Sample rate index in program config element does not "
681 "match the sample rate index configured by the container.\n");
401a9950 682
71e9a1b8
RS
683 num_front = get_bits(gb, 4);
684 num_side = get_bits(gb, 4);
685 num_back = get_bits(gb, 4);
686 num_lfe = get_bits(gb, 2);
687 num_assoc_data = get_bits(gb, 3);
688 num_cc = get_bits(gb, 4);
689
cc0591da
RS
690 if (get_bits1(gb))
691 skip_bits(gb, 4); // mono_mixdown_tag
692 if (get_bits1(gb))
693 skip_bits(gb, 4); // stereo_mixdown_tag
71e9a1b8 694
cc0591da
RS
695 if (get_bits1(gb))
696 skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
71e9a1b8 697
37bed6ff
AC
698 decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front);
699 tags = num_front;
700 decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side);
701 tags += num_side;
702 decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back);
703 tags += num_back;
704 decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe);
705 tags += num_lfe;
71e9a1b8
RS
706
707 skip_bits_long(gb, 4 * num_assoc_data);
708
37bed6ff
AC
709 decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc);
710 tags += num_cc;
71e9a1b8
RS
711
712 align_get_bits(gb);
713
714 /* comment field, first byte is length */
8d637124
AC
715 comment_len = get_bits(gb, 8) * 8;
716 if (get_bits_left(gb) < comment_len) {
6c003e6d 717 av_log(avctx, AV_LOG_ERROR, overread_err);
07c52e2c 718 return AVERROR_INVALIDDATA;
8d637124
AC
719 }
720 skip_bits_long(gb, comment_len);
37bed6ff 721 return tags;
cc0591da 722}
71e9a1b8 723
9cc04edf 724/**
62a57fae
RS
725 * Decode GA "General Audio" specific configuration; reference: table 4.1.
726 *
6c003e6d
JG
727 * @param ac pointer to AACContext, may be null
728 * @param avctx pointer to AVCCodecContext, used for logging
729 *
62a57fae
RS
730 * @return Returns error status. 0 - OK, !0 - error
731 */
6c003e6d
JG
732static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
733 GetBitContext *gb,
37d28953 734 MPEG4AudioConfig *m4ac,
577d383b
DB
735 int channel_config)
736{
5cdefc02 737 int extension_flag, ret, ep_config, res_flags;
37bed6ff
AC
738 uint8_t layout_map[MAX_ELEM_ID*4][3];
739 int tags = 0;
62a57fae 740
577d383b 741 if (get_bits1(gb)) { // frameLengthFlag
12e25ed2 742 avpriv_request_sample(avctx, "960/120 MDCT window");
717addec 743 return AVERROR_PATCHWELCOME;
9cc04edf 744 }
d615187f 745 m4ac->frame_length_short = 0;
9cc04edf
RS
746
747 if (get_bits1(gb)) // dependsOnCoreCoder
748 skip_bits(gb, 14); // coreCoderDelay
749 extension_flag = get_bits1(gb);
750
37d28953
JG
751 if (m4ac->object_type == AOT_AAC_SCALABLE ||
752 m4ac->object_type == AOT_ER_AAC_SCALABLE)
9cc04edf
RS
753 skip_bits(gb, 3); // layerNr
754
9cc04edf
RS
755 if (channel_config == 0) {
756 skip_bits(gb, 4); // element_instance_tag
37bed6ff
AC
757 tags = decode_pce(avctx, m4ac, layout_map, gb);
758 if (tags < 0)
759 return tags;
9cc04edf 760 } else {
6d8629aa
LB
761 if ((ret = set_default_channel_config(avctx, layout_map,
762 &tags, channel_config)))
9cc04edf
RS
763 return ret;
764 }
4acd43a2 765
37bed6ff 766 if (count_channels(layout_map, tags) > 1) {
4acd43a2
AC
767 m4ac->ps = 0;
768 } else if (m4ac->sbr == 1 && m4ac->ps == -1)
769 m4ac->ps = 1;
770
3d3cf674 771 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
9cc04edf
RS
772 return ret;
773
774 if (extension_flag) {
37d28953 775 switch (m4ac->object_type) {
577d383b
DB
776 case AOT_ER_BSAC:
777 skip_bits(gb, 5); // numOfSubFrame
778 skip_bits(gb, 11); // layer_length
779 break;
780 case AOT_ER_AAC_LC:
781 case AOT_ER_AAC_LTP:
782 case AOT_ER_AAC_SCALABLE:
783 case AOT_ER_AAC_LD:
5cdefc02
AC
784 res_flags = get_bits(gb, 3);
785 if (res_flags) {
adea4512 786 avpriv_report_missing_feature(avctx,
f457edb6
AC
787 "AAC data resilience (flags %x)",
788 res_flags);
5cdefc02
AC
789 return AVERROR_PATCHWELCOME;
790 }
577d383b 791 break;
9cc04edf
RS
792 }
793 skip_bits1(gb); // extensionFlag3 (TBD in version 3)
794 }
5cdefc02
AC
795 switch (m4ac->object_type) {
796 case AOT_ER_AAC_LC:
797 case AOT_ER_AAC_LTP:
798 case AOT_ER_AAC_SCALABLE:
799 case AOT_ER_AAC_LD:
800 ep_config = get_bits(gb, 2);
801 if (ep_config) {
adea4512 802 avpriv_report_missing_feature(avctx,
f457edb6 803 "epConfig %d", ep_config);
5cdefc02
AC
804 return AVERROR_PATCHWELCOME;
805 }
806 }
9cc04edf
RS
807 return 0;
808}
809
b3be41ca
AC
810static int decode_eld_specific_config(AACContext *ac, AVCodecContext *avctx,
811 GetBitContext *gb,
812 MPEG4AudioConfig *m4ac,
813 int channel_config)
814{
815 int ret, ep_config, res_flags;
816 uint8_t layout_map[MAX_ELEM_ID*4][3];
817 int tags = 0;
818 const int ELDEXT_TERM = 0;
819
820 m4ac->ps = 0;
821 m4ac->sbr = 0;
822
d615187f 823 m4ac->frame_length_short = get_bits1(gb);
b3be41ca
AC
824 res_flags = get_bits(gb, 3);
825 if (res_flags) {
adea4512 826 avpriv_report_missing_feature(avctx,
b3be41ca
AC
827 "AAC data resilience (flags %x)",
828 res_flags);
829 return AVERROR_PATCHWELCOME;
830 }
831
832 if (get_bits1(gb)) { // ldSbrPresentFlag
adea4512 833 avpriv_report_missing_feature(avctx,
b3be41ca
AC
834 "Low Delay SBR");
835 return AVERROR_PATCHWELCOME;
836 }
837
838 while (get_bits(gb, 4) != ELDEXT_TERM) {
839 int len = get_bits(gb, 4);
840 if (len == 15)
841 len += get_bits(gb, 8);
842 if (len == 15 + 255)
843 len += get_bits(gb, 16);
844 if (get_bits_left(gb) < len * 8 + 4) {
09bd7ddf 845 av_log(avctx, AV_LOG_ERROR, overread_err);
b3be41ca
AC
846 return AVERROR_INVALIDDATA;
847 }
848 skip_bits_long(gb, 8 * len);
849 }
850
851 if ((ret = set_default_channel_config(avctx, layout_map,
852 &tags, channel_config)))
853 return ret;
854
855 if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
856 return ret;
857
858 ep_config = get_bits(gb, 2);
859 if (ep_config) {
adea4512 860 avpriv_report_missing_feature(avctx,
b3be41ca
AC
861 "epConfig %d", ep_config);
862 return AVERROR_PATCHWELCOME;
863 }
864 return 0;
865}
866
9cc04edf
RS
867/**
868 * Decode audio specific configuration; reference: table 1.13.
869 *
6c003e6d
JG
870 * @param ac pointer to AACContext, may be null
871 * @param avctx pointer to AVCCodecContext, used for logging
872 * @param m4ac pointer to MPEG4AudioConfig, used for parsing
fd095539
JG
873 * @param data pointer to buffer holding an audio specific config
874 * @param bit_size size of audio specific config or data in bits
875 * @param sync_extension look for an appended sync extension
9cc04edf 876 *
be63b4ba 877 * @return Returns error status or number of consumed bits. <0 - error
9cc04edf 878 */
37d28953 879static int decode_audio_specific_config(AACContext *ac,
6c003e6d
JG
880 AVCodecContext *avctx,
881 MPEG4AudioConfig *m4ac,
fd095539
JG
882 const uint8_t *data, int bit_size,
883 int sync_extension)
577d383b 884{
9cc04edf 885 GetBitContext gb;
07c52e2c 886 int i, ret;
9cc04edf 887
6a85dfc8 888 ff_dlog(avctx, "extradata size %d\n", avctx->extradata_size);
785c4418 889 for (i = 0; i < avctx->extradata_size; i++)
6a85dfc8
VG
890 ff_dlog(avctx, "%02x ", avctx->extradata[i]);
891 ff_dlog(avctx, "\n");
785c4418 892
71953ebc
LB
893 if ((ret = init_get_bits(&gb, data, bit_size)) < 0)
894 return ret;
9cc04edf 895
6d8629aa
LB
896 if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,
897 sync_extension)) < 0)
07c52e2c 898 return AVERROR_INVALIDDATA;
37d28953 899 if (m4ac->sampling_index > 12) {
6d8629aa
LB
900 av_log(avctx, AV_LOG_ERROR,
901 "invalid sampling rate index %d\n",
902 m4ac->sampling_index);
07c52e2c 903 return AVERROR_INVALIDDATA;
9cc04edf 904 }
1914e6f0
AC
905 if (m4ac->object_type == AOT_ER_AAC_LD &&
906 (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {
907 av_log(avctx, AV_LOG_ERROR,
908 "invalid low delay sampling rate index %d\n",
909 m4ac->sampling_index);
910 return AVERROR_INVALIDDATA;
911 }
9cc04edf
RS
912
913 skip_bits_long(&gb, i);
914
37d28953 915 switch (m4ac->object_type) {
7633a041 916 case AOT_AAC_MAIN:
9cc04edf 917 case AOT_AAC_LC:
ead15f1d 918 case AOT_AAC_LTP:
5cdefc02 919 case AOT_ER_AAC_LC:
1914e6f0 920 case AOT_ER_AAC_LD:
07c52e2c
LB
921 if ((ret = decode_ga_specific_config(ac, avctx, &gb,
922 m4ac, m4ac->chan_config)) < 0)
923 return ret;
9cc04edf 924 break;
b3be41ca
AC
925 case AOT_ER_AAC_ELD:
926 if ((ret = decode_eld_specific_config(ac, avctx, &gb,
927 m4ac, m4ac->chan_config)) < 0)
928 return ret;
929 break;
9cc04edf 930 default:
adea4512 931 avpriv_report_missing_feature(avctx,
f457edb6
AC
932 "Audio object type %s%d",
933 m4ac->sbr == 1 ? "SBR+" : "",
934 m4ac->object_type);
07c52e2c 935 return AVERROR(ENOSYS);
9cc04edf 936 }
37d28953 937
6a85dfc8 938 ff_dlog(avctx,
6d8629aa 939 "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",
785c4418 940 m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,
6d8629aa
LB
941 m4ac->sample_rate, m4ac->sbr,
942 m4ac->ps);
785c4418 943
be63b4ba 944 return get_bits_count(&gb);
9cc04edf
RS
945}
946
62a57fae
RS
947/**
948 * linear congruential pseudorandom number generator
949 *
950 * @param previous_val pointer to the current state of the generator
951 *
952 * @return Returns a 32-bit pseudorandom integer
953 */
577d383b
DB
954static av_always_inline int lcg_random(int previous_val)
955{
edd80ec7
MR
956 union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
957 return v.s;
62a57fae
RS
958}
959
ab2a3028 960static av_always_inline void reset_predict_state(PredictorState *ps)
577d383b
DB
961{
962 ps->r0 = 0.0f;
963 ps->r1 = 0.0f;
7633a041
AC
964 ps->cor0 = 0.0f;
965 ps->cor1 = 0.0f;
966 ps->var0 = 1.0f;
967 ps->var1 = 1.0f;
968}
969
577d383b
DB
970static void reset_all_predictors(PredictorState *ps)
971{
7633a041
AC
972 int i;
973 for (i = 0; i < MAX_PREDICTORS; i++)
974 reset_predict_state(&ps[i]);
975}
976
dafaef2f
BL
977static int sample_rate_idx (int rate)
978{
979 if (92017 <= rate) return 0;
980 else if (75132 <= rate) return 1;
981 else if (55426 <= rate) return 2;
982 else if (46009 <= rate) return 3;
983 else if (37566 <= rate) return 4;
984 else if (27713 <= rate) return 5;
985 else if (23004 <= rate) return 6;
986 else if (18783 <= rate) return 7;
987 else if (13856 <= rate) return 8;
988 else if (11502 <= rate) return 9;
989 else if (9391 <= rate) return 10;
990 else return 11;
991}
992
577d383b
DB
993static void reset_predictor_group(PredictorState *ps, int group_num)
994{
7633a041 995 int i;
577d383b 996 for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
7633a041
AC
997 reset_predict_state(&ps[i]);
998}
999
6d8629aa
LB
1000#define AAC_INIT_VLC_STATIC(num, size) \
1001 INIT_VLC_STATIC(&vlc_spectral[num], 8, ff_aac_spectral_sizes[num], \
1002 ff_aac_spectral_bits[num], sizeof(ff_aac_spectral_bits[num][0]), \
1003 sizeof(ff_aac_spectral_bits[num][0]), \
1004 ff_aac_spectral_codes[num], sizeof(ff_aac_spectral_codes[num][0]), \
1005 sizeof(ff_aac_spectral_codes[num][0]), \
8e5998f0
AC
1006 size);
1007
d6dc5d15 1008static av_cold void aac_static_table_init(void)
504e3f75
DB
1009{
1010 AAC_INIT_VLC_STATIC( 0, 304);
1011 AAC_INIT_VLC_STATIC( 1, 270);
1012 AAC_INIT_VLC_STATIC( 2, 550);
1013 AAC_INIT_VLC_STATIC( 3, 300);
1014 AAC_INIT_VLC_STATIC( 4, 328);
1015 AAC_INIT_VLC_STATIC( 5, 294);
1016 AAC_INIT_VLC_STATIC( 6, 306);
1017 AAC_INIT_VLC_STATIC( 7, 268);
1018 AAC_INIT_VLC_STATIC( 8, 510);
1019 AAC_INIT_VLC_STATIC( 9, 366);
1020 AAC_INIT_VLC_STATIC(10, 462);
1021
1022 ff_aac_sbr_init();
1023
1024 ff_aac_tableinit();
1025
1026 INIT_VLC_STATIC(&vlc_scalefactors, 7,
1027 FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
1028 ff_aac_scalefactor_bits,
1029 sizeof(ff_aac_scalefactor_bits[0]),
1030 sizeof(ff_aac_scalefactor_bits[0]),
1031 ff_aac_scalefactor_code,
1032 sizeof(ff_aac_scalefactor_code[0]),
1033 sizeof(ff_aac_scalefactor_code[0]),
1034 352);
1035
1036
1037 // window initialization
1038 ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
1039 ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
1040 ff_init_ff_sine_windows(10);
1041 ff_init_ff_sine_windows( 9);
1042 ff_init_ff_sine_windows( 7);
1043
1044 cbrt_tableinit();
1045}
1046
1047static AVOnce aac_init = AV_ONCE_INIT;
1048
dd8871a6 1049static av_cold int aac_decode_init(AVCodecContext *avctx)
577d383b 1050{
dd8871a6 1051 AACContext *ac = avctx->priv_data;
07c52e2c 1052 int ret;
71e9a1b8 1053
504e3f75
DB
1054 ret = ff_thread_once(&aac_init, &aac_static_table_init);
1055 if (ret != 0)
1056 return AVERROR_UNKNOWN;
1057
dd8871a6 1058 ac->avctx = avctx;
9fb7e146 1059 ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
71e9a1b8 1060
3d3cf674
JR
1061 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1062
dd8871a6 1063 if (avctx->extradata_size > 0) {
07c52e2c
LB
1064 if ((ret = decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
1065 avctx->extradata,
1066 avctx->extradata_size * 8,
1067 1)) < 0)
1068 return ret;
dafaef2f
BL
1069 } else {
1070 int sr, i;
37bed6ff
AC
1071 uint8_t layout_map[MAX_ELEM_ID*4][3];
1072 int layout_map_tags;
dafaef2f
BL
1073
1074 sr = sample_rate_idx(avctx->sample_rate);
9fb7e146
AC
1075 ac->oc[1].m4ac.sampling_index = sr;
1076 ac->oc[1].m4ac.channels = avctx->channels;
1077 ac->oc[1].m4ac.sbr = -1;
1078 ac->oc[1].m4ac.ps = -1;
dafaef2f
BL
1079
1080 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpeg4audio_channels); i++)
1081 if (ff_mpeg4audio_channels[i] == avctx->channels)
1082 break;
1083 if (i == FF_ARRAY_ELEMS(ff_mpeg4audio_channels)) {
1084 i = 0;
1085 }
9fb7e146 1086 ac->oc[1].m4ac.chan_config = i;
dafaef2f 1087
9fb7e146 1088 if (ac->oc[1].m4ac.chan_config) {
37bed6ff 1089 int ret = set_default_channel_config(avctx, layout_map,
9fb7e146 1090 &layout_map_tags, ac->oc[1].m4ac.chan_config);
94d47382 1091 if (!ret)
37bed6ff 1092 output_configure(ac, layout_map, layout_map_tags,
3d3cf674 1093 OC_GLOBAL_HDR, 0);
9abc9873 1094 else if (avctx->err_recognition & AV_EF_EXPLODE)
94d47382 1095 return AVERROR_INVALIDDATA;
dafaef2f 1096 }
158b3912 1097 }
cc0591da 1098
7c6eb0a1 1099 avpriv_float_dsp_init(&ac->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
71e9a1b8 1100
9cc04edf
RS
1101 ac->random_state = 0x1f2e3d4c;
1102
3d3cf674 1103 ff_mdct_init(&ac->mdct, 11, 1, 1.0 / (32768.0 * 1024.0));
1914e6f0 1104 ff_mdct_init(&ac->mdct_ld, 10, 1, 1.0 / (32768.0 * 512.0));
3d3cf674
JR
1105 ff_mdct_init(&ac->mdct_small, 8, 1, 1.0 / (32768.0 * 128.0));
1106 ff_mdct_init(&ac->mdct_ltp, 11, 0, -2.0 * 32768.0);
d615187f
AC
1107 ret = ff_imdct15_init(&ac->mdct480, 5);
1108 if (ret < 0)
1109 return ret;
1110
71e9a1b8
RS
1111 return 0;
1112}
1113
9cc04edf
RS
1114/**
1115 * Skip data_stream_element; reference: table 4.10.
1116 */
8d637124 1117static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
577d383b 1118{
71e9a1b8
RS
1119 int byte_align = get_bits1(gb);
1120 int count = get_bits(gb, 8);
1121 if (count == 255)
1122 count += get_bits(gb, 8);
1123 if (byte_align)
1124 align_get_bits(gb);
8d637124
AC
1125
1126 if (get_bits_left(gb) < 8 * count) {
dd8871a6 1127 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
07c52e2c 1128 return AVERROR_INVALIDDATA;
8d637124 1129 }
71e9a1b8 1130 skip_bits_long(gb, 8 * count);
8d637124 1131 return 0;
71e9a1b8
RS
1132}
1133
577d383b
DB
1134static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
1135 GetBitContext *gb)
1136{
7633a041
AC
1137 int sfb;
1138 if (get_bits1(gb)) {
1139 ics->predictor_reset_group = get_bits(gb, 5);
6d8629aa
LB
1140 if (ics->predictor_reset_group == 0 ||
1141 ics->predictor_reset_group > 30) {
1142 av_log(ac->avctx, AV_LOG_ERROR,
1143 "Invalid Predictor Reset Group.\n");
07c52e2c 1144 return AVERROR_INVALIDDATA;
7633a041
AC
1145 }
1146 }
9fb7e146 1147 for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index]); sfb++) {
7633a041
AC
1148 ics->prediction_used[sfb] = get_bits1(gb);
1149 }
1150 return 0;
1151}
1152
71e9a1b8 1153/**
ead15f1d
YHL
1154 * Decode Long Term Prediction data; reference: table 4.xx.
1155 */
5707af8d 1156static void decode_ltp(LongTermPrediction *ltp,
ead15f1d
YHL
1157 GetBitContext *gb, uint8_t max_sfb)
1158{
1159 int sfb;
1160
1161 ltp->lag = get_bits(gb, 11);
767848d7 1162 ltp->coef = ltp_coef[get_bits(gb, 3)];
ead15f1d
YHL
1163 for (sfb = 0; sfb < FFMIN(max_sfb, MAX_LTP_LONG_SFB); sfb++)
1164 ltp->used[sfb] = get_bits1(gb);
1165}
1166
1167/**
9cc04edf 1168 * Decode Individual Channel Stream info; reference: table 4.6.
9cc04edf 1169 */
577d383b 1170static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
021914e2 1171 GetBitContext *gb)
577d383b 1172{
82bd8a57
AC
1173 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
1174 const int aot = m4ac->object_type;
1175 const int sampling_index = m4ac->sampling_index;
b3be41ca
AC
1176 if (aot != AOT_ER_AAC_ELD) {
1177 if (get_bits1(gb)) {
1178 av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
87e85a13
VG
1179 if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
1180 return AVERROR_INVALIDDATA;
b3be41ca
AC
1181 }
1182 ics->window_sequence[1] = ics->window_sequence[0];
1183 ics->window_sequence[0] = get_bits(gb, 2);
1184 if (aot == AOT_ER_AAC_LD &&
1185 ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
1186 av_log(ac->avctx, AV_LOG_ERROR,
1187 "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
1188 "window sequence %d found.\n", ics->window_sequence[0]);
1189 ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
1190 return AVERROR_INVALIDDATA;
1191 }
1192 ics->use_kb_window[1] = ics->use_kb_window[0];
1193 ics->use_kb_window[0] = get_bits1(gb);
1914e6f0 1194 }
577d383b
DB
1195 ics->num_window_groups = 1;
1196 ics->group_len[0] = 1;
9ffd5c1c
RS
1197 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
1198 int i;
1199 ics->max_sfb = get_bits(gb, 4);
1200 for (i = 0; i < 7; i++) {
1201 if (get_bits1(gb)) {
577d383b 1202 ics->group_len[ics->num_window_groups - 1]++;
9ffd5c1c
RS
1203 } else {
1204 ics->num_window_groups++;
577d383b 1205 ics->group_len[ics->num_window_groups - 1] = 1;
9ffd5c1c
RS
1206 }
1207 }
577d383b 1208 ics->num_windows = 8;
82bd8a57
AC
1209 ics->swb_offset = ff_swb_offset_128[sampling_index];
1210 ics->num_swb = ff_aac_num_swb_128[sampling_index];
1211 ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
7633a041 1212 ics->predictor_present = 0;
9ffd5c1c 1213 } else {
82bd8a57
AC
1214 ics->max_sfb = get_bits(gb, 6);
1215 ics->num_windows = 1;
b3be41ca 1216 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
d615187f
AC
1217 if (m4ac->frame_length_short) {
1218 ics->swb_offset = ff_swb_offset_480[sampling_index];
1219 ics->num_swb = ff_aac_num_swb_480[sampling_index];
1220 ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
1221 } else {
1222 ics->swb_offset = ff_swb_offset_512[sampling_index];
1223 ics->num_swb = ff_aac_num_swb_512[sampling_index];
1224 ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
1225 }
1914e6f0
AC
1226 if (!ics->num_swb || !ics->swb_offset)
1227 return AVERROR_BUG;
1228 } else {
82bd8a57
AC
1229 ics->swb_offset = ff_swb_offset_1024[sampling_index];
1230 ics->num_swb = ff_aac_num_swb_1024[sampling_index];
1231 ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
1914e6f0 1232 }
b3be41ca
AC
1233 if (aot != AOT_ER_AAC_ELD) {
1234 ics->predictor_present = get_bits1(gb);
1235 ics->predictor_reset_group = 0;
1236 }
7633a041 1237 if (ics->predictor_present) {
b3be41ca 1238 if (aot == AOT_AAC_MAIN) {
7633a041 1239 if (decode_prediction(ac, ics, gb)) {
021914e2 1240 return AVERROR_INVALIDDATA;
7633a041 1241 }
b3be41ca
AC
1242 } else if (aot == AOT_AAC_LC ||
1243 aot == AOT_ER_AAC_LC) {
6d8629aa
LB
1244 av_log(ac->avctx, AV_LOG_ERROR,
1245 "Prediction is not allowed in AAC-LC.\n");
021914e2 1246 return AVERROR_INVALIDDATA;
7633a041 1247 } else {
b3be41ca 1248 if (aot == AOT_ER_AAC_LD) {
67deba8a 1249 avpriv_report_missing_feature(ac->avctx, "LTP in ER AAC LD");
1914e6f0
AC
1250 return AVERROR_PATCHWELCOME;
1251 }
ead15f1d 1252 if ((ics->ltp.present = get_bits(gb, 1)))
5707af8d 1253 decode_ltp(&ics->ltp, gb, ics->max_sfb);
7633a041 1254 }
62a57fae
RS
1255 }
1256 }
1257
577d383b 1258 if (ics->max_sfb > ics->num_swb) {
dd8871a6 1259 av_log(ac->avctx, AV_LOG_ERROR,
6d8629aa
LB
1260 "Number of scalefactor bands in group (%d) "
1261 "exceeds limit (%d).\n",
577d383b 1262 ics->max_sfb, ics->num_swb);
021914e2 1263 return AVERROR_INVALIDDATA;
62a57fae
RS
1264 }
1265
9cc04edf
RS
1266 return 0;
1267}
1268
1269/**
9cc04edf
RS
1270 * Decode band types (section_data payload); reference: table 4.46.
1271 *
1272 * @param band_type array of the used band type
1273 * @param band_type_run_end array of the last scalefactor band of a band type run
1274 *
1275 * @return Returns error status. 0 - OK, !0 - error
1276 */
577d383b
DB
1277static int decode_band_types(AACContext *ac, enum BandType band_type[120],
1278 int band_type_run_end[120], GetBitContext *gb,
1279 IndividualChannelStream *ics)
1280{
cc0591da
RS
1281 int g, idx = 0;
1282 const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
1283 for (g = 0; g < ics->num_window_groups; g++) {
1284 int k = 0;
1285 while (k < ics->max_sfb) {
01d19fbc 1286 uint8_t sect_end = k;
cc0591da
RS
1287 int sect_len_incr;
1288 int sect_band_type = get_bits(gb, 4);
1289 if (sect_band_type == 12) {
dd8871a6 1290 av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
07c52e2c 1291 return AVERROR_INVALIDDATA;
cc0591da 1292 }
1cd9a615
AC
1293 do {
1294 sect_len_incr = get_bits(gb, bits);
01d19fbc 1295 sect_end += sect_len_incr;
1cd9a615
AC
1296 if (get_bits_left(gb) < 0) {
1297 av_log(ac->avctx, AV_LOG_ERROR, overread_err);
07c52e2c 1298 return AVERROR_INVALIDDATA;
1cd9a615
AC
1299 }
1300 if (sect_end > ics->max_sfb) {
1301 av_log(ac->avctx, AV_LOG_ERROR,
1302 "Number of bands (%d) exceeds limit (%d).\n",
1303 sect_end, ics->max_sfb);
07c52e2c 1304 return AVERROR_INVALIDDATA;
1cd9a615
AC
1305 }
1306 } while (sect_len_incr == (1 << bits) - 1);
01d19fbc 1307 for (; k < sect_end; k++) {
9ffd5c1c 1308 band_type [idx] = sect_band_type;
01d19fbc 1309 band_type_run_end[idx++] = sect_end;
9ffd5c1c 1310 }
9cc04edf
RS
1311 }
1312 }
1313 return 0;
1314}
cc0591da 1315
9cc04edf
RS
1316/**
1317 * Decode scalefactors; reference: table 4.47.
cc0591da 1318 *
cc0591da
RS
1319 * @param global_gain first scalefactor value as scalefactors are differentially coded
1320 * @param band_type array of the used band type
1321 * @param band_type_run_end array of the last scalefactor band of a band type run
1322 * @param sf array of scalefactors or intensity stereo positions
1323 *
1324 * @return Returns error status. 0 - OK, !0 - error
1325 */
577d383b
DB
1326static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
1327 unsigned int global_gain,
1328 IndividualChannelStream *ics,
1329 enum BandType band_type[120],
1330 int band_type_run_end[120])
1331{
cc0591da 1332 int g, i, idx = 0;
e4744b59
AC
1333 int offset[3] = { global_gain, global_gain - 90, 0 };
1334 int clipped_offset;
cc0591da 1335 int noise_flag = 1;
cc0591da
RS
1336 for (g = 0; g < ics->num_window_groups; g++) {
1337 for (i = 0; i < ics->max_sfb;) {
1338 int run_end = band_type_run_end[idx];
1339 if (band_type[idx] == ZERO_BT) {
577d383b 1340 for (; i < run_end; i++, idx++)
4a2ef394 1341 sf[idx] = 0.0;
6d8629aa
LB
1342 } else if ((band_type[idx] == INTENSITY_BT) ||
1343 (band_type[idx] == INTENSITY_BT2)) {
577d383b 1344 for (; i < run_end; i++, idx++) {
cc0591da 1345 offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
e4744b59
AC
1346 clipped_offset = av_clip(offset[2], -155, 100);
1347 if (offset[2] != clipped_offset) {
6d97484d
DB
1348 avpriv_request_sample(ac->avctx,
1349 "If you heard an audible artifact, there may be a bug in the decoder. "
1350 "Clipped intensity stereo position (%d -> %d)",
1351 offset[2], clipped_offset);
cc0591da 1352 }
d70fa4c4 1353 sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
cc0591da 1354 }
577d383b
DB
1355 } else if (band_type[idx] == NOISE_BT) {
1356 for (; i < run_end; i++, idx++) {
1357 if (noise_flag-- > 0)
cc0591da
RS
1358 offset[1] += get_bits(gb, 9) - 256;
1359 else
1360 offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
e4744b59 1361 clipped_offset = av_clip(offset[1], -100, 155);
cef7d701 1362 if (offset[1] != clipped_offset) {
6d97484d
DB
1363 avpriv_request_sample(ac->avctx,
1364 "If you heard an audible artifact, there may be a bug in the decoder. "
1365 "Clipped noise gain (%d -> %d)",
1366 offset[1], clipped_offset);
cc0591da 1367 }
767848d7 1368 sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
cc0591da 1369 }
577d383b
DB
1370 } else {
1371 for (; i < run_end; i++, idx++) {
cc0591da 1372 offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 1373 if (offset[0] > 255U) {
dd8871a6 1374 av_log(ac->avctx, AV_LOG_ERROR,
5e239c7f 1375 "Scalefactor (%d) out of range.\n", offset[0]);
07c52e2c 1376 return AVERROR_INVALIDDATA;
cc0591da 1377 }
767848d7 1378 sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
cc0591da
RS
1379 }
1380 }
1381 }
1382 }
1383 return 0;
1384}
1385
1386/**
1387 * Decode pulse data; reference: table 4.7.
1388 */
577d383b
DB
1389static int decode_pulses(Pulse *pulse, GetBitContext *gb,
1390 const uint16_t *swb_offset, int num_swb)
1391{
aac0eda4 1392 int i, pulse_swb;
cc0591da 1393 pulse->num_pulse = get_bits(gb, 2) + 1;
aac0eda4
AC
1394 pulse_swb = get_bits(gb, 6);
1395 if (pulse_swb >= num_swb)
1396 return -1;
1397 pulse->pos[0] = swb_offset[pulse_swb];
408992ba 1398 pulse->pos[0] += get_bits(gb, 5);
aac0eda4
AC
1399 if (pulse->pos[0] > 1023)
1400 return -1;
848a5815
RS
1401 pulse->amp[0] = get_bits(gb, 4);
1402 for (i = 1; i < pulse->num_pulse; i++) {
577d383b 1403 pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
aac0eda4
AC
1404 if (pulse->pos[i] > 1023)
1405 return -1;
848a5815 1406 pulse->amp[i] = get_bits(gb, 4);
cc0591da 1407 }
aac0eda4 1408 return 0;
cc0591da
RS
1409}
1410
1411/**
1dece0d2
RS
1412 * Decode Temporal Noise Shaping data; reference: table 4.48.
1413 *
1414 * @return Returns error status. 0 - OK, !0 - error
1415 */
577d383b
DB
1416static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
1417 GetBitContext *gb, const IndividualChannelStream *ics)
1418{
1dece0d2
RS
1419 int w, filt, i, coef_len, coef_res, coef_compress;
1420 const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
9fb7e146 1421 const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
1dece0d2 1422 for (w = 0; w < ics->num_windows; w++) {
fbd91d7c 1423 if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
1dece0d2
RS
1424 coef_res = get_bits1(gb);
1425
65b20b24
RS
1426 for (filt = 0; filt < tns->n_filt[w]; filt++) {
1427 int tmp2_idx;
577d383b 1428 tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
65b20b24 1429
577d383b 1430 if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
6d8629aa
LB
1431 av_log(ac->avctx, AV_LOG_ERROR,
1432 "TNS filter order %d is greater than maximum %d.\n",
65b20b24
RS
1433 tns->order[w][filt], tns_max_order);
1434 tns->order[w][filt] = 0;
07c52e2c 1435 return AVERROR_INVALIDDATA;
65b20b24 1436 }
51673647 1437 if (tns->order[w][filt]) {
35445d29
RS
1438 tns->direction[w][filt] = get_bits1(gb);
1439 coef_compress = get_bits1(gb);
1440 coef_len = coef_res + 3 - coef_compress;
577d383b 1441 tmp2_idx = 2 * coef_compress + coef_res;
1dece0d2 1442
35445d29
RS
1443 for (i = 0; i < tns->order[w][filt]; i++)
1444 tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
51673647 1445 }
65b20b24 1446 }
fbd91d7c 1447 }
1dece0d2
RS
1448 }
1449 return 0;
1450}
1451
1452/**
9cc04edf
RS
1453 * Decode Mid/Side data; reference: table 4.54.
1454 *
1455 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1456 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1457 * [3] reserved for scalable AAC
1458 */
577d383b
DB
1459static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
1460 int ms_present)
1461{
62a57fae 1462 int idx;
7464e98f 1463 int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
62a57fae 1464 if (ms_present == 1) {
7464e98f 1465 for (idx = 0; idx < max_idx; idx++)
62a57fae
RS
1466 cpe->ms_mask[idx] = get_bits1(gb);
1467 } else if (ms_present == 2) {
7464e98f 1468 memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
62a57fae
RS
1469 }
1470}
9cc04edf 1471
798339fb 1472#ifndef VMUL2
c816d3d0
MR
1473static inline float *VMUL2(float *dst, const float *v, unsigned idx,
1474 const float *scale)
1475{
1476 float s = *scale;
1477 *dst++ = v[idx & 15] * s;
1478 *dst++ = v[idx>>4 & 15] * s;
1479 return dst;
1480}
798339fb 1481#endif
c816d3d0 1482
798339fb 1483#ifndef VMUL4
c816d3d0
MR
1484static inline float *VMUL4(float *dst, const float *v, unsigned idx,
1485 const float *scale)
1486{
1487 float s = *scale;
1488 *dst++ = v[idx & 3] * s;
1489 *dst++ = v[idx>>2 & 3] * s;
1490 *dst++ = v[idx>>4 & 3] * s;
1491 *dst++ = v[idx>>6 & 3] * s;
1492 return dst;
1493}
798339fb 1494#endif
c816d3d0 1495
798339fb 1496#ifndef VMUL2S
c816d3d0
MR
1497static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
1498 unsigned sign, const float *scale)
1499{
5cd56e19 1500 union av_intfloat32 s0, s1;
c816d3d0
MR
1501
1502 s0.f = s1.f = *scale;
1503 s0.i ^= sign >> 1 << 31;
1504 s1.i ^= sign << 31;
1505
1506 *dst++ = v[idx & 15] * s0.f;
1507 *dst++ = v[idx>>4 & 15] * s1.f;
1508
1509 return dst;
1510}
798339fb 1511#endif
c816d3d0 1512
798339fb 1513#ifndef VMUL4S
c816d3d0
MR
1514static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
1515 unsigned sign, const float *scale)
1516{
1517 unsigned nz = idx >> 12;
5cd56e19
AC
1518 union av_intfloat32 s = { .f = *scale };
1519 union av_intfloat32 t;
c816d3d0 1520
187a5379 1521 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1522 *dst++ = v[idx & 3] * t.f;
1523
1524 sign <<= nz & 1; nz >>= 1;
187a5379 1525 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1526 *dst++ = v[idx>>2 & 3] * t.f;
1527
1528 sign <<= nz & 1; nz >>= 1;
187a5379 1529 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1530 *dst++ = v[idx>>4 & 3] * t.f;
1531
3c928477 1532 sign <<= nz & 1;
187a5379 1533 t.i = s.i ^ (sign & 1U<<31);
c816d3d0
MR
1534 *dst++ = v[idx>>6 & 3] * t.f;
1535
1536 return dst;
1537}
798339fb 1538#endif
c816d3d0 1539
9cc04edf 1540/**
9ffd5c1c
RS
1541 * Decode spectral data; reference: table 4.50.
1542 * Dequantize and scale spectral data; reference: 4.6.3.3.
1543 *
1544 * @param coef array of dequantized, scaled spectral data
1545 * @param sf array of scalefactors or intensity stereo positions
1546 * @param pulse_present set if pulses are present
1547 * @param pulse pointer to pulse data struct
1548 * @param band_type array of the used band type
1549 *
1550 * @return Returns error status. 0 - OK, !0 - error
1551 */
577d383b 1552static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
3963a17d 1553 GetBitContext *gb, const float sf[120],
577d383b
DB
1554 int pulse_present, const Pulse *pulse,
1555 const IndividualChannelStream *ics,
1556 enum BandType band_type[120])
1557{
9ffd5c1c 1558 int i, k, g, idx = 0;
577d383b
DB
1559 const int c = 1024 / ics->num_windows;
1560 const uint16_t *offsets = ics->swb_offset;
9ffd5c1c
RS
1561 float *coef_base = coef;
1562
1563 for (g = 0; g < ics->num_windows; g++)
6d8629aa
LB
1564 memset(coef + g * 128 + offsets[ics->max_sfb], 0,
1565 sizeof(float) * (c - offsets[ics->max_sfb]));
9ffd5c1c
RS
1566
1567 for (g = 0; g < ics->num_window_groups; g++) {
05f9d8fc
MR
1568 unsigned g_len = ics->group_len[g];
1569
9ffd5c1c 1570 for (i = 0; i < ics->max_sfb; i++, idx++) {
05f9d8fc
MR
1571 const unsigned cbt_m1 = band_type[idx] - 1;
1572 float *cfo = coef + offsets[i];
1573 int off_len = offsets[i + 1] - offsets[i];
9ffd5c1c 1574 int group;
05f9d8fc
MR
1575
1576 if (cbt_m1 >= INTENSITY_BT2 - 1) {
1577 for (group = 0; group < g_len; group++, cfo+=128) {
1578 memset(cfo, 0, off_len * sizeof(float));
9ffd5c1c 1579 }
05f9d8fc
MR
1580 } else if (cbt_m1 == NOISE_BT - 1) {
1581 for (group = 0; group < g_len; group++, cfo+=128) {
d0ee5021 1582 float scale;
b418a6ca 1583 float band_energy;
42d3fbb3 1584
05f9d8fc 1585 for (k = 0; k < off_len; k++) {
9ffd5c1c 1586 ac->random_state = lcg_random(ac->random_state);
05f9d8fc 1587 cfo[k] = ac->random_state;
d0ee5021 1588 }
42d3fbb3 1589
d56668bd 1590 band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
d0ee5021 1591 scale = sf[idx] / sqrtf(band_energy);
284ea790 1592 ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
9ffd5c1c 1593 }
577d383b 1594 } else {
05f9d8fc
MR
1595 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
1596 const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
1597 VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
d356a53f 1598 OPEN_READER(re, gb);
c816d3d0 1599
95dff4ac
MR
1600 switch (cbt_m1 >> 1) {
1601 case 0:
1602 for (group = 0; group < g_len; group++, cfo+=128) {
1603 float *cf = cfo;
1604 int len = off_len;
42d3fbb3 1605
c816d3d0 1606 do {
d356a53f 1607 int code;
c816d3d0
MR
1608 unsigned cb_idx;
1609
d356a53f
MR
1610 UPDATE_CACHE(re, gb);
1611 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1612 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1613 cf = VMUL4(cf, vq, cb_idx, sf + idx);
1614 } while (len -= 4);
95dff4ac
MR
1615 }
1616 break;
1617
1618 case 1:
1619 for (group = 0; group < g_len; group++, cfo+=128) {
1620 float *cf = cfo;
1621 int len = off_len;
1622
c816d3d0 1623 do {
d356a53f 1624 int code;
c816d3d0
MR
1625 unsigned nnz;
1626 unsigned cb_idx;
1627 uint32_t bits;
1628
d356a53f
MR
1629 UPDATE_CACHE(re, gb);
1630 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1631 cb_idx = cb_vector_idx[code];
c816d3d0 1632 nnz = cb_idx >> 8 & 15;
d1229430 1633 bits = nnz ? GET_CACHE(re, gb) : 0;
d356a53f 1634 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1635 cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
1636 } while (len -= 4);
95dff4ac
MR
1637 }
1638 break;
1639
1640 case 2:
1641 for (group = 0; group < g_len; group++, cfo+=128) {
1642 float *cf = cfo;
1643 int len = off_len;
1644
c816d3d0 1645 do {
d356a53f 1646 int code;
c816d3d0
MR
1647 unsigned cb_idx;
1648
d356a53f
MR
1649 UPDATE_CACHE(re, gb);
1650 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1651 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1652 cf = VMUL2(cf, vq, cb_idx, sf + idx);
1653 } while (len -= 2);
95dff4ac
MR
1654 }
1655 break;
1656
1657 case 3:
1658 case 4:
1659 for (group = 0; group < g_len; group++, cfo+=128) {
1660 float *cf = cfo;
1661 int len = off_len;
1662
c816d3d0 1663 do {
d356a53f 1664 int code;
c816d3d0
MR
1665 unsigned nnz;
1666 unsigned cb_idx;
1667 unsigned sign;
1668
d356a53f
MR
1669 UPDATE_CACHE(re, gb);
1670 GET_VLC(code, re, gb, vlc_tab, 8, 2);
d356a53f 1671 cb_idx = cb_vector_idx[code];
c816d3d0 1672 nnz = cb_idx >> 8 & 15;
d1229430 1673 sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
d356a53f 1674 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1675 cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
1676 } while (len -= 2);
95dff4ac
MR
1677 }
1678 break;
1679
1680 default:
1681 for (group = 0; group < g_len; group++, cfo+=128) {
1682 float *cf = cfo;
1683 uint32_t *icf = (uint32_t *) cf;
1684 int len = off_len;
1685
05f9d8fc 1686 do {
d356a53f 1687 int code;
c816d3d0
MR
1688 unsigned nzt, nnz;
1689 unsigned cb_idx;
1690 uint32_t bits;
1691 int j;
1692
d356a53f
MR
1693 UPDATE_CACHE(re, gb);
1694 GET_VLC(code, re, gb, vlc_tab, 8, 2);
1695
1696 if (!code) {
05f9d8fc
MR
1697 *icf++ = 0;
1698 *icf++ = 0;
c816d3d0
MR
1699 continue;
1700 }
1701
d356a53f 1702 cb_idx = cb_vector_idx[code];
c816d3d0
MR
1703 nnz = cb_idx >> 12;
1704 nzt = cb_idx >> 8;
d356a53f
MR
1705 bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
1706 LAST_SKIP_BITS(re, gb, nnz);
c816d3d0
MR
1707
1708 for (j = 0; j < 2; j++) {
1709 if (nzt & 1<<j) {
d356a53f
MR
1710 uint32_t b;
1711 int n;
c816d3d0
MR
1712 /* The total length of escape_sequence must be < 22 bits according
1713 to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
d356a53f
MR
1714 UPDATE_CACHE(re, gb);
1715 b = GET_CACHE(re, gb);
1716 b = 31 - av_log2(~b);
1717
1718 if (b > 8) {
dd8871a6 1719 av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
07c52e2c 1720 return AVERROR_INVALIDDATA;
c816d3d0 1721 }
d356a53f 1722
d356a53f 1723 SKIP_BITS(re, gb, b + 1);
d356a53f
MR
1724 b += 4;
1725 n = (1 << b) + SHOW_UBITS(re, gb, b);
1726 LAST_SKIP_BITS(re, gb, b);
187a5379 1727 *icf++ = cbrt_tab[n] | (bits & 1U<<31);
c816d3d0
MR
1728 bits <<= 1;
1729 } else {
1730 unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
187a5379 1731 *icf++ = (bits & 1U<<31) | v;
c816d3d0 1732 bits <<= !!v;
e8d5c07b 1733 }
c816d3d0 1734 cb_idx >>= 4;
9ffd5c1c 1735 }
05f9d8fc 1736 } while (len -= 2);
42d3fbb3 1737
284ea790 1738 ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
42d3fbb3 1739 }
9ffd5c1c 1740 }
d356a53f
MR
1741
1742 CLOSE_READER(re, gb);
9ffd5c1c
RS
1743 }
1744 }
05f9d8fc 1745 coef += g_len << 7;
9ffd5c1c
RS
1746 }
1747
1748 if (pulse_present) {
51436848 1749 idx = 0;
577d383b
DB
1750 for (i = 0; i < pulse->num_pulse; i++) {
1751 float co = coef_base[ pulse->pos[i] ];
1752 while (offsets[idx + 1] <= pulse->pos[i])
51436848
AC
1753 idx++;
1754 if (band_type[idx] != NOISE_BT && sf[idx]) {
70735a3f
RS
1755 float ico = -pulse->amp[i];
1756 if (co) {
1757 co /= sf[idx];
1758 ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
1759 }
1760 coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
51436848 1761 }
9ffd5c1c
RS
1762 }
1763 }
1764 return 0;
1765}
1766
577d383b
DB
1767static av_always_inline float flt16_round(float pf)
1768{
5cd56e19 1769 union av_intfloat32 tmp;
4a39ccb4
AC
1770 tmp.f = pf;
1771 tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
1772 return tmp.f;
7633a041
AC
1773}
1774
577d383b
DB
1775static av_always_inline float flt16_even(float pf)
1776{
5cd56e19 1777 union av_intfloat32 tmp;
4a39ccb4 1778 tmp.f = pf;
577d383b 1779 tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
4a39ccb4 1780 return tmp.f;
7633a041
AC
1781}
1782
577d383b
DB
1783static av_always_inline float flt16_trunc(float pf)
1784{
5cd56e19 1785 union av_intfloat32 pun;
4a39ccb4
AC
1786 pun.f = pf;
1787 pun.i &= 0xFFFF0000U;
1788 return pun.f;
7633a041
AC
1789}
1790
70c99adb 1791static av_always_inline void predict(PredictorState *ps, float *coef,
9978ed7d 1792 int output_enable)
577d383b
DB
1793{
1794 const float a = 0.953125; // 61.0 / 64
1795 const float alpha = 0.90625; // 29.0 / 32
7633a041
AC
1796 float e0, e1;
1797 float pv;
1798 float k1, k2;
81824fe0
AC
1799 float r0 = ps->r0, r1 = ps->r1;
1800 float cor0 = ps->cor0, cor1 = ps->cor1;
1801 float var0 = ps->var0, var1 = ps->var1;
7633a041 1802
81824fe0
AC
1803 k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
1804 k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
7633a041 1805
81824fe0 1806 pv = flt16_round(k1 * r0 + k2 * r1);
7633a041 1807 if (output_enable)
767848d7 1808 *coef += pv;
7633a041 1809
767848d7 1810 e0 = *coef;
81824fe0 1811 e1 = e0 - k1 * r0;
7633a041 1812
81824fe0
AC
1813 ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
1814 ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
1815 ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
1816 ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
7633a041 1817
81824fe0 1818 ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
7633a041
AC
1819 ps->r0 = flt16_trunc(a * e0);
1820}
1821
1822/**
1823 * Apply AAC-Main style frequency domain prediction.
1824 */
577d383b
DB
1825static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
1826{
7633a041
AC
1827 int sfb, k;
1828
1829 if (!sce->ics.predictor_initialized) {
aab54133 1830 reset_all_predictors(sce->predictor_state);
7633a041
AC
1831 sce->ics.predictor_initialized = 1;
1832 }
1833
1834 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
6d8629aa
LB
1835 for (sfb = 0;
1836 sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
1837 sfb++) {
1838 for (k = sce->ics.swb_offset[sfb];
1839 k < sce->ics.swb_offset[sfb + 1];
1840 k++) {
70c99adb 1841 predict(&sce->predictor_state[k], &sce->coeffs[k],
6d8629aa
LB
1842 sce->ics.predictor_present &&
1843 sce->ics.prediction_used[sfb]);
7633a041
AC
1844 }
1845 }
1846 if (sce->ics.predictor_reset_group)
6d8629aa
LB
1847 reset_predictor_group(sce->predictor_state,
1848 sce->ics.predictor_reset_group);
7633a041 1849 } else
aab54133 1850 reset_all_predictors(sce->predictor_state);
7633a041
AC
1851}
1852
9ffd5c1c 1853/**
9cc04edf
RS
1854 * Decode an individual_channel_stream payload; reference: table 4.44.
1855 *
1856 * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
1857 * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
1858 *
1859 * @return Returns error status. 0 - OK, !0 - error
1860 */
577d383b
DB
1861static int decode_ics(AACContext *ac, SingleChannelElement *sce,
1862 GetBitContext *gb, int common_window, int scale_flag)
1863{
9cc04edf 1864 Pulse pulse;
577d383b
DB
1865 TemporalNoiseShaping *tns = &sce->tns;
1866 IndividualChannelStream *ics = &sce->ics;
1867 float *out = sce->coeffs;
b3be41ca 1868 int global_gain, eld_syntax, er_syntax, pulse_present = 0;
07c52e2c 1869 int ret;
9cc04edf 1870
b3be41ca
AC
1871 eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1872 er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
1873 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
1874 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
1875 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
1876
848a5815
RS
1877 /* This assignment is to silence a GCC warning about the variable being used
1878 * uninitialized when in fact it always is.
9cc04edf
RS
1879 */
1880 pulse.num_pulse = 0;
9cc04edf
RS
1881
1882 global_gain = get_bits(gb, 8);
1883
1884 if (!common_window && !scale_flag) {
021914e2
AC
1885 if (decode_ics_info(ac, ics, gb) < 0)
1886 return AVERROR_INVALIDDATA;
9cc04edf
RS
1887 }
1888
07c52e2c
LB
1889 if ((ret = decode_band_types(ac, sce->band_type,
1890 sce->band_type_run_end, gb, ics)) < 0)
1891 return ret;
1892 if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
1893 sce->band_type, sce->band_type_run_end)) < 0)
1894 return ret;
9cc04edf
RS
1895
1896 pulse_present = 0;
1897 if (!scale_flag) {
b3be41ca 1898 if (!eld_syntax && (pulse_present = get_bits1(gb))) {
9cc04edf 1899 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
6d8629aa
LB
1900 av_log(ac->avctx, AV_LOG_ERROR,
1901 "Pulse tool not allowed in eight short sequence.\n");
07c52e2c 1902 return AVERROR_INVALIDDATA;
9cc04edf 1903 }
aac0eda4 1904 if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
6d8629aa
LB
1905 av_log(ac->avctx, AV_LOG_ERROR,
1906 "Pulse data corrupt or invalid.\n");
07c52e2c 1907 return AVERROR_INVALIDDATA;
aac0eda4 1908 }
9cc04edf 1909 }
5cdefc02
AC
1910 tns->present = get_bits1(gb);
1911 if (tns->present && !er_syntax)
1912 if (decode_tns(ac, tns, gb, ics) < 0)
1913 return AVERROR_INVALIDDATA;
b3be41ca 1914 if (!eld_syntax && get_bits1(gb)) {
12e25ed2 1915 avpriv_request_sample(ac->avctx, "SSR");
717addec 1916 return AVERROR_PATCHWELCOME;
9cc04edf 1917 }
41ed7ab4
VG
1918 // I see no textual basis in the spec for this occurring after SSR gain
1919 // control, but this is what both reference and real implementations do
5cdefc02
AC
1920 if (tns->present && er_syntax)
1921 if (decode_tns(ac, tns, gb, ics) < 0)
1922 return AVERROR_INVALIDDATA;
9cc04edf
RS
1923 }
1924
6d8629aa
LB
1925 if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
1926 &pulse, ics, sce->band_type) < 0)
07c52e2c 1927 return AVERROR_INVALIDDATA;
7633a041 1928
9fb7e146 1929 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
7633a041
AC
1930 apply_prediction(ac, sce);
1931
9cc04edf
RS
1932 return 0;
1933}
1934
1935/**
9ffd5c1c
RS
1936 * Mid/Side stereo decoding; reference: 4.6.8.1.3.
1937 */
42d3fbb3 1938static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
577d383b
DB
1939{
1940 const IndividualChannelStream *ics = &cpe->ch[0].ics;
9ffd5c1c
RS
1941 float *ch0 = cpe->ch[0].coeffs;
1942 float *ch1 = cpe->ch[1].coeffs;
42d3fbb3 1943 int g, i, group, idx = 0;
577d383b 1944 const uint16_t *offsets = ics->swb_offset;
9ffd5c1c
RS
1945 for (g = 0; g < ics->num_window_groups; g++) {
1946 for (i = 0; i < ics->max_sfb; i++, idx++) {
1947 if (cpe->ms_mask[idx] &&
6d8629aa
LB
1948 cpe->ch[0].band_type[idx] < NOISE_BT &&
1949 cpe->ch[1].band_type[idx] < NOISE_BT) {
9ffd5c1c 1950 for (group = 0; group < ics->group_len[g]; group++) {
5959bfac
RB
1951 ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
1952 ch1 + group * 128 + offsets[i],
1953 offsets[i+1] - offsets[i]);
9ffd5c1c
RS
1954 }
1955 }
1956 }
577d383b
DB
1957 ch0 += ics->group_len[g] * 128;
1958 ch1 += ics->group_len[g] * 128;
9ffd5c1c
RS
1959 }
1960}
1961
1962/**
1963 * intensity stereo decoding; reference: 4.6.8.2.3
1964 *
1965 * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
1966 * [1] mask is decoded from bitstream; [2] mask is all 1s;
1967 * [3] reserved for scalable AAC
1968 */
6d8629aa
LB
1969static void apply_intensity_stereo(AACContext *ac,
1970 ChannelElement *cpe, int ms_present)
577d383b
DB
1971{
1972 const IndividualChannelStream *ics = &cpe->ch[1].ics;
1973 SingleChannelElement *sce1 = &cpe->ch[1];
9ffd5c1c 1974 float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
577d383b 1975 const uint16_t *offsets = ics->swb_offset;
9707f84f 1976 int g, group, i, idx = 0;
9ffd5c1c
RS
1977 int c;
1978 float scale;
1979 for (g = 0; g < ics->num_window_groups; g++) {
1980 for (i = 0; i < ics->max_sfb;) {
6d8629aa
LB
1981 if (sce1->band_type[idx] == INTENSITY_BT ||
1982 sce1->band_type[idx] == INTENSITY_BT2) {
9ffd5c1c
RS
1983 const int bt_run_end = sce1->band_type_run_end[idx];
1984 for (; i < bt_run_end; i++, idx++) {
1985 c = -1 + 2 * (sce1->band_type[idx] - 14);
1986 if (ms_present)
1987 c *= 1 - 2 * cpe->ms_mask[idx];
1988 scale = c * sce1->sf[idx];
1989 for (group = 0; group < ics->group_len[g]; group++)
284ea790
JR
1990 ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
1991 coef0 + group * 128 + offsets[i],
1992 scale,
1993 offsets[i + 1] - offsets[i]);
9ffd5c1c
RS
1994 }
1995 } else {
1996 int bt_run_end = sce1->band_type_run_end[idx];
1997 idx += bt_run_end - i;
1998 i = bt_run_end;
1999 }
2000 }
577d383b
DB
2001 coef0 += ics->group_len[g] * 128;
2002 coef1 += ics->group_len[g] * 128;
9ffd5c1c
RS
2003 }
2004}
2005
2006/**
9cc04edf
RS
2007 * Decode a channel_pair_element; reference: table 4.4.
2008 *
9cc04edf
RS
2009 * @return Returns error status. 0 - OK, !0 - error
2010 */
577d383b
DB
2011static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
2012{
9cc04edf 2013 int i, ret, common_window, ms_present = 0;
b3be41ca 2014 int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
9cc04edf 2015
b3be41ca 2016 common_window = eld_syntax || get_bits1(gb);
9cc04edf 2017 if (common_window) {
021914e2
AC
2018 if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
2019 return AVERROR_INVALIDDATA;
9cc04edf
RS
2020 i = cpe->ch[1].ics.use_kb_window[0];
2021 cpe->ch[1].ics = cpe->ch[0].ics;
2022 cpe->ch[1].ics.use_kb_window[1] = i;
6d8629aa
LB
2023 if (cpe->ch[1].ics.predictor_present &&
2024 (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
ead15f1d 2025 if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
5707af8d 2026 decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
9cc04edf 2027 ms_present = get_bits(gb, 2);
577d383b 2028 if (ms_present == 3) {
dd8871a6 2029 av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
07c52e2c 2030 return AVERROR_INVALIDDATA;
577d383b 2031 } else if (ms_present)
9cc04edf
RS
2032 decode_mid_side_stereo(cpe, gb, ms_present);
2033 }
2034 if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
2035 return ret;
2036 if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
2037 return ret;
2038
aab54133
AC
2039 if (common_window) {
2040 if (ms_present)
42d3fbb3 2041 apply_mid_side_stereo(ac, cpe);
9fb7e146 2042 if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
aab54133
AC
2043 apply_prediction(ac, &cpe->ch[0]);
2044 apply_prediction(ac, &cpe->ch[1]);
2045 }
2046 }
9cc04edf 2047
9707f84f 2048 apply_intensity_stereo(ac, cpe, ms_present);
9cc04edf
RS
2049 return 0;
2050}
2051
93c6ff6c
AC
2052static const float cce_scale[] = {
2053 1.09050773266525765921, //2^(1/8)
2054 1.18920711500272106672, //2^(1/4)
2055 M_SQRT2,
2056 2,
2057};
2058
9ffd5c1c
RS
2059/**
2060 * Decode coupling_channel_element; reference: table 4.8.
2061 *
9ffd5c1c
RS
2062 * @return Returns error status. 0 - OK, !0 - error
2063 */
577d383b
DB
2064static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
2065{
9ffd5c1c 2066 int num_gain = 0;
341b28c0 2067 int c, g, sfb, ret;
9ffd5c1c
RS
2068 int sign;
2069 float scale;
577d383b
DB
2070 SingleChannelElement *sce = &che->ch[0];
2071 ChannelCoupling *coup = &che->coup;
9ffd5c1c 2072
577d383b 2073 coup->coupling_point = 2 * get_bits1(gb);
62a57fae
RS
2074 coup->num_coupled = get_bits(gb, 3);
2075 for (c = 0; c <= coup->num_coupled; c++) {
2076 num_gain++;
2077 coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
2078 coup->id_select[c] = get_bits(gb, 4);
2079 if (coup->type[c] == TYPE_CPE) {
2080 coup->ch_select[c] = get_bits(gb, 2);
2081 if (coup->ch_select[c] == 3)
2082 num_gain++;
2083 } else
88de95c2 2084 coup->ch_select[c] = 2;
62a57fae 2085 }
577d383b 2086 coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
62a57fae 2087
577d383b 2088 sign = get_bits(gb, 1);
93c6ff6c 2089 scale = cce_scale[get_bits(gb, 2)];
62a57fae
RS
2090
2091 if ((ret = decode_ics(ac, sce, gb, 0, 0)))
2092 return ret;
2093
2094 for (c = 0; c < num_gain; c++) {
577d383b
DB
2095 int idx = 0;
2096 int cge = 1;
62a57fae 2097 int gain = 0;
4a2ef394 2098 float gain_cache = 1.0;
62a57fae
RS
2099 if (c) {
2100 cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
2101 gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
531cfe6e 2102 gain_cache = powf(scale, -gain);
62a57fae 2103 }
f1ade11e
AC
2104 if (coup->coupling_point == AFTER_IMDCT) {
2105 coup->gain[c][0] = gain_cache;
2106 } else {
03b12747
AC
2107 for (g = 0; g < sce->ics.num_window_groups; g++) {
2108 for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
2109 if (sce->band_type[idx] != ZERO_BT) {
2110 if (!cge) {
2111 int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
577d383b 2112 if (t) {
03b12747
AC
2113 int s = 1;
2114 t = gain += t;
2115 if (sign) {
2116 s -= 2 * (t & 0x1);
2117 t >>= 1;
2118 }
531cfe6e 2119 gain_cache = powf(scale, -t) * s;
62a57fae 2120 }
62a57fae 2121 }
03b12747 2122 coup->gain[c][idx] = gain_cache;
62a57fae 2123 }
62a57fae 2124 }
f80a8ca5
RS
2125 }
2126 }
62a57fae
RS
2127 }
2128 return 0;
2129}
2130
9cc04edf 2131/**
62a57fae
RS
2132 * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
2133 *
2134 * @return Returns number of bytes consumed.
2135 */
577d383b
DB
2136static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
2137 GetBitContext *gb)
2138{
62a57fae
RS
2139 int i;
2140 int num_excl_chan = 0;
2141
2142 do {
2143 for (i = 0; i < 7; i++)
2144 che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
2145 } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
2146
2147 return num_excl_chan / 7;
2148}
2149
2150/**
9cc04edf
RS
2151 * Decode dynamic range information; reference: table 4.52.
2152 *
9cc04edf
RS
2153 * @return Returns number of bytes consumed.
2154 */
577d383b 2155static int decode_dynamic_range(DynamicRangeControl *che_drc,
5707af8d 2156 GetBitContext *gb)
577d383b
DB
2157{
2158 int n = 1;
9cc04edf
RS
2159 int drc_num_bands = 1;
2160 int i;
2161
2162 /* pce_tag_present? */
577d383b 2163 if (get_bits1(gb)) {
9cc04edf
RS
2164 che_drc->pce_instance_tag = get_bits(gb, 4);
2165 skip_bits(gb, 4); // tag_reserved_bits
2166 n++;
2167 }
2168
2169 /* excluded_chns_present? */
577d383b 2170 if (get_bits1(gb)) {
9cc04edf
RS
2171 n += decode_drc_channel_exclusions(che_drc, gb);
2172 }
2173
2174 /* drc_bands_present? */
2175 if (get_bits1(gb)) {
2176 che_drc->band_incr = get_bits(gb, 4);
2177 che_drc->interpolation_scheme = get_bits(gb, 4);
2178 n++;
2179 drc_num_bands += che_drc->band_incr;
2180 for (i = 0; i < drc_num_bands; i++) {
2181 che_drc->band_top[i] = get_bits(gb, 8);
2182 n++;
2183 }
2184 }
2185
2186 /* prog_ref_level_present? */
2187 if (get_bits1(gb)) {
2188 che_drc->prog_ref_level = get_bits(gb, 7);
2189 skip_bits1(gb); // prog_ref_level_reserved_bits
2190 n++;
2191 }
2192
2193 for (i = 0; i < drc_num_bands; i++) {
2194 che_drc->dyn_rng_sgn[i] = get_bits1(gb);
2195 che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
2196 n++;
2197 }
2198
2199 return n;
2200}
2201
2202/**
2203 * Decode extension data (incomplete); reference: table 4.51.
2204 *
2205 * @param cnt length of TYPE_FIL syntactic element in bytes
2206 *
2207 * @return Returns number of bytes consumed
2208 */
ed492b61
AC
2209static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
2210 ChannelElement *che, enum RawDataBlockType elem_type)
577d383b 2211{
cc0591da
RS
2212 int crc_flag = 0;
2213 int res = cnt;
2214 switch (get_bits(gb, 4)) { // extension type
577d383b
DB
2215 case EXT_SBR_DATA_CRC:
2216 crc_flag++;
2217 case EXT_SBR_DATA:
ed492b61 2218 if (!che) {
dd8871a6 2219 av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
ed492b61 2220 return res;
9fb7e146 2221 } else if (!ac->oc[1].m4ac.sbr) {
dd8871a6 2222 av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
ed492b61
AC
2223 skip_bits_long(gb, 8 * cnt - 4);
2224 return res;
9fb7e146 2225 } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
dd8871a6 2226 av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
ed492b61
AC
2227 skip_bits_long(gb, 8 * cnt - 4);
2228 return res;
9fb7e146
AC
2229 } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
2230 ac->oc[1].m4ac.sbr = 1;
2231 ac->oc[1].m4ac.ps = 1;
454959a5 2232 ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
9fb7e146 2233 output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
3d3cf674 2234 ac->oc[1].status, 1);
ed492b61 2235 } else {
9fb7e146 2236 ac->oc[1].m4ac.sbr = 1;
454959a5 2237 ac->avctx->profile = FF_PROFILE_AAC_HE;
ed492b61
AC
2238 }
2239 res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
577d383b
DB
2240 break;
2241 case EXT_DYNAMIC_RANGE:
5707af8d 2242 res = decode_dynamic_range(&ac->che_drc, gb);
577d383b
DB
2243 break;
2244 case EXT_FILL:
2245 case EXT_FILL_DATA:
2246 case EXT_DATA_ELEMENT:
2247 default:
2248 skip_bits_long(gb, 8 * cnt - 4);
2249 break;
cc0591da
RS
2250 };
2251 return res;
2252}
2253
7d8f3de4
RS
2254/**
2255 * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
2256 *
2257 * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
2258 * @param coef spectral coefficients
2259 */
577d383b
DB
2260static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
2261 IndividualChannelStream *ics, int decode)
2262{
2263 const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
1098e8d2 2264 int w, filt, m, i;
7d8f3de4
RS
2265 int bottom, top, order, start, end, size, inc;
2266 float lpc[TNS_MAX_ORDER];
6d5b0092 2267 float tmp[TNS_MAX_ORDER + 1];
7d8f3de4
RS
2268
2269 for (w = 0; w < ics->num_windows; w++) {
2270 bottom = ics->num_swb;
2271 for (filt = 0; filt < tns->n_filt[w]; filt++) {
2272 top = bottom;
2273 bottom = FFMAX(0, top - tns->length[w][filt]);
2274 order = tns->order[w][filt];
2275 if (order == 0)
2276 continue;
2277
1be0fc29
VS
2278 // tns_decode_coef
2279 compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
7d8f3de4 2280
1dece0d2
RS
2281 start = ics->swb_offset[FFMIN(bottom, mmm)];
2282 end = ics->swb_offset[FFMIN( top, mmm)];
2283 if ((size = end - start) <= 0)
2284 continue;
2285 if (tns->direction[w][filt]) {
577d383b
DB
2286 inc = -1;
2287 start = end - 1;
1dece0d2
RS
2288 } else {
2289 inc = 1;
2290 }
2291 start += w * 128;
2292
ead15f1d
YHL
2293 if (decode) {
2294 // ar filter
2295 for (m = 0; m < size; m++, start += inc)
2296 for (i = 1; i <= FFMIN(m, order); i++)
2297 coef[start] -= coef[start - i * inc] * lpc[i - 1];
2298 } else {
2299 // ma filter
2300 for (m = 0; m < size; m++, start += inc) {
2301 tmp[0] = coef[start];
2302 for (i = 1; i <= FFMIN(m, order); i++)
2303 coef[start] += tmp[i] * lpc[i - 1];
2304 for (i = order; i > 0; i--)
2305 tmp[i] = tmp[i - 1];
2306 }
2307 }
1dece0d2
RS
2308 }
2309 }
2310}
2311
cc0591da 2312/**
ead15f1d
YHL
2313 * Apply windowing and MDCT to obtain the spectral
2314 * coefficient from the predicted sample by LTP.
2315 */
2316static void windowing_and_mdct_ltp(AACContext *ac, float *out,
2317 float *in, IndividualChannelStream *ics)
2318{
2319 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2320 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2321 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2322 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2323
2324 if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
d5a7229b 2325 ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
ead15f1d
YHL
2326 } else {
2327 memset(in, 0, 448 * sizeof(float));
d5a7229b 2328 ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
ead15f1d
YHL
2329 }
2330 if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
42d32469 2331 ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
ead15f1d 2332 } else {
42d32469 2333 ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
ead15f1d
YHL
2334 memset(in + 1024 + 576, 0, 448 * sizeof(float));
2335 }
26f548bb 2336 ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
ead15f1d
YHL
2337}
2338
2339/**
2340 * Apply the long term prediction
2341 */
2342static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
2343{
2344 const LongTermPrediction *ltp = &sce->ics.ltp;
2345 const uint16_t *offsets = sce->ics.swb_offset;
2346 int i, sfb;
2347
2348 if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
e22910b2
YHL
2349 float *predTime = sce->ret;
2350 float *predFreq = ac->buf_mdct;
ead15f1d
YHL
2351 int16_t num_samples = 2048;
2352
2353 if (ltp->lag < 1024)
2354 num_samples = ltp->lag + 1024;
2355 for (i = 0; i < num_samples; i++)
2356 predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
2357 memset(&predTime[i], 0, (2048 - i) * sizeof(float));
2358
2359 windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
2360
2361 if (sce->tns.present)
2362 apply_tns(predFreq, &sce->tns, &sce->ics, 0);
2363
2364 for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
2365 if (ltp->used[sfb])
2366 for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
2367 sce->coeffs[i] += predFreq[i];
2368 }
2369}
2370
2371/**
2372 * Update the LTP buffer for next frame
2373 */
2374static void update_ltp(AACContext *ac, SingleChannelElement *sce)
2375{
2376 IndividualChannelStream *ics = &sce->ics;
2377 float *saved = sce->saved;
2378 float *saved_ltp = sce->coeffs;
2379 const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2380 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2381 int i;
2382
ead15f1d
YHL
2383 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
2384 memcpy(saved_ltp, saved, 512 * sizeof(float));
2385 memset(saved_ltp + 576, 0, 448 * sizeof(float));
42d32469 2386 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
e22910b2
YHL
2387 for (i = 0; i < 64; i++)
2388 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
ead15f1d
YHL
2389 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
2390 memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
2391 memset(saved_ltp + 576, 0, 448 * sizeof(float));
42d32469 2392 ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
e22910b2
YHL
2393 for (i = 0; i < 64; i++)
2394 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
ead15f1d 2395 } else { // LONG_STOP or ONLY_LONG
42d32469 2396 ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
e22910b2
YHL
2397 for (i = 0; i < 512; i++)
2398 saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
ead15f1d
YHL
2399 }
2400
033a4a94
JR
2401 memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
2402 memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
2403 memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
ead15f1d
YHL
2404}
2405
2406/**
9cc04edf
RS
2407 * Conduct IMDCT and windowing.
2408 */
9d06d7bc 2409static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
577d383b
DB
2410{
2411 IndividualChannelStream *ics = &sce->ics;
2412 float *in = sce->coeffs;
2413 float *out = sce->ret;
2414 float *saved = sce->saved;
2415 const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
2416 const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
2417 const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
2418 float *buf = ac->buf_mdct;
2419 float *temp = ac->temp;
9cc04edf
RS
2420 int i;
2421
f4990558 2422 // imdct
62a57fae 2423 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
b0f5852a 2424 for (i = 0; i < 1024; i += 128)
26f548bb 2425 ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
f4990558 2426 } else
26f548bb 2427 ac->mdct.imdct_half(&ac->mdct, buf, in);
f4990558
RS
2428
2429 /* window overlapping
2430 * NOTE: To simplify the overlapping code, all 'meaningless' short to long
2431 * and long to short transitions are considered to be short to short
2432 * transitions. This leaves just two cases (long to long and short to short)
2433 * with a little special sauce for EIGHT_SHORT_SEQUENCE.
2434 */
2435 if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
577d383b 2436 (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
e034cc6c 2437 ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
f4990558 2438 } else {
e034cc6c 2439 memcpy( out, saved, 448 * sizeof(float));
62a57fae 2440
f4990558 2441 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
e034cc6c
JR
2442 ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
2443 ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
2444 ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
2445 ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
2446 ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
2447 memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
f4990558 2448 } else {
e034cc6c
JR
2449 ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
2450 memcpy( out + 576, buf + 64, 448 * sizeof(float));
f4990558
RS
2451 }
2452 }
62a57fae 2453
f4990558
RS
2454 // buffer update
2455 if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
e034cc6c
JR
2456 memcpy( saved, temp + 64, 64 * sizeof(float));
2457 ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
2458 ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
2459 ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
2460 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
f4990558 2461 } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
e034cc6c
JR
2462 memcpy( saved, buf + 512, 448 * sizeof(float));
2463 memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
f4990558 2464 } else { // LONG_STOP or ONLY_LONG
e034cc6c 2465 memcpy( saved, buf + 512, 512 * sizeof(float));
62a57fae
RS
2466 }
2467}
2468
1914e6f0
AC
2469static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
2470{
2471 IndividualChannelStream *ics = &sce->ics;
2472 float *in = sce->coeffs;
2473 float *out = sce->ret;
2474 float *saved = sce->saved;
1914e6f0
AC
2475 float *buf = ac->buf_mdct;
2476
2477 // imdct
2478 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
2479
2480 // window overlapping
7f296441
AC
2481 if (ics->use_kb_window[1]) {
2482 // AAC LD uses a low overlap sine window instead of a KBD window
2483 memcpy(out, saved, 192 * sizeof(float));
2484 ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
2485 memcpy( out + 320, buf + 64, 192 * sizeof(float));
2486 } else {
2487 ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
2488 }
1914e6f0
AC
2489
2490 // buffer update
2491 memcpy(saved, buf + 256, 256 * sizeof(float));
2492}
2493
b3be41ca
AC
2494static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
2495{
2496 float *in = sce->coeffs;
2497 float *out = sce->ret;
2498 float *saved = sce->saved;
b3be41ca
AC
2499 float *buf = ac->buf_mdct;
2500 int i;
d615187f 2501 const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
b3be41ca
AC
2502 const int n2 = n >> 1;
2503 const int n4 = n >> 2;
d615187f
AC
2504 const float *const window = n == 480 ? ff_aac_eld_window_480 :
2505 ff_aac_eld_window_512;
b3be41ca
AC
2506
2507 // Inverse transform, mapped to the conventional IMDCT by
2508 // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
2509 // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
2510 // Audio, Language and Image Processing, 2008. ICALIP 2008. International Conference on
2511 // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
2512 for (i = 0; i < n2; i+=2) {
2513 float temp;
2514 temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
2515 temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
2516 }
d615187f
AC
2517 if (n == 480)
2518 ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
2519 else
2520 ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
b3be41ca
AC
2521 for (i = 0; i < n; i+=2) {
2522 buf[i] = -buf[i];
2523 }
2524 // Like with the regular IMDCT at this point we still have the middle half
2525 // of a transform but with even symmetry on the left and odd symmetry on
2526 // the right
2527
2528 // window overlapping
2529 // The spec says to use samples [0..511] but the reference decoder uses
2530 // samples [128..639].
2531 for (i = n4; i < n2; i ++) {
2532 out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
2533 saved[ i + n2] * window[i + n - n4] +
2534 -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
2535 -saved[2*n + n2 + i] * window[i + 3*n - n4];
2536 }
2537 for (i = 0; i < n2; i ++) {
2538 out[n4 + i] = buf[i] * window[i + n2 - n4] +
2539 -saved[ n - 1 - i] * window[i + n2 + n - n4] +
2540 -saved[ n + i] * window[i + n2 + 2*n - n4] +
2541 saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
2542 }
2543 for (i = 0; i < n4; i ++) {
2544 out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
2545 -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
2546 -saved[ n + n2 + i] * window[i + 3*n - n4];
2547 }
2548
2549 // buffer update
2550 memmove(saved + n, saved, 2 * n * sizeof(float));
2551 memcpy( saved, buf, n * sizeof(float));
2552}
2553
9cc04edf 2554/**
cc0591da
RS
2555 * Apply dependent channel coupling (applied before IMDCT).
2556 *
2557 * @param index index into coupling gain array
2558 */
577d383b
DB
2559static void apply_dependent_coupling(AACContext *ac,
2560 SingleChannelElement *target,
2561 ChannelElement *cce, int index)
2562{
2563 IndividualChannelStream *ics = &cce->ch[0].ics;
2564 const uint16_t *offsets = ics->swb_offset;
2565 float *dest = target->coeffs;
2566 const float *src = cce->ch[0].coeffs;
cc0591da 2567 int g, i, group, k, idx = 0;
9fb7e146 2568 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
dd8871a6 2569 av_log(ac->avctx, AV_LOG_ERROR,
cc0591da
RS
2570 "Dependent coupling is not supported together with LTP\n");
2571 return;
2572 }
2573 for (g = 0; g < ics->num_window_groups; g++) {
2574 for (i = 0; i < ics->max_sfb; i++, idx++) {
fbdae895 2575 if (cce->ch[0].band_type[idx] != ZERO_BT) {
cfd937b0 2576 const float gain = cce->coup.gain[index][idx];
cc0591da 2577 for (group = 0; group < ics->group_len[g]; group++) {
577d383b 2578 for (k = offsets[i]; k < offsets[i + 1]; k++) {
831a1180 2579 // FIXME: SIMDify
577d383b 2580 dest[group * 128 + k] += gain * src[group * 128 + k];
cc0591da
RS
2581 }
2582 }
2583 }
2584 }
577d383b
DB
2585 dest += ics->group_len[g] * 128;
2586 src += ics->group_len[g] * 128;
cc0591da
RS
2587 }
2588}
2589
2590/**
2591 * Apply independent channel coupling (applied after IMDCT).
2592 *
2593 * @param index index into coupling gain array
2594 */
577d383b
DB
2595static void apply_independent_coupling(AACContext *ac,
2596 SingleChannelElement *target,
2597 ChannelElement *cce, int index)
2598{
cc0591da 2599 int i;
039821a8 2600 const float gain = cce->coup.gain[index][0];
577d383b
DB
2601 const float *src = cce->ch[0].ret;
2602 float *dest = target->ret;
9fb7e146 2603 const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
039821a8 2604
ed492b61 2605 for (i = 0; i < len; i++)
9d06d7bc 2606 dest[i] += gain * src[i];
cc0591da
RS
2607}
2608
9ffd5c1c
RS
2609/**
2610 * channel coupling transformation interface
2611 *
9ffd5c1c
RS
2612 * @param apply_coupling_method pointer to (in)dependent coupling function
2613 */
577d383b
DB
2614static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
2615 enum RawDataBlockType type, int elem_id,
2616 enum CouplingPoint coupling_point,
2617 void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
9ffd5c1c 2618{
88de95c2
AC
2619 int i, c;
2620
2621 for (i = 0; i < MAX_ELEM_ID; i++) {
2622 ChannelElement *cce = ac->che[TYPE_CCE][i];
2623 int index = 0;
2624
2625 if (cce && cce->coup.coupling_point == coupling_point) {
577d383b 2626 ChannelCoupling *coup = &cce->coup;
88de95c2
AC
2627
2628 for (c = 0; c <= coup->num_coupled; c++) {
2629 if (coup->type[c] == type && coup->id_select[c] == elem_id) {
2630 if (coup->ch_select[c] != 1) {
2631 apply_coupling_method(ac, &cc->ch[0], cce, index);
2632 if (coup->ch_select[c] != 0)
2633 index++;
2634 }
2635 if (coup->ch_select[c] != 2)
2636 apply_coupling_method(ac, &cc->ch[1], cce, index++);
2637 } else
2638 index += 1 + (coup->ch_select[c] == 3);
9ffd5c1c 2639 }
9ffd5c1c
RS
2640 }
2641 }
2642}
2643
2644/**
2645 * Convert spectral data to float samples, applying all supported tools as appropriate.
2646 */
577d383b
DB
2647static void spectral_to_sample(AACContext *ac)
2648{
b0bc928b 2649 int i, type;
1914e6f0 2650 void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
b3be41ca
AC
2651 switch (ac->oc[1].m4ac.object_type) {
2652 case AOT_ER_AAC_LD:
1914e6f0 2653 imdct_and_window = imdct_and_windowing_ld;
b3be41ca
AC
2654 break;
2655 case AOT_ER_AAC_ELD:
2656 imdct_and_window = imdct_and_windowing_eld;
2657 break;
2658 default:
1914e6f0 2659 imdct_and_window = imdct_and_windowing;
b3be41ca 2660 }
b0bc928b 2661 for (type = 3; type >= 0; type--) {
88de95c2 2662 for (i = 0; i < MAX_ELEM_ID; i++) {
9ffd5c1c 2663 ChannelElement *che = ac->che[type][i];
577d383b
DB
2664 if (che) {
2665 if (type <= TYPE_CPE)
88de95c2 2666 apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
9fb7e146 2667 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
ead15f1d
YHL
2668 if (che->ch[0].ics.predictor_present) {
2669 if (che->ch[0].ics.ltp.present)
2670 apply_ltp(ac, &che->ch[0]);
2671 if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
2672 apply_ltp(ac, &che->ch[1]);
2673 }
2674 }
577d383b 2675 if (che->ch[0].tns.present)
9ffd5c1c 2676 apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
577d383b 2677 if (che->ch[1].tns.present)
9ffd5c1c 2678 apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
577d383b 2679 if (type <= TYPE_CPE)
88de95c2 2680 apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
ed492b61 2681 if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
1914e6f0 2682 imdct_and_window(ac, &che->ch[0]);
9fb7e146 2683 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
ead15f1d 2684 update_ltp(ac, &che->ch[0]);
d0dedce7 2685 if (type == TYPE_CPE) {
1914e6f0 2686 imdct_and_window(ac, &che->ch[1]);
9fb7e146 2687 if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
ead15f1d 2688 update_ltp(ac, &che->ch[1]);
d0dedce7 2689 }
9fb7e146 2690 if (ac->oc[1].m4ac.sbr > 0) {
ca6d3f23
AC
2691 ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
2692 }
ed492b61 2693 }
577d383b 2694 if (type <= TYPE_CCE)
88de95c2 2695 apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
62a57fae
RS
2696 }
2697 }
2698 }
2699}
2700
577d383b
DB
2701static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
2702{
158b3912
RS
2703 int size;
2704 AACADTSHeaderInfo hdr_info;
37bed6ff 2705 uint8_t layout_map[MAX_ELEM_ID*4][3];
a10c4ce2 2706 int layout_map_tags, ret;
158b3912 2707
73ae27e1 2708 size = avpriv_aac_parse_header(gb, &hdr_info);
158b3912 2709 if (size > 0) {
9fb7e146 2710 if (hdr_info.num_aac_frames != 1) {
63d744e2
DB
2711 avpriv_report_missing_feature(ac->avctx,
2712 "More than one AAC RDB per ADTS frame");
717addec 2713 return AVERROR_PATCHWELCOME;
9fb7e146
AC
2714 }
2715 push_output_configuration(ac);
bc2dd367 2716 if (hdr_info.chan_config) {
9fb7e146 2717 ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
a10c4ce2
LB
2718 if ((ret = set_default_channel_config(ac->avctx,
2719 layout_map,
2720 &layout_map_tags,
2721 hdr_info.chan_config)) < 0)
2722 return ret;
2723 if ((ret = output_configure(ac, layout_map, layout_map_tags,
2724 FFMAX(ac->oc[1].status,
2725 OC_TRIAL_FRAME), 0)) < 0)
2726 return ret;
7d87e2ce 2727 } else {
9fb7e146
AC
2728 ac->oc[1].m4ac.chan_config = 0;
2729 }
2730 ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
2731 ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
2732 ac->oc[1].m4ac.object_type = hdr_info.object_type;
d615187f 2733 ac->oc[1].m4ac.frame_length_short = 0;
9fb7e146
AC
2734 if (ac->oc[0].status != OC_LOCKED ||
2735 ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
2736 ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
2737 ac->oc[1].m4ac.sbr = -1;
2738 ac->oc[1].m4ac.ps = -1;
7d87e2ce 2739 }
9fb7e146
AC
2740 if (!hdr_info.crc_absent)
2741 skip_bits(gb, 16);
51741a82 2742 }
158b3912
RS
2743 return size;
2744}
2745
5cdefc02
AC
2746static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
2747 int *got_frame_ptr, GetBitContext *gb)
2748{
2749 AACContext *ac = avctx->priv_data;
edd9ea3f 2750 const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
5cdefc02
AC
2751 ChannelElement *che;
2752 int err, i;
d615187f 2753 int samples = m4ac->frame_length_short ? 960 : 1024;
edd9ea3f
AC
2754 int chan_config = m4ac->chan_config;
2755 int aot = m4ac->object_type;
5cdefc02 2756
b3be41ca 2757 if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
1914e6f0
AC
2758 samples >>= 1;
2759
5cdefc02
AC
2760 ac->frame = data;
2761
2762 if ((err = frame_configure_elements(avctx)) < 0)
2763 return err;
2764
454959a5
GCP
2765 // The FF_PROFILE_AAC_* defines are all object_type - 1
2766 // This may lead to an undefined profile being signaled
edd9ea3f 2767 ac->avctx->profile = aot - 1;
454959a5 2768
5cdefc02
AC
2769 ac->tags_mapped = 0;
2770
a188108e 2771 if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
5cdefc02 2772 avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
edd9ea3f 2773 chan_config);
5cdefc02
AC
2774 return AVERROR_INVALIDDATA;
2775 }
2776 for (i = 0; i < tags_per_config[chan_config]; i++) {
2777 const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
2778 const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
2779 if (!(che=get_che(ac, elem_type, elem_id))) {
2780 av_log(ac->avctx, AV_LOG_ERROR,
2781 "channel element %d.%d is not allocated\n",
2782 elem_type, elem_id);
2783 return AVERROR_INVALIDDATA;
2784 }
b3be41ca
AC
2785 if (aot != AOT_ER_AAC_ELD)
2786 skip_bits(gb, 4);
5cdefc02
AC
2787 switch (elem_type) {
2788 case TYPE_SCE:
2789 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2790 break;
2791 case TYPE_CPE:
2792 err = decode_cpe(ac, gb, che);
2793 break;
2794 case TYPE_LFE:
2795 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
2796 break;
2797 }
2798 if (err < 0)
2799 return err;
2800 }
2801
2802 spectral_to_sample(ac);
2803
2804 ac->frame->nb_samples = samples;
462d5e8e 2805 ac->frame->sample_rate = avctx->sample_rate;
5cdefc02
AC
2806 *got_frame_ptr = 1;
2807
2808 skip_bits_long(gb, get_bits_left(gb));
2809 return 0;
2810}
2811
66a71d98 2812static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
0eea2129 2813 int *got_frame_ptr, GetBitContext *gb)
577d383b 2814{
dd8871a6 2815 AACContext *ac = avctx->priv_data;
ed492b61 2816 ChannelElement *che = NULL, *che_prev = NULL;
ed492b61 2817 enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
0eea2129 2818 int err, elem_id;
9fb7e146 2819 int samples = 0, multiplier, audio_found = 0, pce_found = 0;
62a57fae 2820
ffd21230
JR
2821 ac->frame = data;
2822
66a71d98 2823 if (show_bits(gb, 12) == 0xfff) {
a10c4ce2 2824 if ((err = parse_adts_frame_header(ac, gb)) < 0) {
dd8871a6 2825 av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
9fb7e146 2826 goto fail;
158b3912 2827 }
9fb7e146
AC
2828 if (ac->oc[1].m4ac.sampling_index > 12) {
2829 av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
a10c4ce2 2830 err = AVERROR_INVALIDDATA;
9fb7e146 2831 goto fail;
f418b861 2832 }
158b3912
RS
2833 }
2834
bc76c469
LB
2835 if (avctx->channels)
2836 if ((err = frame_configure_elements(avctx)) < 0)
2837 goto fail;
3d3cf674 2838
454959a5
GCP
2839 // The FF_PROFILE_AAC_* defines are all object_type - 1
2840 // This may lead to an undefined profile being signaled
2841 ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
2842
bb2d8e9f 2843 ac->tags_mapped = 0;
62a57fae 2844 // parse
66a71d98
JG
2845 while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
2846 elem_id = get_bits(gb, 4);
62a57fae 2847
d5eab59a
LB
2848 if (!avctx->channels && elem_type != TYPE_PCE) {
2849 err = AVERROR_INVALIDDATA;
bc76c469 2850 goto fail;
d5eab59a 2851 }
bc76c469 2852
ed99e54d 2853 if (elem_type < TYPE_DSE) {
d4e355d5
AC
2854 if (!(che=get_che(ac, elem_type, elem_id))) {
2855 av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
2856 elem_type, elem_id);
a10c4ce2 2857 err = AVERROR_INVALIDDATA;
9fb7e146 2858 goto fail;
d4e355d5 2859 }
fda36b59 2860 samples = 1024;
ed99e54d 2861 }
fda36b59 2862
62a57fae
RS
2863 switch (elem_type) {
2864
2865 case TYPE_SCE:
66a71d98 2866 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
d8425ed4 2867 audio_found = 1;
62a57fae
RS
2868 break;
2869
2870 case TYPE_CPE:
66a71d98 2871 err = decode_cpe(ac, gb, che);
d8425ed4 2872 audio_found = 1;
62a57fae
RS
2873 break;
2874
2875 case TYPE_CCE:
66a71d98 2876 err = decode_cce(ac, gb, che);
62a57fae
RS
2877 break;
2878
2879 case TYPE_LFE:
66a71d98 2880 err = decode_ics(ac, &che->ch[0], gb, 0, 0);
d8425ed4 2881 audio_found = 1;
62a57fae
RS
2882 break;
2883
2884 case TYPE_DSE:
66a71d98 2885 err = skip_data_stream_element(ac, gb);
62a57fae
RS
2886 break;
2887
577d383b 2888 case TYPE_PCE: {
37bed6ff
AC
2889 uint8_t layout_map[MAX_ELEM_ID*4][3];
2890 int tags;
9fb7e146
AC
2891 push_output_configuration(ac);
2892 tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
37bed6ff
AC
2893 if (tags < 0) {
2894 err = tags;
62a57fae 2895 break;
37bed6ff 2896 }
9fb7e146 2897 if (pce_found) {
dd8871a6 2898 av_log(avctx, AV_LOG_ERROR,
6308765c 2899 "Not evaluating a further program_config_element as this construct is dubious at best.\n");
9fb7e146
AC
2900 pop_output_configuration(ac);
2901 } else {
3d3cf674 2902 err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
9fb7e146
AC
2903 pce_found = 1;
2904 }
62a57fae
RS
2905 break;
2906 }
2907
2908 case TYPE_FIL:
2909 if (elem_id == 15)
66a71d98
JG
2910 elem_id += get_bits(gb, 8) - 1;
2911 if (get_bits_left(gb) < 8 * elem_id) {
dd8871a6 2912 av_log(avctx, AV_LOG_ERROR, overread_err);
a10c4ce2 2913 err = AVERROR_INVALIDDATA;
9fb7e146 2914 goto fail;
8d637124 2915 }
62a57fae 2916 while (elem_id > 0)
66a71d98 2917 elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
62a57fae
RS
2918 err = 0; /* FIXME */
2919 break;
2920
2921 default:
a10c4ce2 2922 err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
62a57fae
RS
2923 break;
2924 }
2925
ed492b61
AC
2926 che_prev = che;
2927 elem_type_prev = elem_type;
2928
577d383b 2929 if (err)
9fb7e146 2930 goto fail;
8d637124 2931
66a71d98 2932 if (get_bits_left(gb) < 3) {
dd8871a6 2933 av_log(avctx, AV_LOG_ERROR, overread_err);
a10c4ce2 2934 err = AVERROR_INVALIDDATA;
9fb7e146 2935 goto fail;
8d637124 2936 }
62a57fae
RS
2937 }
2938
bc76c469
LB
2939 if (!avctx->channels) {
2940 *got_frame_ptr = 0;
2941 return 0;
2942 }
2943
62a57fae
RS
2944 spectral_to_sample(ac);
2945
9fb7e146 2946 multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
54f158bd 2947 samples <<= multiplier;
54f158bd 2948
9fb7e146
AC
2949 if (ac->oc[1].status && audio_found) {
2950 avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
2951 avctx->frame_size = samples;
2952 ac->oc[1].status = OC_LOCKED;
2953 }
981b8fd7 2954
462d5e8e
JS
2955 if (samples) {
2956 ac->frame->nb_samples = samples;
2957 ac->frame->sample_rate = avctx->sample_rate;
2958 }
2959 *got_frame_ptr = !!samples;
2960
66a71d98 2961 return 0;
9fb7e146
AC
2962fail:
2963 pop_output_configuration(ac);
2964 return err;
66a71d98
JG
2965}
2966
2967static int aac_decode_frame(AVCodecContext *avctx, void *data,
0eea2129 2968 int *got_frame_ptr, AVPacket *avpkt)
66a71d98 2969{
132846b0 2970 AACContext *ac = avctx->priv_data;
66a71d98
JG
2971 const uint8_t *buf = avpkt->data;
2972 int buf_size = avpkt->size;
2973 GetBitContext gb;
2974 int buf_consumed;
2975 int buf_offset;
2976 int err;
132846b0
MS
2977 int new_extradata_size;
2978 const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
2979 AV_PKT_DATA_NEW_EXTRADATA,
2980 &new_extradata_size);
2981
2982 if (new_extradata) {
2983 av_free(avctx->extradata);
2984 avctx->extradata = av_mallocz(new_extradata_size +
059a9348 2985 AV_INPUT_BUFFER_PADDING_SIZE);
132846b0
MS
2986 if (!avctx->extradata)
2987 return AVERROR(ENOMEM);
2988 avctx->extradata_size = new_extradata_size;
2989 memcpy(avctx->extradata, new_extradata, new_extradata_size);
9fb7e146
AC
2990 push_output_configuration(ac);
2991 if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
132846b0 2992 avctx->extradata,
9fb7e146
AC
2993 avctx->extradata_size*8, 1) < 0) {
2994 pop_output_configuration(ac);
132846b0 2995 return AVERROR_INVALIDDATA;
9fb7e146 2996 }
132846b0 2997 }
66a71d98 2998
71953ebc
LB
2999 if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
3000 return err;
66a71d98 3001
5cdefc02
AC
3002 switch (ac->oc[1].m4ac.object_type) {
3003 case AOT_ER_AAC_LC:
3004 case AOT_ER_AAC_LTP:
3005 case AOT_ER_AAC_LD:
b3be41ca 3006 case AOT_ER_AAC_ELD:
5cdefc02
AC
3007 err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
3008 break;
3009 default:
3010 err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb);
3011 }
3012 if (err < 0)
66a71d98
JG
3013 return err;
3014
b5e2bb8c 3015 buf_consumed = (get_bits_count(&gb) + 7) >> 3;
c16d5a6f
AC
3016 for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
3017 if (buf[buf_offset])
3018 break;
3019
3020 return buf_size > buf_offset ? buf_consumed : buf_size;
9cc04edf
RS
3021}
3022
dd8871a6 3023static av_cold int aac_decode_close(AVCodecContext *avctx)
577d383b 3024{
dd8871a6 3025 AACContext *ac = avctx->priv_data;
9edae4ad 3026 int i, type;
71e9a1b8 3027
cc0591da 3028 for (i = 0; i < MAX_ELEM_ID; i++) {
ed492b61
AC
3029 for (type = 0; type < 4; type++) {
3030 if (ac->che[type][i])
3031 ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
9edae4ad 3032 av_freep(&ac->che[type][i]);
ed492b61 3033 }
71e9a1b8
RS
3034 }
3035
3036 ff_mdct_end(&ac->mdct);
3037 ff_mdct_end(&ac->mdct_small);
1914e6f0 3038 ff_mdct_end(&ac->mdct_ld);
ead15f1d 3039 ff_mdct_end(&ac->mdct_ltp);
d615187f 3040 ff_imdct15_uninit(&ac->mdct480);
577d383b 3041 return 0;
71e9a1b8
RS
3042}
3043
136e19e1
JG
3044
3045#define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
3046
3047struct LATMContext {
6d8629aa 3048 AACContext aac_ctx; ///< containing AACContext
41ed7ab4 3049 int initialized; ///< initialized after a valid extradata was seen
136e19e1
JG
3050
3051 // parser data
6d8629aa
LB
3052 int audio_mux_version_A; ///< LATM syntax version
3053 int frame_length_type; ///< 0/1 variable/fixed frame length
3054 int frame_length; ///< frame length for fixed frame length
136e19e1
JG
3055};
3056
3057static inline uint32_t latm_get_value(GetBitContext *b)
3058{
3059 int length = get_bits(b, 2);
3060
3061 return get_bits_long(b, (length+1)*8);
3062}
3063
3064static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
fd095539 3065 GetBitContext *gb, int asclen)
136e19e1 3066{
d268b79e
JG
3067 AACContext *ac = &latmctx->aac_ctx;
3068 AVCodecContext *avctx = ac->avctx;
9fb7e146 3069 MPEG4AudioConfig m4ac = { 0 };
fd095539
JG
3070 int config_start_bit = get_bits_count(gb);
3071 int sync_extension = 0;
3072 int bits_consumed, esize;
3073
3074 if (asclen) {
3075 sync_extension = 1;
3076 asclen = FFMIN(asclen, get_bits_left(gb));
3077 } else
3078 asclen = get_bits_left(gb);
136e19e1
JG
3079
3080 if (config_start_bit % 8) {
12e25ed2
DB
3081 avpriv_request_sample(latmctx->aac_ctx.avctx,
3082 "Non-byte-aligned audio-specific config");
717addec 3083 return AVERROR_PATCHWELCOME;
d268b79e 3084 }
b5fc571e
AC
3085 if (asclen <= 0)
3086 return AVERROR_INVALIDDATA;
d268b79e 3087 bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
136e19e1 3088 gb->buffer + (config_start_bit / 8),
fd095539 3089 asclen, sync_extension);
136e19e1 3090
d268b79e
JG
3091 if (bits_consumed < 0)
3092 return AVERROR_INVALIDDATA;
3093
3aca10bf
HL
3094 if (!latmctx->initialized ||
3095 ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
9fb7e146 3096 ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
d268b79e
JG
3097
3098 av_log(avctx, AV_LOG_INFO, "audio config changed\n");
3099 latmctx->initialized = 0;
136e19e1
JG
3100
3101 esize = (bits_consumed+7) / 8;
3102
d268b79e 3103 if (avctx->extradata_size < esize) {
136e19e1 3104 av_free(avctx->extradata);
059a9348 3105 avctx->extradata = av_malloc(esize + AV_INPUT_BUFFER_PADDING_SIZE);
136e19e1
JG
3106 if (!avctx->extradata)
3107 return AVERROR(ENOMEM);
3108 }
3109
3110 avctx->extradata_size = esize;
3111 memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
059a9348 3112 memset(avctx->extradata+esize, 0, AV_INPUT_BUFFER_PADDING_SIZE);
136e19e1 3113 }
d268b79e 3114 skip_bits_long(gb, bits_consumed);
136e19e1
JG
3115
3116 return bits_consumed;
3117}
3118
3119static int read_stream_mux_config(struct LATMContext *latmctx,
3120 GetBitContext *gb)
3121{
3122 int ret, audio_mux_version = get_bits(gb, 1);
3123
3124 latmctx->audio_mux_version_A = 0;
3125 if (audio_mux_version)
3126 latmctx->audio_mux_version_A = get_bits(gb, 1);
3127
3128 if (!latmctx->audio_mux_version_A) {
3129
3130 if (audio_mux_version)
3131 latm_get_value(gb); // taraFullness
3132
3133 skip_bits(gb, 1); // allStreamSameTimeFraming
3134 skip_bits(gb, 6); // numSubFrames
3135 // numPrograms
3136 if (get_bits(gb, 4)) { // numPrograms
12e25ed2 3137 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
136e19e1
JG
3138 return AVERROR_PATCHWELCOME;
3139 }
3140
3141 // for each program (which there is only on in DVB)
3142
3143 // for each layer (which there is only on in DVB)
3144 if (get_bits(gb, 3)) { // numLayer
12e25ed2 3145 avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
136e19e1
JG
3146 return AVERROR_PATCHWELCOME;
3147 }
3148
3149 // for all but first stream: use_same_config = get_bits(gb, 1);
3150 if (!audio_mux_version) {
fd095539 3151 if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
136e19e1
JG
3152 return ret;
3153 } else {
3154 int ascLen = latm_get_value(gb);
fd095539 3155 if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
136e19e1
JG
3156 return ret;
3157 ascLen -= ret;
3158 skip_bits_long(gb, ascLen);
3159 }
3160
3161 latmctx->frame_length_type = get_bits(gb, 3);
3162 switch (latmctx->frame_length_type) {
3163 case 0:
3164 skip_bits(gb, 8); // latmBufferFullness
3165 break;
3166 case 1:
3167 latmctx->frame_length = get_bits(gb, 9);
3168 break;
3169 case 3:
3170 case 4:
3171 case 5:
3172 skip_bits(gb, 6); // CELP frame length table index
3173 break;
3174 case 6:
3175 case 7:
3176 skip_bits(gb, 1); // HVXC frame length table index
3177 break;
3178 }
3179
3180 if (get_bits(gb, 1)) { // other data
3181 if (audio_mux_version) {
3182 latm_get_value(gb); // other_data_bits
3183 } else {
3184 int esc;
3185 do {
3186 esc = get_bits(gb, 1);
3187 skip_bits(gb, 8);
3188 } while (esc);
3189 }
3190 }
3191
3192 if (get_bits(gb, 1)) // crc present
3193 skip_bits(gb, 8); // config_crc
3194 }
3195
3196 return 0;
3197}
3198
3199static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
3200{
3201 uint8_t tmp;
3202
3203 if (ctx->frame_length_type == 0) {
3204 int mux_slot_length = 0;
3205 do {
3206 tmp = get_bits(gb, 8);
3207 mux_slot_length += tmp;
3208 } while (tmp == 255);
3209 return mux_slot_length;
3210 } else if (ctx->frame_length_type == 1) {
3211 return ctx->frame_length;
3212 } else if (ctx->frame_length_type == 3 ||
3213 ctx->frame_length_type == 5 ||
3214 ctx->frame_length_type == 7) {
3215 skip_bits(gb, 2); // mux_slot_length_coded
3216 }
3217 return 0;
3218}
3219
3220static int read_audio_mux_element(struct LATMContext *latmctx,
3221 GetBitContext *gb)
3222{
3223 int err;
3224 uint8_t use_same_mux = get_bits(gb, 1);
3225 if (!use_same_mux) {
3226 if ((err = read_stream_mux_config(latmctx, gb)) < 0)
3227 return err;
3228 } else if (!latmctx->aac_ctx.avctx->extradata) {
3229 av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
3230 "no decoder config found\n");
984736dd 3231 return 1;
136e19e1
JG
3232 }
3233 if (latmctx->audio_mux_version_A == 0) {
3234 int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
3235 if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
3236 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
3237 return AVERROR_INVALIDDATA;
3238 } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
3239 av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
3240 "frame length mismatch %d << %d\n",
3241 mux_slot_length_bytes * 8, get_bits_left(gb));
3242 return AVERROR_INVALIDDATA;
3243 }
3244 }
3245 return 0;
3246}
3247
3248
0eea2129
JR
3249static int latm_decode_frame(AVCodecContext *avctx, void *out,
3250 int *got_frame_ptr, AVPacket *avpkt)
136e19e1
JG
3251{
3252 struct LATMContext *latmctx = avctx->priv_data;
3253 int muxlength, err;
3254 GetBitContext gb;
3255
71953ebc
LB
3256 if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
3257 return err;
136e19e1
JG
3258
3259 // check for LOAS sync word
3260 if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
3261 return AVERROR_INVALIDDATA;
3262
ebb7f7de 3263 muxlength = get_bits(&gb, 13) + 3;
136e19e1 3264 // not enough data, the parser should have sorted this
ebb7f7de 3265 if (muxlength > avpkt->size)
136e19e1
JG
3266 return AVERROR_INVALIDDATA;
3267
984736dd
AK
3268 if ((err = read_audio_mux_element(latmctx, &gb)))
3269 return (err < 0) ? err : avpkt->size;
136e19e1
JG
3270
3271 if (!latmctx->initialized) {
3272 if (!avctx->extradata) {
0eea2129 3273 *got_frame_ptr = 0;