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