2 * Copyright (C) 2003-2004 the ffmpeg project
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * On2 VP3 Video Decoder
25 * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
26 * For more information about the VP3 coding process, visit:
27 * http://wiki.multimedia.cx/index.php?title=On2_VP3
29 * Theora decoder by Alex Beregszaszi
36 #include "libavutil/imgutils.h"
49 #define FRAGMENT_PIXELS 8
51 // FIXME split things out into their own arrays
52 typedef struct Vp3Fragment {
54 uint8_t coding_method;
58 #define SB_NOT_CODED 0
59 #define SB_PARTIALLY_CODED 1
60 #define SB_FULLY_CODED 2
62 // This is the maximum length of a single long bit run that can be encoded
63 // for superblock coding or block qps. Theora special-cases this to read a
64 // bit instead of flipping the current bit to allow for runs longer than 4129.
65 #define MAXIMUM_LONG_BIT_RUN 4129
67 #define MODE_INTER_NO_MV 0
69 #define MODE_INTER_PLUS_MV 2
70 #define MODE_INTER_LAST_MV 3
71 #define MODE_INTER_PRIOR_LAST 4
72 #define MODE_USING_GOLDEN 5
73 #define MODE_GOLDEN_MV 6
74 #define MODE_INTER_FOURMV 7
75 #define CODING_MODE_COUNT 8
77 /* special internal mode */
80 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
81 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
84 /* There are 6 preset schemes, plus a free-form scheme */
85 static const int ModeAlphabet[6][CODING_MODE_COUNT] = {
86 /* scheme 1: Last motion vector dominates */
87 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
88 MODE_INTER_PLUS_MV, MODE_INTER_NO_MV,
89 MODE_INTRA, MODE_USING_GOLDEN,
90 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
93 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
94 MODE_INTER_NO_MV, MODE_INTER_PLUS_MV,
95 MODE_INTRA, MODE_USING_GOLDEN,
96 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
99 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
100 MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
101 MODE_INTRA, MODE_USING_GOLDEN,
102 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
105 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
106 MODE_INTER_NO_MV, MODE_INTER_PRIOR_LAST,
107 MODE_INTRA, MODE_USING_GOLDEN,
108 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
110 /* scheme 5: No motion vector dominates */
111 { MODE_INTER_NO_MV, MODE_INTER_LAST_MV,
112 MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
113 MODE_INTRA, MODE_USING_GOLDEN,
114 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
117 { MODE_INTER_NO_MV, MODE_USING_GOLDEN,
118 MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
119 MODE_INTER_PLUS_MV, MODE_INTRA,
120 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
123 static const uint8_t hilbert_offset[16][2] = {
124 { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
125 { 0, 2 }, { 0, 3 }, { 1, 3 }, { 1, 2 },
126 { 2, 2 }, { 2, 3 }, { 3, 3 }, { 3, 2 },
127 { 3, 1 }, { 2, 1 }, { 2, 0 }, { 3, 0 }
130 #define MIN_DEQUANT_VAL 2
132 typedef struct Vp3DecodeContext {
133 AVCodecContext *avctx;
134 int theora, theora_tables;
137 int chroma_x_shift, chroma_y_shift;
138 ThreadFrame golden_frame;
139 ThreadFrame last_frame;
140 ThreadFrame current_frame;
142 uint8_t idct_permutation[64];
143 uint8_t idct_scantable[64];
145 VideoDSPContext vdsp;
146 VP3DSPContext vp3dsp;
147 DECLARE_ALIGNED(16, int16_t, block)[64];
150 int skip_loop_filter;
156 int superblock_count;
157 int y_superblock_width;
158 int y_superblock_height;
159 int y_superblock_count;
160 int c_superblock_width;
161 int c_superblock_height;
162 int c_superblock_count;
163 int u_superblock_start;
164 int v_superblock_start;
165 unsigned char *superblock_coding;
167 int macroblock_count;
168 int macroblock_width;
169 int macroblock_height;
172 int fragment_width[2];
173 int fragment_height[2];
175 Vp3Fragment *all_fragments;
176 int fragment_start[3];
179 int8_t (*motion_val[2])[2];
182 uint16_t coded_dc_scale_factor[64];
183 uint32_t coded_ac_scale_factor[64];
184 uint8_t base_matrix[384][64];
185 uint8_t qr_count[2][3];
186 uint8_t qr_size[2][3][64];
187 uint16_t qr_base[2][3][64];
190 * This is a list of all tokens in bitstream order. Reordering takes place
191 * by pulling from each level during IDCT. As a consequence, IDCT must be
192 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
193 * otherwise. The 32 different tokens with up to 12 bits of extradata are
194 * collapsed into 3 types, packed as follows:
195 * (from the low to high bits)
197 * 2 bits: type (0,1,2)
198 * 0: EOB run, 14 bits for run length (12 needed)
199 * 1: zero run, 7 bits for run length
200 * 7 bits for the next coefficient (3 needed)
201 * 2: coefficient, 14 bits (11 needed)
203 * Coefficients are signed, so are packed in the highest bits for automatic
206 int16_t *dct_tokens[3][64];
207 int16_t *dct_tokens_base;
208 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
209 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) << 9) + ((zero_run) << 2) + 1)
210 #define TOKEN_COEFF(coeff) (((coeff) << 2) + 2)
213 * number of blocks that contain DCT coefficients at
214 * the given level or higher
216 int num_coded_frags[3][64];
217 int total_num_coded_frags;
219 /* this is a list of indexes into the all_fragments array indicating
220 * which of the fragments are coded */
221 int *coded_fragment_list[3];
229 VLC superblock_run_length_vlc;
230 VLC fragment_run_length_vlc;
232 VLC motion_vector_vlc;
234 /* these arrays need to be on 16-byte boundaries since SSE2 operations
236 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
238 /* This table contains superblock_count * 16 entries. Each set of 16
239 * numbers corresponds to the fragment indexes 0..15 of the superblock.
240 * An entry will be -1 to indicate that no entry corresponds to that
242 int *superblock_fragments;
244 /* This is an array that indicates how a particular macroblock
246 unsigned char *macroblock_coding;
248 uint8_t *edge_emu_buffer;
255 uint32_t huffman_table[80][32][2];
257 uint8_t filter_limit_values[64];
258 DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
261 /************************************************************************
262 * VP3 specific functions
263 ************************************************************************/
265 static void vp3_decode_flush(AVCodecContext *avctx)
267 Vp3DecodeContext *s = avctx->priv_data;
269 if (s->golden_frame.f)
270 ff_thread_release_buffer(avctx, &s->golden_frame);
272 ff_thread_release_buffer(avctx, &s->last_frame);
273 if (s->current_frame.f)
274 ff_thread_release_buffer(avctx, &s->current_frame);
277 static av_cold int vp3_decode_end(AVCodecContext *avctx)
279 Vp3DecodeContext *s = avctx->priv_data;
282 av_freep(&s->superblock_coding);
283 av_freep(&s->all_fragments);
284 av_freep(&s->coded_fragment_list[0]);
285 av_freep(&s->dct_tokens_base);
286 av_freep(&s->superblock_fragments);
287 av_freep(&s->macroblock_coding);
288 av_freep(&s->motion_val[0]);
289 av_freep(&s->motion_val[1]);
290 av_freep(&s->edge_emu_buffer);
292 s->theora_tables = 0;
294 /* release all frames */
295 vp3_decode_flush(avctx);
296 av_frame_free(&s->current_frame.f);
297 av_frame_free(&s->last_frame.f);
298 av_frame_free(&s->golden_frame.f);
300 if (avctx->internal->is_copy)
303 for (i = 0; i < 16; i++) {
304 ff_free_vlc(&s->dc_vlc[i]);
305 ff_free_vlc(&s->ac_vlc_1[i]);
306 ff_free_vlc(&s->ac_vlc_2[i]);
307 ff_free_vlc(&s->ac_vlc_3[i]);
308 ff_free_vlc(&s->ac_vlc_4[i]);
311 ff_free_vlc(&s->superblock_run_length_vlc);
312 ff_free_vlc(&s->fragment_run_length_vlc);
313 ff_free_vlc(&s->mode_code_vlc);
314 ff_free_vlc(&s->motion_vector_vlc);
320 * This function sets up all of the various blocks mappings:
321 * superblocks <-> fragments, macroblocks <-> fragments,
322 * superblocks <-> macroblocks
324 * @return 0 is successful; returns 1 if *anything* went wrong.
326 static int init_block_mapping(Vp3DecodeContext *s)
328 int sb_x, sb_y, plane;
331 for (plane = 0; plane < 3; plane++) {
332 int sb_width = plane ? s->c_superblock_width
333 : s->y_superblock_width;
334 int sb_height = plane ? s->c_superblock_height
335 : s->y_superblock_height;
336 int frag_width = s->fragment_width[!!plane];
337 int frag_height = s->fragment_height[!!plane];
339 for (sb_y = 0; sb_y < sb_height; sb_y++)
340 for (sb_x = 0; sb_x < sb_width; sb_x++)
341 for (i = 0; i < 16; i++) {
342 x = 4 * sb_x + hilbert_offset[i][0];
343 y = 4 * sb_y + hilbert_offset[i][1];
345 if (x < frag_width && y < frag_height)
346 s->superblock_fragments[j++] = s->fragment_start[plane] +
349 s->superblock_fragments[j++] = -1;
353 return 0; /* successful path out */
357 * This function sets up the dequantization tables used for a particular
360 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
362 int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
363 int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
364 int i, plane, inter, qri, bmi, bmj, qistart;
366 for (inter = 0; inter < 2; inter++) {
367 for (plane = 0; plane < 3; plane++) {
369 for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
370 sum += s->qr_size[inter][plane][qri];
371 if (s->qps[qpi] <= sum)
374 qistart = sum - s->qr_size[inter][plane][qri];
375 bmi = s->qr_base[inter][plane][qri];
376 bmj = s->qr_base[inter][plane][qri + 1];
377 for (i = 0; i < 64; i++) {
378 int coeff = (2 * (sum - s->qps[qpi]) * s->base_matrix[bmi][i] -
379 2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
380 s->qr_size[inter][plane][qri]) /
381 (2 * s->qr_size[inter][plane][qri]);
383 int qmin = 8 << (inter + !i);
384 int qscale = i ? ac_scale_factor : dc_scale_factor;
386 s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
387 av_clip((qscale * coeff) / 100 * 4, qmin, 4096);
389 /* all DC coefficients use the same quant so as not to interfere
390 * with DC prediction */
391 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
397 * This function initializes the loop filter boundary limits if the frame's
398 * quality index is different from the previous frame's.
400 * The filter_limit_values may not be larger than 127.
402 static void init_loop_filter(Vp3DecodeContext *s)
404 int *bounding_values = s->bounding_values_array + 127;
409 filter_limit = s->filter_limit_values[s->qps[0]];
410 av_assert0(filter_limit < 128U);
412 /* set up the bounding values */
413 memset(s->bounding_values_array, 0, 256 * sizeof(int));
414 for (x = 0; x < filter_limit; x++) {
415 bounding_values[-x] = -x;
416 bounding_values[x] = x;
418 for (x = value = filter_limit; x < 128 && value; x++, value--) {
419 bounding_values[ x] = value;
420 bounding_values[-x] = -value;
423 bounding_values[128] = value;
424 bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
428 * This function unpacks all of the superblock/macroblock/fragment coding
429 * information from the bitstream.
431 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
433 int superblock_starts[3] = {
434 0, s->u_superblock_start, s->v_superblock_start
437 int current_superblock = 0;
439 int num_partial_superblocks = 0;
442 int current_fragment;
446 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
448 /* unpack the list of partially-coded superblocks */
449 bit = get_bits1(gb) ^ 1;
452 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
453 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
458 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
460 if (current_run == 34)
461 current_run += get_bits(gb, 12);
463 if (current_superblock + current_run > s->superblock_count) {
464 av_log(s->avctx, AV_LOG_ERROR,
465 "Invalid partially coded superblock run length\n");
469 memset(s->superblock_coding + current_superblock, bit, current_run);
471 current_superblock += current_run;
473 num_partial_superblocks += current_run;
476 /* unpack the list of fully coded superblocks if any of the blocks were
477 * not marked as partially coded in the previous step */
478 if (num_partial_superblocks < s->superblock_count) {
479 int superblocks_decoded = 0;
481 current_superblock = 0;
482 bit = get_bits1(gb) ^ 1;
485 while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
486 get_bits_left(gb) > 0) {
487 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
492 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
494 if (current_run == 34)
495 current_run += get_bits(gb, 12);
497 for (j = 0; j < current_run; current_superblock++) {
498 if (current_superblock >= s->superblock_count) {
499 av_log(s->avctx, AV_LOG_ERROR,
500 "Invalid fully coded superblock run length\n");
504 /* skip any superblocks already marked as partially coded */
505 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
506 s->superblock_coding[current_superblock] = 2 * bit;
510 superblocks_decoded += current_run;
514 /* if there were partial blocks, initialize bitstream for
515 * unpacking fragment codings */
516 if (num_partial_superblocks) {
519 /* toggle the bit because as soon as the first run length is
520 * fetched the bit will be toggled again */
525 /* figure out which fragments are coded; iterate through each
526 * superblock (all planes) */
527 s->total_num_coded_frags = 0;
528 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
530 for (plane = 0; plane < 3; plane++) {
531 int sb_start = superblock_starts[plane];
532 int sb_end = sb_start + (plane ? s->c_superblock_count
533 : s->y_superblock_count);
534 int num_coded_frags = 0;
536 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
537 /* iterate through all 16 fragments in a superblock */
538 for (j = 0; j < 16; j++) {
539 /* if the fragment is in bounds, check its coding status */
540 current_fragment = s->superblock_fragments[i * 16 + j];
541 if (current_fragment != -1) {
542 int coded = s->superblock_coding[i];
544 if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
545 /* fragment may or may not be coded; this is the case
546 * that cares about the fragment coding runs */
547 if (current_run-- == 0) {
549 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
555 /* default mode; actual mode will be decoded in
557 s->all_fragments[current_fragment].coding_method =
559 s->coded_fragment_list[plane][num_coded_frags++] =
562 /* not coded; copy this fragment from the prior frame */
563 s->all_fragments[current_fragment].coding_method =
569 s->total_num_coded_frags += num_coded_frags;
570 for (i = 0; i < 64; i++)
571 s->num_coded_frags[plane][i] = num_coded_frags;
573 s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
580 * This function unpacks all the coding mode data for individual macroblocks
581 * from the bitstream.
583 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
585 int i, j, k, sb_x, sb_y;
587 int current_macroblock;
588 int current_fragment;
590 int custom_mode_alphabet[CODING_MODE_COUNT];
595 for (i = 0; i < s->fragment_count; i++)
596 s->all_fragments[i].coding_method = MODE_INTRA;
598 /* fetch the mode coding scheme for this frame */
599 scheme = get_bits(gb, 3);
601 /* is it a custom coding scheme? */
603 for (i = 0; i < 8; i++)
604 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
605 for (i = 0; i < 8; i++)
606 custom_mode_alphabet[get_bits(gb, 3)] = i;
607 alphabet = custom_mode_alphabet;
609 alphabet = ModeAlphabet[scheme - 1];
611 /* iterate through all of the macroblocks that contain 1 or more
613 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
614 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
615 if (get_bits_left(gb) <= 0)
618 for (j = 0; j < 4; j++) {
619 int mb_x = 2 * sb_x + (j >> 1);
620 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
621 current_macroblock = mb_y * s->macroblock_width + mb_x;
623 if (mb_x >= s->macroblock_width ||
624 mb_y >= s->macroblock_height)
627 #define BLOCK_X (2 * mb_x + (k & 1))
628 #define BLOCK_Y (2 * mb_y + (k >> 1))
629 /* coding modes are only stored if the macroblock has
630 * at least one luma block coded, otherwise it must be
632 for (k = 0; k < 4; k++) {
633 current_fragment = BLOCK_Y *
634 s->fragment_width[0] + BLOCK_X;
635 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
639 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
643 /* mode 7 means get 3 bits for each coding mode */
645 coding_mode = get_bits(gb, 3);
647 coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
649 s->macroblock_coding[current_macroblock] = coding_mode;
650 for (k = 0; k < 4; k++) {
651 frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
652 if (frag->coding_method != MODE_COPY)
653 frag->coding_method = coding_mode;
656 #define SET_CHROMA_MODES \
657 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
658 frag[s->fragment_start[1]].coding_method = coding_mode; \
659 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
660 frag[s->fragment_start[2]].coding_method = coding_mode;
662 if (s->chroma_y_shift) {
663 frag = s->all_fragments + mb_y *
664 s->fragment_width[1] + mb_x;
666 } else if (s->chroma_x_shift) {
667 frag = s->all_fragments +
668 2 * mb_y * s->fragment_width[1] + mb_x;
669 for (k = 0; k < 2; k++) {
671 frag += s->fragment_width[1];
674 for (k = 0; k < 4; k++) {
675 frag = s->all_fragments +
676 BLOCK_Y * s->fragment_width[1] + BLOCK_X;
689 * This function unpacks all the motion vectors for the individual
690 * macroblocks from the bitstream.
692 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
694 int j, k, sb_x, sb_y;
698 int last_motion_x = 0;
699 int last_motion_y = 0;
700 int prior_last_motion_x = 0;
701 int prior_last_motion_y = 0;
702 int current_macroblock;
703 int current_fragment;
709 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
710 coding_mode = get_bits1(gb);
712 /* iterate through all of the macroblocks that contain 1 or more
714 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
715 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
716 if (get_bits_left(gb) <= 0)
719 for (j = 0; j < 4; j++) {
720 int mb_x = 2 * sb_x + (j >> 1);
721 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
722 current_macroblock = mb_y * s->macroblock_width + mb_x;
724 if (mb_x >= s->macroblock_width ||
725 mb_y >= s->macroblock_height ||
726 s->macroblock_coding[current_macroblock] == MODE_COPY)
729 switch (s->macroblock_coding[current_macroblock]) {
730 case MODE_INTER_PLUS_MV:
732 /* all 6 fragments use the same motion vector */
733 if (coding_mode == 0) {
734 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
735 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
737 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
738 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
741 /* vector maintenance, only on MODE_INTER_PLUS_MV */
742 if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
743 prior_last_motion_x = last_motion_x;
744 prior_last_motion_y = last_motion_y;
745 last_motion_x = motion_x[0];
746 last_motion_y = motion_y[0];
750 case MODE_INTER_FOURMV:
751 /* vector maintenance */
752 prior_last_motion_x = last_motion_x;
753 prior_last_motion_y = last_motion_y;
755 /* fetch 4 vectors from the bitstream, one for each
756 * Y fragment, then average for the C fragment vectors */
757 for (k = 0; k < 4; k++) {
758 current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
759 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
760 if (coding_mode == 0) {
761 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
762 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
764 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
765 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
767 last_motion_x = motion_x[k];
768 last_motion_y = motion_y[k];
776 case MODE_INTER_LAST_MV:
777 /* all 6 fragments use the last motion vector */
778 motion_x[0] = last_motion_x;
779 motion_y[0] = last_motion_y;
781 /* no vector maintenance (last vector remains the
785 case MODE_INTER_PRIOR_LAST:
786 /* all 6 fragments use the motion vector prior to the
787 * last motion vector */
788 motion_x[0] = prior_last_motion_x;
789 motion_y[0] = prior_last_motion_y;
791 /* vector maintenance */
792 prior_last_motion_x = last_motion_x;
793 prior_last_motion_y = last_motion_y;
794 last_motion_x = motion_x[0];
795 last_motion_y = motion_y[0];
799 /* covers intra, inter without MV, golden without MV */
803 /* no vector maintenance */
807 /* assign the motion vectors to the correct fragments */
808 for (k = 0; k < 4; k++) {
810 BLOCK_Y * s->fragment_width[0] + BLOCK_X;
811 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
812 s->motion_val[0][current_fragment][0] = motion_x[k];
813 s->motion_val[0][current_fragment][1] = motion_y[k];
815 s->motion_val[0][current_fragment][0] = motion_x[0];
816 s->motion_val[0][current_fragment][1] = motion_y[0];
820 if (s->chroma_y_shift) {
821 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
822 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
823 motion_x[2] + motion_x[3], 2);
824 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
825 motion_y[2] + motion_y[3], 2);
827 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
828 motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
829 frag = mb_y * s->fragment_width[1] + mb_x;
830 s->motion_val[1][frag][0] = motion_x[0];
831 s->motion_val[1][frag][1] = motion_y[0];
832 } else if (s->chroma_x_shift) {
833 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
834 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
835 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
836 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
837 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
839 motion_x[1] = motion_x[0];
840 motion_y[1] = motion_y[0];
842 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
843 motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
845 frag = 2 * mb_y * s->fragment_width[1] + mb_x;
846 for (k = 0; k < 2; k++) {
847 s->motion_val[1][frag][0] = motion_x[k];
848 s->motion_val[1][frag][1] = motion_y[k];
849 frag += s->fragment_width[1];
852 for (k = 0; k < 4; k++) {
853 frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
854 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
855 s->motion_val[1][frag][0] = motion_x[k];
856 s->motion_val[1][frag][1] = motion_y[k];
858 s->motion_val[1][frag][0] = motion_x[0];
859 s->motion_val[1][frag][1] = motion_y[0];
870 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
872 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
873 int num_blocks = s->total_num_coded_frags;
875 for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
876 i = blocks_decoded = num_blocks_at_qpi = 0;
878 bit = get_bits1(gb) ^ 1;
882 if (run_length == MAXIMUM_LONG_BIT_RUN)
887 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
888 if (run_length == 34)
889 run_length += get_bits(gb, 12);
890 blocks_decoded += run_length;
893 num_blocks_at_qpi += run_length;
895 for (j = 0; j < run_length; i++) {
896 if (i >= s->total_num_coded_frags)
899 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
900 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
904 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
906 num_blocks -= num_blocks_at_qpi;
913 * This function is called by unpack_dct_coeffs() to extract the VLCs from
914 * the bitstream. The VLCs encode tokens which are used to unpack DCT
915 * data. This function unpacks all the VLCs for either the Y plane or both
916 * C planes, and is called for DC coefficients or different AC coefficient
917 * levels (since different coefficient types require different VLC tables.
919 * This function returns a residual eob run. E.g, if a particular token gave
920 * instructions to EOB the next 5 fragments and there were only 2 fragments
921 * left in the current fragment range, 3 would be returned so that it could
922 * be passed into the next call to this same function.
924 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
925 VLC *table, int coeff_index,
936 int num_coeffs = s->num_coded_frags[plane][coeff_index];
937 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
939 /* local references to structure members to avoid repeated deferences */
940 int *coded_fragment_list = s->coded_fragment_list[plane];
941 Vp3Fragment *all_fragments = s->all_fragments;
942 VLC_TYPE(*vlc_table)[2] = table->table;
945 av_log(s->avctx, AV_LOG_ERROR,
946 "Invalid number of coefficents at level %d\n", coeff_index);
948 if (eob_run > num_coeffs) {
950 blocks_ended = num_coeffs;
951 eob_run -= num_coeffs;
954 blocks_ended = eob_run;
958 // insert fake EOB token to cover the split between planes or zzi
960 dct_tokens[j++] = blocks_ended << 2;
962 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
963 /* decode a VLC into a token */
964 token = get_vlc2(gb, vlc_table, 11, 3);
965 /* use the token to get a zero run, a coefficient, and an eob run */
966 if ((unsigned) token <= 6U) {
967 eob_run = eob_run_base[token];
968 if (eob_run_get_bits[token])
969 eob_run += get_bits(gb, eob_run_get_bits[token]);
971 // record only the number of blocks ended in this plane,
972 // any spill will be recorded in the next plane.
973 if (eob_run > num_coeffs - coeff_i) {
974 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
975 blocks_ended += num_coeffs - coeff_i;
976 eob_run -= num_coeffs - coeff_i;
977 coeff_i = num_coeffs;
979 dct_tokens[j++] = TOKEN_EOB(eob_run);
980 blocks_ended += eob_run;
984 } else if (token >= 0) {
985 bits_to_get = coeff_get_bits[token];
987 bits_to_get = get_bits(gb, bits_to_get);
988 coeff = coeff_tables[token][bits_to_get];
990 zero_run = zero_run_base[token];
991 if (zero_run_get_bits[token])
992 zero_run += get_bits(gb, zero_run_get_bits[token]);
995 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
997 // Save DC into the fragment structure. DC prediction is
998 // done in raster order, so the actual DC can't be in with
999 // other tokens. We still need the token in dct_tokens[]
1000 // however, or else the structure collapses on itself.
1002 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1004 dct_tokens[j++] = TOKEN_COEFF(coeff);
1007 if (coeff_index + zero_run > 64) {
1008 av_log(s->avctx, AV_LOG_DEBUG,
1009 "Invalid zero run of %d with %d coeffs left\n",
1010 zero_run, 64 - coeff_index);
1011 zero_run = 64 - coeff_index;
1014 // zero runs code multiple coefficients,
1015 // so don't try to decode coeffs for those higher levels
1016 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1017 s->num_coded_frags[plane][i]--;
1020 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1025 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1026 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1028 // decrement the number of blocks that have higher coeffecients for each
1029 // EOB run at this level
1031 for (i = coeff_index + 1; i < 64; i++)
1032 s->num_coded_frags[plane][i] -= blocks_ended;
1034 // setup the next buffer
1036 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1037 else if (coeff_index < 63)
1038 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1043 static void reverse_dc_prediction(Vp3DecodeContext *s,
1046 int fragment_height);
1048 * This function unpacks all of the DCT coefficient data from the
1051 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1058 int residual_eob_run = 0;
1062 s->dct_tokens[0][0] = s->dct_tokens_base;
1064 /* fetch the DC table indexes */
1065 dc_y_table = get_bits(gb, 4);
1066 dc_c_table = get_bits(gb, 4);
1068 /* unpack the Y plane DC coefficients */
1069 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1070 0, residual_eob_run);
1071 if (residual_eob_run < 0)
1072 return residual_eob_run;
1074 /* reverse prediction of the Y-plane DC coefficients */
1075 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1077 /* unpack the C plane DC coefficients */
1078 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1079 1, residual_eob_run);
1080 if (residual_eob_run < 0)
1081 return residual_eob_run;
1082 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1083 2, residual_eob_run);
1084 if (residual_eob_run < 0)
1085 return residual_eob_run;
1087 /* reverse prediction of the C-plane DC coefficients */
1088 if (!(s->avctx->flags & CODEC_FLAG_GRAY)) {
1089 reverse_dc_prediction(s, s->fragment_start[1],
1090 s->fragment_width[1], s->fragment_height[1]);
1091 reverse_dc_prediction(s, s->fragment_start[2],
1092 s->fragment_width[1], s->fragment_height[1]);
1095 /* fetch the AC table indexes */
1096 ac_y_table = get_bits(gb, 4);
1097 ac_c_table = get_bits(gb, 4);
1099 /* build tables of AC VLC tables */
1100 for (i = 1; i <= 5; i++) {
1101 y_tables[i] = &s->ac_vlc_1[ac_y_table];
1102 c_tables[i] = &s->ac_vlc_1[ac_c_table];
1104 for (i = 6; i <= 14; i++) {
1105 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1106 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1108 for (i = 15; i <= 27; i++) {
1109 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1110 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1112 for (i = 28; i <= 63; i++) {
1113 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1114 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1117 /* decode all AC coefficents */
1118 for (i = 1; i <= 63; i++) {
1119 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1120 0, residual_eob_run);
1121 if (residual_eob_run < 0)
1122 return residual_eob_run;
1124 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1125 1, residual_eob_run);
1126 if (residual_eob_run < 0)
1127 return residual_eob_run;
1128 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1129 2, residual_eob_run);
1130 if (residual_eob_run < 0)
1131 return residual_eob_run;
1138 * This function reverses the DC prediction for each coded fragment in
1139 * the frame. Much of this function is adapted directly from the original
1142 #define COMPATIBLE_FRAME(x) \
1143 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1144 #define DC_COEFF(u) s->all_fragments[u].dc
1146 static void reverse_dc_prediction(Vp3DecodeContext *s,
1149 int fragment_height)
1157 int i = first_fragment;
1161 /* DC values for the left, up-left, up, and up-right fragments */
1162 int vl, vul, vu, vur;
1164 /* indexes for the left, up-left, up, and up-right fragments */
1168 * The 6 fields mean:
1169 * 0: up-left multiplier
1171 * 2: up-right multiplier
1172 * 3: left multiplier
1174 static const int predictor_transform[16][4] = {
1176 { 0, 0, 0, 128 }, // PL
1177 { 0, 0, 128, 0 }, // PUR
1178 { 0, 0, 53, 75 }, // PUR|PL
1179 { 0, 128, 0, 0 }, // PU
1180 { 0, 64, 0, 64 }, // PU |PL
1181 { 0, 128, 0, 0 }, // PU |PUR
1182 { 0, 0, 53, 75 }, // PU |PUR|PL
1183 { 128, 0, 0, 0 }, // PUL
1184 { 0, 0, 0, 128 }, // PUL|PL
1185 { 64, 0, 64, 0 }, // PUL|PUR
1186 { 0, 0, 53, 75 }, // PUL|PUR|PL
1187 { 0, 128, 0, 0 }, // PUL|PU
1188 { -104, 116, 0, 116 }, // PUL|PU |PL
1189 { 24, 80, 24, 0 }, // PUL|PU |PUR
1190 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1193 /* This table shows which types of blocks can use other blocks for
1194 * prediction. For example, INTRA is the only mode in this table to
1195 * have a frame number of 0. That means INTRA blocks can only predict
1196 * from other INTRA blocks. There are 2 golden frame coding types;
1197 * blocks encoding in these modes can only predict from other blocks
1198 * that were encoded with these 1 of these 2 modes. */
1199 static const unsigned char compatible_frame[9] = {
1200 1, /* MODE_INTER_NO_MV */
1202 1, /* MODE_INTER_PLUS_MV */
1203 1, /* MODE_INTER_LAST_MV */
1204 1, /* MODE_INTER_PRIOR_MV */
1205 2, /* MODE_USING_GOLDEN */
1206 2, /* MODE_GOLDEN_MV */
1207 1, /* MODE_INTER_FOUR_MV */
1210 int current_frame_type;
1212 /* there is a last DC predictor for each of the 3 frame types */
1225 /* for each fragment row... */
1226 for (y = 0; y < fragment_height; y++) {
1227 /* for each fragment in a row... */
1228 for (x = 0; x < fragment_width; x++, i++) {
1230 /* reverse prediction if this block was coded */
1231 if (s->all_fragments[i].coding_method != MODE_COPY) {
1232 current_frame_type =
1233 compatible_frame[s->all_fragments[i].coding_method];
1239 if (COMPATIBLE_FRAME(l))
1243 u = i - fragment_width;
1245 if (COMPATIBLE_FRAME(u))
1248 ul = i - fragment_width - 1;
1250 if (COMPATIBLE_FRAME(ul))
1253 if (x + 1 < fragment_width) {
1254 ur = i - fragment_width + 1;
1256 if (COMPATIBLE_FRAME(ur))
1261 if (transform == 0) {
1262 /* if there were no fragments to predict from, use last
1264 predicted_dc = last_dc[current_frame_type];
1266 /* apply the appropriate predictor transform */
1268 (predictor_transform[transform][0] * vul) +
1269 (predictor_transform[transform][1] * vu) +
1270 (predictor_transform[transform][2] * vur) +
1271 (predictor_transform[transform][3] * vl);
1273 predicted_dc /= 128;
1275 /* check for outranging on the [ul u l] and
1276 * [ul u ur l] predictors */
1277 if ((transform == 15) || (transform == 13)) {
1278 if (FFABS(predicted_dc - vu) > 128)
1280 else if (FFABS(predicted_dc - vl) > 128)
1282 else if (FFABS(predicted_dc - vul) > 128)
1287 /* at long last, apply the predictor */
1288 DC_COEFF(i) += predicted_dc;
1290 last_dc[current_frame_type] = DC_COEFF(i);
1296 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1297 int ystart, int yend)
1300 int *bounding_values = s->bounding_values_array + 127;
1302 int width = s->fragment_width[!!plane];
1303 int height = s->fragment_height[!!plane];
1304 int fragment = s->fragment_start[plane] + ystart * width;
1305 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1306 uint8_t *plane_data = s->current_frame.f->data[plane];
1307 if (!s->flipped_image)
1309 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1311 for (y = ystart; y < yend; y++) {
1312 for (x = 0; x < width; x++) {
1313 /* This code basically just deblocks on the edges of coded blocks.
1314 * However, it has to be much more complicated because of the
1315 * braindamaged deblock ordering used in VP3/Theora. Order matters
1316 * because some pixels get filtered twice. */
1317 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1318 /* do not perform left edge filter for left columns frags */
1320 s->vp3dsp.h_loop_filter(
1322 stride, bounding_values);
1325 /* do not perform top edge filter for top row fragments */
1327 s->vp3dsp.v_loop_filter(
1329 stride, bounding_values);
1332 /* do not perform right edge filter for right column
1333 * fragments or if right fragment neighbor is also coded
1334 * in this frame (it will be filtered in next iteration) */
1335 if ((x < width - 1) &&
1336 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1337 s->vp3dsp.h_loop_filter(
1338 plane_data + 8 * x + 8,
1339 stride, bounding_values);
1342 /* do not perform bottom edge filter for bottom row
1343 * fragments or if bottom fragment neighbor is also coded
1344 * in this frame (it will be filtered in the next row) */
1345 if ((y < height - 1) &&
1346 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1347 s->vp3dsp.v_loop_filter(
1348 plane_data + 8 * x + 8 * stride,
1349 stride, bounding_values);
1355 plane_data += 8 * stride;
1360 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1361 * for the next block in coding order
1363 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1364 int plane, int inter, int16_t block[64])
1366 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1367 uint8_t *perm = s->idct_scantable;
1371 int token = *s->dct_tokens[plane][i];
1372 switch (token & 3) {
1374 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1375 s->dct_tokens[plane][i]++;
1377 *s->dct_tokens[plane][i] = token & ~3;
1380 s->dct_tokens[plane][i]++;
1381 i += (token >> 2) & 0x7f;
1383 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1386 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1390 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1391 s->dct_tokens[plane][i++]++;
1393 default: // shouldn't happen
1397 // return value is expected to be a valid level
1400 // the actual DC+prediction is in the fragment structure
1401 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1406 * called when all pixels up to row y are complete
1408 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1411 int offset[AV_NUM_DATA_POINTERS];
1413 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1414 int y_flipped = s->flipped_image ? s->avctx->height - y : y;
1416 /* At the end of the frame, report INT_MAX instead of the height of
1417 * the frame. This makes the other threads' ff_thread_await_progress()
1418 * calls cheaper, because they don't have to clip their values. */
1419 ff_thread_report_progress(&s->current_frame,
1420 y_flipped == s->avctx->height ? INT_MAX
1425 if (s->avctx->draw_horiz_band == NULL)
1428 h = y - s->last_slice_end;
1429 s->last_slice_end = y;
1432 if (!s->flipped_image)
1433 y = s->avctx->height - y - h;
1435 cy = y >> s->chroma_y_shift;
1436 offset[0] = s->current_frame.f->linesize[0] * y;
1437 offset[1] = s->current_frame.f->linesize[1] * cy;
1438 offset[2] = s->current_frame.f->linesize[2] * cy;
1439 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1443 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1447 * Wait for the reference frame of the current fragment.
1448 * The progress value is in luma pixel rows.
1450 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1451 int motion_y, int y)
1453 ThreadFrame *ref_frame;
1455 int border = motion_y & 1;
1457 if (fragment->coding_method == MODE_USING_GOLDEN ||
1458 fragment->coding_method == MODE_GOLDEN_MV)
1459 ref_frame = &s->golden_frame;
1461 ref_frame = &s->last_frame;
1463 ref_row = y + (motion_y >> 1);
1464 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1466 ff_thread_await_progress(ref_frame, ref_row, 0);
1470 * Perform the final rendering for a particular slice of data.
1471 * The slice number ranges from 0..(c_superblock_height - 1).
1473 static void render_slice(Vp3DecodeContext *s, int slice)
1475 int x, y, i, j, fragment;
1476 int16_t *block = s->block;
1477 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1478 int motion_halfpel_index;
1479 uint8_t *motion_source;
1480 int plane, first_pixel;
1482 if (slice >= s->c_superblock_height)
1485 for (plane = 0; plane < 3; plane++) {
1486 uint8_t *output_plane = s->current_frame.f->data[plane] +
1487 s->data_offset[plane];
1488 uint8_t *last_plane = s->last_frame.f->data[plane] +
1489 s->data_offset[plane];
1490 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
1491 s->data_offset[plane];
1492 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1493 int plane_width = s->width >> (plane && s->chroma_x_shift);
1494 int plane_height = s->height >> (plane && s->chroma_y_shift);
1495 int8_t(*motion_val)[2] = s->motion_val[!!plane];
1497 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
1498 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
1499 int slice_width = plane ? s->c_superblock_width
1500 : s->y_superblock_width;
1502 int fragment_width = s->fragment_width[!!plane];
1503 int fragment_height = s->fragment_height[!!plane];
1504 int fragment_start = s->fragment_start[plane];
1506 int do_await = !plane && HAVE_THREADS &&
1507 (s->avctx->active_thread_type & FF_THREAD_FRAME);
1509 if (!s->flipped_image)
1511 if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1514 /* for each superblock row in the slice (both of them)... */
1515 for (; sb_y < slice_height; sb_y++) {
1516 /* for each superblock in a row... */
1517 for (sb_x = 0; sb_x < slice_width; sb_x++) {
1518 /* for each block in a superblock... */
1519 for (j = 0; j < 16; j++) {
1520 x = 4 * sb_x + hilbert_offset[j][0];
1521 y = 4 * sb_y + hilbert_offset[j][1];
1522 fragment = y * fragment_width + x;
1524 i = fragment_start + fragment;
1527 if (x >= fragment_width || y >= fragment_height)
1530 first_pixel = 8 * y * stride + 8 * x;
1533 s->all_fragments[i].coding_method != MODE_INTRA)
1534 await_reference_row(s, &s->all_fragments[i],
1535 motion_val[fragment][1],
1536 (16 * y) >> s->chroma_y_shift);
1538 /* transform if this block was coded */
1539 if (s->all_fragments[i].coding_method != MODE_COPY) {
1540 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1541 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1542 motion_source = golden_plane;
1544 motion_source = last_plane;
1546 motion_source += first_pixel;
1547 motion_halfpel_index = 0;
1549 /* sort out the motion vector if this fragment is coded
1550 * using a motion vector method */
1551 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1552 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1554 motion_x = motion_val[fragment][0];
1555 motion_y = motion_val[fragment][1];
1557 src_x = (motion_x >> 1) + 8 * x;
1558 src_y = (motion_y >> 1) + 8 * y;
1560 motion_halfpel_index = motion_x & 0x01;
1561 motion_source += (motion_x >> 1);
1563 motion_halfpel_index |= (motion_y & 0x01) << 1;
1564 motion_source += ((motion_y >> 1) * stride);
1566 if (src_x < 0 || src_y < 0 ||
1567 src_x + 9 >= plane_width ||
1568 src_y + 9 >= plane_height) {
1569 uint8_t *temp = s->edge_emu_buffer;
1573 s->vdsp.emulated_edge_mc(temp, motion_source,
1578 motion_source = temp;
1582 /* first, take care of copying a block from either the
1583 * previous or the golden frame */
1584 if (s->all_fragments[i].coding_method != MODE_INTRA) {
1585 /* Note, it is possible to implement all MC cases
1586 * with put_no_rnd_pixels_l2 which would look more
1587 * like the VP3 source but this would be slower as
1588 * put_no_rnd_pixels_tab is better optimzed */
1589 if (motion_halfpel_index != 3) {
1590 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1591 output_plane + first_pixel,
1592 motion_source, stride, 8);
1594 /* d is 0 if motion_x and _y have the same sign,
1596 int d = (motion_x ^ motion_y) >> 31;
1597 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
1599 motion_source + stride + 1 + d,
1604 /* invert DCT and place (or add) in final output */
1606 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1607 vp3_dequant(s, s->all_fragments + i,
1609 s->vp3dsp.idct_put(output_plane + first_pixel,
1613 if (vp3_dequant(s, s->all_fragments + i,
1615 s->vp3dsp.idct_add(output_plane + first_pixel,
1619 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
1624 /* copy directly from the previous frame */
1625 s->hdsp.put_pixels_tab[1][0](
1626 output_plane + first_pixel,
1627 last_plane + first_pixel,
1633 // Filter up to the last row in the superblock row
1634 if (!s->skip_loop_filter)
1635 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
1636 FFMIN(4 * sb_y + 3, fragment_height - 1));
1640 /* this looks like a good place for slice dispatch... */
1642 * if (slice == s->macroblock_height - 1)
1643 * dispatch (both last slice & 2nd-to-last slice);
1644 * else if (slice > 0)
1645 * dispatch (slice - 1);
1648 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
1652 /// Allocate tables for per-frame data in Vp3DecodeContext
1653 static av_cold int allocate_tables(AVCodecContext *avctx)
1655 Vp3DecodeContext *s = avctx->priv_data;
1656 int y_fragment_count, c_fragment_count;
1658 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1659 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1661 s->superblock_coding = av_mallocz(s->superblock_count);
1662 s->all_fragments = av_mallocz(s->fragment_count * sizeof(Vp3Fragment));
1664 s->coded_fragment_list[0] = av_mallocz(s->fragment_count * sizeof(int));
1666 s->dct_tokens_base = av_mallocz(64 * s->fragment_count *
1667 sizeof(*s->dct_tokens_base));
1668 s->motion_val[0] = av_mallocz(y_fragment_count * sizeof(*s->motion_val[0]));
1669 s->motion_val[1] = av_mallocz(c_fragment_count * sizeof(*s->motion_val[1]));
1671 /* work out the block mapping tables */
1672 s->superblock_fragments = av_mallocz(s->superblock_count * 16 * sizeof(int));
1673 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
1675 if (!s->superblock_coding || !s->all_fragments ||
1676 !s->dct_tokens_base || !s->coded_fragment_list[0] ||
1677 !s->superblock_fragments || !s->macroblock_coding ||
1678 !s->motion_val[0] || !s->motion_val[1]) {
1679 vp3_decode_end(avctx);
1683 init_block_mapping(s);
1688 static av_cold int init_frames(Vp3DecodeContext *s)
1690 s->current_frame.f = av_frame_alloc();
1691 s->last_frame.f = av_frame_alloc();
1692 s->golden_frame.f = av_frame_alloc();
1694 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
1695 av_frame_free(&s->current_frame.f);
1696 av_frame_free(&s->last_frame.f);
1697 av_frame_free(&s->golden_frame.f);
1698 return AVERROR(ENOMEM);
1704 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1706 Vp3DecodeContext *s = avctx->priv_data;
1707 int i, inter, plane, ret;
1710 int y_fragment_count, c_fragment_count;
1712 ret = init_frames(s);
1716 avctx->internal->allocate_progress = 1;
1718 if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
1724 s->width = FFALIGN(avctx->width, 16);
1725 s->height = FFALIGN(avctx->height, 16);
1726 if (avctx->codec_id != AV_CODEC_ID_THEORA)
1727 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
1728 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1729 ff_hpeldsp_init(&s->hdsp, avctx->flags | CODEC_FLAG_BITEXACT);
1730 ff_videodsp_init(&s->vdsp, 8);
1731 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
1733 for (i = 0; i < 64; i++) {
1734 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
1735 s->idct_permutation[i] = TRANSPOSE(i);
1736 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
1740 /* initialize to an impossible value which will force a recalculation
1741 * in the first frame decode */
1742 for (i = 0; i < 3; i++)
1745 avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1747 s->y_superblock_width = (s->width + 31) / 32;
1748 s->y_superblock_height = (s->height + 31) / 32;
1749 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1751 /* work out the dimensions for the C planes */
1752 c_width = s->width >> s->chroma_x_shift;
1753 c_height = s->height >> s->chroma_y_shift;
1754 s->c_superblock_width = (c_width + 31) / 32;
1755 s->c_superblock_height = (c_height + 31) / 32;
1756 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1758 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1759 s->u_superblock_start = s->y_superblock_count;
1760 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1762 s->macroblock_width = (s->width + 15) / 16;
1763 s->macroblock_height = (s->height + 15) / 16;
1764 s->macroblock_count = s->macroblock_width * s->macroblock_height;
1766 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1767 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1768 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
1769 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
1771 /* fragment count covers all 8x8 blocks for all 3 planes */
1772 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1773 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1774 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
1775 s->fragment_start[1] = y_fragment_count;
1776 s->fragment_start[2] = y_fragment_count + c_fragment_count;
1778 if (!s->theora_tables) {
1779 for (i = 0; i < 64; i++) {
1780 s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1781 s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1782 s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1783 s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1784 s->base_matrix[2][i] = vp31_inter_dequant[i];
1785 s->filter_limit_values[i] = vp31_filter_limit_values[i];
1788 for (inter = 0; inter < 2; inter++) {
1789 for (plane = 0; plane < 3; plane++) {
1790 s->qr_count[inter][plane] = 1;
1791 s->qr_size[inter][plane][0] = 63;
1792 s->qr_base[inter][plane][0] =
1793 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
1797 /* init VLC tables */
1798 for (i = 0; i < 16; i++) {
1800 init_vlc(&s->dc_vlc[i], 11, 32,
1801 &dc_bias[i][0][1], 4, 2,
1802 &dc_bias[i][0][0], 4, 2, 0);
1804 /* group 1 AC histograms */
1805 init_vlc(&s->ac_vlc_1[i], 11, 32,
1806 &ac_bias_0[i][0][1], 4, 2,
1807 &ac_bias_0[i][0][0], 4, 2, 0);
1809 /* group 2 AC histograms */
1810 init_vlc(&s->ac_vlc_2[i], 11, 32,
1811 &ac_bias_1[i][0][1], 4, 2,
1812 &ac_bias_1[i][0][0], 4, 2, 0);
1814 /* group 3 AC histograms */
1815 init_vlc(&s->ac_vlc_3[i], 11, 32,
1816 &ac_bias_2[i][0][1], 4, 2,
1817 &ac_bias_2[i][0][0], 4, 2, 0);
1819 /* group 4 AC histograms */
1820 init_vlc(&s->ac_vlc_4[i], 11, 32,
1821 &ac_bias_3[i][0][1], 4, 2,
1822 &ac_bias_3[i][0][0], 4, 2, 0);
1825 for (i = 0; i < 16; i++) {
1827 if (init_vlc(&s->dc_vlc[i], 11, 32,
1828 &s->huffman_table[i][0][1], 8, 4,
1829 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
1832 /* group 1 AC histograms */
1833 if (init_vlc(&s->ac_vlc_1[i], 11, 32,
1834 &s->huffman_table[i + 16][0][1], 8, 4,
1835 &s->huffman_table[i + 16][0][0], 8, 4, 0) < 0)
1838 /* group 2 AC histograms */
1839 if (init_vlc(&s->ac_vlc_2[i], 11, 32,
1840 &s->huffman_table[i + 16 * 2][0][1], 8, 4,
1841 &s->huffman_table[i + 16 * 2][0][0], 8, 4, 0) < 0)
1844 /* group 3 AC histograms */
1845 if (init_vlc(&s->ac_vlc_3[i], 11, 32,
1846 &s->huffman_table[i + 16 * 3][0][1], 8, 4,
1847 &s->huffman_table[i + 16 * 3][0][0], 8, 4, 0) < 0)
1850 /* group 4 AC histograms */
1851 if (init_vlc(&s->ac_vlc_4[i], 11, 32,
1852 &s->huffman_table[i + 16 * 4][0][1], 8, 4,
1853 &s->huffman_table[i + 16 * 4][0][0], 8, 4, 0) < 0)
1858 init_vlc(&s->superblock_run_length_vlc, 6, 34,
1859 &superblock_run_length_vlc_table[0][1], 4, 2,
1860 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1862 init_vlc(&s->fragment_run_length_vlc, 5, 30,
1863 &fragment_run_length_vlc_table[0][1], 4, 2,
1864 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1866 init_vlc(&s->mode_code_vlc, 3, 8,
1867 &mode_code_vlc_table[0][1], 2, 1,
1868 &mode_code_vlc_table[0][0], 2, 1, 0);
1870 init_vlc(&s->motion_vector_vlc, 6, 63,
1871 &motion_vector_vlc_table[0][1], 2, 1,
1872 &motion_vector_vlc_table[0][0], 2, 1, 0);
1874 return allocate_tables(avctx);
1877 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1881 /// Release and shuffle frames after decode finishes
1882 static int update_frames(AVCodecContext *avctx)
1884 Vp3DecodeContext *s = avctx->priv_data;
1887 /* shuffle frames (last = current) */
1888 ff_thread_release_buffer(avctx, &s->last_frame);
1889 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
1894 ff_thread_release_buffer(avctx, &s->golden_frame);
1895 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
1899 ff_thread_release_buffer(avctx, &s->current_frame);
1903 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
1905 ff_thread_release_buffer(s->avctx, dst);
1906 if (src->f->data[0])
1907 return ff_thread_ref_frame(dst, src);
1911 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
1914 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
1915 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
1916 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
1921 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1923 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1924 int qps_changed = 0, i, err;
1926 #define copy_fields(to, from, start_field, end_field) \
1927 memcpy(&to->start_field, &from->start_field, \
1928 (char *) &to->end_field - (char *) &to->start_field)
1930 if (!s1->current_frame.f->data[0] ||
1931 s->width != s1->width || s->height != s1->height) {
1938 // init tables if the first frame hasn't been decoded
1939 if (!s->current_frame.f->data[0]) {
1940 int y_fragment_count, c_fragment_count;
1942 err = allocate_tables(dst);
1945 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1946 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1947 memcpy(s->motion_val[0], s1->motion_val[0],
1948 y_fragment_count * sizeof(*s->motion_val[0]));
1949 memcpy(s->motion_val[1], s1->motion_val[1],
1950 c_fragment_count * sizeof(*s->motion_val[1]));
1953 // copy previous frame data
1954 if ((err = ref_frames(s, s1)) < 0)
1957 s->keyframe = s1->keyframe;
1959 // copy qscale data if necessary
1960 for (i = 0; i < 3; i++) {
1961 if (s->qps[i] != s1->qps[1]) {
1963 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
1967 if (s->qps[0] != s1->qps[0])
1968 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
1969 sizeof(s->bounding_values_array));
1972 copy_fields(s, s1, qps, superblock_count);
1976 return update_frames(dst);
1979 static int vp3_decode_frame(AVCodecContext *avctx,
1980 void *data, int *got_frame,
1983 const uint8_t *buf = avpkt->data;
1984 int buf_size = avpkt->size;
1985 Vp3DecodeContext *s = avctx->priv_data;
1989 init_get_bits(&gb, buf, buf_size * 8);
1991 #if CONFIG_THEORA_DECODER
1992 if (s->theora && get_bits1(&gb)) {
1993 int type = get_bits(&gb, 7);
1994 skip_bits_long(&gb, 6*8); /* "theora" */
1996 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
1997 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
1998 return AVERROR_PATCHWELCOME;
2001 vp3_decode_end(avctx);
2002 ret = theora_decode_header(avctx, &gb);
2005 vp3_decode_end(avctx);
2007 ret = vp3_decode_init(avctx);
2009 } else if (type == 2) {
2010 ret = theora_decode_tables(avctx, &gb);
2012 vp3_decode_end(avctx);
2014 ret = vp3_decode_init(avctx);
2018 av_log(avctx, AV_LOG_ERROR,
2019 "Header packet passed to frame decoder, skipping\n");
2024 s->keyframe = !get_bits1(&gb);
2025 if (!s->all_fragments) {
2026 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2031 for (i = 0; i < 3; i++)
2032 s->last_qps[i] = s->qps[i];
2036 s->qps[s->nqps++] = get_bits(&gb, 6);
2037 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2038 for (i = s->nqps; i < 3; i++)
2041 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2042 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2043 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2045 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2046 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2047 : AVDISCARD_NONKEY);
2049 if (s->qps[0] != s->last_qps[0])
2050 init_loop_filter(s);
2052 for (i = 0; i < s->nqps; i++)
2053 // reinit all dequantizers if the first one changed, because
2054 // the DC of the first quantizer must be used for all matrices
2055 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2056 init_dequantizer(s, i);
2058 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2061 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2062 : AV_PICTURE_TYPE_P;
2063 s->current_frame.f->key_frame = s->keyframe;
2064 if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2067 if (!s->edge_emu_buffer)
2068 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2072 skip_bits(&gb, 4); /* width code */
2073 skip_bits(&gb, 4); /* height code */
2075 s->version = get_bits(&gb, 5);
2076 if (avctx->frame_number == 0)
2077 av_log(s->avctx, AV_LOG_DEBUG,
2078 "VP version: %d\n", s->version);
2081 if (s->version || s->theora) {
2083 av_log(s->avctx, AV_LOG_ERROR,
2084 "Warning, unsupported keyframe coding type?!\n");
2085 skip_bits(&gb, 2); /* reserved? */
2088 if (!s->golden_frame.f->data[0]) {
2089 av_log(s->avctx, AV_LOG_WARNING,
2090 "vp3: first frame not a keyframe\n");
2092 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2093 if (ff_thread_get_buffer(avctx, &s->golden_frame,
2094 AV_GET_BUFFER_FLAG_REF) < 0)
2096 ff_thread_release_buffer(avctx, &s->last_frame);
2097 if ((ret = ff_thread_ref_frame(&s->last_frame,
2098 &s->golden_frame)) < 0)
2100 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2104 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2105 ff_thread_finish_setup(avctx);
2107 if (unpack_superblocks(s, &gb)) {
2108 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2111 if (unpack_modes(s, &gb)) {
2112 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2115 if (unpack_vectors(s, &gb)) {
2116 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2119 if (unpack_block_qpis(s, &gb)) {
2120 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2123 if (unpack_dct_coeffs(s, &gb)) {
2124 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2128 for (i = 0; i < 3; i++) {
2129 int height = s->height >> (i && s->chroma_y_shift);
2130 if (s->flipped_image)
2131 s->data_offset[i] = 0;
2133 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2136 s->last_slice_end = 0;
2137 for (i = 0; i < s->c_superblock_height; i++)
2140 // filter the last row
2141 for (i = 0; i < 3; i++) {
2142 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2143 apply_loop_filter(s, i, row, row + 1);
2145 vp3_draw_horiz_band(s, s->avctx->height);
2147 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2151 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2152 ret = update_frames(avctx);
2160 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2162 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2163 av_frame_unref(s->current_frame.f);
2168 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2170 Vp3DecodeContext *s = avctx->priv_data;
2172 if (get_bits1(gb)) {
2174 if (s->entries >= 32) { /* overflow */
2175 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2178 token = get_bits(gb, 5);
2179 av_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2180 s->hti, s->hbits, token, s->entries, s->huff_code_size);
2181 s->huffman_table[s->hti][token][0] = s->hbits;
2182 s->huffman_table[s->hti][token][1] = s->huff_code_size;
2185 if (s->huff_code_size >= 32) { /* overflow */
2186 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2189 s->huff_code_size++;
2191 if (read_huffman_tree(avctx, gb))
2194 if (read_huffman_tree(avctx, gb))
2197 s->huff_code_size--;
2202 static int vp3_init_thread_copy(AVCodecContext *avctx)
2204 Vp3DecodeContext *s = avctx->priv_data;
2206 s->superblock_coding = NULL;
2207 s->all_fragments = NULL;
2208 s->coded_fragment_list[0] = NULL;
2209 s->dct_tokens_base = NULL;
2210 s->superblock_fragments = NULL;
2211 s->macroblock_coding = NULL;
2212 s->motion_val[0] = NULL;
2213 s->motion_val[1] = NULL;
2214 s->edge_emu_buffer = NULL;
2216 return init_frames(s);
2219 #if CONFIG_THEORA_DECODER
2220 static const enum AVPixelFormat theora_pix_fmts[4] = {
2221 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2224 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2226 Vp3DecodeContext *s = avctx->priv_data;
2227 int visible_width, visible_height, colorspace;
2228 int offset_x = 0, offset_y = 0;
2230 AVRational fps, aspect;
2232 s->theora = get_bits_long(gb, 24);
2233 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2235 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2236 * but previous versions have the image flipped relative to vp3 */
2237 if (s->theora < 0x030200) {
2238 s->flipped_image = 1;
2239 av_log(avctx, AV_LOG_DEBUG,
2240 "Old (<alpha3) Theora bitstream, flipped image\n");
2244 s->width = get_bits(gb, 16) << 4;
2246 s->height = get_bits(gb, 16) << 4;
2248 if (s->theora >= 0x030200) {
2249 visible_width = get_bits_long(gb, 24);
2250 visible_height = get_bits_long(gb, 24);
2252 offset_x = get_bits(gb, 8); /* offset x */
2253 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2256 fps.num = get_bits_long(gb, 32);
2257 fps.den = get_bits_long(gb, 32);
2258 if (fps.num && fps.den) {
2259 if (fps.num < 0 || fps.den < 0) {
2260 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2261 return AVERROR_INVALIDDATA;
2263 av_reduce(&avctx->time_base.num, &avctx->time_base.den,
2264 fps.den, fps.num, 1 << 30);
2267 aspect.num = get_bits_long(gb, 24);
2268 aspect.den = get_bits_long(gb, 24);
2269 if (aspect.num && aspect.den) {
2270 av_reduce(&avctx->sample_aspect_ratio.num,
2271 &avctx->sample_aspect_ratio.den,
2272 aspect.num, aspect.den, 1 << 30);
2275 if (s->theora < 0x030200)
2276 skip_bits(gb, 5); /* keyframe frequency force */
2277 colorspace = get_bits(gb, 8);
2278 skip_bits(gb, 24); /* bitrate */
2280 skip_bits(gb, 6); /* quality hint */
2282 if (s->theora >= 0x030200) {
2283 skip_bits(gb, 5); /* keyframe frequency force */
2284 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2285 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2286 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2287 return AVERROR_INVALIDDATA;
2289 skip_bits(gb, 3); /* reserved */
2292 // align_get_bits(gb);
2294 if (visible_width <= s->width && visible_width > s->width - 16 &&
2295 visible_height <= s->height && visible_height > s->height - 16 &&
2296 !offset_x && (offset_y == s->height - visible_height))
2297 ret = ff_set_dimensions(avctx, visible_width, visible_height);
2299 ret = ff_set_dimensions(avctx, s->width, s->height);
2303 if (colorspace == 1)
2304 avctx->color_primaries = AVCOL_PRI_BT470M;
2305 else if (colorspace == 2)
2306 avctx->color_primaries = AVCOL_PRI_BT470BG;
2308 if (colorspace == 1 || colorspace == 2) {
2309 avctx->colorspace = AVCOL_SPC_BT470BG;
2310 avctx->color_trc = AVCOL_TRC_BT709;
2316 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2318 Vp3DecodeContext *s = avctx->priv_data;
2319 int i, n, matrices, inter, plane;
2321 if (s->theora >= 0x030200) {
2322 n = get_bits(gb, 3);
2323 /* loop filter limit values table */
2325 for (i = 0; i < 64; i++)
2326 s->filter_limit_values[i] = get_bits(gb, n);
2329 if (s->theora >= 0x030200)
2330 n = get_bits(gb, 4) + 1;
2333 /* quality threshold table */
2334 for (i = 0; i < 64; i++)
2335 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2337 if (s->theora >= 0x030200)
2338 n = get_bits(gb, 4) + 1;
2341 /* dc scale factor table */
2342 for (i = 0; i < 64; i++)
2343 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2345 if (s->theora >= 0x030200)
2346 matrices = get_bits(gb, 9) + 1;
2350 if (matrices > 384) {
2351 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2355 for (n = 0; n < matrices; n++)
2356 for (i = 0; i < 64; i++)
2357 s->base_matrix[n][i] = get_bits(gb, 8);
2359 for (inter = 0; inter <= 1; inter++) {
2360 for (plane = 0; plane <= 2; plane++) {
2362 if (inter || plane > 0)
2363 newqr = get_bits1(gb);
2366 if (inter && get_bits1(gb)) {
2370 qtj = (3 * inter + plane - 1) / 3;
2371 plj = (plane + 2) % 3;
2373 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
2374 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
2375 sizeof(s->qr_size[0][0]));
2376 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
2377 sizeof(s->qr_base[0][0]));
2383 i = get_bits(gb, av_log2(matrices - 1) + 1);
2384 if (i >= matrices) {
2385 av_log(avctx, AV_LOG_ERROR,
2386 "invalid base matrix index\n");
2389 s->qr_base[inter][plane][qri] = i;
2392 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
2393 s->qr_size[inter][plane][qri++] = i;
2398 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2401 s->qr_count[inter][plane] = qri;
2406 /* Huffman tables */
2407 for (s->hti = 0; s->hti < 80; s->hti++) {
2409 s->huff_code_size = 1;
2410 if (!get_bits1(gb)) {
2412 if (read_huffman_tree(avctx, gb))
2415 if (read_huffman_tree(avctx, gb))
2420 s->theora_tables = 1;
2425 static av_cold int theora_decode_init(AVCodecContext *avctx)
2427 Vp3DecodeContext *s = avctx->priv_data;
2430 uint8_t *header_start[3];
2434 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2438 if (!avctx->extradata_size) {
2439 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2443 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2444 42, header_start, header_len) < 0) {
2445 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2449 for (i = 0; i < 3; i++) {
2450 if (header_len[i] <= 0)
2452 init_get_bits(&gb, header_start[i], header_len[i] * 8);
2454 ptype = get_bits(&gb, 8);
2456 if (!(ptype & 0x80)) {
2457 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2461 // FIXME: Check for this as well.
2462 skip_bits_long(&gb, 6 * 8); /* "theora" */
2466 if (theora_decode_header(avctx, &gb) < 0)
2470 // FIXME: is this needed? it breaks sometimes
2471 // theora_decode_comments(avctx, gb);
2474 if (theora_decode_tables(avctx, &gb))
2478 av_log(avctx, AV_LOG_ERROR,
2479 "Unknown Theora config packet: %d\n", ptype & ~0x80);
2482 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
2483 av_log(avctx, AV_LOG_WARNING,
2484 "%d bits left in packet %X\n",
2485 8 * header_len[i] - get_bits_count(&gb), ptype);
2486 if (s->theora < 0x030200)
2490 return vp3_decode_init(avctx);
2493 AVCodec ff_theora_decoder = {
2495 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2496 .type = AVMEDIA_TYPE_VIDEO,
2497 .id = AV_CODEC_ID_THEORA,
2498 .priv_data_size = sizeof(Vp3DecodeContext),
2499 .init = theora_decode_init,
2500 .close = vp3_decode_end,
2501 .decode = vp3_decode_frame,
2502 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2503 CODEC_CAP_FRAME_THREADS,
2504 .flush = vp3_decode_flush,
2505 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2506 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
2510 AVCodec ff_vp3_decoder = {
2512 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2513 .type = AVMEDIA_TYPE_VIDEO,
2514 .id = AV_CODEC_ID_VP3,
2515 .priv_data_size = sizeof(Vp3DecodeContext),
2516 .init = vp3_decode_init,
2517 .close = vp3_decode_end,
2518 .decode = vp3_decode_frame,
2519 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2520 CODEC_CAP_FRAME_THREADS,
2521 .flush = vp3_decode_flush,
2522 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2523 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),