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