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