GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/atrac9dec.c Lines: 0 529 0.0 %
Date: 2019-11-22 03:34:36 Branches: 0 319 0.0 %

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