2 * Copyright (C) 2003-2004 The FFmpeg project
3 * Copyright (C) 2019 Peter Ross
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * On2 VP3/VP4 Video Decoder
26 * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
27 * For more information about the VP3 coding process, visit:
28 * http://wiki.multimedia.cx/index.php?title=On2_VP3
30 * Theora decoder by Alex Beregszaszi
37 #include "libavutil/imgutils.h"
51 #define FRAGMENT_PIXELS 8
53 // FIXME split things out into their own arrays
54 typedef struct Vp3Fragment {
56 uint8_t coding_method;
60 #define SB_NOT_CODED 0
61 #define SB_PARTIALLY_CODED 1
62 #define SB_FULLY_CODED 2
64 // This is the maximum length of a single long bit run that can be encoded
65 // for superblock coding or block qps. Theora special-cases this to read a
66 // bit instead of flipping the current bit to allow for runs longer than 4129.
67 #define MAXIMUM_LONG_BIT_RUN 4129
69 #define MODE_INTER_NO_MV 0
71 #define MODE_INTER_PLUS_MV 2
72 #define MODE_INTER_LAST_MV 3
73 #define MODE_INTER_PRIOR_LAST 4
74 #define MODE_USING_GOLDEN 5
75 #define MODE_GOLDEN_MV 6
76 #define MODE_INTER_FOURMV 7
77 #define CODING_MODE_COUNT 8
79 /* special internal mode */
82 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
83 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
86 /* There are 6 preset schemes, plus a free-form scheme */
87 static const int ModeAlphabet[6][CODING_MODE_COUNT] = {
88 /* scheme 1: Last motion vector dominates */
89 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
90 MODE_INTER_PLUS_MV, MODE_INTER_NO_MV,
91 MODE_INTRA, MODE_USING_GOLDEN,
92 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
95 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
96 MODE_INTER_NO_MV, MODE_INTER_PLUS_MV,
97 MODE_INTRA, MODE_USING_GOLDEN,
98 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
101 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
102 MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
103 MODE_INTRA, MODE_USING_GOLDEN,
104 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
107 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
108 MODE_INTER_NO_MV, MODE_INTER_PRIOR_LAST,
109 MODE_INTRA, MODE_USING_GOLDEN,
110 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
112 /* scheme 5: No motion vector dominates */
113 { MODE_INTER_NO_MV, MODE_INTER_LAST_MV,
114 MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
115 MODE_INTRA, MODE_USING_GOLDEN,
116 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
119 { MODE_INTER_NO_MV, MODE_USING_GOLDEN,
120 MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
121 MODE_INTER_PLUS_MV, MODE_INTRA,
122 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
125 static const uint8_t hilbert_offset[16][2] = {
126 { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
127 { 0, 2 }, { 0, 3 }, { 1, 3 }, { 1, 2 },
128 { 2, 2 }, { 2, 3 }, { 3, 3 }, { 3, 2 },
129 { 3, 1 }, { 2, 1 }, { 2, 0 }, { 3, 0 }
137 VP4_DC_UNDEFINED = NB_VP4_DC_TYPES
140 static const uint8_t vp4_pred_block_type_map[8] = {
141 [MODE_INTER_NO_MV] = VP4_DC_INTER,
142 [MODE_INTRA] = VP4_DC_INTRA,
143 [MODE_INTER_PLUS_MV] = VP4_DC_INTER,
144 [MODE_INTER_LAST_MV] = VP4_DC_INTER,
145 [MODE_INTER_PRIOR_LAST] = VP4_DC_INTER,
146 [MODE_USING_GOLDEN] = VP4_DC_GOLDEN,
147 [MODE_GOLDEN_MV] = VP4_DC_GOLDEN,
148 [MODE_INTER_FOURMV] = VP4_DC_INTER,
156 #define MIN_DEQUANT_VAL 2
158 typedef struct Vp3DecodeContext {
159 AVCodecContext *avctx;
160 int theora, theora_tables, theora_header;
163 int chroma_x_shift, chroma_y_shift;
164 ThreadFrame golden_frame;
165 ThreadFrame last_frame;
166 ThreadFrame current_frame;
168 uint8_t idct_permutation[64];
169 uint8_t idct_scantable[64];
171 VideoDSPContext vdsp;
172 VP3DSPContext vp3dsp;
173 DECLARE_ALIGNED(16, int16_t, block)[64];
176 int skip_loop_filter;
182 int superblock_count;
183 int y_superblock_width;
184 int y_superblock_height;
185 int y_superblock_count;
186 int c_superblock_width;
187 int c_superblock_height;
188 int c_superblock_count;
189 int u_superblock_start;
190 int v_superblock_start;
191 unsigned char *superblock_coding;
193 int macroblock_count; /* y macroblock count */
194 int macroblock_width;
195 int macroblock_height;
196 int c_macroblock_count;
197 int c_macroblock_width;
198 int c_macroblock_height;
199 int yuv_macroblock_count; /* y+u+v macroblock count */
202 int fragment_width[2];
203 int fragment_height[2];
205 Vp3Fragment *all_fragments;
206 int fragment_start[3];
212 int8_t (*motion_val[2])[2];
215 uint16_t coded_dc_scale_factor[2][64];
216 uint32_t coded_ac_scale_factor[64];
217 uint8_t base_matrix[384][64];
218 uint8_t qr_count[2][3];
219 uint8_t qr_size[2][3][64];
220 uint16_t qr_base[2][3][64];
223 * This is a list of all tokens in bitstream order. Reordering takes place
224 * by pulling from each level during IDCT. As a consequence, IDCT must be
225 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
226 * otherwise. The 32 different tokens with up to 12 bits of extradata are
227 * collapsed into 3 types, packed as follows:
228 * (from the low to high bits)
230 * 2 bits: type (0,1,2)
231 * 0: EOB run, 14 bits for run length (12 needed)
232 * 1: zero run, 7 bits for run length
233 * 7 bits for the next coefficient (3 needed)
234 * 2: coefficient, 14 bits (11 needed)
236 * Coefficients are signed, so are packed in the highest bits for automatic
239 int16_t *dct_tokens[3][64];
240 int16_t *dct_tokens_base;
241 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
242 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
243 #define TOKEN_COEFF(coeff) (((coeff) * 4) + 2)
246 * number of blocks that contain DCT coefficients at
247 * the given level or higher
249 int num_coded_frags[3][64];
250 int total_num_coded_frags;
252 /* this is a list of indexes into the all_fragments array indicating
253 * which of the fragments are coded */
254 int *coded_fragment_list[3];
256 int *kf_coded_fragment_list;
257 int *nkf_coded_fragment_list;
258 int num_kf_coded_fragment[3];
266 VLC superblock_run_length_vlc; /* version < 2 */
267 VLC fragment_run_length_vlc; /* version < 2 */
268 VLC block_pattern_vlc[2]; /* version >= 2*/
270 VLC motion_vector_vlc; /* version < 2 */
271 VLC vp4_mv_vlc[2][7]; /* version >=2 */
273 /* these arrays need to be on 16-byte boundaries since SSE2 operations
275 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
277 /* This table contains superblock_count * 16 entries. Each set of 16
278 * numbers corresponds to the fragment indexes 0..15 of the superblock.
279 * An entry will be -1 to indicate that no entry corresponds to that
281 int *superblock_fragments;
283 /* This is an array that indicates how a particular macroblock
285 unsigned char *macroblock_coding;
287 uint8_t *edge_emu_buffer;
294 uint32_t huffman_table[80][32][2];
296 uint8_t filter_limit_values[64];
297 DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
299 VP4Predictor * dc_pred_row; /* dc_pred_row[y_superblock_width * 4] */
302 /************************************************************************
303 * VP3 specific functions
304 ************************************************************************/
306 static av_cold void free_tables(AVCodecContext *avctx)
308 Vp3DecodeContext *s = avctx->priv_data;
310 av_freep(&s->superblock_coding);
311 av_freep(&s->all_fragments);
312 av_freep(&s->nkf_coded_fragment_list);
313 av_freep(&s->kf_coded_fragment_list);
314 av_freep(&s->dct_tokens_base);
315 av_freep(&s->superblock_fragments);
316 av_freep(&s->macroblock_coding);
317 av_freep(&s->dc_pred_row);
318 av_freep(&s->motion_val[0]);
319 av_freep(&s->motion_val[1]);
322 static void vp3_decode_flush(AVCodecContext *avctx)
324 Vp3DecodeContext *s = avctx->priv_data;
326 if (s->golden_frame.f)
327 ff_thread_release_buffer(avctx, &s->golden_frame);
329 ff_thread_release_buffer(avctx, &s->last_frame);
330 if (s->current_frame.f)
331 ff_thread_release_buffer(avctx, &s->current_frame);
334 static av_cold int vp3_decode_end(AVCodecContext *avctx)
336 Vp3DecodeContext *s = avctx->priv_data;
340 av_freep(&s->edge_emu_buffer);
342 s->theora_tables = 0;
344 /* release all frames */
345 vp3_decode_flush(avctx);
346 av_frame_free(&s->current_frame.f);
347 av_frame_free(&s->last_frame.f);
348 av_frame_free(&s->golden_frame.f);
350 if (avctx->internal->is_copy)
353 for (i = 0; i < 16; i++) {
354 ff_free_vlc(&s->dc_vlc[i]);
355 ff_free_vlc(&s->ac_vlc_1[i]);
356 ff_free_vlc(&s->ac_vlc_2[i]);
357 ff_free_vlc(&s->ac_vlc_3[i]);
358 ff_free_vlc(&s->ac_vlc_4[i]);
361 ff_free_vlc(&s->superblock_run_length_vlc);
362 ff_free_vlc(&s->fragment_run_length_vlc);
363 ff_free_vlc(&s->mode_code_vlc);
364 ff_free_vlc(&s->motion_vector_vlc);
366 for (j = 0; j < 2; j++)
367 for (i = 0; i < 7; i++)
368 ff_free_vlc(&s->vp4_mv_vlc[j][i]);
370 for (i = 0; i < 2; i++)
371 ff_free_vlc(&s->block_pattern_vlc[i]);
376 * This function sets up all of the various blocks mappings:
377 * superblocks <-> fragments, macroblocks <-> fragments,
378 * superblocks <-> macroblocks
380 * @return 0 is successful; returns 1 if *anything* went wrong.
382 static int init_block_mapping(Vp3DecodeContext *s)
384 int sb_x, sb_y, plane;
387 for (plane = 0; plane < 3; plane++) {
388 int sb_width = plane ? s->c_superblock_width
389 : s->y_superblock_width;
390 int sb_height = plane ? s->c_superblock_height
391 : s->y_superblock_height;
392 int frag_width = s->fragment_width[!!plane];
393 int frag_height = s->fragment_height[!!plane];
395 for (sb_y = 0; sb_y < sb_height; sb_y++)
396 for (sb_x = 0; sb_x < sb_width; sb_x++)
397 for (i = 0; i < 16; i++) {
398 x = 4 * sb_x + hilbert_offset[i][0];
399 y = 4 * sb_y + hilbert_offset[i][1];
401 if (x < frag_width && y < frag_height)
402 s->superblock_fragments[j++] = s->fragment_start[plane] +
405 s->superblock_fragments[j++] = -1;
409 return 0; /* successful path out */
413 * This function sets up the dequantization tables used for a particular
416 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
418 int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
419 int i, plane, inter, qri, bmi, bmj, qistart;
421 for (inter = 0; inter < 2; inter++) {
422 for (plane = 0; plane < 3; plane++) {
423 int dc_scale_factor = s->coded_dc_scale_factor[!!plane][s->qps[qpi]];
425 for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
426 sum += s->qr_size[inter][plane][qri];
427 if (s->qps[qpi] <= sum)
430 qistart = sum - s->qr_size[inter][plane][qri];
431 bmi = s->qr_base[inter][plane][qri];
432 bmj = s->qr_base[inter][plane][qri + 1];
433 for (i = 0; i < 64; i++) {
434 int coeff = (2 * (sum - s->qps[qpi]) * s->base_matrix[bmi][i] -
435 2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
436 s->qr_size[inter][plane][qri]) /
437 (2 * s->qr_size[inter][plane][qri]);
439 int qmin = 8 << (inter + !i);
440 int qscale = i ? ac_scale_factor : dc_scale_factor;
441 int qbias = (1 + inter) * 3;
442 s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
443 (i == 0 || s->version < 2) ? av_clip((qscale * coeff) / 100 * 4, qmin, 4096)
444 : (qscale * (coeff - qbias) / 100 + qbias) * 4;
446 /* all DC coefficients use the same quant so as not to interfere
447 * with DC prediction */
448 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
454 * This function initializes the loop filter boundary limits if the frame's
455 * quality index is different from the previous frame's.
457 * The filter_limit_values may not be larger than 127.
459 static void init_loop_filter(Vp3DecodeContext *s)
461 ff_vp3dsp_set_bounding_values(s->bounding_values_array, s->filter_limit_values[s->qps[0]]);
465 * This function unpacks all of the superblock/macroblock/fragment coding
466 * information from the bitstream.
468 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
470 int superblock_starts[3] = {
471 0, s->u_superblock_start, s->v_superblock_start
474 int current_superblock = 0;
476 int num_partial_superblocks = 0;
479 int current_fragment;
481 int plane0_num_coded_frags = 0;
484 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
486 /* unpack the list of partially-coded superblocks */
487 bit = get_bits1(gb) ^ 1;
490 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
491 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
496 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
498 if (current_run == 34)
499 current_run += get_bits(gb, 12);
501 if (current_run > s->superblock_count - current_superblock) {
502 av_log(s->avctx, AV_LOG_ERROR,
503 "Invalid partially coded superblock run length\n");
507 memset(s->superblock_coding + current_superblock, bit, current_run);
509 current_superblock += current_run;
511 num_partial_superblocks += current_run;
514 /* unpack the list of fully coded superblocks if any of the blocks were
515 * not marked as partially coded in the previous step */
516 if (num_partial_superblocks < s->superblock_count) {
517 int superblocks_decoded = 0;
519 current_superblock = 0;
520 bit = get_bits1(gb) ^ 1;
523 while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
524 get_bits_left(gb) > 0) {
525 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
530 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
532 if (current_run == 34)
533 current_run += get_bits(gb, 12);
535 for (j = 0; j < current_run; current_superblock++) {
536 if (current_superblock >= s->superblock_count) {
537 av_log(s->avctx, AV_LOG_ERROR,
538 "Invalid fully coded superblock run length\n");
542 /* skip any superblocks already marked as partially coded */
543 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
544 s->superblock_coding[current_superblock] = 2 * bit;
548 superblocks_decoded += current_run;
552 /* if there were partial blocks, initialize bitstream for
553 * unpacking fragment codings */
554 if (num_partial_superblocks) {
557 /* toggle the bit because as soon as the first run length is
558 * fetched the bit will be toggled again */
563 /* figure out which fragments are coded; iterate through each
564 * superblock (all planes) */
565 s->total_num_coded_frags = 0;
566 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
568 s->coded_fragment_list[0] = s->keyframe ? s->kf_coded_fragment_list
569 : s->nkf_coded_fragment_list;
571 for (plane = 0; plane < 3; plane++) {
572 int sb_start = superblock_starts[plane];
573 int sb_end = sb_start + (plane ? s->c_superblock_count
574 : s->y_superblock_count);
575 int num_coded_frags = 0;
578 if (s->num_kf_coded_fragment[plane] == -1) {
579 for (i = sb_start; i < sb_end; i++) {
580 /* iterate through all 16 fragments in a superblock */
581 for (j = 0; j < 16; j++) {
582 /* if the fragment is in bounds, check its coding status */
583 current_fragment = s->superblock_fragments[i * 16 + j];
584 if (current_fragment != -1) {
585 s->coded_fragment_list[plane][num_coded_frags++] =
590 s->num_kf_coded_fragment[plane] = num_coded_frags;
592 num_coded_frags = s->num_kf_coded_fragment[plane];
594 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
595 if (get_bits_left(gb) < plane0_num_coded_frags >> 2) {
596 return AVERROR_INVALIDDATA;
598 /* iterate through all 16 fragments in a superblock */
599 for (j = 0; j < 16; j++) {
600 /* if the fragment is in bounds, check its coding status */
601 current_fragment = s->superblock_fragments[i * 16 + j];
602 if (current_fragment != -1) {
603 int coded = s->superblock_coding[i];
605 if (coded == SB_PARTIALLY_CODED) {
606 /* fragment may or may not be coded; this is the case
607 * that cares about the fragment coding runs */
608 if (current_run-- == 0) {
610 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
616 /* default mode; actual mode will be decoded in
618 s->all_fragments[current_fragment].coding_method =
620 s->coded_fragment_list[plane][num_coded_frags++] =
623 /* not coded; copy this fragment from the prior frame */
624 s->all_fragments[current_fragment].coding_method =
632 plane0_num_coded_frags = num_coded_frags;
633 s->total_num_coded_frags += num_coded_frags;
634 for (i = 0; i < 64; i++)
635 s->num_coded_frags[plane][i] = num_coded_frags;
637 s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
643 #define BLOCK_X (2 * mb_x + (k & 1))
644 #define BLOCK_Y (2 * mb_y + (k >> 1))
646 #if CONFIG_VP4_DECODER
648 * @return number of blocks, or > yuv_macroblock_count on error.
649 * return value is always >= 1.
651 static int vp4_get_mb_count(Vp3DecodeContext *s, GetBitContext *gb)
655 while ((bits = show_bits(gb, 9)) == 0x1ff) {
658 if (v > s->yuv_macroblock_count) {
659 av_log(s->avctx, AV_LOG_ERROR, "Invalid run length\n");
664 skip_bits(gb, 2 + n); \
665 v += (1 << n) + get_bits(gb, n); }
666 #define thresh(n) (0x200 - (0x80 >> n))
667 #define else_if(n) else if (bits < thresh(n)) body(n)
670 } else if (bits < thresh(0)) {
687 static int vp4_get_block_pattern(Vp3DecodeContext *s, GetBitContext *gb, int *next_block_pattern_table)
689 int v = get_vlc2(gb, s->block_pattern_vlc[*next_block_pattern_table].table, 3, 2);
691 av_log(s->avctx, AV_LOG_ERROR, "Invalid block pattern\n");
692 *next_block_pattern_table = 0;
695 *next_block_pattern_table = vp4_block_pattern_table_selector[v];
699 static int vp4_unpack_macroblocks(Vp3DecodeContext *s, GetBitContext *gb)
701 int plane, i, j, k, fragment;
702 int next_block_pattern_table;
703 int bit, current_run, has_partial;
705 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
712 for (i = 0; i < s->yuv_macroblock_count; i += current_run) {
713 if (get_bits_left(gb) <= 0)
714 return AVERROR_INVALIDDATA;
715 current_run = vp4_get_mb_count(s, gb);
716 if (current_run > s->yuv_macroblock_count - i)
718 memset(s->superblock_coding + i, 2 * bit, current_run);
724 if (get_bits_left(gb) <= 0)
725 return AVERROR_INVALIDDATA;
727 current_run = vp4_get_mb_count(s, gb);
728 for (i = 0; i < s->yuv_macroblock_count; i++) {
729 if (!s->superblock_coding[i]) {
732 current_run = vp4_get_mb_count(s, gb);
734 s->superblock_coding[i] = bit;
738 if (current_run) /* handle situation when vp4_get_mb_count() fails */
742 next_block_pattern_table = 0;
744 for (plane = 0; plane < 3; plane++) {
746 int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
747 int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
748 int mb_width = plane ? s->c_macroblock_width : s->macroblock_width;
749 int mb_height = plane ? s->c_macroblock_height : s->macroblock_height;
750 int fragment_width = s->fragment_width[!!plane];
751 int fragment_height = s->fragment_height[!!plane];
753 for (sb_y = 0; sb_y < sb_height; sb_y++) {
754 for (sb_x = 0; sb_x < sb_width; sb_x++) {
755 for (j = 0; j < 4; j++) {
756 int mb_x = 2 * sb_x + (j >> 1);
757 int mb_y = 2 * sb_y + (j >> 1) ^ (j & 1);
758 int mb_coded, pattern, coded;
760 if (mb_x >= mb_width || mb_y >= mb_height)
763 mb_coded = s->superblock_coding[i++];
765 if (mb_coded == SB_FULLY_CODED)
767 else if (mb_coded == SB_PARTIALLY_CODED)
768 pattern = vp4_get_block_pattern(s, gb, &next_block_pattern_table);
772 for (k = 0; k < 4; k++) {
773 if (BLOCK_X >= fragment_width || BLOCK_Y >= fragment_height)
775 fragment = s->fragment_start[plane] + BLOCK_Y * fragment_width + BLOCK_X;
776 coded = pattern & (8 >> k);
777 /* MODE_INTER_NO_MV is the default for coded fragments.
778 the actual method is decoded in the next phase. */
779 s->all_fragments[fragment].coding_method = coded ? MODE_INTER_NO_MV : MODE_COPY;
790 * This function unpacks all the coding mode data for individual macroblocks
791 * from the bitstream.
793 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
795 int i, j, k, sb_x, sb_y;
797 int current_macroblock;
798 int current_fragment;
800 int custom_mode_alphabet[CODING_MODE_COUNT];
805 for (i = 0; i < s->fragment_count; i++)
806 s->all_fragments[i].coding_method = MODE_INTRA;
808 /* fetch the mode coding scheme for this frame */
809 scheme = get_bits(gb, 3);
811 /* is it a custom coding scheme? */
813 for (i = 0; i < 8; i++)
814 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
815 for (i = 0; i < 8; i++)
816 custom_mode_alphabet[get_bits(gb, 3)] = i;
817 alphabet = custom_mode_alphabet;
819 alphabet = ModeAlphabet[scheme - 1];
821 /* iterate through all of the macroblocks that contain 1 or more
823 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
824 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
825 if (get_bits_left(gb) <= 0)
828 for (j = 0; j < 4; j++) {
829 int mb_x = 2 * sb_x + (j >> 1);
830 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
831 current_macroblock = mb_y * s->macroblock_width + mb_x;
833 if (mb_x >= s->macroblock_width ||
834 mb_y >= s->macroblock_height)
837 /* coding modes are only stored if the macroblock has
838 * at least one luma block coded, otherwise it must be
840 for (k = 0; k < 4; k++) {
841 current_fragment = BLOCK_Y *
842 s->fragment_width[0] + BLOCK_X;
843 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
847 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
851 /* mode 7 means get 3 bits for each coding mode */
853 coding_mode = get_bits(gb, 3);
855 coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
857 s->macroblock_coding[current_macroblock] = coding_mode;
858 for (k = 0; k < 4; k++) {
859 frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
860 if (frag->coding_method != MODE_COPY)
861 frag->coding_method = coding_mode;
864 #define SET_CHROMA_MODES \
865 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
866 frag[s->fragment_start[1]].coding_method = coding_mode; \
867 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
868 frag[s->fragment_start[2]].coding_method = coding_mode;
870 if (s->chroma_y_shift) {
871 frag = s->all_fragments + mb_y *
872 s->fragment_width[1] + mb_x;
874 } else if (s->chroma_x_shift) {
875 frag = s->all_fragments +
876 2 * mb_y * s->fragment_width[1] + mb_x;
877 for (k = 0; k < 2; k++) {
879 frag += s->fragment_width[1];
882 for (k = 0; k < 4; k++) {
883 frag = s->all_fragments +
884 BLOCK_Y * s->fragment_width[1] + BLOCK_X;
896 static int vp4_get_mv(Vp3DecodeContext *s, GetBitContext *gb, int axis, int last_motion)
898 int v = get_vlc2(gb, s->vp4_mv_vlc[axis][vp4_mv_table_selector[FFABS(last_motion)]].table, 6, 2) - 31;
899 return last_motion < 0 ? -v : v;
903 * This function unpacks all the motion vectors for the individual
904 * macroblocks from the bitstream.
906 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
908 int j, k, sb_x, sb_y;
912 int last_motion_x = 0;
913 int last_motion_y = 0;
914 int prior_last_motion_x = 0;
915 int prior_last_motion_y = 0;
916 int last_gold_motion_x = 0;
917 int last_gold_motion_y = 0;
918 int current_macroblock;
919 int current_fragment;
925 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme; 2 is VP4 code scheme */
926 coding_mode = s->version < 2 ? get_bits1(gb) : 2;
928 /* iterate through all of the macroblocks that contain 1 or more
930 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
931 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
932 if (get_bits_left(gb) <= 0)
935 for (j = 0; j < 4; j++) {
936 int mb_x = 2 * sb_x + (j >> 1);
937 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
938 current_macroblock = mb_y * s->macroblock_width + mb_x;
940 if (mb_x >= s->macroblock_width ||
941 mb_y >= s->macroblock_height ||
942 s->macroblock_coding[current_macroblock] == MODE_COPY)
945 switch (s->macroblock_coding[current_macroblock]) {
947 if (coding_mode == 2) { /* VP4 */
948 last_gold_motion_x = motion_x[0] = vp4_get_mv(s, gb, 0, last_gold_motion_x);
949 last_gold_motion_y = motion_y[0] = vp4_get_mv(s, gb, 1, last_gold_motion_y);
951 } /* otherwise fall through */
952 case MODE_INTER_PLUS_MV:
953 /* all 6 fragments use the same motion vector */
954 if (coding_mode == 0) {
955 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
956 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
957 } else if (coding_mode == 1) {
958 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
959 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
961 motion_x[0] = vp4_get_mv(s, gb, 0, last_motion_x);
962 motion_y[0] = vp4_get_mv(s, gb, 1, last_motion_y);
965 /* vector maintenance, only on MODE_INTER_PLUS_MV */
966 if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
967 prior_last_motion_x = last_motion_x;
968 prior_last_motion_y = last_motion_y;
969 last_motion_x = motion_x[0];
970 last_motion_y = motion_y[0];
974 case MODE_INTER_FOURMV:
975 /* vector maintenance */
976 prior_last_motion_x = last_motion_x;
977 prior_last_motion_y = last_motion_y;
979 /* fetch 4 vectors from the bitstream, one for each
980 * Y fragment, then average for the C fragment vectors */
981 for (k = 0; k < 4; k++) {
982 current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
983 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
984 if (coding_mode == 0) {
985 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
986 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
987 } else if (coding_mode == 1) {
988 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
989 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
991 motion_x[k] = vp4_get_mv(s, gb, 0, prior_last_motion_x);
992 motion_y[k] = vp4_get_mv(s, gb, 1, prior_last_motion_y);
994 last_motion_x = motion_x[k];
995 last_motion_y = motion_y[k];
1003 case MODE_INTER_LAST_MV:
1004 /* all 6 fragments use the last motion vector */
1005 motion_x[0] = last_motion_x;
1006 motion_y[0] = last_motion_y;
1008 /* no vector maintenance (last vector remains the
1012 case MODE_INTER_PRIOR_LAST:
1013 /* all 6 fragments use the motion vector prior to the
1014 * last motion vector */
1015 motion_x[0] = prior_last_motion_x;
1016 motion_y[0] = prior_last_motion_y;
1018 /* vector maintenance */
1019 prior_last_motion_x = last_motion_x;
1020 prior_last_motion_y = last_motion_y;
1021 last_motion_x = motion_x[0];
1022 last_motion_y = motion_y[0];
1026 /* covers intra, inter without MV, golden without MV */
1030 /* no vector maintenance */
1034 /* assign the motion vectors to the correct fragments */
1035 for (k = 0; k < 4; k++) {
1037 BLOCK_Y * s->fragment_width[0] + BLOCK_X;
1038 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1039 s->motion_val[0][current_fragment][0] = motion_x[k];
1040 s->motion_val[0][current_fragment][1] = motion_y[k];
1042 s->motion_val[0][current_fragment][0] = motion_x[0];
1043 s->motion_val[0][current_fragment][1] = motion_y[0];
1047 if (s->chroma_y_shift) {
1048 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1049 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
1050 motion_x[2] + motion_x[3], 2);
1051 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
1052 motion_y[2] + motion_y[3], 2);
1054 if (s->version <= 2) {
1055 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1056 motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
1058 frag = mb_y * s->fragment_width[1] + mb_x;
1059 s->motion_val[1][frag][0] = motion_x[0];
1060 s->motion_val[1][frag][1] = motion_y[0];
1061 } else if (s->chroma_x_shift) {
1062 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1063 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
1064 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
1065 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
1066 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
1068 motion_x[1] = motion_x[0];
1069 motion_y[1] = motion_y[0];
1071 if (s->version <= 2) {
1072 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1073 motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
1075 frag = 2 * mb_y * s->fragment_width[1] + mb_x;
1076 for (k = 0; k < 2; k++) {
1077 s->motion_val[1][frag][0] = motion_x[k];
1078 s->motion_val[1][frag][1] = motion_y[k];
1079 frag += s->fragment_width[1];
1082 for (k = 0; k < 4; k++) {
1083 frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
1084 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1085 s->motion_val[1][frag][0] = motion_x[k];
1086 s->motion_val[1][frag][1] = motion_y[k];
1088 s->motion_val[1][frag][0] = motion_x[0];
1089 s->motion_val[1][frag][1] = motion_y[0];
1100 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
1102 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
1103 int num_blocks = s->total_num_coded_frags;
1105 for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
1106 i = blocks_decoded = num_blocks_at_qpi = 0;
1108 bit = get_bits1(gb) ^ 1;
1112 if (run_length == MAXIMUM_LONG_BIT_RUN)
1113 bit = get_bits1(gb);
1117 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
1118 if (run_length == 34)
1119 run_length += get_bits(gb, 12);
1120 blocks_decoded += run_length;
1123 num_blocks_at_qpi += run_length;
1125 for (j = 0; j < run_length; i++) {
1126 if (i >= s->total_num_coded_frags)
1129 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
1130 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
1134 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
1136 num_blocks -= num_blocks_at_qpi;
1142 static inline int get_eob_run(GetBitContext *gb, int token)
1144 int v = eob_run_table[token].base;
1145 if (eob_run_table[token].bits)
1146 v += get_bits(gb, eob_run_table[token].bits);
1150 static inline int get_coeff(GetBitContext *gb, int token, int16_t *coeff)
1152 int bits_to_get, zero_run;
1154 bits_to_get = coeff_get_bits[token];
1156 bits_to_get = get_bits(gb, bits_to_get);
1157 *coeff = coeff_tables[token][bits_to_get];
1159 zero_run = zero_run_base[token];
1160 if (zero_run_get_bits[token])
1161 zero_run += get_bits(gb, zero_run_get_bits[token]);
1167 * This function is called by unpack_dct_coeffs() to extract the VLCs from
1168 * the bitstream. The VLCs encode tokens which are used to unpack DCT
1169 * data. This function unpacks all the VLCs for either the Y plane or both
1170 * C planes, and is called for DC coefficients or different AC coefficient
1171 * levels (since different coefficient types require different VLC tables.
1173 * This function returns a residual eob run. E.g, if a particular token gave
1174 * instructions to EOB the next 5 fragments and there were only 2 fragments
1175 * left in the current fragment range, 3 would be returned so that it could
1176 * be passed into the next call to this same function.
1178 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1179 VLC *table, int coeff_index,
1189 int num_coeffs = s->num_coded_frags[plane][coeff_index];
1190 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
1192 /* local references to structure members to avoid repeated dereferences */
1193 int *coded_fragment_list = s->coded_fragment_list[plane];
1194 Vp3Fragment *all_fragments = s->all_fragments;
1195 VLC_TYPE(*vlc_table)[2] = table->table;
1197 if (num_coeffs < 0) {
1198 av_log(s->avctx, AV_LOG_ERROR,
1199 "Invalid number of coefficients at level %d\n", coeff_index);
1200 return AVERROR_INVALIDDATA;
1203 if (eob_run > num_coeffs) {
1205 blocks_ended = num_coeffs;
1206 eob_run -= num_coeffs;
1209 blocks_ended = eob_run;
1213 // insert fake EOB token to cover the split between planes or zzi
1215 dct_tokens[j++] = blocks_ended << 2;
1217 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1218 /* decode a VLC into a token */
1219 token = get_vlc2(gb, vlc_table, 11, 3);
1220 /* use the token to get a zero run, a coefficient, and an eob run */
1221 if ((unsigned) token <= 6U) {
1222 eob_run = get_eob_run(gb, token);
1226 // record only the number of blocks ended in this plane,
1227 // any spill will be recorded in the next plane.
1228 if (eob_run > num_coeffs - coeff_i) {
1229 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1230 blocks_ended += num_coeffs - coeff_i;
1231 eob_run -= num_coeffs - coeff_i;
1232 coeff_i = num_coeffs;
1234 dct_tokens[j++] = TOKEN_EOB(eob_run);
1235 blocks_ended += eob_run;
1239 } else if (token >= 0) {
1240 zero_run = get_coeff(gb, token, &coeff);
1243 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1245 // Save DC into the fragment structure. DC prediction is
1246 // done in raster order, so the actual DC can't be in with
1247 // other tokens. We still need the token in dct_tokens[]
1248 // however, or else the structure collapses on itself.
1250 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1252 dct_tokens[j++] = TOKEN_COEFF(coeff);
1255 if (coeff_index + zero_run > 64) {
1256 av_log(s->avctx, AV_LOG_DEBUG,
1257 "Invalid zero run of %d with %d coeffs left\n",
1258 zero_run, 64 - coeff_index);
1259 zero_run = 64 - coeff_index;
1262 // zero runs code multiple coefficients,
1263 // so don't try to decode coeffs for those higher levels
1264 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1265 s->num_coded_frags[plane][i]--;
1268 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1273 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1274 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1276 // decrement the number of blocks that have higher coefficients for each
1277 // EOB run at this level
1279 for (i = coeff_index + 1; i < 64; i++)
1280 s->num_coded_frags[plane][i] -= blocks_ended;
1282 // setup the next buffer
1284 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1285 else if (coeff_index < 63)
1286 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1291 static void reverse_dc_prediction(Vp3DecodeContext *s,
1294 int fragment_height);
1296 * This function unpacks all of the DCT coefficient data from the
1299 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1306 int residual_eob_run = 0;
1310 s->dct_tokens[0][0] = s->dct_tokens_base;
1312 if (get_bits_left(gb) < 16)
1313 return AVERROR_INVALIDDATA;
1315 /* fetch the DC table indexes */
1316 dc_y_table = get_bits(gb, 4);
1317 dc_c_table = get_bits(gb, 4);
1319 /* unpack the Y plane DC coefficients */
1320 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1321 0, residual_eob_run);
1322 if (residual_eob_run < 0)
1323 return residual_eob_run;
1324 if (get_bits_left(gb) < 8)
1325 return AVERROR_INVALIDDATA;
1327 /* reverse prediction of the Y-plane DC coefficients */
1328 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1330 /* unpack the C plane DC coefficients */
1331 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1332 1, residual_eob_run);
1333 if (residual_eob_run < 0)
1334 return residual_eob_run;
1335 residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1336 2, residual_eob_run);
1337 if (residual_eob_run < 0)
1338 return residual_eob_run;
1340 /* reverse prediction of the C-plane DC coefficients */
1341 if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1342 reverse_dc_prediction(s, s->fragment_start[1],
1343 s->fragment_width[1], s->fragment_height[1]);
1344 reverse_dc_prediction(s, s->fragment_start[2],
1345 s->fragment_width[1], s->fragment_height[1]);
1348 if (get_bits_left(gb) < 8)
1349 return AVERROR_INVALIDDATA;
1350 /* fetch the AC table indexes */
1351 ac_y_table = get_bits(gb, 4);
1352 ac_c_table = get_bits(gb, 4);
1354 /* build tables of AC VLC tables */
1355 for (i = 1; i <= 5; i++) {
1356 y_tables[i] = &s->ac_vlc_1[ac_y_table];
1357 c_tables[i] = &s->ac_vlc_1[ac_c_table];
1359 for (i = 6; i <= 14; i++) {
1360 y_tables[i] = &s->ac_vlc_2[ac_y_table];
1361 c_tables[i] = &s->ac_vlc_2[ac_c_table];
1363 for (i = 15; i <= 27; i++) {
1364 y_tables[i] = &s->ac_vlc_3[ac_y_table];
1365 c_tables[i] = &s->ac_vlc_3[ac_c_table];
1367 for (i = 28; i <= 63; i++) {
1368 y_tables[i] = &s->ac_vlc_4[ac_y_table];
1369 c_tables[i] = &s->ac_vlc_4[ac_c_table];
1372 /* decode all AC coefficients */
1373 for (i = 1; i <= 63; i++) {
1374 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1375 0, residual_eob_run);
1376 if (residual_eob_run < 0)
1377 return residual_eob_run;
1379 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1380 1, residual_eob_run);
1381 if (residual_eob_run < 0)
1382 return residual_eob_run;
1383 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1384 2, residual_eob_run);
1385 if (residual_eob_run < 0)
1386 return residual_eob_run;
1392 #if CONFIG_VP4_DECODER
1394 * eob_tracker[] is instead of TOKEN_EOB(value)
1395 * a dummy TOKEN_EOB(0) value is used to make vp3_dequant work
1397 * @return < 0 on error
1399 static int vp4_unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1400 VLC *vlc_tables[64],
1401 int plane, int eob_tracker[64], int fragment)
1409 while (!eob_tracker[coeff_i]) {
1410 if (get_bits_left(gb) < 1)
1411 return AVERROR_INVALIDDATA;
1413 token = get_vlc2(gb, vlc_tables[coeff_i]->table, 11, 3);
1415 /* use the token to get a zero run, a coefficient, and an eob run */
1416 if ((unsigned) token <= 6U) {
1417 eob_run = get_eob_run(gb, token);
1418 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1419 eob_tracker[coeff_i] = eob_run - 1;
1421 } else if (token >= 0) {
1422 zero_run = get_coeff(gb, token, &coeff);
1425 if (coeff_i + zero_run > 64) {
1426 av_log(s->avctx, AV_LOG_DEBUG,
1427 "Invalid zero run of %d with %d coeffs left\n",
1428 zero_run, 64 - coeff_i);
1429 zero_run = 64 - coeff_i;
1431 *s->dct_tokens[plane][coeff_i]++ = TOKEN_ZERO_RUN(coeff, zero_run);
1432 coeff_i += zero_run;
1435 s->all_fragments[fragment].dc = coeff;
1437 *s->dct_tokens[plane][coeff_i]++ = TOKEN_COEFF(coeff);
1440 if (coeff_i >= 64) /* > 64 occurs when there is a zero_run overflow */
1441 return 0; /* stop */
1443 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1447 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1448 eob_tracker[coeff_i]--;
1452 static void vp4_dc_predictor_reset(VP4Predictor *p)
1455 p->type = VP4_DC_UNDEFINED;
1458 static void vp4_dc_pred_before(const Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1462 for (i = 0; i < 4; i++)
1463 dc_pred[0][i + 1] = s->dc_pred_row[sb_x * 4 + i];
1465 for (j = 1; j < 5; j++)
1466 for (i = 0; i < 4; i++)
1467 vp4_dc_predictor_reset(&dc_pred[j][i + 1]);
1470 static void vp4_dc_pred_after(Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1474 for (i = 0; i < 4; i++)
1475 s->dc_pred_row[sb_x * 4 + i] = dc_pred[4][i + 1];
1477 for (i = 1; i < 5; i++)
1478 dc_pred[i][0] = dc_pred[i][4];
1481 /* note: dc_pred points to the current block */
1482 static int vp4_dc_pred(const Vp3DecodeContext *s, const VP4Predictor * dc_pred, const int * last_dc, int type, int plane)
1487 if (dc_pred[-6].type == type) {
1488 dc += dc_pred[-6].dc;
1492 if (dc_pred[6].type == type) {
1493 dc += dc_pred[6].dc;
1497 if (count != 2 && dc_pred[-1].type == type) {
1498 dc += dc_pred[-1].dc;
1502 if (count != 2 && dc_pred[1].type == type) {
1503 dc += dc_pred[1].dc;
1507 /* using division instead of shift to correctly handle negative values */
1508 return count == 2 ? dc / 2 : last_dc[type];
1511 static void vp4_set_tokens_base(Vp3DecodeContext *s)
1514 int16_t *base = s->dct_tokens_base;
1515 for (plane = 0; plane < 3; plane++) {
1516 for (i = 0; i < 64; i++) {
1517 s->dct_tokens[plane][i] = base;
1518 base += s->fragment_width[!!plane] * s->fragment_height[!!plane];
1523 static int vp4_unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1531 int plane, sb_y, sb_x;
1532 int eob_tracker[64];
1533 VP4Predictor dc_pred[6][6];
1534 int last_dc[NB_VP4_DC_TYPES];
1536 if (get_bits_left(gb) < 16)
1537 return AVERROR_INVALIDDATA;
1539 /* fetch the DC table indexes */
1540 dc_y_table = get_bits(gb, 4);
1541 dc_c_table = get_bits(gb, 4);
1543 ac_y_table = get_bits(gb, 4);
1544 ac_c_table = get_bits(gb, 4);
1546 /* build tables of DC/AC VLC tables */
1548 tables[0][0] = &s->dc_vlc[dc_y_table];
1549 tables[1][0] = &s->dc_vlc[dc_c_table];
1550 for (i = 1; i <= 5; i++) {
1551 tables[0][i] = &s->ac_vlc_1[ac_y_table];
1552 tables[1][i] = &s->ac_vlc_1[ac_c_table];
1554 for (i = 6; i <= 14; i++) {
1555 tables[0][i] = &s->ac_vlc_2[ac_y_table];
1556 tables[1][i] = &s->ac_vlc_2[ac_c_table];
1558 for (i = 15; i <= 27; i++) {
1559 tables[0][i] = &s->ac_vlc_3[ac_y_table];
1560 tables[1][i] = &s->ac_vlc_3[ac_c_table];
1562 for (i = 28; i <= 63; i++) {
1563 tables[0][i] = &s->ac_vlc_4[ac_y_table];
1564 tables[1][i] = &s->ac_vlc_4[ac_c_table];
1567 vp4_set_tokens_base(s);
1569 memset(last_dc, 0, sizeof(last_dc));
1571 for (plane = 0; plane < ((s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 1 : 3); plane++) {
1572 memset(eob_tracker, 0, sizeof(eob_tracker));
1574 /* initialise dc prediction */
1575 for (i = 0; i < s->fragment_width[!!plane]; i++)
1576 vp4_dc_predictor_reset(&s->dc_pred_row[i]);
1578 for (j = 0; j < 6; j++)
1579 for (i = 0; i < 6; i++)
1580 vp4_dc_predictor_reset(&dc_pred[j][i]);
1582 for (sb_y = 0; sb_y * 4 < s->fragment_height[!!plane]; sb_y++) {
1583 for (sb_x = 0; sb_x *4 < s->fragment_width[!!plane]; sb_x++) {
1584 vp4_dc_pred_before(s, dc_pred, sb_x);
1585 for (j = 0; j < 16; j++) {
1586 int hx = hilbert_offset[j][0];
1587 int hy = hilbert_offset[j][1];
1588 int x = 4 * sb_x + hx;
1589 int y = 4 * sb_y + hy;
1590 VP4Predictor *this_dc_pred = &dc_pred[hy + 1][hx + 1];
1591 int fragment, dc_block_type;
1593 if (x >= s->fragment_width[!!plane] || y >= s->fragment_height[!!plane])
1596 fragment = s->fragment_start[plane] + y * s->fragment_width[!!plane] + x;
1598 if (s->all_fragments[fragment].coding_method == MODE_COPY)
1601 if (vp4_unpack_vlcs(s, gb, tables[!!plane], plane, eob_tracker, fragment) < 0)
1604 dc_block_type = vp4_pred_block_type_map[s->all_fragments[fragment].coding_method];
1606 s->all_fragments[fragment].dc +=
1607 vp4_dc_pred(s, this_dc_pred, last_dc, dc_block_type, plane);
1609 this_dc_pred->type = dc_block_type,
1610 this_dc_pred->dc = last_dc[dc_block_type] = s->all_fragments[fragment].dc;
1612 vp4_dc_pred_after(s, dc_pred, sb_x);
1617 vp4_set_tokens_base(s);
1624 * This function reverses the DC prediction for each coded fragment in
1625 * the frame. Much of this function is adapted directly from the original
1628 #define COMPATIBLE_FRAME(x) \
1629 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1630 #define DC_COEFF(u) s->all_fragments[u].dc
1632 static void reverse_dc_prediction(Vp3DecodeContext *s,
1635 int fragment_height)
1643 int i = first_fragment;
1647 /* DC values for the left, up-left, up, and up-right fragments */
1648 int vl, vul, vu, vur;
1650 /* indexes for the left, up-left, up, and up-right fragments */
1654 * The 6 fields mean:
1655 * 0: up-left multiplier
1657 * 2: up-right multiplier
1658 * 3: left multiplier
1660 static const int predictor_transform[16][4] = {
1662 { 0, 0, 0, 128 }, // PL
1663 { 0, 0, 128, 0 }, // PUR
1664 { 0, 0, 53, 75 }, // PUR|PL
1665 { 0, 128, 0, 0 }, // PU
1666 { 0, 64, 0, 64 }, // PU |PL
1667 { 0, 128, 0, 0 }, // PU |PUR
1668 { 0, 0, 53, 75 }, // PU |PUR|PL
1669 { 128, 0, 0, 0 }, // PUL
1670 { 0, 0, 0, 128 }, // PUL|PL
1671 { 64, 0, 64, 0 }, // PUL|PUR
1672 { 0, 0, 53, 75 }, // PUL|PUR|PL
1673 { 0, 128, 0, 0 }, // PUL|PU
1674 { -104, 116, 0, 116 }, // PUL|PU |PL
1675 { 24, 80, 24, 0 }, // PUL|PU |PUR
1676 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1679 /* This table shows which types of blocks can use other blocks for
1680 * prediction. For example, INTRA is the only mode in this table to
1681 * have a frame number of 0. That means INTRA blocks can only predict
1682 * from other INTRA blocks. There are 2 golden frame coding types;
1683 * blocks encoding in these modes can only predict from other blocks
1684 * that were encoded with these 1 of these 2 modes. */
1685 static const unsigned char compatible_frame[9] = {
1686 1, /* MODE_INTER_NO_MV */
1688 1, /* MODE_INTER_PLUS_MV */
1689 1, /* MODE_INTER_LAST_MV */
1690 1, /* MODE_INTER_PRIOR_MV */
1691 2, /* MODE_USING_GOLDEN */
1692 2, /* MODE_GOLDEN_MV */
1693 1, /* MODE_INTER_FOUR_MV */
1696 int current_frame_type;
1698 /* there is a last DC predictor for each of the 3 frame types */
1711 /* for each fragment row... */
1712 for (y = 0; y < fragment_height; y++) {
1713 /* for each fragment in a row... */
1714 for (x = 0; x < fragment_width; x++, i++) {
1716 /* reverse prediction if this block was coded */
1717 if (s->all_fragments[i].coding_method != MODE_COPY) {
1718 current_frame_type =
1719 compatible_frame[s->all_fragments[i].coding_method];
1725 if (COMPATIBLE_FRAME(l))
1729 u = i - fragment_width;
1731 if (COMPATIBLE_FRAME(u))
1734 ul = i - fragment_width - 1;
1736 if (COMPATIBLE_FRAME(ul))
1739 if (x + 1 < fragment_width) {
1740 ur = i - fragment_width + 1;
1742 if (COMPATIBLE_FRAME(ur))
1747 if (transform == 0) {
1748 /* if there were no fragments to predict from, use last
1750 predicted_dc = last_dc[current_frame_type];
1752 /* apply the appropriate predictor transform */
1754 (predictor_transform[transform][0] * vul) +
1755 (predictor_transform[transform][1] * vu) +
1756 (predictor_transform[transform][2] * vur) +
1757 (predictor_transform[transform][3] * vl);
1759 predicted_dc /= 128;
1761 /* check for outranging on the [ul u l] and
1762 * [ul u ur l] predictors */
1763 if ((transform == 15) || (transform == 13)) {
1764 if (FFABS(predicted_dc - vu) > 128)
1766 else if (FFABS(predicted_dc - vl) > 128)
1768 else if (FFABS(predicted_dc - vul) > 128)
1773 /* at long last, apply the predictor */
1774 DC_COEFF(i) += predicted_dc;
1776 last_dc[current_frame_type] = DC_COEFF(i);
1782 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1783 int ystart, int yend)
1786 int *bounding_values = s->bounding_values_array + 127;
1788 int width = s->fragment_width[!!plane];
1789 int height = s->fragment_height[!!plane];
1790 int fragment = s->fragment_start[plane] + ystart * width;
1791 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1792 uint8_t *plane_data = s->current_frame.f->data[plane];
1793 if (!s->flipped_image)
1795 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1797 for (y = ystart; y < yend; y++) {
1798 for (x = 0; x < width; x++) {
1799 /* This code basically just deblocks on the edges of coded blocks.
1800 * However, it has to be much more complicated because of the
1801 * brain damaged deblock ordering used in VP3/Theora. Order matters
1802 * because some pixels get filtered twice. */
1803 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1804 /* do not perform left edge filter for left columns frags */
1806 s->vp3dsp.h_loop_filter(
1808 stride, bounding_values);
1811 /* do not perform top edge filter for top row fragments */
1813 s->vp3dsp.v_loop_filter(
1815 stride, bounding_values);
1818 /* do not perform right edge filter for right column
1819 * fragments or if right fragment neighbor is also coded
1820 * in this frame (it will be filtered in next iteration) */
1821 if ((x < width - 1) &&
1822 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1823 s->vp3dsp.h_loop_filter(
1824 plane_data + 8 * x + 8,
1825 stride, bounding_values);
1828 /* do not perform bottom edge filter for bottom row
1829 * fragments or if bottom fragment neighbor is also coded
1830 * in this frame (it will be filtered in the next row) */
1831 if ((y < height - 1) &&
1832 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1833 s->vp3dsp.v_loop_filter(
1834 plane_data + 8 * x + 8 * stride,
1835 stride, bounding_values);
1841 plane_data += 8 * stride;
1846 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1847 * for the next block in coding order
1849 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1850 int plane, int inter, int16_t block[64])
1852 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1853 uint8_t *perm = s->idct_scantable;
1857 int token = *s->dct_tokens[plane][i];
1858 switch (token & 3) {
1860 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1861 s->dct_tokens[plane][i]++;
1863 *s->dct_tokens[plane][i] = token & ~3;
1866 s->dct_tokens[plane][i]++;
1867 i += (token >> 2) & 0x7f;
1869 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1872 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1876 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1877 s->dct_tokens[plane][i++]++;
1879 default: // shouldn't happen
1883 // return value is expected to be a valid level
1886 // the actual DC+prediction is in the fragment structure
1887 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1892 * called when all pixels up to row y are complete
1894 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1897 int offset[AV_NUM_DATA_POINTERS];
1899 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1900 int y_flipped = s->flipped_image ? s->height - y : y;
1902 /* At the end of the frame, report INT_MAX instead of the height of
1903 * the frame. This makes the other threads' ff_thread_await_progress()
1904 * calls cheaper, because they don't have to clip their values. */
1905 ff_thread_report_progress(&s->current_frame,
1906 y_flipped == s->height ? INT_MAX
1911 if (!s->avctx->draw_horiz_band)
1914 h = y - s->last_slice_end;
1915 s->last_slice_end = y;
1918 if (!s->flipped_image)
1919 y = s->height - y - h;
1921 cy = y >> s->chroma_y_shift;
1922 offset[0] = s->current_frame.f->linesize[0] * y;
1923 offset[1] = s->current_frame.f->linesize[1] * cy;
1924 offset[2] = s->current_frame.f->linesize[2] * cy;
1925 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1929 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1933 * Wait for the reference frame of the current fragment.
1934 * The progress value is in luma pixel rows.
1936 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1937 int motion_y, int y)
1939 ThreadFrame *ref_frame;
1941 int border = motion_y & 1;
1943 if (fragment->coding_method == MODE_USING_GOLDEN ||
1944 fragment->coding_method == MODE_GOLDEN_MV)
1945 ref_frame = &s->golden_frame;
1947 ref_frame = &s->last_frame;
1949 ref_row = y + (motion_y >> 1);
1950 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1952 ff_thread_await_progress(ref_frame, ref_row, 0);
1955 #if CONFIG_VP4_DECODER
1957 * @return non-zero if temp (edge_emu_buffer) was populated
1959 static int vp4_mc_loop_filter(Vp3DecodeContext *s, int plane, int motion_x, int motion_y, int bx, int by,
1960 uint8_t * motion_source, int stride, int src_x, int src_y, uint8_t *temp)
1962 int motion_shift = plane ? 4 : 2;
1963 int subpel_mask = plane ? 3 : 1;
1964 int *bounding_values = s->bounding_values_array + 127;
1969 int x_subpel, y_subpel;
1970 int x_offset, y_offset;
1972 int block_width = plane ? 8 : 16;
1973 int plane_width = s->width >> (plane && s->chroma_x_shift);
1974 int plane_height = s->height >> (plane && s->chroma_y_shift);
1976 #define loop_stride 12
1977 uint8_t loop[12 * loop_stride];
1979 /* using division instead of shift to correctly handle negative values */
1980 x = 8 * bx + motion_x / motion_shift;
1981 y = 8 * by + motion_y / motion_shift;
1983 x_subpel = motion_x & subpel_mask;
1984 y_subpel = motion_y & subpel_mask;
1986 if (x_subpel || y_subpel) {
1991 x = FFMIN(x, x + FFSIGN(motion_x));
1994 y = FFMIN(y, y + FFSIGN(motion_y));
1996 x2 = x + block_width;
1997 y2 = y + block_width;
1999 if (x2 < 0 || x2 >= plane_width || y2 < 0 || y2 >= plane_height)
2002 x_offset = (-(x + 2) & 7) + 2;
2003 y_offset = (-(y + 2) & 7) + 2;
2005 if (x_offset > 8 + x_subpel && y_offset > 8 + y_subpel)
2008 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2009 loop_stride, stride,
2010 12, 12, src_x - 1, src_y - 1,
2014 if (x_offset <= 8 + x_subpel)
2015 ff_vp3dsp_h_loop_filter_12(loop + x_offset, loop_stride, bounding_values);
2017 if (y_offset <= 8 + y_subpel)
2018 ff_vp3dsp_v_loop_filter_12(loop + y_offset*loop_stride, loop_stride, bounding_values);
2025 if (!x_offset && !y_offset)
2028 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2029 loop_stride, stride,
2030 12, 12, src_x - 1, src_y - 1,
2034 #define safe_loop_filter(name, ptr, stride, bounding_values) \
2035 if ((uintptr_t)(ptr) & 7) \
2036 s->vp3dsp.name##_unaligned(ptr, stride, bounding_values); \
2038 s->vp3dsp.name(ptr, stride, bounding_values);
2041 safe_loop_filter(h_loop_filter, loop + loop_stride + x_offset + 1, loop_stride, bounding_values);
2044 safe_loop_filter(v_loop_filter, loop + (y_offset + 1)*loop_stride + 1, loop_stride, bounding_values);
2047 for (i = 0; i < 9; i++)
2048 memcpy(temp + i*stride, loop + (i + 1) * loop_stride + 1, 9);
2055 * Perform the final rendering for a particular slice of data.
2056 * The slice number ranges from 0..(c_superblock_height - 1).
2058 static void render_slice(Vp3DecodeContext *s, int slice)
2060 int x, y, i, j, fragment;
2061 int16_t *block = s->block;
2062 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
2063 int motion_halfpel_index;
2064 uint8_t *motion_source;
2065 int plane, first_pixel;
2067 if (slice >= s->c_superblock_height)
2070 for (plane = 0; plane < 3; plane++) {
2071 uint8_t *output_plane = s->current_frame.f->data[plane] +
2072 s->data_offset[plane];
2073 uint8_t *last_plane = s->last_frame.f->data[plane] +
2074 s->data_offset[plane];
2075 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
2076 s->data_offset[plane];
2077 ptrdiff_t stride = s->current_frame.f->linesize[plane];
2078 int plane_width = s->width >> (plane && s->chroma_x_shift);
2079 int plane_height = s->height >> (plane && s->chroma_y_shift);
2080 int8_t(*motion_val)[2] = s->motion_val[!!plane];
2082 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
2083 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
2084 int slice_width = plane ? s->c_superblock_width
2085 : s->y_superblock_width;
2087 int fragment_width = s->fragment_width[!!plane];
2088 int fragment_height = s->fragment_height[!!plane];
2089 int fragment_start = s->fragment_start[plane];
2091 int do_await = !plane && HAVE_THREADS &&
2092 (s->avctx->active_thread_type & FF_THREAD_FRAME);
2094 if (!s->flipped_image)
2096 if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
2099 /* for each superblock row in the slice (both of them)... */
2100 for (; sb_y < slice_height; sb_y++) {
2101 /* for each superblock in a row... */
2102 for (sb_x = 0; sb_x < slice_width; sb_x++) {
2103 /* for each block in a superblock... */
2104 for (j = 0; j < 16; j++) {
2105 x = 4 * sb_x + hilbert_offset[j][0];
2106 y = 4 * sb_y + hilbert_offset[j][1];
2107 fragment = y * fragment_width + x;
2109 i = fragment_start + fragment;
2112 if (x >= fragment_width || y >= fragment_height)
2115 first_pixel = 8 * y * stride + 8 * x;
2118 s->all_fragments[i].coding_method != MODE_INTRA)
2119 await_reference_row(s, &s->all_fragments[i],
2120 motion_val[fragment][1],
2121 (16 * y) >> s->chroma_y_shift);
2123 /* transform if this block was coded */
2124 if (s->all_fragments[i].coding_method != MODE_COPY) {
2125 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2126 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
2127 motion_source = golden_plane;
2129 motion_source = last_plane;
2131 motion_source += first_pixel;
2132 motion_halfpel_index = 0;
2134 /* sort out the motion vector if this fragment is coded
2135 * using a motion vector method */
2136 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
2137 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
2139 int standard_mc = 1;
2140 motion_x = motion_val[fragment][0];
2141 motion_y = motion_val[fragment][1];
2142 #if CONFIG_VP4_DECODER
2143 if (plane && s->version >= 2) {
2144 motion_x = (motion_x >> 1) | (motion_x & 1);
2145 motion_y = (motion_y >> 1) | (motion_y & 1);
2149 src_x = (motion_x >> 1) + 8 * x;
2150 src_y = (motion_y >> 1) + 8 * y;
2152 motion_halfpel_index = motion_x & 0x01;
2153 motion_source += (motion_x >> 1);
2155 motion_halfpel_index |= (motion_y & 0x01) << 1;
2156 motion_source += ((motion_y >> 1) * stride);
2158 #if CONFIG_VP4_DECODER
2159 if (s->version >= 2) {
2160 uint8_t *temp = s->edge_emu_buffer;
2163 if (vp4_mc_loop_filter(s, plane, motion_val[fragment][0], motion_val[fragment][1], x, y, motion_source, stride, src_x, src_y, temp)) {
2164 motion_source = temp;
2170 if (standard_mc && (
2171 src_x < 0 || src_y < 0 ||
2172 src_x + 9 >= plane_width ||
2173 src_y + 9 >= plane_height)) {
2174 uint8_t *temp = s->edge_emu_buffer;
2178 s->vdsp.emulated_edge_mc(temp, motion_source,
2183 motion_source = temp;
2187 /* first, take care of copying a block from either the
2188 * previous or the golden frame */
2189 if (s->all_fragments[i].coding_method != MODE_INTRA) {
2190 /* Note, it is possible to implement all MC cases
2191 * with put_no_rnd_pixels_l2 which would look more
2192 * like the VP3 source but this would be slower as
2193 * put_no_rnd_pixels_tab is better optimized */
2194 if (motion_halfpel_index != 3) {
2195 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
2196 output_plane + first_pixel,
2197 motion_source, stride, 8);
2199 /* d is 0 if motion_x and _y have the same sign,
2201 int d = (motion_x ^ motion_y) >> 31;
2202 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
2204 motion_source + stride + 1 + d,
2209 /* invert DCT and place (or add) in final output */
2211 if (s->all_fragments[i].coding_method == MODE_INTRA) {
2212 vp3_dequant(s, s->all_fragments + i,
2214 s->vp3dsp.idct_put(output_plane + first_pixel,
2218 if (vp3_dequant(s, s->all_fragments + i,
2220 s->vp3dsp.idct_add(output_plane + first_pixel,
2224 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
2229 /* copy directly from the previous frame */
2230 s->hdsp.put_pixels_tab[1][0](
2231 output_plane + first_pixel,
2232 last_plane + first_pixel,
2238 // Filter up to the last row in the superblock row
2239 if (s->version < 2 && !s->skip_loop_filter)
2240 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
2241 FFMIN(4 * sb_y + 3, fragment_height - 1));
2245 /* this looks like a good place for slice dispatch... */
2247 * if (slice == s->macroblock_height - 1)
2248 * dispatch (both last slice & 2nd-to-last slice);
2249 * else if (slice > 0)
2250 * dispatch (slice - 1);
2253 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
2257 /// Allocate tables for per-frame data in Vp3DecodeContext
2258 static av_cold int allocate_tables(AVCodecContext *avctx)
2260 Vp3DecodeContext *s = avctx->priv_data;
2261 int y_fragment_count, c_fragment_count;
2265 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2266 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2268 /* superblock_coding is used by unpack_superblocks (VP3/Theora) and vp4_unpack_macroblocks (VP4) */
2269 s->superblock_coding = av_mallocz(FFMAX(s->superblock_count, s->yuv_macroblock_count));
2270 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
2272 s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2273 s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2274 memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
2276 s->dct_tokens_base = av_mallocz_array(s->fragment_count,
2277 64 * sizeof(*s->dct_tokens_base));
2278 s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
2279 s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
2281 /* work out the block mapping tables */
2282 s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
2283 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
2285 s->dc_pred_row = av_malloc_array(s->y_superblock_width * 4, sizeof(*s->dc_pred_row));
2287 if (!s->superblock_coding || !s->all_fragments ||
2288 !s->dct_tokens_base || !s->kf_coded_fragment_list ||
2289 !s->nkf_coded_fragment_list ||
2290 !s->superblock_fragments || !s->macroblock_coding ||
2292 !s->motion_val[0] || !s->motion_val[1]) {
2293 vp3_decode_end(avctx);
2297 init_block_mapping(s);
2302 static av_cold int init_frames(Vp3DecodeContext *s)
2304 s->current_frame.f = av_frame_alloc();
2305 s->last_frame.f = av_frame_alloc();
2306 s->golden_frame.f = av_frame_alloc();
2308 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
2309 av_frame_free(&s->current_frame.f);
2310 av_frame_free(&s->last_frame.f);
2311 av_frame_free(&s->golden_frame.f);
2312 return AVERROR(ENOMEM);
2318 static av_cold int vp3_decode_init(AVCodecContext *avctx)
2320 Vp3DecodeContext *s = avctx->priv_data;
2321 int i, inter, plane, ret;
2324 int y_fragment_count, c_fragment_count;
2325 #if CONFIG_VP4_DECODER
2329 ret = init_frames(s);
2333 avctx->internal->allocate_progress = 1;
2335 if (avctx->codec_tag == MKTAG('V', 'P', '4', '0'))
2337 else if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
2343 s->width = FFALIGN(avctx->coded_width, 16);
2344 s->height = FFALIGN(avctx->coded_height, 16);
2345 if (avctx->codec_id != AV_CODEC_ID_THEORA)
2346 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2347 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
2348 ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
2349 ff_videodsp_init(&s->vdsp, 8);
2350 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
2352 for (i = 0; i < 64; i++) {
2353 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
2354 s->idct_permutation[i] = TRANSPOSE(i);
2355 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
2359 /* initialize to an impossible value which will force a recalculation
2360 * in the first frame decode */
2361 for (i = 0; i < 3; i++)
2364 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
2368 s->y_superblock_width = (s->width + 31) / 32;
2369 s->y_superblock_height = (s->height + 31) / 32;
2370 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
2372 /* work out the dimensions for the C planes */
2373 c_width = s->width >> s->chroma_x_shift;
2374 c_height = s->height >> s->chroma_y_shift;
2375 s->c_superblock_width = (c_width + 31) / 32;
2376 s->c_superblock_height = (c_height + 31) / 32;
2377 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
2379 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
2380 s->u_superblock_start = s->y_superblock_count;
2381 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
2383 s->macroblock_width = (s->width + 15) / 16;
2384 s->macroblock_height = (s->height + 15) / 16;
2385 s->macroblock_count = s->macroblock_width * s->macroblock_height;
2386 s->c_macroblock_width = (c_width + 15) / 16;
2387 s->c_macroblock_height = (c_height + 15) / 16;
2388 s->c_macroblock_count = s->c_macroblock_width * s->c_macroblock_height;
2389 s->yuv_macroblock_count = s->macroblock_count + 2 * s->c_macroblock_count;
2391 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
2392 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
2393 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
2394 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
2396 /* fragment count covers all 8x8 blocks for all 3 planes */
2397 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2398 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2399 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
2400 s->fragment_start[1] = y_fragment_count;
2401 s->fragment_start[2] = y_fragment_count + c_fragment_count;
2403 if (!s->theora_tables) {
2404 for (i = 0; i < 64; i++) {
2405 s->coded_dc_scale_factor[0][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_y_dc_scale_factor[i];
2406 s->coded_dc_scale_factor[1][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_uv_dc_scale_factor[i];
2407 s->coded_ac_scale_factor[i] = s->version < 2 ? vp31_ac_scale_factor[i] : vp4_ac_scale_factor[i];
2408 s->base_matrix[0][i] = s->version < 2 ? vp31_intra_y_dequant[i] : vp4_generic_dequant[i];
2409 s->base_matrix[1][i] = s->version < 2 ? vp31_intra_c_dequant[i] : vp4_generic_dequant[i];
2410 s->base_matrix[2][i] = s->version < 2 ? vp31_inter_dequant[i] : vp4_generic_dequant[i];
2411 s->filter_limit_values[i] = s->version < 2 ? vp31_filter_limit_values[i] : vp4_filter_limit_values[i];
2414 for (inter = 0; inter < 2; inter++) {
2415 for (plane = 0; plane < 3; plane++) {
2416 s->qr_count[inter][plane] = 1;
2417 s->qr_size[inter][plane][0] = 63;
2418 s->qr_base[inter][plane][0] =
2419 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
2423 /* init VLC tables */
2424 if (s->version < 2) {
2425 for (i = 0; i < 16; i++) {
2427 init_vlc(&s->dc_vlc[i], 11, 32,
2428 &dc_bias[i][0][1], 4, 2,
2429 &dc_bias[i][0][0], 4, 2, 0);
2431 /* group 1 AC histograms */
2432 init_vlc(&s->ac_vlc_1[i], 11, 32,
2433 &ac_bias_0[i][0][1], 4, 2,
2434 &ac_bias_0[i][0][0], 4, 2, 0);
2436 /* group 2 AC histograms */
2437 init_vlc(&s->ac_vlc_2[i], 11, 32,
2438 &ac_bias_1[i][0][1], 4, 2,
2439 &ac_bias_1[i][0][0], 4, 2, 0);
2441 /* group 3 AC histograms */
2442 init_vlc(&s->ac_vlc_3[i], 11, 32,
2443 &ac_bias_2[i][0][1], 4, 2,
2444 &ac_bias_2[i][0][0], 4, 2, 0);
2446 /* group 4 AC histograms */
2447 init_vlc(&s->ac_vlc_4[i], 11, 32,
2448 &ac_bias_3[i][0][1], 4, 2,
2449 &ac_bias_3[i][0][0], 4, 2, 0);
2451 #if CONFIG_VP4_DECODER
2452 } else { /* version >= 2 */
2453 for (i = 0; i < 16; i++) {
2455 init_vlc(&s->dc_vlc[i], 11, 32,
2456 &vp4_dc_bias[i][0][1], 4, 2,
2457 &vp4_dc_bias[i][0][0], 4, 2, 0);
2459 /* group 1 AC histograms */
2460 init_vlc(&s->ac_vlc_1[i], 11, 32,
2461 &vp4_ac_bias_0[i][0][1], 4, 2,
2462 &vp4_ac_bias_0[i][0][0], 4, 2, 0);
2464 /* group 2 AC histograms */
2465 init_vlc(&s->ac_vlc_2[i], 11, 32,
2466 &vp4_ac_bias_1[i][0][1], 4, 2,
2467 &vp4_ac_bias_1[i][0][0], 4, 2, 0);
2469 /* group 3 AC histograms */
2470 init_vlc(&s->ac_vlc_3[i], 11, 32,
2471 &vp4_ac_bias_2[i][0][1], 4, 2,
2472 &vp4_ac_bias_2[i][0][0], 4, 2, 0);
2474 /* group 4 AC histograms */
2475 init_vlc(&s->ac_vlc_4[i], 11, 32,
2476 &vp4_ac_bias_3[i][0][1], 4, 2,
2477 &vp4_ac_bias_3[i][0][0], 4, 2, 0);
2482 for (i = 0; i < 16; i++) {
2484 if (init_vlc(&s->dc_vlc[i], 11, 32,
2485 &s->huffman_table[i][0][1], 8, 4,
2486 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
2489 /* group 1 AC histograms */
2490 if (init_vlc(&s->ac_vlc_1[i], 11, 32,
2491 &s->huffman_table[i + 16][0][1], 8, 4,
2492 &s->huffman_table[i + 16][0][0], 8, 4, 0) < 0)
2495 /* group 2 AC histograms */
2496 if (init_vlc(&s->ac_vlc_2[i], 11, 32,
2497 &s->huffman_table[i + 16 * 2][0][1], 8, 4,
2498 &s->huffman_table[i + 16 * 2][0][0], 8, 4, 0) < 0)
2501 /* group 3 AC histograms */
2502 if (init_vlc(&s->ac_vlc_3[i], 11, 32,
2503 &s->huffman_table[i + 16 * 3][0][1], 8, 4,
2504 &s->huffman_table[i + 16 * 3][0][0], 8, 4, 0) < 0)
2507 /* group 4 AC histograms */
2508 if (init_vlc(&s->ac_vlc_4[i], 11, 32,
2509 &s->huffman_table[i + 16 * 4][0][1], 8, 4,
2510 &s->huffman_table[i + 16 * 4][0][0], 8, 4, 0) < 0)
2515 init_vlc(&s->superblock_run_length_vlc, 6, 34,
2516 &superblock_run_length_vlc_table[0][1], 4, 2,
2517 &superblock_run_length_vlc_table[0][0], 4, 2, 0);
2519 init_vlc(&s->fragment_run_length_vlc, 5, 30,
2520 &fragment_run_length_vlc_table[0][1], 4, 2,
2521 &fragment_run_length_vlc_table[0][0], 4, 2, 0);
2523 init_vlc(&s->mode_code_vlc, 3, 8,
2524 &mode_code_vlc_table[0][1], 2, 1,
2525 &mode_code_vlc_table[0][0], 2, 1, 0);
2527 init_vlc(&s->motion_vector_vlc, 6, 63,
2528 &motion_vector_vlc_table[0][1], 2, 1,
2529 &motion_vector_vlc_table[0][0], 2, 1, 0);
2531 #if CONFIG_VP4_DECODER
2532 for (j = 0; j < 2; j++)
2533 for (i = 0; i < 7; i++)
2534 init_vlc(&s->vp4_mv_vlc[j][i], 6, 63,
2535 &vp4_mv_vlc[j][i][0][1], 4, 2,
2536 &vp4_mv_vlc[j][i][0][0], 4, 2, 0);
2539 for (i = 0; i < 2; i++)
2540 init_vlc(&s->block_pattern_vlc[i], 3, 14,
2541 &vp4_block_pattern_vlc[i][0][1], 2, 1,
2542 &vp4_block_pattern_vlc[i][0][0], 2, 1, 0);
2545 return allocate_tables(avctx);
2548 av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
2552 /// Release and shuffle frames after decode finishes
2553 static int update_frames(AVCodecContext *avctx)
2555 Vp3DecodeContext *s = avctx->priv_data;
2558 /* shuffle frames (last = current) */
2559 ff_thread_release_buffer(avctx, &s->last_frame);
2560 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
2565 ff_thread_release_buffer(avctx, &s->golden_frame);
2566 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
2570 ff_thread_release_buffer(avctx, &s->current_frame);
2575 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
2577 ff_thread_release_buffer(s->avctx, dst);
2578 if (src->f->data[0])
2579 return ff_thread_ref_frame(dst, src);
2583 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
2586 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
2587 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
2588 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
2593 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
2595 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
2596 int qps_changed = 0, i, err;
2598 #define copy_fields(to, from, start_field, end_field) \
2599 memcpy(&to->start_field, &from->start_field, \
2600 (char *) &to->end_field - (char *) &to->start_field)
2602 if (!s1->current_frame.f->data[0] ||
2603 s->width != s1->width || s->height != s1->height) {
2610 if (!s->current_frame.f)
2611 return AVERROR(ENOMEM);
2612 // init tables if the first frame hasn't been decoded
2613 if (!s->current_frame.f->data[0]) {
2614 int y_fragment_count, c_fragment_count;
2616 err = allocate_tables(dst);
2619 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2620 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2621 memcpy(s->motion_val[0], s1->motion_val[0],
2622 y_fragment_count * sizeof(*s->motion_val[0]));
2623 memcpy(s->motion_val[1], s1->motion_val[1],
2624 c_fragment_count * sizeof(*s->motion_val[1]));
2627 // copy previous frame data
2628 if ((err = ref_frames(s, s1)) < 0)
2631 s->keyframe = s1->keyframe;
2633 // copy qscale data if necessary
2634 for (i = 0; i < 3; i++) {
2635 if (s->qps[i] != s1->qps[1]) {
2637 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2641 if (s->qps[0] != s1->qps[0])
2642 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2643 sizeof(s->bounding_values_array));
2646 copy_fields(s, s1, qps, superblock_count);
2650 return update_frames(dst);
2654 static int vp3_decode_frame(AVCodecContext *avctx,
2655 void *data, int *got_frame,
2658 AVFrame *frame = data;
2659 const uint8_t *buf = avpkt->data;
2660 int buf_size = avpkt->size;
2661 Vp3DecodeContext *s = avctx->priv_data;
2665 if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2668 #if CONFIG_THEORA_DECODER
2669 if (s->theora && get_bits1(&gb)) {
2670 int type = get_bits(&gb, 7);
2671 skip_bits_long(&gb, 6*8); /* "theora" */
2673 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2674 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2675 return AVERROR_PATCHWELCOME;
2678 vp3_decode_end(avctx);
2679 ret = theora_decode_header(avctx, &gb);
2682 ret = vp3_decode_init(avctx);
2684 vp3_decode_end(avctx);
2688 } else if (type == 2) {
2689 vp3_decode_end(avctx);
2690 ret = theora_decode_tables(avctx, &gb);
2692 ret = vp3_decode_init(avctx);
2694 vp3_decode_end(avctx);
2700 av_log(avctx, AV_LOG_ERROR,
2701 "Header packet passed to frame decoder, skipping\n");
2706 s->keyframe = !get_bits1(&gb);
2707 if (!s->all_fragments) {
2708 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2713 for (i = 0; i < 3; i++)
2714 s->last_qps[i] = s->qps[i];
2718 s->qps[s->nqps++] = get_bits(&gb, 6);
2719 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2720 for (i = s->nqps; i < 3; i++)
2723 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2724 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2725 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2727 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2728 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2729 : AVDISCARD_NONKEY);
2731 if (s->qps[0] != s->last_qps[0])
2732 init_loop_filter(s);
2734 for (i = 0; i < s->nqps; i++)
2735 // reinit all dequantizers if the first one changed, because
2736 // the DC of the first quantizer must be used for all matrices
2737 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2738 init_dequantizer(s, i);
2740 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2743 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2744 : AV_PICTURE_TYPE_P;
2745 s->current_frame.f->key_frame = s->keyframe;
2746 if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2749 if (!s->edge_emu_buffer)
2750 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2754 skip_bits(&gb, 4); /* width code */
2755 skip_bits(&gb, 4); /* height code */
2757 s->version = get_bits(&gb, 5);
2758 if (avctx->frame_number == 0)
2759 av_log(s->avctx, AV_LOG_DEBUG,
2760 "VP version: %d\n", s->version);
2763 if (s->version || s->theora) {
2765 av_log(s->avctx, AV_LOG_ERROR,
2766 "Warning, unsupported keyframe coding type?!\n");
2767 skip_bits(&gb, 2); /* reserved? */
2769 #if CONFIG_VP4_DECODER
2770 if (s->version >= 2) {
2771 int mb_height, mb_width;
2772 int mb_width_mul, mb_width_div, mb_height_mul, mb_height_div;
2774 mb_height = get_bits(&gb, 8);
2775 mb_width = get_bits(&gb, 8);
2776 if (mb_height != s->macroblock_height ||
2777 mb_width != s->macroblock_width)
2778 avpriv_request_sample(s->avctx, "macroblock dimension mismatch");
2780 mb_width_mul = get_bits(&gb, 5);
2781 mb_width_div = get_bits(&gb, 3);
2782 mb_height_mul = get_bits(&gb, 5);
2783 mb_height_div = get_bits(&gb, 3);
2784 if (mb_width_mul != 1 || mb_width_div != 1 || mb_height_mul != 1 || mb_height_div != 1)
2785 avpriv_request_sample(s->avctx, "unexpected macroblock dimension multipler/divider");
2787 if (get_bits(&gb, 2))
2788 avpriv_request_sample(s->avctx, "unknown bits");
2793 if (!s->golden_frame.f->data[0]) {
2794 av_log(s->avctx, AV_LOG_WARNING,
2795 "vp3: first frame not a keyframe\n");
2797 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2798 if (ff_thread_get_buffer(avctx, &s->golden_frame,
2799 AV_GET_BUFFER_FLAG_REF) < 0)
2801 ff_thread_release_buffer(avctx, &s->last_frame);
2802 if ((ret = ff_thread_ref_frame(&s->last_frame,
2803 &s->golden_frame)) < 0)
2805 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2809 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2810 ff_thread_finish_setup(avctx);
2812 if (s->version < 2) {
2813 if (unpack_superblocks(s, &gb)) {
2814 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2817 #if CONFIG_VP4_DECODER
2819 if (vp4_unpack_macroblocks(s, &gb)) {
2820 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_macroblocks\n");
2825 if (unpack_modes(s, &gb)) {
2826 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2829 if (unpack_vectors(s, &gb)) {
2830 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2833 if (unpack_block_qpis(s, &gb)) {
2834 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2838 if (s->version < 2) {
2839 if (unpack_dct_coeffs(s, &gb)) {
2840 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2843 #if CONFIG_VP4_DECODER
2845 if (vp4_unpack_dct_coeffs(s, &gb)) {
2846 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_dct_coeffs\n");
2852 for (i = 0; i < 3; i++) {
2853 int height = s->height >> (i && s->chroma_y_shift);
2854 if (s->flipped_image)
2855 s->data_offset[i] = 0;
2857 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2860 s->last_slice_end = 0;
2861 for (i = 0; i < s->c_superblock_height; i++)
2864 // filter the last row
2866 for (i = 0; i < 3; i++) {
2867 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2868 apply_loop_filter(s, i, row, row + 1);
2870 vp3_draw_horiz_band(s, s->height);
2872 /* output frame, offset as needed */
2873 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2876 frame->crop_left = s->offset_x;
2877 frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
2878 frame->crop_top = s->offset_y;
2879 frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2883 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2884 ret = update_frames(avctx);
2892 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2894 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2895 av_frame_unref(s->current_frame.f);
2900 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2902 Vp3DecodeContext *s = avctx->priv_data;
2904 if (get_bits1(gb)) {
2906 if (s->entries >= 32) { /* overflow */
2907 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2910 token = get_bits(gb, 5);
2911 ff_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2912 s->hti, s->hbits, token, s->entries, s->huff_code_size);
2913 s->huffman_table[s->hti][token][0] = s->hbits;
2914 s->huffman_table[s->hti][token][1] = s->huff_code_size;
2917 if (s->huff_code_size >= 32) { /* overflow */
2918 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2921 s->huff_code_size++;
2923 if (read_huffman_tree(avctx, gb))
2926 if (read_huffman_tree(avctx, gb))
2929 s->huff_code_size--;
2935 static int vp3_init_thread_copy(AVCodecContext *avctx)
2937 Vp3DecodeContext *s = avctx->priv_data;
2939 s->superblock_coding = NULL;
2940 s->all_fragments = NULL;
2941 s->coded_fragment_list[0] = NULL;
2942 s-> kf_coded_fragment_list= NULL;
2943 s->nkf_coded_fragment_list= NULL;
2944 s->dct_tokens_base = NULL;
2945 s->superblock_fragments = NULL;
2946 s->macroblock_coding = NULL;
2947 s->motion_val[0] = NULL;
2948 s->motion_val[1] = NULL;
2949 s->edge_emu_buffer = NULL;
2950 s->dc_pred_row = NULL;
2952 return init_frames(s);
2956 #if CONFIG_THEORA_DECODER
2957 static const enum AVPixelFormat theora_pix_fmts[4] = {
2958 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2961 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2963 Vp3DecodeContext *s = avctx->priv_data;
2964 int visible_width, visible_height, colorspace;
2965 uint8_t offset_x = 0, offset_y = 0;
2967 AVRational fps, aspect;
2969 s->theora_header = 0;
2970 s->theora = get_bits_long(gb, 24);
2971 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2974 avpriv_request_sample(s->avctx, "theora 0");
2977 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2978 * but previous versions have the image flipped relative to vp3 */
2979 if (s->theora < 0x030200) {
2980 s->flipped_image = 1;
2981 av_log(avctx, AV_LOG_DEBUG,
2982 "Old (<alpha3) Theora bitstream, flipped image\n");
2986 s->width = get_bits(gb, 16) << 4;
2988 s->height = get_bits(gb, 16) << 4;
2990 if (s->theora >= 0x030200) {
2991 visible_width = get_bits_long(gb, 24);
2992 visible_height = get_bits_long(gb, 24);
2994 offset_x = get_bits(gb, 8); /* offset x */
2995 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2999 if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
3000 visible_width + offset_x > s->width ||
3001 visible_height + offset_y > s->height) {
3002 av_log(avctx, AV_LOG_ERROR,
3003 "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
3004 visible_width, visible_height, offset_x, offset_y,
3005 s->width, s->height);
3006 return AVERROR_INVALIDDATA;
3009 fps.num = get_bits_long(gb, 32);
3010 fps.den = get_bits_long(gb, 32);
3011 if (fps.num && fps.den) {
3012 if (fps.num < 0 || fps.den < 0) {
3013 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
3014 return AVERROR_INVALIDDATA;
3016 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
3017 fps.den, fps.num, 1 << 30);
3020 aspect.num = get_bits_long(gb, 24);
3021 aspect.den = get_bits_long(gb, 24);
3022 if (aspect.num && aspect.den) {
3023 av_reduce(&avctx->sample_aspect_ratio.num,
3024 &avctx->sample_aspect_ratio.den,
3025 aspect.num, aspect.den, 1 << 30);
3026 ff_set_sar(avctx, avctx->sample_aspect_ratio);
3029 if (s->theora < 0x030200)
3030 skip_bits(gb, 5); /* keyframe frequency force */
3031 colorspace = get_bits(gb, 8);
3032 skip_bits(gb, 24); /* bitrate */
3034 skip_bits(gb, 6); /* quality hint */
3036 if (s->theora >= 0x030200) {
3037 skip_bits(gb, 5); /* keyframe frequency force */
3038 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
3039 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
3040 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
3041 return AVERROR_INVALIDDATA;
3043 skip_bits(gb, 3); /* reserved */
3045 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
3047 ret = ff_set_dimensions(avctx, s->width, s->height);
3050 if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
3051 avctx->width = visible_width;
3052 avctx->height = visible_height;
3053 // translate offsets from theora axis ([0,0] lower left)
3054 // to normal axis ([0,0] upper left)
3055 s->offset_x = offset_x;
3056 s->offset_y = s->height - visible_height - offset_y;
3059 if (colorspace == 1)
3060 avctx->color_primaries = AVCOL_PRI_BT470M;
3061 else if (colorspace == 2)
3062 avctx->color_primaries = AVCOL_PRI_BT470BG;
3064 if (colorspace == 1 || colorspace == 2) {
3065 avctx->colorspace = AVCOL_SPC_BT470BG;
3066 avctx->color_trc = AVCOL_TRC_BT709;
3069 s->theora_header = 1;
3073 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
3075 Vp3DecodeContext *s = avctx->priv_data;
3076 int i, n, matrices, inter, plane;
3078 if (!s->theora_header)
3079 return AVERROR_INVALIDDATA;
3081 if (s->theora >= 0x030200) {
3082 n = get_bits(gb, 3);
3083 /* loop filter limit values table */
3085 for (i = 0; i < 64; i++)
3086 s->filter_limit_values[i] = get_bits(gb, n);
3089 if (s->theora >= 0x030200)
3090 n = get_bits(gb, 4) + 1;
3093 /* quality threshold table */
3094 for (i = 0; i < 64; i++)
3095 s->coded_ac_scale_factor[i] = get_bits(gb, n);
3097 if (s->theora >= 0x030200)
3098 n = get_bits(gb, 4) + 1;
3101 /* dc scale factor table */
3102 for (i = 0; i < 64; i++)
3103 s->coded_dc_scale_factor[0][i] =
3104 s->coded_dc_scale_factor[1][i] = get_bits(gb, n);
3106 if (s->theora >= 0x030200)
3107 matrices = get_bits(gb, 9) + 1;
3111 if (matrices > 384) {
3112 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
3116 for (n = 0; n < matrices; n++)
3117 for (i = 0; i < 64; i++)
3118 s->base_matrix[n][i] = get_bits(gb, 8);
3120 for (inter = 0; inter <= 1; inter++) {
3121 for (plane = 0; plane <= 2; plane++) {
3123 if (inter || plane > 0)
3124 newqr = get_bits1(gb);
3127 if (inter && get_bits1(gb)) {
3131 qtj = (3 * inter + plane - 1) / 3;
3132 plj = (plane + 2) % 3;
3134 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
3135 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
3136 sizeof(s->qr_size[0][0]));
3137 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
3138 sizeof(s->qr_base[0][0]));
3144 i = get_bits(gb, av_log2(matrices - 1) + 1);
3145 if (i >= matrices) {
3146 av_log(avctx, AV_LOG_ERROR,
3147 "invalid base matrix index\n");
3150 s->qr_base[inter][plane][qri] = i;
3153 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
3154 s->qr_size[inter][plane][qri++] = i;
3159 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
3162 s->qr_count[inter][plane] = qri;
3167 /* Huffman tables */
3168 for (s->hti = 0; s->hti < 80; s->hti++) {
3170 s->huff_code_size = 1;
3171 if (!get_bits1(gb)) {
3173 if (read_huffman_tree(avctx, gb))
3176 if (read_huffman_tree(avctx, gb))
3181 s->theora_tables = 1;
3186 static av_cold int theora_decode_init(AVCodecContext *avctx)
3188 Vp3DecodeContext *s = avctx->priv_data;
3191 const uint8_t *header_start[3];
3196 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
3200 if (!avctx->extradata_size) {
3201 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
3205 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
3206 42, header_start, header_len) < 0) {
3207 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
3211 for (i = 0; i < 3; i++) {
3212 if (header_len[i] <= 0)
3214 ret = init_get_bits8(&gb, header_start[i], header_len[i]);
3218 ptype = get_bits(&gb, 8);
3220 if (!(ptype & 0x80)) {
3221 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
3225 // FIXME: Check for this as well.
3226 skip_bits_long(&gb, 6 * 8); /* "theora" */
3230 if (theora_decode_header(avctx, &gb) < 0)
3234 // FIXME: is this needed? it breaks sometimes
3235 // theora_decode_comments(avctx, gb);
3238 if (theora_decode_tables(avctx, &gb))
3242 av_log(avctx, AV_LOG_ERROR,
3243 "Unknown Theora config packet: %d\n", ptype & ~0x80);
3246 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
3247 av_log(avctx, AV_LOG_WARNING,
3248 "%d bits left in packet %X\n",
3249 8 * header_len[i] - get_bits_count(&gb), ptype);
3250 if (s->theora < 0x030200)
3254 return vp3_decode_init(avctx);
3257 AVCodec ff_theora_decoder = {
3259 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
3260 .type = AVMEDIA_TYPE_VIDEO,
3261 .id = AV_CODEC_ID_THEORA,
3262 .priv_data_size = sizeof(Vp3DecodeContext),
3263 .init = theora_decode_init,
3264 .close = vp3_decode_end,
3265 .decode = vp3_decode_frame,
3266 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3267 AV_CODEC_CAP_FRAME_THREADS,
3268 .flush = vp3_decode_flush,
3269 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
3270 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3271 .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING,
3275 AVCodec ff_vp3_decoder = {
3277 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
3278 .type = AVMEDIA_TYPE_VIDEO,
3279 .id = AV_CODEC_ID_VP3,
3280 .priv_data_size = sizeof(Vp3DecodeContext),
3281 .init = vp3_decode_init,
3282 .close = vp3_decode_end,
3283 .decode = vp3_decode_frame,
3284 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3285 AV_CODEC_CAP_FRAME_THREADS,
3286 .flush = vp3_decode_flush,
3287 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
3288 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3291 #if CONFIG_VP4_DECODER
3292 AVCodec ff_vp4_decoder = {
3294 .long_name = NULL_IF_CONFIG_SMALL("On2 VP4"),
3295 .type = AVMEDIA_TYPE_VIDEO,
3296 .id = AV_CODEC_ID_VP4,
3297 .priv_data_size = sizeof(Vp3DecodeContext),
3298 .init = vp3_decode_init,
3299 .close = vp3_decode_end,
3300 .decode = vp3_decode_frame,
3301 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3302 AV_CODEC_CAP_FRAME_THREADS,
3303 .flush = vp3_decode_flush,
3304 .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
3305 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),