]> git.sesse.net Git - ffmpeg/blob - libavcodec/vp3.c
vp3: Init MVs to 0
[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 libavcodec/vp3.c
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 "avcodec.h"
37 #include "dsputil.h"
38 #include "get_bits.h"
39
40 #include "vp3data.h"
41 #include "xiph.h"
42
43 #define FRAGMENT_PIXELS 8
44
45 static av_cold int vp3_decode_end(AVCodecContext *avctx);
46
47 //FIXME split things out into their own arrays
48 typedef struct Vp3Fragment {
49     int16_t dc;
50     uint8_t coding_method;
51     int8_t motion_x;
52     int8_t motion_y;
53     uint8_t qpi;
54 } Vp3Fragment;
55
56 #define SB_NOT_CODED        0
57 #define SB_PARTIALLY_CODED  1
58 #define SB_FULLY_CODED      2
59
60 // This is the maximum length of a single long bit run that can be encoded
61 // for superblock coding or block qps. Theora special-cases this to read a
62 // bit instead of flipping the current bit to allow for runs longer than 4129.
63 #define MAXIMUM_LONG_BIT_RUN 4129
64
65 #define MODE_INTER_NO_MV      0
66 #define MODE_INTRA            1
67 #define MODE_INTER_PLUS_MV    2
68 #define MODE_INTER_LAST_MV    3
69 #define MODE_INTER_PRIOR_LAST 4
70 #define MODE_USING_GOLDEN     5
71 #define MODE_GOLDEN_MV        6
72 #define MODE_INTER_FOURMV     7
73 #define CODING_MODE_COUNT     8
74
75 /* special internal mode */
76 #define MODE_COPY             8
77
78 /* There are 6 preset schemes, plus a free-form scheme */
79 static const int ModeAlphabet[6][CODING_MODE_COUNT] =
80 {
81     /* scheme 1: Last motion vector dominates */
82     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
83          MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
84          MODE_INTRA,            MODE_USING_GOLDEN,
85          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
86
87     /* scheme 2 */
88     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
89          MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
90          MODE_INTRA,            MODE_USING_GOLDEN,
91          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
92
93     /* scheme 3 */
94     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
95          MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
96          MODE_INTRA,            MODE_USING_GOLDEN,
97          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
98
99     /* scheme 4 */
100     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
101          MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
102          MODE_INTRA,            MODE_USING_GOLDEN,
103          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
104
105     /* scheme 5: No motion vector dominates */
106     {    MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,
107          MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
108          MODE_INTRA,            MODE_USING_GOLDEN,
109          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
110
111     /* scheme 6 */
112     {    MODE_INTER_NO_MV,      MODE_USING_GOLDEN,
113          MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
114          MODE_INTER_PLUS_MV,    MODE_INTRA,
115          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
116
117 };
118
119 static const uint8_t hilbert_offset[16][2] = {
120     {0,0}, {1,0}, {1,1}, {0,1},
121     {0,2}, {0,3}, {1,3}, {1,2},
122     {2,2}, {2,3}, {3,3}, {3,2},
123     {3,1}, {2,1}, {2,0}, {3,0}
124 };
125
126 #define MIN_DEQUANT_VAL 2
127
128 typedef struct Vp3DecodeContext {
129     AVCodecContext *avctx;
130     int theora, theora_tables;
131     int version;
132     int width, height;
133     AVFrame golden_frame;
134     AVFrame last_frame;
135     AVFrame current_frame;
136     int keyframe;
137     DSPContext dsp;
138     int flipped_image;
139     int last_slice_end;
140
141     int qps[3];
142     int nqps;
143     int last_qps[3];
144
145     int superblock_count;
146     int y_superblock_width;
147     int y_superblock_height;
148     int y_superblock_count;
149     int c_superblock_width;
150     int c_superblock_height;
151     int c_superblock_count;
152     int u_superblock_start;
153     int v_superblock_start;
154     unsigned char *superblock_coding;
155
156     int macroblock_count;
157     int macroblock_width;
158     int macroblock_height;
159
160     int fragment_count;
161     int fragment_width;
162     int fragment_height;
163
164     Vp3Fragment *all_fragments;
165     int fragment_start[3];
166     int data_offset[3];
167
168     ScanTable scantable;
169
170     /* tables */
171     uint16_t coded_dc_scale_factor[64];
172     uint32_t coded_ac_scale_factor[64];
173     uint8_t base_matrix[384][64];
174     uint8_t qr_count[2][3];
175     uint8_t qr_size [2][3][64];
176     uint16_t qr_base[2][3][64];
177
178     /**
179      * This is a list of all tokens in bitstream order. Reordering takes place
180      * by pulling from each level during IDCT. As a consequence, IDCT must be
181      * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
182      * otherwise. The 32 different tokens with up to 12 bits of extradata are
183      * collapsed into 3 types, packed as follows:
184      *   (from the low to high bits)
185      *
186      * 2 bits: type (0,1,2)
187      *   0: EOB run, 14 bits for run length (12 needed)
188      *   1: zero run, 7 bits for run length
189      *                7 bits for the next coefficient (3 needed)
190      *   2: coefficient, 14 bits (11 needed)
191      *
192      * Coefficients are signed, so are packed in the highest bits for automatic
193      * sign extension.
194      */
195     int16_t *dct_tokens[3][64];
196     int16_t *dct_tokens_base;
197 #define TOKEN_EOB(eob_run)              ((eob_run) << 2)
198 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) << 9) + ((zero_run) << 2) + 1)
199 #define TOKEN_COEFF(coeff)              (((coeff) << 2) + 2)
200
201     /**
202      * number of blocks that contain DCT coefficients at the given level or higher
203      */
204     int num_coded_frags[3][64];
205     int total_num_coded_frags;
206
207     /* this is a list of indexes into the all_fragments array indicating
208      * which of the fragments are coded */
209     int *coded_fragment_list[3];
210
211     VLC dc_vlc[16];
212     VLC ac_vlc_1[16];
213     VLC ac_vlc_2[16];
214     VLC ac_vlc_3[16];
215     VLC ac_vlc_4[16];
216
217     VLC superblock_run_length_vlc;
218     VLC fragment_run_length_vlc;
219     VLC mode_code_vlc;
220     VLC motion_vector_vlc;
221
222     /* these arrays need to be on 16-byte boundaries since SSE2 operations
223      * index into them */
224     DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64];     //<qmat[qpi][is_inter][plane]
225
226     /* This table contains superblock_count * 16 entries. Each set of 16
227      * numbers corresponds to the fragment indexes 0..15 of the superblock.
228      * An entry will be -1 to indicate that no entry corresponds to that
229      * index. */
230     int *superblock_fragments;
231
232     /* This is an array that indicates how a particular macroblock
233      * is coded. */
234     unsigned char *macroblock_coding;
235
236     uint8_t edge_emu_buffer[9*2048]; //FIXME dynamic alloc
237     int8_t qscale_table[2048]; //FIXME dynamic alloc (width+15)/16
238
239     /* Huffman decode */
240     int hti;
241     unsigned int hbits;
242     int entries;
243     int huff_code_size;
244     uint16_t huffman_table[80][32][2];
245
246     uint8_t filter_limit_values[64];
247     DECLARE_ALIGNED(8, int, bounding_values_array)[256+2];
248 } Vp3DecodeContext;
249
250 /************************************************************************
251  * VP3 specific functions
252  ************************************************************************/
253
254 /*
255  * This function sets up all of the various blocks mappings:
256  * superblocks <-> fragments, macroblocks <-> fragments,
257  * superblocks <-> macroblocks
258  *
259  * Returns 0 is successful; returns 1 if *anything* went wrong.
260  */
261 static int init_block_mapping(Vp3DecodeContext *s)
262 {
263     int sb_x, sb_y, plane;
264     int x, y, i, j = 0;
265
266     for (plane = 0; plane < 3; plane++) {
267         int sb_width    = plane ? s->c_superblock_width  : s->y_superblock_width;
268         int sb_height   = plane ? s->c_superblock_height : s->y_superblock_height;
269         int frag_width  = s->fragment_width  >> !!plane;
270         int frag_height = s->fragment_height >> !!plane;
271
272         for (sb_y = 0; sb_y < sb_height; sb_y++)
273             for (sb_x = 0; sb_x < sb_width; sb_x++)
274                 for (i = 0; i < 16; i++) {
275                     x = 4*sb_x + hilbert_offset[i][0];
276                     y = 4*sb_y + hilbert_offset[i][1];
277
278                     if (x < frag_width && y < frag_height)
279                         s->superblock_fragments[j++] = s->fragment_start[plane] + y*frag_width + x;
280                     else
281                         s->superblock_fragments[j++] = -1;
282                 }
283     }
284
285     return 0;  /* successful path out */
286 }
287
288 /*
289  * This function wipes out all of the fragment data.
290  */
291 static void init_frame(Vp3DecodeContext *s, GetBitContext *gb)
292 {
293     int i;
294
295     /* zero out all of the fragment information */
296     for (i = 0; i < s->fragment_count; i++) {
297         s->all_fragments[i].motion_x = 0;
298         s->all_fragments[i].motion_y = 0;
299         s->all_fragments[i].dc = 0;
300         s->all_fragments[i].qpi = 0;
301     }
302 }
303
304 /*
305  * This function sets up the dequantization tables used for a particular
306  * frame.
307  */
308 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
309 {
310     int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
311     int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
312     int i, plane, inter, qri, bmi, bmj, qistart;
313
314     for(inter=0; inter<2; inter++){
315         for(plane=0; plane<3; plane++){
316             int sum=0;
317             for(qri=0; qri<s->qr_count[inter][plane]; qri++){
318                 sum+= s->qr_size[inter][plane][qri];
319                 if(s->qps[qpi] <= sum)
320                     break;
321             }
322             qistart= sum - s->qr_size[inter][plane][qri];
323             bmi= s->qr_base[inter][plane][qri  ];
324             bmj= s->qr_base[inter][plane][qri+1];
325             for(i=0; i<64; i++){
326                 int coeff= (  2*(sum    -s->qps[qpi])*s->base_matrix[bmi][i]
327                             - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
328                             + s->qr_size[inter][plane][qri])
329                            / (2*s->qr_size[inter][plane][qri]);
330
331                 int qmin= 8<<(inter + !i);
332                 int qscale= i ? ac_scale_factor : dc_scale_factor;
333
334                 s->qmat[qpi][inter][plane][s->dsp.idct_permutation[i]]= av_clip((qscale * coeff)/100 * 4, qmin, 4096);
335             }
336             // all DC coefficients use the same quant so as not to interfere with DC prediction
337             s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
338         }
339     }
340
341     memset(s->qscale_table, (FFMAX(s->qmat[0][0][0][1], s->qmat[0][0][1][1])+8)/16, 512); //FIXME finetune
342 }
343
344 /*
345  * This function initializes the loop filter boundary limits if the frame's
346  * quality index is different from the previous frame's.
347  *
348  * The filter_limit_values may not be larger than 127.
349  */
350 static void init_loop_filter(Vp3DecodeContext *s)
351 {
352     int *bounding_values= s->bounding_values_array+127;
353     int filter_limit;
354     int x;
355     int value;
356
357     filter_limit = s->filter_limit_values[s->qps[0]];
358
359     /* set up the bounding values */
360     memset(s->bounding_values_array, 0, 256 * sizeof(int));
361     for (x = 0; x < filter_limit; x++) {
362         bounding_values[-x] = -x;
363         bounding_values[x] = x;
364     }
365     for (x = value = filter_limit; x < 128 && value; x++, value--) {
366         bounding_values[ x] =  value;
367         bounding_values[-x] = -value;
368     }
369     if (value)
370         bounding_values[128] = value;
371     bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
372 }
373
374 /*
375  * This function unpacks all of the superblock/macroblock/fragment coding
376  * information from the bitstream.
377  */
378 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
379 {
380     int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };
381     int bit = 0;
382     int current_superblock = 0;
383     int current_run = 0;
384     int num_partial_superblocks = 0;
385
386     int i, j;
387     int current_fragment;
388     int plane;
389
390     if (s->keyframe) {
391         memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
392
393     } else {
394
395         /* unpack the list of partially-coded superblocks */
396         bit = get_bits1(gb);
397         while (current_superblock < s->superblock_count) {
398                 current_run = get_vlc2(gb,
399                     s->superblock_run_length_vlc.table, 6, 2) + 1;
400                 if (current_run == 34)
401                     current_run += get_bits(gb, 12);
402
403             if (current_superblock + current_run > s->superblock_count) {
404                 av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");
405                 return -1;
406             }
407
408             memset(s->superblock_coding + current_superblock, bit, current_run);
409
410             current_superblock += current_run;
411             if (bit)
412                 num_partial_superblocks += current_run;
413
414             if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
415                 bit = get_bits1(gb);
416             else
417                 bit ^= 1;
418         }
419
420         /* unpack the list of fully coded superblocks if any of the blocks were
421          * not marked as partially coded in the previous step */
422         if (num_partial_superblocks < s->superblock_count) {
423             int superblocks_decoded = 0;
424
425             current_superblock = 0;
426             bit = get_bits1(gb);
427             while (superblocks_decoded < s->superblock_count - num_partial_superblocks) {
428                         current_run = get_vlc2(gb,
429                             s->superblock_run_length_vlc.table, 6, 2) + 1;
430                         if (current_run == 34)
431                             current_run += get_bits(gb, 12);
432
433                 for (j = 0; j < current_run; current_superblock++) {
434                     if (current_superblock >= s->superblock_count) {
435                         av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");
436                         return -1;
437                     }
438
439                 /* skip any superblocks already marked as partially coded */
440                 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
441                     s->superblock_coding[current_superblock] = 2*bit;
442                     j++;
443                 }
444                 }
445                 superblocks_decoded += current_run;
446
447                 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
448                     bit = get_bits1(gb);
449                 else
450                     bit ^= 1;
451             }
452         }
453
454         /* if there were partial blocks, initialize bitstream for
455          * unpacking fragment codings */
456         if (num_partial_superblocks) {
457
458             current_run = 0;
459             bit = get_bits1(gb);
460             /* toggle the bit because as soon as the first run length is
461              * fetched the bit will be toggled again */
462             bit ^= 1;
463         }
464     }
465
466     /* figure out which fragments are coded; iterate through each
467      * superblock (all planes) */
468     s->total_num_coded_frags = 0;
469     memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
470
471     for (plane = 0; plane < 3; plane++) {
472         int sb_start = superblock_starts[plane];
473         int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
474         int num_coded_frags = 0;
475
476     for (i = sb_start; i < sb_end; i++) {
477
478         /* iterate through all 16 fragments in a superblock */
479         for (j = 0; j < 16; j++) {
480
481             /* if the fragment is in bounds, check its coding status */
482             current_fragment = s->superblock_fragments[i * 16 + j];
483             if (current_fragment >= s->fragment_count) {
484                 av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_superblocks(): bad fragment number (%d >= %d)\n",
485                     current_fragment, s->fragment_count);
486                 return 1;
487             }
488             if (current_fragment != -1) {
489                 int coded = s->superblock_coding[i];
490
491                 if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
492
493                     /* fragment may or may not be coded; this is the case
494                      * that cares about the fragment coding runs */
495                     if (current_run-- == 0) {
496                         bit ^= 1;
497                         current_run = get_vlc2(gb,
498                             s->fragment_run_length_vlc.table, 5, 2);
499                     }
500                     coded = bit;
501                 }
502
503                     if (coded) {
504                         /* default mode; actual mode will be decoded in
505                          * the next phase */
506                         s->all_fragments[current_fragment].coding_method =
507                             MODE_INTER_NO_MV;
508                         s->coded_fragment_list[plane][num_coded_frags++] =
509                             current_fragment;
510                     } else {
511                         /* not coded; copy this fragment from the prior frame */
512                         s->all_fragments[current_fragment].coding_method =
513                             MODE_COPY;
514                     }
515             }
516         }
517     }
518         s->total_num_coded_frags += num_coded_frags;
519         for (i = 0; i < 64; i++)
520             s->num_coded_frags[plane][i] = num_coded_frags;
521         if (plane < 2)
522             s->coded_fragment_list[plane+1] = s->coded_fragment_list[plane] + num_coded_frags;
523     }
524     return 0;
525 }
526
527 /*
528  * This function unpacks all the coding mode data for individual macroblocks
529  * from the bitstream.
530  */
531 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
532 {
533     int i, j, k, sb_x, sb_y;
534     int scheme;
535     int current_macroblock;
536     int current_fragment;
537     int coding_mode;
538     int custom_mode_alphabet[CODING_MODE_COUNT];
539     const int *alphabet;
540
541     if (s->keyframe) {
542         for (i = 0; i < s->fragment_count; i++)
543             s->all_fragments[i].coding_method = MODE_INTRA;
544
545     } else {
546
547         /* fetch the mode coding scheme for this frame */
548         scheme = get_bits(gb, 3);
549
550         /* is it a custom coding scheme? */
551         if (scheme == 0) {
552             for (i = 0; i < 8; i++)
553                 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
554             for (i = 0; i < 8; i++)
555                 custom_mode_alphabet[get_bits(gb, 3)] = i;
556             alphabet = custom_mode_alphabet;
557         } else
558             alphabet = ModeAlphabet[scheme-1];
559
560         /* iterate through all of the macroblocks that contain 1 or more
561          * coded fragments */
562         for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
563             for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
564
565             for (j = 0; j < 4; j++) {
566                 int mb_x = 2*sb_x +   (j>>1);
567                 int mb_y = 2*sb_y + (((j>>1)+j)&1);
568                 current_macroblock = mb_y * s->macroblock_width + mb_x;
569
570                 if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height)
571                     continue;
572
573 #define BLOCK_X (2*mb_x + (k&1))
574 #define BLOCK_Y (2*mb_y + (k>>1))
575                 /* coding modes are only stored if the macroblock has at least one
576                  * luma block coded, otherwise it must be INTER_NO_MV */
577                 for (k = 0; k < 4; k++) {
578                     current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;
579                     if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
580                         break;
581                 }
582                 if (k == 4) {
583                     s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
584                     continue;
585                 }
586
587                 /* mode 7 means get 3 bits for each coding mode */
588                 if (scheme == 7)
589                     coding_mode = get_bits(gb, 3);
590                 else
591                     coding_mode = alphabet
592                         [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
593
594                 s->macroblock_coding[current_macroblock] = coding_mode;
595                 for (k = 0; k < 4; k++) {
596                     current_fragment =
597                         BLOCK_Y*s->fragment_width + BLOCK_X;
598                     if (s->all_fragments[current_fragment].coding_method !=
599                         MODE_COPY)
600                         s->all_fragments[current_fragment].coding_method =
601                             coding_mode;
602                 }
603                 for (k = 0; k < 2; k++) {
604                     current_fragment = s->fragment_start[k+1] +
605                         mb_y*(s->fragment_width>>1) + mb_x;
606                     if (s->all_fragments[current_fragment].coding_method !=
607                         MODE_COPY)
608                         s->all_fragments[current_fragment].coding_method =
609                             coding_mode;
610                 }
611             }
612             }
613         }
614     }
615
616     return 0;
617 }
618
619 /*
620  * This function unpacks all the motion vectors for the individual
621  * macroblocks from the bitstream.
622  */
623 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
624 {
625     int j, k, sb_x, sb_y;
626     int coding_mode;
627     int motion_x[6];
628     int motion_y[6];
629     int last_motion_x = 0;
630     int last_motion_y = 0;
631     int prior_last_motion_x = 0;
632     int prior_last_motion_y = 0;
633     int current_macroblock;
634     int current_fragment;
635
636     if (s->keyframe)
637         return 0;
638
639     memset(motion_x, 0, 6 * sizeof(int));
640     memset(motion_y, 0, 6 * sizeof(int));
641
642     /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
643     coding_mode = get_bits1(gb);
644
645     /* iterate through all of the macroblocks that contain 1 or more
646      * coded fragments */
647     for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
648         for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
649
650         for (j = 0; j < 4; j++) {
651             int mb_x = 2*sb_x +   (j>>1);
652             int mb_y = 2*sb_y + (((j>>1)+j)&1);
653             current_macroblock = mb_y * s->macroblock_width + mb_x;
654
655             if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
656                 (s->macroblock_coding[current_macroblock] == MODE_COPY))
657                 continue;
658
659             switch (s->macroblock_coding[current_macroblock]) {
660
661             case MODE_INTER_PLUS_MV:
662             case MODE_GOLDEN_MV:
663                 /* all 6 fragments use the same motion vector */
664                 if (coding_mode == 0) {
665                     motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
666                     motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
667                 } else {
668                     motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
669                     motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
670                 }
671
672                 /* vector maintenance, only on MODE_INTER_PLUS_MV */
673                 if (s->macroblock_coding[current_macroblock] ==
674                     MODE_INTER_PLUS_MV) {
675                     prior_last_motion_x = last_motion_x;
676                     prior_last_motion_y = last_motion_y;
677                     last_motion_x = motion_x[0];
678                     last_motion_y = motion_y[0];
679                 }
680                 break;
681
682             case MODE_INTER_FOURMV:
683                 /* vector maintenance */
684                 prior_last_motion_x = last_motion_x;
685                 prior_last_motion_y = last_motion_y;
686
687                 /* fetch 4 vectors from the bitstream, one for each
688                  * Y fragment, then average for the C fragment vectors */
689                 motion_x[4] = motion_y[4] = 0;
690                 for (k = 0; k < 4; k++) {
691                     current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;
692                     if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
693                         if (coding_mode == 0) {
694                             motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
695                             motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
696                         } else {
697                             motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
698                             motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
699                         }
700                         last_motion_x = motion_x[k];
701                         last_motion_y = motion_y[k];
702                     } else {
703                         motion_x[k] = 0;
704                         motion_y[k] = 0;
705                     }
706                     motion_x[4] += motion_x[k];
707                     motion_y[4] += motion_y[k];
708                 }
709
710                 motion_x[5]=
711                 motion_x[4]= RSHIFT(motion_x[4], 2);
712                 motion_y[5]=
713                 motion_y[4]= RSHIFT(motion_y[4], 2);
714                 break;
715
716             case MODE_INTER_LAST_MV:
717                 /* all 6 fragments use the last motion vector */
718                 motion_x[0] = last_motion_x;
719                 motion_y[0] = last_motion_y;
720
721                 /* no vector maintenance (last vector remains the
722                  * last vector) */
723                 break;
724
725             case MODE_INTER_PRIOR_LAST:
726                 /* all 6 fragments use the motion vector prior to the
727                  * last motion vector */
728                 motion_x[0] = prior_last_motion_x;
729                 motion_y[0] = prior_last_motion_y;
730
731                 /* vector maintenance */
732                 prior_last_motion_x = last_motion_x;
733                 prior_last_motion_y = last_motion_y;
734                 last_motion_x = motion_x[0];
735                 last_motion_y = motion_y[0];
736                 break;
737
738             default:
739                 /* covers intra, inter without MV, golden without MV */
740                 motion_x[0] = 0;
741                 motion_y[0] = 0;
742
743                 /* no vector maintenance */
744                 break;
745             }
746
747             /* assign the motion vectors to the correct fragments */
748             for (k = 0; k < 4; k++) {
749                 current_fragment =
750                     BLOCK_Y*s->fragment_width + BLOCK_X;
751                 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
752                     s->all_fragments[current_fragment].motion_x = motion_x[k];
753                     s->all_fragments[current_fragment].motion_y = motion_y[k];
754                 } else {
755                     s->all_fragments[current_fragment].motion_x = motion_x[0];
756                     s->all_fragments[current_fragment].motion_y = motion_y[0];
757                 }
758             }
759             for (k = 0; k < 2; k++) {
760                 current_fragment = s->fragment_start[k+1] +
761                     mb_y*(s->fragment_width>>1) + mb_x;
762                 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
763                     s->all_fragments[current_fragment].motion_x = motion_x[k+4];
764                     s->all_fragments[current_fragment].motion_y = motion_y[k+4];
765                 } else {
766                     s->all_fragments[current_fragment].motion_x = motion_x[0];
767                     s->all_fragments[current_fragment].motion_y = motion_y[0];
768                 }
769             }
770         }
771         }
772     }
773
774     return 0;
775 }
776
777 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
778 {
779     int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
780     int num_blocks = s->total_num_coded_frags;
781
782     for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
783         i = blocks_decoded = num_blocks_at_qpi = 0;
784
785         bit = get_bits1(gb);
786
787         do {
788             run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
789             if (run_length == 34)
790                 run_length += get_bits(gb, 12);
791             blocks_decoded += run_length;
792
793             if (!bit)
794                 num_blocks_at_qpi += run_length;
795
796             for (j = 0; j < run_length; i++) {
797                 if (i >= s->total_num_coded_frags)
798                     return -1;
799
800                 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
801                     s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
802                     j++;
803                 }
804             }
805
806             if (run_length == MAXIMUM_LONG_BIT_RUN)
807                 bit = get_bits1(gb);
808             else
809                 bit ^= 1;
810         } while (blocks_decoded < num_blocks);
811
812         num_blocks -= num_blocks_at_qpi;
813     }
814
815     return 0;
816 }
817
818 /*
819  * This function is called by unpack_dct_coeffs() to extract the VLCs from
820  * the bitstream. The VLCs encode tokens which are used to unpack DCT
821  * data. This function unpacks all the VLCs for either the Y plane or both
822  * C planes, and is called for DC coefficients or different AC coefficient
823  * levels (since different coefficient types require different VLC tables.
824  *
825  * This function returns a residual eob run. E.g, if a particular token gave
826  * instructions to EOB the next 5 fragments and there were only 2 fragments
827  * left in the current fragment range, 3 would be returned so that it could
828  * be passed into the next call to this same function.
829  */
830 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
831                         VLC *table, int coeff_index,
832                         int plane,
833                         int eob_run)
834 {
835     int i, j = 0;
836     int token;
837     int zero_run = 0;
838     DCTELEM coeff = 0;
839     int bits_to_get;
840     int blocks_ended;
841     int coeff_i = 0;
842     int num_coeffs = s->num_coded_frags[plane][coeff_index];
843     int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
844
845     /* local references to structure members to avoid repeated deferences */
846     int *coded_fragment_list = s->coded_fragment_list[plane];
847     Vp3Fragment *all_fragments = s->all_fragments;
848     VLC_TYPE (*vlc_table)[2] = table->table;
849
850     if (num_coeffs < 0)
851         av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
852
853     if (eob_run > num_coeffs) {
854         coeff_i = blocks_ended = num_coeffs;
855         eob_run -= num_coeffs;
856     } else {
857         coeff_i = blocks_ended = eob_run;
858         eob_run = 0;
859     }
860
861     // insert fake EOB token to cover the split between planes or zzi
862     if (blocks_ended)
863         dct_tokens[j++] = blocks_ended << 2;
864
865     while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
866             /* decode a VLC into a token */
867             token = get_vlc2(gb, vlc_table, 5, 3);
868             /* use the token to get a zero run, a coefficient, and an eob run */
869             if (token <= 6) {
870                 eob_run = eob_run_base[token];
871                 if (eob_run_get_bits[token])
872                     eob_run += get_bits(gb, eob_run_get_bits[token]);
873
874                 // record only the number of blocks ended in this plane,
875                 // any spill will be recorded in the next plane.
876                 if (eob_run > num_coeffs - coeff_i) {
877                     dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
878                     blocks_ended   += num_coeffs - coeff_i;
879                     eob_run        -= num_coeffs - coeff_i;
880                     coeff_i         = num_coeffs;
881                 } else {
882                     dct_tokens[j++] = TOKEN_EOB(eob_run);
883                     blocks_ended   += eob_run;
884                     coeff_i        += eob_run;
885                     eob_run = 0;
886                 }
887             } else {
888                 bits_to_get = coeff_get_bits[token];
889                 if (bits_to_get)
890                     bits_to_get = get_bits(gb, bits_to_get);
891                 coeff = coeff_tables[token][bits_to_get];
892
893                 zero_run = zero_run_base[token];
894                 if (zero_run_get_bits[token])
895                     zero_run += get_bits(gb, zero_run_get_bits[token]);
896
897                 if (zero_run) {
898                     dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
899                 } else {
900                     // Save DC into the fragment structure. DC prediction is
901                     // done in raster order, so the actual DC can't be in with
902                     // other tokens. We still need the token in dct_tokens[]
903                     // however, or else the structure collapses on itself.
904                     if (!coeff_index)
905                         all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
906
907                     dct_tokens[j++] = TOKEN_COEFF(coeff);
908                 }
909
910                 if (coeff_index + zero_run > 64) {
911                     av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
912                            " %d coeffs left\n", zero_run, 64-coeff_index);
913                     zero_run = 64 - coeff_index;
914                 }
915
916                 // zero runs code multiple coefficients,
917                 // so don't try to decode coeffs for those higher levels
918                 for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
919                     s->num_coded_frags[plane][i]--;
920                 coeff_i++;
921             }
922     }
923
924     if (blocks_ended > s->num_coded_frags[plane][coeff_index])
925         av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
926
927     // decrement the number of blocks that have higher coeffecients for each
928     // EOB run at this level
929     if (blocks_ended)
930         for (i = coeff_index+1; i < 64; i++)
931             s->num_coded_frags[plane][i] -= blocks_ended;
932
933     // setup the next buffer
934     if (plane < 2)
935         s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
936     else if (coeff_index < 63)
937         s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
938
939     return eob_run;
940 }
941
942 static void reverse_dc_prediction(Vp3DecodeContext *s,
943                                   int first_fragment,
944                                   int fragment_width,
945                                   int fragment_height);
946 /*
947  * This function unpacks all of the DCT coefficient data from the
948  * bitstream.
949  */
950 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
951 {
952     int i;
953     int dc_y_table;
954     int dc_c_table;
955     int ac_y_table;
956     int ac_c_table;
957     int residual_eob_run = 0;
958     VLC *y_tables[64];
959     VLC *c_tables[64];
960
961     s->dct_tokens[0][0] = s->dct_tokens_base;
962
963     /* fetch the DC table indexes */
964     dc_y_table = get_bits(gb, 4);
965     dc_c_table = get_bits(gb, 4);
966
967     /* unpack the Y plane DC coefficients */
968     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
969         0, residual_eob_run);
970
971     /* reverse prediction of the Y-plane DC coefficients */
972     reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);
973
974     /* unpack the C plane DC coefficients */
975     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
976         1, residual_eob_run);
977     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
978         2, residual_eob_run);
979
980     /* reverse prediction of the C-plane DC coefficients */
981     if (!(s->avctx->flags & CODEC_FLAG_GRAY))
982     {
983         reverse_dc_prediction(s, s->fragment_start[1],
984             s->fragment_width / 2, s->fragment_height / 2);
985         reverse_dc_prediction(s, s->fragment_start[2],
986             s->fragment_width / 2, s->fragment_height / 2);
987     }
988
989     /* fetch the AC table indexes */
990     ac_y_table = get_bits(gb, 4);
991     ac_c_table = get_bits(gb, 4);
992
993     /* build tables of AC VLC tables */
994     for (i = 1; i <= 5; i++) {
995         y_tables[i] = &s->ac_vlc_1[ac_y_table];
996         c_tables[i] = &s->ac_vlc_1[ac_c_table];
997     }
998     for (i = 6; i <= 14; i++) {
999         y_tables[i] = &s->ac_vlc_2[ac_y_table];
1000         c_tables[i] = &s->ac_vlc_2[ac_c_table];
1001     }
1002     for (i = 15; i <= 27; i++) {
1003         y_tables[i] = &s->ac_vlc_3[ac_y_table];
1004         c_tables[i] = &s->ac_vlc_3[ac_c_table];
1005     }
1006     for (i = 28; i <= 63; i++) {
1007         y_tables[i] = &s->ac_vlc_4[ac_y_table];
1008         c_tables[i] = &s->ac_vlc_4[ac_c_table];
1009     }
1010
1011     /* decode all AC coefficents */
1012     for (i = 1; i <= 63; i++) {
1013             residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1014                 0, residual_eob_run);
1015
1016             residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1017                 1, residual_eob_run);
1018             residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1019                 2, residual_eob_run);
1020     }
1021
1022     return 0;
1023 }
1024
1025 /*
1026  * This function reverses the DC prediction for each coded fragment in
1027  * the frame. Much of this function is adapted directly from the original
1028  * VP3 source code.
1029  */
1030 #define COMPATIBLE_FRAME(x) \
1031   (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1032 #define DC_COEFF(u) s->all_fragments[u].dc
1033
1034 static void reverse_dc_prediction(Vp3DecodeContext *s,
1035                                   int first_fragment,
1036                                   int fragment_width,
1037                                   int fragment_height)
1038 {
1039
1040 #define PUL 8
1041 #define PU 4
1042 #define PUR 2
1043 #define PL 1
1044
1045     int x, y;
1046     int i = first_fragment;
1047
1048     int predicted_dc;
1049
1050     /* DC values for the left, up-left, up, and up-right fragments */
1051     int vl, vul, vu, vur;
1052
1053     /* indexes for the left, up-left, up, and up-right fragments */
1054     int l, ul, u, ur;
1055
1056     /*
1057      * The 6 fields mean:
1058      *   0: up-left multiplier
1059      *   1: up multiplier
1060      *   2: up-right multiplier
1061      *   3: left multiplier
1062      */
1063     static const int predictor_transform[16][4] = {
1064         {  0,  0,  0,  0},
1065         {  0,  0,  0,128},        // PL
1066         {  0,  0,128,  0},        // PUR
1067         {  0,  0, 53, 75},        // PUR|PL
1068         {  0,128,  0,  0},        // PU
1069         {  0, 64,  0, 64},        // PU|PL
1070         {  0,128,  0,  0},        // PU|PUR
1071         {  0,  0, 53, 75},        // PU|PUR|PL
1072         {128,  0,  0,  0},        // PUL
1073         {  0,  0,  0,128},        // PUL|PL
1074         { 64,  0, 64,  0},        // PUL|PUR
1075         {  0,  0, 53, 75},        // PUL|PUR|PL
1076         {  0,128,  0,  0},        // PUL|PU
1077        {-104,116,  0,116},        // PUL|PU|PL
1078         { 24, 80, 24,  0},        // PUL|PU|PUR
1079        {-104,116,  0,116}         // PUL|PU|PUR|PL
1080     };
1081
1082     /* This table shows which types of blocks can use other blocks for
1083      * prediction. For example, INTRA is the only mode in this table to
1084      * have a frame number of 0. That means INTRA blocks can only predict
1085      * from other INTRA blocks. There are 2 golden frame coding types;
1086      * blocks encoding in these modes can only predict from other blocks
1087      * that were encoded with these 1 of these 2 modes. */
1088     static const unsigned char compatible_frame[9] = {
1089         1,    /* MODE_INTER_NO_MV */
1090         0,    /* MODE_INTRA */
1091         1,    /* MODE_INTER_PLUS_MV */
1092         1,    /* MODE_INTER_LAST_MV */
1093         1,    /* MODE_INTER_PRIOR_MV */
1094         2,    /* MODE_USING_GOLDEN */
1095         2,    /* MODE_GOLDEN_MV */
1096         1,    /* MODE_INTER_FOUR_MV */
1097         3     /* MODE_COPY */
1098     };
1099     int current_frame_type;
1100
1101     /* there is a last DC predictor for each of the 3 frame types */
1102     short last_dc[3];
1103
1104     int transform = 0;
1105
1106     vul = vu = vur = vl = 0;
1107     last_dc[0] = last_dc[1] = last_dc[2] = 0;
1108
1109     /* for each fragment row... */
1110     for (y = 0; y < fragment_height; y++) {
1111
1112         /* for each fragment in a row... */
1113         for (x = 0; x < fragment_width; x++, i++) {
1114
1115             /* reverse prediction if this block was coded */
1116             if (s->all_fragments[i].coding_method != MODE_COPY) {
1117
1118                 current_frame_type =
1119                     compatible_frame[s->all_fragments[i].coding_method];
1120
1121                 transform= 0;
1122                 if(x){
1123                     l= i-1;
1124                     vl = DC_COEFF(l);
1125                     if(COMPATIBLE_FRAME(l))
1126                         transform |= PL;
1127                 }
1128                 if(y){
1129                     u= i-fragment_width;
1130                     vu = DC_COEFF(u);
1131                     if(COMPATIBLE_FRAME(u))
1132                         transform |= PU;
1133                     if(x){
1134                         ul= i-fragment_width-1;
1135                         vul = DC_COEFF(ul);
1136                         if(COMPATIBLE_FRAME(ul))
1137                             transform |= PUL;
1138                     }
1139                     if(x + 1 < fragment_width){
1140                         ur= i-fragment_width+1;
1141                         vur = DC_COEFF(ur);
1142                         if(COMPATIBLE_FRAME(ur))
1143                             transform |= PUR;
1144                     }
1145                 }
1146
1147                 if (transform == 0) {
1148
1149                     /* if there were no fragments to predict from, use last
1150                      * DC saved */
1151                     predicted_dc = last_dc[current_frame_type];
1152                 } else {
1153
1154                     /* apply the appropriate predictor transform */
1155                     predicted_dc =
1156                         (predictor_transform[transform][0] * vul) +
1157                         (predictor_transform[transform][1] * vu) +
1158                         (predictor_transform[transform][2] * vur) +
1159                         (predictor_transform[transform][3] * vl);
1160
1161                     predicted_dc /= 128;
1162
1163                     /* check for outranging on the [ul u l] and
1164                      * [ul u ur l] predictors */
1165                     if ((transform == 15) || (transform == 13)) {
1166                         if (FFABS(predicted_dc - vu) > 128)
1167                             predicted_dc = vu;
1168                         else if (FFABS(predicted_dc - vl) > 128)
1169                             predicted_dc = vl;
1170                         else if (FFABS(predicted_dc - vul) > 128)
1171                             predicted_dc = vul;
1172                     }
1173                 }
1174
1175                 /* at long last, apply the predictor */
1176                 DC_COEFF(i) += predicted_dc;
1177                 /* save the DC */
1178                 last_dc[current_frame_type] = DC_COEFF(i);
1179             }
1180         }
1181     }
1182 }
1183
1184 static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1185 {
1186     int x, y;
1187     int *bounding_values= s->bounding_values_array+127;
1188
1189     int width           = s->fragment_width  >> !!plane;
1190     int height          = s->fragment_height >> !!plane;
1191     int fragment        = s->fragment_start        [plane] + ystart * width;
1192     int stride          = s->current_frame.linesize[plane];
1193     uint8_t *plane_data = s->current_frame.data    [plane];
1194     if (!s->flipped_image) stride = -stride;
1195     plane_data += s->data_offset[plane] + 8*ystart*stride;
1196
1197     for (y = ystart; y < yend; y++) {
1198
1199         for (x = 0; x < width; x++) {
1200             /* This code basically just deblocks on the edges of coded blocks.
1201              * However, it has to be much more complicated because of the
1202              * braindamaged deblock ordering used in VP3/Theora. Order matters
1203              * because some pixels get filtered twice. */
1204             if( s->all_fragments[fragment].coding_method != MODE_COPY )
1205             {
1206                 /* do not perform left edge filter for left columns frags */
1207                 if (x > 0) {
1208                     s->dsp.vp3_h_loop_filter(
1209                         plane_data + 8*x,
1210                         stride, bounding_values);
1211                 }
1212
1213                 /* do not perform top edge filter for top row fragments */
1214                 if (y > 0) {
1215                     s->dsp.vp3_v_loop_filter(
1216                         plane_data + 8*x,
1217                         stride, bounding_values);
1218                 }
1219
1220                 /* do not perform right edge filter for right column
1221                  * fragments or if right fragment neighbor is also coded
1222                  * in this frame (it will be filtered in next iteration) */
1223                 if ((x < width - 1) &&
1224                     (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1225                     s->dsp.vp3_h_loop_filter(
1226                         plane_data + 8*x + 8,
1227                         stride, bounding_values);
1228                 }
1229
1230                 /* do not perform bottom edge filter for bottom row
1231                  * fragments or if bottom fragment neighbor is also coded
1232                  * in this frame (it will be filtered in the next row) */
1233                 if ((y < height - 1) &&
1234                     (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1235                     s->dsp.vp3_v_loop_filter(
1236                         plane_data + 8*x + 8*stride,
1237                         stride, bounding_values);
1238                 }
1239             }
1240
1241             fragment++;
1242         }
1243         plane_data += 8*stride;
1244     }
1245 }
1246
1247 /**
1248  * Pulls DCT tokens from the 64 levels to decode and dequant the coefficients
1249  * for the next block in coding order
1250  */
1251 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1252                               int plane, int inter, DCTELEM block[64])
1253 {
1254     int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1255     uint8_t *perm = s->scantable.permutated;
1256     int i = 0;
1257
1258     do {
1259         int token = *s->dct_tokens[plane][i];
1260         switch (token & 3) {
1261         case 0: // EOB
1262             if (--token < 4) // 0-3 are token types, so the EOB run must now be 0
1263                 s->dct_tokens[plane][i]++;
1264             else
1265                 *s->dct_tokens[plane][i] = token & ~3;
1266             goto end;
1267         case 1: // zero run
1268             s->dct_tokens[plane][i]++;
1269             i += (token >> 2) & 0x7f;
1270             block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1271             i++;
1272             break;
1273         case 2: // coeff
1274             block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1275             s->dct_tokens[plane][i++]++;
1276             break;
1277         default:
1278             av_log(s->avctx, AV_LOG_ERROR, "internal: invalid token type\n");
1279             return i;
1280         }
1281     } while (i < 64);
1282 end:
1283     // the actual DC+prediction is in the fragment structure
1284     block[0] = frag->dc * s->qmat[0][inter][plane][0];
1285     return i;
1286 }
1287
1288 /**
1289  * called when all pixels up to row y are complete
1290  */
1291 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1292 {
1293     int h, cy;
1294     int offset[4];
1295
1296     if(s->avctx->draw_horiz_band==NULL)
1297         return;
1298
1299     h= y - s->last_slice_end;
1300     y -= h;
1301
1302     if (!s->flipped_image) {
1303         if (y == 0)
1304             h -= s->height - s->avctx->height;  // account for non-mod16
1305         y = s->height - y - h;
1306     }
1307
1308     cy = y >> 1;
1309     offset[0] = s->current_frame.linesize[0]*y;
1310     offset[1] = s->current_frame.linesize[1]*cy;
1311     offset[2] = s->current_frame.linesize[2]*cy;
1312     offset[3] = 0;
1313
1314     emms_c();
1315     s->avctx->draw_horiz_band(s->avctx, &s->current_frame, offset, y, 3, h);
1316     s->last_slice_end= y + h;
1317 }
1318
1319 /*
1320  * Perform the final rendering for a particular slice of data.
1321  * The slice number ranges from 0..(c_superblock_height - 1).
1322  */
1323 static void render_slice(Vp3DecodeContext *s, int slice)
1324 {
1325     int x, y, i, j;
1326     LOCAL_ALIGNED_16(DCTELEM, block, [64]);
1327     int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1328     int motion_halfpel_index;
1329     uint8_t *motion_source;
1330     int plane, first_pixel;
1331
1332     if (slice >= s->c_superblock_height)
1333         return;
1334
1335     for (plane = 0; plane < 3; plane++) {
1336         uint8_t *output_plane = s->current_frame.data    [plane] + s->data_offset[plane];
1337         uint8_t *  last_plane = s->   last_frame.data    [plane] + s->data_offset[plane];
1338         uint8_t *golden_plane = s-> golden_frame.data    [plane] + s->data_offset[plane];
1339         int stride            = s->current_frame.linesize[plane];
1340         int plane_width       = s->width  >> !!plane;
1341         int plane_height      = s->height >> !!plane;
1342
1343         int sb_x, sb_y        = slice << !plane;
1344         int slice_height      = sb_y + (plane ? 1 : 2);
1345         int slice_width       = plane ? s->c_superblock_width : s->y_superblock_width;
1346
1347         int fragment_width    = s->fragment_width  >> !!plane;
1348         int fragment_height   = s->fragment_height >> !!plane;
1349         int fragment_start    = s->fragment_start[plane];
1350
1351         if (!s->flipped_image) stride = -stride;
1352         if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1353             continue;
1354
1355
1356         if(FFABS(stride) > 2048)
1357             return; //various tables are fixed size
1358
1359         /* for each superblock row in the slice (both of them)... */
1360         for (; sb_y < slice_height; sb_y++) {
1361
1362             /* for each superblock in a row... */
1363             for (sb_x = 0; sb_x < slice_width; sb_x++) {
1364
1365                 /* for each block in a superblock... */
1366                 for (j = 0; j < 16; j++) {
1367                     x = 4*sb_x + hilbert_offset[j][0];
1368                     y = 4*sb_y + hilbert_offset[j][1];
1369
1370                     i = fragment_start + y*fragment_width + x;
1371
1372                     // bounds check
1373                     if (x >= fragment_width || y >= fragment_height)
1374                         continue;
1375
1376                 first_pixel = 8*y*stride + 8*x;
1377
1378                 /* transform if this block was coded */
1379                 if (s->all_fragments[i].coding_method != MODE_COPY) {
1380                     int intra = s->all_fragments[i].coding_method == MODE_INTRA;
1381
1382                     if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1383                         (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1384                         motion_source= golden_plane;
1385                     else
1386                         motion_source= last_plane;
1387
1388                     motion_source += first_pixel;
1389                     motion_halfpel_index = 0;
1390
1391                     /* sort out the motion vector if this fragment is coded
1392                      * using a motion vector method */
1393                     if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1394                         (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1395                         int src_x, src_y;
1396                         motion_x = s->all_fragments[i].motion_x;
1397                         motion_y = s->all_fragments[i].motion_y;
1398                         if(plane){
1399                             motion_x= (motion_x>>1) | (motion_x&1);
1400                             motion_y= (motion_y>>1) | (motion_y&1);
1401                         }
1402
1403                         src_x= (motion_x>>1) + 8*x;
1404                         src_y= (motion_y>>1) + 8*y;
1405
1406                         motion_halfpel_index = motion_x & 0x01;
1407                         motion_source += (motion_x >> 1);
1408
1409                         motion_halfpel_index |= (motion_y & 0x01) << 1;
1410                         motion_source += ((motion_y >> 1) * stride);
1411
1412                         if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1413                             uint8_t *temp= s->edge_emu_buffer;
1414                             if(stride<0) temp -= 9*stride;
1415                             else temp += 9*stride;
1416
1417                             ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
1418                             motion_source= temp;
1419                         }
1420                     }
1421
1422
1423                     /* first, take care of copying a block from either the
1424                      * previous or the golden frame */
1425                     if (s->all_fragments[i].coding_method != MODE_INTRA) {
1426                         /* Note, it is possible to implement all MC cases with
1427                            put_no_rnd_pixels_l2 which would look more like the
1428                            VP3 source but this would be slower as
1429                            put_no_rnd_pixels_tab is better optimzed */
1430                         if(motion_halfpel_index != 3){
1431                             s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1432                                 output_plane + first_pixel,
1433                                 motion_source, stride, 8);
1434                         }else{
1435                             int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1436                             s->dsp.put_no_rnd_pixels_l2[1](
1437                                 output_plane + first_pixel,
1438                                 motion_source - d,
1439                                 motion_source + stride + 1 + d,
1440                                 stride, 8);
1441                         }
1442                     }
1443
1444                         s->dsp.clear_block(block);
1445                         vp3_dequant(s, s->all_fragments + i, plane, !intra, block);
1446
1447                     /* invert DCT and place (or add) in final output */
1448
1449                     if (s->all_fragments[i].coding_method == MODE_INTRA) {
1450                         if(s->avctx->idct_algo!=FF_IDCT_VP3)
1451                             block[0] += 128<<3;
1452                         s->dsp.idct_put(
1453                             output_plane + first_pixel,
1454                             stride,
1455                             block);
1456                     } else {
1457                         s->dsp.idct_add(
1458                             output_plane + first_pixel,
1459                             stride,
1460                             block);
1461                     }
1462                 } else {
1463
1464                     /* copy directly from the previous frame */
1465                     s->dsp.put_pixels_tab[1][0](
1466                         output_plane + first_pixel,
1467                         last_plane + first_pixel,
1468                         stride, 8);
1469
1470                 }
1471                 }
1472             }
1473
1474             // Filter up to the last row in the superblock row
1475             apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
1476         }
1477     }
1478
1479      /* this looks like a good place for slice dispatch... */
1480      /* algorithm:
1481       *   if (slice == s->macroblock_height - 1)
1482       *     dispatch (both last slice & 2nd-to-last slice);
1483       *   else if (slice > 0)
1484       *     dispatch (slice - 1);
1485       */
1486
1487     vp3_draw_horiz_band(s, FFMIN(64*slice + 64-16, s->height-16));
1488 }
1489
1490 /*
1491  * This is the ffmpeg/libavcodec API init function.
1492  */
1493 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1494 {
1495     Vp3DecodeContext *s = avctx->priv_data;
1496     int i, inter, plane;
1497     int c_width;
1498     int c_height;
1499
1500     if (avctx->codec_tag == MKTAG('V','P','3','0'))
1501         s->version = 0;
1502     else
1503         s->version = 1;
1504
1505     s->avctx = avctx;
1506     s->width = FFALIGN(avctx->width, 16);
1507     s->height = FFALIGN(avctx->height, 16);
1508     avctx->pix_fmt = PIX_FMT_YUV420P;
1509     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1510     if(avctx->idct_algo==FF_IDCT_AUTO)
1511         avctx->idct_algo=FF_IDCT_VP3;
1512     dsputil_init(&s->dsp, avctx);
1513
1514     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
1515
1516     /* initialize to an impossible value which will force a recalculation
1517      * in the first frame decode */
1518     for (i = 0; i < 3; i++)
1519         s->qps[i] = -1;
1520
1521     s->y_superblock_width = (s->width + 31) / 32;
1522     s->y_superblock_height = (s->height + 31) / 32;
1523     s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1524
1525     /* work out the dimensions for the C planes */
1526     c_width = s->width / 2;
1527     c_height = s->height / 2;
1528     s->c_superblock_width = (c_width + 31) / 32;
1529     s->c_superblock_height = (c_height + 31) / 32;
1530     s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1531
1532     s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1533     s->u_superblock_start = s->y_superblock_count;
1534     s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1535     s->superblock_coding = av_malloc(s->superblock_count);
1536
1537     s->macroblock_width = (s->width + 15) / 16;
1538     s->macroblock_height = (s->height + 15) / 16;
1539     s->macroblock_count = s->macroblock_width * s->macroblock_height;
1540
1541     s->fragment_width = s->width / FRAGMENT_PIXELS;
1542     s->fragment_height = s->height / FRAGMENT_PIXELS;
1543
1544     /* fragment count covers all 8x8 blocks for all 3 planes */
1545     s->fragment_count = s->fragment_width * s->fragment_height * 3 / 2;
1546     s->fragment_start[1] = s->fragment_width * s->fragment_height;
1547     s->fragment_start[2] = s->fragment_width * s->fragment_height * 5 / 4;
1548
1549     s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
1550     s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
1551     s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
1552     if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
1553         !s->coded_fragment_list[0]) {
1554         vp3_decode_end(avctx);
1555         return -1;
1556     }
1557
1558     if (!s->theora_tables)
1559     {
1560         for (i = 0; i < 64; i++) {
1561             s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1562             s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1563             s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1564             s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1565             s->base_matrix[2][i] = vp31_inter_dequant[i];
1566             s->filter_limit_values[i] = vp31_filter_limit_values[i];
1567         }
1568
1569         for(inter=0; inter<2; inter++){
1570             for(plane=0; plane<3; plane++){
1571                 s->qr_count[inter][plane]= 1;
1572                 s->qr_size [inter][plane][0]= 63;
1573                 s->qr_base [inter][plane][0]=
1574                 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1575             }
1576         }
1577
1578         /* init VLC tables */
1579         for (i = 0; i < 16; i++) {
1580
1581             /* DC histograms */
1582             init_vlc(&s->dc_vlc[i], 5, 32,
1583                 &dc_bias[i][0][1], 4, 2,
1584                 &dc_bias[i][0][0], 4, 2, 0);
1585
1586             /* group 1 AC histograms */
1587             init_vlc(&s->ac_vlc_1[i], 5, 32,
1588                 &ac_bias_0[i][0][1], 4, 2,
1589                 &ac_bias_0[i][0][0], 4, 2, 0);
1590
1591             /* group 2 AC histograms */
1592             init_vlc(&s->ac_vlc_2[i], 5, 32,
1593                 &ac_bias_1[i][0][1], 4, 2,
1594                 &ac_bias_1[i][0][0], 4, 2, 0);
1595
1596             /* group 3 AC histograms */
1597             init_vlc(&s->ac_vlc_3[i], 5, 32,
1598                 &ac_bias_2[i][0][1], 4, 2,
1599                 &ac_bias_2[i][0][0], 4, 2, 0);
1600
1601             /* group 4 AC histograms */
1602             init_vlc(&s->ac_vlc_4[i], 5, 32,
1603                 &ac_bias_3[i][0][1], 4, 2,
1604                 &ac_bias_3[i][0][0], 4, 2, 0);
1605         }
1606     } else {
1607         for (i = 0; i < 16; i++) {
1608
1609             /* DC histograms */
1610             if (init_vlc(&s->dc_vlc[i], 5, 32,
1611                 &s->huffman_table[i][0][1], 4, 2,
1612                 &s->huffman_table[i][0][0], 4, 2, 0) < 0)
1613                 goto vlc_fail;
1614
1615             /* group 1 AC histograms */
1616             if (init_vlc(&s->ac_vlc_1[i], 5, 32,
1617                 &s->huffman_table[i+16][0][1], 4, 2,
1618                 &s->huffman_table[i+16][0][0], 4, 2, 0) < 0)
1619                 goto vlc_fail;
1620
1621             /* group 2 AC histograms */
1622             if (init_vlc(&s->ac_vlc_2[i], 5, 32,
1623                 &s->huffman_table[i+16*2][0][1], 4, 2,
1624                 &s->huffman_table[i+16*2][0][0], 4, 2, 0) < 0)
1625                 goto vlc_fail;
1626
1627             /* group 3 AC histograms */
1628             if (init_vlc(&s->ac_vlc_3[i], 5, 32,
1629                 &s->huffman_table[i+16*3][0][1], 4, 2,
1630                 &s->huffman_table[i+16*3][0][0], 4, 2, 0) < 0)
1631                 goto vlc_fail;
1632
1633             /* group 4 AC histograms */
1634             if (init_vlc(&s->ac_vlc_4[i], 5, 32,
1635                 &s->huffman_table[i+16*4][0][1], 4, 2,
1636                 &s->huffman_table[i+16*4][0][0], 4, 2, 0) < 0)
1637                 goto vlc_fail;
1638         }
1639     }
1640
1641     init_vlc(&s->superblock_run_length_vlc, 6, 34,
1642         &superblock_run_length_vlc_table[0][1], 4, 2,
1643         &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1644
1645     init_vlc(&s->fragment_run_length_vlc, 5, 30,
1646         &fragment_run_length_vlc_table[0][1], 4, 2,
1647         &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1648
1649     init_vlc(&s->mode_code_vlc, 3, 8,
1650         &mode_code_vlc_table[0][1], 2, 1,
1651         &mode_code_vlc_table[0][0], 2, 1, 0);
1652
1653     init_vlc(&s->motion_vector_vlc, 6, 63,
1654         &motion_vector_vlc_table[0][1], 2, 1,
1655         &motion_vector_vlc_table[0][0], 2, 1, 0);
1656
1657     /* work out the block mapping tables */
1658     s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
1659     s->macroblock_coding = av_malloc(s->macroblock_count + 1);
1660     if (!s->superblock_fragments || !s->macroblock_coding) {
1661         vp3_decode_end(avctx);
1662         return -1;
1663     }
1664     init_block_mapping(s);
1665
1666     for (i = 0; i < 3; i++) {
1667         s->current_frame.data[i] = NULL;
1668         s->last_frame.data[i] = NULL;
1669         s->golden_frame.data[i] = NULL;
1670     }
1671
1672     return 0;
1673
1674 vlc_fail:
1675     av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1676     return -1;
1677 }
1678
1679 /*
1680  * This is the ffmpeg/libavcodec API frame decode function.
1681  */
1682 static int vp3_decode_frame(AVCodecContext *avctx,
1683                             void *data, int *data_size,
1684                             AVPacket *avpkt)
1685 {
1686     const uint8_t *buf = avpkt->data;
1687     int buf_size = avpkt->size;
1688     Vp3DecodeContext *s = avctx->priv_data;
1689     GetBitContext gb;
1690     static int counter = 0;
1691     int i;
1692
1693     init_get_bits(&gb, buf, buf_size * 8);
1694
1695     if (s->theora && get_bits1(&gb))
1696     {
1697         av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1698         return -1;
1699     }
1700
1701     s->keyframe = !get_bits1(&gb);
1702     if (!s->theora)
1703         skip_bits(&gb, 1);
1704     for (i = 0; i < 3; i++)
1705         s->last_qps[i] = s->qps[i];
1706
1707     s->nqps=0;
1708     do{
1709         s->qps[s->nqps++]= get_bits(&gb, 6);
1710     } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
1711     for (i = s->nqps; i < 3; i++)
1712         s->qps[i] = -1;
1713
1714     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1715         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
1716             s->keyframe?"key":"", counter, s->qps[0]);
1717     counter++;
1718
1719     if (s->qps[0] != s->last_qps[0])
1720         init_loop_filter(s);
1721
1722     for (i = 0; i < s->nqps; i++)
1723         // reinit all dequantizers if the first one changed, because
1724         // the DC of the first quantizer must be used for all matrices
1725         if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
1726             init_dequantizer(s, i);
1727
1728     if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
1729         return buf_size;
1730
1731     s->current_frame.reference = 3;
1732     s->current_frame.pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
1733     if (avctx->get_buffer(avctx, &s->current_frame) < 0) {
1734         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1735         goto error;
1736     }
1737
1738     if (s->keyframe) {
1739         if (!s->theora)
1740         {
1741             skip_bits(&gb, 4); /* width code */
1742             skip_bits(&gb, 4); /* height code */
1743             if (s->version)
1744             {
1745                 s->version = get_bits(&gb, 5);
1746                 if (counter == 1)
1747                     av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
1748             }
1749         }
1750         if (s->version || s->theora)
1751         {
1752                 if (get_bits1(&gb))
1753                     av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
1754             skip_bits(&gb, 2); /* reserved? */
1755         }
1756     } else {
1757         if (!s->golden_frame.data[0]) {
1758             av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
1759
1760             s->golden_frame.reference = 3;
1761             s->golden_frame.pict_type = FF_I_TYPE;
1762             if (avctx->get_buffer(avctx, &s->golden_frame) < 0) {
1763                 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1764                 goto error;
1765             }
1766             s->last_frame = s->golden_frame;
1767             s->last_frame.type = FF_BUFFER_TYPE_COPY;
1768         }
1769     }
1770
1771     s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
1772     s->current_frame.qstride= 0;
1773
1774     init_frame(s, &gb);
1775
1776     if (unpack_superblocks(s, &gb)){
1777         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
1778         goto error;
1779     }
1780     if (unpack_modes(s, &gb)){
1781         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
1782         goto error;
1783     }
1784     if (unpack_vectors(s, &gb)){
1785         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
1786         goto error;
1787     }
1788     if (unpack_block_qpis(s, &gb)){
1789         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
1790         goto error;
1791     }
1792     if (unpack_dct_coeffs(s, &gb)){
1793         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
1794         goto error;
1795     }
1796
1797     for (i = 0; i < 3; i++) {
1798         if (s->flipped_image)
1799             s->data_offset[i] = 0;
1800         else
1801             s->data_offset[i] = ((s->height>>!!i)-1) * s->current_frame.linesize[i];
1802     }
1803
1804     s->last_slice_end = 0;
1805     for (i = 0; i < s->c_superblock_height; i++)
1806         render_slice(s, i);
1807
1808     // filter the last row
1809     for (i = 0; i < 3; i++) {
1810         int row = (s->height >> (3+!!i)) - 1;
1811         apply_loop_filter(s, i, row, row+1);
1812     }
1813     vp3_draw_horiz_band(s, s->height);
1814
1815     *data_size=sizeof(AVFrame);
1816     *(AVFrame*)data= s->current_frame;
1817
1818     /* release the last frame, if it is allocated and if it is not the
1819      * golden frame */
1820     if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1821         avctx->release_buffer(avctx, &s->last_frame);
1822
1823     /* shuffle frames (last = current) */
1824     s->last_frame= s->current_frame;
1825
1826     if (s->keyframe) {
1827         if (s->golden_frame.data[0])
1828             avctx->release_buffer(avctx, &s->golden_frame);
1829         s->golden_frame = s->current_frame;
1830         s->last_frame.type = FF_BUFFER_TYPE_COPY;
1831     }
1832
1833     s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
1834
1835     return buf_size;
1836
1837 error:
1838     if (s->current_frame.data[0])
1839         avctx->release_buffer(avctx, &s->current_frame);
1840     return -1;
1841 }
1842
1843 /*
1844  * This is the ffmpeg/libavcodec API module cleanup function.
1845  */
1846 static av_cold int vp3_decode_end(AVCodecContext *avctx)
1847 {
1848     Vp3DecodeContext *s = avctx->priv_data;
1849     int i;
1850
1851     av_free(s->superblock_coding);
1852     av_free(s->all_fragments);
1853     av_free(s->coded_fragment_list[0]);
1854     av_free(s->dct_tokens_base);
1855     av_free(s->superblock_fragments);
1856     av_free(s->macroblock_coding);
1857
1858     for (i = 0; i < 16; i++) {
1859         free_vlc(&s->dc_vlc[i]);
1860         free_vlc(&s->ac_vlc_1[i]);
1861         free_vlc(&s->ac_vlc_2[i]);
1862         free_vlc(&s->ac_vlc_3[i]);
1863         free_vlc(&s->ac_vlc_4[i]);
1864     }
1865
1866     free_vlc(&s->superblock_run_length_vlc);
1867     free_vlc(&s->fragment_run_length_vlc);
1868     free_vlc(&s->mode_code_vlc);
1869     free_vlc(&s->motion_vector_vlc);
1870
1871     /* release all frames */
1872     if (s->golden_frame.data[0])
1873         avctx->release_buffer(avctx, &s->golden_frame);
1874     if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1875         avctx->release_buffer(avctx, &s->last_frame);
1876     /* no need to release the current_frame since it will always be pointing
1877      * to the same frame as either the golden or last frame */
1878
1879     return 0;
1880 }
1881
1882 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
1883 {
1884     Vp3DecodeContext *s = avctx->priv_data;
1885
1886     if (get_bits1(gb)) {
1887         int token;
1888         if (s->entries >= 32) { /* overflow */
1889             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1890             return -1;
1891         }
1892         token = get_bits(gb, 5);
1893         //av_log(avctx, AV_LOG_DEBUG, "hti %d hbits %x token %d entry : %d size %d\n", s->hti, s->hbits, token, s->entries, s->huff_code_size);
1894         s->huffman_table[s->hti][token][0] = s->hbits;
1895         s->huffman_table[s->hti][token][1] = s->huff_code_size;
1896         s->entries++;
1897     }
1898     else {
1899         if (s->huff_code_size >= 32) {/* overflow */
1900             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1901             return -1;
1902         }
1903         s->huff_code_size++;
1904         s->hbits <<= 1;
1905         if (read_huffman_tree(avctx, gb))
1906             return -1;
1907         s->hbits |= 1;
1908         if (read_huffman_tree(avctx, gb))
1909             return -1;
1910         s->hbits >>= 1;
1911         s->huff_code_size--;
1912     }
1913     return 0;
1914 }
1915
1916 #if CONFIG_THEORA_DECODER
1917 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
1918 {
1919     Vp3DecodeContext *s = avctx->priv_data;
1920     int visible_width, visible_height, colorspace;
1921
1922     s->theora = get_bits_long(gb, 24);
1923     av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
1924
1925     /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
1926     /* but previous versions have the image flipped relative to vp3 */
1927     if (s->theora < 0x030200)
1928     {
1929         s->flipped_image = 1;
1930         av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
1931     }
1932
1933     visible_width  = s->width  = get_bits(gb, 16) << 4;
1934     visible_height = s->height = get_bits(gb, 16) << 4;
1935
1936     if(avcodec_check_dimensions(avctx, s->width, s->height)){
1937         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
1938         s->width= s->height= 0;
1939         return -1;
1940     }
1941
1942     if (s->theora >= 0x030200) {
1943         visible_width  = get_bits_long(gb, 24);
1944         visible_height = get_bits_long(gb, 24);
1945
1946         skip_bits(gb, 8); /* offset x */
1947         skip_bits(gb, 8); /* offset y */
1948     }
1949
1950     skip_bits(gb, 32); /* fps numerator */
1951     skip_bits(gb, 32); /* fps denumerator */
1952     skip_bits(gb, 24); /* aspect numerator */
1953     skip_bits(gb, 24); /* aspect denumerator */
1954
1955     if (s->theora < 0x030200)
1956         skip_bits(gb, 5); /* keyframe frequency force */
1957     colorspace = get_bits(gb, 8);
1958     skip_bits(gb, 24); /* bitrate */
1959
1960     skip_bits(gb, 6); /* quality hint */
1961
1962     if (s->theora >= 0x030200)
1963     {
1964         skip_bits(gb, 5); /* keyframe frequency force */
1965         skip_bits(gb, 2); /* pixel format: 420,res,422,444 */
1966         skip_bits(gb, 3); /* reserved */
1967     }
1968
1969 //    align_get_bits(gb);
1970
1971     if (   visible_width  <= s->width  && visible_width  > s->width-16
1972         && visible_height <= s->height && visible_height > s->height-16)
1973         avcodec_set_dimensions(avctx, visible_width, visible_height);
1974     else
1975         avcodec_set_dimensions(avctx, s->width, s->height);
1976
1977     if (colorspace == 1) {
1978         avctx->color_primaries = AVCOL_PRI_BT470M;
1979     } else if (colorspace == 2) {
1980         avctx->color_primaries = AVCOL_PRI_BT470BG;
1981     }
1982     if (colorspace == 1 || colorspace == 2) {
1983         avctx->colorspace = AVCOL_SPC_BT470BG;
1984         avctx->color_trc  = AVCOL_TRC_BT709;
1985     }
1986
1987     return 0;
1988 }
1989
1990 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
1991 {
1992     Vp3DecodeContext *s = avctx->priv_data;
1993     int i, n, matrices, inter, plane;
1994
1995     if (s->theora >= 0x030200) {
1996         n = get_bits(gb, 3);
1997         /* loop filter limit values table */
1998         for (i = 0; i < 64; i++) {
1999             s->filter_limit_values[i] = get_bits(gb, n);
2000             if (s->filter_limit_values[i] > 127) {
2001                 av_log(avctx, AV_LOG_ERROR, "filter limit value too large (%i > 127), clamping\n", s->filter_limit_values[i]);
2002                 s->filter_limit_values[i] = 127;
2003             }
2004         }
2005     }
2006
2007     if (s->theora >= 0x030200)
2008         n = get_bits(gb, 4) + 1;
2009     else
2010         n = 16;
2011     /* quality threshold table */
2012     for (i = 0; i < 64; i++)
2013         s->coded_ac_scale_factor[i] = get_bits(gb, n);
2014
2015     if (s->theora >= 0x030200)
2016         n = get_bits(gb, 4) + 1;
2017     else
2018         n = 16;
2019     /* dc scale factor table */
2020     for (i = 0; i < 64; i++)
2021         s->coded_dc_scale_factor[i] = get_bits(gb, n);
2022
2023     if (s->theora >= 0x030200)
2024         matrices = get_bits(gb, 9) + 1;
2025     else
2026         matrices = 3;
2027
2028     if(matrices > 384){
2029         av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2030         return -1;
2031     }
2032
2033     for(n=0; n<matrices; n++){
2034         for (i = 0; i < 64; i++)
2035             s->base_matrix[n][i]= get_bits(gb, 8);
2036     }
2037
2038     for (inter = 0; inter <= 1; inter++) {
2039         for (plane = 0; plane <= 2; plane++) {
2040             int newqr= 1;
2041             if (inter || plane > 0)
2042                 newqr = get_bits1(gb);
2043             if (!newqr) {
2044                 int qtj, plj;
2045                 if(inter && get_bits1(gb)){
2046                     qtj = 0;
2047                     plj = plane;
2048                 }else{
2049                     qtj= (3*inter + plane - 1) / 3;
2050                     plj= (plane + 2) % 3;
2051                 }
2052                 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2053                 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2054                 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2055             } else {
2056                 int qri= 0;
2057                 int qi = 0;
2058
2059                 for(;;){
2060                     i= get_bits(gb, av_log2(matrices-1)+1);
2061                     if(i>= matrices){
2062                         av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2063                         return -1;
2064                     }
2065                     s->qr_base[inter][plane][qri]= i;
2066                     if(qi >= 63)
2067                         break;
2068                     i = get_bits(gb, av_log2(63-qi)+1) + 1;
2069                     s->qr_size[inter][plane][qri++]= i;
2070                     qi += i;
2071                 }
2072
2073                 if (qi > 63) {
2074                     av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2075                     return -1;
2076                 }
2077                 s->qr_count[inter][plane]= qri;
2078             }
2079         }
2080     }
2081
2082     /* Huffman tables */
2083     for (s->hti = 0; s->hti < 80; s->hti++) {
2084         s->entries = 0;
2085         s->huff_code_size = 1;
2086         if (!get_bits1(gb)) {
2087             s->hbits = 0;
2088             if(read_huffman_tree(avctx, gb))
2089                 return -1;
2090             s->hbits = 1;
2091             if(read_huffman_tree(avctx, gb))
2092                 return -1;
2093         }
2094     }
2095
2096     s->theora_tables = 1;
2097
2098     return 0;
2099 }
2100
2101 static av_cold int theora_decode_init(AVCodecContext *avctx)
2102 {
2103     Vp3DecodeContext *s = avctx->priv_data;
2104     GetBitContext gb;
2105     int ptype;
2106     uint8_t *header_start[3];
2107     int header_len[3];
2108     int i;
2109
2110     s->theora = 1;
2111
2112     if (!avctx->extradata_size)
2113     {
2114         av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2115         return -1;
2116     }
2117
2118     if (ff_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2119                               42, header_start, header_len) < 0) {
2120         av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2121         return -1;
2122     }
2123
2124   for(i=0;i<3;i++) {
2125     init_get_bits(&gb, header_start[i], header_len[i] * 8);
2126
2127     ptype = get_bits(&gb, 8);
2128
2129      if (!(ptype & 0x80))
2130      {
2131         av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2132 //        return -1;
2133      }
2134
2135     // FIXME: Check for this as well.
2136     skip_bits_long(&gb, 6*8); /* "theora" */
2137
2138     switch(ptype)
2139     {
2140         case 0x80:
2141             theora_decode_header(avctx, &gb);
2142                 break;
2143         case 0x81:
2144 // FIXME: is this needed? it breaks sometimes
2145 //            theora_decode_comments(avctx, gb);
2146             break;
2147         case 0x82:
2148             if (theora_decode_tables(avctx, &gb))
2149                 return -1;
2150             break;
2151         default:
2152             av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2153             break;
2154     }
2155     if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2156         av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2157     if (s->theora < 0x030200)
2158         break;
2159   }
2160
2161     return vp3_decode_init(avctx);
2162 }
2163
2164 AVCodec theora_decoder = {
2165     "theora",
2166     CODEC_TYPE_VIDEO,
2167     CODEC_ID_THEORA,
2168     sizeof(Vp3DecodeContext),
2169     theora_decode_init,
2170     NULL,
2171     vp3_decode_end,
2172     vp3_decode_frame,
2173     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2174     NULL,
2175     .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2176 };
2177 #endif
2178
2179 AVCodec vp3_decoder = {
2180     "vp3",
2181     CODEC_TYPE_VIDEO,
2182     CODEC_ID_VP3,
2183     sizeof(Vp3DecodeContext),
2184     vp3_decode_init,
2185     NULL,
2186     vp3_decode_end,
2187     vp3_decode_frame,
2188     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2189     NULL,
2190     .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2191 };