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