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