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 HuffEntry {
162 typedef struct HuffTable {
163 HuffEntry entries[32];
167 typedef struct Vp3DecodeContext {
168 AVCodecContext *avctx;
169 int theora, theora_tables, theora_header;
172 int chroma_x_shift, chroma_y_shift;
173 ThreadFrame golden_frame;
174 ThreadFrame last_frame;
175 ThreadFrame current_frame;
177 uint8_t idct_permutation[64];
178 uint8_t idct_scantable[64];
180 VideoDSPContext vdsp;
181 VP3DSPContext vp3dsp;
182 DECLARE_ALIGNED(16, int16_t, block)[64];
185 int skip_loop_filter;
191 int superblock_count;
192 int y_superblock_width;
193 int y_superblock_height;
194 int y_superblock_count;
195 int c_superblock_width;
196 int c_superblock_height;
197 int c_superblock_count;
198 int u_superblock_start;
199 int v_superblock_start;
200 unsigned char *superblock_coding;
202 int macroblock_count; /* y macroblock count */
203 int macroblock_width;
204 int macroblock_height;
205 int c_macroblock_count;
206 int c_macroblock_width;
207 int c_macroblock_height;
208 int yuv_macroblock_count; /* y+u+v macroblock count */
211 int fragment_width[2];
212 int fragment_height[2];
214 Vp3Fragment *all_fragments;
215 int fragment_start[3];
221 int8_t (*motion_val[2])[2];
224 uint16_t coded_dc_scale_factor[2][64];
225 uint32_t coded_ac_scale_factor[64];
226 uint8_t base_matrix[384][64];
227 uint8_t qr_count[2][3];
228 uint8_t qr_size[2][3][64];
229 uint16_t qr_base[2][3][64];
232 * This is a list of all tokens in bitstream order. Reordering takes place
233 * by pulling from each level during IDCT. As a consequence, IDCT must be
234 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
235 * otherwise. The 32 different tokens with up to 12 bits of extradata are
236 * collapsed into 3 types, packed as follows:
237 * (from the low to high bits)
239 * 2 bits: type (0,1,2)
240 * 0: EOB run, 14 bits for run length (12 needed)
241 * 1: zero run, 7 bits for run length
242 * 7 bits for the next coefficient (3 needed)
243 * 2: coefficient, 14 bits (11 needed)
245 * Coefficients are signed, so are packed in the highest bits for automatic
248 int16_t *dct_tokens[3][64];
249 int16_t *dct_tokens_base;
250 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
251 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
252 #define TOKEN_COEFF(coeff) (((coeff) * 4) + 2)
255 * number of blocks that contain DCT coefficients at
256 * the given level or higher
258 int num_coded_frags[3][64];
259 int total_num_coded_frags;
261 /* this is a list of indexes into the all_fragments array indicating
262 * which of the fragments are coded */
263 int *coded_fragment_list[3];
265 int *kf_coded_fragment_list;
266 int *nkf_coded_fragment_list;
267 int num_kf_coded_fragment[3];
269 /* The first 16 of the following VLCs are for the dc coefficients;
270 the others are four groups of 16 VLCs each for ac coefficients. */
271 VLC coeff_vlc[5 * 16];
273 VLC superblock_run_length_vlc; /* version < 2 */
274 VLC fragment_run_length_vlc; /* version < 2 */
275 VLC block_pattern_vlc[2]; /* version >= 2*/
277 VLC motion_vector_vlc; /* version < 2 */
278 VLC vp4_mv_vlc[2][7]; /* version >=2 */
280 /* these arrays need to be on 16-byte boundaries since SSE2 operations
282 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
284 /* This table contains superblock_count * 16 entries. Each set of 16
285 * numbers corresponds to the fragment indexes 0..15 of the superblock.
286 * An entry will be -1 to indicate that no entry corresponds to that
288 int *superblock_fragments;
290 /* This is an array that indicates how a particular macroblock
292 unsigned char *macroblock_coding;
294 uint8_t *edge_emu_buffer;
297 HuffTable huffman_table[5 * 16];
299 uint8_t filter_limit_values[64];
300 DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
302 VP4Predictor * dc_pred_row; /* dc_pred_row[y_superblock_width * 4] */
305 /************************************************************************
306 * VP3 specific functions
307 ************************************************************************/
309 static av_cold void free_tables(AVCodecContext *avctx)
311 Vp3DecodeContext *s = avctx->priv_data;
313 av_freep(&s->superblock_coding);
314 av_freep(&s->all_fragments);
315 av_freep(&s->nkf_coded_fragment_list);
316 av_freep(&s->kf_coded_fragment_list);
317 av_freep(&s->dct_tokens_base);
318 av_freep(&s->superblock_fragments);
319 av_freep(&s->macroblock_coding);
320 av_freep(&s->dc_pred_row);
321 av_freep(&s->motion_val[0]);
322 av_freep(&s->motion_val[1]);
325 static void vp3_decode_flush(AVCodecContext *avctx)
327 Vp3DecodeContext *s = avctx->priv_data;
329 if (s->golden_frame.f)
330 ff_thread_release_buffer(avctx, &s->golden_frame);
332 ff_thread_release_buffer(avctx, &s->last_frame);
333 if (s->current_frame.f)
334 ff_thread_release_buffer(avctx, &s->current_frame);
337 static av_cold int vp3_decode_end(AVCodecContext *avctx)
339 Vp3DecodeContext *s = avctx->priv_data;
343 av_freep(&s->edge_emu_buffer);
345 s->theora_tables = 0;
347 /* release all frames */
348 vp3_decode_flush(avctx);
349 av_frame_free(&s->current_frame.f);
350 av_frame_free(&s->last_frame.f);
351 av_frame_free(&s->golden_frame.f);
353 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++)
354 ff_free_vlc(&s->coeff_vlc[i]);
356 ff_free_vlc(&s->superblock_run_length_vlc);
357 ff_free_vlc(&s->fragment_run_length_vlc);
358 ff_free_vlc(&s->mode_code_vlc);
359 ff_free_vlc(&s->motion_vector_vlc);
361 for (j = 0; j < 2; j++)
362 for (i = 0; i < 7; i++)
363 ff_free_vlc(&s->vp4_mv_vlc[j][i]);
365 for (i = 0; i < 2; i++)
366 ff_free_vlc(&s->block_pattern_vlc[i]);
371 * This function sets up all of the various blocks mappings:
372 * superblocks <-> fragments, macroblocks <-> fragments,
373 * superblocks <-> macroblocks
375 * @return 0 is successful; returns 1 if *anything* went wrong.
377 static int init_block_mapping(Vp3DecodeContext *s)
379 int sb_x, sb_y, plane;
382 for (plane = 0; plane < 3; plane++) {
383 int sb_width = plane ? s->c_superblock_width
384 : s->y_superblock_width;
385 int sb_height = plane ? s->c_superblock_height
386 : s->y_superblock_height;
387 int frag_width = s->fragment_width[!!plane];
388 int frag_height = s->fragment_height[!!plane];
390 for (sb_y = 0; sb_y < sb_height; sb_y++)
391 for (sb_x = 0; sb_x < sb_width; sb_x++)
392 for (i = 0; i < 16; i++) {
393 x = 4 * sb_x + hilbert_offset[i][0];
394 y = 4 * sb_y + hilbert_offset[i][1];
396 if (x < frag_width && y < frag_height)
397 s->superblock_fragments[j++] = s->fragment_start[plane] +
400 s->superblock_fragments[j++] = -1;
404 return 0; /* successful path out */
408 * This function sets up the dequantization tables used for a particular
411 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
413 int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
414 int i, plane, inter, qri, bmi, bmj, qistart;
416 for (inter = 0; inter < 2; inter++) {
417 for (plane = 0; plane < 3; plane++) {
418 int dc_scale_factor = s->coded_dc_scale_factor[!!plane][s->qps[qpi]];
420 for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
421 sum += s->qr_size[inter][plane][qri];
422 if (s->qps[qpi] <= sum)
425 qistart = sum - s->qr_size[inter][plane][qri];
426 bmi = s->qr_base[inter][plane][qri];
427 bmj = s->qr_base[inter][plane][qri + 1];
428 for (i = 0; i < 64; i++) {
429 int coeff = (2 * (sum - s->qps[qpi]) * s->base_matrix[bmi][i] -
430 2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
431 s->qr_size[inter][plane][qri]) /
432 (2 * s->qr_size[inter][plane][qri]);
434 int qmin = 8 << (inter + !i);
435 int qscale = i ? ac_scale_factor : dc_scale_factor;
436 int qbias = (1 + inter) * 3;
437 s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
438 (i == 0 || s->version < 2) ? av_clip((qscale * coeff) / 100 * 4, qmin, 4096)
439 : (qscale * (coeff - qbias) / 100 + qbias) * 4;
441 /* all DC coefficients use the same quant so as not to interfere
442 * with DC prediction */
443 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
449 * This function initializes the loop filter boundary limits if the frame's
450 * quality index is different from the previous frame's.
452 * The filter_limit_values may not be larger than 127.
454 static void init_loop_filter(Vp3DecodeContext *s)
456 ff_vp3dsp_set_bounding_values(s->bounding_values_array, s->filter_limit_values[s->qps[0]]);
460 * This function unpacks all of the superblock/macroblock/fragment coding
461 * information from the bitstream.
463 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
465 int superblock_starts[3] = {
466 0, s->u_superblock_start, s->v_superblock_start
469 int current_superblock = 0;
471 int num_partial_superblocks = 0;
474 int current_fragment;
476 int plane0_num_coded_frags = 0;
479 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
481 /* unpack the list of partially-coded superblocks */
482 bit = get_bits1(gb) ^ 1;
485 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
486 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
491 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
493 if (current_run == 34)
494 current_run += get_bits(gb, 12);
496 if (current_run > s->superblock_count - current_superblock) {
497 av_log(s->avctx, AV_LOG_ERROR,
498 "Invalid partially coded superblock run length\n");
502 memset(s->superblock_coding + current_superblock, bit, current_run);
504 current_superblock += current_run;
506 num_partial_superblocks += current_run;
509 /* unpack the list of fully coded superblocks if any of the blocks were
510 * not marked as partially coded in the previous step */
511 if (num_partial_superblocks < s->superblock_count) {
512 int superblocks_decoded = 0;
514 current_superblock = 0;
515 bit = get_bits1(gb) ^ 1;
518 while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
519 get_bits_left(gb) > 0) {
520 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
525 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
527 if (current_run == 34)
528 current_run += get_bits(gb, 12);
530 for (j = 0; j < current_run; current_superblock++) {
531 if (current_superblock >= s->superblock_count) {
532 av_log(s->avctx, AV_LOG_ERROR,
533 "Invalid fully coded superblock run length\n");
537 /* skip any superblocks already marked as partially coded */
538 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
539 s->superblock_coding[current_superblock] = 2 * bit;
543 superblocks_decoded += current_run;
547 /* if there were partial blocks, initialize bitstream for
548 * unpacking fragment codings */
549 if (num_partial_superblocks) {
552 /* toggle the bit because as soon as the first run length is
553 * fetched the bit will be toggled again */
558 /* figure out which fragments are coded; iterate through each
559 * superblock (all planes) */
560 s->total_num_coded_frags = 0;
561 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
563 s->coded_fragment_list[0] = s->keyframe ? s->kf_coded_fragment_list
564 : s->nkf_coded_fragment_list;
566 for (plane = 0; plane < 3; plane++) {
567 int sb_start = superblock_starts[plane];
568 int sb_end = sb_start + (plane ? s->c_superblock_count
569 : s->y_superblock_count);
570 int num_coded_frags = 0;
573 if (s->num_kf_coded_fragment[plane] == -1) {
574 for (i = sb_start; i < sb_end; i++) {
575 /* iterate through all 16 fragments in a superblock */
576 for (j = 0; j < 16; j++) {
577 /* if the fragment is in bounds, check its coding status */
578 current_fragment = s->superblock_fragments[i * 16 + j];
579 if (current_fragment != -1) {
580 s->coded_fragment_list[plane][num_coded_frags++] =
585 s->num_kf_coded_fragment[plane] = num_coded_frags;
587 num_coded_frags = s->num_kf_coded_fragment[plane];
589 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
590 if (get_bits_left(gb) < plane0_num_coded_frags >> 2) {
591 return AVERROR_INVALIDDATA;
593 /* iterate through all 16 fragments in a superblock */
594 for (j = 0; j < 16; j++) {
595 /* if the fragment is in bounds, check its coding status */
596 current_fragment = s->superblock_fragments[i * 16 + j];
597 if (current_fragment != -1) {
598 int coded = s->superblock_coding[i];
600 if (coded == SB_PARTIALLY_CODED) {
601 /* fragment may or may not be coded; this is the case
602 * that cares about the fragment coding runs */
603 if (current_run-- == 0) {
605 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
611 /* default mode; actual mode will be decoded in
613 s->all_fragments[current_fragment].coding_method =
615 s->coded_fragment_list[plane][num_coded_frags++] =
618 /* not coded; copy this fragment from the prior frame */
619 s->all_fragments[current_fragment].coding_method =
627 plane0_num_coded_frags = num_coded_frags;
628 s->total_num_coded_frags += num_coded_frags;
629 for (i = 0; i < 64; i++)
630 s->num_coded_frags[plane][i] = num_coded_frags;
632 s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
638 #define BLOCK_X (2 * mb_x + (k & 1))
639 #define BLOCK_Y (2 * mb_y + (k >> 1))
641 #if CONFIG_VP4_DECODER
643 * @return number of blocks, or > yuv_macroblock_count on error.
644 * return value is always >= 1.
646 static int vp4_get_mb_count(Vp3DecodeContext *s, GetBitContext *gb)
650 while ((bits = show_bits(gb, 9)) == 0x1ff) {
653 if (v > s->yuv_macroblock_count) {
654 av_log(s->avctx, AV_LOG_ERROR, "Invalid run length\n");
659 skip_bits(gb, 2 + n); \
660 v += (1 << n) + get_bits(gb, n); }
661 #define thresh(n) (0x200 - (0x80 >> n))
662 #define else_if(n) else if (bits < thresh(n)) body(n)
665 } else if (bits < thresh(0)) {
682 static int vp4_get_block_pattern(Vp3DecodeContext *s, GetBitContext *gb, int *next_block_pattern_table)
684 int v = get_vlc2(gb, s->block_pattern_vlc[*next_block_pattern_table].table, 3, 2);
686 av_log(s->avctx, AV_LOG_ERROR, "Invalid block pattern\n");
687 *next_block_pattern_table = 0;
690 *next_block_pattern_table = vp4_block_pattern_table_selector[v];
694 static int vp4_unpack_macroblocks(Vp3DecodeContext *s, GetBitContext *gb)
696 int plane, i, j, k, fragment;
697 int next_block_pattern_table;
698 int bit, current_run, has_partial;
700 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
707 for (i = 0; i < s->yuv_macroblock_count; i += current_run) {
708 if (get_bits_left(gb) <= 0)
709 return AVERROR_INVALIDDATA;
710 current_run = vp4_get_mb_count(s, gb);
711 if (current_run > s->yuv_macroblock_count - i)
713 memset(s->superblock_coding + i, 2 * bit, current_run);
719 if (get_bits_left(gb) <= 0)
720 return AVERROR_INVALIDDATA;
722 current_run = vp4_get_mb_count(s, gb);
723 for (i = 0; i < s->yuv_macroblock_count; i++) {
724 if (!s->superblock_coding[i]) {
727 current_run = vp4_get_mb_count(s, gb);
729 s->superblock_coding[i] = bit;
733 if (current_run) /* handle situation when vp4_get_mb_count() fails */
737 next_block_pattern_table = 0;
739 for (plane = 0; plane < 3; plane++) {
741 int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
742 int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
743 int mb_width = plane ? s->c_macroblock_width : s->macroblock_width;
744 int mb_height = plane ? s->c_macroblock_height : s->macroblock_height;
745 int fragment_width = s->fragment_width[!!plane];
746 int fragment_height = s->fragment_height[!!plane];
748 for (sb_y = 0; sb_y < sb_height; sb_y++) {
749 for (sb_x = 0; sb_x < sb_width; sb_x++) {
750 for (j = 0; j < 4; j++) {
751 int mb_x = 2 * sb_x + (j >> 1);
752 int mb_y = 2 * sb_y + (j >> 1) ^ (j & 1);
753 int mb_coded, pattern, coded;
755 if (mb_x >= mb_width || mb_y >= mb_height)
758 mb_coded = s->superblock_coding[i++];
760 if (mb_coded == SB_FULLY_CODED)
762 else if (mb_coded == SB_PARTIALLY_CODED)
763 pattern = vp4_get_block_pattern(s, gb, &next_block_pattern_table);
767 for (k = 0; k < 4; k++) {
768 if (BLOCK_X >= fragment_width || BLOCK_Y >= fragment_height)
770 fragment = s->fragment_start[plane] + BLOCK_Y * fragment_width + BLOCK_X;
771 coded = pattern & (8 >> k);
772 /* MODE_INTER_NO_MV is the default for coded fragments.
773 the actual method is decoded in the next phase. */
774 s->all_fragments[fragment].coding_method = coded ? MODE_INTER_NO_MV : MODE_COPY;
785 * This function unpacks all the coding mode data for individual macroblocks
786 * from the bitstream.
788 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
790 int i, j, k, sb_x, sb_y;
792 int current_macroblock;
793 int current_fragment;
795 int custom_mode_alphabet[CODING_MODE_COUNT];
800 for (i = 0; i < s->fragment_count; i++)
801 s->all_fragments[i].coding_method = MODE_INTRA;
803 /* fetch the mode coding scheme for this frame */
804 scheme = get_bits(gb, 3);
806 /* is it a custom coding scheme? */
808 for (i = 0; i < 8; i++)
809 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
810 for (i = 0; i < 8; i++)
811 custom_mode_alphabet[get_bits(gb, 3)] = i;
812 alphabet = custom_mode_alphabet;
814 alphabet = ModeAlphabet[scheme - 1];
816 /* iterate through all of the macroblocks that contain 1 or more
818 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
819 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
820 if (get_bits_left(gb) <= 0)
823 for (j = 0; j < 4; j++) {
824 int mb_x = 2 * sb_x + (j >> 1);
825 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
826 current_macroblock = mb_y * s->macroblock_width + mb_x;
828 if (mb_x >= s->macroblock_width ||
829 mb_y >= s->macroblock_height)
832 /* coding modes are only stored if the macroblock has
833 * at least one luma block coded, otherwise it must be
835 for (k = 0; k < 4; k++) {
836 current_fragment = BLOCK_Y *
837 s->fragment_width[0] + BLOCK_X;
838 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
842 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
846 /* mode 7 means get 3 bits for each coding mode */
848 coding_mode = get_bits(gb, 3);
850 coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
852 s->macroblock_coding[current_macroblock] = coding_mode;
853 for (k = 0; k < 4; k++) {
854 frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
855 if (frag->coding_method != MODE_COPY)
856 frag->coding_method = coding_mode;
859 #define SET_CHROMA_MODES \
860 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
861 frag[s->fragment_start[1]].coding_method = coding_mode; \
862 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
863 frag[s->fragment_start[2]].coding_method = coding_mode;
865 if (s->chroma_y_shift) {
866 frag = s->all_fragments + mb_y *
867 s->fragment_width[1] + mb_x;
869 } else if (s->chroma_x_shift) {
870 frag = s->all_fragments +
871 2 * mb_y * s->fragment_width[1] + mb_x;
872 for (k = 0; k < 2; k++) {
874 frag += s->fragment_width[1];
877 for (k = 0; k < 4; k++) {
878 frag = s->all_fragments +
879 BLOCK_Y * s->fragment_width[1] + BLOCK_X;
891 static int vp4_get_mv(Vp3DecodeContext *s, GetBitContext *gb, int axis, int last_motion)
893 int v = get_vlc2(gb, s->vp4_mv_vlc[axis][vp4_mv_table_selector[FFABS(last_motion)]].table, 6, 2) - 31;
894 return last_motion < 0 ? -v : v;
898 * This function unpacks all the motion vectors for the individual
899 * macroblocks from the bitstream.
901 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
903 int j, k, sb_x, sb_y;
907 int last_motion_x = 0;
908 int last_motion_y = 0;
909 int prior_last_motion_x = 0;
910 int prior_last_motion_y = 0;
911 int last_gold_motion_x = 0;
912 int last_gold_motion_y = 0;
913 int current_macroblock;
914 int current_fragment;
920 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme; 2 is VP4 code scheme */
921 coding_mode = s->version < 2 ? get_bits1(gb) : 2;
923 /* iterate through all of the macroblocks that contain 1 or more
925 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
926 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
927 if (get_bits_left(gb) <= 0)
930 for (j = 0; j < 4; j++) {
931 int mb_x = 2 * sb_x + (j >> 1);
932 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
933 current_macroblock = mb_y * s->macroblock_width + mb_x;
935 if (mb_x >= s->macroblock_width ||
936 mb_y >= s->macroblock_height ||
937 s->macroblock_coding[current_macroblock] == MODE_COPY)
940 switch (s->macroblock_coding[current_macroblock]) {
942 if (coding_mode == 2) { /* VP4 */
943 last_gold_motion_x = motion_x[0] = vp4_get_mv(s, gb, 0, last_gold_motion_x);
944 last_gold_motion_y = motion_y[0] = vp4_get_mv(s, gb, 1, last_gold_motion_y);
946 } /* otherwise fall through */
947 case MODE_INTER_PLUS_MV:
948 /* all 6 fragments use the same motion vector */
949 if (coding_mode == 0) {
950 motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
951 motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
952 } else if (coding_mode == 1) {
953 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
954 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
956 motion_x[0] = vp4_get_mv(s, gb, 0, last_motion_x);
957 motion_y[0] = vp4_get_mv(s, gb, 1, last_motion_y);
960 /* vector maintenance, only on MODE_INTER_PLUS_MV */
961 if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
962 prior_last_motion_x = last_motion_x;
963 prior_last_motion_y = last_motion_y;
964 last_motion_x = motion_x[0];
965 last_motion_y = motion_y[0];
969 case MODE_INTER_FOURMV:
970 /* vector maintenance */
971 prior_last_motion_x = last_motion_x;
972 prior_last_motion_y = last_motion_y;
974 /* fetch 4 vectors from the bitstream, one for each
975 * Y fragment, then average for the C fragment vectors */
976 for (k = 0; k < 4; k++) {
977 current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
978 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
979 if (coding_mode == 0) {
980 motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
981 motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
982 } else if (coding_mode == 1) {
983 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
984 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
986 motion_x[k] = vp4_get_mv(s, gb, 0, prior_last_motion_x);
987 motion_y[k] = vp4_get_mv(s, gb, 1, prior_last_motion_y);
989 last_motion_x = motion_x[k];
990 last_motion_y = motion_y[k];
998 case MODE_INTER_LAST_MV:
999 /* all 6 fragments use the last motion vector */
1000 motion_x[0] = last_motion_x;
1001 motion_y[0] = last_motion_y;
1003 /* no vector maintenance (last vector remains the
1007 case MODE_INTER_PRIOR_LAST:
1008 /* all 6 fragments use the motion vector prior to the
1009 * last motion vector */
1010 motion_x[0] = prior_last_motion_x;
1011 motion_y[0] = prior_last_motion_y;
1013 /* vector maintenance */
1014 prior_last_motion_x = last_motion_x;
1015 prior_last_motion_y = last_motion_y;
1016 last_motion_x = motion_x[0];
1017 last_motion_y = motion_y[0];
1021 /* covers intra, inter without MV, golden without MV */
1025 /* no vector maintenance */
1029 /* assign the motion vectors to the correct fragments */
1030 for (k = 0; k < 4; k++) {
1032 BLOCK_Y * s->fragment_width[0] + BLOCK_X;
1033 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1034 s->motion_val[0][current_fragment][0] = motion_x[k];
1035 s->motion_val[0][current_fragment][1] = motion_y[k];
1037 s->motion_val[0][current_fragment][0] = motion_x[0];
1038 s->motion_val[0][current_fragment][1] = motion_y[0];
1042 if (s->chroma_y_shift) {
1043 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1044 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
1045 motion_x[2] + motion_x[3], 2);
1046 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
1047 motion_y[2] + motion_y[3], 2);
1049 if (s->version <= 2) {
1050 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1051 motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
1053 frag = mb_y * s->fragment_width[1] + mb_x;
1054 s->motion_val[1][frag][0] = motion_x[0];
1055 s->motion_val[1][frag][1] = motion_y[0];
1056 } else if (s->chroma_x_shift) {
1057 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1058 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
1059 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
1060 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
1061 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
1063 motion_x[1] = motion_x[0];
1064 motion_y[1] = motion_y[0];
1066 if (s->version <= 2) {
1067 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1068 motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
1070 frag = 2 * mb_y * s->fragment_width[1] + mb_x;
1071 for (k = 0; k < 2; k++) {
1072 s->motion_val[1][frag][0] = motion_x[k];
1073 s->motion_val[1][frag][1] = motion_y[k];
1074 frag += s->fragment_width[1];
1077 for (k = 0; k < 4; k++) {
1078 frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
1079 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1080 s->motion_val[1][frag][0] = motion_x[k];
1081 s->motion_val[1][frag][1] = motion_y[k];
1083 s->motion_val[1][frag][0] = motion_x[0];
1084 s->motion_val[1][frag][1] = motion_y[0];
1095 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
1097 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
1098 int num_blocks = s->total_num_coded_frags;
1100 for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
1101 i = blocks_decoded = num_blocks_at_qpi = 0;
1103 bit = get_bits1(gb) ^ 1;
1107 if (run_length == MAXIMUM_LONG_BIT_RUN)
1108 bit = get_bits1(gb);
1112 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
1113 if (run_length == 34)
1114 run_length += get_bits(gb, 12);
1115 blocks_decoded += run_length;
1118 num_blocks_at_qpi += run_length;
1120 for (j = 0; j < run_length; i++) {
1121 if (i >= s->total_num_coded_frags)
1124 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
1125 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
1129 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
1131 num_blocks -= num_blocks_at_qpi;
1137 static inline int get_eob_run(GetBitContext *gb, int token)
1139 int v = eob_run_table[token].base;
1140 if (eob_run_table[token].bits)
1141 v += get_bits(gb, eob_run_table[token].bits);
1145 static inline int get_coeff(GetBitContext *gb, int token, int16_t *coeff)
1147 int bits_to_get, zero_run;
1149 bits_to_get = coeff_get_bits[token];
1151 bits_to_get = get_bits(gb, bits_to_get);
1152 *coeff = coeff_tables[token][bits_to_get];
1154 zero_run = zero_run_base[token];
1155 if (zero_run_get_bits[token])
1156 zero_run += get_bits(gb, zero_run_get_bits[token]);
1162 * This function is called by unpack_dct_coeffs() to extract the VLCs from
1163 * the bitstream. The VLCs encode tokens which are used to unpack DCT
1164 * data. This function unpacks all the VLCs for either the Y plane or both
1165 * C planes, and is called for DC coefficients or different AC coefficient
1166 * levels (since different coefficient types require different VLC tables.
1168 * This function returns a residual eob run. E.g, if a particular token gave
1169 * instructions to EOB the next 5 fragments and there were only 2 fragments
1170 * left in the current fragment range, 3 would be returned so that it could
1171 * be passed into the next call to this same function.
1173 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1174 VLC *table, int coeff_index,
1184 int num_coeffs = s->num_coded_frags[plane][coeff_index];
1185 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
1187 /* local references to structure members to avoid repeated dereferences */
1188 int *coded_fragment_list = s->coded_fragment_list[plane];
1189 Vp3Fragment *all_fragments = s->all_fragments;
1190 VLC_TYPE(*vlc_table)[2] = table->table;
1192 if (num_coeffs < 0) {
1193 av_log(s->avctx, AV_LOG_ERROR,
1194 "Invalid number of coefficients at level %d\n", coeff_index);
1195 return AVERROR_INVALIDDATA;
1198 if (eob_run > num_coeffs) {
1200 blocks_ended = num_coeffs;
1201 eob_run -= num_coeffs;
1204 blocks_ended = eob_run;
1208 // insert fake EOB token to cover the split between planes or zzi
1210 dct_tokens[j++] = blocks_ended << 2;
1212 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1213 /* decode a VLC into a token */
1214 token = get_vlc2(gb, vlc_table, 11, 3);
1215 /* use the token to get a zero run, a coefficient, and an eob run */
1216 if ((unsigned) token <= 6U) {
1217 eob_run = get_eob_run(gb, token);
1221 // record only the number of blocks ended in this plane,
1222 // any spill will be recorded in the next plane.
1223 if (eob_run > num_coeffs - coeff_i) {
1224 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1225 blocks_ended += num_coeffs - coeff_i;
1226 eob_run -= num_coeffs - coeff_i;
1227 coeff_i = num_coeffs;
1229 dct_tokens[j++] = TOKEN_EOB(eob_run);
1230 blocks_ended += eob_run;
1234 } else if (token >= 0) {
1235 zero_run = get_coeff(gb, token, &coeff);
1238 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1240 // Save DC into the fragment structure. DC prediction is
1241 // done in raster order, so the actual DC can't be in with
1242 // other tokens. We still need the token in dct_tokens[]
1243 // however, or else the structure collapses on itself.
1245 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1247 dct_tokens[j++] = TOKEN_COEFF(coeff);
1250 if (coeff_index + zero_run > 64) {
1251 av_log(s->avctx, AV_LOG_DEBUG,
1252 "Invalid zero run of %d with %d coeffs left\n",
1253 zero_run, 64 - coeff_index);
1254 zero_run = 64 - coeff_index;
1257 // zero runs code multiple coefficients,
1258 // so don't try to decode coeffs for those higher levels
1259 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1260 s->num_coded_frags[plane][i]--;
1263 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1268 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1269 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1271 // decrement the number of blocks that have higher coefficients for each
1272 // EOB run at this level
1274 for (i = coeff_index + 1; i < 64; i++)
1275 s->num_coded_frags[plane][i] -= blocks_ended;
1277 // setup the next buffer
1279 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1280 else if (coeff_index < 63)
1281 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1286 static void reverse_dc_prediction(Vp3DecodeContext *s,
1289 int fragment_height);
1291 * This function unpacks all of the DCT coefficient data from the
1294 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1301 int residual_eob_run = 0;
1305 s->dct_tokens[0][0] = s->dct_tokens_base;
1307 if (get_bits_left(gb) < 16)
1308 return AVERROR_INVALIDDATA;
1310 /* fetch the DC table indexes */
1311 dc_y_table = get_bits(gb, 4);
1312 dc_c_table = get_bits(gb, 4);
1314 /* unpack the Y plane DC coefficients */
1315 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_y_table], 0,
1316 0, residual_eob_run);
1317 if (residual_eob_run < 0)
1318 return residual_eob_run;
1319 if (get_bits_left(gb) < 8)
1320 return AVERROR_INVALIDDATA;
1322 /* reverse prediction of the Y-plane DC coefficients */
1323 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1325 /* unpack the C plane DC coefficients */
1326 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1327 1, residual_eob_run);
1328 if (residual_eob_run < 0)
1329 return residual_eob_run;
1330 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1331 2, residual_eob_run);
1332 if (residual_eob_run < 0)
1333 return residual_eob_run;
1335 /* reverse prediction of the C-plane DC coefficients */
1336 if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1337 reverse_dc_prediction(s, s->fragment_start[1],
1338 s->fragment_width[1], s->fragment_height[1]);
1339 reverse_dc_prediction(s, s->fragment_start[2],
1340 s->fragment_width[1], s->fragment_height[1]);
1343 if (get_bits_left(gb) < 8)
1344 return AVERROR_INVALIDDATA;
1345 /* fetch the AC table indexes */
1346 ac_y_table = get_bits(gb, 4);
1347 ac_c_table = get_bits(gb, 4);
1349 /* build tables of AC VLC tables */
1350 for (i = 1; i <= 5; i++) {
1351 /* AC VLC table group 1 */
1352 y_tables[i] = &s->coeff_vlc[ac_y_table + 16];
1353 c_tables[i] = &s->coeff_vlc[ac_c_table + 16];
1355 for (i = 6; i <= 14; i++) {
1356 /* AC VLC table group 2 */
1357 y_tables[i] = &s->coeff_vlc[ac_y_table + 32];
1358 c_tables[i] = &s->coeff_vlc[ac_c_table + 32];
1360 for (i = 15; i <= 27; i++) {
1361 /* AC VLC table group 3 */
1362 y_tables[i] = &s->coeff_vlc[ac_y_table + 48];
1363 c_tables[i] = &s->coeff_vlc[ac_c_table + 48];
1365 for (i = 28; i <= 63; i++) {
1366 /* AC VLC table group 4 */
1367 y_tables[i] = &s->coeff_vlc[ac_y_table + 64];
1368 c_tables[i] = &s->coeff_vlc[ac_c_table + 64];
1371 /* decode all AC coefficients */
1372 for (i = 1; i <= 63; i++) {
1373 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1374 0, residual_eob_run);
1375 if (residual_eob_run < 0)
1376 return residual_eob_run;
1378 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1379 1, residual_eob_run);
1380 if (residual_eob_run < 0)
1381 return residual_eob_run;
1382 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1383 2, residual_eob_run);
1384 if (residual_eob_run < 0)
1385 return residual_eob_run;
1391 #if CONFIG_VP4_DECODER
1393 * eob_tracker[] is instead of TOKEN_EOB(value)
1394 * a dummy TOKEN_EOB(0) value is used to make vp3_dequant work
1396 * @return < 0 on error
1398 static int vp4_unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1399 VLC *vlc_tables[64],
1400 int plane, int eob_tracker[64], int fragment)
1408 while (!eob_tracker[coeff_i]) {
1409 if (get_bits_left(gb) < 1)
1410 return AVERROR_INVALIDDATA;
1412 token = get_vlc2(gb, vlc_tables[coeff_i]->table, 11, 3);
1414 /* use the token to get a zero run, a coefficient, and an eob run */
1415 if ((unsigned) token <= 6U) {
1416 eob_run = get_eob_run(gb, token);
1417 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1418 eob_tracker[coeff_i] = eob_run - 1;
1420 } else if (token >= 0) {
1421 zero_run = get_coeff(gb, token, &coeff);
1424 if (coeff_i + zero_run > 64) {
1425 av_log(s->avctx, AV_LOG_DEBUG,
1426 "Invalid zero run of %d with %d coeffs left\n",
1427 zero_run, 64 - coeff_i);
1428 zero_run = 64 - coeff_i;
1430 *s->dct_tokens[plane][coeff_i]++ = TOKEN_ZERO_RUN(coeff, zero_run);
1431 coeff_i += zero_run;
1434 s->all_fragments[fragment].dc = coeff;
1436 *s->dct_tokens[plane][coeff_i]++ = TOKEN_COEFF(coeff);
1439 if (coeff_i >= 64) /* > 64 occurs when there is a zero_run overflow */
1440 return 0; /* stop */
1442 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1446 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1447 eob_tracker[coeff_i]--;
1451 static void vp4_dc_predictor_reset(VP4Predictor *p)
1454 p->type = VP4_DC_UNDEFINED;
1457 static void vp4_dc_pred_before(const Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1461 for (i = 0; i < 4; i++)
1462 dc_pred[0][i + 1] = s->dc_pred_row[sb_x * 4 + i];
1464 for (j = 1; j < 5; j++)
1465 for (i = 0; i < 4; i++)
1466 vp4_dc_predictor_reset(&dc_pred[j][i + 1]);
1469 static void vp4_dc_pred_after(Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1473 for (i = 0; i < 4; i++)
1474 s->dc_pred_row[sb_x * 4 + i] = dc_pred[4][i + 1];
1476 for (i = 1; i < 5; i++)
1477 dc_pred[i][0] = dc_pred[i][4];
1480 /* note: dc_pred points to the current block */
1481 static int vp4_dc_pred(const Vp3DecodeContext *s, const VP4Predictor * dc_pred, const int * last_dc, int type, int plane)
1486 if (dc_pred[-6].type == type) {
1487 dc += dc_pred[-6].dc;
1491 if (dc_pred[6].type == type) {
1492 dc += dc_pred[6].dc;
1496 if (count != 2 && dc_pred[-1].type == type) {
1497 dc += dc_pred[-1].dc;
1501 if (count != 2 && dc_pred[1].type == type) {
1502 dc += dc_pred[1].dc;
1506 /* using division instead of shift to correctly handle negative values */
1507 return count == 2 ? dc / 2 : last_dc[type];
1510 static void vp4_set_tokens_base(Vp3DecodeContext *s)
1513 int16_t *base = s->dct_tokens_base;
1514 for (plane = 0; plane < 3; plane++) {
1515 for (i = 0; i < 64; i++) {
1516 s->dct_tokens[plane][i] = base;
1517 base += s->fragment_width[!!plane] * s->fragment_height[!!plane];
1522 static int vp4_unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1530 int plane, sb_y, sb_x;
1531 int eob_tracker[64];
1532 VP4Predictor dc_pred[6][6];
1533 int last_dc[NB_VP4_DC_TYPES];
1535 if (get_bits_left(gb) < 16)
1536 return AVERROR_INVALIDDATA;
1538 /* fetch the DC table indexes */
1539 dc_y_table = get_bits(gb, 4);
1540 dc_c_table = get_bits(gb, 4);
1542 ac_y_table = get_bits(gb, 4);
1543 ac_c_table = get_bits(gb, 4);
1545 /* build tables of DC/AC VLC tables */
1547 /* DC table group */
1548 tables[0][0] = &s->coeff_vlc[dc_y_table];
1549 tables[1][0] = &s->coeff_vlc[dc_c_table];
1550 for (i = 1; i <= 5; i++) {
1551 /* AC VLC table group 1 */
1552 tables[0][i] = &s->coeff_vlc[ac_y_table + 16];
1553 tables[1][i] = &s->coeff_vlc[ac_c_table + 16];
1555 for (i = 6; i <= 14; i++) {
1556 /* AC VLC table group 2 */
1557 tables[0][i] = &s->coeff_vlc[ac_y_table + 32];
1558 tables[1][i] = &s->coeff_vlc[ac_c_table + 32];
1560 for (i = 15; i <= 27; i++) {
1561 /* AC VLC table group 3 */
1562 tables[0][i] = &s->coeff_vlc[ac_y_table + 48];
1563 tables[1][i] = &s->coeff_vlc[ac_c_table + 48];
1565 for (i = 28; i <= 63; i++) {
1566 /* AC VLC table group 4 */
1567 tables[0][i] = &s->coeff_vlc[ac_y_table + 64];
1568 tables[1][i] = &s->coeff_vlc[ac_c_table + 64];
1571 vp4_set_tokens_base(s);
1573 memset(last_dc, 0, sizeof(last_dc));
1575 for (plane = 0; plane < ((s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 1 : 3); plane++) {
1576 memset(eob_tracker, 0, sizeof(eob_tracker));
1578 /* initialise dc prediction */
1579 for (i = 0; i < s->fragment_width[!!plane]; i++)
1580 vp4_dc_predictor_reset(&s->dc_pred_row[i]);
1582 for (j = 0; j < 6; j++)
1583 for (i = 0; i < 6; i++)
1584 vp4_dc_predictor_reset(&dc_pred[j][i]);
1586 for (sb_y = 0; sb_y * 4 < s->fragment_height[!!plane]; sb_y++) {
1587 for (sb_x = 0; sb_x *4 < s->fragment_width[!!plane]; sb_x++) {
1588 vp4_dc_pred_before(s, dc_pred, sb_x);
1589 for (j = 0; j < 16; j++) {
1590 int hx = hilbert_offset[j][0];
1591 int hy = hilbert_offset[j][1];
1592 int x = 4 * sb_x + hx;
1593 int y = 4 * sb_y + hy;
1594 VP4Predictor *this_dc_pred = &dc_pred[hy + 1][hx + 1];
1595 int fragment, dc_block_type;
1597 if (x >= s->fragment_width[!!plane] || y >= s->fragment_height[!!plane])
1600 fragment = s->fragment_start[plane] + y * s->fragment_width[!!plane] + x;
1602 if (s->all_fragments[fragment].coding_method == MODE_COPY)
1605 if (vp4_unpack_vlcs(s, gb, tables[!!plane], plane, eob_tracker, fragment) < 0)
1608 dc_block_type = vp4_pred_block_type_map[s->all_fragments[fragment].coding_method];
1610 s->all_fragments[fragment].dc +=
1611 vp4_dc_pred(s, this_dc_pred, last_dc, dc_block_type, plane);
1613 this_dc_pred->type = dc_block_type,
1614 this_dc_pred->dc = last_dc[dc_block_type] = s->all_fragments[fragment].dc;
1616 vp4_dc_pred_after(s, dc_pred, sb_x);
1621 vp4_set_tokens_base(s);
1628 * This function reverses the DC prediction for each coded fragment in
1629 * the frame. Much of this function is adapted directly from the original
1632 #define COMPATIBLE_FRAME(x) \
1633 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1634 #define DC_COEFF(u) s->all_fragments[u].dc
1636 static void reverse_dc_prediction(Vp3DecodeContext *s,
1639 int fragment_height)
1647 int i = first_fragment;
1651 /* DC values for the left, up-left, up, and up-right fragments */
1652 int vl, vul, vu, vur;
1654 /* indexes for the left, up-left, up, and up-right fragments */
1658 * The 6 fields mean:
1659 * 0: up-left multiplier
1661 * 2: up-right multiplier
1662 * 3: left multiplier
1664 static const int predictor_transform[16][4] = {
1666 { 0, 0, 0, 128 }, // PL
1667 { 0, 0, 128, 0 }, // PUR
1668 { 0, 0, 53, 75 }, // PUR|PL
1669 { 0, 128, 0, 0 }, // PU
1670 { 0, 64, 0, 64 }, // PU |PL
1671 { 0, 128, 0, 0 }, // PU |PUR
1672 { 0, 0, 53, 75 }, // PU |PUR|PL
1673 { 128, 0, 0, 0 }, // PUL
1674 { 0, 0, 0, 128 }, // PUL|PL
1675 { 64, 0, 64, 0 }, // PUL|PUR
1676 { 0, 0, 53, 75 }, // PUL|PUR|PL
1677 { 0, 128, 0, 0 }, // PUL|PU
1678 { -104, 116, 0, 116 }, // PUL|PU |PL
1679 { 24, 80, 24, 0 }, // PUL|PU |PUR
1680 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1683 /* This table shows which types of blocks can use other blocks for
1684 * prediction. For example, INTRA is the only mode in this table to
1685 * have a frame number of 0. That means INTRA blocks can only predict
1686 * from other INTRA blocks. There are 2 golden frame coding types;
1687 * blocks encoding in these modes can only predict from other blocks
1688 * that were encoded with these 1 of these 2 modes. */
1689 static const unsigned char compatible_frame[9] = {
1690 1, /* MODE_INTER_NO_MV */
1692 1, /* MODE_INTER_PLUS_MV */
1693 1, /* MODE_INTER_LAST_MV */
1694 1, /* MODE_INTER_PRIOR_MV */
1695 2, /* MODE_USING_GOLDEN */
1696 2, /* MODE_GOLDEN_MV */
1697 1, /* MODE_INTER_FOUR_MV */
1700 int current_frame_type;
1702 /* there is a last DC predictor for each of the 3 frame types */
1715 /* for each fragment row... */
1716 for (y = 0; y < fragment_height; y++) {
1717 /* for each fragment in a row... */
1718 for (x = 0; x < fragment_width; x++, i++) {
1720 /* reverse prediction if this block was coded */
1721 if (s->all_fragments[i].coding_method != MODE_COPY) {
1722 current_frame_type =
1723 compatible_frame[s->all_fragments[i].coding_method];
1729 if (COMPATIBLE_FRAME(l))
1733 u = i - fragment_width;
1735 if (COMPATIBLE_FRAME(u))
1738 ul = i - fragment_width - 1;
1740 if (COMPATIBLE_FRAME(ul))
1743 if (x + 1 < fragment_width) {
1744 ur = i - fragment_width + 1;
1746 if (COMPATIBLE_FRAME(ur))
1751 if (transform == 0) {
1752 /* if there were no fragments to predict from, use last
1754 predicted_dc = last_dc[current_frame_type];
1756 /* apply the appropriate predictor transform */
1758 (predictor_transform[transform][0] * vul) +
1759 (predictor_transform[transform][1] * vu) +
1760 (predictor_transform[transform][2] * vur) +
1761 (predictor_transform[transform][3] * vl);
1763 predicted_dc /= 128;
1765 /* check for outranging on the [ul u l] and
1766 * [ul u ur l] predictors */
1767 if ((transform == 15) || (transform == 13)) {
1768 if (FFABS(predicted_dc - vu) > 128)
1770 else if (FFABS(predicted_dc - vl) > 128)
1772 else if (FFABS(predicted_dc - vul) > 128)
1777 /* at long last, apply the predictor */
1778 DC_COEFF(i) += predicted_dc;
1780 last_dc[current_frame_type] = DC_COEFF(i);
1786 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1787 int ystart, int yend)
1790 int *bounding_values = s->bounding_values_array + 127;
1792 int width = s->fragment_width[!!plane];
1793 int height = s->fragment_height[!!plane];
1794 int fragment = s->fragment_start[plane] + ystart * width;
1795 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1796 uint8_t *plane_data = s->current_frame.f->data[plane];
1797 if (!s->flipped_image)
1799 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1801 for (y = ystart; y < yend; y++) {
1802 for (x = 0; x < width; x++) {
1803 /* This code basically just deblocks on the edges of coded blocks.
1804 * However, it has to be much more complicated because of the
1805 * brain damaged deblock ordering used in VP3/Theora. Order matters
1806 * because some pixels get filtered twice. */
1807 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1808 /* do not perform left edge filter for left columns frags */
1810 s->vp3dsp.h_loop_filter(
1812 stride, bounding_values);
1815 /* do not perform top edge filter for top row fragments */
1817 s->vp3dsp.v_loop_filter(
1819 stride, bounding_values);
1822 /* do not perform right edge filter for right column
1823 * fragments or if right fragment neighbor is also coded
1824 * in this frame (it will be filtered in next iteration) */
1825 if ((x < width - 1) &&
1826 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1827 s->vp3dsp.h_loop_filter(
1828 plane_data + 8 * x + 8,
1829 stride, bounding_values);
1832 /* do not perform bottom edge filter for bottom row
1833 * fragments or if bottom fragment neighbor is also coded
1834 * in this frame (it will be filtered in the next row) */
1835 if ((y < height - 1) &&
1836 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1837 s->vp3dsp.v_loop_filter(
1838 plane_data + 8 * x + 8 * stride,
1839 stride, bounding_values);
1845 plane_data += 8 * stride;
1850 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1851 * for the next block in coding order
1853 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1854 int plane, int inter, int16_t block[64])
1856 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1857 uint8_t *perm = s->idct_scantable;
1861 int token = *s->dct_tokens[plane][i];
1862 switch (token & 3) {
1864 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1865 s->dct_tokens[plane][i]++;
1867 *s->dct_tokens[plane][i] = token & ~3;
1870 s->dct_tokens[plane][i]++;
1871 i += (token >> 2) & 0x7f;
1873 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1876 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1880 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1881 s->dct_tokens[plane][i++]++;
1883 default: // shouldn't happen
1887 // return value is expected to be a valid level
1890 // the actual DC+prediction is in the fragment structure
1891 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1896 * called when all pixels up to row y are complete
1898 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1901 int offset[AV_NUM_DATA_POINTERS];
1903 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1904 int y_flipped = s->flipped_image ? s->height - y : y;
1906 /* At the end of the frame, report INT_MAX instead of the height of
1907 * the frame. This makes the other threads' ff_thread_await_progress()
1908 * calls cheaper, because they don't have to clip their values. */
1909 ff_thread_report_progress(&s->current_frame,
1910 y_flipped == s->height ? INT_MAX
1915 if (!s->avctx->draw_horiz_band)
1918 h = y - s->last_slice_end;
1919 s->last_slice_end = y;
1922 if (!s->flipped_image)
1923 y = s->height - y - h;
1925 cy = y >> s->chroma_y_shift;
1926 offset[0] = s->current_frame.f->linesize[0] * y;
1927 offset[1] = s->current_frame.f->linesize[1] * cy;
1928 offset[2] = s->current_frame.f->linesize[2] * cy;
1929 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1933 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1937 * Wait for the reference frame of the current fragment.
1938 * The progress value is in luma pixel rows.
1940 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1941 int motion_y, int y)
1943 ThreadFrame *ref_frame;
1945 int border = motion_y & 1;
1947 if (fragment->coding_method == MODE_USING_GOLDEN ||
1948 fragment->coding_method == MODE_GOLDEN_MV)
1949 ref_frame = &s->golden_frame;
1951 ref_frame = &s->last_frame;
1953 ref_row = y + (motion_y >> 1);
1954 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1956 ff_thread_await_progress(ref_frame, ref_row, 0);
1959 #if CONFIG_VP4_DECODER
1961 * @return non-zero if temp (edge_emu_buffer) was populated
1963 static int vp4_mc_loop_filter(Vp3DecodeContext *s, int plane, int motion_x, int motion_y, int bx, int by,
1964 uint8_t * motion_source, int stride, int src_x, int src_y, uint8_t *temp)
1966 int motion_shift = plane ? 4 : 2;
1967 int subpel_mask = plane ? 3 : 1;
1968 int *bounding_values = s->bounding_values_array + 127;
1973 int x_subpel, y_subpel;
1974 int x_offset, y_offset;
1976 int block_width = plane ? 8 : 16;
1977 int plane_width = s->width >> (plane && s->chroma_x_shift);
1978 int plane_height = s->height >> (plane && s->chroma_y_shift);
1980 #define loop_stride 12
1981 uint8_t loop[12 * loop_stride];
1983 /* using division instead of shift to correctly handle negative values */
1984 x = 8 * bx + motion_x / motion_shift;
1985 y = 8 * by + motion_y / motion_shift;
1987 x_subpel = motion_x & subpel_mask;
1988 y_subpel = motion_y & subpel_mask;
1990 if (x_subpel || y_subpel) {
1995 x = FFMIN(x, x + FFSIGN(motion_x));
1998 y = FFMIN(y, y + FFSIGN(motion_y));
2000 x2 = x + block_width;
2001 y2 = y + block_width;
2003 if (x2 < 0 || x2 >= plane_width || y2 < 0 || y2 >= plane_height)
2006 x_offset = (-(x + 2) & 7) + 2;
2007 y_offset = (-(y + 2) & 7) + 2;
2009 if (x_offset > 8 + x_subpel && y_offset > 8 + y_subpel)
2012 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2013 loop_stride, stride,
2014 12, 12, src_x - 1, src_y - 1,
2018 if (x_offset <= 8 + x_subpel)
2019 ff_vp3dsp_h_loop_filter_12(loop + x_offset, loop_stride, bounding_values);
2021 if (y_offset <= 8 + y_subpel)
2022 ff_vp3dsp_v_loop_filter_12(loop + y_offset*loop_stride, loop_stride, bounding_values);
2029 if (!x_offset && !y_offset)
2032 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2033 loop_stride, stride,
2034 12, 12, src_x - 1, src_y - 1,
2038 #define safe_loop_filter(name, ptr, stride, bounding_values) \
2039 if ((uintptr_t)(ptr) & 7) \
2040 s->vp3dsp.name##_unaligned(ptr, stride, bounding_values); \
2042 s->vp3dsp.name(ptr, stride, bounding_values);
2045 safe_loop_filter(h_loop_filter, loop + loop_stride + x_offset + 1, loop_stride, bounding_values);
2048 safe_loop_filter(v_loop_filter, loop + (y_offset + 1)*loop_stride + 1, loop_stride, bounding_values);
2051 for (i = 0; i < 9; i++)
2052 memcpy(temp + i*stride, loop + (i + 1) * loop_stride + 1, 9);
2059 * Perform the final rendering for a particular slice of data.
2060 * The slice number ranges from 0..(c_superblock_height - 1).
2062 static void render_slice(Vp3DecodeContext *s, int slice)
2064 int x, y, i, j, fragment;
2065 int16_t *block = s->block;
2066 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
2067 int motion_halfpel_index;
2068 uint8_t *motion_source;
2069 int plane, first_pixel;
2071 if (slice >= s->c_superblock_height)
2074 for (plane = 0; plane < 3; plane++) {
2075 uint8_t *output_plane = s->current_frame.f->data[plane] +
2076 s->data_offset[plane];
2077 uint8_t *last_plane = s->last_frame.f->data[plane] +
2078 s->data_offset[plane];
2079 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
2080 s->data_offset[plane];
2081 ptrdiff_t stride = s->current_frame.f->linesize[plane];
2082 int plane_width = s->width >> (plane && s->chroma_x_shift);
2083 int plane_height = s->height >> (plane && s->chroma_y_shift);
2084 int8_t(*motion_val)[2] = s->motion_val[!!plane];
2086 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
2087 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
2088 int slice_width = plane ? s->c_superblock_width
2089 : s->y_superblock_width;
2091 int fragment_width = s->fragment_width[!!plane];
2092 int fragment_height = s->fragment_height[!!plane];
2093 int fragment_start = s->fragment_start[plane];
2095 int do_await = !plane && HAVE_THREADS &&
2096 (s->avctx->active_thread_type & FF_THREAD_FRAME);
2098 if (!s->flipped_image)
2100 if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
2103 /* for each superblock row in the slice (both of them)... */
2104 for (; sb_y < slice_height; sb_y++) {
2105 /* for each superblock in a row... */
2106 for (sb_x = 0; sb_x < slice_width; sb_x++) {
2107 /* for each block in a superblock... */
2108 for (j = 0; j < 16; j++) {
2109 x = 4 * sb_x + hilbert_offset[j][0];
2110 y = 4 * sb_y + hilbert_offset[j][1];
2111 fragment = y * fragment_width + x;
2113 i = fragment_start + fragment;
2116 if (x >= fragment_width || y >= fragment_height)
2119 first_pixel = 8 * y * stride + 8 * x;
2122 s->all_fragments[i].coding_method != MODE_INTRA)
2123 await_reference_row(s, &s->all_fragments[i],
2124 motion_val[fragment][1],
2125 (16 * y) >> s->chroma_y_shift);
2127 /* transform if this block was coded */
2128 if (s->all_fragments[i].coding_method != MODE_COPY) {
2129 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2130 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
2131 motion_source = golden_plane;
2133 motion_source = last_plane;
2135 motion_source += first_pixel;
2136 motion_halfpel_index = 0;
2138 /* sort out the motion vector if this fragment is coded
2139 * using a motion vector method */
2140 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
2141 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
2143 int standard_mc = 1;
2144 motion_x = motion_val[fragment][0];
2145 motion_y = motion_val[fragment][1];
2146 #if CONFIG_VP4_DECODER
2147 if (plane && s->version >= 2) {
2148 motion_x = (motion_x >> 1) | (motion_x & 1);
2149 motion_y = (motion_y >> 1) | (motion_y & 1);
2153 src_x = (motion_x >> 1) + 8 * x;
2154 src_y = (motion_y >> 1) + 8 * y;
2156 motion_halfpel_index = motion_x & 0x01;
2157 motion_source += (motion_x >> 1);
2159 motion_halfpel_index |= (motion_y & 0x01) << 1;
2160 motion_source += ((motion_y >> 1) * stride);
2162 #if CONFIG_VP4_DECODER
2163 if (s->version >= 2) {
2164 uint8_t *temp = s->edge_emu_buffer;
2167 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)) {
2168 motion_source = temp;
2174 if (standard_mc && (
2175 src_x < 0 || src_y < 0 ||
2176 src_x + 9 >= plane_width ||
2177 src_y + 9 >= plane_height)) {
2178 uint8_t *temp = s->edge_emu_buffer;
2182 s->vdsp.emulated_edge_mc(temp, motion_source,
2187 motion_source = temp;
2191 /* first, take care of copying a block from either the
2192 * previous or the golden frame */
2193 if (s->all_fragments[i].coding_method != MODE_INTRA) {
2194 /* Note, it is possible to implement all MC cases
2195 * with put_no_rnd_pixels_l2 which would look more
2196 * like the VP3 source but this would be slower as
2197 * put_no_rnd_pixels_tab is better optimized */
2198 if (motion_halfpel_index != 3) {
2199 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
2200 output_plane + first_pixel,
2201 motion_source, stride, 8);
2203 /* d is 0 if motion_x and _y have the same sign,
2205 int d = (motion_x ^ motion_y) >> 31;
2206 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
2208 motion_source + stride + 1 + d,
2213 /* invert DCT and place (or add) in final output */
2215 if (s->all_fragments[i].coding_method == MODE_INTRA) {
2216 vp3_dequant(s, s->all_fragments + i,
2218 s->vp3dsp.idct_put(output_plane + first_pixel,
2222 if (vp3_dequant(s, s->all_fragments + i,
2224 s->vp3dsp.idct_add(output_plane + first_pixel,
2228 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
2233 /* copy directly from the previous frame */
2234 s->hdsp.put_pixels_tab[1][0](
2235 output_plane + first_pixel,
2236 last_plane + first_pixel,
2242 // Filter up to the last row in the superblock row
2243 if (s->version < 2 && !s->skip_loop_filter)
2244 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
2245 FFMIN(4 * sb_y + 3, fragment_height - 1));
2249 /* this looks like a good place for slice dispatch... */
2251 * if (slice == s->macroblock_height - 1)
2252 * dispatch (both last slice & 2nd-to-last slice);
2253 * else if (slice > 0)
2254 * dispatch (slice - 1);
2257 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
2261 /// Allocate tables for per-frame data in Vp3DecodeContext
2262 static av_cold int allocate_tables(AVCodecContext *avctx)
2264 Vp3DecodeContext *s = avctx->priv_data;
2265 int y_fragment_count, c_fragment_count;
2269 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2270 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2272 /* superblock_coding is used by unpack_superblocks (VP3/Theora) and vp4_unpack_macroblocks (VP4) */
2273 s->superblock_coding = av_mallocz(FFMAX(s->superblock_count, s->yuv_macroblock_count));
2274 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
2276 s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2277 s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2278 memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
2280 s->dct_tokens_base = av_mallocz_array(s->fragment_count,
2281 64 * sizeof(*s->dct_tokens_base));
2282 s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
2283 s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
2285 /* work out the block mapping tables */
2286 s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
2287 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
2289 s->dc_pred_row = av_malloc_array(s->y_superblock_width * 4, sizeof(*s->dc_pred_row));
2291 if (!s->superblock_coding || !s->all_fragments ||
2292 !s->dct_tokens_base || !s->kf_coded_fragment_list ||
2293 !s->nkf_coded_fragment_list ||
2294 !s->superblock_fragments || !s->macroblock_coding ||
2296 !s->motion_val[0] || !s->motion_val[1]) {
2300 init_block_mapping(s);
2305 static av_cold int init_frames(Vp3DecodeContext *s)
2307 s->current_frame.f = av_frame_alloc();
2308 s->last_frame.f = av_frame_alloc();
2309 s->golden_frame.f = av_frame_alloc();
2311 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f)
2312 return AVERROR(ENOMEM);
2317 static av_cold int theora_init_huffman_tables(VLC *vlc, const HuffTable *huff)
2319 uint32_t code = 0, codes[32];
2321 for (unsigned i = 0; i < huff->nb_entries; i++) {
2322 codes[i] = code >> (31 - huff->entries[i].len);
2323 code += 0x80000000U >> huff->entries[i].len;
2325 return ff_init_vlc_sparse(vlc, 11, huff->nb_entries,
2326 &huff->entries[0].len, sizeof(huff->entries[0]), 1,
2328 &huff->entries[0].sym, sizeof(huff->entries[0]), 1, 0);
2331 static av_cold int vp3_decode_init(AVCodecContext *avctx)
2333 Vp3DecodeContext *s = avctx->priv_data;
2334 int i, inter, plane, ret;
2337 int y_fragment_count, c_fragment_count;
2338 #if CONFIG_VP4_DECODER
2342 ret = init_frames(s);
2346 if (avctx->codec_tag == MKTAG('V', 'P', '4', '0'))
2348 else if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
2354 s->width = FFALIGN(avctx->coded_width, 16);
2355 s->height = FFALIGN(avctx->coded_height, 16);
2356 if (avctx->codec_id != AV_CODEC_ID_THEORA)
2357 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2358 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
2359 ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
2360 ff_videodsp_init(&s->vdsp, 8);
2361 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
2363 for (i = 0; i < 64; i++) {
2364 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
2365 s->idct_permutation[i] = TRANSPOSE(i);
2366 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
2370 /* initialize to an impossible value which will force a recalculation
2371 * in the first frame decode */
2372 for (i = 0; i < 3; i++)
2375 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
2379 s->y_superblock_width = (s->width + 31) / 32;
2380 s->y_superblock_height = (s->height + 31) / 32;
2381 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
2383 /* work out the dimensions for the C planes */
2384 c_width = s->width >> s->chroma_x_shift;
2385 c_height = s->height >> s->chroma_y_shift;
2386 s->c_superblock_width = (c_width + 31) / 32;
2387 s->c_superblock_height = (c_height + 31) / 32;
2388 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
2390 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
2391 s->u_superblock_start = s->y_superblock_count;
2392 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
2394 s->macroblock_width = (s->width + 15) / 16;
2395 s->macroblock_height = (s->height + 15) / 16;
2396 s->macroblock_count = s->macroblock_width * s->macroblock_height;
2397 s->c_macroblock_width = (c_width + 15) / 16;
2398 s->c_macroblock_height = (c_height + 15) / 16;
2399 s->c_macroblock_count = s->c_macroblock_width * s->c_macroblock_height;
2400 s->yuv_macroblock_count = s->macroblock_count + 2 * s->c_macroblock_count;
2402 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
2403 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
2404 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
2405 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
2407 /* fragment count covers all 8x8 blocks for all 3 planes */
2408 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2409 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2410 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
2411 s->fragment_start[1] = y_fragment_count;
2412 s->fragment_start[2] = y_fragment_count + c_fragment_count;
2414 if (!s->theora_tables) {
2415 for (i = 0; i < 64; i++) {
2416 s->coded_dc_scale_factor[0][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_y_dc_scale_factor[i];
2417 s->coded_dc_scale_factor[1][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_uv_dc_scale_factor[i];
2418 s->coded_ac_scale_factor[i] = s->version < 2 ? vp31_ac_scale_factor[i] : vp4_ac_scale_factor[i];
2419 s->base_matrix[0][i] = s->version < 2 ? vp31_intra_y_dequant[i] : vp4_generic_dequant[i];
2420 s->base_matrix[1][i] = s->version < 2 ? vp31_intra_c_dequant[i] : vp4_generic_dequant[i];
2421 s->base_matrix[2][i] = s->version < 2 ? vp31_inter_dequant[i] : vp4_generic_dequant[i];
2422 s->filter_limit_values[i] = s->version < 2 ? vp31_filter_limit_values[i] : vp4_filter_limit_values[i];
2425 for (inter = 0; inter < 2; inter++) {
2426 for (plane = 0; plane < 3; plane++) {
2427 s->qr_count[inter][plane] = 1;
2428 s->qr_size[inter][plane][0] = 63;
2429 s->qr_base[inter][plane][0] =
2430 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
2434 /* init VLC tables */
2435 if (s->version < 2) {
2436 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2437 if ((ret = init_vlc(&s->coeff_vlc[i], 11, 32,
2438 &vp3_bias[i][0][1], 4, 2,
2439 &vp3_bias[i][0][0], 4, 2, 0)) < 0)
2442 #if CONFIG_VP4_DECODER
2443 } else { /* version >= 2 */
2444 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2445 if ((ret = init_vlc(&s->coeff_vlc[i], 11, 32,
2446 &vp4_bias[i][0][1], 4, 2,
2447 &vp4_bias[i][0][0], 4, 2, 0)) < 0)
2453 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2454 ret = theora_init_huffman_tables(&s->coeff_vlc[i], &s->huffman_table[i]);
2460 if ((ret = init_vlc(&s->superblock_run_length_vlc, 6, 34,
2461 &superblock_run_length_vlc_table[0][1], 4, 2,
2462 &superblock_run_length_vlc_table[0][0], 4, 2, 0)) < 0)
2465 if ((ret = init_vlc(&s->fragment_run_length_vlc, 5, 30,
2466 &fragment_run_length_vlc_table[0][1], 4, 2,
2467 &fragment_run_length_vlc_table[0][0], 4, 2, 0)) < 0)
2470 if ((ret = init_vlc(&s->mode_code_vlc, 3, 8,
2471 &mode_code_vlc_table[0][1], 2, 1,
2472 &mode_code_vlc_table[0][0], 2, 1, 0)) < 0)
2475 if ((ret = init_vlc(&s->motion_vector_vlc, 6, 63,
2476 &motion_vector_vlc_table[0][1], 2, 1,
2477 &motion_vector_vlc_table[0][0], 2, 1, 0)) < 0)
2480 #if CONFIG_VP4_DECODER
2481 for (j = 0; j < 2; j++)
2482 for (i = 0; i < 7; i++)
2483 if ((ret = init_vlc(&s->vp4_mv_vlc[j][i], 6, 63,
2484 &vp4_mv_vlc[j][i][0][1], 4, 2,
2485 &vp4_mv_vlc[j][i][0][0], 4, 2, 0)) < 0)
2489 for (i = 0; i < 2; i++)
2490 if ((ret = init_vlc(&s->block_pattern_vlc[i], 3, 14,
2491 &vp4_block_pattern_vlc[i][0][1], 2, 1,
2492 &vp4_block_pattern_vlc[i][0][0], 2, 1, 0)) < 0)
2496 return allocate_tables(avctx);
2499 /// Release and shuffle frames after decode finishes
2500 static int update_frames(AVCodecContext *avctx)
2502 Vp3DecodeContext *s = avctx->priv_data;
2505 /* shuffle frames (last = current) */
2506 ff_thread_release_buffer(avctx, &s->last_frame);
2507 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
2512 ff_thread_release_buffer(avctx, &s->golden_frame);
2513 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
2517 ff_thread_release_buffer(avctx, &s->current_frame);
2522 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
2524 ff_thread_release_buffer(s->avctx, dst);
2525 if (src->f->data[0])
2526 return ff_thread_ref_frame(dst, src);
2530 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
2533 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
2534 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
2535 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
2540 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
2542 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
2543 int qps_changed = 0, i, err;
2545 if (!s1->current_frame.f->data[0] ||
2546 s->width != s1->width || s->height != s1->height) {
2553 // copy previous frame data
2554 if ((err = ref_frames(s, s1)) < 0)
2557 s->keyframe = s1->keyframe;
2559 // copy qscale data if necessary
2560 for (i = 0; i < 3; i++) {
2561 if (s->qps[i] != s1->qps[1]) {
2563 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2567 if (s->qps[0] != s1->qps[0])
2568 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2569 sizeof(s->bounding_values_array));
2572 memcpy(s->qps, s1->qps, sizeof(s->qps));
2573 memcpy(s->last_qps, s1->last_qps, sizeof(s->last_qps));
2578 return update_frames(dst);
2582 static int vp3_decode_frame(AVCodecContext *avctx,
2583 void *data, int *got_frame,
2586 AVFrame *frame = data;
2587 const uint8_t *buf = avpkt->data;
2588 int buf_size = avpkt->size;
2589 Vp3DecodeContext *s = avctx->priv_data;
2593 if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2596 #if CONFIG_THEORA_DECODER
2597 if (s->theora && get_bits1(&gb)) {
2598 int type = get_bits(&gb, 7);
2599 skip_bits_long(&gb, 6*8); /* "theora" */
2601 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2602 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2603 return AVERROR_PATCHWELCOME;
2606 vp3_decode_end(avctx);
2607 ret = theora_decode_header(avctx, &gb);
2610 ret = vp3_decode_init(avctx);
2612 vp3_decode_end(avctx);
2616 } else if (type == 2) {
2617 vp3_decode_end(avctx);
2618 ret = theora_decode_tables(avctx, &gb);
2620 ret = vp3_decode_init(avctx);
2622 vp3_decode_end(avctx);
2628 av_log(avctx, AV_LOG_ERROR,
2629 "Header packet passed to frame decoder, skipping\n");
2634 s->keyframe = !get_bits1(&gb);
2635 if (!s->all_fragments) {
2636 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2641 for (i = 0; i < 3; i++)
2642 s->last_qps[i] = s->qps[i];
2646 s->qps[s->nqps++] = get_bits(&gb, 6);
2647 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2648 for (i = s->nqps; i < 3; i++)
2651 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2652 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2653 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2655 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2656 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2657 : AVDISCARD_NONKEY);
2659 if (s->qps[0] != s->last_qps[0])
2660 init_loop_filter(s);
2662 for (i = 0; i < s->nqps; i++)
2663 // reinit all dequantizers if the first one changed, because
2664 // the DC of the first quantizer must be used for all matrices
2665 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2666 init_dequantizer(s, i);
2668 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2671 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2672 : AV_PICTURE_TYPE_P;
2673 s->current_frame.f->key_frame = s->keyframe;
2674 if ((ret = ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
2677 if (!s->edge_emu_buffer)
2678 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2682 skip_bits(&gb, 4); /* width code */
2683 skip_bits(&gb, 4); /* height code */
2685 s->version = get_bits(&gb, 5);
2686 if (avctx->frame_number == 0)
2687 av_log(s->avctx, AV_LOG_DEBUG,
2688 "VP version: %d\n", s->version);
2691 if (s->version || s->theora) {
2693 av_log(s->avctx, AV_LOG_ERROR,
2694 "Warning, unsupported keyframe coding type?!\n");
2695 skip_bits(&gb, 2); /* reserved? */
2697 #if CONFIG_VP4_DECODER
2698 if (s->version >= 2) {
2699 int mb_height, mb_width;
2700 int mb_width_mul, mb_width_div, mb_height_mul, mb_height_div;
2702 mb_height = get_bits(&gb, 8);
2703 mb_width = get_bits(&gb, 8);
2704 if (mb_height != s->macroblock_height ||
2705 mb_width != s->macroblock_width)
2706 avpriv_request_sample(s->avctx, "macroblock dimension mismatch");
2708 mb_width_mul = get_bits(&gb, 5);
2709 mb_width_div = get_bits(&gb, 3);
2710 mb_height_mul = get_bits(&gb, 5);
2711 mb_height_div = get_bits(&gb, 3);
2712 if (mb_width_mul != 1 || mb_width_div != 1 || mb_height_mul != 1 || mb_height_div != 1)
2713 avpriv_request_sample(s->avctx, "unexpected macroblock dimension multipler/divider");
2715 if (get_bits(&gb, 2))
2716 avpriv_request_sample(s->avctx, "unknown bits");
2721 if (!s->golden_frame.f->data[0]) {
2722 av_log(s->avctx, AV_LOG_WARNING,
2723 "vp3: first frame not a keyframe\n");
2725 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2726 if ((ret = ff_thread_get_buffer(avctx, &s->golden_frame,
2727 AV_GET_BUFFER_FLAG_REF)) < 0)
2729 ff_thread_release_buffer(avctx, &s->last_frame);
2730 if ((ret = ff_thread_ref_frame(&s->last_frame,
2731 &s->golden_frame)) < 0)
2733 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2737 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2738 ff_thread_finish_setup(avctx);
2740 if (s->version < 2) {
2741 if ((ret = unpack_superblocks(s, &gb)) < 0) {
2742 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2745 #if CONFIG_VP4_DECODER
2747 if ((ret = vp4_unpack_macroblocks(s, &gb)) < 0) {
2748 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_macroblocks\n");
2753 if ((ret = unpack_modes(s, &gb)) < 0) {
2754 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2757 if (ret = unpack_vectors(s, &gb)) {
2758 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2761 if ((ret = unpack_block_qpis(s, &gb)) < 0) {
2762 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2766 if (s->version < 2) {
2767 if ((ret = unpack_dct_coeffs(s, &gb)) < 0) {
2768 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2771 #if CONFIG_VP4_DECODER
2773 if ((ret = vp4_unpack_dct_coeffs(s, &gb)) < 0) {
2774 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_dct_coeffs\n");
2780 for (i = 0; i < 3; i++) {
2781 int height = s->height >> (i && s->chroma_y_shift);
2782 if (s->flipped_image)
2783 s->data_offset[i] = 0;
2785 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2788 s->last_slice_end = 0;
2789 for (i = 0; i < s->c_superblock_height; i++)
2792 // filter the last row
2794 for (i = 0; i < 3; i++) {
2795 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2796 apply_loop_filter(s, i, row, row + 1);
2798 vp3_draw_horiz_band(s, s->height);
2800 /* output frame, offset as needed */
2801 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2804 frame->crop_left = s->offset_x;
2805 frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
2806 frame->crop_top = s->offset_y;
2807 frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2811 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2812 ret = update_frames(avctx);
2820 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2822 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2823 av_frame_unref(s->current_frame.f);
2828 static int read_huffman_tree(HuffTable *huff, GetBitContext *gb, int length,
2829 AVCodecContext *avctx)
2831 if (get_bits1(gb)) {
2833 if (huff->nb_entries >= 32) { /* overflow */
2834 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2837 token = get_bits(gb, 5);
2838 ff_dlog(avctx, "code length %d, curr entry %d, token %d\n",
2839 length, huff->nb_entries, token);
2840 huff->entries[huff->nb_entries++] = (HuffEntry){ length, token };
2842 /* The following bound follows from the fact that nb_entries <= 32. */
2843 if (length >= 31) { /* overflow */
2844 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2848 if (read_huffman_tree(huff, gb, length, avctx))
2850 if (read_huffman_tree(huff, gb, length, avctx))
2856 #if CONFIG_THEORA_DECODER
2857 static const enum AVPixelFormat theora_pix_fmts[4] = {
2858 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2861 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2863 Vp3DecodeContext *s = avctx->priv_data;
2864 int visible_width, visible_height, colorspace;
2865 uint8_t offset_x = 0, offset_y = 0;
2867 AVRational fps, aspect;
2869 s->theora_header = 0;
2870 s->theora = get_bits(gb, 24);
2871 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2874 avpriv_request_sample(s->avctx, "theora 0");
2877 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2878 * but previous versions have the image flipped relative to vp3 */
2879 if (s->theora < 0x030200) {
2880 s->flipped_image = 1;
2881 av_log(avctx, AV_LOG_DEBUG,
2882 "Old (<alpha3) Theora bitstream, flipped image\n");
2886 s->width = get_bits(gb, 16) << 4;
2888 s->height = get_bits(gb, 16) << 4;
2890 if (s->theora >= 0x030200) {
2891 visible_width = get_bits(gb, 24);
2892 visible_height = get_bits(gb, 24);
2894 offset_x = get_bits(gb, 8); /* offset x */
2895 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2899 if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2900 visible_width + offset_x > s->width ||
2901 visible_height + offset_y > s->height) {
2902 av_log(avctx, AV_LOG_ERROR,
2903 "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2904 visible_width, visible_height, offset_x, offset_y,
2905 s->width, s->height);
2906 return AVERROR_INVALIDDATA;
2909 fps.num = get_bits_long(gb, 32);
2910 fps.den = get_bits_long(gb, 32);
2911 if (fps.num && fps.den) {
2912 if (fps.num < 0 || fps.den < 0) {
2913 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2914 return AVERROR_INVALIDDATA;
2916 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2917 fps.den, fps.num, 1 << 30);
2920 aspect.num = get_bits(gb, 24);
2921 aspect.den = get_bits(gb, 24);
2922 if (aspect.num && aspect.den) {
2923 av_reduce(&avctx->sample_aspect_ratio.num,
2924 &avctx->sample_aspect_ratio.den,
2925 aspect.num, aspect.den, 1 << 30);
2926 ff_set_sar(avctx, avctx->sample_aspect_ratio);
2929 if (s->theora < 0x030200)
2930 skip_bits(gb, 5); /* keyframe frequency force */
2931 colorspace = get_bits(gb, 8);
2932 skip_bits(gb, 24); /* bitrate */
2934 skip_bits(gb, 6); /* quality hint */
2936 if (s->theora >= 0x030200) {
2937 skip_bits(gb, 5); /* keyframe frequency force */
2938 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2939 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2940 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2941 return AVERROR_INVALIDDATA;
2943 skip_bits(gb, 3); /* reserved */
2945 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2947 ret = ff_set_dimensions(avctx, s->width, s->height);
2950 if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2951 avctx->width = visible_width;
2952 avctx->height = visible_height;
2953 // translate offsets from theora axis ([0,0] lower left)
2954 // to normal axis ([0,0] upper left)
2955 s->offset_x = offset_x;
2956 s->offset_y = s->height - visible_height - offset_y;
2959 if (colorspace == 1)
2960 avctx->color_primaries = AVCOL_PRI_BT470M;
2961 else if (colorspace == 2)
2962 avctx->color_primaries = AVCOL_PRI_BT470BG;
2964 if (colorspace == 1 || colorspace == 2) {
2965 avctx->colorspace = AVCOL_SPC_BT470BG;
2966 avctx->color_trc = AVCOL_TRC_BT709;
2969 s->theora_header = 1;
2973 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2975 Vp3DecodeContext *s = avctx->priv_data;
2976 int i, n, matrices, inter, plane, ret;
2978 if (!s->theora_header)
2979 return AVERROR_INVALIDDATA;
2981 if (s->theora >= 0x030200) {
2982 n = get_bits(gb, 3);
2983 /* loop filter limit values table */
2985 for (i = 0; i < 64; i++)
2986 s->filter_limit_values[i] = get_bits(gb, n);
2989 if (s->theora >= 0x030200)
2990 n = get_bits(gb, 4) + 1;
2993 /* quality threshold table */
2994 for (i = 0; i < 64; i++)
2995 s->coded_ac_scale_factor[i] = get_bits(gb, n);
2997 if (s->theora >= 0x030200)
2998 n = get_bits(gb, 4) + 1;
3001 /* dc scale factor table */
3002 for (i = 0; i < 64; i++)
3003 s->coded_dc_scale_factor[0][i] =
3004 s->coded_dc_scale_factor[1][i] = get_bits(gb, n);
3006 if (s->theora >= 0x030200)
3007 matrices = get_bits(gb, 9) + 1;
3011 if (matrices > 384) {
3012 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
3016 for (n = 0; n < matrices; n++)
3017 for (i = 0; i < 64; i++)
3018 s->base_matrix[n][i] = get_bits(gb, 8);
3020 for (inter = 0; inter <= 1; inter++) {
3021 for (plane = 0; plane <= 2; plane++) {
3023 if (inter || plane > 0)
3024 newqr = get_bits1(gb);
3027 if (inter && get_bits1(gb)) {
3031 qtj = (3 * inter + plane - 1) / 3;
3032 plj = (plane + 2) % 3;
3034 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
3035 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
3036 sizeof(s->qr_size[0][0]));
3037 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
3038 sizeof(s->qr_base[0][0]));
3044 i = get_bits(gb, av_log2(matrices - 1) + 1);
3045 if (i >= matrices) {
3046 av_log(avctx, AV_LOG_ERROR,
3047 "invalid base matrix index\n");
3050 s->qr_base[inter][plane][qri] = i;
3053 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
3054 s->qr_size[inter][plane][qri++] = i;
3059 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
3062 s->qr_count[inter][plane] = qri;
3067 /* Huffman tables */
3068 for (int i = 0; i < FF_ARRAY_ELEMS(s->huffman_table); i++) {
3069 s->huffman_table[i].nb_entries = 0;
3070 if ((ret = read_huffman_tree(&s->huffman_table[i], gb, 0, avctx)) < 0)
3074 s->theora_tables = 1;
3079 static av_cold int theora_decode_init(AVCodecContext *avctx)
3081 Vp3DecodeContext *s = avctx->priv_data;
3084 const uint8_t *header_start[3];
3089 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
3093 if (!avctx->extradata_size) {
3094 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
3098 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
3099 42, header_start, header_len) < 0) {
3100 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
3104 for (i = 0; i < 3; i++) {
3105 if (header_len[i] <= 0)
3107 ret = init_get_bits8(&gb, header_start[i], header_len[i]);
3111 ptype = get_bits(&gb, 8);
3113 if (!(ptype & 0x80)) {
3114 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
3118 // FIXME: Check for this as well.
3119 skip_bits_long(&gb, 6 * 8); /* "theora" */
3123 if (theora_decode_header(avctx, &gb) < 0)
3127 // FIXME: is this needed? it breaks sometimes
3128 // theora_decode_comments(avctx, gb);
3131 if (theora_decode_tables(avctx, &gb))
3135 av_log(avctx, AV_LOG_ERROR,
3136 "Unknown Theora config packet: %d\n", ptype & ~0x80);
3139 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
3140 av_log(avctx, AV_LOG_WARNING,
3141 "%d bits left in packet %X\n",
3142 8 * header_len[i] - get_bits_count(&gb), ptype);
3143 if (s->theora < 0x030200)
3147 return vp3_decode_init(avctx);
3150 AVCodec ff_theora_decoder = {
3152 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
3153 .type = AVMEDIA_TYPE_VIDEO,
3154 .id = AV_CODEC_ID_THEORA,
3155 .priv_data_size = sizeof(Vp3DecodeContext),
3156 .init = theora_decode_init,
3157 .close = vp3_decode_end,
3158 .decode = vp3_decode_frame,
3159 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3160 AV_CODEC_CAP_FRAME_THREADS,
3161 .flush = vp3_decode_flush,
3162 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3163 .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING | FF_CODEC_CAP_ALLOCATE_PROGRESS |
3164 FF_CODEC_CAP_INIT_CLEANUP,
3168 AVCodec ff_vp3_decoder = {
3170 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
3171 .type = AVMEDIA_TYPE_VIDEO,
3172 .id = AV_CODEC_ID_VP3,
3173 .priv_data_size = sizeof(Vp3DecodeContext),
3174 .init = vp3_decode_init,
3175 .close = vp3_decode_end,
3176 .decode = vp3_decode_frame,
3177 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3178 AV_CODEC_CAP_FRAME_THREADS,
3179 .flush = vp3_decode_flush,
3180 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3181 .caps_internal = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
3184 #if CONFIG_VP4_DECODER
3185 AVCodec ff_vp4_decoder = {
3187 .long_name = NULL_IF_CONFIG_SMALL("On2 VP4"),
3188 .type = AVMEDIA_TYPE_VIDEO,
3189 .id = AV_CODEC_ID_VP4,
3190 .priv_data_size = sizeof(Vp3DecodeContext),
3191 .init = vp3_decode_init,
3192 .close = vp3_decode_end,
3193 .decode = vp3_decode_frame,
3194 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3195 AV_CODEC_CAP_FRAME_THREADS,
3196 .flush = vp3_decode_flush,
3197 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3198 .caps_internal = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,