]> git.sesse.net Git - ffmpeg/blob - libavcodec/vp3.c
8b7ff42668813afcc87b91fa4aecc37310b325d8
[ffmpeg] / libavcodec / vp3.c
1 /*
2  * Copyright (C) 2003-2004 the ffmpeg project
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file libavcodec/vp3.c
23  * On2 VP3 Video Decoder
24  *
25  * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
26  * For more information about the VP3 coding process, visit:
27  *   http://wiki.multimedia.cx/index.php?title=On2_VP3
28  *
29  * Theora decoder by Alex Beregszaszi
30  */
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #include "avcodec.h"
37 #include "dsputil.h"
38 #include "get_bits.h"
39
40 #include "vp3data.h"
41 #include "xiph.h"
42
43 #define FRAGMENT_PIXELS 8
44
45 static av_cold int vp3_decode_end(AVCodecContext *avctx);
46
47 typedef struct Coeff {
48     struct Coeff *next;
49     DCTELEM coeff;
50     uint8_t index;
51 } Coeff;
52
53 //FIXME split things out into their own arrays
54 typedef struct Vp3Fragment {
55     Coeff *next_coeff;
56     uint8_t coding_method;
57     int8_t motion_x;
58     int8_t motion_y;
59     uint8_t qpi;
60 } Vp3Fragment;
61
62 #define SB_NOT_CODED        0
63 #define SB_PARTIALLY_CODED  1
64 #define SB_FULLY_CODED      2
65
66 #define MODE_INTER_NO_MV      0
67 #define MODE_INTRA            1
68 #define MODE_INTER_PLUS_MV    2
69 #define MODE_INTER_LAST_MV    3
70 #define MODE_INTER_PRIOR_LAST 4
71 #define MODE_USING_GOLDEN     5
72 #define MODE_GOLDEN_MV        6
73 #define MODE_INTER_FOURMV     7
74 #define CODING_MODE_COUNT     8
75
76 /* special internal mode */
77 #define MODE_COPY             8
78
79 /* There are 6 preset schemes, plus a free-form scheme */
80 static const int ModeAlphabet[6][CODING_MODE_COUNT] =
81 {
82     /* scheme 1: Last motion vector dominates */
83     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
84          MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
85          MODE_INTRA,            MODE_USING_GOLDEN,
86          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
87
88     /* scheme 2 */
89     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
90          MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
91          MODE_INTRA,            MODE_USING_GOLDEN,
92          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
93
94     /* scheme 3 */
95     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
96          MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
97          MODE_INTRA,            MODE_USING_GOLDEN,
98          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
99
100     /* scheme 4 */
101     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
102          MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
103          MODE_INTRA,            MODE_USING_GOLDEN,
104          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
105
106     /* scheme 5: No motion vector dominates */
107     {    MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,
108          MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
109          MODE_INTRA,            MODE_USING_GOLDEN,
110          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
111
112     /* scheme 6 */
113     {    MODE_INTER_NO_MV,      MODE_USING_GOLDEN,
114          MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
115          MODE_INTER_PLUS_MV,    MODE_INTRA,
116          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
117
118 };
119
120 #define MIN_DEQUANT_VAL 2
121
122 typedef struct Vp3DecodeContext {
123     AVCodecContext *avctx;
124     int theora, theora_tables;
125     int version;
126     int width, height;
127     AVFrame golden_frame;
128     AVFrame last_frame;
129     AVFrame current_frame;
130     int keyframe;
131     DSPContext dsp;
132     int flipped_image;
133     int last_slice_end;
134
135     int qps[3];
136     int nqps;
137     int last_qps[3];
138
139     int superblock_count;
140     int y_superblock_width;
141     int y_superblock_height;
142     int c_superblock_width;
143     int c_superblock_height;
144     int u_superblock_start;
145     int v_superblock_start;
146     unsigned char *superblock_coding;
147
148     int macroblock_count;
149     int macroblock_width;
150     int macroblock_height;
151
152     int fragment_count;
153     int fragment_width;
154     int fragment_height;
155
156     Vp3Fragment *all_fragments;
157     uint8_t *coeff_counts;
158     Coeff *coeffs;
159     Coeff *next_coeff;
160     int fragment_start[3];
161     int data_offset[3];
162
163     ScanTable scantable;
164
165     /* tables */
166     uint16_t coded_dc_scale_factor[64];
167     uint32_t coded_ac_scale_factor[64];
168     uint8_t base_matrix[384][64];
169     uint8_t qr_count[2][3];
170     uint8_t qr_size [2][3][64];
171     uint16_t qr_base[2][3][64];
172
173     /* this is a list of indexes into the all_fragments array indicating
174      * which of the fragments are coded */
175     int *coded_fragment_list;
176     int coded_fragment_list_index;
177
178     /* track which fragments have already been decoded; called 'fast'
179      * because this data structure avoids having to iterate through every
180      * fragment in coded_fragment_list; once a fragment has been fully
181      * decoded, it is removed from this list */
182     int *fast_fragment_list;
183     int fragment_list_y_head;
184     int fragment_list_c_head;
185
186     VLC dc_vlc[16];
187     VLC ac_vlc_1[16];
188     VLC ac_vlc_2[16];
189     VLC ac_vlc_3[16];
190     VLC ac_vlc_4[16];
191
192     VLC superblock_run_length_vlc;
193     VLC fragment_run_length_vlc;
194     VLC mode_code_vlc;
195     VLC motion_vector_vlc;
196
197     /* these arrays need to be on 16-byte boundaries since SSE2 operations
198      * index into them */
199     DECLARE_ALIGNED_16(int16_t, qmat)[3][2][3][64];     //<qmat[qpi][is_inter][plane]
200
201     /* This table contains superblock_count * 16 entries. Each set of 16
202      * numbers corresponds to the fragment indexes 0..15 of the superblock.
203      * An entry will be -1 to indicate that no entry corresponds to that
204      * index. */
205     int *superblock_fragments;
206
207     /* This is an array that indicates how a particular macroblock
208      * is coded. */
209     unsigned char *macroblock_coding;
210
211     int first_coded_y_fragment;
212     int first_coded_c_fragment;
213     int last_coded_y_fragment;
214     int last_coded_c_fragment;
215
216     uint8_t edge_emu_buffer[9*2048]; //FIXME dynamic alloc
217     int8_t qscale_table[2048]; //FIXME dynamic alloc (width+15)/16
218
219     /* Huffman decode */
220     int hti;
221     unsigned int hbits;
222     int entries;
223     int huff_code_size;
224     uint16_t huffman_table[80][32][2];
225
226     uint8_t filter_limit_values[64];
227     DECLARE_ALIGNED_8(int, bounding_values_array)[256+2];
228 } Vp3DecodeContext;
229
230 /************************************************************************
231  * VP3 specific functions
232  ************************************************************************/
233
234 /*
235  * This function sets up all of the various blocks mappings:
236  * superblocks <-> fragments, macroblocks <-> fragments,
237  * superblocks <-> macroblocks
238  *
239  * Returns 0 is successful; returns 1 if *anything* went wrong.
240  */
241 static int init_block_mapping(Vp3DecodeContext *s)
242 {
243     int i, j;
244     signed int hilbert_walk_mb[4];
245
246     int current_fragment = 0;
247     int current_width = 0;
248     int current_height = 0;
249     int right_edge = 0;
250     int bottom_edge = 0;
251     int superblock_row_inc = 0;
252     int mapping_index = 0;
253
254     int current_macroblock;
255     int c_fragment;
256
257     static const signed char travel_width[16] = {
258          1,  1,  0, -1,
259          0,  0,  1,  0,
260          1,  0,  1,  0,
261          0, -1,  0,  1
262     };
263
264     static const signed char travel_height[16] = {
265          0,  0,  1,  0,
266          1,  1,  0, -1,
267          0,  1,  0, -1,
268         -1,  0, -1,  0
269     };
270
271     hilbert_walk_mb[0] = 1;
272     hilbert_walk_mb[1] = s->macroblock_width;
273     hilbert_walk_mb[2] = 1;
274     hilbert_walk_mb[3] = -s->macroblock_width;
275
276     /* iterate through each superblock (all planes) and map the fragments */
277     for (i = 0; i < s->superblock_count; i++) {
278         /* time to re-assign the limits? */
279         if (i == 0) {
280
281             /* start of Y superblocks */
282             right_edge = s->fragment_width;
283             bottom_edge = s->fragment_height;
284             current_width = -1;
285             current_height = 0;
286             superblock_row_inc = 3 * s->fragment_width -
287                 (s->y_superblock_width * 4 - s->fragment_width);
288
289             /* the first operation for this variable is to advance by 1 */
290             current_fragment = -1;
291
292         } else if (i == s->u_superblock_start) {
293
294             /* start of U superblocks */
295             right_edge = s->fragment_width / 2;
296             bottom_edge = s->fragment_height / 2;
297             current_width = -1;
298             current_height = 0;
299             superblock_row_inc = 3 * (s->fragment_width / 2) -
300                 (s->c_superblock_width * 4 - s->fragment_width / 2);
301
302             /* the first operation for this variable is to advance by 1 */
303             current_fragment = s->fragment_start[1] - 1;
304
305         } else if (i == s->v_superblock_start) {
306
307             /* start of V superblocks */
308             right_edge = s->fragment_width / 2;
309             bottom_edge = s->fragment_height / 2;
310             current_width = -1;
311             current_height = 0;
312             superblock_row_inc = 3 * (s->fragment_width / 2) -
313                 (s->c_superblock_width * 4 - s->fragment_width / 2);
314
315             /* the first operation for this variable is to advance by 1 */
316             current_fragment = s->fragment_start[2] - 1;
317
318         }
319
320         if (current_width >= right_edge - 1) {
321             /* reset width and move to next superblock row */
322             current_width = -1;
323             current_height += 4;
324
325             /* fragment is now at the start of a new superblock row */
326             current_fragment += superblock_row_inc;
327         }
328
329         /* iterate through all 16 fragments in a superblock */
330         for (j = 0; j < 16; j++) {
331             current_fragment += travel_width[j] + right_edge * travel_height[j];
332             current_width += travel_width[j];
333             current_height += travel_height[j];
334
335             /* check if the fragment is in bounds */
336             if ((current_width < right_edge) &&
337                 (current_height < bottom_edge)) {
338                 s->superblock_fragments[mapping_index] = current_fragment;
339             } else {
340                 s->superblock_fragments[mapping_index] = -1;
341             }
342
343             mapping_index++;
344         }
345     }
346
347     return 0;  /* successful path out */
348 }
349
350 /*
351  * This function wipes out all of the fragment data.
352  */
353 static void init_frame(Vp3DecodeContext *s, GetBitContext *gb)
354 {
355     int i;
356
357     /* zero out all of the fragment information */
358     s->coded_fragment_list_index = 0;
359     for (i = 0; i < s->fragment_count; i++) {
360         s->coeff_counts[i] = 0;
361         s->all_fragments[i].motion_x = 127;
362         s->all_fragments[i].motion_y = 127;
363         s->all_fragments[i].next_coeff= NULL;
364         s->all_fragments[i].qpi = 0;
365         s->coeffs[i].index=
366         s->coeffs[i].coeff=0;
367         s->coeffs[i].next= NULL;
368     }
369 }
370
371 /*
372  * This function sets up the dequantization tables used for a particular
373  * frame.
374  */
375 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
376 {
377     int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
378     int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
379     int i, plane, inter, qri, bmi, bmj, qistart;
380
381     for(inter=0; inter<2; inter++){
382         for(plane=0; plane<3; plane++){
383             int sum=0;
384             for(qri=0; qri<s->qr_count[inter][plane]; qri++){
385                 sum+= s->qr_size[inter][plane][qri];
386                 if(s->qps[qpi] <= sum)
387                     break;
388             }
389             qistart= sum - s->qr_size[inter][plane][qri];
390             bmi= s->qr_base[inter][plane][qri  ];
391             bmj= s->qr_base[inter][plane][qri+1];
392             for(i=0; i<64; i++){
393                 int coeff= (  2*(sum    -s->qps[qpi])*s->base_matrix[bmi][i]
394                             - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
395                             + s->qr_size[inter][plane][qri])
396                            / (2*s->qr_size[inter][plane][qri]);
397
398                 int qmin= 8<<(inter + !i);
399                 int qscale= i ? ac_scale_factor : dc_scale_factor;
400
401                 s->qmat[qpi][inter][plane][s->dsp.idct_permutation[i]]= av_clip((qscale * coeff)/100 * 4, qmin, 4096);
402             }
403             // all DC coefficients use the same quant so as not to interfere with DC prediction
404             s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
405         }
406     }
407
408     memset(s->qscale_table, (FFMAX(s->qmat[0][0][0][1], s->qmat[0][0][1][1])+8)/16, 512); //FIXME finetune
409 }
410
411 /*
412  * This function initializes the loop filter boundary limits if the frame's
413  * quality index is different from the previous frame's.
414  *
415  * The filter_limit_values may not be larger than 127.
416  */
417 static void init_loop_filter(Vp3DecodeContext *s)
418 {
419     int *bounding_values= s->bounding_values_array+127;
420     int filter_limit;
421     int x;
422     int value;
423
424     filter_limit = s->filter_limit_values[s->qps[0]];
425
426     /* set up the bounding values */
427     memset(s->bounding_values_array, 0, 256 * sizeof(int));
428     for (x = 0; x < filter_limit; x++) {
429         bounding_values[-x] = -x;
430         bounding_values[x] = x;
431     }
432     for (x = value = filter_limit; x < 128 && value; x++, value--) {
433         bounding_values[ x] =  value;
434         bounding_values[-x] = -value;
435     }
436     if (value)
437         bounding_values[128] = value;
438     bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
439 }
440
441 /*
442  * This function unpacks all of the superblock/macroblock/fragment coding
443  * information from the bitstream.
444  */
445 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
446 {
447     int bit = 0;
448     int current_superblock = 0;
449     int current_run = 0;
450     int decode_fully_flags = 0;
451     int decode_partial_blocks = 0;
452     int first_c_fragment_seen;
453
454     int i, j;
455     int current_fragment;
456
457     if (s->keyframe) {
458         memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
459
460     } else {
461
462         /* unpack the list of partially-coded superblocks */
463         bit = get_bits1(gb);
464         /* toggle the bit because as soon as the first run length is
465          * fetched the bit will be toggled again */
466         bit ^= 1;
467         while (current_superblock < s->superblock_count) {
468             if (current_run-- == 0) {
469                 bit ^= 1;
470                 current_run = get_vlc2(gb,
471                     s->superblock_run_length_vlc.table, 6, 2);
472                 if (current_run == 33)
473                     current_run += get_bits(gb, 12);
474
475                 /* if any of the superblocks are not partially coded, flag
476                  * a boolean to decode the list of fully-coded superblocks */
477                 if (bit == 0) {
478                     decode_fully_flags = 1;
479                 } else {
480
481                     /* make a note of the fact that there are partially coded
482                      * superblocks */
483                     decode_partial_blocks = 1;
484                 }
485             }
486             s->superblock_coding[current_superblock++] = bit;
487         }
488
489         /* unpack the list of fully coded superblocks if any of the blocks were
490          * not marked as partially coded in the previous step */
491         if (decode_fully_flags) {
492
493             current_superblock = 0;
494             current_run = 0;
495             bit = get_bits1(gb);
496             /* toggle the bit because as soon as the first run length is
497              * fetched the bit will be toggled again */
498             bit ^= 1;
499             while (current_superblock < s->superblock_count) {
500
501                 /* skip any superblocks already marked as partially coded */
502                 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
503
504                     if (current_run-- == 0) {
505                         bit ^= 1;
506                         current_run = get_vlc2(gb,
507                             s->superblock_run_length_vlc.table, 6, 2);
508                         if (current_run == 33)
509                             current_run += get_bits(gb, 12);
510                     }
511                     s->superblock_coding[current_superblock] = 2*bit;
512                 }
513                 current_superblock++;
514             }
515         }
516
517         /* if there were partial blocks, initialize bitstream for
518          * unpacking fragment codings */
519         if (decode_partial_blocks) {
520
521             current_run = 0;
522             bit = get_bits1(gb);
523             /* toggle the bit because as soon as the first run length is
524              * fetched the bit will be toggled again */
525             bit ^= 1;
526         }
527     }
528
529     /* figure out which fragments are coded; iterate through each
530      * superblock (all planes) */
531     s->coded_fragment_list_index = 0;
532     s->next_coeff= s->coeffs + s->fragment_count;
533     s->first_coded_y_fragment = s->first_coded_c_fragment = 0;
534     s->last_coded_y_fragment = s->last_coded_c_fragment = -1;
535     first_c_fragment_seen = 0;
536     memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
537     for (i = 0; i < s->superblock_count; i++) {
538
539         /* iterate through all 16 fragments in a superblock */
540         for (j = 0; j < 16; j++) {
541
542             /* if the fragment is in bounds, check its coding status */
543             current_fragment = s->superblock_fragments[i * 16 + j];
544             if (current_fragment >= s->fragment_count) {
545                 av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_superblocks(): bad fragment number (%d >= %d)\n",
546                     current_fragment, s->fragment_count);
547                 return 1;
548             }
549             if (current_fragment != -1) {
550                 if (s->superblock_coding[i] == SB_NOT_CODED) {
551
552                     /* copy all the fragments from the prior frame */
553                     s->all_fragments[current_fragment].coding_method =
554                         MODE_COPY;
555
556                 } else if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
557
558                     /* fragment may or may not be coded; this is the case
559                      * that cares about the fragment coding runs */
560                     if (current_run-- == 0) {
561                         bit ^= 1;
562                         current_run = get_vlc2(gb,
563                             s->fragment_run_length_vlc.table, 5, 2);
564                     }
565
566                     if (bit) {
567                         /* default mode; actual mode will be decoded in
568                          * the next phase */
569                         s->all_fragments[current_fragment].coding_method =
570                             MODE_INTER_NO_MV;
571                         s->all_fragments[current_fragment].next_coeff= s->coeffs + current_fragment;
572                         s->coded_fragment_list[s->coded_fragment_list_index] =
573                             current_fragment;
574                         if ((current_fragment >= s->fragment_start[1]) &&
575                             (s->last_coded_y_fragment == -1) &&
576                             (!first_c_fragment_seen)) {
577                             s->first_coded_c_fragment = s->coded_fragment_list_index;
578                             s->last_coded_y_fragment = s->first_coded_c_fragment - 1;
579                             first_c_fragment_seen = 1;
580                         }
581                         s->coded_fragment_list_index++;
582                     } else {
583                         /* not coded; copy this fragment from the prior frame */
584                         s->all_fragments[current_fragment].coding_method =
585                             MODE_COPY;
586                     }
587
588                 } else {
589
590                     /* fragments are fully coded in this superblock; actual
591                      * coding will be determined in next step */
592                     s->all_fragments[current_fragment].coding_method =
593                         MODE_INTER_NO_MV;
594                     s->all_fragments[current_fragment].next_coeff= s->coeffs + current_fragment;
595                     s->coded_fragment_list[s->coded_fragment_list_index] =
596                         current_fragment;
597                     if ((current_fragment >= s->fragment_start[1]) &&
598                         (s->last_coded_y_fragment == -1) &&
599                         (!first_c_fragment_seen)) {
600                         s->first_coded_c_fragment = s->coded_fragment_list_index;
601                         s->last_coded_y_fragment = s->first_coded_c_fragment - 1;
602                         first_c_fragment_seen = 1;
603                     }
604                     s->coded_fragment_list_index++;
605                 }
606             }
607         }
608     }
609
610     if (!first_c_fragment_seen)
611         /* only Y fragments coded in this frame */
612         s->last_coded_y_fragment = s->coded_fragment_list_index - 1;
613     else
614         /* end the list of coded C fragments */
615         s->last_coded_c_fragment = s->coded_fragment_list_index - 1;
616
617     for (i = 0; i < s->fragment_count - 1; i++) {
618         s->fast_fragment_list[i] = i + 1;
619     }
620     s->fast_fragment_list[s->fragment_count - 1] = -1;
621
622     if (s->last_coded_y_fragment == -1)
623         s->fragment_list_y_head = -1;
624     else {
625         s->fragment_list_y_head = s->first_coded_y_fragment;
626         s->fast_fragment_list[s->last_coded_y_fragment] = -1;
627     }
628
629     if (s->last_coded_c_fragment == -1)
630         s->fragment_list_c_head = -1;
631     else {
632         s->fragment_list_c_head = s->first_coded_c_fragment;
633         s->fast_fragment_list[s->last_coded_c_fragment] = -1;
634     }
635
636     return 0;
637 }
638
639 /*
640  * This function unpacks all the coding mode data for individual macroblocks
641  * from the bitstream.
642  */
643 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
644 {
645     int i, j, k, sb_x, sb_y;
646     int scheme;
647     int current_macroblock;
648     int current_fragment;
649     int coding_mode;
650     int custom_mode_alphabet[CODING_MODE_COUNT];
651
652     if (s->keyframe) {
653         for (i = 0; i < s->fragment_count; i++)
654             s->all_fragments[i].coding_method = MODE_INTRA;
655
656     } else {
657
658         /* fetch the mode coding scheme for this frame */
659         scheme = get_bits(gb, 3);
660
661         /* is it a custom coding scheme? */
662         if (scheme == 0) {
663             for (i = 0; i < 8; i++)
664                 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
665             for (i = 0; i < 8; i++)
666                 custom_mode_alphabet[get_bits(gb, 3)] = i;
667         }
668
669         /* iterate through all of the macroblocks that contain 1 or more
670          * coded fragments */
671         for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
672             for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
673
674             for (j = 0; j < 4; j++) {
675                 int mb_x = 2*sb_x +   (j>>1);
676                 int mb_y = 2*sb_y + (((j>>1)+j)&1);
677                 int frags_coded = 0;
678                 current_macroblock = mb_y * s->macroblock_width + mb_x;
679
680                 if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height)
681                     continue;
682
683 #define BLOCK_X (2*mb_x + (k&1))
684 #define BLOCK_Y (2*mb_y + (k>>1))
685                 /* coding modes are only stored if the macroblock has at least one
686                  * luma block coded, otherwise it must be INTER_NO_MV */
687                 for (k = 0; k < 4; k++) {
688                     current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;
689                     if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
690                         break;
691                 }
692                 if (k == 4) {
693                     s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
694                     continue;
695                 }
696
697                 /* mode 7 means get 3 bits for each coding mode */
698                 if (scheme == 7)
699                     coding_mode = get_bits(gb, 3);
700                 else if(scheme == 0)
701                     coding_mode = custom_mode_alphabet
702                         [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
703                 else
704                     coding_mode = ModeAlphabet[scheme-1]
705                         [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
706
707                 s->macroblock_coding[current_macroblock] = coding_mode;
708                 for (k = 0; k < 4; k++) {
709                     current_fragment =
710                         BLOCK_Y*s->fragment_width + BLOCK_X;
711                     if (s->all_fragments[current_fragment].coding_method !=
712                         MODE_COPY)
713                         s->all_fragments[current_fragment].coding_method =
714                             coding_mode;
715                 }
716                 for (k = 0; k < 2; k++) {
717                     current_fragment = s->fragment_start[k+1] +
718                         mb_y*(s->fragment_width>>1) + mb_x;
719                     if (s->all_fragments[current_fragment].coding_method !=
720                         MODE_COPY)
721                         s->all_fragments[current_fragment].coding_method =
722                             coding_mode;
723                 }
724             }
725             }
726         }
727     }
728
729     return 0;
730 }
731
732 /*
733  * This function unpacks all the motion vectors for the individual
734  * macroblocks from the bitstream.
735  */
736 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
737 {
738     int j, k, l, sb_x, sb_y;
739     int coding_mode;
740     int motion_x[6];
741     int motion_y[6];
742     int last_motion_x = 0;
743     int last_motion_y = 0;
744     int prior_last_motion_x = 0;
745     int prior_last_motion_y = 0;
746     int current_macroblock;
747     int current_fragment;
748
749     if (s->keyframe)
750         return 0;
751
752     memset(motion_x, 0, 6 * sizeof(int));
753     memset(motion_y, 0, 6 * sizeof(int));
754
755     /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
756     coding_mode = get_bits1(gb);
757
758     /* iterate through all of the macroblocks that contain 1 or more
759      * coded fragments */
760     for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
761         for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
762
763         for (j = 0; j < 4; j++) {
764             int mb_x = 2*sb_x +   (j>>1);
765             int mb_y = 2*sb_y + (((j>>1)+j)&1);
766             current_macroblock = mb_y * s->macroblock_width + mb_x;
767
768             if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
769                 (s->macroblock_coding[current_macroblock] == MODE_COPY))
770                 continue;
771
772             switch (s->macroblock_coding[current_macroblock]) {
773
774             case MODE_INTER_PLUS_MV:
775             case MODE_GOLDEN_MV:
776                 /* all 6 fragments use the same motion vector */
777                 if (coding_mode == 0) {
778                     motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
779                     motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
780                 } else {
781                     motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
782                     motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
783                 }
784
785                 /* vector maintenance, only on MODE_INTER_PLUS_MV */
786                 if (s->macroblock_coding[current_macroblock] ==
787                     MODE_INTER_PLUS_MV) {
788                     prior_last_motion_x = last_motion_x;
789                     prior_last_motion_y = last_motion_y;
790                     last_motion_x = motion_x[0];
791                     last_motion_y = motion_y[0];
792                 }
793                 break;
794
795             case MODE_INTER_FOURMV:
796                 /* vector maintenance */
797                 prior_last_motion_x = last_motion_x;
798                 prior_last_motion_y = last_motion_y;
799
800                 /* fetch 4 vectors from the bitstream, one for each
801                  * Y fragment, then average for the C fragment vectors */
802                 motion_x[4] = motion_y[4] = 0;
803                 for (k = 0; k < 4; k++) {
804                     current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;
805                     for (l = 0; l < s->coded_fragment_list_index; l++)
806                         if (s->coded_fragment_list[l] == current_fragment)
807                             break;
808                     if (l < s->coded_fragment_list_index) {
809                         if (coding_mode == 0) {
810                             motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
811                             motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
812                         } else {
813                             motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
814                             motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
815                         }
816                         last_motion_x = motion_x[k];
817                         last_motion_y = motion_y[k];
818                     } else {
819                         motion_x[k] = 0;
820                         motion_y[k] = 0;
821                     }
822                     motion_x[4] += motion_x[k];
823                     motion_y[4] += motion_y[k];
824                 }
825
826                 motion_x[5]=
827                 motion_x[4]= RSHIFT(motion_x[4], 2);
828                 motion_y[5]=
829                 motion_y[4]= RSHIFT(motion_y[4], 2);
830                 break;
831
832             case MODE_INTER_LAST_MV:
833                 /* all 6 fragments use the last motion vector */
834                 motion_x[0] = last_motion_x;
835                 motion_y[0] = last_motion_y;
836
837                 /* no vector maintenance (last vector remains the
838                  * last vector) */
839                 break;
840
841             case MODE_INTER_PRIOR_LAST:
842                 /* all 6 fragments use the motion vector prior to the
843                  * last motion vector */
844                 motion_x[0] = prior_last_motion_x;
845                 motion_y[0] = prior_last_motion_y;
846
847                 /* vector maintenance */
848                 prior_last_motion_x = last_motion_x;
849                 prior_last_motion_y = last_motion_y;
850                 last_motion_x = motion_x[0];
851                 last_motion_y = motion_y[0];
852                 break;
853
854             default:
855                 /* covers intra, inter without MV, golden without MV */
856                 motion_x[0] = 0;
857                 motion_y[0] = 0;
858
859                 /* no vector maintenance */
860                 break;
861             }
862
863             /* assign the motion vectors to the correct fragments */
864             for (k = 0; k < 4; k++) {
865                 current_fragment =
866                     BLOCK_Y*s->fragment_width + BLOCK_X;
867                 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
868                     s->all_fragments[current_fragment].motion_x = motion_x[k];
869                     s->all_fragments[current_fragment].motion_y = motion_y[k];
870                 } else {
871                     s->all_fragments[current_fragment].motion_x = motion_x[0];
872                     s->all_fragments[current_fragment].motion_y = motion_y[0];
873                 }
874             }
875             for (k = 0; k < 2; k++) {
876                 current_fragment = s->fragment_start[k+1] +
877                     mb_y*(s->fragment_width>>1) + mb_x;
878                 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
879                     s->all_fragments[current_fragment].motion_x = motion_x[k+4];
880                     s->all_fragments[current_fragment].motion_y = motion_y[k+4];
881                 } else {
882                     s->all_fragments[current_fragment].motion_x = motion_x[0];
883                     s->all_fragments[current_fragment].motion_y = motion_y[0];
884                 }
885             }
886         }
887         }
888     }
889
890     return 0;
891 }
892
893 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
894 {
895     int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
896     int num_blocks = s->coded_fragment_list_index;
897
898     for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
899         i = blocks_decoded = num_blocks_at_qpi = 0;
900
901         bit = get_bits1(gb);
902
903         do {
904             run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
905             if (run_length == 34)
906                 run_length += get_bits(gb, 12);
907             blocks_decoded += run_length;
908
909             if (!bit)
910                 num_blocks_at_qpi += run_length;
911
912             for (j = 0; j < run_length; i++) {
913                 if (i >= s->coded_fragment_list_index)
914                     return -1;
915
916                 if (s->all_fragments[s->coded_fragment_list[i]].qpi == qpi) {
917                     s->all_fragments[s->coded_fragment_list[i]].qpi += bit;
918                     j++;
919                 }
920             }
921
922             if (run_length == 4129)
923                 bit = get_bits1(gb);
924             else
925                 bit ^= 1;
926         } while (blocks_decoded < num_blocks);
927
928         num_blocks -= num_blocks_at_qpi;
929     }
930
931     return 0;
932 }
933
934 /*
935  * This function is called by unpack_dct_coeffs() to extract the VLCs from
936  * the bitstream. The VLCs encode tokens which are used to unpack DCT
937  * data. This function unpacks all the VLCs for either the Y plane or both
938  * C planes, and is called for DC coefficients or different AC coefficient
939  * levels (since different coefficient types require different VLC tables.
940  *
941  * This function returns a residual eob run. E.g, if a particular token gave
942  * instructions to EOB the next 5 fragments and there were only 2 fragments
943  * left in the current fragment range, 3 would be returned so that it could
944  * be passed into the next call to this same function.
945  */
946 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
947                         VLC *table, int coeff_index,
948                         int y_plane,
949                         int eob_run)
950 {
951     int i;
952     int token;
953     int zero_run = 0;
954     DCTELEM coeff = 0;
955     Vp3Fragment *fragment;
956     int bits_to_get;
957     int next_fragment;
958     int previous_fragment;
959     int fragment_num;
960     int *list_head;
961
962     /* local references to structure members to avoid repeated deferences */
963     uint8_t *perm= s->scantable.permutated;
964     int *coded_fragment_list = s->coded_fragment_list;
965     Vp3Fragment *all_fragments = s->all_fragments;
966     uint8_t *coeff_counts = s->coeff_counts;
967     VLC_TYPE (*vlc_table)[2] = table->table;
968     int *fast_fragment_list = s->fast_fragment_list;
969
970     if (y_plane) {
971         next_fragment = s->fragment_list_y_head;
972         list_head = &s->fragment_list_y_head;
973     } else {
974         next_fragment = s->fragment_list_c_head;
975         list_head = &s->fragment_list_c_head;
976     }
977
978     i = next_fragment;
979     previous_fragment = -1;  /* this indicates that the previous fragment is actually the list head */
980     while (i != -1) {
981         fragment_num = coded_fragment_list[i];
982
983         if (coeff_counts[fragment_num] > coeff_index) {
984             previous_fragment = i;
985             i = fast_fragment_list[i];
986             continue;
987         }
988         fragment = &all_fragments[fragment_num];
989
990         if (!eob_run) {
991             /* decode a VLC into a token */
992             token = get_vlc2(gb, vlc_table, 5, 3);
993             /* use the token to get a zero run, a coefficient, and an eob run */
994             if (token <= 6) {
995                 eob_run = eob_run_base[token];
996                 if (eob_run_get_bits[token])
997                     eob_run += get_bits(gb, eob_run_get_bits[token]);
998                 coeff = zero_run = 0;
999             } else {
1000                 bits_to_get = coeff_get_bits[token];
1001                 if (bits_to_get)
1002                     bits_to_get = get_bits(gb, bits_to_get);
1003                 coeff = coeff_tables[token][bits_to_get];
1004
1005                 zero_run = zero_run_base[token];
1006                 if (zero_run_get_bits[token])
1007                     zero_run += get_bits(gb, zero_run_get_bits[token]);
1008             }
1009         }
1010
1011         if (!eob_run) {
1012             coeff_counts[fragment_num] += zero_run;
1013             if (coeff_counts[fragment_num] < 64){
1014                 fragment->next_coeff->coeff= coeff;
1015                 fragment->next_coeff->index= perm[coeff_counts[fragment_num]++]; //FIXME perm here already?
1016                 fragment->next_coeff->next= s->next_coeff;
1017                 s->next_coeff->next=NULL;
1018                 fragment->next_coeff= s->next_coeff++;
1019             }
1020             /* previous fragment is now this fragment */
1021             previous_fragment = i;
1022         } else {
1023             coeff_counts[fragment_num] |= 128;
1024             eob_run--;
1025             /* remove this fragment from the list */
1026             if (previous_fragment != -1)
1027                 fast_fragment_list[previous_fragment] = fast_fragment_list[i];
1028             else
1029                 *list_head = fast_fragment_list[i];
1030             /* previous fragment remains unchanged */
1031         }
1032
1033         i = fast_fragment_list[i];
1034     }
1035
1036     return eob_run;
1037 }
1038
1039 static void reverse_dc_prediction(Vp3DecodeContext *s,
1040                                   int first_fragment,
1041                                   int fragment_width,
1042                                   int fragment_height);
1043 /*
1044  * This function unpacks all of the DCT coefficient data from the
1045  * bitstream.
1046  */
1047 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1048 {
1049     int i;
1050     int dc_y_table;
1051     int dc_c_table;
1052     int ac_y_table;
1053     int ac_c_table;
1054     int residual_eob_run = 0;
1055     VLC *y_tables[64];
1056     VLC *c_tables[64];
1057
1058     /* fetch the DC table indexes */
1059     dc_y_table = get_bits(gb, 4);
1060     dc_c_table = get_bits(gb, 4);
1061
1062     /* unpack the Y plane DC coefficients */
1063     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1064         1, residual_eob_run);
1065
1066     /* reverse prediction of the Y-plane DC coefficients */
1067     reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);
1068
1069     /* unpack the C plane DC coefficients */
1070     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1071         0, residual_eob_run);
1072
1073     /* reverse prediction of the C-plane DC coefficients */
1074     if (!(s->avctx->flags & CODEC_FLAG_GRAY))
1075     {
1076         reverse_dc_prediction(s, s->fragment_start[1],
1077             s->fragment_width / 2, s->fragment_height / 2);
1078         reverse_dc_prediction(s, s->fragment_start[2],
1079             s->fragment_width / 2, s->fragment_height / 2);
1080     }
1081
1082     /* fetch the AC table indexes */
1083     ac_y_table = get_bits(gb, 4);
1084     ac_c_table = get_bits(gb, 4);
1085
1086     /* build tables of AC VLC tables */
1087     for (i = 1; i <= 5; i++) {
1088         y_tables[i] = &s->ac_vlc_1[ac_y_table];
1089         c_tables[i] = &s->ac_vlc_1[ac_c_table];
1090     }
1091     for (i = 6; i <= 14; i++) {
1092         y_tables[i] = &s->ac_vlc_2[ac_y_table];
1093         c_tables[i] = &s->ac_vlc_2[ac_c_table];
1094     }
1095     for (i = 15; i <= 27; i++) {
1096         y_tables[i] = &s->ac_vlc_3[ac_y_table];
1097         c_tables[i] = &s->ac_vlc_3[ac_c_table];
1098     }
1099     for (i = 28; i <= 63; i++) {
1100         y_tables[i] = &s->ac_vlc_4[ac_y_table];
1101         c_tables[i] = &s->ac_vlc_4[ac_c_table];
1102     }
1103
1104     /* decode all AC coefficents */
1105     for (i = 1; i <= 63; i++) {
1106         if (s->fragment_list_y_head != -1)
1107             residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1108                 1, residual_eob_run);
1109
1110         if (s->fragment_list_c_head != -1)
1111             residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1112                 0, residual_eob_run);
1113     }
1114
1115     return 0;
1116 }
1117
1118 /*
1119  * This function reverses the DC prediction for each coded fragment in
1120  * the frame. Much of this function is adapted directly from the original
1121  * VP3 source code.
1122  */
1123 #define COMPATIBLE_FRAME(x) \
1124   (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1125 #define DC_COEFF(u) (s->coeffs[u].index ? 0 : s->coeffs[u].coeff) //FIXME do somethin to simplify this
1126
1127 static void reverse_dc_prediction(Vp3DecodeContext *s,
1128                                   int first_fragment,
1129                                   int fragment_width,
1130                                   int fragment_height)
1131 {
1132
1133 #define PUL 8
1134 #define PU 4
1135 #define PUR 2
1136 #define PL 1
1137
1138     int x, y;
1139     int i = first_fragment;
1140
1141     int predicted_dc;
1142
1143     /* DC values for the left, up-left, up, and up-right fragments */
1144     int vl, vul, vu, vur;
1145
1146     /* indexes for the left, up-left, up, and up-right fragments */
1147     int l, ul, u, ur;
1148
1149     /*
1150      * The 6 fields mean:
1151      *   0: up-left multiplier
1152      *   1: up multiplier
1153      *   2: up-right multiplier
1154      *   3: left multiplier
1155      */
1156     static const int predictor_transform[16][4] = {
1157         {  0,  0,  0,  0},
1158         {  0,  0,  0,128},        // PL
1159         {  0,  0,128,  0},        // PUR
1160         {  0,  0, 53, 75},        // PUR|PL
1161         {  0,128,  0,  0},        // PU
1162         {  0, 64,  0, 64},        // PU|PL
1163         {  0,128,  0,  0},        // PU|PUR
1164         {  0,  0, 53, 75},        // PU|PUR|PL
1165         {128,  0,  0,  0},        // PUL
1166         {  0,  0,  0,128},        // PUL|PL
1167         { 64,  0, 64,  0},        // PUL|PUR
1168         {  0,  0, 53, 75},        // PUL|PUR|PL
1169         {  0,128,  0,  0},        // PUL|PU
1170        {-104,116,  0,116},        // PUL|PU|PL
1171         { 24, 80, 24,  0},        // PUL|PU|PUR
1172        {-104,116,  0,116}         // PUL|PU|PUR|PL
1173     };
1174
1175     /* This table shows which types of blocks can use other blocks for
1176      * prediction. For example, INTRA is the only mode in this table to
1177      * have a frame number of 0. That means INTRA blocks can only predict
1178      * from other INTRA blocks. There are 2 golden frame coding types;
1179      * blocks encoding in these modes can only predict from other blocks
1180      * that were encoded with these 1 of these 2 modes. */
1181     static const unsigned char compatible_frame[9] = {
1182         1,    /* MODE_INTER_NO_MV */
1183         0,    /* MODE_INTRA */
1184         1,    /* MODE_INTER_PLUS_MV */
1185         1,    /* MODE_INTER_LAST_MV */
1186         1,    /* MODE_INTER_PRIOR_MV */
1187         2,    /* MODE_USING_GOLDEN */
1188         2,    /* MODE_GOLDEN_MV */
1189         1,    /* MODE_INTER_FOUR_MV */
1190         3     /* MODE_COPY */
1191     };
1192     int current_frame_type;
1193
1194     /* there is a last DC predictor for each of the 3 frame types */
1195     short last_dc[3];
1196
1197     int transform = 0;
1198
1199     vul = vu = vur = vl = 0;
1200     last_dc[0] = last_dc[1] = last_dc[2] = 0;
1201
1202     /* for each fragment row... */
1203     for (y = 0; y < fragment_height; y++) {
1204
1205         /* for each fragment in a row... */
1206         for (x = 0; x < fragment_width; x++, i++) {
1207
1208             /* reverse prediction if this block was coded */
1209             if (s->all_fragments[i].coding_method != MODE_COPY) {
1210
1211                 current_frame_type =
1212                     compatible_frame[s->all_fragments[i].coding_method];
1213
1214                 transform= 0;
1215                 if(x){
1216                     l= i-1;
1217                     vl = DC_COEFF(l);
1218                     if(COMPATIBLE_FRAME(l))
1219                         transform |= PL;
1220                 }
1221                 if(y){
1222                     u= i-fragment_width;
1223                     vu = DC_COEFF(u);
1224                     if(COMPATIBLE_FRAME(u))
1225                         transform |= PU;
1226                     if(x){
1227                         ul= i-fragment_width-1;
1228                         vul = DC_COEFF(ul);
1229                         if(COMPATIBLE_FRAME(ul))
1230                             transform |= PUL;
1231                     }
1232                     if(x + 1 < fragment_width){
1233                         ur= i-fragment_width+1;
1234                         vur = DC_COEFF(ur);
1235                         if(COMPATIBLE_FRAME(ur))
1236                             transform |= PUR;
1237                     }
1238                 }
1239
1240                 if (transform == 0) {
1241
1242                     /* if there were no fragments to predict from, use last
1243                      * DC saved */
1244                     predicted_dc = last_dc[current_frame_type];
1245                 } else {
1246
1247                     /* apply the appropriate predictor transform */
1248                     predicted_dc =
1249                         (predictor_transform[transform][0] * vul) +
1250                         (predictor_transform[transform][1] * vu) +
1251                         (predictor_transform[transform][2] * vur) +
1252                         (predictor_transform[transform][3] * vl);
1253
1254                     predicted_dc /= 128;
1255
1256                     /* check for outranging on the [ul u l] and
1257                      * [ul u ur l] predictors */
1258                     if ((transform == 15) || (transform == 13)) {
1259                         if (FFABS(predicted_dc - vu) > 128)
1260                             predicted_dc = vu;
1261                         else if (FFABS(predicted_dc - vl) > 128)
1262                             predicted_dc = vl;
1263                         else if (FFABS(predicted_dc - vul) > 128)
1264                             predicted_dc = vul;
1265                     }
1266                 }
1267
1268                 /* at long last, apply the predictor */
1269                 if(s->coeffs[i].index){
1270                     *s->next_coeff= s->coeffs[i];
1271                     s->coeffs[i].index=0;
1272                     s->coeffs[i].coeff=0;
1273                     s->coeffs[i].next= s->next_coeff++;
1274                 }
1275                 s->coeffs[i].coeff += predicted_dc;
1276                 /* save the DC */
1277                 last_dc[current_frame_type] = DC_COEFF(i);
1278                 if(DC_COEFF(i) && !(s->coeff_counts[i]&127)){
1279                     s->coeff_counts[i]= 129;
1280 //                    s->all_fragments[i].next_coeff= s->next_coeff;
1281                     s->coeffs[i].next= s->next_coeff;
1282                     (s->next_coeff++)->next=NULL;
1283                 }
1284             }
1285         }
1286     }
1287 }
1288
1289 static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1290 {
1291     int x, y;
1292     int *bounding_values= s->bounding_values_array+127;
1293
1294     int width           = s->fragment_width  >> !!plane;
1295     int height          = s->fragment_height >> !!plane;
1296     int fragment        = s->fragment_start        [plane] + ystart * width;
1297     int stride          = s->current_frame.linesize[plane];
1298     uint8_t *plane_data = s->current_frame.data    [plane];
1299     if (!s->flipped_image) stride = -stride;
1300     plane_data += s->data_offset[plane] + 8*ystart*stride;
1301
1302     for (y = ystart; y < yend; y++) {
1303
1304         for (x = 0; x < width; x++) {
1305             /* This code basically just deblocks on the edges of coded blocks.
1306              * However, it has to be much more complicated because of the
1307              * braindamaged deblock ordering used in VP3/Theora. Order matters
1308              * because some pixels get filtered twice. */
1309             if( s->all_fragments[fragment].coding_method != MODE_COPY )
1310             {
1311                 /* do not perform left edge filter for left columns frags */
1312                 if (x > 0) {
1313                     s->dsp.vp3_h_loop_filter(
1314                         plane_data + 8*x,
1315                         stride, bounding_values);
1316                 }
1317
1318                 /* do not perform top edge filter for top row fragments */
1319                 if (y > 0) {
1320                     s->dsp.vp3_v_loop_filter(
1321                         plane_data + 8*x,
1322                         stride, bounding_values);
1323                 }
1324
1325                 /* do not perform right edge filter for right column
1326                  * fragments or if right fragment neighbor is also coded
1327                  * in this frame (it will be filtered in next iteration) */
1328                 if ((x < width - 1) &&
1329                     (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1330                     s->dsp.vp3_h_loop_filter(
1331                         plane_data + 8*x + 8,
1332                         stride, bounding_values);
1333                 }
1334
1335                 /* do not perform bottom edge filter for bottom row
1336                  * fragments or if bottom fragment neighbor is also coded
1337                  * in this frame (it will be filtered in the next row) */
1338                 if ((y < height - 1) &&
1339                     (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1340                     s->dsp.vp3_v_loop_filter(
1341                         plane_data + 8*x + 8*stride,
1342                         stride, bounding_values);
1343                 }
1344             }
1345
1346             fragment++;
1347         }
1348         plane_data += 8*stride;
1349     }
1350 }
1351
1352 /**
1353  * called when all pixels up to row y are complete
1354  */
1355 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1356 {
1357     int h, cy;
1358     int offset[4];
1359
1360     if(s->avctx->draw_horiz_band==NULL)
1361         return;
1362
1363     h= y - s->last_slice_end;
1364     y -= h;
1365
1366     if (!s->flipped_image) {
1367         if (y == 0)
1368             h -= s->height - s->avctx->height;  // account for non-mod16
1369         y = s->height - y - h;
1370     }
1371
1372     cy = y >> 1;
1373     offset[0] = s->current_frame.linesize[0]*y;
1374     offset[1] = s->current_frame.linesize[1]*cy;
1375     offset[2] = s->current_frame.linesize[2]*cy;
1376     offset[3] = 0;
1377
1378     emms_c();
1379     s->avctx->draw_horiz_band(s->avctx, &s->current_frame, offset, y, 3, h);
1380     s->last_slice_end= y + h;
1381 }
1382
1383 /*
1384  * Perform the final rendering for a particular slice of data.
1385  * The slice number ranges from 0..(macroblock_height - 1).
1386  */
1387 static void render_slice(Vp3DecodeContext *s, int slice)
1388 {
1389     int x;
1390     int16_t *dequantizer;
1391     DECLARE_ALIGNED_16(DCTELEM, block)[64];
1392     int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1393     int motion_halfpel_index;
1394     uint8_t *motion_source;
1395     int plane;
1396
1397     if (slice >= s->macroblock_height)
1398         return;
1399
1400     for (plane = 0; plane < 3; plane++) {
1401         uint8_t *output_plane = s->current_frame.data    [plane] + s->data_offset[plane];
1402         uint8_t *  last_plane = s->   last_frame.data    [plane] + s->data_offset[plane];
1403         uint8_t *golden_plane = s-> golden_frame.data    [plane] + s->data_offset[plane];
1404         int stride            = s->current_frame.linesize[plane];
1405         int plane_width       = s->width  >> !!plane;
1406         int plane_height      = s->height >> !!plane;
1407         int y =        slice *  FRAGMENT_PIXELS << !plane ;
1408         int slice_height = y + (FRAGMENT_PIXELS << !plane);
1409         int i = s->fragment_start[plane] + (y>>3)*(s->fragment_width>>!!plane);
1410
1411         if (!s->flipped_image) stride = -stride;
1412
1413
1414         if(FFABS(stride) > 2048)
1415             return; //various tables are fixed size
1416
1417         /* for each fragment row in the slice (both of them)... */
1418         for (; y < slice_height; y += 8) {
1419
1420             /* for each fragment in a row... */
1421             for (x = 0; x < plane_width; x += 8, i++) {
1422                 int first_pixel = y*stride + x;
1423
1424                 if ((i < 0) || (i >= s->fragment_count)) {
1425                     av_log(s->avctx, AV_LOG_ERROR, "  vp3:render_slice(): bad fragment number (%d)\n", i);
1426                     return;
1427                 }
1428
1429                 /* transform if this block was coded */
1430                 if ((s->all_fragments[i].coding_method != MODE_COPY) &&
1431                     !((s->avctx->flags & CODEC_FLAG_GRAY) && plane)) {
1432
1433                     if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1434                         (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1435                         motion_source= golden_plane;
1436                     else
1437                         motion_source= last_plane;
1438
1439                     motion_source += first_pixel;
1440                     motion_halfpel_index = 0;
1441
1442                     /* sort out the motion vector if this fragment is coded
1443                      * using a motion vector method */
1444                     if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1445                         (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1446                         int src_x, src_y;
1447                         motion_x = s->all_fragments[i].motion_x;
1448                         motion_y = s->all_fragments[i].motion_y;
1449                         if(plane){
1450                             motion_x= (motion_x>>1) | (motion_x&1);
1451                             motion_y= (motion_y>>1) | (motion_y&1);
1452                         }
1453
1454                         src_x= (motion_x>>1) + x;
1455                         src_y= (motion_y>>1) + y;
1456                         if ((motion_x == 127) || (motion_y == 127))
1457                             av_log(s->avctx, AV_LOG_ERROR, " help! got invalid motion vector! (%X, %X)\n", motion_x, motion_y);
1458
1459                         motion_halfpel_index = motion_x & 0x01;
1460                         motion_source += (motion_x >> 1);
1461
1462                         motion_halfpel_index |= (motion_y & 0x01) << 1;
1463                         motion_source += ((motion_y >> 1) * stride);
1464
1465                         if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1466                             uint8_t *temp= s->edge_emu_buffer;
1467                             if(stride<0) temp -= 9*stride;
1468                             else temp += 9*stride;
1469
1470                             ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
1471                             motion_source= temp;
1472                         }
1473                     }
1474
1475
1476                     /* first, take care of copying a block from either the
1477                      * previous or the golden frame */
1478                     if (s->all_fragments[i].coding_method != MODE_INTRA) {
1479                         /* Note, it is possible to implement all MC cases with
1480                            put_no_rnd_pixels_l2 which would look more like the
1481                            VP3 source but this would be slower as
1482                            put_no_rnd_pixels_tab is better optimzed */
1483                         if(motion_halfpel_index != 3){
1484                             s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1485                                 output_plane + first_pixel,
1486                                 motion_source, stride, 8);
1487                         }else{
1488                             int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1489                             s->dsp.put_no_rnd_pixels_l2[1](
1490                                 output_plane + first_pixel,
1491                                 motion_source - d,
1492                                 motion_source + stride + 1 + d,
1493                                 stride, 8);
1494                         }
1495                         dequantizer = s->qmat[s->all_fragments[i].qpi][1][plane];
1496                     }else{
1497                         dequantizer = s->qmat[s->all_fragments[i].qpi][0][plane];
1498                     }
1499
1500                     /* dequantize the DCT coefficients */
1501                     if(s->avctx->idct_algo==FF_IDCT_VP3){
1502                         Coeff *coeff= s->coeffs + i;
1503                         s->dsp.clear_block(block);
1504                         while(coeff->next){
1505                             block[coeff->index]= coeff->coeff * dequantizer[coeff->index];
1506                             coeff= coeff->next;
1507                         }
1508                     }else{
1509                         Coeff *coeff= s->coeffs + i;
1510                         s->dsp.clear_block(block);
1511                         while(coeff->next){
1512                             block[coeff->index]= (coeff->coeff * dequantizer[coeff->index] + 2)>>2;
1513                             coeff= coeff->next;
1514                         }
1515                     }
1516
1517                     /* invert DCT and place (or add) in final output */
1518
1519                     if (s->all_fragments[i].coding_method == MODE_INTRA) {
1520                         if(s->avctx->idct_algo!=FF_IDCT_VP3)
1521                             block[0] += 128<<3;
1522                         s->dsp.idct_put(
1523                             output_plane + first_pixel,
1524                             stride,
1525                             block);
1526                     } else {
1527                         s->dsp.idct_add(
1528                             output_plane + first_pixel,
1529                             stride,
1530                             block);
1531                     }
1532                 } else {
1533
1534                     /* copy directly from the previous frame */
1535                     s->dsp.put_pixels_tab[1][0](
1536                         output_plane + first_pixel,
1537                         last_plane + first_pixel,
1538                         stride, 8);
1539
1540                 }
1541             }
1542             // Filter the previous block row. We can't filter the current row yet
1543             // since it needs pixels from the next row
1544             if (y > 0)
1545                 apply_loop_filter(s, plane, (y>>3)-1, (y>>3));
1546         }
1547     }
1548
1549      /* this looks like a good place for slice dispatch... */
1550      /* algorithm:
1551       *   if (slice == s->macroblock_height - 1)
1552       *     dispatch (both last slice & 2nd-to-last slice);
1553       *   else if (slice > 0)
1554       *     dispatch (slice - 1);
1555       */
1556
1557     // now that we've filtered the last rows, they're safe to display
1558     if (slice)
1559         vp3_draw_horiz_band(s, 16*slice);
1560 }
1561
1562 /*
1563  * This is the ffmpeg/libavcodec API init function.
1564  */
1565 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1566 {
1567     Vp3DecodeContext *s = avctx->priv_data;
1568     int i, inter, plane;
1569     int c_width;
1570     int c_height;
1571     int y_superblock_count;
1572     int c_superblock_count;
1573
1574     if (avctx->codec_tag == MKTAG('V','P','3','0'))
1575         s->version = 0;
1576     else
1577         s->version = 1;
1578
1579     s->avctx = avctx;
1580     s->width = FFALIGN(avctx->width, 16);
1581     s->height = FFALIGN(avctx->height, 16);
1582     avctx->pix_fmt = PIX_FMT_YUV420P;
1583     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1584     if(avctx->idct_algo==FF_IDCT_AUTO)
1585         avctx->idct_algo=FF_IDCT_VP3;
1586     dsputil_init(&s->dsp, avctx);
1587
1588     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
1589
1590     /* initialize to an impossible value which will force a recalculation
1591      * in the first frame decode */
1592     for (i = 0; i < 3; i++)
1593         s->qps[i] = -1;
1594
1595     s->y_superblock_width = (s->width + 31) / 32;
1596     s->y_superblock_height = (s->height + 31) / 32;
1597     y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1598
1599     /* work out the dimensions for the C planes */
1600     c_width = s->width / 2;
1601     c_height = s->height / 2;
1602     s->c_superblock_width = (c_width + 31) / 32;
1603     s->c_superblock_height = (c_height + 31) / 32;
1604     c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1605
1606     s->superblock_count = y_superblock_count + (c_superblock_count * 2);
1607     s->u_superblock_start = y_superblock_count;
1608     s->v_superblock_start = s->u_superblock_start + c_superblock_count;
1609     s->superblock_coding = av_malloc(s->superblock_count);
1610
1611     s->macroblock_width = (s->width + 15) / 16;
1612     s->macroblock_height = (s->height + 15) / 16;
1613     s->macroblock_count = s->macroblock_width * s->macroblock_height;
1614
1615     s->fragment_width = s->width / FRAGMENT_PIXELS;
1616     s->fragment_height = s->height / FRAGMENT_PIXELS;
1617
1618     /* fragment count covers all 8x8 blocks for all 3 planes */
1619     s->fragment_count = s->fragment_width * s->fragment_height * 3 / 2;
1620     s->fragment_start[1] = s->fragment_width * s->fragment_height;
1621     s->fragment_start[2] = s->fragment_width * s->fragment_height * 5 / 4;
1622
1623     s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
1624     s->coeff_counts = av_malloc(s->fragment_count * sizeof(*s->coeff_counts));
1625     s->coeffs = av_malloc(s->fragment_count * sizeof(Coeff) * 65);
1626     s->coded_fragment_list = av_malloc(s->fragment_count * sizeof(int));
1627     s->fast_fragment_list = av_malloc(s->fragment_count * sizeof(int));
1628     if (!s->superblock_coding || !s->all_fragments || !s->coeff_counts ||
1629         !s->coeffs || !s->coded_fragment_list || !s->fast_fragment_list) {
1630         vp3_decode_end(avctx);
1631         return -1;
1632     }
1633
1634     if (!s->theora_tables)
1635     {
1636         for (i = 0; i < 64; i++) {
1637             s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1638             s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1639             s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1640             s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1641             s->base_matrix[2][i] = vp31_inter_dequant[i];
1642             s->filter_limit_values[i] = vp31_filter_limit_values[i];
1643         }
1644
1645         for(inter=0; inter<2; inter++){
1646             for(plane=0; plane<3; plane++){
1647                 s->qr_count[inter][plane]= 1;
1648                 s->qr_size [inter][plane][0]= 63;
1649                 s->qr_base [inter][plane][0]=
1650                 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1651             }
1652         }
1653
1654         /* init VLC tables */
1655         for (i = 0; i < 16; i++) {
1656
1657             /* DC histograms */
1658             init_vlc(&s->dc_vlc[i], 5, 32,
1659                 &dc_bias[i][0][1], 4, 2,
1660                 &dc_bias[i][0][0], 4, 2, 0);
1661
1662             /* group 1 AC histograms */
1663             init_vlc(&s->ac_vlc_1[i], 5, 32,
1664                 &ac_bias_0[i][0][1], 4, 2,
1665                 &ac_bias_0[i][0][0], 4, 2, 0);
1666
1667             /* group 2 AC histograms */
1668             init_vlc(&s->ac_vlc_2[i], 5, 32,
1669                 &ac_bias_1[i][0][1], 4, 2,
1670                 &ac_bias_1[i][0][0], 4, 2, 0);
1671
1672             /* group 3 AC histograms */
1673             init_vlc(&s->ac_vlc_3[i], 5, 32,
1674                 &ac_bias_2[i][0][1], 4, 2,
1675                 &ac_bias_2[i][0][0], 4, 2, 0);
1676
1677             /* group 4 AC histograms */
1678             init_vlc(&s->ac_vlc_4[i], 5, 32,
1679                 &ac_bias_3[i][0][1], 4, 2,
1680                 &ac_bias_3[i][0][0], 4, 2, 0);
1681         }
1682     } else {
1683         for (i = 0; i < 16; i++) {
1684
1685             /* DC histograms */
1686             if (init_vlc(&s->dc_vlc[i], 5, 32,
1687                 &s->huffman_table[i][0][1], 4, 2,
1688                 &s->huffman_table[i][0][0], 4, 2, 0) < 0)
1689                 goto vlc_fail;
1690
1691             /* group 1 AC histograms */
1692             if (init_vlc(&s->ac_vlc_1[i], 5, 32,
1693                 &s->huffman_table[i+16][0][1], 4, 2,
1694                 &s->huffman_table[i+16][0][0], 4, 2, 0) < 0)
1695                 goto vlc_fail;
1696
1697             /* group 2 AC histograms */
1698             if (init_vlc(&s->ac_vlc_2[i], 5, 32,
1699                 &s->huffman_table[i+16*2][0][1], 4, 2,
1700                 &s->huffman_table[i+16*2][0][0], 4, 2, 0) < 0)
1701                 goto vlc_fail;
1702
1703             /* group 3 AC histograms */
1704             if (init_vlc(&s->ac_vlc_3[i], 5, 32,
1705                 &s->huffman_table[i+16*3][0][1], 4, 2,
1706                 &s->huffman_table[i+16*3][0][0], 4, 2, 0) < 0)
1707                 goto vlc_fail;
1708
1709             /* group 4 AC histograms */
1710             if (init_vlc(&s->ac_vlc_4[i], 5, 32,
1711                 &s->huffman_table[i+16*4][0][1], 4, 2,
1712                 &s->huffman_table[i+16*4][0][0], 4, 2, 0) < 0)
1713                 goto vlc_fail;
1714         }
1715     }
1716
1717     init_vlc(&s->superblock_run_length_vlc, 6, 34,
1718         &superblock_run_length_vlc_table[0][1], 4, 2,
1719         &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1720
1721     init_vlc(&s->fragment_run_length_vlc, 5, 30,
1722         &fragment_run_length_vlc_table[0][1], 4, 2,
1723         &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1724
1725     init_vlc(&s->mode_code_vlc, 3, 8,
1726         &mode_code_vlc_table[0][1], 2, 1,
1727         &mode_code_vlc_table[0][0], 2, 1, 0);
1728
1729     init_vlc(&s->motion_vector_vlc, 6, 63,
1730         &motion_vector_vlc_table[0][1], 2, 1,
1731         &motion_vector_vlc_table[0][0], 2, 1, 0);
1732
1733     /* work out the block mapping tables */
1734     s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
1735     s->macroblock_coding = av_malloc(s->macroblock_count + 1);
1736     if (!s->superblock_fragments || !s->macroblock_coding) {
1737         vp3_decode_end(avctx);
1738         return -1;
1739     }
1740     init_block_mapping(s);
1741
1742     for (i = 0; i < 3; i++) {
1743         s->current_frame.data[i] = NULL;
1744         s->last_frame.data[i] = NULL;
1745         s->golden_frame.data[i] = NULL;
1746     }
1747
1748     return 0;
1749
1750 vlc_fail:
1751     av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1752     return -1;
1753 }
1754
1755 /*
1756  * This is the ffmpeg/libavcodec API frame decode function.
1757  */
1758 static int vp3_decode_frame(AVCodecContext *avctx,
1759                             void *data, int *data_size,
1760                             AVPacket *avpkt)
1761 {
1762     const uint8_t *buf = avpkt->data;
1763     int buf_size = avpkt->size;
1764     Vp3DecodeContext *s = avctx->priv_data;
1765     GetBitContext gb;
1766     static int counter = 0;
1767     int i;
1768
1769     init_get_bits(&gb, buf, buf_size * 8);
1770
1771     if (s->theora && get_bits1(&gb))
1772     {
1773         av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1774         return -1;
1775     }
1776
1777     s->keyframe = !get_bits1(&gb);
1778     if (!s->theora)
1779         skip_bits(&gb, 1);
1780     for (i = 0; i < 3; i++)
1781         s->last_qps[i] = s->qps[i];
1782
1783     s->nqps=0;
1784     do{
1785         s->qps[s->nqps++]= get_bits(&gb, 6);
1786     } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
1787     for (i = s->nqps; i < 3; i++)
1788         s->qps[i] = -1;
1789
1790     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1791         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
1792             s->keyframe?"key":"", counter, s->qps[0]);
1793     counter++;
1794
1795     if (s->qps[0] != s->last_qps[0])
1796         init_loop_filter(s);
1797
1798     for (i = 0; i < s->nqps; i++)
1799         // reinit all dequantizers if the first one changed, because
1800         // the DC of the first quantizer must be used for all matrices
1801         if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
1802             init_dequantizer(s, i);
1803
1804     if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
1805         return buf_size;
1806
1807     if (s->keyframe) {
1808         if (!s->theora)
1809         {
1810             skip_bits(&gb, 4); /* width code */
1811             skip_bits(&gb, 4); /* height code */
1812             if (s->version)
1813             {
1814                 s->version = get_bits(&gb, 5);
1815                 if (counter == 1)
1816                     av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
1817             }
1818         }
1819         if (s->version || s->theora)
1820         {
1821                 if (get_bits1(&gb))
1822                     av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
1823             skip_bits(&gb, 2); /* reserved? */
1824         }
1825
1826         if (s->last_frame.data[0] == s->golden_frame.data[0]) {
1827             if (s->golden_frame.data[0])
1828                 avctx->release_buffer(avctx, &s->golden_frame);
1829             s->last_frame= s->golden_frame; /* ensure that we catch any access to this released frame */
1830         } else {
1831             if (s->golden_frame.data[0])
1832                 avctx->release_buffer(avctx, &s->golden_frame);
1833             if (s->last_frame.data[0])
1834                 avctx->release_buffer(avctx, &s->last_frame);
1835         }
1836
1837         s->golden_frame.reference = 3;
1838         if(avctx->get_buffer(avctx, &s->golden_frame) < 0) {
1839             av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");
1840             return -1;
1841         }
1842
1843         /* golden frame is also the current frame */
1844         s->current_frame= s->golden_frame;
1845     } else {
1846         /* allocate a new current frame */
1847         s->current_frame.reference = 3;
1848         if (!s->golden_frame.data[0]) {
1849             av_log(s->avctx, AV_LOG_ERROR, "vp3: first frame not a keyframe\n");
1850             return -1;
1851         }
1852         if(avctx->get_buffer(avctx, &s->current_frame) < 0) {
1853             av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");
1854             return -1;
1855         }
1856     }
1857
1858     s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
1859     s->current_frame.qstride= 0;
1860
1861     init_frame(s, &gb);
1862
1863     if (unpack_superblocks(s, &gb)){
1864         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
1865         return -1;
1866     }
1867     if (unpack_modes(s, &gb)){
1868         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
1869         return -1;
1870     }
1871     if (unpack_vectors(s, &gb)){
1872         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
1873         return -1;
1874     }
1875     if (unpack_block_qpis(s, &gb)){
1876         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
1877         return -1;
1878     }
1879     if (unpack_dct_coeffs(s, &gb)){
1880         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
1881         return -1;
1882     }
1883
1884     for (i = 0; i < 3; i++) {
1885         if (s->flipped_image)
1886             s->data_offset[i] = 0;
1887         else
1888             s->data_offset[i] = ((s->height>>!!i)-1) * s->current_frame.linesize[i];
1889     }
1890
1891     s->last_slice_end = 0;
1892     for (i = 0; i < s->macroblock_height; i++)
1893         render_slice(s, i);
1894
1895     // filter the last row
1896     for (i = 0; i < 3; i++) {
1897         int row = (s->height >> (3+!!i)) - 1;
1898         apply_loop_filter(s, i, row, row+1);
1899     }
1900     vp3_draw_horiz_band(s, s->height);
1901
1902     *data_size=sizeof(AVFrame);
1903     *(AVFrame*)data= s->current_frame;
1904
1905     /* release the last frame, if it is allocated and if it is not the
1906      * golden frame */
1907     if ((s->last_frame.data[0]) &&
1908         (s->last_frame.data[0] != s->golden_frame.data[0]))
1909         avctx->release_buffer(avctx, &s->last_frame);
1910
1911     /* shuffle frames (last = current) */
1912     s->last_frame= s->current_frame;
1913     s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
1914
1915     return buf_size;
1916 }
1917
1918 /*
1919  * This is the ffmpeg/libavcodec API module cleanup function.
1920  */
1921 static av_cold int vp3_decode_end(AVCodecContext *avctx)
1922 {
1923     Vp3DecodeContext *s = avctx->priv_data;
1924     int i;
1925
1926     av_free(s->superblock_coding);
1927     av_free(s->all_fragments);
1928     av_free(s->coeff_counts);
1929     av_free(s->coeffs);
1930     av_free(s->coded_fragment_list);
1931     av_free(s->fast_fragment_list);
1932     av_free(s->superblock_fragments);
1933     av_free(s->macroblock_coding);
1934
1935     for (i = 0; i < 16; i++) {
1936         free_vlc(&s->dc_vlc[i]);
1937         free_vlc(&s->ac_vlc_1[i]);
1938         free_vlc(&s->ac_vlc_2[i]);
1939         free_vlc(&s->ac_vlc_3[i]);
1940         free_vlc(&s->ac_vlc_4[i]);
1941     }
1942
1943     free_vlc(&s->superblock_run_length_vlc);
1944     free_vlc(&s->fragment_run_length_vlc);
1945     free_vlc(&s->mode_code_vlc);
1946     free_vlc(&s->motion_vector_vlc);
1947
1948     /* release all frames */
1949     if (s->golden_frame.data[0] && s->golden_frame.data[0] != s->last_frame.data[0])
1950         avctx->release_buffer(avctx, &s->golden_frame);
1951     if (s->last_frame.data[0])
1952         avctx->release_buffer(avctx, &s->last_frame);
1953     /* no need to release the current_frame since it will always be pointing
1954      * to the same frame as either the golden or last frame */
1955
1956     return 0;
1957 }
1958
1959 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
1960 {
1961     Vp3DecodeContext *s = avctx->priv_data;
1962
1963     if (get_bits1(gb)) {
1964         int token;
1965         if (s->entries >= 32) { /* overflow */
1966             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1967             return -1;
1968         }
1969         token = get_bits(gb, 5);
1970         //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);
1971         s->huffman_table[s->hti][token][0] = s->hbits;
1972         s->huffman_table[s->hti][token][1] = s->huff_code_size;
1973         s->entries++;
1974     }
1975     else {
1976         if (s->huff_code_size >= 32) {/* overflow */
1977             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1978             return -1;
1979         }
1980         s->huff_code_size++;
1981         s->hbits <<= 1;
1982         if (read_huffman_tree(avctx, gb))
1983             return -1;
1984         s->hbits |= 1;
1985         if (read_huffman_tree(avctx, gb))
1986             return -1;
1987         s->hbits >>= 1;
1988         s->huff_code_size--;
1989     }
1990     return 0;
1991 }
1992
1993 #if CONFIG_THEORA_DECODER
1994 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
1995 {
1996     Vp3DecodeContext *s = avctx->priv_data;
1997     int visible_width, visible_height, colorspace;
1998
1999     s->theora = get_bits_long(gb, 24);
2000     av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2001
2002     /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
2003     /* but previous versions have the image flipped relative to vp3 */
2004     if (s->theora < 0x030200)
2005     {
2006         s->flipped_image = 1;
2007         av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
2008     }
2009
2010     visible_width  = s->width  = get_bits(gb, 16) << 4;
2011     visible_height = s->height = get_bits(gb, 16) << 4;
2012
2013     if(avcodec_check_dimensions(avctx, s->width, s->height)){
2014         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
2015         s->width= s->height= 0;
2016         return -1;
2017     }
2018
2019     if (s->theora >= 0x030200) {
2020         visible_width  = get_bits_long(gb, 24);
2021         visible_height = get_bits_long(gb, 24);
2022
2023         skip_bits(gb, 8); /* offset x */
2024         skip_bits(gb, 8); /* offset y */
2025     }
2026
2027     skip_bits(gb, 32); /* fps numerator */
2028     skip_bits(gb, 32); /* fps denumerator */
2029     skip_bits(gb, 24); /* aspect numerator */
2030     skip_bits(gb, 24); /* aspect denumerator */
2031
2032     if (s->theora < 0x030200)
2033         skip_bits(gb, 5); /* keyframe frequency force */
2034     colorspace = get_bits(gb, 8);
2035     skip_bits(gb, 24); /* bitrate */
2036
2037     skip_bits(gb, 6); /* quality hint */
2038
2039     if (s->theora >= 0x030200)
2040     {
2041         skip_bits(gb, 5); /* keyframe frequency force */
2042         skip_bits(gb, 2); /* pixel format: 420,res,422,444 */
2043         skip_bits(gb, 3); /* reserved */
2044     }
2045
2046 //    align_get_bits(gb);
2047
2048     if (   visible_width  <= s->width  && visible_width  > s->width-16
2049         && visible_height <= s->height && visible_height > s->height-16)
2050         avcodec_set_dimensions(avctx, visible_width, visible_height);
2051     else
2052         avcodec_set_dimensions(avctx, s->width, s->height);
2053
2054     if (colorspace == 1) {
2055         avctx->color_primaries = AVCOL_PRI_BT470M;
2056     } else if (colorspace == 2) {
2057         avctx->color_primaries = AVCOL_PRI_BT470BG;
2058     }
2059     if (colorspace == 1 || colorspace == 2) {
2060         avctx->colorspace = AVCOL_SPC_BT470BG;
2061         avctx->color_trc  = AVCOL_TRC_BT709;
2062     }
2063
2064     return 0;
2065 }
2066
2067 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2068 {
2069     Vp3DecodeContext *s = avctx->priv_data;
2070     int i, n, matrices, inter, plane;
2071
2072     if (s->theora >= 0x030200) {
2073         n = get_bits(gb, 3);
2074         /* loop filter limit values table */
2075         for (i = 0; i < 64; i++) {
2076             s->filter_limit_values[i] = get_bits(gb, n);
2077             if (s->filter_limit_values[i] > 127) {
2078                 av_log(avctx, AV_LOG_ERROR, "filter limit value too large (%i > 127), clamping\n", s->filter_limit_values[i]);
2079                 s->filter_limit_values[i] = 127;
2080             }
2081         }
2082     }
2083
2084     if (s->theora >= 0x030200)
2085         n = get_bits(gb, 4) + 1;
2086     else
2087         n = 16;
2088     /* quality threshold table */
2089     for (i = 0; i < 64; i++)
2090         s->coded_ac_scale_factor[i] = get_bits(gb, n);
2091
2092     if (s->theora >= 0x030200)
2093         n = get_bits(gb, 4) + 1;
2094     else
2095         n = 16;
2096     /* dc scale factor table */
2097     for (i = 0; i < 64; i++)
2098         s->coded_dc_scale_factor[i] = get_bits(gb, n);
2099
2100     if (s->theora >= 0x030200)
2101         matrices = get_bits(gb, 9) + 1;
2102     else
2103         matrices = 3;
2104
2105     if(matrices > 384){
2106         av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2107         return -1;
2108     }
2109
2110     for(n=0; n<matrices; n++){
2111         for (i = 0; i < 64; i++)
2112             s->base_matrix[n][i]= get_bits(gb, 8);
2113     }
2114
2115     for (inter = 0; inter <= 1; inter++) {
2116         for (plane = 0; plane <= 2; plane++) {
2117             int newqr= 1;
2118             if (inter || plane > 0)
2119                 newqr = get_bits1(gb);
2120             if (!newqr) {
2121                 int qtj, plj;
2122                 if(inter && get_bits1(gb)){
2123                     qtj = 0;
2124                     plj = plane;
2125                 }else{
2126                     qtj= (3*inter + plane - 1) / 3;
2127                     plj= (plane + 2) % 3;
2128                 }
2129                 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2130                 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2131                 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2132             } else {
2133                 int qri= 0;
2134                 int qi = 0;
2135
2136                 for(;;){
2137                     i= get_bits(gb, av_log2(matrices-1)+1);
2138                     if(i>= matrices){
2139                         av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2140                         return -1;
2141                     }
2142                     s->qr_base[inter][plane][qri]= i;
2143                     if(qi >= 63)
2144                         break;
2145                     i = get_bits(gb, av_log2(63-qi)+1) + 1;
2146                     s->qr_size[inter][plane][qri++]= i;
2147                     qi += i;
2148                 }
2149
2150                 if (qi > 63) {
2151                     av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2152                     return -1;
2153                 }
2154                 s->qr_count[inter][plane]= qri;
2155             }
2156         }
2157     }
2158
2159     /* Huffman tables */
2160     for (s->hti = 0; s->hti < 80; s->hti++) {
2161         s->entries = 0;
2162         s->huff_code_size = 1;
2163         if (!get_bits1(gb)) {
2164             s->hbits = 0;
2165             if(read_huffman_tree(avctx, gb))
2166                 return -1;
2167             s->hbits = 1;
2168             if(read_huffman_tree(avctx, gb))
2169                 return -1;
2170         }
2171     }
2172
2173     s->theora_tables = 1;
2174
2175     return 0;
2176 }
2177
2178 static av_cold int theora_decode_init(AVCodecContext *avctx)
2179 {
2180     Vp3DecodeContext *s = avctx->priv_data;
2181     GetBitContext gb;
2182     int ptype;
2183     uint8_t *header_start[3];
2184     int header_len[3];
2185     int i;
2186
2187     s->theora = 1;
2188
2189     if (!avctx->extradata_size)
2190     {
2191         av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2192         return -1;
2193     }
2194
2195     if (ff_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2196                               42, header_start, header_len) < 0) {
2197         av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2198         return -1;
2199     }
2200
2201   for(i=0;i<3;i++) {
2202     init_get_bits(&gb, header_start[i], header_len[i] * 8);
2203
2204     ptype = get_bits(&gb, 8);
2205
2206      if (!(ptype & 0x80))
2207      {
2208         av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2209 //        return -1;
2210      }
2211
2212     // FIXME: Check for this as well.
2213     skip_bits_long(&gb, 6*8); /* "theora" */
2214
2215     switch(ptype)
2216     {
2217         case 0x80:
2218             theora_decode_header(avctx, &gb);
2219                 break;
2220         case 0x81:
2221 // FIXME: is this needed? it breaks sometimes
2222 //            theora_decode_comments(avctx, gb);
2223             break;
2224         case 0x82:
2225             if (theora_decode_tables(avctx, &gb))
2226                 return -1;
2227             break;
2228         default:
2229             av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2230             break;
2231     }
2232     if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2233         av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2234     if (s->theora < 0x030200)
2235         break;
2236   }
2237
2238     return vp3_decode_init(avctx);
2239 }
2240
2241 AVCodec theora_decoder = {
2242     "theora",
2243     CODEC_TYPE_VIDEO,
2244     CODEC_ID_THEORA,
2245     sizeof(Vp3DecodeContext),
2246     theora_decode_init,
2247     NULL,
2248     vp3_decode_end,
2249     vp3_decode_frame,
2250     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2251     NULL,
2252     .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2253 };
2254 #endif
2255
2256 AVCodec vp3_decoder = {
2257     "vp3",
2258     CODEC_TYPE_VIDEO,
2259     CODEC_ID_VP3,
2260     sizeof(Vp3DecodeContext),
2261     vp3_decode_init,
2262     NULL,
2263     vp3_decode_end,
2264     vp3_decode_frame,
2265     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2266     NULL,
2267     .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2268 };