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