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