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