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