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;
934 static inline int get_eob_run(GetBitContext *gb, int token)
936 int v = eob_run_table[token].base;
937 if (eob_run_table[token].bits)
938 v += get_bits(gb, eob_run_table[token].bits);
942 static inline int get_coeff(GetBitContext *gb, int token, int16_t *coeff)
944 int bits_to_get, zero_run;
946 bits_to_get = coeff_get_bits[token];
948 bits_to_get = get_bits(gb, bits_to_get);
949 *coeff = coeff_tables[token][bits_to_get];
951 zero_run = zero_run_base[token];
952 if (zero_run_get_bits[token])
953 zero_run += get_bits(gb, zero_run_get_bits[token]);
959 * This function is called by unpack_dct_coeffs() to extract the VLCs from
960 * the bitstream. The VLCs encode tokens which are used to unpack DCT
961 * data. This function unpacks all the VLCs for either the Y plane or both
962 * C planes, and is called for DC coefficients or different AC coefficient
963 * levels (since different coefficient types require different VLC tables.
965 * This function returns a residual eob run. E.g, if a particular token gave
966 * instructions to EOB the next 5 fragments and there were only 2 fragments
967 * left in the current fragment range, 3 would be returned so that it could
968 * be passed into the next call to this same function.
970 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
971 VLC *table, int coeff_index,
981 int num_coeffs = s->num_coded_frags[plane][coeff_index];
982 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
984 /* local references to structure members to avoid repeated dereferences */
985 int *coded_fragment_list = s->coded_fragment_list[plane];
986 Vp3Fragment *all_fragments = s->all_fragments;
987 VLC_TYPE(*vlc_table)[2] = table->table;
989 if (num_coeffs < 0) {
990 av_log(s->avctx, AV_LOG_ERROR,
991 "Invalid number of coefficients at level %d\n", coeff_index);
992 return AVERROR_INVALIDDATA;
995 if (eob_run > num_coeffs) {
997 blocks_ended = num_coeffs;
998 eob_run -= num_coeffs;
1001 blocks_ended = eob_run;
1005 // insert fake EOB token to cover the split between planes or zzi
1007 dct_tokens[j++] = blocks_ended << 2;
1009 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1010 /* decode a VLC into a token */
1011 token = get_vlc2(gb, vlc_table, 11, 3);
1012 /* use the token to get a zero run, a coefficient, and an eob run */
1013 if ((unsigned) token <= 6U) {
1014 eob_run = get_eob_run(gb, token);
1018 // record only the number of blocks ended in this plane,
1019 // any spill will be recorded in the next plane.
1020 if (eob_run > num_coeffs - coeff_i) {
1021 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1022 blocks_ended += num_coeffs - coeff_i;
1023 eob_run -= num_coeffs - coeff_i;
1024 coeff_i = num_coeffs;
1026 dct_tokens[j++] = TOKEN_EOB(eob_run);
1027 blocks_ended += eob_run;
1031 } else if (token >= 0) {
1032 zero_run = get_coeff(gb, token, &coeff);
1035 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1037 // Save DC into the fragment structure. DC prediction is
1038 // done in raster order, so the actual DC can't be in with
1039 // other tokens. We still need the token in dct_tokens[]
1040 // however, or else the structure collapses on itself.
1042 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1044 dct_tokens[j++] = TOKEN_COEFF(coeff);
1047 if (coeff_index + zero_run > 64) {
1048 av_log(s->avctx, AV_LOG_DEBUG,
1049 "Invalid zero run of %d with %d coeffs left\n",
1050 zero_run, 64 - coeff_index);
1051 zero_run = 64 - coeff_index;
1054 // zero runs code multiple coefficients,
1055 // so don't try to decode coeffs for those higher levels
1056 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1057 s->num_coded_frags[plane][i]--;
1060 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1065 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1066 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1068 // decrement the number of blocks that have higher coefficients for each
1069 // EOB run at this level
1071 for (i = coeff_index + 1; i < 64; i++)
1072 s->num_coded_frags[plane][i] -= blocks_ended;
1074 // setup the next buffer
1076 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1077 else if (coeff_index < 63)
1078 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1083 static void reverse_dc_prediction(Vp3DecodeContext *s,
1086 int fragment_height);
1088 * This function unpacks all of the DCT coefficient data from the
1091 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1098 int residual_eob_run = 0;
1102 s->dct_tokens[0][0] = s->dct_tokens_base;
1104 if (get_bits_left(gb) < 16)
1105 return AVERROR_INVALIDDATA;
1107 /* fetch the DC table indexes */
1108 dc_y_table = get_bits(gb, 4);
1109 dc_c_table = get_bits(gb, 4);
1111 /* unpack the Y plane DC coefficients */
1112 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1113 0, residual_eob_run);
1114 if (residual_eob_run < 0)
1115 return residual_eob_run;
1116 if (get_bits_left(gb) < 8)
1117 return AVERROR_INVALIDDATA;
1119 /* reverse prediction of the Y-plane DC coefficients */
1120 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1122 /* unpack the C plane DC coefficients */
1123 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1124 1, residual_eob_run);
1125 if (residual_eob_run < 0)
1126 return residual_eob_run;
1127 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1128 2, residual_eob_run);
1129 if (residual_eob_run < 0)
1130 return residual_eob_run;
1132 /* reverse prediction of the C-plane DC coefficients */
1133 if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1134 reverse_dc_prediction(s, s->fragment_start[1],
1135 s->fragment_width[1], s->fragment_height[1]);
1136 reverse_dc_prediction(s, s->fragment_start[2],
1137 s->fragment_width[1], s->fragment_height[1]);
1140 if (get_bits_left(gb) < 8)
1141 return AVERROR_INVALIDDATA;
1142 /* fetch the AC table indexes */
1143 ac_y_table = get_bits(gb, 4);
1144 ac_c_table = get_bits(gb, 4);
1146 /* build tables of AC VLC tables */
1147 for (i = 1; i <= 5; i++) {
1148 y_tables[i] = &s->ac_vlc_1[ac_y_table];
1149 c_tables[i] = &s->ac_vlc_1[ac_c_table];
1151 for (i = 6; i <= 14; i++) {
1152 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1153 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1155 for (i = 15; i <= 27; i++) {
1156 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1157 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1159 for (i = 28; i <= 63; i++) {
1160 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1161 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1164 /* decode all AC coefficients */
1165 for (i = 1; i <= 63; i++) {
1166 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1167 0, residual_eob_run);
1168 if (residual_eob_run < 0)
1169 return residual_eob_run;
1171 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1172 1, residual_eob_run);
1173 if (residual_eob_run < 0)
1174 return residual_eob_run;
1175 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1176 2, residual_eob_run);
1177 if (residual_eob_run < 0)
1178 return residual_eob_run;
1185 * This function reverses the DC prediction for each coded fragment in
1186 * the frame. Much of this function is adapted directly from the original
1189 #define COMPATIBLE_FRAME(x) \
1190 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1191 #define DC_COEFF(u) s->all_fragments[u].dc
1193 static void reverse_dc_prediction(Vp3DecodeContext *s,
1196 int fragment_height)
1204 int i = first_fragment;
1208 /* DC values for the left, up-left, up, and up-right fragments */
1209 int vl, vul, vu, vur;
1211 /* indexes for the left, up-left, up, and up-right fragments */
1215 * The 6 fields mean:
1216 * 0: up-left multiplier
1218 * 2: up-right multiplier
1219 * 3: left multiplier
1221 static const int predictor_transform[16][4] = {
1223 { 0, 0, 0, 128 }, // PL
1224 { 0, 0, 128, 0 }, // PUR
1225 { 0, 0, 53, 75 }, // PUR|PL
1226 { 0, 128, 0, 0 }, // PU
1227 { 0, 64, 0, 64 }, // PU |PL
1228 { 0, 128, 0, 0 }, // PU |PUR
1229 { 0, 0, 53, 75 }, // PU |PUR|PL
1230 { 128, 0, 0, 0 }, // PUL
1231 { 0, 0, 0, 128 }, // PUL|PL
1232 { 64, 0, 64, 0 }, // PUL|PUR
1233 { 0, 0, 53, 75 }, // PUL|PUR|PL
1234 { 0, 128, 0, 0 }, // PUL|PU
1235 { -104, 116, 0, 116 }, // PUL|PU |PL
1236 { 24, 80, 24, 0 }, // PUL|PU |PUR
1237 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1240 /* This table shows which types of blocks can use other blocks for
1241 * prediction. For example, INTRA is the only mode in this table to
1242 * have a frame number of 0. That means INTRA blocks can only predict
1243 * from other INTRA blocks. There are 2 golden frame coding types;
1244 * blocks encoding in these modes can only predict from other blocks
1245 * that were encoded with these 1 of these 2 modes. */
1246 static const unsigned char compatible_frame[9] = {
1247 1, /* MODE_INTER_NO_MV */
1249 1, /* MODE_INTER_PLUS_MV */
1250 1, /* MODE_INTER_LAST_MV */
1251 1, /* MODE_INTER_PRIOR_MV */
1252 2, /* MODE_USING_GOLDEN */
1253 2, /* MODE_GOLDEN_MV */
1254 1, /* MODE_INTER_FOUR_MV */
1257 int current_frame_type;
1259 /* there is a last DC predictor for each of the 3 frame types */
1272 /* for each fragment row... */
1273 for (y = 0; y < fragment_height; y++) {
1274 /* for each fragment in a row... */
1275 for (x = 0; x < fragment_width; x++, i++) {
1277 /* reverse prediction if this block was coded */
1278 if (s->all_fragments[i].coding_method != MODE_COPY) {
1279 current_frame_type =
1280 compatible_frame[s->all_fragments[i].coding_method];
1286 if (COMPATIBLE_FRAME(l))
1290 u = i - fragment_width;
1292 if (COMPATIBLE_FRAME(u))
1295 ul = i - fragment_width - 1;
1297 if (COMPATIBLE_FRAME(ul))
1300 if (x + 1 < fragment_width) {
1301 ur = i - fragment_width + 1;
1303 if (COMPATIBLE_FRAME(ur))
1308 if (transform == 0) {
1309 /* if there were no fragments to predict from, use last
1311 predicted_dc = last_dc[current_frame_type];
1313 /* apply the appropriate predictor transform */
1315 (predictor_transform[transform][0] * vul) +
1316 (predictor_transform[transform][1] * vu) +
1317 (predictor_transform[transform][2] * vur) +
1318 (predictor_transform[transform][3] * vl);
1320 predicted_dc /= 128;
1322 /* check for outranging on the [ul u l] and
1323 * [ul u ur l] predictors */
1324 if ((transform == 15) || (transform == 13)) {
1325 if (FFABS(predicted_dc - vu) > 128)
1327 else if (FFABS(predicted_dc - vl) > 128)
1329 else if (FFABS(predicted_dc - vul) > 128)
1334 /* at long last, apply the predictor */
1335 DC_COEFF(i) += predicted_dc;
1337 last_dc[current_frame_type] = DC_COEFF(i);
1343 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1344 int ystart, int yend)
1347 int *bounding_values = s->bounding_values_array + 127;
1349 int width = s->fragment_width[!!plane];
1350 int height = s->fragment_height[!!plane];
1351 int fragment = s->fragment_start[plane] + ystart * width;
1352 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1353 uint8_t *plane_data = s->current_frame.f->data[plane];
1354 if (!s->flipped_image)
1356 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1358 for (y = ystart; y < yend; y++) {
1359 for (x = 0; x < width; x++) {
1360 /* This code basically just deblocks on the edges of coded blocks.
1361 * However, it has to be much more complicated because of the
1362 * brain damaged deblock ordering used in VP3/Theora. Order matters
1363 * because some pixels get filtered twice. */
1364 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1365 /* do not perform left edge filter for left columns frags */
1367 s->vp3dsp.h_loop_filter(
1369 stride, bounding_values);
1372 /* do not perform top edge filter for top row fragments */
1374 s->vp3dsp.v_loop_filter(
1376 stride, bounding_values);
1379 /* do not perform right edge filter for right column
1380 * fragments or if right fragment neighbor is also coded
1381 * in this frame (it will be filtered in next iteration) */
1382 if ((x < width - 1) &&
1383 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1384 s->vp3dsp.h_loop_filter(
1385 plane_data + 8 * x + 8,
1386 stride, bounding_values);
1389 /* do not perform bottom edge filter for bottom row
1390 * fragments or if bottom fragment neighbor is also coded
1391 * in this frame (it will be filtered in the next row) */
1392 if ((y < height - 1) &&
1393 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1394 s->vp3dsp.v_loop_filter(
1395 plane_data + 8 * x + 8 * stride,
1396 stride, bounding_values);
1402 plane_data += 8 * stride;
1407 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1408 * for the next block in coding order
1410 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1411 int plane, int inter, int16_t block[64])
1413 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1414 uint8_t *perm = s->idct_scantable;
1418 int token = *s->dct_tokens[plane][i];
1419 switch (token & 3) {
1421 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1422 s->dct_tokens[plane][i]++;
1424 *s->dct_tokens[plane][i] = token & ~3;
1427 s->dct_tokens[plane][i]++;
1428 i += (token >> 2) & 0x7f;
1430 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1433 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1437 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1438 s->dct_tokens[plane][i++]++;
1440 default: // shouldn't happen
1444 // return value is expected to be a valid level
1447 // the actual DC+prediction is in the fragment structure
1448 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1453 * called when all pixels up to row y are complete
1455 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1458 int offset[AV_NUM_DATA_POINTERS];
1460 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1461 int y_flipped = s->flipped_image ? s->height - y : y;
1463 /* At the end of the frame, report INT_MAX instead of the height of
1464 * the frame. This makes the other threads' ff_thread_await_progress()
1465 * calls cheaper, because they don't have to clip their values. */
1466 ff_thread_report_progress(&s->current_frame,
1467 y_flipped == s->height ? INT_MAX
1472 if (!s->avctx->draw_horiz_band)
1475 h = y - s->last_slice_end;
1476 s->last_slice_end = y;
1479 if (!s->flipped_image)
1480 y = s->height - y - h;
1482 cy = y >> s->chroma_y_shift;
1483 offset[0] = s->current_frame.f->linesize[0] * y;
1484 offset[1] = s->current_frame.f->linesize[1] * cy;
1485 offset[2] = s->current_frame.f->linesize[2] * cy;
1486 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1490 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1494 * Wait for the reference frame of the current fragment.
1495 * The progress value is in luma pixel rows.
1497 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1498 int motion_y, int y)
1500 ThreadFrame *ref_frame;
1502 int border = motion_y & 1;
1504 if (fragment->coding_method == MODE_USING_GOLDEN ||
1505 fragment->coding_method == MODE_GOLDEN_MV)
1506 ref_frame = &s->golden_frame;
1508 ref_frame = &s->last_frame;
1510 ref_row = y + (motion_y >> 1);
1511 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1513 ff_thread_await_progress(ref_frame, ref_row, 0);
1517 * Perform the final rendering for a particular slice of data.
1518 * The slice number ranges from 0..(c_superblock_height - 1).
1520 static void render_slice(Vp3DecodeContext *s, int slice)
1522 int x, y, i, j, fragment;
1523 int16_t *block = s->block;
1524 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1525 int motion_halfpel_index;
1526 uint8_t *motion_source;
1527 int plane, first_pixel;
1529 if (slice >= s->c_superblock_height)
1532 for (plane = 0; plane < 3; plane++) {
1533 uint8_t *output_plane = s->current_frame.f->data[plane] +
1534 s->data_offset[plane];
1535 uint8_t *last_plane = s->last_frame.f->data[plane] +
1536 s->data_offset[plane];
1537 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
1538 s->data_offset[plane];
1539 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1540 int plane_width = s->width >> (plane && s->chroma_x_shift);
1541 int plane_height = s->height >> (plane && s->chroma_y_shift);
1542 int8_t(*motion_val)[2] = s->motion_val[!!plane];
1544 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
1545 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
1546 int slice_width = plane ? s->c_superblock_width
1547 : s->y_superblock_width;
1549 int fragment_width = s->fragment_width[!!plane];
1550 int fragment_height = s->fragment_height[!!plane];
1551 int fragment_start = s->fragment_start[plane];
1553 int do_await = !plane && HAVE_THREADS &&
1554 (s->avctx->active_thread_type & FF_THREAD_FRAME);
1556 if (!s->flipped_image)
1558 if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
1561 /* for each superblock row in the slice (both of them)... */
1562 for (; sb_y < slice_height; sb_y++) {
1563 /* for each superblock in a row... */
1564 for (sb_x = 0; sb_x < slice_width; sb_x++) {
1565 /* for each block in a superblock... */
1566 for (j = 0; j < 16; j++) {
1567 x = 4 * sb_x + hilbert_offset[j][0];
1568 y = 4 * sb_y + hilbert_offset[j][1];
1569 fragment = y * fragment_width + x;
1571 i = fragment_start + fragment;
1574 if (x >= fragment_width || y >= fragment_height)
1577 first_pixel = 8 * y * stride + 8 * x;
1580 s->all_fragments[i].coding_method != MODE_INTRA)
1581 await_reference_row(s, &s->all_fragments[i],
1582 motion_val[fragment][1],
1583 (16 * y) >> s->chroma_y_shift);
1585 /* transform if this block was coded */
1586 if (s->all_fragments[i].coding_method != MODE_COPY) {
1587 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1588 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1589 motion_source = golden_plane;
1591 motion_source = last_plane;
1593 motion_source += first_pixel;
1594 motion_halfpel_index = 0;
1596 /* sort out the motion vector if this fragment is coded
1597 * using a motion vector method */
1598 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1599 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1601 motion_x = motion_val[fragment][0];
1602 motion_y = motion_val[fragment][1];
1604 src_x = (motion_x >> 1) + 8 * x;
1605 src_y = (motion_y >> 1) + 8 * y;
1607 motion_halfpel_index = motion_x & 0x01;
1608 motion_source += (motion_x >> 1);
1610 motion_halfpel_index |= (motion_y & 0x01) << 1;
1611 motion_source += ((motion_y >> 1) * stride);
1613 if (src_x < 0 || src_y < 0 ||
1614 src_x + 9 >= plane_width ||
1615 src_y + 9 >= plane_height) {
1616 uint8_t *temp = s->edge_emu_buffer;
1620 s->vdsp.emulated_edge_mc(temp, motion_source,
1625 motion_source = temp;
1629 /* first, take care of copying a block from either the
1630 * previous or the golden frame */
1631 if (s->all_fragments[i].coding_method != MODE_INTRA) {
1632 /* Note, it is possible to implement all MC cases
1633 * with put_no_rnd_pixels_l2 which would look more
1634 * like the VP3 source but this would be slower as
1635 * put_no_rnd_pixels_tab is better optimized */
1636 if (motion_halfpel_index != 3) {
1637 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1638 output_plane + first_pixel,
1639 motion_source, stride, 8);
1641 /* d is 0 if motion_x and _y have the same sign,
1643 int d = (motion_x ^ motion_y) >> 31;
1644 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
1646 motion_source + stride + 1 + d,
1651 /* invert DCT and place (or add) in final output */
1653 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1654 vp3_dequant(s, s->all_fragments + i,
1656 s->vp3dsp.idct_put(output_plane + first_pixel,
1660 if (vp3_dequant(s, s->all_fragments + i,
1662 s->vp3dsp.idct_add(output_plane + first_pixel,
1666 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
1671 /* copy directly from the previous frame */
1672 s->hdsp.put_pixels_tab[1][0](
1673 output_plane + first_pixel,
1674 last_plane + first_pixel,
1680 // Filter up to the last row in the superblock row
1681 if (!s->skip_loop_filter)
1682 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
1683 FFMIN(4 * sb_y + 3, fragment_height - 1));
1687 /* this looks like a good place for slice dispatch... */
1689 * if (slice == s->macroblock_height - 1)
1690 * dispatch (both last slice & 2nd-to-last slice);
1691 * else if (slice > 0)
1692 * dispatch (slice - 1);
1695 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
1699 /// Allocate tables for per-frame data in Vp3DecodeContext
1700 static av_cold int allocate_tables(AVCodecContext *avctx)
1702 Vp3DecodeContext *s = avctx->priv_data;
1703 int y_fragment_count, c_fragment_count;
1707 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1708 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1710 s->superblock_coding = av_mallocz(s->superblock_count);
1711 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
1713 s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
1714 s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
1715 memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
1717 s->dct_tokens_base = av_mallocz_array(s->fragment_count,
1718 64 * sizeof(*s->dct_tokens_base));
1719 s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
1720 s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
1722 /* work out the block mapping tables */
1723 s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
1724 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
1726 if (!s->superblock_coding || !s->all_fragments ||
1727 !s->dct_tokens_base || !s->kf_coded_fragment_list ||
1728 !s->nkf_coded_fragment_list ||
1729 !s->superblock_fragments || !s->macroblock_coding ||
1730 !s->motion_val[0] || !s->motion_val[1]) {
1731 vp3_decode_end(avctx);
1735 init_block_mapping(s);
1740 static av_cold int init_frames(Vp3DecodeContext *s)
1742 s->current_frame.f = av_frame_alloc();
1743 s->last_frame.f = av_frame_alloc();
1744 s->golden_frame.f = av_frame_alloc();
1746 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
1747 av_frame_free(&s->current_frame.f);
1748 av_frame_free(&s->last_frame.f);
1749 av_frame_free(&s->golden_frame.f);
1750 return AVERROR(ENOMEM);
1756 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1758 Vp3DecodeContext *s = avctx->priv_data;
1759 int i, inter, plane, ret;
1762 int y_fragment_count, c_fragment_count;
1764 ret = init_frames(s);
1768 avctx->internal->allocate_progress = 1;
1770 if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
1776 s->width = FFALIGN(avctx->coded_width, 16);
1777 s->height = FFALIGN(avctx->coded_height, 16);
1778 if (avctx->codec_id != AV_CODEC_ID_THEORA)
1779 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
1780 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1781 ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
1782 ff_videodsp_init(&s->vdsp, 8);
1783 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
1785 for (i = 0; i < 64; i++) {
1786 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
1787 s->idct_permutation[i] = TRANSPOSE(i);
1788 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
1792 /* initialize to an impossible value which will force a recalculation
1793 * in the first frame decode */
1794 for (i = 0; i < 3; i++)
1797 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1801 s->y_superblock_width = (s->width + 31) / 32;
1802 s->y_superblock_height = (s->height + 31) / 32;
1803 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1805 /* work out the dimensions for the C planes */
1806 c_width = s->width >> s->chroma_x_shift;
1807 c_height = s->height >> s->chroma_y_shift;
1808 s->c_superblock_width = (c_width + 31) / 32;
1809 s->c_superblock_height = (c_height + 31) / 32;
1810 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1812 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1813 s->u_superblock_start = s->y_superblock_count;
1814 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1816 s->macroblock_width = (s->width + 15) / 16;
1817 s->macroblock_height = (s->height + 15) / 16;
1818 s->macroblock_count = s->macroblock_width * s->macroblock_height;
1820 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1821 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1822 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
1823 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
1825 /* fragment count covers all 8x8 blocks for all 3 planes */
1826 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1827 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1828 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
1829 s->fragment_start[1] = y_fragment_count;
1830 s->fragment_start[2] = y_fragment_count + c_fragment_count;
1832 if (!s->theora_tables) {
1833 for (i = 0; i < 64; i++) {
1834 s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1835 s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1836 s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1837 s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1838 s->base_matrix[2][i] = vp31_inter_dequant[i];
1839 s->filter_limit_values[i] = vp31_filter_limit_values[i];
1842 for (inter = 0; inter < 2; inter++) {
1843 for (plane = 0; plane < 3; plane++) {
1844 s->qr_count[inter][plane] = 1;
1845 s->qr_size[inter][plane][0] = 63;
1846 s->qr_base[inter][plane][0] =
1847 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
1851 /* init VLC tables */
1852 for (i = 0; i < 16; i++) {
1854 init_vlc(&s->dc_vlc[i], 11, 32,
1855 &dc_bias[i][0][1], 4, 2,
1856 &dc_bias[i][0][0], 4, 2, 0);
1858 /* group 1 AC histograms */
1859 init_vlc(&s->ac_vlc_1[i], 11, 32,
1860 &ac_bias_0[i][0][1], 4, 2,
1861 &ac_bias_0[i][0][0], 4, 2, 0);
1863 /* group 2 AC histograms */
1864 init_vlc(&s->ac_vlc_2[i], 11, 32,
1865 &ac_bias_1[i][0][1], 4, 2,
1866 &ac_bias_1[i][0][0], 4, 2, 0);
1868 /* group 3 AC histograms */
1869 init_vlc(&s->ac_vlc_3[i], 11, 32,
1870 &ac_bias_2[i][0][1], 4, 2,
1871 &ac_bias_2[i][0][0], 4, 2, 0);
1873 /* group 4 AC histograms */
1874 init_vlc(&s->ac_vlc_4[i], 11, 32,
1875 &ac_bias_3[i][0][1], 4, 2,
1876 &ac_bias_3[i][0][0], 4, 2, 0);
1879 for (i = 0; i < 16; i++) {
1881 if (init_vlc(&s->dc_vlc[i], 11, 32,
1882 &s->huffman_table[i][0][1], 8, 4,
1883 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
1886 /* group 1 AC histograms */
1887 if (init_vlc(&s->ac_vlc_1[i], 11, 32,
1888 &s->huffman_table[i + 16][0][1], 8, 4,
1889 &s->huffman_table[i + 16][0][0], 8, 4, 0) < 0)
1892 /* group 2 AC histograms */
1893 if (init_vlc(&s->ac_vlc_2[i], 11, 32,
1894 &s->huffman_table[i + 16 * 2][0][1], 8, 4,
1895 &s->huffman_table[i + 16 * 2][0][0], 8, 4, 0) < 0)
1898 /* group 3 AC histograms */
1899 if (init_vlc(&s->ac_vlc_3[i], 11, 32,
1900 &s->huffman_table[i + 16 * 3][0][1], 8, 4,
1901 &s->huffman_table[i + 16 * 3][0][0], 8, 4, 0) < 0)
1904 /* group 4 AC histograms */
1905 if (init_vlc(&s->ac_vlc_4[i], 11, 32,
1906 &s->huffman_table[i + 16 * 4][0][1], 8, 4,
1907 &s->huffman_table[i + 16 * 4][0][0], 8, 4, 0) < 0)
1912 init_vlc(&s->superblock_run_length_vlc, 6, 34,
1913 &superblock_run_length_vlc_table[0][1], 4, 2,
1914 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1916 init_vlc(&s->fragment_run_length_vlc, 5, 30,
1917 &fragment_run_length_vlc_table[0][1], 4, 2,
1918 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1920 init_vlc(&s->mode_code_vlc, 3, 8,
1921 &mode_code_vlc_table[0][1], 2, 1,
1922 &mode_code_vlc_table[0][0], 2, 1, 0);
1924 init_vlc(&s->motion_vector_vlc, 6, 63,
1925 &motion_vector_vlc_table[0][1], 2, 1,
1926 &motion_vector_vlc_table[0][0], 2, 1, 0);
1928 return allocate_tables(avctx);
1931 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1935 /// Release and shuffle frames after decode finishes
1936 static int update_frames(AVCodecContext *avctx)
1938 Vp3DecodeContext *s = avctx->priv_data;
1941 /* shuffle frames (last = current) */
1942 ff_thread_release_buffer(avctx, &s->last_frame);
1943 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
1948 ff_thread_release_buffer(avctx, &s->golden_frame);
1949 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
1953 ff_thread_release_buffer(avctx, &s->current_frame);
1958 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
1960 ff_thread_release_buffer(s->avctx, dst);
1961 if (src->f->data[0])
1962 return ff_thread_ref_frame(dst, src);
1966 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
1969 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
1970 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
1971 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
1976 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1978 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1979 int qps_changed = 0, i, err;
1981 #define copy_fields(to, from, start_field, end_field) \
1982 memcpy(&to->start_field, &from->start_field, \
1983 (char *) &to->end_field - (char *) &to->start_field)
1985 if (!s1->current_frame.f->data[0] ||
1986 s->width != s1->width || s->height != s1->height) {
1993 if (!s->current_frame.f)
1994 return AVERROR(ENOMEM);
1995 // init tables if the first frame hasn't been decoded
1996 if (!s->current_frame.f->data[0]) {
1997 int y_fragment_count, c_fragment_count;
1999 err = allocate_tables(dst);
2002 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2003 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2004 memcpy(s->motion_val[0], s1->motion_val[0],
2005 y_fragment_count * sizeof(*s->motion_val[0]));
2006 memcpy(s->motion_val[1], s1->motion_val[1],
2007 c_fragment_count * sizeof(*s->motion_val[1]));
2010 // copy previous frame data
2011 if ((err = ref_frames(s, s1)) < 0)
2014 s->keyframe = s1->keyframe;
2016 // copy qscale data if necessary
2017 for (i = 0; i < 3; i++) {
2018 if (s->qps[i] != s1->qps[1]) {
2020 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2024 if (s->qps[0] != s1->qps[0])
2025 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2026 sizeof(s->bounding_values_array));
2029 copy_fields(s, s1, qps, superblock_count);
2033 return update_frames(dst);
2037 static int vp3_decode_frame(AVCodecContext *avctx,
2038 void *data, int *got_frame,
2041 AVFrame *frame = data;
2042 const uint8_t *buf = avpkt->data;
2043 int buf_size = avpkt->size;
2044 Vp3DecodeContext *s = avctx->priv_data;
2048 if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2051 #if CONFIG_THEORA_DECODER
2052 if (s->theora && get_bits1(&gb)) {
2053 int type = get_bits(&gb, 7);
2054 skip_bits_long(&gb, 6*8); /* "theora" */
2056 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2057 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2058 return AVERROR_PATCHWELCOME;
2061 vp3_decode_end(avctx);
2062 ret = theora_decode_header(avctx, &gb);
2065 ret = vp3_decode_init(avctx);
2067 vp3_decode_end(avctx);
2071 } else if (type == 2) {
2072 vp3_decode_end(avctx);
2073 ret = theora_decode_tables(avctx, &gb);
2075 ret = vp3_decode_init(avctx);
2077 vp3_decode_end(avctx);
2083 av_log(avctx, AV_LOG_ERROR,
2084 "Header packet passed to frame decoder, skipping\n");
2089 s->keyframe = !get_bits1(&gb);
2090 if (!s->all_fragments) {
2091 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2096 for (i = 0; i < 3; i++)
2097 s->last_qps[i] = s->qps[i];
2101 s->qps[s->nqps++] = get_bits(&gb, 6);
2102 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2103 for (i = s->nqps; i < 3; i++)
2106 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2107 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2108 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2110 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2111 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2112 : AVDISCARD_NONKEY);
2114 if (s->qps[0] != s->last_qps[0])
2115 init_loop_filter(s);
2117 for (i = 0; i < s->nqps; i++)
2118 // reinit all dequantizers if the first one changed, because
2119 // the DC of the first quantizer must be used for all matrices
2120 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2121 init_dequantizer(s, i);
2123 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2126 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2127 : AV_PICTURE_TYPE_P;
2128 s->current_frame.f->key_frame = s->keyframe;
2129 if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2132 if (!s->edge_emu_buffer)
2133 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2137 skip_bits(&gb, 4); /* width code */
2138 skip_bits(&gb, 4); /* height code */
2140 s->version = get_bits(&gb, 5);
2141 if (avctx->frame_number == 0)
2142 av_log(s->avctx, AV_LOG_DEBUG,
2143 "VP version: %d\n", s->version);
2146 if (s->version || s->theora) {
2148 av_log(s->avctx, AV_LOG_ERROR,
2149 "Warning, unsupported keyframe coding type?!\n");
2150 skip_bits(&gb, 2); /* reserved? */
2153 if (!s->golden_frame.f->data[0]) {
2154 av_log(s->avctx, AV_LOG_WARNING,
2155 "vp3: first frame not a keyframe\n");
2157 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2158 if (ff_thread_get_buffer(avctx, &s->golden_frame,
2159 AV_GET_BUFFER_FLAG_REF) < 0)
2161 ff_thread_release_buffer(avctx, &s->last_frame);
2162 if ((ret = ff_thread_ref_frame(&s->last_frame,
2163 &s->golden_frame)) < 0)
2165 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2169 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2170 ff_thread_finish_setup(avctx);
2172 if (unpack_superblocks(s, &gb)) {
2173 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2176 if (unpack_modes(s, &gb)) {
2177 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2180 if (unpack_vectors(s, &gb)) {
2181 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2184 if (unpack_block_qpis(s, &gb)) {
2185 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2188 if (unpack_dct_coeffs(s, &gb)) {
2189 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2193 for (i = 0; i < 3; i++) {
2194 int height = s->height >> (i && s->chroma_y_shift);
2195 if (s->flipped_image)
2196 s->data_offset[i] = 0;
2198 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2201 s->last_slice_end = 0;
2202 for (i = 0; i < s->c_superblock_height; i++)
2205 // filter the last row
2206 for (i = 0; i < 3; i++) {
2207 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2208 apply_loop_filter(s, i, row, row + 1);
2210 vp3_draw_horiz_band(s, s->height);
2212 /* output frame, offset as needed */
2213 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2216 frame->crop_left = s->offset_x;
2217 frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
2218 frame->crop_top = s->offset_y;
2219 frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2223 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2224 ret = update_frames(avctx);
2232 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2234 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2235 av_frame_unref(s->current_frame.f);
2240 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2242 Vp3DecodeContext *s = avctx->priv_data;
2244 if (get_bits1(gb)) {
2246 if (s->entries >= 32) { /* overflow */
2247 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2250 token = get_bits(gb, 5);
2251 ff_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2252 s->hti, s->hbits, token, s->entries, s->huff_code_size);
2253 s->huffman_table[s->hti][token][0] = s->hbits;
2254 s->huffman_table[s->hti][token][1] = s->huff_code_size;
2257 if (s->huff_code_size >= 32) { /* overflow */
2258 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2261 s->huff_code_size++;
2263 if (read_huffman_tree(avctx, gb))
2266 if (read_huffman_tree(avctx, gb))
2269 s->huff_code_size--;
2275 static int vp3_init_thread_copy(AVCodecContext *avctx)
2277 Vp3DecodeContext *s = avctx->priv_data;
2279 s->superblock_coding = NULL;
2280 s->all_fragments = NULL;
2281 s->coded_fragment_list[0] = NULL;
2282 s-> kf_coded_fragment_list= NULL;
2283 s->nkf_coded_fragment_list= NULL;
2284 s->dct_tokens_base = NULL;
2285 s->superblock_fragments = NULL;
2286 s->macroblock_coding = NULL;
2287 s->motion_val[0] = NULL;
2288 s->motion_val[1] = NULL;
2289 s->edge_emu_buffer = NULL;
2291 return init_frames(s);
2295 #if CONFIG_THEORA_DECODER
2296 static const enum AVPixelFormat theora_pix_fmts[4] = {
2297 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2300 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2302 Vp3DecodeContext *s = avctx->priv_data;
2303 int visible_width, visible_height, colorspace;
2304 uint8_t offset_x = 0, offset_y = 0;
2306 AVRational fps, aspect;
2308 s->theora_header = 0;
2309 s->theora = get_bits_long(gb, 24);
2310 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2312 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2313 * but previous versions have the image flipped relative to vp3 */
2314 if (s->theora < 0x030200) {
2315 s->flipped_image = 1;
2316 av_log(avctx, AV_LOG_DEBUG,
2317 "Old (<alpha3) Theora bitstream, flipped image\n");
2321 s->width = get_bits(gb, 16) << 4;
2323 s->height = get_bits(gb, 16) << 4;
2325 if (s->theora >= 0x030200) {
2326 visible_width = get_bits_long(gb, 24);
2327 visible_height = get_bits_long(gb, 24);
2329 offset_x = get_bits(gb, 8); /* offset x */
2330 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2334 if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2335 visible_width + offset_x > s->width ||
2336 visible_height + offset_y > s->height) {
2337 av_log(avctx, AV_LOG_ERROR,
2338 "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2339 visible_width, visible_height, offset_x, offset_y,
2340 s->width, s->height);
2341 return AVERROR_INVALIDDATA;
2344 fps.num = get_bits_long(gb, 32);
2345 fps.den = get_bits_long(gb, 32);
2346 if (fps.num && fps.den) {
2347 if (fps.num < 0 || fps.den < 0) {
2348 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2349 return AVERROR_INVALIDDATA;
2351 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2352 fps.den, fps.num, 1 << 30);
2355 aspect.num = get_bits_long(gb, 24);
2356 aspect.den = get_bits_long(gb, 24);
2357 if (aspect.num && aspect.den) {
2358 av_reduce(&avctx->sample_aspect_ratio.num,
2359 &avctx->sample_aspect_ratio.den,
2360 aspect.num, aspect.den, 1 << 30);
2361 ff_set_sar(avctx, avctx->sample_aspect_ratio);
2364 if (s->theora < 0x030200)
2365 skip_bits(gb, 5); /* keyframe frequency force */
2366 colorspace = get_bits(gb, 8);
2367 skip_bits(gb, 24); /* bitrate */
2369 skip_bits(gb, 6); /* quality hint */
2371 if (s->theora >= 0x030200) {
2372 skip_bits(gb, 5); /* keyframe frequency force */
2373 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2374 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2375 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2376 return AVERROR_INVALIDDATA;
2378 skip_bits(gb, 3); /* reserved */
2380 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2382 ret = ff_set_dimensions(avctx, s->width, s->height);
2385 if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2386 avctx->width = visible_width;
2387 avctx->height = visible_height;
2388 // translate offsets from theora axis ([0,0] lower left)
2389 // to normal axis ([0,0] upper left)
2390 s->offset_x = offset_x;
2391 s->offset_y = s->height - visible_height - offset_y;
2394 if (colorspace == 1)
2395 avctx->color_primaries = AVCOL_PRI_BT470M;
2396 else if (colorspace == 2)
2397 avctx->color_primaries = AVCOL_PRI_BT470BG;
2399 if (colorspace == 1 || colorspace == 2) {
2400 avctx->colorspace = AVCOL_SPC_BT470BG;
2401 avctx->color_trc = AVCOL_TRC_BT709;
2404 s->theora_header = 1;
2408 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2410 Vp3DecodeContext *s = avctx->priv_data;
2411 int i, n, matrices, inter, plane;
2413 if (!s->theora_header)
2414 return AVERROR_INVALIDDATA;
2416 if (s->theora >= 0x030200) {
2417 n = get_bits(gb, 3);
2418 /* loop filter limit values table */
2420 for (i = 0; i < 64; i++)
2421 s->filter_limit_values[i] = get_bits(gb, n);
2424 if (s->theora >= 0x030200)
2425 n = get_bits(gb, 4) + 1;
2428 /* quality threshold table */
2429 for (i = 0; i < 64; i++)
2430 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2432 if (s->theora >= 0x030200)
2433 n = get_bits(gb, 4) + 1;
2436 /* dc scale factor table */
2437 for (i = 0; i < 64; i++)
2438 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2440 if (s->theora >= 0x030200)
2441 matrices = get_bits(gb, 9) + 1;
2445 if (matrices > 384) {
2446 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2450 for (n = 0; n < matrices; n++)
2451 for (i = 0; i < 64; i++)
2452 s->base_matrix[n][i] = get_bits(gb, 8);
2454 for (inter = 0; inter <= 1; inter++) {
2455 for (plane = 0; plane <= 2; plane++) {
2457 if (inter || plane > 0)
2458 newqr = get_bits1(gb);
2461 if (inter && get_bits1(gb)) {
2465 qtj = (3 * inter + plane - 1) / 3;
2466 plj = (plane + 2) % 3;
2468 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
2469 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
2470 sizeof(s->qr_size[0][0]));
2471 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
2472 sizeof(s->qr_base[0][0]));
2478 i = get_bits(gb, av_log2(matrices - 1) + 1);
2479 if (i >= matrices) {
2480 av_log(avctx, AV_LOG_ERROR,
2481 "invalid base matrix index\n");
2484 s->qr_base[inter][plane][qri] = i;
2487 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
2488 s->qr_size[inter][plane][qri++] = i;
2493 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2496 s->qr_count[inter][plane] = qri;
2501 /* Huffman tables */
2502 for (s->hti = 0; s->hti < 80; s->hti++) {
2504 s->huff_code_size = 1;
2505 if (!get_bits1(gb)) {
2507 if (read_huffman_tree(avctx, gb))
2510 if (read_huffman_tree(avctx, gb))
2515 s->theora_tables = 1;
2520 static av_cold int theora_decode_init(AVCodecContext *avctx)
2522 Vp3DecodeContext *s = avctx->priv_data;
2525 const uint8_t *header_start[3];
2530 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2534 if (!avctx->extradata_size) {
2535 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2539 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2540 42, header_start, header_len) < 0) {
2541 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2545 for (i = 0; i < 3; i++) {
2546 if (header_len[i] <= 0)
2548 ret = init_get_bits8(&gb, header_start[i], header_len[i]);
2552 ptype = get_bits(&gb, 8);
2554 if (!(ptype & 0x80)) {
2555 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2559 // FIXME: Check for this as well.
2560 skip_bits_long(&gb, 6 * 8); /* "theora" */
2564 if (theora_decode_header(avctx, &gb) < 0)
2568 // FIXME: is this needed? it breaks sometimes
2569 // theora_decode_comments(avctx, gb);
2572 if (theora_decode_tables(avctx, &gb))
2576 av_log(avctx, AV_LOG_ERROR,
2577 "Unknown Theora config packet: %d\n", ptype & ~0x80);
2580 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
2581 av_log(avctx, AV_LOG_WARNING,
2582 "%d bits left in packet %X\n",
2583 8 * header_len[i] - get_bits_count(&gb), ptype);
2584 if (s->theora < 0x030200)
2588 return vp3_decode_init(avctx);
2591 AVCodec ff_theora_decoder = {
2593 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2594 .type = AVMEDIA_TYPE_VIDEO,
2595 .id = AV_CODEC_ID_THEORA,
2596 .priv_data_size = sizeof(Vp3DecodeContext),
2597 .init = theora_decode_init,
2598 .close = vp3_decode_end,
2599 .decode = vp3_decode_frame,
2600 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
2601 AV_CODEC_CAP_FRAME_THREADS,
2602 .flush = vp3_decode_flush,
2603 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2604 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
2605 .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING,
2609 AVCodec ff_vp3_decoder = {
2611 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2612 .type = AVMEDIA_TYPE_VIDEO,
2613 .id = AV_CODEC_ID_VP3,
2614 .priv_data_size = sizeof(Vp3DecodeContext),
2615 .init = vp3_decode_init,
2616 .close = vp3_decode_end,
2617 .decode = vp3_decode_frame,
2618 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
2619 AV_CODEC_CAP_FRAME_THREADS,
2620 .flush = vp3_decode_flush,
2621 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2622 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),