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