asvdec: Convert to the new bitstream reader
[libav.git] / libavcodec / atrac3.c
CommitLineData
10e26bc7 1/*
7df9e693 2 * ATRAC3 compatible decoder
d311f8f3
BL
3 * Copyright (c) 2006-2008 Maxim Poliakovski
4 * Copyright (c) 2006-2008 Benjamin Larsson
10e26bc7 5 *
2912e87a 6 * This file is part of Libav.
10e26bc7 7 *
2912e87a 8 * Libav is free software; you can redistribute it and/or
10e26bc7
BL
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
2912e87a 13 * Libav is distributed in the hope that it will be useful,
10e26bc7
BL
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
2912e87a 19 * License along with Libav; if not, write to the Free Software
10e26bc7
BL
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
ba87f080 24 * @file
7df9e693 25 * ATRAC3 compatible decoder.
d311f8f3
BL
26 * This decoder handles Sony's ATRAC3 data.
27 *
7df9e693 28 * Container formats used to store ATRAC3 data:
d311f8f3 29 * RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3).
10e26bc7
BL
30 *
31 * To use this decoder, a calling application must supply the extradata
d311f8f3 32 * bytes provided in the containers above.
10e26bc7
BL
33 */
34
35#include <math.h>
36#include <stddef.h>
37#include <stdio.h>
38
6fee1b90 39#include "libavutil/attributes.h"
d5a7229b 40#include "libavutil/float_dsp.h"
10e26bc7 41#include "avcodec.h"
10e26bc7 42#include "bytestream.h"
1429224b 43#include "fft.h"
e55d5390 44#include "get_bits.h"
594d4d5d 45#include "internal.h"
10e26bc7 46
0e1baede 47#include "atrac.h"
10e26bc7
BL
48#include "atrac3data.h"
49
50#define JOINT_STEREO 0x12
51#define STEREO 0x2
52
c9161385
JR
53#define SAMPLES_PER_FRAME 1024
54#define MDCT_SIZE 512
10e26bc7 55
e55d5390 56typedef struct GainBlock {
79cbac8c 57 AtracGainInfo g_block[4];
e55d5390
JR
58} GainBlock;
59
60typedef struct TonalComponent {
61 int pos;
62 int num_coefs;
63 float coef[8];
64} TonalComponent;
65
66typedef struct ChannelUnit {
67 int bands_coded;
68 int num_components;
69 float prev_frame[SAMPLES_PER_FRAME];
70 int gc_blk_switch;
71 TonalComponent components[64];
72 GainBlock gain_block[2];
10e26bc7 73
c9161385 74 DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
e55d5390 75 DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
10e26bc7 76
e55d5390
JR
77 float delay_buf1[46]; ///<qmf delay buffers
78 float delay_buf2[46];
79 float delay_buf3[46];
80} ChannelUnit;
10e26bc7 81
e55d5390 82typedef struct ATRAC3Context {
e55d5390 83 GetBitContext gb;
10e26bc7
BL
84 //@{
85 /** stream data */
e55d5390 86 int coding_mode;
e55d5390 87
e55d5390 88 ChannelUnit *units;
10e26bc7
BL
89 //@}
90 //@{
91 /** joint-stereo related variables */
e55d5390
JR
92 int matrix_coeff_index_prev[4];
93 int matrix_coeff_index_now[4];
94 int matrix_coeff_index_next[4];
95 int weighting_delay[6];
10e26bc7
BL
96 //@}
97 //@{
98 /** data buffers */
e55d5390
JR
99 uint8_t *decoded_bytes_buffer;
100 float temp_buf[1070];
10e26bc7
BL
101 //@}
102 //@{
103 /** extradata */
e55d5390 104 int scrambled_stream;
10e26bc7 105 //@}
a28cccf6 106
79cbac8c 107 AtracGCContext gainc_ctx;
e55d5390 108 FFTContext mdct_ctx;
e55d5390 109 AVFloatDSPContext fdsp;
10e26bc7
BL
110} ATRAC3Context;
111
c9161385 112static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
5d1007f7 113static VLC_TYPE atrac3_vlc_table[4096][2];
e55d5390 114static VLC spectral_coeff_tab[7];
10e26bc7 115
5ce04c14 116/**
e55d5390
JR
117 * Regular 512 points IMDCT without overlapping, with the exception of the
118 * swapping of odd bands caused by the reverse spectra of the QMF.
10e26bc7 119 *
10e26bc7 120 * @param odd_band 1 if the band is an odd band
10e26bc7 121 */
e55d5390 122static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
10e26bc7 123{
e55d5390 124 int i;
10e26bc7
BL
125
126 if (odd_band) {
127 /**
e55d5390
JR
128 * Reverse the odd bands before IMDCT, this is an effect of the QMF
129 * transform or it gives better compression to do it this way.
130 * FIXME: It should be possible to handle this in imdct_calc
131 * for that to happen a modification of the prerotation step of
132 * all SIMD code and C code is needed.
133 * Or fix the functions before so they generate a pre reversed spectrum.
134 */
135 for (i = 0; i < 128; i++)
136 FFSWAP(float, input[i], input[255 - i]);
10e26bc7
BL
137 }
138
e55d5390 139 q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
10e26bc7
BL
140
141 /* Perform windowing on the output. */
e55d5390 142 q->fdsp.vector_fmul(output, output, mdct_window, MDCT_SIZE);
10e26bc7
BL
143}
144
e55d5390
JR
145/*
146 * indata descrambling, only used for data coming from the rm container
10e26bc7 147 */
e55d5390
JR
148static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
149{
10e26bc7
BL
150 int i, off;
151 uint32_t c;
e55d5390
JR
152 const uint32_t *buf;
153 uint32_t *output = (uint32_t *)out;
10e26bc7 154
e55d5390
JR
155 off = (intptr_t)input & 3;
156 buf = (const uint32_t *)(input - off);
eba1ff31
XW
157 if (off)
158 c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
159 else
160 c = av_be2ne32(0x537F6103U);
10e26bc7 161 bytes += 3 + off;
e55d5390
JR
162 for (i = 0; i < bytes / 4; i++)
163 output[i] = c ^ buf[i];
10e26bc7
BL
164
165 if (off)
6d97484d 166 avpriv_request_sample(NULL, "Offset of %d", off);
10e26bc7
BL
167
168 return off;
169}
170
ed796fba 171static av_cold void init_imdct_window(void)
e55d5390 172{
327747de 173 int i, j;
10e26bc7 174
e55d5390 175 /* generate the mdct window, for details see
10e26bc7 176 * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
327747de
JR
177 for (i = 0, j = 255; i < 128; i++, j--) {
178 float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
179 float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
180 float w = 0.5 * (wi * wi + wj * wj);
181 mdct_window[i] = mdct_window[511 - i] = wi / w;
182 mdct_window[j] = mdct_window[511 - j] = wj / w;
e55d5390 183 }
10e26bc7
BL
184}
185
5ef251e5 186static av_cold int atrac3_decode_close(AVCodecContext *avctx)
10e26bc7
BL
187{
188 ATRAC3Context *q = avctx->priv_data;
189
e55d5390 190 av_free(q->units);
10e26bc7 191 av_free(q->decoded_bytes_buffer);
5e76b8bb 192
a28cccf6 193 ff_mdct_end(&q->mdct_ctx);
10e26bc7
BL
194
195 return 0;
196}
197
5ce04c14 198/**
e55d5390 199 * Mantissa decoding
10e26bc7 200 *
e55d5390
JR
201 * @param selector which table the output values are coded with
202 * @param coding_flag constant length coding or variable length coding
203 * @param mantissas mantissa output table
204 * @param num_codes number of values to get
10e26bc7 205 */
e55d5390
JR
206static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
207 int coding_flag, int *mantissas,
208 int num_codes)
10e26bc7 209{
e55d5390 210 int i, code, huff_symb;
10e26bc7
BL
211
212 if (selector == 1)
e55d5390 213 num_codes /= 2;
10e26bc7 214
e55d5390 215 if (coding_flag != 0) {
10e26bc7 216 /* constant length coding (CLC) */
e55d5390 217 int num_bits = clc_length_tab[selector];
10e26bc7
BL
218
219 if (selector > 1) {
e55d5390
JR
220 for (i = 0; i < num_codes; i++) {
221 if (num_bits)
222 code = get_sbits(gb, num_bits);
10e26bc7
BL
223 else
224 code = 0;
e55d5390 225 mantissas[i] = code;
10e26bc7
BL
226 }
227 } else {
e55d5390
JR
228 for (i = 0; i < num_codes; i++) {
229 if (num_bits)
230 code = get_bits(gb, num_bits); // num_bits is always 4 in this case
10e26bc7
BL
231 else
232 code = 0;
e55d5390
JR
233 mantissas[i * 2 ] = mantissa_clc_tab[code >> 2];
234 mantissas[i * 2 + 1] = mantissa_clc_tab[code & 3];
10e26bc7
BL
235 }
236 }
237 } else {
238 /* variable length coding (VLC) */
239 if (selector != 1) {
e55d5390
JR
240 for (i = 0; i < num_codes; i++) {
241 huff_symb = get_vlc2(gb, spectral_coeff_tab[selector-1].table,
242 spectral_coeff_tab[selector-1].bits, 3);
243 huff_symb += 1;
244 code = huff_symb >> 1;
245 if (huff_symb & 1)
10e26bc7 246 code = -code;
e55d5390 247 mantissas[i] = code;
10e26bc7
BL
248 }
249 } else {
e55d5390
JR
250 for (i = 0; i < num_codes; i++) {
251 huff_symb = get_vlc2(gb, spectral_coeff_tab[selector - 1].table,
252 spectral_coeff_tab[selector - 1].bits, 3);
253 mantissas[i * 2 ] = mantissa_vlc_tab[huff_symb * 2 ];
254 mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];
10e26bc7
BL
255 }
256 }
257 }
258}
259
5ce04c14 260/**
10e26bc7
BL
261 * Restore the quantized band spectrum coefficients
262 *
e55d5390 263 * @return subband count, fix for broken specification/files
10e26bc7 264 */
e55d5390 265static int decode_spectrum(GetBitContext *gb, float *output)
10e26bc7 266{
e55d5390
JR
267 int num_subbands, coding_mode, i, j, first, last, subband_size;
268 int subband_vlc_index[32], sf_index[32];
269 int mantissas[128];
270 float scale_factor;
271
272 num_subbands = get_bits(gb, 5); // number of coded subbands
273 coding_mode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
274
275 /* get the VLC selector table for the subbands, 0 means not coded */
276 for (i = 0; i <= num_subbands; i++)
277 subband_vlc_index[i] = get_bits(gb, 3);
278
279 /* read the scale factor indexes from the stream */
280 for (i = 0; i <= num_subbands; i++) {
281 if (subband_vlc_index[i] != 0)
282 sf_index[i] = get_bits(gb, 6);
10e26bc7
BL
283 }
284
e55d5390
JR
285 for (i = 0; i <= num_subbands; i++) {
286 first = subband_tab[i ];
287 last = subband_tab[i + 1];
10e26bc7 288
e55d5390 289 subband_size = last - first;
10e26bc7 290
e55d5390
JR
291 if (subband_vlc_index[i] != 0) {
292 /* decode spectral coefficients for this subband */
10e26bc7
BL
293 /* TODO: This can be done faster is several blocks share the
294 * same VLC selector (subband_vlc_index) */
e55d5390
JR
295 read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,
296 mantissas, subband_size);
10e26bc7 297
e55d5390
JR
298 /* decode the scale factor for this subband */
299 scale_factor = ff_atrac_sf_table[sf_index[i]] *
300 inv_max_quant[subband_vlc_index[i]];
10e26bc7 301
e55d5390
JR
302 /* inverse quantize the coefficients */
303 for (j = 0; first < last; first++, j++)
304 output[first] = mantissas[j] * scale_factor;
10e26bc7 305 } else {
e55d5390 306 /* this subband was not coded, so zero the entire subband */
89a6c32b 307 memset(output + first, 0, subband_size * sizeof(*output));
10e26bc7
BL
308 }
309 }
310
e55d5390
JR
311 /* clear the subbands that were not coded */
312 first = subband_tab[i];
89a6c32b 313 memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
e55d5390 314 return num_subbands;
10e26bc7
BL
315}
316
5ce04c14 317/**
10e26bc7
BL
318 * Restore the quantized tonal components
319 *
e55d5390
JR
320 * @param components tonal components
321 * @param num_bands number of coded bands
10e26bc7 322 */
e55d5390
JR
323static int decode_tonal_components(GetBitContext *gb,
324 TonalComponent *components, int num_bands)
10e26bc7 325{
e55d5390
JR
326 int i, b, c, m;
327 int nb_components, coding_mode_selector, coding_mode;
328 int band_flags[4], mantissa[8];
329 int component_count = 0;
10e26bc7 330
e55d5390 331 nb_components = get_bits(gb, 5);
10e26bc7
BL
332
333 /* no tonal components */
e55d5390 334 if (nb_components == 0)
10e26bc7
BL
335 return 0;
336
e55d5390 337 coding_mode_selector = get_bits(gb, 2);
10e26bc7 338 if (coding_mode_selector == 2)
8f98577d 339 return AVERROR_INVALIDDATA;
10e26bc7
BL
340
341 coding_mode = coding_mode_selector & 1;
342
e55d5390
JR
343 for (i = 0; i < nb_components; i++) {
344 int coded_values_per_component, quant_step_index;
345
346 for (b = 0; b <= num_bands; b++)
347 band_flags[b] = get_bits1(gb);
10e26bc7 348
e55d5390 349 coded_values_per_component = get_bits(gb, 3);
10e26bc7 350
e55d5390 351 quant_step_index = get_bits(gb, 3);
10e26bc7 352 if (quant_step_index <= 1)
8f98577d 353 return AVERROR_INVALIDDATA;
10e26bc7
BL
354
355 if (coding_mode_selector == 3)
356 coding_mode = get_bits1(gb);
357
e55d5390
JR
358 for (b = 0; b < (num_bands + 1) * 4; b++) {
359 int coded_components;
360
361 if (band_flags[b >> 2] == 0)
10e26bc7
BL
362 continue;
363
e55d5390
JR
364 coded_components = get_bits(gb, 3);
365
366 for (c = 0; c < coded_components; c++) {
367 TonalComponent *cmp = &components[component_count];
368 int sf_index, coded_values, max_coded_values;
369 float scale_factor;
10e26bc7 370
e55d5390 371 sf_index = get_bits(gb, 6);
c509f4f7
MN
372 if (component_count >= 64)
373 return AVERROR_INVALIDDATA;
10e26bc7 374
e55d5390
JR
375 cmp->pos = b * 64 + get_bits(gb, 6);
376
377 max_coded_values = SAMPLES_PER_FRAME - cmp->pos;
378 coded_values = coded_values_per_component + 1;
379 coded_values = FFMIN(max_coded_values, coded_values);
10e26bc7 380
e55d5390
JR
381 scale_factor = ff_atrac_sf_table[sf_index] *
382 inv_max_quant[quant_step_index];
10e26bc7 383
e55d5390
JR
384 read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
385 mantissa, coded_values);
386
387 cmp->num_coefs = coded_values;
10e26bc7
BL
388
389 /* inverse quant */
e55d5390
JR
390 for (m = 0; m < coded_values; m++)
391 cmp->coef[m] = mantissa[m] * scale_factor;
10e26bc7
BL
392
393 component_count++;
394 }
395 }
396 }
397
b8c4a515 398 return component_count;
10e26bc7
BL
399}
400
5ce04c14 401/**
10e26bc7
BL
402 * Decode gain parameters for the coded bands
403 *
e55d5390
JR
404 * @param block the gainblock for the current band
405 * @param num_bands amount of coded bands
10e26bc7 406 */
e55d5390
JR
407static int decode_gain_control(GetBitContext *gb, GainBlock *block,
408 int num_bands)
10e26bc7 409{
79cbac8c 410 int i, j;
e55d5390
JR
411 int *level, *loc;
412
79cbac8c 413 AtracGainInfo *gain = block->g_block;
e55d5390
JR
414
415 for (i = 0; i <= num_bands; i++) {
79cbac8c 416 gain[i].num_points = get_bits(gb, 3);
e55d5390
JR
417 level = gain[i].lev_code;
418 loc = gain[i].loc_code;
419
79cbac8c 420 for (j = 0; j < gain[i].num_points; j++) {
be0b4c70
DB
421 level[j] = get_bits(gb, 4);
422 loc[j] = get_bits(gb, 5);
423 if (j && loc[j] <= loc[j - 1])
8f98577d 424 return AVERROR_INVALIDDATA;
10e26bc7
BL
425 }
426 }
427
428 /* Clear the unused blocks. */
e55d5390 429 for (; i < 4 ; i++)
79cbac8c 430 gain[i].num_points = 0;
10e26bc7
BL
431
432 return 0;
433}
434
5ce04c14 435/**
10e26bc7
BL
436 * Combine the tonal band spectrum and regular band spectrum
437 *
e55d5390
JR
438 * @param spectrum output spectrum buffer
439 * @param num_components number of tonal components
440 * @param components tonal components for this band
441 * @return position of the last tonal coefficient
10e26bc7 442 */
e55d5390
JR
443static int add_tonal_components(float *spectrum, int num_components,
444 TonalComponent *components)
10e26bc7 445{
e55d5390
JR
446 int i, j, last_pos = -1;
447 float *input, *output;
10e26bc7 448
e55d5390
JR
449 for (i = 0; i < num_components; i++) {
450 last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
451 input = components[i].coef;
452 output = &spectrum[components[i].pos];
10e26bc7 453
e55d5390 454 for (j = 0; j < components[i].num_coefs; j++)
0e3afacd 455 output[j] += input[j];
10e26bc7 456 }
9d278d88 457
e55d5390 458 return last_pos;
10e26bc7
BL
459}
460
e55d5390
JR
461#define INTERPOLATE(old, new, nsample) \
462 ((old) + (nsample) * 0.125 * ((new) - (old)))
10e26bc7 463
e55d5390
JR
464static void reverse_matrixing(float *su1, float *su2, int *prev_code,
465 int *curr_code)
10e26bc7 466{
e55d5390
JR
467 int i, nsample, band;
468 float mc1_l, mc1_r, mc2_l, mc2_r;
10e26bc7 469
e55d5390
JR
470 for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
471 int s1 = prev_code[i];
472 int s2 = curr_code[i];
aefdb735 473 nsample = band;
10e26bc7
BL
474
475 if (s1 != s2) {
476 /* Selector value changed, interpolation needed. */
e55d5390
JR
477 mc1_l = matrix_coeffs[s1 * 2 ];
478 mc1_r = matrix_coeffs[s1 * 2 + 1];
479 mc2_l = matrix_coeffs[s2 * 2 ];
480 mc2_r = matrix_coeffs[s2 * 2 + 1];
10e26bc7
BL
481
482 /* Interpolation is done over the first eight samples. */
aefdb735
JR
483 for (; nsample < band + 8; nsample++) {
484 float c1 = su1[nsample];
485 float c2 = su2[nsample];
486 c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
487 c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
488 su1[nsample] = c2;
489 su2[nsample] = c1 * 2.0 - c2;
10e26bc7
BL
490 }
491 }
492
493 /* Apply the matrix without interpolation. */
494 switch (s2) {
e55d5390 495 case 0: /* M/S decoding */
aefdb735
JR
496 for (; nsample < band + 256; nsample++) {
497 float c1 = su1[nsample];
498 float c2 = su2[nsample];
499 su1[nsample] = c2 * 2.0;
500 su2[nsample] = (c1 - c2) * 2.0;
e55d5390
JR
501 }
502 break;
503 case 1:
aefdb735
JR
504 for (; nsample < band + 256; nsample++) {
505 float c1 = su1[nsample];
506 float c2 = su2[nsample];
507 su1[nsample] = (c1 + c2) * 2.0;
508 su2[nsample] = c2 * -2.0;
e55d5390
JR
509 }
510 break;
511 case 2:
512 case 3:
aefdb735
JR
513 for (; nsample < band + 256; nsample++) {
514 float c1 = su1[nsample];
515 float c2 = su2[nsample];
516 su1[nsample] = c1 + c2;
517 su2[nsample] = c1 - c2;
e55d5390
JR
518 }
519 break;
520 default:
521 assert(0);
10e26bc7
BL
522 }
523 }
524}
525
e55d5390
JR
526static void get_channel_weights(int index, int flag, float ch[2])
527{
528 if (index == 7) {
10e26bc7
BL
529 ch[0] = 1.0;
530 ch[1] = 1.0;
531 } else {
e55d5390
JR
532 ch[0] = (index & 7) / 7.0;
533 ch[1] = sqrt(2 - ch[0] * ch[0]);
534 if (flag)
10e26bc7
BL
535 FFSWAP(float, ch[0], ch[1]);
536 }
537}
538
e55d5390 539static void channel_weighting(float *su1, float *su2, int *p3)
10e26bc7 540{
e55d5390 541 int band, nsample;
10e26bc7
BL
542 /* w[x][y] y=0 is left y=1 is right */
543 float w[2][2];
544
e55d5390
JR
545 if (p3[1] != 7 || p3[3] != 7) {
546 get_channel_weights(p3[1], p3[0], w[0]);
547 get_channel_weights(p3[3], p3[2], w[1]);
10e26bc7 548
aefdb735
JR
549 for (band = 256; band < 4 * 256; band += 256) {
550 for (nsample = band; nsample < band + 8; nsample++) {
551 su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
552 su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
10e26bc7 553 }
aefdb735
JR
554 for(; nsample < band + 256; nsample++) {
555 su1[nsample] *= w[1][0];
556 su2[nsample] *= w[1][1];
10e26bc7
BL
557 }
558 }
559 }
560}
561
5ce04c14 562/**
10e26bc7
BL
563 * Decode a Sound Unit
564 *
e55d5390
JR
565 * @param snd the channel unit to be used
566 * @param output the decoded samples before IQMF in float representation
567 * @param channel_num channel number
568 * @param coding_mode the coding mode (JOINT_STEREO or regular stereo/mono)
10e26bc7 569 */
e55d5390
JR
570static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
571 ChannelUnit *snd, float *output,
572 int channel_num, int coding_mode)
10e26bc7 573{
e55d5390
JR
574 int band, ret, num_subbands, last_tonal, num_bands;
575 GainBlock *gain1 = &snd->gain_block[ snd->gc_blk_switch];
576 GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
10e26bc7 577
e55d5390
JR
578 if (coding_mode == JOINT_STEREO && channel_num == 1) {
579 if (get_bits(gb, 2) != 3) {
10e26bc7 580 av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
8f98577d 581 return AVERROR_INVALIDDATA;
10e26bc7
BL
582 }
583 } else {
e55d5390 584 if (get_bits(gb, 6) != 0x28) {
10e26bc7 585 av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
8f98577d 586 return AVERROR_INVALIDDATA;
10e26bc7
BL
587 }
588 }
589
590 /* number of coded QMF bands */
e55d5390 591 snd->bands_coded = get_bits(gb, 2);
10e26bc7 592
e55d5390
JR
593 ret = decode_gain_control(gb, gain2, snd->bands_coded);
594 if (ret)
595 return ret;
10e26bc7 596
e55d5390
JR
597 snd->num_components = decode_tonal_components(gb, snd->components,
598 snd->bands_coded);
874c8a17
LB
599 if (snd->num_components < 0)
600 return snd->num_components;
10e26bc7 601
e55d5390 602 num_subbands = decode_spectrum(gb, snd->spectrum);
10e26bc7
BL
603
604 /* Merge the decoded spectrum and tonal components. */
e55d5390
JR
605 last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
606 snd->components);
10e26bc7
BL
607
608
e55d5390
JR
609 /* calculate number of used MLT/QMF bands according to the amount of coded
610 spectral lines */
611 num_bands = (subband_tab[num_subbands] - 1) >> 8;
612 if (last_tonal >= 0)
613 num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
10e26bc7
BL
614
615
616 /* Reconstruct time domain samples. */
e55d5390 617 for (band = 0; band < 4; band++) {
10e26bc7 618 /* Perform the IMDCT step without overlapping. */
e55d5390
JR
619 if (band <= num_bands)
620 imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
621 else
89a6c32b 622 memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
10e26bc7
BL
623
624 /* gain compensation and overlapping */
79cbac8c
MP
625 ff_atrac_gain_compensation(&q->gainc_ctx, snd->imdct_buf,
626 &snd->prev_frame[band * 256],
627 &gain1->g_block[band], &gain2->g_block[band],
628 256, &output[band * 256]);
10e26bc7
BL
629 }
630
631 /* Swap the gain control buffers for the next frame. */
e55d5390 632 snd->gc_blk_switch ^= 1;
10e26bc7
BL
633
634 return 0;
635}
636
5ac673b5 637static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
e55d5390 638 float **out_samples)
10e26bc7 639{
5ac673b5 640 ATRAC3Context *q = avctx->priv_data;
e55d5390 641 int ret, i;
15ae1959 642 uint8_t *ptr1;
10e26bc7 643
e55d5390 644 if (q->coding_mode == JOINT_STEREO) {
10e26bc7
BL
645 /* channel coupling mode */
646 /* decode Sound Unit 1 */
cdd0e0de 647 init_get_bits(&q->gb, databuf, avctx->block_align * 8);
10e26bc7 648
e55d5390
JR
649 ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,
650 JOINT_STEREO);
651 if (ret != 0)
652 return ret;
10e26bc7
BL
653
654 /* Framedata of the su2 in the joint-stereo mode is encoded in
655 * reverse byte order so we need to swap it first. */
15ae1959 656 if (databuf == q->decoded_bytes_buffer) {
cdd0e0de 657 uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;
e55d5390 658 ptr1 = q->decoded_bytes_buffer;
cdd0e0de 659 for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)
e55d5390 660 FFSWAP(uint8_t, *ptr1, *ptr2);
15ae1959 661 } else {
cdd0e0de
JR
662 const uint8_t *ptr2 = databuf + avctx->block_align - 1;
663 for (i = 0; i < avctx->block_align; i++)
15ae1959
AJ
664 q->decoded_bytes_buffer[i] = *ptr2--;
665 }
10e26bc7
BL
666
667 /* Skip the sync codes (0xF8). */
15ae1959 668 ptr1 = q->decoded_bytes_buffer;
10e26bc7 669 for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
cdd0e0de 670 if (i >= avctx->block_align)
8f98577d 671 return AVERROR_INVALIDDATA;
10e26bc7
BL
672 }
673
674
675 /* set the bitstream reader at the start of the second Sound Unit*/
22e76ec6 676 init_get_bits(&q->gb, ptr1, (avctx->block_align - i) * 8);
10e26bc7
BL
677
678 /* Fill the Weighting coeffs delay buffer */
89a6c32b
JR
679 memmove(q->weighting_delay, &q->weighting_delay[2],
680 4 * sizeof(*q->weighting_delay));
5fc32c27 681 q->weighting_delay[4] = get_bits1(&q->gb);
e55d5390 682 q->weighting_delay[5] = get_bits(&q->gb, 3);
10e26bc7
BL
683
684 for (i = 0; i < 4; i++) {
685 q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
e55d5390
JR
686 q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
687 q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);
10e26bc7
BL
688 }
689
690 /* Decode Sound Unit 2. */
e55d5390
JR
691 ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],
692 out_samples[1], 1, JOINT_STEREO);
693 if (ret != 0)
694 return ret;
10e26bc7
BL
695
696 /* Reconstruct the channel coefficients. */
e55d5390
JR
697 reverse_matrixing(out_samples[0], out_samples[1],
698 q->matrix_coeff_index_prev,
699 q->matrix_coeff_index_now);
10e26bc7 700
e55d5390 701 channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
10e26bc7
BL
702 } else {
703 /* normal stereo mode or mono */
704 /* Decode the channel sound units. */
5ac673b5 705 for (i = 0; i < avctx->channels; i++) {
10e26bc7 706 /* Set the bitstream reader at the start of a channel sound unit. */
ee41963f 707 init_get_bits(&q->gb,
cdd0e0de
JR
708 databuf + i * avctx->block_align / avctx->channels,
709 avctx->block_align * 8 / avctx->channels);
10e26bc7 710
e55d5390
JR
711 ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
712 out_samples[i], i, q->coding_mode);
713 if (ret != 0)
714 return ret;
10e26bc7
BL
715 }
716 }
717
718 /* Apply the iQMF synthesis filter. */
5ac673b5 719 for (i = 0; i < avctx->channels; i++) {
e55d5390
JR
720 float *p1 = out_samples[i];
721 float *p2 = p1 + 256;
722 float *p3 = p2 + 256;
723 float *p4 = p3 + 256;
724 ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
725 ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
726 ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
10e26bc7
BL
727 }
728
729 return 0;
730}
731
0eea2129
JR
732static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
733 int *got_frame_ptr, AVPacket *avpkt)
734{
9a75ace2 735 AVFrame *frame = data;
7a00bbad
TB
736 const uint8_t *buf = avpkt->data;
737 int buf_size = avpkt->size;
10e26bc7 738 ATRAC3Context *q = avctx->priv_data;
e55d5390
JR
739 int ret;
740 const uint8_t *databuf;
10e26bc7 741
46a76dec
VS
742 if (buf_size < avctx->block_align) {
743 av_log(avctx, AV_LOG_ERROR,
744 "Frame too small (%d bytes). Truncated file?\n", buf_size);
1fead73d 745 return AVERROR_INVALIDDATA;
46a76dec 746 }
10e26bc7 747
0eea2129 748 /* get output buffer */
9a75ace2 749 frame->nb_samples = SAMPLES_PER_FRAME;
759001c5 750 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
0eea2129 751 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
e55d5390 752 return ret;
7e4881a2
JR
753 }
754
10e26bc7
BL
755 /* Check if we need to descramble and what buffer to pass on. */
756 if (q->scrambled_stream) {
757 decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
758 databuf = q->decoded_bytes_buffer;
759 } else {
760 databuf = buf;
761 }
762
9a75ace2 763 ret = decode_frame(avctx, databuf, (float **)frame->extended_data);
e55d5390
JR
764 if (ret) {
765 av_log(NULL, AV_LOG_ERROR, "Frame decoding error!\n");
766 return ret;
10e26bc7
BL
767 }
768
9a75ace2 769 *got_frame_ptr = 1;
10e26bc7
BL
770
771 return avctx->block_align;
772}
773
6fee1b90 774static av_cold void atrac3_init_static_data(AVCodec *codec)
5d1007f7
JR
775{
776 int i;
777
ed796fba 778 init_imdct_window();
5d1007f7
JR
779 ff_atrac_generate_tables();
780
781 /* Initialize the VLC tables. */
782 for (i = 0; i < 7; i++) {
783 spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
784 spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -
785 atrac3_vlc_offs[i ];
786 init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
787 huff_bits[i], 1, 1,
788 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
789 }
5d1007f7
JR
790}
791
5ef251e5 792static av_cold int atrac3_decode_init(AVCodecContext *avctx)
10e26bc7 793{
47b61702 794 int i, ret;
c51311b9 795 int version, delay, samples_per_frame, frame_factor;
8687f767 796 const uint8_t *edata_ptr = avctx->extradata;
10e26bc7
BL
797 ATRAC3Context *q = avctx->priv_data;
798
5ac673b5
JR
799 if (avctx->channels <= 0 || avctx->channels > 2) {
800 av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
801 return AVERROR(EINVAL);
802 }
803
10e26bc7
BL
804 /* Take care of the codec-specific extradata. */
805 if (avctx->extradata_size == 14) {
806 /* Parse the extradata, WAV format */
e55d5390
JR
807 av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
808 bytestream_get_le16(&edata_ptr)); // Unknown value always 1
7c1f93af 809 edata_ptr += 4; // samples per channel
e55d5390
JR
810 q->coding_mode = bytestream_get_le16(&edata_ptr);
811 av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
812 bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
c51311b9 813 frame_factor = bytestream_get_le16(&edata_ptr); // Unknown always 1
e55d5390
JR
814 av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
815 bytestream_get_le16(&edata_ptr)); // Unknown always 0
10e26bc7
BL
816
817 /* setup */
a2664c91 818 samples_per_frame = SAMPLES_PER_FRAME * avctx->channels;
56a9d2b4 819 version = 4;
64ebbb8f 820 delay = 0x88E;
e55d5390
JR
821 q->coding_mode = q->coding_mode ? JOINT_STEREO : STEREO;
822 q->scrambled_stream = 0;
823
c51311b9
JR
824 if (avctx->block_align != 96 * avctx->channels * frame_factor &&
825 avctx->block_align != 152 * avctx->channels * frame_factor &&
826 avctx->block_align != 192 * avctx->channels * frame_factor) {
e55d5390 827 av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
cdd0e0de 828 "configuration %d/%d/%d\n", avctx->block_align,
c51311b9 829 avctx->channels, frame_factor);
8f98577d 830 return AVERROR_INVALIDDATA;
10e26bc7 831 }
10e26bc7
BL
832 } else if (avctx->extradata_size == 10) {
833 /* Parse the extradata, RM format. */
56a9d2b4 834 version = bytestream_get_be32(&edata_ptr);
a2664c91 835 samples_per_frame = bytestream_get_be16(&edata_ptr);
64ebbb8f 836 delay = bytestream_get_be16(&edata_ptr);
e55d5390 837 q->coding_mode = bytestream_get_be16(&edata_ptr);
e55d5390 838 q->scrambled_stream = 1;
10e26bc7
BL
839
840 } else {
e55d5390
JR
841 av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",
842 avctx->extradata_size);
44d854a5 843 return AVERROR(EINVAL);
10e26bc7 844 }
10e26bc7 845
e55d5390
JR
846 /* Check the extradata */
847
56a9d2b4
JR
848 if (version != 4) {
849 av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
8f98577d 850 return AVERROR_INVALIDDATA;
10e26bc7
BL
851 }
852
a2664c91
JR
853 if (samples_per_frame != SAMPLES_PER_FRAME &&
854 samples_per_frame != SAMPLES_PER_FRAME * 2) {
e55d5390 855 av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
a2664c91 856 samples_per_frame);
8f98577d 857 return AVERROR_INVALIDDATA;
10e26bc7
BL
858 }
859
64ebbb8f 860 if (delay != 0x88E) {
e55d5390 861 av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
64ebbb8f 862 delay);
8f98577d 863 return AVERROR_INVALIDDATA;
10e26bc7
BL
864 }
865
e55d5390
JR
866 if (q->coding_mode == STEREO)
867 av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");
50cf5a7f
LB
868 else if (q->coding_mode == JOINT_STEREO) {
869 if (avctx->channels != 2)
870 return AVERROR_INVALIDDATA;
e55d5390 871 av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
50cf5a7f 872 } else {
e55d5390
JR
873 av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
874 q->coding_mode);
8f98577d 875 return AVERROR_INVALIDDATA;
10e26bc7
BL
876 }
877
e55d5390 878 if (avctx->block_align >= UINT_MAX / 2)
8f98577d 879 return AVERROR(EINVAL);
10e26bc7 880
a1f4cd37 881 q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
059a9348 882 AV_INPUT_BUFFER_PADDING_SIZE);
f929ab05 883 if (!q->decoded_bytes_buffer)
6611c0b4 884 return AVERROR(ENOMEM);
10e26bc7 885
9af4eaa8 886 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
20732246 887
78edce3f
JR
888 /* initialize the MDCT transform */
889 if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
47b61702
JR
890 av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
891 av_freep(&q->decoded_bytes_buffer);
892 return ret;
893 }
10e26bc7 894
10e26bc7
BL
895 /* init the joint-stereo decoding data */
896 q->weighting_delay[0] = 0;
897 q->weighting_delay[1] = 7;
898 q->weighting_delay[2] = 0;
899 q->weighting_delay[3] = 7;
900 q->weighting_delay[4] = 0;
901 q->weighting_delay[5] = 7;
902
e55d5390 903 for (i = 0; i < 4; i++) {
10e26bc7 904 q->matrix_coeff_index_prev[i] = 3;
e55d5390 905 q->matrix_coeff_index_now[i] = 3;
10e26bc7
BL
906 q->matrix_coeff_index_next[i] = 3;
907 }
908
79cbac8c 909 ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);
7c6eb0a1 910 avpriv_float_dsp_init(&q->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
10e26bc7 911
89a6c32b 912 q->units = av_mallocz(sizeof(*q->units) * avctx->channels);
e55d5390 913 if (!q->units) {
47b61702 914 atrac3_decode_close(avctx);
6654296c
PI
915 return AVERROR(ENOMEM);
916 }
10e26bc7
BL
917
918 return 0;
919}
920
e55d5390
JR
921AVCodec ff_atrac3_decoder = {
922 .name = "atrac3",
7df9e693 923 .long_name = NULL_IF_CONFIG_SMALL("ATRAC3 (Adaptive TRansform Acoustic Coding 3)"),
e55d5390
JR
924 .type = AVMEDIA_TYPE_AUDIO,
925 .id = AV_CODEC_ID_ATRAC3,
926 .priv_data_size = sizeof(ATRAC3Context),
927 .init = atrac3_decode_init,
5d1007f7 928 .init_static_data = atrac3_init_static_data,
e55d5390
JR
929 .close = atrac3_decode_close,
930 .decode = atrac3_decode_frame,
def97856 931 .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
e55d5390
JR
932 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
933 AV_SAMPLE_FMT_NONE },
10e26bc7 934};