Coverage Report

Created: 2026-10-28 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/cook.c
Line
Count
Source
1
/*
2
 * COOK compatible decoder
3
 * Copyright (c) 2003 Sascha Sommer
4
 * Copyright (c) 2005 Benjamin Larsson
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
 * Cook compatible decoder. Bastardization of the G.722.1 standard.
26
 * This decoder handles RealNetworks, RealAudio G2 data.
27
 * Cook is identified by the codec name cook in RM files.
28
 *
29
 * To use this decoder, a calling application must supply the extradata
30
 * bytes provided from the RM container; 8+ bytes for mono streams and
31
 * 16+ for stereo streams (maybe more).
32
 *
33
 * Codec technicalities (all this assume a buffer length of 1024):
34
 * Cook works with several different techniques to achieve its compression.
35
 * In the timedomain the buffer is divided into 8 pieces and quantized. If
36
 * two neighboring pieces have different quantization index a smooth
37
 * quantization curve is used to get a smooth overlap between the different
38
 * pieces.
39
 * To get to the transformdomain Cook uses a modulated lapped transform.
40
 * The transform domain has 50 subbands with 20 elements each. This
41
 * means only a maximum of 50*20=1000 coefficients are used out of the 1024
42
 * available.
43
 */
44
45
#include "libavutil/channel_layout.h"
46
#include "libavutil/lfg.h"
47
#include "libavutil/mem.h"
48
#include "libavutil/mem_internal.h"
49
#include "libavutil/thread.h"
50
#include "libavutil/tx.h"
51
52
#include "audiodsp.h"
53
#include "avcodec.h"
54
#include "get_bits.h"
55
#include "bytestream.h"
56
#include "codec_internal.h"
57
#include "decode.h"
58
#include "sinewin.h"
59
#include "unary.h"
60
61
#include "cookdata.h"
62
63
/* the different Cook versions */
64
10
#define MONO            0x1000001
65
937
#define STEREO          0x1000002
66
38
#define JOINT_STEREO    0x1000003
67
537
#define MC_COOK         0x2000000
68
69
16.6M
#define SUBBAND_SIZE    20
70
#define MAX_SUBPACKETS   5
71
72
913k
#define QUANT_VLC_BITS    9
73
12.6k
#define COUPLING_VLC_BITS 6
74
75
typedef struct cook_gains {
76
    int *now;
77
    int *previous;
78
} cook_gains;
79
80
typedef struct COOKSubpacket {
81
    int                 ch_idx;
82
    int                 size;
83
    int                 num_channels;
84
    int                 cookversion;
85
    int                 subbands;
86
    int                 js_subband_start;
87
    int                 js_vlc_bits;
88
    int                 samples_per_channel;
89
    int                 log2_numvector_size;
90
    unsigned int        channel_mask;
91
    VLC                 channel_coupling;
92
    int                 joint_stereo;
93
    int                 bits_per_subpacket;
94
    int                 bits_per_subpdiv;
95
    int                 total_subbands;
96
    int                 numvector_size;       // 1 << log2_numvector_size;
97
98
    float               mono_previous_buffer1[1024];
99
    float               mono_previous_buffer2[1024];
100
101
    cook_gains          gains1;
102
    cook_gains          gains2;
103
    int                 gain_1[9];
104
    int                 gain_2[9];
105
    int                 gain_3[9];
106
    int                 gain_4[9];
107
} COOKSubpacket;
108
109
typedef struct cook {
110
    /*
111
     * The following 5 functions provide the lowlevel arithmetic on
112
     * the internal audio buffers.
113
     */
114
    void (*scalar_dequant)(struct cook *q, int index, int quant_index,
115
                           int *subband_coef_index, int *subband_coef_sign,
116
                           float *mlt_p);
117
118
    void (*decouple)(struct cook *q,
119
                     COOKSubpacket *p,
120
                     int subband,
121
                     float f1, float f2,
122
                     float *decode_buffer,
123
                     float *mlt_buffer1, float *mlt_buffer2);
124
125
    void (*imlt_window)(struct cook *q, float *buffer1,
126
                        cook_gains *gains_ptr, float *previous_buffer);
127
128
    void (*interpolate)(struct cook *q, float *buffer,
129
                        int gain_index, int gain_index_next);
130
131
    void (*saturate_output)(struct cook *q, float *out);
132
133
    AVCodecContext*     avctx;
134
    AudioDSPContext     adsp;
135
    GetBitContext       gb;
136
    /* stream data */
137
    int                 num_vectors;
138
    int                 samples_per_channel;
139
    /* states */
140
    AVLFG               random_state;
141
    int                 discarded_packets;
142
143
    /* transform data */
144
    AVTXContext        *mdct_ctx;
145
    av_tx_fn            mdct_fn;
146
    float*              mlt_window;
147
148
    /* VLC data */
149
    VLC                 envelope_quant_index[13];
150
    VLC                 sqvh[7];          // scalar quantization
151
152
    /* generate tables and related variables */
153
    int                 gain_size_factor;
154
    float               gain_table[31];
155
156
    /* data buffers */
157
158
    uint8_t*            decoded_bytes_buffer;
159
    DECLARE_ALIGNED(32, float, mono_mdct_output)[2048];
160
    float               decode_buffer_1[1024];
161
    float               decode_buffer_2[1024];
162
    float               decode_buffer_0[1060]; /* static allocation for joint decode */
163
164
    const float         *cplscales[5];
165
    int                 num_subpackets;
166
    COOKSubpacket       subpacket[MAX_SUBPACKETS];
167
} COOKContext;
168
169
static float     pow2tab[127];
170
static float rootpow2tab[127];
171
172
/*************** init functions ***************/
173
174
/* table generator */
175
static av_cold void init_pow2table(void)
176
1
{
177
    /* fast way of computing 2^i and 2^(0.5*i) for -63 <= i < 64 */
178
1
    int i;
179
1
    static const float exp2_tab[2] = {1, M_SQRT2};
180
1
    float exp2_val = powf(2, -63);
181
1
    float root_val = powf(2, -32);
182
128
    for (i = -63; i < 64; i++) {
183
127
        if (!(i & 1))
184
63
            root_val *= 2;
185
127
        pow2tab[63 + i] = exp2_val;
186
127
        rootpow2tab[63 + i] = root_val * exp2_tab[i & 1];
187
127
        exp2_val *= 2;
188
127
    }
189
1
}
190
191
/* table generator */
192
static av_cold void init_gain_table(COOKContext *q)
193
600
{
194
600
    int i;
195
600
    q->gain_size_factor = q->samples_per_channel / 8;
196
19.2k
    for (i = 0; i < 31; i++)
197
18.6k
        q->gain_table[i] = pow(pow2tab[i + 48],
198
18.6k
                               (1.0 / (double) q->gain_size_factor));
199
600
}
200
201
static av_cold int build_vlc(VLC *vlc, int nb_bits, const uint8_t counts[16],
202
                             const void *syms, int symbol_size, int offset,
203
                             void *logctx)
204
12.1k
{
205
12.1k
    uint8_t lens[MAX_COOK_VLC_ENTRIES];
206
12.1k
    unsigned num = 0;
207
208
205k
    for (int i = 0; i < 16; i++)
209
1.14M
        for (unsigned count = num + counts[i]; num < count; num++)
210
956k
            lens[num] = i + 1;
211
212
12.1k
    return ff_vlc_init_from_lengths(vlc, nb_bits, num, lens, 1,
213
12.1k
                                    syms, symbol_size, symbol_size,
214
12.1k
                                    offset, 0, logctx);
215
12.1k
}
216
217
static av_cold int init_cook_vlc_tables(COOKContext *q)
218
600
{
219
600
    int i, result;
220
221
600
    result = 0;
222
8.40k
    for (i = 0; i < 13; i++) {
223
7.80k
        result |= build_vlc(&q->envelope_quant_index[i], QUANT_VLC_BITS,
224
7.80k
                            envelope_quant_index_huffcounts[i],
225
7.80k
                            envelope_quant_index_huffsyms[i], 1, -12, q->avctx);
226
7.80k
    }
227
600
    av_log(q->avctx, AV_LOG_DEBUG, "sqvh VLC init\n");
228
4.80k
    for (i = 0; i < 7; i++) {
229
4.20k
        int sym_size = 1 + (i == 3);
230
4.20k
        result |= build_vlc(&q->sqvh[i], vhvlcsize_tab[i],
231
4.20k
                            cvh_huffcounts[i],
232
4.20k
                            cvh_huffsyms[i], sym_size, 0, q->avctx);
233
4.20k
    }
234
235
1.30k
    for (i = 0; i < q->num_subpackets; i++) {
236
708
        if (q->subpacket[i].joint_stereo == 1) {
237
107
            result |= build_vlc(&q->subpacket[i].channel_coupling, COUPLING_VLC_BITS,
238
107
                                ccpl_huffcounts[q->subpacket[i].js_vlc_bits - 2],
239
107
                                ccpl_huffsyms[q->subpacket[i].js_vlc_bits - 2], 1,
240
107
                                0, q->avctx);
241
107
            av_log(q->avctx, AV_LOG_DEBUG, "subpacket %i Joint-stereo VLC used.\n", i);
242
107
        }
243
708
    }
244
245
600
    av_log(q->avctx, AV_LOG_DEBUG, "VLC tables initialized.\n");
246
600
    return result;
247
600
}
248
249
static av_cold int init_cook_mlt(COOKContext *q)
250
600
{
251
600
    int j, ret;
252
600
    int mlt_size = q->samples_per_channel;
253
600
    const float scale = 1.0 / 32768.0;
254
255
600
    if (!(q->mlt_window = av_malloc_array(mlt_size, sizeof(*q->mlt_window))))
256
0
        return AVERROR(ENOMEM);
257
258
    /* Initialize the MLT window: simple sine window. */
259
600
    ff_sine_window_init(q->mlt_window, mlt_size);
260
307k
    for (j = 0; j < mlt_size; j++)
261
306k
        q->mlt_window[j] *= sqrt(2.0 / q->samples_per_channel);
262
263
    /* Initialize the MDCT. */
264
600
    ret = av_tx_init(&q->mdct_ctx, &q->mdct_fn, AV_TX_FLOAT_MDCT,
265
600
                     1, mlt_size, &scale, AV_TX_FULL_IMDCT);
266
600
    if (ret < 0)
267
0
        return ret;
268
269
600
    return 0;
270
600
}
271
272
static av_cold void init_cplscales_table(COOKContext *q)
273
600
{
274
600
    int i;
275
3.60k
    for (i = 0; i < 5; i++)
276
3.00k
        q->cplscales[i] = cplscales[i];
277
600
}
278
279
/*************** init functions end ***********/
280
281
600
#define DECODE_BYTES_PAD1(bytes) (3 - ((bytes) + 3) % 4)
282
#define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
283
284
/**
285
 * Cook indata decoding, every 32 bits are XORed with 0x37c511f2.
286
 * Why? No idea, some checksum/error detection method maybe.
287
 *
288
 * Out buffer size: extra bytes are needed to cope with
289
 * padding/misalignment.
290
 * Subpackets passed to the decoder can contain two, consecutive
291
 * half-subpackets, of identical but arbitrary size.
292
 *          1234 1234 1234 1234  extraA extraB
293
 * Case 1:  AAAA BBBB              0      0
294
 * Case 2:  AAAA ABBB BB--         3      3
295
 * Case 3:  AAAA AABB BBBB         2      2
296
 * Case 4:  AAAA AAAB BBBB BB--    1      5
297
 *
298
 * Nice way to waste CPU cycles.
299
 *
300
 * @param inbuffer  pointer to byte array of indata
301
 * @param out       pointer to byte array of outdata
302
 * @param bytes     number of bytes
303
 */
304
static inline int decode_bytes(const uint8_t *inbuffer, uint8_t *out, int bytes)
305
55.4k
{
306
55.4k
    static const uint32_t tab[4] = {
307
55.4k
        AV_BE2NE32C(0x37c511f2u), AV_BE2NE32C(0xf237c511u),
308
55.4k
        AV_BE2NE32C(0x11f237c5u), AV_BE2NE32C(0xc511f237u),
309
55.4k
    };
310
55.4k
    int i, off;
311
55.4k
    uint32_t c;
312
55.4k
    const uint32_t *buf;
313
55.4k
    uint32_t *obuf = (uint32_t *) out;
314
    /* FIXME: 64 bit platforms would be able to do 64 bits at a time.
315
     * I'm too lazy though, should be something like
316
     * for (i = 0; i < bitamount / 64; i++)
317
     *     (int64_t) out[i] = 0x37c511f237c511f2 ^ av_be2ne64(int64_t) in[i]);
318
     * Buffer alignment needs to be checked. */
319
320
55.4k
    off = (intptr_t) inbuffer & 3;
321
55.4k
    buf = (const uint32_t *) (inbuffer - off);
322
55.4k
    c = tab[off];
323
55.4k
    bytes += 3 + off;
324
2.88M
    for (i = 0; i < bytes / 4; i++)
325
2.82M
        obuf[i] = c ^ buf[i];
326
327
55.4k
    return off;
328
55.4k
}
329
330
static av_cold int cook_decode_close(AVCodecContext *avctx)
331
1.00k
{
332
1.00k
    int i;
333
1.00k
    COOKContext *q = avctx->priv_data;
334
1.00k
    av_log(avctx, AV_LOG_DEBUG, "Deallocating memory.\n");
335
336
    /* Free allocated memory buffers. */
337
1.00k
    av_freep(&q->mlt_window);
338
1.00k
    av_freep(&q->decoded_bytes_buffer);
339
340
    /* Free the transform. */
341
1.00k
    av_tx_uninit(&q->mdct_ctx);
342
343
    /* Free the VLC tables. */
344
14.1k
    for (i = 0; i < 13; i++)
345
13.1k
        ff_vlc_free(&q->envelope_quant_index[i]);
346
8.06k
    for (i = 0; i < 7; i++)
347
7.05k
        ff_vlc_free(&q->sqvh[i]);
348
1.86k
    for (i = 0; i < q->num_subpackets; i++)
349
858
        ff_vlc_free(&q->subpacket[i].channel_coupling);
350
351
1.00k
    av_log(avctx, AV_LOG_DEBUG, "Memory deallocated.\n");
352
353
1.00k
    return 0;
354
1.00k
}
355
356
/**
357
 * Fill the gain array for the timedomain quantization.
358
 *
359
 * @param gb          pointer to the GetBitContext
360
 * @param gaininfo    array[9] of gain indexes
361
 */
362
static void decode_gain_info(GetBitContext *gb, int *gaininfo)
363
55.4k
{
364
55.4k
    int i, n;
365
366
55.4k
    n = get_unary(gb, 0, get_bits_left(gb));     // amount of elements*2 to update
367
368
55.4k
    i = 0;
369
104k
    while (n--) {
370
48.7k
        int index = get_bits(gb, 3);
371
48.7k
        int gain = get_bits1(gb) ? get_bits(gb, 4) - 7 : -1;
372
373
146k
        while (i <= index)
374
97.7k
            gaininfo[i++] = gain;
375
48.7k
    }
376
457k
    while (i <= 8)
377
401k
        gaininfo[i++] = 0;
378
55.4k
}
379
380
/**
381
 * Create the quant index table needed for the envelope.
382
 *
383
 * @param q                 pointer to the COOKContext
384
 * @param quant_index_table pointer to the array
385
 */
386
static int decode_envelope(COOKContext *q, COOKSubpacket *p,
387
                           int *quant_index_table)
388
55.1k
{
389
55.1k
    int i, j, vlc_index;
390
391
55.1k
    quant_index_table[0] = get_bits(&q->gb, 6) - 6; // This is used later in categorize
392
393
952k
    for (i = 1; i < p->total_subbands; i++) {
394
905k
        vlc_index = i;
395
905k
        if (i >= p->js_subband_start * 2) {
396
900k
            vlc_index -= p->js_subband_start;
397
900k
        } else {
398
5.33k
            vlc_index /= 2;
399
5.33k
            if (vlc_index < 1)
400
614
                vlc_index = 1;
401
5.33k
        }
402
905k
        if (vlc_index > 13)
403
430k
            vlc_index = 13; // the VLC tables >13 are identical to No. 13
404
405
905k
        j = get_vlc2(&q->gb, q->envelope_quant_index[vlc_index - 1].table,
406
905k
                     QUANT_VLC_BITS, 2);
407
905k
        quant_index_table[i] = quant_index_table[i - 1] + j; // differential encoding
408
905k
        if (quant_index_table[i] > 63 || quant_index_table[i] < -63) {
409
8.20k
            av_log(q->avctx, AV_LOG_ERROR,
410
8.20k
                   "Invalid quantizer %d at position %d, outside [-63, 63] range\n",
411
8.20k
                   quant_index_table[i], i);
412
8.20k
            return AVERROR_INVALIDDATA;
413
8.20k
        }
414
905k
    }
415
416
46.9k
    return 0;
417
55.1k
}
418
419
/**
420
 * Calculate the category and category_index vector.
421
 *
422
 * @param q                     pointer to the COOKContext
423
 * @param quant_index_table     pointer to the array
424
 * @param category              pointer to the category array
425
 * @param category_index        pointer to the category_index array
426
 */
427
static void categorize(COOKContext *q, COOKSubpacket *p, const int *quant_index_table,
428
                       int *category, int *category_index)
429
46.9k
{
430
46.9k
    int exp_idx, bias, tmpbias1, tmpbias2, bits_left, num_bits, index, v, i, j;
431
46.9k
    int exp_index2[102] = { 0 };
432
46.9k
    int exp_index1[102] = { 0 };
433
434
46.9k
    int tmp_categorize_array[128 * 2] = { 0 };
435
46.9k
    int tmp_categorize_array1_idx = p->numvector_size;
436
46.9k
    int tmp_categorize_array2_idx = p->numvector_size;
437
438
46.9k
    bits_left = p->bits_per_subpacket - get_bits_count(&q->gb);
439
440
46.9k
    if (bits_left > q->samples_per_channel)
441
873
        bits_left = q->samples_per_channel +
442
873
                    ((bits_left - q->samples_per_channel) * 5) / 8;
443
444
46.9k
    bias = -32;
445
446
    /* Estimate bias. */
447
328k
    for (i = 32; i > 0; i = i / 2) {
448
281k
        num_bits = 0;
449
281k
        index    = 0;
450
4.85M
        for (j = p->total_subbands; j > 0; j--) {
451
4.57M
            exp_idx = av_clip_uintp2((i - quant_index_table[index] + bias) / 2, 3);
452
4.57M
            index++;
453
4.57M
            num_bits += expbits_tab[exp_idx];
454
4.57M
        }
455
281k
        if (num_bits >= bits_left - 32)
456
234k
            bias += i;
457
281k
    }
458
459
    /* Calculate total number of bits. */
460
46.9k
    num_bits = 0;
461
808k
    for (i = 0; i < p->total_subbands; i++) {
462
761k
        exp_idx = av_clip_uintp2((bias - quant_index_table[i]) / 2, 3);
463
761k
        num_bits += expbits_tab[exp_idx];
464
761k
        exp_index1[i] = exp_idx;
465
761k
        exp_index2[i] = exp_idx;
466
761k
    }
467
46.9k
    tmpbias1 = tmpbias2 = num_bits;
468
469
985k
    for (j = 1; j < p->numvector_size; j++) {
470
957k
        if (tmpbias1 + tmpbias2 > 2 * bits_left) {  /* ---> */
471
599k
            int max = -999999;
472
599k
            index = -1;
473
9.08M
            for (i = 0; i < p->total_subbands; i++) {
474
8.48M
                if (exp_index1[i] < 7) {
475
5.00M
                    v = (-2 * exp_index1[i]) - quant_index_table[i] + bias;
476
5.00M
                    if (v >= max) {
477
2.78M
                        max   = v;
478
2.78M
                        index = i;
479
2.78M
                    }
480
5.00M
                }
481
8.48M
            }
482
599k
            if (index == -1)
483
19.4k
                break;
484
580k
            tmp_categorize_array[tmp_categorize_array1_idx++] = index;
485
580k
            tmpbias1 -= expbits_tab[exp_index1[index]] -
486
580k
                        expbits_tab[exp_index1[index] + 1];
487
580k
            ++exp_index1[index];
488
580k
        } else {  /* <--- */
489
358k
            int min = 999999;
490
358k
            index = -1;
491
3.00M
            for (i = 0; i < p->total_subbands; i++) {
492
2.64M
                if (exp_index2[i] > 0) {
493
2.12M
                    v = (-2 * exp_index2[i]) - quant_index_table[i] + bias;
494
2.12M
                    if (v < min) {
495
697k
                        min   = v;
496
697k
                        index = i;
497
697k
                    }
498
2.12M
                }
499
2.64M
            }
500
358k
            if (index == -1)
501
466
                break;
502
357k
            tmp_categorize_array[--tmp_categorize_array2_idx] = index;
503
357k
            tmpbias2 -= expbits_tab[exp_index2[index]] -
504
357k
                        expbits_tab[exp_index2[index] - 1];
505
357k
            --exp_index2[index];
506
357k
        }
507
957k
    }
508
509
808k
    for (i = 0; i < p->total_subbands; i++)
510
761k
        category[i] = exp_index2[i];
511
512
1.61M
    for (i = 0; i < p->numvector_size - 1; i++)
513
1.56M
        category_index[i] = tmp_categorize_array[tmp_categorize_array2_idx++];
514
46.9k
}
515
516
517
/**
518
 * Expand the category vector.
519
 *
520
 * @param q                     pointer to the COOKContext
521
 * @param category              pointer to the category array
522
 * @param category_index        pointer to the category_index array
523
 */
524
static inline void expand_category(COOKContext *q, int *category,
525
                                   int *category_index)
526
46.9k
{
527
46.9k
    int i;
528
567k
    for (i = 0; i < q->num_vectors; i++)
529
520k
    {
530
520k
        int idx = category_index[i];
531
520k
        if (++category[idx] >= FF_ARRAY_ELEMS(dither_tab))
532
84.7k
            --category[idx];
533
520k
    }
534
46.9k
}
535
536
/**
537
 * The real requantization of the mltcoefs
538
 *
539
 * @param q                     pointer to the COOKContext
540
 * @param index                 index
541
 * @param quant_index           quantisation index
542
 * @param subband_coef_index    array of indexes to quant_centroid_tab
543
 * @param subband_coef_sign     signs of coefficients
544
 * @param mlt_p                 pointer into the mlt buffer
545
 */
546
static void scalar_dequant_float(COOKContext *q, int index, int quant_index,
547
                                 int *subband_coef_index, int *subband_coef_sign,
548
                                 float *mlt_p)
549
656k
{
550
656k
    int i;
551
656k
    float f1;
552
553
13.7M
    for (i = 0; i < SUBBAND_SIZE; i++) {
554
13.1M
        if (subband_coef_index[i]) {
555
653k
            f1 = quant_centroid_tab[index][subband_coef_index[i]];
556
653k
            if (subband_coef_sign[i])
557
327k
                f1 = -f1;
558
12.4M
        } else {
559
            /* noise coding if subband_coef_index[i] == 0 */
560
12.4M
            f1 = dither_tab[index];
561
12.4M
            if (av_lfg_get(&q->random_state) < 0x80000000)
562
6.23M
                f1 = -f1;
563
12.4M
        }
564
13.1M
        mlt_p[i] = f1 * rootpow2tab[quant_index + 63];
565
13.1M
    }
566
656k
}
567
/**
568
 * Unpack the subband_coef_index and subband_coef_sign vectors.
569
 *
570
 * @param q                     pointer to the COOKContext
571
 * @param category              pointer to the category array
572
 * @param subband_coef_index    array of indexes to quant_centroid_tab
573
 * @param subband_coef_sign     signs of coefficients
574
 */
575
static int unpack_SQVH(COOKContext *q, COOKSubpacket *p, int category,
576
                       int *subband_coef_index, int *subband_coef_sign)
577
134k
{
578
134k
    int i, j;
579
134k
    int vlc, vd, tmp, result;
580
581
134k
    vd = vd_tab[category];
582
134k
    result = 0;
583
1.07M
    for (i = 0; i < vpr_tab[category]; i++) {
584
943k
        vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
585
943k
        if (p->bits_per_subpacket < get_bits_count(&q->gb)) {
586
114k
            vlc = 0;
587
114k
            result = 1;
588
114k
        }
589
3.63M
        for (j = vd - 1; j >= 0; j--) {
590
2.69M
            tmp = (vlc * invradix_tab[category]) / 0x100000;
591
2.69M
            subband_coef_index[vd * i + j] = vlc - tmp * (kmax_tab[category] + 1);
592
2.69M
            vlc = tmp;
593
2.69M
        }
594
3.63M
        for (j = 0; j < vd; j++) {
595
2.69M
            if (subband_coef_index[i * vd + j]) {
596
693k
                if (get_bits_count(&q->gb) < p->bits_per_subpacket) {
597
687k
                    subband_coef_sign[i * vd + j] = get_bits1(&q->gb);
598
687k
                } else {
599
6.21k
                    result = 1;
600
6.21k
                    subband_coef_sign[i * vd + j] = 0;
601
6.21k
                }
602
2.00M
            } else {
603
2.00M
                subband_coef_sign[i * vd + j] = 0;
604
2.00M
            }
605
2.69M
        }
606
943k
    }
607
134k
    return result;
608
134k
}
609
610
611
/**
612
 * Fill the mlt_buffer with mlt coefficients.
613
 *
614
 * @param q                 pointer to the COOKContext
615
 * @param category          pointer to the category array
616
 * @param quant_index_table pointer to the array
617
 * @param mlt_buffer        pointer to mlt coefficients
618
 */
619
static void decode_vectors(COOKContext *q, COOKSubpacket *p, int *category,
620
                           int *quant_index_table, float *mlt_buffer)
621
40.8k
{
622
    /* A zero in this table means that the subband coefficient is
623
       random noise coded. */
624
40.8k
    int subband_coef_index[SUBBAND_SIZE];
625
    /* A zero in this table means that the subband coefficient is a
626
       positive multiplicator. */
627
40.8k
    int subband_coef_sign[SUBBAND_SIZE];
628
40.8k
    int band, j;
629
40.8k
    int index = 0;
630
631
697k
    for (band = 0; band < p->total_subbands; band++) {
632
656k
        index = category[band];
633
656k
        if (category[band] < 7) {
634
134k
            if (unpack_SQVH(q, p, category[band], subband_coef_index, subband_coef_sign)) {
635
23.4k
                index = 7;
636
428k
                for (j = 0; j < p->total_subbands; j++)
637
405k
                    category[band + j] = 7;
638
23.4k
            }
639
134k
        }
640
656k
        if (index >= 7) {
641
545k
            memset(subband_coef_index, 0, sizeof(subband_coef_index));
642
545k
            memset(subband_coef_sign,  0, sizeof(subband_coef_sign));
643
545k
        }
644
656k
        q->scalar_dequant(q, index, quant_index_table[band],
645
656k
                          subband_coef_index, subband_coef_sign,
646
656k
                          &mlt_buffer[band * SUBBAND_SIZE]);
647
656k
    }
648
649
    /* FIXME: should this be removed, or moved into loop above? */
650
40.8k
    if (p->total_subbands * SUBBAND_SIZE >= q->samples_per_channel)
651
5.49k
        return;
652
40.8k
}
653
654
655
static int mono_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer)
656
55.1k
{
657
55.1k
    int category_index[128] = { 0 };
658
55.1k
    int category[128]       = { 0 };
659
55.1k
    int quant_index_table[102];
660
55.1k
    int res, i;
661
662
55.1k
    if ((res = decode_envelope(q, p, quant_index_table)) < 0)
663
8.20k
        return res;
664
46.9k
    q->num_vectors = get_bits(&q->gb, p->log2_numvector_size);
665
46.9k
    categorize(q, p, quant_index_table, category, category_index);
666
46.9k
    expand_category(q, category, category_index);
667
703k
    for (i=0; i<p->total_subbands; i++) {
668
662k
        if (category[i] > 7)
669
6.17k
            return AVERROR_INVALIDDATA;
670
662k
    }
671
40.8k
    decode_vectors(q, p, category, quant_index_table, mlt_buffer);
672
673
40.8k
    return 0;
674
46.9k
}
675
676
677
/**
678
 * the actual requantization of the timedomain samples
679
 *
680
 * @param q                 pointer to the COOKContext
681
 * @param buffer            pointer to the timedomain buffer
682
 * @param gain_index        index for the block multiplier
683
 * @param gain_index_next   index for the next block multiplier
684
 */
685
static void interpolate_float(COOKContext *q, float *buffer,
686
                              int gain_index, int gain_index_next)
687
65.1k
{
688
65.1k
    int i;
689
65.1k
    float fc1, fc2;
690
65.1k
    fc1 = pow2tab[gain_index + 63];
691
692
65.1k
    if (gain_index == gain_index_next) {             // static gain
693
3.39M
        for (i = 0; i < q->gain_size_factor; i++)
694
3.35M
            buffer[i] *= fc1;
695
45.5k
    } else {                                        // smooth gain
696
19.6k
        fc2 = q->gain_table[15 + (gain_index_next - gain_index)];
697
1.45M
        for (i = 0; i < q->gain_size_factor; i++) {
698
1.43M
            buffer[i] *= fc1;
699
1.43M
            fc1       *= fc2;
700
1.43M
        }
701
19.6k
    }
702
65.1k
}
703
704
/**
705
 * Apply transform window, overlap buffers.
706
 *
707
 * @param q                 pointer to the COOKContext
708
 * @param inbuffer          pointer to the mltcoefficients
709
 * @param gains_ptr         current and previous gains
710
 * @param previous_buffer   pointer to the previous buffer to be used for overlapping
711
 */
712
static void imlt_window_float(COOKContext *q, float *inbuffer,
713
                              cook_gains *gains_ptr, float *previous_buffer)
714
42.5k
{
715
42.5k
    const float fc = pow2tab[gains_ptr->previous[0] + 63];
716
42.5k
    int i;
717
    /* The weird thing here, is that the two halves of the time domain
718
     * buffer are swapped. Also, the newest data, that we save away for
719
     * next frame, has the wrong sign. Hence the subtraction below.
720
     * Almost sounds like a complex conjugate/reverse data/FFT effect.
721
     */
722
723
    /* Apply window and overlap */
724
18.6M
    for (i = 0; i < q->samples_per_channel; i++)
725
18.6M
        inbuffer[i] = inbuffer[i] * fc * q->mlt_window[i] -
726
18.6M
                      previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
727
42.5k
}
728
729
/**
730
 * The modulated lapped transform, this takes transform coefficients
731
 * and transforms them into timedomain samples.
732
 * Apply transform window, overlap buffers, apply gain profile
733
 * and buffer management.
734
 *
735
 * @param q                 pointer to the COOKContext
736
 * @param inbuffer          pointer to the mltcoefficients
737
 * @param gains_ptr         current and previous gains
738
 * @param previous_buffer   pointer to the previous buffer to be used for overlapping
739
 */
740
static void imlt_gain(COOKContext *q, float *inbuffer,
741
                      cook_gains *gains_ptr, float *previous_buffer)
742
42.5k
{
743
42.5k
    float *buffer0 = q->mono_mdct_output;
744
42.5k
    float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
745
42.5k
    int i;
746
747
    /* Inverse modified discrete cosine transform */
748
42.5k
    q->mdct_fn(q->mdct_ctx, q->mono_mdct_output, inbuffer, sizeof(float));
749
750
42.5k
    q->imlt_window(q, buffer1, gains_ptr, previous_buffer);
751
752
    /* Apply gain profile */
753
382k
    for (i = 0; i < 8; i++)
754
340k
        if (gains_ptr->now[i] || gains_ptr->now[i + 1])
755
65.1k
            q->interpolate(q, &buffer1[q->gain_size_factor * i],
756
65.1k
                           gains_ptr->now[i], gains_ptr->now[i + 1]);
757
758
    /* Save away the current to be previous block. */
759
42.5k
    memcpy(previous_buffer, buffer0,
760
42.5k
           q->samples_per_channel * sizeof(*previous_buffer));
761
42.5k
}
762
763
764
/**
765
 * function for getting the jointstereo coupling information
766
 *
767
 * @param q                 pointer to the COOKContext
768
 * @param decouple_tab      decoupling array
769
 */
770
static int decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)
771
2.80k
{
772
2.80k
    int i;
773
2.80k
    int vlc    = get_bits1(&q->gb);
774
2.80k
    int start  = cplband[p->js_subband_start];
775
2.80k
    int end    = cplband[p->subbands - 1];
776
2.80k
    int length = end - start + 1;
777
778
2.80k
    if (start > end)
779
116
        return 0;
780
781
2.69k
    if (vlc)
782
13.3k
        for (i = 0; i < length; i++)
783
12.4k
            decouple_tab[start + i] = get_vlc2(&q->gb,
784
12.4k
                                               p->channel_coupling.table,
785
12.4k
                                               COUPLING_VLC_BITS, 3);
786
1.81k
    else
787
12.0k
        for (i = 0; i < length; i++) {
788
10.5k
            int v = get_bits(&q->gb, p->js_vlc_bits);
789
10.5k
            if (v == (1<<p->js_vlc_bits)-1) {
790
288
                av_log(q->avctx, AV_LOG_ERROR, "decouple value too large\n");
791
288
                return AVERROR_INVALIDDATA;
792
288
            }
793
10.2k
            decouple_tab[start + i] = v;
794
10.2k
        }
795
2.40k
    return 0;
796
2.69k
}
797
798
/**
799
 * function decouples a pair of signals from a single signal via multiplication.
800
 *
801
 * @param q                 pointer to the COOKContext
802
 * @param subband           index of the current subband
803
 * @param f1                multiplier for channel 1 extraction
804
 * @param f2                multiplier for channel 2 extraction
805
 * @param decode_buffer     input buffer
806
 * @param mlt_buffer1       pointer to left channel mlt coefficients
807
 * @param mlt_buffer2       pointer to right channel mlt coefficients
808
 */
809
static void decouple_float(COOKContext *q,
810
                           COOKSubpacket *p,
811
                           int subband,
812
                           float f1, float f2,
813
                           float *decode_buffer,
814
                           float *mlt_buffer1, float *mlt_buffer2)
815
25.8k
{
816
25.8k
    int j, tmp_idx;
817
543k
    for (j = 0; j < SUBBAND_SIZE; j++) {
818
517k
        tmp_idx = ((p->js_subband_start + subband) * SUBBAND_SIZE) + j;
819
517k
        mlt_buffer1[SUBBAND_SIZE * subband + j] = f1 * decode_buffer[tmp_idx];
820
517k
        mlt_buffer2[SUBBAND_SIZE * subband + j] = f2 * decode_buffer[tmp_idx];
821
517k
    }
822
25.8k
}
823
824
/**
825
 * function for decoding joint stereo data
826
 *
827
 * @param q                 pointer to the COOKContext
828
 * @param mlt_buffer1       pointer to left channel mlt coefficients
829
 * @param mlt_buffer2       pointer to right channel mlt coefficients
830
 */
831
static int joint_decode(COOKContext *q, COOKSubpacket *p,
832
                        float *mlt_buffer_left, float *mlt_buffer_right)
833
2.80k
{
834
2.80k
    int i, j, res;
835
2.80k
    int decouple_tab[SUBBAND_SIZE] = { 0 };
836
2.80k
    float *decode_buffer = q->decode_buffer_0;
837
2.80k
    int idx, cpl_tmp;
838
2.80k
    float f1, f2;
839
2.80k
    const float *cplscale;
840
841
2.80k
    memset(decode_buffer, 0, sizeof(q->decode_buffer_0));
842
843
    /* Make sure the buffers are zeroed out. */
844
2.80k
    memset(mlt_buffer_left,  0, 1024 * sizeof(*mlt_buffer_left));
845
2.80k
    memset(mlt_buffer_right, 0, 1024 * sizeof(*mlt_buffer_right));
846
2.80k
    if ((res = decouple_info(q, p, decouple_tab)) < 0)
847
288
        return res;
848
2.51k
    if ((res = mono_decode(q, p, decode_buffer)) < 0)
849
543
        return res;
850
    /* The two channels are stored interleaved in decode_buffer. */
851
3.07k
    for (i = 0; i < p->js_subband_start; i++) {
852
22.9k
        for (j = 0; j < SUBBAND_SIZE; j++) {
853
21.9k
            mlt_buffer_left[i  * 20 + j] = decode_buffer[i * 40 + j];
854
21.9k
            mlt_buffer_right[i * 20 + j] = decode_buffer[i * 40 + 20 + j];
855
21.9k
        }
856
1.09k
    }
857
858
    /* When we reach js_subband_start (the higher frequencies)
859
       the coefficients are stored in a coupling scheme. */
860
1.97k
    idx = (1 << p->js_vlc_bits) - 1;
861
27.8k
    for (i = p->js_subband_start; i < p->subbands; i++) {
862
25.8k
        cpl_tmp = cplband[i];
863
25.8k
        idx -= decouple_tab[cpl_tmp];
864
25.8k
        cplscale = q->cplscales[p->js_vlc_bits - 2];  // choose decoupler table
865
25.8k
        f1 = cplscale[decouple_tab[cpl_tmp] + 1];
866
25.8k
        f2 = cplscale[idx];
867
25.8k
        q->decouple(q, p, i, f1, f2, decode_buffer,
868
25.8k
                    mlt_buffer_left, mlt_buffer_right);
869
25.8k
        idx = (1 << p->js_vlc_bits) - 1;
870
25.8k
    }
871
872
1.97k
    return 0;
873
2.51k
}
874
875
/**
876
 * First part of subpacket decoding:
877
 *  decode raw stream bytes and read gain info.
878
 *
879
 * @param q                 pointer to the COOKContext
880
 * @param inbuffer          pointer to raw stream data
881
 * @param gains_ptr         array of current/prev gain pointers
882
 */
883
static inline void decode_bytes_and_gain(COOKContext *q, COOKSubpacket *p,
884
                                         const uint8_t *inbuffer,
885
                                         cook_gains *gains_ptr)
886
55.4k
{
887
55.4k
    int offset;
888
889
55.4k
    offset = decode_bytes(inbuffer, q->decoded_bytes_buffer,
890
55.4k
                          p->bits_per_subpacket / 8);
891
55.4k
    init_get_bits(&q->gb, q->decoded_bytes_buffer + offset,
892
55.4k
                  p->bits_per_subpacket);
893
55.4k
    decode_gain_info(&q->gb, gains_ptr->now);
894
895
    /* Swap current and previous gains */
896
55.4k
    FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
897
55.4k
}
898
899
/**
900
 * Saturate the output signal and interleave.
901
 *
902
 * @param q                 pointer to the COOKContext
903
 * @param out               pointer to the output vector
904
 */
905
static void saturate_output_float(COOKContext *q, float *out)
906
38.0k
{
907
38.0k
    q->adsp.vector_clipf(out, q->mono_mdct_output + q->samples_per_channel,
908
38.0k
                         FFALIGN(q->samples_per_channel, 8), -1.0f, 1.0f);
909
38.0k
}
910
911
912
/**
913
 * Final part of subpacket decoding:
914
 *  Apply modulated lapped transform, gain compensation,
915
 *  clip and convert to integer.
916
 *
917
 * @param q                 pointer to the COOKContext
918
 * @param decode_buffer     pointer to the mlt coefficients
919
 * @param gains_ptr         array of current/prev gain pointers
920
 * @param previous_buffer   pointer to the previous buffer to be used for overlapping
921
 * @param out               pointer to the output buffer
922
 */
923
static inline void mlt_compensate_output(COOKContext *q, float *decode_buffer,
924
                                         cook_gains *gains_ptr, float *previous_buffer,
925
                                         float *out)
926
42.5k
{
927
42.5k
    imlt_gain(q, decode_buffer, gains_ptr, previous_buffer);
928
42.5k
    if (out)
929
38.0k
        q->saturate_output(q, out);
930
42.5k
}
931
932
933
/**
934
 * Cook subpacket decoding. This function returns one decoded subpacket,
935
 * usually 1024 samples per channel.
936
 *
937
 * @param q                 pointer to the COOKContext
938
 * @param inbuffer          pointer to the inbuffer
939
 * @param outbuffer         pointer to the outbuffer
940
 */
941
static int decode_subpacket(COOKContext *q, COOKSubpacket *p,
942
                            const uint8_t *inbuffer, float **outbuffer)
943
41.6k
{
944
41.6k
    int sub_packet_size = p->size;
945
41.6k
    int res;
946
947
41.6k
    memset(q->decode_buffer_1, 0, sizeof(q->decode_buffer_1));
948
41.6k
    decode_bytes_and_gain(q, p, inbuffer, &p->gains1);
949
950
41.6k
    if (p->joint_stereo) {
951
2.80k
        if ((res = joint_decode(q, p, q->decode_buffer_1, q->decode_buffer_2)) < 0)
952
831
            return res;
953
38.7k
    } else {
954
38.7k
        if ((res = mono_decode(q, p, q->decode_buffer_1)) < 0)
955
13.6k
            return res;
956
957
25.1k
        if (p->num_channels == 2) {
958
13.8k
            decode_bytes_and_gain(q, p, inbuffer + sub_packet_size / 2, &p->gains2);
959
13.8k
            if ((res = mono_decode(q, p, q->decode_buffer_2)) < 0)
960
239
                return res;
961
13.8k
        }
962
25.1k
    }
963
964
26.9k
    mlt_compensate_output(q, q->decode_buffer_1, &p->gains1,
965
26.9k
                          p->mono_previous_buffer1,
966
26.9k
                          outbuffer ? outbuffer[p->ch_idx] : NULL);
967
968
26.9k
    if (p->num_channels == 2) {
969
15.6k
        if (p->joint_stereo)
970
1.97k
            mlt_compensate_output(q, q->decode_buffer_2, &p->gains1,
971
1.97k
                                  p->mono_previous_buffer2,
972
1.97k
                                  outbuffer ? outbuffer[p->ch_idx + 1] : NULL);
973
13.6k
        else
974
13.6k
            mlt_compensate_output(q, q->decode_buffer_2, &p->gains2,
975
13.6k
                                  p->mono_previous_buffer2,
976
13.6k
                                  outbuffer ? outbuffer[p->ch_idx + 1] : NULL);
977
15.6k
    }
978
979
26.9k
    return 0;
980
41.6k
}
981
982
983
static int cook_decode_frame(AVCodecContext *avctx, AVFrame *frame,
984
                             int *got_frame_ptr, AVPacket *avpkt)
985
176k
{
986
176k
    const uint8_t *buf = avpkt->data;
987
176k
    int buf_size = avpkt->size;
988
176k
    COOKContext *q = avctx->priv_data;
989
176k
    float **samples = NULL;
990
176k
    int i, ret;
991
176k
    int offset = 0;
992
176k
    int chidx = 0;
993
994
176k
    if (buf_size < avctx->block_align)
995
134k
        return buf_size;
996
997
    /* get output buffer */
998
41.4k
    if (q->discarded_packets >= 2) {
999
34.6k
        frame->nb_samples = q->samples_per_channel;
1000
34.6k
        if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1001
547
            return ret;
1002
34.1k
        samples = (float **)frame->extended_data;
1003
34.1k
    }
1004
1005
    /* estimate subpacket sizes */
1006
40.9k
    q->subpacket[0].size = avctx->block_align;
1007
1008
43.7k
    for (i = 1; i < q->num_subpackets; i++) {
1009
4.08k
        q->subpacket[i].size = 2 * buf[avctx->block_align - q->num_subpackets + i];
1010
4.08k
        q->subpacket[0].size -= q->subpacket[i].size + 1;
1011
4.08k
        if (q->subpacket[0].size < 0) {
1012
1.27k
            av_log(avctx, AV_LOG_DEBUG,
1013
1.27k
                   "frame subpacket size total > avctx->block_align!\n");
1014
1.27k
            return AVERROR_INVALIDDATA;
1015
1.27k
        }
1016
4.08k
    }
1017
1018
    /* decode supbackets */
1019
66.5k
    for (i = 0; i < q->num_subpackets; i++) {
1020
41.6k
        q->subpacket[i].bits_per_subpacket = (q->subpacket[i].size * 8) >>
1021
41.6k
                                              q->subpacket[i].bits_per_subpdiv;
1022
41.6k
        q->subpacket[i].ch_idx = chidx;
1023
41.6k
        av_log(avctx, AV_LOG_DEBUG,
1024
41.6k
               "subpacket[%i] size %i js %i %i block_align %i\n",
1025
41.6k
               i, q->subpacket[i].size, q->subpacket[i].joint_stereo, offset,
1026
41.6k
               avctx->block_align);
1027
1028
41.6k
        if ((ret = decode_subpacket(q, &q->subpacket[i], buf + offset, samples)) < 0)
1029
14.6k
            return ret;
1030
26.9k
        offset += q->subpacket[i].size;
1031
26.9k
        chidx += q->subpacket[i].num_channels;
1032
26.9k
        av_log(avctx, AV_LOG_DEBUG, "subpacket[%i] %i %i\n",
1033
26.9k
               i, q->subpacket[i].size * 8, get_bits_count(&q->gb));
1034
26.9k
    }
1035
1036
    /* Discard the first two frames: no valid audio. */
1037
24.9k
    if (q->discarded_packets < 2) {
1038
755
        q->discarded_packets++;
1039
755
        *got_frame_ptr = 0;
1040
755
        return avctx->block_align;
1041
755
    }
1042
1043
24.2k
    *got_frame_ptr = 1;
1044
1045
24.2k
    return avctx->block_align;
1046
24.9k
}
1047
1048
static void dump_cook_context(COOKContext *q)
1049
600
{
1050
    //int i=0;
1051
5.97k
#define PRINT(a, b) ff_dlog(q->avctx, " %s = %d\n", a, b);
1052
600
    ff_dlog(q->avctx, "COOKextradata\n");
1053
600
    ff_dlog(q->avctx, "cookversion=%x\n", q->subpacket[0].cookversion);
1054
600
    if (q->subpacket[0].cookversion > STEREO) {
1055
286
        PRINT("js_subband_start", q->subpacket[0].js_subband_start);
1056
286
        PRINT("js_vlc_bits", q->subpacket[0].js_vlc_bits);
1057
286
    }
1058
600
    ff_dlog(q->avctx, "COOKContext\n");
1059
600
    PRINT("nb_channels", q->avctx->ch_layout.nb_channels);
1060
600
    PRINT("bit_rate", (int)q->avctx->bit_rate);
1061
600
    PRINT("sample_rate", q->avctx->sample_rate);
1062
600
    PRINT("samples_per_channel", q->subpacket[0].samples_per_channel);
1063
600
    PRINT("subbands", q->subpacket[0].subbands);
1064
600
    PRINT("js_subband_start", q->subpacket[0].js_subband_start);
1065
600
    PRINT("log2_numvector_size", q->subpacket[0].log2_numvector_size);
1066
600
    PRINT("numvector_size", q->subpacket[0].numvector_size);
1067
600
    PRINT("total_subbands", q->subpacket[0].total_subbands);
1068
600
}
1069
1070
/**
1071
 * Cook initialization
1072
 *
1073
 * @param avctx     pointer to the AVCodecContext
1074
 */
1075
static av_cold int cook_decode_init(AVCodecContext *avctx)
1076
1.00k
{
1077
1.00k
    static AVOnce init_static_once = AV_ONCE_INIT;
1078
1.00k
    COOKContext *q = avctx->priv_data;
1079
1.00k
    GetByteContext gb;
1080
1.00k
    int s = 0;
1081
1.00k
    unsigned int channel_mask = 0;
1082
1.00k
    int samples_per_frame = 0;
1083
1.00k
    int total_channels = 0;
1084
1.00k
    int ret;
1085
1.00k
    int channels = avctx->ch_layout.nb_channels;
1086
1087
1.00k
    q->avctx = avctx;
1088
1089
    /* Take care of the codec specific extradata. */
1090
1.00k
    if (avctx->extradata_size < 8) {
1091
119
        av_log(avctx, AV_LOG_ERROR, "Necessary extradata missing!\n");
1092
119
        return AVERROR_INVALIDDATA;
1093
119
    }
1094
889
    av_log(avctx, AV_LOG_DEBUG, "codecdata_length=%d\n", avctx->extradata_size);
1095
1096
889
    bytestream2_init(&gb, avctx->extradata, avctx->extradata_size);
1097
1098
    /* Take data from the AVCodecContext (RM container). */
1099
889
    if (!channels) {
1100
0
        av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
1101
0
        return AVERROR_INVALIDDATA;
1102
0
    }
1103
1104
889
    if (avctx->block_align >= INT_MAX / 8)
1105
7
        return AVERROR(EINVAL);
1106
1107
    /* Initialize RNG. */
1108
882
    av_lfg_init(&q->random_state, 0);
1109
1110
882
    ff_audiodsp_init(&q->adsp);
1111
1112
1.74k
    while (bytestream2_get_bytes_left(&gb)) {
1113
1.07k
        if (s >= FFMIN(MAX_SUBPACKETS, avctx->block_align)) {
1114
3
            avpriv_request_sample(avctx, "subpackets > %d", FFMIN(MAX_SUBPACKETS, avctx->block_align));
1115
3
            return AVERROR_PATCHWELCOME;
1116
3
        }
1117
        /* 8 for mono, 16 for stereo, ? for multichannel
1118
           Swap to right endianness so we don't need to care later on. */
1119
1.07k
        q->subpacket[s].cookversion      = bytestream2_get_be32(&gb);
1120
1.07k
        samples_per_frame                = bytestream2_get_be16(&gb);
1121
1.07k
        q->subpacket[s].subbands         = bytestream2_get_be16(&gb);
1122
1.07k
        bytestream2_get_be32(&gb);    // Unknown unused
1123
1.07k
        q->subpacket[s].js_subband_start = bytestream2_get_be16(&gb);
1124
1.07k
        if (q->subpacket[s].js_subband_start >= 51) {
1125
26
            av_log(avctx, AV_LOG_ERROR, "js_subband_start %d is too large\n", q->subpacket[s].js_subband_start);
1126
26
            return AVERROR_INVALIDDATA;
1127
26
        }
1128
1.04k
        q->subpacket[s].js_vlc_bits      = bytestream2_get_be16(&gb);
1129
1130
        /* Initialize extradata related variables. */
1131
1.04k
        q->subpacket[s].samples_per_channel = samples_per_frame / channels;
1132
1.04k
        q->subpacket[s].bits_per_subpacket = avctx->block_align * 8;
1133
1134
        /* Initialize default data states. */
1135
1.04k
        q->subpacket[s].log2_numvector_size = 5;
1136
1.04k
        q->subpacket[s].total_subbands = q->subpacket[s].subbands;
1137
1.04k
        q->subpacket[s].num_channels = 1;
1138
1139
        /* Initialize version-dependent variables */
1140
1141
1.04k
        av_log(avctx, AV_LOG_DEBUG, "subpacket[%i].cookversion=%x\n", s,
1142
1.04k
               q->subpacket[s].cookversion);
1143
1.04k
        q->subpacket[s].joint_stereo = 0;
1144
1.04k
        switch (q->subpacket[s].cookversion) {
1145
10
        case MONO:
1146
10
            if (channels != 1) {
1147
2
                avpriv_request_sample(avctx, "Container channels != 1");
1148
2
                return AVERROR_PATCHWELCOME;
1149
2
            }
1150
8
            av_log(avctx, AV_LOG_DEBUG, "MONO\n");
1151
8
            break;
1152
337
        case STEREO:
1153
337
            if (channels != 1) {
1154
184
                q->subpacket[s].bits_per_subpdiv = 1;
1155
184
                q->subpacket[s].num_channels = 2;
1156
184
            }
1157
337
            av_log(avctx, AV_LOG_DEBUG, "STEREO\n");
1158
337
            break;
1159
38
        case JOINT_STEREO:
1160
38
            if (channels != 2) {
1161
1
                avpriv_request_sample(avctx, "Container channels != 2");
1162
1
                return AVERROR_PATCHWELCOME;
1163
1
            }
1164
37
            av_log(avctx, AV_LOG_DEBUG, "JOINT_STEREO\n");
1165
37
            if (avctx->extradata_size >= 16) {
1166
2
                q->subpacket[s].total_subbands = q->subpacket[s].subbands +
1167
2
                                                 q->subpacket[s].js_subband_start;
1168
2
                q->subpacket[s].joint_stereo = 1;
1169
2
                q->subpacket[s].num_channels = 2;
1170
2
            }
1171
37
            if (q->subpacket[s].samples_per_channel > 256) {
1172
27
                q->subpacket[s].log2_numvector_size = 6;
1173
27
            }
1174
37
            if (q->subpacket[s].samples_per_channel > 512) {
1175
11
                q->subpacket[s].log2_numvector_size = 7;
1176
11
            }
1177
37
            break;
1178
537
        case MC_COOK:
1179
537
            av_log(avctx, AV_LOG_DEBUG, "MULTI_CHANNEL\n");
1180
537
            channel_mask |= q->subpacket[s].channel_mask = bytestream2_get_be32(&gb);
1181
1182
537
            if (av_popcount64(q->subpacket[s].channel_mask) > 1) {
1183
196
                q->subpacket[s].total_subbands = q->subpacket[s].subbands +
1184
196
                                                 q->subpacket[s].js_subband_start;
1185
196
                q->subpacket[s].joint_stereo = 1;
1186
196
                q->subpacket[s].num_channels = 2;
1187
196
                q->subpacket[s].samples_per_channel = samples_per_frame >> 1;
1188
1189
196
                if (q->subpacket[s].samples_per_channel > 256) {
1190
150
                    q->subpacket[s].log2_numvector_size = 6;
1191
150
                }
1192
196
                if (q->subpacket[s].samples_per_channel > 512) {
1193
19
                    q->subpacket[s].log2_numvector_size = 7;
1194
19
                }
1195
196
            } else
1196
341
                q->subpacket[s].samples_per_channel = samples_per_frame;
1197
1198
537
            break;
1199
126
        default:
1200
126
            avpriv_request_sample(avctx, "Cook version %d",
1201
126
                                  q->subpacket[s].cookversion);
1202
126
            return AVERROR_PATCHWELCOME;
1203
1.04k
        }
1204
1205
919
        if (s > 1 && q->subpacket[s].samples_per_channel != q->samples_per_channel) {
1206
18
            av_log(avctx, AV_LOG_ERROR, "different number of samples per channel!\n");
1207
18
            return AVERROR_INVALIDDATA;
1208
18
        } else
1209
901
            q->samples_per_channel = q->subpacket[0].samples_per_channel;
1210
1211
1212
        /* Initialize variable relations */
1213
901
        q->subpacket[s].numvector_size = (1 << q->subpacket[s].log2_numvector_size);
1214
1215
        /* Try to catch some obviously faulty streams, otherwise it might be exploitable */
1216
901
        if (q->subpacket[s].total_subbands > 53) {
1217
18
            avpriv_request_sample(avctx, "total_subbands > 53");
1218
18
            return AVERROR_PATCHWELCOME;
1219
18
        }
1220
1221
883
        if (q->subpacket[s].joint_stereo &&
1222
183
            q->subpacket[s].js_subband_start > q->subpacket[s].subbands) {
1223
7
            av_log(avctx, AV_LOG_ERROR, "js_subband_start %d > subbands %d\n",
1224
7
                   q->subpacket[s].js_subband_start, q->subpacket[s].subbands);
1225
7
            return AVERROR_INVALIDDATA;
1226
7
        }
1227
1228
876
        if ((q->subpacket[s].js_vlc_bits > 6) ||
1229
868
            (q->subpacket[s].js_vlc_bits < 2 * q->subpacket[s].joint_stereo)) {
1230
11
            av_log(avctx, AV_LOG_ERROR, "js_vlc_bits = %d, only >= %d and <= 6 allowed!\n",
1231
11
                   q->subpacket[s].js_vlc_bits, 2 * q->subpacket[s].joint_stereo);
1232
11
            return AVERROR_INVALIDDATA;
1233
11
        }
1234
1235
865
        if (q->subpacket[s].subbands > 50) {
1236
1
            avpriv_request_sample(avctx, "subbands > 50");
1237
1
            return AVERROR_PATCHWELCOME;
1238
1
        }
1239
864
        if (q->subpacket[s].subbands == 0) {
1240
5
            avpriv_request_sample(avctx, "subbands = 0");
1241
5
            return AVERROR_PATCHWELCOME;
1242
5
        }
1243
859
        q->subpacket[s].gains1.now      = q->subpacket[s].gain_1;
1244
859
        q->subpacket[s].gains1.previous = q->subpacket[s].gain_2;
1245
859
        q->subpacket[s].gains2.now      = q->subpacket[s].gain_3;
1246
859
        q->subpacket[s].gains2.previous = q->subpacket[s].gain_4;
1247
1248
859
        if (total_channels + q->subpacket[s].num_channels > channels) {
1249
1
            av_log(avctx, AV_LOG_ERROR, "Too many subpacket channels %d for channels %d\n",
1250
1
                   total_channels + q->subpacket[s].num_channels, channels);
1251
1
            return AVERROR_INVALIDDATA;
1252
1
        }
1253
858
        total_channels += q->subpacket[s].num_channels;
1254
1255
858
        q->num_subpackets++;
1256
858
        s++;
1257
858
    }
1258
1259
663
    if (channel_mask && av_popcount(channel_mask) != total_channels) {
1260
34
        av_log(avctx, AV_LOG_ERROR, "Channel mask 0x%x does not match %d subpacket channels\n",
1261
34
               channel_mask, total_channels);
1262
34
        return AVERROR_INVALIDDATA;
1263
34
    }
1264
1265
    /* Try to catch some obviously faulty streams, otherwise it might be exploitable */
1266
629
    if (q->samples_per_channel != 256 && q->samples_per_channel != 512 &&
1267
184
        q->samples_per_channel != 1024) {
1268
29
        avpriv_request_sample(avctx, "samples_per_channel = %d",
1269
29
                              q->samples_per_channel);
1270
29
        return AVERROR_PATCHWELCOME;
1271
29
    }
1272
1273
    /* Generate tables */
1274
600
    ff_thread_once(&init_static_once, init_pow2table);
1275
600
    init_gain_table(q);
1276
600
    init_cplscales_table(q);
1277
1278
600
    if ((ret = init_cook_vlc_tables(q)))
1279
0
        return ret;
1280
1281
    /* Pad the databuffer with:
1282
       DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
1283
       AV_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */
1284
600
    q->decoded_bytes_buffer =
1285
600
        av_mallocz(avctx->block_align
1286
600
                   + DECODE_BYTES_PAD1(avctx->block_align)
1287
600
                   + AV_INPUT_BUFFER_PADDING_SIZE);
1288
600
    if (!q->decoded_bytes_buffer)
1289
0
        return AVERROR(ENOMEM);
1290
1291
    /* Initialize transform. */
1292
600
    if ((ret = init_cook_mlt(q)))
1293
0
        return ret;
1294
1295
    /* Initialize COOK signal arithmetic handling */
1296
600
    if (1) {
1297
600
        q->scalar_dequant  = scalar_dequant_float;
1298
600
        q->decouple        = decouple_float;
1299
600
        q->imlt_window     = imlt_window_float;
1300
600
        q->interpolate     = interpolate_float;
1301
600
        q->saturate_output = saturate_output_float;
1302
600
    }
1303
1304
600
    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1305
600
    av_channel_layout_uninit(&avctx->ch_layout);
1306
600
    if (channel_mask)
1307
108
        av_channel_layout_from_mask(&avctx->ch_layout, channel_mask);
1308
492
    else
1309
492
        av_channel_layout_default(&avctx->ch_layout, channels);
1310
1311
1312
600
    dump_cook_context(q);
1313
1314
600
    return 0;
1315
600
}
1316
1317
const FFCodec ff_cook_decoder = {
1318
    .p.name         = "cook",
1319
    CODEC_LONG_NAME("Cook / Cooker / Gecko (RealAudio G2)"),
1320
    .p.type         = AVMEDIA_TYPE_AUDIO,
1321
    .p.id           = AV_CODEC_ID_COOK,
1322
    .priv_data_size = sizeof(COOKContext),
1323
    .init           = cook_decode_init,
1324
    .close          = cook_decode_close,
1325
    FF_CODEC_DECODE_CB(cook_decode_frame),
1326
    .p.capabilities = AV_CODEC_CAP_DR1,
1327
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
1328
};