2 * Copyright (c) 2003-2004 The FFmpeg Project
4 * This file is part of FFmpeg.
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.
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.
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
23 * On2 VP3 Video Decoder
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
29 * Theora decoder by Alex Beregszaszi
36 #include "libavutil/imgutils.h"
49 #define FRAGMENT_PIXELS 8
51 // FIXME split things out into their own arrays
52 typedef struct Vp3Fragment {
54 uint8_t coding_method;
58 #define SB_NOT_CODED 0
59 #define SB_PARTIALLY_CODED 1
60 #define SB_FULLY_CODED 2
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
67 #define MODE_INTER_NO_MV 0
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
77 /* special internal mode */
80 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
81 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
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 },
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 },
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 },
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 },
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 },
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 },
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 }
130 #define MIN_DEQUANT_VAL 2
132 typedef struct Vp3DecodeContext {
133 AVCodecContext *avctx;
134 int theora, theora_tables;
137 int chroma_x_shift, chroma_y_shift;
138 ThreadFrame golden_frame;
139 ThreadFrame last_frame;
140 ThreadFrame current_frame;
142 uint8_t idct_permutation[64];
143 uint8_t idct_scantable[64];
145 VideoDSPContext vdsp;
146 VP3DSPContext vp3dsp;
147 DECLARE_ALIGNED(16, int16_t, block)[64];
150 int skip_loop_filter;
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;
167 int macroblock_count;
168 int macroblock_width;
169 int macroblock_height;
172 int fragment_width[2];
173 int fragment_height[2];
175 Vp3Fragment *all_fragments;
176 int fragment_start[3];
181 int8_t (*motion_val[2])[2];
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];
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)
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)
205 * Coefficients are signed, so are packed in the highest bits for automatic
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)
215 * number of blocks that contain DCT coefficients at
216 * the given level or higher
218 int num_coded_frags[3][64];
219 int total_num_coded_frags;
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];
231 VLC superblock_run_length_vlc;
232 VLC fragment_run_length_vlc;
234 VLC motion_vector_vlc;
236 /* these arrays need to be on 16-byte boundaries since SSE2 operations
238 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
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
244 int *superblock_fragments;
246 /* This is an array that indicates how a particular macroblock
248 unsigned char *macroblock_coding;
250 uint8_t *edge_emu_buffer;
257 uint32_t huffman_table[80][32][2];
259 uint8_t filter_limit_values[64];
260 DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
263 /************************************************************************
264 * VP3 specific functions
265 ************************************************************************/
267 static av_cold void free_tables(AVCodecContext *avctx)
269 Vp3DecodeContext *s = avctx->priv_data;
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]);
281 static void vp3_decode_flush(AVCodecContext *avctx)
283 Vp3DecodeContext *s = avctx->priv_data;
285 if (s->golden_frame.f)
286 ff_thread_release_buffer(avctx, &s->golden_frame);
288 ff_thread_release_buffer(avctx, &s->last_frame);
289 if (s->current_frame.f)
290 ff_thread_release_buffer(avctx, &s->current_frame);
293 static av_cold int vp3_decode_end(AVCodecContext *avctx)
295 Vp3DecodeContext *s = avctx->priv_data;
299 av_freep(&s->edge_emu_buffer);
301 s->theora_tables = 0;
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);
309 if (avctx->internal->is_copy)
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]);
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);
329 * This function sets up all of the various blocks mappings:
330 * superblocks <-> fragments, macroblocks <-> fragments,
331 * superblocks <-> macroblocks
333 * @return 0 is successful; returns 1 if *anything* went wrong.
335 static int init_block_mapping(Vp3DecodeContext *s)
337 int sb_x, sb_y, plane;
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];
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];
354 if (x < frag_width && y < frag_height)
355 s->superblock_fragments[j++] = s->fragment_start[plane] +
358 s->superblock_fragments[j++] = -1;
362 return 0; /* successful path out */
366 * This function sets up the dequantization tables used for a particular
369 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
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;
375 for (inter = 0; inter < 2; inter++) {
376 for (plane = 0; plane < 3; plane++) {
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)
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]);
392 int qmin = 8 << (inter + !i);
393 int qscale = i ? ac_scale_factor : dc_scale_factor;
395 s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
396 av_clip((qscale * coeff) / 100 * 4, qmin, 4096);
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];
406 * This function initializes the loop filter boundary limits if the frame's
407 * quality index is different from the previous frame's.
409 * The filter_limit_values may not be larger than 127.
411 static void init_loop_filter(Vp3DecodeContext *s)
413 int *bounding_values = s->bounding_values_array + 127;
418 filter_limit = s->filter_limit_values[s->qps[0]];
419 av_assert0(filter_limit < 128U);
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;
427 for (x = value = filter_limit; x < 128 && value; x++, value--) {
428 bounding_values[ x] = value;
429 bounding_values[-x] = -value;
432 bounding_values[128] = value;
433 bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
437 * This function unpacks all of the superblock/macroblock/fragment coding
438 * information from the bitstream.
440 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
442 int superblock_starts[3] = {
443 0, s->u_superblock_start, s->v_superblock_start
446 int current_superblock = 0;
448 int num_partial_superblocks = 0;
451 int current_fragment;
455 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
457 /* unpack the list of partially-coded superblocks */
458 bit = get_bits1(gb) ^ 1;
461 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
462 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
467 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
469 if (current_run == 34)
470 current_run += get_bits(gb, 12);
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");
478 memset(s->superblock_coding + current_superblock, bit, current_run);
480 current_superblock += current_run;
482 num_partial_superblocks += current_run;
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;
490 current_superblock = 0;
491 bit = get_bits1(gb) ^ 1;
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)
501 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
503 if (current_run == 34)
504 current_run += get_bits(gb, 12);
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");
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;
519 superblocks_decoded += current_run;
523 /* if there were partial blocks, initialize bitstream for
524 * unpacking fragment codings */
525 if (num_partial_superblocks) {
528 /* toggle the bit because as soon as the first run length is
529 * fetched the bit will be toggled again */
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);
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;
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];
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) {
558 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
564 /* default mode; actual mode will be decoded in
566 s->all_fragments[current_fragment].coding_method =
568 s->coded_fragment_list[plane][num_coded_frags++] =
571 /* not coded; copy this fragment from the prior frame */
572 s->all_fragments[current_fragment].coding_method =
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;
582 s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
589 * This function unpacks all the coding mode data for individual macroblocks
590 * from the bitstream.
592 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
594 int i, j, k, sb_x, sb_y;
596 int current_macroblock;
597 int current_fragment;
599 int custom_mode_alphabet[CODING_MODE_COUNT];
604 for (i = 0; i < s->fragment_count; i++)
605 s->all_fragments[i].coding_method = MODE_INTRA;
607 /* fetch the mode coding scheme for this frame */
608 scheme = get_bits(gb, 3);
610 /* is it a custom coding scheme? */
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;
618 alphabet = ModeAlphabet[scheme - 1];
620 /* iterate through all of the macroblocks that contain 1 or more
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)
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;
632 if (mb_x >= s->macroblock_width ||
633 mb_y >= s->macroblock_height)
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
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)
648 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
652 /* mode 7 means get 3 bits for each coding mode */
654 coding_mode = get_bits(gb, 3);
656 coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
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;
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;
671 if (s->chroma_y_shift) {
672 frag = s->all_fragments + mb_y *
673 s->fragment_width[1] + mb_x;
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++) {
680 frag += s->fragment_width[1];
683 for (k = 0; k < 4; k++) {
684 frag = s->all_fragments +
685 BLOCK_Y * s->fragment_width[1] + BLOCK_X;
698 * This function unpacks all the motion vectors for the individual
699 * macroblocks from the bitstream.
701 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
703 int j, k, sb_x, sb_y;
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;
718 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
719 coding_mode = get_bits1(gb);
721 /* iterate through all of the macroblocks that contain 1 or more
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)
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;
733 if (mb_x >= s->macroblock_width ||
734 mb_y >= s->macroblock_height ||
735 s->macroblock_coding[current_macroblock] == MODE_COPY)
738 switch (s->macroblock_coding[current_macroblock]) {
739 case MODE_INTER_PLUS_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)];
746 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
747 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
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];
759 case MODE_INTER_FOURMV:
760 /* vector maintenance */
761 prior_last_motion_x = last_motion_x;
762 prior_last_motion_y = last_motion_y;
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)];
773 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
774 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
776 last_motion_x = motion_x[k];
777 last_motion_y = motion_y[k];
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;
790 /* no vector maintenance (last vector remains the
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;
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];
808 /* covers intra, inter without MV, golden without MV */
812 /* no vector maintenance */
816 /* assign the motion vectors to the correct fragments */
817 for (k = 0; k < 4; k++) {
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];
824 s->motion_val[0][current_fragment][0] = motion_x[0];
825 s->motion_val[0][current_fragment][1] = motion_y[0];
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);
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);
848 motion_x[1] = motion_x[0];
849 motion_y[1] = motion_y[0];
851 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
852 motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
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];
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];
867 s->motion_val[1][frag][0] = motion_x[0];
868 s->motion_val[1][frag][1] = motion_y[0];
879 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
881 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
882 int num_blocks = s->total_num_coded_frags;
884 for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
885 i = blocks_decoded = num_blocks_at_qpi = 0;
887 bit = get_bits1(gb) ^ 1;
891 if (run_length == MAXIMUM_LONG_BIT_RUN)
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;
902 num_blocks_at_qpi += run_length;
904 for (j = 0; j < run_length; i++) {
905 if (i >= s->total_num_coded_frags)
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;
913 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
915 num_blocks -= num_blocks_at_qpi;
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.
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.
933 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
934 VLC *table, int coeff_index,
945 int num_coeffs = s->num_coded_frags[plane][coeff_index];
946 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
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;
954 av_log(s->avctx, AV_LOG_ERROR,
955 "Invalid number of coefficents at level %d\n", coeff_index);
957 if (eob_run > num_coeffs) {
959 blocks_ended = num_coeffs;
960 eob_run -= num_coeffs;
963 blocks_ended = eob_run;
967 // insert fake EOB token to cover the split between planes or zzi
969 dct_tokens[j++] = blocks_ended << 2;
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]);
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;
988 dct_tokens[j++] = TOKEN_EOB(eob_run);
989 blocks_ended += eob_run;
993 } else if (token >= 0) {
994 bits_to_get = coeff_get_bits[token];
996 bits_to_get = get_bits(gb, bits_to_get);
997 coeff = coeff_tables[token][bits_to_get];
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]);
1004 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
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.
1011 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1013 dct_tokens[j++] = TOKEN_COEFF(coeff);
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;
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]--;
1029 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
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");
1037 // decrement the number of blocks that have higher coefficients for each
1038 // EOB run at this level
1040 for (i = coeff_index + 1; i < 64; i++)
1041 s->num_coded_frags[plane][i] -= blocks_ended;
1043 // setup the next buffer
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;
1052 static void reverse_dc_prediction(Vp3DecodeContext *s,
1055 int fragment_height);
1057 * This function unpacks all of the DCT coefficient data from the
1060 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1067 int residual_eob_run = 0;
1071 s->dct_tokens[0][0] = s->dct_tokens_base;
1073 /* fetch the DC table indexes */
1074 dc_y_table = get_bits(gb, 4);
1075 dc_c_table = get_bits(gb, 4);
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;
1083 /* reverse prediction of the Y-plane DC coefficients */
1084 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
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;
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]);
1104 /* fetch the AC table indexes */
1105 ac_y_table = get_bits(gb, 4);
1106 ac_c_table = get_bits(gb, 4);
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];
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];
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];
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];
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;
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;
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
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
1155 static void reverse_dc_prediction(Vp3DecodeContext *s,
1158 int fragment_height)
1166 int i = first_fragment;
1170 /* DC values for the left, up-left, up, and up-right fragments */
1171 int vl, vul, vu, vur;
1173 /* indexes for the left, up-left, up, and up-right fragments */
1177 * The 6 fields mean:
1178 * 0: up-left multiplier
1180 * 2: up-right multiplier
1181 * 3: left multiplier
1183 static const int predictor_transform[16][4] = {
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
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 */
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 */
1219 int current_frame_type;
1221 /* there is a last DC predictor for each of the 3 frame types */
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++) {
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];
1248 if (COMPATIBLE_FRAME(l))
1252 u = i - fragment_width;
1254 if (COMPATIBLE_FRAME(u))
1257 ul = i - fragment_width - 1;
1259 if (COMPATIBLE_FRAME(ul))
1262 if (x + 1 < fragment_width) {
1263 ur = i - fragment_width + 1;
1265 if (COMPATIBLE_FRAME(ur))
1270 if (transform == 0) {
1271 /* if there were no fragments to predict from, use last
1273 predicted_dc = last_dc[current_frame_type];
1275 /* apply the appropriate predictor transform */
1277 (predictor_transform[transform][0] * vul) +
1278 (predictor_transform[transform][1] * vu) +
1279 (predictor_transform[transform][2] * vur) +
1280 (predictor_transform[transform][3] * vl);
1282 predicted_dc /= 128;
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)
1289 else if (FFABS(predicted_dc - vl) > 128)
1291 else if (FFABS(predicted_dc - vul) > 128)
1296 /* at long last, apply the predictor */
1297 DC_COEFF(i) += predicted_dc;
1299 last_dc[current_frame_type] = DC_COEFF(i);
1305 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1306 int ystart, int yend)
1309 int *bounding_values = s->bounding_values_array + 127;
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)
1318 plane_data += s->data_offset[plane] + 8 * ystart * stride;
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 */
1329 s->vp3dsp.h_loop_filter(
1331 stride, bounding_values);
1334 /* do not perform top edge filter for top row fragments */
1336 s->vp3dsp.v_loop_filter(
1338 stride, bounding_values);
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);
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);
1364 plane_data += 8 * stride;
1369 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1370 * for the next block in coding order
1372 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1373 int plane, int inter, int16_t block[64])
1375 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1376 uint8_t *perm = s->idct_scantable;
1380 int token = *s->dct_tokens[plane][i];
1381 switch (token & 3) {
1383 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1384 s->dct_tokens[plane][i]++;
1386 *s->dct_tokens[plane][i] = token & ~3;
1389 s->dct_tokens[plane][i]++;
1390 i += (token >> 2) & 0x7f;
1392 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1395 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1399 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1400 s->dct_tokens[plane][i++]++;
1402 default: // shouldn't happen
1406 // return value is expected to be a valid level
1409 // the actual DC+prediction is in the fragment structure
1410 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1415 * called when all pixels up to row y are complete
1417 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1420 int offset[AV_NUM_DATA_POINTERS];
1422 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1423 int y_flipped = s->flipped_image ? s->height - y : y;
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
1434 if (!s->avctx->draw_horiz_band)
1437 h = y - s->last_slice_end;
1438 s->last_slice_end = y;
1441 if (!s->flipped_image)
1442 y = s->height - y - h;
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++)
1452 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1456 * Wait for the reference frame of the current fragment.
1457 * The progress value is in luma pixel rows.
1459 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1460 int motion_y, int y)
1462 ThreadFrame *ref_frame;
1464 int border = motion_y & 1;
1466 if (fragment->coding_method == MODE_USING_GOLDEN ||
1467 fragment->coding_method == MODE_GOLDEN_MV)
1468 ref_frame = &s->golden_frame;
1470 ref_frame = &s->last_frame;
1472 ref_row = y + (motion_y >> 1);
1473 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1475 ff_thread_await_progress(ref_frame, ref_row, 0);
1479 * Perform the final rendering for a particular slice of data.
1480 * The slice number ranges from 0..(c_superblock_height - 1).
1482 static void render_slice(Vp3DecodeContext *s, int slice)
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;
1491 if (slice >= s->c_superblock_height)
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];
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;
1511 int fragment_width = s->fragment_width[!!plane];
1512 int fragment_height = s->fragment_height[!!plane];
1513 int fragment_start = s->fragment_start[plane];
1515 int do_await = !plane && HAVE_THREADS &&
1516 (s->avctx->active_thread_type & FF_THREAD_FRAME);
1518 if (!s->flipped_image)
1520 if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
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;
1533 i = fragment_start + fragment;
1536 if (x >= fragment_width || y >= fragment_height)
1539 first_pixel = 8 * y * stride + 8 * x;
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);
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;
1553 motion_source = last_plane;
1555 motion_source += first_pixel;
1556 motion_halfpel_index = 0;
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)) {
1563 motion_x = motion_val[fragment][0];
1564 motion_y = motion_val[fragment][1];
1566 src_x = (motion_x >> 1) + 8 * x;
1567 src_y = (motion_y >> 1) + 8 * y;
1569 motion_halfpel_index = motion_x & 0x01;
1570 motion_source += (motion_x >> 1);
1572 motion_halfpel_index |= (motion_y & 0x01) << 1;
1573 motion_source += ((motion_y >> 1) * stride);
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;
1582 s->vdsp.emulated_edge_mc(temp, motion_source,
1587 motion_source = temp;
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);
1603 /* d is 0 if motion_x and _y have the same sign,
1605 int d = (motion_x ^ motion_y) >> 31;
1606 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
1608 motion_source + stride + 1 + d,
1613 /* invert DCT and place (or add) in final output */
1615 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1616 vp3_dequant(s, s->all_fragments + i,
1618 s->vp3dsp.idct_put(output_plane + first_pixel,
1622 if (vp3_dequant(s, s->all_fragments + i,
1624 s->vp3dsp.idct_add(output_plane + first_pixel,
1628 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
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,
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));
1649 /* this looks like a good place for slice dispatch... */
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);
1657 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
1661 /// Allocate tables for per-frame data in Vp3DecodeContext
1662 static av_cold int allocate_tables(AVCodecContext *avctx)
1664 Vp3DecodeContext *s = avctx->priv_data;
1665 int y_fragment_count, c_fragment_count;
1669 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1670 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1672 s->superblock_coding = av_mallocz(s->superblock_count);
1673 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
1675 s->coded_fragment_list[0] = av_mallocz_array(s->fragment_count, sizeof(int));
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]));
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);
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);
1694 init_block_mapping(s);
1699 static av_cold int init_frames(Vp3DecodeContext *s)
1701 s->current_frame.f = av_frame_alloc();
1702 s->last_frame.f = av_frame_alloc();
1703 s->golden_frame.f = av_frame_alloc();
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);
1715 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1717 Vp3DecodeContext *s = avctx->priv_data;
1718 int i, inter, plane, ret;
1721 int y_fragment_count, c_fragment_count;
1723 ret = init_frames(s);
1727 avctx->internal->allocate_progress = 1;
1729 if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
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);
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]);
1751 /* initialize to an impossible value which will force a recalculation
1752 * in the first frame decode */
1753 for (i = 0; i < 3; i++)
1756 avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
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;
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;
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;
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;
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;
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;
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];
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;
1808 /* init VLC tables */
1809 for (i = 0; i < 16; i++) {
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);
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);
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);
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);
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);
1836 for (i = 0; i < 16; i++) {
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)
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)
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)
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)
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)
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);
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);
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);
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);
1885 return allocate_tables(avctx);
1888 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1892 /// Release and shuffle frames after decode finishes
1893 static int update_frames(AVCodecContext *avctx)
1895 Vp3DecodeContext *s = avctx->priv_data;
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);
1905 ff_thread_release_buffer(avctx, &s->golden_frame);
1906 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
1910 ff_thread_release_buffer(avctx, &s->current_frame);
1914 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
1916 ff_thread_release_buffer(s->avctx, dst);
1917 if (src->f->data[0])
1918 return ff_thread_ref_frame(dst, src);
1922 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
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)
1932 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1934 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1935 int qps_changed = 0, i, err;
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)
1941 if (!s1->current_frame.f->data[0] ||
1942 s->width != s1->width || s->height != s1->height) {
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;
1953 err = allocate_tables(dst);
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]));
1964 // copy previous frame data
1965 if ((err = ref_frames(s, s1)) < 0)
1968 s->keyframe = s1->keyframe;
1970 // copy qscale data if necessary
1971 for (i = 0; i < 3; i++) {
1972 if (s->qps[i] != s1->qps[1]) {
1974 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
1978 if (s->qps[0] != s1->qps[0])
1979 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
1980 sizeof(s->bounding_values_array));
1983 copy_fields(s, s1, qps, superblock_count);
1987 return update_frames(dst);
1990 static int vp3_decode_frame(AVCodecContext *avctx,
1991 void *data, int *got_frame,
1994 const uint8_t *buf = avpkt->data;
1995 int buf_size = avpkt->size;
1996 Vp3DecodeContext *s = avctx->priv_data;
2000 init_get_bits(&gb, buf, buf_size * 8);
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" */
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;
2012 vp3_decode_end(avctx);
2013 ret = theora_decode_header(avctx, &gb);
2016 vp3_decode_end(avctx);
2018 ret = vp3_decode_init(avctx);
2020 } else if (type == 2) {
2021 ret = theora_decode_tables(avctx, &gb);
2023 vp3_decode_end(avctx);
2025 ret = vp3_decode_init(avctx);
2029 av_log(avctx, AV_LOG_ERROR,
2030 "Header packet passed to frame decoder, skipping\n");
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");
2042 for (i = 0; i < 3; i++)
2043 s->last_qps[i] = s->qps[i];
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++)
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]);
2056 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2057 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2058 : AVDISCARD_NONKEY);
2060 if (s->qps[0] != s->last_qps[0])
2061 init_loop_filter(s);
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);
2069 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
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)
2078 if (!s->edge_emu_buffer)
2079 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2083 skip_bits(&gb, 4); /* width code */
2084 skip_bits(&gb, 4); /* height code */
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);
2092 if (s->version || s->theora) {
2094 av_log(s->avctx, AV_LOG_ERROR,
2095 "Warning, unsupported keyframe coding type?!\n");
2096 skip_bits(&gb, 2); /* reserved? */
2099 if (!s->golden_frame.f->data[0]) {
2100 av_log(s->avctx, AV_LOG_WARNING,
2101 "vp3: first frame not a keyframe\n");
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)
2107 ff_thread_release_buffer(avctx, &s->last_frame);
2108 if ((ret = ff_thread_ref_frame(&s->last_frame,
2109 &s->golden_frame)) < 0)
2111 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2115 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2116 ff_thread_finish_setup(avctx);
2118 if (unpack_superblocks(s, &gb)) {
2119 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2122 if (unpack_modes(s, &gb)) {
2123 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2126 if (unpack_vectors(s, &gb)) {
2127 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2130 if (unpack_block_qpis(s, &gb)) {
2131 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2134 if (unpack_dct_coeffs(s, &gb)) {
2135 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
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;
2144 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2147 s->last_slice_end = 0;
2148 for (i = 0; i < s->c_superblock_height; i++)
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);
2156 vp3_draw_horiz_band(s, s->height);
2158 /* output frame, offset as needed */
2159 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
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;
2169 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2170 ret = update_frames(avctx);
2178 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2180 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2181 av_frame_unref(s->current_frame.f);
2186 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2188 Vp3DecodeContext *s = avctx->priv_data;
2190 if (get_bits1(gb)) {
2192 if (s->entries >= 32) { /* overflow */
2193 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
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;
2203 if (s->huff_code_size >= 32) { /* overflow */
2204 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2207 s->huff_code_size++;
2209 if (read_huffman_tree(avctx, gb))
2212 if (read_huffman_tree(avctx, gb))
2215 s->huff_code_size--;
2220 static int vp3_init_thread_copy(AVCodecContext *avctx)
2222 Vp3DecodeContext *s = avctx->priv_data;
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;
2234 return init_frames(s);
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
2242 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2244 Vp3DecodeContext *s = avctx->priv_data;
2245 int visible_width, visible_height, colorspace;
2246 uint8_t offset_x = 0, offset_y = 0;
2248 AVRational fps, aspect;
2250 s->theora = get_bits_long(gb, 24);
2251 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
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");
2262 s->width = get_bits(gb, 16) << 4;
2264 s->height = get_bits(gb, 16) << 4;
2266 if (s->theora >= 0x030200) {
2267 visible_width = get_bits_long(gb, 24);
2268 visible_height = get_bits_long(gb, 24);
2270 offset_x = get_bits(gb, 8); /* offset x */
2271 offset_y = get_bits(gb, 8); /* offset y, from bottom */
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;
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;
2292 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2293 fps.den, fps.num, 1 << 30);
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);
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 */
2310 skip_bits(gb, 6); /* quality hint */
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;
2319 skip_bits(gb, 3); /* reserved */
2322 ret = ff_set_dimensions(avctx, s->width, s->height);
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;
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);
2342 if (colorspace == 1)
2343 avctx->color_primaries = AVCOL_PRI_BT470M;
2344 else if (colorspace == 2)
2345 avctx->color_primaries = AVCOL_PRI_BT470BG;
2347 if (colorspace == 1 || colorspace == 2) {
2348 avctx->colorspace = AVCOL_SPC_BT470BG;
2349 avctx->color_trc = AVCOL_TRC_BT709;
2355 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2357 Vp3DecodeContext *s = avctx->priv_data;
2358 int i, n, matrices, inter, plane;
2360 if (s->theora >= 0x030200) {
2361 n = get_bits(gb, 3);
2362 /* loop filter limit values table */
2364 for (i = 0; i < 64; i++)
2365 s->filter_limit_values[i] = get_bits(gb, n);
2368 if (s->theora >= 0x030200)
2369 n = get_bits(gb, 4) + 1;
2372 /* quality threshold table */
2373 for (i = 0; i < 64; i++)
2374 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2376 if (s->theora >= 0x030200)
2377 n = get_bits(gb, 4) + 1;
2380 /* dc scale factor table */
2381 for (i = 0; i < 64; i++)
2382 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2384 if (s->theora >= 0x030200)
2385 matrices = get_bits(gb, 9) + 1;
2389 if (matrices > 384) {
2390 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2394 for (n = 0; n < matrices; n++)
2395 for (i = 0; i < 64; i++)
2396 s->base_matrix[n][i] = get_bits(gb, 8);
2398 for (inter = 0; inter <= 1; inter++) {
2399 for (plane = 0; plane <= 2; plane++) {
2401 if (inter || plane > 0)
2402 newqr = get_bits1(gb);
2405 if (inter && get_bits1(gb)) {
2409 qtj = (3 * inter + plane - 1) / 3;
2410 plj = (plane + 2) % 3;
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]));
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");
2428 s->qr_base[inter][plane][qri] = i;
2431 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
2432 s->qr_size[inter][plane][qri++] = i;
2437 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2440 s->qr_count[inter][plane] = qri;
2445 /* Huffman tables */
2446 for (s->hti = 0; s->hti < 80; s->hti++) {
2448 s->huff_code_size = 1;
2449 if (!get_bits1(gb)) {
2451 if (read_huffman_tree(avctx, gb))
2454 if (read_huffman_tree(avctx, gb))
2459 s->theora_tables = 1;
2464 static av_cold int theora_decode_init(AVCodecContext *avctx)
2466 Vp3DecodeContext *s = avctx->priv_data;
2469 const uint8_t *header_start[3];
2473 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2477 if (!avctx->extradata_size) {
2478 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
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");
2488 for (i = 0; i < 3; i++) {
2489 if (header_len[i] <= 0)
2491 init_get_bits(&gb, header_start[i], header_len[i] * 8);
2493 ptype = get_bits(&gb, 8);
2495 if (!(ptype & 0x80)) {
2496 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2500 // FIXME: Check for this as well.
2501 skip_bits_long(&gb, 6 * 8); /* "theora" */
2505 if (theora_decode_header(avctx, &gb) < 0)
2509 // FIXME: is this needed? it breaks sometimes
2510 // theora_decode_comments(avctx, gb);
2513 if (theora_decode_tables(avctx, &gb))
2517 av_log(avctx, AV_LOG_ERROR,
2518 "Unknown Theora config packet: %d\n", ptype & ~0x80);
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)
2529 return vp3_decode_init(avctx);
2532 AVCodec ff_theora_decoder = {
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)
2549 AVCodec ff_vp3_decoder = {
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),