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
22 * @file libavcodec/vp3.c
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
43 #define FRAGMENT_PIXELS 8
45 static av_cold int vp3_decode_end(AVCodecContext *avctx);
47 //FIXME split things out into their own arrays
48 typedef struct Vp3Fragment {
50 uint8_t coding_method;
56 #define SB_NOT_CODED 0
57 #define SB_PARTIALLY_CODED 1
58 #define SB_FULLY_CODED 2
60 // This is the maximum length of a single long bit run that can be encoded
61 // for superblock coding or block qps. Theora special-cases this to read a
62 // bit instead of flipping the current bit to allow for runs longer than 4129.
63 #define MAXIMUM_LONG_BIT_RUN 4129
65 #define MODE_INTER_NO_MV 0
67 #define MODE_INTER_PLUS_MV 2
68 #define MODE_INTER_LAST_MV 3
69 #define MODE_INTER_PRIOR_LAST 4
70 #define MODE_USING_GOLDEN 5
71 #define MODE_GOLDEN_MV 6
72 #define MODE_INTER_FOURMV 7
73 #define CODING_MODE_COUNT 8
75 /* special internal mode */
78 /* There are 6 preset schemes, plus a free-form scheme */
79 static const int ModeAlphabet[6][CODING_MODE_COUNT] =
81 /* scheme 1: Last motion vector dominates */
82 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
83 MODE_INTER_PLUS_MV, MODE_INTER_NO_MV,
84 MODE_INTRA, MODE_USING_GOLDEN,
85 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
88 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
89 MODE_INTER_NO_MV, MODE_INTER_PLUS_MV,
90 MODE_INTRA, MODE_USING_GOLDEN,
91 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
94 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
95 MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
96 MODE_INTRA, MODE_USING_GOLDEN,
97 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
100 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
101 MODE_INTER_NO_MV, MODE_INTER_PRIOR_LAST,
102 MODE_INTRA, MODE_USING_GOLDEN,
103 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
105 /* scheme 5: No motion vector dominates */
106 { MODE_INTER_NO_MV, MODE_INTER_LAST_MV,
107 MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
108 MODE_INTRA, MODE_USING_GOLDEN,
109 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
112 { MODE_INTER_NO_MV, MODE_USING_GOLDEN,
113 MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
114 MODE_INTER_PLUS_MV, MODE_INTRA,
115 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
119 static const uint8_t hilbert_offset[16][2] = {
120 {0,0}, {1,0}, {1,1}, {0,1},
121 {0,2}, {0,3}, {1,3}, {1,2},
122 {2,2}, {2,3}, {3,3}, {3,2},
123 {3,1}, {2,1}, {2,0}, {3,0}
126 #define MIN_DEQUANT_VAL 2
128 typedef struct Vp3DecodeContext {
129 AVCodecContext *avctx;
130 int theora, theora_tables;
133 AVFrame golden_frame;
135 AVFrame current_frame;
145 int superblock_count;
146 int y_superblock_width;
147 int y_superblock_height;
148 int y_superblock_count;
149 int c_superblock_width;
150 int c_superblock_height;
151 int c_superblock_count;
152 int u_superblock_start;
153 int v_superblock_start;
154 unsigned char *superblock_coding;
156 int macroblock_count;
157 int macroblock_width;
158 int macroblock_height;
164 Vp3Fragment *all_fragments;
165 int fragment_start[3];
171 uint16_t coded_dc_scale_factor[64];
172 uint32_t coded_ac_scale_factor[64];
173 uint8_t base_matrix[384][64];
174 uint8_t qr_count[2][3];
175 uint8_t qr_size [2][3][64];
176 uint16_t qr_base[2][3][64];
179 * This is a list of all tokens in bitstream order. Reordering takes place
180 * by pulling from each level during IDCT. As a consequence, IDCT must be
181 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
182 * otherwise. The 32 different tokens with up to 12 bits of extradata are
183 * collapsed into 3 types, packed as follows:
184 * (from the low to high bits)
186 * 2 bits: type (0,1,2)
187 * 0: EOB run, 14 bits for run length (12 needed)
188 * 1: zero run, 7 bits for run length
189 * 7 bits for the next coefficient (3 needed)
190 * 2: coefficient, 14 bits (11 needed)
192 * Coefficients are signed, so are packed in the highest bits for automatic
195 int16_t *dct_tokens[3][64];
196 int16_t *dct_tokens_base;
197 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
198 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) << 9) + ((zero_run) << 2) + 1)
199 #define TOKEN_COEFF(coeff) (((coeff) << 2) + 2)
202 * number of blocks that contain DCT coefficients at the given level or higher
204 int num_coded_frags[3][64];
205 int total_num_coded_frags;
207 /* this is a list of indexes into the all_fragments array indicating
208 * which of the fragments are coded */
209 int *coded_fragment_list[3];
217 VLC superblock_run_length_vlc;
218 VLC fragment_run_length_vlc;
220 VLC motion_vector_vlc;
222 /* these arrays need to be on 16-byte boundaries since SSE2 operations
224 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; //<qmat[qpi][is_inter][plane]
226 /* This table contains superblock_count * 16 entries. Each set of 16
227 * numbers corresponds to the fragment indexes 0..15 of the superblock.
228 * An entry will be -1 to indicate that no entry corresponds to that
230 int *superblock_fragments;
232 /* This is an array that indicates how a particular macroblock
234 unsigned char *macroblock_coding;
236 uint8_t edge_emu_buffer[9*2048]; //FIXME dynamic alloc
237 int8_t qscale_table[2048]; //FIXME dynamic alloc (width+15)/16
244 uint16_t huffman_table[80][32][2];
246 uint8_t filter_limit_values[64];
247 DECLARE_ALIGNED(8, int, bounding_values_array)[256+2];
250 /************************************************************************
251 * VP3 specific functions
252 ************************************************************************/
255 * This function sets up all of the various blocks mappings:
256 * superblocks <-> fragments, macroblocks <-> fragments,
257 * superblocks <-> macroblocks
259 * Returns 0 is successful; returns 1 if *anything* went wrong.
261 static int init_block_mapping(Vp3DecodeContext *s)
263 int sb_x, sb_y, plane;
266 for (plane = 0; plane < 3; plane++) {
267 int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
268 int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
269 int frag_width = s->fragment_width >> !!plane;
270 int frag_height = s->fragment_height >> !!plane;
272 for (sb_y = 0; sb_y < sb_height; sb_y++)
273 for (sb_x = 0; sb_x < sb_width; sb_x++)
274 for (i = 0; i < 16; i++) {
275 x = 4*sb_x + hilbert_offset[i][0];
276 y = 4*sb_y + hilbert_offset[i][1];
278 if (x < frag_width && y < frag_height)
279 s->superblock_fragments[j++] = s->fragment_start[plane] + y*frag_width + x;
281 s->superblock_fragments[j++] = -1;
285 return 0; /* successful path out */
289 * This function wipes out all of the fragment data.
291 static void init_frame(Vp3DecodeContext *s, GetBitContext *gb)
295 /* zero out all of the fragment information */
296 for (i = 0; i < s->fragment_count; i++) {
297 s->all_fragments[i].motion_x = 0;
298 s->all_fragments[i].motion_y = 0;
299 s->all_fragments[i].dc = 0;
300 s->all_fragments[i].qpi = 0;
305 * This function sets up the dequantization tables used for a particular
308 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
310 int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
311 int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
312 int i, plane, inter, qri, bmi, bmj, qistart;
314 for(inter=0; inter<2; inter++){
315 for(plane=0; plane<3; plane++){
317 for(qri=0; qri<s->qr_count[inter][plane]; qri++){
318 sum+= s->qr_size[inter][plane][qri];
319 if(s->qps[qpi] <= sum)
322 qistart= sum - s->qr_size[inter][plane][qri];
323 bmi= s->qr_base[inter][plane][qri ];
324 bmj= s->qr_base[inter][plane][qri+1];
326 int coeff= ( 2*(sum -s->qps[qpi])*s->base_matrix[bmi][i]
327 - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
328 + s->qr_size[inter][plane][qri])
329 / (2*s->qr_size[inter][plane][qri]);
331 int qmin= 8<<(inter + !i);
332 int qscale= i ? ac_scale_factor : dc_scale_factor;
334 s->qmat[qpi][inter][plane][s->dsp.idct_permutation[i]]= av_clip((qscale * coeff)/100 * 4, qmin, 4096);
336 // all DC coefficients use the same quant so as not to interfere with DC prediction
337 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
341 memset(s->qscale_table, (FFMAX(s->qmat[0][0][0][1], s->qmat[0][0][1][1])+8)/16, 512); //FIXME finetune
345 * This function initializes the loop filter boundary limits if the frame's
346 * quality index is different from the previous frame's.
348 * The filter_limit_values may not be larger than 127.
350 static void init_loop_filter(Vp3DecodeContext *s)
352 int *bounding_values= s->bounding_values_array+127;
357 filter_limit = s->filter_limit_values[s->qps[0]];
359 /* set up the bounding values */
360 memset(s->bounding_values_array, 0, 256 * sizeof(int));
361 for (x = 0; x < filter_limit; x++) {
362 bounding_values[-x] = -x;
363 bounding_values[x] = x;
365 for (x = value = filter_limit; x < 128 && value; x++, value--) {
366 bounding_values[ x] = value;
367 bounding_values[-x] = -value;
370 bounding_values[128] = value;
371 bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
375 * This function unpacks all of the superblock/macroblock/fragment coding
376 * information from the bitstream.
378 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
380 int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };
382 int current_superblock = 0;
384 int num_partial_superblocks = 0;
387 int current_fragment;
391 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
395 /* unpack the list of partially-coded superblocks */
397 while (current_superblock < s->superblock_count) {
398 current_run = get_vlc2(gb,
399 s->superblock_run_length_vlc.table, 6, 2) + 1;
400 if (current_run == 34)
401 current_run += get_bits(gb, 12);
403 if (current_superblock + current_run > s->superblock_count) {
404 av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");
408 memset(s->superblock_coding + current_superblock, bit, current_run);
410 current_superblock += current_run;
412 num_partial_superblocks += current_run;
414 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
420 /* unpack the list of fully coded superblocks if any of the blocks were
421 * not marked as partially coded in the previous step */
422 if (num_partial_superblocks < s->superblock_count) {
423 int superblocks_decoded = 0;
425 current_superblock = 0;
427 while (superblocks_decoded < s->superblock_count - num_partial_superblocks) {
428 current_run = get_vlc2(gb,
429 s->superblock_run_length_vlc.table, 6, 2) + 1;
430 if (current_run == 34)
431 current_run += get_bits(gb, 12);
433 for (j = 0; j < current_run; current_superblock++) {
434 if (current_superblock >= s->superblock_count) {
435 av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");
439 /* skip any superblocks already marked as partially coded */
440 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
441 s->superblock_coding[current_superblock] = 2*bit;
445 superblocks_decoded += current_run;
447 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
454 /* if there were partial blocks, initialize bitstream for
455 * unpacking fragment codings */
456 if (num_partial_superblocks) {
460 /* toggle the bit because as soon as the first run length is
461 * fetched the bit will be toggled again */
466 /* figure out which fragments are coded; iterate through each
467 * superblock (all planes) */
468 s->total_num_coded_frags = 0;
469 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
471 for (plane = 0; plane < 3; plane++) {
472 int sb_start = superblock_starts[plane];
473 int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
474 int num_coded_frags = 0;
476 for (i = sb_start; i < sb_end; i++) {
478 /* iterate through all 16 fragments in a superblock */
479 for (j = 0; j < 16; j++) {
481 /* if the fragment is in bounds, check its coding status */
482 current_fragment = s->superblock_fragments[i * 16 + j];
483 if (current_fragment >= s->fragment_count) {
484 av_log(s->avctx, AV_LOG_ERROR, " vp3:unpack_superblocks(): bad fragment number (%d >= %d)\n",
485 current_fragment, s->fragment_count);
488 if (current_fragment != -1) {
489 int coded = s->superblock_coding[i];
491 if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
493 /* fragment may or may not be coded; this is the case
494 * that cares about the fragment coding runs */
495 if (current_run-- == 0) {
497 current_run = get_vlc2(gb,
498 s->fragment_run_length_vlc.table, 5, 2);
504 /* default mode; actual mode will be decoded in
506 s->all_fragments[current_fragment].coding_method =
508 s->coded_fragment_list[plane][num_coded_frags++] =
511 /* not coded; copy this fragment from the prior frame */
512 s->all_fragments[current_fragment].coding_method =
518 s->total_num_coded_frags += num_coded_frags;
519 for (i = 0; i < 64; i++)
520 s->num_coded_frags[plane][i] = num_coded_frags;
522 s->coded_fragment_list[plane+1] = s->coded_fragment_list[plane] + num_coded_frags;
528 * This function unpacks all the coding mode data for individual macroblocks
529 * from the bitstream.
531 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
533 int i, j, k, sb_x, sb_y;
535 int current_macroblock;
536 int current_fragment;
538 int custom_mode_alphabet[CODING_MODE_COUNT];
542 for (i = 0; i < s->fragment_count; i++)
543 s->all_fragments[i].coding_method = MODE_INTRA;
547 /* fetch the mode coding scheme for this frame */
548 scheme = get_bits(gb, 3);
550 /* is it a custom coding scheme? */
552 for (i = 0; i < 8; i++)
553 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
554 for (i = 0; i < 8; i++)
555 custom_mode_alphabet[get_bits(gb, 3)] = i;
556 alphabet = custom_mode_alphabet;
558 alphabet = ModeAlphabet[scheme-1];
560 /* iterate through all of the macroblocks that contain 1 or more
562 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
563 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
565 for (j = 0; j < 4; j++) {
566 int mb_x = 2*sb_x + (j>>1);
567 int mb_y = 2*sb_y + (((j>>1)+j)&1);
568 current_macroblock = mb_y * s->macroblock_width + mb_x;
570 if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height)
573 #define BLOCK_X (2*mb_x + (k&1))
574 #define BLOCK_Y (2*mb_y + (k>>1))
575 /* coding modes are only stored if the macroblock has at least one
576 * luma block coded, otherwise it must be INTER_NO_MV */
577 for (k = 0; k < 4; k++) {
578 current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;
579 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
583 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
587 /* mode 7 means get 3 bits for each coding mode */
589 coding_mode = get_bits(gb, 3);
591 coding_mode = alphabet
592 [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
594 s->macroblock_coding[current_macroblock] = coding_mode;
595 for (k = 0; k < 4; k++) {
597 BLOCK_Y*s->fragment_width + BLOCK_X;
598 if (s->all_fragments[current_fragment].coding_method !=
600 s->all_fragments[current_fragment].coding_method =
603 for (k = 0; k < 2; k++) {
604 current_fragment = s->fragment_start[k+1] +
605 mb_y*(s->fragment_width>>1) + mb_x;
606 if (s->all_fragments[current_fragment].coding_method !=
608 s->all_fragments[current_fragment].coding_method =
620 * This function unpacks all the motion vectors for the individual
621 * macroblocks from the bitstream.
623 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
625 int j, k, sb_x, sb_y;
629 int last_motion_x = 0;
630 int last_motion_y = 0;
631 int prior_last_motion_x = 0;
632 int prior_last_motion_y = 0;
633 int current_macroblock;
634 int current_fragment;
639 memset(motion_x, 0, 6 * sizeof(int));
640 memset(motion_y, 0, 6 * sizeof(int));
642 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
643 coding_mode = get_bits1(gb);
645 /* iterate through all of the macroblocks that contain 1 or more
647 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
648 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
650 for (j = 0; j < 4; j++) {
651 int mb_x = 2*sb_x + (j>>1);
652 int mb_y = 2*sb_y + (((j>>1)+j)&1);
653 current_macroblock = mb_y * s->macroblock_width + mb_x;
655 if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
656 (s->macroblock_coding[current_macroblock] == MODE_COPY))
659 switch (s->macroblock_coding[current_macroblock]) {
661 case MODE_INTER_PLUS_MV:
663 /* all 6 fragments use the same motion vector */
664 if (coding_mode == 0) {
665 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
666 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
668 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
669 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
672 /* vector maintenance, only on MODE_INTER_PLUS_MV */
673 if (s->macroblock_coding[current_macroblock] ==
674 MODE_INTER_PLUS_MV) {
675 prior_last_motion_x = last_motion_x;
676 prior_last_motion_y = last_motion_y;
677 last_motion_x = motion_x[0];
678 last_motion_y = motion_y[0];
682 case MODE_INTER_FOURMV:
683 /* vector maintenance */
684 prior_last_motion_x = last_motion_x;
685 prior_last_motion_y = last_motion_y;
687 /* fetch 4 vectors from the bitstream, one for each
688 * Y fragment, then average for the C fragment vectors */
689 motion_x[4] = motion_y[4] = 0;
690 for (k = 0; k < 4; k++) {
691 current_fragment = BLOCK_Y*s->fragment_width + BLOCK_X;
692 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
693 if (coding_mode == 0) {
694 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
695 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
697 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
698 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
700 last_motion_x = motion_x[k];
701 last_motion_y = motion_y[k];
706 motion_x[4] += motion_x[k];
707 motion_y[4] += motion_y[k];
711 motion_x[4]= RSHIFT(motion_x[4], 2);
713 motion_y[4]= RSHIFT(motion_y[4], 2);
716 case MODE_INTER_LAST_MV:
717 /* all 6 fragments use the last motion vector */
718 motion_x[0] = last_motion_x;
719 motion_y[0] = last_motion_y;
721 /* no vector maintenance (last vector remains the
725 case MODE_INTER_PRIOR_LAST:
726 /* all 6 fragments use the motion vector prior to the
727 * last motion vector */
728 motion_x[0] = prior_last_motion_x;
729 motion_y[0] = prior_last_motion_y;
731 /* vector maintenance */
732 prior_last_motion_x = last_motion_x;
733 prior_last_motion_y = last_motion_y;
734 last_motion_x = motion_x[0];
735 last_motion_y = motion_y[0];
739 /* covers intra, inter without MV, golden without MV */
743 /* no vector maintenance */
747 /* assign the motion vectors to the correct fragments */
748 for (k = 0; k < 4; k++) {
750 BLOCK_Y*s->fragment_width + BLOCK_X;
751 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
752 s->all_fragments[current_fragment].motion_x = motion_x[k];
753 s->all_fragments[current_fragment].motion_y = motion_y[k];
755 s->all_fragments[current_fragment].motion_x = motion_x[0];
756 s->all_fragments[current_fragment].motion_y = motion_y[0];
759 for (k = 0; k < 2; k++) {
760 current_fragment = s->fragment_start[k+1] +
761 mb_y*(s->fragment_width>>1) + mb_x;
762 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
763 s->all_fragments[current_fragment].motion_x = motion_x[k+4];
764 s->all_fragments[current_fragment].motion_y = motion_y[k+4];
766 s->all_fragments[current_fragment].motion_x = motion_x[0];
767 s->all_fragments[current_fragment].motion_y = motion_y[0];
777 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
779 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
780 int num_blocks = s->total_num_coded_frags;
782 for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
783 i = blocks_decoded = num_blocks_at_qpi = 0;
788 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
789 if (run_length == 34)
790 run_length += get_bits(gb, 12);
791 blocks_decoded += run_length;
794 num_blocks_at_qpi += run_length;
796 for (j = 0; j < run_length; i++) {
797 if (i >= s->total_num_coded_frags)
800 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
801 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
806 if (run_length == MAXIMUM_LONG_BIT_RUN)
810 } while (blocks_decoded < num_blocks);
812 num_blocks -= num_blocks_at_qpi;
819 * This function is called by unpack_dct_coeffs() to extract the VLCs from
820 * the bitstream. The VLCs encode tokens which are used to unpack DCT
821 * data. This function unpacks all the VLCs for either the Y plane or both
822 * C planes, and is called for DC coefficients or different AC coefficient
823 * levels (since different coefficient types require different VLC tables.
825 * This function returns a residual eob run. E.g, if a particular token gave
826 * instructions to EOB the next 5 fragments and there were only 2 fragments
827 * left in the current fragment range, 3 would be returned so that it could
828 * be passed into the next call to this same function.
830 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
831 VLC *table, int coeff_index,
842 int num_coeffs = s->num_coded_frags[plane][coeff_index];
843 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
845 /* local references to structure members to avoid repeated deferences */
846 int *coded_fragment_list = s->coded_fragment_list[plane];
847 Vp3Fragment *all_fragments = s->all_fragments;
848 VLC_TYPE (*vlc_table)[2] = table->table;
851 av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
853 if (eob_run > num_coeffs) {
854 coeff_i = blocks_ended = num_coeffs;
855 eob_run -= num_coeffs;
857 coeff_i = blocks_ended = eob_run;
861 // insert fake EOB token to cover the split between planes or zzi
863 dct_tokens[j++] = blocks_ended << 2;
865 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
866 /* decode a VLC into a token */
867 token = get_vlc2(gb, vlc_table, 5, 3);
868 /* use the token to get a zero run, a coefficient, and an eob run */
870 eob_run = eob_run_base[token];
871 if (eob_run_get_bits[token])
872 eob_run += get_bits(gb, eob_run_get_bits[token]);
874 // record only the number of blocks ended in this plane,
875 // any spill will be recorded in the next plane.
876 if (eob_run > num_coeffs - coeff_i) {
877 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
878 blocks_ended += num_coeffs - coeff_i;
879 eob_run -= num_coeffs - coeff_i;
880 coeff_i = num_coeffs;
882 dct_tokens[j++] = TOKEN_EOB(eob_run);
883 blocks_ended += eob_run;
888 bits_to_get = coeff_get_bits[token];
890 bits_to_get = get_bits(gb, bits_to_get);
891 coeff = coeff_tables[token][bits_to_get];
893 zero_run = zero_run_base[token];
894 if (zero_run_get_bits[token])
895 zero_run += get_bits(gb, zero_run_get_bits[token]);
898 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
900 // Save DC into the fragment structure. DC prediction is
901 // done in raster order, so the actual DC can't be in with
902 // other tokens. We still need the token in dct_tokens[]
903 // however, or else the structure collapses on itself.
905 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
907 dct_tokens[j++] = TOKEN_COEFF(coeff);
910 if (coeff_index + zero_run > 64) {
911 av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
912 " %d coeffs left\n", zero_run, 64-coeff_index);
913 zero_run = 64 - coeff_index;
916 // zero runs code multiple coefficients,
917 // so don't try to decode coeffs for those higher levels
918 for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
919 s->num_coded_frags[plane][i]--;
924 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
925 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
927 // decrement the number of blocks that have higher coeffecients for each
928 // EOB run at this level
930 for (i = coeff_index+1; i < 64; i++)
931 s->num_coded_frags[plane][i] -= blocks_ended;
933 // setup the next buffer
935 s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
936 else if (coeff_index < 63)
937 s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
942 static void reverse_dc_prediction(Vp3DecodeContext *s,
945 int fragment_height);
947 * This function unpacks all of the DCT coefficient data from the
950 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
957 int residual_eob_run = 0;
961 s->dct_tokens[0][0] = s->dct_tokens_base;
963 /* fetch the DC table indexes */
964 dc_y_table = get_bits(gb, 4);
965 dc_c_table = get_bits(gb, 4);
967 /* unpack the Y plane DC coefficients */
968 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
969 0, residual_eob_run);
971 /* reverse prediction of the Y-plane DC coefficients */
972 reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);
974 /* unpack the C plane DC coefficients */
975 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
976 1, residual_eob_run);
977 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
978 2, residual_eob_run);
980 /* reverse prediction of the C-plane DC coefficients */
981 if (!(s->avctx->flags & CODEC_FLAG_GRAY))
983 reverse_dc_prediction(s, s->fragment_start[1],
984 s->fragment_width / 2, s->fragment_height / 2);
985 reverse_dc_prediction(s, s->fragment_start[2],
986 s->fragment_width / 2, s->fragment_height / 2);
989 /* fetch the AC table indexes */
990 ac_y_table = get_bits(gb, 4);
991 ac_c_table = get_bits(gb, 4);
993 /* build tables of AC VLC tables */
994 for (i = 1; i <= 5; i++) {
995 y_tables[i] = &s->ac_vlc_1[ac_y_table];
996 c_tables[i] = &s->ac_vlc_1[ac_c_table];
998 for (i = 6; i <= 14; i++) {
999 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1000 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1002 for (i = 15; i <= 27; i++) {
1003 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1004 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1006 for (i = 28; i <= 63; i++) {
1007 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1008 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1011 /* decode all AC coefficents */
1012 for (i = 1; i <= 63; i++) {
1013 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1014 0, residual_eob_run);
1016 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1017 1, residual_eob_run);
1018 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1019 2, residual_eob_run);
1026 * This function reverses the DC prediction for each coded fragment in
1027 * the frame. Much of this function is adapted directly from the original
1030 #define COMPATIBLE_FRAME(x) \
1031 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1032 #define DC_COEFF(u) s->all_fragments[u].dc
1034 static void reverse_dc_prediction(Vp3DecodeContext *s,
1037 int fragment_height)
1046 int i = first_fragment;
1050 /* DC values for the left, up-left, up, and up-right fragments */
1051 int vl, vul, vu, vur;
1053 /* indexes for the left, up-left, up, and up-right fragments */
1057 * The 6 fields mean:
1058 * 0: up-left multiplier
1060 * 2: up-right multiplier
1061 * 3: left multiplier
1063 static const int predictor_transform[16][4] = {
1065 { 0, 0, 0,128}, // PL
1066 { 0, 0,128, 0}, // PUR
1067 { 0, 0, 53, 75}, // PUR|PL
1068 { 0,128, 0, 0}, // PU
1069 { 0, 64, 0, 64}, // PU|PL
1070 { 0,128, 0, 0}, // PU|PUR
1071 { 0, 0, 53, 75}, // PU|PUR|PL
1072 {128, 0, 0, 0}, // PUL
1073 { 0, 0, 0,128}, // PUL|PL
1074 { 64, 0, 64, 0}, // PUL|PUR
1075 { 0, 0, 53, 75}, // PUL|PUR|PL
1076 { 0,128, 0, 0}, // PUL|PU
1077 {-104,116, 0,116}, // PUL|PU|PL
1078 { 24, 80, 24, 0}, // PUL|PU|PUR
1079 {-104,116, 0,116} // PUL|PU|PUR|PL
1082 /* This table shows which types of blocks can use other blocks for
1083 * prediction. For example, INTRA is the only mode in this table to
1084 * have a frame number of 0. That means INTRA blocks can only predict
1085 * from other INTRA blocks. There are 2 golden frame coding types;
1086 * blocks encoding in these modes can only predict from other blocks
1087 * that were encoded with these 1 of these 2 modes. */
1088 static const unsigned char compatible_frame[9] = {
1089 1, /* MODE_INTER_NO_MV */
1091 1, /* MODE_INTER_PLUS_MV */
1092 1, /* MODE_INTER_LAST_MV */
1093 1, /* MODE_INTER_PRIOR_MV */
1094 2, /* MODE_USING_GOLDEN */
1095 2, /* MODE_GOLDEN_MV */
1096 1, /* MODE_INTER_FOUR_MV */
1099 int current_frame_type;
1101 /* there is a last DC predictor for each of the 3 frame types */
1106 vul = vu = vur = vl = 0;
1107 last_dc[0] = last_dc[1] = last_dc[2] = 0;
1109 /* for each fragment row... */
1110 for (y = 0; y < fragment_height; y++) {
1112 /* for each fragment in a row... */
1113 for (x = 0; x < fragment_width; x++, i++) {
1115 /* reverse prediction if this block was coded */
1116 if (s->all_fragments[i].coding_method != MODE_COPY) {
1118 current_frame_type =
1119 compatible_frame[s->all_fragments[i].coding_method];
1125 if(COMPATIBLE_FRAME(l))
1129 u= i-fragment_width;
1131 if(COMPATIBLE_FRAME(u))
1134 ul= i-fragment_width-1;
1136 if(COMPATIBLE_FRAME(ul))
1139 if(x + 1 < fragment_width){
1140 ur= i-fragment_width+1;
1142 if(COMPATIBLE_FRAME(ur))
1147 if (transform == 0) {
1149 /* if there were no fragments to predict from, use last
1151 predicted_dc = last_dc[current_frame_type];
1154 /* apply the appropriate predictor transform */
1156 (predictor_transform[transform][0] * vul) +
1157 (predictor_transform[transform][1] * vu) +
1158 (predictor_transform[transform][2] * vur) +
1159 (predictor_transform[transform][3] * vl);
1161 predicted_dc /= 128;
1163 /* check for outranging on the [ul u l] and
1164 * [ul u ur l] predictors */
1165 if ((transform == 15) || (transform == 13)) {
1166 if (FFABS(predicted_dc - vu) > 128)
1168 else if (FFABS(predicted_dc - vl) > 128)
1170 else if (FFABS(predicted_dc - vul) > 128)
1175 /* at long last, apply the predictor */
1176 DC_COEFF(i) += predicted_dc;
1178 last_dc[current_frame_type] = DC_COEFF(i);
1184 static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1187 int *bounding_values= s->bounding_values_array+127;
1189 int width = s->fragment_width >> !!plane;
1190 int height = s->fragment_height >> !!plane;
1191 int fragment = s->fragment_start [plane] + ystart * width;
1192 int stride = s->current_frame.linesize[plane];
1193 uint8_t *plane_data = s->current_frame.data [plane];
1194 if (!s->flipped_image) stride = -stride;
1195 plane_data += s->data_offset[plane] + 8*ystart*stride;
1197 for (y = ystart; y < yend; y++) {
1199 for (x = 0; x < width; x++) {
1200 /* This code basically just deblocks on the edges of coded blocks.
1201 * However, it has to be much more complicated because of the
1202 * braindamaged deblock ordering used in VP3/Theora. Order matters
1203 * because some pixels get filtered twice. */
1204 if( s->all_fragments[fragment].coding_method != MODE_COPY )
1206 /* do not perform left edge filter for left columns frags */
1208 s->dsp.vp3_h_loop_filter(
1210 stride, bounding_values);
1213 /* do not perform top edge filter for top row fragments */
1215 s->dsp.vp3_v_loop_filter(
1217 stride, bounding_values);
1220 /* do not perform right edge filter for right column
1221 * fragments or if right fragment neighbor is also coded
1222 * in this frame (it will be filtered in next iteration) */
1223 if ((x < width - 1) &&
1224 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1225 s->dsp.vp3_h_loop_filter(
1226 plane_data + 8*x + 8,
1227 stride, bounding_values);
1230 /* do not perform bottom edge filter for bottom row
1231 * fragments or if bottom fragment neighbor is also coded
1232 * in this frame (it will be filtered in the next row) */
1233 if ((y < height - 1) &&
1234 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1235 s->dsp.vp3_v_loop_filter(
1236 plane_data + 8*x + 8*stride,
1237 stride, bounding_values);
1243 plane_data += 8*stride;
1248 * Pulls DCT tokens from the 64 levels to decode and dequant the coefficients
1249 * for the next block in coding order
1251 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1252 int plane, int inter, DCTELEM block[64])
1254 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1255 uint8_t *perm = s->scantable.permutated;
1259 int token = *s->dct_tokens[plane][i];
1260 switch (token & 3) {
1262 if (--token < 4) // 0-3 are token types, so the EOB run must now be 0
1263 s->dct_tokens[plane][i]++;
1265 *s->dct_tokens[plane][i] = token & ~3;
1268 s->dct_tokens[plane][i]++;
1269 i += (token >> 2) & 0x7f;
1270 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1274 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1275 s->dct_tokens[plane][i++]++;
1278 av_log(s->avctx, AV_LOG_ERROR, "internal: invalid token type\n");
1283 // the actual DC+prediction is in the fragment structure
1284 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1289 * called when all pixels up to row y are complete
1291 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1296 if(s->avctx->draw_horiz_band==NULL)
1299 h= y - s->last_slice_end;
1302 if (!s->flipped_image) {
1304 h -= s->height - s->avctx->height; // account for non-mod16
1305 y = s->height - y - h;
1309 offset[0] = s->current_frame.linesize[0]*y;
1310 offset[1] = s->current_frame.linesize[1]*cy;
1311 offset[2] = s->current_frame.linesize[2]*cy;
1315 s->avctx->draw_horiz_band(s->avctx, &s->current_frame, offset, y, 3, h);
1316 s->last_slice_end= y + h;
1320 * Perform the final rendering for a particular slice of data.
1321 * The slice number ranges from 0..(c_superblock_height - 1).
1323 static void render_slice(Vp3DecodeContext *s, int slice)
1326 LOCAL_ALIGNED_16(DCTELEM, block, [64]);
1327 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1328 int motion_halfpel_index;
1329 uint8_t *motion_source;
1330 int plane, first_pixel;
1332 if (slice >= s->c_superblock_height)
1335 for (plane = 0; plane < 3; plane++) {
1336 uint8_t *output_plane = s->current_frame.data [plane] + s->data_offset[plane];
1337 uint8_t * last_plane = s-> last_frame.data [plane] + s->data_offset[plane];
1338 uint8_t *golden_plane = s-> golden_frame.data [plane] + s->data_offset[plane];
1339 int stride = s->current_frame.linesize[plane];
1340 int plane_width = s->width >> !!plane;
1341 int plane_height = s->height >> !!plane;
1343 int sb_x, sb_y = slice << !plane;
1344 int slice_height = sb_y + (plane ? 1 : 2);
1345 int slice_width = plane ? s->c_superblock_width : s->y_superblock_width;
1347 int fragment_width = s->fragment_width >> !!plane;
1348 int fragment_height = s->fragment_height >> !!plane;
1349 int fragment_start = s->fragment_start[plane];
1351 if (!s->flipped_image) stride = -stride;
1352 if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1356 if(FFABS(stride) > 2048)
1357 return; //various tables are fixed size
1359 /* for each superblock row in the slice (both of them)... */
1360 for (; sb_y < slice_height; sb_y++) {
1362 /* for each superblock in a row... */
1363 for (sb_x = 0; sb_x < slice_width; sb_x++) {
1365 /* for each block in a superblock... */
1366 for (j = 0; j < 16; j++) {
1367 x = 4*sb_x + hilbert_offset[j][0];
1368 y = 4*sb_y + hilbert_offset[j][1];
1370 i = fragment_start + y*fragment_width + x;
1373 if (x >= fragment_width || y >= fragment_height)
1376 first_pixel = 8*y*stride + 8*x;
1378 /* transform if this block was coded */
1379 if (s->all_fragments[i].coding_method != MODE_COPY) {
1380 int intra = s->all_fragments[i].coding_method == MODE_INTRA;
1382 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1383 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1384 motion_source= golden_plane;
1386 motion_source= last_plane;
1388 motion_source += first_pixel;
1389 motion_halfpel_index = 0;
1391 /* sort out the motion vector if this fragment is coded
1392 * using a motion vector method */
1393 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1394 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1396 motion_x = s->all_fragments[i].motion_x;
1397 motion_y = s->all_fragments[i].motion_y;
1399 motion_x= (motion_x>>1) | (motion_x&1);
1400 motion_y= (motion_y>>1) | (motion_y&1);
1403 src_x= (motion_x>>1) + 8*x;
1404 src_y= (motion_y>>1) + 8*y;
1406 motion_halfpel_index = motion_x & 0x01;
1407 motion_source += (motion_x >> 1);
1409 motion_halfpel_index |= (motion_y & 0x01) << 1;
1410 motion_source += ((motion_y >> 1) * stride);
1412 if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1413 uint8_t *temp= s->edge_emu_buffer;
1414 if(stride<0) temp -= 9*stride;
1415 else temp += 9*stride;
1417 ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
1418 motion_source= temp;
1423 /* first, take care of copying a block from either the
1424 * previous or the golden frame */
1425 if (s->all_fragments[i].coding_method != MODE_INTRA) {
1426 /* Note, it is possible to implement all MC cases with
1427 put_no_rnd_pixels_l2 which would look more like the
1428 VP3 source but this would be slower as
1429 put_no_rnd_pixels_tab is better optimzed */
1430 if(motion_halfpel_index != 3){
1431 s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1432 output_plane + first_pixel,
1433 motion_source, stride, 8);
1435 int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1436 s->dsp.put_no_rnd_pixels_l2[1](
1437 output_plane + first_pixel,
1439 motion_source + stride + 1 + d,
1444 s->dsp.clear_block(block);
1445 vp3_dequant(s, s->all_fragments + i, plane, !intra, block);
1447 /* invert DCT and place (or add) in final output */
1449 if (s->all_fragments[i].coding_method == MODE_INTRA) {
1450 if(s->avctx->idct_algo!=FF_IDCT_VP3)
1453 output_plane + first_pixel,
1458 output_plane + first_pixel,
1464 /* copy directly from the previous frame */
1465 s->dsp.put_pixels_tab[1][0](
1466 output_plane + first_pixel,
1467 last_plane + first_pixel,
1474 // Filter up to the last row in the superblock row
1475 apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
1479 /* this looks like a good place for slice dispatch... */
1481 * if (slice == s->macroblock_height - 1)
1482 * dispatch (both last slice & 2nd-to-last slice);
1483 * else if (slice > 0)
1484 * dispatch (slice - 1);
1487 vp3_draw_horiz_band(s, FFMIN(64*slice + 64-16, s->height-16));
1491 * This is the ffmpeg/libavcodec API init function.
1493 static av_cold int vp3_decode_init(AVCodecContext *avctx)
1495 Vp3DecodeContext *s = avctx->priv_data;
1496 int i, inter, plane;
1500 if (avctx->codec_tag == MKTAG('V','P','3','0'))
1506 s->width = FFALIGN(avctx->width, 16);
1507 s->height = FFALIGN(avctx->height, 16);
1508 avctx->pix_fmt = PIX_FMT_YUV420P;
1509 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1510 if(avctx->idct_algo==FF_IDCT_AUTO)
1511 avctx->idct_algo=FF_IDCT_VP3;
1512 dsputil_init(&s->dsp, avctx);
1514 ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
1516 /* initialize to an impossible value which will force a recalculation
1517 * in the first frame decode */
1518 for (i = 0; i < 3; i++)
1521 s->y_superblock_width = (s->width + 31) / 32;
1522 s->y_superblock_height = (s->height + 31) / 32;
1523 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1525 /* work out the dimensions for the C planes */
1526 c_width = s->width / 2;
1527 c_height = s->height / 2;
1528 s->c_superblock_width = (c_width + 31) / 32;
1529 s->c_superblock_height = (c_height + 31) / 32;
1530 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1532 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1533 s->u_superblock_start = s->y_superblock_count;
1534 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1535 s->superblock_coding = av_malloc(s->superblock_count);
1537 s->macroblock_width = (s->width + 15) / 16;
1538 s->macroblock_height = (s->height + 15) / 16;
1539 s->macroblock_count = s->macroblock_width * s->macroblock_height;
1541 s->fragment_width = s->width / FRAGMENT_PIXELS;
1542 s->fragment_height = s->height / FRAGMENT_PIXELS;
1544 /* fragment count covers all 8x8 blocks for all 3 planes */
1545 s->fragment_count = s->fragment_width * s->fragment_height * 3 / 2;
1546 s->fragment_start[1] = s->fragment_width * s->fragment_height;
1547 s->fragment_start[2] = s->fragment_width * s->fragment_height * 5 / 4;
1549 s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
1550 s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
1551 s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
1552 if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
1553 !s->coded_fragment_list[0]) {
1554 vp3_decode_end(avctx);
1558 if (!s->theora_tables)
1560 for (i = 0; i < 64; i++) {
1561 s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1562 s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1563 s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1564 s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1565 s->base_matrix[2][i] = vp31_inter_dequant[i];
1566 s->filter_limit_values[i] = vp31_filter_limit_values[i];
1569 for(inter=0; inter<2; inter++){
1570 for(plane=0; plane<3; plane++){
1571 s->qr_count[inter][plane]= 1;
1572 s->qr_size [inter][plane][0]= 63;
1573 s->qr_base [inter][plane][0]=
1574 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1578 /* init VLC tables */
1579 for (i = 0; i < 16; i++) {
1582 init_vlc(&s->dc_vlc[i], 5, 32,
1583 &dc_bias[i][0][1], 4, 2,
1584 &dc_bias[i][0][0], 4, 2, 0);
1586 /* group 1 AC histograms */
1587 init_vlc(&s->ac_vlc_1[i], 5, 32,
1588 &ac_bias_0[i][0][1], 4, 2,
1589 &ac_bias_0[i][0][0], 4, 2, 0);
1591 /* group 2 AC histograms */
1592 init_vlc(&s->ac_vlc_2[i], 5, 32,
1593 &ac_bias_1[i][0][1], 4, 2,
1594 &ac_bias_1[i][0][0], 4, 2, 0);
1596 /* group 3 AC histograms */
1597 init_vlc(&s->ac_vlc_3[i], 5, 32,
1598 &ac_bias_2[i][0][1], 4, 2,
1599 &ac_bias_2[i][0][0], 4, 2, 0);
1601 /* group 4 AC histograms */
1602 init_vlc(&s->ac_vlc_4[i], 5, 32,
1603 &ac_bias_3[i][0][1], 4, 2,
1604 &ac_bias_3[i][0][0], 4, 2, 0);
1607 for (i = 0; i < 16; i++) {
1610 if (init_vlc(&s->dc_vlc[i], 5, 32,
1611 &s->huffman_table[i][0][1], 4, 2,
1612 &s->huffman_table[i][0][0], 4, 2, 0) < 0)
1615 /* group 1 AC histograms */
1616 if (init_vlc(&s->ac_vlc_1[i], 5, 32,
1617 &s->huffman_table[i+16][0][1], 4, 2,
1618 &s->huffman_table[i+16][0][0], 4, 2, 0) < 0)
1621 /* group 2 AC histograms */
1622 if (init_vlc(&s->ac_vlc_2[i], 5, 32,
1623 &s->huffman_table[i+16*2][0][1], 4, 2,
1624 &s->huffman_table[i+16*2][0][0], 4, 2, 0) < 0)
1627 /* group 3 AC histograms */
1628 if (init_vlc(&s->ac_vlc_3[i], 5, 32,
1629 &s->huffman_table[i+16*3][0][1], 4, 2,
1630 &s->huffman_table[i+16*3][0][0], 4, 2, 0) < 0)
1633 /* group 4 AC histograms */
1634 if (init_vlc(&s->ac_vlc_4[i], 5, 32,
1635 &s->huffman_table[i+16*4][0][1], 4, 2,
1636 &s->huffman_table[i+16*4][0][0], 4, 2, 0) < 0)
1641 init_vlc(&s->superblock_run_length_vlc, 6, 34,
1642 &superblock_run_length_vlc_table[0][1], 4, 2,
1643 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1645 init_vlc(&s->fragment_run_length_vlc, 5, 30,
1646 &fragment_run_length_vlc_table[0][1], 4, 2,
1647 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1649 init_vlc(&s->mode_code_vlc, 3, 8,
1650 &mode_code_vlc_table[0][1], 2, 1,
1651 &mode_code_vlc_table[0][0], 2, 1, 0);
1653 init_vlc(&s->motion_vector_vlc, 6, 63,
1654 &motion_vector_vlc_table[0][1], 2, 1,
1655 &motion_vector_vlc_table[0][0], 2, 1, 0);
1657 /* work out the block mapping tables */
1658 s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
1659 s->macroblock_coding = av_malloc(s->macroblock_count + 1);
1660 if (!s->superblock_fragments || !s->macroblock_coding) {
1661 vp3_decode_end(avctx);
1664 init_block_mapping(s);
1666 for (i = 0; i < 3; i++) {
1667 s->current_frame.data[i] = NULL;
1668 s->last_frame.data[i] = NULL;
1669 s->golden_frame.data[i] = NULL;
1675 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1680 * This is the ffmpeg/libavcodec API frame decode function.
1682 static int vp3_decode_frame(AVCodecContext *avctx,
1683 void *data, int *data_size,
1686 const uint8_t *buf = avpkt->data;
1687 int buf_size = avpkt->size;
1688 Vp3DecodeContext *s = avctx->priv_data;
1690 static int counter = 0;
1693 init_get_bits(&gb, buf, buf_size * 8);
1695 if (s->theora && get_bits1(&gb))
1697 av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1701 s->keyframe = !get_bits1(&gb);
1704 for (i = 0; i < 3; i++)
1705 s->last_qps[i] = s->qps[i];
1709 s->qps[s->nqps++]= get_bits(&gb, 6);
1710 } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
1711 for (i = s->nqps; i < 3; i++)
1714 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1715 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
1716 s->keyframe?"key":"", counter, s->qps[0]);
1719 if (s->qps[0] != s->last_qps[0])
1720 init_loop_filter(s);
1722 for (i = 0; i < s->nqps; i++)
1723 // reinit all dequantizers if the first one changed, because
1724 // the DC of the first quantizer must be used for all matrices
1725 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
1726 init_dequantizer(s, i);
1728 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
1731 s->current_frame.reference = 3;
1732 s->current_frame.pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
1733 if (avctx->get_buffer(avctx, &s->current_frame) < 0) {
1734 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1741 skip_bits(&gb, 4); /* width code */
1742 skip_bits(&gb, 4); /* height code */
1745 s->version = get_bits(&gb, 5);
1747 av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
1750 if (s->version || s->theora)
1753 av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
1754 skip_bits(&gb, 2); /* reserved? */
1757 if (!s->golden_frame.data[0]) {
1758 av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
1760 s->golden_frame.reference = 3;
1761 s->golden_frame.pict_type = FF_I_TYPE;
1762 if (avctx->get_buffer(avctx, &s->golden_frame) < 0) {
1763 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1766 s->last_frame = s->golden_frame;
1767 s->last_frame.type = FF_BUFFER_TYPE_COPY;
1771 s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
1772 s->current_frame.qstride= 0;
1776 if (unpack_superblocks(s, &gb)){
1777 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
1780 if (unpack_modes(s, &gb)){
1781 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
1784 if (unpack_vectors(s, &gb)){
1785 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
1788 if (unpack_block_qpis(s, &gb)){
1789 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
1792 if (unpack_dct_coeffs(s, &gb)){
1793 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
1797 for (i = 0; i < 3; i++) {
1798 if (s->flipped_image)
1799 s->data_offset[i] = 0;
1801 s->data_offset[i] = ((s->height>>!!i)-1) * s->current_frame.linesize[i];
1804 s->last_slice_end = 0;
1805 for (i = 0; i < s->c_superblock_height; i++)
1808 // filter the last row
1809 for (i = 0; i < 3; i++) {
1810 int row = (s->height >> (3+!!i)) - 1;
1811 apply_loop_filter(s, i, row, row+1);
1813 vp3_draw_horiz_band(s, s->height);
1815 *data_size=sizeof(AVFrame);
1816 *(AVFrame*)data= s->current_frame;
1818 /* release the last frame, if it is allocated and if it is not the
1820 if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1821 avctx->release_buffer(avctx, &s->last_frame);
1823 /* shuffle frames (last = current) */
1824 s->last_frame= s->current_frame;
1827 if (s->golden_frame.data[0])
1828 avctx->release_buffer(avctx, &s->golden_frame);
1829 s->golden_frame = s->current_frame;
1830 s->last_frame.type = FF_BUFFER_TYPE_COPY;
1833 s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
1838 if (s->current_frame.data[0])
1839 avctx->release_buffer(avctx, &s->current_frame);
1844 * This is the ffmpeg/libavcodec API module cleanup function.
1846 static av_cold int vp3_decode_end(AVCodecContext *avctx)
1848 Vp3DecodeContext *s = avctx->priv_data;
1851 av_free(s->superblock_coding);
1852 av_free(s->all_fragments);
1853 av_free(s->coded_fragment_list[0]);
1854 av_free(s->dct_tokens_base);
1855 av_free(s->superblock_fragments);
1856 av_free(s->macroblock_coding);
1858 for (i = 0; i < 16; i++) {
1859 free_vlc(&s->dc_vlc[i]);
1860 free_vlc(&s->ac_vlc_1[i]);
1861 free_vlc(&s->ac_vlc_2[i]);
1862 free_vlc(&s->ac_vlc_3[i]);
1863 free_vlc(&s->ac_vlc_4[i]);
1866 free_vlc(&s->superblock_run_length_vlc);
1867 free_vlc(&s->fragment_run_length_vlc);
1868 free_vlc(&s->mode_code_vlc);
1869 free_vlc(&s->motion_vector_vlc);
1871 /* release all frames */
1872 if (s->golden_frame.data[0])
1873 avctx->release_buffer(avctx, &s->golden_frame);
1874 if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1875 avctx->release_buffer(avctx, &s->last_frame);
1876 /* no need to release the current_frame since it will always be pointing
1877 * to the same frame as either the golden or last frame */
1882 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
1884 Vp3DecodeContext *s = avctx->priv_data;
1886 if (get_bits1(gb)) {
1888 if (s->entries >= 32) { /* overflow */
1889 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1892 token = get_bits(gb, 5);
1893 //av_log(avctx, AV_LOG_DEBUG, "hti %d hbits %x token %d entry : %d size %d\n", s->hti, s->hbits, token, s->entries, s->huff_code_size);
1894 s->huffman_table[s->hti][token][0] = s->hbits;
1895 s->huffman_table[s->hti][token][1] = s->huff_code_size;
1899 if (s->huff_code_size >= 32) {/* overflow */
1900 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1903 s->huff_code_size++;
1905 if (read_huffman_tree(avctx, gb))
1908 if (read_huffman_tree(avctx, gb))
1911 s->huff_code_size--;
1916 #if CONFIG_THEORA_DECODER
1917 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
1919 Vp3DecodeContext *s = avctx->priv_data;
1920 int visible_width, visible_height, colorspace;
1922 s->theora = get_bits_long(gb, 24);
1923 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
1925 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
1926 /* but previous versions have the image flipped relative to vp3 */
1927 if (s->theora < 0x030200)
1929 s->flipped_image = 1;
1930 av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
1933 visible_width = s->width = get_bits(gb, 16) << 4;
1934 visible_height = s->height = get_bits(gb, 16) << 4;
1936 if(avcodec_check_dimensions(avctx, s->width, s->height)){
1937 av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
1938 s->width= s->height= 0;
1942 if (s->theora >= 0x030200) {
1943 visible_width = get_bits_long(gb, 24);
1944 visible_height = get_bits_long(gb, 24);
1946 skip_bits(gb, 8); /* offset x */
1947 skip_bits(gb, 8); /* offset y */
1950 skip_bits(gb, 32); /* fps numerator */
1951 skip_bits(gb, 32); /* fps denumerator */
1952 skip_bits(gb, 24); /* aspect numerator */
1953 skip_bits(gb, 24); /* aspect denumerator */
1955 if (s->theora < 0x030200)
1956 skip_bits(gb, 5); /* keyframe frequency force */
1957 colorspace = get_bits(gb, 8);
1958 skip_bits(gb, 24); /* bitrate */
1960 skip_bits(gb, 6); /* quality hint */
1962 if (s->theora >= 0x030200)
1964 skip_bits(gb, 5); /* keyframe frequency force */
1965 skip_bits(gb, 2); /* pixel format: 420,res,422,444 */
1966 skip_bits(gb, 3); /* reserved */
1969 // align_get_bits(gb);
1971 if ( visible_width <= s->width && visible_width > s->width-16
1972 && visible_height <= s->height && visible_height > s->height-16)
1973 avcodec_set_dimensions(avctx, visible_width, visible_height);
1975 avcodec_set_dimensions(avctx, s->width, s->height);
1977 if (colorspace == 1) {
1978 avctx->color_primaries = AVCOL_PRI_BT470M;
1979 } else if (colorspace == 2) {
1980 avctx->color_primaries = AVCOL_PRI_BT470BG;
1982 if (colorspace == 1 || colorspace == 2) {
1983 avctx->colorspace = AVCOL_SPC_BT470BG;
1984 avctx->color_trc = AVCOL_TRC_BT709;
1990 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
1992 Vp3DecodeContext *s = avctx->priv_data;
1993 int i, n, matrices, inter, plane;
1995 if (s->theora >= 0x030200) {
1996 n = get_bits(gb, 3);
1997 /* loop filter limit values table */
1998 for (i = 0; i < 64; i++) {
1999 s->filter_limit_values[i] = get_bits(gb, n);
2000 if (s->filter_limit_values[i] > 127) {
2001 av_log(avctx, AV_LOG_ERROR, "filter limit value too large (%i > 127), clamping\n", s->filter_limit_values[i]);
2002 s->filter_limit_values[i] = 127;
2007 if (s->theora >= 0x030200)
2008 n = get_bits(gb, 4) + 1;
2011 /* quality threshold table */
2012 for (i = 0; i < 64; i++)
2013 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2015 if (s->theora >= 0x030200)
2016 n = get_bits(gb, 4) + 1;
2019 /* dc scale factor table */
2020 for (i = 0; i < 64; i++)
2021 s->coded_dc_scale_factor[i] = get_bits(gb, n);
2023 if (s->theora >= 0x030200)
2024 matrices = get_bits(gb, 9) + 1;
2029 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2033 for(n=0; n<matrices; n++){
2034 for (i = 0; i < 64; i++)
2035 s->base_matrix[n][i]= get_bits(gb, 8);
2038 for (inter = 0; inter <= 1; inter++) {
2039 for (plane = 0; plane <= 2; plane++) {
2041 if (inter || plane > 0)
2042 newqr = get_bits1(gb);
2045 if(inter && get_bits1(gb)){
2049 qtj= (3*inter + plane - 1) / 3;
2050 plj= (plane + 2) % 3;
2052 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2053 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2054 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2060 i= get_bits(gb, av_log2(matrices-1)+1);
2062 av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2065 s->qr_base[inter][plane][qri]= i;
2068 i = get_bits(gb, av_log2(63-qi)+1) + 1;
2069 s->qr_size[inter][plane][qri++]= i;
2074 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2077 s->qr_count[inter][plane]= qri;
2082 /* Huffman tables */
2083 for (s->hti = 0; s->hti < 80; s->hti++) {
2085 s->huff_code_size = 1;
2086 if (!get_bits1(gb)) {
2088 if(read_huffman_tree(avctx, gb))
2091 if(read_huffman_tree(avctx, gb))
2096 s->theora_tables = 1;
2101 static av_cold int theora_decode_init(AVCodecContext *avctx)
2103 Vp3DecodeContext *s = avctx->priv_data;
2106 uint8_t *header_start[3];
2112 if (!avctx->extradata_size)
2114 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2118 if (ff_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2119 42, header_start, header_len) < 0) {
2120 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2125 init_get_bits(&gb, header_start[i], header_len[i] * 8);
2127 ptype = get_bits(&gb, 8);
2129 if (!(ptype & 0x80))
2131 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2135 // FIXME: Check for this as well.
2136 skip_bits_long(&gb, 6*8); /* "theora" */
2141 theora_decode_header(avctx, &gb);
2144 // FIXME: is this needed? it breaks sometimes
2145 // theora_decode_comments(avctx, gb);
2148 if (theora_decode_tables(avctx, &gb))
2152 av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2155 if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2156 av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2157 if (s->theora < 0x030200)
2161 return vp3_decode_init(avctx);
2164 AVCodec theora_decoder = {
2168 sizeof(Vp3DecodeContext),
2173 CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2175 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2179 AVCodec vp3_decoder = {
2183 sizeof(Vp3DecodeContext),
2188 CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2190 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),