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