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