]> git.sesse.net Git - ffmpeg/blob - libavcodec/bink.c
Revert r24931, it broke Win32 and some BSD compiles (yay fate).
[ffmpeg] / libavcodec / bink.c
1 /*
2  * Bink video decoder
3  * Copyright (c) 2009 Konstantin Shishkov
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavcore/imgutils.h"
23 #include "avcodec.h"
24 #include "dsputil.h"
25 #include "binkdata.h"
26 #include "mathops.h"
27
28 #define ALT_BITSTREAM_READER_LE
29 #include "get_bits.h"
30
31 #define BINK_FLAG_ALPHA 0x00100000
32 #define BINK_FLAG_GRAY  0x00020000
33
34 static VLC bink_trees[16];
35
36 /**
37  * IDs for different data types used in Bink video codec
38  */
39 enum Sources {
40     BINK_SRC_BLOCK_TYPES = 0, ///< 8x8 block types
41     BINK_SRC_SUB_BLOCK_TYPES, ///< 16x16 block types (a subset of 8x8 block types)
42     BINK_SRC_COLORS,          ///< pixel values used for different block types
43     BINK_SRC_PATTERN,         ///< 8-bit values for 2-colour pattern fill
44     BINK_SRC_X_OFF,           ///< X components of motion value
45     BINK_SRC_Y_OFF,           ///< Y components of motion value
46     BINK_SRC_INTRA_DC,        ///< DC values for intrablocks with DCT
47     BINK_SRC_INTER_DC,        ///< DC values for interblocks with DCT
48     BINK_SRC_RUN,             ///< run lengths for special fill block
49
50     BINK_NB_SRC
51 };
52
53 /**
54  * data needed to decode 4-bit Huffman-coded value
55  */
56 typedef struct Tree {
57     int     vlc_num;  ///< tree number (in bink_trees[])
58     uint8_t syms[16]; ///< leaf value to symbol mapping
59 } Tree;
60
61 #define GET_HUFF(gb, tree)  (tree).syms[get_vlc2(gb, bink_trees[(tree).vlc_num].table,\
62                                                  bink_trees[(tree).vlc_num].bits, 1)]
63
64 /**
65  * data structure used for decoding single Bink data type
66  */
67 typedef struct Bundle {
68     int     len;       ///< length of number of entries to decode (in bits)
69     Tree    tree;      ///< Huffman tree-related data
70     uint8_t *data;     ///< buffer for decoded symbols
71     uint8_t *data_end; ///< buffer end
72     uint8_t *cur_dec;  ///< pointer to the not yet decoded part of the buffer
73     uint8_t *cur_ptr;  ///< pointer to the data that is not read from buffer yet
74 } Bundle;
75
76 /*
77  * Decoder context
78  */
79 typedef struct BinkContext {
80     AVCodecContext *avctx;
81     DSPContext     dsp;
82     AVFrame        pic, last;
83     int            version;              ///< internal Bink file version
84     int            has_alpha;
85     int            swap_planes;
86     ScanTable      scantable;            ///< permutated scantable for DCT coeffs decoding
87
88     Bundle         bundle[BINK_NB_SRC];  ///< bundles for decoding all data types
89     Tree           col_high[16];         ///< trees for decoding high nibble in "colours" data type
90     int            col_lastval;          ///< value of last decoded high nibble in "colours" data type
91 } BinkContext;
92
93 /**
94  * Bink video block types
95  */
96 enum BlockTypes {
97     SKIP_BLOCK = 0, ///< skipped block
98     SCALED_BLOCK,   ///< block has size 16x16
99     MOTION_BLOCK,   ///< block is copied from previous frame with some offset
100     RUN_BLOCK,      ///< block is composed from runs of colours with custom scan order
101     RESIDUE_BLOCK,  ///< motion block with some difference added
102     INTRA_BLOCK,    ///< intra DCT block
103     FILL_BLOCK,     ///< block is filled with single colour
104     INTER_BLOCK,    ///< motion block with DCT applied to the difference
105     PATTERN_BLOCK,  ///< block is filled with two colours following custom pattern
106     RAW_BLOCK,      ///< uncoded 8x8 block
107 };
108
109 /**
110  * Initialize length length in all bundles.
111  *
112  * @param c     decoder context
113  * @param width plane width
114  * @param bw    plane width in 8x8 blocks
115  */
116 static void init_lengths(BinkContext *c, int width, int bw)
117 {
118     c->bundle[BINK_SRC_BLOCK_TYPES].len = av_log2((width >> 3) + 511) + 1;
119
120     c->bundle[BINK_SRC_SUB_BLOCK_TYPES].len = av_log2((width >> 4) + 511) + 1;
121
122     c->bundle[BINK_SRC_COLORS].len = av_log2((width >> 3)*64 + 511) + 1;
123
124     c->bundle[BINK_SRC_INTRA_DC].len =
125     c->bundle[BINK_SRC_INTER_DC].len =
126     c->bundle[BINK_SRC_X_OFF].len =
127     c->bundle[BINK_SRC_Y_OFF].len = av_log2((width >> 3) + 511) + 1;
128
129     c->bundle[BINK_SRC_PATTERN].len = av_log2((bw << 3) + 511) + 1;
130
131     c->bundle[BINK_SRC_RUN].len = av_log2((width >> 3)*48 + 511) + 1;
132 }
133
134 /**
135  * Allocate memory for bundles.
136  *
137  * @param c decoder context
138  */
139 static av_cold void init_bundles(BinkContext *c)
140 {
141     int bw, bh, blocks;
142     int i;
143
144     bw = (c->avctx->width  + 7) >> 3;
145     bh = (c->avctx->height + 7) >> 3;
146     blocks = bw * bh;
147
148     for (i = 0; i < BINK_NB_SRC; i++) {
149         c->bundle[i].data = av_malloc(blocks * 64);
150         c->bundle[i].data_end = c->bundle[i].data + blocks * 64;
151     }
152 }
153
154 /**
155  * Free memory used by bundles.
156  *
157  * @param c decoder context
158  */
159 static av_cold void free_bundles(BinkContext *c)
160 {
161     int i;
162     for (i = 0; i < BINK_NB_SRC; i++)
163         av_freep(&c->bundle[i].data);
164 }
165
166 /**
167  * Merge two consequent lists of equal size depending on bits read.
168  *
169  * @param gb   context for reading bits
170  * @param dst  buffer where merged list will be written to
171  * @param src  pointer to the head of the first list (the second lists starts at src+size)
172  * @param size input lists size
173  */
174 static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
175 {
176     uint8_t *src2 = src + size;
177     int size2 = size;
178
179     do {
180         if (!get_bits1(gb)) {
181             *dst++ = *src++;
182             size--;
183         } else {
184             *dst++ = *src2++;
185             size2--;
186         }
187     } while (size && size2);
188
189     while (size--)
190         *dst++ = *src++;
191     while (size2--)
192         *dst++ = *src2++;
193 }
194
195 /**
196  * Read information about Huffman tree used to decode data.
197  *
198  * @param gb   context for reading bits
199  * @param tree pointer for storing tree data
200  */
201 static void read_tree(GetBitContext *gb, Tree *tree)
202 {
203     uint8_t tmp1[16], tmp2[16], *in = tmp1, *out = tmp2;
204     int i, t, len;
205
206     tree->vlc_num = get_bits(gb, 4);
207     if (!tree->vlc_num) {
208         for (i = 0; i < 16; i++)
209             tree->syms[i] = i;
210         return;
211     }
212     if (get_bits1(gb)) {
213         len = get_bits(gb, 3);
214         memset(tmp1, 0, sizeof(tmp1));
215         for (i = 0; i <= len; i++) {
216             tree->syms[i] = get_bits(gb, 4);
217             tmp1[tree->syms[i]] = 1;
218         }
219         for (i = 0; i < 16; i++)
220             if (!tmp1[i])
221                 tree->syms[++len] = i;
222     } else {
223         len = get_bits(gb, 2);
224         for (i = 0; i < 16; i++)
225             in[i] = i;
226         for (i = 0; i <= len; i++) {
227             int size = 1 << i;
228             for (t = 0; t < 16; t += size << 1)
229                 merge(gb, out + t, in + t, size);
230             FFSWAP(uint8_t*, in, out);
231         }
232         memcpy(tree->syms, in, 16);
233     }
234 }
235
236 /**
237  * Prepare bundle for decoding data.
238  *
239  * @param gb          context for reading bits
240  * @param c           decoder context
241  * @param bundle_num  number of the bundle to initialize
242  */
243 static void read_bundle(GetBitContext *gb, BinkContext *c, int bundle_num)
244 {
245     int i;
246
247     if (bundle_num == BINK_SRC_COLORS) {
248         for (i = 0; i < 16; i++)
249             read_tree(gb, &c->col_high[i]);
250         c->col_lastval = 0;
251     }
252     if (bundle_num != BINK_SRC_INTRA_DC && bundle_num != BINK_SRC_INTER_DC)
253         read_tree(gb, &c->bundle[bundle_num].tree);
254     c->bundle[bundle_num].cur_dec =
255     c->bundle[bundle_num].cur_ptr = c->bundle[bundle_num].data;
256 }
257
258 /**
259  * common check before starting decoding bundle data
260  *
261  * @param gb context for reading bits
262  * @param b  bundle
263  * @param t  variable where number of elements to decode will be stored
264  */
265 #define CHECK_READ_VAL(gb, b, t) \
266     if (!b->cur_dec || (b->cur_dec > b->cur_ptr)) \
267         return 0; \
268     t = get_bits(gb, b->len); \
269     if (!t) { \
270         b->cur_dec = NULL; \
271         return 0; \
272     } \
273
274 static int read_runs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
275 {
276     int t, v;
277     const uint8_t *dec_end;
278
279     CHECK_READ_VAL(gb, b, t);
280     dec_end = b->cur_dec + t;
281     if (dec_end > b->data_end) {
282         av_log(avctx, AV_LOG_ERROR, "Run value went out of bounds\n");
283         return -1;
284     }
285     if (get_bits1(gb)) {
286         v = get_bits(gb, 4);
287         memset(b->cur_dec, v, t);
288         b->cur_dec += t;
289     } else {
290         while (b->cur_dec < dec_end)
291             *b->cur_dec++ = GET_HUFF(gb, b->tree);
292     }
293     return 0;
294 }
295
296 static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
297 {
298     int t, sign, v;
299     const uint8_t *dec_end;
300
301     CHECK_READ_VAL(gb, b, t);
302     dec_end = b->cur_dec + t;
303     if (dec_end > b->data_end) {
304         av_log(avctx, AV_LOG_ERROR, "Too many motion values\n");
305         return -1;
306     }
307     if (get_bits1(gb)) {
308         v = get_bits(gb, 4);
309         if (v) {
310             sign = -get_bits1(gb);
311             v = (v ^ sign) - sign;
312         }
313         memset(b->cur_dec, v, t);
314         b->cur_dec += t;
315     } else {
316         do {
317             v = GET_HUFF(gb, b->tree);
318             if (v) {
319                 sign = -get_bits1(gb);
320                 v = (v ^ sign) - sign;
321             }
322             *b->cur_dec++ = v;
323         } while (b->cur_dec < dec_end);
324     }
325     return 0;
326 }
327
328 const uint8_t bink_rlelens[4] = { 4, 8, 12, 32 };
329
330 static int read_block_types(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
331 {
332     int t, v;
333     int last = 0;
334     const uint8_t *dec_end;
335
336     CHECK_READ_VAL(gb, b, t);
337     dec_end = b->cur_dec + t;
338     if (dec_end > b->data_end) {
339         av_log(avctx, AV_LOG_ERROR, "Too many block type values\n");
340         return -1;
341     }
342     if (get_bits1(gb)) {
343         v = get_bits(gb, 4);
344         memset(b->cur_dec, v, t);
345         b->cur_dec += t;
346     } else {
347         do {
348             v = GET_HUFF(gb, b->tree);
349             if (v < 12) {
350                 last = v;
351                 *b->cur_dec++ = v;
352             } else {
353                 int run = bink_rlelens[v - 12];
354
355                 memset(b->cur_dec, last, run);
356                 b->cur_dec += run;
357             }
358         } while (b->cur_dec < dec_end);
359     }
360     return 0;
361 }
362
363 static int read_patterns(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)
364 {
365     int t, v;
366     const uint8_t *dec_end;
367
368     CHECK_READ_VAL(gb, b, t);
369     dec_end = b->cur_dec + t;
370     if (dec_end > b->data_end) {
371         av_log(avctx, AV_LOG_ERROR, "Too many pattern values\n");
372         return -1;
373     }
374     while (b->cur_dec < dec_end) {
375         v  = GET_HUFF(gb, b->tree);
376         v |= GET_HUFF(gb, b->tree) << 4;
377         *b->cur_dec++ = v;
378     }
379
380     return 0;
381 }
382
383 static int read_colors(GetBitContext *gb, Bundle *b, BinkContext *c)
384 {
385     int t, sign, v;
386     const uint8_t *dec_end;
387
388     CHECK_READ_VAL(gb, b, t);
389     dec_end = b->cur_dec + t;
390     if (dec_end > b->data_end) {
391         av_log(c->avctx, AV_LOG_ERROR, "Too many color values\n");
392         return -1;
393     }
394     if (get_bits1(gb)) {
395         c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
396         v = GET_HUFF(gb, b->tree);
397         v = (c->col_lastval << 4) | v;
398         if (c->version < 'i') {
399             sign = ((int8_t) v) >> 7;
400             v = ((v & 0x7F) ^ sign) - sign;
401             v += 0x80;
402         }
403         memset(b->cur_dec, v, t);
404         b->cur_dec += t;
405     } else {
406         while (b->cur_dec < dec_end) {
407             c->col_lastval = GET_HUFF(gb, c->col_high[c->col_lastval]);
408             v = GET_HUFF(gb, b->tree);
409             v = (c->col_lastval << 4) | v;
410             if (c->version < 'i') {
411                 sign = ((int8_t) v) >> 7;
412                 v = ((v & 0x7F) ^ sign) - sign;
413                 v += 0x80;
414             }
415             *b->cur_dec++ = v;
416         }
417     }
418     return 0;
419 }
420
421 /** number of bits used to store first DC value in bundle */
422 #define DC_START_BITS 11
423
424 static int read_dcs(AVCodecContext *avctx, GetBitContext *gb, Bundle *b,
425                     int start_bits, int has_sign)
426 {
427     int i, j, len, len2, bsize, sign, v, v2;
428     int16_t *dst = (int16_t*)b->cur_dec;
429
430     CHECK_READ_VAL(gb, b, len);
431     v = get_bits(gb, start_bits - has_sign);
432     if (v && has_sign) {
433         sign = -get_bits1(gb);
434         v = (v ^ sign) - sign;
435     }
436     *dst++ = v;
437     len--;
438     for (i = 0; i < len; i += 8) {
439         len2 = FFMIN(len - i, 8);
440         bsize = get_bits(gb, 4);
441         if (bsize) {
442             for (j = 0; j < len2; j++) {
443                 v2 = get_bits(gb, bsize);
444                 if (v2) {
445                     sign = -get_bits1(gb);
446                     v2 = (v2 ^ sign) - sign;
447                 }
448                 v += v2;
449                 *dst++ = v;
450                 if (v < -32768 || v > 32767) {
451                     av_log(avctx, AV_LOG_ERROR, "DC value went out of bounds: %d\n", v);
452                     return -1;
453                 }
454             }
455         } else {
456             for (j = 0; j < len2; j++)
457                 *dst++ = v;
458         }
459     }
460
461     b->cur_dec = (uint8_t*)dst;
462     return 0;
463 }
464
465 /**
466  * Retrieve next value from bundle.
467  *
468  * @param c      decoder context
469  * @param bundle bundle number
470  */
471 static inline int get_value(BinkContext *c, int bundle)
472 {
473     int16_t ret;
474
475     if (bundle < BINK_SRC_X_OFF || bundle == BINK_SRC_RUN)
476         return *c->bundle[bundle].cur_ptr++;
477     if (bundle == BINK_SRC_X_OFF || bundle == BINK_SRC_Y_OFF)
478         return (int8_t)*c->bundle[bundle].cur_ptr++;
479     ret = *(int16_t*)c->bundle[bundle].cur_ptr;
480     c->bundle[bundle].cur_ptr += 2;
481     return ret;
482 }
483
484 /**
485  * Read 8x8 block of DCT coefficients.
486  *
487  * @param gb       context for reading bits
488  * @param block    place for storing coefficients
489  * @param scan     scan order table
490  * @param is_intra tells what set of quantizer matrices to use
491  * @return 0 for success, negative value in other cases
492  */
493 static int read_dct_coeffs(GetBitContext *gb, DCTELEM block[64], const uint8_t *scan,
494                            int is_intra)
495 {
496     int coef_list[128];
497     int mode_list[128];
498     int i, t, mask, bits, ccoef, mode, sign;
499     int list_start = 64, list_end = 64, list_pos;
500     int coef_count = 0;
501     int coef_idx[64];
502     int quant_idx;
503     const uint32_t *quant;
504
505     coef_list[list_end] = 4;  mode_list[list_end++] = 0;
506     coef_list[list_end] = 24; mode_list[list_end++] = 0;
507     coef_list[list_end] = 44; mode_list[list_end++] = 0;
508     coef_list[list_end] = 1;  mode_list[list_end++] = 3;
509     coef_list[list_end] = 2;  mode_list[list_end++] = 3;
510     coef_list[list_end] = 3;  mode_list[list_end++] = 3;
511
512     bits = get_bits(gb, 4) - 1;
513     for (mask = 1 << bits; bits >= 0; mask >>= 1, bits--) {
514         list_pos = list_start;
515         while (list_pos < list_end) {
516             if (!(mode_list[list_pos] | coef_list[list_pos]) || !get_bits1(gb)) {
517                 list_pos++;
518                 continue;
519             }
520             ccoef = coef_list[list_pos];
521             mode  = mode_list[list_pos];
522             switch (mode) {
523             case 0:
524                 coef_list[list_pos] = ccoef + 4;
525                 mode_list[list_pos] = 1;
526             case 2:
527                 if (mode == 2) {
528                     coef_list[list_pos]   = 0;
529                     mode_list[list_pos++] = 0;
530                 }
531                 for (i = 0; i < 4; i++, ccoef++) {
532                     if (get_bits1(gb)) {
533                         coef_list[--list_start] = ccoef;
534                         mode_list[  list_start] = 3;
535                     } else {
536                         int t;
537                         if (!bits) {
538                             t = 1 - (get_bits1(gb) << 1);
539                         } else {
540                             t = get_bits(gb, bits) | mask;
541                             sign = -get_bits1(gb);
542                             t = (t ^ sign) - sign;
543                         }
544                         block[scan[ccoef]] = t;
545                         coef_idx[coef_count++] = ccoef;
546                     }
547                 }
548                 break;
549             case 1:
550                 mode_list[list_pos] = 2;
551                 for (i = 0; i < 3; i++) {
552                     ccoef += 4;
553                     coef_list[list_end]   = ccoef;
554                     mode_list[list_end++] = 2;
555                 }
556                 break;
557             case 3:
558                 if (!bits) {
559                     t = 1 - (get_bits1(gb) << 1);
560                 } else {
561                     t = get_bits(gb, bits) | mask;
562                     sign = -get_bits1(gb);
563                     t = (t ^ sign) - sign;
564                 }
565                 block[scan[ccoef]] = t;
566                 coef_idx[coef_count++] = ccoef;
567                 coef_list[list_pos]   = 0;
568                 mode_list[list_pos++] = 0;
569                 break;
570             }
571         }
572     }
573
574     quant_idx = get_bits(gb, 4);
575     quant = is_intra ? bink_intra_quant[quant_idx]
576                      : bink_inter_quant[quant_idx];
577     block[0] = (block[0] * quant[0]) >> 11;
578     for (i = 0; i < coef_count; i++) {
579         int idx = coef_idx[i];
580         block[scan[idx]] = (block[scan[idx]] * quant[idx]) >> 11;
581     }
582
583     return 0;
584 }
585
586 /**
587  * Read 8x8 block with residue after motion compensation.
588  *
589  * @param gb          context for reading bits
590  * @param block       place to store read data
591  * @param masks_count number of masks to decode
592  * @return 0 on success, negative value in other cases
593  */
594 static int read_residue(GetBitContext *gb, DCTELEM block[64], int masks_count)
595 {
596     int coef_list[128];
597     int mode_list[128];
598     int i, sign, mask, ccoef, mode;
599     int list_start = 64, list_end = 64, list_pos;
600     int nz_coeff[64];
601     int nz_coeff_count = 0;
602
603     coef_list[list_end] =  4; mode_list[list_end++] = 0;
604     coef_list[list_end] = 24; mode_list[list_end++] = 0;
605     coef_list[list_end] = 44; mode_list[list_end++] = 0;
606     coef_list[list_end] =  0; mode_list[list_end++] = 2;
607
608     for (mask = 1 << get_bits(gb, 3); mask; mask >>= 1) {
609         for (i = 0; i < nz_coeff_count; i++) {
610             if (!get_bits1(gb))
611                 continue;
612             if (block[nz_coeff[i]] < 0)
613                 block[nz_coeff[i]] -= mask;
614             else
615                 block[nz_coeff[i]] += mask;
616             masks_count--;
617             if (masks_count < 0)
618                 return 0;
619         }
620         list_pos = list_start;
621         while (list_pos < list_end) {
622             if (!(coef_list[list_pos] | mode_list[list_pos]) || !get_bits1(gb)) {
623                 list_pos++;
624                 continue;
625             }
626             ccoef = coef_list[list_pos];
627             mode  = mode_list[list_pos];
628             switch (mode) {
629             case 0:
630                 coef_list[list_pos] = ccoef + 4;
631                 mode_list[list_pos] = 1;
632             case 2:
633                 if (mode == 2) {
634                     coef_list[list_pos]   = 0;
635                     mode_list[list_pos++] = 0;
636                 }
637                 for (i = 0; i < 4; i++, ccoef++) {
638                     if (get_bits1(gb)) {
639                         coef_list[--list_start] = ccoef;
640                         mode_list[  list_start] = 3;
641                     } else {
642                         nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
643                         sign = -get_bits1(gb);
644                         block[bink_scan[ccoef]] = (mask ^ sign) - sign;
645                         masks_count--;
646                         if (masks_count < 0)
647                             return 0;
648                     }
649                 }
650                 break;
651             case 1:
652                 mode_list[list_pos] = 2;
653                 for (i = 0; i < 3; i++) {
654                     ccoef += 4;
655                     coef_list[list_end]   = ccoef;
656                     mode_list[list_end++] = 2;
657                 }
658                 break;
659             case 3:
660                 nz_coeff[nz_coeff_count++] = bink_scan[ccoef];
661                 sign = -get_bits1(gb);
662                 block[bink_scan[ccoef]] = (mask ^ sign) - sign;
663                 coef_list[list_pos]   = 0;
664                 mode_list[list_pos++] = 0;
665                 masks_count--;
666                 if (masks_count < 0)
667                     return 0;
668                 break;
669             }
670         }
671     }
672
673     return 0;
674 }
675
676 static int bink_decode_plane(BinkContext *c, GetBitContext *gb, int plane_idx,
677                              int is_chroma)
678 {
679     int blk;
680     int i, j, bx, by;
681     uint8_t *dst, *prev, *ref, *ref_start, *ref_end;
682     int v, col[2];
683     const uint8_t *scan;
684     int xoff, yoff;
685     LOCAL_ALIGNED_16(DCTELEM, block, [64]);
686     LOCAL_ALIGNED_16(uint8_t, ublock, [64]);
687     int coordmap[64];
688
689     const int stride = c->pic.linesize[plane_idx];
690     int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;
691     int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;
692     int width = c->avctx->width >> is_chroma;
693
694     init_lengths(c, FFMAX(width, 8), bw);
695     for (i = 0; i < BINK_NB_SRC; i++)
696         read_bundle(gb, c, i);
697
698     ref_start = c->last.data[plane_idx];
699     ref_end   = c->last.data[plane_idx]
700                 + (bw - 1 + c->last.linesize[plane_idx] * (bh - 1)) * 8;
701
702     for (i = 0; i < 64; i++)
703         coordmap[i] = (i & 7) + (i >> 3) * stride;
704
705     for (by = 0; by < bh; by++) {
706         if (read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES]) < 0)
707             return -1;
708         if (read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES]) < 0)
709             return -1;
710         if (read_colors(gb, &c->bundle[BINK_SRC_COLORS], c) < 0)
711             return -1;
712         if (read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN]) < 0)
713             return -1;
714         if (read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF]) < 0)
715             return -1;
716         if (read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF]) < 0)
717             return -1;
718         if (read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0) < 0)
719             return -1;
720         if (read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1) < 0)
721             return -1;
722         if (read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN]) < 0)
723             return -1;
724
725         if (by == bh)
726             break;
727         dst  = c->pic.data[plane_idx]  + 8*by*stride;
728         prev = c->last.data[plane_idx] + 8*by*stride;
729         for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {
730             blk = get_value(c, BINK_SRC_BLOCK_TYPES);
731             // 16x16 block type on odd line means part of the already decoded block, so skip it
732             if ((by & 1) && blk == SCALED_BLOCK) {
733                 bx++;
734                 dst  += 8;
735                 prev += 8;
736                 continue;
737             }
738             switch (blk) {
739             case SKIP_BLOCK:
740                 c->dsp.put_pixels_tab[1][0](dst, prev, stride, 8);
741                 break;
742             case SCALED_BLOCK:
743                 blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);
744                 switch (blk) {
745                 case RUN_BLOCK:
746                     scan = bink_patterns[get_bits(gb, 4)];
747                     i = 0;
748                     do {
749                         int run = get_value(c, BINK_SRC_RUN) + 1;
750
751                         i += run;
752                         if (i > 64) {
753                             av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
754                             return -1;
755                         }
756                         if (get_bits1(gb)) {
757                             v = get_value(c, BINK_SRC_COLORS);
758                             for (j = 0; j < run; j++)
759                                 ublock[*scan++] = v;
760                         } else {
761                             for (j = 0; j < run; j++)
762                                 ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
763                         }
764                     } while (i < 63);
765                     if (i == 63)
766                         ublock[*scan++] = get_value(c, BINK_SRC_COLORS);
767                     break;
768                 case INTRA_BLOCK:
769                     c->dsp.clear_block(block);
770                     block[0] = get_value(c, BINK_SRC_INTRA_DC);
771                     read_dct_coeffs(gb, block, c->scantable.permutated, 1);
772                     c->dsp.idct(block);
773                     c->dsp.put_pixels_nonclamped(block, ublock, 8);
774                     break;
775                 case FILL_BLOCK:
776                     v = get_value(c, BINK_SRC_COLORS);
777                     c->dsp.fill_block_tab[0](dst, v, stride, 16);
778                     break;
779                 case PATTERN_BLOCK:
780                     for (i = 0; i < 2; i++)
781                         col[i] = get_value(c, BINK_SRC_COLORS);
782                     for (j = 0; j < 8; j++) {
783                         v = get_value(c, BINK_SRC_PATTERN);
784                         for (i = 0; i < 8; i++, v >>= 1)
785                             ublock[i + j*8] = col[v & 1];
786                     }
787                     break;
788                 case RAW_BLOCK:
789                     for (j = 0; j < 8; j++)
790                         for (i = 0; i < 8; i++)
791                             ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);
792                     break;
793                 default:
794                     av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);
795                     return -1;
796                 }
797                 if (blk != FILL_BLOCK)
798                 c->dsp.scale_block(ublock, dst, stride);
799                 bx++;
800                 dst  += 8;
801                 prev += 8;
802                 break;
803             case MOTION_BLOCK:
804                 xoff = get_value(c, BINK_SRC_X_OFF);
805                 yoff = get_value(c, BINK_SRC_Y_OFF);
806                 ref = prev + xoff + yoff * stride;
807                 if (ref < ref_start || ref > ref_end) {
808                     av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
809                            bx*8 + xoff, by*8 + yoff);
810                     return -1;
811                 }
812                 c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
813                 break;
814             case RUN_BLOCK:
815                 scan = bink_patterns[get_bits(gb, 4)];
816                 i = 0;
817                 do {
818                     int run = get_value(c, BINK_SRC_RUN) + 1;
819
820                     i += run;
821                     if (i > 64) {
822                         av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");
823                         return -1;
824                     }
825                     if (get_bits1(gb)) {
826                         v = get_value(c, BINK_SRC_COLORS);
827                         for (j = 0; j < run; j++)
828                             dst[coordmap[*scan++]] = v;
829                     } else {
830                         for (j = 0; j < run; j++)
831                             dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
832                     }
833                 } while (i < 63);
834                 if (i == 63)
835                     dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);
836                 break;
837             case RESIDUE_BLOCK:
838                 xoff = get_value(c, BINK_SRC_X_OFF);
839                 yoff = get_value(c, BINK_SRC_Y_OFF);
840                 ref = prev + xoff + yoff * stride;
841                 if (ref < ref_start || ref > ref_end) {
842                     av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",
843                            bx*8 + xoff, by*8 + yoff);
844                     return -1;
845                 }
846                 c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
847                 c->dsp.clear_block(block);
848                 v = get_bits(gb, 7);
849                 read_residue(gb, block, v);
850                 c->dsp.add_pixels8(dst, block, stride);
851                 break;
852             case INTRA_BLOCK:
853                 c->dsp.clear_block(block);
854                 block[0] = get_value(c, BINK_SRC_INTRA_DC);
855                 read_dct_coeffs(gb, block, c->scantable.permutated, 1);
856                 c->dsp.idct_put(dst, stride, block);
857                 break;
858             case FILL_BLOCK:
859                 v = get_value(c, BINK_SRC_COLORS);
860                 c->dsp.fill_block_tab[1](dst, v, stride, 8);
861                 break;
862             case INTER_BLOCK:
863                 xoff = get_value(c, BINK_SRC_X_OFF);
864                 yoff = get_value(c, BINK_SRC_Y_OFF);
865                 ref = prev + xoff + yoff * stride;
866                 c->dsp.put_pixels_tab[1][0](dst, ref, stride, 8);
867                 c->dsp.clear_block(block);
868                 block[0] = get_value(c, BINK_SRC_INTER_DC);
869                 read_dct_coeffs(gb, block, c->scantable.permutated, 0);
870                 c->dsp.idct_add(dst, stride, block);
871                 break;
872             case PATTERN_BLOCK:
873                 for (i = 0; i < 2; i++)
874                     col[i] = get_value(c, BINK_SRC_COLORS);
875                 for (i = 0; i < 8; i++) {
876                     v = get_value(c, BINK_SRC_PATTERN);
877                     for (j = 0; j < 8; j++, v >>= 1)
878                         dst[i*stride + j] = col[v & 1];
879                 }
880                 break;
881             case RAW_BLOCK:
882                 for (i = 0; i < 8; i++)
883                     memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);
884                 c->bundle[BINK_SRC_COLORS].cur_ptr += 64;
885                 break;
886             default:
887                 av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);
888                 return -1;
889             }
890         }
891     }
892     if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary
893         skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));
894
895     return 0;
896 }
897
898 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *pkt)
899 {
900     BinkContext * const c = avctx->priv_data;
901     GetBitContext gb;
902     int plane, plane_idx;
903     int bits_count = pkt->size << 3;
904
905     if(c->pic.data[0])
906         avctx->release_buffer(avctx, &c->pic);
907
908     if(avctx->get_buffer(avctx, &c->pic) < 0){
909         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
910         return -1;
911     }
912
913     init_get_bits(&gb, pkt->data, bits_count);
914     if (c->has_alpha) {
915         if (c->version >= 'i')
916             skip_bits_long(&gb, 32);
917         if (bink_decode_plane(c, &gb, 3, 0) < 0)
918             return -1;
919     }
920     if (c->version >= 'i')
921         skip_bits_long(&gb, 32);
922
923     for (plane = 0; plane < 3; plane++) {
924         plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);
925
926         if (bink_decode_plane(c, &gb, plane_idx, !!plane) < 0)
927             return -1;
928         if (get_bits_count(&gb) >= bits_count)
929             break;
930     }
931     emms_c();
932
933     *data_size = sizeof(AVFrame);
934     *(AVFrame*)data = c->pic;
935
936     FFSWAP(AVFrame, c->pic, c->last);
937
938     /* always report that the buffer was completely consumed */
939     return pkt->size;
940 }
941
942 static av_cold int decode_init(AVCodecContext *avctx)
943 {
944     BinkContext * const c = avctx->priv_data;
945     static VLC_TYPE table[16 * 128][2];
946     int i;
947     int flags;
948
949     c->version = avctx->codec_tag >> 24;
950     if (c->version < 'c') {
951         av_log(avctx, AV_LOG_ERROR, "Too old version '%c'\n", c->version);
952         return -1;
953     }
954     if (avctx->extradata_size < 4) {
955         av_log(avctx, AV_LOG_ERROR, "Extradata missing or too short\n");
956         return -1;
957     }
958     flags = AV_RL32(avctx->extradata);
959     c->has_alpha = flags & BINK_FLAG_ALPHA;
960     c->swap_planes = c->version >= 'h';
961     if (!bink_trees[15].table) {
962         for (i = 0; i < 16; i++) {
963             const int maxbits = bink_tree_lens[i][15];
964             bink_trees[i].table = table + i*128;
965             bink_trees[i].table_allocated = 1 << maxbits;
966             init_vlc(&bink_trees[i], maxbits, 16,
967                      bink_tree_lens[i], 1, 1,
968                      bink_tree_bits[i], 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
969         }
970     }
971     c->avctx = avctx;
972
973     c->pic.data[0] = NULL;
974
975     if (av_check_image_size(avctx->width, avctx->height, 0, avctx) < 0) {
976         return 1;
977     }
978
979     avctx->pix_fmt = c->has_alpha ? PIX_FMT_YUVA420P : PIX_FMT_YUV420P;
980
981     avctx->idct_algo = FF_IDCT_BINK;
982     dsputil_init(&c->dsp, avctx);
983     ff_init_scantable(c->dsp.idct_permutation, &c->scantable, bink_scan);
984
985     init_bundles(c);
986
987     return 0;
988 }
989
990 static av_cold int decode_end(AVCodecContext *avctx)
991 {
992     BinkContext * const c = avctx->priv_data;
993
994     if (c->pic.data[0])
995         avctx->release_buffer(avctx, &c->pic);
996     if (c->last.data[0])
997         avctx->release_buffer(avctx, &c->last);
998
999     free_bundles(c);
1000     return 0;
1001 }
1002
1003 AVCodec bink_decoder = {
1004     "binkvideo",
1005     AVMEDIA_TYPE_VIDEO,
1006     CODEC_ID_BINKVIDEO,
1007     sizeof(BinkContext),
1008     decode_init,
1009     NULL,
1010     decode_end,
1011     decode_frame,
1012     .long_name = NULL_IF_CONFIG_SMALL("Bink video"),
1013 };