]> git.sesse.net Git - ffmpeg/blob - libavcodec/vp3.c
When bswap_32 is a macro, png images fail to decode properly, patch by (Milan Cutka...
[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     /* for each fragment row... */
2098     for (y = 0; y < height; y += 8) {
2099
2100         /* for each fragment in a row... */
2101         for (x = 0; x < width; x += 8, i++) {
2102
2103             if ((i < 0) || (i >= s->fragment_count)) {
2104                 av_log(s->avctx, AV_LOG_ERROR, "  vp3:render_fragments(): bad fragment number (%d)\n", i);
2105                 return;
2106             }
2107
2108             /* transform if this block was coded */
2109             if ((s->all_fragments[i].coding_method != MODE_COPY) &&
2110                 !((s->avctx->flags & CODEC_FLAG_GRAY) && plane)) {
2111
2112                 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2113                     (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
2114                     motion_source= golden_plane;
2115                 else 
2116                     motion_source= last_plane;
2117
2118                 motion_source += s->all_fragments[i].first_pixel;
2119                 motion_halfpel_index = 0;
2120
2121                 /* sort out the motion vector if this fragment is coded
2122                  * using a motion vector method */
2123                 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
2124                     (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
2125                     int src_x, src_y;
2126                     motion_x = s->all_fragments[i].motion_x;
2127                     motion_y = s->all_fragments[i].motion_y;
2128                     if(plane){
2129                         motion_x= (motion_x>>1) | (motion_x&1);
2130                         motion_y= (motion_y>>1) | (motion_y&1);
2131                     }
2132
2133                     src_x= (motion_x>>1) + x;
2134                     src_y= (motion_y>>1) + y;
2135 if ((motion_x == 0xbeef) || (motion_y == 0xbeef))
2136 av_log(s->avctx, AV_LOG_ERROR, " help! got beefy vector! (%X, %X)\n", motion_x, motion_y);
2137
2138                     motion_halfpel_index = motion_x & 0x01;
2139                     motion_source += (motion_x >> 1);
2140
2141 //                    motion_y = -motion_y;
2142                     motion_halfpel_index |= (motion_y & 0x01) << 1;
2143                     motion_source += ((motion_y >> 1) * stride);
2144
2145                     if(src_x<0 || src_y<0 || src_x + 9 >= width || src_y + 9 >= height){
2146                         uint8_t *temp= s->edge_emu_buffer;
2147                         if(stride<0) temp -= 9*stride;
2148                         else temp += 9*stride;
2149
2150                         ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, width, height);
2151                         motion_source= temp;
2152                     }
2153                 }
2154                 
2155
2156                 /* first, take care of copying a block from either the
2157                  * previous or the golden frame */
2158                 if (s->all_fragments[i].coding_method != MODE_INTRA) {
2159                     //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
2160                     if(motion_halfpel_index != 3){
2161                         s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
2162                             output_plane + s->all_fragments[i].first_pixel,
2163                             motion_source, stride, 8);
2164                     }else{
2165                         int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
2166                         s->dsp.put_no_rnd_pixels_l2[1](
2167                             output_plane + s->all_fragments[i].first_pixel,
2168                             motion_source - d, 
2169                             motion_source + stride + 1 + d, 
2170                             stride, 8);
2171                     }
2172                 }
2173
2174                 /* dequantize the DCT coefficients */
2175                 debug_idct("fragment %d, coding mode %d, DC = %d, dequant = %d:\n", 
2176                     i, s->all_fragments[i].coding_method, 
2177                     s->all_fragments[i].coeffs[0], dequantizer[0]);
2178
2179                 /* invert DCT and place (or add) in final output */
2180                 s->dsp.vp3_idct(s->all_fragments[i].coeffs,
2181                     dequantizer,
2182                     s->all_fragments[i].coeff_count,
2183                     output_samples);
2184                 if (s->all_fragments[i].coding_method == MODE_INTRA) {
2185                     s->dsp.put_signed_pixels_clamped(output_samples,
2186                         output_plane + s->all_fragments[i].first_pixel,
2187                         stride);
2188                 } else {
2189                     s->dsp.add_pixels_clamped(output_samples,
2190                         output_plane + s->all_fragments[i].first_pixel,
2191                         stride);
2192                 }
2193
2194                 debug_idct("block after idct_%s():\n",
2195                     (s->all_fragments[i].coding_method == MODE_INTRA)?
2196                     "put" : "add");
2197                 for (m = 0; m < 8; m++) {
2198                     for (n = 0; n < 8; n++) {
2199                         debug_idct(" %3d", *(output_plane + 
2200                             s->all_fragments[i].first_pixel + (m * stride + n)));
2201                     }
2202                     debug_idct("\n");
2203                 }
2204                 debug_idct("\n");
2205
2206             } else {
2207
2208                 /* copy directly from the previous frame */
2209                 s->dsp.put_pixels_tab[1][0](
2210                     output_plane + s->all_fragments[i].first_pixel,
2211                     last_plane + s->all_fragments[i].first_pixel,
2212                     stride, 8);
2213
2214             }
2215         }
2216     }
2217
2218     emms_c();
2219
2220 }
2221
2222 /* 
2223  * This function computes the first pixel addresses for each fragment.
2224  * This function needs to be invoked after the first frame is allocated
2225  * so that it has access to the plane strides.
2226  */
2227 static void vp3_calculate_pixel_addresses(Vp3DecodeContext *s) 
2228 {
2229
2230     int i, x, y;
2231
2232     /* figure out the first pixel addresses for each of the fragments */
2233     /* Y plane */
2234     i = 0;
2235     for (y = s->fragment_height; y > 0; y--) {
2236         for (x = 0; x < s->fragment_width; x++) {
2237             s->all_fragments[i++].first_pixel = 
2238                 s->golden_frame.linesize[0] * y * FRAGMENT_PIXELS -
2239                     s->golden_frame.linesize[0] +
2240                     x * FRAGMENT_PIXELS;
2241             debug_init("  fragment %d, first pixel @ %d\n", 
2242                 i-1, s->all_fragments[i-1].first_pixel);
2243         }
2244     }
2245
2246     /* U plane */
2247     i = s->u_fragment_start;
2248     for (y = s->fragment_height / 2; y > 0; y--) {
2249         for (x = 0; x < s->fragment_width / 2; x++) {
2250             s->all_fragments[i++].first_pixel = 
2251                 s->golden_frame.linesize[1] * y * FRAGMENT_PIXELS -
2252                     s->golden_frame.linesize[1] +
2253                     x * FRAGMENT_PIXELS;
2254             debug_init("  fragment %d, first pixel @ %d\n", 
2255                 i-1, s->all_fragments[i-1].first_pixel);
2256         }
2257     }
2258
2259     /* V plane */
2260     i = s->v_fragment_start;
2261     for (y = s->fragment_height / 2; y > 0; y--) {
2262         for (x = 0; x < s->fragment_width / 2; x++) {
2263             s->all_fragments[i++].first_pixel = 
2264                 s->golden_frame.linesize[2] * y * FRAGMENT_PIXELS -
2265                     s->golden_frame.linesize[2] +
2266                     x * FRAGMENT_PIXELS;
2267             debug_init("  fragment %d, first pixel @ %d\n", 
2268                 i-1, s->all_fragments[i-1].first_pixel);
2269         }
2270     }
2271 }
2272
2273 /* FIXME: this should be merged with the above! */
2274 static void theora_calculate_pixel_addresses(Vp3DecodeContext *s) 
2275 {
2276
2277     int i, x, y;
2278
2279     /* figure out the first pixel addresses for each of the fragments */
2280     /* Y plane */
2281     i = 0;
2282     for (y = 1; y <= s->fragment_height; y++) {
2283         for (x = 0; x < s->fragment_width; x++) {
2284             s->all_fragments[i++].first_pixel = 
2285                 s->golden_frame.linesize[0] * y * FRAGMENT_PIXELS -
2286                     s->golden_frame.linesize[0] +
2287                     x * FRAGMENT_PIXELS;
2288             debug_init("  fragment %d, first pixel @ %d\n", 
2289                 i-1, s->all_fragments[i-1].first_pixel);
2290         }
2291     }
2292
2293     /* U plane */
2294     i = s->u_fragment_start;
2295     for (y = 1; y <= s->fragment_height / 2; y++) {
2296         for (x = 0; x < s->fragment_width / 2; x++) {
2297             s->all_fragments[i++].first_pixel = 
2298                 s->golden_frame.linesize[1] * y * FRAGMENT_PIXELS -
2299                     s->golden_frame.linesize[1] +
2300                     x * FRAGMENT_PIXELS;
2301             debug_init("  fragment %d, first pixel @ %d\n", 
2302                 i-1, s->all_fragments[i-1].first_pixel);
2303         }
2304     }
2305
2306     /* V plane */
2307     i = s->v_fragment_start;
2308     for (y = 1; y <= s->fragment_height / 2; y++) {
2309         for (x = 0; x < s->fragment_width / 2; x++) {
2310             s->all_fragments[i++].first_pixel = 
2311                 s->golden_frame.linesize[2] * y * FRAGMENT_PIXELS -
2312                     s->golden_frame.linesize[2] +
2313                     x * FRAGMENT_PIXELS;
2314             debug_init("  fragment %d, first pixel @ %d\n", 
2315                 i-1, s->all_fragments[i-1].first_pixel);
2316         }
2317     }
2318 }
2319
2320 /*
2321  * This is the ffmpeg/libavcodec API init function.
2322  */
2323 static int vp3_decode_init(AVCodecContext *avctx)
2324 {
2325     Vp3DecodeContext *s = avctx->priv_data;
2326     int i;
2327     int c_width;
2328     int c_height;
2329     int y_superblock_count;
2330     int c_superblock_count;
2331
2332     if (avctx->codec_tag == MKTAG('V','P','3','0'))
2333         s->version = 0;
2334     else
2335         s->version = 1;
2336
2337     s->avctx = avctx;
2338 #if 0
2339     s->width = avctx->width;
2340     s->height = avctx->height;
2341 #else
2342     s->width = (avctx->width + 15) & 0xFFFFFFF0;
2343     s->height = (avctx->height + 15) & 0xFFFFFFF0;
2344 #endif
2345     avctx->pix_fmt = PIX_FMT_YUV420P;
2346     avctx->has_b_frames = 0;
2347     dsputil_init(&s->dsp, avctx);
2348     s->dsp.vp3_dsp_init();
2349
2350     /* initialize to an impossible value which will force a recalculation
2351      * in the first frame decode */
2352     s->quality_index = -1;
2353
2354     s->y_superblock_width = (s->width + 31) / 32;
2355     s->y_superblock_height = (s->height + 31) / 32;
2356     y_superblock_count = s->y_superblock_width * s->y_superblock_height;
2357
2358     /* work out the dimensions for the C planes */
2359     c_width = s->width / 2;
2360     c_height = s->height / 2;
2361     s->c_superblock_width = (c_width + 31) / 32;
2362     s->c_superblock_height = (c_height + 31) / 32;
2363     c_superblock_count = s->c_superblock_width * s->c_superblock_height;
2364
2365     s->superblock_count = y_superblock_count + (c_superblock_count * 2);
2366     s->u_superblock_start = y_superblock_count;
2367     s->v_superblock_start = s->u_superblock_start + c_superblock_count;
2368     s->superblock_coding = av_malloc(s->superblock_count);
2369
2370     s->macroblock_width = (s->width + 15) / 16;
2371     s->macroblock_height = (s->height + 15) / 16;
2372     s->macroblock_count = s->macroblock_width * s->macroblock_height;
2373
2374     s->fragment_width = s->width / FRAGMENT_PIXELS;
2375     s->fragment_height = s->height / FRAGMENT_PIXELS;
2376
2377     /* fragment count covers all 8x8 blocks for all 3 planes */
2378     s->fragment_count = s->fragment_width * s->fragment_height * 3 / 2;
2379     s->u_fragment_start = s->fragment_width * s->fragment_height;
2380     s->v_fragment_start = s->fragment_width * s->fragment_height * 5 / 4;
2381
2382     debug_init("  Y plane: %d x %d\n", s->width, s->height);
2383     debug_init("  C plane: %d x %d\n", c_width, c_height);
2384     debug_init("  Y superblocks: %d x %d, %d total\n",
2385         s->y_superblock_width, s->y_superblock_height, y_superblock_count);
2386     debug_init("  C superblocks: %d x %d, %d total\n",
2387         s->c_superblock_width, s->c_superblock_height, c_superblock_count);
2388     debug_init("  total superblocks = %d, U starts @ %d, V starts @ %d\n", 
2389         s->superblock_count, s->u_superblock_start, s->v_superblock_start);
2390     debug_init("  macroblocks: %d x %d, %d total\n",
2391         s->macroblock_width, s->macroblock_height, s->macroblock_count);
2392     debug_init("  %d fragments, %d x %d, u starts @ %d, v starts @ %d\n",
2393         s->fragment_count,
2394         s->fragment_width,
2395         s->fragment_height,
2396         s->u_fragment_start,
2397         s->v_fragment_start);
2398
2399     s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
2400     s->coded_fragment_list = av_malloc(s->fragment_count * sizeof(int));
2401     s->pixel_addresses_inited = 0;
2402
2403     if (!s->theora_tables)
2404     {
2405         for (i = 0; i < 64; i++)
2406             s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
2407         for (i = 0; i < 64; i++)
2408             s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
2409         for (i = 0; i < 64; i++)
2410             s->coded_intra_y_dequant[i] = vp31_intra_y_dequant[i];
2411         for (i = 0; i < 64; i++)
2412             s->coded_intra_c_dequant[i] = vp31_intra_c_dequant[i];
2413         for (i = 0; i < 64; i++)
2414             s->coded_inter_dequant[i] = vp31_inter_dequant[i];
2415     }
2416
2417     /* init VLC tables */
2418     for (i = 0; i < 16; i++) {
2419
2420         /* DC histograms */
2421         init_vlc(&s->dc_vlc[i], 5, 32,
2422             &dc_bias[i][0][1], 4, 2,
2423             &dc_bias[i][0][0], 4, 2);
2424
2425         /* group 1 AC histograms */
2426         init_vlc(&s->ac_vlc_1[i], 5, 32,
2427             &ac_bias_0[i][0][1], 4, 2,
2428             &ac_bias_0[i][0][0], 4, 2);
2429
2430         /* group 2 AC histograms */
2431         init_vlc(&s->ac_vlc_2[i], 5, 32,
2432             &ac_bias_1[i][0][1], 4, 2,
2433             &ac_bias_1[i][0][0], 4, 2);
2434
2435         /* group 3 AC histograms */
2436         init_vlc(&s->ac_vlc_3[i], 5, 32,
2437             &ac_bias_2[i][0][1], 4, 2,
2438             &ac_bias_2[i][0][0], 4, 2);
2439
2440         /* group 4 AC histograms */
2441         init_vlc(&s->ac_vlc_4[i], 5, 32,
2442             &ac_bias_3[i][0][1], 4, 2,
2443             &ac_bias_3[i][0][0], 4, 2);
2444     }
2445
2446     /* build quantization zigzag table */
2447     for (i = 0; i < 64; i++)
2448         zigzag_index[dezigzag_index[i]] = i;
2449
2450     /* work out the block mapping tables */
2451     s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
2452     s->superblock_macroblocks = av_malloc(s->superblock_count * 4 * sizeof(int));
2453     s->macroblock_fragments = av_malloc(s->macroblock_count * 6 * sizeof(int));
2454     s->macroblock_coding = av_malloc(s->macroblock_count + 1);
2455     init_block_mapping(s);
2456
2457     for (i = 0; i < 3; i++) {
2458         s->current_frame.data[i] = NULL;
2459         s->last_frame.data[i] = NULL;
2460         s->golden_frame.data[i] = NULL;
2461     }
2462
2463     return 0;
2464 }
2465
2466 /*
2467  * This is the ffmpeg/libavcodec API frame decode function.
2468  */
2469 static int vp3_decode_frame(AVCodecContext *avctx, 
2470                             void *data, int *data_size,
2471                             uint8_t *buf, int buf_size)
2472 {
2473     Vp3DecodeContext *s = avctx->priv_data;
2474     GetBitContext gb;
2475     static int counter = 0;
2476
2477     init_get_bits(&gb, buf, buf_size * 8);
2478     
2479     if (s->theora && get_bits1(&gb))
2480     {
2481         int ptype = get_bits(&gb, 7);
2482
2483         skip_bits(&gb, 6*8); /* "theora" */
2484         
2485         switch(ptype)
2486         {
2487             case 1:
2488                 theora_decode_comments(avctx, gb);
2489                 break;
2490             case 2:
2491                 theora_decode_tables(avctx, gb);
2492                 init_dequantizer(s);
2493                 break;
2494             default:
2495                 av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype);
2496         }
2497         return buf_size;
2498     }
2499
2500     s->keyframe = !get_bits1(&gb);
2501     if (!s->theora)
2502         skip_bits(&gb, 1);
2503     s->last_quality_index = s->quality_index;
2504     s->quality_index = get_bits(&gb, 6);
2505     if (s->theora >= 0x030300)
2506         skip_bits1(&gb);
2507
2508     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2509         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2510             s->keyframe?"key":"", counter, s->quality_index);
2511     counter++;
2512
2513     if (s->quality_index != s->last_quality_index)
2514         init_dequantizer(s);
2515
2516     if (s->keyframe) {
2517         if (!s->theora)
2518         {
2519             skip_bits(&gb, 4); /* width code */
2520             skip_bits(&gb, 4); /* height code */
2521             if (s->version)
2522             {
2523                 s->version = get_bits(&gb, 5);
2524                 if (counter == 1)
2525                     av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
2526             }
2527         }
2528         if (s->version || s->theora)
2529         {
2530             if (get_bits1(&gb))
2531                 av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
2532             skip_bits(&gb, 2); /* reserved? */
2533         }
2534
2535         if (s->last_frame.data[0] == s->golden_frame.data[0]) {
2536             if (s->golden_frame.data[0])
2537                 avctx->release_buffer(avctx, &s->golden_frame);
2538             s->last_frame= s->golden_frame; /* ensure that we catch any access to this released frame */
2539         } else {
2540             if (s->golden_frame.data[0])
2541                 avctx->release_buffer(avctx, &s->golden_frame);
2542             if (s->last_frame.data[0])
2543                 avctx->release_buffer(avctx, &s->last_frame);
2544         }
2545
2546         s->golden_frame.reference = 3;
2547         if(avctx->get_buffer(avctx, &s->golden_frame) < 0) {
2548             av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");
2549             return -1;
2550         }
2551
2552         /* golden frame is also the current frame */
2553         memcpy(&s->current_frame, &s->golden_frame, sizeof(AVFrame));
2554
2555         /* time to figure out pixel addresses? */
2556         if (!s->pixel_addresses_inited)
2557         {
2558             if (!s->flipped_image)
2559                 vp3_calculate_pixel_addresses(s);
2560             else
2561                 theora_calculate_pixel_addresses(s);
2562         }
2563     } else {
2564         /* allocate a new current frame */
2565         s->current_frame.reference = 3;
2566         if(avctx->get_buffer(avctx, &s->current_frame) < 0) {
2567             av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");
2568             return -1;
2569         }
2570     }
2571
2572     s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
2573     s->current_frame.qstride= 0;
2574
2575     init_frame(s, &gb);
2576
2577 #if KEYFRAMES_ONLY
2578 if (!s->keyframe) {
2579
2580     memcpy(s->current_frame.data[0], s->golden_frame.data[0],
2581         s->current_frame.linesize[0] * s->height);
2582     memcpy(s->current_frame.data[1], s->golden_frame.data[1],
2583         s->current_frame.linesize[1] * s->height / 2);
2584     memcpy(s->current_frame.data[2], s->golden_frame.data[2],
2585         s->current_frame.linesize[2] * s->height / 2);
2586
2587 } else {
2588 #endif
2589
2590     if (unpack_superblocks(s, &gb) ||
2591         unpack_modes(s, &gb) ||
2592         unpack_vectors(s, &gb) ||
2593         unpack_dct_coeffs(s, &gb)) {
2594
2595         av_log(s->avctx, AV_LOG_ERROR, "  vp3: could not decode frame\n");
2596         return -1;
2597     }
2598
2599     reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);
2600     render_fragments(s, 0, s->width, s->height, 0);
2601
2602     if ((avctx->flags & CODEC_FLAG_GRAY) == 0) {
2603         reverse_dc_prediction(s, s->u_fragment_start,
2604             s->fragment_width / 2, s->fragment_height / 2);
2605         reverse_dc_prediction(s, s->v_fragment_start,
2606             s->fragment_width / 2, s->fragment_height / 2);
2607         render_fragments(s, s->u_fragment_start, s->width / 2, s->height / 2, 1);
2608         render_fragments(s, s->v_fragment_start, s->width / 2, s->height / 2, 2);
2609     } else {
2610         memset(s->current_frame.data[1], 0x80, s->width * s->height / 4);
2611         memset(s->current_frame.data[2], 0x80, s->width * s->height / 4);
2612     }
2613
2614 #if KEYFRAMES_ONLY
2615 }
2616 #endif
2617
2618     *data_size=sizeof(AVFrame);
2619     *(AVFrame*)data= s->current_frame;
2620
2621     /* release the last frame, if it is allocated and if it is not the
2622      * golden frame */
2623     if ((s->last_frame.data[0]) &&
2624         (s->last_frame.data[0] != s->golden_frame.data[0]))
2625         avctx->release_buffer(avctx, &s->last_frame);
2626
2627     /* shuffle frames (last = current) */
2628     memcpy(&s->last_frame, &s->current_frame, sizeof(AVFrame));
2629     s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
2630
2631     return buf_size;
2632 }
2633
2634 /*
2635  * This is the ffmpeg/libavcodec API module cleanup function.
2636  */
2637 static int vp3_decode_end(AVCodecContext *avctx)
2638 {
2639     Vp3DecodeContext *s = avctx->priv_data;
2640
2641     av_free(s->all_fragments);
2642     av_free(s->coded_fragment_list);
2643     av_free(s->superblock_fragments);
2644     av_free(s->superblock_macroblocks);
2645     av_free(s->macroblock_fragments);
2646     av_free(s->macroblock_coding);
2647     
2648     /* release all frames */
2649     if (s->golden_frame.data[0] && s->golden_frame.data[0] != s->last_frame.data[0])
2650         avctx->release_buffer(avctx, &s->golden_frame);
2651     if (s->last_frame.data[0])
2652         avctx->release_buffer(avctx, &s->last_frame);
2653     /* no need to release the current_frame since it will always be pointing
2654      * to the same frame as either the golden or last frame */
2655
2656     return 0;
2657 }
2658
2659 static int theora_decode_header(AVCodecContext *avctx, GetBitContext gb)
2660 {
2661     Vp3DecodeContext *s = avctx->priv_data;
2662     int major, minor, micro;
2663
2664     major = get_bits(&gb, 8); /* version major */
2665     minor = get_bits(&gb, 8); /* version minor */
2666     micro = get_bits(&gb, 8); /* version micro */
2667     av_log(avctx, AV_LOG_INFO, "Theora bitstream version %d.%d.%d\n",
2668         major, minor, micro);
2669
2670     /* FIXME: endianess? */
2671     s->theora = (major << 16) | (minor << 8) | micro;
2672
2673     /* 3.3.0 aka alpha3 has the same frame orientation as original vp3 */
2674     /* but previous versions have the image flipped relative to vp3 */
2675     if (s->theora < 0x030300)
2676     {
2677         s->flipped_image = 1;
2678         av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
2679     }
2680
2681     s->width = get_bits(&gb, 16) << 4;
2682     s->height = get_bits(&gb, 16) << 4;
2683     
2684     skip_bits(&gb, 24); /* frame width */
2685     skip_bits(&gb, 24); /* frame height */
2686
2687     skip_bits(&gb, 8); /* offset x */
2688     skip_bits(&gb, 8); /* offset y */
2689
2690     skip_bits(&gb, 32); /* fps numerator */
2691     skip_bits(&gb, 32); /* fps denumerator */
2692     skip_bits(&gb, 24); /* aspect numerator */
2693     skip_bits(&gb, 24); /* aspect denumerator */
2694     
2695     if (s->theora < 0x030300)
2696         skip_bits(&gb, 5); /* keyframe frequency force */
2697     skip_bits(&gb, 8); /* colorspace */
2698     skip_bits(&gb, 24); /* bitrate */
2699
2700     skip_bits(&gb, 6); /* last(?) quality index */
2701     
2702     if (s->theora >= 0x030300)
2703     {
2704         skip_bits(&gb, 5); /* keyframe frequency force */
2705         skip_bits(&gb, 5); /* spare bits */
2706     }
2707     
2708 //    align_get_bits(&gb);
2709     
2710     avctx->width = s->width;
2711     avctx->height = s->height;
2712
2713     vp3_decode_init(avctx);
2714
2715     return 0;
2716 }
2717
2718 static int theora_decode_comments(AVCodecContext *avctx, GetBitContext gb)
2719 {
2720     int nb_comments, i, tmp;
2721
2722     tmp = get_bits_long(&gb, 32);
2723     tmp = be2me_32(tmp);
2724     while(tmp--)
2725             skip_bits(&gb, 8);
2726
2727     nb_comments = get_bits_long(&gb, 32);
2728     nb_comments = be2me_32(nb_comments);
2729     for (i = 0; i < nb_comments; i++)
2730     {
2731         tmp = get_bits_long(&gb, 32);
2732         tmp = be2me_32(tmp);
2733         while(tmp--)
2734             skip_bits(&gb, 8);
2735     }
2736     
2737     return 0;
2738 }
2739
2740 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext gb)
2741 {
2742     Vp3DecodeContext *s = avctx->priv_data;
2743     int i;
2744     
2745     /* quality threshold table */
2746     for (i = 0; i < 64; i++)
2747         s->coded_ac_scale_factor[i] = get_bits(&gb, 16);
2748
2749     /* dc scale factor table */
2750     for (i = 0; i < 64; i++)
2751         s->coded_dc_scale_factor[i] = get_bits(&gb, 16);
2752
2753     /* y coeffs */
2754     for (i = 0; i < 64; i++)
2755         s->coded_intra_y_dequant[i] = get_bits(&gb, 8);
2756
2757     /* uv coeffs */
2758     for (i = 0; i < 64; i++)
2759         s->coded_intra_c_dequant[i] = get_bits(&gb, 8);
2760
2761     /* inter coeffs */
2762     for (i = 0; i < 64; i++)
2763         s->coded_inter_dequant[i] = get_bits(&gb, 8);
2764
2765     /* FIXME: read huffmann tree.. */
2766     
2767     s->theora_tables = 1;
2768     
2769     return 0;
2770 }
2771
2772 static int theora_decode_init(AVCodecContext *avctx)
2773 {
2774     Vp3DecodeContext *s = avctx->priv_data;
2775     GetBitContext gb;
2776     int ptype;
2777     
2778     s->theora = 1;
2779
2780     if (!avctx->extradata_size)
2781         return -1;
2782
2783     init_get_bits(&gb, avctx->extradata, avctx->extradata_size);
2784
2785     ptype = get_bits(&gb, 8);
2786     debug_vp3("Theora headerpacket type: %x\n", ptype);
2787             
2788     if (!(ptype & 0x80))
2789         return -1;
2790         
2791     skip_bits(&gb, 6*8); /* "theora" */
2792         
2793     switch(ptype)
2794     {
2795         case 0x80:
2796             theora_decode_header(avctx, gb);
2797             vp3_decode_init(avctx);
2798             break;
2799         case 0x81:
2800             theora_decode_comments(avctx, gb);
2801             break;
2802         case 0x82:
2803             theora_decode_tables(avctx, gb);
2804             break;
2805     }
2806
2807     return 0;
2808 }
2809
2810 AVCodec vp3_decoder = {
2811     "vp3",
2812     CODEC_TYPE_VIDEO,
2813     CODEC_ID_VP3,
2814     sizeof(Vp3DecodeContext),
2815     vp3_decode_init,
2816     NULL,
2817     vp3_decode_end,
2818     vp3_decode_frame,
2819     0,
2820     NULL
2821 };
2822
2823 AVCodec theora_decoder = {
2824     "theora",
2825     CODEC_TYPE_VIDEO,
2826     CODEC_ID_THEORA,
2827     sizeof(Vp3DecodeContext),
2828     theora_decode_init,
2829     NULL,
2830     vp3_decode_end,
2831     vp3_decode_frame,
2832     0,
2833     NULL
2834 };