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