GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/bink.c Lines: 672 816 82.4 %
Date: 2021-04-19 06:27:07 Branches: 417 529 78.8 %

Line Branch Exec Source
1
/*
2
 * Bink video decoder
3
 * Copyright (c) 2009 Konstantin Shishkov
4
 * Copyright (C) 2011 Peter Ross <pross@xvid.org>
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
#include "libavutil/attributes.h"
24
#include "libavutil/imgutils.h"
25
#include "libavutil/internal.h"
26
#include "libavutil/mem_internal.h"
27
28
#define BITSTREAM_READER_LE
29
#include "avcodec.h"
30
#include "binkdata.h"
31
#include "binkdsp.h"
32
#include "blockdsp.h"
33
#include "get_bits.h"
34
#include "hpeldsp.h"
35
#include "internal.h"
36
#include "mathops.h"
37
38
#define BINK_FLAG_ALPHA 0x00100000
39
#define BINK_FLAG_GRAY  0x00020000
40
41
static VLC bink_trees[16];
42
43
/**
44
 * IDs for different data types used in old version of Bink video codec
45
 */
46
enum OldSources {
47
    BINKB_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
48
    BINKB_SRC_COLORS,          ///< pixel values used for different block types
49
    BINKB_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
50
    BINKB_SRC_X_OFF,           ///< X components of motion value
51
    BINKB_SRC_Y_OFF,           ///< Y components of motion value
52
    BINKB_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
53
    BINKB_SRC_INTER_DC,        ///< DC values for interblocks with DCT
54
    BINKB_SRC_INTRA_Q,         ///< quantizer values for intrablocks with DCT
55
    BINKB_SRC_INTER_Q,         ///< quantizer values for interblocks with DCT
56
    BINKB_SRC_INTER_COEFS,     ///< number of coefficients for residue blocks
57
58
    BINKB_NB_SRC
59
};
60
61
static const int binkb_bundle_sizes[BINKB_NB_SRC] = {
62
    4, 8, 8, 5, 5, 11, 11, 4, 4, 7
63
};
64
65
static const int binkb_bundle_signed[BINKB_NB_SRC] = {
66
    0, 0, 0, 1, 1, 0, 1, 0, 0, 0
67
};
68
69
static int32_t binkb_intra_quant[16][64];
70
static int32_t binkb_inter_quant[16][64];
71
72
/**
73
 * IDs for different data types used in Bink video codec
74
 */
75
enum Sources {
76
    BINK_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
77
    BINK_SRC_SUB_BLOCK_TYPES, ///< 16x16 block types (a subset of 8x8 block types)
78
    BINK_SRC_COLORS,          ///< pixel values used for different block types
79
    BINK_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
80
    BINK_SRC_X_OFF,           ///< X components of motion value
81
    BINK_SRC_Y_OFF,           ///< Y components of motion value
82
    BINK_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
83
    BINK_SRC_INTER_DC,        ///< DC values for interblocks with DCT
84
    BINK_SRC_RUN,             ///< run lengths for special fill block
85
86
    BINK_NB_SRC
87
};
88
89
/**
90
 * data needed to decode 4-bit Huffman-coded value
91
 */
92
typedef struct Tree {
93
    int     vlc_num;  ///< tree number (in bink_trees[])
94
    uint8_t syms[16]; ///< leaf value to symbol mapping
95
} Tree;
96
97
#define GET_HUFF(gb, tree)  (tree).syms[get_vlc2(gb, bink_trees[(tree).vlc_num].table,\
98
                                                 bink_trees[(tree).vlc_num].bits, 1)]
99
100
/**
101
 * data structure used for decoding single Bink data type
102
 */
103
typedef struct Bundle {
104
    int     len;       ///< length of number of entries to decode (in bits)
105
    Tree    tree;      ///< Huffman tree-related data
106
    uint8_t *data;     ///< buffer for decoded symbols
107
    uint8_t *data_end; ///< buffer end
108
    uint8_t *cur_dec;  ///< pointer to the not yet decoded part of the buffer
109
    uint8_t *cur_ptr;  ///< pointer to the data that is not read from buffer yet
110
} Bundle;
111
112
/*
113
 * Decoder context
114
 */
115
typedef struct BinkContext {
116
    AVCodecContext *avctx;
117
    BlockDSPContext bdsp;
118
    op_pixels_func put_pixels_tab;
119
    BinkDSPContext binkdsp;
120
    AVFrame        *last;
121
    int            version;              ///< internal Bink file version
122
    int            has_alpha;
123
    int            swap_planes;
124
    unsigned       frame_num;
125
126
    Bundle         bundle[BINKB_NB_SRC]; ///< bundles for decoding all data types
127
    Tree           col_high[16];         ///< trees for decoding high nibble in "colours" data type
128
    int            col_lastval;          ///< value of last decoded high nibble in "colours" data type
129
} BinkContext;
130
131
/**
132
 * Bink video block types
133
 */
134
enum BlockTypes {
135
    SKIP_BLOCK = 0, ///< skipped block
136
    SCALED_BLOCK,   ///< block has size 16x16
137
    MOTION_BLOCK,   ///< block is copied from previous frame with some offset
138
    RUN_BLOCK,      ///< block is composed from runs of colours with custom scan order
139
    RESIDUE_BLOCK,  ///< motion block with some difference added
140
    INTRA_BLOCK,    ///< intra DCT block
141
    FILL_BLOCK,     ///< block is filled with single colour
142
    INTER_BLOCK,    ///< motion block with DCT applied to the difference
143
    PATTERN_BLOCK,  ///< block is filled with two colours following custom pattern
144
    RAW_BLOCK,      ///< uncoded 8x8 block
145
};
146
147
/**
148
 * Initialize length in all bundles.
149
 *
150
 * @param c     decoder context
151
 * @param width plane width
152
 * @param bw    plane width in 8x8 blocks
153
 */
154
153
static void init_lengths(BinkContext *c, int width, int bw)
155
{
156
153
    width = FFALIGN(width, 8);
157
158
153
    c->bundle[BINK_SRC_BLOCK_TYPES].len = av_log2((width >> 3) + 511) + 1;
159
160
153
    c->bundle[BINK_SRC_SUB_BLOCK_TYPES].len = av_log2((width >> 4) + 511) + 1;
161
162
153
    c->bundle[BINK_SRC_COLORS].len = av_log2(bw*64 + 511) + 1;
163
164
153
    c->bundle[BINK_SRC_INTRA_DC].len =
165
153
    c->bundle[BINK_SRC_INTER_DC].len =
166
153
    c->bundle[BINK_SRC_X_OFF].len =
167
153
    c->bundle[BINK_SRC_Y_OFF].len = av_log2((width >> 3) + 511) + 1;
168
169
153
    c->bundle[BINK_SRC_PATTERN].len = av_log2((bw << 3) + 511) + 1;
170
171
153
    c->bundle[BINK_SRC_RUN].len = av_log2(bw*48 + 511) + 1;
172
153
}
173
174
/**
175
 * Allocate memory for bundles.
176
 *
177
 * @param c decoder context
178
 */
179
9
static av_cold int init_bundles(BinkContext *c)
180
{
181
    int bw, bh, blocks;
182
    uint8_t *tmp;
183
    int i;
184
185
9
    bw = (c->avctx->width  + 7) >> 3;
186
9
    bh = (c->avctx->height + 7) >> 3;
187
9
    blocks = bw * bh;
188
189
9
    tmp = av_calloc(blocks, 64 * BINKB_NB_SRC);
190
9
    if (!tmp)
191
        return AVERROR(ENOMEM);
192
99
    for (i = 0; i < BINKB_NB_SRC; i++) {
193
90
        c->bundle[i].data     = tmp;
194
90
        tmp                  += blocks * 64;
195
90
        c->bundle[i].data_end = tmp;
196
    }
197
198
9
    return 0;
199
}
200
201
/**
202
 * Free memory used by bundles.
203
 *
204
 * @param c decoder context
205
 */
206
9
static av_cold void free_bundles(BinkContext *c)
207
{
208
9
    av_freep(&c->bundle[0].data);
209
9
}
210
211
/**
212
 * Merge two consequent lists of equal size depending on bits read.
213
 *
214
 * @param gb   context for reading bits
215
 * @param dst  buffer where merged list will be written to
216
 * @param src  pointer to the head of the first list (the second lists starts at src+size)
217
 * @param size input lists size
218
 */
219
1600
static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
220
{
221
1600
    uint8_t *src2 = src + size;
222
1600
    int size2 = size;
223
224
    do {
225
3761
        if (!get_bits1(gb)) {
226
2289
            *dst++ = *src++;
227
2289
            size--;
228
        } else {
229
1472
            *dst++ = *src2++;
230
1472
            size2--;
231
        }
232

3761
    } while (size && size2);
233
234
2551
    while (size--)
235
951
        *dst++ = *src++;
236
3368
    while (size2--)
237
1768
        *dst++ = *src2++;
238
1600
}
239
240
/**
241
 * Read information about Huffman tree used to decode data.
242
 *
243
 * @param gb   context for reading bits
244
 * @param tree pointer for storing tree data
245
 */
246
3519
static int read_tree(GetBitContext *gb, Tree *tree)
247
{
248
3519
    uint8_t tmp1[16] = { 0 }, tmp2[16], *in = tmp1, *out = tmp2;
249
    int i, t, len;
250
251
3519
    if (get_bits_left(gb) < 4)
252
        return AVERROR_INVALIDDATA;
253
254
3519
    tree->vlc_num = get_bits(gb, 4);
255
3519
    if (!tree->vlc_num) {
256
26163
        for (i = 0; i < 16; i++)
257
24624
            tree->syms[i] = i;
258
1539
        return 0;
259
    }
260
1980
    if (get_bits1(gb)) {
261
1871
        len = get_bits(gb, 3);
262
8413
        for (i = 0; i <= len; i++) {
263
6542
            tree->syms[i] = get_bits(gb, 4);
264
6542
            tmp1[tree->syms[i]] = 1;
265
        }
266

30950
        for (i = 0; i < 16 && len < 16 - 1; i++)
267
29079
            if (!tmp1[i])
268
23394
                tree->syms[++len] = i;
269
    } else {
270
109
        len = get_bits(gb, 2);
271
1853
        for (i = 0; i < 16; i++)
272
1744
            in[i] = i;
273
514
        for (i = 0; i <= len; i++) {
274
405
            int size = 1 << i;
275
2005
            for (t = 0; t < 16; t += size << 1)
276
1600
                merge(gb, out + t, in + t, size);
277
405
            FFSWAP(uint8_t*, in, out);
278
        }
279
109
        memcpy(tree->syms, in, 16);
280
    }
281
1980
    return 0;
282
}
283
284
/**
285
 * Prepare bundle for decoding data.
286
 *
287
 * @param gb          context for reading bits
288
 * @param c           decoder context
289
 * @param bundle_num  number of the bundle to initialize
290
 */
291
1377
static int read_bundle(GetBitContext *gb, BinkContext *c, int bundle_num)
292
{
293
    int i;
294
295
1377
    if (bundle_num == BINK_SRC_COLORS) {
296
2601
        for (i = 0; i < 16; i++) {
297
2448
            int ret = read_tree(gb, &c->col_high[i]);
298
2448
            if (ret < 0)
299
                return ret;
300
        }
301
153
        c->col_lastval = 0;
302
    }
303

1377
    if (bundle_num != BINK_SRC_INTRA_DC && bundle_num != BINK_SRC_INTER_DC) {
304
1071
        int ret = read_tree(gb, &c->bundle[bundle_num].tree);
305
1071
        if (ret < 0)
306
            return ret;
307
    }
308
1377
    c->bundle[bundle_num].cur_dec =
309
1377
    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
310
311
1377
    return 0;
312
}
313
314
/**
315
 * common check before starting decoding bundle data
316
 *
317
 * @param gb context for reading bits
318
 * @param b  bundle
319
 * @param t  variable where number of elements to decode will be stored
320
 */
321
#define CHECK_READ_VAL(gb, b, t) \
322
    if (!b->cur_dec || (b->cur_dec > b->cur_ptr)) \
323
        return 0; \
324
    t = get_bits(gb, b->len); \
325
    if (!t) { \
326
        b->cur_dec = NULL; \
327
        return 0; \
328
    } \
329
330
6120
static int read_runs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
331
{
332
    int t, v;
333
    const uint8_t *dec_end;
334
335

6120
    CHECK_READ_VAL(gb, b, t);
336
285
    dec_end = b->cur_dec + t;
337
285
    if (dec_end > b->data_end) {
338
        av_log(avctx, AV_LOG_ERROR, "Run value went out of bounds\n");
339
        return AVERROR_INVALIDDATA;
340
    }
341
285
    if (get_bits_left(gb) < 1)
342
        return AVERROR_INVALIDDATA;
343
285
    if (get_bits1(gb)) {
344
        v = get_bits(gb, 4);
345
        memset(b->cur_dec, v, t);
346
        b->cur_dec += t;
347
    } else {
348
97098
        while (b->cur_dec < dec_end)
349
96813
            *b->cur_dec++ = GET_HUFF(gb, b->tree);
350
    }
351
285
    return 0;
352
}
353
354
12240
static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
355
{
356
    int t, sign, v;
357
    const uint8_t *dec_end;
358
359

12240
    CHECK_READ_VAL(gb, b, t);
360
572
    dec_end = b->cur_dec + t;
361
572
    if (dec_end > b->data_end) {
362
        av_log(avctx, AV_LOG_ERROR, "Too many motion values\n");
363
        return AVERROR_INVALIDDATA;
364
    }
365
572
    if (get_bits_left(gb) < 1)
366
        return AVERROR_INVALIDDATA;
367
572
    if (get_bits1(gb)) {
368
        v = get_bits(gb, 4);
369
        if (v) {
370
            sign = -get_bits1(gb);
371
            v = (v ^ sign) - sign;
372
        }
373
        memset(b->cur_dec, v, t);
374
        b->cur_dec += t;
375
    } else {
376
221164
        while (b->cur_dec < dec_end) {
377
220592
            v = GET_HUFF(gb, b->tree);
378
220592
            if (v) {
379
207492
                sign = -get_bits1(gb);
380
207492
                v = (v ^ sign) - sign;
381
            }
382
220592
            *b->cur_dec++ = v;
383
        }
384
    }
385
572
    return 0;
386
}
387
388
static const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
389
390
12240
static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
391
{
392
12240
    BinkContext * const c = avctx->priv_data;
393
    int t, v;
394
12240
    int last = 0;
395
    const uint8_t *dec_end;
396
397

12240
    CHECK_READ_VAL(gb, b, t);
398
832
    if (c->version == 'k') {
399
        t ^= 0xBBu;
400
        if (t == 0) {
401
            b->cur_dec = NULL;
402
            return 0;
403
        }
404
    }
405
832
    dec_end = b->cur_dec + t;
406
832
    if (dec_end > b->data_end) {
407
        av_log(avctx, AV_LOG_ERROR, "Too many block type values\n");
408
        return AVERROR_INVALIDDATA;
409
    }
410
832
    if (get_bits_left(gb) < 1)
411
        return AVERROR_INVALIDDATA;
412
832
    if (get_bits1(gb)) {
413
        v = get_bits(gb, 4);
414
        memset(b->cur_dec, v, t);
415
        b->cur_dec += t;
416
    } else {
417
252252
        while (b->cur_dec < dec_end) {
418
251420
            v = GET_HUFF(gb, b->tree);
419
251420
            if (v < 12) {
420
238193
                last = v;
421
238193
                *b->cur_dec++ = v;
422
            } else {
423
13227
                int run = bink_rlelens[v - 12];
424
425
13227
                if (dec_end - b->cur_dec < run)
426
                    return AVERROR_INVALIDDATA;
427
13227
                memset(b->cur_dec, last, run);
428
13227
                b->cur_dec += run;
429
            }
430
        }
431
    }
432
832
    return 0;
433
}
434
435
6120
static int read_patterns(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
436
{
437
    int t, v;
438
    const uint8_t *dec_end;
439
440

6120
    CHECK_READ_VAL(gb, b, t);
441
206
    dec_end = b->cur_dec + t;
442
206
    if (dec_end > b->data_end) {
443
        av_log(avctx, AV_LOG_ERROR, "Too many pattern values\n");
444
        return AVERROR_INVALIDDATA;
445
    }
446
53502
    while (b->cur_dec < dec_end) {
447
53296
        if (get_bits_left(gb) < 2)
448
            return AVERROR_INVALIDDATA;
449
53296
        v  = GET_HUFF(gb, b->tree);
450
53296
        v |= GET_HUFF(gb, b->tree) << 4;
451
53296
        *b->cur_dec++ = v;
452
    }
453
454
206
    return 0;
455
}
456
457
6120
static int read_colors(GetBitContext *gb, Bundle *b, BinkContext *c)
458
{
459
    int t, sign, v;
460
    const uint8_t *dec_end;
461
462

6120
    CHECK_READ_VAL(gb, b, t);
463
410
    dec_end = b->cur_dec + t;
464
410
    if (dec_end > b->data_end) {
465
        av_log(c->avctx, AV_LOG_ERROR, "Too many color values\n");
466
        return AVERROR_INVALIDDATA;
467
    }
468
410
    if (get_bits_left(gb) < 1)
469
        return AVERROR_INVALIDDATA;
470
410
    if (get_bits1(gb)) {
471
        c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
472
        v = GET_HUFF(gb, b->tree);
473
        v = (c->col_lastval << 4) | v;
474
        if (c->version < 'i') {
475
            sign = ((int8_t) v) >> 7;
476
            v = ((v & 0x7F) ^ sign) - sign;
477
            v += 0x80;
478
        }
479
        memset(b->cur_dec, v, t);
480
        b->cur_dec += t;
481
    } else {
482
191282
        while (b->cur_dec < dec_end) {
483
190872
            if (get_bits_left(gb) < 2)
484
                return AVERROR_INVALIDDATA;
485
190872
            c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
486
190872
            v = GET_HUFF(gb, b->tree);
487
190872
            v = (c->col_lastval << 4) | v;
488
190872
            if (c->version < 'i') {
489
148464
                sign = ((int8_t) v) >> 7;
490
148464
                v = ((v & 0x7F) ^ sign) - sign;
491
148464
                v += 0x80;
492
            }
493
190872
            *b->cur_dec++ = v;
494
        }
495
    }
496
410
    return 0;
497
}
498
499
/** number of bits used to store first DC value in bundle */
500
#define DC_START_BITS 11
501
502
12240
static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,
503
                    int start_bits, int has_sign)
504
{
505
    int i, j, len, len2, bsize, sign, v, v2;
506
12240
    int16_t *dst     = (int16_t*)b->cur_dec;
507
12240
    int16_t *dst_end = (int16_t*)b->data_end;
508
509

12240
    CHECK_READ_VAL(gb, b, len);
510
332
    if (get_bits_left(gb) < start_bits - has_sign)
511
        return AVERROR_INVALIDDATA;
512
332
    v = get_bits(gb, start_bits - has_sign);
513

332
    if (v && has_sign) {
514
129
        sign = -get_bits1(gb);
515
129
        v = (v ^ sign) - sign;
516
    }
517
332
    if (dst_end - dst < 1)
518
        return AVERROR_INVALIDDATA;
519
332
    *dst++ = v;
520
332
    len--;
521
6125
    for (i = 0; i < len; i += 8) {
522
5793
        len2 = FFMIN(len - i, 8);
523
5793
        if (dst_end - dst < len2)
524
            return AVERROR_INVALIDDATA;
525
5793
        bsize = get_bits(gb, 4);
526
5793
        if (bsize) {
527
50942
            for (j = 0; j < len2; j++) {
528
45153
                v2 = get_bits(gb, bsize);
529
45153
                if (v2) {
530
42581
                    sign = -get_bits1(gb);
531
42581
                    v2 = (v2 ^ sign) - sign;
532
                }
533
45153
                v += v2;
534
45153
                *dst++ = v;
535

45153
                if (v < -32768 || v > 32767) {
536
                    av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v);
537
                    return AVERROR_INVALIDDATA;
538
                }
539
            }
540
        } else {
541
22
            for (j = 0; j < len2; j++)
542
18
                *dst++ = v;
543
        }
544
    }
545
546
332
    b->cur_dec = (uint8_t*)dst;
547
332
    return 0;
548
}
549
550
/**
551
 * Retrieve next value from bundle.
552
 *
553
 * @param c      decoder context
554
 * @param bundle bundle number
555
 */
556
939741
static inline int get_value(BinkContext *c, int bundle)
557
{
558
    int ret;
559
560

939741
    if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN)
561
673646
        return *c->bundle[bundle].cur_ptr++;
562

266095
    if (bundle == BINK_SRC_X_OFF || bundle == BINK_SRC_Y_OFF)
563
220592
        return (int8_t)*c->bundle[bundle].cur_ptr++;
564
45503
    ret = *(int16_t*)c->bundle[bundle].cur_ptr;
565
45503
    c->bundle[bundle].cur_ptr += 2;
566
45503
    return ret;
567
}
568
569
900
static av_cold void binkb_init_bundle(BinkContext *c, int bundle_num)
570
{
571
900
    c->bundle[bundle_num].cur_dec =
572
900
    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
573
900
    c->bundle[bundle_num].len = 13;
574
900
}
575
576
90
static av_cold void binkb_init_bundles(BinkContext *c)
577
{
578
    int i;
579
990
    for (i = 0; i < BINKB_NB_SRC; i++)
580
900
        binkb_init_bundle(c, i);
581
90
}
582
583
9300
static int binkb_read_bundle(BinkContext *c, GetBitContext *gb, int bundle_num)
584
{
585
9300
    const int bits = binkb_bundle_sizes[bundle_num];
586
9300
    const int mask = 1 << (bits - 1);
587
9300
    const int issigned = binkb_bundle_signed[bundle_num];
588
9300
    Bundle *b = &c->bundle[bundle_num];
589
    int i, len;
590
591

9300
    CHECK_READ_VAL(gb, b, len);
592

468
    if (b->data_end - b->cur_dec < len * (1 + (bits > 8)))
593
        return AVERROR_INVALIDDATA;
594
468
    if (bits <= 8) {
595
463
        if (!issigned) {
596
40084
            for (i = 0; i < len; i++)
597
39801
                *b->cur_dec++ = get_bits(gb, bits);
598
        } else {
599
27350
            for (i = 0; i < len; i++)
600
27170
                *b->cur_dec++ = get_bits(gb, bits) - mask;
601
        }
602
    } else {
603
5
        int16_t *dst = (int16_t*)b->cur_dec;
604
605
5
        if (!issigned) {
606
            for (i = 0; i < len; i++)
607
                *dst++ = get_bits(gb, bits);
608
        } else {
609
10
            for (i = 0; i < len; i++)
610
5
                *dst++ = get_bits(gb, bits) - mask;
611
        }
612
5
        b->cur_dec = (uint8_t*)dst;
613
    }
614
468
    return 0;
615
}
616
617
61472
static inline int binkb_get_value(BinkContext *c, int bundle_num)
618
{
619
    int16_t ret;
620
61472
    const int bits = binkb_bundle_sizes[bundle_num];
621
622
61472
    if (bits <= 8) {
623
61467
        int val = *c->bundle[bundle_num].cur_ptr++;
624
61467
        return binkb_bundle_signed[bundle_num] ? (int8_t)val : val;
625
    }
626
5
    ret = *(int16_t*)c->bundle[bundle_num].cur_ptr;
627
5
    c->bundle[bundle_num].cur_ptr += 2;
628
5
    return ret;
629
}
630
631
/**
632
 * Read 8x8 block of DCT coefficients.
633
 *
634
 * @param gb       context for reading bits
635
 * @param block    place for storing coefficients
636
 * @param scan     scan order table
637
 * @param quant_matrices quantization matrices
638
 * @return 0 for success, negative value in other cases
639
 */
640
45508
static int read_dct_coeffs(BinkContext *c, GetBitContext *gb, int32_t block[64],
641
                           const uint8_t *scan, int *coef_count_,
642
                           int coef_idx[64], int q)
643
{
644
    int coef_list[128];
645
    int mode_list[128];
646
    int i, t, bits, ccoef, mode, sign;
647
45508
    int list_start = 64, list_end = 64, list_pos;
648
45508
    int coef_count = 0;
649
    int quant_idx;
650
651
45508
    if (get_bits_left(gb) < 4)
652
        return AVERROR_INVALIDDATA;
653
654
45508
    coef_list[list_end] = 4;  mode_list[list_end++] = 0;
655
45508
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
656
45508
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
657
45508
    coef_list[list_end] = 1;  mode_list[list_end++] = 3;
658
45508
    coef_list[list_end] = 2;  mode_list[list_end++] = 3;
659
45508
    coef_list[list_end] = 3;  mode_list[list_end++] = 3;
660
661
147042
    for (bits = get_bits(gb, 4) - 1; bits >= 0; bits--) {
662
101534
        list_pos = list_start;
663
101534
        while (list_pos < list_end) {
664

982733
            if (!(mode_list[list_pos] | coef_list[list_pos]) || !get_bits1(gb)) {
665
671039
                list_pos++;
666
671039
                continue;
667
            }
668
311694
            ccoef = coef_list[list_pos];
669
311694
            mode  = mode_list[list_pos];
670

311694
            switch (mode) {
671
66858
            case 0:
672
66858
                coef_list[list_pos] = ccoef + 4;
673
66858
                mode_list[list_pos] = 1;
674
121182
            case 2:
675
121182
                if (mode == 2) {
676
54324
                    coef_list[list_pos]   = 0;
677
54324
                    mode_list[list_pos++] = 0;
678
                }
679
605910
                for (i = 0; i < 4; i++, ccoef++) {
680
484728
                    if (get_bits1(gb)) {
681
291256
                        coef_list[--list_start] = ccoef;
682
291256
                        mode_list[  list_start] = 3;
683
                    } else {
684
193472
                        if (!bits) {
685
131103
                            t = 1 - (get_bits1(gb) << 1);
686
                        } else {
687
62369
                            t = get_bits(gb, bits) | 1 << bits;
688
62369
                            sign = -get_bits1(gb);
689
62369
                            t = (t ^ sign) - sign;
690
                        }
691
193472
                        block[scan[ccoef]] = t;
692
193472
                        coef_idx[coef_count++] = ccoef;
693
                    }
694
                }
695
121182
                break;
696
25484
            case 1:
697
25484
                mode_list[list_pos] = 2;
698
101936
                for (i = 0; i < 3; i++) {
699
76452
                    ccoef += 4;
700
76452
                    coef_list[list_end]   = ccoef;
701
76452
                    mode_list[list_end++] = 2;
702
                }
703
25484
                break;
704
165028
            case 3:
705
165028
                if (!bits) {
706
92955
                    t = 1 - (get_bits1(gb) << 1);
707
                } else {
708
72073
                    t = get_bits(gb, bits) | 1 << bits;
709
72073
                    sign = -get_bits1(gb);
710
72073
                    t = (t ^ sign) - sign;
711
                }
712
165028
                block[scan[ccoef]] = t;
713
165028
                coef_idx[coef_count++] = ccoef;
714
165028
                coef_list[list_pos]   = 0;
715
165028
                mode_list[list_pos++] = 0;
716
165028
                break;
717
            }
718
1084267
        }
719
    }
720
721
45508
    if (q == -1) {
722
45503
        quant_idx = get_bits(gb, 4);
723
    } else {
724
5
        quant_idx = q;
725
5
        if (quant_idx > 15U) {
726
            av_log(c->avctx, AV_LOG_ERROR, "quant_index %d out of range\n", quant_idx);
727
            return AVERROR_INVALIDDATA;
728
        }
729
    }
730
731
45508
    *coef_count_ = coef_count;
732
733
45508
    return quant_idx;
734
}
735
736
45508
static void unquantize_dct_coeffs(int32_t block[64], const uint32_t quant[64],
737
                                  int coef_count, int coef_idx[64],
738
                                  const uint8_t *scan)
739
{
740
    int i;
741
45508
    block[0] = (int)(block[0] * quant[0]) >> 11;
742
404008
    for (i = 0; i < coef_count; i++) {
743
358500
        int idx = coef_idx[i];
744
358500
        block[scan[idx]] = (int)(block[scan[idx]] * quant[idx]) >> 11;
745
    }
746
45508
}
747
748
/**
749
 * Read 8x8 block with residue after motion compensation.
750
 *
751
 * @param gb          context for reading bits
752
 * @param block       place to store read data
753
 * @param masks_count number of masks to decode
754
 * @return 0 on success, negative value in other cases
755
 */
756
17330
static int read_residue(GetBitContext *gb, int16_t block[64], int masks_count)
757
{
758
    int coef_list[128];
759
    int mode_list[128];
760
    int i, sign, mask, ccoef, mode;
761
17330
    int list_start = 64, list_end = 64, list_pos;
762
    int nz_coeff[64];
763
17330
    int nz_coeff_count = 0;
764
765
17330
    coef_list[list_end] =  4; mode_list[list_end++] = 0;
766
17330
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
767
17330
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
768
17330
    coef_list[list_end] =  0; mode_list[list_end++] = 2;
769
770
26427
    for (mask = 1 << get_bits(gb, 3); mask; mask >>= 1) {
771
92594
        for (i = 0; i < nz_coeff_count; i++) {
772
67080
            if (!get_bits1(gb))
773
42197
                continue;
774
24883
            if (block[nz_coeff[i]] < 0)
775
11567
                block[nz_coeff[i]] -= mask;
776
            else
777
13316
                block[nz_coeff[i]] += mask;
778
24883
            masks_count--;
779
24883
            if (masks_count < 0)
780
913
                return 0;
781
        }
782
25514
        list_pos = list_start;
783
25514
        while (list_pos < list_end) {
784

347825
            if (!(coef_list[list_pos] | mode_list[list_pos]) || !get_bits1(gb)) {
785
194572
                list_pos++;
786
194572
                continue;
787
            }
788
153253
            ccoef = coef_list[list_pos];
789
153253
            mode  = mode_list[list_pos];
790

153253
            switch (mode) {
791
33694
            case 0:
792
33694
                coef_list[list_pos] = ccoef + 4;
793
33694
                mode_list[list_pos] = 1;
794
91973
            case 2:
795
91973
                if (mode == 2) {
796
58279
                    coef_list[list_pos]   = 0;
797
58279
                    mode_list[list_pos++] = 0;
798
                }
799
423685
                for (i = 0; i < 4; i++, ccoef++) {
800
346698
                    if (get_bits1(gb)) {
801
249374
                        coef_list[--list_start] = ccoef;
802
249374
                        mode_list[  list_start] = 3;
803
                    } else {
804
97324
                        nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
805
97324
                        sign = -get_bits1(gb);
806
97324
                        block[bink_scan[ccoef]] = (mask ^ sign) - sign;
807
97324
                        masks_count--;
808
97324
                        if (masks_count < 0)
809
14986
                            return 0;
810
                    }
811
                }
812
76987
                break;
813
29117
            case 1:
814
29117
                mode_list[list_pos] = 2;
815
116468
                for (i = 0; i < 3; i++) {
816
87351
                    ccoef += 4;
817
87351
                    coef_list[list_end]   = ccoef;
818
87351
                    mode_list[list_end++] = 2;
819
                }
820
29117
                break;
821
32163
            case 3:
822
32163
                nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
823
32163
                sign = -get_bits1(gb);
824
32163
                block[bink_scan[ccoef]] = (mask ^ sign) - sign;
825
32163
                coef_list[list_pos]   = 0;
826
32163
                mode_list[list_pos++] = 0;
827
32163
                masks_count--;
828
32163
                if (masks_count < 0)
829
1431
                    return 0;
830
30732
                break;
831
            }
832
356922
        }
833
    }
834
835
    return 0;
836
}
837
838
/**
839
 * Copy 8x8 block from source to destination, where src and dst may be overlapped
840
 */
841
13417
static inline void put_pixels8x8_overlapped(uint8_t *dst, uint8_t *src, int stride)
842
{
843
    uint8_t tmp[64];
844
    int i;
845
120753
    for (i = 0; i < 8; i++)
846
107336
        memcpy(tmp + i*8, src + i*stride, 8);
847
120753
    for (i = 0; i < 8; i++)
848
107336
        memcpy(dst + i*stride, tmp + i*8, 8);
849
13417
}
850
851
90
static int binkb_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb,
852
                              int plane_idx, int is_key, int is_chroma)
853
{
854
    int blk, ret;
855
    int i, j, bx, by;
856
    uint8_t *dst, *ref, *ref_start, *ref_end;
857
    int v, col[2];
858
    const uint8_t *scan;
859
    int xoff, yoff;
860
90
    LOCAL_ALIGNED_32(int16_t, block, [64]);
861
90
    LOCAL_ALIGNED_16(int32_t, dctblock, [64]);
862
    int coordmap[64];
863
90
    int ybias = is_key ? -15 : 0;
864
    int qp, quant_idx, coef_count, coef_idx[64];
865
866
90
    const int stride = frame->linesize[plane_idx];
867
90
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
868
90
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
869
870
90
    binkb_init_bundles(c);
871
90
    ref_start = frame->data[plane_idx];
872
90
    ref_end   = frame->data[plane_idx] + (bh * frame->linesize[plane_idx] + bw) * 8;
873
874
5850
    for (i = 0; i < 64; i++)
875
5760
        coordmap[i] = (i & 7) + (i >> 3) * stride;
876
877
1020
    for (by = 0; by < bh; by++) {
878
10230
        for (i = 0; i < BINKB_NB_SRC; i++) {
879
9300
            if ((ret = binkb_read_bundle(c, gb, i)) < 0)
880
                return ret;
881
        }
882
883
930
        dst  = frame->data[plane_idx]  + 8*by*stride;
884
18420
        for (bx = 0; bx < bw; bx++, dst += 8) {
885
17490
            blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES);
886


17490
            switch (blk) {
887
3593
            case 0:
888
3593
                break;
889
184
            case 1:
890
184
                scan = bink_patterns[get_bits(gb, 4)];
891
184
                i = 0;
892
                do {
893
                    int mode, run;
894
895
1732
                    mode = get_bits1(gb);
896
1732
                    run = get_bits(gb, binkb_runbits[i]) + 1;
897
898
1732
                    i += run;
899
1732
                    if (i > 64) {
900
                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
901
                        return AVERROR_INVALIDDATA;
902
                    }
903
1732
                    if (mode) {
904
1172
                        v = binkb_get_value(c, BINKB_SRC_COLORS);
905
11075
                        for (j = 0; j < run; j++)
906
9903
                            dst[coordmap[*scan++]] = v;
907
                    } else {
908
2388
                        for (j = 0; j < run; j++)
909
1828
                            dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
910
                    }
911
1732
                } while (i < 63);
912
184
                if (i == 63)
913
45
                    dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
914
184
                break;
915
            case 2:
916
                memset(dctblock, 0, sizeof(*dctblock) * 64);
917
                dctblock[0] = binkb_get_value(c, BINKB_SRC_INTRA_DC);
918
                qp = binkb_get_value(c, BINKB_SRC_INTRA_Q);
919
                if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, qp)) < 0)
920
                    return quant_idx;
921
                unquantize_dct_coeffs(dctblock, binkb_intra_quant[quant_idx], coef_count, coef_idx, bink_scan);
922
                c->binkdsp.idct_put(dst, stride, dctblock);
923
                break;
924
13580
            case 3:
925
13580
                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
926
13580
                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
927
13580
                ref = dst + xoff + yoff * stride;
928

13580
                if (ref < ref_start || ref + 8*stride > ref_end) {
929
                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
930

13580
                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
931
168
                    c->put_pixels_tab(dst, ref, stride, 8);
932
                } else {
933
13412
                    put_pixels8x8_overlapped(dst, ref, stride);
934
                }
935
13580
                c->bdsp.clear_block(block);
936
13580
                v = binkb_get_value(c, BINKB_SRC_INTER_COEFS);
937
13580
                read_residue(gb, block, v);
938
13580
                c->binkdsp.add_pixels8(dst, block, stride);
939
13580
                break;
940
5
            case 4:
941
5
                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
942
5
                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
943
5
                ref = dst + xoff + yoff * stride;
944

5
                if (ref < ref_start || ref + 8 * stride > ref_end) {
945
                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
946

5
                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
947
                    c->put_pixels_tab(dst, ref, stride, 8);
948
                } else {
949
5
                    put_pixels8x8_overlapped(dst, ref, stride);
950
                }
951
5
                memset(dctblock, 0, sizeof(*dctblock) * 64);
952
5
                dctblock[0] = binkb_get_value(c, BINKB_SRC_INTER_DC);
953
5
                qp = binkb_get_value(c, BINKB_SRC_INTER_Q);
954
5
                if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, qp)) < 0)
955
                    return quant_idx;
956
5
                unquantize_dct_coeffs(dctblock, binkb_inter_quant[quant_idx], coef_count, coef_idx, bink_scan);
957
5
                c->binkdsp.idct_add(dst, stride, dctblock);
958
5
                break;
959
27
            case 5:
960
27
                v = binkb_get_value(c, BINKB_SRC_COLORS);
961
27
                c->bdsp.fill_block_tab[1](dst, v, stride, 8);
962
27
                break;
963
15
            case 6:
964
45
                for (i = 0; i < 2; i++)
965
30
                    col[i] = binkb_get_value(c, BINKB_SRC_COLORS);
966
135
                for (i = 0; i < 8; i++) {
967
120
                    v = binkb_get_value(c, BINKB_SRC_PATTERN);
968
1080
                    for (j = 0; j < 8; j++, v >>= 1)
969
960
                        dst[i*stride + j] = col[v & 1];
970
                }
971
15
                break;
972
            case 7:
973
                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
974
                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
975
                ref = dst + xoff + yoff * stride;
976
                if (ref < ref_start || ref + 8 * stride > ref_end) {
977
                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
978
                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
979
                    c->put_pixels_tab(dst, ref, stride, 8);
980
                } else {
981
                    put_pixels8x8_overlapped(dst, ref, stride);
982
                }
983
                break;
984
86
            case 8:
985
774
                for (i = 0; i < 8; i++)
986
688
                    memcpy(dst + i*stride, c->bundle[BINKB_SRC_COLORS].cur_ptr + i*8, 8);
987
86
                c->bundle[BINKB_SRC_COLORS].cur_ptr += 64;
988
86
                break;
989
            default:
990
                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
991
                return AVERROR_INVALIDDATA;
992
            }
993
        }
994
    }
995
90
    if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
996
87
        skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
997
998
90
    return 0;
999
}
1000
1001
110296
static int bink_put_pixels(BinkContext *c,
1002
                           uint8_t *dst, uint8_t *prev, int stride,
1003
                           uint8_t *ref_start,
1004
                           uint8_t *ref_end)
1005
{
1006
110296
    int xoff     = get_value(c, BINK_SRC_X_OFF);
1007
110296
    int yoff     = get_value(c, BINK_SRC_Y_OFF);
1008
110296
    uint8_t *ref = prev + xoff + yoff * stride;
1009

110296
    if (ref < ref_start || ref > ref_end) {
1010
        av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
1011
               xoff, yoff);
1012
        return AVERROR_INVALIDDATA;
1013
    }
1014
110296
    c->put_pixels_tab(dst, ref, stride, 8);
1015
1016
110296
    return 0;
1017
}
1018
1019
153
static int bink_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb,
1020
                             int plane_idx, int is_chroma)
1021
{
1022
    int blk, ret;
1023
    int i, j, bx, by;
1024
    uint8_t *dst, *prev, *ref_start, *ref_end;
1025
    int v, col[2];
1026
    const uint8_t *scan;
1027
153
    LOCAL_ALIGNED_32(int16_t, block, [64]);
1028
153
    LOCAL_ALIGNED_16(uint8_t, ublock, [64]);
1029
153
    LOCAL_ALIGNED_16(int32_t, dctblock, [64]);
1030
    int coordmap[64], quant_idx, coef_count, coef_idx[64];
1031
1032
153
    const int stride = frame->linesize[plane_idx];
1033
153
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
1034
153
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
1035
153
    int width = c->avctx->width >> is_chroma;
1036
153
    int height = c->avctx->height >> is_chroma;
1037
1038

153
    if (c->version == 'k' && get_bits1(gb)) {
1039
        int fill = get_bits(gb, 8);
1040
1041
        dst = frame->data[plane_idx];
1042
1043
        for (i = 0; i < height; i++)
1044
            memset(dst + i * stride, fill, width);
1045
        goto end;
1046
    }
1047
1048
153
    init_lengths(c, FFMAX(width, 8), bw);
1049
1530
    for (i = 0; i < BINK_NB_SRC; i++) {
1050
1377
        ret = read_bundle(gb, c, i);
1051
1377
        if (ret < 0)
1052
            return ret;
1053
    }
1054
1055
453
    ref_start = c->last->data[plane_idx] ? c->last->data[plane_idx]
1056
153
                                         : frame->data[plane_idx];
1057
153
    ref_end   = ref_start
1058
153
                + (bw - 1 + c->last->linesize[plane_idx] * (bh - 1)) * 8;
1059
1060
9945
    for (i = 0; i < 64; i++)
1061
9792
        coordmap[i] = (i & 7) + (i >> 3) * stride;
1062
1063
6273
    for (by = 0; by < bh; by++) {
1064
6120
        if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES])) < 0)
1065
            return ret;
1066
6120
        if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES])) < 0)
1067
            return ret;
1068
6120
        if ((ret = read_colors(gb, &c->bundle[BINK_SRC_COLORS], c)) < 0)
1069
            return ret;
1070
6120
        if ((ret = read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN])) < 0)
1071
            return ret;
1072
6120
        if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF])) < 0)
1073
            return ret;
1074
6120
        if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF])) < 0)
1075
            return ret;
1076
6120
        if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0)) < 0)
1077
            return ret;
1078
6120
        if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1)) < 0)
1079
            return ret;
1080
6120
        if ((ret = read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN])) < 0)
1081
            return ret;
1082
1083
6120
        dst  = frame->data[plane_idx]  + 8*by*stride;
1084
18120
        prev = (c->last->data[plane_idx] ? c->last->data[plane_idx]
1085
6120
                                         : frame->data[plane_idx]) + 8*by*stride;
1086
320890
        for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {
1087
314770
            blk = get_value(c, BINK_SRC_BLOCK_TYPES);
1088
            // 16x16 block type on odd line means part of the already decoded block, so skip it
1089

314770
            if ((by & 1) && blk == SCALED_BLOCK) {
1090
26215
                bx++;
1091
26215
                dst  += 8;
1092
26215
                prev += 8;
1093
26215
                continue;
1094
            }
1095


288555
            switch (blk) {
1096
85550
            case SKIP_BLOCK:
1097
85550
                c->put_pixels_tab(dst, prev, stride, 8);
1098
85550
                break;
1099
26215
            case SCALED_BLOCK:
1100
26215
                blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);
1101
                switch (blk) {
1102
902
                case RUN_BLOCK:
1103
902
                    if (get_bits_left(gb) < 4)
1104
                        return AVERROR_INVALIDDATA;
1105
902
                    scan = bink_patterns[get_bits(gb, 4)];
1106
902
                    i = 0;
1107
                    do {
1108
6551
                        int run = get_value(c, BINK_SRC_RUN) + 1;
1109
1110
6551
                        i += run;
1111
6551
                        if (i > 64) {
1112
                            av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1113
                            return AVERROR_INVALIDDATA;
1114
                        }
1115
6551
                        if (get_bits1(gb)) {
1116
5908
                            v = get_value(c, BINK_SRC_COLORS);
1117
62492
                            for (j = 0; j < run; j++)
1118
56584
                                ublock[*scan++] = v;
1119
                        } else {
1120
1690
                            for (j = 0; j < run; j++)
1121
1047
                                ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
1122
                        }
1123
6551
                    } while (i < 63);
1124
902
                    if (i == 63)
1125
97
                        ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
1126
902
                    break;
1127
19454
                case INTRA_BLOCK:
1128
19454
                    memset(dctblock, 0, sizeof(*dctblock) * 64);
1129
19454
                    dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);
1130
19454
                    if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, -1)) < 0)
1131
                        return quant_idx;
1132
19454
                    unquantize_dct_coeffs(dctblock, bink_intra_quant[quant_idx], coef_count, coef_idx, bink_scan);
1133
19454
                    c->binkdsp.idct_put(ublock, 8, dctblock);
1134
19454
                    break;
1135
5108
                case FILL_BLOCK:
1136
5108
                    v = get_value(c, BINK_SRC_COLORS);
1137
5108
                    c->bdsp.fill_block_tab[0](dst, v, stride, 16);
1138
5108
                    break;
1139
751
                case PATTERN_BLOCK:
1140
2253
                    for (i = 0; i < 2; i++)
1141
1502
                        col[i] = get_value(c, BINK_SRC_COLORS);
1142
6759
                    for (j = 0; j < 8; j++) {
1143
6008
                        v = get_value(c, BINK_SRC_PATTERN);
1144
54072
                        for (i = 0; i < 8; i++, v >>= 1)
1145
48064
                            ublock[i + j*8] = col[v & 1];
1146
                    }
1147
751
                    break;
1148
                case RAW_BLOCK:
1149
                    for (j = 0; j < 8; j++)
1150
                        for (i = 0; i < 8; i++)
1151
                            ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);
1152
                    break;
1153
                default:
1154
                    av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);
1155
                    return AVERROR_INVALIDDATA;
1156
                }
1157
26215
                if (blk != FILL_BLOCK)
1158
21107
                c->binkdsp.scale_block(ublock, dst, stride);
1159
26215
                bx++;
1160
26215
                dst  += 8;
1161
26215
                prev += 8;
1162
26215
                break;
1163
97378
            case MOTION_BLOCK:
1164
97378
                ret = bink_put_pixels(c, dst, prev, stride,
1165
                                      ref_start, ref_end);
1166
97378
                if (ret < 0)
1167
                    return ret;
1168
97378
                break;
1169
11625
            case RUN_BLOCK:
1170
11625
                scan = bink_patterns[get_bits(gb, 4)];
1171
11625
                i = 0;
1172
                do {
1173
90262
                    int run = get_value(c, BINK_SRC_RUN) + 1;
1174
1175
90262
                    i += run;
1176
90262
                    if (i > 64) {
1177
                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1178
                        return AVERROR_INVALIDDATA;
1179
                    }
1180
90262
                    if (get_bits1(gb)) {
1181
76178
                        v = get_value(c, BINK_SRC_COLORS);
1182
771235
                        for (j = 0; j < run; j++)
1183
695057
                            dst[coordmap[*scan++]] = v;
1184
                    } else {
1185
62125
                        for (j = 0; j < run; j++)
1186
48041
                            dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
1187
                    }
1188
90262
                } while (i < 63);
1189
11625
                if (i == 63)
1190
902
                    dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
1191
11625
                break;
1192
3750
            case RESIDUE_BLOCK:
1193
3750
                ret = bink_put_pixels(c, dst, prev, stride,
1194
                                      ref_start, ref_end);
1195
3750
                if (ret < 0)
1196
                    return ret;
1197
3750
                c->bdsp.clear_block(block);
1198
3750
                v = get_bits(gb, 7);
1199
3750
                read_residue(gb, block, v);
1200
3750
                c->binkdsp.add_pixels8(dst, block, stride);
1201
3750
                break;
1202
16881
            case INTRA_BLOCK:
1203
16881
                memset(dctblock, 0, sizeof(*dctblock) * 64);
1204
16881
                dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);
1205
16881
                if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, -1)) < 0)
1206
                    return quant_idx;
1207
16881
                unquantize_dct_coeffs(dctblock, bink_intra_quant[quant_idx], coef_count, coef_idx, bink_scan);
1208
16881
                c->binkdsp.idct_put(dst, stride, dctblock);
1209
16881
                break;
1210
31947
            case FILL_BLOCK:
1211
31947
                v = get_value(c, BINK_SRC_COLORS);
1212
31947
                c->bdsp.fill_block_tab[1](dst, v, stride, 8);
1213
31947
                break;
1214
9168
            case INTER_BLOCK:
1215
9168
                ret = bink_put_pixels(c, dst, prev, stride,
1216
                                      ref_start, ref_end);
1217
9168
                if (ret < 0)
1218
                    return ret;
1219
9168
                memset(dctblock, 0, sizeof(*dctblock) * 64);
1220
9168
                dctblock[0] = get_value(c, BINK_SRC_INTER_DC);
1221
9168
                if ((quant_idx = read_dct_coeffs(c, gb, dctblock, bink_scan, &coef_count, coef_idx, -1)) < 0)
1222
                    return quant_idx;
1223
9168
                unquantize_dct_coeffs(dctblock, bink_inter_quant[quant_idx], coef_count, coef_idx, bink_scan);
1224
9168
                c->binkdsp.idct_add(dst, stride, dctblock);
1225
9168
                break;
1226
5911
            case PATTERN_BLOCK:
1227
17733
                for (i = 0; i < 2; i++)
1228
11822
                    col[i] = get_value(c, BINK_SRC_COLORS);
1229
53199
                for (i = 0; i < 8; i++) {
1230
47288
                    v = get_value(c, BINK_SRC_PATTERN);
1231
425592
                    for (j = 0; j < 8; j++, v >>= 1)
1232
378304
                        dst[i*stride + j] = col[v & 1];
1233
                }
1234
5911
                break;
1235
130
            case RAW_BLOCK:
1236
1170
                for (i = 0; i < 8; i++)
1237
1040
                    memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);
1238
130
                c->bundle[BINK_SRC_COLORS].cur_ptr += 64;
1239
130
                break;
1240
            default:
1241
                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
1242
                return AVERROR_INVALIDDATA;
1243
            }
1244
        }
1245
    }
1246
1247
153
end:
1248
153
    if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
1249
151
        skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
1250
1251
153
    return 0;
1252
}
1253
1254
81
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)
1255
{
1256
81
    BinkContext * const c = avctx->priv_data;
1257
81
    AVFrame *frame = data;
1258
    GetBitContext gb;
1259
    int plane, plane_idx, ret;
1260
81
    int bits_count = pkt->size << 3;
1261
1262
81
    if (c->version > 'b') {
1263
51
        if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
1264
            return ret;
1265
    } else {
1266
30
        if ((ret = ff_reget_buffer(avctx, c->last, 0)) < 0)
1267
            return ret;
1268
30
        if ((ret = av_frame_ref(frame, c->last)) < 0)
1269
            return ret;
1270
    }
1271
1272
81
    init_get_bits(&gb, pkt->data, bits_count);
1273
81
    if (c->has_alpha) {
1274
        if (c->version >= 'i')
1275
            skip_bits_long(&gb, 32);
1276
        if ((ret = bink_decode_plane(c, frame, &gb, 3, 0)) < 0)
1277
            return ret;
1278
    }
1279
81
    if (c->version >= 'i')
1280
31
        skip_bits_long(&gb, 32);
1281
1282
81
    c->frame_num++;
1283
1284
243
    for (plane = 0; plane < 3; plane++) {
1285

243
        plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);
1286
1287
243
        if (c->version > 'b') {
1288
153
            if ((ret = bink_decode_plane(c, frame, &gb, plane_idx, !!plane)) < 0)
1289
                return ret;
1290
        } else {
1291
90
            if ((ret = binkb_decode_plane(c, frame, &gb, plane_idx,
1292
90
                                          c->frame_num == 1, !!plane)) < 0)
1293
                return ret;
1294
        }
1295
243
        if (get_bits_count(&gb) >= bits_count)
1296
81
            break;
1297
    }
1298
81
    emms_c();
1299
1300
81
    if (c->version > 'b') {
1301
51
        av_frame_unref(c->last);
1302
51
        if ((ret = av_frame_ref(c->last, frame)) < 0)
1303
            return ret;
1304
    }
1305
1306
81
    *got_frame = 1;
1307
1308
    /* always report that the buffer was completely consumed */
1309
81
    return pkt->size;
1310
}
1311
1312
/**
1313
 * Calculate quantization tables for version b
1314
 */
1315
1
static av_cold void binkb_calc_quant(void)
1316
{
1317
    uint8_t inv_bink_scan[64];
1318
    static const int s[64]={
1319
        1073741824,1489322693,1402911301,1262586814,1073741824, 843633538, 581104888, 296244703,
1320
        1489322693,2065749918,1945893874,1751258219,1489322693,1170153332, 806015634, 410903207,
1321
        1402911301,1945893874,1832991949,1649649171,1402911301,1102260336, 759250125, 387062357,
1322
        1262586814,1751258219,1649649171,1484645031,1262586814, 992008094, 683307060, 348346918,
1323
        1073741824,1489322693,1402911301,1262586814,1073741824, 843633538, 581104888, 296244703,
1324
         843633538,1170153332,1102260336, 992008094, 843633538, 662838617, 456571181, 232757969,
1325
         581104888, 806015634, 759250125, 683307060, 581104888, 456571181, 314491699, 160326478,
1326
         296244703, 410903207, 387062357, 348346918, 296244703, 232757969, 160326478,  81733730,
1327
    };
1328
    int i, j;
1329
#define C (1LL<<30)
1330
65
    for (i = 0; i < 64; i++)
1331
64
        inv_bink_scan[bink_scan[i]] = i;
1332
1333
17
    for (j = 0; j < 16; j++) {
1334
1040
        for (i = 0; i < 64; i++) {
1335
1024
            int k = inv_bink_scan[i];
1336
1024
            binkb_intra_quant[j][k] = binkb_intra_seed[i] * (int64_t)s[i] *
1337
1024
                                        binkb_num[j]/(binkb_den[j] * (C>>12));
1338
1024
            binkb_inter_quant[j][k] = binkb_inter_seed[i] * (int64_t)s[i] *
1339
1024
                                        binkb_num[j]/(binkb_den[j] * (C>>12));
1340
        }
1341
    }
1342
1
}
1343
1344
9
static av_cold int decode_init(AVCodecContext *avctx)
1345
{
1346
9
    BinkContext * const c = avctx->priv_data;
1347
    static VLC_TYPE table[16 * 128][2];
1348
    static int binkb_initialised = 0;
1349
    HpelDSPContext hdsp;
1350
    int i, ret;
1351
    int flags;
1352
1353
9
    c->version = avctx->codec_tag >> 24;
1354
9
    if (avctx->extradata_size < 4) {
1355
        av_log(avctx, AV_LOG_ERROR, "Extradata missing or too short\n");
1356
        return AVERROR_INVALIDDATA;
1357
    }
1358
9
    flags = AV_RL32(avctx->extradata);
1359
9
    c->has_alpha = flags & BINK_FLAG_ALPHA;
1360
9
    c->swap_planes = c->version >= 'h';
1361
9
    if (!bink_trees[15].table) {
1362
102
        for (i = 0; i < 16; i++) {
1363
96
            const int maxbits = bink_tree_lens[i][15];
1364
96
            bink_trees[i].table = table + i*128;
1365
96
            bink_trees[i].table_allocated = 1 << maxbits;
1366
96
            init_vlc(&bink_trees[i], maxbits, 16,
1367
                     bink_tree_lens[i], 1, 1,
1368
                     bink_tree_bits[i], 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
1369
        }
1370
    }
1371
9
    c->avctx = avctx;
1372
1373
9
    if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
1374
        return ret;
1375
1376
9
    c->last = av_frame_alloc();
1377
9
    if (!c->last)
1378
        return AVERROR(ENOMEM);
1379
1380
9
    avctx->pix_fmt = c->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;
1381
9
    avctx->color_range = c->version == 'k' ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
1382
1383
9
    ff_blockdsp_init(&c->bdsp, avctx);
1384
9
    ff_hpeldsp_init(&hdsp, avctx->flags);
1385
9
    c->put_pixels_tab = hdsp.put_pixels_tab[1][0];
1386
9
    ff_binkdsp_init(&c->binkdsp);
1387
1388
9
    if ((ret = init_bundles(c)) < 0)
1389
        return ret;
1390
1391
9
    if (c->version == 'b') {
1392
2
        if (!binkb_initialised) {
1393
1
            binkb_calc_quant();
1394
1
            binkb_initialised = 1;
1395
        }
1396
    }
1397
1398
9
    return 0;
1399
}
1400
1401
9
static av_cold int decode_end(AVCodecContext *avctx)
1402
{
1403
9
    BinkContext * const c = avctx->priv_data;
1404
1405
9
    av_frame_free(&c->last);
1406
1407
9
    free_bundles(c);
1408
9
    return 0;
1409
}
1410
1411
static void flush(AVCodecContext *avctx)
1412
{
1413
    BinkContext * const c = avctx->priv_data;
1414
1415
    c->frame_num = 0;
1416
}
1417
1418
AVCodec ff_bink_decoder = {
1419
    .name           = "binkvideo",
1420
    .long_name      = NULL_IF_CONFIG_SMALL("Bink video"),
1421
    .type           = AVMEDIA_TYPE_VIDEO,
1422
    .id             = AV_CODEC_ID_BINKVIDEO,
1423
    .priv_data_size = sizeof(BinkContext),
1424
    .init           = decode_init,
1425
    .close          = decode_end,
1426
    .decode         = decode_frame,
1427
    .flush          = flush,
1428
    .capabilities   = AV_CODEC_CAP_DR1,
1429
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
1430
};