GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/atrac3plus.c Lines: 594 838 70.9 %
Date: 2019-11-22 03:34:36 Branches: 403 658 61.2 %

Line Branch Exec Source
1
/*
2
 * ATRAC3+ compatible decoder
3
 *
4
 * Copyright (c) 2010-2013 Maxim Poliakovski
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
23
/**
24
 * @file
25
 * Bitstream parser for ATRAC3+ decoder.
26
 */
27
28
#include "libavutil/avassert.h"
29
#include "avcodec.h"
30
#include "get_bits.h"
31
#include "atrac3plus.h"
32
#include "atrac3plus_data.h"
33
34
static VLC_TYPE tables_data[154276][2];
35
static VLC wl_vlc_tabs[4];
36
static VLC sf_vlc_tabs[8];
37
static VLC ct_vlc_tabs[4];
38
static VLC spec_vlc_tabs[112];
39
static VLC gain_vlc_tabs[11];
40
static VLC tone_vlc_tabs[7];
41
42
/**
43
 * Generate canonical VLC table from given descriptor.
44
 *
45
 * @param[in]     cb          ptr to codebook descriptor
46
 * @param[in]     xlat        ptr to translation table or NULL
47
 * @param[in,out] tab_offset  starting offset to the generated vlc table
48
 * @param[out]    out_vlc     ptr to vlc table to be generated
49
 */
50
420
static av_cold void build_canonical_huff(const uint8_t *cb, const uint8_t *xlat,
51
                                         int *tab_offset, VLC *out_vlc)
52
{
53
    int i, b;
54
    uint16_t codes[256];
55
    uint8_t bits[256];
56
420
    unsigned code = 0;
57
420
    int index = 0;
58
420
    int min_len = *cb++; // get shortest codeword length
59
420
    int max_len = *cb++; // get longest  codeword length
60
61
3792
    for (b = min_len; b <= max_len; b++) {
62
39320
        for (i = *cb++; i > 0; i--) {
63
35948
            av_assert0(index < 256);
64
35948
            bits[index]  = b;
65
35948
            codes[index] = code++;
66
35948
            index++;
67
        }
68
3372
        code <<= 1;
69
    }
70
71
420
    out_vlc->table = &tables_data[*tab_offset];
72
420
    out_vlc->table_allocated = 1 << max_len;
73
74
420
    ff_init_vlc_sparse(out_vlc, max_len, index, bits, 1, 1, codes, 2, 2,
75
                       xlat, 1, 1, INIT_VLC_USE_NEW_STATIC);
76
77
420
    *tab_offset += 1 << max_len;
78
420
}
79
80
4
av_cold void ff_atrac3p_init_vlcs(void)
81
{
82
    int i, wl_vlc_offs, ct_vlc_offs, sf_vlc_offs, tab_offset;
83
84
    static const uint8_t wl_nb_bits[4]  = { 2, 3, 5, 5 };
85
    static const uint8_t wl_nb_codes[4] = { 3, 5, 8, 8 };
86
    static const uint8_t * const wl_bits[4] = {
87
        atrac3p_wl_huff_bits1, atrac3p_wl_huff_bits2,
88
        atrac3p_wl_huff_bits3, atrac3p_wl_huff_bits4
89
    };
90
    static const uint8_t * const wl_codes[4] = {
91
        atrac3p_wl_huff_code1, atrac3p_wl_huff_code2,
92
        atrac3p_wl_huff_code3, atrac3p_wl_huff_code4
93
    };
94
    static const uint8_t * const wl_xlats[4] = {
95
        atrac3p_wl_huff_xlat1, atrac3p_wl_huff_xlat2, NULL, NULL
96
    };
97
98
    static const uint8_t ct_nb_bits[4]  = { 3, 4, 4, 4 };
99
    static const uint8_t ct_nb_codes[4] = { 4, 8, 8, 8 };
100
    static const uint8_t * const ct_bits[4]  = {
101
        atrac3p_ct_huff_bits1, atrac3p_ct_huff_bits2,
102
        atrac3p_ct_huff_bits2, atrac3p_ct_huff_bits3
103
    };
104
    static const uint8_t * const ct_codes[4] = {
105
        atrac3p_ct_huff_code1, atrac3p_ct_huff_code2,
106
        atrac3p_ct_huff_code2, atrac3p_ct_huff_code3
107
    };
108
    static const uint8_t * const ct_xlats[4] = {
109
        NULL, NULL, atrac3p_ct_huff_xlat1, NULL
110
    };
111
112
    static const uint8_t sf_nb_bits[8]  = {  9,  9,  9,  9,  6,  6,  7,  7 };
113
    static const uint8_t sf_nb_codes[8] = { 64, 64, 64, 64, 16, 16, 16, 16 };
114
    static const uint8_t  * const sf_bits[8]  = {
115
        atrac3p_sf_huff_bits1, atrac3p_sf_huff_bits1, atrac3p_sf_huff_bits2,
116
        atrac3p_sf_huff_bits3, atrac3p_sf_huff_bits4, atrac3p_sf_huff_bits4,
117
        atrac3p_sf_huff_bits5, atrac3p_sf_huff_bits6
118
    };
119
    static const uint16_t * const sf_codes[8] = {
120
        atrac3p_sf_huff_code1, atrac3p_sf_huff_code1, atrac3p_sf_huff_code2,
121
        atrac3p_sf_huff_code3, atrac3p_sf_huff_code4, atrac3p_sf_huff_code4,
122
        atrac3p_sf_huff_code5, atrac3p_sf_huff_code6
123
    };
124
    static const uint8_t  * const sf_xlats[8] = {
125
        atrac3p_sf_huff_xlat1, atrac3p_sf_huff_xlat2, NULL, NULL,
126
        atrac3p_sf_huff_xlat4, atrac3p_sf_huff_xlat5, NULL, NULL
127
    };
128
129
    static const uint8_t * const gain_cbs[11] = {
130
        atrac3p_huff_gain_npoints1_cb, atrac3p_huff_gain_npoints1_cb,
131
        atrac3p_huff_gain_lev1_cb, atrac3p_huff_gain_lev2_cb,
132
        atrac3p_huff_gain_lev3_cb, atrac3p_huff_gain_lev4_cb,
133
        atrac3p_huff_gain_loc3_cb, atrac3p_huff_gain_loc1_cb,
134
        atrac3p_huff_gain_loc4_cb, atrac3p_huff_gain_loc2_cb,
135
        atrac3p_huff_gain_loc5_cb
136
    };
137
    static const uint8_t * const gain_xlats[11] = {
138
        NULL, atrac3p_huff_gain_npoints2_xlat, atrac3p_huff_gain_lev1_xlat,
139
        atrac3p_huff_gain_lev2_xlat, atrac3p_huff_gain_lev3_xlat,
140
        atrac3p_huff_gain_lev4_xlat, atrac3p_huff_gain_loc3_xlat,
141
        atrac3p_huff_gain_loc1_xlat, atrac3p_huff_gain_loc4_xlat,
142
        atrac3p_huff_gain_loc2_xlat, atrac3p_huff_gain_loc5_xlat
143
    };
144
145
    static const uint8_t * const tone_cbs[7] = {
146
        atrac3p_huff_tonebands_cb,  atrac3p_huff_numwavs1_cb,
147
        atrac3p_huff_numwavs2_cb,   atrac3p_huff_wav_ampsf1_cb,
148
        atrac3p_huff_wav_ampsf2_cb, atrac3p_huff_wav_ampsf3_cb,
149
        atrac3p_huff_freq_cb
150
    };
151
    static const uint8_t * const tone_xlats[7] = {
152
        NULL, NULL, atrac3p_huff_numwavs2_xlat, atrac3p_huff_wav_ampsf1_xlat,
153
        atrac3p_huff_wav_ampsf2_xlat, atrac3p_huff_wav_ampsf3_xlat,
154
        atrac3p_huff_freq_xlat
155
    };
156
157
20
    for (i = 0, wl_vlc_offs = 0, ct_vlc_offs = 2508; i < 4; i++) {
158
16
        wl_vlc_tabs[i].table = &tables_data[wl_vlc_offs];
159
16
        wl_vlc_tabs[i].table_allocated = 1 << wl_nb_bits[i];
160
16
        ct_vlc_tabs[i].table = &tables_data[ct_vlc_offs];
161
16
        ct_vlc_tabs[i].table_allocated = 1 << ct_nb_bits[i];
162
163
16
        ff_init_vlc_sparse(&wl_vlc_tabs[i], wl_nb_bits[i], wl_nb_codes[i],
164
16
                           wl_bits[i],  1, 1,
165
16
                           wl_codes[i], 1, 1,
166
16
                           wl_xlats[i], 1, 1,
167
                           INIT_VLC_USE_NEW_STATIC);
168
169
16
        ff_init_vlc_sparse(&ct_vlc_tabs[i], ct_nb_bits[i], ct_nb_codes[i],
170
16
                           ct_bits[i],  1, 1,
171
16
                           ct_codes[i], 1, 1,
172
16
                           ct_xlats[i], 1, 1,
173
                           INIT_VLC_USE_NEW_STATIC);
174
175
16
        wl_vlc_offs += wl_vlc_tabs[i].table_allocated;
176
16
        ct_vlc_offs += ct_vlc_tabs[i].table_allocated;
177
    }
178
179
36
    for (i = 0, sf_vlc_offs = 76; i < 8; i++) {
180
32
        sf_vlc_tabs[i].table = &tables_data[sf_vlc_offs];
181
32
        sf_vlc_tabs[i].table_allocated = 1 << sf_nb_bits[i];
182
183
32
        ff_init_vlc_sparse(&sf_vlc_tabs[i], sf_nb_bits[i], sf_nb_codes[i],
184
32
                           sf_bits[i],  1, 1,
185
32
                           sf_codes[i], 2, 2,
186
32
                           sf_xlats[i], 1, 1,
187
                           INIT_VLC_USE_NEW_STATIC);
188
32
        sf_vlc_offs += sf_vlc_tabs[i].table_allocated;
189
    }
190
191
4
    tab_offset = 2564;
192
193
    /* build huffman tables for spectrum decoding */
194
452
    for (i = 0; i < 112; i++) {
195
448
        if (atrac3p_spectra_tabs[i].cb)
196
348
            build_canonical_huff(atrac3p_spectra_tabs[i].cb,
197
                                 atrac3p_spectra_tabs[i].xlat,
198
                                 &tab_offset, &spec_vlc_tabs[i]);
199
        else
200
100
            spec_vlc_tabs[i].table = 0;
201
    }
202
203
    /* build huffman tables for gain data decoding */
204
48
    for (i = 0; i < 11; i++)
205
44
        build_canonical_huff(gain_cbs[i], gain_xlats[i], &tab_offset, &gain_vlc_tabs[i]);
206
207
    /* build huffman tables for tone decoding */
208
32
    for (i = 0; i < 7; i++)
209
28
        build_canonical_huff(tone_cbs[i], tone_xlats[i], &tab_offset, &tone_vlc_tabs[i]);
210
4
}
211
212
/**
213
 * Decode number of coded quantization units.
214
 *
215
 * @param[in]     gb            the GetBit context
216
 * @param[in,out] chan          ptr to the channel parameters
217
 * @param[in,out] ctx           ptr to the channel unit context
218
 * @param[in]     avctx         ptr to the AVCodecContext
219
 * @return result code: 0 = OK, otherwise - error code
220
 */
221
724
static int num_coded_units(GetBitContext *gb, Atrac3pChanParams *chan,
222
                           Atrac3pChanUnitCtx *ctx, AVCodecContext *avctx)
223
{
224
724
    chan->fill_mode = get_bits(gb, 2);
225
724
    if (!chan->fill_mode) {
226
155
        chan->num_coded_vals = ctx->num_quant_units;
227
    } else {
228
569
        chan->num_coded_vals = get_bits(gb, 5);
229
569
        if (chan->num_coded_vals > ctx->num_quant_units) {
230
            av_log(avctx, AV_LOG_ERROR,
231
                   "Invalid number of transmitted units!\n");
232
            return AVERROR_INVALIDDATA;
233
        }
234
235
569
        if (chan->fill_mode == 3)
236
134
            chan->split_point = get_bits(gb, 2) + (chan->ch_num << 1) + 1;
237
    }
238
239
724
    return 0;
240
}
241
242
/**
243
 * Add weighting coefficients to the decoded word-length information.
244
 *
245
 * @param[in,out] ctx           ptr to the channel unit context
246
 * @param[in,out] chan          ptr to the channel parameters
247
 * @param[in]     wtab_idx      index of the table of weights
248
 * @param[in]     avctx         ptr to the AVCodecContext
249
 * @return result code: 0 = OK, otherwise - error code
250
 */
251
110
static int add_wordlen_weights(Atrac3pChanUnitCtx *ctx,
252
                               Atrac3pChanParams *chan, int wtab_idx,
253
                               AVCodecContext *avctx)
254
{
255
    int i;
256
110
    const int8_t *weights_tab =
257
110
        &atrac3p_wl_weights[chan->ch_num * 3 + wtab_idx - 1][0];
258
259
2970
    for (i = 0; i < ctx->num_quant_units; i++) {
260
2860
        chan->qu_wordlen[i] += weights_tab[i];
261

2860
        if (chan->qu_wordlen[i] < 0 || chan->qu_wordlen[i] > 7) {
262
            av_log(avctx, AV_LOG_ERROR,
263
                   "WL index out of range: pos=%d, val=%d!\n",
264
                   i, chan->qu_wordlen[i]);
265
            return AVERROR_INVALIDDATA;
266
        }
267
    }
268
269
110
    return 0;
270
}
271
272
/**
273
 * Subtract weighting coefficients from decoded scalefactors.
274
 *
275
 * @param[in,out] ctx           ptr to the channel unit context
276
 * @param[in,out] chan          ptr to the channel parameters
277
 * @param[in]     wtab_idx      index of table of weights
278
 * @param[in]     avctx         ptr to the AVCodecContext
279
 * @return result code: 0 = OK, otherwise - error code
280
 */
281
144
static int subtract_sf_weights(Atrac3pChanUnitCtx *ctx,
282
                               Atrac3pChanParams *chan, int wtab_idx,
283
                               AVCodecContext *avctx)
284
{
285
    int i;
286
144
    const int8_t *weights_tab = &atrac3p_sf_weights[wtab_idx - 1][0];
287
288
3888
    for (i = 0; i < ctx->used_quant_units; i++) {
289
3744
        chan->qu_sf_idx[i] -= weights_tab[i];
290

3744
        if (chan->qu_sf_idx[i] < 0 || chan->qu_sf_idx[i] > 63) {
291
            av_log(avctx, AV_LOG_ERROR,
292
                   "SF index out of range: pos=%d, val=%d!\n",
293
                   i, chan->qu_sf_idx[i]);
294
            return AVERROR_INVALIDDATA;
295
        }
296
    }
297
298
144
    return 0;
299
}
300
301
/**
302
 * Unpack vector quantization tables.
303
 *
304
 * @param[in]    start_val    start value for the unpacked table
305
 * @param[in]    shape_vec    ptr to table to unpack
306
 * @param[out]   dst          ptr to output array
307
 * @param[in]    num_values   number of values to unpack
308
 */
309
243
static inline void unpack_vq_shape(int start_val, const int8_t *shape_vec,
310
                                   int *dst, int num_values)
311
{
312
    int i;
313
314
243
    if (num_values) {
315
243
        dst[0] = dst[1] = dst[2] = start_val;
316
4965
        for (i = 3; i < num_values; i++)
317
4722
            dst[i] = start_val - shape_vec[atrac3p_qu_num_to_seg[i] - 1];
318
    }
319
243
}
320
321
#define UNPACK_SF_VQ_SHAPE(gb, dst, num_vals)                            \
322
    start_val = get_bits((gb), 6);                                       \
323
    unpack_vq_shape(start_val, &atrac3p_sf_shapes[get_bits((gb), 6)][0], \
324
                    (dst), (num_vals))
325
326
/**
327
 * Decode word length for each quantization unit of a channel.
328
 *
329
 * @param[in]     gb            the GetBit context
330
 * @param[in,out] ctx           ptr to the channel unit context
331
 * @param[in]     ch_num        channel to process
332
 * @param[in]     avctx         ptr to the AVCodecContext
333
 * @return result code: 0 = OK, otherwise - error code
334
 */
335
1626
static int decode_channel_wordlen(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
336
                                  int ch_num, AVCodecContext *avctx)
337
{
338
1626
    int i, weight_idx = 0, delta, diff, pos, delta_bits, min_val, flag,
339
        ret, start_val;
340
    VLC *vlc_tab;
341
1626
    Atrac3pChanParams *chan     = &ctx->channels[ch_num];
342
1626
    Atrac3pChanParams *ref_chan = &ctx->channels[0];
343
344
1626
    chan->fill_mode = 0;
345
346

1626
    switch (get_bits(gb, 2)) { /* switch according to coding mode */
347
902
    case 0: /* coded using constant number of bits */
348
29766
        for (i = 0; i < ctx->num_quant_units; i++)
349
28864
            chan->qu_wordlen[i] = get_bits(gb, 3);
350
902
        break;
351
368
    case 1:
352
368
        if (ch_num) {
353
351
            if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
354
                return ret;
355
356
351
            if (chan->num_coded_vals) {
357
314
                vlc_tab = &wl_vlc_tabs[get_bits(gb, 2)];
358
359
4833
                for (i = 0; i < chan->num_coded_vals; i++) {
360
4519
                    delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
361
4519
                    chan->qu_wordlen[i] = (ref_chan->qu_wordlen[i] + delta) & 7;
362
                }
363
            }
364
        } else {
365
17
            weight_idx = get_bits(gb, 2);
366
17
            if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
367
                return ret;
368
369
17
            if (chan->num_coded_vals) {
370
17
                pos = get_bits(gb, 5);
371
17
                if (pos > chan->num_coded_vals) {
372
                    av_log(avctx, AV_LOG_ERROR,
373
                           "WL mode 1: invalid position!\n");
374
                    return AVERROR_INVALIDDATA;
375
                }
376
377
17
                delta_bits = get_bits(gb, 2);
378
17
                min_val    = get_bits(gb, 3);
379
380
75
                for (i = 0; i < pos; i++)
381
58
                    chan->qu_wordlen[i] = get_bits(gb, 3);
382
383
363
                for (i = pos; i < chan->num_coded_vals; i++)
384
346
                    chan->qu_wordlen[i] = (min_val + get_bitsz(gb, delta_bits)) & 7;
385
            }
386
        }
387
368
        break;
388
162
    case 2:
389
162
        if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
390
            return ret;
391
392

162
        if (ch_num && chan->num_coded_vals) {
393
11
            vlc_tab = &wl_vlc_tabs[get_bits(gb, 2)];
394
11
            delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
395
11
            chan->qu_wordlen[0] = (ref_chan->qu_wordlen[0] + delta) & 7;
396
397
151
            for (i = 1; i < chan->num_coded_vals; i++) {
398
140
                diff = ref_chan->qu_wordlen[i] - ref_chan->qu_wordlen[i - 1];
399
140
                delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
400
140
                chan->qu_wordlen[i] = (chan->qu_wordlen[i - 1] + diff + delta) & 7;
401
            }
402
151
        } else if (chan->num_coded_vals) {
403
151
            flag    = get_bits(gb, 1);
404
151
            vlc_tab = &wl_vlc_tabs[get_bits(gb, 1)];
405
406
151
            start_val = get_bits(gb, 3);
407
151
            unpack_vq_shape(start_val,
408
151
                            &atrac3p_wl_shapes[start_val][get_bits(gb, 4)][0],
409
151
                            chan->qu_wordlen, chan->num_coded_vals);
410
411
151
            if (!flag) {
412
2964
                for (i = 0; i < chan->num_coded_vals; i++) {
413
2826
                    delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
414
2826
                    chan->qu_wordlen[i] = (chan->qu_wordlen[i] + delta) & 7;
415
                }
416
            } else {
417
128
                for (i = 0; i < (chan->num_coded_vals & - 2); i += 2)
418
115
                    if (!get_bits1(gb)) {
419
102
                        chan->qu_wordlen[i]     = (chan->qu_wordlen[i] +
420
51
                                                   get_vlc2(gb, vlc_tab->table,
421
51
                                                            vlc_tab->bits, 1)) & 7;
422
102
                        chan->qu_wordlen[i + 1] = (chan->qu_wordlen[i + 1] +
423
51
                                                   get_vlc2(gb, vlc_tab->table,
424
51
                                                            vlc_tab->bits, 1)) & 7;
425
                    }
426
427
13
                if (chan->num_coded_vals & 1)
428
6
                    chan->qu_wordlen[i] = (chan->qu_wordlen[i] +
429
3
                                           get_vlc2(gb, vlc_tab->table,
430
3
                                                    vlc_tab->bits, 1)) & 7;
431
            }
432
        }
433
162
        break;
434
194
    case 3:
435
194
        weight_idx = get_bits(gb, 2);
436
194
        if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
437
            return ret;
438
439
194
        if (chan->num_coded_vals) {
440
157
            vlc_tab = &wl_vlc_tabs[get_bits(gb, 2)];
441
442
            /* first coefficient is coded directly */
443
157
            chan->qu_wordlen[0] = get_bits(gb, 3);
444
445
3005
            for (i = 1; i < chan->num_coded_vals; i++) {
446
2848
                delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
447
2848
                chan->qu_wordlen[i] = (chan->qu_wordlen[i - 1] + delta) & 7;
448
            }
449
        }
450
194
        break;
451
    }
452
453
1626
    if (chan->fill_mode == 2) {
454
2147
        for (i = chan->num_coded_vals; i < ctx->num_quant_units; i++)
455
1978
            chan->qu_wordlen[i] = ch_num ? get_bits1(gb) : 1;
456
1457
    } else if (chan->fill_mode == 3) {
457
267
        pos = ch_num ? chan->num_coded_vals + chan->split_point
458
134
                     : ctx->num_quant_units - chan->split_point;
459
134
        if (pos > FF_ARRAY_ELEMS(chan->qu_wordlen)) {
460
            av_log(avctx, AV_LOG_ERROR, "Split point beyond array\n");
461
            pos = FF_ARRAY_ELEMS(chan->qu_wordlen);
462
        }
463
663
        for (i = chan->num_coded_vals; i < pos; i++)
464
529
            chan->qu_wordlen[i] = 1;
465
    }
466
467
1626
    if (weight_idx)
468
110
        return add_wordlen_weights(ctx, chan, weight_idx, avctx);
469
470
1516
    return 0;
471
}
472
473
/**
474
 * Decode scale factor indexes for each quant unit of a channel.
475
 *
476
 * @param[in]     gb            the GetBit context
477
 * @param[in,out] ctx           ptr to the channel unit context
478
 * @param[in]     ch_num        channel to process
479
 * @param[in]     avctx         ptr to the AVCodecContext
480
 * @return result code: 0 = OK, otherwise - error code
481
 */
482
1552
static int decode_channel_sf_idx(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
483
                                 int ch_num, AVCodecContext *avctx)
484
{
485
1552
    int i, weight_idx = 0, delta, diff, num_long_vals,
486
        delta_bits, min_val, vlc_sel, start_val;
487
    VLC *vlc_tab;
488
1552
    Atrac3pChanParams *chan     = &ctx->channels[ch_num];
489
1552
    Atrac3pChanParams *ref_chan = &ctx->channels[0];
490
491

1552
    switch (get_bits(gb, 2)) { /* switch according to coding mode */
492
902
    case 0: /* coded using constant number of bits */
493
27962
        for (i = 0; i < ctx->used_quant_units; i++)
494
27060
            chan->qu_sf_idx[i] = get_bits(gb, 6);
495
902
        break;
496
322
    case 1:
497
322
        if (ch_num) {
498
211
            vlc_tab = &sf_vlc_tabs[get_bits(gb, 2)];
499
500
5697
            for (i = 0; i < ctx->used_quant_units; i++) {
501
5486
                delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
502
5486
                chan->qu_sf_idx[i] = (ref_chan->qu_sf_idx[i] + delta) & 0x3F;
503
            }
504
        } else {
505
111
            weight_idx = get_bits(gb, 2);
506
111
            if (weight_idx == 3) {
507
42
                UNPACK_SF_VQ_SHAPE(gb, chan->qu_sf_idx, ctx->used_quant_units);
508
509
42
                num_long_vals = get_bits(gb, 5);
510
42
                delta_bits    = get_bits(gb, 2);
511
42
                min_val       = get_bits(gb, 4) - 7;
512
513
874
                for (i = 0; i < num_long_vals; i++)
514
1664
                    chan->qu_sf_idx[i] = (chan->qu_sf_idx[i] +
515
832
                                          get_bits(gb, 4) - 7) & 0x3F;
516
517
                /* all others are: min_val + delta */
518
302
                for (i = num_long_vals; i < ctx->used_quant_units; i++)
519
520
                    chan->qu_sf_idx[i] = (chan->qu_sf_idx[i] + min_val +
520
260
                                          get_bitsz(gb, delta_bits)) & 0x3F;
521
            } else {
522
69
                num_long_vals = get_bits(gb, 5);
523
69
                delta_bits    = get_bits(gb, 3);
524
69
                min_val       = get_bits(gb, 6);
525

69
                if (num_long_vals > ctx->used_quant_units || delta_bits == 7) {
526
                    av_log(avctx, AV_LOG_ERROR,
527
                           "SF mode 1: invalid parameters!\n");
528
                    return AVERROR_INVALIDDATA;
529
                }
530
531
                /* read full-precision SF indexes */
532
719
                for (i = 0; i < num_long_vals; i++)
533
650
                    chan->qu_sf_idx[i] = get_bits(gb, 6);
534
535
                /* all others are: min_val + delta */
536
1213
                for (i = num_long_vals; i < ctx->used_quant_units; i++)
537
1144
                    chan->qu_sf_idx[i] = (min_val +
538
1144
                                          get_bitsz(gb, delta_bits)) & 0x3F;
539
            }
540
        }
541
322
        break;
542
163
    case 2:
543
163
        if (ch_num) {
544
114
            vlc_tab = &sf_vlc_tabs[get_bits(gb, 2)];
545
546
114
            delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
547
114
            chan->qu_sf_idx[0] = (ref_chan->qu_sf_idx[0] + delta) & 0x3F;
548
549
2964
            for (i = 1; i < ctx->used_quant_units; i++) {
550
2850
                diff  = ref_chan->qu_sf_idx[i] - ref_chan->qu_sf_idx[i - 1];
551
2850
                delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
552
2850
                chan->qu_sf_idx[i] = (chan->qu_sf_idx[i - 1] + diff + delta) & 0x3F;
553
            }
554
        } else {
555
49
            vlc_tab = &sf_vlc_tabs[get_bits(gb, 2) + 4];
556
557
49
            UNPACK_SF_VQ_SHAPE(gb, chan->qu_sf_idx, ctx->used_quant_units);
558
559
1323
            for (i = 0; i < ctx->used_quant_units; i++) {
560
1274
                delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
561
1274
                chan->qu_sf_idx[i] = (chan->qu_sf_idx[i] +
562
1274
                                      sign_extend(delta, 4)) & 0x3F;
563
            }
564
        }
565
163
        break;
566
165
    case 3:
567
165
        if (ch_num) {
568
            /* copy coefficients from reference channel */
569
            for (i = 0; i < ctx->used_quant_units; i++)
570
                chan->qu_sf_idx[i] = ref_chan->qu_sf_idx[i];
571
        } else {
572
165
            weight_idx = get_bits(gb, 2);
573
165
            vlc_sel    = get_bits(gb, 2);
574
165
            vlc_tab    = &sf_vlc_tabs[vlc_sel];
575
576
165
            if (weight_idx == 3) {
577
1
                vlc_tab = &sf_vlc_tabs[vlc_sel + 4];
578
579
1
                UNPACK_SF_VQ_SHAPE(gb, chan->qu_sf_idx, ctx->used_quant_units);
580
581
1
                diff               = (get_bits(gb, 4)    + 56)   & 0x3F;
582
1
                chan->qu_sf_idx[0] = (chan->qu_sf_idx[0] + diff) & 0x3F;
583
584
26
                for (i = 1; i < ctx->used_quant_units; i++) {
585
25
                    delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
586
25
                    diff               = (diff + sign_extend(delta, 4)) & 0x3F;
587
25
                    chan->qu_sf_idx[i] = (diff + chan->qu_sf_idx[i])    & 0x3F;
588
                }
589
            } else {
590
                /* 1st coefficient is coded directly */
591
164
                chan->qu_sf_idx[0] = get_bits(gb, 6);
592
593
4264
                for (i = 1; i < ctx->used_quant_units; i++) {
594
4100
                    delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
595
4100
                    chan->qu_sf_idx[i] = (chan->qu_sf_idx[i - 1] + delta) & 0x3F;
596
                }
597
            }
598
        }
599
165
        break;
600
    }
601
602

1552
    if (weight_idx && weight_idx < 3)
603
144
        return subtract_sf_weights(ctx, chan, weight_idx, avctx);
604
605
1408
    return 0;
606
}
607
608
/**
609
 * Decode word length information for each channel.
610
 *
611
 * @param[in]     gb            the GetBit context
612
 * @param[in,out] ctx           ptr to the channel unit context
613
 * @param[in]     num_channels  number of channels to process
614
 * @param[in]     avctx         ptr to the AVCodecContext
615
 * @return result code: 0 = OK, otherwise - error code
616
 */
617
813
static int decode_quant_wordlen(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
618
                                int num_channels, AVCodecContext *avctx)
619
{
620
    int ch_num, i, ret;
621
622
2439
    for (ch_num = 0; ch_num < num_channels; ch_num++) {
623
1626
        memset(ctx->channels[ch_num].qu_wordlen, 0,
624
               sizeof(ctx->channels[ch_num].qu_wordlen));
625
626
1626
        if ((ret = decode_channel_wordlen(gb, ctx, ch_num, avctx)) < 0)
627
            return ret;
628
    }
629
630
    /* scan for last non-zero coeff in both channels and
631
     * set number of quant units having coded spectrum */
632
2677
    for (i = ctx->num_quant_units - 1; i >= 0; i--)
633

2640
        if (ctx->channels[0].qu_wordlen[i] ||
634
1864
            (num_channels == 2 && ctx->channels[1].qu_wordlen[i]))
635
            break;
636
813
    ctx->used_quant_units = i + 1;
637
638
813
    return 0;
639
}
640
641
/**
642
 * Decode scale factor indexes for each channel.
643
 *
644
 * @param[in]     gb            the GetBit context
645
 * @param[in,out] ctx           ptr to the channel unit context
646
 * @param[in]     num_channels  number of channels to process
647
 * @param[in]     avctx         ptr to the AVCodecContext
648
 * @return result code: 0 = OK, otherwise - error code
649
 */
650
813
static int decode_scale_factors(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
651
                                int num_channels, AVCodecContext *avctx)
652
{
653
    int ch_num, ret;
654
655
813
    if (!ctx->used_quant_units)
656
37
        return 0;
657
658
2328
    for (ch_num = 0; ch_num < num_channels; ch_num++) {
659
1552
        memset(ctx->channels[ch_num].qu_sf_idx, 0,
660
               sizeof(ctx->channels[ch_num].qu_sf_idx));
661
662
1552
        if ((ret = decode_channel_sf_idx(gb, ctx, ch_num, avctx)) < 0)
663
            return ret;
664
    }
665
666
776
    return 0;
667
}
668
669
/**
670
 * Decode number of code table values.
671
 *
672
 * @param[in]     gb            the GetBit context
673
 * @param[in,out] ctx           ptr to the channel unit context
674
 * @param[in]     avctx         ptr to the AVCodecContext
675
 * @return result code: 0 = OK, otherwise - error code
676
 */
677
1552
static int get_num_ct_values(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
678
                             AVCodecContext *avctx)
679
{
680
    int num_coded_vals;
681
682
1552
    if (get_bits1(gb)) {
683
356
        num_coded_vals = get_bits(gb, 5);
684
356
        if (num_coded_vals > ctx->used_quant_units) {
685
            av_log(avctx, AV_LOG_ERROR,
686
                   "Invalid number of code table indexes: %d!\n", num_coded_vals);
687
            return AVERROR_INVALIDDATA;
688
        }
689
356
        return num_coded_vals;
690
    } else
691
1196
        return ctx->used_quant_units;
692
}
693
694
#define DEC_CT_IDX_COMMON(OP)                                           \
695
    num_vals = get_num_ct_values(gb, ctx, avctx);                       \
696
    if (num_vals < 0)                                                   \
697
        return num_vals;                                                \
698
                                                                        \
699
    for (i = 0; i < num_vals; i++) {                                    \
700
        if (chan->qu_wordlen[i]) {                                      \
701
            chan->qu_tab_idx[i] = OP;                                   \
702
        } else if (ch_num && ref_chan->qu_wordlen[i])                   \
703
            /* get clone master flag */                                 \
704
            chan->qu_tab_idx[i] = get_bits1(gb);                        \
705
    }
706
707
#define CODING_DIRECT get_bits(gb, num_bits)
708
709
#define CODING_VLC get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1)
710
711
#define CODING_VLC_DELTA                                                \
712
    (!i) ? CODING_VLC                                                   \
713
         : (pred + get_vlc2(gb, delta_vlc->table,                       \
714
                            delta_vlc->bits, 1)) & mask;                \
715
    pred = chan->qu_tab_idx[i]
716
717
#define CODING_VLC_DIFF                                                 \
718
    (ref_chan->qu_tab_idx[i] +                                          \
719
     get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1)) & mask
720
721
/**
722
 * Decode code table indexes for each quant unit of a channel.
723
 *
724
 * @param[in]     gb            the GetBit context
725
 * @param[in,out] ctx           ptr to the channel unit context
726
 * @param[in]     ch_num        channel to process
727
 * @param[in]     avctx         ptr to the AVCodecContext
728
 * @return result code: 0 = OK, otherwise - error code
729
 */
730
1552
static int decode_channel_code_tab(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
731
                                   int ch_num, AVCodecContext *avctx)
732
{
733
    int i, num_vals, num_bits, pred;
734
1552
    int mask = ctx->use_full_table ? 7 : 3; /* mask for modular arithmetic */
735
    VLC *vlc_tab, *delta_vlc;
736
1552
    Atrac3pChanParams *chan     = &ctx->channels[ch_num];
737
1552
    Atrac3pChanParams *ref_chan = &ctx->channels[0];
738
739
1552
    chan->table_type = get_bits1(gb);
740
741

1552
    switch (get_bits(gb, 2)) { /* switch according to coding mode */
742
980
    case 0: /* directly coded */
743
980
        num_bits = ctx->use_full_table + 2;
744


29385
        DEC_CT_IDX_COMMON(CODING_DIRECT);
745
980
        break;
746
275
    case 1: /* entropy-coded */
747
550
        vlc_tab = ctx->use_full_table ? &ct_vlc_tabs[1]
748
275
                                      : ct_vlc_tabs;
749


6385
        DEC_CT_IDX_COMMON(CODING_VLC);
750
275
        break;
751
191
    case 2: /* entropy-coded delta */
752
191
        if (ctx->use_full_table) {
753
191
            vlc_tab   = &ct_vlc_tabs[1];
754
191
            delta_vlc = &ct_vlc_tabs[2];
755
        } else {
756
            vlc_tab   = ct_vlc_tabs;
757
            delta_vlc = ct_vlc_tabs;
758
        }
759
191
        pred = 0;
760



4501
        DEC_CT_IDX_COMMON(CODING_VLC_DELTA);
761
191
        break;
762
106
    case 3: /* entropy-coded difference to master */
763
106
        if (ch_num) {
764
212
            vlc_tab = ctx->use_full_table ? &ct_vlc_tabs[3]
765
106
                                          : ct_vlc_tabs;
766


1755
            DEC_CT_IDX_COMMON(CODING_VLC_DIFF);
767
        }
768
106
        break;
769
    }
770
771
1552
    return 0;
772
}
773
774
/**
775
 * Decode code table indexes for each channel.
776
 *
777
 * @param[in]     gb            the GetBit context
778
 * @param[in,out] ctx           ptr to the channel unit context
779
 * @param[in]     num_channels  number of channels to process
780
 * @param[in]     avctx         ptr to the AVCodecContext
781
 * @return result code: 0 = OK, otherwise - error code
782
 */
783
813
static int decode_code_table_indexes(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
784
                                     int num_channels, AVCodecContext *avctx)
785
{
786
    int ch_num, ret;
787
788
813
    if (!ctx->used_quant_units)
789
37
        return 0;
790
791
776
    ctx->use_full_table = get_bits1(gb);
792
793
2328
    for (ch_num = 0; ch_num < num_channels; ch_num++) {
794
1552
        memset(ctx->channels[ch_num].qu_tab_idx, 0,
795
               sizeof(ctx->channels[ch_num].qu_tab_idx));
796
797
1552
        if ((ret = decode_channel_code_tab(gb, ctx, ch_num, avctx)) < 0)
798
            return ret;
799
    }
800
801
776
    return 0;
802
}
803
804
/**
805
 * Decode huffman-coded spectral lines for a given quant unit.
806
 *
807
 * This is a generalized version for all known coding modes.
808
 * Its speed can be improved by creating separate functions for each mode.
809
 *
810
 * @param[in]   gb          the GetBit context
811
 * @param[in]   tab         code table telling how to decode spectral lines
812
 * @param[in]   vlc_tab     ptr to the huffman table associated with the code table
813
 * @param[out]  out         pointer to buffer where decoded data should be stored
814
 * @param[in]   num_specs   number of spectral lines to decode
815
 */
816
40703
static void decode_qu_spectra(GetBitContext *gb, const Atrac3pSpecCodeTab *tab,
817
                              VLC *vlc_tab, int16_t *out, const int num_specs)
818
{
819
    int i, j, pos, cf;
820
40703
    int group_size = tab->group_size;
821
40703
    int num_coeffs = tab->num_coeffs;
822
40703
    int bits       = tab->bits;
823
40703
    int is_signed  = tab->is_signed;
824
    unsigned val;
825
826
1209621
    for (pos = 0; pos < num_specs;) {
827

1168918
        if (group_size == 1 || get_bits1(gb)) {
828
2332486
            for (j = 0; j < group_size; j++) {
829
1180390
                val = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
830
831
3119394
                for (i = 0; i < num_coeffs; i++) {
832
1939004
                    cf = av_mod_uintp2(val, bits);
833
1939004
                    if (is_signed)
834
1268212
                        cf = sign_extend(cf, bits);
835

670792
                    else if (cf && get_bits1(gb))
836
233973
                        cf = -cf;
837
838
1939004
                    out[pos++] = cf;
839
1939004
                    val      >>= bits;
840
                }
841
            }
842
        } else /* group skipped */
843
16822
            pos += group_size * num_coeffs;
844
    }
845
40703
}
846
847
/**
848
 * Decode huffman-coded IMDCT spectrum for all channels.
849
 *
850
 * @param[in]     gb            the GetBit context
851
 * @param[in,out] ctx           ptr to the channel unit context
852
 * @param[in]     num_channels  number of channels to process
853
 * @param[in]     avctx         ptr to the AVCodecContext
854
 */
855
813
static void decode_spectrum(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
856
                            int num_channels, AVCodecContext *avctx)
857
{
858
    int i, ch_num, qu, wordlen, codetab, tab_index, num_specs;
859
    const Atrac3pSpecCodeTab *tab;
860
    Atrac3pChanParams *chan;
861
862
2439
    for (ch_num = 0; ch_num < num_channels; ch_num++) {
863
1626
        chan = &ctx->channels[ch_num];
864
865
1626
        memset(chan->spectrum, 0, sizeof(chan->spectrum));
866
867
        /* set power compensation level to disabled */
868
1626
        memset(chan->power_levs, ATRAC3P_POWER_COMP_OFF, sizeof(chan->power_levs));
869
870
45586
        for (qu = 0; qu < ctx->used_quant_units; qu++) {
871
43960
            num_specs = ff_atrac3p_qu_to_spec_pos[qu + 1] -
872
43960
                        ff_atrac3p_qu_to_spec_pos[qu];
873
874
43960
            wordlen = chan->qu_wordlen[qu];
875
43960
            codetab = chan->qu_tab_idx[qu];
876
43960
            if (wordlen) {
877
40703
                if (!ctx->use_full_table)
878
27060
                    codetab = atrac3p_ct_restricted_to_full[chan->table_type][wordlen - 1][codetab];
879
880
40703
                tab_index = (chan->table_type * 8 + codetab) * 7 + wordlen - 1;
881
40703
                tab       = &atrac3p_spectra_tabs[tab_index];
882
883
                /* this allows reusing VLC tables */
884
40703
                if (tab->redirect >= 0)
885
6326
                    tab_index = tab->redirect;
886
887
40703
                decode_qu_spectra(gb, tab, &spec_vlc_tabs[tab_index],
888
40703
                                  &chan->spectrum[ff_atrac3p_qu_to_spec_pos[qu]],
889
                                  num_specs);
890

3257
            } else if (ch_num && ctx->channels[0].qu_wordlen[qu] && !codetab) {
891
                /* copy coefficients from master */
892
3257
                memcpy(&chan->spectrum[ff_atrac3p_qu_to_spec_pos[qu]],
893
3257
                       &ctx->channels[0].spectrum[ff_atrac3p_qu_to_spec_pos[qu]],
894
                       num_specs *
895
                       sizeof(chan->spectrum[ff_atrac3p_qu_to_spec_pos[qu]]));
896
3257
                chan->qu_wordlen[qu] = ctx->channels[0].qu_wordlen[qu];
897
            }
898
        }
899
900
        /* Power compensation levels only present in the bitstream
901
         * if there are more than 2 quant units. The lowest two units
902
         * correspond to the frequencies 0...351 Hz, whose shouldn't
903
         * be affected by the power compensation. */
904
1626
        if (ctx->used_quant_units > 2) {
905
1552
            num_specs = atrac3p_subband_to_num_powgrps[ctx->num_coded_subbands - 1];
906
8662
            for (i = 0; i < num_specs; i++)
907
7110
                chan->power_levs[i] = get_bits(gb, 4);
908
        }
909
    }
910
813
}
911
912
/**
913
 * Retrieve specified amount of flag bits from the input bitstream.
914
 * The data can be shortened in the case of the following two common conditions:
915
 * if all bits are zero then only one signal bit = 0 will be stored,
916
 * if all bits are ones then two signal bits = 1,0 will be stored.
917
 * Otherwise, all necessary bits will be directly stored
918
 * prefixed by two signal bits = 1,1.
919
 *
920
 * @param[in]   gb              ptr to the GetBitContext
921
 * @param[out]  out             where to place decoded flags
922
 * @param[in]   num_flags       number of flags to process
923
 * @return: 0 = all flag bits are zero, 1 = there is at least one non-zero flag bit
924
 */
925
3252
static int get_subband_flags(GetBitContext *gb, uint8_t *out, int num_flags)
926
{
927
    int i, result;
928
929
3252
    memset(out, 0, num_flags);
930
931
3252
    result = get_bits1(gb);
932
3252
    if (result) {
933
493
        if (get_bits1(gb))
934
4609
            for (i = 0; i < num_flags; i++)
935
4190
                out[i] = get_bits1(gb);
936
        else
937
74
            memset(out, 1, num_flags);
938
    }
939
940
3252
    return result;
941
}
942
943
/**
944
 * Decode mdct window shape flags for all channels.
945
 *
946
 * @param[in]     gb            the GetBit context
947
 * @param[in,out] ctx           ptr to the channel unit context
948
 * @param[in]     num_channels  number of channels to process
949
 */
950
813
static void decode_window_shape(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
951
                                int num_channels)
952
{
953
    int ch_num;
954
955
2439
    for (ch_num = 0; ch_num < num_channels; ch_num++)
956
1626
        get_subband_flags(gb, ctx->channels[ch_num].wnd_shape,
957
                          ctx->num_subbands);
958
813
}
959
960
/**
961
 * Decode number of gain control points.
962
 *
963
 * @param[in]     gb              the GetBit context
964
 * @param[in,out] ctx             ptr to the channel unit context
965
 * @param[in]     ch_num          channel to process
966
 * @param[in]     coded_subbands  number of subbands to process
967
 * @return result code: 0 = OK, otherwise - error code
968
 */
969
582
static int decode_gainc_npoints(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
970
                                int ch_num, int coded_subbands)
971
{
972
    int i, delta, delta_bits, min_val;
973
582
    Atrac3pChanParams *chan     = &ctx->channels[ch_num];
974
582
    Atrac3pChanParams *ref_chan = &ctx->channels[0];
975
976

582
    switch (get_bits(gb, 2)) { /* switch according to coding mode */
977
15
    case 0: /* fixed-length coding */
978
40
        for (i = 0; i < coded_subbands; i++)
979
25
            chan->gain_data[i].num_points = get_bits(gb, 3);
980
15
        break;
981
509
    case 1: /* variable-length coding */
982
4086
        for (i = 0; i < coded_subbands; i++)
983
3577
            chan->gain_data[i].num_points =
984
3577
                get_vlc2(gb, gain_vlc_tabs[0].table,
985
                         gain_vlc_tabs[0].bits, 1);
986
509
        break;
987
38
    case 2:
988
38
        if (ch_num) { /* VLC modulo delta to master channel */
989
162
            for (i = 0; i < coded_subbands; i++) {
990
142
                delta = get_vlc2(gb, gain_vlc_tabs[1].table,
991
                                 gain_vlc_tabs[1].bits, 1);
992
142
                chan->gain_data[i].num_points =
993
142
                    (ref_chan->gain_data[i].num_points + delta) & 7;
994
            }
995
        } else { /* VLC modulo delta to previous */
996
36
            chan->gain_data[0].num_points =
997
18
                get_vlc2(gb, gain_vlc_tabs[0].table,
998
                         gain_vlc_tabs[0].bits, 1);
999
1000
105
            for (i = 1; i < coded_subbands; i++) {
1001
87
                delta = get_vlc2(gb, gain_vlc_tabs[1].table,
1002
                                 gain_vlc_tabs[1].bits, 1);
1003
87
                chan->gain_data[i].num_points =
1004
87
                    (chan->gain_data[i - 1].num_points + delta) & 7;
1005
            }
1006
        }
1007
38
        break;
1008
20
    case 3:
1009
20
        if (ch_num) { /* copy data from master channel */
1010
66
            for (i = 0; i < coded_subbands; i++)
1011
48
                chan->gain_data[i].num_points =
1012
48
                    ref_chan->gain_data[i].num_points;
1013
        } else { /* shorter delta to min */
1014
2
            delta_bits = get_bits(gb, 2);
1015
2
            min_val    = get_bits(gb, 3);
1016
1017
25
            for (i = 0; i < coded_subbands; i++) {
1018
23
                chan->gain_data[i].num_points = min_val + get_bitsz(gb, delta_bits);
1019
23
                if (chan->gain_data[i].num_points > 7)
1020
                    return AVERROR_INVALIDDATA;
1021
            }
1022
        }
1023
    }
1024
1025
582
    return 0;
1026
}
1027
1028
/**
1029
 * Implements coding mode 3 (slave) for gain compensation levels.
1030
 *
1031
 * @param[out]   dst   ptr to the output array
1032
 * @param[in]    ref   ptr to the reference channel
1033
 */
1034
1605
static inline void gainc_level_mode3s(AtracGainInfo *dst, AtracGainInfo *ref)
1035
{
1036
    int i;
1037
1038
2000
    for (i = 0; i < dst->num_points; i++)
1039
395
        dst->lev_code[i] = (i >= ref->num_points) ? 7 : ref->lev_code[i];
1040
1605
}
1041
1042
/**
1043
 * Implements coding mode 1 (master) for gain compensation levels.
1044
 *
1045
 * @param[in]     gb     the GetBit context
1046
 * @param[in]     ctx    ptr to the channel unit context
1047
 * @param[out]    dst    ptr to the output array
1048
 */
1049
2009
static inline void gainc_level_mode1m(GetBitContext *gb,
1050
                                      Atrac3pChanUnitCtx *ctx,
1051
                                      AtracGainInfo *dst)
1052
{
1053
    int i, delta;
1054
1055
2009
    if (dst->num_points > 0)
1056
501
        dst->lev_code[0] = get_vlc2(gb, gain_vlc_tabs[2].table,
1057
                                    gain_vlc_tabs[2].bits, 1);
1058
1059
2110
    for (i = 1; i < dst->num_points; i++) {
1060
101
        delta = get_vlc2(gb, gain_vlc_tabs[3].table,
1061
                         gain_vlc_tabs[3].bits, 1);
1062
101
        dst->lev_code[i] = (dst->lev_code[i - 1] + delta) & 0xF;
1063
    }
1064
2009
}
1065
1066
/**
1067
 * Decode level code for each gain control point.
1068
 *
1069
 * @param[in]     gb              the GetBit context
1070
 * @param[in,out] ctx             ptr to the channel unit context
1071
 * @param[in]     ch_num          channel to process
1072
 * @param[in]     coded_subbands  number of subbands to process
1073
 * @return result code: 0 = OK, otherwise - error code
1074
 */
1075
582
static int decode_gainc_levels(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1076
                               int ch_num, int coded_subbands)
1077
{
1078
    int sb, i, delta, delta_bits, min_val, pred;
1079
582
    Atrac3pChanParams *chan     = &ctx->channels[ch_num];
1080
582
    Atrac3pChanParams *ref_chan = &ctx->channels[0];
1081
1082

582
    switch (get_bits(gb, 2)) { /* switch according to coding mode */
1083
9
    case 0: /* fixed-length coding */
1084
62
        for (sb = 0; sb < coded_subbands; sb++)
1085
71
            for (i = 0; i < chan->gain_data[sb].num_points; i++)
1086
18
                chan->gain_data[sb].lev_code[i] = get_bits(gb, 4);
1087
9
        break;
1088
302
    case 1:
1089
302
        if (ch_num) { /* VLC modulo delta to master channel */
1090
112
            for (sb = 0; sb < coded_subbands; sb++)
1091
162
                for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1092
68
                    delta = get_vlc2(gb, gain_vlc_tabs[5].table,
1093
                                     gain_vlc_tabs[5].bits, 1);
1094
136
                    pred = (i >= ref_chan->gain_data[sb].num_points)
1095
68
                           ? 7 : ref_chan->gain_data[sb].lev_code[i];
1096
68
                    chan->gain_data[sb].lev_code[i] = (pred + delta) & 0xF;
1097
                }
1098
        } else { /* VLC modulo delta to previous */
1099
2242
            for (sb = 0; sb < coded_subbands; sb++)
1100
1958
                gainc_level_mode1m(gb, ctx, &chan->gain_data[sb]);
1101
        }
1102
302
        break;
1103
36
    case 2:
1104
36
        if (ch_num) { /* VLC modulo delta to previous or clone master */
1105
257
            for (sb = 0; sb < coded_subbands; sb++)
1106
225
                if (chan->gain_data[sb].num_points > 0) {
1107
102
                    if (get_bits1(gb))
1108
49
                        gainc_level_mode1m(gb, ctx, &chan->gain_data[sb]);
1109
                    else
1110
53
                        gainc_level_mode3s(&chan->gain_data[sb],
1111
53
                                           &ref_chan->gain_data[sb]);
1112
                }
1113
        } else { /* VLC modulo delta to lev_codes of previous subband */
1114
4
            if (chan->gain_data[0].num_points > 0)
1115
2
                gainc_level_mode1m(gb, ctx, &chan->gain_data[0]);
1116
1117
38
            for (sb = 1; sb < coded_subbands; sb++)
1118
77
                for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1119
43
                    delta = get_vlc2(gb, gain_vlc_tabs[4].table,
1120
                                     gain_vlc_tabs[4].bits, 1);
1121
86
                    pred = (i >= chan->gain_data[sb - 1].num_points)
1122
43
                           ? 7 : chan->gain_data[sb - 1].lev_code[i];
1123
43
                    chan->gain_data[sb].lev_code[i] = (pred + delta) & 0xF;
1124
                }
1125
        }
1126
36
        break;
1127
235
    case 3:
1128
235
        if (ch_num) { /* clone master */
1129
1787
            for (sb = 0; sb < coded_subbands; sb++)
1130
1552
                gainc_level_mode3s(&chan->gain_data[sb],
1131
1552
                                   &ref_chan->gain_data[sb]);
1132
        } else { /* shorter delta to min */
1133
            delta_bits = get_bits(gb, 2);
1134
            min_val    = get_bits(gb, 4);
1135
1136
            for (sb = 0; sb < coded_subbands; sb++)
1137
                for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1138
                    chan->gain_data[sb].lev_code[i] = min_val + get_bitsz(gb, delta_bits);
1139
                    if (chan->gain_data[sb].lev_code[i] > 15)
1140
                        return AVERROR_INVALIDDATA;
1141
                }
1142
        }
1143
235
        break;
1144
    }
1145
1146
582
    return 0;
1147
}
1148
1149
/**
1150
 * Implements coding mode 0 for gain compensation locations.
1151
 *
1152
 * @param[in]     gb     the GetBit context
1153
 * @param[in]     ctx    ptr to the channel unit context
1154
 * @param[out]    dst    ptr to the output array
1155
 * @param[in]     pos    position of the value to be processed
1156
 */
1157
664
static inline void gainc_loc_mode0(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1158
                                   AtracGainInfo *dst, int pos)
1159
{
1160
    int delta_bits;
1161
1162

664
    if (!pos || dst->loc_code[pos - 1] < 15)
1163
646
        dst->loc_code[pos] = get_bits(gb, 5);
1164
18
    else if (dst->loc_code[pos - 1] >= 30)
1165
        dst->loc_code[pos] = 31;
1166
    else {
1167
18
        delta_bits         = av_log2(30 - dst->loc_code[pos - 1]) + 1;
1168
36
        dst->loc_code[pos] = dst->loc_code[pos - 1] +
1169
18
                             get_bits(gb, delta_bits) + 1;
1170
    }
1171
664
}
1172
1173
/**
1174
 * Implements coding mode 1 for gain compensation locations.
1175
 *
1176
 * @param[in]     gb     the GetBit context
1177
 * @param[in]     ctx    ptr to the channel unit context
1178
 * @param[out]    dst    ptr to the output array
1179
 */
1180
111
static inline void gainc_loc_mode1(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1181
                                   AtracGainInfo *dst)
1182
{
1183
    int i;
1184
    VLC *tab;
1185
1186
111
    if (dst->num_points > 0) {
1187
        /* 1st coefficient is stored directly */
1188
70
        dst->loc_code[0] = get_bits(gb, 5);
1189
1190
114
        for (i = 1; i < dst->num_points; i++) {
1191
            /* switch VLC according to the curve direction
1192
             * (ascending/descending) */
1193
88
            tab              = (dst->lev_code[i] <= dst->lev_code[i - 1])
1194
                               ? &gain_vlc_tabs[7]
1195
44
                               : &gain_vlc_tabs[9];
1196
44
            dst->loc_code[i] = dst->loc_code[i - 1] +
1197
44
                               get_vlc2(gb, tab->table, tab->bits, 1);
1198
        }
1199
    }
1200
111
}
1201
1202
/**
1203
 * Decode location code for each gain control point.
1204
 *
1205
 * @param[in]     gb              the GetBit context
1206
 * @param[in,out] ctx             ptr to the channel unit context
1207
 * @param[in]     ch_num          channel to process
1208
 * @param[in]     coded_subbands  number of subbands to process
1209
 * @param[in]     avctx           ptr to the AVCodecContext
1210
 * @return result code: 0 = OK, otherwise - error code
1211
 */
1212
582
static int decode_gainc_loc_codes(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1213
                                  int ch_num, int coded_subbands,
1214
                                  AVCodecContext *avctx)
1215
{
1216
    int sb, i, delta, delta_bits, min_val, pred, more_than_ref;
1217
    AtracGainInfo *dst, *ref;
1218
    VLC *tab;
1219
582
    Atrac3pChanParams *chan     = &ctx->channels[ch_num];
1220
582
    Atrac3pChanParams *ref_chan = &ctx->channels[0];
1221
1222

582
    switch (get_bits(gb, 2)) { /* switch according to coding mode */
1223
433
    case 0: /* sequence of numbers in ascending order */
1224
3350
        for (sb = 0; sb < coded_subbands; sb++)
1225
3563
            for (i = 0; i < chan->gain_data[sb].num_points; i++)
1226
646
                gainc_loc_mode0(gb, ctx, &chan->gain_data[sb], i);
1227
433
        break;
1228
64
    case 1:
1229
64
        if (ch_num) {
1230
365
            for (sb = 0; sb < coded_subbands; sb++) {
1231
312
                if (chan->gain_data[sb].num_points <= 0)
1232
219
                    continue;
1233
93
                dst = &chan->gain_data[sb];
1234
93
                ref = &ref_chan->gain_data[sb];
1235
1236
                /* 1st value is vlc-coded modulo delta to master */
1237
93
                delta = get_vlc2(gb, gain_vlc_tabs[10].table,
1238
                                 gain_vlc_tabs[10].bits, 1);
1239
93
                pred = ref->num_points > 0 ? ref->loc_code[0] : 0;
1240
93
                dst->loc_code[0] = (pred + delta) & 0x1F;
1241
1242
113
                for (i = 1; i < dst->num_points; i++) {
1243
20
                    more_than_ref = i >= ref->num_points;
1244
20
                    if (dst->lev_code[i] > dst->lev_code[i - 1]) {
1245
                        /* ascending curve */
1246
                        if (more_than_ref) {
1247
                            delta =
1248
                                get_vlc2(gb, gain_vlc_tabs[9].table,
1249
                                         gain_vlc_tabs[9].bits, 1);
1250
                            dst->loc_code[i] = dst->loc_code[i - 1] + delta;
1251
                        } else {
1252
                            if (get_bits1(gb))
1253
                                gainc_loc_mode0(gb, ctx, dst, i);  // direct coding
1254
                            else
1255
                                dst->loc_code[i] = ref->loc_code[i];  // clone master
1256
                        }
1257
                    } else { /* descending curve */
1258
20
                        tab   = more_than_ref ? &gain_vlc_tabs[7]
1259
20
                                              : &gain_vlc_tabs[10];
1260
20
                        delta = get_vlc2(gb, tab->table, tab->bits, 1);
1261
20
                        if (more_than_ref)
1262
13
                            dst->loc_code[i] = dst->loc_code[i - 1] + delta;
1263
                        else
1264
7
                            dst->loc_code[i] = (ref->loc_code[i] + delta) & 0x1F;
1265
                    }
1266
                }
1267
            }
1268
        } else /* VLC delta to previous */
1269
78
            for (sb = 0; sb < coded_subbands; sb++)
1270
67
                gainc_loc_mode1(gb, ctx, &chan->gain_data[sb]);
1271
64
        break;
1272
57
    case 2:
1273
57
        if (ch_num) {
1274
150
            for (sb = 0; sb < coded_subbands; sb++) {
1275
134
                if (chan->gain_data[sb].num_points <= 0)
1276
74
                    continue;
1277
60
                dst = &chan->gain_data[sb];
1278
60
                ref = &ref_chan->gain_data[sb];
1279

60
                if (dst->num_points > ref->num_points || get_bits1(gb))
1280
44
                    gainc_loc_mode1(gb, ctx, dst);
1281
                else /* clone master for the whole subband */
1282
38
                    for (i = 0; i < chan->gain_data[sb].num_points; i++)
1283
22
                        dst->loc_code[i] = ref->loc_code[i];
1284
            }
1285
        } else {
1286
            /* data for the first subband is coded directly */
1287
49
            for (i = 0; i < chan->gain_data[0].num_points; i++)
1288
8
                gainc_loc_mode0(gb, ctx, &chan->gain_data[0], i);
1289
1290
315
            for (sb = 1; sb < coded_subbands; sb++) {
1291
274
                if (chan->gain_data[sb].num_points <= 0)
1292
177
                    continue;
1293
97
                dst = &chan->gain_data[sb];
1294
1295
                /* 1st value is vlc-coded modulo delta to the corresponding
1296
                 * value of the previous subband if any or zero */
1297
97
                delta = get_vlc2(gb, gain_vlc_tabs[6].table,
1298
                                 gain_vlc_tabs[6].bits, 1);
1299
194
                pred             = dst[-1].num_points > 0
1300
97
                                   ? dst[-1].loc_code[0] : 0;
1301
97
                dst->loc_code[0] = (pred + delta) & 0x1F;
1302
1303
123
                for (i = 1; i < dst->num_points; i++) {
1304
26
                    more_than_ref = i >= dst[-1].num_points;
1305
                    /* Select VLC table according to curve direction and
1306
                     * presence of prediction. */
1307
26
                    tab = &gain_vlc_tabs[(dst->lev_code[i] > dst->lev_code[i - 1]) *
1308
26
                                                   2 + more_than_ref + 6];
1309
26
                    delta = get_vlc2(gb, tab->table, tab->bits, 1);
1310
26
                    if (more_than_ref)
1311
23
                        dst->loc_code[i] = dst->loc_code[i - 1] + delta;
1312
                    else
1313
3
                        dst->loc_code[i] = (dst[-1].loc_code[i] + delta) & 0x1F;
1314
                }
1315
            }
1316
        }
1317
57
        break;
1318
28
    case 3:
1319
28
        if (ch_num) { /* clone master or direct or direct coding */
1320
84
            for (sb = 0; sb < coded_subbands; sb++)
1321
102
                for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1322
33
                    if (i >= ref_chan->gain_data[sb].num_points)
1323
10
                        gainc_loc_mode0(gb, ctx, &chan->gain_data[sb], i);
1324
                    else
1325
23
                        chan->gain_data[sb].loc_code[i] =
1326
23
                            ref_chan->gain_data[sb].loc_code[i];
1327
                }
1328
        } else { /* shorter delta to min */
1329
13
            delta_bits = get_bits(gb, 2) + 1;
1330
13
            min_val    = get_bits(gb, 5);
1331
1332
119
            for (sb = 0; sb < coded_subbands; sb++)
1333
173
                for (i = 0; i < chan->gain_data[sb].num_points; i++)
1334
67
                    chan->gain_data[sb].loc_code[i] = min_val + i +
1335
67
                                                      get_bits(gb, delta_bits);
1336
        }
1337
28
        break;
1338
    }
1339
1340
    /* Validate decoded information */
1341
4502
    for (sb = 0; sb < coded_subbands; sb++) {
1342
3920
        dst = &chan->gain_data[sb];
1343
5046
        for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1344

1126
            if (dst->loc_code[i] < 0 || dst->loc_code[i] > 31 ||
1345
151
                (i && dst->loc_code[i] <= dst->loc_code[i - 1])) {
1346
                av_log(avctx, AV_LOG_ERROR,
1347
                       "Invalid gain location: ch=%d, sb=%d, pos=%d, val=%d\n",
1348
                       ch_num, sb, i, dst->loc_code[i]);
1349
                return AVERROR_INVALIDDATA;
1350
            }
1351
        }
1352
    }
1353
1354
582
    return 0;
1355
}
1356
1357
/**
1358
 * Decode gain control data for all channels.
1359
 *
1360
 * @param[in]     gb            the GetBit context
1361
 * @param[in,out] ctx           ptr to the channel unit context
1362
 * @param[in]     num_channels  number of channels to process
1363
 * @param[in]     avctx         ptr to the AVCodecContext
1364
 * @return result code: 0 = OK, otherwise - error code
1365
 */
1366
813
static int decode_gainc_data(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1367
                             int num_channels, AVCodecContext *avctx)
1368
{
1369
    int ch_num, coded_subbands, sb, ret;
1370
1371
2439
    for (ch_num = 0; ch_num < num_channels; ch_num++) {
1372
1626
        memset(ctx->channels[ch_num].gain_data, 0,
1373
               sizeof(*ctx->channels[ch_num].gain_data) * ATRAC3P_SUBBANDS);
1374
1375
1626
        if (get_bits1(gb)) { /* gain control data present? */
1376
582
            coded_subbands = get_bits(gb, 4) + 1;
1377
582
            if (get_bits1(gb)) /* is high band gain data replication on? */
1378
6
                ctx->channels[ch_num].num_gain_subbands = get_bits(gb, 4) + 1;
1379
            else
1380
576
                ctx->channels[ch_num].num_gain_subbands = coded_subbands;
1381
1382

1164
            if ((ret = decode_gainc_npoints(gb, ctx, ch_num, coded_subbands)) < 0 ||
1383
1164
                (ret = decode_gainc_levels(gb, ctx, ch_num, coded_subbands))  < 0 ||
1384
582
                (ret = decode_gainc_loc_codes(gb, ctx, ch_num, coded_subbands, avctx)) < 0)
1385
                return ret;
1386
1387
582
            if (coded_subbands > 0) { /* propagate gain data if requested */
1388
588
                for (sb = coded_subbands; sb < ctx->channels[ch_num].num_gain_subbands; sb++)
1389
6
                    ctx->channels[ch_num].gain_data[sb] =
1390
6
                        ctx->channels[ch_num].gain_data[sb - 1];
1391
            }
1392
        } else {
1393
1044
            ctx->channels[ch_num].num_gain_subbands = 0;
1394
        }
1395
    }
1396
1397
813
    return 0;
1398
}
1399
1400
/**
1401
 * Decode envelope for all tones of a channel.
1402
 *
1403
 * @param[in]     gb                the GetBit context
1404
 * @param[in,out] ctx               ptr to the channel unit context
1405
 * @param[in]     ch_num            channel to process
1406
 * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1407
 *                                  1 - tone data present
1408
 */
1409
static void decode_tones_envelope(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1410
                                  int ch_num, int band_has_tones[])
1411
{
1412
    int sb;
1413
    Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1414
    Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1415
1416
    if (!ch_num || !get_bits1(gb)) { /* mode 0: fixed-length coding */
1417
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1418
            if (!band_has_tones[sb])
1419
                continue;
1420
            dst[sb].pend_env.has_start_point = get_bits1(gb);
1421
            dst[sb].pend_env.start_pos       = dst[sb].pend_env.has_start_point
1422
                                               ? get_bits(gb, 5) : -1;
1423
            dst[sb].pend_env.has_stop_point  = get_bits1(gb);
1424
            dst[sb].pend_env.stop_pos        = dst[sb].pend_env.has_stop_point
1425
                                               ? get_bits(gb, 5) : 32;
1426
        }
1427
    } else { /* mode 1(slave only): copy master */
1428
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1429
            if (!band_has_tones[sb])
1430
                continue;
1431
            dst[sb].pend_env.has_start_point = ref[sb].pend_env.has_start_point;
1432
            dst[sb].pend_env.has_stop_point  = ref[sb].pend_env.has_stop_point;
1433
            dst[sb].pend_env.start_pos       = ref[sb].pend_env.start_pos;
1434
            dst[sb].pend_env.stop_pos        = ref[sb].pend_env.stop_pos;
1435
        }
1436
    }
1437
}
1438
1439
/**
1440
 * Decode number of tones for each subband of a channel.
1441
 *
1442
 * @param[in]     gb                the GetBit context
1443
 * @param[in,out] ctx               ptr to the channel unit context
1444
 * @param[in]     ch_num            channel to process
1445
 * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1446
 *                                  1 - tone data present
1447
 * @param[in]     avctx             ptr to the AVCodecContext
1448
 * @return result code: 0 = OK, otherwise - error code
1449
 */
1450
static int decode_band_numwavs(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1451
                               int ch_num, int band_has_tones[],
1452
                               AVCodecContext *avctx)
1453
{
1454
    int mode, sb, delta;
1455
    Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1456
    Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1457
1458
    mode = get_bits(gb, ch_num + 1);
1459
    switch (mode) {
1460
    case 0: /** fixed-length coding */
1461
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1462
            if (band_has_tones[sb])
1463
                dst[sb].num_wavs = get_bits(gb, 4);
1464
        break;
1465
    case 1: /** variable-length coding */
1466
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1467
            if (band_has_tones[sb])
1468
                dst[sb].num_wavs =
1469
                    get_vlc2(gb, tone_vlc_tabs[1].table,
1470
                             tone_vlc_tabs[1].bits, 1);
1471
        break;
1472
    case 2: /** VLC modulo delta to master (slave only) */
1473
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1474
            if (band_has_tones[sb]) {
1475
                delta = get_vlc2(gb, tone_vlc_tabs[2].table,
1476
                                 tone_vlc_tabs[2].bits, 1);
1477
                delta = sign_extend(delta, 3);
1478
                dst[sb].num_wavs = (ref[sb].num_wavs + delta) & 0xF;
1479
            }
1480
        break;
1481
    case 3: /** copy master (slave only) */
1482
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1483
            if (band_has_tones[sb])
1484
                dst[sb].num_wavs = ref[sb].num_wavs;
1485
        break;
1486
    }
1487
1488
    /** initialize start tone index for each subband */
1489
    for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1490
        if (band_has_tones[sb]) {
1491
            if (ctx->waves_info->tones_index + dst[sb].num_wavs > 48) {
1492
                av_log(avctx, AV_LOG_ERROR,
1493
                       "Too many tones: %d (max. 48), frame: %d!\n",
1494
                       ctx->waves_info->tones_index + dst[sb].num_wavs,
1495
                       avctx->frame_number);
1496
                return AVERROR_INVALIDDATA;
1497
            }
1498
            dst[sb].start_index           = ctx->waves_info->tones_index;
1499
            ctx->waves_info->tones_index += dst[sb].num_wavs;
1500
        }
1501
1502
    return 0;
1503
}
1504
1505
/**
1506
 * Decode frequency information for each subband of a channel.
1507
 *
1508
 * @param[in]     gb                the GetBit context
1509
 * @param[in,out] ctx               ptr to the channel unit context
1510
 * @param[in]     ch_num            channel to process
1511
 * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1512
 *                                  1 - tone data present
1513
 */
1514
static void decode_tones_frequency(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1515
                                   int ch_num, int band_has_tones[])
1516
{
1517
    int sb, i, direction, nbits, pred, delta;
1518
    Atrac3pWaveParam *iwav, *owav;
1519
    Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1520
    Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1521
1522
    if (!ch_num || !get_bits1(gb)) { /* mode 0: fixed-length coding */
1523
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1524
            if (!band_has_tones[sb] || !dst[sb].num_wavs)
1525
                continue;
1526
            iwav      = &ctx->waves_info->waves[dst[sb].start_index];
1527
            direction = (dst[sb].num_wavs > 1) ? get_bits1(gb) : 0;
1528
            if (direction) { /** packed numbers in descending order */
1529
                if (dst[sb].num_wavs)
1530
                    iwav[dst[sb].num_wavs - 1].freq_index = get_bits(gb, 10);
1531
                for (i = dst[sb].num_wavs - 2; i >= 0 ; i--) {
1532
                    nbits = av_log2(iwav[i+1].freq_index) + 1;
1533
                    iwav[i].freq_index = get_bits(gb, nbits);
1534
                }
1535
            } else { /** packed numbers in ascending order */
1536
                for (i = 0; i < dst[sb].num_wavs; i++) {
1537
                    if (!i || iwav[i - 1].freq_index < 512)
1538
                        iwav[i].freq_index = get_bits(gb, 10);
1539
                    else {
1540
                        nbits = av_log2(1023 - iwav[i - 1].freq_index) + 1;
1541
                        iwav[i].freq_index = get_bits(gb, nbits) +
1542
                                             1024 - (1 << nbits);
1543
                    }
1544
                }
1545
            }
1546
        }
1547
    } else { /* mode 1: VLC modulo delta to master (slave only) */
1548
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1549
            if (!band_has_tones[sb] || !dst[sb].num_wavs)
1550
                continue;
1551
            iwav = &ctx->waves_info->waves[ref[sb].start_index];
1552
            owav = &ctx->waves_info->waves[dst[sb].start_index];
1553
            for (i = 0; i < dst[sb].num_wavs; i++) {
1554
                delta = get_vlc2(gb, tone_vlc_tabs[6].table,
1555
                                 tone_vlc_tabs[6].bits, 1);
1556
                delta = sign_extend(delta, 8);
1557
                pred  = (i < ref[sb].num_wavs) ? iwav[i].freq_index :
1558
                        (ref[sb].num_wavs ? iwav[ref[sb].num_wavs - 1].freq_index : 0);
1559
                owav[i].freq_index = (pred + delta) & 0x3FF;
1560
            }
1561
        }
1562
    }
1563
}
1564
1565
/**
1566
 * Decode amplitude information for each subband of a channel.
1567
 *
1568
 * @param[in]     gb                the GetBit context
1569
 * @param[in,out] ctx               ptr to the channel unit context
1570
 * @param[in]     ch_num            channel to process
1571
 * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1572
 *                                  1 - tone data present
1573
 */
1574
static void decode_tones_amplitude(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1575
                                   int ch_num, int band_has_tones[])
1576
{
1577
    int mode, sb, j, i, diff, maxdiff, fi, delta, pred;
1578
    Atrac3pWaveParam *wsrc, *wref;
1579
    int refwaves[48] = { 0 };
1580
    Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1581
    Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1582
1583
    if (ch_num) {
1584
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1585
            if (!band_has_tones[sb] || !dst[sb].num_wavs)
1586
                continue;
1587
            wsrc = &ctx->waves_info->waves[dst[sb].start_index];
1588
            wref = &ctx->waves_info->waves[ref[sb].start_index];
1589
            for (j = 0; j < dst[sb].num_wavs; j++) {
1590
                for (i = 0, fi = 0, maxdiff = 1024; i < ref[sb].num_wavs; i++) {
1591
                    diff = FFABS(wsrc[j].freq_index - wref[i].freq_index);
1592
                    if (diff < maxdiff) {
1593
                        maxdiff = diff;
1594
                        fi      = i;
1595
                    }
1596
                }
1597
1598
                if (maxdiff < 8)
1599
                    refwaves[dst[sb].start_index + j] = fi + ref[sb].start_index;
1600
                else if (j < ref[sb].num_wavs)
1601
                    refwaves[dst[sb].start_index + j] = j + ref[sb].start_index;
1602
                else
1603
                    refwaves[dst[sb].start_index + j] = -1;
1604
            }
1605
        }
1606
    }
1607
1608
    mode = get_bits(gb, ch_num + 1);
1609
1610
    switch (mode) {
1611
    case 0: /** fixed-length coding */
1612
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1613
            if (!band_has_tones[sb] || !dst[sb].num_wavs)
1614
                continue;
1615
            if (ctx->waves_info->amplitude_mode)
1616
                for (i = 0; i < dst[sb].num_wavs; i++)
1617
                    ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = get_bits(gb, 6);
1618
            else
1619
                ctx->waves_info->waves[dst[sb].start_index].amp_sf = get_bits(gb, 6);
1620
        }
1621
        break;
1622
    case 1: /** min + VLC delta */
1623
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1624
            if (!band_has_tones[sb] || !dst[sb].num_wavs)
1625
                continue;
1626
            if (ctx->waves_info->amplitude_mode)
1627
                for (i = 0; i < dst[sb].num_wavs; i++)
1628
                    ctx->waves_info->waves[dst[sb].start_index + i].amp_sf =
1629
                        get_vlc2(gb, tone_vlc_tabs[3].table,
1630
                                 tone_vlc_tabs[3].bits, 1) + 20;
1631
            else
1632
                ctx->waves_info->waves[dst[sb].start_index].amp_sf =
1633
                    get_vlc2(gb, tone_vlc_tabs[4].table,
1634
                             tone_vlc_tabs[4].bits, 1) + 24;
1635
        }
1636
        break;
1637
    case 2: /** VLC modulo delta to master (slave only) */
1638
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1639
            if (!band_has_tones[sb] || !dst[sb].num_wavs)
1640
                continue;
1641
            for (i = 0; i < dst[sb].num_wavs; i++) {
1642
                delta = get_vlc2(gb, tone_vlc_tabs[5].table,
1643
                                 tone_vlc_tabs[5].bits, 1);
1644
                delta = sign_extend(delta, 5);
1645
                pred  = refwaves[dst[sb].start_index + i] >= 0 ?
1646
                        ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf : 34;
1647
                ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = (pred + delta) & 0x3F;
1648
            }
1649
        }
1650
        break;
1651
    case 3: /** clone master (slave only) */
1652
        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1653
            if (!band_has_tones[sb])
1654
                continue;
1655
            for (i = 0; i < dst[sb].num_wavs; i++)
1656
                ctx->waves_info->waves[dst[sb].start_index + i].amp_sf =
1657
                    refwaves[dst[sb].start_index + i] >= 0
1658
                    ? ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf
1659
                    : 32;
1660
        }
1661
        break;
1662
    }
1663
}
1664
1665
/**
1666
 * Decode phase information for each subband of a channel.
1667
 *
1668
 * @param[in]     gb                the GetBit context
1669
 * @param[in,out] ctx               ptr to the channel unit context
1670
 * @param[in]     ch_num            channel to process
1671
 * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1672
 *                                  1 - tone data present
1673
 */
1674
static void decode_tones_phase(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1675
                               int ch_num, int band_has_tones[])
1676
{
1677
    int sb, i;
1678
    Atrac3pWaveParam *wparam;
1679
    Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1680
1681
    for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1682
        if (!band_has_tones[sb])
1683
            continue;
1684
        wparam = &ctx->waves_info->waves[dst[sb].start_index];
1685
        for (i = 0; i < dst[sb].num_wavs; i++)
1686
            wparam[i].phase_index = get_bits(gb, 5);
1687
    }
1688
}
1689
1690
/**
1691
 * Decode tones info for all channels.
1692
 *
1693
 * @param[in]     gb            the GetBit context
1694
 * @param[in,out] ctx           ptr to the channel unit context
1695
 * @param[in]     num_channels  number of channels to process
1696
 * @param[in]     avctx         ptr to the AVCodecContext
1697
 * @return result code: 0 = OK, otherwise - error code
1698
 */
1699
813
static int decode_tones_info(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1700
                             int num_channels, AVCodecContext *avctx)
1701
{
1702
    int ch_num, i, ret;
1703
    int band_has_tones[16];
1704
1705
2439
    for (ch_num = 0; ch_num < num_channels; ch_num++)
1706
1626
        memset(ctx->channels[ch_num].tones_info, 0,
1707
               sizeof(*ctx->channels[ch_num].tones_info) * ATRAC3P_SUBBANDS);
1708
1709
813
    ctx->waves_info->tones_present = get_bits1(gb);
1710
813
    if (!ctx->waves_info->tones_present)
1711
813
        return 0;
1712
1713
    memset(ctx->waves_info->waves, 0, sizeof(ctx->waves_info->waves));
1714
1715
    ctx->waves_info->amplitude_mode = get_bits1(gb);
1716
    if (!ctx->waves_info->amplitude_mode) {
1717
        avpriv_report_missing_feature(avctx, "GHA amplitude mode 0");
1718
        return AVERROR_PATCHWELCOME;
1719
    }
1720
1721
    ctx->waves_info->num_tone_bands =
1722
        get_vlc2(gb, tone_vlc_tabs[0].table,
1723
                 tone_vlc_tabs[0].bits, 1) + 1;
1724
1725
    if (num_channels == 2) {
1726
        get_subband_flags(gb, ctx->waves_info->tone_sharing, ctx->waves_info->num_tone_bands);
1727
        get_subband_flags(gb, ctx->waves_info->tone_master,  ctx->waves_info->num_tone_bands);
1728
        get_subband_flags(gb, ctx->waves_info->invert_phase, ctx->waves_info->num_tone_bands);
1729
    }
1730
1731
    ctx->waves_info->tones_index = 0;
1732
1733
    for (ch_num = 0; ch_num < num_channels; ch_num++) {
1734
        for (i = 0; i < ctx->waves_info->num_tone_bands; i++)
1735
            band_has_tones[i] = !ch_num ? 1 : !ctx->waves_info->tone_sharing[i];
1736
1737
        decode_tones_envelope(gb, ctx, ch_num, band_has_tones);
1738
        if ((ret = decode_band_numwavs(gb, ctx, ch_num, band_has_tones,
1739
                                       avctx)) < 0)
1740
            return ret;
1741
1742
        decode_tones_frequency(gb, ctx, ch_num, band_has_tones);
1743
        decode_tones_amplitude(gb, ctx, ch_num, band_has_tones);
1744
        decode_tones_phase(gb, ctx, ch_num, band_has_tones);
1745
    }
1746
1747
    if (num_channels == 2) {
1748
        for (i = 0; i < ctx->waves_info->num_tone_bands; i++) {
1749
            if (ctx->waves_info->tone_sharing[i])
1750
                ctx->channels[1].tones_info[i] = ctx->channels[0].tones_info[i];
1751
1752
            if (ctx->waves_info->tone_master[i])
1753
                FFSWAP(Atrac3pWavesData, ctx->channels[0].tones_info[i],
1754
                       ctx->channels[1].tones_info[i]);
1755
        }
1756
    }
1757
1758
    return 0;
1759
}
1760
1761
813
int ff_atrac3p_decode_channel_unit(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1762
                                   int num_channels, AVCodecContext *avctx)
1763
{
1764
    int ret;
1765
1766
    /* parse sound header */
1767
813
    ctx->num_quant_units = get_bits(gb, 5) + 1;
1768

813
    if (ctx->num_quant_units > 28 && ctx->num_quant_units < 32) {
1769
        av_log(avctx, AV_LOG_ERROR,
1770
               "Invalid number of quantization units: %d!\n",
1771
               ctx->num_quant_units);
1772
        return AVERROR_INVALIDDATA;
1773
    }
1774
1775
813
    ctx->mute_flag = get_bits1(gb);
1776
1777
    /* decode various sound parameters */
1778
813
    if ((ret = decode_quant_wordlen(gb, ctx, num_channels, avctx)) < 0)
1779
        return ret;
1780
1781
813
    ctx->num_subbands       = atrac3p_qu_to_subband[ctx->num_quant_units - 1] + 1;
1782
1626
    ctx->num_coded_subbands = ctx->used_quant_units
1783
776
                              ? atrac3p_qu_to_subband[ctx->used_quant_units - 1] + 1
1784
813
                              : 0;
1785
1786
813
    if ((ret = decode_scale_factors(gb, ctx, num_channels, avctx)) < 0)
1787
        return ret;
1788
1789
813
    if ((ret = decode_code_table_indexes(gb, ctx, num_channels, avctx)) < 0)
1790
        return ret;
1791
1792
813
    decode_spectrum(gb, ctx, num_channels, avctx);
1793
1794
813
    if (num_channels == 2) {
1795
813
        get_subband_flags(gb, ctx->swap_channels, ctx->num_coded_subbands);
1796
813
        get_subband_flags(gb, ctx->negate_coeffs, ctx->num_coded_subbands);
1797
    }
1798
1799
813
    decode_window_shape(gb, ctx, num_channels);
1800
1801
813
    if ((ret = decode_gainc_data(gb, ctx, num_channels, avctx)) < 0)
1802
        return ret;
1803
1804
813
    if ((ret = decode_tones_info(gb, ctx, num_channels, avctx)) < 0)
1805
        return ret;
1806
1807
    /* decode global noise info */
1808
813
    ctx->noise_present = get_bits1(gb);
1809
813
    if (ctx->noise_present) {
1810
        ctx->noise_level_index = get_bits(gb, 4);
1811
        ctx->noise_table_index = get_bits(gb, 4);
1812
    }
1813
1814
813
    return 0;
1815
}