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