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]] =
385 av_clip((qscale * coeff) / 100 * 4, qmin, 4096);
387 // all DC coefficients use the same quant so as not to interfere with DC prediction
388 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
394 * This function initializes the loop filter boundary limits if the frame's
395 * quality index is different from the previous frame's.
397 * The filter_limit_values may not be larger than 127.
399 static void init_loop_filter(Vp3DecodeContext *s)
401 int *bounding_values= s->bounding_values_array+127;
406 filter_limit = s->filter_limit_values[s->qps[0]];
407 av_assert0(filter_limit < 128U);
409 /* set up the bounding values */
410 memset(s->bounding_values_array, 0, 256 * sizeof(int));
411 for (x = 0; x < filter_limit; x++) {
412 bounding_values[-x] = -x;
413 bounding_values[x] = x;
415 for (x = value = filter_limit; x < 128 && value; x++, value--) {
416 bounding_values[ x] = value;
417 bounding_values[-x] = -value;
420 bounding_values[128] = value;
421 bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
425 * This function unpacks all of the superblock/macroblock/fragment coding
426 * information from the bitstream.
428 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
430 int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };
432 int current_superblock = 0;
434 int num_partial_superblocks = 0;
437 int current_fragment;
441 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
445 /* unpack the list of partially-coded superblocks */
446 bit = get_bits1(gb) ^ 1;
449 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
450 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
455 current_run = get_vlc2(gb,
456 s->superblock_run_length_vlc.table, 6, 2) + 1;
457 if (current_run == 34)
458 current_run += get_bits(gb, 12);
460 if (current_superblock + current_run > s->superblock_count) {
461 av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");
465 memset(s->superblock_coding + current_superblock, bit, current_run);
467 current_superblock += current_run;
469 num_partial_superblocks += current_run;
472 /* unpack the list of fully coded superblocks if any of the blocks were
473 * not marked as partially coded in the previous step */
474 if (num_partial_superblocks < s->superblock_count) {
475 int superblocks_decoded = 0;
477 current_superblock = 0;
478 bit = get_bits1(gb) ^ 1;
481 while (superblocks_decoded < s->superblock_count - num_partial_superblocks
482 && get_bits_left(gb) > 0) {
484 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
489 current_run = get_vlc2(gb,
490 s->superblock_run_length_vlc.table, 6, 2) + 1;
491 if (current_run == 34)
492 current_run += get_bits(gb, 12);
494 for (j = 0; j < current_run; current_superblock++) {
495 if (current_superblock >= s->superblock_count) {
496 av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");
500 /* skip any superblocks already marked as partially coded */
501 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
502 s->superblock_coding[current_superblock] = 2*bit;
506 superblocks_decoded += current_run;
510 /* if there were partial blocks, initialize bitstream for
511 * unpacking fragment codings */
512 if (num_partial_superblocks) {
516 /* toggle the bit because as soon as the first run length is
517 * fetched the bit will be toggled again */
522 /* figure out which fragments are coded; iterate through each
523 * superblock (all planes) */
524 s->total_num_coded_frags = 0;
525 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
527 for (plane = 0; plane < 3; plane++) {
528 int sb_start = superblock_starts[plane];
529 int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
530 int num_coded_frags = 0;
532 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
534 /* iterate through all 16 fragments in a superblock */
535 for (j = 0; j < 16; j++) {
537 /* if the fragment is in bounds, check its coding status */
538 current_fragment = s->superblock_fragments[i * 16 + j];
539 if (current_fragment != -1) {
540 int coded = s->superblock_coding[i];
542 if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
544 /* fragment may or may not be coded; this is the case
545 * that cares about the fragment coding runs */
546 if (current_run-- == 0) {
548 current_run = get_vlc2(gb,
549 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] + num_coded_frags;
579 * This function unpacks all the coding mode data for individual macroblocks
580 * from the bitstream.
582 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
584 int i, j, k, sb_x, sb_y;
586 int current_macroblock;
587 int current_fragment;
589 int custom_mode_alphabet[CODING_MODE_COUNT];
594 for (i = 0; i < s->fragment_count; i++)
595 s->all_fragments[i].coding_method = MODE_INTRA;
599 /* fetch the mode coding scheme for this frame */
600 scheme = get_bits(gb, 3);
602 /* is it a custom coding scheme? */
604 for (i = 0; i < 8; i++)
605 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
606 for (i = 0; i < 8; i++)
607 custom_mode_alphabet[get_bits(gb, 3)] = i;
608 alphabet = custom_mode_alphabet;
610 alphabet = ModeAlphabet[scheme-1];
612 /* iterate through all of the macroblocks that contain 1 or more
614 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
615 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
616 if (get_bits_left(gb) <= 0)
619 for (j = 0; j < 4; j++) {
620 int mb_x = 2*sb_x + (j>>1);
621 int mb_y = 2*sb_y + (((j>>1)+j)&1);
622 current_macroblock = mb_y * s->macroblock_width + mb_x;
624 if (mb_x >= s->macroblock_width || 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 at least one
630 * luma block coded, otherwise it must be INTER_NO_MV */
631 for (k = 0; k < 4; k++) {
632 current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
633 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
637 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
641 /* mode 7 means get 3 bits for each coding mode */
643 coding_mode = get_bits(gb, 3);
645 coding_mode = alphabet
646 [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
648 s->macroblock_coding[current_macroblock] = coding_mode;
649 for (k = 0; k < 4; k++) {
650 frag = s->all_fragments + BLOCK_Y*s->fragment_width[0] + BLOCK_X;
651 if (frag->coding_method != MODE_COPY)
652 frag->coding_method = coding_mode;
655 #define SET_CHROMA_MODES \
656 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
657 frag[s->fragment_start[1]].coding_method = coding_mode;\
658 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
659 frag[s->fragment_start[2]].coding_method = coding_mode;
661 if (s->chroma_y_shift) {
662 frag = s->all_fragments + mb_y*s->fragment_width[1] + mb_x;
664 } else if (s->chroma_x_shift) {
665 frag = s->all_fragments + 2*mb_y*s->fragment_width[1] + mb_x;
666 for (k = 0; k < 2; k++) {
668 frag += s->fragment_width[1];
671 for (k = 0; k < 4; k++) {
672 frag = s->all_fragments + BLOCK_Y*s->fragment_width[1] + BLOCK_X;
685 * This function unpacks all the motion vectors for the individual
686 * macroblocks from the bitstream.
688 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
690 int j, k, sb_x, sb_y;
694 int last_motion_x = 0;
695 int last_motion_y = 0;
696 int prior_last_motion_x = 0;
697 int prior_last_motion_y = 0;
698 int current_macroblock;
699 int current_fragment;
705 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
706 coding_mode = get_bits1(gb);
708 /* iterate through all of the macroblocks that contain 1 or more
710 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
711 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
712 if (get_bits_left(gb) <= 0)
715 for (j = 0; j < 4; j++) {
716 int mb_x = 2*sb_x + (j>>1);
717 int mb_y = 2*sb_y + (((j>>1)+j)&1);
718 current_macroblock = mb_y * s->macroblock_width + mb_x;
720 if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
721 (s->macroblock_coding[current_macroblock] == MODE_COPY))
724 switch (s->macroblock_coding[current_macroblock]) {
726 case MODE_INTER_PLUS_MV:
728 /* all 6 fragments use the same motion vector */
729 if (coding_mode == 0) {
730 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
731 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
733 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
734 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
737 /* vector maintenance, only on MODE_INTER_PLUS_MV */
738 if (s->macroblock_coding[current_macroblock] ==
739 MODE_INTER_PLUS_MV) {
740 prior_last_motion_x = last_motion_x;
741 prior_last_motion_y = last_motion_y;
742 last_motion_x = motion_x[0];
743 last_motion_y = motion_y[0];
747 case MODE_INTER_FOURMV:
748 /* vector maintenance */
749 prior_last_motion_x = last_motion_x;
750 prior_last_motion_y = last_motion_y;
752 /* fetch 4 vectors from the bitstream, one for each
753 * Y fragment, then average for the C fragment vectors */
754 for (k = 0; k < 4; k++) {
755 current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
756 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
757 if (coding_mode == 0) {
758 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
759 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
761 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
762 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
764 last_motion_x = motion_x[k];
765 last_motion_y = motion_y[k];
773 case MODE_INTER_LAST_MV:
774 /* all 6 fragments use the last motion vector */
775 motion_x[0] = last_motion_x;
776 motion_y[0] = last_motion_y;
778 /* no vector maintenance (last vector remains the
782 case MODE_INTER_PRIOR_LAST:
783 /* all 6 fragments use the motion vector prior to the
784 * last motion vector */
785 motion_x[0] = prior_last_motion_x;
786 motion_y[0] = prior_last_motion_y;
788 /* vector maintenance */
789 prior_last_motion_x = last_motion_x;
790 prior_last_motion_y = last_motion_y;
791 last_motion_x = motion_x[0];
792 last_motion_y = motion_y[0];
796 /* covers intra, inter without MV, golden without MV */
800 /* no vector maintenance */
804 /* assign the motion vectors to the correct fragments */
805 for (k = 0; k < 4; k++) {
807 BLOCK_Y*s->fragment_width[0] + BLOCK_X;
808 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
809 s->motion_val[0][current_fragment][0] = motion_x[k];
810 s->motion_val[0][current_fragment][1] = motion_y[k];
812 s->motion_val[0][current_fragment][0] = motion_x[0];
813 s->motion_val[0][current_fragment][1] = motion_y[0];
817 if (s->chroma_y_shift) {
818 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
819 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] + motion_x[2] + motion_x[3], 2);
820 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] + motion_y[2] + motion_y[3], 2);
822 motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
823 motion_y[0] = (motion_y[0]>>1) | (motion_y[0]&1);
824 frag = mb_y*s->fragment_width[1] + mb_x;
825 s->motion_val[1][frag][0] = motion_x[0];
826 s->motion_val[1][frag][1] = motion_y[0];
827 } else if (s->chroma_x_shift) {
828 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
829 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
830 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
831 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
832 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
834 motion_x[1] = motion_x[0];
835 motion_y[1] = motion_y[0];
837 motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
838 motion_x[1] = (motion_x[1]>>1) | (motion_x[1]&1);
840 frag = 2*mb_y*s->fragment_width[1] + mb_x;
841 for (k = 0; k < 2; k++) {
842 s->motion_val[1][frag][0] = motion_x[k];
843 s->motion_val[1][frag][1] = motion_y[k];
844 frag += s->fragment_width[1];
847 for (k = 0; k < 4; k++) {
848 frag = BLOCK_Y*s->fragment_width[1] + BLOCK_X;
849 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
850 s->motion_val[1][frag][0] = motion_x[k];
851 s->motion_val[1][frag][1] = motion_y[k];
853 s->motion_val[1][frag][0] = motion_x[0];
854 s->motion_val[1][frag][1] = motion_y[0];
865 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
867 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
868 int num_blocks = s->total_num_coded_frags;
870 for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
871 i = blocks_decoded = num_blocks_at_qpi = 0;
873 bit = get_bits1(gb) ^ 1;
877 if (run_length == MAXIMUM_LONG_BIT_RUN)
882 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
883 if (run_length == 34)
884 run_length += get_bits(gb, 12);
885 blocks_decoded += run_length;
888 num_blocks_at_qpi += run_length;
890 for (j = 0; j < run_length; i++) {
891 if (i >= s->total_num_coded_frags)
894 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
895 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
899 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
901 num_blocks -= num_blocks_at_qpi;
908 * This function is called by unpack_dct_coeffs() to extract the VLCs from
909 * the bitstream. The VLCs encode tokens which are used to unpack DCT
910 * data. This function unpacks all the VLCs for either the Y plane or both
911 * C planes, and is called for DC coefficients or different AC coefficient
912 * levels (since different coefficient types require different VLC tables.
914 * This function returns a residual eob run. E.g, if a particular token gave
915 * instructions to EOB the next 5 fragments and there were only 2 fragments
916 * left in the current fragment range, 3 would be returned so that it could
917 * be passed into the next call to this same function.
919 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
920 VLC *table, int coeff_index,
931 int num_coeffs = s->num_coded_frags[plane][coeff_index];
932 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
934 /* local references to structure members to avoid repeated deferences */
935 int *coded_fragment_list = s->coded_fragment_list[plane];
936 Vp3Fragment *all_fragments = s->all_fragments;
937 VLC_TYPE (*vlc_table)[2] = table->table;
940 av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
942 if (eob_run > num_coeffs) {
943 coeff_i = blocks_ended = num_coeffs;
944 eob_run -= num_coeffs;
946 coeff_i = blocks_ended = eob_run;
950 // insert fake EOB token to cover the split between planes or zzi
952 dct_tokens[j++] = blocks_ended << 2;
954 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
955 /* decode a VLC into a token */
956 token = get_vlc2(gb, vlc_table, 11, 3);
957 /* use the token to get a zero run, a coefficient, and an eob run */
958 if ((unsigned) token <= 6U) {
959 eob_run = eob_run_base[token];
960 if (eob_run_get_bits[token])
961 eob_run += get_bits(gb, eob_run_get_bits[token]);
963 // record only the number of blocks ended in this plane,
964 // any spill will be recorded in the next plane.
965 if (eob_run > num_coeffs - coeff_i) {
966 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
967 blocks_ended += num_coeffs - coeff_i;
968 eob_run -= num_coeffs - coeff_i;
969 coeff_i = num_coeffs;
971 dct_tokens[j++] = TOKEN_EOB(eob_run);
972 blocks_ended += eob_run;
976 } else if (token >= 0) {
977 bits_to_get = coeff_get_bits[token];
979 bits_to_get = get_bits(gb, bits_to_get);
980 coeff = coeff_tables[token][bits_to_get];
982 zero_run = zero_run_base[token];
983 if (zero_run_get_bits[token])
984 zero_run += get_bits(gb, zero_run_get_bits[token]);
987 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
989 // Save DC into the fragment structure. DC prediction is
990 // done in raster order, so the actual DC can't be in with
991 // other tokens. We still need the token in dct_tokens[]
992 // however, or else the structure collapses on itself.
994 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
996 dct_tokens[j++] = TOKEN_COEFF(coeff);
999 if (coeff_index + zero_run > 64) {
1000 av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
1001 " %d coeffs left\n", zero_run, 64-coeff_index);
1002 zero_run = 64 - coeff_index;
1005 // zero runs code multiple coefficients,
1006 // so don't try to decode coeffs for those higher levels
1007 for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
1008 s->num_coded_frags[plane][i]--;
1011 av_log(s->avctx, AV_LOG_ERROR,
1012 "Invalid token %d\n", token);
1017 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1018 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1020 // decrement the number of blocks that have higher coeffecients for each
1021 // EOB run at this level
1023 for (i = coeff_index+1; i < 64; i++)
1024 s->num_coded_frags[plane][i] -= blocks_ended;
1026 // setup the next buffer
1028 s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
1029 else if (coeff_index < 63)
1030 s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
1035 static void reverse_dc_prediction(Vp3DecodeContext *s,
1038 int fragment_height);
1040 * This function unpacks all of the DCT coefficient data from the
1043 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1050 int residual_eob_run = 0;
1054 s->dct_tokens[0][0] = s->dct_tokens_base;
1056 /* fetch the DC table indexes */
1057 dc_y_table = get_bits(gb, 4);
1058 dc_c_table = get_bits(gb, 4);
1060 /* unpack the Y plane DC coefficients */
1061 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1062 0, residual_eob_run);
1063 if (residual_eob_run < 0)
1064 return residual_eob_run;
1066 /* reverse prediction of the Y-plane DC coefficients */
1067 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1069 /* unpack the C plane DC coefficients */
1070 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1071 1, residual_eob_run);
1072 if (residual_eob_run < 0)
1073 return residual_eob_run;
1074 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1075 2, residual_eob_run);
1076 if (residual_eob_run < 0)
1077 return residual_eob_run;
1079 /* reverse prediction of the C-plane DC coefficients */
1080 if (!(s->avctx->flags & CODEC_FLAG_GRAY))
1082 reverse_dc_prediction(s, s->fragment_start[1],
1083 s->fragment_width[1], s->fragment_height[1]);
1084 reverse_dc_prediction(s, s->fragment_start[2],
1085 s->fragment_width[1], s->fragment_height[1]);
1088 /* fetch the AC table indexes */
1089 ac_y_table = get_bits(gb, 4);
1090 ac_c_table = get_bits(gb, 4);
1092 /* build tables of AC VLC tables */
1093 for (i = 1; i <= 5; i++) {
1094 y_tables[i] = &s->ac_vlc_1[ac_y_table];
1095 c_tables[i] = &s->ac_vlc_1[ac_c_table];
1097 for (i = 6; i <= 14; i++) {
1098 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1099 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1101 for (i = 15; i <= 27; i++) {
1102 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1103 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1105 for (i = 28; i <= 63; i++) {
1106 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1107 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1110 /* decode all AC coefficents */
1111 for (i = 1; i <= 63; i++) {
1112 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1113 0, residual_eob_run);
1114 if (residual_eob_run < 0)
1115 return residual_eob_run;
1117 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1118 1, residual_eob_run);
1119 if (residual_eob_run < 0)
1120 return residual_eob_run;
1121 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1122 2, residual_eob_run);
1123 if (residual_eob_run < 0)
1124 return residual_eob_run;
1131 * This function reverses the DC prediction for each coded fragment in
1132 * the frame. Much of this function is adapted directly from the original
1135 #define COMPATIBLE_FRAME(x) \
1136 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1137 #define DC_COEFF(u) s->all_fragments[u].dc
1139 static void reverse_dc_prediction(Vp3DecodeContext *s,
1142 int fragment_height)
1151 int i = first_fragment;
1155 /* DC values for the left, up-left, up, and up-right fragments */
1156 int vl, vul, vu, vur;
1158 /* indexes for the left, up-left, up, and up-right fragments */
1162 * The 6 fields mean:
1163 * 0: up-left multiplier
1165 * 2: up-right multiplier
1166 * 3: left multiplier
1168 static const int predictor_transform[16][4] = {
1170 { 0, 0, 0,128}, // PL
1171 { 0, 0,128, 0}, // PUR
1172 { 0, 0, 53, 75}, // PUR|PL
1173 { 0,128, 0, 0}, // PU
1174 { 0, 64, 0, 64}, // PU|PL
1175 { 0,128, 0, 0}, // PU|PUR
1176 { 0, 0, 53, 75}, // PU|PUR|PL
1177 {128, 0, 0, 0}, // PUL
1178 { 0, 0, 0,128}, // PUL|PL
1179 { 64, 0, 64, 0}, // PUL|PUR
1180 { 0, 0, 53, 75}, // PUL|PUR|PL
1181 { 0,128, 0, 0}, // PUL|PU
1182 {-104,116, 0,116}, // PUL|PU|PL
1183 { 24, 80, 24, 0}, // PUL|PU|PUR
1184 {-104,116, 0,116} // PUL|PU|PUR|PL
1187 /* This table shows which types of blocks can use other blocks for
1188 * prediction. For example, INTRA is the only mode in this table to
1189 * have a frame number of 0. That means INTRA blocks can only predict
1190 * from other INTRA blocks. There are 2 golden frame coding types;
1191 * blocks encoding in these modes can only predict from other blocks
1192 * that were encoded with these 1 of these 2 modes. */
1193 static const unsigned char compatible_frame[9] = {
1194 1, /* MODE_INTER_NO_MV */
1196 1, /* MODE_INTER_PLUS_MV */
1197 1, /* MODE_INTER_LAST_MV */
1198 1, /* MODE_INTER_PRIOR_MV */
1199 2, /* MODE_USING_GOLDEN */
1200 2, /* MODE_GOLDEN_MV */
1201 1, /* MODE_INTER_FOUR_MV */
1204 int current_frame_type;
1206 /* there is a last DC predictor for each of the 3 frame types */
1211 vul = vu = vur = vl = 0;
1212 last_dc[0] = last_dc[1] = last_dc[2] = 0;
1214 /* for each fragment row... */
1215 for (y = 0; y < fragment_height; y++) {
1217 /* for each fragment in a row... */
1218 for (x = 0; x < fragment_width; x++, i++) {
1220 /* reverse prediction if this block was coded */
1221 if (s->all_fragments[i].coding_method != MODE_COPY) {
1223 current_frame_type =
1224 compatible_frame[s->all_fragments[i].coding_method];
1230 if(COMPATIBLE_FRAME(l))
1234 u= i-fragment_width;
1236 if(COMPATIBLE_FRAME(u))
1239 ul= i-fragment_width-1;
1241 if(COMPATIBLE_FRAME(ul))
1244 if(x + 1 < fragment_width){
1245 ur= i-fragment_width+1;
1247 if(COMPATIBLE_FRAME(ur))
1252 if (transform == 0) {
1254 /* if there were no fragments to predict from, use last
1256 predicted_dc = last_dc[current_frame_type];
1259 /* apply the appropriate predictor transform */
1261 (predictor_transform[transform][0] * vul) +
1262 (predictor_transform[transform][1] * vu) +
1263 (predictor_transform[transform][2] * vur) +
1264 (predictor_transform[transform][3] * vl);
1266 predicted_dc /= 128;
1268 /* check for outranging on the [ul u l] and
1269 * [ul u ur l] predictors */
1270 if ((transform == 15) || (transform == 13)) {
1271 if (FFABS(predicted_dc - vu) > 128)
1273 else if (FFABS(predicted_dc - vl) > 128)
1275 else if (FFABS(predicted_dc - vul) > 128)
1280 /* at long last, apply the predictor */
1281 DC_COEFF(i) += predicted_dc;
1283 last_dc[current_frame_type] = DC_COEFF(i);
1289 static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1292 int *bounding_values= s->bounding_values_array+127;
1294 int width = s->fragment_width[!!plane];
1295 int height = s->fragment_height[!!plane];
1296 int fragment = s->fragment_start [plane] + ystart * width;
1297 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1298 uint8_t *plane_data = s->current_frame.f->data [plane];
1299 if (!s->flipped_image) stride = -stride;
1300 plane_data += s->data_offset[plane] + 8*ystart*stride;
1302 for (y = ystart; y < yend; y++) {
1304 for (x = 0; x < width; x++) {
1305 /* This code basically just deblocks on the edges of coded blocks.
1306 * However, it has to be much more complicated because of the
1307 * braindamaged deblock ordering used in VP3/Theora. Order matters
1308 * because some pixels get filtered twice. */
1309 if( s->all_fragments[fragment].coding_method != MODE_COPY )
1311 /* do not perform left edge filter for left columns frags */
1313 s->vp3dsp.h_loop_filter(
1315 stride, bounding_values);
1318 /* do not perform top edge filter for top row fragments */
1320 s->vp3dsp.v_loop_filter(
1322 stride, bounding_values);
1325 /* do not perform right edge filter for right column
1326 * fragments or if right fragment neighbor is also coded
1327 * in this frame (it will be filtered in next iteration) */
1328 if ((x < width - 1) &&
1329 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1330 s->vp3dsp.h_loop_filter(
1331 plane_data + 8*x + 8,
1332 stride, bounding_values);
1335 /* do not perform bottom edge filter for bottom row
1336 * fragments or if bottom fragment neighbor is also coded
1337 * in this frame (it will be filtered in the next row) */
1338 if ((y < height - 1) &&
1339 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1340 s->vp3dsp.v_loop_filter(
1341 plane_data + 8*x + 8*stride,
1342 stride, bounding_values);
1348 plane_data += 8*stride;
1353 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1354 * for the next block in coding order
1356 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1357 int plane, int inter, int16_t block[64])
1359 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1360 uint8_t *perm = s->idct_scantable;
1364 int token = *s->dct_tokens[plane][i];
1365 switch (token & 3) {
1367 if (--token < 4) // 0-3 are token types, so the EOB run must now be 0
1368 s->dct_tokens[plane][i]++;
1370 *s->dct_tokens[plane][i] = token & ~3;
1373 s->dct_tokens[plane][i]++;
1374 i += (token >> 2) & 0x7f;
1376 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1379 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1383 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1384 s->dct_tokens[plane][i++]++;
1386 default: // shouldn't happen
1390 // return value is expected to be a valid level
1393 // the actual DC+prediction is in the fragment structure
1394 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1399 * called when all pixels up to row y are complete
1401 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1404 int offset[AV_NUM_DATA_POINTERS];
1406 if (HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
1407 int y_flipped = s->flipped_image ? s->avctx->height-y : y;
1409 // At the end of the frame, report INT_MAX instead of the height of the frame.
1410 // This makes the other threads' ff_thread_await_progress() calls cheaper, because
1411 // they don't have to clip their values.
1412 ff_thread_report_progress(&s->current_frame, y_flipped==s->avctx->height ? INT_MAX : y_flipped-1, 0);
1415 if(s->avctx->draw_horiz_band==NULL)
1418 h= y - s->last_slice_end;
1419 s->last_slice_end= y;
1422 if (!s->flipped_image) {
1423 y = s->avctx->height - y - h;
1426 cy = y >> s->chroma_y_shift;
1427 offset[0] = s->current_frame.f->linesize[0]*y;
1428 offset[1] = s->current_frame.f->linesize[1]*cy;
1429 offset[2] = s->current_frame.f->linesize[2]*cy;
1430 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1434 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1438 * Wait for the reference frame of the current fragment.
1439 * The progress value is in luma pixel rows.
1441 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment, int motion_y, int y)
1443 ThreadFrame *ref_frame;
1445 int border = motion_y&1;
1447 if (fragment->coding_method == MODE_USING_GOLDEN ||
1448 fragment->coding_method == MODE_GOLDEN_MV)
1449 ref_frame = &s->golden_frame;
1451 ref_frame = &s->last_frame;
1453 ref_row = y + (motion_y>>1);
1454 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1456 ff_thread_await_progress(ref_frame, ref_row, 0);
1460 * Perform the final rendering for a particular slice of data.
1461 * The slice number ranges from 0..(c_superblock_height - 1).
1463 static void render_slice(Vp3DecodeContext *s, int slice)
1465 int x, y, i, j, fragment;
1466 int16_t *block = s->block;
1467 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1468 int motion_halfpel_index;
1469 uint8_t *motion_source;
1470 int plane, first_pixel;
1472 if (slice >= s->c_superblock_height)
1475 for (plane = 0; plane < 3; plane++) {
1476 uint8_t *output_plane = s->current_frame.f->data [plane] + s->data_offset[plane];
1477 uint8_t * last_plane = s-> last_frame.f->data [plane] + s->data_offset[plane];
1478 uint8_t *golden_plane = s-> golden_frame.f->data [plane] + s->data_offset[plane];
1479 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1480 int plane_width = s->width >> (plane && s->chroma_x_shift);
1481 int plane_height = s->height >> (plane && s->chroma_y_shift);
1482 int8_t (*motion_val)[2] = s->motion_val[!!plane];
1484 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
1485 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
1486 int slice_width = plane ? s->c_superblock_width : s->y_superblock_width;
1488 int fragment_width = s->fragment_width[!!plane];
1489 int fragment_height = s->fragment_height[!!plane];
1490 int fragment_start = s->fragment_start[plane];
1491 int do_await = !plane && HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_FRAME);
1493 if (!s->flipped_image) stride = -stride;
1494 if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1497 /* for each superblock row in the slice (both of them)... */
1498 for (; sb_y < slice_height; sb_y++) {
1500 /* for each superblock in a row... */
1501 for (sb_x = 0; sb_x < slice_width; sb_x++) {
1503 /* for each block in a superblock... */
1504 for (j = 0; j < 16; j++) {
1505 x = 4*sb_x + hilbert_offset[j][0];
1506 y = 4*sb_y + hilbert_offset[j][1];
1507 fragment = y*fragment_width + x;
1509 i = fragment_start + fragment;
1512 if (x >= fragment_width || y >= fragment_height)
1515 first_pixel = 8*y*stride + 8*x;
1517 if (do_await && s->all_fragments[i].coding_method != MODE_INTRA)
1518 await_reference_row(s, &s->all_fragments[i], motion_val[fragment][1], (16*y) >> s->chroma_y_shift);
1520 /* transform if this block was coded */
1521 if (s->all_fragments[i].coding_method != MODE_COPY) {
1522 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1523 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1524 motion_source= golden_plane;
1526 motion_source= last_plane;
1528 motion_source += first_pixel;
1529 motion_halfpel_index = 0;
1531 /* sort out the motion vector if this fragment is coded
1532 * using a motion vector method */
1533 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1534 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1536 motion_x = motion_val[fragment][0];
1537 motion_y = motion_val[fragment][1];
1539 src_x= (motion_x>>1) + 8*x;
1540 src_y= (motion_y>>1) + 8*y;
1542 motion_halfpel_index = motion_x & 0x01;
1543 motion_source += (motion_x >> 1);
1545 motion_halfpel_index |= (motion_y & 0x01) << 1;
1546 motion_source += ((motion_y >> 1) * stride);
1548 if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1549 uint8_t *temp= s->edge_emu_buffer;
1550 if(stride<0) temp -= 8*stride;
1552 s->vdsp.emulated_edge_mc(temp, motion_source,
1557 motion_source= temp;
1562 /* first, take care of copying a block from either the
1563 * previous or the golden frame */
1564 if (s->all_fragments[i].coding_method != MODE_INTRA) {
1565 /* Note, it is possible to implement all MC cases with
1566 put_no_rnd_pixels_l2 which would look more like the
1567 VP3 source but this would be slower as
1568 put_no_rnd_pixels_tab is better optimzed */
1569 if(motion_halfpel_index != 3){
1570 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1571 output_plane + first_pixel,
1572 motion_source, stride, 8);
1574 int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1575 s->vp3dsp.put_no_rnd_pixels_l2(
1576 output_plane + first_pixel,
1578 motion_source + stride + 1 + d,
1583 /* invert DCT and place (or add) in final output */
1585 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1586 vp3_dequant(s, s->all_fragments + i, plane, 0, block);
1588 output_plane + first_pixel,
1592 if (vp3_dequant(s, s->all_fragments + i, plane, 1, block)) {
1594 output_plane + first_pixel,
1598 s->vp3dsp.idct_dc_add(output_plane + first_pixel, stride, block);
1603 /* copy directly from the previous frame */
1604 s->hdsp.put_pixels_tab[1][0](
1605 output_plane + first_pixel,
1606 last_plane + first_pixel,
1613 // Filter up to the last row in the superblock row
1614 if (!s->skip_loop_filter)
1615 apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
1619 /* this looks like a good place for slice dispatch... */
1621 * if (slice == s->macroblock_height - 1)
1622 * dispatch (both last slice & 2nd-to-last slice);
1623 * else if (slice > 0)
1624 * dispatch (slice - 1);
1627 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) -16, s->height-16));
1630 /// Allocate tables for per-frame data in Vp3DecodeContext
1631 static av_cold int allocate_tables(AVCodecContext *avctx)
1633 Vp3DecodeContext *s = avctx->priv_data;
1634 int y_fragment_count, c_fragment_count;
1636 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1637 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1639 s->superblock_coding = av_mallocz(s->superblock_count);
1640 s->all_fragments = av_mallocz(s->fragment_count * sizeof(Vp3Fragment));
1641 s->coded_fragment_list[0] = av_mallocz(s->fragment_count * sizeof(int));
1642 s->dct_tokens_base = av_mallocz(64*s->fragment_count * sizeof(*s->dct_tokens_base));
1643 s->motion_val[0] = av_mallocz(y_fragment_count * sizeof(*s->motion_val[0]));
1644 s->motion_val[1] = av_mallocz(c_fragment_count * sizeof(*s->motion_val[1]));
1646 /* work out the block mapping tables */
1647 s->superblock_fragments = av_mallocz(s->superblock_count * 16 * sizeof(int));
1648 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
1650 if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
1651 !s->coded_fragment_list[0] || !s->superblock_fragments || !s->macroblock_coding ||
1652 !s->motion_val[0] || !s->motion_val[1]) {
1653 vp3_decode_end(avctx);
1657 init_block_mapping(s);
1662 static av_cold int init_frames(Vp3DecodeContext *s)
1664 s->current_frame.f = av_frame_alloc();
1665 s->last_frame.f = av_frame_alloc();
1666 s->golden_frame.f = av_frame_alloc();
1668 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
1669 av_frame_free(&s->current_frame.f);
1670 av_frame_free(&s->last_frame.f);
1671 av_frame_free(&s->golden_frame.f);
1672 return AVERROR(ENOMEM);
1678 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1680 Vp3DecodeContext *s = avctx->priv_data;
1681 int i, inter, plane, ret;
1684 int y_fragment_count, c_fragment_count;
1686 ret = init_frames(s);
1690 avctx->internal->allocate_progress = 1;
1692 if (avctx->codec_tag == MKTAG('V','P','3','0'))
1698 s->width = FFALIGN(avctx->width, 16);
1699 s->height = FFALIGN(avctx->height, 16);
1700 if (avctx->codec_id != AV_CODEC_ID_THEORA)
1701 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
1702 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1703 ff_hpeldsp_init(&s->hdsp, avctx->flags | CODEC_FLAG_BITEXACT);
1704 ff_videodsp_init(&s->vdsp, 8);
1705 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
1707 for (i = 0; i < 64; i++) {
1708 #define T(x) (x >> 3) | ((x & 7) << 3)
1709 s->idct_permutation[i] = T(i);
1710 s->idct_scantable[i] = T(ff_zigzag_direct[i]);
1714 /* initialize to an impossible value which will force a recalculation
1715 * in the first frame decode */
1716 for (i = 0; i < 3; i++)
1719 avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1721 s->y_superblock_width = (s->width + 31) / 32;
1722 s->y_superblock_height = (s->height + 31) / 32;
1723 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1725 /* work out the dimensions for the C planes */
1726 c_width = s->width >> s->chroma_x_shift;
1727 c_height = s->height >> s->chroma_y_shift;
1728 s->c_superblock_width = (c_width + 31) / 32;
1729 s->c_superblock_height = (c_height + 31) / 32;
1730 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1732 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1733 s->u_superblock_start = s->y_superblock_count;
1734 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1736 s->macroblock_width = (s->width + 15) / 16;
1737 s->macroblock_height = (s->height + 15) / 16;
1738 s->macroblock_count = s->macroblock_width * s->macroblock_height;
1740 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1741 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1742 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
1743 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
1745 /* fragment count covers all 8x8 blocks for all 3 planes */
1746 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1747 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1748 s->fragment_count = y_fragment_count + 2*c_fragment_count;
1749 s->fragment_start[1] = y_fragment_count;
1750 s->fragment_start[2] = y_fragment_count + c_fragment_count;
1752 if (!s->theora_tables)
1754 for (i = 0; i < 64; i++) {
1755 s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1756 s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1757 s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1758 s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1759 s->base_matrix[2][i] = vp31_inter_dequant[i];
1760 s->filter_limit_values[i] = vp31_filter_limit_values[i];
1763 for(inter=0; inter<2; inter++){
1764 for(plane=0; plane<3; plane++){
1765 s->qr_count[inter][plane]= 1;
1766 s->qr_size [inter][plane][0]= 63;
1767 s->qr_base [inter][plane][0]=
1768 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1772 /* init VLC tables */
1773 for (i = 0; i < 16; i++) {
1776 init_vlc(&s->dc_vlc[i], 11, 32,
1777 &dc_bias[i][0][1], 4, 2,
1778 &dc_bias[i][0][0], 4, 2, 0);
1780 /* group 1 AC histograms */
1781 init_vlc(&s->ac_vlc_1[i], 11, 32,
1782 &ac_bias_0[i][0][1], 4, 2,
1783 &ac_bias_0[i][0][0], 4, 2, 0);
1785 /* group 2 AC histograms */
1786 init_vlc(&s->ac_vlc_2[i], 11, 32,
1787 &ac_bias_1[i][0][1], 4, 2,
1788 &ac_bias_1[i][0][0], 4, 2, 0);
1790 /* group 3 AC histograms */
1791 init_vlc(&s->ac_vlc_3[i], 11, 32,
1792 &ac_bias_2[i][0][1], 4, 2,
1793 &ac_bias_2[i][0][0], 4, 2, 0);
1795 /* group 4 AC histograms */
1796 init_vlc(&s->ac_vlc_4[i], 11, 32,
1797 &ac_bias_3[i][0][1], 4, 2,
1798 &ac_bias_3[i][0][0], 4, 2, 0);
1802 for (i = 0; i < 16; i++) {
1804 if (init_vlc(&s->dc_vlc[i], 11, 32,
1805 &s->huffman_table[i][0][1], 8, 4,
1806 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
1809 /* group 1 AC histograms */
1810 if (init_vlc(&s->ac_vlc_1[i], 11, 32,
1811 &s->huffman_table[i+16][0][1], 8, 4,
1812 &s->huffman_table[i+16][0][0], 8, 4, 0) < 0)
1815 /* group 2 AC histograms */
1816 if (init_vlc(&s->ac_vlc_2[i], 11, 32,
1817 &s->huffman_table[i+16*2][0][1], 8, 4,
1818 &s->huffman_table[i+16*2][0][0], 8, 4, 0) < 0)
1821 /* group 3 AC histograms */
1822 if (init_vlc(&s->ac_vlc_3[i], 11, 32,
1823 &s->huffman_table[i+16*3][0][1], 8, 4,
1824 &s->huffman_table[i+16*3][0][0], 8, 4, 0) < 0)
1827 /* group 4 AC histograms */
1828 if (init_vlc(&s->ac_vlc_4[i], 11, 32,
1829 &s->huffman_table[i+16*4][0][1], 8, 4,
1830 &s->huffman_table[i+16*4][0][0], 8, 4, 0) < 0)
1835 init_vlc(&s->superblock_run_length_vlc, 6, 34,
1836 &superblock_run_length_vlc_table[0][1], 4, 2,
1837 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1839 init_vlc(&s->fragment_run_length_vlc, 5, 30,
1840 &fragment_run_length_vlc_table[0][1], 4, 2,
1841 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1843 init_vlc(&s->mode_code_vlc, 3, 8,
1844 &mode_code_vlc_table[0][1], 2, 1,
1845 &mode_code_vlc_table[0][0], 2, 1, 0);
1847 init_vlc(&s->motion_vector_vlc, 6, 63,
1848 &motion_vector_vlc_table[0][1], 2, 1,
1849 &motion_vector_vlc_table[0][0], 2, 1, 0);
1851 return allocate_tables(avctx);
1854 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1858 /// Release and shuffle frames after decode finishes
1859 static int update_frames(AVCodecContext *avctx)
1861 Vp3DecodeContext *s = avctx->priv_data;
1865 /* shuffle frames (last = current) */
1866 ff_thread_release_buffer(avctx, &s->last_frame);
1867 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
1872 ff_thread_release_buffer(avctx, &s->golden_frame);
1873 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
1877 ff_thread_release_buffer(avctx, &s->current_frame);
1881 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
1883 ff_thread_release_buffer(s->avctx, dst);
1884 if (src->f->data[0])
1885 return ff_thread_ref_frame(dst, src);
1889 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
1892 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
1893 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
1894 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
1899 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1901 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1902 int qps_changed = 0, i, err;
1904 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1906 if (!s1->current_frame.f->data[0]
1907 ||s->width != s1->width
1908 ||s->height!= s1->height) {
1915 // init tables if the first frame hasn't been decoded
1916 if (!s->current_frame.f->data[0]) {
1917 int y_fragment_count, c_fragment_count;
1919 err = allocate_tables(dst);
1922 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1923 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1924 memcpy(s->motion_val[0], s1->motion_val[0], y_fragment_count * sizeof(*s->motion_val[0]));
1925 memcpy(s->motion_val[1], s1->motion_val[1], c_fragment_count * sizeof(*s->motion_val[1]));
1928 // copy previous frame data
1929 if ((err = ref_frames(s, s1)) < 0)
1932 s->keyframe = s1->keyframe;
1934 // copy qscale data if necessary
1935 for (i = 0; i < 3; i++) {
1936 if (s->qps[i] != s1->qps[1]) {
1938 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
1942 if (s->qps[0] != s1->qps[0])
1943 memcpy(&s->bounding_values_array, &s1->bounding_values_array, sizeof(s->bounding_values_array));
1946 copy_fields(s, s1, qps, superblock_count);
1950 return update_frames(dst);
1953 static int vp3_decode_frame(AVCodecContext *avctx,
1954 void *data, int *got_frame,
1957 const uint8_t *buf = avpkt->data;
1958 int buf_size = avpkt->size;
1959 Vp3DecodeContext *s = avctx->priv_data;
1963 init_get_bits(&gb, buf, buf_size * 8);
1965 #if CONFIG_THEORA_DECODER
1966 if (s->theora && get_bits1(&gb))
1968 int type = get_bits(&gb, 7);
1969 skip_bits_long(&gb, 6*8); /* "theora" */
1971 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
1972 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
1973 return AVERROR_PATCHWELCOME;
1976 vp3_decode_end(avctx);
1977 ret = theora_decode_header(avctx, &gb);
1980 vp3_decode_end(avctx);
1982 ret = vp3_decode_init(avctx);
1984 } else if (type == 2) {
1985 ret = theora_decode_tables(avctx, &gb);
1987 vp3_decode_end(avctx);
1989 ret = vp3_decode_init(avctx);
1993 av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1998 s->keyframe = !get_bits1(&gb);
1999 if (!s->all_fragments) {
2000 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2005 for (i = 0; i < 3; i++)
2006 s->last_qps[i] = s->qps[i];
2010 s->qps[s->nqps++]= get_bits(&gb, 6);
2011 } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
2012 for (i = s->nqps; i < 3; i++)
2015 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2016 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2017 s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);
2019 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2020 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);
2022 if (s->qps[0] != s->last_qps[0])
2023 init_loop_filter(s);
2025 for (i = 0; i < s->nqps; i++)
2026 // reinit all dequantizers if the first one changed, because
2027 // the DC of the first quantizer must be used for all matrices
2028 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2029 init_dequantizer(s, i);
2031 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2034 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
2035 s->current_frame.f->key_frame = s->keyframe;
2036 if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2039 if (!s->edge_emu_buffer)
2040 s->edge_emu_buffer = av_malloc(9*FFABS(s->current_frame.f->linesize[0]));
2045 skip_bits(&gb, 4); /* width code */
2046 skip_bits(&gb, 4); /* height code */
2049 s->version = get_bits(&gb, 5);
2050 if (avctx->frame_number == 0)
2051 av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
2054 if (s->version || s->theora)
2057 av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
2058 skip_bits(&gb, 2); /* reserved? */
2061 if (!s->golden_frame.f->data[0]) {
2062 av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
2064 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2065 if (ff_thread_get_buffer(avctx, &s->golden_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2067 ff_thread_release_buffer(avctx, &s->last_frame);
2068 if ((ret = ff_thread_ref_frame(&s->last_frame, &s->golden_frame)) < 0)
2070 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2074 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2075 ff_thread_finish_setup(avctx);
2077 if (unpack_superblocks(s, &gb)){
2078 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2081 if (unpack_modes(s, &gb)){
2082 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2085 if (unpack_vectors(s, &gb)){
2086 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2089 if (unpack_block_qpis(s, &gb)){
2090 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2093 if (unpack_dct_coeffs(s, &gb)){
2094 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2098 for (i = 0; i < 3; i++) {
2099 int height = s->height >> (i && s->chroma_y_shift);
2100 if (s->flipped_image)
2101 s->data_offset[i] = 0;
2103 s->data_offset[i] = (height-1) * s->current_frame.f->linesize[i];
2106 s->last_slice_end = 0;
2107 for (i = 0; i < s->c_superblock_height; i++)
2110 // filter the last row
2111 for (i = 0; i < 3; i++) {
2112 int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;
2113 apply_loop_filter(s, i, row, row+1);
2115 vp3_draw_horiz_band(s, s->avctx->height);
2117 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2121 if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME)) {
2122 ret = update_frames(avctx);
2130 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2132 if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
2133 av_frame_unref(s->current_frame.f);
2138 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2140 Vp3DecodeContext *s = avctx->priv_data;
2142 if (get_bits1(gb)) {
2144 if (s->entries >= 32) { /* overflow */
2145 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2148 token = get_bits(gb, 5);
2149 av_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2150 s->hti, s->hbits, token, s->entries, s->huff_code_size);
2151 s->huffman_table[s->hti][token][0] = s->hbits;
2152 s->huffman_table[s->hti][token][1] = s->huff_code_size;
2156 if (s->huff_code_size >= 32) {/* overflow */
2157 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2160 s->huff_code_size++;
2162 if (read_huffman_tree(avctx, gb))
2165 if (read_huffman_tree(avctx, gb))
2168 s->huff_code_size--;
2173 static int vp3_init_thread_copy(AVCodecContext *avctx)
2175 Vp3DecodeContext *s = avctx->priv_data;
2177 s->superblock_coding = NULL;
2178 s->all_fragments = NULL;
2179 s->coded_fragment_list[0] = NULL;
2180 s->dct_tokens_base = NULL;
2181 s->superblock_fragments = NULL;
2182 s->macroblock_coding = NULL;
2183 s->motion_val[0] = NULL;
2184 s->motion_val[1] = NULL;
2185 s->edge_emu_buffer = NULL;
2187 return init_frames(s);
2190 #if CONFIG_THEORA_DECODER
2191 static const enum AVPixelFormat theora_pix_fmts[4] = {
2192 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2195 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2197 Vp3DecodeContext *s = avctx->priv_data;
2198 int visible_width, visible_height, colorspace;
2199 int offset_x = 0, offset_y = 0;
2201 AVRational fps, aspect;
2203 s->theora = get_bits_long(gb, 24);
2204 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2206 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
2207 /* but previous versions have the image flipped relative to vp3 */
2208 if (s->theora < 0x030200)
2210 s->flipped_image = 1;
2211 av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
2214 visible_width = s->width = get_bits(gb, 16) << 4;
2215 visible_height = s->height = get_bits(gb, 16) << 4;
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 && fps.den) {
2228 if (fps.num < 0 || fps.den < 0) {
2229 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2230 return AVERROR_INVALIDDATA;
2232 av_reduce(&avctx->time_base.num, &avctx->time_base.den,
2233 fps.den, fps.num, 1<<30);
2236 aspect.num = get_bits_long(gb, 24);
2237 aspect.den = get_bits_long(gb, 24);
2238 if (aspect.num && aspect.den) {
2239 av_reduce(&avctx->sample_aspect_ratio.num,
2240 &avctx->sample_aspect_ratio.den,
2241 aspect.num, aspect.den, 1<<30);
2244 if (s->theora < 0x030200)
2245 skip_bits(gb, 5); /* keyframe frequency force */
2246 colorspace = get_bits(gb, 8);
2247 skip_bits(gb, 24); /* bitrate */
2249 skip_bits(gb, 6); /* quality hint */
2251 if (s->theora >= 0x030200)
2253 skip_bits(gb, 5); /* keyframe frequency force */
2254 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2255 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2256 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2257 return AVERROR_INVALIDDATA;
2259 skip_bits(gb, 3); /* reserved */
2262 // align_get_bits(gb);
2264 if ( visible_width <= s->width && visible_width > s->width-16
2265 && visible_height <= s->height && visible_height > s->height-16
2266 && !offset_x && (offset_y == s->height - visible_height))
2267 ret = ff_set_dimensions(avctx, visible_width, visible_height);
2269 ret = ff_set_dimensions(avctx, s->width, s->height);
2273 if (colorspace == 1) {
2274 avctx->color_primaries = AVCOL_PRI_BT470M;
2275 } else if (colorspace == 2) {
2276 avctx->color_primaries = AVCOL_PRI_BT470BG;
2278 if (colorspace == 1 || colorspace == 2) {
2279 avctx->colorspace = AVCOL_SPC_BT470BG;
2280 avctx->color_trc = AVCOL_TRC_BT709;
2286 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2288 Vp3DecodeContext *s = avctx->priv_data;
2289 int i, n, matrices, inter, plane;
2291 if (s->theora >= 0x030200) {
2292 n = get_bits(gb, 3);
2293 /* loop filter limit values table */
2295 for (i = 0; i < 64; i++)
2296 s->filter_limit_values[i] = get_bits(gb, n);
2299 if (s->theora >= 0x030200)
2300 n = get_bits(gb, 4) + 1;
2303 /* quality threshold table */
2304 for (i = 0; i < 64; i++)
2305 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2307 if (s->theora >= 0x030200)
2308 n = get_bits(gb, 4) + 1;
2311 /* dc scale factor table */
2312 for (i = 0; i < 64; i++)
2313 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2315 if (s->theora >= 0x030200)
2316 matrices = get_bits(gb, 9) + 1;
2321 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2325 for(n=0; n<matrices; n++){
2326 for (i = 0; i < 64; i++)
2327 s->base_matrix[n][i]= get_bits(gb, 8);
2330 for (inter = 0; inter <= 1; inter++) {
2331 for (plane = 0; plane <= 2; plane++) {
2333 if (inter || plane > 0)
2334 newqr = get_bits1(gb);
2337 if(inter && get_bits1(gb)){
2341 qtj= (3*inter + plane - 1) / 3;
2342 plj= (plane + 2) % 3;
2344 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2345 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2346 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2352 i= get_bits(gb, av_log2(matrices-1)+1);
2354 av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2357 s->qr_base[inter][plane][qri]= i;
2360 i = get_bits(gb, av_log2(63-qi)+1) + 1;
2361 s->qr_size[inter][plane][qri++]= i;
2366 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2369 s->qr_count[inter][plane]= qri;
2374 /* Huffman tables */
2375 for (s->hti = 0; s->hti < 80; s->hti++) {
2377 s->huff_code_size = 1;
2378 if (!get_bits1(gb)) {
2380 if(read_huffman_tree(avctx, gb))
2383 if(read_huffman_tree(avctx, gb))
2388 s->theora_tables = 1;
2393 static av_cold int theora_decode_init(AVCodecContext *avctx)
2395 Vp3DecodeContext *s = avctx->priv_data;
2398 uint8_t *header_start[3];
2402 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2406 if (!avctx->extradata_size)
2408 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2412 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2413 42, header_start, header_len) < 0) {
2414 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2419 if (header_len[i] <= 0)
2421 init_get_bits(&gb, header_start[i], header_len[i] * 8);
2423 ptype = get_bits(&gb, 8);
2425 if (!(ptype & 0x80))
2427 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2431 // FIXME: Check for this as well.
2432 skip_bits_long(&gb, 6*8); /* "theora" */
2437 if (theora_decode_header(avctx, &gb) < 0)
2441 // FIXME: is this needed? it breaks sometimes
2442 // theora_decode_comments(avctx, gb);
2445 if (theora_decode_tables(avctx, &gb))
2449 av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2452 if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2453 av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2454 if (s->theora < 0x030200)
2458 return vp3_decode_init(avctx);
2461 AVCodec ff_theora_decoder = {
2463 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2464 .type = AVMEDIA_TYPE_VIDEO,
2465 .id = AV_CODEC_ID_THEORA,
2466 .priv_data_size = sizeof(Vp3DecodeContext),
2467 .init = theora_decode_init,
2468 .close = vp3_decode_end,
2469 .decode = vp3_decode_frame,
2470 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2471 CODEC_CAP_FRAME_THREADS,
2472 .flush = vp3_decode_flush,
2473 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2474 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
2478 AVCodec ff_vp3_decoder = {
2480 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2481 .type = AVMEDIA_TYPE_VIDEO,
2482 .id = AV_CODEC_ID_VP3,
2483 .priv_data_size = sizeof(Vp3DecodeContext),
2484 .init = vp3_decode_init,
2485 .close = vp3_decode_end,
2486 .decode = vp3_decode_frame,
2487 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2488 CODEC_CAP_FRAME_THREADS,
2489 .flush = vp3_decode_flush,
2490 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
2491 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),