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