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