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