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