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