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, theora_header;
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];
182 int8_t (*motion_val[2])[2];
185 uint16_t coded_dc_scale_factor[64];
186 uint32_t coded_ac_scale_factor[64];
187 uint8_t base_matrix[384][64];
188 uint8_t qr_count[2][3];
189 uint8_t qr_size[2][3][64];
190 uint16_t qr_base[2][3][64];
193 * This is a list of all tokens in bitstream order. Reordering takes place
194 * by pulling from each level during IDCT. As a consequence, IDCT must be
195 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
196 * otherwise. The 32 different tokens with up to 12 bits of extradata are
197 * collapsed into 3 types, packed as follows:
198 * (from the low to high bits)
200 * 2 bits: type (0,1,2)
201 * 0: EOB run, 14 bits for run length (12 needed)
202 * 1: zero run, 7 bits for run length
203 * 7 bits for the next coefficient (3 needed)
204 * 2: coefficient, 14 bits (11 needed)
206 * Coefficients are signed, so are packed in the highest bits for automatic
209 int16_t *dct_tokens[3][64];
210 int16_t *dct_tokens_base;
211 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
212 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
213 #define TOKEN_COEFF(coeff) (((coeff) * 4) + 2)
216 * number of blocks that contain DCT coefficients at
217 * the given level or higher
219 int num_coded_frags[3][64];
220 int total_num_coded_frags;
222 /* this is a list of indexes into the all_fragments array indicating
223 * which of the fragments are coded */
224 int *coded_fragment_list[3];
226 int *kf_coded_fragment_list;
227 int *nkf_coded_fragment_list;
228 int num_kf_coded_fragment[3];
236 VLC superblock_run_length_vlc;
237 VLC fragment_run_length_vlc;
239 VLC motion_vector_vlc;
241 /* these arrays need to be on 16-byte boundaries since SSE2 operations
243 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
245 /* This table contains superblock_count * 16 entries. Each set of 16
246 * numbers corresponds to the fragment indexes 0..15 of the superblock.
247 * An entry will be -1 to indicate that no entry corresponds to that
249 int *superblock_fragments;
251 /* This is an array that indicates how a particular macroblock
253 unsigned char *macroblock_coding;
255 uint8_t *edge_emu_buffer;
262 uint32_t huffman_table[80][32][2];
264 uint8_t filter_limit_values[64];
265 DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
268 /************************************************************************
269 * VP3 specific functions
270 ************************************************************************/
272 static av_cold void free_tables(AVCodecContext *avctx)
274 Vp3DecodeContext *s = avctx->priv_data;
276 av_freep(&s->superblock_coding);
277 av_freep(&s->all_fragments);
278 av_freep(&s->nkf_coded_fragment_list);
279 av_freep(&s->kf_coded_fragment_list);
280 av_freep(&s->dct_tokens_base);
281 av_freep(&s->superblock_fragments);
282 av_freep(&s->macroblock_coding);
283 av_freep(&s->motion_val[0]);
284 av_freep(&s->motion_val[1]);
287 static void vp3_decode_flush(AVCodecContext *avctx)
289 Vp3DecodeContext *s = avctx->priv_data;
291 if (s->golden_frame.f)
292 ff_thread_release_buffer(avctx, &s->golden_frame);
294 ff_thread_release_buffer(avctx, &s->last_frame);
295 if (s->current_frame.f)
296 ff_thread_release_buffer(avctx, &s->current_frame);
299 static av_cold int vp3_decode_end(AVCodecContext *avctx)
301 Vp3DecodeContext *s = avctx->priv_data;
305 av_freep(&s->edge_emu_buffer);
307 s->theora_tables = 0;
309 /* release all frames */
310 vp3_decode_flush(avctx);
311 av_frame_free(&s->current_frame.f);
312 av_frame_free(&s->last_frame.f);
313 av_frame_free(&s->golden_frame.f);
315 if (avctx->internal->is_copy)
318 for (i = 0; i < 16; i++) {
319 ff_free_vlc(&s->dc_vlc[i]);
320 ff_free_vlc(&s->ac_vlc_1[i]);
321 ff_free_vlc(&s->ac_vlc_2[i]);
322 ff_free_vlc(&s->ac_vlc_3[i]);
323 ff_free_vlc(&s->ac_vlc_4[i]);
326 ff_free_vlc(&s->superblock_run_length_vlc);
327 ff_free_vlc(&s->fragment_run_length_vlc);
328 ff_free_vlc(&s->mode_code_vlc);
329 ff_free_vlc(&s->motion_vector_vlc);
335 * This function sets up all of the various blocks mappings:
336 * superblocks <-> fragments, macroblocks <-> fragments,
337 * superblocks <-> macroblocks
339 * @return 0 is successful; returns 1 if *anything* went wrong.
341 static int init_block_mapping(Vp3DecodeContext *s)
343 int sb_x, sb_y, plane;
346 for (plane = 0; plane < 3; plane++) {
347 int sb_width = plane ? s->c_superblock_width
348 : s->y_superblock_width;
349 int sb_height = plane ? s->c_superblock_height
350 : s->y_superblock_height;
351 int frag_width = s->fragment_width[!!plane];
352 int frag_height = s->fragment_height[!!plane];
354 for (sb_y = 0; sb_y < sb_height; sb_y++)
355 for (sb_x = 0; sb_x < sb_width; sb_x++)
356 for (i = 0; i < 16; i++) {
357 x = 4 * sb_x + hilbert_offset[i][0];
358 y = 4 * sb_y + hilbert_offset[i][1];
360 if (x < frag_width && y < frag_height)
361 s->superblock_fragments[j++] = s->fragment_start[plane] +
364 s->superblock_fragments[j++] = -1;
368 return 0; /* successful path out */
372 * This function sets up the dequantization tables used for a particular
375 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
377 int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
378 int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
379 int i, plane, inter, qri, bmi, bmj, qistart;
381 for (inter = 0; inter < 2; inter++) {
382 for (plane = 0; plane < 3; plane++) {
384 for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
385 sum += s->qr_size[inter][plane][qri];
386 if (s->qps[qpi] <= sum)
389 qistart = sum - s->qr_size[inter][plane][qri];
390 bmi = s->qr_base[inter][plane][qri];
391 bmj = s->qr_base[inter][plane][qri + 1];
392 for (i = 0; i < 64; i++) {
393 int coeff = (2 * (sum - s->qps[qpi]) * s->base_matrix[bmi][i] -
394 2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
395 s->qr_size[inter][plane][qri]) /
396 (2 * s->qr_size[inter][plane][qri]);
398 int qmin = 8 << (inter + !i);
399 int qscale = i ? ac_scale_factor : dc_scale_factor;
401 s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
402 av_clip((qscale * coeff) / 100 * 4, qmin, 4096);
404 /* all DC coefficients use the same quant so as not to interfere
405 * with DC prediction */
406 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
412 * This function initializes the loop filter boundary limits if the frame's
413 * quality index is different from the previous frame's.
415 * The filter_limit_values may not be larger than 127.
417 static void init_loop_filter(Vp3DecodeContext *s)
419 ff_vp3dsp_set_bounding_values(s->bounding_values_array, s->filter_limit_values[s->qps[0]]);
423 * This function unpacks all of the superblock/macroblock/fragment coding
424 * information from the bitstream.
426 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
428 int superblock_starts[3] = {
429 0, s->u_superblock_start, s->v_superblock_start
432 int current_superblock = 0;
434 int num_partial_superblocks = 0;
437 int current_fragment;
439 int plane0_num_coded_frags = 0;
442 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
444 /* unpack the list of partially-coded superblocks */
445 bit = get_bits1(gb) ^ 1;
448 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
449 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
454 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
456 if (current_run == 34)
457 current_run += get_bits(gb, 12);
459 if (current_run > s->superblock_count - current_superblock) {
460 av_log(s->avctx, AV_LOG_ERROR,
461 "Invalid partially coded superblock run length\n");
465 memset(s->superblock_coding + current_superblock, bit, current_run);
467 current_superblock += current_run;
469 num_partial_superblocks += current_run;
472 /* unpack the list of fully coded superblocks if any of the blocks were
473 * not marked as partially coded in the previous step */
474 if (num_partial_superblocks < s->superblock_count) {
475 int superblocks_decoded = 0;
477 current_superblock = 0;
478 bit = get_bits1(gb) ^ 1;
481 while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
482 get_bits_left(gb) > 0) {
483 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
488 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
490 if (current_run == 34)
491 current_run += get_bits(gb, 12);
493 for (j = 0; j < current_run; current_superblock++) {
494 if (current_superblock >= s->superblock_count) {
495 av_log(s->avctx, AV_LOG_ERROR,
496 "Invalid fully coded superblock run length\n");
500 /* skip any superblocks already marked as partially coded */
501 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
502 s->superblock_coding[current_superblock] = 2 * bit;
506 superblocks_decoded += current_run;
510 /* if there were partial blocks, initialize bitstream for
511 * unpacking fragment codings */
512 if (num_partial_superblocks) {
515 /* toggle the bit because as soon as the first run length is
516 * fetched the bit will be toggled again */
521 /* figure out which fragments are coded; iterate through each
522 * superblock (all planes) */
523 s->total_num_coded_frags = 0;
524 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
526 s->coded_fragment_list[0] = s->keyframe ? s->kf_coded_fragment_list
527 : s->nkf_coded_fragment_list;
529 for (plane = 0; plane < 3; plane++) {
530 int sb_start = superblock_starts[plane];
531 int sb_end = sb_start + (plane ? s->c_superblock_count
532 : s->y_superblock_count);
533 int num_coded_frags = 0;
536 if (s->num_kf_coded_fragment[plane] == -1) {
537 for (i = sb_start; i < sb_end; i++) {
538 /* iterate through all 16 fragments in a superblock */
539 for (j = 0; j < 16; j++) {
540 /* if the fragment is in bounds, check its coding status */
541 current_fragment = s->superblock_fragments[i * 16 + j];
542 if (current_fragment != -1) {
543 s->coded_fragment_list[plane][num_coded_frags++] =
548 s->num_kf_coded_fragment[plane] = num_coded_frags;
550 num_coded_frags = s->num_kf_coded_fragment[plane];
552 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
553 if (get_bits_left(gb) < plane0_num_coded_frags >> 2) {
554 return AVERROR_INVALIDDATA;
556 /* iterate through all 16 fragments in a superblock */
557 for (j = 0; j < 16; j++) {
558 /* if the fragment is in bounds, check its coding status */
559 current_fragment = s->superblock_fragments[i * 16 + j];
560 if (current_fragment != -1) {
561 int coded = s->superblock_coding[i];
563 if (coded == SB_PARTIALLY_CODED) {
564 /* fragment may or may not be coded; this is the case
565 * that cares about the fragment coding runs */
566 if (current_run-- == 0) {
568 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
574 /* default mode; actual mode will be decoded in
576 s->all_fragments[current_fragment].coding_method =
578 s->coded_fragment_list[plane][num_coded_frags++] =
581 /* not coded; copy this fragment from the prior frame */
582 s->all_fragments[current_fragment].coding_method =
590 plane0_num_coded_frags = num_coded_frags;
591 s->total_num_coded_frags += num_coded_frags;
592 for (i = 0; i < 64; i++)
593 s->num_coded_frags[plane][i] = num_coded_frags;
595 s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
602 * This function unpacks all the coding mode data for individual macroblocks
603 * from the bitstream.
605 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
607 int i, j, k, sb_x, sb_y;
609 int current_macroblock;
610 int current_fragment;
612 int custom_mode_alphabet[CODING_MODE_COUNT];
617 for (i = 0; i < s->fragment_count; i++)
618 s->all_fragments[i].coding_method = MODE_INTRA;
620 /* fetch the mode coding scheme for this frame */
621 scheme = get_bits(gb, 3);
623 /* is it a custom coding scheme? */
625 for (i = 0; i < 8; i++)
626 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
627 for (i = 0; i < 8; i++)
628 custom_mode_alphabet[get_bits(gb, 3)] = i;
629 alphabet = custom_mode_alphabet;
631 alphabet = ModeAlphabet[scheme - 1];
633 /* iterate through all of the macroblocks that contain 1 or more
635 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
636 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
637 if (get_bits_left(gb) <= 0)
640 for (j = 0; j < 4; j++) {
641 int mb_x = 2 * sb_x + (j >> 1);
642 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
643 current_macroblock = mb_y * s->macroblock_width + mb_x;
645 if (mb_x >= s->macroblock_width ||
646 mb_y >= s->macroblock_height)
649 #define BLOCK_X (2 * mb_x + (k & 1))
650 #define BLOCK_Y (2 * mb_y + (k >> 1))
651 /* coding modes are only stored if the macroblock has
652 * at least one luma block coded, otherwise it must be
654 for (k = 0; k < 4; k++) {
655 current_fragment = BLOCK_Y *
656 s->fragment_width[0] + BLOCK_X;
657 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
661 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
665 /* mode 7 means get 3 bits for each coding mode */
667 coding_mode = get_bits(gb, 3);
669 coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
671 s->macroblock_coding[current_macroblock] = coding_mode;
672 for (k = 0; k < 4; k++) {
673 frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
674 if (frag->coding_method != MODE_COPY)
675 frag->coding_method = coding_mode;
678 #define SET_CHROMA_MODES \
679 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
680 frag[s->fragment_start[1]].coding_method = coding_mode; \
681 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
682 frag[s->fragment_start[2]].coding_method = coding_mode;
684 if (s->chroma_y_shift) {
685 frag = s->all_fragments + mb_y *
686 s->fragment_width[1] + mb_x;
688 } else if (s->chroma_x_shift) {
689 frag = s->all_fragments +
690 2 * mb_y * s->fragment_width[1] + mb_x;
691 for (k = 0; k < 2; k++) {
693 frag += s->fragment_width[1];
696 for (k = 0; k < 4; k++) {
697 frag = s->all_fragments +
698 BLOCK_Y * s->fragment_width[1] + BLOCK_X;
711 * This function unpacks all the motion vectors for the individual
712 * macroblocks from the bitstream.
714 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
716 int j, k, sb_x, sb_y;
720 int last_motion_x = 0;
721 int last_motion_y = 0;
722 int prior_last_motion_x = 0;
723 int prior_last_motion_y = 0;
724 int current_macroblock;
725 int current_fragment;
731 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
732 coding_mode = get_bits1(gb);
734 /* iterate through all of the macroblocks that contain 1 or more
736 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
737 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
738 if (get_bits_left(gb) <= 0)
741 for (j = 0; j < 4; j++) {
742 int mb_x = 2 * sb_x + (j >> 1);
743 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
744 current_macroblock = mb_y * s->macroblock_width + mb_x;
746 if (mb_x >= s->macroblock_width ||
747 mb_y >= s->macroblock_height ||
748 s->macroblock_coding[current_macroblock] == MODE_COPY)
751 switch (s->macroblock_coding[current_macroblock]) {
752 case MODE_INTER_PLUS_MV:
754 /* all 6 fragments use the same motion vector */
755 if (coding_mode == 0) {
756 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
757 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
759 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
760 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
763 /* vector maintenance, only on MODE_INTER_PLUS_MV */
764 if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
765 prior_last_motion_x = last_motion_x;
766 prior_last_motion_y = last_motion_y;
767 last_motion_x = motion_x[0];
768 last_motion_y = motion_y[0];
772 case MODE_INTER_FOURMV:
773 /* vector maintenance */
774 prior_last_motion_x = last_motion_x;
775 prior_last_motion_y = last_motion_y;
777 /* fetch 4 vectors from the bitstream, one for each
778 * Y fragment, then average for the C fragment vectors */
779 for (k = 0; k < 4; k++) {
780 current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
781 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
782 if (coding_mode == 0) {
783 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
784 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
786 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
787 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
789 last_motion_x = motion_x[k];
790 last_motion_y = motion_y[k];
798 case MODE_INTER_LAST_MV:
799 /* all 6 fragments use the last motion vector */
800 motion_x[0] = last_motion_x;
801 motion_y[0] = last_motion_y;
803 /* no vector maintenance (last vector remains the
807 case MODE_INTER_PRIOR_LAST:
808 /* all 6 fragments use the motion vector prior to the
809 * last motion vector */
810 motion_x[0] = prior_last_motion_x;
811 motion_y[0] = prior_last_motion_y;
813 /* vector maintenance */
814 prior_last_motion_x = last_motion_x;
815 prior_last_motion_y = last_motion_y;
816 last_motion_x = motion_x[0];
817 last_motion_y = motion_y[0];
821 /* covers intra, inter without MV, golden without MV */
825 /* no vector maintenance */
829 /* assign the motion vectors to the correct fragments */
830 for (k = 0; k < 4; k++) {
832 BLOCK_Y * s->fragment_width[0] + BLOCK_X;
833 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
834 s->motion_val[0][current_fragment][0] = motion_x[k];
835 s->motion_val[0][current_fragment][1] = motion_y[k];
837 s->motion_val[0][current_fragment][0] = motion_x[0];
838 s->motion_val[0][current_fragment][1] = motion_y[0];
842 if (s->chroma_y_shift) {
843 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
844 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
845 motion_x[2] + motion_x[3], 2);
846 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
847 motion_y[2] + motion_y[3], 2);
849 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
850 motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
851 frag = mb_y * s->fragment_width[1] + mb_x;
852 s->motion_val[1][frag][0] = motion_x[0];
853 s->motion_val[1][frag][1] = motion_y[0];
854 } else if (s->chroma_x_shift) {
855 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
856 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
857 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
858 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
859 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
861 motion_x[1] = motion_x[0];
862 motion_y[1] = motion_y[0];
864 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
865 motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
867 frag = 2 * mb_y * s->fragment_width[1] + mb_x;
868 for (k = 0; k < 2; k++) {
869 s->motion_val[1][frag][0] = motion_x[k];
870 s->motion_val[1][frag][1] = motion_y[k];
871 frag += s->fragment_width[1];
874 for (k = 0; k < 4; k++) {
875 frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
876 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
877 s->motion_val[1][frag][0] = motion_x[k];
878 s->motion_val[1][frag][1] = motion_y[k];
880 s->motion_val[1][frag][0] = motion_x[0];
881 s->motion_val[1][frag][1] = motion_y[0];
892 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
894 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
895 int num_blocks = s->total_num_coded_frags;
897 for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
898 i = blocks_decoded = num_blocks_at_qpi = 0;
900 bit = get_bits1(gb) ^ 1;
904 if (run_length == MAXIMUM_LONG_BIT_RUN)
909 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
910 if (run_length == 34)
911 run_length += get_bits(gb, 12);
912 blocks_decoded += run_length;
915 num_blocks_at_qpi += run_length;
917 for (j = 0; j < run_length; i++) {
918 if (i >= s->total_num_coded_frags)
921 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
922 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
926 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
928 num_blocks -= num_blocks_at_qpi;
935 * This function is called by unpack_dct_coeffs() to extract the VLCs from
936 * the bitstream. The VLCs encode tokens which are used to unpack DCT
937 * data. This function unpacks all the VLCs for either the Y plane or both
938 * C planes, and is called for DC coefficients or different AC coefficient
939 * levels (since different coefficient types require different VLC tables.
941 * This function returns a residual eob run. E.g, if a particular token gave
942 * instructions to EOB the next 5 fragments and there were only 2 fragments
943 * left in the current fragment range, 3 would be returned so that it could
944 * be passed into the next call to this same function.
946 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
947 VLC *table, int coeff_index,
958 int num_coeffs = s->num_coded_frags[plane][coeff_index];
959 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
961 /* local references to structure members to avoid repeated dereferences */
962 int *coded_fragment_list = s->coded_fragment_list[plane];
963 Vp3Fragment *all_fragments = s->all_fragments;
964 VLC_TYPE(*vlc_table)[2] = table->table;
966 if (num_coeffs < 0) {
967 av_log(s->avctx, AV_LOG_ERROR,
968 "Invalid number of coefficients at level %d\n", coeff_index);
969 return AVERROR_INVALIDDATA;
972 if (eob_run > num_coeffs) {
974 blocks_ended = num_coeffs;
975 eob_run -= num_coeffs;
978 blocks_ended = eob_run;
982 // insert fake EOB token to cover the split between planes or zzi
984 dct_tokens[j++] = blocks_ended << 2;
986 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
987 /* decode a VLC into a token */
988 token = get_vlc2(gb, vlc_table, 11, 3);
989 /* use the token to get a zero run, a coefficient, and an eob run */
990 if ((unsigned) token <= 6U) {
991 eob_run = eob_run_base[token];
992 if (eob_run_get_bits[token])
993 eob_run += get_bits(gb, eob_run_get_bits[token]);
998 // record only the number of blocks ended in this plane,
999 // any spill will be recorded in the next plane.
1000 if (eob_run > num_coeffs - coeff_i) {
1001 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1002 blocks_ended += num_coeffs - coeff_i;
1003 eob_run -= num_coeffs - coeff_i;
1004 coeff_i = num_coeffs;
1006 dct_tokens[j++] = TOKEN_EOB(eob_run);
1007 blocks_ended += eob_run;
1011 } else if (token >= 0) {
1012 bits_to_get = coeff_get_bits[token];
1014 bits_to_get = get_bits(gb, bits_to_get);
1015 coeff = coeff_tables[token][bits_to_get];
1017 zero_run = zero_run_base[token];
1018 if (zero_run_get_bits[token])
1019 zero_run += get_bits(gb, zero_run_get_bits[token]);
1022 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1024 // Save DC into the fragment structure. DC prediction is
1025 // done in raster order, so the actual DC can't be in with
1026 // other tokens. We still need the token in dct_tokens[]
1027 // however, or else the structure collapses on itself.
1029 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1031 dct_tokens[j++] = TOKEN_COEFF(coeff);
1034 if (coeff_index + zero_run > 64) {
1035 av_log(s->avctx, AV_LOG_DEBUG,
1036 "Invalid zero run of %d with %d coeffs left\n",
1037 zero_run, 64 - coeff_index);
1038 zero_run = 64 - coeff_index;
1041 // zero runs code multiple coefficients,
1042 // so don't try to decode coeffs for those higher levels
1043 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1044 s->num_coded_frags[plane][i]--;
1047 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1052 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1053 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1055 // decrement the number of blocks that have higher coefficients for each
1056 // EOB run at this level
1058 for (i = coeff_index + 1; i < 64; i++)
1059 s->num_coded_frags[plane][i] -= blocks_ended;
1061 // setup the next buffer
1063 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1064 else if (coeff_index < 63)
1065 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1070 static void reverse_dc_prediction(Vp3DecodeContext *s,
1073 int fragment_height);
1075 * This function unpacks all of the DCT coefficient data from the
1078 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1085 int residual_eob_run = 0;
1089 s->dct_tokens[0][0] = s->dct_tokens_base;
1091 if (get_bits_left(gb) < 16)
1092 return AVERROR_INVALIDDATA;
1094 /* fetch the DC table indexes */
1095 dc_y_table = get_bits(gb, 4);
1096 dc_c_table = get_bits(gb, 4);
1098 /* unpack the Y plane DC coefficients */
1099 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1100 0, residual_eob_run);
1101 if (residual_eob_run < 0)
1102 return residual_eob_run;
1103 if (get_bits_left(gb) < 8)
1104 return AVERROR_INVALIDDATA;
1106 /* reverse prediction of the Y-plane DC coefficients */
1107 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1109 /* unpack the C plane DC coefficients */
1110 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1111 1, residual_eob_run);
1112 if (residual_eob_run < 0)
1113 return residual_eob_run;
1114 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1115 2, residual_eob_run);
1116 if (residual_eob_run < 0)
1117 return residual_eob_run;
1119 /* reverse prediction of the C-plane DC coefficients */
1120 if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1121 reverse_dc_prediction(s, s->fragment_start[1],
1122 s->fragment_width[1], s->fragment_height[1]);
1123 reverse_dc_prediction(s, s->fragment_start[2],
1124 s->fragment_width[1], s->fragment_height[1]);
1127 if (get_bits_left(gb) < 8)
1128 return AVERROR_INVALIDDATA;
1129 /* fetch the AC table indexes */
1130 ac_y_table = get_bits(gb, 4);
1131 ac_c_table = get_bits(gb, 4);
1133 /* build tables of AC VLC tables */
1134 for (i = 1; i <= 5; i++) {
1135 y_tables[i] = &s->ac_vlc_1[ac_y_table];
1136 c_tables[i] = &s->ac_vlc_1[ac_c_table];
1138 for (i = 6; i <= 14; i++) {
1139 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1140 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1142 for (i = 15; i <= 27; i++) {
1143 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1144 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1146 for (i = 28; i <= 63; i++) {
1147 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1148 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1151 /* decode all AC coefficients */
1152 for (i = 1; i <= 63; i++) {
1153 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1154 0, residual_eob_run);
1155 if (residual_eob_run < 0)
1156 return residual_eob_run;
1158 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1159 1, residual_eob_run);
1160 if (residual_eob_run < 0)
1161 return residual_eob_run;
1162 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1163 2, residual_eob_run);
1164 if (residual_eob_run < 0)
1165 return residual_eob_run;
1172 * This function reverses the DC prediction for each coded fragment in
1173 * the frame. Much of this function is adapted directly from the original
1176 #define COMPATIBLE_FRAME(x) \
1177 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1178 #define DC_COEFF(u) s->all_fragments[u].dc
1180 static void reverse_dc_prediction(Vp3DecodeContext *s,
1183 int fragment_height)
1191 int i = first_fragment;
1195 /* DC values for the left, up-left, up, and up-right fragments */
1196 int vl, vul, vu, vur;
1198 /* indexes for the left, up-left, up, and up-right fragments */
1202 * The 6 fields mean:
1203 * 0: up-left multiplier
1205 * 2: up-right multiplier
1206 * 3: left multiplier
1208 static const int predictor_transform[16][4] = {
1210 { 0, 0, 0, 128 }, // PL
1211 { 0, 0, 128, 0 }, // PUR
1212 { 0, 0, 53, 75 }, // PUR|PL
1213 { 0, 128, 0, 0 }, // PU
1214 { 0, 64, 0, 64 }, // PU |PL
1215 { 0, 128, 0, 0 }, // PU |PUR
1216 { 0, 0, 53, 75 }, // PU |PUR|PL
1217 { 128, 0, 0, 0 }, // PUL
1218 { 0, 0, 0, 128 }, // PUL|PL
1219 { 64, 0, 64, 0 }, // PUL|PUR
1220 { 0, 0, 53, 75 }, // PUL|PUR|PL
1221 { 0, 128, 0, 0 }, // PUL|PU
1222 { -104, 116, 0, 116 }, // PUL|PU |PL
1223 { 24, 80, 24, 0 }, // PUL|PU |PUR
1224 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1227 /* This table shows which types of blocks can use other blocks for
1228 * prediction. For example, INTRA is the only mode in this table to
1229 * have a frame number of 0. That means INTRA blocks can only predict
1230 * from other INTRA blocks. There are 2 golden frame coding types;
1231 * blocks encoding in these modes can only predict from other blocks
1232 * that were encoded with these 1 of these 2 modes. */
1233 static const unsigned char compatible_frame[9] = {
1234 1, /* MODE_INTER_NO_MV */
1236 1, /* MODE_INTER_PLUS_MV */
1237 1, /* MODE_INTER_LAST_MV */
1238 1, /* MODE_INTER_PRIOR_MV */
1239 2, /* MODE_USING_GOLDEN */
1240 2, /* MODE_GOLDEN_MV */
1241 1, /* MODE_INTER_FOUR_MV */
1244 int current_frame_type;
1246 /* there is a last DC predictor for each of the 3 frame types */
1259 /* for each fragment row... */
1260 for (y = 0; y < fragment_height; y++) {
1261 /* for each fragment in a row... */
1262 for (x = 0; x < fragment_width; x++, i++) {
1264 /* reverse prediction if this block was coded */
1265 if (s->all_fragments[i].coding_method != MODE_COPY) {
1266 current_frame_type =
1267 compatible_frame[s->all_fragments[i].coding_method];
1273 if (COMPATIBLE_FRAME(l))
1277 u = i - fragment_width;
1279 if (COMPATIBLE_FRAME(u))
1282 ul = i - fragment_width - 1;
1284 if (COMPATIBLE_FRAME(ul))
1287 if (x + 1 < fragment_width) {
1288 ur = i - fragment_width + 1;
1290 if (COMPATIBLE_FRAME(ur))
1295 if (transform == 0) {
1296 /* if there were no fragments to predict from, use last
1298 predicted_dc = last_dc[current_frame_type];
1300 /* apply the appropriate predictor transform */
1302 (predictor_transform[transform][0] * vul) +
1303 (predictor_transform[transform][1] * vu) +
1304 (predictor_transform[transform][2] * vur) +
1305 (predictor_transform[transform][3] * vl);
1307 predicted_dc /= 128;
1309 /* check for outranging on the [ul u l] and
1310 * [ul u ur l] predictors */
1311 if ((transform == 15) || (transform == 13)) {
1312 if (FFABS(predicted_dc - vu) > 128)
1314 else if (FFABS(predicted_dc - vl) > 128)
1316 else if (FFABS(predicted_dc - vul) > 128)
1321 /* at long last, apply the predictor */
1322 DC_COEFF(i) += predicted_dc;
1324 last_dc[current_frame_type] = DC_COEFF(i);
1330 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1331 int ystart, int yend)
1334 int *bounding_values = s->bounding_values_array + 127;
1336 int width = s->fragment_width[!!plane];
1337 int height = s->fragment_height[!!plane];
1338 int fragment = s->fragment_start[plane] + ystart * width;
1339 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1340 uint8_t *plane_data = s->current_frame.f->data[plane];
1341 if (!s->flipped_image)
1343 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1345 for (y = ystart; y < yend; y++) {
1346 for (x = 0; x < width; x++) {
1347 /* This code basically just deblocks on the edges of coded blocks.
1348 * However, it has to be much more complicated because of the
1349 * brain damaged deblock ordering used in VP3/Theora. Order matters
1350 * because some pixels get filtered twice. */
1351 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1352 /* do not perform left edge filter for left columns frags */
1354 s->vp3dsp.h_loop_filter(
1356 stride, bounding_values);
1359 /* do not perform top edge filter for top row fragments */
1361 s->vp3dsp.v_loop_filter(
1363 stride, bounding_values);
1366 /* do not perform right edge filter for right column
1367 * fragments or if right fragment neighbor is also coded
1368 * in this frame (it will be filtered in next iteration) */
1369 if ((x < width - 1) &&
1370 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1371 s->vp3dsp.h_loop_filter(
1372 plane_data + 8 * x + 8,
1373 stride, bounding_values);
1376 /* do not perform bottom edge filter for bottom row
1377 * fragments or if bottom fragment neighbor is also coded
1378 * in this frame (it will be filtered in the next row) */
1379 if ((y < height - 1) &&
1380 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1381 s->vp3dsp.v_loop_filter(
1382 plane_data + 8 * x + 8 * stride,
1383 stride, bounding_values);
1389 plane_data += 8 * stride;
1394 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1395 * for the next block in coding order
1397 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1398 int plane, int inter, int16_t block[64])
1400 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1401 uint8_t *perm = s->idct_scantable;
1405 int token = *s->dct_tokens[plane][i];
1406 switch (token & 3) {
1408 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1409 s->dct_tokens[plane][i]++;
1411 *s->dct_tokens[plane][i] = token & ~3;
1414 s->dct_tokens[plane][i]++;
1415 i += (token >> 2) & 0x7f;
1417 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1420 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1424 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1425 s->dct_tokens[plane][i++]++;
1427 default: // shouldn't happen
1431 // return value is expected to be a valid level
1434 // the actual DC+prediction is in the fragment structure
1435 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1440 * called when all pixels up to row y are complete
1442 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1445 int offset[AV_NUM_DATA_POINTERS];
1447 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1448 int y_flipped = s->flipped_image ? s->height - y : y;
1450 /* At the end of the frame, report INT_MAX instead of the height of
1451 * the frame. This makes the other threads' ff_thread_await_progress()
1452 * calls cheaper, because they don't have to clip their values. */
1453 ff_thread_report_progress(&s->current_frame,
1454 y_flipped == s->height ? INT_MAX
1459 if (!s->avctx->draw_horiz_band)
1462 h = y - s->last_slice_end;
1463 s->last_slice_end = y;
1466 if (!s->flipped_image)
1467 y = s->height - y - h;
1469 cy = y >> s->chroma_y_shift;
1470 offset[0] = s->current_frame.f->linesize[0] * y;
1471 offset[1] = s->current_frame.f->linesize[1] * cy;
1472 offset[2] = s->current_frame.f->linesize[2] * cy;
1473 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1477 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1481 * Wait for the reference frame of the current fragment.
1482 * The progress value is in luma pixel rows.
1484 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1485 int motion_y, int y)
1487 ThreadFrame *ref_frame;
1489 int border = motion_y & 1;
1491 if (fragment->coding_method == MODE_USING_GOLDEN ||
1492 fragment->coding_method == MODE_GOLDEN_MV)
1493 ref_frame = &s->golden_frame;
1495 ref_frame = &s->last_frame;
1497 ref_row = y + (motion_y >> 1);
1498 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1500 ff_thread_await_progress(ref_frame, ref_row, 0);
1504 * Perform the final rendering for a particular slice of data.
1505 * The slice number ranges from 0..(c_superblock_height - 1).
1507 static void render_slice(Vp3DecodeContext *s, int slice)
1509 int x, y, i, j, fragment;
1510 int16_t *block = s->block;
1511 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1512 int motion_halfpel_index;
1513 uint8_t *motion_source;
1514 int plane, first_pixel;
1516 if (slice >= s->c_superblock_height)
1519 for (plane = 0; plane < 3; plane++) {
1520 uint8_t *output_plane = s->current_frame.f->data[plane] +
1521 s->data_offset[plane];
1522 uint8_t *last_plane = s->last_frame.f->data[plane] +
1523 s->data_offset[plane];
1524 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
1525 s->data_offset[plane];
1526 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1527 int plane_width = s->width >> (plane && s->chroma_x_shift);
1528 int plane_height = s->height >> (plane && s->chroma_y_shift);
1529 int8_t(*motion_val)[2] = s->motion_val[!!plane];
1531 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
1532 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
1533 int slice_width = plane ? s->c_superblock_width
1534 : s->y_superblock_width;
1536 int fragment_width = s->fragment_width[!!plane];
1537 int fragment_height = s->fragment_height[!!plane];
1538 int fragment_start = s->fragment_start[plane];
1540 int do_await = !plane && HAVE_THREADS &&
1541 (s->avctx->active_thread_type & FF_THREAD_FRAME);
1543 if (!s->flipped_image)
1545 if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
1548 /* for each superblock row in the slice (both of them)... */
1549 for (; sb_y < slice_height; sb_y++) {
1550 /* for each superblock in a row... */
1551 for (sb_x = 0; sb_x < slice_width; sb_x++) {
1552 /* for each block in a superblock... */
1553 for (j = 0; j < 16; j++) {
1554 x = 4 * sb_x + hilbert_offset[j][0];
1555 y = 4 * sb_y + hilbert_offset[j][1];
1556 fragment = y * fragment_width + x;
1558 i = fragment_start + fragment;
1561 if (x >= fragment_width || y >= fragment_height)
1564 first_pixel = 8 * y * stride + 8 * x;
1567 s->all_fragments[i].coding_method != MODE_INTRA)
1568 await_reference_row(s, &s->all_fragments[i],
1569 motion_val[fragment][1],
1570 (16 * y) >> s->chroma_y_shift);
1572 /* transform if this block was coded */
1573 if (s->all_fragments[i].coding_method != MODE_COPY) {
1574 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1575 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1576 motion_source = golden_plane;
1578 motion_source = last_plane;
1580 motion_source += first_pixel;
1581 motion_halfpel_index = 0;
1583 /* sort out the motion vector if this fragment is coded
1584 * using a motion vector method */
1585 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1586 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1588 motion_x = motion_val[fragment][0];
1589 motion_y = motion_val[fragment][1];
1591 src_x = (motion_x >> 1) + 8 * x;
1592 src_y = (motion_y >> 1) + 8 * y;
1594 motion_halfpel_index = motion_x & 0x01;
1595 motion_source += (motion_x >> 1);
1597 motion_halfpel_index |= (motion_y & 0x01) << 1;
1598 motion_source += ((motion_y >> 1) * stride);
1600 if (src_x < 0 || src_y < 0 ||
1601 src_x + 9 >= plane_width ||
1602 src_y + 9 >= plane_height) {
1603 uint8_t *temp = s->edge_emu_buffer;
1607 s->vdsp.emulated_edge_mc(temp, motion_source,
1612 motion_source = temp;
1616 /* first, take care of copying a block from either the
1617 * previous or the golden frame */
1618 if (s->all_fragments[i].coding_method != MODE_INTRA) {
1619 /* Note, it is possible to implement all MC cases
1620 * with put_no_rnd_pixels_l2 which would look more
1621 * like the VP3 source but this would be slower as
1622 * put_no_rnd_pixels_tab is better optimized */
1623 if (motion_halfpel_index != 3) {
1624 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1625 output_plane + first_pixel,
1626 motion_source, stride, 8);
1628 /* d is 0 if motion_x and _y have the same sign,
1630 int d = (motion_x ^ motion_y) >> 31;
1631 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
1633 motion_source + stride + 1 + d,
1638 /* invert DCT and place (or add) in final output */
1640 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1641 vp3_dequant(s, s->all_fragments + i,
1643 s->vp3dsp.idct_put(output_plane + first_pixel,
1647 if (vp3_dequant(s, s->all_fragments + i,
1649 s->vp3dsp.idct_add(output_plane + first_pixel,
1653 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
1658 /* copy directly from the previous frame */
1659 s->hdsp.put_pixels_tab[1][0](
1660 output_plane + first_pixel,
1661 last_plane + first_pixel,
1667 // Filter up to the last row in the superblock row
1668 if (!s->skip_loop_filter)
1669 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
1670 FFMIN(4 * sb_y + 3, fragment_height - 1));
1674 /* this looks like a good place for slice dispatch... */
1676 * if (slice == s->macroblock_height - 1)
1677 * dispatch (both last slice & 2nd-to-last slice);
1678 * else if (slice > 0)
1679 * dispatch (slice - 1);
1682 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
1686 /// Allocate tables for per-frame data in Vp3DecodeContext
1687 static av_cold int allocate_tables(AVCodecContext *avctx)
1689 Vp3DecodeContext *s = avctx->priv_data;
1690 int y_fragment_count, c_fragment_count;
1694 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1695 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1697 s->superblock_coding = av_mallocz(s->superblock_count);
1698 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
1700 s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
1701 s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
1702 memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
1704 s->dct_tokens_base = av_mallocz_array(s->fragment_count,
1705 64 * sizeof(*s->dct_tokens_base));
1706 s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
1707 s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
1709 /* work out the block mapping tables */
1710 s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
1711 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
1713 if (!s->superblock_coding || !s->all_fragments ||
1714 !s->dct_tokens_base || !s->kf_coded_fragment_list ||
1715 !s->nkf_coded_fragment_list ||
1716 !s->superblock_fragments || !s->macroblock_coding ||
1717 !s->motion_val[0] || !s->motion_val[1]) {
1718 vp3_decode_end(avctx);
1722 init_block_mapping(s);
1727 static av_cold int init_frames(Vp3DecodeContext *s)
1729 s->current_frame.f = av_frame_alloc();
1730 s->last_frame.f = av_frame_alloc();
1731 s->golden_frame.f = av_frame_alloc();
1733 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
1734 av_frame_free(&s->current_frame.f);
1735 av_frame_free(&s->last_frame.f);
1736 av_frame_free(&s->golden_frame.f);
1737 return AVERROR(ENOMEM);
1743 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1745 Vp3DecodeContext *s = avctx->priv_data;
1746 int i, inter, plane, ret;
1749 int y_fragment_count, c_fragment_count;
1751 ret = init_frames(s);
1755 avctx->internal->allocate_progress = 1;
1757 if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
1763 s->width = FFALIGN(avctx->coded_width, 16);
1764 s->height = FFALIGN(avctx->coded_height, 16);
1765 if (avctx->codec_id != AV_CODEC_ID_THEORA)
1766 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
1767 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1768 ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
1769 ff_videodsp_init(&s->vdsp, 8);
1770 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
1772 for (i = 0; i < 64; i++) {
1773 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
1774 s->idct_permutation[i] = TRANSPOSE(i);
1775 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
1779 /* initialize to an impossible value which will force a recalculation
1780 * in the first frame decode */
1781 for (i = 0; i < 3; i++)
1784 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1788 s->y_superblock_width = (s->width + 31) / 32;
1789 s->y_superblock_height = (s->height + 31) / 32;
1790 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1792 /* work out the dimensions for the C planes */
1793 c_width = s->width >> s->chroma_x_shift;
1794 c_height = s->height >> s->chroma_y_shift;
1795 s->c_superblock_width = (c_width + 31) / 32;
1796 s->c_superblock_height = (c_height + 31) / 32;
1797 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1799 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1800 s->u_superblock_start = s->y_superblock_count;
1801 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1803 s->macroblock_width = (s->width + 15) / 16;
1804 s->macroblock_height = (s->height + 15) / 16;
1805 s->macroblock_count = s->macroblock_width * s->macroblock_height;
1807 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1808 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1809 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
1810 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
1812 /* fragment count covers all 8x8 blocks for all 3 planes */
1813 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1814 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1815 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
1816 s->fragment_start[1] = y_fragment_count;
1817 s->fragment_start[2] = y_fragment_count + c_fragment_count;
1819 if (!s->theora_tables) {
1820 for (i = 0; i < 64; i++) {
1821 s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1822 s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1823 s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1824 s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1825 s->base_matrix[2][i] = vp31_inter_dequant[i];
1826 s->filter_limit_values[i] = vp31_filter_limit_values[i];
1829 for (inter = 0; inter < 2; inter++) {
1830 for (plane = 0; plane < 3; plane++) {
1831 s->qr_count[inter][plane] = 1;
1832 s->qr_size[inter][plane][0] = 63;
1833 s->qr_base[inter][plane][0] =
1834 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
1838 /* init VLC tables */
1839 for (i = 0; i < 16; i++) {
1841 init_vlc(&s->dc_vlc[i], 11, 32,
1842 &dc_bias[i][0][1], 4, 2,
1843 &dc_bias[i][0][0], 4, 2, 0);
1845 /* group 1 AC histograms */
1846 init_vlc(&s->ac_vlc_1[i], 11, 32,
1847 &ac_bias_0[i][0][1], 4, 2,
1848 &ac_bias_0[i][0][0], 4, 2, 0);
1850 /* group 2 AC histograms */
1851 init_vlc(&s->ac_vlc_2[i], 11, 32,
1852 &ac_bias_1[i][0][1], 4, 2,
1853 &ac_bias_1[i][0][0], 4, 2, 0);
1855 /* group 3 AC histograms */
1856 init_vlc(&s->ac_vlc_3[i], 11, 32,
1857 &ac_bias_2[i][0][1], 4, 2,
1858 &ac_bias_2[i][0][0], 4, 2, 0);
1860 /* group 4 AC histograms */
1861 init_vlc(&s->ac_vlc_4[i], 11, 32,
1862 &ac_bias_3[i][0][1], 4, 2,
1863 &ac_bias_3[i][0][0], 4, 2, 0);
1866 for (i = 0; i < 16; i++) {
1868 if (init_vlc(&s->dc_vlc[i], 11, 32,
1869 &s->huffman_table[i][0][1], 8, 4,
1870 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
1873 /* group 1 AC histograms */
1874 if (init_vlc(&s->ac_vlc_1[i], 11, 32,
1875 &s->huffman_table[i + 16][0][1], 8, 4,
1876 &s->huffman_table[i + 16][0][0], 8, 4, 0) < 0)
1879 /* group 2 AC histograms */
1880 if (init_vlc(&s->ac_vlc_2[i], 11, 32,
1881 &s->huffman_table[i + 16 * 2][0][1], 8, 4,
1882 &s->huffman_table[i + 16 * 2][0][0], 8, 4, 0) < 0)
1885 /* group 3 AC histograms */
1886 if (init_vlc(&s->ac_vlc_3[i], 11, 32,
1887 &s->huffman_table[i + 16 * 3][0][1], 8, 4,
1888 &s->huffman_table[i + 16 * 3][0][0], 8, 4, 0) < 0)
1891 /* group 4 AC histograms */
1892 if (init_vlc(&s->ac_vlc_4[i], 11, 32,
1893 &s->huffman_table[i + 16 * 4][0][1], 8, 4,
1894 &s->huffman_table[i + 16 * 4][0][0], 8, 4, 0) < 0)
1899 init_vlc(&s->superblock_run_length_vlc, 6, 34,
1900 &superblock_run_length_vlc_table[0][1], 4, 2,
1901 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1903 init_vlc(&s->fragment_run_length_vlc, 5, 30,
1904 &fragment_run_length_vlc_table[0][1], 4, 2,
1905 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1907 init_vlc(&s->mode_code_vlc, 3, 8,
1908 &mode_code_vlc_table[0][1], 2, 1,
1909 &mode_code_vlc_table[0][0], 2, 1, 0);
1911 init_vlc(&s->motion_vector_vlc, 6, 63,
1912 &motion_vector_vlc_table[0][1], 2, 1,
1913 &motion_vector_vlc_table[0][0], 2, 1, 0);
1915 return allocate_tables(avctx);
1918 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1922 /// Release and shuffle frames after decode finishes
1923 static int update_frames(AVCodecContext *avctx)
1925 Vp3DecodeContext *s = avctx->priv_data;
1928 /* shuffle frames (last = current) */
1929 ff_thread_release_buffer(avctx, &s->last_frame);
1930 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
1935 ff_thread_release_buffer(avctx, &s->golden_frame);
1936 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
1940 ff_thread_release_buffer(avctx, &s->current_frame);
1945 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
1947 ff_thread_release_buffer(s->avctx, dst);
1948 if (src->f->data[0])
1949 return ff_thread_ref_frame(dst, src);
1953 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
1956 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
1957 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
1958 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
1963 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1965 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1966 int qps_changed = 0, i, err;
1968 #define copy_fields(to, from, start_field, end_field) \
1969 memcpy(&to->start_field, &from->start_field, \
1970 (char *) &to->end_field - (char *) &to->start_field)
1972 if (!s1->current_frame.f->data[0] ||
1973 s->width != s1->width || s->height != s1->height) {
1980 if (!s->current_frame.f)
1981 return AVERROR(ENOMEM);
1982 // init tables if the first frame hasn't been decoded
1983 if (!s->current_frame.f->data[0]) {
1984 int y_fragment_count, c_fragment_count;
1986 err = allocate_tables(dst);
1989 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1990 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1991 memcpy(s->motion_val[0], s1->motion_val[0],
1992 y_fragment_count * sizeof(*s->motion_val[0]));
1993 memcpy(s->motion_val[1], s1->motion_val[1],
1994 c_fragment_count * sizeof(*s->motion_val[1]));
1997 // copy previous frame data
1998 if ((err = ref_frames(s, s1)) < 0)
2001 s->keyframe = s1->keyframe;
2003 // copy qscale data if necessary
2004 for (i = 0; i < 3; i++) {
2005 if (s->qps[i] != s1->qps[1]) {
2007 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2011 if (s->qps[0] != s1->qps[0])
2012 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2013 sizeof(s->bounding_values_array));
2016 copy_fields(s, s1, qps, superblock_count);
2020 return update_frames(dst);
2024 static int vp3_decode_frame(AVCodecContext *avctx,
2025 void *data, int *got_frame,
2028 AVFrame *frame = data;
2029 const uint8_t *buf = avpkt->data;
2030 int buf_size = avpkt->size;
2031 Vp3DecodeContext *s = avctx->priv_data;
2035 if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2038 #if CONFIG_THEORA_DECODER
2039 if (s->theora && get_bits1(&gb)) {
2040 int type = get_bits(&gb, 7);
2041 skip_bits_long(&gb, 6*8); /* "theora" */
2043 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2044 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2045 return AVERROR_PATCHWELCOME;
2048 vp3_decode_end(avctx);
2049 ret = theora_decode_header(avctx, &gb);
2052 ret = vp3_decode_init(avctx);
2054 vp3_decode_end(avctx);
2058 } else if (type == 2) {
2059 vp3_decode_end(avctx);
2060 ret = theora_decode_tables(avctx, &gb);
2062 ret = vp3_decode_init(avctx);
2064 vp3_decode_end(avctx);
2070 av_log(avctx, AV_LOG_ERROR,
2071 "Header packet passed to frame decoder, skipping\n");
2076 s->keyframe = !get_bits1(&gb);
2077 if (!s->all_fragments) {
2078 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2083 for (i = 0; i < 3; i++)
2084 s->last_qps[i] = s->qps[i];
2088 s->qps[s->nqps++] = get_bits(&gb, 6);
2089 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2090 for (i = s->nqps; i < 3; i++)
2093 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2094 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2095 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2097 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2098 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2099 : AVDISCARD_NONKEY);
2101 if (s->qps[0] != s->last_qps[0])
2102 init_loop_filter(s);
2104 for (i = 0; i < s->nqps; i++)
2105 // reinit all dequantizers if the first one changed, because
2106 // the DC of the first quantizer must be used for all matrices
2107 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2108 init_dequantizer(s, i);
2110 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2113 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2114 : AV_PICTURE_TYPE_P;
2115 s->current_frame.f->key_frame = s->keyframe;
2116 if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2119 if (!s->edge_emu_buffer)
2120 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2124 skip_bits(&gb, 4); /* width code */
2125 skip_bits(&gb, 4); /* height code */
2127 s->version = get_bits(&gb, 5);
2128 if (avctx->frame_number == 0)
2129 av_log(s->avctx, AV_LOG_DEBUG,
2130 "VP version: %d\n", s->version);
2133 if (s->version || s->theora) {
2135 av_log(s->avctx, AV_LOG_ERROR,
2136 "Warning, unsupported keyframe coding type?!\n");
2137 skip_bits(&gb, 2); /* reserved? */
2140 if (!s->golden_frame.f->data[0]) {
2141 av_log(s->avctx, AV_LOG_WARNING,
2142 "vp3: first frame not a keyframe\n");
2144 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2145 if (ff_thread_get_buffer(avctx, &s->golden_frame,
2146 AV_GET_BUFFER_FLAG_REF) < 0)
2148 ff_thread_release_buffer(avctx, &s->last_frame);
2149 if ((ret = ff_thread_ref_frame(&s->last_frame,
2150 &s->golden_frame)) < 0)
2152 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2156 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2157 ff_thread_finish_setup(avctx);
2159 if (unpack_superblocks(s, &gb)) {
2160 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2163 if (unpack_modes(s, &gb)) {
2164 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2167 if (unpack_vectors(s, &gb)) {
2168 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2171 if (unpack_block_qpis(s, &gb)) {
2172 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2175 if (unpack_dct_coeffs(s, &gb)) {
2176 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2180 for (i = 0; i < 3; i++) {
2181 int height = s->height >> (i && s->chroma_y_shift);
2182 if (s->flipped_image)
2183 s->data_offset[i] = 0;
2185 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2188 s->last_slice_end = 0;
2189 for (i = 0; i < s->c_superblock_height; i++)
2192 // filter the last row
2193 for (i = 0; i < 3; i++) {
2194 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2195 apply_loop_filter(s, i, row, row + 1);
2197 vp3_draw_horiz_band(s, s->height);
2199 /* output frame, offset as needed */
2200 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2203 frame->crop_left = s->offset_x;
2204 frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
2205 frame->crop_top = s->offset_y;
2206 frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2210 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2211 ret = update_frames(avctx);
2219 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2221 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2222 av_frame_unref(s->current_frame.f);
2227 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2229 Vp3DecodeContext *s = avctx->priv_data;
2231 if (get_bits1(gb)) {
2233 if (s->entries >= 32) { /* overflow */
2234 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2237 token = get_bits(gb, 5);
2238 ff_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2239 s->hti, s->hbits, token, s->entries, s->huff_code_size);
2240 s->huffman_table[s->hti][token][0] = s->hbits;
2241 s->huffman_table[s->hti][token][1] = s->huff_code_size;
2244 if (s->huff_code_size >= 32) { /* overflow */
2245 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2248 s->huff_code_size++;
2250 if (read_huffman_tree(avctx, gb))
2253 if (read_huffman_tree(avctx, gb))
2256 s->huff_code_size--;
2262 static int vp3_init_thread_copy(AVCodecContext *avctx)
2264 Vp3DecodeContext *s = avctx->priv_data;
2266 s->superblock_coding = NULL;
2267 s->all_fragments = NULL;
2268 s->coded_fragment_list[0] = NULL;
2269 s-> kf_coded_fragment_list= NULL;
2270 s->nkf_coded_fragment_list= NULL;
2271 s->dct_tokens_base = NULL;
2272 s->superblock_fragments = NULL;
2273 s->macroblock_coding = NULL;
2274 s->motion_val[0] = NULL;
2275 s->motion_val[1] = NULL;
2276 s->edge_emu_buffer = NULL;
2278 return init_frames(s);
2282 #if CONFIG_THEORA_DECODER
2283 static const enum AVPixelFormat theora_pix_fmts[4] = {
2284 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2287 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2289 Vp3DecodeContext *s = avctx->priv_data;
2290 int visible_width, visible_height, colorspace;
2291 uint8_t offset_x = 0, offset_y = 0;
2293 AVRational fps, aspect;
2295 s->theora_header = 0;
2296 s->theora = get_bits_long(gb, 24);
2297 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2299 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2300 * but previous versions have the image flipped relative to vp3 */
2301 if (s->theora < 0x030200) {
2302 s->flipped_image = 1;
2303 av_log(avctx, AV_LOG_DEBUG,
2304 "Old (<alpha3) Theora bitstream, flipped image\n");
2308 s->width = get_bits(gb, 16) << 4;
2310 s->height = get_bits(gb, 16) << 4;
2312 if (s->theora >= 0x030200) {
2313 visible_width = get_bits_long(gb, 24);
2314 visible_height = get_bits_long(gb, 24);
2316 offset_x = get_bits(gb, 8); /* offset x */
2317 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2321 if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2322 visible_width + offset_x > s->width ||
2323 visible_height + offset_y > s->height) {
2324 av_log(avctx, AV_LOG_ERROR,
2325 "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2326 visible_width, visible_height, offset_x, offset_y,
2327 s->width, s->height);
2328 return AVERROR_INVALIDDATA;
2331 fps.num = get_bits_long(gb, 32);
2332 fps.den = get_bits_long(gb, 32);
2333 if (fps.num && fps.den) {
2334 if (fps.num < 0 || fps.den < 0) {
2335 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2336 return AVERROR_INVALIDDATA;
2338 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2339 fps.den, fps.num, 1 << 30);
2342 aspect.num = get_bits_long(gb, 24);
2343 aspect.den = get_bits_long(gb, 24);
2344 if (aspect.num && aspect.den) {
2345 av_reduce(&avctx->sample_aspect_ratio.num,
2346 &avctx->sample_aspect_ratio.den,
2347 aspect.num, aspect.den, 1 << 30);
2348 ff_set_sar(avctx, avctx->sample_aspect_ratio);
2351 if (s->theora < 0x030200)
2352 skip_bits(gb, 5); /* keyframe frequency force */
2353 colorspace = get_bits(gb, 8);
2354 skip_bits(gb, 24); /* bitrate */
2356 skip_bits(gb, 6); /* quality hint */
2358 if (s->theora >= 0x030200) {
2359 skip_bits(gb, 5); /* keyframe frequency force */
2360 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2361 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2362 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2363 return AVERROR_INVALIDDATA;
2365 skip_bits(gb, 3); /* reserved */
2367 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2369 ret = ff_set_dimensions(avctx, s->width, s->height);
2372 if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2373 avctx->width = visible_width;
2374 avctx->height = visible_height;
2375 // translate offsets from theora axis ([0,0] lower left)
2376 // to normal axis ([0,0] upper left)
2377 s->offset_x = offset_x;
2378 s->offset_y = s->height - visible_height - offset_y;
2381 if (colorspace == 1)
2382 avctx->color_primaries = AVCOL_PRI_BT470M;
2383 else if (colorspace == 2)
2384 avctx->color_primaries = AVCOL_PRI_BT470BG;
2386 if (colorspace == 1 || colorspace == 2) {
2387 avctx->colorspace = AVCOL_SPC_BT470BG;
2388 avctx->color_trc = AVCOL_TRC_BT709;
2391 s->theora_header = 1;
2395 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2397 Vp3DecodeContext *s = avctx->priv_data;
2398 int i, n, matrices, inter, plane;
2400 if (!s->theora_header)
2401 return AVERROR_INVALIDDATA;
2403 if (s->theora >= 0x030200) {
2404 n = get_bits(gb, 3);
2405 /* loop filter limit values table */
2407 for (i = 0; i < 64; i++)
2408 s->filter_limit_values[i] = get_bits(gb, n);
2411 if (s->theora >= 0x030200)
2412 n = get_bits(gb, 4) + 1;
2415 /* quality threshold table */
2416 for (i = 0; i < 64; i++)
2417 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2419 if (s->theora >= 0x030200)
2420 n = get_bits(gb, 4) + 1;
2423 /* dc scale factor table */
2424 for (i = 0; i < 64; i++)
2425 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2427 if (s->theora >= 0x030200)
2428 matrices = get_bits(gb, 9) + 1;
2432 if (matrices > 384) {
2433 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2437 for (n = 0; n < matrices; n++)
2438 for (i = 0; i < 64; i++)
2439 s->base_matrix[n][i] = get_bits(gb, 8);
2441 for (inter = 0; inter <= 1; inter++) {
2442 for (plane = 0; plane <= 2; plane++) {
2444 if (inter || plane > 0)
2445 newqr = get_bits1(gb);
2448 if (inter && get_bits1(gb)) {
2452 qtj = (3 * inter + plane - 1) / 3;
2453 plj = (plane + 2) % 3;
2455 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
2456 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
2457 sizeof(s->qr_size[0][0]));
2458 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
2459 sizeof(s->qr_base[0][0]));
2465 i = get_bits(gb, av_log2(matrices - 1) + 1);
2466 if (i >= matrices) {
2467 av_log(avctx, AV_LOG_ERROR,
2468 "invalid base matrix index\n");
2471 s->qr_base[inter][plane][qri] = i;
2474 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
2475 s->qr_size[inter][plane][qri++] = i;
2480 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2483 s->qr_count[inter][plane] = qri;
2488 /* Huffman tables */
2489 for (s->hti = 0; s->hti < 80; s->hti++) {
2491 s->huff_code_size = 1;
2492 if (!get_bits1(gb)) {
2494 if (read_huffman_tree(avctx, gb))
2497 if (read_huffman_tree(avctx, gb))
2502 s->theora_tables = 1;
2507 static av_cold int theora_decode_init(AVCodecContext *avctx)
2509 Vp3DecodeContext *s = avctx->priv_data;
2512 const uint8_t *header_start[3];
2517 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2521 if (!avctx->extradata_size) {
2522 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2526 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2527 42, header_start, header_len) < 0) {
2528 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2532 for (i = 0; i < 3; i++) {
2533 if (header_len[i] <= 0)
2535 ret = init_get_bits8(&gb, header_start[i], header_len[i]);
2539 ptype = get_bits(&gb, 8);
2541 if (!(ptype & 0x80)) {
2542 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2546 // FIXME: Check for this as well.
2547 skip_bits_long(&gb, 6 * 8); /* "theora" */
2551 if (theora_decode_header(avctx, &gb) < 0)
2555 // FIXME: is this needed? it breaks sometimes
2556 // theora_decode_comments(avctx, gb);
2559 if (theora_decode_tables(avctx, &gb))
2563 av_log(avctx, AV_LOG_ERROR,
2564 "Unknown Theora config packet: %d\n", ptype & ~0x80);
2567 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
2568 av_log(avctx, AV_LOG_WARNING,
2569 "%d bits left in packet %X\n",
2570 8 * header_len[i] - get_bits_count(&gb), ptype);
2571 if (s->theora < 0x030200)
2575 return vp3_decode_init(avctx);
2578 AVCodec ff_theora_decoder = {
2580 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2581 .type = AVMEDIA_TYPE_VIDEO,
2582 .id = AV_CODEC_ID_THEORA,
2583 .priv_data_size = sizeof(Vp3DecodeContext),
2584 .init = theora_decode_init,
2585 .close = vp3_decode_end,
2586 .decode = vp3_decode_frame,
2587 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
2588 AV_CODEC_CAP_FRAME_THREADS,
2589 .flush = vp3_decode_flush,
2590 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2591 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
2592 .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING,
2596 AVCodec ff_vp3_decoder = {
2598 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2599 .type = AVMEDIA_TYPE_VIDEO,
2600 .id = AV_CODEC_ID_VP3,
2601 .priv_data_size = sizeof(Vp3DecodeContext),
2602 .init = vp3_decode_init,
2603 .close = vp3_decode_end,
2604 .decode = vp3_decode_frame,
2605 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
2606 AV_CODEC_CAP_FRAME_THREADS,
2607 .flush = vp3_decode_flush,
2608 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2609 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),