Statistics
| Branch: | Revision:

ffmpeg / libavcodec / bink.c @ 2912e87a

History | View | Annotate | Download (43.4 KB)

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 Libav.
7
 *
8
 * Libav 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
 * Libav 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 Libav; 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/imgutils.h"
24
#include "avcodec.h"
25
#include "dsputil.h"
26
#include "binkdata.h"
27
#include "mathops.h"
28

    
29
#define ALT_BITSTREAM_READER_LE
30
#include "get_bits.h"
31

    
32
#define BINK_FLAG_ALPHA 0x00100000
33
#define BINK_FLAG_GRAY  0x00020000
34

    
35
static VLC bink_trees[16];
36

    
37
/**
38
 * IDs for different data types used in old version of Bink video codec
39
 */
40
enum OldSources {
41
    BINKB_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
42
    BINKB_SRC_COLORS,          ///< pixel values used for different block types
43
    BINKB_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
44
    BINKB_SRC_X_OFF,           ///< X components of motion value
45
    BINKB_SRC_Y_OFF,           ///< Y components of motion value
46
    BINKB_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
47
    BINKB_SRC_INTER_DC,        ///< DC values for interblocks with DCT
48
    BINKB_SRC_INTRA_Q,         ///< quantizer values for intrablocks with DCT
49
    BINKB_SRC_INTER_Q,         ///< quantizer values for interblocks with DCT
50
    BINKB_SRC_INTER_COEFS,     ///< number of coefficients for residue blocks
51

    
52
    BINKB_NB_SRC
53
};
54

    
55
static const int binkb_bundle_sizes[BINKB_NB_SRC] = {
56
    4, 8, 8, 5, 5, 11, 11, 4, 4, 7
57
};
58

    
59
static const int binkb_bundle_signed[BINKB_NB_SRC] = {
60
    0, 0, 0, 1, 1, 0, 1, 0, 0, 0
61
};
62

    
63
static uint32_t binkb_intra_quant[16][64];
64
static uint32_t binkb_inter_quant[16][64];
65

    
66
/**
67
 * IDs for different data types used in Bink video codec
68
 */
69
enum Sources {
70
    BINK_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
71
    BINK_SRC_SUB_BLOCK_TYPES, ///< 16x16 block types (a subset of 8x8 block types)
72
    BINK_SRC_COLORS,          ///< pixel values used for different block types
73
    BINK_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
74
    BINK_SRC_X_OFF,           ///< X components of motion value
75
    BINK_SRC_Y_OFF,           ///< Y components of motion value
76
    BINK_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
77
    BINK_SRC_INTER_DC,        ///< DC values for interblocks with DCT
78
    BINK_SRC_RUN,             ///< run lengths for special fill block
79

    
80
    BINK_NB_SRC
81
};
82

    
83
/**
84
 * data needed to decode 4-bit Huffman-coded value
85
 */
86
typedef struct Tree {
87
    int     vlc_num;  ///< tree number (in bink_trees[])
88
    uint8_t syms[16]; ///< leaf value to symbol mapping
89
} Tree;
90

    
91
#define GET_HUFF(gb, tree)  (tree).syms[get_vlc2(gb, bink_trees[(tree).vlc_num].table,\
92
                                                 bink_trees[(tree).vlc_num].bits, 1)]
93

    
94
/**
95
 * data structure used for decoding single Bink data type
96
 */
97
typedef struct Bundle {
98
    int     len;       ///< length of number of entries to decode (in bits)
99
    Tree    tree;      ///< Huffman tree-related data
100
    uint8_t *data;     ///< buffer for decoded symbols
101
    uint8_t *data_end; ///< buffer end
102
    uint8_t *cur_dec;  ///< pointer to the not yet decoded part of the buffer
103
    uint8_t *cur_ptr;  ///< pointer to the data that is not read from buffer yet
104
} Bundle;
105

    
106
/*
107
 * Decoder context
108
 */
109
typedef struct BinkContext {
110
    AVCodecContext *avctx;
111
    DSPContext     dsp;
112
    AVFrame        pic, last;
113
    int            version;              ///< internal Bink file version
114
    int            has_alpha;
115
    int            swap_planes;
116
    ScanTable      scantable;            ///< permutated scantable for DCT coeffs decoding
117

    
118
    Bundle         bundle[BINKB_NB_SRC]; ///< bundles for decoding all data types
119
    Tree           col_high[16];         ///< trees for decoding high nibble in "colours" data type
120
    int            col_lastval;          ///< value of last decoded high nibble in "colours" data type
121
} BinkContext;
122

    
123
/**
124
 * Bink video block types
125
 */
126
enum BlockTypes {
127
    SKIP_BLOCK = 0, ///< skipped block
128
    SCALED_BLOCK,   ///< block has size 16x16
129
    MOTION_BLOCK,   ///< block is copied from previous frame with some offset
130
    RUN_BLOCK,      ///< block is composed from runs of colours with custom scan order
131
    RESIDUE_BLOCK,  ///< motion block with some difference added
132
    INTRA_BLOCK,    ///< intra DCT block
133
    FILL_BLOCK,     ///< block is filled with single colour
134
    INTER_BLOCK,    ///< motion block with DCT applied to the difference
135
    PATTERN_BLOCK,  ///< block is filled with two colours following custom pattern
136
    RAW_BLOCK,      ///< uncoded 8x8 block
137
};
138

    
139
/**
140
 * Initialize length length in all bundles.
141
 *
142
 * @param c     decoder context
143
 * @param width plane width
144
 * @param bw    plane width in 8x8 blocks
145
 */
146
static void init_lengths(BinkContext *c, int width, int bw)
147
{
148
    c->bundle[BINK_SRC_BLOCK_TYPES].len = av_log2((width >> 3) + 511) + 1;
149

    
150
    c->bundle[BINK_SRC_SUB_BLOCK_TYPES].len = av_log2((width >> 4) + 511) + 1;
151

    
152
    c->bundle[BINK_SRC_COLORS].len = av_log2(bw*64 + 511) + 1;
153

    
154
    c->bundle[BINK_SRC_INTRA_DC].len =
155
    c->bundle[BINK_SRC_INTER_DC].len =
156
    c->bundle[BINK_SRC_X_OFF].len =
157
    c->bundle[BINK_SRC_Y_OFF].len = av_log2((width >> 3) + 511) + 1;
158

    
159
    c->bundle[BINK_SRC_PATTERN].len = av_log2((bw << 3) + 511) + 1;
160

    
161
    c->bundle[BINK_SRC_RUN].len = av_log2(bw*48 + 511) + 1;
162
}
163

    
164
/**
165
 * Allocate memory for bundles.
166
 *
167
 * @param c decoder context
168
 */
169
static av_cold void init_bundles(BinkContext *c)
170
{
171
    int bw, bh, blocks;
172
    int i;
173

    
174
    bw = (c->avctx->width  + 7) >> 3;
175
    bh = (c->avctx->height + 7) >> 3;
176
    blocks = bw * bh;
177

    
178
    for (i = 0; i < BINKB_NB_SRC; i++) {
179
        c->bundle[i].data = av_malloc(blocks * 64);
180
        c->bundle[i].data_end = c->bundle[i].data + blocks * 64;
181
    }
182
}
183

    
184
/**
185
 * Free memory used by bundles.
186
 *
187
 * @param c decoder context
188
 */
189
static av_cold void free_bundles(BinkContext *c)
190
{
191
    int i;
192
    for (i = 0; i < BINKB_NB_SRC; i++)
193
        av_freep(&c->bundle[i].data);
194
}
195

    
196
/**
197
 * Merge two consequent lists of equal size depending on bits read.
198
 *
199
 * @param gb   context for reading bits
200
 * @param dst  buffer where merged list will be written to
201
 * @param src  pointer to the head of the first list (the second lists starts at src+size)
202
 * @param size input lists size
203
 */
204
static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
205
{
206
    uint8_t *src2 = src + size;
207
    int size2 = size;
208

    
209
    do {
210
        if (!get_bits1(gb)) {
211
            *dst++ = *src++;
212
            size--;
213
        } else {
214
            *dst++ = *src2++;
215
            size2--;
216
        }
217
    } while (size && size2);
218

    
219
    while (size--)
220
        *dst++ = *src++;
221
    while (size2--)
222
        *dst++ = *src2++;
223
}
224

    
225
/**
226
 * Read information about Huffman tree used to decode data.
227
 *
228
 * @param gb   context for reading bits
229
 * @param tree pointer for storing tree data
230
 */
231
static void read_tree(GetBitContext *gb, Tree *tree)
232
{
233
    uint8_t tmp1[16], tmp2[16], *in = tmp1, *out = tmp2;
234
    int i, t, len;
235

    
236
    tree->vlc_num = get_bits(gb, 4);
237
    if (!tree->vlc_num) {
238
        for (i = 0; i < 16; i++)
239
            tree->syms[i] = i;
240
        return;
241
    }
242
    if (get_bits1(gb)) {
243
        len = get_bits(gb, 3);
244
        memset(tmp1, 0, sizeof(tmp1));
245
        for (i = 0; i <= len; i++) {
246
            tree->syms[i] = get_bits(gb, 4);
247
            tmp1[tree->syms[i]] = 1;
248
        }
249
        for (i = 0; i < 16; i++)
250
            if (!tmp1[i])
251
                tree->syms[++len] = i;
252
    } else {
253
        len = get_bits(gb, 2);
254
        for (i = 0; i < 16; i++)
255
            in[i] = i;
256
        for (i = 0; i <= len; i++) {
257
            int size = 1 << i;
258
            for (t = 0; t < 16; t += size << 1)
259
                merge(gb, out + t, in + t, size);
260
            FFSWAP(uint8_t*, in, out);
261
        }
262
        memcpy(tree->syms, in, 16);
263
    }
264
}
265

    
266
/**
267
 * Prepare bundle for decoding data.
268
 *
269
 * @param gb          context for reading bits
270
 * @param c           decoder context
271
 * @param bundle_num  number of the bundle to initialize
272
 */
273
static void read_bundle(GetBitContext *gb, BinkContext *c, int bundle_num)
274
{
275
    int i;
276

    
277
    if (bundle_num == BINK_SRC_COLORS) {
278
        for (i = 0; i < 16; i++)
279
            read_tree(gb, &c->col_high[i]);
280
        c->col_lastval = 0;
281
    }
282
    if (bundle_num != BINK_SRC_INTRA_DC && bundle_num != BINK_SRC_INTER_DC)
283
        read_tree(gb, &c->bundle[bundle_num].tree);
284
    c->bundle[bundle_num].cur_dec =
285
    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
286
}
287

    
288
/**
289
 * common check before starting decoding bundle data
290
 *
291
 * @param gb context for reading bits
292
 * @param b  bundle
293
 * @param t  variable where number of elements to decode will be stored
294
 */
295
#define CHECK_READ_VAL(gb, b, t) \
296
    if (!b->cur_dec || (b->cur_dec > b->cur_ptr)) \
297
        return 0; \
298
    t = get_bits(gb, b->len); \
299
    if (!t) { \
300
        b->cur_dec = NULL; \
301
        return 0; \
302
    } \
303

    
304
static int read_runs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
305
{
306
    int t, v;
307
    const uint8_t *dec_end;
308

    
309
    CHECK_READ_VAL(gb, b, t);
310
    dec_end = b->cur_dec + t;
311
    if (dec_end > b->data_end) {
312
        av_log(avctx, AV_LOG_ERROR, "Run value went out of bounds\n");
313
        return -1;
314
    }
315
    if (get_bits1(gb)) {
316
        v = get_bits(gb, 4);
317
        memset(b->cur_dec, v, t);
318
        b->cur_dec += t;
319
    } else {
320
        while (b->cur_dec < dec_end)
321
            *b->cur_dec++ = GET_HUFF(gb, b->tree);
322
    }
323
    return 0;
324
}
325

    
326
static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
327
{
328
    int t, sign, v;
329
    const uint8_t *dec_end;
330

    
331
    CHECK_READ_VAL(gb, b, t);
332
    dec_end = b->cur_dec + t;
333
    if (dec_end > b->data_end) {
334
        av_log(avctx, AV_LOG_ERROR, "Too many motion values\n");
335
        return -1;
336
    }
337
    if (get_bits1(gb)) {
338
        v = get_bits(gb, 4);
339
        if (v) {
340
            sign = -get_bits1(gb);
341
            v = (v ^ sign) - sign;
342
        }
343
        memset(b->cur_dec, v, t);
344
        b->cur_dec += t;
345
    } else {
346
        do {
347
            v = GET_HUFF(gb, b->tree);
348
            if (v) {
349
                sign = -get_bits1(gb);
350
                v = (v ^ sign) - sign;
351
            }
352
            *b->cur_dec++ = v;
353
        } while (b->cur_dec < dec_end);
354
    }
355
    return 0;
356
}
357

    
358
static const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
359

    
360
static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
361
{
362
    int t, v;
363
    int last = 0;
364
    const uint8_t *dec_end;
365

    
366
    CHECK_READ_VAL(gb, b, t);
367
    dec_end = b->cur_dec + t;
368
    if (dec_end > b->data_end) {
369
        av_log(avctx, AV_LOG_ERROR, "Too many block type values\n");
370
        return -1;
371
    }
372
    if (get_bits1(gb)) {
373
        v = get_bits(gb, 4);
374
        memset(b->cur_dec, v, t);
375
        b->cur_dec += t;
376
    } else {
377
        do {
378
            v = GET_HUFF(gb, b->tree);
379
            if (v < 12) {
380
                last = v;
381
                *b->cur_dec++ = v;
382
            } else {
383
                int run = bink_rlelens[v - 12];
384

    
385
                memset(b->cur_dec, last, run);
386
                b->cur_dec += run;
387
            }
388
        } while (b->cur_dec < dec_end);
389
    }
390
    return 0;
391
}
392

    
393
static int read_patterns(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
394
{
395
    int t, v;
396
    const uint8_t *dec_end;
397

    
398
    CHECK_READ_VAL(gb, b, t);
399
    dec_end = b->cur_dec + t;
400
    if (dec_end > b->data_end) {
401
        av_log(avctx, AV_LOG_ERROR, "Too many pattern values\n");
402
        return -1;
403
    }
404
    while (b->cur_dec < dec_end) {
405
        v  = GET_HUFF(gb, b->tree);
406
        v |= GET_HUFF(gb, b->tree) << 4;
407
        *b->cur_dec++ = v;
408
    }
409

    
410
    return 0;
411
}
412

    
413
static int read_colors(GetBitContext *gb, Bundle *b, BinkContext *c)
414
{
415
    int t, sign, v;
416
    const uint8_t *dec_end;
417

    
418
    CHECK_READ_VAL(gb, b, t);
419
    dec_end = b->cur_dec + t;
420
    if (dec_end > b->data_end) {
421
        av_log(c->avctx, AV_LOG_ERROR, "Too many color values\n");
422
        return -1;
423
    }
424
    if (get_bits1(gb)) {
425
        c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
426
        v = GET_HUFF(gb, b->tree);
427
        v = (c->col_lastval << 4) | v;
428
        if (c->version < 'i') {
429
            sign = ((int8_t) v) >> 7;
430
            v = ((v & 0x7F) ^ sign) - sign;
431
            v += 0x80;
432
        }
433
        memset(b->cur_dec, v, t);
434
        b->cur_dec += t;
435
    } else {
436
        while (b->cur_dec < dec_end) {
437
            c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
438
            v = GET_HUFF(gb, b->tree);
439
            v = (c->col_lastval << 4) | v;
440
            if (c->version < 'i') {
441
                sign = ((int8_t) v) >> 7;
442
                v = ((v & 0x7F) ^ sign) - sign;
443
                v += 0x80;
444
            }
445
            *b->cur_dec++ = v;
446
        }
447
    }
448
    return 0;
449
}
450

    
451
/** number of bits used to store first DC value in bundle */
452
#define DC_START_BITS 11
453

    
454
static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,
455
                    int start_bits, int has_sign)
456
{
457
    int i, j, len, len2, bsize, sign, v, v2;
458
    int16_t *dst = (int16_t*)b->cur_dec;
459

    
460
    CHECK_READ_VAL(gb, b, len);
461
    v = get_bits(gb, start_bits - has_sign);
462
    if (v && has_sign) {
463
        sign = -get_bits1(gb);
464
        v = (v ^ sign) - sign;
465
    }
466
    *dst++ = v;
467
    len--;
468
    for (i = 0; i < len; i += 8) {
469
        len2 = FFMIN(len - i, 8);
470
        bsize = get_bits(gb, 4);
471
        if (bsize) {
472
            for (j = 0; j < len2; j++) {
473
                v2 = get_bits(gb, bsize);
474
                if (v2) {
475
                    sign = -get_bits1(gb);
476
                    v2 = (v2 ^ sign) - sign;
477
                }
478
                v += v2;
479
                *dst++ = v;
480
                if (v < -32768 || v > 32767) {
481
                    av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v);
482
                    return -1;
483
                }
484
            }
485
        } else {
486
            for (j = 0; j < len2; j++)
487
                *dst++ = v;
488
        }
489
    }
490

    
491
    b->cur_dec = (uint8_t*)dst;
492
    return 0;
493
}
494

    
495
/**
496
 * Retrieve next value from bundle.
497
 *
498
 * @param c      decoder context
499
 * @param bundle bundle number
500
 */
501
static inline int get_value(BinkContext *c, int bundle)
502
{
503
    int ret;
504

    
505
    if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN)
506
        return *c->bundle[bundle].cur_ptr++;
507
    if (bundle == BINK_SRC_X_OFF || bundle == BINK_SRC_Y_OFF)
508
        return (int8_t)*c->bundle[bundle].cur_ptr++;
509
    ret = *(int16_t*)c->bundle[bundle].cur_ptr;
510
    c->bundle[bundle].cur_ptr += 2;
511
    return ret;
512
}
513

    
514
static void binkb_init_bundle(BinkContext *c, int bundle_num)
515
{
516
    c->bundle[bundle_num].cur_dec =
517
    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
518
    c->bundle[bundle_num].len = 13;
519
}
520

    
521
static void binkb_init_bundles(BinkContext *c)
522
{
523
    int i;
524
    for (i = 0; i < BINKB_NB_SRC; i++)
525
        binkb_init_bundle(c, i);
526
}
527

    
528
static int binkb_read_bundle(BinkContext *c, GetBitContext *gb, int bundle_num)
529
{
530
    const int bits = binkb_bundle_sizes[bundle_num];
531
    const int mask = 1 << (bits - 1);
532
    const int issigned = binkb_bundle_signed[bundle_num];
533
    Bundle *b = &c->bundle[bundle_num];
534
    int i, len;
535

    
536
    CHECK_READ_VAL(gb, b, len);
537
    if (bits <= 8) {
538
        if (!issigned) {
539
            for (i = 0; i < len; i++)
540
                *b->cur_dec++ = get_bits(gb, bits);
541
        } else {
542
            for (i = 0; i < len; i++)
543
                *b->cur_dec++ = get_bits(gb, bits) - mask;
544
        }
545
    } else {
546
        int16_t *dst = (int16_t*)b->cur_dec;
547

    
548
        if (!issigned) {
549
            for (i = 0; i < len; i++)
550
                *dst++ = get_bits(gb, bits);
551
        } else {
552
            for (i = 0; i < len; i++)
553
                *dst++ = get_bits(gb, bits) - mask;
554
        }
555
        b->cur_dec = (uint8_t*)dst;
556
    }
557
    return 0;
558
}
559

    
560
static inline int binkb_get_value(BinkContext *c, int bundle_num)
561
{
562
    int16_t ret;
563
    const int bits = binkb_bundle_sizes[bundle_num];
564

    
565
    if (bits <= 8) {
566
        int val = *c->bundle[bundle_num].cur_ptr++;
567
        return binkb_bundle_signed[bundle_num] ? (int8_t)val : val;
568
    }
569
    ret = *(int16_t*)c->bundle[bundle_num].cur_ptr;
570
    c->bundle[bundle_num].cur_ptr += 2;
571
    return ret;
572
}
573

    
574
/**
575
 * Read 8x8 block of DCT coefficients.
576
 *
577
 * @param gb       context for reading bits
578
 * @param block    place for storing coefficients
579
 * @param scan     scan order table
580
 * @param quant_matrices quantization matrices
581
 * @return 0 for success, negative value in other cases
582
 */
583
static int read_dct_coeffs(GetBitContext *gb, DCTELEM block[64], const uint8_t *scan,
584
                           const uint32_t quant_matrices[16][64], int q)
585
{
586
    int coef_list[128];
587
    int mode_list[128];
588
    int i, t, mask, bits, ccoef, mode, sign;
589
    int list_start = 64, list_end = 64, list_pos;
590
    int coef_count = 0;
591
    int coef_idx[64];
592
    int quant_idx;
593
    const uint32_t *quant;
594

    
595
    coef_list[list_end] = 4;  mode_list[list_end++] = 0;
596
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
597
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
598
    coef_list[list_end] = 1;  mode_list[list_end++] = 3;
599
    coef_list[list_end] = 2;  mode_list[list_end++] = 3;
600
    coef_list[list_end] = 3;  mode_list[list_end++] = 3;
601

    
602
    bits = get_bits(gb, 4) - 1;
603
    for (mask = 1 << bits; bits >= 0; mask >>= 1, bits--) {
604
        list_pos = list_start;
605
        while (list_pos < list_end) {
606
            if (!(mode_list[list_pos] | coef_list[list_pos]) || !get_bits1(gb)) {
607
                list_pos++;
608
                continue;
609
            }
610
            ccoef = coef_list[list_pos];
611
            mode  = mode_list[list_pos];
612
            switch (mode) {
613
            case 0:
614
                coef_list[list_pos] = ccoef + 4;
615
                mode_list[list_pos] = 1;
616
            case 2:
617
                if (mode == 2) {
618
                    coef_list[list_pos]   = 0;
619
                    mode_list[list_pos++] = 0;
620
                }
621
                for (i = 0; i < 4; i++, ccoef++) {
622
                    if (get_bits1(gb)) {
623
                        coef_list[--list_start] = ccoef;
624
                        mode_list[  list_start] = 3;
625
                    } else {
626
                        int t;
627
                        if (!bits) {
628
                            t = 1 - (get_bits1(gb) << 1);
629
                        } else {
630
                            t = get_bits(gb, bits) | mask;
631
                            sign = -get_bits1(gb);
632
                            t = (t ^ sign) - sign;
633
                        }
634
                        block[scan[ccoef]] = t;
635
                        coef_idx[coef_count++] = ccoef;
636
                    }
637
                }
638
                break;
639
            case 1:
640
                mode_list[list_pos] = 2;
641
                for (i = 0; i < 3; i++) {
642
                    ccoef += 4;
643
                    coef_list[list_end]   = ccoef;
644
                    mode_list[list_end++] = 2;
645
                }
646
                break;
647
            case 3:
648
                if (!bits) {
649
                    t = 1 - (get_bits1(gb) << 1);
650
                } else {
651
                    t = get_bits(gb, bits) | mask;
652
                    sign = -get_bits1(gb);
653
                    t = (t ^ sign) - sign;
654
                }
655
                block[scan[ccoef]] = t;
656
                coef_idx[coef_count++] = ccoef;
657
                coef_list[list_pos]   = 0;
658
                mode_list[list_pos++] = 0;
659
                break;
660
            }
661
        }
662
    }
663

    
664
    if (q == -1) {
665
        quant_idx = get_bits(gb, 4);
666
    } else {
667
        quant_idx = q;
668
    }
669

    
670
    quant = quant_matrices[quant_idx];
671

    
672
    block[0] = (block[0] * quant[0]) >> 11;
673
    for (i = 0; i < coef_count; i++) {
674
        int idx = coef_idx[i];
675
        block[scan[idx]] = (block[scan[idx]] * quant[idx]) >> 11;
676
    }
677

    
678
    return 0;
679
}
680

    
681
/**
682
 * Read 8x8 block with residue after motion compensation.
683
 *
684
 * @param gb          context for reading bits
685
 * @param block       place to store read data
686
 * @param masks_count number of masks to decode
687
 * @return 0 on success, negative value in other cases
688
 */
689
static int read_residue(GetBitContext *gb, DCTELEM block[64], int masks_count)
690
{
691
    int coef_list[128];
692
    int mode_list[128];
693
    int i, sign, mask, ccoef, mode;
694
    int list_start = 64, list_end = 64, list_pos;
695
    int nz_coeff[64];
696
    int nz_coeff_count = 0;
697

    
698
    coef_list[list_end] =  4; mode_list[list_end++] = 0;
699
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
700
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
701
    coef_list[list_end] =  0; mode_list[list_end++] = 2;
702

    
703
    for (mask = 1 << get_bits(gb, 3); mask; mask >>= 1) {
704
        for (i = 0; i < nz_coeff_count; i++) {
705
            if (!get_bits1(gb))
706
                continue;
707
            if (block[nz_coeff[i]] < 0)
708
                block[nz_coeff[i]] -= mask;
709
            else
710
                block[nz_coeff[i]] += mask;
711
            masks_count--;
712
            if (masks_count < 0)
713
                return 0;
714
        }
715
        list_pos = list_start;
716
        while (list_pos < list_end) {
717
            if (!(coef_list[list_pos] | mode_list[list_pos]) || !get_bits1(gb)) {
718
                list_pos++;
719
                continue;
720
            }
721
            ccoef = coef_list[list_pos];
722
            mode  = mode_list[list_pos];
723
            switch (mode) {
724
            case 0:
725
                coef_list[list_pos] = ccoef + 4;
726
                mode_list[list_pos] = 1;
727
            case 2:
728
                if (mode == 2) {
729
                    coef_list[list_pos]   = 0;
730
                    mode_list[list_pos++] = 0;
731
                }
732
                for (i = 0; i < 4; i++, ccoef++) {
733
                    if (get_bits1(gb)) {
734
                        coef_list[--list_start] = ccoef;
735
                        mode_list[  list_start] = 3;
736
                    } else {
737
                        nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
738
                        sign = -get_bits1(gb);
739
                        block[bink_scan[ccoef]] = (mask ^ sign) - sign;
740
                        masks_count--;
741
                        if (masks_count < 0)
742
                            return 0;
743
                    }
744
                }
745
                break;
746
            case 1:
747
                mode_list[list_pos] = 2;
748
                for (i = 0; i < 3; i++) {
749
                    ccoef += 4;
750
                    coef_list[list_end]   = ccoef;
751
                    mode_list[list_end++] = 2;
752
                }
753
                break;
754
            case 3:
755
                nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
756
                sign = -get_bits1(gb);
757
                block[bink_scan[ccoef]] = (mask ^ sign) - sign;
758
                coef_list[list_pos]   = 0;
759
                mode_list[list_pos++] = 0;
760
                masks_count--;
761
                if (masks_count < 0)
762
                    return 0;
763
                break;
764
            }
765
        }
766
    }
767

    
768
    return 0;
769
}
770

    
771
/**
772
 * Copy 8x8 block from source to destination, where src and dst may be overlapped
773
 */
774
static inline void put_pixels8x8_overlapped(uint8_t *dst, uint8_t *src, int stride)
775
{
776
    uint8_t tmp[64];
777
    int i;
778
    for (i = 0; i < 8; i++)
779
        memcpy(tmp + i*8, src + i*stride, 8);
780
    for (i = 0; i < 8; i++)
781
        memcpy(dst + i*stride, tmp + i*8, 8);
782
}
783

    
784
static int binkb_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
785
                              int is_key, int is_chroma)
786
{
787
    int blk;
788
    int i, j, bx, by;
789
    uint8_t *dst, *ref, *ref_start, *ref_end;
790
    int v, col[2];
791
    const uint8_t *scan;
792
    int xoff, yoff;
793
    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
794
    int coordmap[64];
795
    int ybias = is_key ? -15 : 0;
796
    int qp;
797

    
798
    const int stride = c->pic.linesize[plane_idx];
799
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
800
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
801

    
802
    binkb_init_bundles(c);
803
    ref_start = c->pic.data[plane_idx];
804
    ref_end   = c->pic.data[plane_idx] + (bh * c->pic.linesize[plane_idx] + bw) * 8;
805

    
806
    for (i = 0; i < 64; i++)
807
        coordmap[i] = (i & 7) + (i >> 3) * stride;
808

    
809
    for (by = 0; by < bh; by++) {
810
        for (i = 0; i < BINKB_NB_SRC; i++) {
811
            if (binkb_read_bundle(c, gb, i) < 0)
812
                return -1;
813
        }
814

    
815
        dst  = c->pic.data[plane_idx]  + 8*by*stride;
816
        for (bx = 0; bx < bw; bx++, dst += 8) {
817
            blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES);
818
            switch (blk) {
819
            case 0:
820
                break;
821
            case 1:
822
                scan = bink_patterns[get_bits(gb, 4)];
823
                i = 0;
824
                do {
825
                    int mode, run;
826

    
827
                    mode = get_bits1(gb);
828
                    run = get_bits(gb, binkb_runbits[i]) + 1;
829

    
830
                    i += run;
831
                    if (i > 64) {
832
                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
833
                        return -1;
834
                    }
835
                    if (mode) {
836
                        v = binkb_get_value(c, BINKB_SRC_COLORS);
837
                        for (j = 0; j < run; j++)
838
                            dst[coordmap[*scan++]] = v;
839
                    } else {
840
                        for (j = 0; j < run; j++)
841
                            dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
842
                    }
843
                } while (i < 63);
844
                if (i == 63)
845
                    dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
846
                break;
847
            case 2:
848
                c->dsp.clear_block(block);
849
                block[0] = binkb_get_value(c, BINKB_SRC_INTRA_DC);
850
                qp = binkb_get_value(c, BINKB_SRC_INTRA_Q);
851
                read_dct_coeffs(gb, block, c->scantable.permutated, binkb_intra_quant, qp);
852
                c->dsp.idct_put(dst, stride, block);
853
                break;
854
            case 3:
855
                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
856
                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
857
                ref = dst + xoff + yoff * stride;
858
                if (ref < ref_start || ref + 8*stride > ref_end) {
859
                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
860
                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
861
                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
862
                } else {
863
                    put_pixels8x8_overlapped(dst, ref, stride);
864
                }
865
                c->dsp.clear_block(block);
866
                v = binkb_get_value(c, BINKB_SRC_INTER_COEFS);
867
                read_residue(gb, block, v);
868
                c->dsp.add_pixels8(dst, block, stride);
869
                break;
870
            case 4:
871
                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
872
                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
873
                ref = dst + xoff + yoff * stride;
874
                if (ref < ref_start || ref + 8 * stride > ref_end) {
875
                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
876
                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
877
                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
878
                } else {
879
                    put_pixels8x8_overlapped(dst, ref, stride);
880
                }
881
                c->dsp.clear_block(block);
882
                block[0] = binkb_get_value(c, BINKB_SRC_INTER_DC);
883
                qp = binkb_get_value(c, BINKB_SRC_INTER_Q);
884
                read_dct_coeffs(gb, block, c->scantable.permutated, binkb_inter_quant, qp);
885
                c->dsp.idct_add(dst, stride, block);
886
                break;
887
            case 5:
888
                v = binkb_get_value(c, BINKB_SRC_COLORS);
889
                c->dsp.fill_block_tab[1](dst, v, stride, 8);
890
                break;
891
            case 6:
892
                for (i = 0; i < 2; i++)
893
                    col[i] = binkb_get_value(c, BINKB_SRC_COLORS);
894
                for (i = 0; i < 8; i++) {
895
                    v = binkb_get_value(c, BINKB_SRC_PATTERN);
896
                    for (j = 0; j < 8; j++, v >>= 1)
897
                        dst[i*stride + j] = col[v & 1];
898
                }
899
                break;
900
            case 7:
901
                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
902
                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
903
                ref = dst + xoff + yoff * stride;
904
                if (ref < ref_start || ref + 8 * stride > ref_end) {
905
                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
906
                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
907
                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
908
                } else {
909
                    put_pixels8x8_overlapped(dst, ref, stride);
910
                }
911
                break;
912
            case 8:
913
                for (i = 0; i < 8; i++)
914
                    memcpy(dst + i*stride, c->bundle[BINKB_SRC_COLORS].cur_ptr + i*8, 8);
915
                c->bundle[BINKB_SRC_COLORS].cur_ptr += 64;
916
                break;
917
            default:
918
                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
919
                return -1;
920
            }
921
        }
922
    }
923
    if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
924
        skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
925

    
926
    return 0;
927
}
928

    
929
static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
930
                             int is_chroma)
931
{
932
    int blk;
933
    int i, j, bx, by;
934
    uint8_t *dst, *prev, *ref, *ref_start, *ref_end;
935
    int v, col[2];
936
    const uint8_t *scan;
937
    int xoff, yoff;
938
    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
939
    LOCAL_ALIGNED_16(uint8_t, ublock, [64]);
940
    int coordmap[64];
941

    
942
    const int stride = c->pic.linesize[plane_idx];
943
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
944
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
945
    int width = c->avctx->width >> is_chroma;
946

    
947
    init_lengths(c, FFMAX(width, 8), bw);
948
    for (i = 0; i < BINK_NB_SRC; i++)
949
        read_bundle(gb, c, i);
950

    
951
    ref_start = c->last.data[plane_idx];
952
    ref_end   = c->last.data[plane_idx]
953
                + (bw - 1 + c->last.linesize[plane_idx] * (bh - 1)) * 8;
954

    
955
    for (i = 0; i < 64; i++)
956
        coordmap[i] = (i & 7) + (i >> 3) * stride;
957

    
958
    for (by = 0; by < bh; by++) {
959
        if (read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES]) < 0)
960
            return -1;
961
        if (read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES]) < 0)
962
            return -1;
963
        if (read_colors(gb, &c->bundle[BINK_SRC_COLORS], c) < 0)
964
            return -1;
965
        if (read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN]) < 0)
966
            return -1;
967
        if (read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF]) < 0)
968
            return -1;
969
        if (read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF]) < 0)
970
            return -1;
971
        if (read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0) < 0)
972
            return -1;
973
        if (read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1) < 0)
974
            return -1;
975
        if (read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN]) < 0)
976
            return -1;
977

    
978
        if (by == bh)
979
            break;
980
        dst  = c->pic.data[plane_idx]  + 8*by*stride;
981
        prev = c->last.data[plane_idx] + 8*by*stride;
982
        for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {
983
            blk = get_value(c, BINK_SRC_BLOCK_TYPES);
984
            // 16x16 block type on odd line means part of the already decoded block, so skip it
985
            if ((by & 1) && blk == SCALED_BLOCK) {
986
                bx++;
987
                dst  += 8;
988
                prev += 8;
989
                continue;
990
            }
991
            switch (blk) {
992
            case SKIP_BLOCK:
993
                c->dsp.put_pixels_tab[1][0](dst, prev, stride, 8);
994
                break;
995
            case SCALED_BLOCK:
996
                blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);
997
                switch (blk) {
998
                case RUN_BLOCK:
999
                    scan = bink_patterns[get_bits(gb, 4)];
1000
                    i = 0;
1001
                    do {
1002
                        int run = get_value(c, BINK_SRC_RUN) + 1;
1003

    
1004
                        i += run;
1005
                        if (i > 64) {
1006
                            av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1007
                            return -1;
1008
                        }
1009
                        if (get_bits1(gb)) {
1010
                            v = get_value(c, BINK_SRC_COLORS);
1011
                            for (j = 0; j < run; j++)
1012
                                ublock[*scan++] = v;
1013
                        } else {
1014
                            for (j = 0; j < run; j++)
1015
                                ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
1016
                        }
1017
                    } while (i < 63);
1018
                    if (i == 63)
1019
                        ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
1020
                    break;
1021
                case INTRA_BLOCK:
1022
                    c->dsp.clear_block(block);
1023
                    block[0] = get_value(c, BINK_SRC_INTRA_DC);
1024
                    read_dct_coeffs(gb, block, c->scantable.permutated, bink_intra_quant, -1);
1025
                    c->dsp.idct(block);
1026
                    c->dsp.put_pixels_nonclamped(block, ublock, 8);
1027
                    break;
1028
                case FILL_BLOCK:
1029
                    v = get_value(c, BINK_SRC_COLORS);
1030
                    c->dsp.fill_block_tab[0](dst, v, stride, 16);
1031
                    break;
1032
                case PATTERN_BLOCK:
1033
                    for (i = 0; i < 2; i++)
1034
                        col[i] = get_value(c, BINK_SRC_COLORS);
1035
                    for (j = 0; j < 8; j++) {
1036
                        v = get_value(c, BINK_SRC_PATTERN);
1037
                        for (i = 0; i < 8; i++, v >>= 1)
1038
                            ublock[i + j*8] = col[v & 1];
1039
                    }
1040
                    break;
1041
                case RAW_BLOCK:
1042
                    for (j = 0; j < 8; j++)
1043
                        for (i = 0; i < 8; i++)
1044
                            ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);
1045
                    break;
1046
                default:
1047
                    av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);
1048
                    return -1;
1049
                }
1050
                if (blk != FILL_BLOCK)
1051
                c->dsp.scale_block(ublock, dst, stride);
1052
                bx++;
1053
                dst  += 8;
1054
                prev += 8;
1055
                break;
1056
            case MOTION_BLOCK:
1057
                xoff = get_value(c, BINK_SRC_X_OFF);
1058
                yoff = get_value(c, BINK_SRC_Y_OFF);
1059
                ref = prev + xoff + yoff * stride;
1060
                if (ref < ref_start || ref > ref_end) {
1061
                    av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
1062
                           bx*8 + xoff, by*8 + yoff);
1063
                    return -1;
1064
                }
1065
                c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
1066
                break;
1067
            case RUN_BLOCK:
1068
                scan = bink_patterns[get_bits(gb, 4)];
1069
                i = 0;
1070
                do {
1071
                    int run = get_value(c, BINK_SRC_RUN) + 1;
1072

    
1073
                    i += run;
1074
                    if (i > 64) {
1075
                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1076
                        return -1;
1077
                    }
1078
                    if (get_bits1(gb)) {
1079
                        v = get_value(c, BINK_SRC_COLORS);
1080
                        for (j = 0; j < run; j++)
1081
                            dst[coordmap[*scan++]] = v;
1082
                    } else {
1083
                        for (j = 0; j < run; j++)
1084
                            dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
1085
                    }
1086
                } while (i < 63);
1087
                if (i == 63)
1088
                    dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
1089
                break;
1090
            case RESIDUE_BLOCK:
1091
                xoff = get_value(c, BINK_SRC_X_OFF);
1092
                yoff = get_value(c, BINK_SRC_Y_OFF);
1093
                ref = prev + xoff + yoff * stride;
1094
                if (ref < ref_start || ref > ref_end) {
1095
                    av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
1096
                           bx*8 + xoff, by*8 + yoff);
1097
                    return -1;
1098
                }
1099
                c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
1100
                c->dsp.clear_block(block);
1101
                v = get_bits(gb, 7);
1102
                read_residue(gb, block, v);
1103
                c->dsp.add_pixels8(dst, block, stride);
1104
                break;
1105
            case INTRA_BLOCK:
1106
                c->dsp.clear_block(block);
1107
                block[0] = get_value(c, BINK_SRC_INTRA_DC);
1108
                read_dct_coeffs(gb, block, c->scantable.permutated, bink_intra_quant, -1);
1109
                c->dsp.idct_put(dst, stride, block);
1110
                break;
1111
            case FILL_BLOCK:
1112
                v = get_value(c, BINK_SRC_COLORS);
1113
                c->dsp.fill_block_tab[1](dst, v, stride, 8);
1114
                break;
1115
            case INTER_BLOCK:
1116
                xoff = get_value(c, BINK_SRC_X_OFF);
1117
                yoff = get_value(c, BINK_SRC_Y_OFF);
1118
                ref = prev + xoff + yoff * stride;
1119
                c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
1120
                c->dsp.clear_block(block);
1121
                block[0] = get_value(c, BINK_SRC_INTER_DC);
1122
                read_dct_coeffs(gb, block, c->scantable.permutated, bink_inter_quant, -1);
1123
                c->dsp.idct_add(dst, stride, block);
1124
                break;
1125
            case PATTERN_BLOCK:
1126
                for (i = 0; i < 2; i++)
1127
                    col[i] = get_value(c, BINK_SRC_COLORS);
1128
                for (i = 0; i < 8; i++) {
1129
                    v = get_value(c, BINK_SRC_PATTERN);
1130
                    for (j = 0; j < 8; j++, v >>= 1)
1131
                        dst[i*stride + j] = col[v & 1];
1132
                }
1133
                break;
1134
            case RAW_BLOCK:
1135
                for (i = 0; i < 8; i++)
1136
                    memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);
1137
                c->bundle[BINK_SRC_COLORS].cur_ptr += 64;
1138
                break;
1139
            default:
1140
                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
1141
                return -1;
1142
            }
1143
        }
1144
    }
1145
    if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
1146
        skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
1147

    
1148
    return 0;
1149
}
1150

    
1151
static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *pkt)
1152
{
1153
    BinkContext * const c = avctx->priv_data;
1154
    GetBitContext gb;
1155
    int plane, plane_idx;
1156
    int bits_count = pkt->size << 3;
1157

    
1158
    if (c->version > 'b') {
1159
        if(c->pic.data[0])
1160
            avctx->release_buffer(avctx, &c->pic);
1161

    
1162
        if(avctx->get_buffer(avctx, &c->pic) < 0){
1163
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1164
            return -1;
1165
        }
1166
    } else {
1167
        if(avctx->reget_buffer(avctx, &c->pic) < 0){
1168
            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1169
            return -1;
1170
        }
1171
    }
1172

    
1173
    init_get_bits(&gb, pkt->data, bits_count);
1174
    if (c->has_alpha) {
1175
        if (c->version >= 'i')
1176
            skip_bits_long(&gb, 32);
1177
        if (bink_decode_plane(c, &gb, 3, 0) < 0)
1178
            return -1;
1179
    }
1180
    if (c->version >= 'i')
1181
        skip_bits_long(&gb, 32);
1182

    
1183
    for (plane = 0; plane < 3; plane++) {
1184
        plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);
1185

    
1186
        if (c->version > 'b') {
1187
            if (bink_decode_plane(c, &gb, plane_idx, !!plane) < 0)
1188
                return -1;
1189
        } else {
1190
            if (binkb_decode_plane(c, &gb, plane_idx, !pkt->pts, !!plane) < 0)
1191
                return -1;
1192
        }
1193
        if (get_bits_count(&gb) >= bits_count)
1194
            break;
1195
    }
1196
    emms_c();
1197

    
1198
    *data_size = sizeof(AVFrame);
1199
    *(AVFrame*)data = c->pic;
1200

    
1201
    if (c->version > 'b')
1202
        FFSWAP(AVFrame, c->pic, c->last);
1203

    
1204
    /* always report that the buffer was completely consumed */
1205
    return pkt->size;
1206
}
1207

    
1208
/**
1209
 * Caclulate quantization tables for version b
1210
 */
1211
static av_cold void binkb_calc_quant()
1212
{
1213
    uint8_t inv_bink_scan[64];
1214
    double s[64];
1215
    int i, j;
1216

    
1217
    for (j = 0; j < 8; j++) {
1218
        for (i = 0; i < 8; i++) {
1219
            if (j && j != 4)
1220
               if (i && i != 4)
1221
                   s[j*8 + i] = cos(j * M_PI/16.0) * cos(i * M_PI/16.0) * 2.0;
1222
               else
1223
                   s[j*8 + i] = cos(j * M_PI/16.0) * sqrt(2.0);
1224
            else
1225
               if (i && i != 4)
1226
                   s[j*8 + i] = cos(i * M_PI/16.0) * sqrt(2.0);
1227
               else
1228
                   s[j*8 + i] = 1.0;
1229
        }
1230
    }
1231

    
1232
    for (i = 0; i < 64; i++)
1233
        inv_bink_scan[bink_scan[i]] = i;
1234

    
1235
    for (j = 0; j < 16; j++) {
1236
        for (i = 0; i < 64; i++) {
1237
            int k = inv_bink_scan[i];
1238
            if (s[i] == 1.0) {
1239
                binkb_intra_quant[j][k] = (1L << 12) * binkb_intra_seed[i] *
1240
                                          binkb_num[j]/binkb_den[j];
1241
                binkb_inter_quant[j][k] = (1L << 12) * binkb_inter_seed[i] *
1242
                                          binkb_num[j]/binkb_den[j];
1243
            } else {
1244
                binkb_intra_quant[j][k] = (1L << 12) * binkb_intra_seed[i] * s[i] *
1245
                                          binkb_num[j]/(double)binkb_den[j];
1246
                binkb_inter_quant[j][k] = (1L << 12) * binkb_inter_seed[i] * s[i] *
1247
                                          binkb_num[j]/(double)binkb_den[j];
1248
            }
1249
        }
1250
    }
1251
}
1252

    
1253
static av_cold int decode_init(AVCodecContext *avctx)
1254
{
1255
    BinkContext * const c = avctx->priv_data;
1256
    static VLC_TYPE table[16 * 128][2];
1257
    static int binkb_initialised = 0;
1258
    int i;
1259
    int flags;
1260

    
1261
    c->version = avctx->codec_tag >> 24;
1262
    if (avctx->extradata_size < 4) {
1263
        av_log(avctx, AV_LOG_ERROR, "Extradata missing or too short\n");
1264
        return -1;
1265
    }
1266
    flags = AV_RL32(avctx->extradata);
1267
    c->has_alpha = flags & BINK_FLAG_ALPHA;
1268
    c->swap_planes = c->version >= 'h';
1269
    if (!bink_trees[15].table) {
1270
        for (i = 0; i < 16; i++) {
1271
            const int maxbits = bink_tree_lens[i][15];
1272
            bink_trees[i].table = table + i*128;
1273
            bink_trees[i].table_allocated = 1 << maxbits;
1274
            init_vlc(&bink_trees[i], maxbits, 16,
1275
                     bink_tree_lens[i], 1, 1,
1276
                     bink_tree_bits[i], 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
1277
        }
1278
    }
1279
    c->avctx = avctx;
1280

    
1281
    c->pic.data[0] = NULL;
1282

    
1283
    if (av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
1284
        return 1;
1285
    }
1286

    
1287
    avctx->pix_fmt = c->has_alpha ? PIX_FMT_YUVA420P : PIX_FMT_YUV420P;
1288

    
1289
    avctx->idct_algo = FF_IDCT_BINK;
1290
    dsputil_init(&c->dsp, avctx);
1291
    ff_init_scantable(c->dsp.idct_permutation, &c->scantable, bink_scan);
1292

    
1293
    init_bundles(c);
1294

    
1295
    if (c->version == 'b') {
1296
        if (!binkb_initialised) {
1297
            binkb_calc_quant();
1298
            binkb_initialised = 1;
1299
        }
1300
    }
1301

    
1302
    return 0;
1303
}
1304

    
1305
static av_cold int decode_end(AVCodecContext *avctx)
1306
{
1307
    BinkContext * const c = avctx->priv_data;
1308

    
1309
    if (c->pic.data[0])
1310
        avctx->release_buffer(avctx, &c->pic);
1311
    if (c->last.data[0])
1312
        avctx->release_buffer(avctx, &c->last);
1313

    
1314
    free_bundles(c);
1315
    return 0;
1316
}
1317

    
1318
AVCodec ff_bink_decoder = {
1319
    "binkvideo",
1320
    AVMEDIA_TYPE_VIDEO,
1321
    CODEC_ID_BINKVIDEO,
1322
    sizeof(BinkContext),
1323
    decode_init,
1324
    NULL,
1325
    decode_end,
1326
    decode_frame,
1327
    .long_name = NULL_IF_CONFIG_SMALL("Bink video"),
1328
};