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

23
#include "libavutil/attributes.h"
24
#include "libavutil/imgutils.h"
25
#include "libavutil/internal.h"
26 27

#define BITSTREAM_READER_LE
Kostya Shishkov's avatar
Kostya Shishkov committed
28 29
#include "avcodec.h"
#include "binkdata.h"
30
#include "binkdsp.h"
31
#include "blockdsp.h"
32
#include "get_bits.h"
33
#include "hpeldsp.h"
34
#include "internal.h"
Kostya Shishkov's avatar
Kostya Shishkov committed
35 36
#include "mathops.h"

37 38 39
#define BINK_FLAG_ALPHA 0x00100000
#define BINK_FLAG_GRAY  0x00020000

Kostya Shishkov's avatar
Kostya Shishkov committed
40 41
static VLC bink_trees[16];

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/**
 * IDs for different data types used in old version of Bink video codec
 */
enum OldSources {
    BINKB_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
    BINKB_SRC_COLORS,          ///< pixel values used for different block types
    BINKB_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
    BINKB_SRC_X_OFF,           ///< X components of motion value
    BINKB_SRC_Y_OFF,           ///< Y components of motion value
    BINKB_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
    BINKB_SRC_INTER_DC,        ///< DC values for interblocks with DCT
    BINKB_SRC_INTRA_Q,         ///< quantizer values for intrablocks with DCT
    BINKB_SRC_INTER_Q,         ///< quantizer values for interblocks with DCT
    BINKB_SRC_INTER_COEFS,     ///< number of coefficients for residue blocks

    BINKB_NB_SRC
};

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

static const int binkb_bundle_signed[BINKB_NB_SRC] = {
    0, 0, 0, 1, 1, 0, 1, 0, 0, 0
};

68 69
static int32_t binkb_intra_quant[16][64];
static int32_t binkb_inter_quant[16][64];
70

Kostya Shishkov's avatar
Kostya Shishkov committed
71 72 73 74 75 76 77 78 79 80 81
/**
 * IDs for different data types used in Bink video codec
 */
enum Sources {
    BINK_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
    BINK_SRC_SUB_BLOCK_TYPES, ///< 16x16 block types (a subset of 8x8 block types)
    BINK_SRC_COLORS,          ///< pixel values used for different block types
    BINK_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
    BINK_SRC_X_OFF,           ///< X components of motion value
    BINK_SRC_Y_OFF,           ///< Y components of motion value
    BINK_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
Kostya Shishkov's avatar
Kostya Shishkov committed
82
    BINK_SRC_INTER_DC,        ///< DC values for interblocks with DCT
Kostya Shishkov's avatar
Kostya Shishkov committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    BINK_SRC_RUN,             ///< run lengths for special fill block

    BINK_NB_SRC
};

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

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

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

/*
 * Decoder context
 */
typedef struct BinkContext {
    AVCodecContext *avctx;
116
    BlockDSPContext bdsp;
117
    HpelDSPContext hdsp;
118
    BinkDSPContext binkdsp;
119
    AVFrame        *last;
Kostya Shishkov's avatar
Kostya Shishkov committed
120
    int            version;              ///< internal Bink file version
121
    int            has_alpha;
Kostya Shishkov's avatar
Kostya Shishkov committed
122 123
    int            swap_planes;

124
    Bundle         bundle[BINKB_NB_SRC]; ///< bundles for decoding all data types
Kostya Shishkov's avatar
Kostya Shishkov committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    Tree           col_high[16];         ///< trees for decoding high nibble in "colours" data type
    int            col_lastval;          ///< value of last decoded high nibble in "colours" data type
} BinkContext;

/**
 * Bink video block types
 */
enum BlockTypes {
    SKIP_BLOCK = 0, ///< skipped block
    SCALED_BLOCK,   ///< block has size 16x16
    MOTION_BLOCK,   ///< block is copied from previous frame with some offset
    RUN_BLOCK,      ///< block is composed from runs of colours with custom scan order
    RESIDUE_BLOCK,  ///< motion block with some difference added
    INTRA_BLOCK,    ///< intra DCT block
    FILL_BLOCK,     ///< block is filled with single colour
    INTER_BLOCK,    ///< motion block with DCT applied to the difference
    PATTERN_BLOCK,  ///< block is filled with two colours following custom pattern
    RAW_BLOCK,      ///< uncoded 8x8 block
};

/**
146
 * Initialize length length in all bundles.
Kostya Shishkov's avatar
Kostya Shishkov committed
147 148 149 150 151 152 153
 *
 * @param c     decoder context
 * @param width plane width
 * @param bw    plane width in 8x8 blocks
 */
static void init_lengths(BinkContext *c, int width, int bw)
{
154
    width = FFALIGN(width, 8);
155

Kostya Shishkov's avatar
Kostya Shishkov committed
156 157 158 159
    c->bundle[BINK_SRC_BLOCK_TYPES].len = av_log2((width >> 3) + 511) + 1;

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

160
    c->bundle[BINK_SRC_COLORS].len = av_log2(bw*64 + 511) + 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
161 162 163 164 165 166 167 168

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

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

169
    c->bundle[BINK_SRC_RUN].len = av_log2(bw*48 + 511) + 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
170 171 172
}

/**
173
 * Allocate memory for bundles.
Kostya Shishkov's avatar
Kostya Shishkov committed
174 175 176 177 178 179 180 181 182 183 184 185
 *
 * @param c decoder context
 */
static av_cold void init_bundles(BinkContext *c)
{
    int bw, bh, blocks;
    int i;

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

186
    for (i = 0; i < BINKB_NB_SRC; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
187 188 189 190 191 192
        c->bundle[i].data = av_malloc(blocks * 64);
        c->bundle[i].data_end = c->bundle[i].data + blocks * 64;
    }
}

/**
193
 * Free memory used by bundles.
Kostya Shishkov's avatar
Kostya Shishkov committed
194 195 196 197 198 199
 *
 * @param c decoder context
 */
static av_cold void free_bundles(BinkContext *c)
{
    int i;
200
    for (i = 0; i < BINKB_NB_SRC; i++)
Kostya Shishkov's avatar
Kostya Shishkov committed
201 202 203 204
        av_freep(&c->bundle[i].data);
}

/**
205
 * Merge two consequent lists of equal size depending on bits read.
Kostya Shishkov's avatar
Kostya Shishkov committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
 *
 * @param gb   context for reading bits
 * @param dst  buffer where merged list will be written to
 * @param src  pointer to the head of the first list (the second lists starts at src+size)
 * @param size input lists size
 */
static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
{
    uint8_t *src2 = src + size;
    int size2 = size;

    do {
        if (!get_bits1(gb)) {
            *dst++ = *src++;
            size--;
        } else {
            *dst++ = *src2++;
            size2--;
        }
    } while (size && size2);

    while (size--)
        *dst++ = *src++;
    while (size2--)
        *dst++ = *src2++;
}

/**
234
 * Read information about Huffman tree used to decode data.
Kostya Shishkov's avatar
Kostya Shishkov committed
235 236 237 238 239 240
 *
 * @param gb   context for reading bits
 * @param tree pointer for storing tree data
 */
static void read_tree(GetBitContext *gb, Tree *tree)
{
241
    uint8_t tmp1[16] = { 0 }, tmp2[16], *in = tmp1, *out = tmp2;
Kostya Shishkov's avatar
Kostya Shishkov committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255
    int i, t, len;

    tree->vlc_num = get_bits(gb, 4);
    if (!tree->vlc_num) {
        for (i = 0; i < 16; i++)
            tree->syms[i] = i;
        return;
    }
    if (get_bits1(gb)) {
        len = get_bits(gb, 3);
        for (i = 0; i <= len; i++) {
            tree->syms[i] = get_bits(gb, 4);
            tmp1[tree->syms[i]] = 1;
        }
256
        for (i = 0; i < 16 && len < 16 - 1; i++)
Kostya Shishkov's avatar
Kostya Shishkov committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
            if (!tmp1[i])
                tree->syms[++len] = i;
    } else {
        len = get_bits(gb, 2);
        for (i = 0; i < 16; i++)
            in[i] = i;
        for (i = 0; i <= len; i++) {
            int size = 1 << i;
            for (t = 0; t < 16; t += size << 1)
                merge(gb, out + t, in + t, size);
            FFSWAP(uint8_t*, in, out);
        }
        memcpy(tree->syms, in, 16);
    }
}

/**
274
 * Prepare bundle for decoding data.
Kostya Shishkov's avatar
Kostya Shishkov committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
 *
 * @param gb          context for reading bits
 * @param c           decoder context
 * @param bundle_num  number of the bundle to initialize
 */
static void read_bundle(GetBitContext *gb, BinkContext *c, int bundle_num)
{
    int i;

    if (bundle_num == BINK_SRC_COLORS) {
        for (i = 0; i < 16; i++)
            read_tree(gb, &c->col_high[i]);
        c->col_lastval = 0;
    }
    if (bundle_num != BINK_SRC_INTRA_DC && bundle_num != BINK_SRC_INTER_DC)
        read_tree(gb, &c->bundle[bundle_num].tree);
    c->bundle[bundle_num].cur_dec =
    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
}

/**
 * common check before starting decoding bundle data
 *
 * @param gb context for reading bits
 * @param b  bundle
 * @param t  variable where number of elements to decode will be stored
 */
#define CHECK_READ_VAL(gb, b, t) \
    if (!b->cur_dec || (b->cur_dec > b->cur_ptr)) \
        return 0; \
    t = get_bits(gb, b->len); \
    if (!t) { \
        b->cur_dec = NULL; \
        return 0; \
    } \

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

    CHECK_READ_VAL(gb, b, t);
    dec_end = b->cur_dec + t;
    if (dec_end > b->data_end) {
        av_log(avctx, AV_LOG_ERROR, "Run value went out of bounds\n");
320
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    }
    if (get_bits1(gb)) {
        v = get_bits(gb, 4);
        memset(b->cur_dec, v, t);
        b->cur_dec += t;
    } else {
        while (b->cur_dec < dec_end)
            *b->cur_dec++ = GET_HUFF(gb, b->tree);
    }
    return 0;
}

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

    CHECK_READ_VAL(gb, b, t);
    dec_end = b->cur_dec + t;
    if (dec_end > b->data_end) {
        av_log(avctx, AV_LOG_ERROR, "Too many motion values\n");
342
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
343 344 345 346 347 348 349 350 351 352
    }
    if (get_bits1(gb)) {
        v = get_bits(gb, 4);
        if (v) {
            sign = -get_bits1(gb);
            v = (v ^ sign) - sign;
        }
        memset(b->cur_dec, v, t);
        b->cur_dec += t;
    } else {
353
        while (b->cur_dec < dec_end) {
Kostya Shishkov's avatar
Kostya Shishkov committed
354 355 356 357 358 359
            v = GET_HUFF(gb, b->tree);
            if (v) {
                sign = -get_bits1(gb);
                v = (v ^ sign) - sign;
            }
            *b->cur_dec++ = v;
360
        }
Kostya Shishkov's avatar
Kostya Shishkov committed
361 362 363 364
    }
    return 0;
}

365
static const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
Kostya Shishkov's avatar
Kostya Shishkov committed
366 367 368 369 370 371 372 373 374 375 376

static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
{
    int t, v;
    int last = 0;
    const uint8_t *dec_end;

    CHECK_READ_VAL(gb, b, t);
    dec_end = b->cur_dec + t;
    if (dec_end > b->data_end) {
        av_log(avctx, AV_LOG_ERROR, "Too many block type values\n");
377
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
378 379 380 381 382 383
    }
    if (get_bits1(gb)) {
        v = get_bits(gb, 4);
        memset(b->cur_dec, v, t);
        b->cur_dec += t;
    } else {
384
        while (b->cur_dec < dec_end) {
Kostya Shishkov's avatar
Kostya Shishkov committed
385 386 387 388 389 390 391
            v = GET_HUFF(gb, b->tree);
            if (v < 12) {
                last = v;
                *b->cur_dec++ = v;
            } else {
                int run = bink_rlelens[v - 12];

392
                if (dec_end - b->cur_dec < run)
393
                    return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
394 395 396
                memset(b->cur_dec, last, run);
                b->cur_dec += run;
            }
397
        }
Kostya Shishkov's avatar
Kostya Shishkov committed
398 399 400 401 402 403 404 405 406 407 408 409 410
    }
    return 0;
}

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

    CHECK_READ_VAL(gb, b, t);
    dec_end = b->cur_dec + t;
    if (dec_end > b->data_end) {
        av_log(avctx, AV_LOG_ERROR, "Too many pattern values\n");
411
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    }
    while (b->cur_dec < dec_end) {
        v  = GET_HUFF(gb, b->tree);
        v |= GET_HUFF(gb, b->tree) << 4;
        *b->cur_dec++ = v;
    }

    return 0;
}

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

    CHECK_READ_VAL(gb, b, t);
    dec_end = b->cur_dec + t;
    if (dec_end > b->data_end) {
        av_log(c->avctx, AV_LOG_ERROR, "Too many color values\n");
431
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    }
    if (get_bits1(gb)) {
        c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
        v = GET_HUFF(gb, b->tree);
        v = (c->col_lastval << 4) | v;
        if (c->version < 'i') {
            sign = ((int8_t) v) >> 7;
            v = ((v & 0x7F) ^ sign) - sign;
            v += 0x80;
        }
        memset(b->cur_dec, v, t);
        b->cur_dec += t;
    } else {
        while (b->cur_dec < dec_end) {
            c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
            v = GET_HUFF(gb, b->tree);
            v = (c->col_lastval << 4) | v;
            if (c->version < 'i') {
                sign = ((int8_t) v) >> 7;
                v = ((v & 0x7F) ^ sign) - sign;
                v += 0x80;
            }
            *b->cur_dec++ = v;
        }
    }
    return 0;
}

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

static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,
                    int start_bits, int has_sign)
{
    int i, j, len, len2, bsize, sign, v, v2;
467 468
    int16_t *dst     = (int16_t*)b->cur_dec;
    int16_t *dst_end = (int16_t*)b->data_end;
Kostya Shishkov's avatar
Kostya Shishkov committed
469 470 471 472 473 474 475

    CHECK_READ_VAL(gb, b, len);
    v = get_bits(gb, start_bits - has_sign);
    if (v && has_sign) {
        sign = -get_bits1(gb);
        v = (v ^ sign) - sign;
    }
476
    if (dst_end - dst < 1)
477
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
478 479 480 481
    *dst++ = v;
    len--;
    for (i = 0; i < len; i += 8) {
        len2 = FFMIN(len - i, 8);
482
        if (dst_end - dst < len2)
483
            return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
484 485 486 487 488 489 490 491 492 493 494 495
        bsize = get_bits(gb, 4);
        if (bsize) {
            for (j = 0; j < len2; j++) {
                v2 = get_bits(gb, bsize);
                if (v2) {
                    sign = -get_bits1(gb);
                    v2 = (v2 ^ sign) - sign;
                }
                v += v2;
                *dst++ = v;
                if (v < -32768 || v > 32767) {
                    av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v);
496
                    return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
497 498 499 500 501 502 503 504 505 506 507 508 509
                }
            }
        } else {
            for (j = 0; j < len2; j++)
                *dst++ = v;
        }
    }

    b->cur_dec = (uint8_t*)dst;
    return 0;
}

/**
510
 * Retrieve next value from bundle.
Kostya Shishkov's avatar
Kostya Shishkov committed
511 512 513 514 515 516
 *
 * @param c      decoder context
 * @param bundle bundle number
 */
static inline int get_value(BinkContext *c, int bundle)
{
517
    int ret;
Kostya Shishkov's avatar
Kostya Shishkov committed
518 519 520 521 522 523 524 525 526 527

    if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN)
        return *c->bundle[bundle].cur_ptr++;
    if (bundle == BINK_SRC_X_OFF || bundle == BINK_SRC_Y_OFF)
        return (int8_t)*c->bundle[bundle].cur_ptr++;
    ret = *(int16_t*)c->bundle[bundle].cur_ptr;
    c->bundle[bundle].cur_ptr += 2;
    return ret;
}

528
static av_cold void binkb_init_bundle(BinkContext *c, int bundle_num)
529 530 531 532 533 534
{
    c->bundle[bundle_num].cur_dec =
    c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
    c->bundle[bundle_num].len = 13;
}

535
static av_cold void binkb_init_bundles(BinkContext *c)
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
{
    int i;
    for (i = 0; i < BINKB_NB_SRC; i++)
        binkb_init_bundle(c, i);
}

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

    CHECK_READ_VAL(gb, b, len);
551
    if (b->data_end - b->cur_dec < len * (1 + (bits > 8)))
552
        return AVERROR_INVALIDDATA;
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    if (bits <= 8) {
        if (!issigned) {
            for (i = 0; i < len; i++)
                *b->cur_dec++ = get_bits(gb, bits);
        } else {
            for (i = 0; i < len; i++)
                *b->cur_dec++ = get_bits(gb, bits) - mask;
        }
    } else {
        int16_t *dst = (int16_t*)b->cur_dec;

        if (!issigned) {
            for (i = 0; i < len; i++)
                *dst++ = get_bits(gb, bits);
        } else {
            for (i = 0; i < len; i++)
                *dst++ = get_bits(gb, bits) - mask;
        }
        b->cur_dec = (uint8_t*)dst;
    }
    return 0;
}

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

    if (bits <= 8) {
        int val = *c->bundle[bundle_num].cur_ptr++;
        return binkb_bundle_signed[bundle_num] ? (int8_t)val : val;
    }
    ret = *(int16_t*)c->bundle[bundle_num].cur_ptr;
    c->bundle[bundle_num].cur_ptr += 2;
    return ret;
}

Kostya Shishkov's avatar
Kostya Shishkov committed
590
/**
591
 * Read 8x8 block of DCT coefficients.
Kostya Shishkov's avatar
Kostya Shishkov committed
592 593 594 595
 *
 * @param gb       context for reading bits
 * @param block    place for storing coefficients
 * @param scan     scan order table
596
 * @param quant_matrices quantization matrices
Kostya Shishkov's avatar
Kostya Shishkov committed
597 598
 * @return 0 for success, negative value in other cases
 */
599 600
static int read_dct_coeffs(GetBitContext *gb, int32_t block[64], const uint8_t *scan,
                           const int32_t quant_matrices[16][64], int q)
Kostya Shishkov's avatar
Kostya Shishkov committed
601 602 603
{
    int coef_list[128];
    int mode_list[128];
604
    int i, t, bits, ccoef, mode, sign;
Kostya Shishkov's avatar
Kostya Shishkov committed
605 606 607 608
    int list_start = 64, list_end = 64, list_pos;
    int coef_count = 0;
    int coef_idx[64];
    int quant_idx;
609
    const int32_t *quant;
Kostya Shishkov's avatar
Kostya Shishkov committed
610 611 612 613 614 615 616 617

    coef_list[list_end] = 4;  mode_list[list_end++] = 0;
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
    coef_list[list_end] = 1;  mode_list[list_end++] = 3;
    coef_list[list_end] = 2;  mode_list[list_end++] = 3;
    coef_list[list_end] = 3;  mode_list[list_end++] = 3;

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

678 679 680 681 682 683
    if (q == -1) {
        quant_idx = get_bits(gb, 4);
    } else {
        quant_idx = q;
    }

684 685 686
    if (quant_idx >= 16)
        return AVERROR_INVALIDDATA;

687
    quant = quant_matrices[quant_idx];
688

Kostya Shishkov's avatar
Kostya Shishkov committed
689 690 691 692 693 694 695 696 697 698
    block[0] = (block[0] * quant[0]) >> 11;
    for (i = 0; i < coef_count; i++) {
        int idx = coef_idx[i];
        block[scan[idx]] = (block[scan[idx]] * quant[idx]) >> 11;
    }

    return 0;
}

/**
699
 * Read 8x8 block with residue after motion compensation.
Kostya Shishkov's avatar
Kostya Shishkov committed
700 701 702 703 704 705
 *
 * @param gb          context for reading bits
 * @param block       place to store read data
 * @param masks_count number of masks to decode
 * @return 0 on success, negative value in other cases
 */
Diego Biurrun's avatar
Diego Biurrun committed
706
static int read_residue(GetBitContext *gb, int16_t block[64], int masks_count)
Kostya Shishkov's avatar
Kostya Shishkov committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
{
    int coef_list[128];
    int mode_list[128];
    int i, sign, mask, ccoef, mode;
    int list_start = 64, list_end = 64, list_pos;
    int nz_coeff[64];
    int nz_coeff_count = 0;

    coef_list[list_end] =  4; mode_list[list_end++] = 0;
    coef_list[list_end] = 24; mode_list[list_end++] = 0;
    coef_list[list_end] = 44; mode_list[list_end++] = 0;
    coef_list[list_end] =  0; mode_list[list_end++] = 2;

    for (mask = 1 << get_bits(gb, 3); mask; mask >>= 1) {
        for (i = 0; i < nz_coeff_count; i++) {
            if (!get_bits1(gb))
                continue;
            if (block[nz_coeff[i]] < 0)
                block[nz_coeff[i]] -= mask;
            else
                block[nz_coeff[i]] += mask;
            masks_count--;
            if (masks_count < 0)
                return 0;
        }
        list_pos = list_start;
        while (list_pos < list_end) {
            if (!(coef_list[list_pos] | mode_list[list_pos]) || !get_bits1(gb)) {
                list_pos++;
                continue;
            }
            ccoef = coef_list[list_pos];
            mode  = mode_list[list_pos];
            switch (mode) {
            case 0:
                coef_list[list_pos] = ccoef + 4;
                mode_list[list_pos] = 1;
            case 2:
                if (mode == 2) {
                    coef_list[list_pos]   = 0;
                    mode_list[list_pos++] = 0;
                }
                for (i = 0; i < 4; i++, ccoef++) {
                    if (get_bits1(gb)) {
                        coef_list[--list_start] = ccoef;
                        mode_list[  list_start] = 3;
                    } else {
                        nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
                        sign = -get_bits1(gb);
                        block[bink_scan[ccoef]] = (mask ^ sign) - sign;
                        masks_count--;
                        if (masks_count < 0)
                            return 0;
                    }
                }
                break;
            case 1:
                mode_list[list_pos] = 2;
                for (i = 0; i < 3; i++) {
                    ccoef += 4;
                    coef_list[list_end]   = ccoef;
                    mode_list[list_end++] = 2;
                }
                break;
            case 3:
                nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
                sign = -get_bits1(gb);
                block[bink_scan[ccoef]] = (mask ^ sign) - sign;
                coef_list[list_pos]   = 0;
                mode_list[list_pos++] = 0;
                masks_count--;
                if (masks_count < 0)
                    return 0;
                break;
            }
        }
    }

    return 0;
}

788 789 790 791 792 793 794 795 796 797 798 799 800
/**
 * Copy 8x8 block from source to destination, where src and dst may be overlapped
 */
static inline void put_pixels8x8_overlapped(uint8_t *dst, uint8_t *src, int stride)
{
    uint8_t tmp[64];
    int i;
    for (i = 0; i < 8; i++)
        memcpy(tmp + i*8, src + i*stride, 8);
    for (i = 0; i < 8; i++)
        memcpy(dst + i*stride, tmp + i*8, 8);
}

801 802
static int binkb_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb,
                              int plane_idx, int is_key, int is_chroma)
803
{
804
    int blk, ret;
805 806 807 808 809
    int i, j, bx, by;
    uint8_t *dst, *ref, *ref_start, *ref_end;
    int v, col[2];
    const uint8_t *scan;
    int xoff, yoff;
Diego Biurrun's avatar
Diego Biurrun committed
810
    LOCAL_ALIGNED_16(int16_t, block, [64]);
811
    LOCAL_ALIGNED_16(int32_t, dctblock, [64]);
812 813 814 815
    int coordmap[64];
    int ybias = is_key ? -15 : 0;
    int qp;

816
    const int stride = frame->linesize[plane_idx];
817 818 819 820
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;

    binkb_init_bundles(c);
821 822
    ref_start = frame->data[plane_idx];
    ref_end   = frame->data[plane_idx] + (bh * frame->linesize[plane_idx] + bw) * 8;
823 824 825 826 827 828

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

    for (by = 0; by < bh; by++) {
        for (i = 0; i < BINKB_NB_SRC; i++) {
829 830
            if ((ret = binkb_read_bundle(c, gb, i)) < 0)
                return ret;
831 832
        }

833
        dst  = frame->data[plane_idx]  + 8*by*stride;
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
        for (bx = 0; bx < bw; bx++, dst += 8) {
            blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES);
            switch (blk) {
            case 0:
                break;
            case 1:
                scan = bink_patterns[get_bits(gb, 4)];
                i = 0;
                do {
                    int mode, run;

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

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

    return 0;
}

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
static int bink_put_pixels(BinkContext *c,
                           uint8_t *dst, uint8_t *prev, int stride,
                           uint8_t *ref_start,
                           uint8_t *ref_end)
{
    int xoff     = get_value(c, BINK_SRC_X_OFF);
    int yoff     = get_value(c, BINK_SRC_Y_OFF);
    uint8_t *ref = prev + xoff + yoff * stride;
    if (ref < ref_start || ref > ref_end) {
        av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
               xoff, yoff);
        return AVERROR_INVALIDDATA;
    }
    c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);

    return 0;
}

965 966
static int bink_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb,
                             int plane_idx, int is_chroma)
Kostya Shishkov's avatar
Kostya Shishkov committed
967
{
968
    int blk, ret;
969
    int i, j, bx, by;
970
    uint8_t *dst, *prev, *ref_start, *ref_end;
Kostya Shishkov's avatar
Kostya Shishkov committed
971 972
    int v, col[2];
    const uint8_t *scan;
Diego Biurrun's avatar
Diego Biurrun committed
973
    LOCAL_ALIGNED_16(int16_t, block, [64]);
974
    LOCAL_ALIGNED_16(uint8_t, ublock, [64]);
975
    LOCAL_ALIGNED_16(int32_t, dctblock, [64]);
Kostya Shishkov's avatar
Kostya Shishkov committed
976 977
    int coordmap[64];

978
    const int stride = frame->linesize[plane_idx];
979 980 981
    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
    int width = c->avctx->width >> is_chroma;
Kostya Shishkov's avatar
Kostya Shishkov committed
982

983 984 985 986
    init_lengths(c, FFMAX(width, 8), bw);
    for (i = 0; i < BINK_NB_SRC; i++)
        read_bundle(gb, c, i);

987
    ref_start = c->last->data[plane_idx] ? c->last->data[plane_idx]
988
                                         : frame->data[plane_idx];
989
    ref_end   = ref_start
990
                + (bw - 1 + c->last->linesize[plane_idx] * (bh - 1)) * 8;
991 992 993 994 995

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

    for (by = 0; by < bh; by++) {
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
        if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES])) < 0)
            return ret;
        if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES])) < 0)
            return ret;
        if ((ret = read_colors(gb, &c->bundle[BINK_SRC_COLORS], c)) < 0)
            return ret;
        if ((ret = read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN])) < 0)
            return ret;
        if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF])) < 0)
            return ret;
        if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF])) < 0)
            return ret;
        if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0)) < 0)
            return ret;
        if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1)) < 0)
            return ret;
        if ((ret = read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN])) < 0)
            return ret;
1014 1015 1016

        if (by == bh)
            break;
1017
        dst  = frame->data[plane_idx]  + 8*by*stride;
1018
        prev = (c->last->data[plane_idx] ? c->last->data[plane_idx]
1019
                                         : frame->data[plane_idx]) + 8*by*stride;
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
        for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {
            blk = get_value(c, BINK_SRC_BLOCK_TYPES);
            // 16x16 block type on odd line means part of the already decoded block, so skip it
            if ((by & 1) && blk == SCALED_BLOCK) {
                bx++;
                dst  += 8;
                prev += 8;
                continue;
            }
            switch (blk) {
            case SKIP_BLOCK:
1031
                c->hdsp.put_pixels_tab[1][0](dst, prev, stride, 8);
Kostya Shishkov's avatar
Kostya Shishkov committed
1032
                break;
1033 1034
            case SCALED_BLOCK:
                blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);
Kostya Shishkov's avatar
Kostya Shishkov committed
1035 1036
                switch (blk) {
                case RUN_BLOCK:
1037
                    scan = bink_patterns[get_bits(gb, 4)];
Kostya Shishkov's avatar
Kostya Shishkov committed
1038 1039 1040 1041 1042 1043
                    i = 0;
                    do {
                        int run = get_value(c, BINK_SRC_RUN) + 1;

                        i += run;
                        if (i > 64) {
1044
                            av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1045
                            return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
1046
                        }
1047
                        if (get_bits1(gb)) {
Kostya Shishkov's avatar
Kostya Shishkov committed
1048 1049
                            v = get_value(c, BINK_SRC_COLORS);
                            for (j = 0; j < run; j++)
1050
                                ublock[*scan++] = v;
Kostya Shishkov's avatar
Kostya Shishkov committed
1051 1052
                        } else {
                            for (j = 0; j < run; j++)
1053
                                ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
Kostya Shishkov's avatar
Kostya Shishkov committed
1054 1055 1056
                        }
                    } while (i < 63);
                    if (i == 63)
1057
                        ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
Kostya Shishkov's avatar
Kostya Shishkov committed
1058 1059
                    break;
                case INTRA_BLOCK:
1060 1061 1062
                    memset(dctblock, 0, sizeof(*dctblock) * 64);
                    dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);
                    read_dct_coeffs(gb, dctblock, bink_scan, bink_intra_quant, -1);
1063
                    c->binkdsp.idct_put(ublock, 8, dctblock);
Kostya Shishkov's avatar
Kostya Shishkov committed
1064 1065 1066
                    break;
                case FILL_BLOCK:
                    v = get_value(c, BINK_SRC_COLORS);
1067
                    c->bdsp.fill_block_tab[0](dst, v, stride, 16);
Kostya Shishkov's avatar
Kostya Shishkov committed
1068 1069 1070 1071
                    break;
                case PATTERN_BLOCK:
                    for (i = 0; i < 2; i++)
                        col[i] = get_value(c, BINK_SRC_COLORS);
1072
                    for (j = 0; j < 8; j++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
1073
                        v = get_value(c, BINK_SRC_PATTERN);
1074 1075
                        for (i = 0; i < 8; i++, v >>= 1)
                            ublock[i + j*8] = col[v & 1];
Kostya Shishkov's avatar
Kostya Shishkov committed
1076 1077 1078
                    }
                    break;
                case RAW_BLOCK:
1079 1080 1081
                    for (j = 0; j < 8; j++)
                        for (i = 0; i < 8; i++)
                            ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);
Kostya Shishkov's avatar
Kostya Shishkov committed
1082 1083
                    break;
                default:
1084
                    av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);
1085
                    return AVERROR_INVALIDDATA;
1086 1087
                }
                if (blk != FILL_BLOCK)
1088
                c->binkdsp.scale_block(ublock, dst, stride);
1089 1090 1091 1092 1093
                bx++;
                dst  += 8;
                prev += 8;
                break;
            case MOTION_BLOCK:
1094 1095 1096 1097
                ret = bink_put_pixels(c, dst, prev, stride,
                                      ref_start, ref_end);
                if (ret < 0)
                    return ret;
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
                break;
            case RUN_BLOCK:
                scan = bink_patterns[get_bits(gb, 4)];
                i = 0;
                do {
                    int run = get_value(c, BINK_SRC_RUN) + 1;

                    i += run;
                    if (i > 64) {
                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1108
                        return AVERROR_INVALIDDATA;
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
                    }
                    if (get_bits1(gb)) {
                        v = get_value(c, BINK_SRC_COLORS);
                        for (j = 0; j < run; j++)
                            dst[coordmap[*scan++]] = v;
                    } else {
                        for (j = 0; j < run; j++)
                            dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
                    }
                } while (i < 63);
                if (i == 63)
                    dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
                break;
            case RESIDUE_BLOCK:
1123 1124 1125 1126
                ret = bink_put_pixels(c, dst, prev, stride,
                                      ref_start, ref_end);
                if (ret < 0)
                    return ret;
1127
                c->bdsp.clear_block(block);
1128 1129
                v = get_bits(gb, 7);
                read_residue(gb, block, v);
1130
                c->binkdsp.add_pixels8(dst, block, stride);
1131 1132
                break;
            case INTRA_BLOCK:
1133 1134 1135
                memset(dctblock, 0, sizeof(*dctblock) * 64);
                dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);
                read_dct_coeffs(gb, dctblock, bink_scan, bink_intra_quant, -1);
1136
                c->binkdsp.idct_put(dst, stride, dctblock);
1137 1138 1139
                break;
            case FILL_BLOCK:
                v = get_value(c, BINK_SRC_COLORS);
1140
                c->bdsp.fill_block_tab[1](dst, v, stride, 8);
1141 1142
                break;
            case INTER_BLOCK:
1143 1144 1145 1146
                ret = bink_put_pixels(c, dst, prev, stride,
                                      ref_start, ref_end);
                if (ret < 0)
                    return ret;
1147 1148 1149
                memset(dctblock, 0, sizeof(*dctblock) * 64);
                dctblock[0] = get_value(c, BINK_SRC_INTER_DC);
                read_dct_coeffs(gb, dctblock, bink_scan, bink_inter_quant, -1);
1150
                c->binkdsp.idct_add(dst, stride, dctblock);
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
                break;
            case PATTERN_BLOCK:
                for (i = 0; i < 2; i++)
                    col[i] = get_value(c, BINK_SRC_COLORS);
                for (i = 0; i < 8; i++) {
                    v = get_value(c, BINK_SRC_PATTERN);
                    for (j = 0; j < 8; j++, v >>= 1)
                        dst[i*stride + j] = col[v & 1];
                }
                break;
            case RAW_BLOCK:
                for (i = 0; i < 8; i++)
                    memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);
                c->bundle[BINK_SRC_COLORS].cur_ptr += 64;
                break;
            default:
                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
1168
                return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
1169 1170
            }
        }
1171 1172 1173
    }
    if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
        skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
1174 1175 1176 1177

    return 0;
}

1178
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)
1179 1180
{
    BinkContext * const c = avctx->priv_data;
1181
    AVFrame *frame = data;
1182
    GetBitContext gb;
1183
    int plane, plane_idx, ret;
1184 1185
    int bits_count = pkt->size << 3;

1186
    if (c->version > 'b') {
1187
        if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0) {
1188
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1189
            return ret;
1190
        }
1191
    } else {
1192
        if ((ret = ff_reget_buffer(avctx, c->last)) < 0) {
1193
            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1194
            return ret;
1195
        }
1196 1197
        if ((ret = av_frame_ref(frame, c->last)) < 0)
            return ret;
1198
    }
1199 1200 1201

    init_get_bits(&gb, pkt->data, bits_count);
    if (c->has_alpha) {
1202 1203
        if (c->version >= 'i')
            skip_bits_long(&gb, 32);
1204
        if ((ret = bink_decode_plane(c, frame, &gb, 3, 0)) < 0)
1205
            return ret;
1206 1207 1208 1209 1210 1211 1212
    }
    if (c->version >= 'i')
        skip_bits_long(&gb, 32);

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

1213
        if (c->version > 'b') {
1214
            if ((ret = bink_decode_plane(c, frame, &gb, plane_idx, !!plane)) < 0)
1215
                return ret;
1216
        } else {
1217
            if ((ret = binkb_decode_plane(c, frame, &gb, plane_idx,
1218
                                          !avctx->frame_number, !!plane)) < 0)
1219
                return ret;
1220
        }
1221 1222
        if (get_bits_count(&gb) >= bits_count)
            break;
Kostya Shishkov's avatar
Kostya Shishkov committed
1223 1224 1225
    }
    emms_c();

1226 1227 1228 1229 1230
    if (c->version > 'b') {
        av_frame_unref(c->last);
        if ((ret = av_frame_ref(c->last, frame)) < 0)
            return ret;
    }
Kostya Shishkov's avatar
Kostya Shishkov committed
1231

1232
    *got_frame = 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
1233 1234 1235 1236 1237

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

1238
/**
1239
 * Calculate quantization tables for version b
1240
 */
1241
static av_cold void binkb_calc_quant(void)
1242
{
1243
    uint8_t inv_bink_scan[64];
1244
    double s[64];
1245 1246 1247 1248 1249 1250
    int i, j;

    for (j = 0; j < 8; j++) {
        for (i = 0; i < 8; i++) {
            if (j && j != 4)
               if (i && i != 4)
1251
                   s[j*8 + i] = cos(j * M_PI/16.0) * cos(i * M_PI/16.0) * 2.0;
1252
               else
1253
                   s[j*8 + i] = cos(j * M_PI/16.0) * sqrt(2.0);
1254 1255
            else
               if (i && i != 4)
1256
                   s[j*8 + i] = cos(i * M_PI/16.0) * sqrt(2.0);
1257
               else
1258
                   s[j*8 + i] = 1.0;
1259 1260 1261
        }
    }

1262 1263 1264
    for (i = 0; i < 64; i++)
        inv_bink_scan[bink_scan[i]] = i;

1265 1266
    for (j = 0; j < 16; j++) {
        for (i = 0; i < 64; i++) {
1267
            int k = inv_bink_scan[i];
1268
            if (s[i] == 1.0) {
1269
                binkb_intra_quant[j][k] = (1L << 12) * binkb_intra_seed[i] *
1270
                                          binkb_num[j]/binkb_den[j];
1271
                binkb_inter_quant[j][k] = (1L << 12) * binkb_inter_seed[i] *
1272 1273
                                          binkb_num[j]/binkb_den[j];
            } else {
1274
                binkb_intra_quant[j][k] = (1L << 12) * binkb_intra_seed[i] * s[i] *
1275
                                          binkb_num[j]/(double)binkb_den[j];
1276
                binkb_inter_quant[j][k] = (1L << 12) * binkb_inter_seed[i] * s[i] *
1277 1278
                                          binkb_num[j]/(double)binkb_den[j];
            }
1279 1280 1281 1282
        }
    }
}

Kostya Shishkov's avatar
Kostya Shishkov committed
1283 1284 1285 1286
static av_cold int decode_init(AVCodecContext *avctx)
{
    BinkContext * const c = avctx->priv_data;
    static VLC_TYPE table[16 * 128][2];
1287
    static int binkb_initialised = 0;
1288
    int i, ret;
1289
    int flags;
Kostya Shishkov's avatar
Kostya Shishkov committed
1290 1291

    c->version = avctx->codec_tag >> 24;
1292 1293
    if (avctx->extradata_size < 4) {
        av_log(avctx, AV_LOG_ERROR, "Extradata missing or too short\n");
1294
        return AVERROR_INVALIDDATA;
1295 1296 1297
    }
    flags = AV_RL32(avctx->extradata);
    c->has_alpha = flags & BINK_FLAG_ALPHA;
1298
    c->swap_planes = c->version >= 'h';
Kostya Shishkov's avatar
Kostya Shishkov committed
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    if (!bink_trees[15].table) {
        for (i = 0; i < 16; i++) {
            const int maxbits = bink_tree_lens[i][15];
            bink_trees[i].table = table + i*128;
            bink_trees[i].table_allocated = 1 << maxbits;
            init_vlc(&bink_trees[i], maxbits, 16,
                     bink_tree_lens[i], 1, 1,
                     bink_tree_bits[i], 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
        }
    }
    c->avctx = avctx;

1311 1312
    c->last = av_frame_alloc();
    if (!c->last)
1313
        return AVERROR(ENOMEM);
Kostya Shishkov's avatar
Kostya Shishkov committed
1314

1315 1316 1317
    if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
        return ret;

1318
    avctx->pix_fmt = c->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;
Kostya Shishkov's avatar
Kostya Shishkov committed
1319

1320
    ff_blockdsp_init(&c->bdsp, avctx);
1321
    ff_hpeldsp_init(&c->hdsp, avctx->flags);
1322
    ff_binkdsp_init(&c->binkdsp);
Kostya Shishkov's avatar
Kostya Shishkov committed
1323 1324 1325

    init_bundles(c);

1326 1327 1328 1329 1330 1331 1332
    if (c->version == 'b') {
        if (!binkb_initialised) {
            binkb_calc_quant();
            binkb_initialised = 1;
        }
    }

Kostya Shishkov's avatar
Kostya Shishkov committed
1333 1334 1335 1336 1337 1338 1339
    return 0;
}

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

1340
    av_frame_free(&c->last);
Kostya Shishkov's avatar
Kostya Shishkov committed
1341 1342 1343 1344 1345

    free_bundles(c);
    return 0;
}

1346
AVCodec ff_bink_decoder = {
1347
    .name           = "binkvideo",
1348
    .long_name      = NULL_IF_CONFIG_SMALL("Bink video"),
1349
    .type           = AVMEDIA_TYPE_VIDEO,
1350
    .id             = AV_CODEC_ID_BINKVIDEO,
1351 1352 1353 1354
    .priv_data_size = sizeof(BinkContext),
    .init           = decode_init,
    .close          = decode_end,
    .decode         = decode_frame,
1355
    .capabilities   = AV_CODEC_CAP_DR1,
Kostya Shishkov's avatar
Kostya Shishkov committed
1356
};