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