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