]> git.sesse.net Git - ffmpeg/blob - libavcodec/vp3.c
fixed buffer allocation logic (hopefully) so that decoder does not crash
[ffmpeg] / libavcodec / vp3.c
1 /*
2  *
3  * Copyright (C) 2003 the ffmpeg project
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  * VP3 Video Decoder by Mike Melanson (melanson@pcisys.net)
20  *
21  */
22
23 /**
24  * @file vp3.c
25  * On2 VP3 Video Decoder
26  */
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 #include "common.h"
34 #include "avcodec.h"
35 #include "dsputil.h"
36 #include "mpegvideo.h"
37 #include "dsputil.h"
38 #include "bswap.h"
39
40 #include "vp3data.h"
41
42 #define FRAGMENT_PIXELS 8
43
44 /* 
45  * Debugging Variables
46  * 
47  * Define one or more of the following compile-time variables to 1 to obtain
48  * elaborate information about certain aspects of the decoding process.
49  *
50  * DEBUG_VP3: high-level decoding flow
51  * DEBUG_INIT: initialization parameters
52  * DEBUG_DEQUANTIZERS: display how the dequanization tables are built
53  * DEBUG_BLOCK_CODING: unpacking the superblock/macroblock/fragment coding
54  * DEBUG_MODES: unpacking the coding modes for individual fragments
55  * DEBUG_VECTORS: display the motion vectors
56  * DEBUG_TOKEN: display exhaustive information about each DCT token
57  * DEBUG_VLC: display the VLCs as they are extracted from the stream
58  * DEBUG_DC_PRED: display the process of reversing DC prediction
59  * DEBUG_IDCT: show every detail of the IDCT process
60  */
61
62 #define DEBUG_VP3 0
63 #define DEBUG_INIT 0
64 #define DEBUG_DEQUANTIZERS 0
65 #define DEBUG_BLOCK_CODING 0
66 #define DEBUG_MODES 0
67 #define DEBUG_VECTORS 0
68 #define DEBUG_TOKEN 0
69 #define DEBUG_VLC 0
70 #define DEBUG_DC_PRED 0
71 #define DEBUG_IDCT 0
72
73 #if DEBUG_VP3
74 #define debug_vp3 printf
75 #else
76 static inline void debug_vp3(const char *format, ...) { }
77 #endif
78
79 #if DEBUG_INIT
80 #define debug_init printf
81 #else
82 static inline void debug_init(const char *format, ...) { }
83 #endif
84
85 #if DEBUG_DEQUANTIZERS
86 #define debug_dequantizers printf 
87 #else
88 static inline void debug_dequantizers(const char *format, ...) { } 
89 #endif
90
91 #if DEBUG_BLOCK_CODING
92 #define debug_block_coding printf 
93 #else
94 static inline void debug_block_coding(const char *format, ...) { } 
95 #endif
96
97 #if DEBUG_MODES
98 #define debug_modes printf 
99 #else
100 static inline void debug_modes(const char *format, ...) { } 
101 #endif
102
103 #if DEBUG_VECTORS
104 #define debug_vectors printf 
105 #else
106 static inline void debug_vectors(const char *format, ...) { } 
107 #endif
108
109 #if DEBUG_TOKEN 
110 #define debug_token printf 
111 #else
112 static inline void debug_token(const char *format, ...) { } 
113 #endif
114
115 #if DEBUG_VLC
116 #define debug_vlc printf 
117 #else
118 static inline void debug_vlc(const char *format, ...) { } 
119 #endif
120
121 #if DEBUG_DC_PRED
122 #define debug_dc_pred printf 
123 #else
124 static inline void debug_dc_pred(const char *format, ...) { } 
125 #endif
126
127 #if DEBUG_IDCT
128 #define debug_idct printf 
129 #else
130 static inline void debug_idct(const char *format, ...) { } 
131 #endif
132
133 typedef struct Vp3Fragment {
134     DCTELEM coeffs[64];
135     int coding_method;
136     int coeff_count;
137     int last_coeff;
138     int motion_x;
139     int motion_y;
140     /* this indicates which ffmpeg put_pixels() function to use:
141      * 00b = no halfpel, 01b = x halfpel, 10b = y halfpel, 11b = both halfpel */
142     int motion_halfpel_index;
143     /* address of first pixel taking into account which plane the fragment
144      * lives on as well as the plane stride */
145     int first_pixel;
146     /* this is the macroblock that the fragment belongs to */
147     int macroblock;
148 } Vp3Fragment;
149
150 #define SB_NOT_CODED        0
151 #define SB_PARTIALLY_CODED  1
152 #define SB_FULLY_CODED      2
153
154 #define MODE_INTER_NO_MV      0
155 #define MODE_INTRA            1
156 #define MODE_INTER_PLUS_MV    2
157 #define MODE_INTER_LAST_MV    3
158 #define MODE_INTER_PRIOR_LAST 4
159 #define MODE_USING_GOLDEN     5
160 #define MODE_GOLDEN_MV        6
161 #define MODE_INTER_FOURMV     7
162 #define CODING_MODE_COUNT     8
163
164 /* special internal mode */
165 #define MODE_COPY             8
166
167 /* There are 6 preset schemes, plus a free-form scheme */
168 static int ModeAlphabet[7][CODING_MODE_COUNT] =
169 {
170     /* this is the custom scheme */
171     { 0, 0, 0, 0, 0, 0, 0, 0 },
172
173     /* scheme 1: Last motion vector dominates */
174     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,  
175          MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
176          MODE_INTRA,            MODE_USING_GOLDEN,      
177          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
178
179     /* scheme 2 */
180     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,  
181          MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
182          MODE_INTRA,            MODE_USING_GOLDEN,      
183          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
184
185     /* scheme 3 */
186     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,     
187          MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
188          MODE_INTRA,            MODE_USING_GOLDEN,      
189          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
190
191     /* scheme 4 */
192     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,     
193          MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
194          MODE_INTRA,            MODE_USING_GOLDEN,      
195          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
196
197     /* scheme 5: No motion vector dominates */
198     {    MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,     
199          MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
200          MODE_INTRA,            MODE_USING_GOLDEN,      
201          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
202
203     /* scheme 6 */
204     {    MODE_INTER_NO_MV,      MODE_USING_GOLDEN,      
205          MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
206          MODE_INTER_PLUS_MV,    MODE_INTRA,             
207          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
208
209 };
210
211 #define MIN_DEQUANT_VAL 2
212
213 typedef struct Vp3DecodeContext {
214     AVCodecContext *avctx;
215     int width, height;
216     AVFrame golden_frame;
217     AVFrame last_frame;
218     AVFrame current_frame;
219     int keyframe;
220     DSPContext dsp;
221
222     int quality_index;
223     int last_quality_index;
224
225     int superblock_count;
226     int superblock_width;
227     int superblock_height;
228     int u_superblock_start;
229     int v_superblock_start;
230     unsigned char *superblock_coding;
231
232     int macroblock_count;
233     int macroblock_width;
234     int macroblock_height;
235
236     int fragment_count;
237     int fragment_width;
238     int fragment_height;
239
240     Vp3Fragment *all_fragments;
241     int u_fragment_start;
242     int v_fragment_start;
243
244     /* this is a list of indices into the all_fragments array indicating
245      * which of the fragments are coded */
246     int *coded_fragment_list;
247     int coded_fragment_list_index;
248     int pixel_addresses_inited;
249
250     VLC dc_vlc[16];
251     VLC ac_vlc_1[16];
252     VLC ac_vlc_2[16];
253     VLC ac_vlc_3[16];
254     VLC ac_vlc_4[16];
255
256     int16_t intra_y_dequant[64];
257     int16_t intra_c_dequant[64];
258     int16_t inter_dequant[64];
259
260     /* This table contains superblock_count * 16 entries. Each set of 16
261      * numbers corresponds to the fragment indices 0..15 of the superblock.
262      * An entry will be -1 to indicate that no entry corresponds to that
263      * index. */
264     int *superblock_fragments;
265
266     /* This table contains superblock_count * 4 entries. Each set of 4
267      * numbers corresponds to the macroblock indices 0..3 of the superblock.
268      * An entry will be -1 to indicate that no entry corresponds to that
269      * index. */
270     int *superblock_macroblocks;
271
272     /* This table contains macroblock_count * 6 entries. Each set of 6
273      * numbers corresponds to the fragment indices 0..5 which comprise
274      * the macroblock (4 Y fragments and 2 C fragments). */
275     int *macroblock_fragments;
276     /* This is an array of flags indicating whether a particular 
277      * macroblock is coded. */
278     unsigned char *macroblock_coded;
279
280 } Vp3DecodeContext;
281
282 /************************************************************************
283  * VP3 specific functions
284  ************************************************************************/
285
286 /*
287  * This function sets up all of the various blocks mappings:
288  * superblocks <-> fragments, macroblocks <-> fragments,
289  * superblocks <-> macroblocks
290  */
291 static void init_block_mapping(Vp3DecodeContext *s) 
292 {
293     int i, j;
294     signed int hilbert_walk_y[16];
295     signed int hilbert_walk_c[16];
296     signed int hilbert_walk_mb[4];
297
298     int current_fragment = 0;
299     int current_width = 0;
300     int current_height = 0;
301     int right_edge = 0;
302     int bottom_edge = 0;
303     int superblock_row_inc = 0;
304     int *hilbert = NULL;
305     int mapping_index = 0;
306
307     int current_macroblock;
308     int c_fragment;
309
310     signed char travel_width[16] = {
311          1,  1,  0, -1, 
312          0,  0,  1,  0,
313          1,  0,  1,  0,
314          0, -1,  0,  1
315     };
316
317     signed char travel_height[16] = {
318          0,  0,  1,  0,
319          1,  1,  0, -1,
320          0,  1,  0, -1,
321         -1,  0, -1,  0
322     };
323
324     signed char travel_width_mb[4] = {
325          1,  0,  1,  0
326     };
327
328     signed char travel_height_mb[4] = {
329          0,  1,  0, -1
330     };
331
332     debug_vp3("  vp3: initialize block mapping tables\n");
333
334     /* figure out hilbert pattern per these frame dimensions */
335     hilbert_walk_y[0]  = 1;
336     hilbert_walk_y[1]  = 1;
337     hilbert_walk_y[2]  = s->fragment_width;
338     hilbert_walk_y[3]  = -1;
339     hilbert_walk_y[4]  = s->fragment_width;
340     hilbert_walk_y[5]  = s->fragment_width;
341     hilbert_walk_y[6]  = 1;
342     hilbert_walk_y[7]  = -s->fragment_width;
343     hilbert_walk_y[8]  = 1;
344     hilbert_walk_y[9]  = s->fragment_width;
345     hilbert_walk_y[10]  = 1;
346     hilbert_walk_y[11] = -s->fragment_width;
347     hilbert_walk_y[12] = -s->fragment_width;
348     hilbert_walk_y[13] = -1;
349     hilbert_walk_y[14] = -s->fragment_width;
350     hilbert_walk_y[15] = 1;
351
352     hilbert_walk_c[0]  = 1;
353     hilbert_walk_c[1]  = 1;
354     hilbert_walk_c[2]  = s->fragment_width / 2;
355     hilbert_walk_c[3]  = -1;
356     hilbert_walk_c[4]  = s->fragment_width / 2;
357     hilbert_walk_c[5]  = s->fragment_width / 2;
358     hilbert_walk_c[6]  = 1;
359     hilbert_walk_c[7]  = -s->fragment_width / 2;
360     hilbert_walk_c[8]  = 1;
361     hilbert_walk_c[9]  = s->fragment_width / 2;
362     hilbert_walk_c[10]  = 1;
363     hilbert_walk_c[11] = -s->fragment_width / 2;
364     hilbert_walk_c[12] = -s->fragment_width / 2;
365     hilbert_walk_c[13] = -1;
366     hilbert_walk_c[14] = -s->fragment_width / 2;
367     hilbert_walk_c[15] = 1;
368
369     hilbert_walk_mb[0] = 1;
370     hilbert_walk_mb[1] = s->macroblock_width;
371     hilbert_walk_mb[2] = 1;
372     hilbert_walk_mb[3] = -s->macroblock_width;
373
374     /* iterate through each superblock (all planes) and map the fragments */
375     for (i = 0; i < s->superblock_count; i++) {
376         debug_init("    superblock %d (u starts @ %d, v starts @ %d)\n",
377             i, s->u_superblock_start, s->v_superblock_start);
378
379         /* time to re-assign the limits? */
380         if (i == 0) {
381
382             /* start of Y superblocks */
383             right_edge = s->fragment_width;
384             bottom_edge = s->fragment_height;
385             current_width = 0;
386             current_height = 0;
387             superblock_row_inc = 3 * s->fragment_width;
388             hilbert = hilbert_walk_y;
389
390             /* the first operation for this variable is to advance by 1 */
391             current_fragment = -1;
392
393         } else if (i == s->u_superblock_start) {
394
395             /* start of U superblocks */
396             right_edge = s->fragment_width / 2;
397             bottom_edge = s->fragment_height / 2;
398             current_width = 0;
399             current_height = 0;
400             superblock_row_inc = 3 * (s->fragment_width / 2);
401             hilbert = hilbert_walk_c;
402
403             /* the first operation for this variable is to advance by 1 */
404             current_fragment = s->u_fragment_start - 1;
405
406         } else if (i == s->v_superblock_start) {
407
408             /* start of V superblocks */
409             right_edge = s->fragment_width / 2;
410             bottom_edge = s->fragment_height / 2;
411             current_width = 0;
412             current_height = 0;
413             superblock_row_inc = 3 * (s->fragment_width / 2);
414             hilbert = hilbert_walk_c;
415
416             /* the first operation for this variable is to advance by 1 */
417             current_fragment = s->v_fragment_start - 1;
418
419         }
420
421         if (current_width >= right_edge) {
422             /* reset width and move to next superblock row */
423             current_width = 0;
424             current_height += 4;
425
426             /* fragment is now at the start of a new superblock row */
427             current_fragment += superblock_row_inc;
428         }
429
430         /* iterate through all 16 fragments in a superblock */
431         for (j = 0; j < 16; j++) {
432             current_fragment += hilbert[j];
433             current_height += travel_height[j];
434
435             /* check if the fragment is in bounds */
436             if ((current_width <= right_edge) &&
437                 (current_height < bottom_edge)) {
438                 s->superblock_fragments[mapping_index] = current_fragment;
439                 debug_init("    mapping fragment %d to superblock %d, position %d\n", 
440                     s->superblock_fragments[mapping_index], i, j);
441             } else {
442                 s->superblock_fragments[mapping_index] = -1;
443                 debug_init("    superblock %d, position %d has no fragment\n", 
444                     i, j);
445             }
446
447             current_width += travel_width[j];
448             mapping_index++;
449         }
450     }
451
452     /* initialize the superblock <-> macroblock mapping; iterate through
453      * all of the Y plane superblocks to build this mapping */
454     right_edge = s->macroblock_width;
455     bottom_edge = s->macroblock_height;
456     current_width = 0;
457     current_height = 0;
458     superblock_row_inc = s->macroblock_width;
459     hilbert = hilbert_walk_mb;
460     mapping_index = 0;
461     current_macroblock = -1;
462     for (i = 0; i < s->u_superblock_start; i++) {
463
464         if (current_width >= right_edge) {
465             /* reset width and move to next superblock row */
466             current_width = 0;
467             current_height += 2;
468
469             /* macroblock is now at the start of a new superblock row */
470             current_macroblock += superblock_row_inc;
471         }
472
473         /* iterate through each potential macroblock in the superblock */
474         for (j = 0; j < 4; j++) {
475             current_macroblock += hilbert_walk_mb[j];
476             current_height += travel_height_mb[j];
477
478             /* check if the macroblock is in bounds */
479             if ((current_width <= right_edge) &&
480                 (current_height < bottom_edge)) {
481                 s->superblock_macroblocks[mapping_index] = current_macroblock;
482                 debug_init("    mapping macroblock %d to superblock %d, position %d\n",
483                     s->superblock_macroblocks[mapping_index], i, j);
484             } else {
485                 s->superblock_macroblocks[mapping_index] = -1;
486                 debug_init("    superblock %d, position %d has no macroblock\n",
487                     i, j);
488             }
489
490             current_width += travel_width_mb[j];
491             mapping_index++;
492         }
493     }
494
495     /* initialize the macroblock <-> fragment mapping */
496     current_fragment = 0;
497     current_macroblock = 0;
498     mapping_index = 0;
499     for (i = 0; i < s->fragment_height; i += 2) {
500
501         for (j = 0; j < s->fragment_width; j += 2) {
502
503             debug_init("    macroblock %d contains fragments: ", current_macroblock);
504             s->all_fragments[current_fragment].macroblock = current_macroblock;
505             s->macroblock_fragments[mapping_index++] = current_fragment;
506             debug_init("%d ", current_fragment);
507
508             if (j + 1 < s->fragment_width) {
509                 s->all_fragments[current_fragment + 1].macroblock = current_macroblock;
510                 s->macroblock_fragments[mapping_index++] = current_fragment + 1;
511                 debug_init("%d ", current_fragment + 1);
512             } else
513                 s->macroblock_fragments[mapping_index++] = -1;
514
515             if (i + 1 < s->fragment_height) {
516                 s->all_fragments[current_fragment + s->fragment_width].macroblock = 
517                     current_macroblock;
518                 s->macroblock_fragments[mapping_index++] = 
519                     current_fragment + s->fragment_width;
520                 debug_init("%d ", current_fragment + s->fragment_width);
521             } else
522                 s->macroblock_fragments[mapping_index++] = -1;
523
524             if ((j + 1 < s->fragment_width) && (i + 1 < s->fragment_height)) {
525                 s->all_fragments[current_fragment + s->fragment_width + 1].macroblock = 
526                     current_macroblock;
527                 s->macroblock_fragments[mapping_index++] = 
528                     current_fragment + s->fragment_width + 1;
529                 debug_init("%d ", current_fragment + s->fragment_width + 1);
530             } else
531                 s->macroblock_fragments[mapping_index++] = -1;
532
533             /* C planes */
534             c_fragment = s->u_fragment_start + 
535                 (i * s->fragment_width / 4) + (j / 2);
536         s->all_fragments[c_fragment].macroblock = s->macroblock_count;
537             s->macroblock_fragments[mapping_index++] = c_fragment;
538             debug_init("%d ", c_fragment);
539
540             c_fragment = s->v_fragment_start + 
541                 (i * s->fragment_width / 4) + (j / 2);
542         s->all_fragments[c_fragment].macroblock = s->macroblock_count;
543             s->macroblock_fragments[mapping_index++] = c_fragment;
544             debug_init("%d ", c_fragment);
545
546             debug_init("\n");
547
548             if (j + 2 <= s->fragment_width)
549                 current_fragment += 2;
550             else 
551                 current_fragment++;
552             current_macroblock++;
553         }
554
555         current_fragment += s->fragment_width;
556     }
557 }
558
559 /*
560  * This function unpacks a single token (which should be in the range 0..31)
561  * and returns a zero run (number of zero coefficients in current DCT matrix
562  * before next non-zero coefficient), the next DCT coefficient, and the
563  * number of consecutive, non-EOB'd DCT blocks to EOB.
564  */
565 static void unpack_token(GetBitContext *gb, int token, int *zero_run,
566                          DCTELEM *coeff, int *eob_run) 
567 {
568     int sign;
569
570     *zero_run = 0;
571     *eob_run = 0;
572     *coeff = 0;
573
574     debug_token("    vp3 token %d: ", token);
575     switch (token) {
576
577     case 0:
578         debug_token("DCT_EOB_TOKEN, EOB next block\n");
579         *eob_run = 1;
580         break;
581
582     case 1:
583         debug_token("DCT_EOB_PAIR_TOKEN, EOB next 2 blocks\n");
584         *eob_run = 2;
585         break;
586
587     case 2:
588         debug_token("DCT_EOB_TRIPLE_TOKEN, EOB next 3 blocks\n");
589         *eob_run = 3;
590         break;
591
592     case 3:
593         debug_token("DCT_REPEAT_RUN_TOKEN, ");
594         *eob_run = get_bits(gb, 2) + 4;
595         debug_token("EOB the next %d blocks\n", *eob_run);
596         break;
597
598     case 4:
599         debug_token("DCT_REPEAT_RUN2_TOKEN, ");
600         *eob_run = get_bits(gb, 3) + 8;
601         debug_token("EOB the next %d blocks\n", *eob_run);
602         break;
603
604     case 5:
605         debug_token("DCT_REPEAT_RUN3_TOKEN, ");
606         *eob_run = get_bits(gb, 4) + 16;
607         debug_token("EOB the next %d blocks\n", *eob_run);
608         break;
609
610     case 6:
611         debug_token("DCT_REPEAT_RUN4_TOKEN, ");
612         *eob_run = get_bits(gb, 12);
613         debug_token("EOB the next %d blocks\n", *eob_run);
614         break;
615
616     case 7:
617         debug_token("DCT_SHORT_ZRL_TOKEN, ");
618         /* note that this token actually indicates that (3 extra bits) + 1 0s
619          * should be output; this case specifies a run of (3 EBs) 0s and a
620          * coefficient of 0. */
621         *zero_run = get_bits(gb, 3);
622         *coeff = 0;
623         debug_token("skip the next %d positions in output matrix\n", *zero_run + 1);
624         break;
625
626     case 8:
627         debug_token("DCT_ZRL_TOKEN, ");
628         /* note that this token actually indicates that (6 extra bits) + 1 0s
629          * should be output; this case specifies a run of (6 EBs) 0s and a
630          * coefficient of 0. */
631         *zero_run = get_bits(gb, 6);
632         *coeff = 0;
633         debug_token("skip the next %d positions in output matrix\n", *zero_run + 1);
634         break;
635
636     case 9:
637         debug_token("ONE_TOKEN, output 1\n");
638         *coeff = 1;
639         break;
640
641     case 10:
642         debug_token("MINUS_ONE_TOKEN, output -1\n");
643         *coeff = -1;
644         break;
645
646     case 11:
647         debug_token("TWO_TOKEN, output 2\n");
648         *coeff = 2;
649         break;
650
651     case 12:
652         debug_token("MINUS_TWO_TOKEN, output -2\n");
653         *coeff = -2;
654         break;
655
656     case 13:
657     case 14:
658     case 15:
659     case 16:
660         debug_token("LOW_VAL_TOKENS, ");
661         if (get_bits(gb, 1))
662             *coeff = -(3 + (token - 13));
663         else
664             *coeff = 3 + (token - 13);
665         debug_token("output %d\n", *coeff);
666         break;
667
668     case 17:
669         debug_token("DCT_VAL_CATEGORY3, ");
670         sign = get_bits(gb, 1);
671         *coeff = 7 + get_bits(gb, 1);
672         if (sign)
673             *coeff = -(*coeff);
674         debug_token("output %d\n", *coeff);
675         break;
676
677     case 18:
678         debug_token("DCT_VAL_CATEGORY4, ");
679         sign = get_bits(gb, 1);
680         *coeff = 9 + get_bits(gb, 2);
681         if (sign)
682             *coeff = -(*coeff);
683         debug_token("output %d\n", *coeff);
684         break;
685
686     case 19:
687         debug_token("DCT_VAL_CATEGORY5, ");
688         sign = get_bits(gb, 1);
689         *coeff = 13 + get_bits(gb, 3);
690         if (sign)
691             *coeff = -(*coeff);
692         debug_token("output %d\n", *coeff);
693         break;
694
695     case 20:
696         debug_token("DCT_VAL_CATEGORY6, ");
697         sign = get_bits(gb, 1);
698         *coeff = 21 + get_bits(gb, 4);
699         if (sign)
700             *coeff = -(*coeff);
701         debug_token("output %d\n", *coeff);
702         break;
703
704     case 21:
705         debug_token("DCT_VAL_CATEGORY7, ");
706         sign = get_bits(gb, 1);
707         *coeff = 37 + get_bits(gb, 5);
708         if (sign)
709             *coeff = -(*coeff);
710         debug_token("output %d\n", *coeff);
711         break;
712
713     case 22:
714         debug_token("DCT_VAL_CATEGORY8, ");
715         sign = get_bits(gb, 1);
716         *coeff = 69 + get_bits(gb, 9);
717         if (sign)
718             *coeff = -(*coeff);
719         debug_token("output %d\n", *coeff);
720         break;
721
722     case 23:
723     case 24:
724     case 25:
725     case 26:
726     case 27:
727         debug_token("DCT_RUN_CATEGORY1, ");
728         *zero_run = token - 22;
729         if (get_bits(gb, 1))
730             *coeff = -1;
731         else
732             *coeff = 1;
733         debug_token("output %d 0s, then %d\n", *zero_run, *coeff);
734         break;
735
736     case 28:
737         debug_token("DCT_RUN_CATEGORY1B, ");
738         if (get_bits(gb, 1))
739             *coeff = -1;
740         else
741             *coeff = 1;
742         *zero_run = 6 + get_bits(gb, 2);
743         debug_token("output %d 0s, then %d\n", *zero_run, *coeff);
744         break;
745
746     case 29:
747         debug_token("DCT_RUN_CATEGORY1C, ");
748         if (get_bits(gb, 1))
749             *coeff = -1;
750         else
751             *coeff = 1;
752         *zero_run = 10 + get_bits(gb, 3);
753         debug_token("output %d 0s, then %d\n", *zero_run, *coeff);
754         break;
755
756     case 30:
757         debug_token("DCT_RUN_CATEGORY2, ");
758         sign = get_bits(gb, 1);
759         *coeff = 2 + get_bits(gb, 1);
760         if (sign)
761             *coeff = -(*coeff);
762         *zero_run = 1;
763         debug_token("output %d 0s, then %d\n", *zero_run, *coeff);
764         break;
765
766     case 31:
767         debug_token("DCT_RUN_CATEGORY2, ");
768         sign = get_bits(gb, 1);
769         *coeff = 2 + get_bits(gb, 1);
770         if (sign)
771             *coeff = -(*coeff);
772         *zero_run = 2 + get_bits(gb, 1);
773         debug_token("output %d 0s, then %d\n", *zero_run, *coeff);
774         break;
775
776     default:
777         printf ("  vp3: help! Got a bad token: %d > 31\n", token);
778         break;
779
780   }
781 }
782
783 /*
784  * This function wipes out all of the fragment data.
785  */
786 static void init_frame(Vp3DecodeContext *s, GetBitContext *gb)
787 {
788     int i;
789
790     /* zero out all of the fragment information */
791     s->coded_fragment_list_index = 0;
792     for (i = 0; i < s->fragment_count; i++) {
793         memset(s->all_fragments[i].coeffs, 0, 64 * sizeof(DCTELEM));
794         s->all_fragments[i].coeff_count = 0;
795         s->all_fragments[i].last_coeff = 0;
796     }
797 }
798
799 /*
800  * This function sets of the dequantization tables used for a particular
801  * frame.
802  */
803 static void init_dequantizer(Vp3DecodeContext *s)
804 {
805
806     int quality_scale = vp31_quality_threshold[s->quality_index];
807     int dc_scale_factor = vp31_dc_scale_factor[s->quality_index];
808     int i, j;
809
810     debug_vp3("  vp3: initializing dequantization tables\n");
811
812     /* 
813      * Scale dequantizers:
814      *
815      *   quantizer * sf
816      *   --------------
817      *        100
818      *
819      * where sf = dc_scale_factor for DC quantizer
820      *           or quality_scale for AC quantizer
821      *
822      * Then, saturate the result to a lower limit of MIN_DEQUANT_VAL.
823      */
824 #define SCALER 1
825
826     /* scale DC quantizers */
827     s->intra_y_dequant[0] = vp31_intra_y_dequant[0] * dc_scale_factor / 100;
828     if (s->intra_y_dequant[0] < MIN_DEQUANT_VAL * 2)
829         s->intra_y_dequant[0] = MIN_DEQUANT_VAL * 2;
830     s->intra_y_dequant[0] *= SCALER;
831
832     s->intra_c_dequant[0] = vp31_intra_c_dequant[0] * dc_scale_factor / 100;
833     if (s->intra_c_dequant[0] < MIN_DEQUANT_VAL * 2)
834         s->intra_c_dequant[0] = MIN_DEQUANT_VAL * 2;
835     s->intra_c_dequant[0] *= SCALER;
836
837     s->inter_dequant[0] = vp31_inter_dequant[0] * dc_scale_factor / 100;
838     if (s->inter_dequant[0] < MIN_DEQUANT_VAL * 4)
839         s->inter_dequant[0] = MIN_DEQUANT_VAL * 4;
840     s->inter_dequant[0] *= SCALER;
841
842     /* scale AC quantizers, zigzag at the same time in preparation for
843      * the dequantization phase */
844     for (i = 1; i < 64; i++) {
845
846         j = quant_index[i];
847
848         s->intra_y_dequant[j] = vp31_intra_y_dequant[i] * quality_scale / 100;
849         if (s->intra_y_dequant[j] < MIN_DEQUANT_VAL)
850             s->intra_y_dequant[j] = MIN_DEQUANT_VAL;
851         s->intra_y_dequant[j] *= SCALER;
852
853         s->intra_c_dequant[j] = vp31_intra_c_dequant[i] * quality_scale / 100;
854         if (s->intra_c_dequant[j] < MIN_DEQUANT_VAL)
855             s->intra_c_dequant[j] = MIN_DEQUANT_VAL;
856         s->intra_c_dequant[j] *= SCALER;
857
858         s->inter_dequant[j] = vp31_inter_dequant[i] * quality_scale / 100;
859         if (s->inter_dequant[j] < MIN_DEQUANT_VAL * 2)
860             s->inter_dequant[j] = MIN_DEQUANT_VAL * 2;
861         s->inter_dequant[j] *= SCALER;
862     }
863
864     /* print debug information as requested */
865     debug_dequantizers("intra Y dequantizers:\n");
866     for (i = 0; i < 8; i++) {
867       for (j = i * 8; j < i * 8 + 8; j++) {
868         debug_dequantizers(" %4d,", s->intra_y_dequant[j]);
869       }
870       debug_dequantizers("\n");
871     }
872     debug_dequantizers("\n");
873
874     debug_dequantizers("intra C dequantizers:\n");
875     for (i = 0; i < 8; i++) {
876       for (j = i * 8; j < i * 8 + 8; j++) {
877         debug_dequantizers(" %4d,", s->intra_c_dequant[j]);
878       }
879       debug_dequantizers("\n");
880     }
881     debug_dequantizers("\n");
882
883     debug_dequantizers("interframe dequantizers:\n");
884     for (i = 0; i < 8; i++) {
885       for (j = i * 8; j < i * 8 + 8; j++) {
886         debug_dequantizers(" %4d,", s->inter_dequant[j]);
887       }
888       debug_dequantizers("\n");
889     }
890     debug_dequantizers("\n");
891 }
892
893 /*
894  * This function is used to fetch runs of 1s or 0s from the bitstream for
895  * use in determining which superblocks are fully and partially coded.
896  *
897  *  Codeword                RunLength
898  *  0                       1
899  *  10x                     2-3
900  *  110x                    4-5
901  *  1110xx                  6-9
902  *  11110xxx                10-17
903  *  111110xxxx              18-33
904  *  111111xxxxxxxxxxxx      34-4129
905  */
906 static int get_superblock_run_length(GetBitContext *gb)
907 {
908
909     if (get_bits(gb, 1) == 0)
910         return 1;
911
912     else if (get_bits(gb, 1) == 0)
913         return (2 + get_bits(gb, 1));
914
915     else if (get_bits(gb, 1) == 0)
916         return (4 + get_bits(gb, 1));
917
918     else if (get_bits(gb, 1) == 0)
919         return (6 + get_bits(gb, 2));
920
921     else if (get_bits(gb, 1) == 0)
922         return (10 + get_bits(gb, 3));
923
924     else if (get_bits(gb, 1) == 0)
925         return (18 + get_bits(gb, 4));
926
927     else
928         return (34 + get_bits(gb, 12));
929
930 }
931
932 /*
933  * This function is used to fetch runs of 1s or 0s from the bitstream for
934  * use in determining which particular fragments are coded.
935  *
936  * Codeword                RunLength
937  * 0x                      1-2
938  * 10x                     3-4
939  * 110x                    5-6
940  * 1110xx                  7-10
941  * 11110xx                 11-14
942  * 11111xxxx               15-30
943  */
944 static int get_fragment_run_length(GetBitContext *gb)
945 {
946
947     if (get_bits(gb, 1) == 0)
948         return (1 + get_bits(gb, 1));
949
950     else if (get_bits(gb, 1) == 0)
951         return (3 + get_bits(gb, 1));
952
953     else if (get_bits(gb, 1) == 0)
954         return (5 + get_bits(gb, 1));
955
956     else if (get_bits(gb, 1) == 0)
957         return (7 + get_bits(gb, 2));
958
959     else if (get_bits(gb, 1) == 0)
960         return (11 + get_bits(gb, 2));
961
962     else
963         return (15 + get_bits(gb, 4));
964
965 }
966
967 /*
968  * This function decodes a VLC from the bitstream and returns a number
969  * that ranges from 0..7. The number indicates which of the 8 coding
970  * modes to use.
971  *
972  *  VLC       Number
973  *  0            0
974  *  10           1
975  *  110          2
976  *  1110         3
977  *  11110        4
978  *  111110       5
979  *  1111110      6
980  *  1111111      7
981  *
982  */
983 static int get_mode_code(GetBitContext *gb)
984 {
985
986     if (get_bits(gb, 1) == 0)
987         return 0;
988
989     else if (get_bits(gb, 1) == 0)
990         return 1;
991
992     else if (get_bits(gb, 1) == 0)
993         return 2;
994
995     else if (get_bits(gb, 1) == 0)
996         return 3;
997
998     else if (get_bits(gb, 1) == 0)
999         return 4;
1000
1001     else if (get_bits(gb, 1) == 0)
1002         return 5;
1003
1004     else if (get_bits(gb, 1) == 0)
1005         return 6;
1006
1007     else
1008         return 7;
1009
1010 }
1011
1012 /*
1013  * This function extracts a motion vector from the bitstream using a VLC
1014  * scheme. 3 bits are fetched from the bitstream and 1 of 8 actions is
1015  * taken depending on the value on those 3 bits:
1016  *
1017  *  0: return 0
1018  *  1: return 1
1019  *  2: return -1
1020  *  3: if (next bit is 1) return -2, else return 2
1021  *  4: if (next bit is 1) return -3, else return 3
1022  *  5: return 4 + (next 2 bits), next bit is sign
1023  *  6: return 8 + (next 3 bits), next bit is sign
1024  *  7: return 16 + (next 4 bits), next bit is sign
1025  */
1026 static int get_motion_vector_vlc(GetBitContext *gb)
1027 {
1028     int bits;
1029
1030     bits = get_bits(gb, 3);
1031
1032     switch(bits) {
1033
1034     case 0:
1035         bits = 0;
1036         break;
1037
1038     case 1:
1039         bits = 1;
1040         break;
1041
1042     case 2:
1043         bits = -1;
1044         break;
1045
1046     case 3:
1047         if (get_bits(gb, 1) == 0)
1048             bits = 2;
1049         else
1050             bits = -2;
1051         break;
1052
1053     case 4:
1054         if (get_bits(gb, 1) == 0)
1055             bits = 3;
1056         else
1057             bits = -3;
1058         break;
1059
1060     case 5:
1061         bits = 4 + get_bits(gb, 2);
1062         if (get_bits(gb, 1) == 1)
1063             bits = -bits;
1064         break;
1065
1066     case 6:
1067         bits = 8 + get_bits(gb, 3);
1068         if (get_bits(gb, 1) == 1)
1069             bits = -bits;
1070         break;
1071
1072     case 7:
1073         bits = 16 + get_bits(gb, 4);
1074         if (get_bits(gb, 1) == 1)
1075             bits = -bits;
1076         break;
1077
1078     }
1079
1080     return bits;
1081 }
1082
1083 /*
1084  * This function fetches a 5-bit number from the stream followed by
1085  * a sign and calls it a motion vector.
1086  */
1087 static int get_motion_vector_fixed(GetBitContext *gb)
1088 {
1089
1090     int bits;
1091
1092     bits = get_bits(gb, 5);
1093
1094     if (get_bits(gb, 1) == 1)
1095         bits = -bits;
1096
1097     return bits;
1098 }
1099
1100 /*
1101  * This function unpacks all of the superblock/macroblock/fragment coding 
1102  * information from the bitstream.
1103  */
1104 static void unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
1105 {
1106     int bit = 0;
1107     int current_superblock = 0;
1108     int current_run = 0;
1109     int decode_fully_flags = 0;
1110     int decode_partial_blocks = 0;
1111
1112     int i, j;
1113     int current_fragment;
1114
1115     debug_vp3("  vp3: unpacking superblock coding\n");
1116
1117     if (s->keyframe) {
1118
1119         debug_vp3("    keyframe-- all superblocks are fully coded\n");
1120         memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
1121
1122     } else {
1123
1124         /* unpack the list of partially-coded superblocks */
1125         bit = get_bits(gb, 1);
1126         /* toggle the bit because as soon as the first run length is 
1127          * fetched the bit will be toggled again */
1128         bit ^= 1;
1129         while (current_superblock < s->superblock_count) {
1130             if (current_run == 0) {
1131                 bit ^= 1;
1132                 current_run = get_superblock_run_length(gb);
1133                 debug_block_coding("      setting superblocks %d..%d to %s\n",
1134                     current_superblock,
1135                     current_superblock + current_run - 1,
1136                     (bit) ? "partially coded" : "not coded");
1137
1138                 /* if any of the superblocks are not partially coded, flag
1139                  * a boolean to decode the list of fully-coded superblocks */
1140                 if (bit == 0)
1141                     decode_fully_flags = 1;
1142             } else {
1143
1144                 /* make a note of the fact that there are partially coded
1145                  * superblocks */
1146                 decode_partial_blocks = 1;
1147
1148             }
1149             s->superblock_coding[current_superblock++] = 
1150                 (bit) ? SB_PARTIALLY_CODED : SB_NOT_CODED;
1151             current_run--;
1152         }
1153
1154         /* unpack the list of fully coded superblocks if any of the blocks were
1155          * not marked as partially coded in the previous step */
1156         if (decode_fully_flags) {
1157
1158             current_superblock = 0;
1159             current_run = 0;
1160             bit = get_bits(gb, 1);
1161             /* toggle the bit because as soon as the first run length is 
1162              * fetched the bit will be toggled again */
1163             bit ^= 1;
1164             while (current_superblock < s->superblock_count) {
1165
1166                 /* skip any superblocks already marked as partially coded */
1167                 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
1168
1169                     if (current_run == 0) {
1170                         bit ^= 1;
1171                         current_run = get_superblock_run_length(gb);
1172                     }
1173
1174                     debug_block_coding("      setting superblock %d to %s\n",
1175                         current_superblock,
1176                         (bit) ? "fully coded" : "not coded");
1177                     s->superblock_coding[current_superblock] = 
1178                         (bit) ? SB_FULLY_CODED : SB_NOT_CODED;
1179                     current_run--;
1180                 }
1181                 current_superblock++;
1182             }
1183         }
1184
1185         /* if there were partial blocks, initialize bitstream for
1186          * unpacking fragment codings */
1187         if (decode_partial_blocks) {
1188
1189             current_run = 0;
1190             bit = get_bits(gb, 1);
1191             /* toggle the bit because as soon as the first run length is 
1192              * fetched the bit will be toggled again */
1193             bit ^= 1;
1194         }
1195     }
1196
1197     /* figure out which fragments are coded; iterate through each
1198      * superblock (all planes) */
1199     s->coded_fragment_list_index = 0;
1200     memset(s->macroblock_coded, 0, s->macroblock_count);
1201     for (i = 0; i < s->superblock_count; i++) {
1202
1203         /* iterate through all 16 fragments in a superblock */
1204         for (j = 0; j < 16; j++) {
1205
1206             /* if the fragment is in bounds, check its coding status */
1207             current_fragment = s->superblock_fragments[i * 16 + j];
1208             if (current_fragment != -1) {
1209                 if (s->superblock_coding[i] == SB_NOT_CODED) {
1210
1211                     /* copy all the fragments from the prior frame */
1212                     s->all_fragments[current_fragment].coding_method = 
1213                         MODE_COPY;
1214
1215                 } else if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
1216
1217                     /* fragment may or may not be coded; this is the case
1218                      * that cares about the fragment coding runs */
1219                     if (current_run == 0) {
1220                         bit ^= 1;
1221                         current_run = get_fragment_run_length(gb);
1222                     }
1223
1224                     if (bit) {
1225                         /* mode will be decoded in the next phase */
1226                         s->all_fragments[current_fragment].coding_method = 
1227                             MODE_INTER_NO_MV;
1228                         s->coded_fragment_list[s->coded_fragment_list_index++] = 
1229                             current_fragment;
1230                         s->macroblock_coded[s->all_fragments[current_fragment].macroblock] = 1;
1231                         debug_block_coding("      superblock %d is partially coded, fragment %d is coded\n",
1232                             i, current_fragment);
1233                     } else {
1234                         /* not coded; copy this fragment from the prior frame */
1235                         s->all_fragments[current_fragment].coding_method =
1236                             MODE_COPY;
1237                         debug_block_coding("      superblock %d is partially coded, fragment %d is not coded\n",
1238                             i, current_fragment);
1239                     }
1240
1241                     current_run--;
1242
1243                 } else {
1244
1245                     /* fragments are fully coded in this superblock; actual
1246                      * coding will be determined in next step */
1247                     s->all_fragments[current_fragment].coding_method = 
1248                         MODE_INTER_NO_MV;
1249                     s->coded_fragment_list[s->coded_fragment_list_index++] = 
1250                         current_fragment;
1251                     s->macroblock_coded[s->all_fragments[current_fragment].macroblock] = 1;
1252                     debug_block_coding("      superblock %d is fully coded, fragment %d is coded\n",
1253                         i, current_fragment);
1254                 }
1255             }
1256         }
1257     }
1258 }
1259
1260 /*
1261  * This function unpacks all the coding mode data for individual macroblocks
1262  * from the bitstream.
1263  */
1264 static void unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
1265 {
1266     int i, j, k;
1267     int scheme;
1268     int current_macroblock;
1269     int current_fragment;
1270     int coding_mode;
1271
1272     debug_vp3("  vp3: unpacking encoding modes\n");
1273
1274     if (s->keyframe) {
1275         debug_vp3("    keyframe-- all blocks are coded as INTRA\n");
1276
1277         for (i = 0; i < s->fragment_count; i++)
1278             s->all_fragments[i].coding_method = MODE_INTRA;
1279
1280     } else {
1281
1282         /* fetch the mode coding scheme for this frame */
1283         scheme = get_bits(gb, 3);
1284         debug_modes("    using mode alphabet %d\n", scheme);
1285
1286         /* is it a custom coding scheme? */
1287         if (scheme == 0) {
1288             debug_modes("    custom mode alphabet ahead:\n");
1289             for (i = 0; i < 8; i++)
1290                 ModeAlphabet[0][i] = get_bits(gb, 3);
1291         }
1292
1293         for (i = 0; i < 8; i++)
1294             debug_modes("      mode[%d][%d] = %d\n", scheme, i, 
1295                 ModeAlphabet[scheme][i]);
1296
1297         /* iterate through all of the macroblocks that contain 1 or more
1298          * coded fragments */
1299         for (i = 0; i < s->u_superblock_start; i++) {
1300
1301             for (j = 0; j < 4; j++) {
1302                 current_macroblock = s->superblock_macroblocks[i * 4 + j];
1303                 if ((current_macroblock == -1) ||
1304                     (!s->macroblock_coded[current_macroblock]))
1305                     continue;
1306
1307                 /* mode 7 means get 3 bits for each coding mode */
1308                 if (scheme == 7)
1309                     coding_mode = get_bits(gb, 3);
1310                 else
1311                     coding_mode = ModeAlphabet[scheme][get_mode_code(gb)];
1312
1313                 for (k = 0; k < 6; k++) {
1314                     current_fragment = 
1315                         s->macroblock_fragments[current_macroblock * 6 + k];
1316                     if (s->all_fragments[current_fragment].coding_method != 
1317                         MODE_COPY)
1318                         s->all_fragments[current_fragment].coding_method =
1319                             coding_mode;
1320                 }
1321
1322                 debug_modes("    coding method for macroblock starting @ fragment %d = %d\n",
1323                     s->macroblock_fragments[current_macroblock * 6], coding_mode);
1324             }
1325         }
1326     }
1327 }
1328
1329 /*
1330  * This function adjusts the components of a motion vector for the halfpel
1331  * motion grid. c_plane indicates whether the vector applies to the U or V
1332  * plane. The function returns the halfpel function index to be used in
1333  * ffmpeg's put_pixels[]() array of functions.
1334  */
1335 static inline int adjust_vector(int *x, int *y, int c_plane)
1336 {
1337     int motion_halfpel_index = 0;
1338     int x_halfpel;
1339     int y_halfpel;
1340
1341     if (!c_plane) {
1342
1343         x_halfpel = *x & 1;
1344         motion_halfpel_index |= x_halfpel;
1345         if (*x >= 0)
1346             *x >>= 1;
1347         else
1348             *x = -( (-(*x) >> 1) + x_halfpel);
1349
1350         y_halfpel = *y & 1;
1351         motion_halfpel_index |= (y_halfpel << 1);
1352         if (*y >= 0)
1353             *y >>= 1;
1354         else
1355             *y = -( (-(*y) >> 1) + y_halfpel);
1356
1357     } else {
1358
1359         x_halfpel = ((*x & 0x03) != 0);
1360         motion_halfpel_index |= x_halfpel;
1361         if (*x >= 0)
1362             *x >>= 2;
1363         else
1364             *x = -( (-(*x) >> 2) + x_halfpel);
1365
1366         y_halfpel = ((*y & 0x03) != 0);
1367         motion_halfpel_index |= (y_halfpel << 1);
1368         if (*y >= 0)
1369             *y >>= 2;
1370         else
1371             *y = -( (-(*y) >> 2) + y_halfpel);
1372
1373     }
1374
1375     return motion_halfpel_index;
1376 }
1377
1378 /*
1379  * This function unpacks all the motion vectors for the individual
1380  * macroblocks from the bitstream.
1381  */
1382 static void unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
1383 {
1384     int i, j, k;
1385     int coding_mode;
1386     int motion_x[6];
1387     int motion_y[6];
1388     int last_motion_x = 0;
1389     int last_motion_y = 0;
1390     int prior_last_motion_x = 0;
1391     int prior_last_motion_y = 0;
1392     int current_macroblock;
1393     int current_fragment;
1394
1395     debug_vp3("  vp3: unpacking motion vectors\n");
1396
1397     if (s->keyframe) {
1398
1399         debug_vp3("    keyframe-- there are no motion vectors\n");
1400
1401     } else {
1402
1403         memset(motion_x, 0, 6 * sizeof(int));
1404         memset(motion_y, 0, 6 * sizeof(int));
1405
1406         /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
1407         coding_mode = get_bits(gb, 1);
1408         debug_vectors("    using %s scheme for unpacking motion vectors\n",
1409             (coding_mode == 0) ? "VLC" : "fixed-length");
1410
1411         /* iterate through all of the macroblocks that contain 1 or more
1412          * coded fragments */
1413         for (i = 0; i < s->u_superblock_start; i++) {
1414
1415             for (j = 0; j < 4; j++) {
1416                 current_macroblock = s->superblock_macroblocks[i * 4 + j];
1417                 if ((current_macroblock == -1) ||
1418                     (!s->macroblock_coded[current_macroblock]))
1419                     continue;
1420
1421                 current_fragment = s->macroblock_fragments[current_macroblock * 6];
1422                 switch (s->all_fragments[current_fragment].coding_method) {
1423
1424                 case MODE_INTER_PLUS_MV:
1425                 case MODE_GOLDEN_MV:
1426                     /* all 6 fragments use the same motion vector */
1427                     if (coding_mode == 0) {
1428                         motion_x[0] = get_motion_vector_vlc(gb);
1429                         motion_y[0] = get_motion_vector_vlc(gb);
1430                     } else {
1431                         motion_x[0] = get_motion_vector_fixed(gb);
1432                         motion_y[0] = get_motion_vector_fixed(gb);
1433                     }
1434                     for (k = 1; k < 6; k++) {
1435                         motion_x[k] = motion_x[0];
1436                         motion_y[k] = motion_y[0];
1437                     }
1438
1439                     /* vector maintenance, only on MODE_INTER_PLUS_MV */
1440                     if (s->all_fragments[current_fragment].coding_method ==
1441                         MODE_INTER_PLUS_MV) {
1442                         prior_last_motion_x = last_motion_x;
1443                         prior_last_motion_y = last_motion_y;
1444                         last_motion_x = motion_x[0];
1445                         last_motion_y = motion_y[0];
1446                     }
1447                     break;
1448
1449                 case MODE_INTER_FOURMV:
1450                     /* fetch 4 vectors from the bitstream, one for each
1451                      * Y fragment, then average for the C fragment vectors */
1452                     motion_x[4] = motion_y[4] = 0;
1453                     for (k = 0; k < 4; k++) {
1454                         if (coding_mode == 0) {
1455                             motion_x[k] = get_motion_vector_vlc(gb);
1456                             motion_y[k] = get_motion_vector_vlc(gb);
1457                         } else {
1458                             motion_x[k] = get_motion_vector_fixed(gb);
1459                             motion_y[k] = get_motion_vector_fixed(gb);
1460                         }
1461                         motion_x[4] += motion_x[k];
1462                         motion_y[4] += motion_y[k];
1463                     }
1464
1465                     if (motion_x[4] >= 0) 
1466                         motion_x[4] = (motion_x[4] + 2) / 4;
1467                     else
1468                         motion_x[4] = (motion_x[4] - 2) / 4;
1469                     motion_x[5] = motion_x[4];
1470
1471                     if (motion_y[4] >= 0) 
1472                         motion_y[4] = (motion_y[4] + 2) / 4;
1473                     else
1474                         motion_y[4] = (motion_y[4] - 2) / 4;
1475                     motion_y[5] = motion_y[4];
1476
1477                     /* vector maintenance; vector[3] is treated as the
1478                      * last vector in this case */
1479                     prior_last_motion_x = last_motion_x;
1480                     prior_last_motion_y = last_motion_y;
1481                     last_motion_x = motion_x[3];
1482                     last_motion_y = motion_y[3];
1483                     break;
1484
1485                 case MODE_INTER_LAST_MV:
1486                     /* all 6 fragments use the last motion vector */
1487                     motion_x[0] = last_motion_x;
1488                     motion_y[0] = last_motion_y;
1489                     for (k = 1; k < 6; k++) {
1490                         motion_x[k] = motion_x[0];
1491                         motion_y[k] = motion_y[0];
1492                     }
1493
1494                     /* no vector maintenance (last vector remains the
1495                      * last vector) */
1496                     break;
1497
1498                 case MODE_INTER_PRIOR_LAST:
1499                     /* all 6 fragments use the motion vector prior to the
1500                      * last motion vector */
1501                     motion_x[0] = prior_last_motion_x;
1502                     motion_y[0] = prior_last_motion_y;
1503                     for (k = 1; k < 6; k++) {
1504                         motion_x[k] = motion_x[0];
1505                         motion_y[k] = motion_y[0];
1506                     }
1507
1508                     /* vector maintenance */
1509                     prior_last_motion_x = last_motion_x;
1510                     prior_last_motion_y = last_motion_y;
1511                     last_motion_x = motion_x[0];
1512                     last_motion_y = motion_y[0];
1513                     break;
1514
1515                 default:
1516                     /* covers intra, inter without MV, golden without MV */
1517                     memset(motion_x, 0, 6 * sizeof(int));
1518                     memset(motion_y, 0, 6 * sizeof(int));
1519
1520                     /* no vector maintenance */
1521                     break;
1522                 }
1523
1524                 /* assign the motion vectors to the correct fragments */
1525                 debug_vectors("    vectors for macroblock starting @ fragment %d (coding method %d):\n",
1526                     current_fragment,
1527                     s->all_fragments[current_fragment].coding_method);
1528                 for (k = 0; k < 6; k++) {
1529                     current_fragment = 
1530                         s->macroblock_fragments[current_macroblock * 6 + k];
1531                     s->all_fragments[current_fragment].motion_halfpel_index =
1532                         adjust_vector(&motion_x[k], &motion_y[k],
1533                         ((k == 4) || (k == 5)));
1534                     s->all_fragments[current_fragment].motion_x = motion_x[k];
1535                     s->all_fragments[current_fragment].motion_y = motion_y[k];
1536                     debug_vectors("    vector %d: fragment %d = (%d, %d), index %d\n",
1537                         k, current_fragment, motion_x[k], motion_y[k],
1538                         s->all_fragments[current_fragment].motion_halfpel_index);
1539                 }
1540             }
1541         }
1542     }
1543 }
1544
1545 /* 
1546  * This function is called by unpack_dct_coeffs() to extract the VLCs from
1547  * the bitstream. The VLCs encode tokens which are used to unpack DCT
1548  * data. This function unpacks all the VLCs for either the Y plane or both
1549  * C planes, and is called for DC coefficients or different AC coefficient
1550  * levels (since different coefficient types require different VLC tables.
1551  *
1552  * This function returns a residual eob run. E.g, if a particular token gave
1553  * instructions to EOB the next 5 fragments and there were only 2 fragments
1554  * left in the current fragment range, 3 would be returned so that it could
1555  * be passed into the next call to this same function.
1556  */
1557 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1558                         VLC *table, int coeff_index,
1559                         int first_fragment, int last_fragment,
1560                         int eob_run)
1561 {
1562     int i;
1563     int token;
1564     int zero_run;
1565     DCTELEM coeff;
1566     Vp3Fragment *fragment;
1567
1568     for (i = first_fragment; i < last_fragment; i++) {
1569
1570         fragment = &s->all_fragments[s->coded_fragment_list[i]];
1571         if (fragment->coeff_count > coeff_index)
1572             continue;
1573
1574         if (!eob_run) {
1575             /* decode a VLC into a token */
1576             token = get_vlc2(gb, table->table, 5, 3);
1577             debug_vlc(" token = %2d, ", token);
1578             /* use the token to get a zero run, a coefficient, and an eob run */
1579             unpack_token(gb, token, &zero_run, &coeff, &eob_run);
1580         }
1581
1582         if (!eob_run) {
1583             fragment->coeff_count += zero_run;
1584             if (fragment->coeff_count < 64)
1585                 fragment->coeffs[fragment->coeff_count++] = coeff;
1586             debug_vlc(" fragment %d coeff = %d\n",
1587                 s->coded_fragment_list[i], fragment->coeffs[coeff_index]);
1588         } else {
1589             fragment->last_coeff = fragment->coeff_count;
1590             fragment->coeff_count = 64;
1591             debug_vlc(" fragment %d eob with %d coefficients\n", 
1592                 s->coded_fragment_list[i], fragment->last_coeff);
1593             eob_run--;
1594         }
1595     }
1596
1597     return eob_run;
1598 }
1599
1600 /*
1601  * This function unpacks all of the DCT coefficient data from the
1602  * bitstream.
1603  */
1604 static void unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1605 {
1606     int i;
1607     int dc_y_table;
1608     int dc_c_table;
1609     int ac_y_table;
1610     int ac_c_table;
1611     int residual_eob_run = 0;
1612
1613     /* for the binary search */
1614     int left, middle, right, found;
1615     /* this indicates the first fragment of the color plane data */
1616     int plane_split = 0;
1617
1618     debug_vp3("  vp3: unpacking DCT coefficients\n");
1619
1620     /* find the plane split (the first color plane fragment) using a binary 
1621      * search; test the boundaries first */
1622     if (s->coded_fragment_list_index == 0)
1623         return;
1624     if (s->u_fragment_start <= s->coded_fragment_list[0])
1625         plane_split = 0;  /* this means no Y fragments */
1626     else if (s->coded_fragment_list[s->coded_fragment_list_index - 1] >
1627         s->u_fragment_start) {
1628
1629         left = 0;
1630         right = s->coded_fragment_list_index - 1;
1631         found = 0;
1632         do {
1633             middle = (left + right + 1) / 2;
1634             if ((s->coded_fragment_list[middle] >= s->u_fragment_start) &&
1635                 (s->coded_fragment_list[middle - 1] < s->u_fragment_start))
1636                 found = 1;
1637             else if (s->coded_fragment_list[middle] < s->u_fragment_start)
1638                 left = middle;
1639             else
1640                 right = middle;
1641         } while (!found);
1642
1643         plane_split = middle;
1644     }
1645
1646     debug_vp3("  plane split @ index %d (fragment %d)\n", plane_split,
1647         s->coded_fragment_list[plane_split]);
1648
1649     /* fetch the DC table indices */
1650     dc_y_table = get_bits(gb, 4);
1651     dc_c_table = get_bits(gb, 4);
1652
1653     /* unpack the Y plane DC coefficients */
1654     debug_vp3("  vp3: unpacking Y plane DC coefficients using table %d\n",
1655         dc_y_table);
1656     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0, 
1657         0, plane_split, residual_eob_run);
1658
1659     /* unpack the C plane DC coefficients */
1660     debug_vp3("  vp3: unpacking C plane DC coefficients using table %d\n",
1661         dc_c_table);
1662     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1663         plane_split, s->coded_fragment_list_index, residual_eob_run);
1664
1665     /* fetch the level 1 AC table indices */
1666     ac_y_table = get_bits(gb, 4);
1667     ac_c_table = get_bits(gb, 4);
1668
1669     /* unpack the level 1 AC coefficients (coeffs 1-5) */
1670     for (i = 1; i <= 5; i++) {
1671
1672         debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",
1673             i, ac_y_table);
1674         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_1[ac_y_table], i, 
1675             0, plane_split, residual_eob_run);
1676
1677         debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",
1678             i, ac_c_table);
1679         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_1[ac_c_table], i, 
1680             plane_split, s->coded_fragment_list_index, residual_eob_run);
1681     }
1682
1683     /* unpack the level 2 AC coefficients (coeffs 6-14) */
1684     for (i = 6; i <= 14; i++) {
1685
1686         debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",
1687             i, ac_y_table);
1688         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_2[ac_y_table], i, 
1689             0, plane_split, residual_eob_run);
1690
1691         debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",
1692             i, ac_c_table);
1693         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_2[ac_c_table], i, 
1694             plane_split, s->coded_fragment_list_index, residual_eob_run);
1695     }
1696
1697     /* unpack the level 3 AC coefficients (coeffs 15-27) */
1698     for (i = 15; i <= 27; i++) {
1699
1700         debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",
1701             i, ac_y_table);
1702         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_3[ac_y_table], i, 
1703             0, plane_split, residual_eob_run);
1704
1705         debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",
1706             i, ac_c_table);
1707         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_3[ac_c_table], i, 
1708             plane_split, s->coded_fragment_list_index, residual_eob_run);
1709     }
1710
1711     /* unpack the level 4 AC coefficients (coeffs 28-63) */
1712     for (i = 28; i <= 63; i++) {
1713
1714         debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",
1715             i, ac_y_table);
1716         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_4[ac_y_table], i, 
1717             0, plane_split, residual_eob_run);
1718
1719         debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",
1720             i, ac_c_table);
1721         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_4[ac_c_table], i, 
1722             plane_split, s->coded_fragment_list_index, residual_eob_run);
1723     }
1724 }
1725
1726 /*
1727  * This function reverses the DC prediction for each coded fragment in
1728  * the frame. Much of this function is adapted directly from the original 
1729  * VP3 source code.
1730  */
1731 #define COMPATIBLE_FRAME(x) \
1732   (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1733 #define FRAME_CODED(x) (s->all_fragments[x].coding_method != MODE_COPY)
1734 #define HIGHBITDUPPED(X) (((signed short) X)  >> 15)
1735 static inline int iabs (int x) { return ((x < 0) ? -x : x); }
1736
1737 static void reverse_dc_prediction(Vp3DecodeContext *s,
1738                                   int first_fragment,
1739                                   int fragment_width,
1740                                   int fragment_height) 
1741 {
1742
1743 #define PUL 8
1744 #define PU 4
1745 #define PUR 2
1746 #define PL 1
1747
1748     int x, y;
1749     int i = first_fragment;
1750
1751     /*
1752      * Fragment prediction groups:
1753      *
1754      * 32222222226
1755      * 10000000004
1756      * 10000000004
1757      * 10000000004
1758      * 10000000004
1759      *
1760      * Note: Groups 5 and 7 do not exist as it would mean that the 
1761      * fragment's x coordinate is both 0 and (width - 1) at the same time.
1762      */
1763     int predictor_group;
1764     short predicted_dc;
1765
1766     /* validity flags for the left, up-left, up, and up-right fragments */
1767     int fl, ful, fu, fur;
1768
1769     /* DC values for the left, up-left, up, and up-right fragments */
1770     int vl, vul, vu, vur;
1771
1772     /* indices for the left, up-left, up, and up-right fragments */
1773     int l, ul, u, ur;
1774
1775     /* 
1776      * The 6 fields mean:
1777      *   0: up-left multiplier
1778      *   1: up multiplier
1779      *   2: up-right multiplier
1780      *   3: left multiplier
1781      *   4: mask
1782      *   5: right bit shift divisor (e.g., 7 means >>=7, a.k.a. div by 128)
1783      */
1784     int predictor_transform[16][6] = {
1785         {  0,  0,  0,  0,   0,  0 },
1786         {  0,  0,  0,  1,   0,  0 },        // PL
1787         {  0,  0,  1,  0,   0,  0 },        // PUR
1788         {  0,  0, 53, 75, 127,  7 },        // PUR|PL
1789         {  0,  1,  0,  0,   0,  0 },        // PU
1790         {  0,  1,  0,  1,   1,  1 },        // PU|PL
1791         {  0,  1,  0,  0,   0,  0 },        // PU|PUR
1792         {  0,  0, 53, 75, 127,  7 },        // PU|PUR|PL
1793         {  1,  0,  0,  0,   0,  0 },        // PUL
1794         {  0,  0,  0,  1,   0,  0 },        // PUL|PL
1795         {  1,  0,  1,  0,   1,  1 },        // PUL|PUR
1796         {  0,  0, 53, 75, 127,  7 },        // PUL|PUR|PL
1797         {  0,  1,  0,  0,   0,  0 },        // PUL|PU
1798         {-26, 29,  0, 29,  31,  5 },        // PUL|PU|PL
1799         {  3, 10,  3,  0,  15,  4 },        // PUL|PU|PUR
1800         {-26, 29,  0, 29,  31,  5 }         // PUL|PU|PUR|PL
1801     };
1802
1803     /* This table shows which types of blocks can use other blocks for
1804      * prediction. For example, INTRA is the only mode in this table to
1805      * have a frame number of 0. That means INTRA blocks can only predict
1806      * from other INTRA blocks. There are 2 golden frame coding types; 
1807      * blocks encoding in these modes can only predict from other blocks
1808      * that were encoded with these 1 of these 2 modes. */
1809     unsigned char compatible_frame[8] = {
1810         1,    /* MODE_INTER_NO_MV */
1811         0,    /* MODE_INTRA */
1812         1,    /* MODE_INTER_PLUS_MV */
1813         1,    /* MODE_INTER_LAST_MV */
1814         1,    /* MODE_INTER_PRIOR_MV */
1815         2,    /* MODE_USING_GOLDEN */
1816         2,    /* MODE_GOLDEN_MV */
1817         1     /* MODE_INTER_FOUR_MV */
1818     };
1819     int current_frame_type;
1820
1821     /* there is a last DC predictor for each of the 3 frame types */
1822     short last_dc[3];
1823
1824     int transform = 0;
1825
1826     debug_vp3("  vp3: reversing DC prediction\n");
1827
1828     vul = vu = vur = vl = 0;
1829     last_dc[0] = last_dc[1] = last_dc[2] = 0;
1830
1831     /* for each fragment row... */
1832     for (y = 0; y < fragment_height; y++) {
1833
1834         /* for each fragment in a row... */
1835         for (x = 0; x < fragment_width; x++, i++) {
1836
1837             /* reverse prediction if this block was coded */
1838             if (s->all_fragments[i].coding_method != MODE_COPY) {
1839
1840                 current_frame_type = 
1841                     compatible_frame[s->all_fragments[i].coding_method];
1842                 predictor_group = (x == 0) + ((y == 0) << 1) +
1843                     ((x + 1 == fragment_width) << 2);
1844                 debug_dc_pred(" frag %d: group %d, orig DC = %d, ",
1845                     i, predictor_group, s->all_fragments[i].coeffs[0]);
1846
1847                 switch (predictor_group) {
1848
1849                 case 0:
1850                     /* main body of fragments; consider all 4 possible
1851                      * fragments for prediction */
1852
1853                     /* calculate the indices of the predicting fragments */
1854                     ul = i - fragment_width - 1;
1855                     u = i - fragment_width;
1856                     ur = i - fragment_width + 1;
1857                     l = i - 1;
1858
1859                     /* fetch the DC values for the predicting fragments */
1860                     vul = s->all_fragments[ul].coeffs[0];
1861                     vu = s->all_fragments[u].coeffs[0];
1862                     vur = s->all_fragments[ur].coeffs[0];
1863                     vl = s->all_fragments[l].coeffs[0];
1864
1865                     /* figure out which fragments are valid */
1866                     ful = FRAME_CODED(ul) && COMPATIBLE_FRAME(ul);
1867                     fu = FRAME_CODED(u) && COMPATIBLE_FRAME(u);
1868                     fur = FRAME_CODED(ur) && COMPATIBLE_FRAME(ur);
1869                     fl = FRAME_CODED(l) && COMPATIBLE_FRAME(l);
1870
1871                     /* decide which predictor transform to use */
1872                     transform = (fl*PL) | (fu*PU) | (ful*PUL) | (fur*PUR);
1873
1874                     break;
1875
1876                 case 1:
1877                     /* left column of fragments, not including top corner;
1878                      * only consider up and up-right fragments */
1879
1880                     /* calculate the indices of the predicting fragments */
1881                     u = i - fragment_width;
1882                     ur = i - fragment_width + 1;
1883
1884                     /* fetch the DC values for the predicting fragments */
1885                     vu = s->all_fragments[u].coeffs[0];
1886                     vur = s->all_fragments[ur].coeffs[0];
1887
1888                     /* figure out which fragments are valid */
1889                     fur = FRAME_CODED(ur) && COMPATIBLE_FRAME(ur);
1890                     fu = FRAME_CODED(u) && COMPATIBLE_FRAME(u);
1891
1892                     /* decide which predictor transform to use */
1893                     transform = (fu*PU) | (fur*PUR);
1894
1895                     break;
1896
1897                 case 2:
1898                 case 6:
1899                     /* top row of fragments, not including top-left frag;
1900                      * only consider the left fragment for prediction */
1901
1902                     /* calculate the indices of the predicting fragments */
1903                     l = i - 1;
1904
1905                     /* fetch the DC values for the predicting fragments */
1906                     vl = s->all_fragments[l].coeffs[0];
1907
1908                     /* figure out which fragments are valid */
1909                     fl = FRAME_CODED(l) && COMPATIBLE_FRAME(l);
1910
1911                     /* decide which predictor transform to use */
1912                     transform = (fl*PL);
1913
1914                     break;
1915
1916                 case 3:
1917                     /* top-left fragment */
1918
1919                     /* nothing to predict from in this case */
1920                     transform = 0;
1921
1922                     break;
1923
1924                 case 4:
1925                     /* right column of fragments, not including top corner;
1926                      * consider up-left, up, and left fragments for
1927                      * prediction */
1928
1929                     /* calculate the indices of the predicting fragments */
1930                     ul = i - fragment_width - 1;
1931                     u = i - fragment_width;
1932                     l = i - 1;
1933
1934                     /* fetch the DC values for the predicting fragments */
1935                     vul = s->all_fragments[ul].coeffs[0];
1936                     vu = s->all_fragments[u].coeffs[0];
1937                     vl = s->all_fragments[l].coeffs[0];
1938
1939                     /* figure out which fragments are valid */
1940                     ful = FRAME_CODED(ul) && COMPATIBLE_FRAME(ul);
1941                     fu = FRAME_CODED(u) && COMPATIBLE_FRAME(u);
1942                     fl = FRAME_CODED(l) && COMPATIBLE_FRAME(l);
1943
1944                     /* decide which predictor transform to use */
1945                     transform = (fl*PL) | (fu*PU) | (ful*PUL);
1946
1947                     break;
1948
1949                 }
1950
1951                 debug_dc_pred("transform = %d, ", transform);
1952
1953                 if (transform == 0) {
1954
1955                     /* if there were no fragments to predict from, use last
1956                      * DC saved */
1957                     s->all_fragments[i].coeffs[0] += last_dc[current_frame_type];
1958                     debug_dc_pred("from last DC (%d) = %d\n", 
1959                         current_frame_type, s->all_fragments[i].coeffs[0]);
1960
1961                 } else {
1962
1963                     /* apply the appropriate predictor transform */
1964                     predicted_dc =
1965                         (predictor_transform[transform][0] * vul) +
1966                         (predictor_transform[transform][1] * vu) +
1967                         (predictor_transform[transform][2] * vur) +
1968                         (predictor_transform[transform][3] * vl);
1969
1970                     /* if there is a shift value in the transform, add
1971                      * the sign bit before the shift */
1972                     if (predictor_transform[transform][5] != 0) {
1973                         predicted_dc += ((predicted_dc >> 15) & 
1974                             predictor_transform[transform][4]);
1975                         predicted_dc >>= predictor_transform[transform][5];
1976                     }
1977
1978                     /* check for outranging on the [ul u l] and
1979                      * [ul u ur l] predictors */
1980                     if ((transform == 13) || (transform == 15)) {
1981                         if (iabs(predicted_dc - vu) > 128)
1982                             predicted_dc = vu;
1983                         else if (iabs(predicted_dc - vl) > 128)
1984                             predicted_dc = vl;
1985                         else if (iabs(predicted_dc - vul) > 128)
1986                             predicted_dc = vul;
1987                     }
1988
1989                     /* at long last, apply the predictor */
1990                     s->all_fragments[i].coeffs[0] += predicted_dc;
1991                     debug_dc_pred("from pred DC = %d\n", 
1992                     s->all_fragments[i].coeffs[0]);
1993                 }
1994
1995                 /* save the DC */
1996                 last_dc[current_frame_type] = s->all_fragments[i].coeffs[0];
1997             }
1998         }
1999     }
2000 }
2001
2002 /*
2003  * This function performs the final rendering of each fragment's data
2004  * onto the output frame.
2005  */
2006 static void render_fragments(Vp3DecodeContext *s,
2007                              int first_fragment,
2008                              int width,
2009                              int height,
2010                              int plane /* 0 = Y, 1 = U, 2 = V */) 
2011 {
2012     int x, y;
2013     int m, n;
2014     int i = first_fragment;
2015     int j;
2016     int16_t *dequantizer;
2017     DCTELEM dequant_block[64];
2018     unsigned char *output_plane;
2019     unsigned char *last_plane;
2020     unsigned char *golden_plane;
2021     int stride;
2022     int motion_x, motion_y;
2023     int motion_x_limit, motion_y_limit;
2024     int motion_halfpel_index;
2025     unsigned char *motion_source;
2026
2027     debug_vp3("  vp3: rendering final fragments for %s\n",
2028         (plane == 0) ? "Y plane" : (plane == 1) ? "U plane" : "V plane");
2029
2030     /* set up plane-specific parameters */
2031     if (plane == 0) {
2032         dequantizer = s->intra_y_dequant;
2033         output_plane = s->current_frame.data[0];
2034         last_plane = s->last_frame.data[0];
2035         golden_plane = s->golden_frame.data[0];
2036         stride = -s->current_frame.linesize[0];
2037     } else if (plane == 1) {
2038         dequantizer = s->intra_c_dequant;
2039         output_plane = s->current_frame.data[1];
2040         last_plane = s->last_frame.data[1];
2041         golden_plane = s->golden_frame.data[1];
2042         stride = -s->current_frame.linesize[1];
2043     } else {
2044         dequantizer = s->intra_c_dequant;
2045         output_plane = s->current_frame.data[2];
2046         last_plane = s->last_frame.data[2];
2047         golden_plane = s->golden_frame.data[2];
2048         stride = -s->current_frame.linesize[2];
2049     }
2050
2051     motion_x_limit = width - 8;
2052     motion_y_limit = height - 8;
2053
2054     /* for each fragment row... */
2055     for (y = 0; y < height; y += 8) {
2056
2057         /* for each fragment in a row... */
2058         for (x = 0; x < width; x += 8, i++) {
2059
2060             /* transform if this block was coded */
2061             if (s->all_fragments[i].coding_method != MODE_COPY) {
2062 //            if (s->all_fragments[i].coding_method == MODE_INTRA) {
2063
2064                 /* sort out the motion vector */
2065                 motion_x = x + s->all_fragments[i].motion_x;
2066                 motion_y = y + s->all_fragments[i].motion_y;
2067                 motion_halfpel_index = s->all_fragments[i].motion_halfpel_index;
2068
2069                 if (motion_x < 0)
2070                     motion_x = 0;
2071                 if (motion_y < 0)
2072                     motion_y = 0;
2073                 if (motion_x > motion_x_limit)
2074                     motion_x = motion_x_limit;
2075                 if (motion_y > motion_y_limit)
2076                     motion_y = motion_y_limit;
2077
2078                 /* first, take care of copying a block from either the
2079                  * previous or the golden frame */
2080                 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2081                     (s->all_fragments[i].coding_method == MODE_GOLDEN_MV)) {
2082
2083                     motion_source = golden_plane;
2084                     motion_source += motion_x;
2085                     motion_source += (motion_y * -stride);
2086
2087                     s->dsp.put_pixels_tab[1][motion_halfpel_index](
2088                         output_plane + s->all_fragments[i].first_pixel,
2089                         motion_source,
2090                         stride, 8);
2091
2092                 } else 
2093                 if (s->all_fragments[i].coding_method != MODE_INTRA) {
2094
2095                     motion_source = last_plane;
2096                     motion_source += motion_x;
2097                     motion_source += (motion_y * -stride);
2098
2099                     s->dsp.put_pixels_tab[1][motion_halfpel_index](
2100                         output_plane + s->all_fragments[i].first_pixel,
2101                         motion_source,
2102                         stride, 8);
2103                 }
2104
2105                 /* dequantize the DCT coefficients */
2106                 debug_idct("fragment %d, coding mode %d, DC = %d, dequant = %d:\n", 
2107                     i, s->all_fragments[i].coding_method, 
2108                     s->all_fragments[i].coeffs[0], dequantizer[0]);
2109                 for (j = 0; j < 64; j++)
2110                     dequant_block[dequant_index[j]] =
2111                         s->all_fragments[i].coeffs[j] *
2112                         dequantizer[j];
2113                 dequant_block[0] += 1024;
2114
2115                 debug_idct("dequantized block:\n");
2116                 for (m = 0; m < 8; m++) {
2117                     for (n = 0; n < 8; n++) {
2118                         debug_idct(" %5d", dequant_block[m * 8 + n]);
2119                     }
2120                     debug_idct("\n");
2121                 }
2122                 debug_idct("\n");
2123
2124                 /* invert DCT and place in final output */
2125
2126                 if (s->all_fragments[i].coding_method == MODE_INTRA)
2127                     s->dsp.idct_put(
2128                         output_plane + s->all_fragments[i].first_pixel,
2129                         stride, dequant_block);
2130                 else
2131 //                    s->dsp.idct_add(
2132                     s->dsp.idct_put(
2133                         output_plane + s->all_fragments[i].first_pixel,
2134                         stride, dequant_block);
2135
2136                 debug_idct("block after idct_%s():\n",
2137                     (s->all_fragments[i].coding_method == MODE_INTRA)?
2138                     "put" : "add");
2139                 for (m = 0; m < 8; m++) {
2140                     for (n = 0; n < 8; n++) {
2141                         debug_idct(" %3d", *(output_plane + 
2142                             s->all_fragments[i].first_pixel + (m * stride + n)));
2143                     }
2144                     debug_idct("\n");
2145                 }
2146                 debug_idct("\n");
2147
2148             } else {
2149
2150                 /* copy directly from the previous frame */
2151                 s->dsp.put_pixels_tab[1][0](
2152                     output_plane + s->all_fragments[i].first_pixel,
2153                     last_plane + s->all_fragments[i].first_pixel,
2154                     stride, 8);
2155
2156             }
2157         }
2158     }
2159
2160     emms_c();
2161
2162 }
2163
2164 /* 
2165  * This function computes the first pixel addresses for each fragment.
2166  * This function needs to be invoked after the first frame is allocated
2167  * so that it has access to the plane strides.
2168  */
2169 static void vp3_calculate_pixel_addresses(Vp3DecodeContext *s) 
2170 {
2171
2172     int i, x, y;
2173
2174     /* figure out the first pixel addresses for each of the fragments */
2175     /* Y plane */
2176     i = 0;
2177     for (y = s->fragment_height; y > 0; y--) {
2178         for (x = 0; x < s->fragment_width; x++) {
2179             s->all_fragments[i++].first_pixel = 
2180                 s->golden_frame.linesize[0] * y * FRAGMENT_PIXELS -
2181                     s->golden_frame.linesize[0] +
2182                     x * FRAGMENT_PIXELS;
2183             debug_init("  fragment %d, first pixel @ %d\n", 
2184                 i-1, s->all_fragments[i-1].first_pixel);
2185         }
2186     }
2187
2188     /* U plane */
2189     i = s->u_fragment_start;
2190     for (y = s->fragment_height / 2; y > 0; y--) {
2191         for (x = 0; x < s->fragment_width / 2; x++) {
2192             s->all_fragments[i++].first_pixel = 
2193                 s->golden_frame.linesize[1] * y * FRAGMENT_PIXELS -
2194                     s->golden_frame.linesize[1] +
2195                     x * FRAGMENT_PIXELS;
2196             debug_init("  fragment %d, first pixel @ %d\n", 
2197                 i-1, s->all_fragments[i-1].first_pixel);
2198         }
2199     }
2200
2201     /* V plane */
2202     i = s->v_fragment_start;
2203     for (y = s->fragment_height / 2; y > 0; y--) {
2204         for (x = 0; x < s->fragment_width / 2; x++) {
2205             s->all_fragments[i++].first_pixel = 
2206                 s->golden_frame.linesize[2] * y * FRAGMENT_PIXELS -
2207                     s->golden_frame.linesize[2] +
2208                     x * FRAGMENT_PIXELS;
2209             debug_init("  fragment %d, first pixel @ %d\n", 
2210                 i-1, s->all_fragments[i-1].first_pixel);
2211         }
2212     }
2213 }
2214
2215 /*
2216  * This is the ffmpeg/libavcodec API init function.
2217  */
2218 static int vp3_decode_init(AVCodecContext *avctx)
2219 {
2220     Vp3DecodeContext *s = avctx->priv_data;
2221     int i;
2222
2223     s->avctx = avctx;
2224     s->width = avctx->width;
2225     s->height = avctx->height;
2226     avctx->pix_fmt = PIX_FMT_YUV420P;
2227     avctx->has_b_frames = 0;
2228     dsputil_init(&s->dsp, avctx);
2229
2230     /* initialize to an impossible value which will force a recalculation
2231      * in the first frame decode */
2232     s->quality_index = -1;
2233
2234     s->superblock_width = (s->width + 31) / 32;
2235     s->superblock_height = (s->height + 31) / 32;
2236     s->superblock_count = s->superblock_width * s->superblock_height * 3 / 2;
2237     s->u_superblock_start = s->superblock_width * s->superblock_height;
2238     s->v_superblock_start = s->superblock_width * s->superblock_height * 5 / 4;
2239     s->superblock_coding = av_malloc(s->superblock_count);
2240
2241     s->macroblock_width = (s->width + 15) / 16;
2242     s->macroblock_height = (s->height + 15) / 16;
2243     s->macroblock_count = s->macroblock_width * s->macroblock_height;
2244
2245     s->fragment_width = s->width / FRAGMENT_PIXELS;
2246     s->fragment_height = s->height / FRAGMENT_PIXELS;
2247
2248     /* fragment count covers all 8x8 blocks for all 3 planes */
2249     s->fragment_count = s->fragment_width * s->fragment_height * 3 / 2;
2250     s->u_fragment_start = s->fragment_width * s->fragment_height;
2251     s->v_fragment_start = s->fragment_width * s->fragment_height * 5 / 4;
2252
2253     debug_init("  width: %d x %d\n", s->width, s->height);
2254     debug_init("  superblocks: %d x %d, %d total\n",
2255         s->superblock_width, s->superblock_height, s->superblock_count);
2256     debug_init("  macroblocks: %d x %d, %d total\n",
2257         s->macroblock_width, s->macroblock_height, s->macroblock_count);
2258     debug_init("  %d fragments, %d x %d, u starts @ %d, v starts @ %d\n",
2259         s->fragment_count,
2260         s->fragment_width,
2261         s->fragment_height,
2262         s->u_fragment_start,
2263         s->v_fragment_start);
2264
2265     s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
2266     s->coded_fragment_list = av_malloc(s->fragment_count * sizeof(int));
2267     s->pixel_addresses_inited = 0;
2268
2269     /* init VLC tables */
2270     for (i = 0; i < 16; i++) {
2271
2272         /* Dc histograms */
2273         init_vlc(&s->dc_vlc[i], 5, 32,
2274             &dc_bias[i][0][1], 4, 2,
2275             &dc_bias[i][0][0], 4, 2);
2276
2277         /* level 1 AC histograms */
2278         init_vlc(&s->ac_vlc_1[i], 5, 32,
2279             &ac_bias_0[i][0][1], 4, 2,
2280             &ac_bias_0[i][0][0], 4, 2);
2281
2282         /* level 2 AC histograms */
2283         init_vlc(&s->ac_vlc_2[i], 5, 32,
2284             &ac_bias_1[i][0][1], 4, 2,
2285             &ac_bias_1[i][0][0], 4, 2);
2286
2287         /* level 3 AC histograms */
2288         init_vlc(&s->ac_vlc_3[i], 5, 32,
2289             &ac_bias_2[i][0][1], 4, 2,
2290             &ac_bias_2[i][0][0], 4, 2);
2291
2292         /* level 4 AC histograms */
2293         init_vlc(&s->ac_vlc_4[i], 5, 32,
2294             &ac_bias_3[i][0][1], 4, 2,
2295             &ac_bias_3[i][0][0], 4, 2);
2296     }
2297
2298     /* build quantization table */
2299     for (i = 0; i < 64; i++)
2300         quant_index[dequant_index[i]] = i;
2301
2302     /* work out the block mapping tables */
2303     s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
2304     s->superblock_macroblocks = av_malloc(s->superblock_count * 4 * sizeof(int));
2305     s->macroblock_fragments = av_malloc(s->macroblock_count * 6 * sizeof(int));
2306     s->macroblock_coded = av_malloc(s->macroblock_count + 1);
2307     init_block_mapping(s);
2308
2309     for (i = 0; i < 3; i++) {
2310         s->current_frame.data[i] = NULL;
2311         s->last_frame.data[i] = NULL;
2312         s->golden_frame.data[i] = NULL;
2313     }
2314
2315     return 0;
2316 }
2317
2318 /*
2319  * This is the ffmpeg/libavcodec API frame decode function.
2320  */
2321 static int vp3_decode_frame(AVCodecContext *avctx, 
2322                             void *data, int *data_size,
2323                             uint8_t *buf, int buf_size)
2324 {
2325     Vp3DecodeContext *s = avctx->priv_data;
2326     GetBitContext gb;
2327     static int counter = 0;
2328
2329     *data_size = 0;
2330
2331     init_get_bits(&gb, buf, buf_size * 8);
2332
2333     s->keyframe = get_bits(&gb, 1);
2334     s->keyframe ^= 1;
2335     skip_bits(&gb, 1);
2336     s->last_quality_index = s->quality_index;
2337     s->quality_index = get_bits(&gb, 6);
2338     if (s->quality_index != s->last_quality_index)
2339         init_dequantizer(s);
2340
2341     debug_vp3(" VP3 frame #%d: Q index = %d", counter, s->quality_index);
2342     counter++;
2343
2344     if (s->keyframe) {
2345         /* release the previous golden frame and get a new one */
2346         if (s->golden_frame.data[0])
2347             avctx->release_buffer(avctx, &s->golden_frame);
2348
2349         /* last frame, if allocated, is hereby invalidated */
2350         if (s->last_frame.data[0])
2351             avctx->release_buffer(avctx, &s->last_frame);
2352
2353         s->golden_frame.reference = 0;
2354         if(avctx->get_buffer(avctx, &s->golden_frame) < 0) {
2355             printf("vp3: get_buffer() failed\n");
2356             return -1;
2357         }
2358
2359         /* golden frame is also the current frame */
2360         memcpy(&s->current_frame, &s->golden_frame, sizeof(AVFrame));
2361
2362         /* time to figure out pixel addresses? */
2363         if (!s->pixel_addresses_inited)
2364             vp3_calculate_pixel_addresses(s);
2365
2366     } else {
2367
2368         /* allocate a new current frame */
2369         s->current_frame.reference = 0;
2370         if(avctx->get_buffer(avctx, &s->current_frame) < 0) {
2371             printf("vp3: get_buffer() failed\n");
2372             return -1;
2373         }
2374
2375     }
2376
2377     if (s->keyframe) {
2378       debug_vp3(", keyframe\n");
2379       /* skip the other 2 header bytes for now */
2380       skip_bits(&gb, 16);
2381     } else
2382       debug_vp3("\n");
2383
2384     init_frame(s, &gb);
2385
2386     unpack_superblocks(s, &gb);
2387     unpack_modes(s, &gb);
2388     unpack_vectors(s, &gb);
2389     unpack_dct_coeffs(s, &gb);
2390
2391     reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);
2392     reverse_dc_prediction(s, s->u_fragment_start,
2393         s->fragment_width / 2, s->fragment_height / 2);
2394     reverse_dc_prediction(s, s->v_fragment_start,
2395         s->fragment_width / 2, s->fragment_height / 2);
2396
2397     render_fragments(s, 0, s->width, s->height, 0);
2398     render_fragments(s, s->u_fragment_start, s->width / 2, s->height / 2, 1);
2399     render_fragments(s, s->v_fragment_start, s->width / 2, s->height / 2, 2);
2400
2401     *data_size=sizeof(AVFrame);
2402     *(AVFrame*)data= s->current_frame;
2403
2404     /* release the last frame, if it is allocated and if it is not the
2405      * golden frame */
2406     if ((s->last_frame.data[0]) &&
2407         (s->last_frame.data[0] != s->golden_frame.data[0]))
2408         avctx->release_buffer(avctx, &s->last_frame);
2409
2410     /* shuffle frames (last = current) */
2411     memcpy(&s->last_frame, &s->current_frame, sizeof(AVFrame));
2412
2413     return buf_size;
2414 }
2415
2416 /*
2417  * This is the ffmpeg/libavcodec API module cleanup function.
2418  */
2419 static int vp3_decode_end(AVCodecContext *avctx)
2420 {
2421     Vp3DecodeContext *s = avctx->priv_data;
2422
2423     av_free(s->all_fragments);
2424     av_free(s->coded_fragment_list);
2425     av_free(s->superblock_fragments);
2426     av_free(s->superblock_macroblocks);
2427     av_free(s->macroblock_fragments);
2428     av_free(s->macroblock_coded);
2429
2430     /* release all frames */
2431     avctx->release_buffer(avctx, &s->golden_frame);
2432     avctx->release_buffer(avctx, &s->last_frame);
2433     avctx->release_buffer(avctx, &s->current_frame);
2434
2435     return 0;
2436 }
2437
2438 AVCodec vp3_decoder = {
2439     "vp3",
2440     CODEC_TYPE_VIDEO,
2441     CODEC_ID_VP3,
2442     sizeof(Vp3DecodeContext),
2443     vp3_decode_init,
2444     NULL,
2445     vp3_decode_end,
2446     vp3_decode_frame,
2447     0,
2448     NULL
2449 };