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