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