]> git.sesse.net Git - ffmpeg/blob - libavcodec/vp3.c
avcodec/vp3: Make tables used to initialize VLCs smaller
[ffmpeg] / libavcodec / vp3.c
1 /*
2  * Copyright (C) 2003-2004 The FFmpeg project
3  * Copyright (C) 2019 Peter Ross
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 /**
23  * @file
24  * On2 VP3/VP4 Video Decoder
25  *
26  * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
27  * For more information about the VP3 coding process, visit:
28  *   http://wiki.multimedia.cx/index.php?title=On2_VP3
29  *
30  * Theora decoder by Alex Beregszaszi
31  */
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36
37 #include "libavutil/imgutils.h"
38
39 #include "avcodec.h"
40 #include "get_bits.h"
41 #include "hpeldsp.h"
42 #include "internal.h"
43 #include "mathops.h"
44 #include "thread.h"
45 #include "videodsp.h"
46 #include "vp3data.h"
47 #include "vp4data.h"
48 #include "vp3dsp.h"
49 #include "xiph.h"
50
51 #define VP4_MV_VLC_BITS     6
52 #define SUPERBLOCK_VLC_BITS 6
53
54 #define FRAGMENT_PIXELS 8
55
56 // FIXME split things out into their own arrays
57 typedef struct Vp3Fragment {
58     int16_t dc;
59     uint8_t coding_method;
60     uint8_t qpi;
61 } Vp3Fragment;
62
63 #define SB_NOT_CODED        0
64 #define SB_PARTIALLY_CODED  1
65 #define SB_FULLY_CODED      2
66
67 // This is the maximum length of a single long bit run that can be encoded
68 // for superblock coding or block qps. Theora special-cases this to read a
69 // bit instead of flipping the current bit to allow for runs longer than 4129.
70 #define MAXIMUM_LONG_BIT_RUN 4129
71
72 #define MODE_INTER_NO_MV      0
73 #define MODE_INTRA            1
74 #define MODE_INTER_PLUS_MV    2
75 #define MODE_INTER_LAST_MV    3
76 #define MODE_INTER_PRIOR_LAST 4
77 #define MODE_USING_GOLDEN     5
78 #define MODE_GOLDEN_MV        6
79 #define MODE_INTER_FOURMV     7
80 #define CODING_MODE_COUNT     8
81
82 /* special internal mode */
83 #define MODE_COPY             8
84
85 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
86 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
87
88
89 /* There are 6 preset schemes, plus a free-form scheme */
90 static const int ModeAlphabet[6][CODING_MODE_COUNT] = {
91     /* scheme 1: Last motion vector dominates */
92     { MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
93       MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
94       MODE_INTRA,            MODE_USING_GOLDEN,
95       MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
96
97     /* scheme 2 */
98     { MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
99       MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
100       MODE_INTRA,            MODE_USING_GOLDEN,
101       MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
102
103     /* scheme 3 */
104     { MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
105       MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
106       MODE_INTRA,            MODE_USING_GOLDEN,
107       MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
108
109     /* scheme 4 */
110     { MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
111       MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
112       MODE_INTRA,            MODE_USING_GOLDEN,
113       MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
114
115     /* scheme 5: No motion vector dominates */
116     { MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,
117       MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
118       MODE_INTRA,            MODE_USING_GOLDEN,
119       MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
120
121     /* scheme 6 */
122     { MODE_INTER_NO_MV,      MODE_USING_GOLDEN,
123       MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
124       MODE_INTER_PLUS_MV,    MODE_INTRA,
125       MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
126 };
127
128 static const uint8_t hilbert_offset[16][2] = {
129     { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
130     { 0, 2 }, { 0, 3 }, { 1, 3 }, { 1, 2 },
131     { 2, 2 }, { 2, 3 }, { 3, 3 }, { 3, 2 },
132     { 3, 1 }, { 2, 1 }, { 2, 0 }, { 3, 0 }
133 };
134
135 enum {
136     VP4_DC_INTRA  = 0,
137     VP4_DC_INTER  = 1,
138     VP4_DC_GOLDEN = 2,
139     NB_VP4_DC_TYPES,
140     VP4_DC_UNDEFINED = NB_VP4_DC_TYPES
141 };
142
143 static const uint8_t vp4_pred_block_type_map[8] = {
144     [MODE_INTER_NO_MV]      = VP4_DC_INTER,
145     [MODE_INTRA]            = VP4_DC_INTRA,
146     [MODE_INTER_PLUS_MV]    = VP4_DC_INTER,
147     [MODE_INTER_LAST_MV]    = VP4_DC_INTER,
148     [MODE_INTER_PRIOR_LAST] = VP4_DC_INTER,
149     [MODE_USING_GOLDEN]     = VP4_DC_GOLDEN,
150     [MODE_GOLDEN_MV]        = VP4_DC_GOLDEN,
151     [MODE_INTER_FOURMV]     = VP4_DC_INTER,
152 };
153
154 typedef struct {
155     int dc;
156     int type;
157 } VP4Predictor;
158
159 #define MIN_DEQUANT_VAL 2
160
161 typedef struct HuffEntry {
162     uint8_t len, sym;
163 } HuffEntry;
164
165 typedef struct HuffTable {
166     HuffEntry entries[32];
167     uint8_t   nb_entries;
168 } HuffTable;
169
170 typedef struct Vp3DecodeContext {
171     AVCodecContext *avctx;
172     int theora, theora_tables, theora_header;
173     int version;
174     int width, height;
175     int chroma_x_shift, chroma_y_shift;
176     ThreadFrame golden_frame;
177     ThreadFrame last_frame;
178     ThreadFrame current_frame;
179     int keyframe;
180     uint8_t idct_permutation[64];
181     uint8_t idct_scantable[64];
182     HpelDSPContext hdsp;
183     VideoDSPContext vdsp;
184     VP3DSPContext vp3dsp;
185     DECLARE_ALIGNED(16, int16_t, block)[64];
186     int flipped_image;
187     int last_slice_end;
188     int skip_loop_filter;
189
190     int qps[3];
191     int nqps;
192     int last_qps[3];
193
194     int superblock_count;
195     int y_superblock_width;
196     int y_superblock_height;
197     int y_superblock_count;
198     int c_superblock_width;
199     int c_superblock_height;
200     int c_superblock_count;
201     int u_superblock_start;
202     int v_superblock_start;
203     unsigned char *superblock_coding;
204
205     int macroblock_count; /* y macroblock count */
206     int macroblock_width;
207     int macroblock_height;
208     int c_macroblock_count;
209     int c_macroblock_width;
210     int c_macroblock_height;
211     int yuv_macroblock_count; /* y+u+v macroblock count */
212
213     int fragment_count;
214     int fragment_width[2];
215     int fragment_height[2];
216
217     Vp3Fragment *all_fragments;
218     int fragment_start[3];
219     int data_offset[3];
220     uint8_t offset_x;
221     uint8_t offset_y;
222     int offset_x_warned;
223
224     int8_t (*motion_val[2])[2];
225
226     /* tables */
227     uint16_t coded_dc_scale_factor[2][64];
228     uint32_t coded_ac_scale_factor[64];
229     uint8_t base_matrix[384][64];
230     uint8_t qr_count[2][3];
231     uint8_t qr_size[2][3][64];
232     uint16_t qr_base[2][3][64];
233
234     /**
235      * This is a list of all tokens in bitstream order. Reordering takes place
236      * by pulling from each level during IDCT. As a consequence, IDCT must be
237      * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
238      * otherwise. The 32 different tokens with up to 12 bits of extradata are
239      * collapsed into 3 types, packed as follows:
240      *   (from the low to high bits)
241      *
242      * 2 bits: type (0,1,2)
243      *   0: EOB run, 14 bits for run length (12 needed)
244      *   1: zero run, 7 bits for run length
245      *                7 bits for the next coefficient (3 needed)
246      *   2: coefficient, 14 bits (11 needed)
247      *
248      * Coefficients are signed, so are packed in the highest bits for automatic
249      * sign extension.
250      */
251     int16_t *dct_tokens[3][64];
252     int16_t *dct_tokens_base;
253 #define TOKEN_EOB(eob_run)              ((eob_run) << 2)
254 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
255 #define TOKEN_COEFF(coeff)              (((coeff) * 4) + 2)
256
257     /**
258      * number of blocks that contain DCT coefficients at
259      * the given level or higher
260      */
261     int num_coded_frags[3][64];
262     int total_num_coded_frags;
263
264     /* this is a list of indexes into the all_fragments array indicating
265      * which of the fragments are coded */
266     int *coded_fragment_list[3];
267
268     int *kf_coded_fragment_list;
269     int *nkf_coded_fragment_list;
270     int num_kf_coded_fragment[3];
271
272     /* The first 16 of the following VLCs are for the dc coefficients;
273        the others are four groups of 16 VLCs each for ac coefficients. */
274     VLC coeff_vlc[5 * 16];
275
276     VLC superblock_run_length_vlc; /* version < 2 */
277     VLC fragment_run_length_vlc; /* version < 2 */
278     VLC block_pattern_vlc[2]; /* version >= 2*/
279     VLC mode_code_vlc;
280     VLC motion_vector_vlc; /* version < 2 */
281     VLC vp4_mv_vlc[2][7]; /* version >=2 */
282
283     /* these arrays need to be on 16-byte boundaries since SSE2 operations
284      * index into them */
285     DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64];     ///< qmat[qpi][is_inter][plane]
286
287     /* This table contains superblock_count * 16 entries. Each set of 16
288      * numbers corresponds to the fragment indexes 0..15 of the superblock.
289      * An entry will be -1 to indicate that no entry corresponds to that
290      * index. */
291     int *superblock_fragments;
292
293     /* This is an array that indicates how a particular macroblock
294      * is coded. */
295     unsigned char *macroblock_coding;
296
297     uint8_t *edge_emu_buffer;
298
299     /* Huffman decode */
300     HuffTable huffman_table[5 * 16];
301
302     uint8_t filter_limit_values[64];
303     DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
304
305     VP4Predictor * dc_pred_row; /* dc_pred_row[y_superblock_width * 4] */
306 } Vp3DecodeContext;
307
308 /************************************************************************
309  * VP3 specific functions
310  ************************************************************************/
311
312 static av_cold void free_tables(AVCodecContext *avctx)
313 {
314     Vp3DecodeContext *s = avctx->priv_data;
315
316     av_freep(&s->superblock_coding);
317     av_freep(&s->all_fragments);
318     av_freep(&s->nkf_coded_fragment_list);
319     av_freep(&s->kf_coded_fragment_list);
320     av_freep(&s->dct_tokens_base);
321     av_freep(&s->superblock_fragments);
322     av_freep(&s->macroblock_coding);
323     av_freep(&s->dc_pred_row);
324     av_freep(&s->motion_val[0]);
325     av_freep(&s->motion_val[1]);
326 }
327
328 static void vp3_decode_flush(AVCodecContext *avctx)
329 {
330     Vp3DecodeContext *s = avctx->priv_data;
331
332     if (s->golden_frame.f)
333         ff_thread_release_buffer(avctx, &s->golden_frame);
334     if (s->last_frame.f)
335         ff_thread_release_buffer(avctx, &s->last_frame);
336     if (s->current_frame.f)
337         ff_thread_release_buffer(avctx, &s->current_frame);
338 }
339
340 static av_cold int vp3_decode_end(AVCodecContext *avctx)
341 {
342     Vp3DecodeContext *s = avctx->priv_data;
343     int i, j;
344
345     free_tables(avctx);
346     av_freep(&s->edge_emu_buffer);
347
348     s->theora_tables = 0;
349
350     /* release all frames */
351     vp3_decode_flush(avctx);
352     av_frame_free(&s->current_frame.f);
353     av_frame_free(&s->last_frame.f);
354     av_frame_free(&s->golden_frame.f);
355
356     for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++)
357         ff_free_vlc(&s->coeff_vlc[i]);
358
359     ff_free_vlc(&s->superblock_run_length_vlc);
360     ff_free_vlc(&s->fragment_run_length_vlc);
361     ff_free_vlc(&s->mode_code_vlc);
362     ff_free_vlc(&s->motion_vector_vlc);
363
364     for (j = 0; j < 2; j++)
365         for (i = 0; i < 7; i++)
366             ff_free_vlc(&s->vp4_mv_vlc[j][i]);
367
368     for (i = 0; i < 2; i++)
369         ff_free_vlc(&s->block_pattern_vlc[i]);
370     return 0;
371 }
372
373 /**
374  * This function sets up all of the various blocks mappings:
375  * superblocks <-> fragments, macroblocks <-> fragments,
376  * superblocks <-> macroblocks
377  *
378  * @return 0 is successful; returns 1 if *anything* went wrong.
379  */
380 static int init_block_mapping(Vp3DecodeContext *s)
381 {
382     int sb_x, sb_y, plane;
383     int x, y, i, j = 0;
384
385     for (plane = 0; plane < 3; plane++) {
386         int sb_width    = plane ? s->c_superblock_width
387                                 : s->y_superblock_width;
388         int sb_height   = plane ? s->c_superblock_height
389                                 : s->y_superblock_height;
390         int frag_width  = s->fragment_width[!!plane];
391         int frag_height = s->fragment_height[!!plane];
392
393         for (sb_y = 0; sb_y < sb_height; sb_y++)
394             for (sb_x = 0; sb_x < sb_width; sb_x++)
395                 for (i = 0; i < 16; i++) {
396                     x = 4 * sb_x + hilbert_offset[i][0];
397                     y = 4 * sb_y + hilbert_offset[i][1];
398
399                     if (x < frag_width && y < frag_height)
400                         s->superblock_fragments[j++] = s->fragment_start[plane] +
401                                                        y * frag_width + x;
402                     else
403                         s->superblock_fragments[j++] = -1;
404                 }
405     }
406
407     return 0;  /* successful path out */
408 }
409
410 /*
411  * This function sets up the dequantization tables used for a particular
412  * frame.
413  */
414 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
415 {
416     int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
417     int i, plane, inter, qri, bmi, bmj, qistart;
418
419     for (inter = 0; inter < 2; inter++) {
420         for (plane = 0; plane < 3; plane++) {
421             int dc_scale_factor = s->coded_dc_scale_factor[!!plane][s->qps[qpi]];
422             int sum = 0;
423             for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
424                 sum += s->qr_size[inter][plane][qri];
425                 if (s->qps[qpi] <= sum)
426                     break;
427             }
428             qistart = sum - s->qr_size[inter][plane][qri];
429             bmi     = s->qr_base[inter][plane][qri];
430             bmj     = s->qr_base[inter][plane][qri + 1];
431             for (i = 0; i < 64; i++) {
432                 int coeff = (2 * (sum     - s->qps[qpi]) * s->base_matrix[bmi][i] -
433                              2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
434                              s->qr_size[inter][plane][qri]) /
435                             (2 * s->qr_size[inter][plane][qri]);
436
437                 int qmin   = 8 << (inter + !i);
438                 int qscale = i ? ac_scale_factor : dc_scale_factor;
439                 int qbias = (1 + inter) * 3;
440                 s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
441                     (i == 0 || s->version < 2) ? av_clip((qscale * coeff) / 100 * 4, qmin, 4096)
442                                                : (qscale * (coeff - qbias) / 100 + qbias) * 4;
443             }
444             /* all DC coefficients use the same quant so as not to interfere
445              * with DC prediction */
446             s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
447         }
448     }
449 }
450
451 /*
452  * This function initializes the loop filter boundary limits if the frame's
453  * quality index is different from the previous frame's.
454  *
455  * The filter_limit_values may not be larger than 127.
456  */
457 static void init_loop_filter(Vp3DecodeContext *s)
458 {
459     ff_vp3dsp_set_bounding_values(s->bounding_values_array, s->filter_limit_values[s->qps[0]]);
460 }
461
462 /*
463  * This function unpacks all of the superblock/macroblock/fragment coding
464  * information from the bitstream.
465  */
466 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
467 {
468     int superblock_starts[3] = {
469         0, s->u_superblock_start, s->v_superblock_start
470     };
471     int bit = 0;
472     int current_superblock = 0;
473     int current_run = 0;
474     int num_partial_superblocks = 0;
475
476     int i, j;
477     int current_fragment;
478     int plane;
479     int plane0_num_coded_frags = 0;
480
481     if (s->keyframe) {
482         memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
483     } else {
484         /* unpack the list of partially-coded superblocks */
485         bit         = get_bits1(gb) ^ 1;
486         current_run = 0;
487
488         while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
489             if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
490                 bit = get_bits1(gb);
491             else
492                 bit ^= 1;
493
494             current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
495                                    SUPERBLOCK_VLC_BITS, 2);
496             if (current_run == 34)
497                 current_run += get_bits(gb, 12);
498
499             if (current_run > s->superblock_count - current_superblock) {
500                 av_log(s->avctx, AV_LOG_ERROR,
501                        "Invalid partially coded superblock run length\n");
502                 return -1;
503             }
504
505             memset(s->superblock_coding + current_superblock, bit, current_run);
506
507             current_superblock += current_run;
508             if (bit)
509                 num_partial_superblocks += current_run;
510         }
511
512         /* unpack the list of fully coded superblocks if any of the blocks were
513          * not marked as partially coded in the previous step */
514         if (num_partial_superblocks < s->superblock_count) {
515             int superblocks_decoded = 0;
516
517             current_superblock = 0;
518             bit                = get_bits1(gb) ^ 1;
519             current_run        = 0;
520
521             while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
522                    get_bits_left(gb) > 0) {
523                 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
524                     bit = get_bits1(gb);
525                 else
526                     bit ^= 1;
527
528                 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
529                                        SUPERBLOCK_VLC_BITS, 2);
530                 if (current_run == 34)
531                     current_run += get_bits(gb, 12);
532
533                 for (j = 0; j < current_run; current_superblock++) {
534                     if (current_superblock >= s->superblock_count) {
535                         av_log(s->avctx, AV_LOG_ERROR,
536                                "Invalid fully coded superblock run length\n");
537                         return -1;
538                     }
539
540                     /* skip any superblocks already marked as partially coded */
541                     if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
542                         s->superblock_coding[current_superblock] = 2 * bit;
543                         j++;
544                     }
545                 }
546                 superblocks_decoded += current_run;
547             }
548         }
549
550         /* if there were partial blocks, initialize bitstream for
551          * unpacking fragment codings */
552         if (num_partial_superblocks) {
553             current_run = 0;
554             bit         = get_bits1(gb);
555             /* toggle the bit because as soon as the first run length is
556              * fetched the bit will be toggled again */
557             bit ^= 1;
558         }
559     }
560
561     /* figure out which fragments are coded; iterate through each
562      * superblock (all planes) */
563     s->total_num_coded_frags = 0;
564     memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
565
566     s->coded_fragment_list[0] = s->keyframe ? s->kf_coded_fragment_list
567                                             : s->nkf_coded_fragment_list;
568
569     for (plane = 0; plane < 3; plane++) {
570         int sb_start = superblock_starts[plane];
571         int sb_end   = sb_start + (plane ? s->c_superblock_count
572                                          : s->y_superblock_count);
573         int num_coded_frags = 0;
574
575         if (s->keyframe) {
576             if (s->num_kf_coded_fragment[plane] == -1) {
577                 for (i = sb_start; i < sb_end; i++) {
578                     /* iterate through all 16 fragments in a superblock */
579                     for (j = 0; j < 16; j++) {
580                         /* if the fragment is in bounds, check its coding status */
581                         current_fragment = s->superblock_fragments[i * 16 + j];
582                         if (current_fragment != -1) {
583                             s->coded_fragment_list[plane][num_coded_frags++] =
584                                 current_fragment;
585                         }
586                     }
587                 }
588                 s->num_kf_coded_fragment[plane] = num_coded_frags;
589             } else
590                 num_coded_frags = s->num_kf_coded_fragment[plane];
591         } else {
592             for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
593                 if (get_bits_left(gb) < plane0_num_coded_frags >> 2) {
594                     return AVERROR_INVALIDDATA;
595                 }
596                 /* iterate through all 16 fragments in a superblock */
597                 for (j = 0; j < 16; j++) {
598                     /* if the fragment is in bounds, check its coding status */
599                     current_fragment = s->superblock_fragments[i * 16 + j];
600                     if (current_fragment != -1) {
601                         int coded = s->superblock_coding[i];
602
603                         if (coded == SB_PARTIALLY_CODED) {
604                             /* fragment may or may not be coded; this is the case
605                              * that cares about the fragment coding runs */
606                             if (current_run-- == 0) {
607                                 bit        ^= 1;
608                                 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
609                             }
610                             coded = bit;
611                         }
612
613                         if (coded) {
614                             /* default mode; actual mode will be decoded in
615                              * the next phase */
616                             s->all_fragments[current_fragment].coding_method =
617                                 MODE_INTER_NO_MV;
618                             s->coded_fragment_list[plane][num_coded_frags++] =
619                                 current_fragment;
620                         } else {
621                             /* not coded; copy this fragment from the prior frame */
622                             s->all_fragments[current_fragment].coding_method =
623                                 MODE_COPY;
624                         }
625                     }
626                 }
627             }
628         }
629         if (!plane)
630             plane0_num_coded_frags = num_coded_frags;
631         s->total_num_coded_frags += num_coded_frags;
632         for (i = 0; i < 64; i++)
633             s->num_coded_frags[plane][i] = num_coded_frags;
634         if (plane < 2)
635             s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
636                                                 num_coded_frags;
637     }
638     return 0;
639 }
640
641 #define BLOCK_X (2 * mb_x + (k & 1))
642 #define BLOCK_Y (2 * mb_y + (k >> 1))
643
644 #if CONFIG_VP4_DECODER
645 /**
646  * @return number of blocks, or > yuv_macroblock_count on error.
647  *         return value is always >= 1.
648  */
649 static int vp4_get_mb_count(Vp3DecodeContext *s, GetBitContext *gb)
650 {
651     int v = 1;
652     int bits;
653     while ((bits = show_bits(gb, 9)) == 0x1ff) {
654         skip_bits(gb, 9);
655         v += 256;
656         if (v > s->yuv_macroblock_count) {
657             av_log(s->avctx, AV_LOG_ERROR, "Invalid run length\n");
658             return v;
659         }
660     }
661 #define body(n) { \
662     skip_bits(gb, 2 + n); \
663     v += (1 << n) + get_bits(gb, n); }
664 #define thresh(n) (0x200 - (0x80 >> n))
665 #define else_if(n) else if (bits < thresh(n)) body(n)
666     if (bits < 0x100) {
667         skip_bits(gb, 1);
668     } else if (bits < thresh(0)) {
669         skip_bits(gb, 2);
670         v += 1;
671     }
672     else_if(1)
673     else_if(2)
674     else_if(3)
675     else_if(4)
676     else_if(5)
677     else_if(6)
678     else body(7)
679 #undef body
680 #undef thresh
681 #undef else_if
682     return v;
683 }
684
685 static int vp4_get_block_pattern(Vp3DecodeContext *s, GetBitContext *gb, int *next_block_pattern_table)
686 {
687     int v = get_vlc2(gb, s->block_pattern_vlc[*next_block_pattern_table].table, 3, 2);
688     *next_block_pattern_table = vp4_block_pattern_table_selector[v];
689     return v + 1;
690 }
691
692 static int vp4_unpack_macroblocks(Vp3DecodeContext *s, GetBitContext *gb)
693 {
694     int plane, i, j, k, fragment;
695     int next_block_pattern_table;
696     int bit, current_run, has_partial;
697
698     memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
699
700     if (s->keyframe)
701         return 0;
702
703     has_partial = 0;
704     bit         = get_bits1(gb);
705     for (i = 0; i < s->yuv_macroblock_count; i += current_run) {
706         if (get_bits_left(gb) <= 0)
707             return AVERROR_INVALIDDATA;
708         current_run = vp4_get_mb_count(s, gb);
709         if (current_run > s->yuv_macroblock_count - i)
710             return -1;
711         memset(s->superblock_coding + i, 2 * bit, current_run);
712         bit ^= 1;
713         has_partial |= bit;
714     }
715
716     if (has_partial) {
717         if (get_bits_left(gb) <= 0)
718             return AVERROR_INVALIDDATA;
719         bit  = get_bits1(gb);
720         current_run = vp4_get_mb_count(s, gb);
721         for (i = 0; i < s->yuv_macroblock_count; i++) {
722             if (!s->superblock_coding[i]) {
723                 if (!current_run) {
724                     bit ^= 1;
725                     current_run = vp4_get_mb_count(s, gb);
726                 }
727                 s->superblock_coding[i] = bit;
728                 current_run--;
729             }
730         }
731         if (current_run) /* handle situation when vp4_get_mb_count() fails */
732             return -1;
733     }
734
735     next_block_pattern_table = 0;
736     i = 0;
737     for (plane = 0; plane < 3; plane++) {
738         int sb_x, sb_y;
739         int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
740         int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
741         int mb_width = plane ? s->c_macroblock_width : s->macroblock_width;
742         int mb_height = plane ? s->c_macroblock_height : s->macroblock_height;
743         int fragment_width = s->fragment_width[!!plane];
744         int fragment_height = s->fragment_height[!!plane];
745
746         for (sb_y = 0; sb_y < sb_height; sb_y++) {
747             for (sb_x = 0; sb_x < sb_width; sb_x++) {
748                 for (j = 0; j < 4; j++) {
749                     int mb_x = 2 * sb_x + (j >> 1);
750                     int mb_y = 2 * sb_y + (j >> 1) ^ (j & 1);
751                     int mb_coded, pattern, coded;
752
753                     if (mb_x >= mb_width || mb_y >= mb_height)
754                         continue;
755
756                     mb_coded = s->superblock_coding[i++];
757
758                     if (mb_coded == SB_FULLY_CODED)
759                         pattern = 0xF;
760                     else if (mb_coded == SB_PARTIALLY_CODED)
761                         pattern = vp4_get_block_pattern(s, gb, &next_block_pattern_table);
762                     else
763                         pattern = 0;
764
765                     for (k = 0; k < 4; k++) {
766                         if (BLOCK_X >= fragment_width || BLOCK_Y >= fragment_height)
767                             continue;
768                         fragment = s->fragment_start[plane] + BLOCK_Y * fragment_width + BLOCK_X;
769                         coded = pattern & (8 >> k);
770                         /* MODE_INTER_NO_MV is the default for coded fragments.
771                            the actual method is decoded in the next phase. */
772                         s->all_fragments[fragment].coding_method = coded ? MODE_INTER_NO_MV : MODE_COPY;
773                     }
774                 }
775             }
776         }
777     }
778     return 0;
779 }
780 #endif
781
782 /*
783  * This function unpacks all the coding mode data for individual macroblocks
784  * from the bitstream.
785  */
786 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
787 {
788     int i, j, k, sb_x, sb_y;
789     int scheme;
790     int current_macroblock;
791     int current_fragment;
792     int coding_mode;
793     int custom_mode_alphabet[CODING_MODE_COUNT];
794     const int *alphabet;
795     Vp3Fragment *frag;
796
797     if (s->keyframe) {
798         for (i = 0; i < s->fragment_count; i++)
799             s->all_fragments[i].coding_method = MODE_INTRA;
800     } else {
801         /* fetch the mode coding scheme for this frame */
802         scheme = get_bits(gb, 3);
803
804         /* is it a custom coding scheme? */
805         if (scheme == 0) {
806             for (i = 0; i < 8; i++)
807                 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
808             for (i = 0; i < 8; i++)
809                 custom_mode_alphabet[get_bits(gb, 3)] = i;
810             alphabet = custom_mode_alphabet;
811         } else
812             alphabet = ModeAlphabet[scheme - 1];
813
814         /* iterate through all of the macroblocks that contain 1 or more
815          * coded fragments */
816         for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
817             for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
818                 if (get_bits_left(gb) <= 0)
819                     return -1;
820
821                 for (j = 0; j < 4; j++) {
822                     int mb_x = 2 * sb_x + (j >> 1);
823                     int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
824                     current_macroblock = mb_y * s->macroblock_width + mb_x;
825
826                     if (mb_x >= s->macroblock_width ||
827                         mb_y >= s->macroblock_height)
828                         continue;
829
830                     /* coding modes are only stored if the macroblock has
831                      * at least one luma block coded, otherwise it must be
832                      * INTER_NO_MV */
833                     for (k = 0; k < 4; k++) {
834                         current_fragment = BLOCK_Y *
835                                            s->fragment_width[0] + BLOCK_X;
836                         if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
837                             break;
838                     }
839                     if (k == 4) {
840                         s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
841                         continue;
842                     }
843
844                     /* mode 7 means get 3 bits for each coding mode */
845                     if (scheme == 7)
846                         coding_mode = get_bits(gb, 3);
847                     else
848                         coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
849
850                     s->macroblock_coding[current_macroblock] = coding_mode;
851                     for (k = 0; k < 4; k++) {
852                         frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
853                         if (frag->coding_method != MODE_COPY)
854                             frag->coding_method = coding_mode;
855                     }
856
857 #define SET_CHROMA_MODES                                                      \
858     if (frag[s->fragment_start[1]].coding_method != MODE_COPY)                \
859         frag[s->fragment_start[1]].coding_method = coding_mode;               \
860     if (frag[s->fragment_start[2]].coding_method != MODE_COPY)                \
861         frag[s->fragment_start[2]].coding_method = coding_mode;
862
863                     if (s->chroma_y_shift) {
864                         frag = s->all_fragments + mb_y *
865                                s->fragment_width[1] + mb_x;
866                         SET_CHROMA_MODES
867                     } else if (s->chroma_x_shift) {
868                         frag = s->all_fragments +
869                                2 * mb_y * s->fragment_width[1] + mb_x;
870                         for (k = 0; k < 2; k++) {
871                             SET_CHROMA_MODES
872                             frag += s->fragment_width[1];
873                         }
874                     } else {
875                         for (k = 0; k < 4; k++) {
876                             frag = s->all_fragments +
877                                    BLOCK_Y * s->fragment_width[1] + BLOCK_X;
878                             SET_CHROMA_MODES
879                         }
880                     }
881                 }
882             }
883         }
884     }
885
886     return 0;
887 }
888
889 static int vp4_get_mv(Vp3DecodeContext *s, GetBitContext *gb, int axis, int last_motion)
890 {
891     int v = get_vlc2(gb, s->vp4_mv_vlc[axis][vp4_mv_table_selector[FFABS(last_motion)]].table,
892                      VP4_MV_VLC_BITS, 2);
893     return last_motion < 0 ? -v : v;
894 }
895
896 /*
897  * This function unpacks all the motion vectors for the individual
898  * macroblocks from the bitstream.
899  */
900 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
901 {
902     int j, k, sb_x, sb_y;
903     int coding_mode;
904     int motion_x[4];
905     int motion_y[4];
906     int last_motion_x = 0;
907     int last_motion_y = 0;
908     int prior_last_motion_x = 0;
909     int prior_last_motion_y = 0;
910     int last_gold_motion_x = 0;
911     int last_gold_motion_y = 0;
912     int current_macroblock;
913     int current_fragment;
914     int frag;
915
916     if (s->keyframe)
917         return 0;
918
919     /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme; 2 is VP4 code scheme */
920     coding_mode = s->version < 2 ? get_bits1(gb) : 2;
921
922     /* iterate through all of the macroblocks that contain 1 or more
923      * coded fragments */
924     for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
925         for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
926             if (get_bits_left(gb) <= 0)
927                 return -1;
928
929             for (j = 0; j < 4; j++) {
930                 int mb_x = 2 * sb_x + (j >> 1);
931                 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
932                 current_macroblock = mb_y * s->macroblock_width + mb_x;
933
934                 if (mb_x >= s->macroblock_width  ||
935                     mb_y >= s->macroblock_height ||
936                     s->macroblock_coding[current_macroblock] == MODE_COPY)
937                     continue;
938
939                 switch (s->macroblock_coding[current_macroblock]) {
940                 case MODE_GOLDEN_MV:
941                     if (coding_mode == 2) { /* VP4 */
942                         last_gold_motion_x = motion_x[0] = vp4_get_mv(s, gb, 0, last_gold_motion_x);
943                         last_gold_motion_y = motion_y[0] = vp4_get_mv(s, gb, 1, last_gold_motion_y);
944                         break;
945                     } /* otherwise fall through */
946                 case MODE_INTER_PLUS_MV:
947                     /* all 6 fragments use the same motion vector */
948                     if (coding_mode == 0) {
949                         motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
950                         motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
951                     } else if (coding_mode == 1) {
952                         motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
953                         motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
954                     } else { /* VP4 */
955                         motion_x[0] = vp4_get_mv(s, gb, 0, last_motion_x);
956                         motion_y[0] = vp4_get_mv(s, gb, 1, last_motion_y);
957                     }
958
959                     /* vector maintenance, only on MODE_INTER_PLUS_MV */
960                     if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
961                         prior_last_motion_x = last_motion_x;
962                         prior_last_motion_y = last_motion_y;
963                         last_motion_x       = motion_x[0];
964                         last_motion_y       = motion_y[0];
965                     }
966                     break;
967
968                 case MODE_INTER_FOURMV:
969                     /* vector maintenance */
970                     prior_last_motion_x = last_motion_x;
971                     prior_last_motion_y = last_motion_y;
972
973                     /* fetch 4 vectors from the bitstream, one for each
974                      * Y fragment, then average for the C fragment vectors */
975                     for (k = 0; k < 4; k++) {
976                         current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
977                         if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
978                             if (coding_mode == 0) {
979                                 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
980                                 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
981                             } else if (coding_mode == 1) {
982                                 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
983                                 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
984                             } else { /* VP4 */
985                                 motion_x[k] = vp4_get_mv(s, gb, 0, prior_last_motion_x);
986                                 motion_y[k] = vp4_get_mv(s, gb, 1, prior_last_motion_y);
987                             }
988                             last_motion_x = motion_x[k];
989                             last_motion_y = motion_y[k];
990                         } else {
991                             motion_x[k] = 0;
992                             motion_y[k] = 0;
993                         }
994                     }
995                     break;
996
997                 case MODE_INTER_LAST_MV:
998                     /* all 6 fragments use the last motion vector */
999                     motion_x[0] = last_motion_x;
1000                     motion_y[0] = last_motion_y;
1001
1002                     /* no vector maintenance (last vector remains the
1003                      * last vector) */
1004                     break;
1005
1006                 case MODE_INTER_PRIOR_LAST:
1007                     /* all 6 fragments use the motion vector prior to the
1008                      * last motion vector */
1009                     motion_x[0] = prior_last_motion_x;
1010                     motion_y[0] = prior_last_motion_y;
1011
1012                     /* vector maintenance */
1013                     prior_last_motion_x = last_motion_x;
1014                     prior_last_motion_y = last_motion_y;
1015                     last_motion_x       = motion_x[0];
1016                     last_motion_y       = motion_y[0];
1017                     break;
1018
1019                 default:
1020                     /* covers intra, inter without MV, golden without MV */
1021                     motion_x[0] = 0;
1022                     motion_y[0] = 0;
1023
1024                     /* no vector maintenance */
1025                     break;
1026                 }
1027
1028                 /* assign the motion vectors to the correct fragments */
1029                 for (k = 0; k < 4; k++) {
1030                     current_fragment =
1031                         BLOCK_Y * s->fragment_width[0] + BLOCK_X;
1032                     if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1033                         s->motion_val[0][current_fragment][0] = motion_x[k];
1034                         s->motion_val[0][current_fragment][1] = motion_y[k];
1035                     } else {
1036                         s->motion_val[0][current_fragment][0] = motion_x[0];
1037                         s->motion_val[0][current_fragment][1] = motion_y[0];
1038                     }
1039                 }
1040
1041                 if (s->chroma_y_shift) {
1042                     if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1043                         motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
1044                                              motion_x[2] + motion_x[3], 2);
1045                         motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
1046                                              motion_y[2] + motion_y[3], 2);
1047                     }
1048                     if (s->version <= 2) {
1049                         motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1050                         motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
1051                     }
1052                     frag = mb_y * s->fragment_width[1] + mb_x;
1053                     s->motion_val[1][frag][0] = motion_x[0];
1054                     s->motion_val[1][frag][1] = motion_y[0];
1055                 } else if (s->chroma_x_shift) {
1056                     if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1057                         motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
1058                         motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
1059                         motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
1060                         motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
1061                     } else {
1062                         motion_x[1] = motion_x[0];
1063                         motion_y[1] = motion_y[0];
1064                     }
1065                     if (s->version <= 2) {
1066                         motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1067                         motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
1068                     }
1069                     frag = 2 * mb_y * s->fragment_width[1] + mb_x;
1070                     for (k = 0; k < 2; k++) {
1071                         s->motion_val[1][frag][0] = motion_x[k];
1072                         s->motion_val[1][frag][1] = motion_y[k];
1073                         frag += s->fragment_width[1];
1074                     }
1075                 } else {
1076                     for (k = 0; k < 4; k++) {
1077                         frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
1078                         if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1079                             s->motion_val[1][frag][0] = motion_x[k];
1080                             s->motion_val[1][frag][1] = motion_y[k];
1081                         } else {
1082                             s->motion_val[1][frag][0] = motion_x[0];
1083                             s->motion_val[1][frag][1] = motion_y[0];
1084                         }
1085                     }
1086                 }
1087             }
1088         }
1089     }
1090
1091     return 0;
1092 }
1093
1094 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
1095 {
1096     int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
1097     int num_blocks = s->total_num_coded_frags;
1098
1099     for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
1100         i = blocks_decoded = num_blocks_at_qpi = 0;
1101
1102         bit        = get_bits1(gb) ^ 1;
1103         run_length = 0;
1104
1105         do {
1106             if (run_length == MAXIMUM_LONG_BIT_RUN)
1107                 bit = get_bits1(gb);
1108             else
1109                 bit ^= 1;
1110
1111             run_length = get_vlc2(gb, s->superblock_run_length_vlc.table,
1112                                   SUPERBLOCK_VLC_BITS, 2);
1113             if (run_length == 34)
1114                 run_length += get_bits(gb, 12);
1115             blocks_decoded += run_length;
1116
1117             if (!bit)
1118                 num_blocks_at_qpi += run_length;
1119
1120             for (j = 0; j < run_length; i++) {
1121                 if (i >= s->total_num_coded_frags)
1122                     return -1;
1123
1124                 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
1125                     s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
1126                     j++;
1127                 }
1128             }
1129         } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
1130
1131         num_blocks -= num_blocks_at_qpi;
1132     }
1133
1134     return 0;
1135 }
1136
1137 static inline int get_eob_run(GetBitContext *gb, int token)
1138 {
1139     int v = eob_run_table[token].base;
1140     if (eob_run_table[token].bits)
1141         v += get_bits(gb, eob_run_table[token].bits);
1142     return v;
1143 }
1144
1145 static inline int get_coeff(GetBitContext *gb, int token, int16_t *coeff)
1146 {
1147     int bits_to_get, zero_run;
1148
1149     bits_to_get = coeff_get_bits[token];
1150     if (bits_to_get)
1151         bits_to_get = get_bits(gb, bits_to_get);
1152     *coeff = coeff_tables[token][bits_to_get];
1153
1154     zero_run = zero_run_base[token];
1155     if (zero_run_get_bits[token])
1156         zero_run += get_bits(gb, zero_run_get_bits[token]);
1157
1158     return zero_run;
1159 }
1160
1161 /*
1162  * This function is called by unpack_dct_coeffs() to extract the VLCs from
1163  * the bitstream. The VLCs encode tokens which are used to unpack DCT
1164  * data. This function unpacks all the VLCs for either the Y plane or both
1165  * C planes, and is called for DC coefficients or different AC coefficient
1166  * levels (since different coefficient types require different VLC tables.
1167  *
1168  * This function returns a residual eob run. E.g, if a particular token gave
1169  * instructions to EOB the next 5 fragments and there were only 2 fragments
1170  * left in the current fragment range, 3 would be returned so that it could
1171  * be passed into the next call to this same function.
1172  */
1173 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1174                        VLC *table, int coeff_index,
1175                        int plane,
1176                        int eob_run)
1177 {
1178     int i, j = 0;
1179     int token;
1180     int zero_run  = 0;
1181     int16_t coeff = 0;
1182     int blocks_ended;
1183     int coeff_i = 0;
1184     int num_coeffs      = s->num_coded_frags[plane][coeff_index];
1185     int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
1186
1187     /* local references to structure members to avoid repeated dereferences */
1188     int *coded_fragment_list   = s->coded_fragment_list[plane];
1189     Vp3Fragment *all_fragments = s->all_fragments;
1190     VLC_TYPE(*vlc_table)[2] = table->table;
1191
1192     if (num_coeffs < 0) {
1193         av_log(s->avctx, AV_LOG_ERROR,
1194                "Invalid number of coefficients at level %d\n", coeff_index);
1195         return AVERROR_INVALIDDATA;
1196     }
1197
1198     if (eob_run > num_coeffs) {
1199         coeff_i      =
1200         blocks_ended = num_coeffs;
1201         eob_run     -= num_coeffs;
1202     } else {
1203         coeff_i      =
1204         blocks_ended = eob_run;
1205         eob_run      = 0;
1206     }
1207
1208     // insert fake EOB token to cover the split between planes or zzi
1209     if (blocks_ended)
1210         dct_tokens[j++] = blocks_ended << 2;
1211
1212     while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1213         /* decode a VLC into a token */
1214         token = get_vlc2(gb, vlc_table, 11, 3);
1215         /* use the token to get a zero run, a coefficient, and an eob run */
1216         if ((unsigned) token <= 6U) {
1217             eob_run = get_eob_run(gb, token);
1218             if (!eob_run)
1219                 eob_run = INT_MAX;
1220
1221             // record only the number of blocks ended in this plane,
1222             // any spill will be recorded in the next plane.
1223             if (eob_run > num_coeffs - coeff_i) {
1224                 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1225                 blocks_ended   += num_coeffs - coeff_i;
1226                 eob_run        -= num_coeffs - coeff_i;
1227                 coeff_i         = num_coeffs;
1228             } else {
1229                 dct_tokens[j++] = TOKEN_EOB(eob_run);
1230                 blocks_ended   += eob_run;
1231                 coeff_i        += eob_run;
1232                 eob_run         = 0;
1233             }
1234         } else if (token >= 0) {
1235             zero_run = get_coeff(gb, token, &coeff);
1236
1237             if (zero_run) {
1238                 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1239             } else {
1240                 // Save DC into the fragment structure. DC prediction is
1241                 // done in raster order, so the actual DC can't be in with
1242                 // other tokens. We still need the token in dct_tokens[]
1243                 // however, or else the structure collapses on itself.
1244                 if (!coeff_index)
1245                     all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1246
1247                 dct_tokens[j++] = TOKEN_COEFF(coeff);
1248             }
1249
1250             if (coeff_index + zero_run > 64) {
1251                 av_log(s->avctx, AV_LOG_DEBUG,
1252                        "Invalid zero run of %d with %d coeffs left\n",
1253                        zero_run, 64 - coeff_index);
1254                 zero_run = 64 - coeff_index;
1255             }
1256
1257             // zero runs code multiple coefficients,
1258             // so don't try to decode coeffs for those higher levels
1259             for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1260                 s->num_coded_frags[plane][i]--;
1261             coeff_i++;
1262         } else {
1263             av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1264             return -1;
1265         }
1266     }
1267
1268     if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1269         av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1270
1271     // decrement the number of blocks that have higher coefficients for each
1272     // EOB run at this level
1273     if (blocks_ended)
1274         for (i = coeff_index + 1; i < 64; i++)
1275             s->num_coded_frags[plane][i] -= blocks_ended;
1276
1277     // setup the next buffer
1278     if (plane < 2)
1279         s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1280     else if (coeff_index < 63)
1281         s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1282
1283     return eob_run;
1284 }
1285
1286 static void reverse_dc_prediction(Vp3DecodeContext *s,
1287                                   int first_fragment,
1288                                   int fragment_width,
1289                                   int fragment_height);
1290 /*
1291  * This function unpacks all of the DCT coefficient data from the
1292  * bitstream.
1293  */
1294 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1295 {
1296     int i;
1297     int dc_y_table;
1298     int dc_c_table;
1299     int ac_y_table;
1300     int ac_c_table;
1301     int residual_eob_run = 0;
1302     VLC *y_tables[64];
1303     VLC *c_tables[64];
1304
1305     s->dct_tokens[0][0] = s->dct_tokens_base;
1306
1307     if (get_bits_left(gb) < 16)
1308         return AVERROR_INVALIDDATA;
1309
1310     /* fetch the DC table indexes */
1311     dc_y_table = get_bits(gb, 4);
1312     dc_c_table = get_bits(gb, 4);
1313
1314     /* unpack the Y plane DC coefficients */
1315     residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_y_table], 0,
1316                                    0, residual_eob_run);
1317     if (residual_eob_run < 0)
1318         return residual_eob_run;
1319     if (get_bits_left(gb) < 8)
1320         return AVERROR_INVALIDDATA;
1321
1322     /* reverse prediction of the Y-plane DC coefficients */
1323     reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1324
1325     /* unpack the C plane DC coefficients */
1326     residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1327                                    1, residual_eob_run);
1328     if (residual_eob_run < 0)
1329         return residual_eob_run;
1330     residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1331                                    2, residual_eob_run);
1332     if (residual_eob_run < 0)
1333         return residual_eob_run;
1334
1335     /* reverse prediction of the C-plane DC coefficients */
1336     if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1337         reverse_dc_prediction(s, s->fragment_start[1],
1338                               s->fragment_width[1], s->fragment_height[1]);
1339         reverse_dc_prediction(s, s->fragment_start[2],
1340                               s->fragment_width[1], s->fragment_height[1]);
1341     }
1342
1343     if (get_bits_left(gb) < 8)
1344         return AVERROR_INVALIDDATA;
1345     /* fetch the AC table indexes */
1346     ac_y_table = get_bits(gb, 4);
1347     ac_c_table = get_bits(gb, 4);
1348
1349     /* build tables of AC VLC tables */
1350     for (i = 1; i <= 5; i++) {
1351         /* AC VLC table group 1 */
1352         y_tables[i] = &s->coeff_vlc[ac_y_table + 16];
1353         c_tables[i] = &s->coeff_vlc[ac_c_table + 16];
1354     }
1355     for (i = 6; i <= 14; i++) {
1356         /* AC VLC table group 2 */
1357         y_tables[i] = &s->coeff_vlc[ac_y_table + 32];
1358         c_tables[i] = &s->coeff_vlc[ac_c_table + 32];
1359     }
1360     for (i = 15; i <= 27; i++) {
1361         /* AC VLC table group 3 */
1362         y_tables[i] = &s->coeff_vlc[ac_y_table + 48];
1363         c_tables[i] = &s->coeff_vlc[ac_c_table + 48];
1364     }
1365     for (i = 28; i <= 63; i++) {
1366         /* AC VLC table group 4 */
1367         y_tables[i] = &s->coeff_vlc[ac_y_table + 64];
1368         c_tables[i] = &s->coeff_vlc[ac_c_table + 64];
1369     }
1370
1371     /* decode all AC coefficients */
1372     for (i = 1; i <= 63; i++) {
1373         residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1374                                        0, residual_eob_run);
1375         if (residual_eob_run < 0)
1376             return residual_eob_run;
1377
1378         residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1379                                        1, residual_eob_run);
1380         if (residual_eob_run < 0)
1381             return residual_eob_run;
1382         residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1383                                        2, residual_eob_run);
1384         if (residual_eob_run < 0)
1385             return residual_eob_run;
1386     }
1387
1388     return 0;
1389 }
1390
1391 #if CONFIG_VP4_DECODER
1392 /**
1393  * eob_tracker[] is instead of TOKEN_EOB(value)
1394  * a dummy TOKEN_EOB(0) value is used to make vp3_dequant work
1395  *
1396  * @return < 0 on error
1397  */
1398 static int vp4_unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1399                        VLC *vlc_tables[64],
1400                        int plane, int eob_tracker[64], int fragment)
1401 {
1402     int token;
1403     int zero_run  = 0;
1404     int16_t coeff = 0;
1405     int coeff_i = 0;
1406     int eob_run;
1407
1408     while (!eob_tracker[coeff_i]) {
1409         if (get_bits_left(gb) < 1)
1410             return AVERROR_INVALIDDATA;
1411
1412         token = get_vlc2(gb, vlc_tables[coeff_i]->table, 11, 3);
1413
1414         /* use the token to get a zero run, a coefficient, and an eob run */
1415         if ((unsigned) token <= 6U) {
1416             eob_run = get_eob_run(gb, token);
1417             *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1418             eob_tracker[coeff_i] = eob_run - 1;
1419             return 0;
1420         } else if (token >= 0) {
1421             zero_run = get_coeff(gb, token, &coeff);
1422
1423             if (zero_run) {
1424                 if (coeff_i + zero_run > 64) {
1425                     av_log(s->avctx, AV_LOG_DEBUG,
1426                         "Invalid zero run of %d with %d coeffs left\n",
1427                         zero_run, 64 - coeff_i);
1428                     zero_run = 64 - coeff_i;
1429                 }
1430                 *s->dct_tokens[plane][coeff_i]++ = TOKEN_ZERO_RUN(coeff, zero_run);
1431                 coeff_i += zero_run;
1432             } else {
1433                 if (!coeff_i)
1434                     s->all_fragments[fragment].dc = coeff;
1435
1436                 *s->dct_tokens[plane][coeff_i]++ = TOKEN_COEFF(coeff);
1437             }
1438             coeff_i++;
1439             if (coeff_i >= 64) /* > 64 occurs when there is a zero_run overflow */
1440                 return 0; /* stop */
1441         } else {
1442             av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1443             return -1;
1444         }
1445     }
1446     *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1447     eob_tracker[coeff_i]--;
1448     return 0;
1449 }
1450
1451 static void vp4_dc_predictor_reset(VP4Predictor *p)
1452 {
1453     p->dc = 0;
1454     p->type = VP4_DC_UNDEFINED;
1455 }
1456
1457 static void vp4_dc_pred_before(const Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1458 {
1459     int i, j;
1460
1461     for (i = 0; i < 4; i++)
1462         dc_pred[0][i + 1] = s->dc_pred_row[sb_x * 4 + i];
1463
1464     for (j = 1; j < 5; j++)
1465         for (i = 0; i < 4; i++)
1466             vp4_dc_predictor_reset(&dc_pred[j][i + 1]);
1467 }
1468
1469 static void vp4_dc_pred_after(Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1470 {
1471     int i;
1472
1473     for (i = 0; i < 4; i++)
1474         s->dc_pred_row[sb_x * 4 + i] = dc_pred[4][i + 1];
1475
1476     for (i = 1; i < 5; i++)
1477         dc_pred[i][0] = dc_pred[i][4];
1478 }
1479
1480 /* note: dc_pred points to the current block */
1481 static int vp4_dc_pred(const Vp3DecodeContext *s, const VP4Predictor * dc_pred, const int * last_dc, int type, int plane)
1482 {
1483     int count = 0;
1484     int dc = 0;
1485
1486     if (dc_pred[-6].type == type) {
1487         dc += dc_pred[-6].dc;
1488         count++;
1489     }
1490
1491     if (dc_pred[6].type == type) {
1492         dc += dc_pred[6].dc;
1493         count++;
1494     }
1495
1496     if (count != 2 && dc_pred[-1].type == type) {
1497         dc += dc_pred[-1].dc;
1498         count++;
1499     }
1500
1501     if (count != 2 && dc_pred[1].type == type) {
1502         dc += dc_pred[1].dc;
1503         count++;
1504     }
1505
1506     /* using division instead of shift to correctly handle negative values */
1507     return count == 2 ? dc / 2 : last_dc[type];
1508 }
1509
1510 static void vp4_set_tokens_base(Vp3DecodeContext *s)
1511 {
1512     int plane, i;
1513     int16_t *base = s->dct_tokens_base;
1514     for (plane = 0; plane < 3; plane++) {
1515         for (i = 0; i < 64; i++) {
1516             s->dct_tokens[plane][i] = base;
1517             base += s->fragment_width[!!plane] * s->fragment_height[!!plane];
1518         }
1519     }
1520 }
1521
1522 static int vp4_unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1523 {
1524     int i, j;
1525     int dc_y_table;
1526     int dc_c_table;
1527     int ac_y_table;
1528     int ac_c_table;
1529     VLC *tables[2][64];
1530     int plane, sb_y, sb_x;
1531     int eob_tracker[64];
1532     VP4Predictor dc_pred[6][6];
1533     int last_dc[NB_VP4_DC_TYPES];
1534
1535     if (get_bits_left(gb) < 16)
1536         return AVERROR_INVALIDDATA;
1537
1538     /* fetch the DC table indexes */
1539     dc_y_table = get_bits(gb, 4);
1540     dc_c_table = get_bits(gb, 4);
1541
1542     ac_y_table = get_bits(gb, 4);
1543     ac_c_table = get_bits(gb, 4);
1544
1545     /* build tables of DC/AC VLC tables */
1546
1547     /* DC table group */
1548     tables[0][0] = &s->coeff_vlc[dc_y_table];
1549     tables[1][0] = &s->coeff_vlc[dc_c_table];
1550     for (i = 1; i <= 5; i++) {
1551         /* AC VLC table group 1 */
1552         tables[0][i] = &s->coeff_vlc[ac_y_table + 16];
1553         tables[1][i] = &s->coeff_vlc[ac_c_table + 16];
1554     }
1555     for (i = 6; i <= 14; i++) {
1556         /* AC VLC table group 2 */
1557         tables[0][i] = &s->coeff_vlc[ac_y_table + 32];
1558         tables[1][i] = &s->coeff_vlc[ac_c_table + 32];
1559     }
1560     for (i = 15; i <= 27; i++) {
1561         /* AC VLC table group 3 */
1562         tables[0][i] = &s->coeff_vlc[ac_y_table + 48];
1563         tables[1][i] = &s->coeff_vlc[ac_c_table + 48];
1564     }
1565     for (i = 28; i <= 63; i++) {
1566         /* AC VLC table group 4 */
1567         tables[0][i] = &s->coeff_vlc[ac_y_table + 64];
1568         tables[1][i] = &s->coeff_vlc[ac_c_table + 64];
1569     }
1570
1571     vp4_set_tokens_base(s);
1572
1573     memset(last_dc, 0, sizeof(last_dc));
1574
1575     for (plane = 0; plane < ((s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 1 : 3); plane++) {
1576         memset(eob_tracker, 0, sizeof(eob_tracker));
1577
1578         /* initialise dc prediction */
1579         for (i = 0; i < s->fragment_width[!!plane]; i++)
1580             vp4_dc_predictor_reset(&s->dc_pred_row[i]);
1581
1582         for (j = 0; j < 6; j++)
1583             for (i = 0; i < 6; i++)
1584                 vp4_dc_predictor_reset(&dc_pred[j][i]);
1585
1586         for (sb_y = 0; sb_y * 4 < s->fragment_height[!!plane]; sb_y++) {
1587             for (sb_x = 0; sb_x *4 < s->fragment_width[!!plane]; sb_x++) {
1588                 vp4_dc_pred_before(s, dc_pred, sb_x);
1589                 for (j = 0; j < 16; j++) {
1590                         int hx = hilbert_offset[j][0];
1591                         int hy = hilbert_offset[j][1];
1592                         int x  = 4 * sb_x + hx;
1593                         int y  = 4 * sb_y + hy;
1594                         VP4Predictor *this_dc_pred = &dc_pred[hy + 1][hx + 1];
1595                         int fragment, dc_block_type;
1596
1597                         if (x >= s->fragment_width[!!plane] || y >= s->fragment_height[!!plane])
1598                             continue;
1599
1600                         fragment = s->fragment_start[plane] + y * s->fragment_width[!!plane] + x;
1601
1602                         if (s->all_fragments[fragment].coding_method == MODE_COPY)
1603                             continue;
1604
1605                         if (vp4_unpack_vlcs(s, gb, tables[!!plane], plane, eob_tracker, fragment) < 0)
1606                             return -1;
1607
1608                         dc_block_type = vp4_pred_block_type_map[s->all_fragments[fragment].coding_method];
1609
1610                         s->all_fragments[fragment].dc +=
1611                             vp4_dc_pred(s, this_dc_pred, last_dc, dc_block_type, plane);
1612
1613                         this_dc_pred->type = dc_block_type,
1614                         this_dc_pred->dc   = last_dc[dc_block_type] = s->all_fragments[fragment].dc;
1615                 }
1616                 vp4_dc_pred_after(s, dc_pred, sb_x);
1617             }
1618         }
1619     }
1620
1621     vp4_set_tokens_base(s);
1622
1623     return 0;
1624 }
1625 #endif
1626
1627 /*
1628  * This function reverses the DC prediction for each coded fragment in
1629  * the frame. Much of this function is adapted directly from the original
1630  * VP3 source code.
1631  */
1632 #define COMPATIBLE_FRAME(x)                                                   \
1633     (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1634 #define DC_COEFF(u) s->all_fragments[u].dc
1635
1636 static void reverse_dc_prediction(Vp3DecodeContext *s,
1637                                   int first_fragment,
1638                                   int fragment_width,
1639                                   int fragment_height)
1640 {
1641 #define PUL 8
1642 #define PU 4
1643 #define PUR 2
1644 #define PL 1
1645
1646     int x, y;
1647     int i = first_fragment;
1648
1649     int predicted_dc;
1650
1651     /* DC values for the left, up-left, up, and up-right fragments */
1652     int vl, vul, vu, vur;
1653
1654     /* indexes for the left, up-left, up, and up-right fragments */
1655     int l, ul, u, ur;
1656
1657     /*
1658      * The 6 fields mean:
1659      *   0: up-left multiplier
1660      *   1: up multiplier
1661      *   2: up-right multiplier
1662      *   3: left multiplier
1663      */
1664     static const int predictor_transform[16][4] = {
1665         {    0,   0,   0,   0 },
1666         {    0,   0,   0, 128 }, // PL
1667         {    0,   0, 128,   0 }, // PUR
1668         {    0,   0,  53,  75 }, // PUR|PL
1669         {    0, 128,   0,   0 }, // PU
1670         {    0,  64,   0,  64 }, // PU |PL
1671         {    0, 128,   0,   0 }, // PU |PUR
1672         {    0,   0,  53,  75 }, // PU |PUR|PL
1673         {  128,   0,   0,   0 }, // PUL
1674         {    0,   0,   0, 128 }, // PUL|PL
1675         {   64,   0,  64,   0 }, // PUL|PUR
1676         {    0,   0,  53,  75 }, // PUL|PUR|PL
1677         {    0, 128,   0,   0 }, // PUL|PU
1678         { -104, 116,   0, 116 }, // PUL|PU |PL
1679         {   24,  80,  24,   0 }, // PUL|PU |PUR
1680         { -104, 116,   0, 116 }  // PUL|PU |PUR|PL
1681     };
1682
1683     /* This table shows which types of blocks can use other blocks for
1684      * prediction. For example, INTRA is the only mode in this table to
1685      * have a frame number of 0. That means INTRA blocks can only predict
1686      * from other INTRA blocks. There are 2 golden frame coding types;
1687      * blocks encoding in these modes can only predict from other blocks
1688      * that were encoded with these 1 of these 2 modes. */
1689     static const unsigned char compatible_frame[9] = {
1690         1,    /* MODE_INTER_NO_MV */
1691         0,    /* MODE_INTRA */
1692         1,    /* MODE_INTER_PLUS_MV */
1693         1,    /* MODE_INTER_LAST_MV */
1694         1,    /* MODE_INTER_PRIOR_MV */
1695         2,    /* MODE_USING_GOLDEN */
1696         2,    /* MODE_GOLDEN_MV */
1697         1,    /* MODE_INTER_FOUR_MV */
1698         3     /* MODE_COPY */
1699     };
1700     int current_frame_type;
1701
1702     /* there is a last DC predictor for each of the 3 frame types */
1703     short last_dc[3];
1704
1705     int transform = 0;
1706
1707     vul =
1708     vu  =
1709     vur =
1710     vl  = 0;
1711     last_dc[0] =
1712     last_dc[1] =
1713     last_dc[2] = 0;
1714
1715     /* for each fragment row... */
1716     for (y = 0; y < fragment_height; y++) {
1717         /* for each fragment in a row... */
1718         for (x = 0; x < fragment_width; x++, i++) {
1719
1720             /* reverse prediction if this block was coded */
1721             if (s->all_fragments[i].coding_method != MODE_COPY) {
1722                 current_frame_type =
1723                     compatible_frame[s->all_fragments[i].coding_method];
1724
1725                 transform = 0;
1726                 if (x) {
1727                     l  = i - 1;
1728                     vl = DC_COEFF(l);
1729                     if (COMPATIBLE_FRAME(l))
1730                         transform |= PL;
1731                 }
1732                 if (y) {
1733                     u  = i - fragment_width;
1734                     vu = DC_COEFF(u);
1735                     if (COMPATIBLE_FRAME(u))
1736                         transform |= PU;
1737                     if (x) {
1738                         ul  = i - fragment_width - 1;
1739                         vul = DC_COEFF(ul);
1740                         if (COMPATIBLE_FRAME(ul))
1741                             transform |= PUL;
1742                     }
1743                     if (x + 1 < fragment_width) {
1744                         ur  = i - fragment_width + 1;
1745                         vur = DC_COEFF(ur);
1746                         if (COMPATIBLE_FRAME(ur))
1747                             transform |= PUR;
1748                     }
1749                 }
1750
1751                 if (transform == 0) {
1752                     /* if there were no fragments to predict from, use last
1753                      * DC saved */
1754                     predicted_dc = last_dc[current_frame_type];
1755                 } else {
1756                     /* apply the appropriate predictor transform */
1757                     predicted_dc =
1758                         (predictor_transform[transform][0] * vul) +
1759                         (predictor_transform[transform][1] * vu) +
1760                         (predictor_transform[transform][2] * vur) +
1761                         (predictor_transform[transform][3] * vl);
1762
1763                     predicted_dc /= 128;
1764
1765                     /* check for outranging on the [ul u l] and
1766                      * [ul u ur l] predictors */
1767                     if ((transform == 15) || (transform == 13)) {
1768                         if (FFABS(predicted_dc - vu) > 128)
1769                             predicted_dc = vu;
1770                         else if (FFABS(predicted_dc - vl) > 128)
1771                             predicted_dc = vl;
1772                         else if (FFABS(predicted_dc - vul) > 128)
1773                             predicted_dc = vul;
1774                     }
1775                 }
1776
1777                 /* at long last, apply the predictor */
1778                 DC_COEFF(i) += predicted_dc;
1779                 /* save the DC */
1780                 last_dc[current_frame_type] = DC_COEFF(i);
1781             }
1782         }
1783     }
1784 }
1785
1786 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1787                               int ystart, int yend)
1788 {
1789     int x, y;
1790     int *bounding_values = s->bounding_values_array + 127;
1791
1792     int width           = s->fragment_width[!!plane];
1793     int height          = s->fragment_height[!!plane];
1794     int fragment        = s->fragment_start[plane] + ystart * width;
1795     ptrdiff_t stride    = s->current_frame.f->linesize[plane];
1796     uint8_t *plane_data = s->current_frame.f->data[plane];
1797     if (!s->flipped_image)
1798         stride = -stride;
1799     plane_data += s->data_offset[plane] + 8 * ystart * stride;
1800
1801     for (y = ystart; y < yend; y++) {
1802         for (x = 0; x < width; x++) {
1803             /* This code basically just deblocks on the edges of coded blocks.
1804              * However, it has to be much more complicated because of the
1805              * brain damaged deblock ordering used in VP3/Theora. Order matters
1806              * because some pixels get filtered twice. */
1807             if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1808                 /* do not perform left edge filter for left columns frags */
1809                 if (x > 0) {
1810                     s->vp3dsp.h_loop_filter(
1811                         plane_data + 8 * x,
1812                         stride, bounding_values);
1813                 }
1814
1815                 /* do not perform top edge filter for top row fragments */
1816                 if (y > 0) {
1817                     s->vp3dsp.v_loop_filter(
1818                         plane_data + 8 * x,
1819                         stride, bounding_values);
1820                 }
1821
1822                 /* do not perform right edge filter for right column
1823                  * fragments or if right fragment neighbor is also coded
1824                  * in this frame (it will be filtered in next iteration) */
1825                 if ((x < width - 1) &&
1826                     (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1827                     s->vp3dsp.h_loop_filter(
1828                         plane_data + 8 * x + 8,
1829                         stride, bounding_values);
1830                 }
1831
1832                 /* do not perform bottom edge filter for bottom row
1833                  * fragments or if bottom fragment neighbor is also coded
1834                  * in this frame (it will be filtered in the next row) */
1835                 if ((y < height - 1) &&
1836                     (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1837                     s->vp3dsp.v_loop_filter(
1838                         plane_data + 8 * x + 8 * stride,
1839                         stride, bounding_values);
1840                 }
1841             }
1842
1843             fragment++;
1844         }
1845         plane_data += 8 * stride;
1846     }
1847 }
1848
1849 /**
1850  * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1851  * for the next block in coding order
1852  */
1853 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1854                               int plane, int inter, int16_t block[64])
1855 {
1856     int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1857     uint8_t *perm = s->idct_scantable;
1858     int i = 0;
1859
1860     do {
1861         int token = *s->dct_tokens[plane][i];
1862         switch (token & 3) {
1863         case 0: // EOB
1864             if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1865                 s->dct_tokens[plane][i]++;
1866             else
1867                 *s->dct_tokens[plane][i] = token & ~3;
1868             goto end;
1869         case 1: // zero run
1870             s->dct_tokens[plane][i]++;
1871             i += (token >> 2) & 0x7f;
1872             if (i > 63) {
1873                 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1874                 return i;
1875             }
1876             block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1877             i++;
1878             break;
1879         case 2: // coeff
1880             block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1881             s->dct_tokens[plane][i++]++;
1882             break;
1883         default: // shouldn't happen
1884             return i;
1885         }
1886     } while (i < 64);
1887     // return value is expected to be a valid level
1888     i--;
1889 end:
1890     // the actual DC+prediction is in the fragment structure
1891     block[0] = frag->dc * s->qmat[0][inter][plane][0];
1892     return i;
1893 }
1894
1895 /**
1896  * called when all pixels up to row y are complete
1897  */
1898 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1899 {
1900     int h, cy, i;
1901     int offset[AV_NUM_DATA_POINTERS];
1902
1903     if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1904         int y_flipped = s->flipped_image ? s->height - y : y;
1905
1906         /* At the end of the frame, report INT_MAX instead of the height of
1907          * the frame. This makes the other threads' ff_thread_await_progress()
1908          * calls cheaper, because they don't have to clip their values. */
1909         ff_thread_report_progress(&s->current_frame,
1910                                   y_flipped == s->height ? INT_MAX
1911                                                          : y_flipped - 1,
1912                                   0);
1913     }
1914
1915     if (!s->avctx->draw_horiz_band)
1916         return;
1917
1918     h = y - s->last_slice_end;
1919     s->last_slice_end = y;
1920     y -= h;
1921
1922     if (!s->flipped_image)
1923         y = s->height - y - h;
1924
1925     cy        = y >> s->chroma_y_shift;
1926     offset[0] = s->current_frame.f->linesize[0] * y;
1927     offset[1] = s->current_frame.f->linesize[1] * cy;
1928     offset[2] = s->current_frame.f->linesize[2] * cy;
1929     for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1930         offset[i] = 0;
1931
1932     emms_c();
1933     s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1934 }
1935
1936 /**
1937  * Wait for the reference frame of the current fragment.
1938  * The progress value is in luma pixel rows.
1939  */
1940 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1941                                 int motion_y, int y)
1942 {
1943     ThreadFrame *ref_frame;
1944     int ref_row;
1945     int border = motion_y & 1;
1946
1947     if (fragment->coding_method == MODE_USING_GOLDEN ||
1948         fragment->coding_method == MODE_GOLDEN_MV)
1949         ref_frame = &s->golden_frame;
1950     else
1951         ref_frame = &s->last_frame;
1952
1953     ref_row = y + (motion_y >> 1);
1954     ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1955
1956     ff_thread_await_progress(ref_frame, ref_row, 0);
1957 }
1958
1959 #if CONFIG_VP4_DECODER
1960 /**
1961  * @return non-zero if temp (edge_emu_buffer) was populated
1962  */
1963 static int vp4_mc_loop_filter(Vp3DecodeContext *s, int plane, int motion_x, int motion_y, int bx, int by,
1964        uint8_t * motion_source, int stride, int src_x, int src_y, uint8_t *temp)
1965 {
1966     int motion_shift = plane ? 4 : 2;
1967     int subpel_mask = plane ? 3 : 1;
1968     int *bounding_values = s->bounding_values_array + 127;
1969
1970     int i;
1971     int x, y;
1972     int x2, y2;
1973     int x_subpel, y_subpel;
1974     int x_offset, y_offset;
1975
1976     int block_width = plane ? 8 : 16;
1977     int plane_width  = s->width  >> (plane && s->chroma_x_shift);
1978     int plane_height = s->height >> (plane && s->chroma_y_shift);
1979
1980 #define loop_stride 12
1981     uint8_t loop[12 * loop_stride];
1982
1983     /* using division instead of shift to correctly handle negative values */
1984     x = 8 * bx + motion_x / motion_shift;
1985     y = 8 * by + motion_y / motion_shift;
1986
1987     x_subpel = motion_x & subpel_mask;
1988     y_subpel = motion_y & subpel_mask;
1989
1990     if (x_subpel || y_subpel) {
1991         x--;
1992         y--;
1993
1994         if (x_subpel)
1995             x = FFMIN(x, x + FFSIGN(motion_x));
1996
1997         if (y_subpel)
1998             y = FFMIN(y, y + FFSIGN(motion_y));
1999
2000         x2 = x + block_width;
2001         y2 = y + block_width;
2002
2003         if (x2 < 0 || x2 >= plane_width || y2 < 0 || y2 >= plane_height)
2004             return 0;
2005
2006         x_offset = (-(x + 2) & 7) + 2;
2007         y_offset = (-(y + 2) & 7) + 2;
2008
2009         if (x_offset > 8 + x_subpel && y_offset > 8 + y_subpel)
2010             return 0;
2011
2012         s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2013              loop_stride, stride,
2014              12, 12, src_x - 1, src_y - 1,
2015              plane_width,
2016              plane_height);
2017
2018         if (x_offset <= 8 + x_subpel)
2019             ff_vp3dsp_h_loop_filter_12(loop + x_offset, loop_stride, bounding_values);
2020
2021         if (y_offset <= 8 + y_subpel)
2022             ff_vp3dsp_v_loop_filter_12(loop + y_offset*loop_stride, loop_stride, bounding_values);
2023
2024     } else {
2025
2026         x_offset = -x & 7;
2027         y_offset = -y & 7;
2028
2029         if (!x_offset && !y_offset)
2030             return 0;
2031
2032         s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2033              loop_stride, stride,
2034              12, 12, src_x - 1, src_y - 1,
2035              plane_width,
2036              plane_height);
2037
2038 #define safe_loop_filter(name, ptr, stride, bounding_values) \
2039     if ((uintptr_t)(ptr) & 7) \
2040         s->vp3dsp.name##_unaligned(ptr, stride, bounding_values); \
2041     else \
2042         s->vp3dsp.name(ptr, stride, bounding_values);
2043
2044         if (x_offset)
2045             safe_loop_filter(h_loop_filter, loop + loop_stride + x_offset + 1, loop_stride, bounding_values);
2046
2047         if (y_offset)
2048             safe_loop_filter(v_loop_filter, loop + (y_offset + 1)*loop_stride + 1, loop_stride, bounding_values);
2049     }
2050
2051     for (i = 0; i < 9; i++)
2052         memcpy(temp + i*stride, loop + (i + 1) * loop_stride + 1, 9);
2053
2054     return 1;
2055 }
2056 #endif
2057
2058 /*
2059  * Perform the final rendering for a particular slice of data.
2060  * The slice number ranges from 0..(c_superblock_height - 1).
2061  */
2062 static void render_slice(Vp3DecodeContext *s, int slice)
2063 {
2064     int x, y, i, j, fragment;
2065     int16_t *block = s->block;
2066     int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
2067     int motion_halfpel_index;
2068     uint8_t *motion_source;
2069     int plane, first_pixel;
2070
2071     if (slice >= s->c_superblock_height)
2072         return;
2073
2074     for (plane = 0; plane < 3; plane++) {
2075         uint8_t *output_plane = s->current_frame.f->data[plane] +
2076                                 s->data_offset[plane];
2077         uint8_t *last_plane = s->last_frame.f->data[plane] +
2078                               s->data_offset[plane];
2079         uint8_t *golden_plane = s->golden_frame.f->data[plane] +
2080                                 s->data_offset[plane];
2081         ptrdiff_t stride = s->current_frame.f->linesize[plane];
2082         int plane_width  = s->width  >> (plane && s->chroma_x_shift);
2083         int plane_height = s->height >> (plane && s->chroma_y_shift);
2084         int8_t(*motion_val)[2] = s->motion_val[!!plane];
2085
2086         int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
2087         int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
2088         int slice_width  = plane ? s->c_superblock_width
2089                                  : s->y_superblock_width;
2090
2091         int fragment_width  = s->fragment_width[!!plane];
2092         int fragment_height = s->fragment_height[!!plane];
2093         int fragment_start  = s->fragment_start[plane];
2094
2095         int do_await = !plane && HAVE_THREADS &&
2096                        (s->avctx->active_thread_type & FF_THREAD_FRAME);
2097
2098         if (!s->flipped_image)
2099             stride = -stride;
2100         if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
2101             continue;
2102
2103         /* for each superblock row in the slice (both of them)... */
2104         for (; sb_y < slice_height; sb_y++) {
2105             /* for each superblock in a row... */
2106             for (sb_x = 0; sb_x < slice_width; sb_x++) {
2107                 /* for each block in a superblock... */
2108                 for (j = 0; j < 16; j++) {
2109                     x        = 4 * sb_x + hilbert_offset[j][0];
2110                     y        = 4 * sb_y + hilbert_offset[j][1];
2111                     fragment = y * fragment_width + x;
2112
2113                     i = fragment_start + fragment;
2114
2115                     // bounds check
2116                     if (x >= fragment_width || y >= fragment_height)
2117                         continue;
2118
2119                     first_pixel = 8 * y * stride + 8 * x;
2120
2121                     if (do_await &&
2122                         s->all_fragments[i].coding_method != MODE_INTRA)
2123                         await_reference_row(s, &s->all_fragments[i],
2124                                             motion_val[fragment][1],
2125                                             (16 * y) >> s->chroma_y_shift);
2126
2127                     /* transform if this block was coded */
2128                     if (s->all_fragments[i].coding_method != MODE_COPY) {
2129                         if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2130                             (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
2131                             motion_source = golden_plane;
2132                         else
2133                             motion_source = last_plane;
2134
2135                         motion_source       += first_pixel;
2136                         motion_halfpel_index = 0;
2137
2138                         /* sort out the motion vector if this fragment is coded
2139                          * using a motion vector method */
2140                         if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
2141                             (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
2142                             int src_x, src_y;
2143                             int standard_mc = 1;
2144                             motion_x = motion_val[fragment][0];
2145                             motion_y = motion_val[fragment][1];
2146 #if CONFIG_VP4_DECODER
2147                             if (plane && s->version >= 2) {
2148                                 motion_x = (motion_x >> 1) | (motion_x & 1);
2149                                 motion_y = (motion_y >> 1) | (motion_y & 1);
2150                             }
2151 #endif
2152
2153                             src_x = (motion_x >> 1) + 8 * x;
2154                             src_y = (motion_y >> 1) + 8 * y;
2155
2156                             motion_halfpel_index = motion_x & 0x01;
2157                             motion_source       += (motion_x >> 1);
2158
2159                             motion_halfpel_index |= (motion_y & 0x01) << 1;
2160                             motion_source        += ((motion_y >> 1) * stride);
2161
2162 #if CONFIG_VP4_DECODER
2163                             if (s->version >= 2) {
2164                                 uint8_t *temp = s->edge_emu_buffer;
2165                                 if (stride < 0)
2166                                     temp -= 8 * stride;
2167                                 if (vp4_mc_loop_filter(s, plane, motion_val[fragment][0], motion_val[fragment][1], x, y, motion_source, stride, src_x, src_y, temp)) {
2168                                     motion_source = temp;
2169                                     standard_mc = 0;
2170                                 }
2171                             }
2172 #endif
2173
2174                             if (standard_mc && (
2175                                 src_x < 0 || src_y < 0 ||
2176                                 src_x + 9 >= plane_width ||
2177                                 src_y + 9 >= plane_height)) {
2178                                 uint8_t *temp = s->edge_emu_buffer;
2179                                 if (stride < 0)
2180                                     temp -= 8 * stride;
2181
2182                                 s->vdsp.emulated_edge_mc(temp, motion_source,
2183                                                          stride, stride,
2184                                                          9, 9, src_x, src_y,
2185                                                          plane_width,
2186                                                          plane_height);
2187                                 motion_source = temp;
2188                             }
2189                         }
2190
2191                         /* first, take care of copying a block from either the
2192                          * previous or the golden frame */
2193                         if (s->all_fragments[i].coding_method != MODE_INTRA) {
2194                             /* Note, it is possible to implement all MC cases
2195                              * with put_no_rnd_pixels_l2 which would look more
2196                              * like the VP3 source but this would be slower as
2197                              * put_no_rnd_pixels_tab is better optimized */
2198                             if (motion_halfpel_index != 3) {
2199                                 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
2200                                     output_plane + first_pixel,
2201                                     motion_source, stride, 8);
2202                             } else {
2203                                 /* d is 0 if motion_x and _y have the same sign,
2204                                  * else -1 */
2205                                 int d = (motion_x ^ motion_y) >> 31;
2206                                 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
2207                                                                motion_source - d,
2208                                                                motion_source + stride + 1 + d,
2209                                                                stride, 8);
2210                             }
2211                         }
2212
2213                         /* invert DCT and place (or add) in final output */
2214
2215                         if (s->all_fragments[i].coding_method == MODE_INTRA) {
2216                             vp3_dequant(s, s->all_fragments + i,
2217                                         plane, 0, block);
2218                             s->vp3dsp.idct_put(output_plane + first_pixel,
2219                                                stride,
2220                                                block);
2221                         } else {
2222                             if (vp3_dequant(s, s->all_fragments + i,
2223                                             plane, 1, block)) {
2224                                 s->vp3dsp.idct_add(output_plane + first_pixel,
2225                                                    stride,
2226                                                    block);
2227                             } else {
2228                                 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
2229                                                       stride, block);
2230                             }
2231                         }
2232                     } else {
2233                         /* copy directly from the previous frame */
2234                         s->hdsp.put_pixels_tab[1][0](
2235                             output_plane + first_pixel,
2236                             last_plane + first_pixel,
2237                             stride, 8);
2238                     }
2239                 }
2240             }
2241
2242             // Filter up to the last row in the superblock row
2243             if (s->version < 2 && !s->skip_loop_filter)
2244                 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
2245                                   FFMIN(4 * sb_y + 3, fragment_height - 1));
2246         }
2247     }
2248
2249     /* this looks like a good place for slice dispatch... */
2250     /* algorithm:
2251      *   if (slice == s->macroblock_height - 1)
2252      *     dispatch (both last slice & 2nd-to-last slice);
2253      *   else if (slice > 0)
2254      *     dispatch (slice - 1);
2255      */
2256
2257     vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
2258                                  s->height - 16));
2259 }
2260
2261 /// Allocate tables for per-frame data in Vp3DecodeContext
2262 static av_cold int allocate_tables(AVCodecContext *avctx)
2263 {
2264     Vp3DecodeContext *s = avctx->priv_data;
2265     int y_fragment_count, c_fragment_count;
2266
2267     free_tables(avctx);
2268
2269     y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2270     c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2271
2272     /* superblock_coding is used by unpack_superblocks (VP3/Theora) and vp4_unpack_macroblocks (VP4) */
2273     s->superblock_coding = av_mallocz(FFMAX(s->superblock_count, s->yuv_macroblock_count));
2274     s->all_fragments     = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
2275
2276     s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2277     s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2278     memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
2279
2280     s->dct_tokens_base = av_mallocz_array(s->fragment_count,
2281                                           64 * sizeof(*s->dct_tokens_base));
2282     s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
2283     s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
2284
2285     /* work out the block mapping tables */
2286     s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
2287     s->macroblock_coding    = av_mallocz(s->macroblock_count + 1);
2288
2289     s->dc_pred_row = av_malloc_array(s->y_superblock_width * 4, sizeof(*s->dc_pred_row));
2290
2291     if (!s->superblock_coding    || !s->all_fragments          ||
2292         !s->dct_tokens_base      || !s->kf_coded_fragment_list ||
2293         !s->nkf_coded_fragment_list ||
2294         !s->superblock_fragments || !s->macroblock_coding      ||
2295         !s->dc_pred_row ||
2296         !s->motion_val[0]        || !s->motion_val[1]) {
2297         return -1;
2298     }
2299
2300     init_block_mapping(s);
2301
2302     return 0;
2303 }
2304
2305 static av_cold int init_frames(Vp3DecodeContext *s)
2306 {
2307     s->current_frame.f = av_frame_alloc();
2308     s->last_frame.f    = av_frame_alloc();
2309     s->golden_frame.f  = av_frame_alloc();
2310
2311     if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f)
2312         return AVERROR(ENOMEM);
2313
2314     return 0;
2315 }
2316
2317 static av_cold int theora_init_huffman_tables(VLC *vlc, const HuffTable *huff)
2318 {
2319     uint32_t code = 0, codes[32];
2320
2321     for (unsigned i = 0; i < huff->nb_entries; i++) {
2322         codes[i] = code        >> (31 - huff->entries[i].len);
2323         code    += 0x80000000U >> huff->entries[i].len;
2324     }
2325     return ff_init_vlc_sparse(vlc, 11, huff->nb_entries,
2326                               &huff->entries[0].len, sizeof(huff->entries[0]), 1,
2327                               codes, 4, 4,
2328                               &huff->entries[0].sym, sizeof(huff->entries[0]), 1, 0);
2329 }
2330
2331 static av_cold int vp3_decode_init(AVCodecContext *avctx)
2332 {
2333     Vp3DecodeContext *s = avctx->priv_data;
2334     int i, inter, plane, ret;
2335     int c_width;
2336     int c_height;
2337     int y_fragment_count, c_fragment_count;
2338 #if CONFIG_VP4_DECODER
2339     int j;
2340 #endif
2341
2342     ret = init_frames(s);
2343     if (ret < 0)
2344         return ret;
2345
2346     if (avctx->codec_tag == MKTAG('V', 'P', '4', '0'))
2347         s->version = 3;
2348     else if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
2349         s->version = 0;
2350     else
2351         s->version = 1;
2352
2353     s->avctx  = avctx;
2354     s->width  = FFALIGN(avctx->coded_width, 16);
2355     s->height = FFALIGN(avctx->coded_height, 16);
2356     if (avctx->codec_id != AV_CODEC_ID_THEORA)
2357         avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2358     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
2359     ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
2360     ff_videodsp_init(&s->vdsp, 8);
2361     ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
2362
2363     for (i = 0; i < 64; i++) {
2364 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
2365         s->idct_permutation[i] = TRANSPOSE(i);
2366         s->idct_scantable[i]   = TRANSPOSE(ff_zigzag_direct[i]);
2367 #undef TRANSPOSE
2368     }
2369
2370     /* initialize to an impossible value which will force a recalculation
2371      * in the first frame decode */
2372     for (i = 0; i < 3; i++)
2373         s->qps[i] = -1;
2374
2375     ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
2376     if (ret)
2377         return ret;
2378
2379     s->y_superblock_width  = (s->width  + 31) / 32;
2380     s->y_superblock_height = (s->height + 31) / 32;
2381     s->y_superblock_count  = s->y_superblock_width * s->y_superblock_height;
2382
2383     /* work out the dimensions for the C planes */
2384     c_width                = s->width >> s->chroma_x_shift;
2385     c_height               = s->height >> s->chroma_y_shift;
2386     s->c_superblock_width  = (c_width  + 31) / 32;
2387     s->c_superblock_height = (c_height + 31) / 32;
2388     s->c_superblock_count  = s->c_superblock_width * s->c_superblock_height;
2389
2390     s->superblock_count   = s->y_superblock_count + (s->c_superblock_count * 2);
2391     s->u_superblock_start = s->y_superblock_count;
2392     s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
2393
2394     s->macroblock_width  = (s->width  + 15) / 16;
2395     s->macroblock_height = (s->height + 15) / 16;
2396     s->macroblock_count  = s->macroblock_width * s->macroblock_height;
2397     s->c_macroblock_width  = (c_width  + 15) / 16;
2398     s->c_macroblock_height = (c_height + 15) / 16;
2399     s->c_macroblock_count  = s->c_macroblock_width * s->c_macroblock_height;
2400     s->yuv_macroblock_count = s->macroblock_count + 2 * s->c_macroblock_count;
2401
2402     s->fragment_width[0]  = s->width / FRAGMENT_PIXELS;
2403     s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
2404     s->fragment_width[1]  = s->fragment_width[0] >> s->chroma_x_shift;
2405     s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
2406
2407     /* fragment count covers all 8x8 blocks for all 3 planes */
2408     y_fragment_count     = s->fragment_width[0] * s->fragment_height[0];
2409     c_fragment_count     = s->fragment_width[1] * s->fragment_height[1];
2410     s->fragment_count    = y_fragment_count + 2 * c_fragment_count;
2411     s->fragment_start[1] = y_fragment_count;
2412     s->fragment_start[2] = y_fragment_count + c_fragment_count;
2413
2414     if (!s->theora_tables) {
2415         for (i = 0; i < 64; i++) {
2416             s->coded_dc_scale_factor[0][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_y_dc_scale_factor[i];
2417             s->coded_dc_scale_factor[1][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_uv_dc_scale_factor[i];
2418             s->coded_ac_scale_factor[i] = s->version < 2 ? vp31_ac_scale_factor[i] : vp4_ac_scale_factor[i];
2419             s->base_matrix[0][i]        = s->version < 2 ? vp31_intra_y_dequant[i] : vp4_generic_dequant[i];
2420             s->base_matrix[1][i]        = s->version < 2 ? vp31_intra_c_dequant[i] : vp4_generic_dequant[i];
2421             s->base_matrix[2][i]        = s->version < 2 ? vp31_inter_dequant[i]   : vp4_generic_dequant[i];
2422             s->filter_limit_values[i]   = s->version < 2 ? vp31_filter_limit_values[i] : vp4_filter_limit_values[i];
2423         }
2424
2425         for (inter = 0; inter < 2; inter++) {
2426             for (plane = 0; plane < 3; plane++) {
2427                 s->qr_count[inter][plane]   = 1;
2428                 s->qr_size[inter][plane][0] = 63;
2429                 s->qr_base[inter][plane][0] =
2430                 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
2431             }
2432         }
2433
2434         /* init VLC tables */
2435         if (s->version < 2) {
2436             for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2437                 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, 32,
2438                                                &vp3_bias[i][0][1], 2,
2439                                                &vp3_bias[i][0][0], 2, 1,
2440                                                0, 0, avctx);
2441                 if (ret < 0)
2442                     return ret;
2443             }
2444 #if CONFIG_VP4_DECODER
2445         } else { /* version >= 2 */
2446             for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2447                 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, 32,
2448                                                &vp4_bias[i][0][1], 2,
2449                                                &vp4_bias[i][0][0], 2, 1,
2450                                                0, 0, avctx);
2451                 if (ret < 0)
2452                     return ret;
2453             }
2454 #endif
2455         }
2456     } else {
2457         for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2458             ret = theora_init_huffman_tables(&s->coeff_vlc[i], &s->huffman_table[i]);
2459             if (ret < 0)
2460                 return ret;
2461         }
2462     }
2463
2464     ret = ff_init_vlc_from_lengths(&s->superblock_run_length_vlc, SUPERBLOCK_VLC_BITS, 34,
2465                                    superblock_run_length_vlc_lens, 1,
2466                                    NULL, 0, 0, 1, 0, avctx);
2467     if (ret < 0)
2468         return ret;
2469
2470     ret = ff_init_vlc_from_lengths(&s->fragment_run_length_vlc, 5, 30,
2471                                    fragment_run_length_vlc_len, 1,
2472                                    NULL, 0, 0, 0, 0, avctx);
2473     if (ret < 0)
2474         return ret;
2475
2476     ret = ff_init_vlc_from_lengths(&s->mode_code_vlc, 3, 8,
2477                                    mode_code_vlc_len, 1,
2478                                    NULL, 0, 0, 0, 0, avctx);
2479     if (ret < 0)
2480         return ret;
2481
2482     if ((ret = init_vlc(&s->motion_vector_vlc, 6, 63,
2483                         &motion_vector_vlc_table[0][1], 2, 1,
2484                         &motion_vector_vlc_table[0][0], 2, 1, 0)) < 0)
2485         return ret;
2486
2487 #if CONFIG_VP4_DECODER
2488     for (j = 0; j < 2; j++)
2489         for (i = 0; i < 7; i++) {
2490             ret = ff_init_vlc_from_lengths(&s->vp4_mv_vlc[j][i], VP4_MV_VLC_BITS, 63,
2491                                            &vp4_mv_vlc[j][i][0][1], 2,
2492                                            &vp4_mv_vlc[j][i][0][0], 2, 1, -31,
2493                                            0, avctx);
2494             if (ret < 0)
2495                 return ret;
2496         }
2497
2498     /* version >= 2 */
2499     for (i = 0; i < 2; i++)
2500         if ((ret = init_vlc(&s->block_pattern_vlc[i], 3, 14,
2501                             &vp4_block_pattern_vlc[i][0][1], 2, 1,
2502                             &vp4_block_pattern_vlc[i][0][0], 2, 1, 0)) < 0)
2503             return ret;
2504 #endif
2505
2506     return allocate_tables(avctx);
2507 }
2508
2509 /// Release and shuffle frames after decode finishes
2510 static int update_frames(AVCodecContext *avctx)
2511 {
2512     Vp3DecodeContext *s = avctx->priv_data;
2513     int ret = 0;
2514
2515     /* shuffle frames (last = current) */
2516     ff_thread_release_buffer(avctx, &s->last_frame);
2517     ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
2518     if (ret < 0)
2519         goto fail;
2520
2521     if (s->keyframe) {
2522         ff_thread_release_buffer(avctx, &s->golden_frame);
2523         ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
2524     }
2525
2526 fail:
2527     ff_thread_release_buffer(avctx, &s->current_frame);
2528     return ret;
2529 }
2530
2531 #if HAVE_THREADS
2532 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
2533 {
2534     ff_thread_release_buffer(s->avctx, dst);
2535     if (src->f->data[0])
2536         return ff_thread_ref_frame(dst, src);
2537     return 0;
2538 }
2539
2540 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
2541 {
2542     int ret;
2543     if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
2544         (ret = ref_frame(dst, &dst->golden_frame,  &src->golden_frame)) < 0  ||
2545         (ret = ref_frame(dst, &dst->last_frame,    &src->last_frame)) < 0)
2546         return ret;
2547     return 0;
2548 }
2549
2550 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
2551 {
2552     Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
2553     int qps_changed = 0, i, err;
2554
2555     if (!s1->current_frame.f->data[0] ||
2556         s->width != s1->width || s->height != s1->height) {
2557         if (s != s1)
2558             ref_frames(s, s1);
2559         return -1;
2560     }
2561
2562     if (s != s1) {
2563         // copy previous frame data
2564         if ((err = ref_frames(s, s1)) < 0)
2565             return err;
2566
2567         s->keyframe = s1->keyframe;
2568
2569         // copy qscale data if necessary
2570         for (i = 0; i < 3; i++) {
2571             if (s->qps[i] != s1->qps[1]) {
2572                 qps_changed = 1;
2573                 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2574             }
2575         }
2576
2577         if (s->qps[0] != s1->qps[0])
2578             memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2579                    sizeof(s->bounding_values_array));
2580
2581         if (qps_changed) {
2582             memcpy(s->qps,      s1->qps,      sizeof(s->qps));
2583             memcpy(s->last_qps, s1->last_qps, sizeof(s->last_qps));
2584             s->nqps = s1->nqps;
2585         }
2586     }
2587
2588     return update_frames(dst);
2589 }
2590 #endif
2591
2592 static int vp3_decode_frame(AVCodecContext *avctx,
2593                             void *data, int *got_frame,
2594                             AVPacket *avpkt)
2595 {
2596     AVFrame     *frame  = data;
2597     const uint8_t *buf  = avpkt->data;
2598     int buf_size        = avpkt->size;
2599     Vp3DecodeContext *s = avctx->priv_data;
2600     GetBitContext gb;
2601     int i, ret;
2602
2603     if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2604         return ret;
2605
2606 #if CONFIG_THEORA_DECODER
2607     if (s->theora && get_bits1(&gb)) {
2608         int type = get_bits(&gb, 7);
2609         skip_bits_long(&gb, 6*8); /* "theora" */
2610
2611         if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2612             av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2613             return AVERROR_PATCHWELCOME;
2614         }
2615         if (type == 0) {
2616             vp3_decode_end(avctx);
2617             ret = theora_decode_header(avctx, &gb);
2618
2619             if (ret >= 0)
2620                 ret = vp3_decode_init(avctx);
2621             if (ret < 0) {
2622                 vp3_decode_end(avctx);
2623                 return ret;
2624             }
2625             return buf_size;
2626         } else if (type == 2) {
2627             vp3_decode_end(avctx);
2628             ret = theora_decode_tables(avctx, &gb);
2629             if (ret >= 0)
2630                 ret = vp3_decode_init(avctx);
2631             if (ret < 0) {
2632                 vp3_decode_end(avctx);
2633                 return ret;
2634             }
2635             return buf_size;
2636         }
2637
2638         av_log(avctx, AV_LOG_ERROR,
2639                "Header packet passed to frame decoder, skipping\n");
2640         return -1;
2641     }
2642 #endif
2643
2644     s->keyframe = !get_bits1(&gb);
2645     if (!s->all_fragments) {
2646         av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2647         return -1;
2648     }
2649     if (!s->theora)
2650         skip_bits(&gb, 1);
2651     for (i = 0; i < 3; i++)
2652         s->last_qps[i] = s->qps[i];
2653
2654     s->nqps = 0;
2655     do {
2656         s->qps[s->nqps++] = get_bits(&gb, 6);
2657     } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2658     for (i = s->nqps; i < 3; i++)
2659         s->qps[i] = -1;
2660
2661     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2662         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2663                s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2664
2665     s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2666                           avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2667                                                                   : AVDISCARD_NONKEY);
2668
2669     if (s->qps[0] != s->last_qps[0])
2670         init_loop_filter(s);
2671
2672     for (i = 0; i < s->nqps; i++)
2673         // reinit all dequantizers if the first one changed, because
2674         // the DC of the first quantizer must be used for all matrices
2675         if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2676             init_dequantizer(s, i);
2677
2678     if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2679         return buf_size;
2680
2681     s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2682                                                 : AV_PICTURE_TYPE_P;
2683     s->current_frame.f->key_frame = s->keyframe;
2684     if ((ret = ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
2685         goto error;
2686
2687     if (!s->edge_emu_buffer)
2688         s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2689
2690     if (s->keyframe) {
2691         if (!s->theora) {
2692             skip_bits(&gb, 4); /* width code */
2693             skip_bits(&gb, 4); /* height code */
2694             if (s->version) {
2695                 s->version = get_bits(&gb, 5);
2696                 if (avctx->frame_number == 0)
2697                     av_log(s->avctx, AV_LOG_DEBUG,
2698                            "VP version: %d\n", s->version);
2699             }
2700         }
2701         if (s->version || s->theora) {
2702             if (get_bits1(&gb))
2703                 av_log(s->avctx, AV_LOG_ERROR,
2704                        "Warning, unsupported keyframe coding type?!\n");
2705             skip_bits(&gb, 2); /* reserved? */
2706
2707 #if CONFIG_VP4_DECODER
2708             if (s->version >= 2) {
2709                 int mb_height, mb_width;
2710                 int mb_width_mul, mb_width_div, mb_height_mul, mb_height_div;
2711
2712                 mb_height = get_bits(&gb, 8);
2713                 mb_width  = get_bits(&gb, 8);
2714                 if (mb_height != s->macroblock_height ||
2715                     mb_width != s->macroblock_width)
2716                     avpriv_request_sample(s->avctx, "macroblock dimension mismatch");
2717
2718                 mb_width_mul = get_bits(&gb, 5);
2719                 mb_width_div = get_bits(&gb, 3);
2720                 mb_height_mul = get_bits(&gb, 5);
2721                 mb_height_div = get_bits(&gb, 3);
2722                 if (mb_width_mul != 1 || mb_width_div != 1 || mb_height_mul != 1 || mb_height_div != 1)
2723                     avpriv_request_sample(s->avctx, "unexpected macroblock dimension multipler/divider");
2724
2725                 if (get_bits(&gb, 2))
2726                     avpriv_request_sample(s->avctx, "unknown bits");
2727             }
2728 #endif
2729         }
2730     } else {
2731         if (!s->golden_frame.f->data[0]) {
2732             av_log(s->avctx, AV_LOG_WARNING,
2733                    "vp3: first frame not a keyframe\n");
2734
2735             s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2736             if ((ret = ff_thread_get_buffer(avctx, &s->golden_frame,
2737                                      AV_GET_BUFFER_FLAG_REF)) < 0)
2738                 goto error;
2739             ff_thread_release_buffer(avctx, &s->last_frame);
2740             if ((ret = ff_thread_ref_frame(&s->last_frame,
2741                                            &s->golden_frame)) < 0)
2742                 goto error;
2743             ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2744         }
2745     }
2746
2747     memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2748     ff_thread_finish_setup(avctx);
2749
2750     if (s->version < 2) {
2751         if ((ret = unpack_superblocks(s, &gb)) < 0) {
2752             av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2753             goto error;
2754         }
2755 #if CONFIG_VP4_DECODER
2756     } else {
2757         if ((ret = vp4_unpack_macroblocks(s, &gb)) < 0) {
2758             av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_macroblocks\n");
2759             goto error;
2760     }
2761 #endif
2762     }
2763     if ((ret = unpack_modes(s, &gb)) < 0) {
2764         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2765         goto error;
2766     }
2767     if (ret = unpack_vectors(s, &gb)) {
2768         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2769         goto error;
2770     }
2771     if ((ret = unpack_block_qpis(s, &gb)) < 0) {
2772         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2773         goto error;
2774     }
2775
2776     if (s->version < 2) {
2777         if ((ret = unpack_dct_coeffs(s, &gb)) < 0) {
2778             av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2779             goto error;
2780         }
2781 #if CONFIG_VP4_DECODER
2782     } else {
2783         if ((ret = vp4_unpack_dct_coeffs(s, &gb)) < 0) {
2784             av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_dct_coeffs\n");
2785             goto error;
2786         }
2787 #endif
2788     }
2789
2790     for (i = 0; i < 3; i++) {
2791         int height = s->height >> (i && s->chroma_y_shift);
2792         if (s->flipped_image)
2793             s->data_offset[i] = 0;
2794         else
2795             s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2796     }
2797
2798     s->last_slice_end = 0;
2799     for (i = 0; i < s->c_superblock_height; i++)
2800         render_slice(s, i);
2801
2802     // filter the last row
2803     if (s->version < 2)
2804         for (i = 0; i < 3; i++) {
2805             int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2806             apply_loop_filter(s, i, row, row + 1);
2807         }
2808     vp3_draw_horiz_band(s, s->height);
2809
2810     /* output frame, offset as needed */
2811     if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2812         return ret;
2813
2814     frame->crop_left   = s->offset_x;
2815     frame->crop_right  = avctx->coded_width - avctx->width - s->offset_x;
2816     frame->crop_top    = s->offset_y;
2817     frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2818
2819     *got_frame = 1;
2820
2821     if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2822         ret = update_frames(avctx);
2823         if (ret < 0)
2824             return ret;
2825     }
2826
2827     return buf_size;
2828
2829 error:
2830     ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2831
2832     if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2833         av_frame_unref(s->current_frame.f);
2834
2835     return ret;
2836 }
2837
2838 static int read_huffman_tree(HuffTable *huff, GetBitContext *gb, int length,
2839                              AVCodecContext *avctx)
2840 {
2841     if (get_bits1(gb)) {
2842         int token;
2843         if (huff->nb_entries >= 32) { /* overflow */
2844             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2845             return -1;
2846         }
2847         token = get_bits(gb, 5);
2848         ff_dlog(avctx, "code length %d, curr entry %d, token %d\n",
2849                 length, huff->nb_entries, token);
2850         huff->entries[huff->nb_entries++] = (HuffEntry){ length, token };
2851     } else {
2852         /* The following bound follows from the fact that nb_entries <= 32. */
2853         if (length >= 31) { /* overflow */
2854             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2855             return -1;
2856         }
2857         length++;
2858         if (read_huffman_tree(huff, gb, length, avctx))
2859             return -1;
2860         if (read_huffman_tree(huff, gb, length, avctx))
2861             return -1;
2862     }
2863     return 0;
2864 }
2865
2866 #if CONFIG_THEORA_DECODER
2867 static const enum AVPixelFormat theora_pix_fmts[4] = {
2868     AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2869 };
2870
2871 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2872 {
2873     Vp3DecodeContext *s = avctx->priv_data;
2874     int visible_width, visible_height, colorspace;
2875     uint8_t offset_x = 0, offset_y = 0;
2876     int ret;
2877     AVRational fps, aspect;
2878
2879     s->theora_header = 0;
2880     s->theora = get_bits(gb, 24);
2881     av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2882     if (!s->theora) {
2883         s->theora = 1;
2884         avpriv_request_sample(s->avctx, "theora 0");
2885     }
2886
2887     /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2888      * but previous versions have the image flipped relative to vp3 */
2889     if (s->theora < 0x030200) {
2890         s->flipped_image = 1;
2891         av_log(avctx, AV_LOG_DEBUG,
2892                "Old (<alpha3) Theora bitstream, flipped image\n");
2893     }
2894
2895     visible_width  =
2896     s->width       = get_bits(gb, 16) << 4;
2897     visible_height =
2898     s->height      = get_bits(gb, 16) << 4;
2899
2900     if (s->theora >= 0x030200) {
2901         visible_width  = get_bits(gb, 24);
2902         visible_height = get_bits(gb, 24);
2903
2904         offset_x = get_bits(gb, 8); /* offset x */
2905         offset_y = get_bits(gb, 8); /* offset y, from bottom */
2906     }
2907
2908     /* sanity check */
2909     if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2910         visible_width  + offset_x > s->width ||
2911         visible_height + offset_y > s->height) {
2912         av_log(avctx, AV_LOG_ERROR,
2913                "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2914                visible_width, visible_height, offset_x, offset_y,
2915                s->width, s->height);
2916         return AVERROR_INVALIDDATA;
2917     }
2918
2919     fps.num = get_bits_long(gb, 32);
2920     fps.den = get_bits_long(gb, 32);
2921     if (fps.num && fps.den) {
2922         if (fps.num < 0 || fps.den < 0) {
2923             av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2924             return AVERROR_INVALIDDATA;
2925         }
2926         av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2927                   fps.den, fps.num, 1 << 30);
2928     }
2929
2930     aspect.num = get_bits(gb, 24);
2931     aspect.den = get_bits(gb, 24);
2932     if (aspect.num && aspect.den) {
2933         av_reduce(&avctx->sample_aspect_ratio.num,
2934                   &avctx->sample_aspect_ratio.den,
2935                   aspect.num, aspect.den, 1 << 30);
2936         ff_set_sar(avctx, avctx->sample_aspect_ratio);
2937     }
2938
2939     if (s->theora < 0x030200)
2940         skip_bits(gb, 5); /* keyframe frequency force */
2941     colorspace = get_bits(gb, 8);
2942     skip_bits(gb, 24); /* bitrate */
2943
2944     skip_bits(gb, 6); /* quality hint */
2945
2946     if (s->theora >= 0x030200) {
2947         skip_bits(gb, 5); /* keyframe frequency force */
2948         avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2949         if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2950             av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2951             return AVERROR_INVALIDDATA;
2952         }
2953         skip_bits(gb, 3); /* reserved */
2954     } else
2955         avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2956
2957     ret = ff_set_dimensions(avctx, s->width, s->height);
2958     if (ret < 0)
2959         return ret;
2960     if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2961         avctx->width  = visible_width;
2962         avctx->height = visible_height;
2963         // translate offsets from theora axis ([0,0] lower left)
2964         // to normal axis ([0,0] upper left)
2965         s->offset_x = offset_x;
2966         s->offset_y = s->height - visible_height - offset_y;
2967     }
2968
2969     if (colorspace == 1)
2970         avctx->color_primaries = AVCOL_PRI_BT470M;
2971     else if (colorspace == 2)
2972         avctx->color_primaries = AVCOL_PRI_BT470BG;
2973
2974     if (colorspace == 1 || colorspace == 2) {
2975         avctx->colorspace = AVCOL_SPC_BT470BG;
2976         avctx->color_trc  = AVCOL_TRC_BT709;
2977     }
2978
2979     s->theora_header = 1;
2980     return 0;
2981 }
2982
2983 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2984 {
2985     Vp3DecodeContext *s = avctx->priv_data;
2986     int i, n, matrices, inter, plane, ret;
2987
2988     if (!s->theora_header)
2989         return AVERROR_INVALIDDATA;
2990
2991     if (s->theora >= 0x030200) {
2992         n = get_bits(gb, 3);
2993         /* loop filter limit values table */
2994         if (n)
2995             for (i = 0; i < 64; i++)
2996                 s->filter_limit_values[i] = get_bits(gb, n);
2997     }
2998
2999     if (s->theora >= 0x030200)
3000         n = get_bits(gb, 4) + 1;
3001     else
3002         n = 16;
3003     /* quality threshold table */
3004     for (i = 0; i < 64; i++)
3005         s->coded_ac_scale_factor[i] = get_bits(gb, n);
3006
3007     if (s->theora >= 0x030200)
3008         n = get_bits(gb, 4) + 1;
3009     else
3010         n = 16;
3011     /* dc scale factor table */
3012     for (i = 0; i < 64; i++)
3013         s->coded_dc_scale_factor[0][i] =
3014         s->coded_dc_scale_factor[1][i] = get_bits(gb, n);
3015
3016     if (s->theora >= 0x030200)
3017         matrices = get_bits(gb, 9) + 1;
3018     else
3019         matrices = 3;
3020
3021     if (matrices > 384) {
3022         av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
3023         return -1;
3024     }
3025
3026     for (n = 0; n < matrices; n++)
3027         for (i = 0; i < 64; i++)
3028             s->base_matrix[n][i] = get_bits(gb, 8);
3029
3030     for (inter = 0; inter <= 1; inter++) {
3031         for (plane = 0; plane <= 2; plane++) {
3032             int newqr = 1;
3033             if (inter || plane > 0)
3034                 newqr = get_bits1(gb);
3035             if (!newqr) {
3036                 int qtj, plj;
3037                 if (inter && get_bits1(gb)) {
3038                     qtj = 0;
3039                     plj = plane;
3040                 } else {
3041                     qtj = (3 * inter + plane - 1) / 3;
3042                     plj = (plane + 2) % 3;
3043                 }
3044                 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
3045                 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
3046                        sizeof(s->qr_size[0][0]));
3047                 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
3048                        sizeof(s->qr_base[0][0]));
3049             } else {
3050                 int qri = 0;
3051                 int qi  = 0;
3052
3053                 for (;;) {
3054                     i = get_bits(gb, av_log2(matrices - 1) + 1);
3055                     if (i >= matrices) {
3056                         av_log(avctx, AV_LOG_ERROR,
3057                                "invalid base matrix index\n");
3058                         return -1;
3059                     }
3060                     s->qr_base[inter][plane][qri] = i;
3061                     if (qi >= 63)
3062                         break;
3063                     i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
3064                     s->qr_size[inter][plane][qri++] = i;
3065                     qi += i;
3066                 }
3067
3068                 if (qi > 63) {
3069                     av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
3070                     return -1;
3071                 }
3072                 s->qr_count[inter][plane] = qri;
3073             }
3074         }
3075     }
3076
3077     /* Huffman tables */
3078     for (int i = 0; i < FF_ARRAY_ELEMS(s->huffman_table); i++) {
3079         s->huffman_table[i].nb_entries = 0;
3080         if ((ret = read_huffman_tree(&s->huffman_table[i], gb, 0, avctx)) < 0)
3081             return ret;
3082     }
3083
3084     s->theora_tables = 1;
3085
3086     return 0;
3087 }
3088
3089 static av_cold int theora_decode_init(AVCodecContext *avctx)
3090 {
3091     Vp3DecodeContext *s = avctx->priv_data;
3092     GetBitContext gb;
3093     int ptype;
3094     const uint8_t *header_start[3];
3095     int header_len[3];
3096     int i;
3097     int ret;
3098
3099     avctx->pix_fmt = AV_PIX_FMT_YUV420P;
3100
3101     s->theora = 1;
3102
3103     if (!avctx->extradata_size) {
3104         av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
3105         return -1;
3106     }
3107
3108     if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
3109                                   42, header_start, header_len) < 0) {
3110         av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
3111         return -1;
3112     }
3113
3114     for (i = 0; i < 3; i++) {
3115         if (header_len[i] <= 0)
3116             continue;
3117         ret = init_get_bits8(&gb, header_start[i], header_len[i]);
3118         if (ret < 0)
3119             return ret;
3120
3121         ptype = get_bits(&gb, 8);
3122
3123         if (!(ptype & 0x80)) {
3124             av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
3125 //          return -1;
3126         }
3127
3128         // FIXME: Check for this as well.
3129         skip_bits_long(&gb, 6 * 8); /* "theora" */
3130
3131         switch (ptype) {
3132         case 0x80:
3133             if (theora_decode_header(avctx, &gb) < 0)
3134                 return -1;
3135             break;
3136         case 0x81:
3137 // FIXME: is this needed? it breaks sometimes
3138 //            theora_decode_comments(avctx, gb);
3139             break;
3140         case 0x82:
3141             if (theora_decode_tables(avctx, &gb))
3142                 return -1;
3143             break;
3144         default:
3145             av_log(avctx, AV_LOG_ERROR,
3146                    "Unknown Theora config packet: %d\n", ptype & ~0x80);
3147             break;
3148         }
3149         if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
3150             av_log(avctx, AV_LOG_WARNING,
3151                    "%d bits left in packet %X\n",
3152                    8 * header_len[i] - get_bits_count(&gb), ptype);
3153         if (s->theora < 0x030200)
3154             break;
3155     }
3156
3157     return vp3_decode_init(avctx);
3158 }
3159
3160 AVCodec ff_theora_decoder = {
3161     .name                  = "theora",
3162     .long_name             = NULL_IF_CONFIG_SMALL("Theora"),
3163     .type                  = AVMEDIA_TYPE_VIDEO,
3164     .id                    = AV_CODEC_ID_THEORA,
3165     .priv_data_size        = sizeof(Vp3DecodeContext),
3166     .init                  = theora_decode_init,
3167     .close                 = vp3_decode_end,
3168     .decode                = vp3_decode_frame,
3169     .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3170                              AV_CODEC_CAP_FRAME_THREADS,
3171     .flush                 = vp3_decode_flush,
3172     .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3173     .caps_internal         = FF_CODEC_CAP_EXPORTS_CROPPING | FF_CODEC_CAP_ALLOCATE_PROGRESS |
3174                              FF_CODEC_CAP_INIT_CLEANUP,
3175 };
3176 #endif
3177
3178 AVCodec ff_vp3_decoder = {
3179     .name                  = "vp3",
3180     .long_name             = NULL_IF_CONFIG_SMALL("On2 VP3"),
3181     .type                  = AVMEDIA_TYPE_VIDEO,
3182     .id                    = AV_CODEC_ID_VP3,
3183     .priv_data_size        = sizeof(Vp3DecodeContext),
3184     .init                  = vp3_decode_init,
3185     .close                 = vp3_decode_end,
3186     .decode                = vp3_decode_frame,
3187     .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3188                              AV_CODEC_CAP_FRAME_THREADS,
3189     .flush                 = vp3_decode_flush,
3190     .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3191     .caps_internal         = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
3192 };
3193
3194 #if CONFIG_VP4_DECODER
3195 AVCodec ff_vp4_decoder = {
3196     .name                  = "vp4",
3197     .long_name             = NULL_IF_CONFIG_SMALL("On2 VP4"),
3198     .type                  = AVMEDIA_TYPE_VIDEO,
3199     .id                    = AV_CODEC_ID_VP4,
3200     .priv_data_size        = sizeof(Vp3DecodeContext),
3201     .init                  = vp3_decode_init,
3202     .close                 = vp3_decode_end,
3203     .decode                = vp3_decode_frame,
3204     .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3205                              AV_CODEC_CAP_FRAME_THREADS,
3206     .flush                 = vp3_decode_flush,
3207     .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3208     .caps_internal         = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
3209 };
3210 #endif