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