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 int *bounding_values = s->bounding_values_array + 127;
424 filter_limit = s->filter_limit_values[s->qps[0]];
425 av_assert0(filter_limit < 128U);
427 /* set up the bounding values */
428 memset(s->bounding_values_array, 0, 256 * sizeof(int));
429 for (x = 0; x < filter_limit; x++) {
430 bounding_values[-x] = -x;
431 bounding_values[x] = x;
433 for (x = value = filter_limit; x < 128 && value; x++, value--) {
434 bounding_values[ x] = value;
435 bounding_values[-x] = -value;
438 bounding_values[128] = value;
439 bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
443 * This function unpacks all of the superblock/macroblock/fragment coding
444 * information from the bitstream.
446 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
448 int superblock_starts[3] = {
449 0, s->u_superblock_start, s->v_superblock_start
452 int current_superblock = 0;
454 int num_partial_superblocks = 0;
457 int current_fragment;
459 int plane0_num_coded_frags = 0;
462 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
464 /* unpack the list of partially-coded superblocks */
465 bit = get_bits1(gb) ^ 1;
468 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
469 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
474 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
476 if (current_run == 34)
477 current_run += get_bits(gb, 12);
479 if (current_run > s->superblock_count - current_superblock) {
480 av_log(s->avctx, AV_LOG_ERROR,
481 "Invalid partially coded superblock run length\n");
485 memset(s->superblock_coding + current_superblock, bit, current_run);
487 current_superblock += current_run;
489 num_partial_superblocks += current_run;
492 /* unpack the list of fully coded superblocks if any of the blocks were
493 * not marked as partially coded in the previous step */
494 if (num_partial_superblocks < s->superblock_count) {
495 int superblocks_decoded = 0;
497 current_superblock = 0;
498 bit = get_bits1(gb) ^ 1;
501 while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
502 get_bits_left(gb) > 0) {
503 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
508 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
510 if (current_run == 34)
511 current_run += get_bits(gb, 12);
513 for (j = 0; j < current_run; current_superblock++) {
514 if (current_superblock >= s->superblock_count) {
515 av_log(s->avctx, AV_LOG_ERROR,
516 "Invalid fully coded superblock run length\n");
520 /* skip any superblocks already marked as partially coded */
521 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
522 s->superblock_coding[current_superblock] = 2 * bit;
526 superblocks_decoded += current_run;
530 /* if there were partial blocks, initialize bitstream for
531 * unpacking fragment codings */
532 if (num_partial_superblocks) {
535 /* toggle the bit because as soon as the first run length is
536 * fetched the bit will be toggled again */
541 /* figure out which fragments are coded; iterate through each
542 * superblock (all planes) */
543 s->total_num_coded_frags = 0;
544 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
546 s->coded_fragment_list[0] = s->keyframe ? s->kf_coded_fragment_list
547 : s->nkf_coded_fragment_list;
549 for (plane = 0; plane < 3; plane++) {
550 int sb_start = superblock_starts[plane];
551 int sb_end = sb_start + (plane ? s->c_superblock_count
552 : s->y_superblock_count);
553 int num_coded_frags = 0;
556 if (s->num_kf_coded_fragment[plane] == -1) {
557 for (i = sb_start; i < sb_end; i++) {
558 /* iterate through all 16 fragments in a superblock */
559 for (j = 0; j < 16; j++) {
560 /* if the fragment is in bounds, check its coding status */
561 current_fragment = s->superblock_fragments[i * 16 + j];
562 if (current_fragment != -1) {
563 s->coded_fragment_list[plane][num_coded_frags++] =
568 s->num_kf_coded_fragment[plane] = num_coded_frags;
570 num_coded_frags = s->num_kf_coded_fragment[plane];
572 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
573 if (get_bits_left(gb) < plane0_num_coded_frags >> 2) {
574 return AVERROR_INVALIDDATA;
576 /* iterate through all 16 fragments in a superblock */
577 for (j = 0; j < 16; j++) {
578 /* if the fragment is in bounds, check its coding status */
579 current_fragment = s->superblock_fragments[i * 16 + j];
580 if (current_fragment != -1) {
581 int coded = s->superblock_coding[i];
583 if (coded == SB_PARTIALLY_CODED) {
584 /* fragment may or may not be coded; this is the case
585 * that cares about the fragment coding runs */
586 if (current_run-- == 0) {
588 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
594 /* default mode; actual mode will be decoded in
596 s->all_fragments[current_fragment].coding_method =
598 s->coded_fragment_list[plane][num_coded_frags++] =
601 /* not coded; copy this fragment from the prior frame */
602 s->all_fragments[current_fragment].coding_method =
610 plane0_num_coded_frags = num_coded_frags;
611 s->total_num_coded_frags += num_coded_frags;
612 for (i = 0; i < 64; i++)
613 s->num_coded_frags[plane][i] = num_coded_frags;
615 s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
622 * This function unpacks all the coding mode data for individual macroblocks
623 * from the bitstream.
625 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
627 int i, j, k, sb_x, sb_y;
629 int current_macroblock;
630 int current_fragment;
632 int custom_mode_alphabet[CODING_MODE_COUNT];
637 for (i = 0; i < s->fragment_count; i++)
638 s->all_fragments[i].coding_method = MODE_INTRA;
640 /* fetch the mode coding scheme for this frame */
641 scheme = get_bits(gb, 3);
643 /* is it a custom coding scheme? */
645 for (i = 0; i < 8; i++)
646 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
647 for (i = 0; i < 8; i++)
648 custom_mode_alphabet[get_bits(gb, 3)] = i;
649 alphabet = custom_mode_alphabet;
651 alphabet = ModeAlphabet[scheme - 1];
653 /* iterate through all of the macroblocks that contain 1 or more
655 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
656 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
657 if (get_bits_left(gb) <= 0)
660 for (j = 0; j < 4; j++) {
661 int mb_x = 2 * sb_x + (j >> 1);
662 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
663 current_macroblock = mb_y * s->macroblock_width + mb_x;
665 if (mb_x >= s->macroblock_width ||
666 mb_y >= s->macroblock_height)
669 #define BLOCK_X (2 * mb_x + (k & 1))
670 #define BLOCK_Y (2 * mb_y + (k >> 1))
671 /* coding modes are only stored if the macroblock has
672 * at least one luma block coded, otherwise it must be
674 for (k = 0; k < 4; k++) {
675 current_fragment = BLOCK_Y *
676 s->fragment_width[0] + BLOCK_X;
677 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
681 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
685 /* mode 7 means get 3 bits for each coding mode */
687 coding_mode = get_bits(gb, 3);
689 coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
691 s->macroblock_coding[current_macroblock] = coding_mode;
692 for (k = 0; k < 4; k++) {
693 frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
694 if (frag->coding_method != MODE_COPY)
695 frag->coding_method = coding_mode;
698 #define SET_CHROMA_MODES \
699 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
700 frag[s->fragment_start[1]].coding_method = coding_mode; \
701 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
702 frag[s->fragment_start[2]].coding_method = coding_mode;
704 if (s->chroma_y_shift) {
705 frag = s->all_fragments + mb_y *
706 s->fragment_width[1] + mb_x;
708 } else if (s->chroma_x_shift) {
709 frag = s->all_fragments +
710 2 * mb_y * s->fragment_width[1] + mb_x;
711 for (k = 0; k < 2; k++) {
713 frag += s->fragment_width[1];
716 for (k = 0; k < 4; k++) {
717 frag = s->all_fragments +
718 BLOCK_Y * s->fragment_width[1] + BLOCK_X;
731 * This function unpacks all the motion vectors for the individual
732 * macroblocks from the bitstream.
734 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
736 int j, k, sb_x, sb_y;
740 int last_motion_x = 0;
741 int last_motion_y = 0;
742 int prior_last_motion_x = 0;
743 int prior_last_motion_y = 0;
744 int current_macroblock;
745 int current_fragment;
751 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
752 coding_mode = get_bits1(gb);
754 /* iterate through all of the macroblocks that contain 1 or more
756 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
757 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
758 if (get_bits_left(gb) <= 0)
761 for (j = 0; j < 4; j++) {
762 int mb_x = 2 * sb_x + (j >> 1);
763 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
764 current_macroblock = mb_y * s->macroblock_width + mb_x;
766 if (mb_x >= s->macroblock_width ||
767 mb_y >= s->macroblock_height ||
768 s->macroblock_coding[current_macroblock] == MODE_COPY)
771 switch (s->macroblock_coding[current_macroblock]) {
772 case MODE_INTER_PLUS_MV:
774 /* all 6 fragments use the same motion vector */
775 if (coding_mode == 0) {
776 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
777 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
779 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
780 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
783 /* vector maintenance, only on MODE_INTER_PLUS_MV */
784 if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
785 prior_last_motion_x = last_motion_x;
786 prior_last_motion_y = last_motion_y;
787 last_motion_x = motion_x[0];
788 last_motion_y = motion_y[0];
792 case MODE_INTER_FOURMV:
793 /* vector maintenance */
794 prior_last_motion_x = last_motion_x;
795 prior_last_motion_y = last_motion_y;
797 /* fetch 4 vectors from the bitstream, one for each
798 * Y fragment, then average for the C fragment vectors */
799 for (k = 0; k < 4; k++) {
800 current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
801 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
802 if (coding_mode == 0) {
803 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
804 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
806 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
807 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
809 last_motion_x = motion_x[k];
810 last_motion_y = motion_y[k];
818 case MODE_INTER_LAST_MV:
819 /* all 6 fragments use the last motion vector */
820 motion_x[0] = last_motion_x;
821 motion_y[0] = last_motion_y;
823 /* no vector maintenance (last vector remains the
827 case MODE_INTER_PRIOR_LAST:
828 /* all 6 fragments use the motion vector prior to the
829 * last motion vector */
830 motion_x[0] = prior_last_motion_x;
831 motion_y[0] = prior_last_motion_y;
833 /* vector maintenance */
834 prior_last_motion_x = last_motion_x;
835 prior_last_motion_y = last_motion_y;
836 last_motion_x = motion_x[0];
837 last_motion_y = motion_y[0];
841 /* covers intra, inter without MV, golden without MV */
845 /* no vector maintenance */
849 /* assign the motion vectors to the correct fragments */
850 for (k = 0; k < 4; k++) {
852 BLOCK_Y * s->fragment_width[0] + BLOCK_X;
853 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
854 s->motion_val[0][current_fragment][0] = motion_x[k];
855 s->motion_val[0][current_fragment][1] = motion_y[k];
857 s->motion_val[0][current_fragment][0] = motion_x[0];
858 s->motion_val[0][current_fragment][1] = motion_y[0];
862 if (s->chroma_y_shift) {
863 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
864 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
865 motion_x[2] + motion_x[3], 2);
866 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
867 motion_y[2] + motion_y[3], 2);
869 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
870 motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
871 frag = mb_y * s->fragment_width[1] + mb_x;
872 s->motion_val[1][frag][0] = motion_x[0];
873 s->motion_val[1][frag][1] = motion_y[0];
874 } else if (s->chroma_x_shift) {
875 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
876 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
877 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
878 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
879 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
881 motion_x[1] = motion_x[0];
882 motion_y[1] = motion_y[0];
884 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
885 motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
887 frag = 2 * mb_y * s->fragment_width[1] + mb_x;
888 for (k = 0; k < 2; k++) {
889 s->motion_val[1][frag][0] = motion_x[k];
890 s->motion_val[1][frag][1] = motion_y[k];
891 frag += s->fragment_width[1];
894 for (k = 0; k < 4; k++) {
895 frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
896 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
897 s->motion_val[1][frag][0] = motion_x[k];
898 s->motion_val[1][frag][1] = motion_y[k];
900 s->motion_val[1][frag][0] = motion_x[0];
901 s->motion_val[1][frag][1] = motion_y[0];
912 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
914 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
915 int num_blocks = s->total_num_coded_frags;
917 for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
918 i = blocks_decoded = num_blocks_at_qpi = 0;
920 bit = get_bits1(gb) ^ 1;
924 if (run_length == MAXIMUM_LONG_BIT_RUN)
929 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
930 if (run_length == 34)
931 run_length += get_bits(gb, 12);
932 blocks_decoded += run_length;
935 num_blocks_at_qpi += run_length;
937 for (j = 0; j < run_length; i++) {
938 if (i >= s->total_num_coded_frags)
941 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
942 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
946 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
948 num_blocks -= num_blocks_at_qpi;
955 * This function is called by unpack_dct_coeffs() to extract the VLCs from
956 * the bitstream. The VLCs encode tokens which are used to unpack DCT
957 * data. This function unpacks all the VLCs for either the Y plane or both
958 * C planes, and is called for DC coefficients or different AC coefficient
959 * levels (since different coefficient types require different VLC tables.
961 * This function returns a residual eob run. E.g, if a particular token gave
962 * instructions to EOB the next 5 fragments and there were only 2 fragments
963 * left in the current fragment range, 3 would be returned so that it could
964 * be passed into the next call to this same function.
966 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
967 VLC *table, int coeff_index,
978 int num_coeffs = s->num_coded_frags[plane][coeff_index];
979 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
981 /* local references to structure members to avoid repeated dereferences */
982 int *coded_fragment_list = s->coded_fragment_list[plane];
983 Vp3Fragment *all_fragments = s->all_fragments;
984 VLC_TYPE(*vlc_table)[2] = table->table;
986 if (num_coeffs < 0) {
987 av_log(s->avctx, AV_LOG_ERROR,
988 "Invalid number of coefficients at level %d\n", coeff_index);
989 return AVERROR_INVALIDDATA;
992 if (eob_run > num_coeffs) {
994 blocks_ended = num_coeffs;
995 eob_run -= num_coeffs;
998 blocks_ended = eob_run;
1002 // insert fake EOB token to cover the split between planes or zzi
1004 dct_tokens[j++] = blocks_ended << 2;
1006 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1007 /* decode a VLC into a token */
1008 token = get_vlc2(gb, vlc_table, 11, 3);
1009 /* use the token to get a zero run, a coefficient, and an eob run */
1010 if ((unsigned) token <= 6U) {
1011 eob_run = eob_run_base[token];
1012 if (eob_run_get_bits[token])
1013 eob_run += get_bits(gb, eob_run_get_bits[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 bits_to_get = coeff_get_bits[token];
1034 bits_to_get = get_bits(gb, bits_to_get);
1035 coeff = coeff_tables[token][bits_to_get];
1037 zero_run = zero_run_base[token];
1038 if (zero_run_get_bits[token])
1039 zero_run += get_bits(gb, zero_run_get_bits[token]);
1042 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1044 // Save DC into the fragment structure. DC prediction is
1045 // done in raster order, so the actual DC can't be in with
1046 // other tokens. We still need the token in dct_tokens[]
1047 // however, or else the structure collapses on itself.
1049 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1051 dct_tokens[j++] = TOKEN_COEFF(coeff);
1054 if (coeff_index + zero_run > 64) {
1055 av_log(s->avctx, AV_LOG_DEBUG,
1056 "Invalid zero run of %d with %d coeffs left\n",
1057 zero_run, 64 - coeff_index);
1058 zero_run = 64 - coeff_index;
1061 // zero runs code multiple coefficients,
1062 // so don't try to decode coeffs for those higher levels
1063 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1064 s->num_coded_frags[plane][i]--;
1067 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1072 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1073 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1075 // decrement the number of blocks that have higher coefficients for each
1076 // EOB run at this level
1078 for (i = coeff_index + 1; i < 64; i++)
1079 s->num_coded_frags[plane][i] -= blocks_ended;
1081 // setup the next buffer
1083 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1084 else if (coeff_index < 63)
1085 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1090 static void reverse_dc_prediction(Vp3DecodeContext *s,
1093 int fragment_height);
1095 * This function unpacks all of the DCT coefficient data from the
1098 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1105 int residual_eob_run = 0;
1109 s->dct_tokens[0][0] = s->dct_tokens_base;
1111 if (get_bits_left(gb) < 16)
1112 return AVERROR_INVALIDDATA;
1114 /* fetch the DC table indexes */
1115 dc_y_table = get_bits(gb, 4);
1116 dc_c_table = get_bits(gb, 4);
1118 /* unpack the Y plane DC coefficients */
1119 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1120 0, residual_eob_run);
1121 if (residual_eob_run < 0)
1122 return residual_eob_run;
1123 if (get_bits_left(gb) < 8)
1124 return AVERROR_INVALIDDATA;
1126 /* reverse prediction of the Y-plane DC coefficients */
1127 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1129 /* unpack the C plane DC coefficients */
1130 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1131 1, residual_eob_run);
1132 if (residual_eob_run < 0)
1133 return residual_eob_run;
1134 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1135 2, residual_eob_run);
1136 if (residual_eob_run < 0)
1137 return residual_eob_run;
1139 /* reverse prediction of the C-plane DC coefficients */
1140 if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1141 reverse_dc_prediction(s, s->fragment_start[1],
1142 s->fragment_width[1], s->fragment_height[1]);
1143 reverse_dc_prediction(s, s->fragment_start[2],
1144 s->fragment_width[1], s->fragment_height[1]);
1147 if (get_bits_left(gb) < 8)
1148 return AVERROR_INVALIDDATA;
1149 /* fetch the AC table indexes */
1150 ac_y_table = get_bits(gb, 4);
1151 ac_c_table = get_bits(gb, 4);
1153 /* build tables of AC VLC tables */
1154 for (i = 1; i <= 5; i++) {
1155 y_tables[i] = &s->ac_vlc_1[ac_y_table];
1156 c_tables[i] = &s->ac_vlc_1[ac_c_table];
1158 for (i = 6; i <= 14; i++) {
1159 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1160 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1162 for (i = 15; i <= 27; i++) {
1163 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1164 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1166 for (i = 28; i <= 63; i++) {
1167 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1168 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1171 /* decode all AC coefficients */
1172 for (i = 1; i <= 63; i++) {
1173 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1174 0, residual_eob_run);
1175 if (residual_eob_run < 0)
1176 return residual_eob_run;
1178 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1179 1, residual_eob_run);
1180 if (residual_eob_run < 0)
1181 return residual_eob_run;
1182 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1183 2, residual_eob_run);
1184 if (residual_eob_run < 0)
1185 return residual_eob_run;
1192 * This function reverses the DC prediction for each coded fragment in
1193 * the frame. Much of this function is adapted directly from the original
1196 #define COMPATIBLE_FRAME(x) \
1197 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1198 #define DC_COEFF(u) s->all_fragments[u].dc
1200 static void reverse_dc_prediction(Vp3DecodeContext *s,
1203 int fragment_height)
1211 int i = first_fragment;
1215 /* DC values for the left, up-left, up, and up-right fragments */
1216 int vl, vul, vu, vur;
1218 /* indexes for the left, up-left, up, and up-right fragments */
1222 * The 6 fields mean:
1223 * 0: up-left multiplier
1225 * 2: up-right multiplier
1226 * 3: left multiplier
1228 static const int predictor_transform[16][4] = {
1230 { 0, 0, 0, 128 }, // PL
1231 { 0, 0, 128, 0 }, // PUR
1232 { 0, 0, 53, 75 }, // PUR|PL
1233 { 0, 128, 0, 0 }, // PU
1234 { 0, 64, 0, 64 }, // PU |PL
1235 { 0, 128, 0, 0 }, // PU |PUR
1236 { 0, 0, 53, 75 }, // PU |PUR|PL
1237 { 128, 0, 0, 0 }, // PUL
1238 { 0, 0, 0, 128 }, // PUL|PL
1239 { 64, 0, 64, 0 }, // PUL|PUR
1240 { 0, 0, 53, 75 }, // PUL|PUR|PL
1241 { 0, 128, 0, 0 }, // PUL|PU
1242 { -104, 116, 0, 116 }, // PUL|PU |PL
1243 { 24, 80, 24, 0 }, // PUL|PU |PUR
1244 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1247 /* This table shows which types of blocks can use other blocks for
1248 * prediction. For example, INTRA is the only mode in this table to
1249 * have a frame number of 0. That means INTRA blocks can only predict
1250 * from other INTRA blocks. There are 2 golden frame coding types;
1251 * blocks encoding in these modes can only predict from other blocks
1252 * that were encoded with these 1 of these 2 modes. */
1253 static const unsigned char compatible_frame[9] = {
1254 1, /* MODE_INTER_NO_MV */
1256 1, /* MODE_INTER_PLUS_MV */
1257 1, /* MODE_INTER_LAST_MV */
1258 1, /* MODE_INTER_PRIOR_MV */
1259 2, /* MODE_USING_GOLDEN */
1260 2, /* MODE_GOLDEN_MV */
1261 1, /* MODE_INTER_FOUR_MV */
1264 int current_frame_type;
1266 /* there is a last DC predictor for each of the 3 frame types */
1279 /* for each fragment row... */
1280 for (y = 0; y < fragment_height; y++) {
1281 /* for each fragment in a row... */
1282 for (x = 0; x < fragment_width; x++, i++) {
1284 /* reverse prediction if this block was coded */
1285 if (s->all_fragments[i].coding_method != MODE_COPY) {
1286 current_frame_type =
1287 compatible_frame[s->all_fragments[i].coding_method];
1293 if (COMPATIBLE_FRAME(l))
1297 u = i - fragment_width;
1299 if (COMPATIBLE_FRAME(u))
1302 ul = i - fragment_width - 1;
1304 if (COMPATIBLE_FRAME(ul))
1307 if (x + 1 < fragment_width) {
1308 ur = i - fragment_width + 1;
1310 if (COMPATIBLE_FRAME(ur))
1315 if (transform == 0) {
1316 /* if there were no fragments to predict from, use last
1318 predicted_dc = last_dc[current_frame_type];
1320 /* apply the appropriate predictor transform */
1322 (predictor_transform[transform][0] * vul) +
1323 (predictor_transform[transform][1] * vu) +
1324 (predictor_transform[transform][2] * vur) +
1325 (predictor_transform[transform][3] * vl);
1327 predicted_dc /= 128;
1329 /* check for outranging on the [ul u l] and
1330 * [ul u ur l] predictors */
1331 if ((transform == 15) || (transform == 13)) {
1332 if (FFABS(predicted_dc - vu) > 128)
1334 else if (FFABS(predicted_dc - vl) > 128)
1336 else if (FFABS(predicted_dc - vul) > 128)
1341 /* at long last, apply the predictor */
1342 DC_COEFF(i) += predicted_dc;
1344 last_dc[current_frame_type] = DC_COEFF(i);
1350 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1351 int ystart, int yend)
1354 int *bounding_values = s->bounding_values_array + 127;
1356 int width = s->fragment_width[!!plane];
1357 int height = s->fragment_height[!!plane];
1358 int fragment = s->fragment_start[plane] + ystart * width;
1359 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1360 uint8_t *plane_data = s->current_frame.f->data[plane];
1361 if (!s->flipped_image)
1363 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1365 for (y = ystart; y < yend; y++) {
1366 for (x = 0; x < width; x++) {
1367 /* This code basically just deblocks on the edges of coded blocks.
1368 * However, it has to be much more complicated because of the
1369 * brain damaged deblock ordering used in VP3/Theora. Order matters
1370 * because some pixels get filtered twice. */
1371 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1372 /* do not perform left edge filter for left columns frags */
1374 s->vp3dsp.h_loop_filter(
1376 stride, bounding_values);
1379 /* do not perform top edge filter for top row fragments */
1381 s->vp3dsp.v_loop_filter(
1383 stride, bounding_values);
1386 /* do not perform right edge filter for right column
1387 * fragments or if right fragment neighbor is also coded
1388 * in this frame (it will be filtered in next iteration) */
1389 if ((x < width - 1) &&
1390 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1391 s->vp3dsp.h_loop_filter(
1392 plane_data + 8 * x + 8,
1393 stride, bounding_values);
1396 /* do not perform bottom edge filter for bottom row
1397 * fragments or if bottom fragment neighbor is also coded
1398 * in this frame (it will be filtered in the next row) */
1399 if ((y < height - 1) &&
1400 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1401 s->vp3dsp.v_loop_filter(
1402 plane_data + 8 * x + 8 * stride,
1403 stride, bounding_values);
1409 plane_data += 8 * stride;
1414 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1415 * for the next block in coding order
1417 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1418 int plane, int inter, int16_t block[64])
1420 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1421 uint8_t *perm = s->idct_scantable;
1425 int token = *s->dct_tokens[plane][i];
1426 switch (token & 3) {
1428 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1429 s->dct_tokens[plane][i]++;
1431 *s->dct_tokens[plane][i] = token & ~3;
1434 s->dct_tokens[plane][i]++;
1435 i += (token >> 2) & 0x7f;
1437 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1440 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1444 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1445 s->dct_tokens[plane][i++]++;
1447 default: // shouldn't happen
1451 // return value is expected to be a valid level
1454 // the actual DC+prediction is in the fragment structure
1455 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1460 * called when all pixels up to row y are complete
1462 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1465 int offset[AV_NUM_DATA_POINTERS];
1467 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1468 int y_flipped = s->flipped_image ? s->height - y : y;
1470 /* At the end of the frame, report INT_MAX instead of the height of
1471 * the frame. This makes the other threads' ff_thread_await_progress()
1472 * calls cheaper, because they don't have to clip their values. */
1473 ff_thread_report_progress(&s->current_frame,
1474 y_flipped == s->height ? INT_MAX
1479 if (!s->avctx->draw_horiz_band)
1482 h = y - s->last_slice_end;
1483 s->last_slice_end = y;
1486 if (!s->flipped_image)
1487 y = s->height - y - h;
1489 cy = y >> s->chroma_y_shift;
1490 offset[0] = s->current_frame.f->linesize[0] * y;
1491 offset[1] = s->current_frame.f->linesize[1] * cy;
1492 offset[2] = s->current_frame.f->linesize[2] * cy;
1493 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1497 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1501 * Wait for the reference frame of the current fragment.
1502 * The progress value is in luma pixel rows.
1504 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1505 int motion_y, int y)
1507 ThreadFrame *ref_frame;
1509 int border = motion_y & 1;
1511 if (fragment->coding_method == MODE_USING_GOLDEN ||
1512 fragment->coding_method == MODE_GOLDEN_MV)
1513 ref_frame = &s->golden_frame;
1515 ref_frame = &s->last_frame;
1517 ref_row = y + (motion_y >> 1);
1518 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1520 ff_thread_await_progress(ref_frame, ref_row, 0);
1524 * Perform the final rendering for a particular slice of data.
1525 * The slice number ranges from 0..(c_superblock_height - 1).
1527 static void render_slice(Vp3DecodeContext *s, int slice)
1529 int x, y, i, j, fragment;
1530 int16_t *block = s->block;
1531 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1532 int motion_halfpel_index;
1533 uint8_t *motion_source;
1534 int plane, first_pixel;
1536 if (slice >= s->c_superblock_height)
1539 for (plane = 0; plane < 3; plane++) {
1540 uint8_t *output_plane = s->current_frame.f->data[plane] +
1541 s->data_offset[plane];
1542 uint8_t *last_plane = s->last_frame.f->data[plane] +
1543 s->data_offset[plane];
1544 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
1545 s->data_offset[plane];
1546 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1547 int plane_width = s->width >> (plane && s->chroma_x_shift);
1548 int plane_height = s->height >> (plane && s->chroma_y_shift);
1549 int8_t(*motion_val)[2] = s->motion_val[!!plane];
1551 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
1552 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
1553 int slice_width = plane ? s->c_superblock_width
1554 : s->y_superblock_width;
1556 int fragment_width = s->fragment_width[!!plane];
1557 int fragment_height = s->fragment_height[!!plane];
1558 int fragment_start = s->fragment_start[plane];
1560 int do_await = !plane && HAVE_THREADS &&
1561 (s->avctx->active_thread_type & FF_THREAD_FRAME);
1563 if (!s->flipped_image)
1565 if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
1568 /* for each superblock row in the slice (both of them)... */
1569 for (; sb_y < slice_height; sb_y++) {
1570 /* for each superblock in a row... */
1571 for (sb_x = 0; sb_x < slice_width; sb_x++) {
1572 /* for each block in a superblock... */
1573 for (j = 0; j < 16; j++) {
1574 x = 4 * sb_x + hilbert_offset[j][0];
1575 y = 4 * sb_y + hilbert_offset[j][1];
1576 fragment = y * fragment_width + x;
1578 i = fragment_start + fragment;
1581 if (x >= fragment_width || y >= fragment_height)
1584 first_pixel = 8 * y * stride + 8 * x;
1587 s->all_fragments[i].coding_method != MODE_INTRA)
1588 await_reference_row(s, &s->all_fragments[i],
1589 motion_val[fragment][1],
1590 (16 * y) >> s->chroma_y_shift);
1592 /* transform if this block was coded */
1593 if (s->all_fragments[i].coding_method != MODE_COPY) {
1594 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1595 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1596 motion_source = golden_plane;
1598 motion_source = last_plane;
1600 motion_source += first_pixel;
1601 motion_halfpel_index = 0;
1603 /* sort out the motion vector if this fragment is coded
1604 * using a motion vector method */
1605 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1606 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1608 motion_x = motion_val[fragment][0];
1609 motion_y = motion_val[fragment][1];
1611 src_x = (motion_x >> 1) + 8 * x;
1612 src_y = (motion_y >> 1) + 8 * y;
1614 motion_halfpel_index = motion_x & 0x01;
1615 motion_source += (motion_x >> 1);
1617 motion_halfpel_index |= (motion_y & 0x01) << 1;
1618 motion_source += ((motion_y >> 1) * stride);
1620 if (src_x < 0 || src_y < 0 ||
1621 src_x + 9 >= plane_width ||
1622 src_y + 9 >= plane_height) {
1623 uint8_t *temp = s->edge_emu_buffer;
1627 s->vdsp.emulated_edge_mc(temp, motion_source,
1632 motion_source = temp;
1636 /* first, take care of copying a block from either the
1637 * previous or the golden frame */
1638 if (s->all_fragments[i].coding_method != MODE_INTRA) {
1639 /* Note, it is possible to implement all MC cases
1640 * with put_no_rnd_pixels_l2 which would look more
1641 * like the VP3 source but this would be slower as
1642 * put_no_rnd_pixels_tab is better optimized */
1643 if (motion_halfpel_index != 3) {
1644 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1645 output_plane + first_pixel,
1646 motion_source, stride, 8);
1648 /* d is 0 if motion_x and _y have the same sign,
1650 int d = (motion_x ^ motion_y) >> 31;
1651 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
1653 motion_source + stride + 1 + d,
1658 /* invert DCT and place (or add) in final output */
1660 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1661 vp3_dequant(s, s->all_fragments + i,
1663 s->vp3dsp.idct_put(output_plane + first_pixel,
1667 if (vp3_dequant(s, s->all_fragments + i,
1669 s->vp3dsp.idct_add(output_plane + first_pixel,
1673 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
1678 /* copy directly from the previous frame */
1679 s->hdsp.put_pixels_tab[1][0](
1680 output_plane + first_pixel,
1681 last_plane + first_pixel,
1687 // Filter up to the last row in the superblock row
1688 if (!s->skip_loop_filter)
1689 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
1690 FFMIN(4 * sb_y + 3, fragment_height - 1));
1694 /* this looks like a good place for slice dispatch... */
1696 * if (slice == s->macroblock_height - 1)
1697 * dispatch (both last slice & 2nd-to-last slice);
1698 * else if (slice > 0)
1699 * dispatch (slice - 1);
1702 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
1706 /// Allocate tables for per-frame data in Vp3DecodeContext
1707 static av_cold int allocate_tables(AVCodecContext *avctx)
1709 Vp3DecodeContext *s = avctx->priv_data;
1710 int y_fragment_count, c_fragment_count;
1714 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1715 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1717 s->superblock_coding = av_mallocz(s->superblock_count);
1718 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
1720 s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
1721 s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
1722 memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
1724 s->dct_tokens_base = av_mallocz_array(s->fragment_count,
1725 64 * sizeof(*s->dct_tokens_base));
1726 s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
1727 s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
1729 /* work out the block mapping tables */
1730 s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
1731 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
1733 if (!s->superblock_coding || !s->all_fragments ||
1734 !s->dct_tokens_base || !s->kf_coded_fragment_list ||
1735 !s->nkf_coded_fragment_list ||
1736 !s->superblock_fragments || !s->macroblock_coding ||
1737 !s->motion_val[0] || !s->motion_val[1]) {
1738 vp3_decode_end(avctx);
1742 init_block_mapping(s);
1747 static av_cold int init_frames(Vp3DecodeContext *s)
1749 s->current_frame.f = av_frame_alloc();
1750 s->last_frame.f = av_frame_alloc();
1751 s->golden_frame.f = av_frame_alloc();
1753 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
1754 av_frame_free(&s->current_frame.f);
1755 av_frame_free(&s->last_frame.f);
1756 av_frame_free(&s->golden_frame.f);
1757 return AVERROR(ENOMEM);
1763 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1765 Vp3DecodeContext *s = avctx->priv_data;
1766 int i, inter, plane, ret;
1769 int y_fragment_count, c_fragment_count;
1771 ret = init_frames(s);
1775 avctx->internal->allocate_progress = 1;
1777 if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
1783 s->width = FFALIGN(avctx->coded_width, 16);
1784 s->height = FFALIGN(avctx->coded_height, 16);
1785 if (avctx->codec_id != AV_CODEC_ID_THEORA)
1786 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
1787 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1788 ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
1789 ff_videodsp_init(&s->vdsp, 8);
1790 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
1792 for (i = 0; i < 64; i++) {
1793 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
1794 s->idct_permutation[i] = TRANSPOSE(i);
1795 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
1799 /* initialize to an impossible value which will force a recalculation
1800 * in the first frame decode */
1801 for (i = 0; i < 3; i++)
1804 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1808 s->y_superblock_width = (s->width + 31) / 32;
1809 s->y_superblock_height = (s->height + 31) / 32;
1810 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1812 /* work out the dimensions for the C planes */
1813 c_width = s->width >> s->chroma_x_shift;
1814 c_height = s->height >> s->chroma_y_shift;
1815 s->c_superblock_width = (c_width + 31) / 32;
1816 s->c_superblock_height = (c_height + 31) / 32;
1817 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1819 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1820 s->u_superblock_start = s->y_superblock_count;
1821 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1823 s->macroblock_width = (s->width + 15) / 16;
1824 s->macroblock_height = (s->height + 15) / 16;
1825 s->macroblock_count = s->macroblock_width * s->macroblock_height;
1827 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1828 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1829 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
1830 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
1832 /* fragment count covers all 8x8 blocks for all 3 planes */
1833 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1834 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1835 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
1836 s->fragment_start[1] = y_fragment_count;
1837 s->fragment_start[2] = y_fragment_count + c_fragment_count;
1839 if (!s->theora_tables) {
1840 for (i = 0; i < 64; i++) {
1841 s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1842 s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1843 s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1844 s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1845 s->base_matrix[2][i] = vp31_inter_dequant[i];
1846 s->filter_limit_values[i] = vp31_filter_limit_values[i];
1849 for (inter = 0; inter < 2; inter++) {
1850 for (plane = 0; plane < 3; plane++) {
1851 s->qr_count[inter][plane] = 1;
1852 s->qr_size[inter][plane][0] = 63;
1853 s->qr_base[inter][plane][0] =
1854 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
1858 /* init VLC tables */
1859 for (i = 0; i < 16; i++) {
1861 init_vlc(&s->dc_vlc[i], 11, 32,
1862 &dc_bias[i][0][1], 4, 2,
1863 &dc_bias[i][0][0], 4, 2, 0);
1865 /* group 1 AC histograms */
1866 init_vlc(&s->ac_vlc_1[i], 11, 32,
1867 &ac_bias_0[i][0][1], 4, 2,
1868 &ac_bias_0[i][0][0], 4, 2, 0);
1870 /* group 2 AC histograms */
1871 init_vlc(&s->ac_vlc_2[i], 11, 32,
1872 &ac_bias_1[i][0][1], 4, 2,
1873 &ac_bias_1[i][0][0], 4, 2, 0);
1875 /* group 3 AC histograms */
1876 init_vlc(&s->ac_vlc_3[i], 11, 32,
1877 &ac_bias_2[i][0][1], 4, 2,
1878 &ac_bias_2[i][0][0], 4, 2, 0);
1880 /* group 4 AC histograms */
1881 init_vlc(&s->ac_vlc_4[i], 11, 32,
1882 &ac_bias_3[i][0][1], 4, 2,
1883 &ac_bias_3[i][0][0], 4, 2, 0);
1886 for (i = 0; i < 16; i++) {
1888 if (init_vlc(&s->dc_vlc[i], 11, 32,
1889 &s->huffman_table[i][0][1], 8, 4,
1890 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
1893 /* group 1 AC histograms */
1894 if (init_vlc(&s->ac_vlc_1[i], 11, 32,
1895 &s->huffman_table[i + 16][0][1], 8, 4,
1896 &s->huffman_table[i + 16][0][0], 8, 4, 0) < 0)
1899 /* group 2 AC histograms */
1900 if (init_vlc(&s->ac_vlc_2[i], 11, 32,
1901 &s->huffman_table[i + 16 * 2][0][1], 8, 4,
1902 &s->huffman_table[i + 16 * 2][0][0], 8, 4, 0) < 0)
1905 /* group 3 AC histograms */
1906 if (init_vlc(&s->ac_vlc_3[i], 11, 32,
1907 &s->huffman_table[i + 16 * 3][0][1], 8, 4,
1908 &s->huffman_table[i + 16 * 3][0][0], 8, 4, 0) < 0)
1911 /* group 4 AC histograms */
1912 if (init_vlc(&s->ac_vlc_4[i], 11, 32,
1913 &s->huffman_table[i + 16 * 4][0][1], 8, 4,
1914 &s->huffman_table[i + 16 * 4][0][0], 8, 4, 0) < 0)
1919 init_vlc(&s->superblock_run_length_vlc, 6, 34,
1920 &superblock_run_length_vlc_table[0][1], 4, 2,
1921 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1923 init_vlc(&s->fragment_run_length_vlc, 5, 30,
1924 &fragment_run_length_vlc_table[0][1], 4, 2,
1925 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1927 init_vlc(&s->mode_code_vlc, 3, 8,
1928 &mode_code_vlc_table[0][1], 2, 1,
1929 &mode_code_vlc_table[0][0], 2, 1, 0);
1931 init_vlc(&s->motion_vector_vlc, 6, 63,
1932 &motion_vector_vlc_table[0][1], 2, 1,
1933 &motion_vector_vlc_table[0][0], 2, 1, 0);
1935 return allocate_tables(avctx);
1938 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1942 /// Release and shuffle frames after decode finishes
1943 static int update_frames(AVCodecContext *avctx)
1945 Vp3DecodeContext *s = avctx->priv_data;
1948 /* shuffle frames (last = current) */
1949 ff_thread_release_buffer(avctx, &s->last_frame);
1950 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
1955 ff_thread_release_buffer(avctx, &s->golden_frame);
1956 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
1960 ff_thread_release_buffer(avctx, &s->current_frame);
1965 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
1967 ff_thread_release_buffer(s->avctx, dst);
1968 if (src->f->data[0])
1969 return ff_thread_ref_frame(dst, src);
1973 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
1976 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
1977 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
1978 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
1983 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1985 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1986 int qps_changed = 0, i, err;
1988 #define copy_fields(to, from, start_field, end_field) \
1989 memcpy(&to->start_field, &from->start_field, \
1990 (char *) &to->end_field - (char *) &to->start_field)
1992 if (!s1->current_frame.f->data[0] ||
1993 s->width != s1->width || s->height != s1->height) {
2000 if (!s->current_frame.f)
2001 return AVERROR(ENOMEM);
2002 // init tables if the first frame hasn't been decoded
2003 if (!s->current_frame.f->data[0]) {
2004 int y_fragment_count, c_fragment_count;
2006 err = allocate_tables(dst);
2009 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2010 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2011 memcpy(s->motion_val[0], s1->motion_val[0],
2012 y_fragment_count * sizeof(*s->motion_val[0]));
2013 memcpy(s->motion_val[1], s1->motion_val[1],
2014 c_fragment_count * sizeof(*s->motion_val[1]));
2017 // copy previous frame data
2018 if ((err = ref_frames(s, s1)) < 0)
2021 s->keyframe = s1->keyframe;
2023 // copy qscale data if necessary
2024 for (i = 0; i < 3; i++) {
2025 if (s->qps[i] != s1->qps[1]) {
2027 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2031 if (s->qps[0] != s1->qps[0])
2032 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2033 sizeof(s->bounding_values_array));
2036 copy_fields(s, s1, qps, superblock_count);
2040 return update_frames(dst);
2044 static int vp3_decode_frame(AVCodecContext *avctx,
2045 void *data, int *got_frame,
2048 AVFrame *frame = data;
2049 const uint8_t *buf = avpkt->data;
2050 int buf_size = avpkt->size;
2051 Vp3DecodeContext *s = avctx->priv_data;
2055 if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2058 #if CONFIG_THEORA_DECODER
2059 if (s->theora && get_bits1(&gb)) {
2060 int type = get_bits(&gb, 7);
2061 skip_bits_long(&gb, 6*8); /* "theora" */
2063 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2064 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2065 return AVERROR_PATCHWELCOME;
2068 vp3_decode_end(avctx);
2069 ret = theora_decode_header(avctx, &gb);
2072 ret = vp3_decode_init(avctx);
2074 vp3_decode_end(avctx);
2078 } else if (type == 2) {
2079 vp3_decode_end(avctx);
2080 ret = theora_decode_tables(avctx, &gb);
2082 ret = vp3_decode_init(avctx);
2084 vp3_decode_end(avctx);
2090 av_log(avctx, AV_LOG_ERROR,
2091 "Header packet passed to frame decoder, skipping\n");
2096 s->keyframe = !get_bits1(&gb);
2097 if (!s->all_fragments) {
2098 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2103 for (i = 0; i < 3; i++)
2104 s->last_qps[i] = s->qps[i];
2108 s->qps[s->nqps++] = get_bits(&gb, 6);
2109 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2110 for (i = s->nqps; i < 3; i++)
2113 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2114 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2115 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2117 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2118 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2119 : AVDISCARD_NONKEY);
2121 if (s->qps[0] != s->last_qps[0])
2122 init_loop_filter(s);
2124 for (i = 0; i < s->nqps; i++)
2125 // reinit all dequantizers if the first one changed, because
2126 // the DC of the first quantizer must be used for all matrices
2127 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2128 init_dequantizer(s, i);
2130 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2133 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2134 : AV_PICTURE_TYPE_P;
2135 s->current_frame.f->key_frame = s->keyframe;
2136 if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2139 if (!s->edge_emu_buffer)
2140 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2144 skip_bits(&gb, 4); /* width code */
2145 skip_bits(&gb, 4); /* height code */
2147 s->version = get_bits(&gb, 5);
2148 if (avctx->frame_number == 0)
2149 av_log(s->avctx, AV_LOG_DEBUG,
2150 "VP version: %d\n", s->version);
2153 if (s->version || s->theora) {
2155 av_log(s->avctx, AV_LOG_ERROR,
2156 "Warning, unsupported keyframe coding type?!\n");
2157 skip_bits(&gb, 2); /* reserved? */
2160 if (!s->golden_frame.f->data[0]) {
2161 av_log(s->avctx, AV_LOG_WARNING,
2162 "vp3: first frame not a keyframe\n");
2164 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2165 if (ff_thread_get_buffer(avctx, &s->golden_frame,
2166 AV_GET_BUFFER_FLAG_REF) < 0)
2168 ff_thread_release_buffer(avctx, &s->last_frame);
2169 if ((ret = ff_thread_ref_frame(&s->last_frame,
2170 &s->golden_frame)) < 0)
2172 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2176 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2177 ff_thread_finish_setup(avctx);
2179 if (unpack_superblocks(s, &gb)) {
2180 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2183 if (unpack_modes(s, &gb)) {
2184 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2187 if (unpack_vectors(s, &gb)) {
2188 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2191 if (unpack_block_qpis(s, &gb)) {
2192 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2195 if (unpack_dct_coeffs(s, &gb)) {
2196 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2200 for (i = 0; i < 3; i++) {
2201 int height = s->height >> (i && s->chroma_y_shift);
2202 if (s->flipped_image)
2203 s->data_offset[i] = 0;
2205 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2208 s->last_slice_end = 0;
2209 for (i = 0; i < s->c_superblock_height; i++)
2212 // filter the last row
2213 for (i = 0; i < 3; i++) {
2214 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2215 apply_loop_filter(s, i, row, row + 1);
2217 vp3_draw_horiz_band(s, s->height);
2219 /* output frame, offset as needed */
2220 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2223 frame->crop_left = s->offset_x;
2224 frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
2225 frame->crop_top = s->offset_y;
2226 frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2230 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2231 ret = update_frames(avctx);
2239 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2241 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2242 av_frame_unref(s->current_frame.f);
2247 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2249 Vp3DecodeContext *s = avctx->priv_data;
2251 if (get_bits1(gb)) {
2253 if (s->entries >= 32) { /* overflow */
2254 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2257 token = get_bits(gb, 5);
2258 ff_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2259 s->hti, s->hbits, token, s->entries, s->huff_code_size);
2260 s->huffman_table[s->hti][token][0] = s->hbits;
2261 s->huffman_table[s->hti][token][1] = s->huff_code_size;
2264 if (s->huff_code_size >= 32) { /* overflow */
2265 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2268 s->huff_code_size++;
2270 if (read_huffman_tree(avctx, gb))
2273 if (read_huffman_tree(avctx, gb))
2276 s->huff_code_size--;
2282 static int vp3_init_thread_copy(AVCodecContext *avctx)
2284 Vp3DecodeContext *s = avctx->priv_data;
2286 s->superblock_coding = NULL;
2287 s->all_fragments = NULL;
2288 s->coded_fragment_list[0] = NULL;
2289 s-> kf_coded_fragment_list= NULL;
2290 s->nkf_coded_fragment_list= NULL;
2291 s->dct_tokens_base = NULL;
2292 s->superblock_fragments = NULL;
2293 s->macroblock_coding = NULL;
2294 s->motion_val[0] = NULL;
2295 s->motion_val[1] = NULL;
2296 s->edge_emu_buffer = NULL;
2298 return init_frames(s);
2302 #if CONFIG_THEORA_DECODER
2303 static const enum AVPixelFormat theora_pix_fmts[4] = {
2304 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2307 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2309 Vp3DecodeContext *s = avctx->priv_data;
2310 int visible_width, visible_height, colorspace;
2311 uint8_t offset_x = 0, offset_y = 0;
2313 AVRational fps, aspect;
2315 s->theora_header = 0;
2316 s->theora = get_bits_long(gb, 24);
2317 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2319 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2320 * but previous versions have the image flipped relative to vp3 */
2321 if (s->theora < 0x030200) {
2322 s->flipped_image = 1;
2323 av_log(avctx, AV_LOG_DEBUG,
2324 "Old (<alpha3) Theora bitstream, flipped image\n");
2328 s->width = get_bits(gb, 16) << 4;
2330 s->height = get_bits(gb, 16) << 4;
2332 if (s->theora >= 0x030200) {
2333 visible_width = get_bits_long(gb, 24);
2334 visible_height = get_bits_long(gb, 24);
2336 offset_x = get_bits(gb, 8); /* offset x */
2337 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2341 if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2342 visible_width + offset_x > s->width ||
2343 visible_height + offset_y > s->height) {
2344 av_log(avctx, AV_LOG_ERROR,
2345 "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2346 visible_width, visible_height, offset_x, offset_y,
2347 s->width, s->height);
2348 return AVERROR_INVALIDDATA;
2351 fps.num = get_bits_long(gb, 32);
2352 fps.den = get_bits_long(gb, 32);
2353 if (fps.num && fps.den) {
2354 if (fps.num < 0 || fps.den < 0) {
2355 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2356 return AVERROR_INVALIDDATA;
2358 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2359 fps.den, fps.num, 1 << 30);
2362 aspect.num = get_bits_long(gb, 24);
2363 aspect.den = get_bits_long(gb, 24);
2364 if (aspect.num && aspect.den) {
2365 av_reduce(&avctx->sample_aspect_ratio.num,
2366 &avctx->sample_aspect_ratio.den,
2367 aspect.num, aspect.den, 1 << 30);
2368 ff_set_sar(avctx, avctx->sample_aspect_ratio);
2371 if (s->theora < 0x030200)
2372 skip_bits(gb, 5); /* keyframe frequency force */
2373 colorspace = get_bits(gb, 8);
2374 skip_bits(gb, 24); /* bitrate */
2376 skip_bits(gb, 6); /* quality hint */
2378 if (s->theora >= 0x030200) {
2379 skip_bits(gb, 5); /* keyframe frequency force */
2380 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2381 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2382 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2383 return AVERROR_INVALIDDATA;
2385 skip_bits(gb, 3); /* reserved */
2387 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2389 ret = ff_set_dimensions(avctx, s->width, s->height);
2392 if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2393 avctx->width = visible_width;
2394 avctx->height = visible_height;
2395 // translate offsets from theora axis ([0,0] lower left)
2396 // to normal axis ([0,0] upper left)
2397 s->offset_x = offset_x;
2398 s->offset_y = s->height - visible_height - offset_y;
2401 if (colorspace == 1)
2402 avctx->color_primaries = AVCOL_PRI_BT470M;
2403 else if (colorspace == 2)
2404 avctx->color_primaries = AVCOL_PRI_BT470BG;
2406 if (colorspace == 1 || colorspace == 2) {
2407 avctx->colorspace = AVCOL_SPC_BT470BG;
2408 avctx->color_trc = AVCOL_TRC_BT709;
2411 s->theora_header = 1;
2415 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2417 Vp3DecodeContext *s = avctx->priv_data;
2418 int i, n, matrices, inter, plane;
2420 if (!s->theora_header)
2421 return AVERROR_INVALIDDATA;
2423 if (s->theora >= 0x030200) {
2424 n = get_bits(gb, 3);
2425 /* loop filter limit values table */
2427 for (i = 0; i < 64; i++)
2428 s->filter_limit_values[i] = get_bits(gb, n);
2431 if (s->theora >= 0x030200)
2432 n = get_bits(gb, 4) + 1;
2435 /* quality threshold table */
2436 for (i = 0; i < 64; i++)
2437 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2439 if (s->theora >= 0x030200)
2440 n = get_bits(gb, 4) + 1;
2443 /* dc scale factor table */
2444 for (i = 0; i < 64; i++)
2445 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2447 if (s->theora >= 0x030200)
2448 matrices = get_bits(gb, 9) + 1;
2452 if (matrices > 384) {
2453 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2457 for (n = 0; n < matrices; n++)
2458 for (i = 0; i < 64; i++)
2459 s->base_matrix[n][i] = get_bits(gb, 8);
2461 for (inter = 0; inter <= 1; inter++) {
2462 for (plane = 0; plane <= 2; plane++) {
2464 if (inter || plane > 0)
2465 newqr = get_bits1(gb);
2468 if (inter && get_bits1(gb)) {
2472 qtj = (3 * inter + plane - 1) / 3;
2473 plj = (plane + 2) % 3;
2475 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
2476 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
2477 sizeof(s->qr_size[0][0]));
2478 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
2479 sizeof(s->qr_base[0][0]));
2485 i = get_bits(gb, av_log2(matrices - 1) + 1);
2486 if (i >= matrices) {
2487 av_log(avctx, AV_LOG_ERROR,
2488 "invalid base matrix index\n");
2491 s->qr_base[inter][plane][qri] = i;
2494 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
2495 s->qr_size[inter][plane][qri++] = i;
2500 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2503 s->qr_count[inter][plane] = qri;
2508 /* Huffman tables */
2509 for (s->hti = 0; s->hti < 80; s->hti++) {
2511 s->huff_code_size = 1;
2512 if (!get_bits1(gb)) {
2514 if (read_huffman_tree(avctx, gb))
2517 if (read_huffman_tree(avctx, gb))
2522 s->theora_tables = 1;
2527 static av_cold int theora_decode_init(AVCodecContext *avctx)
2529 Vp3DecodeContext *s = avctx->priv_data;
2532 const uint8_t *header_start[3];
2537 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2541 if (!avctx->extradata_size) {
2542 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2546 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2547 42, header_start, header_len) < 0) {
2548 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2552 for (i = 0; i < 3; i++) {
2553 if (header_len[i] <= 0)
2555 ret = init_get_bits8(&gb, header_start[i], header_len[i]);
2559 ptype = get_bits(&gb, 8);
2561 if (!(ptype & 0x80)) {
2562 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2566 // FIXME: Check for this as well.
2567 skip_bits_long(&gb, 6 * 8); /* "theora" */
2571 if (theora_decode_header(avctx, &gb) < 0)
2575 // FIXME: is this needed? it breaks sometimes
2576 // theora_decode_comments(avctx, gb);
2579 if (theora_decode_tables(avctx, &gb))
2583 av_log(avctx, AV_LOG_ERROR,
2584 "Unknown Theora config packet: %d\n", ptype & ~0x80);
2587 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
2588 av_log(avctx, AV_LOG_WARNING,
2589 "%d bits left in packet %X\n",
2590 8 * header_len[i] - get_bits_count(&gb), ptype);
2591 if (s->theora < 0x030200)
2595 return vp3_decode_init(avctx);
2598 AVCodec ff_theora_decoder = {
2600 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2601 .type = AVMEDIA_TYPE_VIDEO,
2602 .id = AV_CODEC_ID_THEORA,
2603 .priv_data_size = sizeof(Vp3DecodeContext),
2604 .init = theora_decode_init,
2605 .close = vp3_decode_end,
2606 .decode = vp3_decode_frame,
2607 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
2608 AV_CODEC_CAP_FRAME_THREADS,
2609 .flush = vp3_decode_flush,
2610 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2611 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
2612 .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING,
2616 AVCodec ff_vp3_decoder = {
2618 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2619 .type = AVMEDIA_TYPE_VIDEO,
2620 .id = AV_CODEC_ID_VP3,
2621 .priv_data_size = sizeof(Vp3DecodeContext),
2622 .init = vp3_decode_init,
2623 .close = vp3_decode_end,
2624 .decode = vp3_decode_frame,
2625 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
2626 AV_CODEC_CAP_FRAME_THREADS,
2627 .flush = vp3_decode_flush,
2628 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2629 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),