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