]> git.sesse.net Git - ffmpeg/blob - libavcodec/atrac9dec.c
avcodec/atrac9dec: Don't create VLCs that are never used
[ffmpeg] / libavcodec / atrac9dec.c
1 /*
2  * ATRAC9 decoder
3  * Copyright (c) 2018 Rostislav Pehlivanov <atomnuker@gmail.com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "internal.h"
23 #include "get_bits.h"
24 #include "fft.h"
25 #include "atrac9tab.h"
26 #include "libavutil/lfg.h"
27 #include "libavutil/float_dsp.h"
28
29 #define ATRAC9_SF_VLC_BITS 8
30
31 typedef struct ATRAC9ChannelData {
32     int band_ext;
33     int q_unit_cnt;
34     int band_ext_data[4];
35     int32_t scalefactors[31];
36     int32_t scalefactors_prev[31];
37
38     int precision_coarse[30];
39     int precision_fine[30];
40     int precision_mask[30];
41
42     int codebookset[30];
43
44     int32_t q_coeffs_coarse[256];
45     int32_t q_coeffs_fine[256];
46
47     DECLARE_ALIGNED(32, float, coeffs  )[256];
48     DECLARE_ALIGNED(32, float, prev_win)[128];
49 } ATRAC9ChannelData;
50
51 typedef struct ATRAC9BlockData {
52     ATRAC9ChannelData channel[2];
53
54     /* Base */
55     int band_count;
56     int q_unit_cnt;
57     int q_unit_cnt_prev;
58
59     /* Stereo block only */
60     int stereo_q_unit;
61
62     /* Band extension only */
63     int has_band_ext;
64     int has_band_ext_data;
65     int band_ext_q_unit;
66
67     /* Gradient */
68     int grad_mode;
69     int grad_boundary;
70     int gradient[31];
71
72     /* Stereo */
73     int cpe_base_channel;
74     int is_signs[30];
75
76     int reuseable;
77
78 } ATRAC9BlockData;
79
80 typedef struct ATRAC9Context {
81     AVCodecContext *avctx;
82     AVFloatDSPContext *fdsp;
83     FFTContext imdct;
84     ATRAC9BlockData block[5];
85     AVLFG lfg;
86
87     /* Set on init */
88     int frame_log2;
89     int avg_frame_size;
90     int frame_count;
91     int samplerate_idx;
92     const ATRAC9BlockConfig *block_config;
93
94     /* Generated on init */
95     VLC sf_vlc[2][8];            /* Signed/unsigned, length */
96     VLC coeff_vlc[2][8][4];      /* Cookbook, precision, cookbook index */
97     uint8_t alloc_curve[48][48];
98     DECLARE_ALIGNED(32, float, imdct_win)[256];
99
100     DECLARE_ALIGNED(32, float, temp)[256];
101 } ATRAC9Context;
102
103 static inline int parse_gradient(ATRAC9Context *s, ATRAC9BlockData *b,
104                                  GetBitContext *gb)
105 {
106     int grad_range[2];
107     int grad_value[2];
108     int values, sign, base;
109     uint8_t *curve;
110     float scale;
111
112     b->grad_mode = get_bits(gb, 2);
113     if (b->grad_mode) {
114         grad_range[0] = get_bits(gb, 5);
115         grad_range[1] = 31;
116         grad_value[0] = get_bits(gb, 5);
117         grad_value[1] = 31;
118     } else {
119         grad_range[0] = get_bits(gb, 6);
120         grad_range[1] = get_bits(gb, 6) + 1;
121         grad_value[0] = get_bits(gb, 5);
122         grad_value[1] = get_bits(gb, 5);
123     }
124     b->grad_boundary = get_bits(gb, 4);
125
126     if (grad_range[0] >= grad_range[1] || grad_range[1] > 31)
127         return AVERROR_INVALIDDATA;
128
129     if (b->grad_boundary > b->q_unit_cnt)
130         return AVERROR_INVALIDDATA;
131
132     values    = grad_value[1] - grad_value[0];
133     sign      = 1 - 2*(values < 0);
134     base      = grad_value[0] + sign;
135     scale     = (FFABS(values) - 1) / 31.0f;
136     curve     = s->alloc_curve[grad_range[1] - grad_range[0] - 1];
137
138     for (int i = 0; i <= b->q_unit_cnt; i++)
139         b->gradient[i] = grad_value[i >= grad_range[0]];
140
141     for (int i = grad_range[0]; i < grad_range[1]; i++)
142         b->gradient[i] = base + sign*((int)(scale*curve[i - grad_range[0]]));
143
144     return 0;
145 }
146
147 static inline void calc_precision(ATRAC9Context *s, ATRAC9BlockData *b,
148                                   ATRAC9ChannelData *c)
149 {
150     memset(c->precision_mask, 0, sizeof(c->precision_mask));
151     for (int i = 1; i < b->q_unit_cnt; i++) {
152         const int delta = FFABS(c->scalefactors[i] - c->scalefactors[i - 1]) - 1;
153         if (delta > 0) {
154             const int neg = c->scalefactors[i - 1] > c->scalefactors[i];
155             c->precision_mask[i - neg] += FFMIN(delta, 5);
156         }
157     }
158
159     if (b->grad_mode) {
160         for (int i = 0; i < b->q_unit_cnt; i++) {
161             c->precision_coarse[i] = c->scalefactors[i];
162             c->precision_coarse[i] += c->precision_mask[i] - b->gradient[i];
163             if (c->precision_coarse[i] < 0)
164                 continue;
165             switch (b->grad_mode) {
166             case 1:
167                 c->precision_coarse[i] >>= 1;
168                 break;
169             case 2:
170                 c->precision_coarse[i] = (3 * c->precision_coarse[i]) >> 3;
171                 break;
172             case 3:
173                 c->precision_coarse[i] >>= 2;
174                 break;
175             }
176         }
177     } else {
178         for (int i = 0; i < b->q_unit_cnt; i++)
179             c->precision_coarse[i] = c->scalefactors[i] - b->gradient[i];
180     }
181
182
183     for (int i = 0; i < b->q_unit_cnt; i++)
184         c->precision_coarse[i] = FFMAX(c->precision_coarse[i], 1);
185
186     for (int i = 0; i < b->grad_boundary; i++)
187         c->precision_coarse[i]++;
188
189     for (int i = 0; i < b->q_unit_cnt; i++) {
190         c->precision_fine[i] = 0;
191         if (c->precision_coarse[i] > 15) {
192             c->precision_fine[i] = FFMIN(c->precision_coarse[i], 30) - 15;
193             c->precision_coarse[i] = 15;
194         }
195     }
196 }
197
198 static inline int parse_band_ext(ATRAC9Context *s, ATRAC9BlockData *b,
199                                  GetBitContext *gb, int stereo)
200 {
201     int ext_band = 0;
202
203     if (b->has_band_ext) {
204         if (b->q_unit_cnt < 13 || b->q_unit_cnt > 20)
205             return AVERROR_INVALIDDATA;
206         ext_band = at9_tab_band_ext_group[b->q_unit_cnt - 13][2];
207         if (stereo) {
208             b->channel[1].band_ext = get_bits(gb, 2);
209             b->channel[1].band_ext = ext_band > 2 ? b->channel[1].band_ext : 4;
210         } else {
211             skip_bits1(gb);
212         }
213     }
214
215     b->has_band_ext_data = get_bits1(gb);
216     if (!b->has_band_ext_data)
217         return 0;
218
219     if (!b->has_band_ext) {
220         skip_bits(gb, 2);
221         skip_bits_long(gb, get_bits(gb, 5));
222         return 0;
223     }
224
225     b->channel[0].band_ext = get_bits(gb, 2);
226     b->channel[0].band_ext = ext_band > 2 ? b->channel[0].band_ext : 4;
227
228     if (!get_bits(gb, 5)) {
229         for (int i = 0; i <= stereo; i++) {
230             ATRAC9ChannelData *c = &b->channel[i];
231             const int count = at9_tab_band_ext_cnt[c->band_ext][ext_band];
232             for (int j = 0; j < count; j++) {
233                 int len = at9_tab_band_ext_lengths[c->band_ext][ext_band][j];
234                 c->band_ext_data[j] = av_clip_uintp2_c(c->band_ext_data[j], len);
235             }
236         }
237
238         return 0;
239     }
240
241     for (int i = 0; i <= stereo; i++) {
242         ATRAC9ChannelData *c = &b->channel[i];
243         const int count = at9_tab_band_ext_cnt[c->band_ext][ext_band];
244         for (int j = 0; j < count; j++) {
245             int len = at9_tab_band_ext_lengths[c->band_ext][ext_band][j];
246             c->band_ext_data[j] = get_bits(gb, len);
247         }
248     }
249
250     return 0;
251 }
252
253 static inline int read_scalefactors(ATRAC9Context *s, ATRAC9BlockData *b,
254                                     ATRAC9ChannelData *c, GetBitContext *gb,
255                                     int channel_idx, int first_in_pkt)
256 {
257     static const uint8_t mode_map[2][4] = { { 0, 1, 2, 3 }, { 0, 2, 3, 4 } };
258     const int mode = mode_map[channel_idx][get_bits(gb, 2)];
259
260     memset(c->scalefactors, 0, sizeof(c->scalefactors));
261
262     if (first_in_pkt && (mode == 4 || ((mode == 3) && !channel_idx))) {
263         av_log(s->avctx, AV_LOG_ERROR, "Invalid scalefactor coding mode!\n");
264         return AVERROR_INVALIDDATA;
265     }
266
267     switch (mode) {
268     case 0: { /* VLC delta offset */
269         const uint8_t *sf_weights = at9_tab_sf_weights[get_bits(gb, 3)];
270         const int base = get_bits(gb, 5);
271         const int len = get_bits(gb, 2) + 3;
272         const VLC *tab = &s->sf_vlc[0][len];
273
274         c->scalefactors[0] = get_bits(gb, len);
275
276         for (int i = 1; i < b->band_ext_q_unit; i++) {
277             int val = c->scalefactors[i - 1] + get_vlc2(gb, tab->table,
278                                                         ATRAC9_SF_VLC_BITS, 1);
279             c->scalefactors[i] = val & ((1 << len) - 1);
280         }
281
282         for (int i = 0; i < b->band_ext_q_unit; i++)
283             c->scalefactors[i] += base - sf_weights[i];
284
285         break;
286     }
287     case 1: { /* CLC offset */
288         const int len = get_bits(gb, 2) + 2;
289         const int base = len < 5 ? get_bits(gb, 5) : 0;
290         for (int i = 0; i < b->band_ext_q_unit; i++)
291             c->scalefactors[i] = base + get_bits(gb, len);
292         break;
293     }
294     case 2:
295     case 4: { /* VLC dist to baseline */
296         const int *baseline = mode == 4 ? c->scalefactors_prev :
297                               channel_idx ? b->channel[0].scalefactors :
298                               c->scalefactors_prev;
299         const int baseline_len = mode == 4 ? b->q_unit_cnt_prev :
300                                  channel_idx ? b->band_ext_q_unit :
301                                  b->q_unit_cnt_prev;
302
303         const int len = get_bits(gb, 2) + 2;
304         const int unit_cnt = FFMIN(b->band_ext_q_unit, baseline_len);
305         const VLC *tab = &s->sf_vlc[1][len];
306
307         for (int i = 0; i < unit_cnt; i++) {
308             int dist = get_vlc2(gb, tab->table, ATRAC9_SF_VLC_BITS, 1);
309             c->scalefactors[i] = baseline[i] + dist;
310         }
311
312         for (int i = unit_cnt; i < b->band_ext_q_unit; i++)
313             c->scalefactors[i] = get_bits(gb, 5);
314
315         break;
316     }
317     case 3: { /* VLC offset with baseline */
318         const int *baseline = channel_idx ? b->channel[0].scalefactors :
319                               c->scalefactors_prev;
320         const int baseline_len = channel_idx ? b->band_ext_q_unit :
321                                  b->q_unit_cnt_prev;
322
323         const int base = get_bits(gb, 5) - (1 << (5 - 1));
324         const int len = get_bits(gb, 2) + 1;
325         const int unit_cnt = FFMIN(b->band_ext_q_unit, baseline_len);
326         const VLC *tab = &s->sf_vlc[0][len];
327
328         c->scalefactors[0] = get_bits(gb, len);
329
330         for (int i = 1; i < unit_cnt; i++) {
331             int val = c->scalefactors[i - 1] + get_vlc2(gb, tab->table,
332                                                         ATRAC9_SF_VLC_BITS, 1);
333             c->scalefactors[i] = val & ((1 << len) - 1);
334         }
335
336         for (int i = 0; i < unit_cnt; i++)
337             c->scalefactors[i] += base + baseline[i];
338
339         for (int i = unit_cnt; i < b->band_ext_q_unit; i++)
340             c->scalefactors[i] = get_bits(gb, 5);
341         break;
342     }
343     }
344
345     for (int i = 0; i < b->band_ext_q_unit; i++)
346         if (c->scalefactors[i] < 0 || c->scalefactors[i] > 31)
347             return AVERROR_INVALIDDATA;
348
349     memcpy(c->scalefactors_prev, c->scalefactors, sizeof(c->scalefactors));
350
351     return 0;
352 }
353
354 static inline void calc_codebook_idx(ATRAC9Context *s, ATRAC9BlockData *b,
355                                      ATRAC9ChannelData *c)
356 {
357     int avg = 0;
358     const int last_sf = c->scalefactors[c->q_unit_cnt];
359
360     memset(c->codebookset, 0, sizeof(c->codebookset));
361
362     if (c->q_unit_cnt <= 1)
363         return;
364     if (s->samplerate_idx > 7)
365         return;
366
367     c->scalefactors[c->q_unit_cnt] = c->scalefactors[c->q_unit_cnt - 1];
368
369     if (c->q_unit_cnt > 12) {
370         for (int i = 0; i < 12; i++)
371             avg += c->scalefactors[i];
372         avg = (avg + 6) / 12;
373     }
374
375     for (int i = 8; i < c->q_unit_cnt; i++) {
376         const int prev = c->scalefactors[i - 1];
377         const int cur  = c->scalefactors[i    ];
378         const int next = c->scalefactors[i + 1];
379         const int min  = FFMIN(prev, next);
380         if ((cur - min >= 3 || 2*cur - prev - next >= 3))
381             c->codebookset[i] = 1;
382     }
383
384
385     for (int i = 12; i < c->q_unit_cnt; i++) {
386         const int cur = c->scalefactors[i];
387         const int cnd = at9_q_unit_to_coeff_cnt[i] == 16;
388         const int min = FFMIN(c->scalefactors[i + 1], c->scalefactors[i - 1]);
389         if (c->codebookset[i])
390             continue;
391
392         c->codebookset[i] = (((cur - min) >= 2) && (cur >= (avg - cnd)));
393     }
394
395     c->scalefactors[c->q_unit_cnt] = last_sf;
396 }
397
398 static inline void read_coeffs_coarse(ATRAC9Context *s, ATRAC9BlockData *b,
399                                       ATRAC9ChannelData *c, GetBitContext *gb)
400 {
401     const int max_prec = s->samplerate_idx > 7 ? 1 : 7;
402
403     memset(c->q_coeffs_coarse, 0, sizeof(c->q_coeffs_coarse));
404
405     for (int i = 0; i < c->q_unit_cnt; i++) {
406         int *coeffs = &c->q_coeffs_coarse[at9_q_unit_to_coeff_idx[i]];
407         const int bands = at9_q_unit_to_coeff_cnt[i];
408         const int prec = c->precision_coarse[i] + 1;
409
410         if (prec <= max_prec) {
411             const int cb = c->codebookset[i];
412             const int cbi = at9_q_unit_to_codebookidx[i];
413             const VLC *tab = &s->coeff_vlc[cb][prec][cbi];
414             const HuffmanCodebook *huff = &at9_huffman_coeffs[cb][prec][cbi];
415             const int groups = bands >> huff->value_cnt_pow;
416
417             for (int j = 0; j < groups; j++) {
418                 uint16_t val = get_vlc2(gb, tab->table, 9, 2);
419
420                 for (int k = 0; k < huff->value_cnt; k++) {
421                     coeffs[k] = sign_extend(val, huff->value_bits);
422                     val >>= huff->value_bits;
423                 }
424
425                 coeffs += huff->value_cnt;
426             }
427         } else {
428             for (int j = 0; j < bands; j++)
429                 coeffs[j] = sign_extend(get_bits(gb, prec), prec);
430         }
431     }
432 }
433
434 static inline void read_coeffs_fine(ATRAC9Context *s, ATRAC9BlockData *b,
435                                     ATRAC9ChannelData *c, GetBitContext *gb)
436 {
437     memset(c->q_coeffs_fine, 0, sizeof(c->q_coeffs_fine));
438
439     for (int i = 0; i < c->q_unit_cnt; i++) {
440         const int start = at9_q_unit_to_coeff_idx[i + 0];
441         const int end   = at9_q_unit_to_coeff_idx[i + 1];
442         const int len   = c->precision_fine[i] + 1;
443
444         if (c->precision_fine[i] <= 0)
445             continue;
446
447         for (int j = start; j < end; j++)
448             c->q_coeffs_fine[j] = sign_extend(get_bits(gb, len), len);
449     }
450 }
451
452 static inline void dequantize(ATRAC9Context *s, ATRAC9BlockData *b,
453                               ATRAC9ChannelData *c)
454 {
455     memset(c->coeffs, 0, sizeof(c->coeffs));
456
457     for (int i = 0; i < c->q_unit_cnt; i++) {
458         const int start = at9_q_unit_to_coeff_idx[i + 0];
459         const int end   = at9_q_unit_to_coeff_idx[i + 1];
460
461         const float coarse_c = at9_quant_step_coarse[c->precision_coarse[i]];
462         const float fine_c   = at9_quant_step_fine[c->precision_fine[i]];
463
464         for (int j = start; j < end; j++) {
465             const float vc = c->q_coeffs_coarse[j] * coarse_c;
466             const float vf = c->q_coeffs_fine[j]   * fine_c;
467             c->coeffs[j] = vc + vf;
468         }
469     }
470 }
471
472 static inline void apply_intensity_stereo(ATRAC9Context *s, ATRAC9BlockData *b,
473                                           const int stereo)
474 {
475     float *src = b->channel[ b->cpe_base_channel].coeffs;
476     float *dst = b->channel[!b->cpe_base_channel].coeffs;
477
478     if (!stereo)
479         return;
480
481     if (b->q_unit_cnt <= b->stereo_q_unit)
482         return;
483
484     for (int i = b->stereo_q_unit; i < b->q_unit_cnt; i++) {
485         const int sign  = b->is_signs[i];
486         const int start = at9_q_unit_to_coeff_idx[i + 0];
487         const int end   = at9_q_unit_to_coeff_idx[i + 1];
488         for (int j = start; j < end; j++)
489             dst[j] = sign*src[j];
490     }
491 }
492
493 static inline void apply_scalefactors(ATRAC9Context *s, ATRAC9BlockData *b,
494                                       const int stereo)
495 {
496     for (int i = 0; i <= stereo; i++) {
497         float *coeffs = b->channel[i].coeffs;
498         for (int j = 0; j < b->q_unit_cnt; j++) {
499             const int start = at9_q_unit_to_coeff_idx[j + 0];
500             const int end   = at9_q_unit_to_coeff_idx[j + 1];
501             const int scalefactor = b->channel[i].scalefactors[j];
502             const float scale = at9_scalefactor_c[scalefactor];
503             for (int k = start; k < end; k++)
504                 coeffs[k] *= scale;
505         }
506     }
507 }
508
509 static inline void fill_with_noise(ATRAC9Context *s, ATRAC9ChannelData *c,
510                                    int start, int count)
511 {
512     float maxval = 0.0f;
513     for (int i = 0; i < count; i += 2) {
514         double tmp[2];
515         av_bmg_get(&s->lfg, tmp);
516         c->coeffs[start + i + 0] = tmp[0];
517         c->coeffs[start + i + 1] = tmp[1];
518         maxval = FFMAX(FFMAX(FFABS(tmp[0]), FFABS(tmp[1])), maxval);
519     }
520     /* Normalize */
521     for (int i = 0; i < count; i++)
522         c->coeffs[start + i] /= maxval;
523 }
524
525 static inline void scale_band_ext_coeffs(ATRAC9ChannelData *c, float sf[6],
526                                          const int s_unit, const int e_unit)
527 {
528     for (int i = s_unit; i < e_unit; i++) {
529         const int start = at9_q_unit_to_coeff_idx[i + 0];
530         const int end   = at9_q_unit_to_coeff_idx[i + 1];
531         for (int j = start; j < end; j++)
532             c->coeffs[j] *= sf[i - s_unit];
533     }
534 }
535
536 static inline void apply_band_extension(ATRAC9Context *s, ATRAC9BlockData *b,
537                                        const int stereo)
538 {
539     const int g_units[4] = { /* A, B, C, total units */
540         b->q_unit_cnt,
541         at9_tab_band_ext_group[b->q_unit_cnt - 13][0],
542         at9_tab_band_ext_group[b->q_unit_cnt - 13][1],
543         FFMAX(g_units[2], 22),
544     };
545
546     const int g_bins[4] = { /* A, B, C, total bins */
547         at9_q_unit_to_coeff_idx[g_units[0]],
548         at9_q_unit_to_coeff_idx[g_units[1]],
549         at9_q_unit_to_coeff_idx[g_units[2]],
550         at9_q_unit_to_coeff_idx[g_units[3]],
551     };
552
553     for (int ch = 0; ch <= stereo; ch++) {
554         ATRAC9ChannelData *c = &b->channel[ch];
555
556         /* Mirror the spectrum */
557         for (int i = 0; i < 3; i++)
558             for (int j = 0; j < (g_bins[i + 1] - g_bins[i + 0]); j++)
559                 c->coeffs[g_bins[i] + j] = c->coeffs[g_bins[i] - j - 1];
560
561         switch (c->band_ext) {
562         case 0: {
563             float sf[6] = { 0.0f };
564             const int l = g_units[3] - g_units[0] - 1;
565             const int n_start = at9_q_unit_to_coeff_idx[g_units[3] - 1];
566             const int n_cnt   = at9_q_unit_to_coeff_cnt[g_units[3] - 1];
567             switch (at9_tab_band_ext_group[b->q_unit_cnt - 13][2]) {
568             case 3:
569                 sf[0] = at9_band_ext_scales_m0[0][0][c->band_ext_data[0]];
570                 sf[1] = at9_band_ext_scales_m0[0][1][c->band_ext_data[0]];
571                 sf[2] = at9_band_ext_scales_m0[0][2][c->band_ext_data[1]];
572                 sf[3] = at9_band_ext_scales_m0[0][3][c->band_ext_data[2]];
573                 sf[4] = at9_band_ext_scales_m0[0][4][c->band_ext_data[3]];
574                 break;
575             case 4:
576                 sf[0] = at9_band_ext_scales_m0[1][0][c->band_ext_data[0]];
577                 sf[1] = at9_band_ext_scales_m0[1][1][c->band_ext_data[0]];
578                 sf[2] = at9_band_ext_scales_m0[1][2][c->band_ext_data[1]];
579                 sf[3] = at9_band_ext_scales_m0[1][3][c->band_ext_data[2]];
580                 sf[4] = at9_band_ext_scales_m0[1][4][c->band_ext_data[3]];
581                 break;
582             case 5:
583                 sf[0] = at9_band_ext_scales_m0[2][0][c->band_ext_data[0]];
584                 sf[1] = at9_band_ext_scales_m0[2][1][c->band_ext_data[1]];
585                 sf[2] = at9_band_ext_scales_m0[2][2][c->band_ext_data[1]];
586                 break;
587             }
588
589             sf[l] = at9_scalefactor_c[c->scalefactors[g_units[0]]];
590
591             fill_with_noise(s, c, n_start, n_cnt);
592             scale_band_ext_coeffs(c, sf, g_units[0], g_units[3]);
593             break;
594         }
595         case 1: {
596             float sf[6];
597             for (int i = g_units[0]; i < g_units[3]; i++)
598                 sf[i - g_units[0]] = at9_scalefactor_c[c->scalefactors[i]];
599
600             fill_with_noise(s, c, g_bins[0], g_bins[3] - g_bins[0]);
601             scale_band_ext_coeffs(c, sf, g_units[0], g_units[3]);
602             break;
603         }
604         case 2: {
605             const float g_sf[2] = {
606                 at9_band_ext_scales_m2[c->band_ext_data[0]],
607                 at9_band_ext_scales_m2[c->band_ext_data[1]],
608             };
609
610             for (int i = 0; i < 2; i++)
611                 for (int j = g_bins[i + 0]; j < g_bins[i + 1]; j++)
612                     c->coeffs[j] *= g_sf[i];
613             break;
614         }
615         case 3: {
616             float scale = at9_band_ext_scales_m3[c->band_ext_data[0]][0];
617             float rate  = at9_band_ext_scales_m3[c->band_ext_data[1]][1];
618             rate = pow(2, rate);
619             for (int i = g_bins[0]; i < g_bins[3]; i++) {
620                 scale *= rate;
621                 c->coeffs[i] *= scale;
622             }
623             break;
624         }
625         case 4: {
626             const float m = at9_band_ext_scales_m4[c->band_ext_data[0]];
627             const float g_sf[3] = { 0.7079468f*m, 0.5011902f*m, 0.3548279f*m };
628
629             for (int i = 0; i < 3; i++)
630                 for (int j = g_bins[i + 0]; j < g_bins[i + 1]; j++)
631                     c->coeffs[j] *= g_sf[i];
632             break;
633         }
634         }
635     }
636 }
637
638 static int atrac9_decode_block(ATRAC9Context *s, GetBitContext *gb,
639                                ATRAC9BlockData *b, AVFrame *frame,
640                                int frame_idx, int block_idx)
641 {
642     const int first_in_pkt = !get_bits1(gb);
643     const int reuse_params =  get_bits1(gb);
644     const int stereo = s->block_config->type[block_idx] == ATRAC9_BLOCK_TYPE_CPE;
645
646     if (s->block_config->type[block_idx] == ATRAC9_BLOCK_TYPE_LFE) {
647         ATRAC9ChannelData *c = &b->channel[0];
648         const int precision = reuse_params ? 8 : 4;
649         c->q_unit_cnt = b->q_unit_cnt = 2;
650
651         memset(c->scalefactors, 0, sizeof(c->scalefactors));
652         memset(c->q_coeffs_fine, 0, sizeof(c->q_coeffs_fine));
653         memset(c->q_coeffs_coarse, 0, sizeof(c->q_coeffs_coarse));
654
655         for (int i = 0; i < b->q_unit_cnt; i++) {
656             c->scalefactors[i] = get_bits(gb, 5);
657             c->precision_coarse[i] = precision;
658             c->precision_fine[i] = 0;
659         }
660
661         for (int i = 0; i < c->q_unit_cnt; i++) {
662             const int start = at9_q_unit_to_coeff_idx[i + 0];
663             const int end   = at9_q_unit_to_coeff_idx[i + 1];
664             for (int j = start; j < end; j++)
665                 c->q_coeffs_coarse[j] = get_bits(gb, c->precision_coarse[i] + 1);
666         }
667
668         dequantize        (s, b, c);
669         apply_scalefactors(s, b, 0);
670
671         goto imdct;
672     }
673
674     if (first_in_pkt && reuse_params) {
675         av_log(s->avctx, AV_LOG_ERROR, "Invalid block flags!\n");
676         return AVERROR_INVALIDDATA;
677     }
678
679     /* Band parameters */
680     if (!reuse_params) {
681         int stereo_band, ext_band;
682         const int min_band_count = s->samplerate_idx > 7 ? 1 : 3;
683         b->reuseable = 0;
684         b->band_count = get_bits(gb, 4) + min_band_count;
685         b->q_unit_cnt = at9_tab_band_q_unit_map[b->band_count];
686
687         b->band_ext_q_unit = b->stereo_q_unit = b->q_unit_cnt;
688
689         if (b->band_count > at9_tab_sri_max_bands[s->samplerate_idx]) {
690             av_log(s->avctx, AV_LOG_ERROR, "Invalid band count %i!\n",
691                    b->band_count);
692             return AVERROR_INVALIDDATA;
693         }
694
695         if (stereo) {
696             stereo_band = get_bits(gb, 4) + min_band_count;
697             if (stereo_band > b->band_count) {
698                 av_log(s->avctx, AV_LOG_ERROR, "Invalid stereo band %i!\n",
699                        stereo_band);
700                 return AVERROR_INVALIDDATA;
701             }
702             b->stereo_q_unit = at9_tab_band_q_unit_map[stereo_band];
703         }
704
705         b->has_band_ext = get_bits1(gb);
706         if (b->has_band_ext) {
707             ext_band = get_bits(gb, 4) + min_band_count;
708             if (ext_band < b->band_count) {
709                 av_log(s->avctx, AV_LOG_ERROR, "Invalid extension band %i!\n",
710                        ext_band);
711                 return AVERROR_INVALIDDATA;
712             }
713             b->band_ext_q_unit = at9_tab_band_q_unit_map[ext_band];
714         }
715         b->reuseable = 1;
716     }
717     if (!b->reuseable) {
718         av_log(s->avctx, AV_LOG_ERROR, "invalid block reused!\n");
719         return AVERROR_INVALIDDATA;
720     }
721
722     /* Calculate bit alloc gradient */
723     if (parse_gradient(s, b, gb))
724         return AVERROR_INVALIDDATA;
725
726     /* IS data */
727     b->cpe_base_channel = 0;
728     if (stereo) {
729         b->cpe_base_channel = get_bits1(gb);
730         if (get_bits1(gb)) {
731             for (int i = b->stereo_q_unit; i < b->q_unit_cnt; i++)
732                 b->is_signs[i] = 1 - 2*get_bits1(gb);
733         } else {
734             for (int i = 0; i < FF_ARRAY_ELEMS(b->is_signs); i++)
735                 b->is_signs[i] = 1;
736         }
737     }
738
739     /* Band extension */
740     if (parse_band_ext(s, b, gb, stereo))
741         return AVERROR_INVALIDDATA;
742
743     /* Scalefactors */
744     for (int i = 0; i <= stereo; i++) {
745         ATRAC9ChannelData *c = &b->channel[i];
746         c->q_unit_cnt = i == b->cpe_base_channel ? b->q_unit_cnt :
747                                                    b->stereo_q_unit;
748         if (read_scalefactors(s, b, c, gb, i, first_in_pkt))
749             return AVERROR_INVALIDDATA;
750
751         calc_precision    (s, b, c);
752         calc_codebook_idx (s, b, c);
753         read_coeffs_coarse(s, b, c, gb);
754         read_coeffs_fine  (s, b, c, gb);
755         dequantize        (s, b, c);
756     }
757
758     b->q_unit_cnt_prev = b->has_band_ext ? b->band_ext_q_unit : b->q_unit_cnt;
759
760     apply_intensity_stereo(s, b, stereo);
761     apply_scalefactors    (s, b, stereo);
762
763     if (b->has_band_ext && b->has_band_ext_data)
764         apply_band_extension  (s, b, stereo);
765
766 imdct:
767     for (int i = 0; i <= stereo; i++) {
768         ATRAC9ChannelData *c = &b->channel[i];
769         const int dst_idx = s->block_config->plane_map[block_idx][i];
770         const int wsize = 1 << s->frame_log2;
771         const ptrdiff_t offset = wsize*frame_idx*sizeof(float);
772         float *dst = (float *)(frame->extended_data[dst_idx] + offset);
773
774         s->imdct.imdct_half(&s->imdct, s->temp, c->coeffs);
775         s->fdsp->vector_fmul_window(dst, c->prev_win, s->temp,
776                                     s->imdct_win, wsize >> 1);
777         memcpy(c->prev_win, s->temp + (wsize >> 1), sizeof(float)*wsize >> 1);
778     }
779
780     return 0;
781 }
782
783 static int atrac9_decode_frame(AVCodecContext *avctx, void *data,
784                                int *got_frame_ptr, AVPacket *avpkt)
785 {
786     int ret;
787     GetBitContext gb;
788     AVFrame *frame = data;
789     ATRAC9Context *s = avctx->priv_data;
790     const int frames = FFMIN(avpkt->size / s->avg_frame_size, s->frame_count);
791
792     frame->nb_samples = (1 << s->frame_log2) * frames;
793     ret = ff_get_buffer(avctx, frame, 0);
794     if (ret < 0)
795         return ret;
796
797     init_get_bits8(&gb, avpkt->data, avpkt->size);
798
799     for (int i = 0; i < frames; i++) {
800         for (int j = 0; j < s->block_config->count; j++) {
801             ret = atrac9_decode_block(s, &gb, &s->block[j], frame, i, j);
802             if (ret)
803                 return ret;
804             align_get_bits(&gb);
805         }
806     }
807
808     *got_frame_ptr = 1;
809
810     return avctx->block_align;
811 }
812
813 static void atrac9_decode_flush(AVCodecContext *avctx)
814 {
815     ATRAC9Context *s = avctx->priv_data;
816
817     for (int j = 0; j < s->block_config->count; j++) {
818         ATRAC9BlockData *b = &s->block[j];
819         const int stereo = s->block_config->type[j] == ATRAC9_BLOCK_TYPE_CPE;
820         for (int i = 0; i <= stereo; i++) {
821             ATRAC9ChannelData *c = &b->channel[i];
822             memset(c->prev_win, 0, sizeof(c->prev_win));
823         }
824     }
825 }
826
827 static av_cold int atrac9_decode_close(AVCodecContext *avctx)
828 {
829     ATRAC9Context *s = avctx->priv_data;
830
831     for (int i = 1; i < 7; i++)
832         ff_free_vlc(&s->sf_vlc[0][i]);
833     for (int i = 2; i < 6; i++)
834         ff_free_vlc(&s->sf_vlc[1][i]);
835     for (int i = 0; i < 2; i++)
836         for (int j = 0; j < 8; j++)
837             for (int k = 0; k < 4; k++)
838                 ff_free_vlc(&s->coeff_vlc[i][j][k]);
839
840     ff_mdct_end(&s->imdct);
841     av_freep(&s->fdsp);
842
843     return 0;
844 }
845
846 static av_cold int atrac9_decode_init(AVCodecContext *avctx)
847 {
848     GetBitContext gb;
849     ATRAC9Context *s = avctx->priv_data;
850     int version, block_config_idx, superframe_idx, alloc_c_len;
851     const uint8_t (*tab)[2];
852     int ret;
853
854     s->avctx = avctx;
855
856     av_lfg_init(&s->lfg, 0xFBADF00D);
857
858     if (avctx->block_align <= 0) {
859         av_log(avctx, AV_LOG_ERROR, "Invalid block align\n");
860         return AVERROR_INVALIDDATA;
861     }
862
863     if (avctx->extradata_size != 12) {
864         av_log(avctx, AV_LOG_ERROR, "Invalid extradata length!\n");
865         return AVERROR_INVALIDDATA;
866     }
867
868     version = AV_RL32(avctx->extradata);
869     if (version > 2) {
870         av_log(avctx, AV_LOG_ERROR, "Unsupported version (%i)!\n", version);
871         return AVERROR_INVALIDDATA;
872     }
873
874     init_get_bits8(&gb, avctx->extradata + 4, avctx->extradata_size);
875
876     if (get_bits(&gb, 8) != 0xFE) {
877         av_log(avctx, AV_LOG_ERROR, "Incorrect magic byte!\n");
878         return AVERROR_INVALIDDATA;
879     }
880
881     s->samplerate_idx = get_bits(&gb, 4);
882     avctx->sample_rate = at9_tab_samplerates[s->samplerate_idx];
883
884     block_config_idx = get_bits(&gb, 3);
885     if (block_config_idx > 5) {
886         av_log(avctx, AV_LOG_ERROR, "Incorrect block config!\n");
887         return AVERROR_INVALIDDATA;
888     }
889     s->block_config = &at9_block_layout[block_config_idx];
890
891     avctx->channel_layout = s->block_config->channel_layout;
892     avctx->channels       = av_get_channel_layout_nb_channels(avctx->channel_layout);
893     avctx->sample_fmt     = AV_SAMPLE_FMT_FLTP;
894
895     if (get_bits1(&gb)) {
896         av_log(avctx, AV_LOG_ERROR, "Incorrect verification bit!\n");
897         return AVERROR_INVALIDDATA;
898     }
899
900     /* Average frame size in bytes */
901     s->avg_frame_size = get_bits(&gb, 11) + 1;
902
903     superframe_idx = get_bits(&gb, 2);
904     if (superframe_idx & 1) {
905         av_log(avctx, AV_LOG_ERROR, "Invalid superframe index!\n");
906         return AVERROR_INVALIDDATA;
907     }
908
909     s->frame_count = 1 << superframe_idx;
910     s->frame_log2  = at9_tab_sri_frame_log2[s->samplerate_idx];
911
912     if (ff_mdct_init(&s->imdct, s->frame_log2 + 1, 1, 1.0f / 32768.0f))
913         return AVERROR(ENOMEM);
914
915     s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
916     if (!s->fdsp)
917         return AVERROR(ENOMEM);
918
919     /* iMDCT window */
920     for (int i = 0; i < (1 << s->frame_log2); i++) {
921         const int   len  = 1 << s->frame_log2;
922         const float sidx = (      i + 0.5f) / len;
923         const float eidx = (len - i - 0.5f) / len;
924         const float s_c  = sinf(sidx*M_PI - M_PI_2)*0.5f + 0.5f;
925         const float e_c  = sinf(eidx*M_PI - M_PI_2)*0.5f + 0.5f;
926         s->imdct_win[i]  = s_c / ((s_c * s_c) + (e_c * e_c));
927     }
928
929     /* Allocation curve */
930     alloc_c_len = FF_ARRAY_ELEMS(at9_tab_b_dist);
931     for (int i = 1; i <= alloc_c_len; i++)
932         for (int j = 0; j < i; j++)
933             s->alloc_curve[i - 1][j] = at9_tab_b_dist[(j * alloc_c_len) / i];
934
935     /* Unsigned scalefactor VLCs */
936     tab = at9_sfb_a_tab;
937     for (int i = 1; i < 7; i++) {
938         const HuffmanCodebook *hf = &at9_huffman_sf_unsigned[i];
939
940         ret = ff_init_vlc_from_lengths(&s->sf_vlc[0][i], ATRAC9_SF_VLC_BITS,
941                                        hf->size, &tab[0][1], 2,
942                                        &tab[0][0], 2, 1, 0, 0, avctx);
943         if (ret < 0)
944             return ret;
945         tab += hf->size;
946     }
947
948     /* Signed scalefactor VLCs */
949     tab = at9_sfb_b_tab;
950     for (int i = 2; i < 6; i++) {
951         const HuffmanCodebook *hf = &at9_huffman_sf_signed[i];
952
953         /* The symbols are signed integers in the range -16..15;
954          * the values in the source table are offset by 16 to make
955          * them fit into an uint8_t; the -16 reverses this shift. */
956         ret = ff_init_vlc_from_lengths(&s->sf_vlc[1][i], ATRAC9_SF_VLC_BITS,
957                                        hf->size, &tab[0][1], 2,
958                                        &tab[0][0], 2, 1, -16, 0, avctx);
959         if (ret < 0)
960             return ret;
961         tab += hf->size;
962     }
963
964     /* Coefficient VLCs */
965     tab = at9_coeffs_tab;
966     for (int i = 0; i < 2; i++) {
967         for (int j = 2; j < 8; j++) {
968             for (int k = i; k < 4; k++) {
969                 const HuffmanCodebook *hf = &at9_huffman_coeffs[i][j][k];
970                 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i][j][k], 9,
971                                                hf->size, &tab[0][1], 2,
972                                                &tab[0][0], 2, 1, 0, 0, avctx);
973                 if (ret < 0)
974                     return ret;
975                 tab += hf->size;
976             }
977         }
978     }
979
980     return 0;
981 }
982
983 AVCodec ff_atrac9_decoder = {
984     .name           = "atrac9",
985     .long_name      = NULL_IF_CONFIG_SMALL("ATRAC9 (Adaptive TRansform Acoustic Coding 9)"),
986     .type           = AVMEDIA_TYPE_AUDIO,
987     .id             = AV_CODEC_ID_ATRAC9,
988     .priv_data_size = sizeof(ATRAC9Context),
989     .init           = atrac9_decode_init,
990     .close          = atrac9_decode_close,
991     .decode         = atrac9_decode_frame,
992     .flush          = atrac9_decode_flush,
993     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
994     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
995 };