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