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