2 * Atrac 3 compatible decoder
3 * Copyright (c) 2006-2008 Maxim Poliakovski
4 * Copyright (c) 2006-2008 Benjamin Larsson
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
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.
13 * Libav is distributed in the hope that it will be useful,
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.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * Atrac 3 compatible decoder.
26 * This decoder handles Sony's ATRAC3 data.
28 * Container formats used to store atrac 3 data:
29 * RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3).
31 * To use this decoder, a calling application must supply the extradata
32 * bytes provided in the containers above.
39 #include "libavutil/float_dsp.h"
41 #include "bytestream.h"
43 #include "fmtconvert.h"
48 #include "atrac3data.h"
50 #define JOINT_STEREO 0x12
53 #define SAMPLES_PER_FRAME 1024
56 typedef struct GainInfo {
62 typedef struct GainBlock {
66 typedef struct TonalComponent {
72 typedef struct ChannelUnit {
75 float prev_frame[SAMPLES_PER_FRAME];
77 TonalComponent components[64];
78 GainBlock gain_block[2];
80 DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
81 DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
83 float delay_buf1[46]; ///<qmf delay buffers
88 typedef struct ATRAC3Context {
97 /** joint-stereo related variables */
98 int matrix_coeff_index_prev[4];
99 int matrix_coeff_index_now[4];
100 int matrix_coeff_index_next[4];
101 int weighting_delay[6];
105 uint8_t *decoded_bytes_buffer;
106 float temp_buf[1070];
110 int scrambled_stream;
114 FmtConvertContext fmt_conv;
115 AVFloatDSPContext fdsp;
118 static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
119 static VLC_TYPE atrac3_vlc_table[4096][2];
120 static VLC spectral_coeff_tab[7];
121 static float gain_tab1[16];
122 static float gain_tab2[31];
126 * Regular 512 points IMDCT without overlapping, with the exception of the
127 * swapping of odd bands caused by the reverse spectra of the QMF.
129 * @param odd_band 1 if the band is an odd band
131 static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
137 * Reverse the odd bands before IMDCT, this is an effect of the QMF
138 * transform or it gives better compression to do it this way.
139 * FIXME: It should be possible to handle this in imdct_calc
140 * for that to happen a modification of the prerotation step of
141 * all SIMD code and C code is needed.
142 * Or fix the functions before so they generate a pre reversed spectrum.
144 for (i = 0; i < 128; i++)
145 FFSWAP(float, input[i], input[255 - i]);
148 q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
150 /* Perform windowing on the output. */
151 q->fdsp.vector_fmul(output, output, mdct_window, MDCT_SIZE);
155 * indata descrambling, only used for data coming from the rm container
157 static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
162 uint32_t *output = (uint32_t *)out;
164 off = (intptr_t)input & 3;
165 buf = (const uint32_t *)(input - off);
166 c = av_be2ne32((0x537F6103 >> (off * 8)) | (0x537F6103 << (32 - (off * 8))));
168 for (i = 0; i < bytes / 4; i++)
169 output[i] = c ^ buf[i];
172 av_log_ask_for_sample(NULL, "Offset of %d not handled.\n", off);
177 static av_cold void init_atrac3_window(void)
181 /* generate the mdct window, for details see
182 * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
183 for (i = 0, j = 255; i < 128; i++, j--) {
184 float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
185 float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
186 float w = 0.5 * (wi * wi + wj * wj);
187 mdct_window[i] = mdct_window[511 - i] = wi / w;
188 mdct_window[j] = mdct_window[511 - j] = wj / w;
192 static av_cold int atrac3_decode_close(AVCodecContext *avctx)
194 ATRAC3Context *q = avctx->priv_data;
197 av_free(q->decoded_bytes_buffer);
199 ff_mdct_end(&q->mdct_ctx);
207 * @param selector which table the output values are coded with
208 * @param coding_flag constant length coding or variable length coding
209 * @param mantissas mantissa output table
210 * @param num_codes number of values to get
212 static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
213 int coding_flag, int *mantissas,
216 int i, code, huff_symb;
221 if (coding_flag != 0) {
222 /* constant length coding (CLC) */
223 int num_bits = clc_length_tab[selector];
226 for (i = 0; i < num_codes; i++) {
228 code = get_sbits(gb, num_bits);
234 for (i = 0; i < num_codes; i++) {
236 code = get_bits(gb, num_bits); // num_bits is always 4 in this case
239 mantissas[i * 2 ] = mantissa_clc_tab[code >> 2];
240 mantissas[i * 2 + 1] = mantissa_clc_tab[code & 3];
244 /* variable length coding (VLC) */
246 for (i = 0; i < num_codes; i++) {
247 huff_symb = get_vlc2(gb, spectral_coeff_tab[selector-1].table,
248 spectral_coeff_tab[selector-1].bits, 3);
250 code = huff_symb >> 1;
256 for (i = 0; i < num_codes; i++) {
257 huff_symb = get_vlc2(gb, spectral_coeff_tab[selector - 1].table,
258 spectral_coeff_tab[selector - 1].bits, 3);
259 mantissas[i * 2 ] = mantissa_vlc_tab[huff_symb * 2 ];
260 mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];
267 * Restore the quantized band spectrum coefficients
269 * @return subband count, fix for broken specification/files
271 static int decode_spectrum(GetBitContext *gb, float *output)
273 int num_subbands, coding_mode, i, j, first, last, subband_size;
274 int subband_vlc_index[32], sf_index[32];
278 num_subbands = get_bits(gb, 5); // number of coded subbands
279 coding_mode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
281 /* get the VLC selector table for the subbands, 0 means not coded */
282 for (i = 0; i <= num_subbands; i++)
283 subband_vlc_index[i] = get_bits(gb, 3);
285 /* read the scale factor indexes from the stream */
286 for (i = 0; i <= num_subbands; i++) {
287 if (subband_vlc_index[i] != 0)
288 sf_index[i] = get_bits(gb, 6);
291 for (i = 0; i <= num_subbands; i++) {
292 first = subband_tab[i ];
293 last = subband_tab[i + 1];
295 subband_size = last - first;
297 if (subband_vlc_index[i] != 0) {
298 /* decode spectral coefficients for this subband */
299 /* TODO: This can be done faster is several blocks share the
300 * same VLC selector (subband_vlc_index) */
301 read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,
302 mantissas, subband_size);
304 /* decode the scale factor for this subband */
305 scale_factor = ff_atrac_sf_table[sf_index[i]] *
306 inv_max_quant[subband_vlc_index[i]];
308 /* inverse quantize the coefficients */
309 for (j = 0; first < last; first++, j++)
310 output[first] = mantissas[j] * scale_factor;
312 /* this subband was not coded, so zero the entire subband */
313 memset(output + first, 0, subband_size * sizeof(*output));
317 /* clear the subbands that were not coded */
318 first = subband_tab[i];
319 memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
324 * Restore the quantized tonal components
326 * @param components tonal components
327 * @param num_bands number of coded bands
329 static int decode_tonal_components(GetBitContext *gb,
330 TonalComponent *components, int num_bands)
333 int nb_components, coding_mode_selector, coding_mode;
334 int band_flags[4], mantissa[8];
335 int component_count = 0;
337 nb_components = get_bits(gb, 5);
339 /* no tonal components */
340 if (nb_components == 0)
343 coding_mode_selector = get_bits(gb, 2);
344 if (coding_mode_selector == 2)
345 return AVERROR_INVALIDDATA;
347 coding_mode = coding_mode_selector & 1;
349 for (i = 0; i < nb_components; i++) {
350 int coded_values_per_component, quant_step_index;
352 for (b = 0; b <= num_bands; b++)
353 band_flags[b] = get_bits1(gb);
355 coded_values_per_component = get_bits(gb, 3);
357 quant_step_index = get_bits(gb, 3);
358 if (quant_step_index <= 1)
359 return AVERROR_INVALIDDATA;
361 if (coding_mode_selector == 3)
362 coding_mode = get_bits1(gb);
364 for (b = 0; b < (num_bands + 1) * 4; b++) {
365 int coded_components;
367 if (band_flags[b >> 2] == 0)
370 coded_components = get_bits(gb, 3);
372 for (c = 0; c < coded_components; c++) {
373 TonalComponent *cmp = &components[component_count];
374 int sf_index, coded_values, max_coded_values;
377 sf_index = get_bits(gb, 6);
378 if (component_count >= 64)
379 return AVERROR_INVALIDDATA;
381 cmp->pos = b * 64 + get_bits(gb, 6);
383 max_coded_values = SAMPLES_PER_FRAME - cmp->pos;
384 coded_values = coded_values_per_component + 1;
385 coded_values = FFMIN(max_coded_values, coded_values);
387 scale_factor = ff_atrac_sf_table[sf_index] *
388 inv_max_quant[quant_step_index];
390 read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
391 mantissa, coded_values);
393 cmp->num_coefs = coded_values;
396 for (m = 0; m < coded_values; m++)
397 cmp->coef[m] = mantissa[m] * scale_factor;
404 return component_count;
408 * Decode gain parameters for the coded bands
410 * @param block the gainblock for the current band
411 * @param num_bands amount of coded bands
413 static int decode_gain_control(GetBitContext *gb, GainBlock *block,
419 GainInfo *gain = block->g_block;
421 for (i = 0; i <= num_bands; i++) {
422 num_data = get_bits(gb, 3);
423 gain[i].num_gain_data = num_data;
424 level = gain[i].lev_code;
425 loc = gain[i].loc_code;
427 for (cf = 0; cf < gain[i].num_gain_data; cf++) {
428 level[cf] = get_bits(gb, 4);
429 loc [cf] = get_bits(gb, 5);
430 if (cf && loc[cf] <= loc[cf - 1])
431 return AVERROR_INVALIDDATA;
435 /* Clear the unused blocks. */
437 gain[i].num_gain_data = 0;
443 * Apply gain parameters and perform the MDCT overlapping part
445 * @param input input buffer
446 * @param prev previous buffer to perform overlap against
447 * @param output output buffer
448 * @param gain1 current band gain info
449 * @param gain2 next band gain info
451 static void gain_compensate_and_overlap(float *input, float *prev,
452 float *output, GainInfo *gain1,
455 float g1, g2, gain_inc;
456 int i, j, num_data, start_loc, end_loc;
459 if (gain2->num_gain_data == 0)
462 g1 = gain_tab1[gain2->lev_code[0]];
464 if (gain1->num_gain_data == 0) {
465 for (i = 0; i < 256; i++)
466 output[i] = input[i] * g1 + prev[i];
468 num_data = gain1->num_gain_data;
469 gain1->loc_code[num_data] = 32;
470 gain1->lev_code[num_data] = 4;
472 for (i = 0, j = 0; i < num_data; i++) {
473 start_loc = gain1->loc_code[i] * 8;
474 end_loc = start_loc + 8;
476 g2 = gain_tab1[gain1->lev_code[i]];
477 gain_inc = gain_tab2[gain1->lev_code[i + 1] -
478 gain1->lev_code[i ] + 15];
481 for (; j < start_loc; j++)
482 output[j] = (input[j] * g1 + prev[j]) * g2;
484 /* interpolation is done over eight samples */
485 for (; j < end_loc; j++) {
486 output[j] = (input[j] * g1 + prev[j]) * g2;
492 output[j] = input[j] * g1 + prev[j];
495 /* Delay for the overlapping part. */
496 memcpy(prev, &input[256], 256 * sizeof(*prev));
500 * Combine the tonal band spectrum and regular band spectrum
502 * @param spectrum output spectrum buffer
503 * @param num_components number of tonal components
504 * @param components tonal components for this band
505 * @return position of the last tonal coefficient
507 static int add_tonal_components(float *spectrum, int num_components,
508 TonalComponent *components)
510 int i, j, last_pos = -1;
511 float *input, *output;
513 for (i = 0; i < num_components; i++) {
514 last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
515 input = components[i].coef;
516 output = &spectrum[components[i].pos];
518 for (j = 0; j < components[i].num_coefs; j++)
519 output[j] += input[j];
525 #define INTERPOLATE(old, new, nsample) \
526 ((old) + (nsample) * 0.125 * ((new) - (old)))
528 static void reverse_matrixing(float *su1, float *su2, int *prev_code,
531 int i, nsample, band;
532 float mc1_l, mc1_r, mc2_l, mc2_r;
534 for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
535 int s1 = prev_code[i];
536 int s2 = curr_code[i];
540 /* Selector value changed, interpolation needed. */
541 mc1_l = matrix_coeffs[s1 * 2 ];
542 mc1_r = matrix_coeffs[s1 * 2 + 1];
543 mc2_l = matrix_coeffs[s2 * 2 ];
544 mc2_r = matrix_coeffs[s2 * 2 + 1];
546 /* Interpolation is done over the first eight samples. */
547 for (; nsample < band + 8; nsample++) {
548 float c1 = su1[nsample];
549 float c2 = su2[nsample];
550 c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
551 c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
553 su2[nsample] = c1 * 2.0 - c2;
557 /* Apply the matrix without interpolation. */
559 case 0: /* M/S decoding */
560 for (; nsample < band + 256; nsample++) {
561 float c1 = su1[nsample];
562 float c2 = su2[nsample];
563 su1[nsample] = c2 * 2.0;
564 su2[nsample] = (c1 - c2) * 2.0;
568 for (; nsample < band + 256; nsample++) {
569 float c1 = su1[nsample];
570 float c2 = su2[nsample];
571 su1[nsample] = (c1 + c2) * 2.0;
572 su2[nsample] = c2 * -2.0;
577 for (; nsample < band + 256; nsample++) {
578 float c1 = su1[nsample];
579 float c2 = su2[nsample];
580 su1[nsample] = c1 + c2;
581 su2[nsample] = c1 - c2;
590 static void get_channel_weights(int index, int flag, float ch[2])
596 ch[0] = (index & 7) / 7.0;
597 ch[1] = sqrt(2 - ch[0] * ch[0]);
599 FFSWAP(float, ch[0], ch[1]);
603 static void channel_weighting(float *su1, float *su2, int *p3)
606 /* w[x][y] y=0 is left y=1 is right */
609 if (p3[1] != 7 || p3[3] != 7) {
610 get_channel_weights(p3[1], p3[0], w[0]);
611 get_channel_weights(p3[3], p3[2], w[1]);
613 for (band = 256; band < 4 * 256; band += 256) {
614 for (nsample = band; nsample < band + 8; nsample++) {
615 su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
616 su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
618 for(; nsample < band + 256; nsample++) {
619 su1[nsample] *= w[1][0];
620 su2[nsample] *= w[1][1];
627 * Decode a Sound Unit
629 * @param snd the channel unit to be used
630 * @param output the decoded samples before IQMF in float representation
631 * @param channel_num channel number
632 * @param coding_mode the coding mode (JOINT_STEREO or regular stereo/mono)
634 static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
635 ChannelUnit *snd, float *output,
636 int channel_num, int coding_mode)
638 int band, ret, num_subbands, last_tonal, num_bands;
639 GainBlock *gain1 = &snd->gain_block[ snd->gc_blk_switch];
640 GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
642 if (coding_mode == JOINT_STEREO && channel_num == 1) {
643 if (get_bits(gb, 2) != 3) {
644 av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
645 return AVERROR_INVALIDDATA;
648 if (get_bits(gb, 6) != 0x28) {
649 av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
650 return AVERROR_INVALIDDATA;
654 /* number of coded QMF bands */
655 snd->bands_coded = get_bits(gb, 2);
657 ret = decode_gain_control(gb, gain2, snd->bands_coded);
661 snd->num_components = decode_tonal_components(gb, snd->components,
663 if (snd->num_components == -1)
666 num_subbands = decode_spectrum(gb, snd->spectrum);
668 /* Merge the decoded spectrum and tonal components. */
669 last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
673 /* calculate number of used MLT/QMF bands according to the amount of coded
675 num_bands = (subband_tab[num_subbands] - 1) >> 8;
677 num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
680 /* Reconstruct time domain samples. */
681 for (band = 0; band < 4; band++) {
682 /* Perform the IMDCT step without overlapping. */
683 if (band <= num_bands)
684 imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
686 memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
688 /* gain compensation and overlapping */
689 gain_compensate_and_overlap(snd->imdct_buf,
690 &snd->prev_frame[band * 256],
692 &gain1->g_block[band],
693 &gain2->g_block[band]);
696 /* Swap the gain control buffers for the next frame. */
697 snd->gc_blk_switch ^= 1;
702 static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
705 ATRAC3Context *q = avctx->priv_data;
709 if (q->coding_mode == JOINT_STEREO) {
710 /* channel coupling mode */
711 /* decode Sound Unit 1 */
712 init_get_bits(&q->gb, databuf, avctx->block_align * 8);
714 ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,
719 /* Framedata of the su2 in the joint-stereo mode is encoded in
720 * reverse byte order so we need to swap it first. */
721 if (databuf == q->decoded_bytes_buffer) {
722 uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;
723 ptr1 = q->decoded_bytes_buffer;
724 for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)
725 FFSWAP(uint8_t, *ptr1, *ptr2);
727 const uint8_t *ptr2 = databuf + avctx->block_align - 1;
728 for (i = 0; i < avctx->block_align; i++)
729 q->decoded_bytes_buffer[i] = *ptr2--;
732 /* Skip the sync codes (0xF8). */
733 ptr1 = q->decoded_bytes_buffer;
734 for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
735 if (i >= avctx->block_align)
736 return AVERROR_INVALIDDATA;
740 /* set the bitstream reader at the start of the second Sound Unit*/
741 init_get_bits(&q->gb, ptr1, avctx->block_align * 8);
743 /* Fill the Weighting coeffs delay buffer */
744 memmove(q->weighting_delay, &q->weighting_delay[2],
745 4 * sizeof(*q->weighting_delay));
746 q->weighting_delay[4] = get_bits1(&q->gb);
747 q->weighting_delay[5] = get_bits(&q->gb, 3);
749 for (i = 0; i < 4; i++) {
750 q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
751 q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
752 q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);
755 /* Decode Sound Unit 2. */
756 ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],
757 out_samples[1], 1, JOINT_STEREO);
761 /* Reconstruct the channel coefficients. */
762 reverse_matrixing(out_samples[0], out_samples[1],
763 q->matrix_coeff_index_prev,
764 q->matrix_coeff_index_now);
766 channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
768 /* normal stereo mode or mono */
769 /* Decode the channel sound units. */
770 for (i = 0; i < avctx->channels; i++) {
771 /* Set the bitstream reader at the start of a channel sound unit. */
772 init_get_bits(&q->gb,
773 databuf + i * avctx->block_align / avctx->channels,
774 avctx->block_align * 8 / avctx->channels);
776 ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
777 out_samples[i], i, q->coding_mode);
783 /* Apply the iQMF synthesis filter. */
784 for (i = 0; i < avctx->channels; i++) {
785 float *p1 = out_samples[i];
786 float *p2 = p1 + 256;
787 float *p3 = p2 + 256;
788 float *p4 = p3 + 256;
789 ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
790 ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
791 ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
797 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
798 int *got_frame_ptr, AVPacket *avpkt)
800 AVFrame *frame = data;
801 const uint8_t *buf = avpkt->data;
802 int buf_size = avpkt->size;
803 ATRAC3Context *q = avctx->priv_data;
805 const uint8_t *databuf;
807 if (buf_size < avctx->block_align) {
808 av_log(avctx, AV_LOG_ERROR,
809 "Frame too small (%d bytes). Truncated file?\n", buf_size);
810 return AVERROR_INVALIDDATA;
813 /* get output buffer */
814 frame->nb_samples = SAMPLES_PER_FRAME;
815 if ((ret = ff_get_buffer(avctx, frame)) < 0) {
816 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
820 /* Check if we need to descramble and what buffer to pass on. */
821 if (q->scrambled_stream) {
822 decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
823 databuf = q->decoded_bytes_buffer;
828 ret = decode_frame(avctx, databuf, (float **)frame->extended_data);
830 av_log(NULL, AV_LOG_ERROR, "Frame decoding error!\n");
836 return avctx->block_align;
839 static void atrac3_init_static_data(AVCodec *codec)
843 init_atrac3_window();
844 ff_atrac_generate_tables();
846 /* Initialize the VLC tables. */
847 for (i = 0; i < 7; i++) {
848 spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
849 spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -
851 init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
853 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
856 /* Generate gain tables */
857 for (i = 0; i < 16; i++)
858 gain_tab1[i] = powf(2.0, (4 - i));
860 for (i = -15; i < 16; i++)
861 gain_tab2[i + 15] = powf(2.0, i * -0.125);
864 static av_cold int atrac3_decode_init(AVCodecContext *avctx)
867 int version, delay, samples_per_frame, frame_factor;
868 const uint8_t *edata_ptr = avctx->extradata;
869 ATRAC3Context *q = avctx->priv_data;
871 if (avctx->channels <= 0 || avctx->channels > 2) {
872 av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
873 return AVERROR(EINVAL);
876 /* Take care of the codec-specific extradata. */
877 if (avctx->extradata_size == 14) {
878 /* Parse the extradata, WAV format */
879 av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
880 bytestream_get_le16(&edata_ptr)); // Unknown value always 1
881 edata_ptr += 4; // samples per channel
882 q->coding_mode = bytestream_get_le16(&edata_ptr);
883 av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
884 bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
885 frame_factor = bytestream_get_le16(&edata_ptr); // Unknown always 1
886 av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
887 bytestream_get_le16(&edata_ptr)); // Unknown always 0
890 samples_per_frame = SAMPLES_PER_FRAME * avctx->channels;
893 q->coding_mode = q->coding_mode ? JOINT_STEREO : STEREO;
894 q->scrambled_stream = 0;
896 if (avctx->block_align != 96 * avctx->channels * frame_factor &&
897 avctx->block_align != 152 * avctx->channels * frame_factor &&
898 avctx->block_align != 192 * avctx->channels * frame_factor) {
899 av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
900 "configuration %d/%d/%d\n", avctx->block_align,
901 avctx->channels, frame_factor);
902 return AVERROR_INVALIDDATA;
904 } else if (avctx->extradata_size == 10) {
905 /* Parse the extradata, RM format. */
906 version = bytestream_get_be32(&edata_ptr);
907 samples_per_frame = bytestream_get_be16(&edata_ptr);
908 delay = bytestream_get_be16(&edata_ptr);
909 q->coding_mode = bytestream_get_be16(&edata_ptr);
910 q->scrambled_stream = 1;
913 av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",
914 avctx->extradata_size);
915 return AVERROR(EINVAL);
918 /* Check the extradata */
921 av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
922 return AVERROR_INVALIDDATA;
925 if (samples_per_frame != SAMPLES_PER_FRAME &&
926 samples_per_frame != SAMPLES_PER_FRAME * 2) {
927 av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
929 return AVERROR_INVALIDDATA;
932 if (delay != 0x88E) {
933 av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
935 return AVERROR_INVALIDDATA;
938 if (q->coding_mode == STEREO)
939 av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");
940 else if (q->coding_mode == JOINT_STEREO)
941 av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
943 av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
945 return AVERROR_INVALIDDATA;
948 if (avctx->block_align >= UINT_MAX / 2)
949 return AVERROR(EINVAL);
951 q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
952 FF_INPUT_BUFFER_PADDING_SIZE);
953 if (q->decoded_bytes_buffer == NULL)
954 return AVERROR(ENOMEM);
956 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
958 /* initialize the MDCT transform */
959 if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
960 av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
961 av_freep(&q->decoded_bytes_buffer);
965 /* init the joint-stereo decoding data */
966 q->weighting_delay[0] = 0;
967 q->weighting_delay[1] = 7;
968 q->weighting_delay[2] = 0;
969 q->weighting_delay[3] = 7;
970 q->weighting_delay[4] = 0;
971 q->weighting_delay[5] = 7;
973 for (i = 0; i < 4; i++) {
974 q->matrix_coeff_index_prev[i] = 3;
975 q->matrix_coeff_index_now[i] = 3;
976 q->matrix_coeff_index_next[i] = 3;
979 avpriv_float_dsp_init(&q->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
980 ff_fmt_convert_init(&q->fmt_conv, avctx);
982 q->units = av_mallocz(sizeof(*q->units) * avctx->channels);
984 atrac3_decode_close(avctx);
985 return AVERROR(ENOMEM);
991 AVCodec ff_atrac3_decoder = {
993 .type = AVMEDIA_TYPE_AUDIO,
994 .id = AV_CODEC_ID_ATRAC3,
995 .priv_data_size = sizeof(ATRAC3Context),
996 .init = atrac3_decode_init,
997 .init_static_data = atrac3_init_static_data,
998 .close = atrac3_decode_close,
999 .decode = atrac3_decode_frame,
1000 .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1001 .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
1002 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1003 AV_SAMPLE_FMT_NONE },