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