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