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