]> git.sesse.net Git - ffmpeg/blob - libavcodec/bink.c
jpeg2000: Zero prec->cblk
[ffmpeg] / libavcodec / bink.c
1 /*
2  * Bink video decoder
3  * Copyright (c) 2009 Konstantin Shishkov
4  * Copyright (C) 2011 Peter Ross <pross@xvid.org>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "libavutil/attributes.h"
24 #include "libavutil/imgutils.h"
25 #include "libavutil/internal.h"
26 #include "avcodec.h"
27 #include "dsputil.h"
28 #include "binkdata.h"
29 #include "binkdsp.h"
30 #include "hpeldsp.h"
31 #include "internal.h"
32 #include "mathops.h"
33
34 #define BITSTREAM_READER_LE
35 #include "get_bits.h"
36
37 #define BINK_FLAG_ALPHA 0x00100000
38 #define BINK_FLAG_GRAY  0x00020000
39
40 static VLC bink_trees[16];
41
42 /**
43  * IDs for different data types used in old version of Bink video codec
44  */
45 enum OldSources {
46     BINKB_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
47     BINKB_SRC_COLORS,          ///< pixel values used for different block types
48     BINKB_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
49     BINKB_SRC_X_OFF,           ///< X components of motion value
50     BINKB_SRC_Y_OFF,           ///< Y components of motion value
51     BINKB_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
52     BINKB_SRC_INTER_DC,        ///< DC values for interblocks with DCT
53     BINKB_SRC_INTRA_Q,         ///< quantizer values for intrablocks with DCT
54     BINKB_SRC_INTER_Q,         ///< quantizer values for interblocks with DCT
55     BINKB_SRC_INTER_COEFS,     ///< number of coefficients for residue blocks
56
57     BINKB_NB_SRC
58 };
59
60 static const int binkb_bundle_sizes[BINKB_NB_SRC] = {
61     4, 8, 8, 5, 5, 11, 11, 4, 4, 7
62 };
63
64 static const int binkb_bundle_signed[BINKB_NB_SRC] = {
65     0, 0, 0, 1, 1, 0, 1, 0, 0, 0
66 };
67
68 static int32_t binkb_intra_quant[16][64];
69 static int32_t binkb_inter_quant[16][64];
70
71 /**
72  * IDs for different data types used in Bink video codec
73  */
74 enum Sources {
75     BINK_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
76     BINK_SRC_SUB_BLOCK_TYPES, ///< 16x16 block types (a subset of 8x8 block types)
77     BINK_SRC_COLORS,          ///< pixel values used for different block types
78     BINK_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
79     BINK_SRC_X_OFF,           ///< X components of motion value
80     BINK_SRC_Y_OFF,           ///< Y components of motion value
81     BINK_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
82     BINK_SRC_INTER_DC,        ///< DC values for interblocks with DCT
83     BINK_SRC_RUN,             ///< run lengths for special fill block
84
85     BINK_NB_SRC
86 };
87
88 /**
89  * data needed to decode 4-bit Huffman-coded value
90  */
91 typedef struct Tree {
92     int     vlc_num;  ///< tree number (in bink_trees[])
93     uint8_t syms[16]; ///< leaf value to symbol mapping
94 } Tree;
95
96 #define GET_HUFF(gb, tree)  (tree).syms[get_vlc2(gb, bink_trees[(tree).vlc_num].table,\
97                                                  bink_trees[(tree).vlc_num].bits, 1)]
98
99 /**
100  * data structure used for decoding single Bink data type
101  */
102 typedef struct Bundle {
103     int     len;       ///< length of number of entries to decode (in bits)
104     Tree    tree;      ///< Huffman tree-related data
105     uint8_t *data;     ///< buffer for decoded symbols
106     uint8_t *data_end; ///< buffer end
107     uint8_t *cur_dec;  ///< pointer to the not yet decoded part of the buffer
108     uint8_t *cur_ptr;  ///< pointer to the data that is not read from buffer yet
109 } Bundle;
110
111 /*
112  * Decoder context
113  */
114 typedef struct BinkContext {
115     AVCodecContext *avctx;
116     DSPContext     dsp;
117     HpelDSPContext hdsp;
118     BinkDSPContext bdsp;
119     AVFrame        *last;
120     int            version;              ///< internal Bink file version
121     int            has_alpha;
122     int            swap_planes;
123
124     Bundle         bundle[BINKB_NB_SRC]; ///< bundles for decoding all data types
125     Tree           col_high[16];         ///< trees for decoding high nibble in "colours" data type
126     int            col_lastval;          ///< value of last decoded high nibble in "colours" data type
127 } BinkContext;
128
129 /**
130  * Bink video block types
131  */
132 enum BlockTypes {
133     SKIP_BLOCK = 0, ///< skipped block
134     SCALED_BLOCK,   ///< block has size 16x16
135     MOTION_BLOCK,   ///< block is copied from previous frame with some offset
136     RUN_BLOCK,      ///< block is composed from runs of colours with custom scan order
137     RESIDUE_BLOCK,  ///< motion block with some difference added
138     INTRA_BLOCK,    ///< intra DCT block
139     FILL_BLOCK,     ///< block is filled with single colour
140     INTER_BLOCK,    ///< motion block with DCT applied to the difference
141     PATTERN_BLOCK,  ///< block is filled with two colours following custom pattern
142     RAW_BLOCK,      ///< uncoded 8x8 block
143 };
144
145 /**
146  * Initialize length length in all bundles.
147  *
148  * @param c     decoder context
149  * @param width plane width
150  * @param bw    plane width in 8x8 blocks
151  */
152 static void init_lengths(BinkContext *c, int width, int bw)
153 {
154     width = FFALIGN(width, 8);
155
156     c->bundle[BINK_SRC_BLOCK_TYPES].len = av_log2((width >> 3) + 511) + 1;
157
158     c->bundle[BINK_SRC_SUB_BLOCK_TYPES].len = av_log2((width >> 4) + 511) + 1;
159
160     c->bundle[BINK_SRC_COLORS].len = av_log2(bw*64 + 511) + 1;
161
162     c->bundle[BINK_SRC_INTRA_DC].len =
163     c->bundle[BINK_SRC_INTER_DC].len =
164     c->bundle[BINK_SRC_X_OFF].len =
165     c->bundle[BINK_SRC_Y_OFF].len = av_log2((width >> 3) + 511) + 1;
166
167     c->bundle[BINK_SRC_PATTERN].len = av_log2((bw << 3) + 511) + 1;
168
169     c->bundle[BINK_SRC_RUN].len = av_log2(bw*48 + 511) + 1;
170 }
171
172 /**
173  * Allocate memory for bundles.
174  *
175  * @param c decoder context
176  */
177 static av_cold int init_bundles(BinkContext *c)
178 {
179     int bw, bh, blocks;
180     int i;
181
182     bw = (c->avctx->width  + 7) >> 3;
183     bh = (c->avctx->height + 7) >> 3;
184     blocks = bw * bh;
185
186     for (i = 0; i < BINKB_NB_SRC; i++) {
187         c->bundle[i].data = av_malloc(blocks * 64);
188         if (!c->bundle[i].data)
189             return AVERROR(ENOMEM);
190         c->bundle[i].data_end = c->bundle[i].data + blocks * 64;
191     }
192
193     return 0;
194 }
195
196 /**
197  * Free memory used by bundles.
198  *
199  * @param c decoder context
200  */
201 static av_cold void free_bundles(BinkContext *c)
202 {
203     int i;
204     for (i = 0; i < BINKB_NB_SRC; i++)
205         av_freep(&c->bundle[i].data);
206 }
207
208 /**
209  * Merge two consequent lists of equal size depending on bits read.
210  *
211  * @param gb   context for reading bits
212  * @param dst  buffer where merged list will be written to
213  * @param src  pointer to the head of the first list (the second lists starts at src+size)
214  * @param size input lists size
215  */
216 static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
217 {
218     uint8_t *src2 = src + size;
219     int size2 = size;
220
221     do {
222         if (!get_bits1(gb)) {
223             *dst++ = *src++;
224             size--;
225         } else {
226             *dst++ = *src2++;
227             size2--;
228         }
229     } while (size && size2);
230
231     while (size--)
232         *dst++ = *src++;
233     while (size2--)
234         *dst++ = *src2++;
235 }
236
237 /**
238  * Read information about Huffman tree used to decode data.
239  *
240  * @param gb   context for reading bits
241  * @param tree pointer for storing tree data
242  */
243 static void read_tree(GetBitContext *gb, Tree *tree)
244 {
245     uint8_t tmp1[16] = { 0 }, tmp2[16], *in = tmp1, *out = tmp2;
246     int i, t, len;
247
248     tree->vlc_num = get_bits(gb, 4);
249     if (!tree->vlc_num) {
250         for (i = 0; i < 16; i++)
251             tree->syms[i] = i;
252         return;
253     }
254     if (get_bits1(gb)) {
255         len = get_bits(gb, 3);
256         for (i = 0; i <= len; i++) {
257             tree->syms[i] = get_bits(gb, 4);
258             tmp1[tree->syms[i]] = 1;
259         }
260         for (i = 0; i < 16 && len < 16 - 1; i++)
261             if (!tmp1[i])
262                 tree->syms[++len] = i;
263     } else {
264         len = get_bits(gb, 2);
265         for (i = 0; i < 16; i++)
266             in[i] = i;
267         for (i = 0; i <= len; i++) {
268             int size = 1 << i;
269             for (t = 0; t < 16; t += size << 1)
270                 merge(gb, out + t, in + t, size);
271             FFSWAP(uint8_t*, in, out);
272         }
273         memcpy(tree->syms, in, 16);
274     }
275 }
276
277 /**
278  * Prepare bundle for decoding data.
279  *
280  * @param gb          context for reading bits
281  * @param c           decoder context
282  * @param bundle_num  number of the bundle to initialize
283  */
284 static void read_bundle(GetBitContext *gb, BinkContext *c, int bundle_num)
285 {
286     int i;
287
288     if (bundle_num == BINK_SRC_COLORS) {
289         for (i = 0; i < 16; i++)
290             read_tree(gb, &c->col_high[i]);
291         c->col_lastval = 0;
292     }
293     if (bundle_num != BINK_SRC_INTRA_DC && bundle_num != BINK_SRC_INTER_DC)
294         read_tree(gb, &c->bundle[bundle_num].tree);
295     c->bundle[bundle_num].cur_dec =
296     c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
297 }
298
299 /**
300  * common check before starting decoding bundle data
301  *
302  * @param gb context for reading bits
303  * @param b  bundle
304  * @param t  variable where number of elements to decode will be stored
305  */
306 #define CHECK_READ_VAL(gb, b, t) \
307     if (!b->cur_dec || (b->cur_dec > b->cur_ptr)) \
308         return 0; \
309     t = get_bits(gb, b->len); \
310     if (!t) { \
311         b->cur_dec = NULL; \
312         return 0; \
313     } \
314
315 static int read_runs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
316 {
317     int t, v;
318     const uint8_t *dec_end;
319
320     CHECK_READ_VAL(gb, b, t);
321     dec_end = b->cur_dec + t;
322     if (dec_end > b->data_end) {
323         av_log(avctx, AV_LOG_ERROR, "Run value went out of bounds\n");
324         return AVERROR_INVALIDDATA;
325     }
326     if (get_bits1(gb)) {
327         v = get_bits(gb, 4);
328         memset(b->cur_dec, v, t);
329         b->cur_dec += t;
330     } else {
331         while (b->cur_dec < dec_end)
332             *b->cur_dec++ = GET_HUFF(gb, b->tree);
333     }
334     return 0;
335 }
336
337 static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
338 {
339     int t, sign, v;
340     const uint8_t *dec_end;
341
342     CHECK_READ_VAL(gb, b, t);
343     dec_end = b->cur_dec + t;
344     if (dec_end > b->data_end) {
345         av_log(avctx, AV_LOG_ERROR, "Too many motion values\n");
346         return AVERROR_INVALIDDATA;
347     }
348     if (get_bits1(gb)) {
349         v = get_bits(gb, 4);
350         if (v) {
351             sign = -get_bits1(gb);
352             v = (v ^ sign) - sign;
353         }
354         memset(b->cur_dec, v, t);
355         b->cur_dec += t;
356     } else {
357         while (b->cur_dec < dec_end) {
358             v = GET_HUFF(gb, b->tree);
359             if (v) {
360                 sign = -get_bits1(gb);
361                 v = (v ^ sign) - sign;
362             }
363             *b->cur_dec++ = v;
364         }
365     }
366     return 0;
367 }
368
369 static const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
370
371 static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
372 {
373     int t, v;
374     int last = 0;
375     const uint8_t *dec_end;
376
377     CHECK_READ_VAL(gb, b, t);
378     dec_end = b->cur_dec + t;
379     if (dec_end > b->data_end) {
380         av_log(avctx, AV_LOG_ERROR, "Too many block type values\n");
381         return AVERROR_INVALIDDATA;
382     }
383     if (get_bits1(gb)) {
384         v = get_bits(gb, 4);
385         memset(b->cur_dec, v, t);
386         b->cur_dec += t;
387     } else {
388         while (b->cur_dec < dec_end) {
389             v = GET_HUFF(gb, b->tree);
390             if (v < 12) {
391                 last = v;
392                 *b->cur_dec++ = v;
393             } else {
394                 int run = bink_rlelens[v - 12];
395
396                 if (dec_end - b->cur_dec < run)
397                     return AVERROR_INVALIDDATA;
398                 memset(b->cur_dec, last, run);
399                 b->cur_dec += run;
400             }
401         }
402     }
403     return 0;
404 }
405
406 static int read_patterns(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
407 {
408     int t, v;
409     const uint8_t *dec_end;
410
411     CHECK_READ_VAL(gb, b, t);
412     dec_end = b->cur_dec + t;
413     if (dec_end > b->data_end) {
414         av_log(avctx, AV_LOG_ERROR, "Too many pattern values\n");
415         return AVERROR_INVALIDDATA;
416     }
417     while (b->cur_dec < dec_end) {
418         v  = GET_HUFF(gb, b->tree);
419         v |= GET_HUFF(gb, b->tree) << 4;
420         *b->cur_dec++ = v;
421     }
422
423     return 0;
424 }
425
426 static int read_colors(GetBitContext *gb, Bundle *b, BinkContext *c)
427 {
428     int t, sign, v;
429     const uint8_t *dec_end;
430
431     CHECK_READ_VAL(gb, b, t);
432     dec_end = b->cur_dec + t;
433     if (dec_end > b->data_end) {
434         av_log(c->avctx, AV_LOG_ERROR, "Too many color values\n");
435         return AVERROR_INVALIDDATA;
436     }
437     if (get_bits1(gb)) {
438         c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
439         v = GET_HUFF(gb, b->tree);
440         v = (c->col_lastval << 4) | v;
441         if (c->version < 'i') {
442             sign = ((int8_t) v) >> 7;
443             v = ((v & 0x7F) ^ sign) - sign;
444             v += 0x80;
445         }
446         memset(b->cur_dec, v, t);
447         b->cur_dec += t;
448     } else {
449         while (b->cur_dec < dec_end) {
450             c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
451             v = GET_HUFF(gb, b->tree);
452             v = (c->col_lastval << 4) | v;
453             if (c->version < 'i') {
454                 sign = ((int8_t) v) >> 7;
455                 v = ((v & 0x7F) ^ sign) - sign;
456                 v += 0x80;
457             }
458             *b->cur_dec++ = v;
459         }
460     }
461     return 0;
462 }
463
464 /** number of bits used to store first DC value in bundle */
465 #define DC_START_BITS 11
466
467 static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,
468                     int start_bits, int has_sign)
469 {
470     int i, j, len, len2, bsize, sign, v, v2;
471     int16_t *dst     = (int16_t*)b->cur_dec;
472     int16_t *dst_end = (int16_t*)b->data_end;
473
474     CHECK_READ_VAL(gb, b, len);
475     v = get_bits(gb, start_bits - has_sign);
476     if (v && has_sign) {
477         sign = -get_bits1(gb);
478         v = (v ^ sign) - sign;
479     }
480     if (dst_end - dst < 1)
481         return AVERROR_INVALIDDATA;
482     *dst++ = v;
483     len--;
484     for (i = 0; i < len; i += 8) {
485         len2 = FFMIN(len - i, 8);
486         if (dst_end - dst < len2)
487             return AVERROR_INVALIDDATA;
488         bsize = get_bits(gb, 4);
489         if (bsize) {
490             for (j = 0; j < len2; j++) {
491                 v2 = get_bits(gb, bsize);
492                 if (v2) {
493                     sign = -get_bits1(gb);
494                     v2 = (v2 ^ sign) - sign;
495                 }
496                 v += v2;
497                 *dst++ = v;
498                 if (v < -32768 || v > 32767) {
499                     av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v);
500                     return AVERROR_INVALIDDATA;
501                 }
502             }
503         } else {
504             for (j = 0; j < len2; j++)
505                 *dst++ = v;
506         }
507     }
508
509     b->cur_dec = (uint8_t*)dst;
510     return 0;
511 }
512
513 /**
514  * Retrieve next value from bundle.
515  *
516  * @param c      decoder context
517  * @param bundle bundle number
518  */
519 static inline int get_value(BinkContext *c, int bundle)
520 {
521     int ret;
522
523     if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN)
524         return *c->bundle[bundle].cur_ptr++;
525     if (bundle == BINK_SRC_X_OFF || bundle == BINK_SRC_Y_OFF)
526         return (int8_t)*c->bundle[bundle].cur_ptr++;
527     ret = *(int16_t*)c->bundle[bundle].cur_ptr;
528     c->bundle[bundle].cur_ptr += 2;
529     return ret;
530 }
531
532 static av_cold void binkb_init_bundle(BinkContext *c, int bundle_num)
533 {
534     c->bundle[bundle_num].cur_dec =
535     c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
536     c->bundle[bundle_num].len = 13;
537 }
538
539 static av_cold void binkb_init_bundles(BinkContext *c)
540 {
541     int i;
542     for (i = 0; i < BINKB_NB_SRC; i++)
543         binkb_init_bundle(c, i);
544 }
545
546 static int binkb_read_bundle(BinkContext *c, GetBitContext *gb, int bundle_num)
547 {
548     const int bits = binkb_bundle_sizes[bundle_num];
549     const int mask = 1 << (bits - 1);
550     const int issigned = binkb_bundle_signed[bundle_num];
551     Bundle *b = &c->bundle[bundle_num];
552     int i, len;
553
554     CHECK_READ_VAL(gb, b, len);
555     if (b->data_end - b->cur_dec < len * (1 + (bits > 8)))
556         return AVERROR_INVALIDDATA;
557     if (bits <= 8) {
558         if (!issigned) {
559             for (i = 0; i < len; i++)
560                 *b->cur_dec++ = get_bits(gb, bits);
561         } else {
562             for (i = 0; i < len; i++)
563                 *b->cur_dec++ = get_bits(gb, bits) - mask;
564         }
565     } else {
566         int16_t *dst = (int16_t*)b->cur_dec;
567
568         if (!issigned) {
569             for (i = 0; i < len; i++)
570                 *dst++ = get_bits(gb, bits);
571         } else {
572             for (i = 0; i < len; i++)
573                 *dst++ = get_bits(gb, bits) - mask;
574         }
575         b->cur_dec = (uint8_t*)dst;
576     }
577     return 0;
578 }
579
580 static inline int binkb_get_value(BinkContext *c, int bundle_num)
581 {
582     int16_t ret;
583     const int bits = binkb_bundle_sizes[bundle_num];
584
585     if (bits <= 8) {
586         int val = *c->bundle[bundle_num].cur_ptr++;
587         return binkb_bundle_signed[bundle_num] ? (int8_t)val : val;
588     }
589     ret = *(int16_t*)c->bundle[bundle_num].cur_ptr;
590     c->bundle[bundle_num].cur_ptr += 2;
591     return ret;
592 }
593
594 /**
595  * Read 8x8 block of DCT coefficients.
596  *
597  * @param gb       context for reading bits
598  * @param block    place for storing coefficients
599  * @param scan     scan order table
600  * @param quant_matrices quantization matrices
601  * @return 0 for success, negative value in other cases
602  */
603 static int read_dct_coeffs(GetBitContext *gb, int32_t block[64], const uint8_t *scan,
604                            const int32_t quant_matrices[16][64], int q)
605 {
606     int coef_list[128];
607     int mode_list[128];
608     int i, t, bits, ccoef, mode, sign;
609     int list_start = 64, list_end = 64, list_pos;
610     int coef_count = 0;
611     int coef_idx[64];
612     int quant_idx;
613     const int32_t *quant;
614
615     coef_list[list_end] = 4;  mode_list[list_end++] = 0;
616     coef_list[list_end] = 24; mode_list[list_end++] = 0;
617     coef_list[list_end] = 44; mode_list[list_end++] = 0;
618     coef_list[list_end] = 1;  mode_list[list_end++] = 3;
619     coef_list[list_end] = 2;  mode_list[list_end++] = 3;
620     coef_list[list_end] = 3;  mode_list[list_end++] = 3;
621
622     for (bits = get_bits(gb, 4) - 1; bits >= 0; bits--) {
623         list_pos = list_start;
624         while (list_pos < list_end) {
625             if (!(mode_list[list_pos] | coef_list[list_pos]) || !get_bits1(gb)) {
626                 list_pos++;
627                 continue;
628             }
629             ccoef = coef_list[list_pos];
630             mode  = mode_list[list_pos];
631             switch (mode) {
632             case 0:
633                 coef_list[list_pos] = ccoef + 4;
634                 mode_list[list_pos] = 1;
635             case 2:
636                 if (mode == 2) {
637                     coef_list[list_pos]   = 0;
638                     mode_list[list_pos++] = 0;
639                 }
640                 for (i = 0; i < 4; i++, ccoef++) {
641                     if (get_bits1(gb)) {
642                         coef_list[--list_start] = ccoef;
643                         mode_list[  list_start] = 3;
644                     } else {
645                         if (!bits) {
646                             t = 1 - (get_bits1(gb) << 1);
647                         } else {
648                             t = get_bits(gb, bits) | 1 << bits;
649                             sign = -get_bits1(gb);
650                             t = (t ^ sign) - sign;
651                         }
652                         block[scan[ccoef]] = t;
653                         coef_idx[coef_count++] = ccoef;
654                     }
655                 }
656                 break;
657             case 1:
658                 mode_list[list_pos] = 2;
659                 for (i = 0; i < 3; i++) {
660                     ccoef += 4;
661                     coef_list[list_end]   = ccoef;
662                     mode_list[list_end++] = 2;
663                 }
664                 break;
665             case 3:
666                 if (!bits) {
667                     t = 1 - (get_bits1(gb) << 1);
668                 } else {
669                     t = get_bits(gb, bits) | 1 << bits;
670                     sign = -get_bits1(gb);
671                     t = (t ^ sign) - sign;
672                 }
673                 block[scan[ccoef]] = t;
674                 coef_idx[coef_count++] = ccoef;
675                 coef_list[list_pos]   = 0;
676                 mode_list[list_pos++] = 0;
677                 break;
678             }
679         }
680     }
681
682     if (q == -1) {
683         quant_idx = get_bits(gb, 4);
684     } else {
685         quant_idx = q;
686         if (quant_idx > 15U) {
687             av_log(NULL, AV_LOG_ERROR, "quant_index %d out of range\n", quant_idx);
688             return AVERROR_INVALIDDATA;
689         }
690     }
691
692     quant = quant_matrices[quant_idx];
693
694     block[0] = (block[0] * quant[0]) >> 11;
695     for (i = 0; i < coef_count; i++) {
696         int idx = coef_idx[i];
697         block[scan[idx]] = (block[scan[idx]] * quant[idx]) >> 11;
698     }
699
700     return 0;
701 }
702
703 /**
704  * Read 8x8 block with residue after motion compensation.
705  *
706  * @param gb          context for reading bits
707  * @param block       place to store read data
708  * @param masks_count number of masks to decode
709  * @return 0 on success, negative value in other cases
710  */
711 static int read_residue(GetBitContext *gb, int16_t block[64], int masks_count)
712 {
713     int coef_list[128];
714     int mode_list[128];
715     int i, sign, mask, ccoef, mode;
716     int list_start = 64, list_end = 64, list_pos;
717     int nz_coeff[64];
718     int nz_coeff_count = 0;
719
720     coef_list[list_end] =  4; mode_list[list_end++] = 0;
721     coef_list[list_end] = 24; mode_list[list_end++] = 0;
722     coef_list[list_end] = 44; mode_list[list_end++] = 0;
723     coef_list[list_end] =  0; mode_list[list_end++] = 2;
724
725     for (mask = 1 << get_bits(gb, 3); mask; mask >>= 1) {
726         for (i = 0; i < nz_coeff_count; i++) {
727             if (!get_bits1(gb))
728                 continue;
729             if (block[nz_coeff[i]] < 0)
730                 block[nz_coeff[i]] -= mask;
731             else
732                 block[nz_coeff[i]] += mask;
733             masks_count--;
734             if (masks_count < 0)
735                 return 0;
736         }
737         list_pos = list_start;
738         while (list_pos < list_end) {
739             if (!(coef_list[list_pos] | mode_list[list_pos]) || !get_bits1(gb)) {
740                 list_pos++;
741                 continue;
742             }
743             ccoef = coef_list[list_pos];
744             mode  = mode_list[list_pos];
745             switch (mode) {
746             case 0:
747                 coef_list[list_pos] = ccoef + 4;
748                 mode_list[list_pos] = 1;
749             case 2:
750                 if (mode == 2) {
751                     coef_list[list_pos]   = 0;
752                     mode_list[list_pos++] = 0;
753                 }
754                 for (i = 0; i < 4; i++, ccoef++) {
755                     if (get_bits1(gb)) {
756                         coef_list[--list_start] = ccoef;
757                         mode_list[  list_start] = 3;
758                     } else {
759                         nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
760                         sign = -get_bits1(gb);
761                         block[bink_scan[ccoef]] = (mask ^ sign) - sign;
762                         masks_count--;
763                         if (masks_count < 0)
764                             return 0;
765                     }
766                 }
767                 break;
768             case 1:
769                 mode_list[list_pos] = 2;
770                 for (i = 0; i < 3; i++) {
771                     ccoef += 4;
772                     coef_list[list_end]   = ccoef;
773                     mode_list[list_end++] = 2;
774                 }
775                 break;
776             case 3:
777                 nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
778                 sign = -get_bits1(gb);
779                 block[bink_scan[ccoef]] = (mask ^ sign) - sign;
780                 coef_list[list_pos]   = 0;
781                 mode_list[list_pos++] = 0;
782                 masks_count--;
783                 if (masks_count < 0)
784                     return 0;
785                 break;
786             }
787         }
788     }
789
790     return 0;
791 }
792
793 /**
794  * Copy 8x8 block from source to destination, where src and dst may be overlapped
795  */
796 static inline void put_pixels8x8_overlapped(uint8_t *dst, uint8_t *src, int stride)
797 {
798     uint8_t tmp[64];
799     int i;
800     for (i = 0; i < 8; i++)
801         memcpy(tmp + i*8, src + i*stride, 8);
802     for (i = 0; i < 8; i++)
803         memcpy(dst + i*stride, tmp + i*8, 8);
804 }
805
806 static int binkb_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb,
807                               int plane_idx, int is_key, int is_chroma)
808 {
809     int blk, ret;
810     int i, j, bx, by;
811     uint8_t *dst, *ref, *ref_start, *ref_end;
812     int v, col[2];
813     const uint8_t *scan;
814     int xoff, yoff;
815     LOCAL_ALIGNED_16(int16_t, block, [64]);
816     LOCAL_ALIGNED_16(int32_t, dctblock, [64]);
817     int coordmap[64];
818     int ybias = is_key ? -15 : 0;
819     int qp;
820
821     const int stride = frame->linesize[plane_idx];
822     int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
823     int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
824
825     binkb_init_bundles(c);
826     ref_start = frame->data[plane_idx];
827     ref_end   = frame->data[plane_idx] + (bh * frame->linesize[plane_idx] + bw) * 8;
828
829     for (i = 0; i < 64; i++)
830         coordmap[i] = (i & 7) + (i >> 3) * stride;
831
832     for (by = 0; by < bh; by++) {
833         for (i = 0; i < BINKB_NB_SRC; i++) {
834             if ((ret = binkb_read_bundle(c, gb, i)) < 0)
835                 return ret;
836         }
837
838         dst  = frame->data[plane_idx]  + 8*by*stride;
839         for (bx = 0; bx < bw; bx++, dst += 8) {
840             blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES);
841             switch (blk) {
842             case 0:
843                 break;
844             case 1:
845                 scan = bink_patterns[get_bits(gb, 4)];
846                 i = 0;
847                 do {
848                     int mode, run;
849
850                     mode = get_bits1(gb);
851                     run = get_bits(gb, binkb_runbits[i]) + 1;
852
853                     i += run;
854                     if (i > 64) {
855                         av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
856                         return AVERROR_INVALIDDATA;
857                     }
858                     if (mode) {
859                         v = binkb_get_value(c, BINKB_SRC_COLORS);
860                         for (j = 0; j < run; j++)
861                             dst[coordmap[*scan++]] = v;
862                     } else {
863                         for (j = 0; j < run; j++)
864                             dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
865                     }
866                 } while (i < 63);
867                 if (i == 63)
868                     dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);
869                 break;
870             case 2:
871                 memset(dctblock, 0, sizeof(*dctblock) * 64);
872                 dctblock[0] = binkb_get_value(c, BINKB_SRC_INTRA_DC);
873                 qp = binkb_get_value(c, BINKB_SRC_INTRA_Q);
874                 read_dct_coeffs(gb, dctblock, bink_scan, (const int32_t (*)[64])binkb_intra_quant, qp);
875                 c->bdsp.idct_put(dst, stride, dctblock);
876                 break;
877             case 3:
878                 xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
879                 yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
880                 ref = dst + xoff + yoff * stride;
881                 if (ref < ref_start || ref + 8*stride > ref_end) {
882                     av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
883                 } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
884                     c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);
885                 } else {
886                     put_pixels8x8_overlapped(dst, ref, stride);
887                 }
888                 c->dsp.clear_block(block);
889                 v = binkb_get_value(c, BINKB_SRC_INTER_COEFS);
890                 read_residue(gb, block, v);
891                 c->dsp.add_pixels8(dst, block, stride);
892                 break;
893             case 4:
894                 xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
895                 yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
896                 ref = dst + xoff + yoff * stride;
897                 if (ref < ref_start || ref + 8 * stride > ref_end) {
898                     av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
899                 } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
900                     c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);
901                 } else {
902                     put_pixels8x8_overlapped(dst, ref, stride);
903                 }
904                 memset(dctblock, 0, sizeof(*dctblock) * 64);
905                 dctblock[0] = binkb_get_value(c, BINKB_SRC_INTER_DC);
906                 qp = binkb_get_value(c, BINKB_SRC_INTER_Q);
907                 read_dct_coeffs(gb, dctblock, bink_scan, (const int32_t (*)[64])binkb_inter_quant, qp);
908                 c->bdsp.idct_add(dst, stride, dctblock);
909                 break;
910             case 5:
911                 v = binkb_get_value(c, BINKB_SRC_COLORS);
912                 c->dsp.fill_block_tab[1](dst, v, stride, 8);
913                 break;
914             case 6:
915                 for (i = 0; i < 2; i++)
916                     col[i] = binkb_get_value(c, BINKB_SRC_COLORS);
917                 for (i = 0; i < 8; i++) {
918                     v = binkb_get_value(c, BINKB_SRC_PATTERN);
919                     for (j = 0; j < 8; j++, v >>= 1)
920                         dst[i*stride + j] = col[v & 1];
921                 }
922                 break;
923             case 7:
924                 xoff = binkb_get_value(c, BINKB_SRC_X_OFF);
925                 yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;
926                 ref = dst + xoff + yoff * stride;
927                 if (ref < ref_start || ref + 8 * stride > ref_end) {
928                     av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");
929                 } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {
930                     c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);
931                 } else {
932                     put_pixels8x8_overlapped(dst, ref, stride);
933                 }
934                 break;
935             case 8:
936                 for (i = 0; i < 8; i++)
937                     memcpy(dst + i*stride, c->bundle[BINKB_SRC_COLORS].cur_ptr + i*8, 8);
938                 c->bundle[BINKB_SRC_COLORS].cur_ptr += 64;
939                 break;
940             default:
941                 av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
942                 return AVERROR_INVALIDDATA;
943             }
944         }
945     }
946     if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
947         skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
948
949     return 0;
950 }
951
952 static int bink_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb,
953                              int plane_idx, int is_chroma)
954 {
955     int blk, ret;
956     int i, j, bx, by;
957     uint8_t *dst, *prev, *ref, *ref_start, *ref_end;
958     int v, col[2];
959     const uint8_t *scan;
960     int xoff, yoff;
961     LOCAL_ALIGNED_16(int16_t, block, [64]);
962     LOCAL_ALIGNED_16(uint8_t, ublock, [64]);
963     LOCAL_ALIGNED_16(int32_t, dctblock, [64]);
964     int coordmap[64];
965
966     const int stride = frame->linesize[plane_idx];
967     int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
968     int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
969     int width = c->avctx->width >> is_chroma;
970
971     init_lengths(c, FFMAX(width, 8), bw);
972     for (i = 0; i < BINK_NB_SRC; i++)
973         read_bundle(gb, c, i);
974
975     ref_start = c->last->data[plane_idx] ? c->last->data[plane_idx]
976                                          : frame->data[plane_idx];
977     ref_end   = ref_start
978                 + (bw - 1 + c->last->linesize[plane_idx] * (bh - 1)) * 8;
979
980     for (i = 0; i < 64; i++)
981         coordmap[i] = (i & 7) + (i >> 3) * stride;
982
983     for (by = 0; by < bh; by++) {
984         if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES])) < 0)
985             return ret;
986         if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES])) < 0)
987             return ret;
988         if ((ret = read_colors(gb, &c->bundle[BINK_SRC_COLORS], c)) < 0)
989             return ret;
990         if ((ret = read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN])) < 0)
991             return ret;
992         if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF])) < 0)
993             return ret;
994         if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF])) < 0)
995             return ret;
996         if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0)) < 0)
997             return ret;
998         if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1)) < 0)
999             return ret;
1000         if ((ret = read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN])) < 0)
1001             return ret;
1002
1003         if (by == bh)
1004             break;
1005         dst  = frame->data[plane_idx]  + 8*by*stride;
1006         prev = (c->last->data[plane_idx] ? c->last->data[plane_idx]
1007                                          : frame->data[plane_idx]) + 8*by*stride;
1008         for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {
1009             blk = get_value(c, BINK_SRC_BLOCK_TYPES);
1010             // 16x16 block type on odd line means part of the already decoded block, so skip it
1011             if ((by & 1) && blk == SCALED_BLOCK) {
1012                 bx++;
1013                 dst  += 8;
1014                 prev += 8;
1015                 continue;
1016             }
1017             switch (blk) {
1018             case SKIP_BLOCK:
1019                 c->hdsp.put_pixels_tab[1][0](dst, prev, stride, 8);
1020                 break;
1021             case SCALED_BLOCK:
1022                 blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);
1023                 switch (blk) {
1024                 case RUN_BLOCK:
1025                     scan = bink_patterns[get_bits(gb, 4)];
1026                     i = 0;
1027                     do {
1028                         int run = get_value(c, BINK_SRC_RUN) + 1;
1029
1030                         i += run;
1031                         if (i > 64) {
1032                             av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1033                             return AVERROR_INVALIDDATA;
1034                         }
1035                         if (get_bits1(gb)) {
1036                             v = get_value(c, BINK_SRC_COLORS);
1037                             for (j = 0; j < run; j++)
1038                                 ublock[*scan++] = v;
1039                         } else {
1040                             for (j = 0; j < run; j++)
1041                                 ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
1042                         }
1043                     } while (i < 63);
1044                     if (i == 63)
1045                         ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
1046                     break;
1047                 case INTRA_BLOCK:
1048                     memset(dctblock, 0, sizeof(*dctblock) * 64);
1049                     dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);
1050                     read_dct_coeffs(gb, dctblock, bink_scan, bink_intra_quant, -1);
1051                     c->bdsp.idct_put(ublock, 8, dctblock);
1052                     break;
1053                 case FILL_BLOCK:
1054                     v = get_value(c, BINK_SRC_COLORS);
1055                     c->dsp.fill_block_tab[0](dst, v, stride, 16);
1056                     break;
1057                 case PATTERN_BLOCK:
1058                     for (i = 0; i < 2; i++)
1059                         col[i] = get_value(c, BINK_SRC_COLORS);
1060                     for (j = 0; j < 8; j++) {
1061                         v = get_value(c, BINK_SRC_PATTERN);
1062                         for (i = 0; i < 8; i++, v >>= 1)
1063                             ublock[i + j*8] = col[v & 1];
1064                     }
1065                     break;
1066                 case RAW_BLOCK:
1067                     for (j = 0; j < 8; j++)
1068                         for (i = 0; i < 8; i++)
1069                             ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);
1070                     break;
1071                 default:
1072                     av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);
1073                     return AVERROR_INVALIDDATA;
1074                 }
1075                 if (blk != FILL_BLOCK)
1076                 c->bdsp.scale_block(ublock, dst, stride);
1077                 bx++;
1078                 dst  += 8;
1079                 prev += 8;
1080                 break;
1081             case MOTION_BLOCK:
1082                 xoff = get_value(c, BINK_SRC_X_OFF);
1083                 yoff = get_value(c, BINK_SRC_Y_OFF);
1084                 ref = prev + xoff + yoff * stride;
1085                 if (ref < ref_start || ref > ref_end) {
1086                     av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
1087                            bx*8 + xoff, by*8 + yoff);
1088                     return AVERROR_INVALIDDATA;
1089                 }
1090                 c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);
1091                 break;
1092             case RUN_BLOCK:
1093                 scan = bink_patterns[get_bits(gb, 4)];
1094                 i = 0;
1095                 do {
1096                     int run = get_value(c, BINK_SRC_RUN) + 1;
1097
1098                     i += run;
1099                     if (i > 64) {
1100                         av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
1101                         return AVERROR_INVALIDDATA;
1102                     }
1103                     if (get_bits1(gb)) {
1104                         v = get_value(c, BINK_SRC_COLORS);
1105                         for (j = 0; j < run; j++)
1106                             dst[coordmap[*scan++]] = v;
1107                     } else {
1108                         for (j = 0; j < run; j++)
1109                             dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
1110                     }
1111                 } while (i < 63);
1112                 if (i == 63)
1113                     dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
1114                 break;
1115             case RESIDUE_BLOCK:
1116                 xoff = get_value(c, BINK_SRC_X_OFF);
1117                 yoff = get_value(c, BINK_SRC_Y_OFF);
1118                 ref = prev + xoff + yoff * stride;
1119                 if (ref < ref_start || ref > ref_end) {
1120                     av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
1121                            bx*8 + xoff, by*8 + yoff);
1122                     return AVERROR_INVALIDDATA;
1123                 }
1124                 c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);
1125                 c->dsp.clear_block(block);
1126                 v = get_bits(gb, 7);
1127                 read_residue(gb, block, v);
1128                 c->dsp.add_pixels8(dst, block, stride);
1129                 break;
1130             case INTRA_BLOCK:
1131                 memset(dctblock, 0, sizeof(*dctblock) * 64);
1132                 dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);
1133                 read_dct_coeffs(gb, dctblock, bink_scan, bink_intra_quant, -1);
1134                 c->bdsp.idct_put(dst, stride, dctblock);
1135                 break;
1136             case FILL_BLOCK:
1137                 v = get_value(c, BINK_SRC_COLORS);
1138                 c->dsp.fill_block_tab[1](dst, v, stride, 8);
1139                 break;
1140             case INTER_BLOCK:
1141                 xoff = get_value(c, BINK_SRC_X_OFF);
1142                 yoff = get_value(c, BINK_SRC_Y_OFF);
1143                 ref = prev + xoff + yoff * stride;
1144                 if (ref < ref_start || ref > ref_end) {
1145                     av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
1146                            bx*8 + xoff, by*8 + yoff);
1147                     return -1;
1148                 }
1149                 c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);
1150                 memset(dctblock, 0, sizeof(*dctblock) * 64);
1151                 dctblock[0] = get_value(c, BINK_SRC_INTER_DC);
1152                 read_dct_coeffs(gb, dctblock, bink_scan, bink_inter_quant, -1);
1153                 c->bdsp.idct_add(dst, stride, dctblock);
1154                 break;
1155             case PATTERN_BLOCK:
1156                 for (i = 0; i < 2; i++)
1157                     col[i] = get_value(c, BINK_SRC_COLORS);
1158                 for (i = 0; i < 8; i++) {
1159                     v = get_value(c, BINK_SRC_PATTERN);
1160                     for (j = 0; j < 8; j++, v >>= 1)
1161                         dst[i*stride + j] = col[v & 1];
1162                 }
1163                 break;
1164             case RAW_BLOCK:
1165                 for (i = 0; i < 8; i++)
1166                     memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);
1167                 c->bundle[BINK_SRC_COLORS].cur_ptr += 64;
1168                 break;
1169             default:
1170                 av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
1171                 return AVERROR_INVALIDDATA;
1172             }
1173         }
1174     }
1175     if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
1176         skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
1177
1178     return 0;
1179 }
1180
1181 static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)
1182 {
1183     BinkContext * const c = avctx->priv_data;
1184     AVFrame *frame = data;
1185     GetBitContext gb;
1186     int plane, plane_idx, ret;
1187     int bits_count = pkt->size << 3;
1188
1189     if (c->version > 'b') {
1190         if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
1191             return ret;
1192     } else {
1193         if ((ret = ff_reget_buffer(avctx, c->last)) < 0)
1194             return ret;
1195         if ((ret = av_frame_ref(frame, c->last)) < 0)
1196             return ret;
1197     }
1198
1199     init_get_bits(&gb, pkt->data, bits_count);
1200     if (c->has_alpha) {
1201         if (c->version >= 'i')
1202             skip_bits_long(&gb, 32);
1203         if ((ret = bink_decode_plane(c, frame, &gb, 3, 0)) < 0)
1204             return ret;
1205     }
1206     if (c->version >= 'i')
1207         skip_bits_long(&gb, 32);
1208
1209     for (plane = 0; plane < 3; plane++) {
1210         plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);
1211
1212         if (c->version > 'b') {
1213             if ((ret = bink_decode_plane(c, frame, &gb, plane_idx, !!plane)) < 0)
1214                 return ret;
1215         } else {
1216             if ((ret = binkb_decode_plane(c, frame, &gb, plane_idx,
1217                                           !avctx->frame_number, !!plane)) < 0)
1218                 return ret;
1219         }
1220         if (get_bits_count(&gb) >= bits_count)
1221             break;
1222     }
1223     emms_c();
1224
1225     if (c->version > 'b') {
1226         av_frame_unref(c->last);
1227         if ((ret = av_frame_ref(c->last, frame)) < 0)
1228             return ret;
1229     }
1230
1231     *got_frame = 1;
1232
1233     /* always report that the buffer was completely consumed */
1234     return pkt->size;
1235 }
1236
1237 /**
1238  * Caclulate quantization tables for version b
1239  */
1240 static av_cold void binkb_calc_quant(void)
1241 {
1242     uint8_t inv_bink_scan[64];
1243     static const int s[64]={
1244         1073741824,1489322693,1402911301,1262586814,1073741824, 843633538, 581104888, 296244703,
1245         1489322693,2065749918,1945893874,1751258219,1489322693,1170153332, 806015634, 410903207,
1246         1402911301,1945893874,1832991949,1649649171,1402911301,1102260336, 759250125, 387062357,
1247         1262586814,1751258219,1649649171,1484645031,1262586814, 992008094, 683307060, 348346918,
1248         1073741824,1489322693,1402911301,1262586814,1073741824, 843633538, 581104888, 296244703,
1249          843633538,1170153332,1102260336, 992008094, 843633538, 662838617, 456571181, 232757969,
1250          581104888, 806015634, 759250125, 683307060, 581104888, 456571181, 314491699, 160326478,
1251          296244703, 410903207, 387062357, 348346918, 296244703, 232757969, 160326478,  81733730,
1252     };
1253     int i, j;
1254 #define C (1LL<<30)
1255     for (i = 0; i < 64; i++)
1256         inv_bink_scan[bink_scan[i]] = i;
1257
1258     for (j = 0; j < 16; j++) {
1259         for (i = 0; i < 64; i++) {
1260             int k = inv_bink_scan[i];
1261             binkb_intra_quant[j][k] = binkb_intra_seed[i] * (int64_t)s[i] *
1262                                         binkb_num[j]/(binkb_den[j] * (C>>12));
1263             binkb_inter_quant[j][k] = binkb_inter_seed[i] * (int64_t)s[i] *
1264                                         binkb_num[j]/(binkb_den[j] * (C>>12));
1265         }
1266     }
1267 }
1268
1269 static av_cold int decode_init(AVCodecContext *avctx)
1270 {
1271     BinkContext * const c = avctx->priv_data;
1272     static VLC_TYPE table[16 * 128][2];
1273     static int binkb_initialised = 0;
1274     int i, ret;
1275     int flags;
1276
1277     c->version = avctx->codec_tag >> 24;
1278     if (avctx->extradata_size < 4) {
1279         av_log(avctx, AV_LOG_ERROR, "Extradata missing or too short\n");
1280         return AVERROR_INVALIDDATA;
1281     }
1282     flags = AV_RL32(avctx->extradata);
1283     c->has_alpha = flags & BINK_FLAG_ALPHA;
1284     c->swap_planes = c->version >= 'h';
1285     if (!bink_trees[15].table) {
1286         for (i = 0; i < 16; i++) {
1287             const int maxbits = bink_tree_lens[i][15];
1288             bink_trees[i].table = table + i*128;
1289             bink_trees[i].table_allocated = 1 << maxbits;
1290             init_vlc(&bink_trees[i], maxbits, 16,
1291                      bink_tree_lens[i], 1, 1,
1292                      bink_tree_bits[i], 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
1293         }
1294     }
1295     c->avctx = avctx;
1296
1297     c->last = av_frame_alloc();
1298     if (!c->last)
1299         return AVERROR(ENOMEM);
1300
1301     if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
1302         return ret;
1303
1304     avctx->pix_fmt = c->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;
1305
1306     ff_dsputil_init(&c->dsp, avctx);
1307     ff_hpeldsp_init(&c->hdsp, avctx->flags);
1308     ff_binkdsp_init(&c->bdsp);
1309
1310     if ((ret = init_bundles(c)) < 0) {
1311         free_bundles(c);
1312         return ret;
1313     }
1314
1315     if (c->version == 'b') {
1316         if (!binkb_initialised) {
1317             binkb_calc_quant();
1318             binkb_initialised = 1;
1319         }
1320     }
1321
1322     return 0;
1323 }
1324
1325 static av_cold int decode_end(AVCodecContext *avctx)
1326 {
1327     BinkContext * const c = avctx->priv_data;
1328
1329     av_frame_free(&c->last);
1330
1331     free_bundles(c);
1332     return 0;
1333 }
1334
1335 AVCodec ff_bink_decoder = {
1336     .name           = "binkvideo",
1337     .type           = AVMEDIA_TYPE_VIDEO,
1338     .id             = AV_CODEC_ID_BINKVIDEO,
1339     .priv_data_size = sizeof(BinkContext),
1340     .init           = decode_init,
1341     .close          = decode_end,
1342     .decode         = decode_frame,
1343     .long_name      = NULL_IF_CONFIG_SMALL("Bink video"),
1344     .capabilities   = CODEC_CAP_DR1,
1345 };