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