]> git.sesse.net Git - ffmpeg/blob - libavcodec/atrac3.c
parser: Move Doxygen documentation to the header files
[ffmpeg] / libavcodec / atrac3.c
1 /*
2  * Atrac 3 compatible decoder
3  * Copyright (c) 2006-2008 Maxim Poliakovski
4  * Copyright (c) 2006-2008 Benjamin Larsson
5  *
6  * This file is part of Libav.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 /**
24  * @file
25  * Atrac 3 compatible decoder.
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).
30  *
31  * To use this decoder, a calling application must supply the extradata
32  * bytes provided in the containers above.
33  */
34
35 #include <math.h>
36 #include <stddef.h>
37 #include <stdio.h>
38
39 #include "libavutil/float_dsp.h"
40 #include "avcodec.h"
41 #include "bytestream.h"
42 #include "fft.h"
43 #include "fmtconvert.h"
44 #include "get_bits.h"
45
46 #include "atrac.h"
47 #include "atrac3data.h"
48
49 #define JOINT_STEREO    0x12
50 #define STEREO          0x2
51
52 #define SAMPLES_PER_FRAME 1024
53 #define MDCT_SIZE          512
54
55 typedef struct GainInfo {
56     int num_gain_data;
57     int lev_code[8];
58     int loc_code[8];
59 } GainInfo;
60
61 typedef struct GainBlock {
62     GainInfo g_block[4];
63 } GainBlock;
64
65 typedef struct TonalComponent {
66     int pos;
67     int num_coefs;
68     float coef[8];
69 } TonalComponent;
70
71 typedef 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];
78
79     DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
80     DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
81
82     float          delay_buf1[46]; ///<qmf delay buffers
83     float          delay_buf2[46];
84     float          delay_buf3[46];
85 } ChannelUnit;
86
87 typedef struct ATRAC3Context {
88     AVFrame frame;
89     GetBitContext gb;
90     //@{
91     /** stream data */
92     int coding_mode;
93
94     ChannelUnit *units;
95     //@}
96     //@{
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];
102     //@}
103     //@{
104     /** data buffers */
105     uint8_t *decoded_bytes_buffer;
106     float temp_buf[1070];
107     //@}
108     //@{
109     /** extradata */
110     int scrambled_stream;
111     //@}
112
113     FFTContext mdct_ctx;
114     FmtConvertContext fmt_conv;
115     AVFloatDSPContext fdsp;
116 } ATRAC3Context;
117
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];
123
124
125 /*
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.
128  *
129  * @param odd_band  1 if the band is an odd band
130  */
131 static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
132 {
133     int i;
134
135     if (odd_band) {
136         /**
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.
143          */
144         for (i = 0; i < 128; i++)
145             FFSWAP(float, input[i], input[255 - i]);
146     }
147
148     q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
149
150     /* Perform windowing on the output. */
151     q->fdsp.vector_fmul(output, output, mdct_window, MDCT_SIZE);
152 }
153
154 /*
155  * indata descrambling, only used for data coming from the rm container
156  */
157 static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
158 {
159     int i, off;
160     uint32_t c;
161     const uint32_t *buf;
162     uint32_t *output = (uint32_t *)out;
163
164     off = (intptr_t)input & 3;
165     buf = (const uint32_t *)(input - off);
166     c   = av_be2ne32((0x537F6103 >> (off * 8)) | (0x537F6103 << (32 - (off * 8))));
167     bytes += 3 + off;
168     for (i = 0; i < bytes / 4; i++)
169         output[i] = c ^ buf[i];
170
171     if (off)
172         av_log_ask_for_sample(NULL, "Offset of %d not handled.\n", off);
173
174     return off;
175 }
176
177 static av_cold void init_atrac3_window(void)
178 {
179     int i, j;
180
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;
189     }
190 }
191
192 static av_cold int atrac3_decode_close(AVCodecContext *avctx)
193 {
194     ATRAC3Context *q = avctx->priv_data;
195
196     av_free(q->units);
197     av_free(q->decoded_bytes_buffer);
198
199     ff_mdct_end(&q->mdct_ctx);
200
201     return 0;
202 }
203
204 /*
205  * Mantissa decoding
206  *
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
211  */
212 static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
213                                        int coding_flag, int *mantissas,
214                                        int num_codes)
215 {
216     int i, code, huff_symb;
217
218     if (selector == 1)
219         num_codes /= 2;
220
221     if (coding_flag != 0) {
222         /* constant length coding (CLC) */
223         int num_bits = clc_length_tab[selector];
224
225         if (selector > 1) {
226             for (i = 0; i < num_codes; i++) {
227                 if (num_bits)
228                     code = get_sbits(gb, num_bits);
229                 else
230                     code = 0;
231                 mantissas[i] = code;
232             }
233         } else {
234             for (i = 0; i < num_codes; i++) {
235                 if (num_bits)
236                     code = get_bits(gb, num_bits); // num_bits is always 4 in this case
237                 else
238                     code = 0;
239                 mantissas[i * 2    ] = mantissa_clc_tab[code >> 2];
240                 mantissas[i * 2 + 1] = mantissa_clc_tab[code &  3];
241             }
242         }
243     } else {
244         /* variable length coding (VLC) */
245         if (selector != 1) {
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);
249                 huff_symb += 1;
250                 code = huff_symb >> 1;
251                 if (huff_symb & 1)
252                     code = -code;
253                 mantissas[i] = code;
254             }
255         } else {
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];
261             }
262         }
263     }
264 }
265
266 /*
267  * Restore the quantized band spectrum coefficients
268  *
269  * @return subband count, fix for broken specification/files
270  */
271 static int decode_spectrum(GetBitContext *gb, float *output)
272 {
273     int num_subbands, coding_mode, i, j, first, last, subband_size;
274     int subband_vlc_index[32], sf_index[32];
275     int mantissas[128];
276     float scale_factor;
277
278     num_subbands = get_bits(gb, 5);  // number of coded subbands
279     coding_mode  = get_bits1(gb);    // coding Mode: 0 - VLC/ 1-CLC
280
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);
284
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);
289     }
290
291     for (i = 0; i <= num_subbands; i++) {
292         first = subband_tab[i    ];
293         last  = subband_tab[i + 1];
294
295         subband_size = last - first;
296
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);
303
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]];
307
308             /* inverse quantize the coefficients */
309             for (j = 0; first < last; first++, j++)
310                 output[first] = mantissas[j] * scale_factor;
311         } else {
312             /* this subband was not coded, so zero the entire subband */
313             memset(output + first, 0, subband_size * sizeof(*output));
314         }
315     }
316
317     /* clear the subbands that were not coded */
318     first = subband_tab[i];
319     memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
320     return num_subbands;
321 }
322
323 /*
324  * Restore the quantized tonal components
325  *
326  * @param components tonal components
327  * @param num_bands  number of coded bands
328  */
329 static int decode_tonal_components(GetBitContext *gb,
330                                    TonalComponent *components, int num_bands)
331 {
332     int i, b, c, m;
333     int nb_components, coding_mode_selector, coding_mode;
334     int band_flags[4], mantissa[8];
335     int component_count = 0;
336
337     nb_components = get_bits(gb, 5);
338
339     /* no tonal components */
340     if (nb_components == 0)
341         return 0;
342
343     coding_mode_selector = get_bits(gb, 2);
344     if (coding_mode_selector == 2)
345         return AVERROR_INVALIDDATA;
346
347     coding_mode = coding_mode_selector & 1;
348
349     for (i = 0; i < nb_components; i++) {
350         int coded_values_per_component, quant_step_index;
351
352         for (b = 0; b <= num_bands; b++)
353             band_flags[b] = get_bits1(gb);
354
355         coded_values_per_component = get_bits(gb, 3);
356
357         quant_step_index = get_bits(gb, 3);
358         if (quant_step_index <= 1)
359             return AVERROR_INVALIDDATA;
360
361         if (coding_mode_selector == 3)
362             coding_mode = get_bits1(gb);
363
364         for (b = 0; b < (num_bands + 1) * 4; b++) {
365             int coded_components;
366
367             if (band_flags[b >> 2] == 0)
368                 continue;
369
370             coded_components = get_bits(gb, 3);
371
372             for (c = 0; c < coded_components; c++) {
373                 TonalComponent *cmp = &components[component_count];
374                 int sf_index, coded_values, max_coded_values;
375                 float scale_factor;
376
377                 sf_index = get_bits(gb, 6);
378                 if (component_count >= 64)
379                     return AVERROR_INVALIDDATA;
380
381                 cmp->pos = b * 64 + get_bits(gb, 6);
382
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);
386
387                 scale_factor = ff_atrac_sf_table[sf_index] *
388                                inv_max_quant[quant_step_index];
389
390                 read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
391                                            mantissa, coded_values);
392
393                 cmp->num_coefs = coded_values;
394
395                 /* inverse quant */
396                 for (m = 0; m < coded_values; m++)
397                     cmp->coef[m] = mantissa[m] * scale_factor;
398
399                 component_count++;
400             }
401         }
402     }
403
404     return component_count;
405 }
406
407 /*
408  * Decode gain parameters for the coded bands
409  *
410  * @param block      the gainblock for the current band
411  * @param num_bands  amount of coded bands
412  */
413 static int decode_gain_control(GetBitContext *gb, GainBlock *block,
414                                int num_bands)
415 {
416     int i, cf, num_data;
417     int *level, *loc;
418
419     GainInfo *gain = block->g_block;
420
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;
426
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;
432         }
433     }
434
435     /* Clear the unused blocks. */
436     for (; i < 4 ; i++)
437         gain[i].num_gain_data = 0;
438
439     return 0;
440 }
441
442 /*
443  * Apply gain parameters and perform the MDCT overlapping part
444  *
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
450  */
451 static void gain_compensate_and_overlap(float *input, float *prev,
452                                         float *output, GainInfo *gain1,
453                                         GainInfo *gain2)
454 {
455     float g1, g2, gain_inc;
456     int i, j, num_data, start_loc, end_loc;
457
458
459     if (gain2->num_gain_data == 0)
460         g1 = 1.0;
461     else
462         g1 = gain_tab1[gain2->lev_code[0]];
463
464     if (gain1->num_gain_data == 0) {
465         for (i = 0; i < 256; i++)
466             output[i] = input[i] * g1 + prev[i];
467     } else {
468         num_data = gain1->num_gain_data;
469         gain1->loc_code[num_data] = 32;
470         gain1->lev_code[num_data] = 4;
471
472         for (i = 0, j = 0; i < num_data; i++) {
473             start_loc = gain1->loc_code[i] * 8;
474             end_loc   = start_loc + 8;
475
476             g2       = gain_tab1[gain1->lev_code[i]];
477             gain_inc = gain_tab2[gain1->lev_code[i + 1] -
478                                  gain1->lev_code[i    ] + 15];
479
480             /* interpolate */
481             for (; j < start_loc; j++)
482                 output[j] = (input[j] * g1 + prev[j]) * g2;
483
484             /* interpolation is done over eight samples */
485             for (; j < end_loc; j++) {
486                 output[j] = (input[j] * g1 + prev[j]) * g2;
487                 g2 *= gain_inc;
488             }
489         }
490
491         for (; j < 256; j++)
492             output[j] = input[j] * g1 + prev[j];
493     }
494
495     /* Delay for the overlapping part. */
496     memcpy(prev, &input[256], 256 * sizeof(*prev));
497 }
498
499 /*
500  * Combine the tonal band spectrum and regular band spectrum
501  *
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
506  */
507 static int add_tonal_components(float *spectrum, int num_components,
508                                 TonalComponent *components)
509 {
510     int i, j, last_pos = -1;
511     float *input, *output;
512
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];
517
518         for (j = 0; j < components[i].num_coefs; j++)
519             output[i] += input[i];
520     }
521
522     return last_pos;
523 }
524
525 #define INTERPOLATE(old, new, nsample) \
526     ((old) + (nsample) * 0.125 * ((new) - (old)))
527
528 static void reverse_matrixing(float *su1, float *su2, int *prev_code,
529                               int *curr_code)
530 {
531     int i, nsample, band;
532     float mc1_l, mc1_r, mc2_l, mc2_r;
533
534     for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
535         int s1 = prev_code[i];
536         int s2 = curr_code[i];
537         nsample = band;
538
539         if (s1 != s2) {
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];
545
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);
552                 su1[nsample] = c2;
553                 su2[nsample] = c1 * 2.0 - c2;
554             }
555         }
556
557         /* Apply the matrix without interpolation. */
558         switch (s2) {
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;
565             }
566             break;
567         case 1:
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;
573             }
574             break;
575         case 2:
576         case 3:
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;
582             }
583             break;
584         default:
585             assert(0);
586         }
587     }
588 }
589
590 static void get_channel_weights(int index, int flag, float ch[2])
591 {
592     if (index == 7) {
593         ch[0] = 1.0;
594         ch[1] = 1.0;
595     } else {
596         ch[0] = (index & 7) / 7.0;
597         ch[1] = sqrt(2 - ch[0] * ch[0]);
598         if (flag)
599             FFSWAP(float, ch[0], ch[1]);
600     }
601 }
602
603 static void channel_weighting(float *su1, float *su2, int *p3)
604 {
605     int band, nsample;
606     /* w[x][y] y=0 is left y=1 is right */
607     float w[2][2];
608
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]);
612
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);
617             }
618             for(; nsample < band + 256; nsample++) {
619                 su1[nsample] *= w[1][0];
620                 su2[nsample] *= w[1][1];
621             }
622         }
623     }
624 }
625
626 /*
627  * Decode a Sound Unit
628  *
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)
633  */
634 static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
635                                      ChannelUnit *snd, float *output,
636                                      int channel_num, int coding_mode)
637 {
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];
641
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;
646         }
647     } else {
648         if (get_bits(gb, 6) != 0x28) {
649             av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
650             return AVERROR_INVALIDDATA;
651         }
652     }
653
654     /* number of coded QMF bands */
655     snd->bands_coded = get_bits(gb, 2);
656
657     ret = decode_gain_control(gb, gain2, snd->bands_coded);
658     if (ret)
659         return ret;
660
661     snd->num_components = decode_tonal_components(gb, snd->components,
662                                                   snd->bands_coded);
663     if (snd->num_components == -1)
664         return -1;
665
666     num_subbands = decode_spectrum(gb, snd->spectrum);
667
668     /* Merge the decoded spectrum and tonal components. */
669     last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
670                                       snd->components);
671
672
673     /* calculate number of used MLT/QMF bands according to the amount of coded
674        spectral lines */
675     num_bands = (subband_tab[num_subbands] - 1) >> 8;
676     if (last_tonal >= 0)
677         num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
678
679
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);
685         else
686             memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
687
688         /* gain compensation and overlapping */
689         gain_compensate_and_overlap(snd->imdct_buf,
690                                     &snd->prev_frame[band * 256],
691                                     &output[band * 256],
692                                     &gain1->g_block[band],
693                                     &gain2->g_block[band]);
694     }
695
696     /* Swap the gain control buffers for the next frame. */
697     snd->gc_blk_switch ^= 1;
698
699     return 0;
700 }
701
702 static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
703                         float **out_samples)
704 {
705     ATRAC3Context *q = avctx->priv_data;
706     int ret, i;
707     uint8_t *ptr1;
708
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);
713
714         ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,
715                                         JOINT_STEREO);
716         if (ret != 0)
717             return ret;
718
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);
726         } else {
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--;
730         }
731
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;
737         }
738
739
740         /* set the bitstream reader at the start of the second Sound Unit*/
741         init_get_bits(&q->gb, ptr1, avctx->block_align * 8);
742
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);
748
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);
753         }
754
755         /* Decode Sound Unit 2. */
756         ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],
757                                         out_samples[1], 1, JOINT_STEREO);
758         if (ret != 0)
759             return ret;
760
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);
765
766         channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
767     } else {
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);
775
776             ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
777                                             out_samples[i], i, q->coding_mode);
778             if (ret != 0)
779                 return ret;
780         }
781     }
782
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);
792     }
793
794     return 0;
795 }
796
797 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
798                                int *got_frame_ptr, AVPacket *avpkt)
799 {
800     const uint8_t *buf = avpkt->data;
801     int buf_size = avpkt->size;
802     ATRAC3Context *q = avctx->priv_data;
803     int ret;
804     const uint8_t *databuf;
805
806     if (buf_size < avctx->block_align) {
807         av_log(avctx, AV_LOG_ERROR,
808                "Frame too small (%d bytes). Truncated file?\n", buf_size);
809         return AVERROR_INVALIDDATA;
810     }
811
812     /* get output buffer */
813     q->frame.nb_samples = SAMPLES_PER_FRAME;
814     if ((ret = avctx->get_buffer(avctx, &q->frame)) < 0) {
815         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
816         return ret;
817     }
818
819     /* Check if we need to descramble and what buffer to pass on. */
820     if (q->scrambled_stream) {
821         decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
822         databuf = q->decoded_bytes_buffer;
823     } else {
824         databuf = buf;
825     }
826
827     ret = decode_frame(avctx, databuf, (float **)q->frame.extended_data);
828     if (ret) {
829         av_log(NULL, AV_LOG_ERROR, "Frame decoding error!\n");
830         return ret;
831     }
832
833     *got_frame_ptr   = 1;
834     *(AVFrame *)data = q->frame;
835
836     return avctx->block_align;
837 }
838
839 static void atrac3_init_static_data(AVCodec *codec)
840 {
841     int i;
842
843     init_atrac3_window();
844     ff_atrac_generate_tables();
845
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] -
850                                                 atrac3_vlc_offs[i    ];
851         init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
852                  huff_bits[i],  1, 1,
853                  huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
854     }
855
856     /* Generate gain tables */
857     for (i = 0; i < 16; i++)
858         gain_tab1[i] = powf(2.0, (4 - i));
859
860     for (i = -15; i < 16; i++)
861         gain_tab2[i + 15] = powf(2.0, i * -0.125);
862 }
863
864 static av_cold int atrac3_decode_init(AVCodecContext *avctx)
865 {
866     int i, ret;
867     int version, delay, samples_per_frame, frame_factor;
868     const uint8_t *edata_ptr = avctx->extradata;
869     ATRAC3Context *q = avctx->priv_data;
870
871     if (avctx->channels <= 0 || avctx->channels > 2) {
872         av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
873         return AVERROR(EINVAL);
874     }
875
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
888
889         /* setup */
890         samples_per_frame    = SAMPLES_PER_FRAME * avctx->channels;
891         version              = 4;
892         delay                = 0x88E;
893         q->coding_mode       = q->coding_mode ? JOINT_STEREO : STEREO;
894         q->scrambled_stream  = 0;
895
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;
903         }
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;
911
912     } else {
913         av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",
914                avctx->extradata_size);
915         return AVERROR(EINVAL);
916     }
917
918     /* Check the extradata */
919
920     if (version != 4) {
921         av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
922         return AVERROR_INVALIDDATA;
923     }
924
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",
928                samples_per_frame);
929         return AVERROR_INVALIDDATA;
930     }
931
932     if (delay != 0x88E) {
933         av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
934                delay);
935         return AVERROR_INVALIDDATA;
936     }
937
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");
942     else {
943         av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
944                q->coding_mode);
945         return AVERROR_INVALIDDATA;
946     }
947
948     if (avctx->block_align >= UINT_MAX / 2)
949         return AVERROR(EINVAL);
950
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);
955
956     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
957
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);
962         return ret;
963     }
964
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;
972
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;
977     }
978
979     avpriv_float_dsp_init(&q->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
980     ff_fmt_convert_init(&q->fmt_conv, avctx);
981
982     q->units = av_mallocz(sizeof(*q->units) * avctx->channels);
983     if (!q->units) {
984         atrac3_decode_close(avctx);
985         return AVERROR(ENOMEM);
986     }
987
988     avcodec_get_frame_defaults(&q->frame);
989     avctx->coded_frame = &q->frame;
990
991     return 0;
992 }
993
994 AVCodec ff_atrac3_decoder = {
995     .name             = "atrac3",
996     .type             = AVMEDIA_TYPE_AUDIO,
997     .id               = AV_CODEC_ID_ATRAC3,
998     .priv_data_size   = sizeof(ATRAC3Context),
999     .init             = atrac3_decode_init,
1000     .init_static_data = atrac3_init_static_data,
1001     .close            = atrac3_decode_close,
1002     .decode           = atrac3_decode_frame,
1003     .capabilities     = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1004     .long_name        = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
1005     .sample_fmts      = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
1006                                                         AV_SAMPLE_FMT_NONE },
1007 };