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