Statistics
| Branch: | Revision:

ffmpeg / libavcodec / bink.c @ 47d62c96

History | View | Annotate | Download (43.5 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 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 "libavcore/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
typedef const uint32_t quant_matrices[16][64];
575
static const quant_matrices * bink_quant_matrices[2][2] = {
576
    { &bink_inter_quant,  &bink_intra_quant  },
577
    { &binkb_inter_quant, &binkb_intra_quant },
578
};
579

    
580
/**
581
 * Read 8x8 block of DCT coefficients.
582
 *
583
 * @param gb       context for reading bits
584
 * @param block    place for storing coefficients
585
 * @param scan     scan order table
586
 * @param is_binkb use version 'b' quantizer matrices
587
 * @param is_intra tells what set of quantizer matrices to use
588
 * @return 0 for success, negative value in other cases
589
 */
590
static int read_dct_coeffs(GetBitContext *gb, DCTELEM block[64], const uint8_t *scan,
591
                           int is_binkb, int is_intra, int q)
592
{
593
    int coef_list[128];
594
    int mode_list[128];
595
    int i, t, mask, bits, ccoef, mode, sign;
596
    int list_start = 64, list_end = 64, list_pos;
597
    int coef_count = 0;
598
    int coef_idx[64];
599
    int quant_idx;
600
    const uint32_t *quant;
601

    
602
    coef_list[list_end] = 4;  mode_list[list_end++] = 0;
603
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
604
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
605
    coef_list[list_end] = 1;  mode_list[list_end++] = 3;
606
    coef_list[list_end] = 2;  mode_list[list_end++] = 3;
607
    coef_list[list_end] = 3;  mode_list[list_end++] = 3;
608

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

    
671
    if (q == -1) {
672
        quant_idx = get_bits(gb, 4);
673
    } else {
674
        quant_idx = q;
675
    }
676

    
677
    quant = (*bink_quant_matrices[is_binkb][is_intra])[quant_idx];
678

    
679
    block[0] = (block[0] * quant[0]) >> 11;
680
    for (i = 0; i < coef_count; i++) {
681
        int idx = coef_idx[i];
682
        block[scan[idx]] = (block[scan[idx]] * quant[idx]) >> 11;
683
    }
684

    
685
    return 0;
686
}
687

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

    
705
    coef_list[list_end] =  4; mode_list[list_end++] = 0;
706
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
707
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
708
    coef_list[list_end] =  0; mode_list[list_end++] = 2;
709

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

    
775
    return 0;
776
}
777

    
778
/**
779
 * Copy 8x8 block from source to destination, where src and dst may be overlapped
780
 */
781
static inline void put_pixels8x8_overlapped(uint8_t *dst, uint8_t *src, int stride)
782
{
783
    uint8_t tmp[64];
784
    int i;
785
    for (i = 0; i < 8; i++)
786
        memcpy(tmp + i*8, src + i*stride, 8);
787
    for (i = 0; i < 8; i++)
788
        memcpy(dst + i*stride, tmp + i*8, 8);
789
}
790

    
791
static int binkb_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
792
                              int is_key, int is_chroma)
793
{
794
    int blk;
795
    int i, j, bx, by;
796
    uint8_t *dst, *ref, *ref_start, *ref_end;
797
    int v, col[2];
798
    const uint8_t *scan;
799
    int xoff, yoff;
800
    DECLARE_ALIGNED(16, DCTELEM, block[64]);
801
    int coordmap[64];
802
    int ybias = is_key ? -15 : 0;
803
    int qp;
804

    
805
    const int stride = c->pic.linesize[plane_idx];
806
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
807
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
808

    
809
    binkb_init_bundles(c);
810
    ref_start = c->pic.data[plane_idx];
811
    ref_end   = c->pic.data[plane_idx] + (bh * c->pic.linesize[plane_idx] + bw) * 8;
812

    
813
    for (i = 0; i < 64; i++)
814
        coordmap[i] = (i & 7) + (i >> 3) * stride;
815

    
816
    for (by = 0; by < bh; by++) {
817
        for (i = 0; i < BINKB_NB_SRC; i++) {
818
            if (binkb_read_bundle(c, gb, i) < 0)
819
                return -1;
820
        }
821

    
822
        dst  = c->pic.data[plane_idx]  + 8*by*stride;
823
        for (bx = 0; bx < bw; bx++, dst += 8) {
824
            blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES);
825
            switch (blk) {
826
            case 0:
827
                break;
828
            case 1:
829
                scan = bink_patterns[get_bits(gb, 4)];
830
                i = 0;
831
                do {
832
                    int mode, run;
833

    
834
                    mode = get_bits1(gb);
835
                    run = get_bits(gb, binkb_runbits[i]) + 1;
836

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

    
933
    return 0;
934
}
935

    
936
static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
937
                             int is_chroma)
938
{
939
    int blk;
940
    int i, j, bx, by;
941
    uint8_t *dst, *prev, *ref, *ref_start, *ref_end;
942
    int v, col[2];
943
    const uint8_t *scan;
944
    int xoff, yoff;
945
    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
946
    LOCAL_ALIGNED_16(uint8_t, ublock, [64]);
947
    int coordmap[64];
948

    
949
    const int stride = c->pic.linesize[plane_idx];
950
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
951
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
952
    int width = c->avctx->width >> is_chroma;
953

    
954
    init_lengths(c, FFMAX(width, 8), bw);
955
    for (i = 0; i < BINK_NB_SRC; i++)
956
        read_bundle(gb, c, i);
957

    
958
    ref_start = c->last.data[plane_idx];
959
    ref_end   = c->last.data[plane_idx]
960
                + (bw - 1 + c->last.linesize[plane_idx] * (bh - 1)) * 8;
961

    
962
    for (i = 0; i < 64; i++)
963
        coordmap[i] = (i & 7) + (i >> 3) * stride;
964

    
965
    for (by = 0; by < bh; by++) {
966
        if (read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES]) < 0)
967
            return -1;
968
        if (read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES]) < 0)
969
            return -1;
970
        if (read_colors(gb, &c->bundle[BINK_SRC_COLORS], c) < 0)
971
            return -1;
972
        if (read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN]) < 0)
973
            return -1;
974
        if (read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF]) < 0)
975
            return -1;
976
        if (read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF]) < 0)
977
            return -1;
978
        if (read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0) < 0)
979
            return -1;
980
        if (read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1) < 0)
981
            return -1;
982
        if (read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN]) < 0)
983
            return -1;
984

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

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

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

    
1155
    return 0;
1156
}
1157

    
1158
static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *pkt)
1159
{
1160
    BinkContext * const c = avctx->priv_data;
1161
    GetBitContext gb;
1162
    int plane, plane_idx;
1163
    int bits_count = pkt->size << 3;
1164

    
1165
    if (c->version > 'b') {
1166
        if(c->pic.data[0])
1167
            avctx->release_buffer(avctx, &c->pic);
1168

    
1169
        if(avctx->get_buffer(avctx, &c->pic) < 0){
1170
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1171
            return -1;
1172
        }
1173
    } else {
1174
        if(avctx->reget_buffer(avctx, &c->pic) < 0){
1175
            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1176
            return -1;
1177
        }
1178
    }
1179

    
1180
    init_get_bits(&gb, pkt->data, bits_count);
1181
    if (c->has_alpha) {
1182
        if (c->version >= 'i')
1183
            skip_bits_long(&gb, 32);
1184
        if (bink_decode_plane(c, &gb, 3, 0) < 0)
1185
            return -1;
1186
    }
1187
    if (c->version >= 'i')
1188
        skip_bits_long(&gb, 32);
1189

    
1190
    for (plane = 0; plane < 3; plane++) {
1191
        plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);
1192

    
1193
        if (c->version > 'b') {
1194
            if (bink_decode_plane(c, &gb, plane_idx, !!plane) < 0)
1195
                return -1;
1196
        } else {
1197
            if (binkb_decode_plane(c, &gb, plane_idx, !pkt->pts, !!plane) < 0)
1198
                return -1;
1199
        }
1200
        if (get_bits_count(&gb) >= bits_count)
1201
            break;
1202
    }
1203
    emms_c();
1204

    
1205
    *data_size = sizeof(AVFrame);
1206
    *(AVFrame*)data = c->pic;
1207

    
1208
    if (c->version > 'b')
1209
        FFSWAP(AVFrame, c->pic, c->last);
1210

    
1211
    /* always report that the buffer was completely consumed */
1212
    return pkt->size;
1213
}
1214

    
1215
/**
1216
 * Caclulate quantization tables for version b
1217
 */
1218
static av_cold void binkb_calc_quant()
1219
{
1220
    double s[64];
1221
    int i, j;
1222

    
1223
    for (j = 0; j < 8; j++) {
1224
        for (i = 0; i < 8; i++) {
1225
            if (j && j != 4)
1226
               if (i && i != 4)
1227
                   s[j*8 + i] = cos(j * M_PI/16.0) * cos(i * M_PI/16.0) * 2.0;
1228
               else
1229
                   s[j*8 + i] = cos(j * M_PI/16.0) * sqrt(2.0);
1230
            else
1231
               if (i && i != 4)
1232
                   s[j*8 + i] = cos(i * M_PI/16.0) * sqrt(2.0);
1233
               else
1234
                   s[j*8 + i] = 1.0;
1235
        }
1236
    }
1237

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

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

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

    
1283
    c->pic.data[0] = NULL;
1284

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

    
1289
    avctx->pix_fmt = c->has_alpha ? PIX_FMT_YUVA420P : PIX_FMT_YUV420P;
1290

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

    
1295
    init_bundles(c);
1296

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

    
1304
    return 0;
1305
}
1306

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

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

    
1316
    free_bundles(c);
1317
    return 0;
1318
}
1319

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