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"
48 #define FRAGMENT_PIXELS 8
50 //FIXME split things out into their own arrays
51 typedef struct Vp3Fragment {
53 uint8_t coding_method;
57 #define SB_NOT_CODED 0
58 #define SB_PARTIALLY_CODED 1
59 #define SB_FULLY_CODED 2
61 // This is the maximum length of a single long bit run that can be encoded
62 // for superblock coding or block qps. Theora special-cases this to read a
63 // bit instead of flipping the current bit to allow for runs longer than 4129.
64 #define MAXIMUM_LONG_BIT_RUN 4129
66 #define MODE_INTER_NO_MV 0
68 #define MODE_INTER_PLUS_MV 2
69 #define MODE_INTER_LAST_MV 3
70 #define MODE_INTER_PRIOR_LAST 4
71 #define MODE_USING_GOLDEN 5
72 #define MODE_GOLDEN_MV 6
73 #define MODE_INTER_FOURMV 7
74 #define CODING_MODE_COUNT 8
76 /* special internal mode */
79 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
80 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
83 /* There are 6 preset schemes, plus a free-form scheme */
84 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 },
124 static const uint8_t hilbert_offset[16][2] = {
125 {0,0}, {1,0}, {1,1}, {0,1},
126 {0,2}, {0,3}, {1,3}, {1,2},
127 {2,2}, {2,3}, {3,3}, {3,2},
128 {3,1}, {2,1}, {2,0}, {3,0}
131 #define MIN_DEQUANT_VAL 2
133 typedef struct Vp3DecodeContext {
134 AVCodecContext *avctx;
135 int theora, theora_tables;
138 int chroma_x_shift, chroma_y_shift;
139 ThreadFrame golden_frame;
140 ThreadFrame last_frame;
141 ThreadFrame current_frame;
143 uint8_t idct_permutation[64];
144 uint8_t idct_scantable[64];
146 VideoDSPContext vdsp;
147 VP3DSPContext vp3dsp;
148 DECLARE_ALIGNED(16, int16_t, block)[64];
151 int skip_loop_filter;
157 int superblock_count;
158 int y_superblock_width;
159 int y_superblock_height;
160 int y_superblock_count;
161 int c_superblock_width;
162 int c_superblock_height;
163 int c_superblock_count;
164 int u_superblock_start;
165 int v_superblock_start;
166 unsigned char *superblock_coding;
168 int macroblock_count;
169 int macroblock_width;
170 int macroblock_height;
173 int fragment_width[2];
174 int fragment_height[2];
176 Vp3Fragment *all_fragments;
177 int fragment_start[3];
180 int8_t (*motion_val[2])[2];
183 uint16_t coded_dc_scale_factor[64];
184 uint32_t coded_ac_scale_factor[64];
185 uint8_t base_matrix[384][64];
186 uint8_t qr_count[2][3];
187 uint8_t qr_size [2][3][64];
188 uint16_t qr_base[2][3][64];
191 * This is a list of all tokens in bitstream order. Reordering takes place
192 * by pulling from each level during IDCT. As a consequence, IDCT must be
193 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
194 * otherwise. The 32 different tokens with up to 12 bits of extradata are
195 * collapsed into 3 types, packed as follows:
196 * (from the low to high bits)
198 * 2 bits: type (0,1,2)
199 * 0: EOB run, 14 bits for run length (12 needed)
200 * 1: zero run, 7 bits for run length
201 * 7 bits for the next coefficient (3 needed)
202 * 2: coefficient, 14 bits (11 needed)
204 * Coefficients are signed, so are packed in the highest bits for automatic
207 int16_t *dct_tokens[3][64];
208 int16_t *dct_tokens_base;
209 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
210 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) << 9) + ((zero_run) << 2) + 1)
211 #define TOKEN_COEFF(coeff) (((coeff) << 2) + 2)
214 * number of blocks that contain DCT coefficients at 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);
321 * This function sets up all of the various blocks mappings:
322 * superblocks <-> fragments, macroblocks <-> fragments,
323 * superblocks <-> macroblocks
325 * @return 0 is successful; returns 1 if *anything* went wrong.
327 static int init_block_mapping(Vp3DecodeContext *s)
329 int sb_x, sb_y, plane;
332 for (plane = 0; plane < 3; plane++) {
333 int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
334 int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
335 int frag_width = s->fragment_width[!!plane];
336 int frag_height = s->fragment_height[!!plane];
338 for (sb_y = 0; sb_y < sb_height; sb_y++)
339 for (sb_x = 0; sb_x < sb_width; sb_x++)
340 for (i = 0; i < 16; i++) {
341 x = 4*sb_x + hilbert_offset[i][0];
342 y = 4*sb_y + hilbert_offset[i][1];
344 if (x < frag_width && y < frag_height)
345 s->superblock_fragments[j++] = s->fragment_start[plane] + y*frag_width + x;
347 s->superblock_fragments[j++] = -1;
351 return 0; /* successful path out */
355 * This function sets up the dequantization tables used for a particular
358 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
360 int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
361 int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
362 int i, plane, inter, qri, bmi, bmj, qistart;
364 for(inter=0; inter<2; inter++){
365 for(plane=0; plane<3; plane++){
367 for(qri=0; qri<s->qr_count[inter][plane]; qri++){
368 sum+= s->qr_size[inter][plane][qri];
369 if(s->qps[qpi] <= sum)
372 qistart= sum - s->qr_size[inter][plane][qri];
373 bmi= s->qr_base[inter][plane][qri ];
374 bmj= s->qr_base[inter][plane][qri+1];
376 int coeff= ( 2*(sum -s->qps[qpi])*s->base_matrix[bmi][i]
377 - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
378 + s->qr_size[inter][plane][qri])
379 / (2*s->qr_size[inter][plane][qri]);
381 int qmin= 8<<(inter + !i);
382 int qscale= i ? ac_scale_factor : dc_scale_factor;
384 s->qmat[qpi][inter][plane][s->idct_permutation[i]]= av_clip((qscale * coeff)/100 * 4, qmin, 4096);
386 // all DC coefficients use the same quant so as not to interfere with DC prediction
387 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
393 * This function initializes the loop filter boundary limits if the frame's
394 * quality index is different from the previous frame's.
396 * The filter_limit_values may not be larger than 127.
398 static void init_loop_filter(Vp3DecodeContext *s)
400 int *bounding_values= s->bounding_values_array+127;
405 filter_limit = s->filter_limit_values[s->qps[0]];
406 av_assert0(filter_limit < 128U);
408 /* set up the bounding values */
409 memset(s->bounding_values_array, 0, 256 * sizeof(int));
410 for (x = 0; x < filter_limit; x++) {
411 bounding_values[-x] = -x;
412 bounding_values[x] = x;
414 for (x = value = filter_limit; x < 128 && value; x++, value--) {
415 bounding_values[ x] = value;
416 bounding_values[-x] = -value;
419 bounding_values[128] = value;
420 bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
424 * This function unpacks all of the superblock/macroblock/fragment coding
425 * information from the bitstream.
427 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
429 int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };
431 int current_superblock = 0;
433 int num_partial_superblocks = 0;
436 int current_fragment;
440 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
444 /* unpack the list of partially-coded superblocks */
445 bit = get_bits1(gb) ^ 1;
448 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
449 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
454 current_run = get_vlc2(gb,
455 s->superblock_run_length_vlc.table, 6, 2) + 1;
456 if (current_run == 34)
457 current_run += get_bits(gb, 12);
459 if (current_superblock + current_run > s->superblock_count) {
460 av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");
464 memset(s->superblock_coding + current_superblock, bit, current_run);
466 current_superblock += current_run;
468 num_partial_superblocks += current_run;
471 /* unpack the list of fully coded superblocks if any of the blocks were
472 * not marked as partially coded in the previous step */
473 if (num_partial_superblocks < s->superblock_count) {
474 int superblocks_decoded = 0;
476 current_superblock = 0;
477 bit = get_bits1(gb) ^ 1;
480 while (superblocks_decoded < s->superblock_count - num_partial_superblocks
481 && get_bits_left(gb) > 0) {
483 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
488 current_run = get_vlc2(gb,
489 s->superblock_run_length_vlc.table, 6, 2) + 1;
490 if (current_run == 34)
491 current_run += get_bits(gb, 12);
493 for (j = 0; j < current_run; current_superblock++) {
494 if (current_superblock >= s->superblock_count) {
495 av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");
499 /* skip any superblocks already marked as partially coded */
500 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
501 s->superblock_coding[current_superblock] = 2*bit;
505 superblocks_decoded += current_run;
509 /* if there were partial blocks, initialize bitstream for
510 * unpacking fragment codings */
511 if (num_partial_superblocks) {
515 /* toggle the bit because as soon as the first run length is
516 * fetched the bit will be toggled again */
521 /* figure out which fragments are coded; iterate through each
522 * superblock (all planes) */
523 s->total_num_coded_frags = 0;
524 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
526 for (plane = 0; plane < 3; plane++) {
527 int sb_start = superblock_starts[plane];
528 int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
529 int num_coded_frags = 0;
531 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
533 /* iterate through all 16 fragments in a superblock */
534 for (j = 0; j < 16; j++) {
536 /* if the fragment is in bounds, check its coding status */
537 current_fragment = s->superblock_fragments[i * 16 + j];
538 if (current_fragment != -1) {
539 int coded = s->superblock_coding[i];
541 if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
543 /* fragment may or may not be coded; this is the case
544 * that cares about the fragment coding runs */
545 if (current_run-- == 0) {
547 current_run = get_vlc2(gb,
548 s->fragment_run_length_vlc.table, 5, 2);
554 /* default mode; actual mode will be decoded in
556 s->all_fragments[current_fragment].coding_method =
558 s->coded_fragment_list[plane][num_coded_frags++] =
561 /* not coded; copy this fragment from the prior frame */
562 s->all_fragments[current_fragment].coding_method =
568 s->total_num_coded_frags += num_coded_frags;
569 for (i = 0; i < 64; i++)
570 s->num_coded_frags[plane][i] = num_coded_frags;
572 s->coded_fragment_list[plane+1] = s->coded_fragment_list[plane] + num_coded_frags;
578 * This function unpacks all the coding mode data for individual macroblocks
579 * from the bitstream.
581 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
583 int i, j, k, sb_x, sb_y;
585 int current_macroblock;
586 int current_fragment;
588 int custom_mode_alphabet[CODING_MODE_COUNT];
593 for (i = 0; i < s->fragment_count; i++)
594 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 || mb_y >= s->macroblock_height)
626 #define BLOCK_X (2*mb_x + (k&1))
627 #define BLOCK_Y (2*mb_y + (k>>1))
628 /* coding modes are only stored if the macroblock has at least one
629 * luma block coded, otherwise it must be INTER_NO_MV */
630 for (k = 0; k < 4; k++) {
631 current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
632 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
636 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
640 /* mode 7 means get 3 bits for each coding mode */
642 coding_mode = get_bits(gb, 3);
644 coding_mode = alphabet
645 [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
647 s->macroblock_coding[current_macroblock] = coding_mode;
648 for (k = 0; k < 4; k++) {
649 frag = s->all_fragments + BLOCK_Y*s->fragment_width[0] + BLOCK_X;
650 if (frag->coding_method != MODE_COPY)
651 frag->coding_method = coding_mode;
654 #define SET_CHROMA_MODES \
655 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
656 frag[s->fragment_start[1]].coding_method = coding_mode;\
657 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
658 frag[s->fragment_start[2]].coding_method = coding_mode;
660 if (s->chroma_y_shift) {
661 frag = s->all_fragments + mb_y*s->fragment_width[1] + mb_x;
663 } else if (s->chroma_x_shift) {
664 frag = s->all_fragments + 2*mb_y*s->fragment_width[1] + mb_x;
665 for (k = 0; k < 2; k++) {
667 frag += s->fragment_width[1];
670 for (k = 0; k < 4; k++) {
671 frag = s->all_fragments + BLOCK_Y*s->fragment_width[1] + BLOCK_X;
684 * This function unpacks all the motion vectors for the individual
685 * macroblocks from the bitstream.
687 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
689 int j, k, sb_x, sb_y;
693 int last_motion_x = 0;
694 int last_motion_y = 0;
695 int prior_last_motion_x = 0;
696 int prior_last_motion_y = 0;
697 int current_macroblock;
698 int current_fragment;
704 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
705 coding_mode = get_bits1(gb);
707 /* iterate through all of the macroblocks that contain 1 or more
709 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
710 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
711 if (get_bits_left(gb) <= 0)
714 for (j = 0; j < 4; j++) {
715 int mb_x = 2*sb_x + (j>>1);
716 int mb_y = 2*sb_y + (((j>>1)+j)&1);
717 current_macroblock = mb_y * s->macroblock_width + mb_x;
719 if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
720 (s->macroblock_coding[current_macroblock] == MODE_COPY))
723 switch (s->macroblock_coding[current_macroblock]) {
725 case MODE_INTER_PLUS_MV:
727 /* all 6 fragments use the same motion vector */
728 if (coding_mode == 0) {
729 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
730 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
732 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
733 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
736 /* vector maintenance, only on MODE_INTER_PLUS_MV */
737 if (s->macroblock_coding[current_macroblock] ==
738 MODE_INTER_PLUS_MV) {
739 prior_last_motion_x = last_motion_x;
740 prior_last_motion_y = last_motion_y;
741 last_motion_x = motion_x[0];
742 last_motion_y = motion_y[0];
746 case MODE_INTER_FOURMV:
747 /* vector maintenance */
748 prior_last_motion_x = last_motion_x;
749 prior_last_motion_y = last_motion_y;
751 /* fetch 4 vectors from the bitstream, one for each
752 * Y fragment, then average for the C fragment vectors */
753 for (k = 0; k < 4; k++) {
754 current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
755 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
756 if (coding_mode == 0) {
757 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
758 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
760 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
761 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
763 last_motion_x = motion_x[k];
764 last_motion_y = motion_y[k];
772 case MODE_INTER_LAST_MV:
773 /* all 6 fragments use the last motion vector */
774 motion_x[0] = last_motion_x;
775 motion_y[0] = last_motion_y;
777 /* no vector maintenance (last vector remains the
781 case MODE_INTER_PRIOR_LAST:
782 /* all 6 fragments use the motion vector prior to the
783 * last motion vector */
784 motion_x[0] = prior_last_motion_x;
785 motion_y[0] = prior_last_motion_y;
787 /* vector maintenance */
788 prior_last_motion_x = last_motion_x;
789 prior_last_motion_y = last_motion_y;
790 last_motion_x = motion_x[0];
791 last_motion_y = motion_y[0];
795 /* covers intra, inter without MV, golden without MV */
799 /* no vector maintenance */
803 /* assign the motion vectors to the correct fragments */
804 for (k = 0; k < 4; k++) {
806 BLOCK_Y*s->fragment_width[0] + BLOCK_X;
807 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
808 s->motion_val[0][current_fragment][0] = motion_x[k];
809 s->motion_val[0][current_fragment][1] = motion_y[k];
811 s->motion_val[0][current_fragment][0] = motion_x[0];
812 s->motion_val[0][current_fragment][1] = motion_y[0];
816 if (s->chroma_y_shift) {
817 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
818 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] + motion_x[2] + motion_x[3], 2);
819 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] + motion_y[2] + motion_y[3], 2);
821 motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
822 motion_y[0] = (motion_y[0]>>1) | (motion_y[0]&1);
823 frag = mb_y*s->fragment_width[1] + mb_x;
824 s->motion_val[1][frag][0] = motion_x[0];
825 s->motion_val[1][frag][1] = motion_y[0];
826 } else if (s->chroma_x_shift) {
827 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
828 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
829 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
830 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
831 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
833 motion_x[1] = motion_x[0];
834 motion_y[1] = motion_y[0];
836 motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
837 motion_x[1] = (motion_x[1]>>1) | (motion_x[1]&1);
839 frag = 2*mb_y*s->fragment_width[1] + mb_x;
840 for (k = 0; k < 2; k++) {
841 s->motion_val[1][frag][0] = motion_x[k];
842 s->motion_val[1][frag][1] = motion_y[k];
843 frag += s->fragment_width[1];
846 for (k = 0; k < 4; k++) {
847 frag = BLOCK_Y*s->fragment_width[1] + BLOCK_X;
848 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
849 s->motion_val[1][frag][0] = motion_x[k];
850 s->motion_val[1][frag][1] = motion_y[k];
852 s->motion_val[1][frag][0] = motion_x[0];
853 s->motion_val[1][frag][1] = motion_y[0];
864 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
866 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
867 int num_blocks = s->total_num_coded_frags;
869 for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
870 i = blocks_decoded = num_blocks_at_qpi = 0;
872 bit = get_bits1(gb) ^ 1;
876 if (run_length == MAXIMUM_LONG_BIT_RUN)
881 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
882 if (run_length == 34)
883 run_length += get_bits(gb, 12);
884 blocks_decoded += run_length;
887 num_blocks_at_qpi += run_length;
889 for (j = 0; j < run_length; i++) {
890 if (i >= s->total_num_coded_frags)
893 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
894 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
898 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
900 num_blocks -= num_blocks_at_qpi;
907 * This function is called by unpack_dct_coeffs() to extract the VLCs from
908 * the bitstream. The VLCs encode tokens which are used to unpack DCT
909 * data. This function unpacks all the VLCs for either the Y plane or both
910 * C planes, and is called for DC coefficients or different AC coefficient
911 * levels (since different coefficient types require different VLC tables.
913 * This function returns a residual eob run. E.g, if a particular token gave
914 * instructions to EOB the next 5 fragments and there were only 2 fragments
915 * left in the current fragment range, 3 would be returned so that it could
916 * be passed into the next call to this same function.
918 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
919 VLC *table, int coeff_index,
930 int num_coeffs = s->num_coded_frags[plane][coeff_index];
931 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
933 /* local references to structure members to avoid repeated deferences */
934 int *coded_fragment_list = s->coded_fragment_list[plane];
935 Vp3Fragment *all_fragments = s->all_fragments;
936 VLC_TYPE (*vlc_table)[2] = table->table;
939 av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
941 if (eob_run > num_coeffs) {
942 coeff_i = blocks_ended = num_coeffs;
943 eob_run -= num_coeffs;
945 coeff_i = blocks_ended = eob_run;
949 // insert fake EOB token to cover the split between planes or zzi
951 dct_tokens[j++] = blocks_ended << 2;
953 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
954 /* decode a VLC into a token */
955 token = get_vlc2(gb, vlc_table, 11, 3);
956 /* use the token to get a zero run, a coefficient, and an eob run */
957 if ((unsigned) token <= 6U) {
958 eob_run = eob_run_base[token];
959 if (eob_run_get_bits[token])
960 eob_run += get_bits(gb, eob_run_get_bits[token]);
962 // record only the number of blocks ended in this plane,
963 // any spill will be recorded in the next plane.
964 if (eob_run > num_coeffs - coeff_i) {
965 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
966 blocks_ended += num_coeffs - coeff_i;
967 eob_run -= num_coeffs - coeff_i;
968 coeff_i = num_coeffs;
970 dct_tokens[j++] = TOKEN_EOB(eob_run);
971 blocks_ended += eob_run;
975 } else if (token >= 0) {
976 bits_to_get = coeff_get_bits[token];
978 bits_to_get = get_bits(gb, bits_to_get);
979 coeff = coeff_tables[token][bits_to_get];
981 zero_run = zero_run_base[token];
982 if (zero_run_get_bits[token])
983 zero_run += get_bits(gb, zero_run_get_bits[token]);
986 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
988 // Save DC into the fragment structure. DC prediction is
989 // done in raster order, so the actual DC can't be in with
990 // other tokens. We still need the token in dct_tokens[]
991 // however, or else the structure collapses on itself.
993 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
995 dct_tokens[j++] = TOKEN_COEFF(coeff);
998 if (coeff_index + zero_run > 64) {
999 av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
1000 " %d coeffs left\n", zero_run, 64-coeff_index);
1001 zero_run = 64 - coeff_index;
1004 // zero runs code multiple coefficients,
1005 // so don't try to decode coeffs for those higher levels
1006 for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
1007 s->num_coded_frags[plane][i]--;
1010 av_log(s->avctx, AV_LOG_ERROR,
1011 "Invalid token %d\n", token);
1016 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1017 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1019 // decrement the number of blocks that have higher coeffecients for each
1020 // EOB run at this level
1022 for (i = coeff_index+1; i < 64; i++)
1023 s->num_coded_frags[plane][i] -= blocks_ended;
1025 // setup the next buffer
1027 s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
1028 else if (coeff_index < 63)
1029 s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
1034 static void reverse_dc_prediction(Vp3DecodeContext *s,
1037 int fragment_height);
1039 * This function unpacks all of the DCT coefficient data from the
1042 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1049 int residual_eob_run = 0;
1053 s->dct_tokens[0][0] = s->dct_tokens_base;
1055 /* fetch the DC table indexes */
1056 dc_y_table = get_bits(gb, 4);
1057 dc_c_table = get_bits(gb, 4);
1059 /* unpack the Y plane DC coefficients */
1060 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1061 0, residual_eob_run);
1062 if (residual_eob_run < 0)
1063 return residual_eob_run;
1065 /* reverse prediction of the Y-plane DC coefficients */
1066 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1068 /* unpack the C plane DC coefficients */
1069 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1070 1, residual_eob_run);
1071 if (residual_eob_run < 0)
1072 return residual_eob_run;
1073 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1074 2, residual_eob_run);
1075 if (residual_eob_run < 0)
1076 return residual_eob_run;
1078 /* reverse prediction of the C-plane DC coefficients */
1079 if (!(s->avctx->flags & CODEC_FLAG_GRAY))
1081 reverse_dc_prediction(s, s->fragment_start[1],
1082 s->fragment_width[1], s->fragment_height[1]);
1083 reverse_dc_prediction(s, s->fragment_start[2],
1084 s->fragment_width[1], s->fragment_height[1]);
1087 /* fetch the AC table indexes */
1088 ac_y_table = get_bits(gb, 4);
1089 ac_c_table = get_bits(gb, 4);
1091 /* build tables of AC VLC tables */
1092 for (i = 1; i <= 5; i++) {
1093 y_tables[i] = &s->ac_vlc_1[ac_y_table];
1094 c_tables[i] = &s->ac_vlc_1[ac_c_table];
1096 for (i = 6; i <= 14; i++) {
1097 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1098 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1100 for (i = 15; i <= 27; i++) {
1101 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1102 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1104 for (i = 28; i <= 63; i++) {
1105 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1106 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1109 /* decode all AC coefficents */
1110 for (i = 1; i <= 63; i++) {
1111 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1112 0, residual_eob_run);
1113 if (residual_eob_run < 0)
1114 return residual_eob_run;
1116 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1117 1, residual_eob_run);
1118 if (residual_eob_run < 0)
1119 return residual_eob_run;
1120 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1121 2, residual_eob_run);
1122 if (residual_eob_run < 0)
1123 return residual_eob_run;
1130 * This function reverses the DC prediction for each coded fragment in
1131 * the frame. Much of this function is adapted directly from the original
1134 #define COMPATIBLE_FRAME(x) \
1135 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1136 #define DC_COEFF(u) s->all_fragments[u].dc
1138 static void reverse_dc_prediction(Vp3DecodeContext *s,
1141 int fragment_height)
1150 int i = first_fragment;
1154 /* DC values for the left, up-left, up, and up-right fragments */
1155 int vl, vul, vu, vur;
1157 /* indexes for the left, up-left, up, and up-right fragments */
1161 * The 6 fields mean:
1162 * 0: up-left multiplier
1164 * 2: up-right multiplier
1165 * 3: left multiplier
1167 static const int predictor_transform[16][4] = {
1169 { 0, 0, 0,128}, // PL
1170 { 0, 0,128, 0}, // PUR
1171 { 0, 0, 53, 75}, // PUR|PL
1172 { 0,128, 0, 0}, // PU
1173 { 0, 64, 0, 64}, // PU|PL
1174 { 0,128, 0, 0}, // PU|PUR
1175 { 0, 0, 53, 75}, // PU|PUR|PL
1176 {128, 0, 0, 0}, // PUL
1177 { 0, 0, 0,128}, // PUL|PL
1178 { 64, 0, 64, 0}, // PUL|PUR
1179 { 0, 0, 53, 75}, // PUL|PUR|PL
1180 { 0,128, 0, 0}, // PUL|PU
1181 {-104,116, 0,116}, // PUL|PU|PL
1182 { 24, 80, 24, 0}, // PUL|PU|PUR
1183 {-104,116, 0,116} // PUL|PU|PUR|PL
1186 /* This table shows which types of blocks can use other blocks for
1187 * prediction. For example, INTRA is the only mode in this table to
1188 * have a frame number of 0. That means INTRA blocks can only predict
1189 * from other INTRA blocks. There are 2 golden frame coding types;
1190 * blocks encoding in these modes can only predict from other blocks
1191 * that were encoded with these 1 of these 2 modes. */
1192 static const unsigned char compatible_frame[9] = {
1193 1, /* MODE_INTER_NO_MV */
1195 1, /* MODE_INTER_PLUS_MV */
1196 1, /* MODE_INTER_LAST_MV */
1197 1, /* MODE_INTER_PRIOR_MV */
1198 2, /* MODE_USING_GOLDEN */
1199 2, /* MODE_GOLDEN_MV */
1200 1, /* MODE_INTER_FOUR_MV */
1203 int current_frame_type;
1205 /* there is a last DC predictor for each of the 3 frame types */
1210 vul = vu = vur = vl = 0;
1211 last_dc[0] = last_dc[1] = last_dc[2] = 0;
1213 /* for each fragment row... */
1214 for (y = 0; y < fragment_height; y++) {
1216 /* for each fragment in a row... */
1217 for (x = 0; x < fragment_width; x++, i++) {
1219 /* reverse prediction if this block was coded */
1220 if (s->all_fragments[i].coding_method != MODE_COPY) {
1222 current_frame_type =
1223 compatible_frame[s->all_fragments[i].coding_method];
1229 if(COMPATIBLE_FRAME(l))
1233 u= i-fragment_width;
1235 if(COMPATIBLE_FRAME(u))
1238 ul= i-fragment_width-1;
1240 if(COMPATIBLE_FRAME(ul))
1243 if(x + 1 < fragment_width){
1244 ur= i-fragment_width+1;
1246 if(COMPATIBLE_FRAME(ur))
1251 if (transform == 0) {
1253 /* if there were no fragments to predict from, use last
1255 predicted_dc = last_dc[current_frame_type];
1258 /* apply the appropriate predictor transform */
1260 (predictor_transform[transform][0] * vul) +
1261 (predictor_transform[transform][1] * vu) +
1262 (predictor_transform[transform][2] * vur) +
1263 (predictor_transform[transform][3] * vl);
1265 predicted_dc /= 128;
1267 /* check for outranging on the [ul u l] and
1268 * [ul u ur l] predictors */
1269 if ((transform == 15) || (transform == 13)) {
1270 if (FFABS(predicted_dc - vu) > 128)
1272 else if (FFABS(predicted_dc - vl) > 128)
1274 else if (FFABS(predicted_dc - vul) > 128)
1279 /* at long last, apply the predictor */
1280 DC_COEFF(i) += predicted_dc;
1282 last_dc[current_frame_type] = DC_COEFF(i);
1288 static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1291 int *bounding_values= s->bounding_values_array+127;
1293 int width = s->fragment_width[!!plane];
1294 int height = s->fragment_height[!!plane];
1295 int fragment = s->fragment_start [plane] + ystart * width;
1296 int stride = s->current_frame.f->linesize[plane];
1297 uint8_t *plane_data = s->current_frame.f->data [plane];
1298 if (!s->flipped_image) stride = -stride;
1299 plane_data += s->data_offset[plane] + 8*ystart*stride;
1301 for (y = ystart; y < yend; y++) {
1303 for (x = 0; x < width; x++) {
1304 /* This code basically just deblocks on the edges of coded blocks.
1305 * However, it has to be much more complicated because of the
1306 * braindamaged deblock ordering used in VP3/Theora. Order matters
1307 * because some pixels get filtered twice. */
1308 if( s->all_fragments[fragment].coding_method != MODE_COPY )
1310 /* do not perform left edge filter for left columns frags */
1312 s->vp3dsp.h_loop_filter(
1314 stride, bounding_values);
1317 /* do not perform top edge filter for top row fragments */
1319 s->vp3dsp.v_loop_filter(
1321 stride, bounding_values);
1324 /* do not perform right edge filter for right column
1325 * fragments or if right fragment neighbor is also coded
1326 * in this frame (it will be filtered in next iteration) */
1327 if ((x < width - 1) &&
1328 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1329 s->vp3dsp.h_loop_filter(
1330 plane_data + 8*x + 8,
1331 stride, bounding_values);
1334 /* do not perform bottom edge filter for bottom row
1335 * fragments or if bottom fragment neighbor is also coded
1336 * in this frame (it will be filtered in the next row) */
1337 if ((y < height - 1) &&
1338 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1339 s->vp3dsp.v_loop_filter(
1340 plane_data + 8*x + 8*stride,
1341 stride, bounding_values);
1347 plane_data += 8*stride;
1352 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1353 * for the next block in coding order
1355 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1356 int plane, int inter, int16_t block[64])
1358 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1359 uint8_t *perm = s->idct_scantable;
1363 int token = *s->dct_tokens[plane][i];
1364 switch (token & 3) {
1366 if (--token < 4) // 0-3 are token types, so the EOB run must now be 0
1367 s->dct_tokens[plane][i]++;
1369 *s->dct_tokens[plane][i] = token & ~3;
1372 s->dct_tokens[plane][i]++;
1373 i += (token >> 2) & 0x7f;
1375 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1378 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1382 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1383 s->dct_tokens[plane][i++]++;
1385 default: // shouldn't happen
1389 // return value is expected to be a valid level
1392 // the actual DC+prediction is in the fragment structure
1393 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1398 * called when all pixels up to row y are complete
1400 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1403 int offset[AV_NUM_DATA_POINTERS];
1405 if (HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
1406 int y_flipped = s->flipped_image ? s->avctx->height-y : y;
1408 // At the end of the frame, report INT_MAX instead of the height of the frame.
1409 // This makes the other threads' ff_thread_await_progress() calls cheaper, because
1410 // they don't have to clip their values.
1411 ff_thread_report_progress(&s->current_frame, y_flipped==s->avctx->height ? INT_MAX : y_flipped-1, 0);
1414 if(s->avctx->draw_horiz_band==NULL)
1417 h= y - s->last_slice_end;
1418 s->last_slice_end= y;
1421 if (!s->flipped_image) {
1422 y = s->avctx->height - y - h;
1425 cy = y >> s->chroma_y_shift;
1426 offset[0] = s->current_frame.f->linesize[0]*y;
1427 offset[1] = s->current_frame.f->linesize[1]*cy;
1428 offset[2] = s->current_frame.f->linesize[2]*cy;
1429 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1433 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1437 * Wait for the reference frame of the current fragment.
1438 * The progress value is in luma pixel rows.
1440 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment, int motion_y, int y)
1442 ThreadFrame *ref_frame;
1444 int border = motion_y&1;
1446 if (fragment->coding_method == MODE_USING_GOLDEN ||
1447 fragment->coding_method == MODE_GOLDEN_MV)
1448 ref_frame = &s->golden_frame;
1450 ref_frame = &s->last_frame;
1452 ref_row = y + (motion_y>>1);
1453 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1455 ff_thread_await_progress(ref_frame, ref_row, 0);
1459 * Perform the final rendering for a particular slice of data.
1460 * The slice number ranges from 0..(c_superblock_height - 1).
1462 static void render_slice(Vp3DecodeContext *s, int slice)
1464 int x, y, i, j, fragment;
1465 int16_t *block = s->block;
1466 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1467 int motion_halfpel_index;
1468 uint8_t *motion_source;
1469 int plane, first_pixel;
1471 if (slice >= s->c_superblock_height)
1474 for (plane = 0; plane < 3; plane++) {
1475 uint8_t *output_plane = s->current_frame.f->data [plane] + s->data_offset[plane];
1476 uint8_t * last_plane = s-> last_frame.f->data [plane] + s->data_offset[plane];
1477 uint8_t *golden_plane = s-> golden_frame.f->data [plane] + s->data_offset[plane];
1478 int stride = s->current_frame.f->linesize[plane];
1479 int plane_width = s->width >> (plane && s->chroma_x_shift);
1480 int plane_height = s->height >> (plane && s->chroma_y_shift);
1481 int8_t (*motion_val)[2] = s->motion_val[!!plane];
1483 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
1484 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
1485 int slice_width = plane ? s->c_superblock_width : s->y_superblock_width;
1487 int fragment_width = s->fragment_width[!!plane];
1488 int fragment_height = s->fragment_height[!!plane];
1489 int fragment_start = s->fragment_start[plane];
1490 int do_await = !plane && HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_FRAME);
1492 if (!s->flipped_image) stride = -stride;
1493 if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1496 /* for each superblock row in the slice (both of them)... */
1497 for (; sb_y < slice_height; sb_y++) {
1499 /* for each superblock in a row... */
1500 for (sb_x = 0; sb_x < slice_width; sb_x++) {
1502 /* for each block in a superblock... */
1503 for (j = 0; j < 16; j++) {
1504 x = 4*sb_x + hilbert_offset[j][0];
1505 y = 4*sb_y + hilbert_offset[j][1];
1506 fragment = y*fragment_width + x;
1508 i = fragment_start + fragment;
1511 if (x >= fragment_width || y >= fragment_height)
1514 first_pixel = 8*y*stride + 8*x;
1516 if (do_await && s->all_fragments[i].coding_method != MODE_INTRA)
1517 await_reference_row(s, &s->all_fragments[i], motion_val[fragment][1], (16*y) >> s->chroma_y_shift);
1519 /* transform if this block was coded */
1520 if (s->all_fragments[i].coding_method != MODE_COPY) {
1521 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1522 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1523 motion_source= golden_plane;
1525 motion_source= last_plane;
1527 motion_source += first_pixel;
1528 motion_halfpel_index = 0;
1530 /* sort out the motion vector if this fragment is coded
1531 * using a motion vector method */
1532 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1533 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1535 motion_x = motion_val[fragment][0];
1536 motion_y = motion_val[fragment][1];
1538 src_x= (motion_x>>1) + 8*x;
1539 src_y= (motion_y>>1) + 8*y;
1541 motion_halfpel_index = motion_x & 0x01;
1542 motion_source += (motion_x >> 1);
1544 motion_halfpel_index |= (motion_y & 0x01) << 1;
1545 motion_source += ((motion_y >> 1) * stride);
1547 if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1548 uint8_t *temp= s->edge_emu_buffer;
1549 if(stride<0) temp -= 8*stride;
1551 s->vdsp.emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
1552 motion_source= temp;
1557 /* first, take care of copying a block from either the
1558 * previous or the golden frame */
1559 if (s->all_fragments[i].coding_method != MODE_INTRA) {
1560 /* Note, it is possible to implement all MC cases with
1561 put_no_rnd_pixels_l2 which would look more like the
1562 VP3 source but this would be slower as
1563 put_no_rnd_pixels_tab is better optimzed */
1564 if(motion_halfpel_index != 3){
1565 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1566 output_plane + first_pixel,
1567 motion_source, stride, 8);
1569 int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1570 s->vp3dsp.put_no_rnd_pixels_l2(
1571 output_plane + first_pixel,
1573 motion_source + stride + 1 + d,
1578 /* invert DCT and place (or add) in final output */
1580 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1581 vp3_dequant(s, s->all_fragments + i, plane, 0, block);
1583 output_plane + first_pixel,
1587 if (vp3_dequant(s, s->all_fragments + i, plane, 1, block)) {
1589 output_plane + first_pixel,
1593 s->vp3dsp.idct_dc_add(output_plane + first_pixel, stride, block);
1598 /* copy directly from the previous frame */
1599 s->hdsp.put_pixels_tab[1][0](
1600 output_plane + first_pixel,
1601 last_plane + first_pixel,
1608 // Filter up to the last row in the superblock row
1609 if (!s->skip_loop_filter)
1610 apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
1614 /* this looks like a good place for slice dispatch... */
1616 * if (slice == s->macroblock_height - 1)
1617 * dispatch (both last slice & 2nd-to-last slice);
1618 * else if (slice > 0)
1619 * dispatch (slice - 1);
1622 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) -16, s->height-16));
1625 /// Allocate tables for per-frame data in Vp3DecodeContext
1626 static av_cold int allocate_tables(AVCodecContext *avctx)
1628 Vp3DecodeContext *s = avctx->priv_data;
1629 int y_fragment_count, c_fragment_count;
1631 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1632 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1634 s->superblock_coding = av_malloc(s->superblock_count);
1635 s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
1636 s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
1637 s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
1638 s->motion_val[0] = av_malloc(y_fragment_count * sizeof(*s->motion_val[0]));
1639 s->motion_val[1] = av_malloc(c_fragment_count * sizeof(*s->motion_val[1]));
1641 /* work out the block mapping tables */
1642 s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
1643 s->macroblock_coding = av_malloc(s->macroblock_count + 1);
1645 if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
1646 !s->coded_fragment_list[0] || !s->superblock_fragments || !s->macroblock_coding ||
1647 !s->motion_val[0] || !s->motion_val[1]) {
1648 vp3_decode_end(avctx);
1652 init_block_mapping(s);
1657 static av_cold int init_frames(Vp3DecodeContext *s)
1659 s->current_frame.f = av_frame_alloc();
1660 s->last_frame.f = av_frame_alloc();
1661 s->golden_frame.f = av_frame_alloc();
1663 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
1664 av_frame_free(&s->current_frame.f);
1665 av_frame_free(&s->last_frame.f);
1666 av_frame_free(&s->golden_frame.f);
1667 return AVERROR(ENOMEM);
1673 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1675 Vp3DecodeContext *s = avctx->priv_data;
1676 int i, inter, plane, ret;
1679 int y_fragment_count, c_fragment_count;
1681 ret = init_frames(s);
1685 avctx->internal->allocate_progress = 1;
1687 if (avctx->codec_tag == MKTAG('V','P','3','0'))
1693 s->width = FFALIGN(avctx->width, 16);
1694 s->height = FFALIGN(avctx->height, 16);
1695 if (avctx->codec_id != AV_CODEC_ID_THEORA)
1696 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
1697 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1698 ff_hpeldsp_init(&s->hdsp, avctx->flags | CODEC_FLAG_BITEXACT);
1699 ff_videodsp_init(&s->vdsp, 8);
1700 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
1702 for (i = 0; i < 64; i++) {
1703 #define T(x) (x >> 3) | ((x & 7) << 3)
1704 s->idct_permutation[i] = T(i);
1705 s->idct_scantable[i] = T(ff_zigzag_direct[i]);
1709 /* initialize to an impossible value which will force a recalculation
1710 * in the first frame decode */
1711 for (i = 0; i < 3; i++)
1714 avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1716 s->y_superblock_width = (s->width + 31) / 32;
1717 s->y_superblock_height = (s->height + 31) / 32;
1718 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1720 /* work out the dimensions for the C planes */
1721 c_width = s->width >> s->chroma_x_shift;
1722 c_height = s->height >> s->chroma_y_shift;
1723 s->c_superblock_width = (c_width + 31) / 32;
1724 s->c_superblock_height = (c_height + 31) / 32;
1725 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1727 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1728 s->u_superblock_start = s->y_superblock_count;
1729 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1731 s->macroblock_width = (s->width + 15) / 16;
1732 s->macroblock_height = (s->height + 15) / 16;
1733 s->macroblock_count = s->macroblock_width * s->macroblock_height;
1735 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1736 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1737 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
1738 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
1740 /* fragment count covers all 8x8 blocks for all 3 planes */
1741 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1742 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1743 s->fragment_count = y_fragment_count + 2*c_fragment_count;
1744 s->fragment_start[1] = y_fragment_count;
1745 s->fragment_start[2] = y_fragment_count + c_fragment_count;
1747 if (!s->theora_tables)
1749 for (i = 0; i < 64; i++) {
1750 s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1751 s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1752 s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1753 s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1754 s->base_matrix[2][i] = vp31_inter_dequant[i];
1755 s->filter_limit_values[i] = vp31_filter_limit_values[i];
1758 for(inter=0; inter<2; inter++){
1759 for(plane=0; plane<3; plane++){
1760 s->qr_count[inter][plane]= 1;
1761 s->qr_size [inter][plane][0]= 63;
1762 s->qr_base [inter][plane][0]=
1763 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1767 /* init VLC tables */
1768 for (i = 0; i < 16; i++) {
1771 init_vlc(&s->dc_vlc[i], 11, 32,
1772 &dc_bias[i][0][1], 4, 2,
1773 &dc_bias[i][0][0], 4, 2, 0);
1775 /* group 1 AC histograms */
1776 init_vlc(&s->ac_vlc_1[i], 11, 32,
1777 &ac_bias_0[i][0][1], 4, 2,
1778 &ac_bias_0[i][0][0], 4, 2, 0);
1780 /* group 2 AC histograms */
1781 init_vlc(&s->ac_vlc_2[i], 11, 32,
1782 &ac_bias_1[i][0][1], 4, 2,
1783 &ac_bias_1[i][0][0], 4, 2, 0);
1785 /* group 3 AC histograms */
1786 init_vlc(&s->ac_vlc_3[i], 11, 32,
1787 &ac_bias_2[i][0][1], 4, 2,
1788 &ac_bias_2[i][0][0], 4, 2, 0);
1790 /* group 4 AC histograms */
1791 init_vlc(&s->ac_vlc_4[i], 11, 32,
1792 &ac_bias_3[i][0][1], 4, 2,
1793 &ac_bias_3[i][0][0], 4, 2, 0);
1797 for (i = 0; i < 16; i++) {
1799 if (init_vlc(&s->dc_vlc[i], 11, 32,
1800 &s->huffman_table[i][0][1], 8, 4,
1801 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
1804 /* group 1 AC histograms */
1805 if (init_vlc(&s->ac_vlc_1[i], 11, 32,
1806 &s->huffman_table[i+16][0][1], 8, 4,
1807 &s->huffman_table[i+16][0][0], 8, 4, 0) < 0)
1810 /* group 2 AC histograms */
1811 if (init_vlc(&s->ac_vlc_2[i], 11, 32,
1812 &s->huffman_table[i+16*2][0][1], 8, 4,
1813 &s->huffman_table[i+16*2][0][0], 8, 4, 0) < 0)
1816 /* group 3 AC histograms */
1817 if (init_vlc(&s->ac_vlc_3[i], 11, 32,
1818 &s->huffman_table[i+16*3][0][1], 8, 4,
1819 &s->huffman_table[i+16*3][0][0], 8, 4, 0) < 0)
1822 /* group 4 AC histograms */
1823 if (init_vlc(&s->ac_vlc_4[i], 11, 32,
1824 &s->huffman_table[i+16*4][0][1], 8, 4,
1825 &s->huffman_table[i+16*4][0][0], 8, 4, 0) < 0)
1830 init_vlc(&s->superblock_run_length_vlc, 6, 34,
1831 &superblock_run_length_vlc_table[0][1], 4, 2,
1832 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1834 init_vlc(&s->fragment_run_length_vlc, 5, 30,
1835 &fragment_run_length_vlc_table[0][1], 4, 2,
1836 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1838 init_vlc(&s->mode_code_vlc, 3, 8,
1839 &mode_code_vlc_table[0][1], 2, 1,
1840 &mode_code_vlc_table[0][0], 2, 1, 0);
1842 init_vlc(&s->motion_vector_vlc, 6, 63,
1843 &motion_vector_vlc_table[0][1], 2, 1,
1844 &motion_vector_vlc_table[0][0], 2, 1, 0);
1846 return allocate_tables(avctx);
1849 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1853 /// Release and shuffle frames after decode finishes
1854 static int update_frames(AVCodecContext *avctx)
1856 Vp3DecodeContext *s = avctx->priv_data;
1860 /* shuffle frames (last = current) */
1861 ff_thread_release_buffer(avctx, &s->last_frame);
1862 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
1867 ff_thread_release_buffer(avctx, &s->golden_frame);
1868 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
1872 ff_thread_release_buffer(avctx, &s->current_frame);
1876 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
1878 ff_thread_release_buffer(s->avctx, dst);
1879 if (src->f->data[0])
1880 return ff_thread_ref_frame(dst, src);
1884 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
1887 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
1888 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
1889 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
1894 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1896 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1897 int qps_changed = 0, i, err;
1899 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1901 if (!s1->current_frame.f->data[0]
1902 ||s->width != s1->width
1903 ||s->height!= s1->height) {
1910 // init tables if the first frame hasn't been decoded
1911 if (!s->current_frame.f->data[0]) {
1912 int y_fragment_count, c_fragment_count;
1914 err = allocate_tables(dst);
1917 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1918 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1919 memcpy(s->motion_val[0], s1->motion_val[0], y_fragment_count * sizeof(*s->motion_val[0]));
1920 memcpy(s->motion_val[1], s1->motion_val[1], c_fragment_count * sizeof(*s->motion_val[1]));
1923 // copy previous frame data
1924 if ((err = ref_frames(s, s1)) < 0)
1927 s->keyframe = s1->keyframe;
1929 // copy qscale data if necessary
1930 for (i = 0; i < 3; i++) {
1931 if (s->qps[i] != s1->qps[1]) {
1933 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
1937 if (s->qps[0] != s1->qps[0])
1938 memcpy(&s->bounding_values_array, &s1->bounding_values_array, sizeof(s->bounding_values_array));
1941 copy_fields(s, s1, qps, superblock_count);
1945 return update_frames(dst);
1948 static int vp3_decode_frame(AVCodecContext *avctx,
1949 void *data, int *got_frame,
1952 const uint8_t *buf = avpkt->data;
1953 int buf_size = avpkt->size;
1954 Vp3DecodeContext *s = avctx->priv_data;
1958 init_get_bits(&gb, buf, buf_size * 8);
1960 #if CONFIG_THEORA_DECODER
1961 if (s->theora && get_bits1(&gb))
1963 int type = get_bits(&gb, 7);
1964 skip_bits_long(&gb, 6*8); /* "theora" */
1966 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
1967 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
1968 return AVERROR_PATCHWELCOME;
1971 vp3_decode_end(avctx);
1972 ret = theora_decode_header(avctx, &gb);
1975 vp3_decode_end(avctx);
1977 ret = vp3_decode_init(avctx);
1979 } else if (type == 2) {
1980 ret = theora_decode_tables(avctx, &gb);
1982 vp3_decode_end(avctx);
1984 ret = vp3_decode_init(avctx);
1988 av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1993 s->keyframe = !get_bits1(&gb);
1994 if (!s->all_fragments) {
1995 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2000 for (i = 0; i < 3; i++)
2001 s->last_qps[i] = s->qps[i];
2005 s->qps[s->nqps++]= get_bits(&gb, 6);
2006 } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
2007 for (i = s->nqps; i < 3; i++)
2010 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2011 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2012 s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);
2014 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2015 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);
2017 if (s->qps[0] != s->last_qps[0])
2018 init_loop_filter(s);
2020 for (i = 0; i < s->nqps; i++)
2021 // reinit all dequantizers if the first one changed, because
2022 // the DC of the first quantizer must be used for all matrices
2023 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2024 init_dequantizer(s, i);
2026 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2029 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
2030 s->current_frame.f->key_frame = s->keyframe;
2031 if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2034 if (!s->edge_emu_buffer)
2035 s->edge_emu_buffer = av_malloc(9*FFABS(s->current_frame.f->linesize[0]));
2040 skip_bits(&gb, 4); /* width code */
2041 skip_bits(&gb, 4); /* height code */
2044 s->version = get_bits(&gb, 5);
2045 if (avctx->frame_number == 0)
2046 av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
2049 if (s->version || s->theora)
2052 av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
2053 skip_bits(&gb, 2); /* reserved? */
2056 if (!s->golden_frame.f->data[0]) {
2057 av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
2059 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2060 if (ff_thread_get_buffer(avctx, &s->golden_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2062 ff_thread_release_buffer(avctx, &s->last_frame);
2063 if ((ret = ff_thread_ref_frame(&s->last_frame, &s->golden_frame)) < 0)
2065 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2069 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2070 ff_thread_finish_setup(avctx);
2072 if (unpack_superblocks(s, &gb)){
2073 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2076 if (unpack_modes(s, &gb)){
2077 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2080 if (unpack_vectors(s, &gb)){
2081 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2084 if (unpack_block_qpis(s, &gb)){
2085 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2088 if (unpack_dct_coeffs(s, &gb)){
2089 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2093 for (i = 0; i < 3; i++) {
2094 int height = s->height >> (i && s->chroma_y_shift);
2095 if (s->flipped_image)
2096 s->data_offset[i] = 0;
2098 s->data_offset[i] = (height-1) * s->current_frame.f->linesize[i];
2101 s->last_slice_end = 0;
2102 for (i = 0; i < s->c_superblock_height; i++)
2105 // filter the last row
2106 for (i = 0; i < 3; i++) {
2107 int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;
2108 apply_loop_filter(s, i, row, row+1);
2110 vp3_draw_horiz_band(s, s->avctx->height);
2112 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2116 if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME)) {
2117 ret = update_frames(avctx);
2125 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2127 if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
2128 av_frame_unref(s->current_frame.f);
2133 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2135 Vp3DecodeContext *s = avctx->priv_data;
2137 if (get_bits1(gb)) {
2139 if (s->entries >= 32) { /* overflow */
2140 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2143 token = get_bits(gb, 5);
2144 av_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2145 s->hti, s->hbits, token, s->entries, s->huff_code_size);
2146 s->huffman_table[s->hti][token][0] = s->hbits;
2147 s->huffman_table[s->hti][token][1] = s->huff_code_size;
2151 if (s->huff_code_size >= 32) {/* overflow */
2152 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2155 s->huff_code_size++;
2157 if (read_huffman_tree(avctx, gb))
2160 if (read_huffman_tree(avctx, gb))
2163 s->huff_code_size--;
2168 static int vp3_init_thread_copy(AVCodecContext *avctx)
2170 Vp3DecodeContext *s = avctx->priv_data;
2172 s->superblock_coding = NULL;
2173 s->all_fragments = NULL;
2174 s->coded_fragment_list[0] = NULL;
2175 s->dct_tokens_base = NULL;
2176 s->superblock_fragments = NULL;
2177 s->macroblock_coding = NULL;
2178 s->motion_val[0] = NULL;
2179 s->motion_val[1] = NULL;
2180 s->edge_emu_buffer = NULL;
2182 return init_frames(s);
2185 #if CONFIG_THEORA_DECODER
2186 static const enum AVPixelFormat theora_pix_fmts[4] = {
2187 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2190 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2192 Vp3DecodeContext *s = avctx->priv_data;
2193 int visible_width, visible_height, colorspace;
2194 int offset_x = 0, offset_y = 0;
2195 AVRational fps, aspect;
2197 s->theora = get_bits_long(gb, 24);
2198 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2200 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
2201 /* but previous versions have the image flipped relative to vp3 */
2202 if (s->theora < 0x030200)
2204 s->flipped_image = 1;
2205 av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
2208 visible_width = s->width = get_bits(gb, 16) << 4;
2209 visible_height = s->height = get_bits(gb, 16) << 4;
2211 if(av_image_check_size(s->width, s->height, 0, avctx)){
2212 av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
2213 s->width= s->height= 0;
2217 if (s->theora >= 0x030200) {
2218 visible_width = get_bits_long(gb, 24);
2219 visible_height = get_bits_long(gb, 24);
2221 offset_x = get_bits(gb, 8); /* offset x */
2222 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2225 fps.num = get_bits_long(gb, 32);
2226 fps.den = get_bits_long(gb, 32);
2227 if (fps.num>0 && fps.den>0) {
2228 av_reduce(&avctx->time_base.num, &avctx->time_base.den,
2229 fps.den, fps.num, 1<<30);
2232 aspect.num = get_bits_long(gb, 24);
2233 aspect.den = get_bits_long(gb, 24);
2234 if (aspect.num && aspect.den) {
2235 av_reduce(&avctx->sample_aspect_ratio.num,
2236 &avctx->sample_aspect_ratio.den,
2237 aspect.num, aspect.den, 1<<30);
2240 if (s->theora < 0x030200)
2241 skip_bits(gb, 5); /* keyframe frequency force */
2242 colorspace = get_bits(gb, 8);
2243 skip_bits(gb, 24); /* bitrate */
2245 skip_bits(gb, 6); /* quality hint */
2247 if (s->theora >= 0x030200)
2249 skip_bits(gb, 5); /* keyframe frequency force */
2250 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2251 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2252 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2253 return AVERROR_INVALIDDATA;
2255 skip_bits(gb, 3); /* reserved */
2258 // align_get_bits(gb);
2260 if ( visible_width <= s->width && visible_width > s->width-16
2261 && visible_height <= s->height && visible_height > s->height-16
2262 && !offset_x && (offset_y == s->height - visible_height))
2263 avcodec_set_dimensions(avctx, visible_width, visible_height);
2265 avcodec_set_dimensions(avctx, s->width, s->height);
2267 if (colorspace == 1) {
2268 avctx->color_primaries = AVCOL_PRI_BT470M;
2269 } else if (colorspace == 2) {
2270 avctx->color_primaries = AVCOL_PRI_BT470BG;
2272 if (colorspace == 1 || colorspace == 2) {
2273 avctx->colorspace = AVCOL_SPC_BT470BG;
2274 avctx->color_trc = AVCOL_TRC_BT709;
2280 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2282 Vp3DecodeContext *s = avctx->priv_data;
2283 int i, n, matrices, inter, plane;
2285 if (s->theora >= 0x030200) {
2286 n = get_bits(gb, 3);
2287 /* loop filter limit values table */
2289 for (i = 0; i < 64; i++)
2290 s->filter_limit_values[i] = get_bits(gb, n);
2293 if (s->theora >= 0x030200)
2294 n = get_bits(gb, 4) + 1;
2297 /* quality threshold table */
2298 for (i = 0; i < 64; i++)
2299 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2301 if (s->theora >= 0x030200)
2302 n = get_bits(gb, 4) + 1;
2305 /* dc scale factor table */
2306 for (i = 0; i < 64; i++)
2307 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2309 if (s->theora >= 0x030200)
2310 matrices = get_bits(gb, 9) + 1;
2315 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2319 for(n=0; n<matrices; n++){
2320 for (i = 0; i < 64; i++)
2321 s->base_matrix[n][i]= get_bits(gb, 8);
2324 for (inter = 0; inter <= 1; inter++) {
2325 for (plane = 0; plane <= 2; plane++) {
2327 if (inter || plane > 0)
2328 newqr = get_bits1(gb);
2331 if(inter && get_bits1(gb)){
2335 qtj= (3*inter + plane - 1) / 3;
2336 plj= (plane + 2) % 3;
2338 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2339 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2340 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2346 i= get_bits(gb, av_log2(matrices-1)+1);
2348 av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2351 s->qr_base[inter][plane][qri]= i;
2354 i = get_bits(gb, av_log2(63-qi)+1) + 1;
2355 s->qr_size[inter][plane][qri++]= i;
2360 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2363 s->qr_count[inter][plane]= qri;
2368 /* Huffman tables */
2369 for (s->hti = 0; s->hti < 80; s->hti++) {
2371 s->huff_code_size = 1;
2372 if (!get_bits1(gb)) {
2374 if(read_huffman_tree(avctx, gb))
2377 if(read_huffman_tree(avctx, gb))
2382 s->theora_tables = 1;
2387 static av_cold int theora_decode_init(AVCodecContext *avctx)
2389 Vp3DecodeContext *s = avctx->priv_data;
2392 uint8_t *header_start[3];
2396 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2400 if (!avctx->extradata_size)
2402 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2406 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2407 42, header_start, header_len) < 0) {
2408 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2413 if (header_len[i] <= 0)
2415 init_get_bits(&gb, header_start[i], header_len[i] * 8);
2417 ptype = get_bits(&gb, 8);
2419 if (!(ptype & 0x80))
2421 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2425 // FIXME: Check for this as well.
2426 skip_bits_long(&gb, 6*8); /* "theora" */
2431 if (theora_decode_header(avctx, &gb) < 0)
2435 // FIXME: is this needed? it breaks sometimes
2436 // theora_decode_comments(avctx, gb);
2439 if (theora_decode_tables(avctx, &gb))
2443 av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2446 if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2447 av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2448 if (s->theora < 0x030200)
2452 return vp3_decode_init(avctx);
2455 AVCodec ff_theora_decoder = {
2457 .type = AVMEDIA_TYPE_VIDEO,
2458 .id = AV_CODEC_ID_THEORA,
2459 .priv_data_size = sizeof(Vp3DecodeContext),
2460 .init = theora_decode_init,
2461 .close = vp3_decode_end,
2462 .decode = vp3_decode_frame,
2463 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2464 CODEC_CAP_FRAME_THREADS,
2465 .flush = vp3_decode_flush,
2466 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2467 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2468 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
2472 AVCodec ff_vp3_decoder = {
2474 .type = AVMEDIA_TYPE_VIDEO,
2475 .id = AV_CODEC_ID_VP3,
2476 .priv_data_size = sizeof(Vp3DecodeContext),
2477 .init = vp3_decode_init,
2478 .close = vp3_decode_end,
2479 .decode = vp3_decode_frame,
2480 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2481 CODEC_CAP_FRAME_THREADS,
2482 .flush = vp3_decode_flush,
2483 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2484 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2485 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),