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