]> git.sesse.net Git - ffmpeg/blob - libavcodec/vp3.c
c5256112a7df73f6ea8f2444c2a6eb79cd22e432
[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 = 127;
298         s->all_fragments[i].motion_y = 127;
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                         if ((motion_x == 127) || (motion_y == 127))
1406                             av_log(s->avctx, AV_LOG_ERROR, " help! got invalid motion vector! (%X, %X)\n", motion_x, motion_y);
1407
1408                         motion_halfpel_index = motion_x & 0x01;
1409                         motion_source += (motion_x >> 1);
1410
1411                         motion_halfpel_index |= (motion_y & 0x01) << 1;
1412                         motion_source += ((motion_y >> 1) * stride);
1413
1414                         if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1415                             uint8_t *temp= s->edge_emu_buffer;
1416                             if(stride<0) temp -= 9*stride;
1417                             else temp += 9*stride;
1418
1419                             ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
1420                             motion_source= temp;
1421                         }
1422                     }
1423
1424
1425                     /* first, take care of copying a block from either the
1426                      * previous or the golden frame */
1427                     if (s->all_fragments[i].coding_method != MODE_INTRA) {
1428                         /* Note, it is possible to implement all MC cases with
1429                            put_no_rnd_pixels_l2 which would look more like the
1430                            VP3 source but this would be slower as
1431                            put_no_rnd_pixels_tab is better optimzed */
1432                         if(motion_halfpel_index != 3){
1433                             s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1434                                 output_plane + first_pixel,
1435                                 motion_source, stride, 8);
1436                         }else{
1437                             int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1438                             s->dsp.put_no_rnd_pixels_l2[1](
1439                                 output_plane + first_pixel,
1440                                 motion_source - d,
1441                                 motion_source + stride + 1 + d,
1442                                 stride, 8);
1443                         }
1444                     }
1445
1446                         s->dsp.clear_block(block);
1447                         vp3_dequant(s, s->all_fragments + i, plane, !intra, block);
1448
1449                     /* invert DCT and place (or add) in final output */
1450
1451                     if (s->all_fragments[i].coding_method == MODE_INTRA) {
1452                         if(s->avctx->idct_algo!=FF_IDCT_VP3)
1453                             block[0] += 128<<3;
1454                         s->dsp.idct_put(
1455                             output_plane + first_pixel,
1456                             stride,
1457                             block);
1458                     } else {
1459                         s->dsp.idct_add(
1460                             output_plane + first_pixel,
1461                             stride,
1462                             block);
1463                     }
1464                 } else {
1465
1466                     /* copy directly from the previous frame */
1467                     s->dsp.put_pixels_tab[1][0](
1468                         output_plane + first_pixel,
1469                         last_plane + first_pixel,
1470                         stride, 8);
1471
1472                 }
1473                 }
1474             }
1475
1476             // Filter up to the last row in the superblock row
1477             apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
1478         }
1479     }
1480
1481      /* this looks like a good place for slice dispatch... */
1482      /* algorithm:
1483       *   if (slice == s->macroblock_height - 1)
1484       *     dispatch (both last slice & 2nd-to-last slice);
1485       *   else if (slice > 0)
1486       *     dispatch (slice - 1);
1487       */
1488
1489     vp3_draw_horiz_band(s, FFMIN(64*slice + 64-16, s->height-16));
1490 }
1491
1492 /*
1493  * This is the ffmpeg/libavcodec API init function.
1494  */
1495 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1496 {
1497     Vp3DecodeContext *s = avctx->priv_data;
1498     int i, inter, plane;
1499     int c_width;
1500     int c_height;
1501
1502     if (avctx->codec_tag == MKTAG('V','P','3','0'))
1503         s->version = 0;
1504     else
1505         s->version = 1;
1506
1507     s->avctx = avctx;
1508     s->width = FFALIGN(avctx->width, 16);
1509     s->height = FFALIGN(avctx->height, 16);
1510     avctx->pix_fmt = PIX_FMT_YUV420P;
1511     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1512     if(avctx->idct_algo==FF_IDCT_AUTO)
1513         avctx->idct_algo=FF_IDCT_VP3;
1514     dsputil_init(&s->dsp, avctx);
1515
1516     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
1517
1518     /* initialize to an impossible value which will force a recalculation
1519      * in the first frame decode */
1520     for (i = 0; i < 3; i++)
1521         s->qps[i] = -1;
1522
1523     s->y_superblock_width = (s->width + 31) / 32;
1524     s->y_superblock_height = (s->height + 31) / 32;
1525     s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1526
1527     /* work out the dimensions for the C planes */
1528     c_width = s->width / 2;
1529     c_height = s->height / 2;
1530     s->c_superblock_width = (c_width + 31) / 32;
1531     s->c_superblock_height = (c_height + 31) / 32;
1532     s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1533
1534     s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1535     s->u_superblock_start = s->y_superblock_count;
1536     s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1537     s->superblock_coding = av_malloc(s->superblock_count);
1538
1539     s->macroblock_width = (s->width + 15) / 16;
1540     s->macroblock_height = (s->height + 15) / 16;
1541     s->macroblock_count = s->macroblock_width * s->macroblock_height;
1542
1543     s->fragment_width = s->width / FRAGMENT_PIXELS;
1544     s->fragment_height = s->height / FRAGMENT_PIXELS;
1545
1546     /* fragment count covers all 8x8 blocks for all 3 planes */
1547     s->fragment_count = s->fragment_width * s->fragment_height * 3 / 2;
1548     s->fragment_start[1] = s->fragment_width * s->fragment_height;
1549     s->fragment_start[2] = s->fragment_width * s->fragment_height * 5 / 4;
1550
1551     s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
1552     s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
1553     s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
1554     if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
1555         !s->coded_fragment_list[0]) {
1556         vp3_decode_end(avctx);
1557         return -1;
1558     }
1559
1560     if (!s->theora_tables)
1561     {
1562         for (i = 0; i < 64; i++) {
1563             s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1564             s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1565             s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1566             s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1567             s->base_matrix[2][i] = vp31_inter_dequant[i];
1568             s->filter_limit_values[i] = vp31_filter_limit_values[i];
1569         }
1570
1571         for(inter=0; inter<2; inter++){
1572             for(plane=0; plane<3; plane++){
1573                 s->qr_count[inter][plane]= 1;
1574                 s->qr_size [inter][plane][0]= 63;
1575                 s->qr_base [inter][plane][0]=
1576                 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1577             }
1578         }
1579
1580         /* init VLC tables */
1581         for (i = 0; i < 16; i++) {
1582
1583             /* DC histograms */
1584             init_vlc(&s->dc_vlc[i], 5, 32,
1585                 &dc_bias[i][0][1], 4, 2,
1586                 &dc_bias[i][0][0], 4, 2, 0);
1587
1588             /* group 1 AC histograms */
1589             init_vlc(&s->ac_vlc_1[i], 5, 32,
1590                 &ac_bias_0[i][0][1], 4, 2,
1591                 &ac_bias_0[i][0][0], 4, 2, 0);
1592
1593             /* group 2 AC histograms */
1594             init_vlc(&s->ac_vlc_2[i], 5, 32,
1595                 &ac_bias_1[i][0][1], 4, 2,
1596                 &ac_bias_1[i][0][0], 4, 2, 0);
1597
1598             /* group 3 AC histograms */
1599             init_vlc(&s->ac_vlc_3[i], 5, 32,
1600                 &ac_bias_2[i][0][1], 4, 2,
1601                 &ac_bias_2[i][0][0], 4, 2, 0);
1602
1603             /* group 4 AC histograms */
1604             init_vlc(&s->ac_vlc_4[i], 5, 32,
1605                 &ac_bias_3[i][0][1], 4, 2,
1606                 &ac_bias_3[i][0][0], 4, 2, 0);
1607         }
1608     } else {
1609         for (i = 0; i < 16; i++) {
1610
1611             /* DC histograms */
1612             if (init_vlc(&s->dc_vlc[i], 5, 32,
1613                 &s->huffman_table[i][0][1], 4, 2,
1614                 &s->huffman_table[i][0][0], 4, 2, 0) < 0)
1615                 goto vlc_fail;
1616
1617             /* group 1 AC histograms */
1618             if (init_vlc(&s->ac_vlc_1[i], 5, 32,
1619                 &s->huffman_table[i+16][0][1], 4, 2,
1620                 &s->huffman_table[i+16][0][0], 4, 2, 0) < 0)
1621                 goto vlc_fail;
1622
1623             /* group 2 AC histograms */
1624             if (init_vlc(&s->ac_vlc_2[i], 5, 32,
1625                 &s->huffman_table[i+16*2][0][1], 4, 2,
1626                 &s->huffman_table[i+16*2][0][0], 4, 2, 0) < 0)
1627                 goto vlc_fail;
1628
1629             /* group 3 AC histograms */
1630             if (init_vlc(&s->ac_vlc_3[i], 5, 32,
1631                 &s->huffman_table[i+16*3][0][1], 4, 2,
1632                 &s->huffman_table[i+16*3][0][0], 4, 2, 0) < 0)
1633                 goto vlc_fail;
1634
1635             /* group 4 AC histograms */
1636             if (init_vlc(&s->ac_vlc_4[i], 5, 32,
1637                 &s->huffman_table[i+16*4][0][1], 4, 2,
1638                 &s->huffman_table[i+16*4][0][0], 4, 2, 0) < 0)
1639                 goto vlc_fail;
1640         }
1641     }
1642
1643     init_vlc(&s->superblock_run_length_vlc, 6, 34,
1644         &superblock_run_length_vlc_table[0][1], 4, 2,
1645         &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1646
1647     init_vlc(&s->fragment_run_length_vlc, 5, 30,
1648         &fragment_run_length_vlc_table[0][1], 4, 2,
1649         &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1650
1651     init_vlc(&s->mode_code_vlc, 3, 8,
1652         &mode_code_vlc_table[0][1], 2, 1,
1653         &mode_code_vlc_table[0][0], 2, 1, 0);
1654
1655     init_vlc(&s->motion_vector_vlc, 6, 63,
1656         &motion_vector_vlc_table[0][1], 2, 1,
1657         &motion_vector_vlc_table[0][0], 2, 1, 0);
1658
1659     /* work out the block mapping tables */
1660     s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
1661     s->macroblock_coding = av_malloc(s->macroblock_count + 1);
1662     if (!s->superblock_fragments || !s->macroblock_coding) {
1663         vp3_decode_end(avctx);
1664         return -1;
1665     }
1666     init_block_mapping(s);
1667
1668     for (i = 0; i < 3; i++) {
1669         s->current_frame.data[i] = NULL;
1670         s->last_frame.data[i] = NULL;
1671         s->golden_frame.data[i] = NULL;
1672     }
1673
1674     return 0;
1675
1676 vlc_fail:
1677     av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1678     return -1;
1679 }
1680
1681 /*
1682  * This is the ffmpeg/libavcodec API frame decode function.
1683  */
1684 static int vp3_decode_frame(AVCodecContext *avctx,
1685                             void *data, int *data_size,
1686                             AVPacket *avpkt)
1687 {
1688     const uint8_t *buf = avpkt->data;
1689     int buf_size = avpkt->size;
1690     Vp3DecodeContext *s = avctx->priv_data;
1691     GetBitContext gb;
1692     static int counter = 0;
1693     int i;
1694
1695     init_get_bits(&gb, buf, buf_size * 8);
1696
1697     if (s->theora && get_bits1(&gb))
1698     {
1699         av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1700         return -1;
1701     }
1702
1703     s->keyframe = !get_bits1(&gb);
1704     if (!s->theora)
1705         skip_bits(&gb, 1);
1706     for (i = 0; i < 3; i++)
1707         s->last_qps[i] = s->qps[i];
1708
1709     s->nqps=0;
1710     do{
1711         s->qps[s->nqps++]= get_bits(&gb, 6);
1712     } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
1713     for (i = s->nqps; i < 3; i++)
1714         s->qps[i] = -1;
1715
1716     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1717         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
1718             s->keyframe?"key":"", counter, s->qps[0]);
1719     counter++;
1720
1721     if (s->qps[0] != s->last_qps[0])
1722         init_loop_filter(s);
1723
1724     for (i = 0; i < s->nqps; i++)
1725         // reinit all dequantizers if the first one changed, because
1726         // the DC of the first quantizer must be used for all matrices
1727         if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
1728             init_dequantizer(s, i);
1729
1730     if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
1731         return buf_size;
1732
1733     s->current_frame.reference = 3;
1734     s->current_frame.pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
1735     if (avctx->get_buffer(avctx, &s->current_frame) < 0) {
1736         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1737         goto error;
1738     }
1739
1740     if (s->keyframe) {
1741         if (!s->theora)
1742         {
1743             skip_bits(&gb, 4); /* width code */
1744             skip_bits(&gb, 4); /* height code */
1745             if (s->version)
1746             {
1747                 s->version = get_bits(&gb, 5);
1748                 if (counter == 1)
1749                     av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
1750             }
1751         }
1752         if (s->version || s->theora)
1753         {
1754                 if (get_bits1(&gb))
1755                     av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
1756             skip_bits(&gb, 2); /* reserved? */
1757         }
1758     } else {
1759         if (!s->golden_frame.data[0]) {
1760             av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
1761
1762             s->golden_frame.reference = 3;
1763             s->golden_frame.pict_type = FF_I_TYPE;
1764             if (avctx->get_buffer(avctx, &s->golden_frame) < 0) {
1765                 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1766                 goto error;
1767             }
1768             s->last_frame = s->golden_frame;
1769             s->last_frame.type = FF_BUFFER_TYPE_COPY;
1770         }
1771     }
1772
1773     s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
1774     s->current_frame.qstride= 0;
1775
1776     init_frame(s, &gb);
1777
1778     if (unpack_superblocks(s, &gb)){
1779         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
1780         goto error;
1781     }
1782     if (unpack_modes(s, &gb)){
1783         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
1784         goto error;
1785     }
1786     if (unpack_vectors(s, &gb)){
1787         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
1788         goto error;
1789     }
1790     if (unpack_block_qpis(s, &gb)){
1791         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
1792         goto error;
1793     }
1794     if (unpack_dct_coeffs(s, &gb)){
1795         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
1796         goto error;
1797     }
1798
1799     for (i = 0; i < 3; i++) {
1800         if (s->flipped_image)
1801             s->data_offset[i] = 0;
1802         else
1803             s->data_offset[i] = ((s->height>>!!i)-1) * s->current_frame.linesize[i];
1804     }
1805
1806     s->last_slice_end = 0;
1807     for (i = 0; i < s->c_superblock_height; i++)
1808         render_slice(s, i);
1809
1810     // filter the last row
1811     for (i = 0; i < 3; i++) {
1812         int row = (s->height >> (3+!!i)) - 1;
1813         apply_loop_filter(s, i, row, row+1);
1814     }
1815     vp3_draw_horiz_band(s, s->height);
1816
1817     *data_size=sizeof(AVFrame);
1818     *(AVFrame*)data= s->current_frame;
1819
1820     /* release the last frame, if it is allocated and if it is not the
1821      * golden frame */
1822     if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1823         avctx->release_buffer(avctx, &s->last_frame);
1824
1825     /* shuffle frames (last = current) */
1826     s->last_frame= s->current_frame;
1827
1828     if (s->keyframe) {
1829         if (s->golden_frame.data[0])
1830             avctx->release_buffer(avctx, &s->golden_frame);
1831         s->golden_frame = s->current_frame;
1832         s->last_frame.type = FF_BUFFER_TYPE_COPY;
1833     }
1834
1835     s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
1836
1837     return buf_size;
1838
1839 error:
1840     if (s->current_frame.data[0])
1841         avctx->release_buffer(avctx, &s->current_frame);
1842     return -1;
1843 }
1844
1845 /*
1846  * This is the ffmpeg/libavcodec API module cleanup function.
1847  */
1848 static av_cold int vp3_decode_end(AVCodecContext *avctx)
1849 {
1850     Vp3DecodeContext *s = avctx->priv_data;
1851     int i;
1852
1853     av_free(s->superblock_coding);
1854     av_free(s->all_fragments);
1855     av_free(s->coded_fragment_list[0]);
1856     av_free(s->dct_tokens_base);
1857     av_free(s->superblock_fragments);
1858     av_free(s->macroblock_coding);
1859
1860     for (i = 0; i < 16; i++) {
1861         free_vlc(&s->dc_vlc[i]);
1862         free_vlc(&s->ac_vlc_1[i]);
1863         free_vlc(&s->ac_vlc_2[i]);
1864         free_vlc(&s->ac_vlc_3[i]);
1865         free_vlc(&s->ac_vlc_4[i]);
1866     }
1867
1868     free_vlc(&s->superblock_run_length_vlc);
1869     free_vlc(&s->fragment_run_length_vlc);
1870     free_vlc(&s->mode_code_vlc);
1871     free_vlc(&s->motion_vector_vlc);
1872
1873     /* release all frames */
1874     if (s->golden_frame.data[0])
1875         avctx->release_buffer(avctx, &s->golden_frame);
1876     if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1877         avctx->release_buffer(avctx, &s->last_frame);
1878     /* no need to release the current_frame since it will always be pointing
1879      * to the same frame as either the golden or last frame */
1880
1881     return 0;
1882 }
1883
1884 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
1885 {
1886     Vp3DecodeContext *s = avctx->priv_data;
1887
1888     if (get_bits1(gb)) {
1889         int token;
1890         if (s->entries >= 32) { /* overflow */
1891             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1892             return -1;
1893         }
1894         token = get_bits(gb, 5);
1895         //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);
1896         s->huffman_table[s->hti][token][0] = s->hbits;
1897         s->huffman_table[s->hti][token][1] = s->huff_code_size;
1898         s->entries++;
1899     }
1900     else {
1901         if (s->huff_code_size >= 32) {/* overflow */
1902             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1903             return -1;
1904         }
1905         s->huff_code_size++;
1906         s->hbits <<= 1;
1907         if (read_huffman_tree(avctx, gb))
1908             return -1;
1909         s->hbits |= 1;
1910         if (read_huffman_tree(avctx, gb))
1911             return -1;
1912         s->hbits >>= 1;
1913         s->huff_code_size--;
1914     }
1915     return 0;
1916 }
1917
1918 #if CONFIG_THEORA_DECODER
1919 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
1920 {
1921     Vp3DecodeContext *s = avctx->priv_data;
1922     int visible_width, visible_height, colorspace;
1923
1924     s->theora = get_bits_long(gb, 24);
1925     av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
1926
1927     /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
1928     /* but previous versions have the image flipped relative to vp3 */
1929     if (s->theora < 0x030200)
1930     {
1931         s->flipped_image = 1;
1932         av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
1933     }
1934
1935     visible_width  = s->width  = get_bits(gb, 16) << 4;
1936     visible_height = s->height = get_bits(gb, 16) << 4;
1937
1938     if(avcodec_check_dimensions(avctx, s->width, s->height)){
1939         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
1940         s->width= s->height= 0;
1941         return -1;
1942     }
1943
1944     if (s->theora >= 0x030200) {
1945         visible_width  = get_bits_long(gb, 24);
1946         visible_height = get_bits_long(gb, 24);
1947
1948         skip_bits(gb, 8); /* offset x */
1949         skip_bits(gb, 8); /* offset y */
1950     }
1951
1952     skip_bits(gb, 32); /* fps numerator */
1953     skip_bits(gb, 32); /* fps denumerator */
1954     skip_bits(gb, 24); /* aspect numerator */
1955     skip_bits(gb, 24); /* aspect denumerator */
1956
1957     if (s->theora < 0x030200)
1958         skip_bits(gb, 5); /* keyframe frequency force */
1959     colorspace = get_bits(gb, 8);
1960     skip_bits(gb, 24); /* bitrate */
1961
1962     skip_bits(gb, 6); /* quality hint */
1963
1964     if (s->theora >= 0x030200)
1965     {
1966         skip_bits(gb, 5); /* keyframe frequency force */
1967         skip_bits(gb, 2); /* pixel format: 420,res,422,444 */
1968         skip_bits(gb, 3); /* reserved */
1969     }
1970
1971 //    align_get_bits(gb);
1972
1973     if (   visible_width  <= s->width  && visible_width  > s->width-16
1974         && visible_height <= s->height && visible_height > s->height-16)
1975         avcodec_set_dimensions(avctx, visible_width, visible_height);
1976     else
1977         avcodec_set_dimensions(avctx, s->width, s->height);
1978
1979     if (colorspace == 1) {
1980         avctx->color_primaries = AVCOL_PRI_BT470M;
1981     } else if (colorspace == 2) {
1982         avctx->color_primaries = AVCOL_PRI_BT470BG;
1983     }
1984     if (colorspace == 1 || colorspace == 2) {
1985         avctx->colorspace = AVCOL_SPC_BT470BG;
1986         avctx->color_trc  = AVCOL_TRC_BT709;
1987     }
1988
1989     return 0;
1990 }
1991
1992 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
1993 {
1994     Vp3DecodeContext *s = avctx->priv_data;
1995     int i, n, matrices, inter, plane;
1996
1997     if (s->theora >= 0x030200) {
1998         n = get_bits(gb, 3);
1999         /* loop filter limit values table */
2000         for (i = 0; i < 64; i++) {
2001             s->filter_limit_values[i] = get_bits(gb, n);
2002             if (s->filter_limit_values[i] > 127) {
2003                 av_log(avctx, AV_LOG_ERROR, "filter limit value too large (%i > 127), clamping\n", s->filter_limit_values[i]);
2004                 s->filter_limit_values[i] = 127;
2005             }
2006         }
2007     }
2008
2009     if (s->theora >= 0x030200)
2010         n = get_bits(gb, 4) + 1;
2011     else
2012         n = 16;
2013     /* quality threshold table */
2014     for (i = 0; i < 64; i++)
2015         s->coded_ac_scale_factor[i] = get_bits(gb, n);
2016
2017     if (s->theora >= 0x030200)
2018         n = get_bits(gb, 4) + 1;
2019     else
2020         n = 16;
2021     /* dc scale factor table */
2022     for (i = 0; i < 64; i++)
2023         s->coded_dc_scale_factor[i] = get_bits(gb, n);
2024
2025     if (s->theora >= 0x030200)
2026         matrices = get_bits(gb, 9) + 1;
2027     else
2028         matrices = 3;
2029
2030     if(matrices > 384){
2031         av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2032         return -1;
2033     }
2034
2035     for(n=0; n<matrices; n++){
2036         for (i = 0; i < 64; i++)
2037             s->base_matrix[n][i]= get_bits(gb, 8);
2038     }
2039
2040     for (inter = 0; inter <= 1; inter++) {
2041         for (plane = 0; plane <= 2; plane++) {
2042             int newqr= 1;
2043             if (inter || plane > 0)
2044                 newqr = get_bits1(gb);
2045             if (!newqr) {
2046                 int qtj, plj;
2047                 if(inter && get_bits1(gb)){
2048                     qtj = 0;
2049                     plj = plane;
2050                 }else{
2051                     qtj= (3*inter + plane - 1) / 3;
2052                     plj= (plane + 2) % 3;
2053                 }
2054                 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2055                 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2056                 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2057             } else {
2058                 int qri= 0;
2059                 int qi = 0;
2060
2061                 for(;;){
2062                     i= get_bits(gb, av_log2(matrices-1)+1);
2063                     if(i>= matrices){
2064                         av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2065                         return -1;
2066                     }
2067                     s->qr_base[inter][plane][qri]= i;
2068                     if(qi >= 63)
2069                         break;
2070                     i = get_bits(gb, av_log2(63-qi)+1) + 1;
2071                     s->qr_size[inter][plane][qri++]= i;
2072                     qi += i;
2073                 }
2074
2075                 if (qi > 63) {
2076                     av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2077                     return -1;
2078                 }
2079                 s->qr_count[inter][plane]= qri;
2080             }
2081         }
2082     }
2083
2084     /* Huffman tables */
2085     for (s->hti = 0; s->hti < 80; s->hti++) {
2086         s->entries = 0;
2087         s->huff_code_size = 1;
2088         if (!get_bits1(gb)) {
2089             s->hbits = 0;
2090             if(read_huffman_tree(avctx, gb))
2091                 return -1;
2092             s->hbits = 1;
2093             if(read_huffman_tree(avctx, gb))
2094                 return -1;
2095         }
2096     }
2097
2098     s->theora_tables = 1;
2099
2100     return 0;
2101 }
2102
2103 static av_cold int theora_decode_init(AVCodecContext *avctx)
2104 {
2105     Vp3DecodeContext *s = avctx->priv_data;
2106     GetBitContext gb;
2107     int ptype;
2108     uint8_t *header_start[3];
2109     int header_len[3];
2110     int i;
2111
2112     s->theora = 1;
2113
2114     if (!avctx->extradata_size)
2115     {
2116         av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2117         return -1;
2118     }
2119
2120     if (ff_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2121                               42, header_start, header_len) < 0) {
2122         av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2123         return -1;
2124     }
2125
2126   for(i=0;i<3;i++) {
2127     init_get_bits(&gb, header_start[i], header_len[i] * 8);
2128
2129     ptype = get_bits(&gb, 8);
2130
2131      if (!(ptype & 0x80))
2132      {
2133         av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2134 //        return -1;
2135      }
2136
2137     // FIXME: Check for this as well.
2138     skip_bits_long(&gb, 6*8); /* "theora" */
2139
2140     switch(ptype)
2141     {
2142         case 0x80:
2143             theora_decode_header(avctx, &gb);
2144                 break;
2145         case 0x81:
2146 // FIXME: is this needed? it breaks sometimes
2147 //            theora_decode_comments(avctx, gb);
2148             break;
2149         case 0x82:
2150             if (theora_decode_tables(avctx, &gb))
2151                 return -1;
2152             break;
2153         default:
2154             av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2155             break;
2156     }
2157     if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2158         av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2159     if (s->theora < 0x030200)
2160         break;
2161   }
2162
2163     return vp3_decode_init(avctx);
2164 }
2165
2166 AVCodec theora_decoder = {
2167     "theora",
2168     CODEC_TYPE_VIDEO,
2169     CODEC_ID_THEORA,
2170     sizeof(Vp3DecodeContext),
2171     theora_decode_init,
2172     NULL,
2173     vp3_decode_end,
2174     vp3_decode_frame,
2175     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2176     NULL,
2177     .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2178 };
2179 #endif
2180
2181 AVCodec vp3_decoder = {
2182     "vp3",
2183     CODEC_TYPE_VIDEO,
2184     CODEC_ID_VP3,
2185     sizeof(Vp3DecodeContext),
2186     vp3_decode_init,
2187     NULL,
2188     vp3_decode_end,
2189     vp3_decode_frame,
2190     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2191     NULL,
2192     .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2193 };