Statistics
| Branch: | Revision:

ffmpeg / libavcodec / bink.c @ 1d6065ad

History | View | Annotate | Download (32.6 KB)

1
/*
2
 * Bink video decoder
3
 * Copyright (c) 2009 Konstantin Shishkov
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
#include "avcodec.h"
23
#include "dsputil.h"
24
#include "binkdata.h"
25
#include "mathops.h"
26

    
27
#define ALT_BITSTREAM_READER_LE
28
#include "get_bits.h"
29

    
30
static VLC bink_trees[16];
31

    
32
/**
33
 * IDs for different data types used in Bink video codec
34
 */
35
enum Sources {
36
    BINK_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
37
    BINK_SRC_SUB_BLOCK_TYPES, ///< 16x16 block types (a subset of 8x8 block types)
38
    BINK_SRC_COLORS,          ///< pixel values used for different block types
39
    BINK_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
40
    BINK_SRC_X_OFF,           ///< X components of motion value
41
    BINK_SRC_Y_OFF,           ///< Y components of motion value
42
    BINK_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
43
    BINK_SRC_INTER_DC,        ///< DC values for intrablocks with DCT
44
    BINK_SRC_RUN,             ///< run lengths for special fill block
45

    
46
    BINK_NB_SRC
47
};
48

    
49
/**
50
 * data needed to decode 4-bit Huffman-coded value
51
 */
52
typedef struct Tree {
53
    int     vlc_num;  ///< tree number (in bink_trees[])
54
    uint8_t syms[16]; ///< leaf value to symbol mapping
55
} Tree;
56

    
57
#define GET_HUFF(gb, tree)  (tree).syms[get_vlc2(gb, bink_trees[(tree).vlc_num].table,\
58
                                                 bink_trees[(tree).vlc_num].bits, 1)]
59

    
60
/**
61
 * data structure used for decoding single Bink data type
62
 */
63
typedef struct Bundle {
64
    int     len;       ///< length of number of entries to decode (in bits)
65
    Tree    tree;      ///< Huffman tree-related data
66
    uint8_t *data;     ///< buffer for decoded symbols
67
    uint8_t *data_end; ///< buffer end
68
    uint8_t *cur_dec;  ///< pointer to the not yet decoded part of the buffer
69
    uint8_t *cur_ptr;  ///< pointer to the data that is not read from buffer yet
70
} Bundle;
71

    
72
/*
73
 * Decoder context
74
 */
75
typedef struct BinkContext {
76
    AVCodecContext *avctx;
77
    DSPContext     dsp;
78
    AVFrame        pic, last;
79
    int            version;              ///< internal Bink file version
80
    int            has_alpha;
81
    int            swap_planes;
82
    ScanTable      scantable;            ///< permutated scantable for DCT coeffs decoding
83

    
84
    Bundle         bundle[BINK_NB_SRC];  ///< bundles for decoding all data types
85
    Tree           col_high[16];         ///< trees for decoding high nibble in "colours" data type
86
    int            col_lastval;          ///< value of last decoded high nibble in "colours" data type
87
} BinkContext;
88

    
89
/**
90
 * Bink video block types
91
 */
92
enum BlockTypes {
93
    SKIP_BLOCK = 0, ///< skipped block
94
    SCALED_BLOCK,   ///< block has size 16x16
95
    MOTION_BLOCK,   ///< block is copied from previous frame with some offset
96
    RUN_BLOCK,      ///< block is composed from runs of colours with custom scan order
97
    RESIDUE_BLOCK,  ///< motion block with some difference added
98
    INTRA_BLOCK,    ///< intra DCT block
99
    FILL_BLOCK,     ///< block is filled with single colour
100
    INTER_BLOCK,    ///< motion block with DCT applied to the difference
101
    PATTERN_BLOCK,  ///< block is filled with two colours following custom pattern
102
    RAW_BLOCK,      ///< uncoded 8x8 block
103
};
104

    
105
/**
106
 * Initializes length length in all bundles.
107
 *
108
 * @param c     decoder context
109
 * @param width plane width
110
 * @param bw    plane width in 8x8 blocks
111
 */
112
static void init_lengths(BinkContext *c, int width, int bw)
113
{
114
    c->bundle[BINK_SRC_BLOCK_TYPES].len = av_log2((width >> 3) + 511) + 1;
115

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

    
118
    c->bundle[BINK_SRC_COLORS].len = av_log2((width >> 3)*64 + 511) + 1;
119

    
120
    c->bundle[BINK_SRC_INTRA_DC].len =
121
    c->bundle[BINK_SRC_INTER_DC].len =
122
    c->bundle[BINK_SRC_X_OFF].len =
123
    c->bundle[BINK_SRC_Y_OFF].len = av_log2((width >> 3) + 511) + 1;
124

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

    
127
    c->bundle[BINK_SRC_RUN].len = av_log2((width >> 3)*48 + 511) + 1;
128
}
129

    
130
/**
131
 * Allocates memory for bundles.
132
 *
133
 * @param c decoder context
134
 */
135
static av_cold void init_bundles(BinkContext *c)
136
{
137
    int bw, bh, blocks;
138
    int i;
139

    
140
    bw = (c->avctx->width  + 7) >> 3;
141
    bh = (c->avctx->height + 7) >> 3;
142
    blocks = bw * bh;
143

    
144
    for (i = 0; i < BINK_NB_SRC; i++) {
145
        c->bundle[i].data = av_malloc(blocks * 64);
146
        c->bundle[i].data_end = c->bundle[i].data + blocks * 64;
147
    }
148
}
149

    
150
/**
151
 * Frees memory used by bundles.
152
 *
153
 * @param c decoder context
154
 */
155
static av_cold void free_bundles(BinkContext *c)
156
{
157
    int i;
158
    for (i = 0; i < BINK_NB_SRC; i++)
159
        av_freep(&c->bundle[i].data);
160
}
161

    
162
/**
163
 * Merges two consequent lists of equal size depending on bits read.
164
 *
165
 * @param gb   context for reading bits
166
 * @param dst  buffer where merged list will be written to
167
 * @param src  pointer to the head of the first list (the second lists starts at src+size)
168
 * @param size input lists size
169
 */
170
static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
171
{
172
    uint8_t *src2 = src + size;
173
    int size2 = size;
174

    
175
    do {
176
        if (!get_bits1(gb)) {
177
            *dst++ = *src++;
178
            size--;
179
        } else {
180
            *dst++ = *src2++;
181
            size2--;
182
        }
183
    } while (size && size2);
184

    
185
    while (size--)
186
        *dst++ = *src++;
187
    while (size2--)
188
        *dst++ = *src2++;
189
}
190

    
191
/**
192
 * Reads information about Huffman tree used to decode data.
193
 *
194
 * @param gb   context for reading bits
195
 * @param tree pointer for storing tree data
196
 */
197
static void read_tree(GetBitContext *gb, Tree *tree)
198
{
199
    uint8_t tmp1[16], tmp2[16], *in = tmp1, *out = tmp2;
200
    int i, t, len;
201

    
202
    tree->vlc_num = get_bits(gb, 4);
203
    if (!tree->vlc_num) {
204
        for (i = 0; i < 16; i++)
205
            tree->syms[i] = i;
206
        return;
207
    }
208
    if (get_bits1(gb)) {
209
        len = get_bits(gb, 3);
210
        memset(tmp1, 0, sizeof(tmp1));
211
        for (i = 0; i <= len; i++) {
212
            tree->syms[i] = get_bits(gb, 4);
213
            tmp1[tree->syms[i]] = 1;
214
        }
215
        for (i = 0; i < 16; i++)
216
            if (!tmp1[i])
217
                tree->syms[++len] = i;
218
    } else {
219
        len = get_bits(gb, 2);
220
        for (i = 0; i < 16; i++)
221
            in[i] = i;
222
        for (i = 0; i <= len; i++) {
223
            int size = 1 << i;
224
            for (t = 0; t < 16; t += size << 1)
225
                merge(gb, out + t, in + t, size);
226
            FFSWAP(uint8_t*, in, out);
227
        }
228
        memcpy(tree->syms, in, 16);
229
    }
230
}
231

    
232
/**
233
 * Prepares bundle for decoding data.
234
 *
235
 * @param gb          context for reading bits
236
 * @param c           decoder context
237
 * @param bundle_num  number of the bundle to initialize
238
 */
239
static void read_bundle(GetBitContext *gb, BinkContext *c, int bundle_num)
240
{
241
    int i;
242

    
243
    if (bundle_num == BINK_SRC_COLORS) {
244
        for (i = 0; i < 16; i++)
245
            read_tree(gb, &c->col_high[i]);
246
        c->col_lastval = 0;
247
    }
248
    if (bundle_num != BINK_SRC_INTRA_DC && bundle_num != BINK_SRC_INTER_DC)
249
        read_tree(gb, &c->bundle[bundle_num].tree);
250
    c->bundle[bundle_num].cur_dec =
251
    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
252
}
253

    
254
/**
255
 * common check before starting decoding bundle data
256
 *
257
 * @param gb context for reading bits
258
 * @param b  bundle
259
 * @param t  variable where number of elements to decode will be stored
260
 */
261
#define CHECK_READ_VAL(gb, b, t) \
262
    if (!b->cur_dec || (b->cur_dec > b->cur_ptr)) \
263
        return 0; \
264
    t = get_bits(gb, b->len); \
265
    if (!t) { \
266
        b->cur_dec = NULL; \
267
        return 0; \
268
    } \
269

    
270
static int read_runs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
271
{
272
    int t, v;
273
    const uint8_t *dec_end;
274

    
275
    CHECK_READ_VAL(gb, b, t);
276
    dec_end = b->cur_dec + t;
277
    if (dec_end > b->data_end) {
278
        av_log(avctx, AV_LOG_ERROR, "Run value went out of bounds\n");
279
        return -1;
280
    }
281
    if (get_bits1(gb)) {
282
        v = get_bits(gb, 4);
283
        memset(b->cur_dec, v, t);
284
        b->cur_dec += t;
285
    } else {
286
        while (b->cur_dec < dec_end)
287
            *b->cur_dec++ = GET_HUFF(gb, b->tree);
288
    }
289
    return 0;
290
}
291

    
292
static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
293
{
294
    int t, sign, v;
295
    const uint8_t *dec_end;
296

    
297
    CHECK_READ_VAL(gb, b, t);
298
    dec_end = b->cur_dec + t;
299
    if (dec_end > b->data_end) {
300
        av_log(avctx, AV_LOG_ERROR, "Too many motion values\n");
301
        return -1;
302
    }
303
    if (get_bits1(gb)) {
304
        v = get_bits(gb, 4);
305
        if (v) {
306
            sign = -get_bits1(gb);
307
            v = (v ^ sign) - sign;
308
        }
309
        memset(b->cur_dec, v, t);
310
        b->cur_dec += t;
311
    } else {
312
        do {
313
            v = GET_HUFF(gb, b->tree);
314
            if (v) {
315
                sign = -get_bits1(gb);
316
                v = (v ^ sign) - sign;
317
            }
318
            *b->cur_dec++ = v;
319
        } while (b->cur_dec < dec_end);
320
    }
321
    return 0;
322
}
323

    
324
const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
325

    
326
static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
327
{
328
    int t, v;
329
    int last = 0;
330
    const uint8_t *dec_end;
331

    
332
    CHECK_READ_VAL(gb, b, t);
333
    dec_end = b->cur_dec + t;
334
    if (dec_end > b->data_end) {
335
        av_log(avctx, AV_LOG_ERROR, "Too many block type values\n");
336
        return -1;
337
    }
338
    if (get_bits1(gb)) {
339
        v = get_bits(gb, 4);
340
        memset(b->cur_dec, v, t);
341
        b->cur_dec += t;
342
    } else {
343
        do {
344
            v = GET_HUFF(gb, b->tree);
345
            if (v < 12) {
346
                last = v;
347
                *b->cur_dec++ = v;
348
            } else {
349
                int run = bink_rlelens[v - 12];
350

    
351
                memset(b->cur_dec, last, run);
352
                b->cur_dec += run;
353
            }
354
        } while (b->cur_dec < dec_end);
355
    }
356
    return 0;
357
}
358

    
359
static int read_patterns(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
360
{
361
    int t, v;
362
    const uint8_t *dec_end;
363

    
364
    CHECK_READ_VAL(gb, b, t);
365
    dec_end = b->cur_dec + t;
366
    if (dec_end > b->data_end) {
367
        av_log(avctx, AV_LOG_ERROR, "Too many pattern values\n");
368
        return -1;
369
    }
370
    while (b->cur_dec < dec_end) {
371
        v  = GET_HUFF(gb, b->tree);
372
        v |= GET_HUFF(gb, b->tree) << 4;
373
        *b->cur_dec++ = v;
374
    }
375

    
376
    return 0;
377
}
378

    
379
static int read_colors(GetBitContext *gb, Bundle *b, BinkContext *c)
380
{
381
    int t, sign, v;
382
    const uint8_t *dec_end;
383

    
384
    CHECK_READ_VAL(gb, b, t);
385
    dec_end = b->cur_dec + t;
386
    if (dec_end > b->data_end) {
387
        av_log(c->avctx, AV_LOG_ERROR, "Too many color values\n");
388
        return -1;
389
    }
390
    if (get_bits1(gb)) {
391
        c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
392
        v = GET_HUFF(gb, b->tree);
393
        v = (c->col_lastval << 4) | v;
394
        if (c->version < 'i') {
395
            sign = ((int8_t) v) >> 7;
396
            v = ((v & 0x7F) ^ sign) - sign;
397
            v += 0x80;
398
        }
399
        memset(b->cur_dec, v, t);
400
        b->cur_dec += t;
401
    } else {
402
        while (b->cur_dec < dec_end) {
403
            c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
404
            v = GET_HUFF(gb, b->tree);
405
            v = (c->col_lastval << 4) | v;
406
            if (c->version < 'i') {
407
                sign = ((int8_t) v) >> 7;
408
                v = ((v & 0x7F) ^ sign) - sign;
409
                v += 0x80;
410
            }
411
            *b->cur_dec++ = v;
412
        }
413
    }
414
    return 0;
415
}
416

    
417
/** number of bits used to store first DC value in bundle */
418
#define DC_START_BITS 11
419

    
420
static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,
421
                    int start_bits, int has_sign)
422
{
423
    int i, j, len, len2, bsize, sign, v, v2;
424
    int16_t *dst = (int16_t*)b->cur_dec;
425

    
426
    CHECK_READ_VAL(gb, b, len);
427
    v = get_bits(gb, start_bits - has_sign);
428
    if (v && has_sign) {
429
        sign = -get_bits1(gb);
430
        v = (v ^ sign) - sign;
431
    }
432
    *dst++ = v;
433
    len--;
434
    for (i = 0; i < len; i += 8) {
435
        len2 = FFMIN(len - i, 8);
436
        bsize = get_bits(gb, 4);
437
        if (bsize) {
438
            for (j = 0; j < len2; j++) {
439
                v2 = get_bits(gb, bsize);
440
                if (v2) {
441
                    sign = -get_bits1(gb);
442
                    v2 = (v2 ^ sign) - sign;
443
                }
444
                v += v2;
445
                *dst++ = v;
446
                if (v < -32768 || v > 32767) {
447
                    av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v);
448
                    return -1;
449
                }
450
            }
451
        } else {
452
            for (j = 0; j < len2; j++)
453
                *dst++ = v;
454
        }
455
    }
456

    
457
    b->cur_dec = (uint8_t*)dst;
458
    return 0;
459
}
460

    
461
/**
462
 * Retrieves next value from bundle.
463
 *
464
 * @param c      decoder context
465
 * @param bundle bundle number
466
 */
467
static inline int get_value(BinkContext *c, int bundle)
468
{
469
    int16_t ret;
470

    
471
    if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN)
472
        return *c->bundle[bundle].cur_ptr++;
473
    if (bundle == BINK_SRC_X_OFF || bundle == BINK_SRC_Y_OFF)
474
        return (int8_t)*c->bundle[bundle].cur_ptr++;
475
    ret = *(int16_t*)c->bundle[bundle].cur_ptr;
476
    c->bundle[bundle].cur_ptr += 2;
477
    return ret;
478
}
479

    
480
/**
481
 * Reads 8x8 block of DCT coefficients.
482
 *
483
 * @param gb       context for reading bits
484
 * @param block    place for storing coefficients
485
 * @param scan     scan order table
486
 * @param is_intra tells what set of quantizer matrices to use
487
 * @return 0 for success, negative value in other cases
488
 */
489
static int read_dct_coeffs(GetBitContext *gb, DCTELEM block[64], const uint8_t *scan,
490
                           int is_intra)
491
{
492
    int coef_list[128];
493
    int mode_list[128];
494
    int i, t, mask, bits, ccoef, mode, sign;
495
    int list_start = 64, list_end = 64, list_pos;
496
    int coef_count = 0;
497
    int coef_idx[64];
498
    int quant_idx;
499
    const uint32_t *quant;
500

    
501
    coef_list[list_end] = 4;  mode_list[list_end++] = 0;
502
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
503
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
504
    coef_list[list_end] = 1;  mode_list[list_end++] = 3;
505
    coef_list[list_end] = 2;  mode_list[list_end++] = 3;
506
    coef_list[list_end] = 3;  mode_list[list_end++] = 3;
507

    
508
    bits = get_bits(gb, 4) - 1;
509
    for (mask = 1 << bits; bits >= 0; mask >>= 1, bits--) {
510
        list_pos = list_start;
511
        while (list_pos < list_end) {
512
            if (!(mode_list[list_pos] | coef_list[list_pos]) || !get_bits1(gb)) {
513
                list_pos++;
514
                continue;
515
            }
516
            ccoef = coef_list[list_pos];
517
            mode  = mode_list[list_pos];
518
            switch (mode) {
519
            case 0:
520
                coef_list[list_pos] = ccoef + 4;
521
                mode_list[list_pos] = 1;
522
            case 2:
523
                if (mode == 2) {
524
                    coef_list[list_pos]   = 0;
525
                    mode_list[list_pos++] = 0;
526
                }
527
                for (i = 0; i < 4; i++, ccoef++) {
528
                    if (get_bits1(gb)) {
529
                        coef_list[--list_start] = ccoef;
530
                        mode_list[  list_start] = 3;
531
                    } else {
532
                        int t;
533
                        if (!bits) {
534
                            t = 1 - (get_bits1(gb) << 1);
535
                        } else {
536
                            t = get_bits(gb, bits) | mask;
537
                            sign = -get_bits1(gb);
538
                            t = (t ^ sign) - sign;
539
                        }
540
                        block[scan[ccoef]] = t;
541
                        coef_idx[coef_count++] = ccoef;
542
                    }
543
                }
544
                break;
545
            case 1:
546
                mode_list[list_pos] = 2;
547
                for (i = 0; i < 3; i++) {
548
                    ccoef += 4;
549
                    coef_list[list_end]   = ccoef;
550
                    mode_list[list_end++] = 2;
551
                }
552
                break;
553
            case 3:
554
                if (!bits) {
555
                    t = 1 - (get_bits1(gb) << 1);
556
                } else {
557
                    t = get_bits(gb, bits) | mask;
558
                    sign = -get_bits1(gb);
559
                    t = (t ^ sign) - sign;
560
                }
561
                block[scan[ccoef]] = t;
562
                coef_idx[coef_count++] = ccoef;
563
                coef_list[list_pos]   = 0;
564
                mode_list[list_pos++] = 0;
565
                break;
566
            }
567
        }
568
    }
569

    
570
    quant_idx = get_bits(gb, 4);
571
    quant = is_intra ? bink_intra_quant[quant_idx]
572
                     : bink_inter_quant[quant_idx];
573
    block[0] = (block[0] * quant[0]) >> 11;
574
    for (i = 0; i < coef_count; i++) {
575
        int idx = coef_idx[i];
576
        block[scan[idx]] = (block[scan[idx]] * quant[idx]) >> 11;
577
    }
578

    
579
    return 0;
580
}
581

    
582
/**
583
 * Reads 8x8 block with residue after motion compensation.
584
 *
585
 * @param gb          context for reading bits
586
 * @param block       place to store read data
587
 * @param masks_count number of masks to decode
588
 * @return 0 on success, negative value in other cases
589
 */
590
static int read_residue(GetBitContext *gb, DCTELEM block[64], int masks_count)
591
{
592
    int coef_list[128];
593
    int mode_list[128];
594
    int i, sign, mask, ccoef, mode;
595
    int list_start = 64, list_end = 64, list_pos;
596
    int nz_coeff[64];
597
    int nz_coeff_count = 0;
598

    
599
    coef_list[list_end] =  4; mode_list[list_end++] = 0;
600
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
601
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
602
    coef_list[list_end] =  0; mode_list[list_end++] = 2;
603

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

    
669
    return 0;
670
}
671

    
672
static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *pkt)
673
{
674
    BinkContext * const c = avctx->priv_data;
675
    GetBitContext gb;
676
    int blk;
677
    int i, j, plane, plane_idx, bx, by;
678
    uint8_t *dst, *prev, *ref, *ref_start, *ref_end;
679
    int v, col[2];
680
    const uint8_t *scan;
681
    int xoff, yoff;
682
    DECLARE_ALIGNED_16(DCTELEM, block[64]);
683
    DECLARE_ALIGNED_16(uint8_t, ublock[64]);
684
    int coordmap[64];
685
    int bits_count = pkt->size << 3;
686

    
687
    if(c->pic.data[0])
688
        avctx->release_buffer(avctx, &c->pic);
689

    
690
    if(avctx->get_buffer(avctx, &c->pic) < 0){
691
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
692
        return -1;
693
    }
694

    
695
    init_get_bits(&gb, pkt->data, bits_count);
696
    if (c->has_alpha) {
697
        int aplane_bits = get_bits_long(&gb, 32) << 3;
698
        if (aplane_bits <= 32 || (aplane_bits & 0x1F)) {
699
            av_log(avctx, AV_LOG_ERROR, "Incorrect alpha plane size %d\n", aplane_bits);
700
            return -1;
701
        }
702
        skip_bits_long(&gb, aplane_bits - 32);
703
    }
704
    if (c->version >= 'i')
705
        skip_bits_long(&gb, 32);
706

    
707
    for (plane = 0; plane < 3; plane++) {
708
        const int stride = c->pic.linesize[plane];
709
        int bw = plane ? (avctx->width  + 15) >> 4 : (avctx->width  + 7) >> 3;
710
        int bh = plane ? (avctx->height + 15) >> 4 : (avctx->height + 7) >> 3;
711
        int width = avctx->width >> !!plane;
712

    
713
        init_lengths(c, FFMAX(width, 8), bw);
714
        for (i = 0; i < BINK_NB_SRC; i++)
715
            read_bundle(&gb, c, i);
716

    
717
        plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);
718
        ref_start = c->last.data[plane_idx];
719
        ref_end   = c->last.data[plane_idx]
720
                    + (bw - 1 + c->last.linesize[plane_idx] * (bh - 1)) * 8;
721

    
722
        for (i = 0; i < 64; i++)
723
            coordmap[i] = (i & 7) + (i >> 3) * stride;
724

    
725
        for (by = 0; by < bh; by++) {
726
            if (read_block_types(avctx, &gb, &c->bundle[BINK_SRC_BLOCK_TYPES]) < 0)
727
                return -1;
728
            if (read_block_types(avctx, &gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES]) < 0)
729
                return -1;
730
            if (read_colors(&gb, &c->bundle[BINK_SRC_COLORS], c) < 0)
731
                return -1;
732
            if (read_patterns(avctx, &gb, &c->bundle[BINK_SRC_PATTERN]) < 0)
733
                return -1;
734
            if (read_motion_values(avctx, &gb, &c->bundle[BINK_SRC_X_OFF]) < 0)
735
                return -1;
736
            if (read_motion_values(avctx, &gb, &c->bundle[BINK_SRC_Y_OFF]) < 0)
737
                return -1;
738
            if (read_dcs(avctx, &gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0) < 0)
739
                return -1;
740
            if (read_dcs(avctx, &gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1) < 0)
741
                return -1;
742
            if (read_runs(avctx, &gb, &c->bundle[BINK_SRC_RUN]) < 0)
743
                return -1;
744

    
745
            if (by == bh)
746
                break;
747
            dst  = c->pic.data[plane_idx]  + 8*by*stride;
748
            prev = c->last.data[plane_idx] + 8*by*stride;
749
            for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {
750
                blk = get_value(c, BINK_SRC_BLOCK_TYPES);
751
                // 16x16 block type on odd line means part of the already decoded block, so skip it
752
                if ((by & 1) && blk == SCALED_BLOCK) {
753
                    bx++;
754
                    dst  += 8;
755
                    prev += 8;
756
                    continue;
757
                }
758
                switch (blk) {
759
                case SKIP_BLOCK:
760
                    c->dsp.put_pixels_tab[1][0](dst, prev, stride, 8);
761
                    break;
762
                case SCALED_BLOCK:
763
                    blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);
764
                    switch (blk) {
765
                    case RUN_BLOCK:
766
                        scan = bink_patterns[get_bits(&gb, 4)];
767
                        i = 0;
768
                        do {
769
                            int run = get_value(c, BINK_SRC_RUN) + 1;
770

    
771
                            i += run;
772
                            if (i > 64) {
773
                                av_log(avctx, AV_LOG_ERROR, "Run went out of bounds\n");
774
                                return -1;
775
                            }
776
                            if (get_bits1(&gb)) {
777
                                v = get_value(c, BINK_SRC_COLORS);
778
                                for (j = 0; j < run; j++)
779
                                    ublock[*scan++] = v;
780
                            } else {
781
                                for (j = 0; j < run; j++)
782
                                    ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
783
                            }
784
                        } while (i < 63);
785
                        if (i == 63)
786
                            ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
787
                        break;
788
                    case INTRA_BLOCK:
789
                        c->dsp.clear_block(block);
790
                        block[0] = get_value(c, BINK_SRC_INTRA_DC);
791
                        read_dct_coeffs(&gb, block, c->scantable.permutated, 1);
792
                        c->dsp.idct(block);
793
                        c->dsp.put_pixels_nonclamped(block, ublock, 8);
794
                        break;
795
                    case FILL_BLOCK:
796
                        v = get_value(c, BINK_SRC_COLORS);
797
                        c->dsp.fill_block_tab[0](dst, v, stride, 16);
798
                        break;
799
                    case PATTERN_BLOCK:
800
                        for (i = 0; i < 2; i++)
801
                            col[i] = get_value(c, BINK_SRC_COLORS);
802
                        for (j = 0; j < 8; j++) {
803
                            v = get_value(c, BINK_SRC_PATTERN);
804
                            for (i = 0; i < 8; i++, v >>= 1)
805
                                ublock[i + j*8] = col[v & 1];
806
                        }
807
                        break;
808
                    case RAW_BLOCK:
809
                        for (j = 0; j < 8; j++)
810
                            for (i = 0; i < 8; i++)
811
                                ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);
812
                        break;
813
                    default:
814
                        av_log(avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);
815
                        return -1;
816
                    }
817
                    if (blk != FILL_BLOCK)
818
                        c->dsp.scale_block(ublock, dst, stride);
819
                    bx++;
820
                    dst  += 8;
821
                    prev += 8;
822
                    break;
823
                case MOTION_BLOCK:
824
                    xoff = get_value(c, BINK_SRC_X_OFF);
825
                    yoff = get_value(c, BINK_SRC_Y_OFF);
826
                    ref = prev + xoff + yoff * stride;
827
                    if (ref < ref_start || ref > ref_end) {
828
                        av_log(avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
829
                               bx*8 + xoff, by*8 + yoff);
830
                        return -1;
831
                    }
832
                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
833
                    break;
834
                case RUN_BLOCK:
835
                    scan = bink_patterns[get_bits(&gb, 4)];
836
                    i = 0;
837
                    do {
838
                        int run = get_value(c, BINK_SRC_RUN) + 1;
839

    
840
                        i += run;
841
                        if (i > 64) {
842
                            av_log(avctx, AV_LOG_ERROR, "Run went out of bounds\n");
843
                            return -1;
844
                        }
845
                        if (get_bits1(&gb)) {
846
                            v = get_value(c, BINK_SRC_COLORS);
847
                            for (j = 0; j < run; j++)
848
                                dst[coordmap[*scan++]] = v;
849
                        } else {
850
                            for (j = 0; j < run; j++)
851
                                dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
852
                        }
853
                    } while (i < 63);
854
                    if (i == 63)
855
                        dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
856
                    break;
857
                case RESIDUE_BLOCK:
858
                    xoff = get_value(c, BINK_SRC_X_OFF);
859
                    yoff = get_value(c, BINK_SRC_Y_OFF);
860
                    ref = prev + xoff + yoff * stride;
861
                    if (ref < ref_start || ref > ref_end) {
862
                        av_log(avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
863
                               bx*8 + xoff, by*8 + yoff);
864
                        return -1;
865
                    }
866
                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
867
                    c->dsp.clear_block(block);
868
                    v = get_bits(&gb, 7);
869
                    read_residue(&gb, block, v);
870
                    c->dsp.add_pixels8(dst, block, stride);
871
                    break;
872
                case INTRA_BLOCK:
873
                    c->dsp.clear_block(block);
874
                    block[0] = get_value(c, BINK_SRC_INTRA_DC);
875
                    read_dct_coeffs(&gb, block, c->scantable.permutated, 1);
876
                    c->dsp.idct_put(dst, stride, block);
877
                    break;
878
                case FILL_BLOCK:
879
                    v = get_value(c, BINK_SRC_COLORS);
880
                    c->dsp.fill_block_tab[1](dst, v, stride, 8);
881
                    break;
882
                case INTER_BLOCK:
883
                    xoff = get_value(c, BINK_SRC_X_OFF);
884
                    yoff = get_value(c, BINK_SRC_Y_OFF);
885
                    ref = prev + xoff + yoff * stride;
886
                    c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
887
                    c->dsp.clear_block(block);
888
                    block[0] = get_value(c, BINK_SRC_INTER_DC);
889
                    read_dct_coeffs(&gb, block, c->scantable.permutated, 0);
890
                    c->dsp.idct_add(dst, stride, block);
891
                    break;
892
                case PATTERN_BLOCK:
893
                    for (i = 0; i < 2; i++)
894
                        col[i] = get_value(c, BINK_SRC_COLORS);
895
                    for (i = 0; i < 8; i++) {
896
                        v = get_value(c, BINK_SRC_PATTERN);
897
                        for (j = 0; j < 8; j++, v >>= 1)
898
                            dst[i*stride + j] = col[v & 1];
899
                    }
900
                    break;
901
                case RAW_BLOCK:
902
                    for (i = 0; i < 8; i++)
903
                        memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);
904
                    c->bundle[BINK_SRC_COLORS].cur_ptr += 64;
905
                    break;
906
                default:
907
                    av_log(avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
908
                    return -1;
909
                }
910
            }
911
        }
912
        if (get_bits_count(&gb) & 0x1F) //next plane data starts at 32-bit boundary
913
            skip_bits_long(&gb, 32 - (get_bits_count(&gb) & 0x1F));
914
        if (get_bits_count(&gb) >= bits_count)
915
            break;
916
    }
917
    emms_c();
918

    
919
    *data_size = sizeof(AVFrame);
920
    *(AVFrame*)data = c->pic;
921

    
922
    FFSWAP(AVFrame, c->pic, c->last);
923

    
924
    /* always report that the buffer was completely consumed */
925
    return pkt->size;
926
}
927

    
928
static av_cold int decode_init(AVCodecContext *avctx)
929
{
930
    BinkContext * const c = avctx->priv_data;
931
    static VLC_TYPE table[16 * 128][2];
932
    int i;
933

    
934
    c->version = avctx->codec_tag >> 24;
935
    if (c->version < 'c') {
936
        av_log(avctx, AV_LOG_ERROR, "Too old version '%c'\n", c->version);
937
        return -1;
938
    }
939
    c->has_alpha = 0; //TODO: demuxer should supply decoder with flags
940
    c->swap_planes = c->version >= 'i';
941
    if (!bink_trees[15].table) {
942
        for (i = 0; i < 16; i++) {
943
            const int maxbits = bink_tree_lens[i][15];
944
            bink_trees[i].table = table + i*128;
945
            bink_trees[i].table_allocated = 1 << maxbits;
946
            init_vlc(&bink_trees[i], maxbits, 16,
947
                     bink_tree_lens[i], 1, 1,
948
                     bink_tree_bits[i], 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
949
        }
950
    }
951
    c->avctx = avctx;
952

    
953
    c->pic.data[0] = NULL;
954

    
955
    if (avcodec_check_dimensions(avctx, avctx->width, avctx->height) < 0) {
956
        return 1;
957
    }
958

    
959
    avctx->pix_fmt = PIX_FMT_YUV420P;
960

    
961
    avctx->idct_algo = FF_IDCT_BINK;
962
    dsputil_init(&c->dsp, avctx);
963
    ff_init_scantable(c->dsp.idct_permutation, &c->scantable, bink_scan);
964

    
965
    init_bundles(c);
966

    
967
    return 0;
968
}
969

    
970
static av_cold int decode_end(AVCodecContext *avctx)
971
{
972
    BinkContext * const c = avctx->priv_data;
973

    
974
    if (c->pic.data[0])
975
        avctx->release_buffer(avctx, &c->pic);
976
    if (c->last.data[0])
977
        avctx->release_buffer(avctx, &c->last);
978

    
979
    free_bundles(c);
980
    return 0;
981
}
982

    
983
AVCodec bink_decoder = {
984
    "binkvideo",
985
    CODEC_TYPE_VIDEO,
986
    CODEC_ID_BINKVIDEO,
987
    sizeof(BinkContext),
988
    decode_init,
989
    NULL,
990
    decode_end,
991
    decode_frame,
992
    .long_name = NULL_IF_CONFIG_SMALL("Bink video"),
993
};