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