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"
38 #include "libavutil/mem_internal.h"
52 #define VP3_MV_VLC_BITS 6
53 #define VP4_MV_VLC_BITS 6
54 #define SUPERBLOCK_VLC_BITS 6
56 #define FRAGMENT_PIXELS 8
58 // FIXME split things out into their own arrays
59 typedef struct Vp3Fragment {
61 uint8_t coding_method;
65 #define SB_NOT_CODED 0
66 #define SB_PARTIALLY_CODED 1
67 #define SB_FULLY_CODED 2
69 // This is the maximum length of a single long bit run that can be encoded
70 // for superblock coding or block qps. Theora special-cases this to read a
71 // bit instead of flipping the current bit to allow for runs longer than 4129.
72 #define MAXIMUM_LONG_BIT_RUN 4129
74 #define MODE_INTER_NO_MV 0
76 #define MODE_INTER_PLUS_MV 2
77 #define MODE_INTER_LAST_MV 3
78 #define MODE_INTER_PRIOR_LAST 4
79 #define MODE_USING_GOLDEN 5
80 #define MODE_GOLDEN_MV 6
81 #define MODE_INTER_FOURMV 7
82 #define CODING_MODE_COUNT 8
84 /* special internal mode */
87 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
88 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
91 /* There are 6 preset schemes, plus a free-form scheme */
92 static const int ModeAlphabet[6][CODING_MODE_COUNT] = {
93 /* scheme 1: Last motion vector dominates */
94 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
95 MODE_INTER_PLUS_MV, MODE_INTER_NO_MV,
96 MODE_INTRA, MODE_USING_GOLDEN,
97 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
100 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
101 MODE_INTER_NO_MV, MODE_INTER_PLUS_MV,
102 MODE_INTRA, MODE_USING_GOLDEN,
103 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
106 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
107 MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
108 MODE_INTRA, MODE_USING_GOLDEN,
109 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
112 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
113 MODE_INTER_NO_MV, MODE_INTER_PRIOR_LAST,
114 MODE_INTRA, MODE_USING_GOLDEN,
115 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
117 /* scheme 5: No motion vector dominates */
118 { MODE_INTER_NO_MV, MODE_INTER_LAST_MV,
119 MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
120 MODE_INTRA, MODE_USING_GOLDEN,
121 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
124 { MODE_INTER_NO_MV, MODE_USING_GOLDEN,
125 MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
126 MODE_INTER_PLUS_MV, MODE_INTRA,
127 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
130 static const uint8_t hilbert_offset[16][2] = {
131 { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
132 { 0, 2 }, { 0, 3 }, { 1, 3 }, { 1, 2 },
133 { 2, 2 }, { 2, 3 }, { 3, 3 }, { 3, 2 },
134 { 3, 1 }, { 2, 1 }, { 2, 0 }, { 3, 0 }
142 VP4_DC_UNDEFINED = NB_VP4_DC_TYPES
145 static const uint8_t vp4_pred_block_type_map[8] = {
146 [MODE_INTER_NO_MV] = VP4_DC_INTER,
147 [MODE_INTRA] = VP4_DC_INTRA,
148 [MODE_INTER_PLUS_MV] = VP4_DC_INTER,
149 [MODE_INTER_LAST_MV] = VP4_DC_INTER,
150 [MODE_INTER_PRIOR_LAST] = VP4_DC_INTER,
151 [MODE_USING_GOLDEN] = VP4_DC_GOLDEN,
152 [MODE_GOLDEN_MV] = VP4_DC_GOLDEN,
153 [MODE_INTER_FOURMV] = VP4_DC_INTER,
161 #define MIN_DEQUANT_VAL 2
163 typedef struct HuffEntry {
167 typedef struct HuffTable {
168 HuffEntry entries[32];
172 typedef struct Vp3DecodeContext {
173 AVCodecContext *avctx;
174 int theora, theora_tables, theora_header;
177 int chroma_x_shift, chroma_y_shift;
178 ThreadFrame golden_frame;
179 ThreadFrame last_frame;
180 ThreadFrame current_frame;
182 uint8_t idct_permutation[64];
183 uint8_t idct_scantable[64];
185 VideoDSPContext vdsp;
186 VP3DSPContext vp3dsp;
187 DECLARE_ALIGNED(16, int16_t, block)[64];
190 int skip_loop_filter;
196 int superblock_count;
197 int y_superblock_width;
198 int y_superblock_height;
199 int y_superblock_count;
200 int c_superblock_width;
201 int c_superblock_height;
202 int c_superblock_count;
203 int u_superblock_start;
204 int v_superblock_start;
205 unsigned char *superblock_coding;
207 int macroblock_count; /* y macroblock count */
208 int macroblock_width;
209 int macroblock_height;
210 int c_macroblock_count;
211 int c_macroblock_width;
212 int c_macroblock_height;
213 int yuv_macroblock_count; /* y+u+v macroblock count */
216 int fragment_width[2];
217 int fragment_height[2];
219 Vp3Fragment *all_fragments;
220 int fragment_start[3];
226 int8_t (*motion_val[2])[2];
229 uint16_t coded_dc_scale_factor[2][64];
230 uint32_t coded_ac_scale_factor[64];
231 uint8_t base_matrix[384][64];
232 uint8_t qr_count[2][3];
233 uint8_t qr_size[2][3][64];
234 uint16_t qr_base[2][3][64];
237 * This is a list of all tokens in bitstream order. Reordering takes place
238 * by pulling from each level during IDCT. As a consequence, IDCT must be
239 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
240 * otherwise. The 32 different tokens with up to 12 bits of extradata are
241 * collapsed into 3 types, packed as follows:
242 * (from the low to high bits)
244 * 2 bits: type (0,1,2)
245 * 0: EOB run, 14 bits for run length (12 needed)
246 * 1: zero run, 7 bits for run length
247 * 7 bits for the next coefficient (3 needed)
248 * 2: coefficient, 14 bits (11 needed)
250 * Coefficients are signed, so are packed in the highest bits for automatic
253 int16_t *dct_tokens[3][64];
254 int16_t *dct_tokens_base;
255 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
256 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
257 #define TOKEN_COEFF(coeff) (((coeff) * 4) + 2)
260 * number of blocks that contain DCT coefficients at
261 * the given level or higher
263 int num_coded_frags[3][64];
264 int total_num_coded_frags;
266 /* this is a list of indexes into the all_fragments array indicating
267 * which of the fragments are coded */
268 int *coded_fragment_list[3];
270 int *kf_coded_fragment_list;
271 int *nkf_coded_fragment_list;
272 int num_kf_coded_fragment[3];
274 /* The first 16 of the following VLCs are for the dc coefficients;
275 the others are four groups of 16 VLCs each for ac coefficients. */
276 VLC coeff_vlc[5 * 16];
278 VLC superblock_run_length_vlc; /* version < 2 */
279 VLC fragment_run_length_vlc; /* version < 2 */
280 VLC block_pattern_vlc[2]; /* version >= 2*/
282 VLC motion_vector_vlc; /* version < 2 */
283 VLC vp4_mv_vlc[2][7]; /* version >=2 */
285 /* these arrays need to be on 16-byte boundaries since SSE2 operations
287 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
289 /* This table contains superblock_count * 16 entries. Each set of 16
290 * numbers corresponds to the fragment indexes 0..15 of the superblock.
291 * An entry will be -1 to indicate that no entry corresponds to that
293 int *superblock_fragments;
295 /* This is an array that indicates how a particular macroblock
297 unsigned char *macroblock_coding;
299 uint8_t *edge_emu_buffer;
302 HuffTable huffman_table[5 * 16];
304 uint8_t filter_limit_values[64];
305 DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
307 VP4Predictor * dc_pred_row; /* dc_pred_row[y_superblock_width * 4] */
310 /************************************************************************
311 * VP3 specific functions
312 ************************************************************************/
314 static av_cold void free_tables(AVCodecContext *avctx)
316 Vp3DecodeContext *s = avctx->priv_data;
318 av_freep(&s->superblock_coding);
319 av_freep(&s->all_fragments);
320 av_freep(&s->nkf_coded_fragment_list);
321 av_freep(&s->kf_coded_fragment_list);
322 av_freep(&s->dct_tokens_base);
323 av_freep(&s->superblock_fragments);
324 av_freep(&s->macroblock_coding);
325 av_freep(&s->dc_pred_row);
326 av_freep(&s->motion_val[0]);
327 av_freep(&s->motion_val[1]);
330 static void vp3_decode_flush(AVCodecContext *avctx)
332 Vp3DecodeContext *s = avctx->priv_data;
334 if (s->golden_frame.f)
335 ff_thread_release_buffer(avctx, &s->golden_frame);
337 ff_thread_release_buffer(avctx, &s->last_frame);
338 if (s->current_frame.f)
339 ff_thread_release_buffer(avctx, &s->current_frame);
342 static av_cold int vp3_decode_end(AVCodecContext *avctx)
344 Vp3DecodeContext *s = avctx->priv_data;
348 av_freep(&s->edge_emu_buffer);
350 s->theora_tables = 0;
352 /* release all frames */
353 vp3_decode_flush(avctx);
354 av_frame_free(&s->current_frame.f);
355 av_frame_free(&s->last_frame.f);
356 av_frame_free(&s->golden_frame.f);
358 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++)
359 ff_free_vlc(&s->coeff_vlc[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,
497 SUPERBLOCK_VLC_BITS, 2);
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,
531 SUPERBLOCK_VLC_BITS, 2);
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);
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,
895 return last_motion < 0 ? -v : v;
899 * This function unpacks all the motion vectors for the individual
900 * macroblocks from the bitstream.
902 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
904 int j, k, sb_x, sb_y;
908 int last_motion_x = 0;
909 int last_motion_y = 0;
910 int prior_last_motion_x = 0;
911 int prior_last_motion_y = 0;
912 int last_gold_motion_x = 0;
913 int last_gold_motion_y = 0;
914 int current_macroblock;
915 int current_fragment;
921 /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme; 2 is VP4 code scheme */
922 coding_mode = s->version < 2 ? get_bits1(gb) : 2;
924 /* iterate through all of the macroblocks that contain 1 or more
926 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
927 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
928 if (get_bits_left(gb) <= 0)
931 for (j = 0; j < 4; j++) {
932 int mb_x = 2 * sb_x + (j >> 1);
933 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
934 current_macroblock = mb_y * s->macroblock_width + mb_x;
936 if (mb_x >= s->macroblock_width ||
937 mb_y >= s->macroblock_height ||
938 s->macroblock_coding[current_macroblock] == MODE_COPY)
941 switch (s->macroblock_coding[current_macroblock]) {
943 if (coding_mode == 2) { /* VP4 */
944 last_gold_motion_x = motion_x[0] = vp4_get_mv(s, gb, 0, last_gold_motion_x);
945 last_gold_motion_y = motion_y[0] = vp4_get_mv(s, gb, 1, last_gold_motion_y);
947 } /* otherwise fall through */
948 case MODE_INTER_PLUS_MV:
949 /* all 6 fragments use the same motion vector */
950 if (coding_mode == 0) {
951 motion_x[0] = get_vlc2(gb, s->motion_vector_vlc.table,
953 motion_y[0] = get_vlc2(gb, s->motion_vector_vlc.table,
955 } else if (coding_mode == 1) {
956 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
957 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
959 motion_x[0] = vp4_get_mv(s, gb, 0, last_motion_x);
960 motion_y[0] = vp4_get_mv(s, gb, 1, last_motion_y);
963 /* vector maintenance, only on MODE_INTER_PLUS_MV */
964 if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
965 prior_last_motion_x = last_motion_x;
966 prior_last_motion_y = last_motion_y;
967 last_motion_x = motion_x[0];
968 last_motion_y = motion_y[0];
972 case MODE_INTER_FOURMV:
973 /* vector maintenance */
974 prior_last_motion_x = last_motion_x;
975 prior_last_motion_y = last_motion_y;
977 /* fetch 4 vectors from the bitstream, one for each
978 * Y fragment, then average for the C fragment vectors */
979 for (k = 0; k < 4; k++) {
980 current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
981 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
982 if (coding_mode == 0) {
983 motion_x[k] = get_vlc2(gb, s->motion_vector_vlc.table,
985 motion_y[k] = get_vlc2(gb, s->motion_vector_vlc.table,
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,
1118 SUPERBLOCK_VLC_BITS, 2);
1119 if (run_length == 34)
1120 run_length += get_bits(gb, 12);
1121 blocks_decoded += run_length;
1124 num_blocks_at_qpi += run_length;
1126 for (j = 0; j < run_length; i++) {
1127 if (i >= s->total_num_coded_frags)
1130 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
1131 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
1135 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
1137 num_blocks -= num_blocks_at_qpi;
1143 static inline int get_eob_run(GetBitContext *gb, int token)
1145 int v = eob_run_table[token].base;
1146 if (eob_run_table[token].bits)
1147 v += get_bits(gb, eob_run_table[token].bits);
1151 static inline int get_coeff(GetBitContext *gb, int token, int16_t *coeff)
1153 int bits_to_get, zero_run;
1155 bits_to_get = coeff_get_bits[token];
1157 bits_to_get = get_bits(gb, bits_to_get);
1158 *coeff = coeff_tables[token][bits_to_get];
1160 zero_run = zero_run_base[token];
1161 if (zero_run_get_bits[token])
1162 zero_run += get_bits(gb, zero_run_get_bits[token]);
1168 * This function is called by unpack_dct_coeffs() to extract the VLCs from
1169 * the bitstream. The VLCs encode tokens which are used to unpack DCT
1170 * data. This function unpacks all the VLCs for either the Y plane or both
1171 * C planes, and is called for DC coefficients or different AC coefficient
1172 * levels (since different coefficient types require different VLC tables.
1174 * This function returns a residual eob run. E.g, if a particular token gave
1175 * instructions to EOB the next 5 fragments and there were only 2 fragments
1176 * left in the current fragment range, 3 would be returned so that it could
1177 * be passed into the next call to this same function.
1179 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1180 VLC *table, int coeff_index,
1190 int num_coeffs = s->num_coded_frags[plane][coeff_index];
1191 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
1193 /* local references to structure members to avoid repeated dereferences */
1194 int *coded_fragment_list = s->coded_fragment_list[plane];
1195 Vp3Fragment *all_fragments = s->all_fragments;
1196 VLC_TYPE(*vlc_table)[2] = table->table;
1198 if (num_coeffs < 0) {
1199 av_log(s->avctx, AV_LOG_ERROR,
1200 "Invalid number of coefficients at level %d\n", coeff_index);
1201 return AVERROR_INVALIDDATA;
1204 if (eob_run > num_coeffs) {
1206 blocks_ended = num_coeffs;
1207 eob_run -= num_coeffs;
1210 blocks_ended = eob_run;
1214 // insert fake EOB token to cover the split between planes or zzi
1216 dct_tokens[j++] = blocks_ended << 2;
1218 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1219 /* decode a VLC into a token */
1220 token = get_vlc2(gb, vlc_table, 11, 3);
1221 /* use the token to get a zero run, a coefficient, and an eob run */
1222 if ((unsigned) token <= 6U) {
1223 eob_run = get_eob_run(gb, token);
1227 // record only the number of blocks ended in this plane,
1228 // any spill will be recorded in the next plane.
1229 if (eob_run > num_coeffs - coeff_i) {
1230 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1231 blocks_ended += num_coeffs - coeff_i;
1232 eob_run -= num_coeffs - coeff_i;
1233 coeff_i = num_coeffs;
1235 dct_tokens[j++] = TOKEN_EOB(eob_run);
1236 blocks_ended += eob_run;
1240 } else if (token >= 0) {
1241 zero_run = get_coeff(gb, token, &coeff);
1244 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1246 // Save DC into the fragment structure. DC prediction is
1247 // done in raster order, so the actual DC can't be in with
1248 // other tokens. We still need the token in dct_tokens[]
1249 // however, or else the structure collapses on itself.
1251 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1253 dct_tokens[j++] = TOKEN_COEFF(coeff);
1256 if (coeff_index + zero_run > 64) {
1257 av_log(s->avctx, AV_LOG_DEBUG,
1258 "Invalid zero run of %d with %d coeffs left\n",
1259 zero_run, 64 - coeff_index);
1260 zero_run = 64 - coeff_index;
1263 // zero runs code multiple coefficients,
1264 // so don't try to decode coeffs for those higher levels
1265 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1266 s->num_coded_frags[plane][i]--;
1269 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1274 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1275 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1277 // decrement the number of blocks that have higher coefficients for each
1278 // EOB run at this level
1280 for (i = coeff_index + 1; i < 64; i++)
1281 s->num_coded_frags[plane][i] -= blocks_ended;
1283 // setup the next buffer
1285 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1286 else if (coeff_index < 63)
1287 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1292 static void reverse_dc_prediction(Vp3DecodeContext *s,
1295 int fragment_height);
1297 * This function unpacks all of the DCT coefficient data from the
1300 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1307 int residual_eob_run = 0;
1311 s->dct_tokens[0][0] = s->dct_tokens_base;
1313 if (get_bits_left(gb) < 16)
1314 return AVERROR_INVALIDDATA;
1316 /* fetch the DC table indexes */
1317 dc_y_table = get_bits(gb, 4);
1318 dc_c_table = get_bits(gb, 4);
1320 /* unpack the Y plane DC coefficients */
1321 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_y_table], 0,
1322 0, residual_eob_run);
1323 if (residual_eob_run < 0)
1324 return residual_eob_run;
1325 if (get_bits_left(gb) < 8)
1326 return AVERROR_INVALIDDATA;
1328 /* reverse prediction of the Y-plane DC coefficients */
1329 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1331 /* unpack the C plane DC coefficients */
1332 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1333 1, residual_eob_run);
1334 if (residual_eob_run < 0)
1335 return residual_eob_run;
1336 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1337 2, residual_eob_run);
1338 if (residual_eob_run < 0)
1339 return residual_eob_run;
1341 /* reverse prediction of the C-plane DC coefficients */
1342 if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1343 reverse_dc_prediction(s, s->fragment_start[1],
1344 s->fragment_width[1], s->fragment_height[1]);
1345 reverse_dc_prediction(s, s->fragment_start[2],
1346 s->fragment_width[1], s->fragment_height[1]);
1349 if (get_bits_left(gb) < 8)
1350 return AVERROR_INVALIDDATA;
1351 /* fetch the AC table indexes */
1352 ac_y_table = get_bits(gb, 4);
1353 ac_c_table = get_bits(gb, 4);
1355 /* build tables of AC VLC tables */
1356 for (i = 1; i <= 5; i++) {
1357 /* AC VLC table group 1 */
1358 y_tables[i] = &s->coeff_vlc[ac_y_table + 16];
1359 c_tables[i] = &s->coeff_vlc[ac_c_table + 16];
1361 for (i = 6; i <= 14; i++) {
1362 /* AC VLC table group 2 */
1363 y_tables[i] = &s->coeff_vlc[ac_y_table + 32];
1364 c_tables[i] = &s->coeff_vlc[ac_c_table + 32];
1366 for (i = 15; i <= 27; i++) {
1367 /* AC VLC table group 3 */
1368 y_tables[i] = &s->coeff_vlc[ac_y_table + 48];
1369 c_tables[i] = &s->coeff_vlc[ac_c_table + 48];
1371 for (i = 28; i <= 63; i++) {
1372 /* AC VLC table group 4 */
1373 y_tables[i] = &s->coeff_vlc[ac_y_table + 64];
1374 c_tables[i] = &s->coeff_vlc[ac_c_table + 64];
1377 /* decode all AC coefficients */
1378 for (i = 1; i <= 63; i++) {
1379 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1380 0, residual_eob_run);
1381 if (residual_eob_run < 0)
1382 return residual_eob_run;
1384 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1385 1, residual_eob_run);
1386 if (residual_eob_run < 0)
1387 return residual_eob_run;
1388 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1389 2, residual_eob_run);
1390 if (residual_eob_run < 0)
1391 return residual_eob_run;
1397 #if CONFIG_VP4_DECODER
1399 * eob_tracker[] is instead of TOKEN_EOB(value)
1400 * a dummy TOKEN_EOB(0) value is used to make vp3_dequant work
1402 * @return < 0 on error
1404 static int vp4_unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1405 VLC *vlc_tables[64],
1406 int plane, int eob_tracker[64], int fragment)
1414 while (!eob_tracker[coeff_i]) {
1415 if (get_bits_left(gb) < 1)
1416 return AVERROR_INVALIDDATA;
1418 token = get_vlc2(gb, vlc_tables[coeff_i]->table, 11, 3);
1420 /* use the token to get a zero run, a coefficient, and an eob run */
1421 if ((unsigned) token <= 6U) {
1422 eob_run = get_eob_run(gb, token);
1423 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1424 eob_tracker[coeff_i] = eob_run - 1;
1426 } else if (token >= 0) {
1427 zero_run = get_coeff(gb, token, &coeff);
1430 if (coeff_i + zero_run > 64) {
1431 av_log(s->avctx, AV_LOG_DEBUG,
1432 "Invalid zero run of %d with %d coeffs left\n",
1433 zero_run, 64 - coeff_i);
1434 zero_run = 64 - coeff_i;
1436 *s->dct_tokens[plane][coeff_i]++ = TOKEN_ZERO_RUN(coeff, zero_run);
1437 coeff_i += zero_run;
1440 s->all_fragments[fragment].dc = coeff;
1442 *s->dct_tokens[plane][coeff_i]++ = TOKEN_COEFF(coeff);
1445 if (coeff_i >= 64) /* > 64 occurs when there is a zero_run overflow */
1446 return 0; /* stop */
1448 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1452 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1453 eob_tracker[coeff_i]--;
1457 static void vp4_dc_predictor_reset(VP4Predictor *p)
1460 p->type = VP4_DC_UNDEFINED;
1463 static void vp4_dc_pred_before(const Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1467 for (i = 0; i < 4; i++)
1468 dc_pred[0][i + 1] = s->dc_pred_row[sb_x * 4 + i];
1470 for (j = 1; j < 5; j++)
1471 for (i = 0; i < 4; i++)
1472 vp4_dc_predictor_reset(&dc_pred[j][i + 1]);
1475 static void vp4_dc_pred_after(Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1479 for (i = 0; i < 4; i++)
1480 s->dc_pred_row[sb_x * 4 + i] = dc_pred[4][i + 1];
1482 for (i = 1; i < 5; i++)
1483 dc_pred[i][0] = dc_pred[i][4];
1486 /* note: dc_pred points to the current block */
1487 static int vp4_dc_pred(const Vp3DecodeContext *s, const VP4Predictor * dc_pred, const int * last_dc, int type, int plane)
1492 if (dc_pred[-6].type == type) {
1493 dc += dc_pred[-6].dc;
1497 if (dc_pred[6].type == type) {
1498 dc += dc_pred[6].dc;
1502 if (count != 2 && dc_pred[-1].type == type) {
1503 dc += dc_pred[-1].dc;
1507 if (count != 2 && dc_pred[1].type == type) {
1508 dc += dc_pred[1].dc;
1512 /* using division instead of shift to correctly handle negative values */
1513 return count == 2 ? dc / 2 : last_dc[type];
1516 static void vp4_set_tokens_base(Vp3DecodeContext *s)
1519 int16_t *base = s->dct_tokens_base;
1520 for (plane = 0; plane < 3; plane++) {
1521 for (i = 0; i < 64; i++) {
1522 s->dct_tokens[plane][i] = base;
1523 base += s->fragment_width[!!plane] * s->fragment_height[!!plane];
1528 static int vp4_unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1536 int plane, sb_y, sb_x;
1537 int eob_tracker[64];
1538 VP4Predictor dc_pred[6][6];
1539 int last_dc[NB_VP4_DC_TYPES];
1541 if (get_bits_left(gb) < 16)
1542 return AVERROR_INVALIDDATA;
1544 /* fetch the DC table indexes */
1545 dc_y_table = get_bits(gb, 4);
1546 dc_c_table = get_bits(gb, 4);
1548 ac_y_table = get_bits(gb, 4);
1549 ac_c_table = get_bits(gb, 4);
1551 /* build tables of DC/AC VLC tables */
1553 /* DC table group */
1554 tables[0][0] = &s->coeff_vlc[dc_y_table];
1555 tables[1][0] = &s->coeff_vlc[dc_c_table];
1556 for (i = 1; i <= 5; i++) {
1557 /* AC VLC table group 1 */
1558 tables[0][i] = &s->coeff_vlc[ac_y_table + 16];
1559 tables[1][i] = &s->coeff_vlc[ac_c_table + 16];
1561 for (i = 6; i <= 14; i++) {
1562 /* AC VLC table group 2 */
1563 tables[0][i] = &s->coeff_vlc[ac_y_table + 32];
1564 tables[1][i] = &s->coeff_vlc[ac_c_table + 32];
1566 for (i = 15; i <= 27; i++) {
1567 /* AC VLC table group 3 */
1568 tables[0][i] = &s->coeff_vlc[ac_y_table + 48];
1569 tables[1][i] = &s->coeff_vlc[ac_c_table + 48];
1571 for (i = 28; i <= 63; i++) {
1572 /* AC VLC table group 4 */
1573 tables[0][i] = &s->coeff_vlc[ac_y_table + 64];
1574 tables[1][i] = &s->coeff_vlc[ac_c_table + 64];
1577 vp4_set_tokens_base(s);
1579 memset(last_dc, 0, sizeof(last_dc));
1581 for (plane = 0; plane < ((s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 1 : 3); plane++) {
1582 memset(eob_tracker, 0, sizeof(eob_tracker));
1584 /* initialise dc prediction */
1585 for (i = 0; i < s->fragment_width[!!plane]; i++)
1586 vp4_dc_predictor_reset(&s->dc_pred_row[i]);
1588 for (j = 0; j < 6; j++)
1589 for (i = 0; i < 6; i++)
1590 vp4_dc_predictor_reset(&dc_pred[j][i]);
1592 for (sb_y = 0; sb_y * 4 < s->fragment_height[!!plane]; sb_y++) {
1593 for (sb_x = 0; sb_x *4 < s->fragment_width[!!plane]; sb_x++) {
1594 vp4_dc_pred_before(s, dc_pred, sb_x);
1595 for (j = 0; j < 16; j++) {
1596 int hx = hilbert_offset[j][0];
1597 int hy = hilbert_offset[j][1];
1598 int x = 4 * sb_x + hx;
1599 int y = 4 * sb_y + hy;
1600 VP4Predictor *this_dc_pred = &dc_pred[hy + 1][hx + 1];
1601 int fragment, dc_block_type;
1603 if (x >= s->fragment_width[!!plane] || y >= s->fragment_height[!!plane])
1606 fragment = s->fragment_start[plane] + y * s->fragment_width[!!plane] + x;
1608 if (s->all_fragments[fragment].coding_method == MODE_COPY)
1611 if (vp4_unpack_vlcs(s, gb, tables[!!plane], plane, eob_tracker, fragment) < 0)
1614 dc_block_type = vp4_pred_block_type_map[s->all_fragments[fragment].coding_method];
1616 s->all_fragments[fragment].dc +=
1617 vp4_dc_pred(s, this_dc_pred, last_dc, dc_block_type, plane);
1619 this_dc_pred->type = dc_block_type,
1620 this_dc_pred->dc = last_dc[dc_block_type] = s->all_fragments[fragment].dc;
1622 vp4_dc_pred_after(s, dc_pred, sb_x);
1627 vp4_set_tokens_base(s);
1634 * This function reverses the DC prediction for each coded fragment in
1635 * the frame. Much of this function is adapted directly from the original
1638 #define COMPATIBLE_FRAME(x) \
1639 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1640 #define DC_COEFF(u) s->all_fragments[u].dc
1642 static void reverse_dc_prediction(Vp3DecodeContext *s,
1645 int fragment_height)
1653 int i = first_fragment;
1657 /* DC values for the left, up-left, up, and up-right fragments */
1658 int vl, vul, vu, vur;
1660 /* indexes for the left, up-left, up, and up-right fragments */
1664 * The 6 fields mean:
1665 * 0: up-left multiplier
1667 * 2: up-right multiplier
1668 * 3: left multiplier
1670 static const int predictor_transform[16][4] = {
1672 { 0, 0, 0, 128 }, // PL
1673 { 0, 0, 128, 0 }, // PUR
1674 { 0, 0, 53, 75 }, // PUR|PL
1675 { 0, 128, 0, 0 }, // PU
1676 { 0, 64, 0, 64 }, // PU |PL
1677 { 0, 128, 0, 0 }, // PU |PUR
1678 { 0, 0, 53, 75 }, // PU |PUR|PL
1679 { 128, 0, 0, 0 }, // PUL
1680 { 0, 0, 0, 128 }, // PUL|PL
1681 { 64, 0, 64, 0 }, // PUL|PUR
1682 { 0, 0, 53, 75 }, // PUL|PUR|PL
1683 { 0, 128, 0, 0 }, // PUL|PU
1684 { -104, 116, 0, 116 }, // PUL|PU |PL
1685 { 24, 80, 24, 0 }, // PUL|PU |PUR
1686 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1689 /* This table shows which types of blocks can use other blocks for
1690 * prediction. For example, INTRA is the only mode in this table to
1691 * have a frame number of 0. That means INTRA blocks can only predict
1692 * from other INTRA blocks. There are 2 golden frame coding types;
1693 * blocks encoding in these modes can only predict from other blocks
1694 * that were encoded with these 1 of these 2 modes. */
1695 static const unsigned char compatible_frame[9] = {
1696 1, /* MODE_INTER_NO_MV */
1698 1, /* MODE_INTER_PLUS_MV */
1699 1, /* MODE_INTER_LAST_MV */
1700 1, /* MODE_INTER_PRIOR_MV */
1701 2, /* MODE_USING_GOLDEN */
1702 2, /* MODE_GOLDEN_MV */
1703 1, /* MODE_INTER_FOUR_MV */
1706 int current_frame_type;
1708 /* there is a last DC predictor for each of the 3 frame types */
1721 /* for each fragment row... */
1722 for (y = 0; y < fragment_height; y++) {
1723 /* for each fragment in a row... */
1724 for (x = 0; x < fragment_width; x++, i++) {
1726 /* reverse prediction if this block was coded */
1727 if (s->all_fragments[i].coding_method != MODE_COPY) {
1728 current_frame_type =
1729 compatible_frame[s->all_fragments[i].coding_method];
1735 if (COMPATIBLE_FRAME(l))
1739 u = i - fragment_width;
1741 if (COMPATIBLE_FRAME(u))
1744 ul = i - fragment_width - 1;
1746 if (COMPATIBLE_FRAME(ul))
1749 if (x + 1 < fragment_width) {
1750 ur = i - fragment_width + 1;
1752 if (COMPATIBLE_FRAME(ur))
1757 if (transform == 0) {
1758 /* if there were no fragments to predict from, use last
1760 predicted_dc = last_dc[current_frame_type];
1762 /* apply the appropriate predictor transform */
1764 (predictor_transform[transform][0] * vul) +
1765 (predictor_transform[transform][1] * vu) +
1766 (predictor_transform[transform][2] * vur) +
1767 (predictor_transform[transform][3] * vl);
1769 predicted_dc /= 128;
1771 /* check for outranging on the [ul u l] and
1772 * [ul u ur l] predictors */
1773 if ((transform == 15) || (transform == 13)) {
1774 if (FFABS(predicted_dc - vu) > 128)
1776 else if (FFABS(predicted_dc - vl) > 128)
1778 else if (FFABS(predicted_dc - vul) > 128)
1783 /* at long last, apply the predictor */
1784 DC_COEFF(i) += predicted_dc;
1786 last_dc[current_frame_type] = DC_COEFF(i);
1792 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1793 int ystart, int yend)
1796 int *bounding_values = s->bounding_values_array + 127;
1798 int width = s->fragment_width[!!plane];
1799 int height = s->fragment_height[!!plane];
1800 int fragment = s->fragment_start[plane] + ystart * width;
1801 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1802 uint8_t *plane_data = s->current_frame.f->data[plane];
1803 if (!s->flipped_image)
1805 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1807 for (y = ystart; y < yend; y++) {
1808 for (x = 0; x < width; x++) {
1809 /* This code basically just deblocks on the edges of coded blocks.
1810 * However, it has to be much more complicated because of the
1811 * brain damaged deblock ordering used in VP3/Theora. Order matters
1812 * because some pixels get filtered twice. */
1813 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1814 /* do not perform left edge filter for left columns frags */
1816 s->vp3dsp.h_loop_filter(
1818 stride, bounding_values);
1821 /* do not perform top edge filter for top row fragments */
1823 s->vp3dsp.v_loop_filter(
1825 stride, bounding_values);
1828 /* do not perform right edge filter for right column
1829 * fragments or if right fragment neighbor is also coded
1830 * in this frame (it will be filtered in next iteration) */
1831 if ((x < width - 1) &&
1832 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1833 s->vp3dsp.h_loop_filter(
1834 plane_data + 8 * x + 8,
1835 stride, bounding_values);
1838 /* do not perform bottom edge filter for bottom row
1839 * fragments or if bottom fragment neighbor is also coded
1840 * in this frame (it will be filtered in the next row) */
1841 if ((y < height - 1) &&
1842 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1843 s->vp3dsp.v_loop_filter(
1844 plane_data + 8 * x + 8 * stride,
1845 stride, bounding_values);
1851 plane_data += 8 * stride;
1856 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1857 * for the next block in coding order
1859 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1860 int plane, int inter, int16_t block[64])
1862 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1863 uint8_t *perm = s->idct_scantable;
1867 int token = *s->dct_tokens[plane][i];
1868 switch (token & 3) {
1870 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1871 s->dct_tokens[plane][i]++;
1873 *s->dct_tokens[plane][i] = token & ~3;
1876 s->dct_tokens[plane][i]++;
1877 i += (token >> 2) & 0x7f;
1879 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1882 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1886 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1887 s->dct_tokens[plane][i++]++;
1889 default: // shouldn't happen
1893 // return value is expected to be a valid level
1896 // the actual DC+prediction is in the fragment structure
1897 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1902 * called when all pixels up to row y are complete
1904 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1907 int offset[AV_NUM_DATA_POINTERS];
1909 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1910 int y_flipped = s->flipped_image ? s->height - y : y;
1912 /* At the end of the frame, report INT_MAX instead of the height of
1913 * the frame. This makes the other threads' ff_thread_await_progress()
1914 * calls cheaper, because they don't have to clip their values. */
1915 ff_thread_report_progress(&s->current_frame,
1916 y_flipped == s->height ? INT_MAX
1921 if (!s->avctx->draw_horiz_band)
1924 h = y - s->last_slice_end;
1925 s->last_slice_end = y;
1928 if (!s->flipped_image)
1929 y = s->height - y - h;
1931 cy = y >> s->chroma_y_shift;
1932 offset[0] = s->current_frame.f->linesize[0] * y;
1933 offset[1] = s->current_frame.f->linesize[1] * cy;
1934 offset[2] = s->current_frame.f->linesize[2] * cy;
1935 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1939 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1943 * Wait for the reference frame of the current fragment.
1944 * The progress value is in luma pixel rows.
1946 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1947 int motion_y, int y)
1949 ThreadFrame *ref_frame;
1951 int border = motion_y & 1;
1953 if (fragment->coding_method == MODE_USING_GOLDEN ||
1954 fragment->coding_method == MODE_GOLDEN_MV)
1955 ref_frame = &s->golden_frame;
1957 ref_frame = &s->last_frame;
1959 ref_row = y + (motion_y >> 1);
1960 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1962 ff_thread_await_progress(ref_frame, ref_row, 0);
1965 #if CONFIG_VP4_DECODER
1967 * @return non-zero if temp (edge_emu_buffer) was populated
1969 static int vp4_mc_loop_filter(Vp3DecodeContext *s, int plane, int motion_x, int motion_y, int bx, int by,
1970 uint8_t * motion_source, int stride, int src_x, int src_y, uint8_t *temp)
1972 int motion_shift = plane ? 4 : 2;
1973 int subpel_mask = plane ? 3 : 1;
1974 int *bounding_values = s->bounding_values_array + 127;
1979 int x_subpel, y_subpel;
1980 int x_offset, y_offset;
1982 int block_width = plane ? 8 : 16;
1983 int plane_width = s->width >> (plane && s->chroma_x_shift);
1984 int plane_height = s->height >> (plane && s->chroma_y_shift);
1986 #define loop_stride 12
1987 uint8_t loop[12 * loop_stride];
1989 /* using division instead of shift to correctly handle negative values */
1990 x = 8 * bx + motion_x / motion_shift;
1991 y = 8 * by + motion_y / motion_shift;
1993 x_subpel = motion_x & subpel_mask;
1994 y_subpel = motion_y & subpel_mask;
1996 if (x_subpel || y_subpel) {
2001 x = FFMIN(x, x + FFSIGN(motion_x));
2004 y = FFMIN(y, y + FFSIGN(motion_y));
2006 x2 = x + block_width;
2007 y2 = y + block_width;
2009 if (x2 < 0 || x2 >= plane_width || y2 < 0 || y2 >= plane_height)
2012 x_offset = (-(x + 2) & 7) + 2;
2013 y_offset = (-(y + 2) & 7) + 2;
2015 if (x_offset > 8 + x_subpel && y_offset > 8 + y_subpel)
2018 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2019 loop_stride, stride,
2020 12, 12, src_x - 1, src_y - 1,
2024 if (x_offset <= 8 + x_subpel)
2025 ff_vp3dsp_h_loop_filter_12(loop + x_offset, loop_stride, bounding_values);
2027 if (y_offset <= 8 + y_subpel)
2028 ff_vp3dsp_v_loop_filter_12(loop + y_offset*loop_stride, loop_stride, bounding_values);
2035 if (!x_offset && !y_offset)
2038 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2039 loop_stride, stride,
2040 12, 12, src_x - 1, src_y - 1,
2044 #define safe_loop_filter(name, ptr, stride, bounding_values) \
2045 if ((uintptr_t)(ptr) & 7) \
2046 s->vp3dsp.name##_unaligned(ptr, stride, bounding_values); \
2048 s->vp3dsp.name(ptr, stride, bounding_values);
2051 safe_loop_filter(h_loop_filter, loop + loop_stride + x_offset + 1, loop_stride, bounding_values);
2054 safe_loop_filter(v_loop_filter, loop + (y_offset + 1)*loop_stride + 1, loop_stride, bounding_values);
2057 for (i = 0; i < 9; i++)
2058 memcpy(temp + i*stride, loop + (i + 1) * loop_stride + 1, 9);
2065 * Perform the final rendering for a particular slice of data.
2066 * The slice number ranges from 0..(c_superblock_height - 1).
2068 static void render_slice(Vp3DecodeContext *s, int slice)
2070 int x, y, i, j, fragment;
2071 int16_t *block = s->block;
2072 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
2073 int motion_halfpel_index;
2074 uint8_t *motion_source;
2075 int plane, first_pixel;
2077 if (slice >= s->c_superblock_height)
2080 for (plane = 0; plane < 3; plane++) {
2081 uint8_t *output_plane = s->current_frame.f->data[plane] +
2082 s->data_offset[plane];
2083 uint8_t *last_plane = s->last_frame.f->data[plane] +
2084 s->data_offset[plane];
2085 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
2086 s->data_offset[plane];
2087 ptrdiff_t stride = s->current_frame.f->linesize[plane];
2088 int plane_width = s->width >> (plane && s->chroma_x_shift);
2089 int plane_height = s->height >> (plane && s->chroma_y_shift);
2090 int8_t(*motion_val)[2] = s->motion_val[!!plane];
2092 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
2093 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
2094 int slice_width = plane ? s->c_superblock_width
2095 : s->y_superblock_width;
2097 int fragment_width = s->fragment_width[!!plane];
2098 int fragment_height = s->fragment_height[!!plane];
2099 int fragment_start = s->fragment_start[plane];
2101 int do_await = !plane && HAVE_THREADS &&
2102 (s->avctx->active_thread_type & FF_THREAD_FRAME);
2104 if (!s->flipped_image)
2106 if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
2109 /* for each superblock row in the slice (both of them)... */
2110 for (; sb_y < slice_height; sb_y++) {
2111 /* for each superblock in a row... */
2112 for (sb_x = 0; sb_x < slice_width; sb_x++) {
2113 /* for each block in a superblock... */
2114 for (j = 0; j < 16; j++) {
2115 x = 4 * sb_x + hilbert_offset[j][0];
2116 y = 4 * sb_y + hilbert_offset[j][1];
2117 fragment = y * fragment_width + x;
2119 i = fragment_start + fragment;
2122 if (x >= fragment_width || y >= fragment_height)
2125 first_pixel = 8 * y * stride + 8 * x;
2128 s->all_fragments[i].coding_method != MODE_INTRA)
2129 await_reference_row(s, &s->all_fragments[i],
2130 motion_val[fragment][1],
2131 (16 * y) >> s->chroma_y_shift);
2133 /* transform if this block was coded */
2134 if (s->all_fragments[i].coding_method != MODE_COPY) {
2135 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2136 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
2137 motion_source = golden_plane;
2139 motion_source = last_plane;
2141 motion_source += first_pixel;
2142 motion_halfpel_index = 0;
2144 /* sort out the motion vector if this fragment is coded
2145 * using a motion vector method */
2146 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
2147 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
2149 int standard_mc = 1;
2150 motion_x = motion_val[fragment][0];
2151 motion_y = motion_val[fragment][1];
2152 #if CONFIG_VP4_DECODER
2153 if (plane && s->version >= 2) {
2154 motion_x = (motion_x >> 1) | (motion_x & 1);
2155 motion_y = (motion_y >> 1) | (motion_y & 1);
2159 src_x = (motion_x >> 1) + 8 * x;
2160 src_y = (motion_y >> 1) + 8 * y;
2162 motion_halfpel_index = motion_x & 0x01;
2163 motion_source += (motion_x >> 1);
2165 motion_halfpel_index |= (motion_y & 0x01) << 1;
2166 motion_source += ((motion_y >> 1) * stride);
2168 #if CONFIG_VP4_DECODER
2169 if (s->version >= 2) {
2170 uint8_t *temp = s->edge_emu_buffer;
2173 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)) {
2174 motion_source = temp;
2180 if (standard_mc && (
2181 src_x < 0 || src_y < 0 ||
2182 src_x + 9 >= plane_width ||
2183 src_y + 9 >= plane_height)) {
2184 uint8_t *temp = s->edge_emu_buffer;
2188 s->vdsp.emulated_edge_mc(temp, motion_source,
2193 motion_source = temp;
2197 /* first, take care of copying a block from either the
2198 * previous or the golden frame */
2199 if (s->all_fragments[i].coding_method != MODE_INTRA) {
2200 /* Note, it is possible to implement all MC cases
2201 * with put_no_rnd_pixels_l2 which would look more
2202 * like the VP3 source but this would be slower as
2203 * put_no_rnd_pixels_tab is better optimized */
2204 if (motion_halfpel_index != 3) {
2205 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
2206 output_plane + first_pixel,
2207 motion_source, stride, 8);
2209 /* d is 0 if motion_x and _y have the same sign,
2211 int d = (motion_x ^ motion_y) >> 31;
2212 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
2214 motion_source + stride + 1 + d,
2219 /* invert DCT and place (or add) in final output */
2221 if (s->all_fragments[i].coding_method == MODE_INTRA) {
2222 vp3_dequant(s, s->all_fragments + i,
2224 s->vp3dsp.idct_put(output_plane + first_pixel,
2228 if (vp3_dequant(s, s->all_fragments + i,
2230 s->vp3dsp.idct_add(output_plane + first_pixel,
2234 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
2239 /* copy directly from the previous frame */
2240 s->hdsp.put_pixels_tab[1][0](
2241 output_plane + first_pixel,
2242 last_plane + first_pixel,
2248 // Filter up to the last row in the superblock row
2249 if (s->version < 2 && !s->skip_loop_filter)
2250 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
2251 FFMIN(4 * sb_y + 3, fragment_height - 1));
2255 /* this looks like a good place for slice dispatch... */
2257 * if (slice == s->macroblock_height - 1)
2258 * dispatch (both last slice & 2nd-to-last slice);
2259 * else if (slice > 0)
2260 * dispatch (slice - 1);
2263 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
2267 /// Allocate tables for per-frame data in Vp3DecodeContext
2268 static av_cold int allocate_tables(AVCodecContext *avctx)
2270 Vp3DecodeContext *s = avctx->priv_data;
2271 int y_fragment_count, c_fragment_count;
2275 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2276 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2278 /* superblock_coding is used by unpack_superblocks (VP3/Theora) and vp4_unpack_macroblocks (VP4) */
2279 s->superblock_coding = av_mallocz(FFMAX(s->superblock_count, s->yuv_macroblock_count));
2280 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
2282 s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2283 s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2284 memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
2286 s->dct_tokens_base = av_mallocz_array(s->fragment_count,
2287 64 * sizeof(*s->dct_tokens_base));
2288 s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
2289 s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
2291 /* work out the block mapping tables */
2292 s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
2293 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
2295 s->dc_pred_row = av_malloc_array(s->y_superblock_width * 4, sizeof(*s->dc_pred_row));
2297 if (!s->superblock_coding || !s->all_fragments ||
2298 !s->dct_tokens_base || !s->kf_coded_fragment_list ||
2299 !s->nkf_coded_fragment_list ||
2300 !s->superblock_fragments || !s->macroblock_coding ||
2302 !s->motion_val[0] || !s->motion_val[1]) {
2306 init_block_mapping(s);
2311 static av_cold int init_frames(Vp3DecodeContext *s)
2313 s->current_frame.f = av_frame_alloc();
2314 s->last_frame.f = av_frame_alloc();
2315 s->golden_frame.f = av_frame_alloc();
2317 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f)
2318 return AVERROR(ENOMEM);
2323 static av_cold int vp3_decode_init(AVCodecContext *avctx)
2325 Vp3DecodeContext *s = avctx->priv_data;
2326 int i, inter, plane, ret;
2329 int y_fragment_count, c_fragment_count;
2330 #if CONFIG_VP4_DECODER
2334 ret = init_frames(s);
2338 if (avctx->codec_tag == MKTAG('V', 'P', '4', '0'))
2340 else if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
2346 s->width = FFALIGN(avctx->coded_width, 16);
2347 s->height = FFALIGN(avctx->coded_height, 16);
2348 if (avctx->codec_id != AV_CODEC_ID_THEORA)
2349 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2350 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
2351 ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
2352 ff_videodsp_init(&s->vdsp, 8);
2353 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
2355 for (i = 0; i < 64; i++) {
2356 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
2357 s->idct_permutation[i] = TRANSPOSE(i);
2358 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
2362 /* initialize to an impossible value which will force a recalculation
2363 * in the first frame decode */
2364 for (i = 0; i < 3; i++)
2367 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
2371 s->y_superblock_width = (s->width + 31) / 32;
2372 s->y_superblock_height = (s->height + 31) / 32;
2373 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
2375 /* work out the dimensions for the C planes */
2376 c_width = s->width >> s->chroma_x_shift;
2377 c_height = s->height >> s->chroma_y_shift;
2378 s->c_superblock_width = (c_width + 31) / 32;
2379 s->c_superblock_height = (c_height + 31) / 32;
2380 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
2382 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
2383 s->u_superblock_start = s->y_superblock_count;
2384 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
2386 s->macroblock_width = (s->width + 15) / 16;
2387 s->macroblock_height = (s->height + 15) / 16;
2388 s->macroblock_count = s->macroblock_width * s->macroblock_height;
2389 s->c_macroblock_width = (c_width + 15) / 16;
2390 s->c_macroblock_height = (c_height + 15) / 16;
2391 s->c_macroblock_count = s->c_macroblock_width * s->c_macroblock_height;
2392 s->yuv_macroblock_count = s->macroblock_count + 2 * s->c_macroblock_count;
2394 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
2395 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
2396 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
2397 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
2399 /* fragment count covers all 8x8 blocks for all 3 planes */
2400 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2401 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2402 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
2403 s->fragment_start[1] = y_fragment_count;
2404 s->fragment_start[2] = y_fragment_count + c_fragment_count;
2406 if (!s->theora_tables) {
2407 for (i = 0; i < 64; i++) {
2408 s->coded_dc_scale_factor[0][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_y_dc_scale_factor[i];
2409 s->coded_dc_scale_factor[1][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_uv_dc_scale_factor[i];
2410 s->coded_ac_scale_factor[i] = s->version < 2 ? vp31_ac_scale_factor[i] : vp4_ac_scale_factor[i];
2411 s->base_matrix[0][i] = s->version < 2 ? vp31_intra_y_dequant[i] : vp4_generic_dequant[i];
2412 s->base_matrix[1][i] = s->version < 2 ? vp31_intra_c_dequant[i] : vp4_generic_dequant[i];
2413 s->base_matrix[2][i] = s->version < 2 ? vp31_inter_dequant[i] : vp4_generic_dequant[i];
2414 s->filter_limit_values[i] = s->version < 2 ? vp31_filter_limit_values[i] : vp4_filter_limit_values[i];
2417 for (inter = 0; inter < 2; inter++) {
2418 for (plane = 0; plane < 3; plane++) {
2419 s->qr_count[inter][plane] = 1;
2420 s->qr_size[inter][plane][0] = 63;
2421 s->qr_base[inter][plane][0] =
2422 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
2426 /* init VLC tables */
2427 if (s->version < 2) {
2428 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2429 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, 32,
2430 &vp3_bias[i][0][1], 2,
2431 &vp3_bias[i][0][0], 2, 1,
2436 #if CONFIG_VP4_DECODER
2437 } else { /* version >= 2 */
2438 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2439 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, 32,
2440 &vp4_bias[i][0][1], 2,
2441 &vp4_bias[i][0][0], 2, 1,
2449 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2450 const HuffTable *tab = &s->huffman_table[i];
2452 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, tab->nb_entries,
2453 &tab->entries[0].len, sizeof(*tab->entries),
2454 &tab->entries[0].sym, sizeof(*tab->entries), 1,
2461 ret = ff_init_vlc_from_lengths(&s->superblock_run_length_vlc, SUPERBLOCK_VLC_BITS, 34,
2462 superblock_run_length_vlc_lens, 1,
2463 NULL, 0, 0, 1, 0, avctx);
2467 ret = ff_init_vlc_from_lengths(&s->fragment_run_length_vlc, 5, 30,
2468 fragment_run_length_vlc_len, 1,
2469 NULL, 0, 0, 0, 0, avctx);
2473 ret = ff_init_vlc_from_lengths(&s->mode_code_vlc, 3, 8,
2474 mode_code_vlc_len, 1,
2475 NULL, 0, 0, 0, 0, avctx);
2479 ret = ff_init_vlc_from_lengths(&s->motion_vector_vlc, VP3_MV_VLC_BITS, 63,
2480 &motion_vector_vlc_table[0][1], 2,
2481 &motion_vector_vlc_table[0][0], 2, 1,
2486 #if CONFIG_VP4_DECODER
2487 for (j = 0; j < 2; j++)
2488 for (i = 0; i < 7; i++) {
2489 ret = ff_init_vlc_from_lengths(&s->vp4_mv_vlc[j][i], VP4_MV_VLC_BITS, 63,
2490 &vp4_mv_vlc[j][i][0][1], 2,
2491 &vp4_mv_vlc[j][i][0][0], 2, 1, -31,
2498 for (i = 0; i < 2; i++)
2499 if ((ret = init_vlc(&s->block_pattern_vlc[i], 3, 14,
2500 &vp4_block_pattern_vlc[i][0][1], 2, 1,
2501 &vp4_block_pattern_vlc[i][0][0], 2, 1, 0)) < 0)
2505 return allocate_tables(avctx);
2508 /// Release and shuffle frames after decode finishes
2509 static int update_frames(AVCodecContext *avctx)
2511 Vp3DecodeContext *s = avctx->priv_data;
2514 /* shuffle frames (last = current) */
2515 ff_thread_release_buffer(avctx, &s->last_frame);
2516 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
2521 ff_thread_release_buffer(avctx, &s->golden_frame);
2522 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
2526 ff_thread_release_buffer(avctx, &s->current_frame);
2531 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
2533 ff_thread_release_buffer(s->avctx, dst);
2534 if (src->f->data[0])
2535 return ff_thread_ref_frame(dst, src);
2539 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
2542 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
2543 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
2544 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
2549 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
2551 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
2552 int qps_changed = 0, i, err;
2554 if (!s1->current_frame.f->data[0] ||
2555 s->width != s1->width || s->height != s1->height) {
2562 // copy previous frame data
2563 if ((err = ref_frames(s, s1)) < 0)
2566 s->keyframe = s1->keyframe;
2568 // copy qscale data if necessary
2569 for (i = 0; i < 3; i++) {
2570 if (s->qps[i] != s1->qps[1]) {
2572 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2576 if (s->qps[0] != s1->qps[0])
2577 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2578 sizeof(s->bounding_values_array));
2581 memcpy(s->qps, s1->qps, sizeof(s->qps));
2582 memcpy(s->last_qps, s1->last_qps, sizeof(s->last_qps));
2587 return update_frames(dst);
2591 static int vp3_decode_frame(AVCodecContext *avctx,
2592 void *data, int *got_frame,
2595 AVFrame *frame = data;
2596 const uint8_t *buf = avpkt->data;
2597 int buf_size = avpkt->size;
2598 Vp3DecodeContext *s = avctx->priv_data;
2602 if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2605 #if CONFIG_THEORA_DECODER
2606 if (s->theora && get_bits1(&gb)) {
2607 int type = get_bits(&gb, 7);
2608 skip_bits_long(&gb, 6*8); /* "theora" */
2610 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2611 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2612 return AVERROR_PATCHWELCOME;
2615 vp3_decode_end(avctx);
2616 ret = theora_decode_header(avctx, &gb);
2619 ret = vp3_decode_init(avctx);
2621 vp3_decode_end(avctx);
2625 } else if (type == 2) {
2626 vp3_decode_end(avctx);
2627 ret = theora_decode_tables(avctx, &gb);
2629 ret = vp3_decode_init(avctx);
2631 vp3_decode_end(avctx);
2637 av_log(avctx, AV_LOG_ERROR,
2638 "Header packet passed to frame decoder, skipping\n");
2643 s->keyframe = !get_bits1(&gb);
2644 if (!s->all_fragments) {
2645 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2650 for (i = 0; i < 3; i++)
2651 s->last_qps[i] = s->qps[i];
2655 s->qps[s->nqps++] = get_bits(&gb, 6);
2656 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2657 for (i = s->nqps; i < 3; i++)
2660 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2661 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2662 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2664 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2665 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2666 : AVDISCARD_NONKEY);
2668 if (s->qps[0] != s->last_qps[0])
2669 init_loop_filter(s);
2671 for (i = 0; i < s->nqps; i++)
2672 // reinit all dequantizers if the first one changed, because
2673 // the DC of the first quantizer must be used for all matrices
2674 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2675 init_dequantizer(s, i);
2677 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2680 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2681 : AV_PICTURE_TYPE_P;
2682 s->current_frame.f->key_frame = s->keyframe;
2683 if ((ret = ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
2686 if (!s->edge_emu_buffer)
2687 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2691 skip_bits(&gb, 4); /* width code */
2692 skip_bits(&gb, 4); /* height code */
2694 s->version = get_bits(&gb, 5);
2695 if (avctx->frame_number == 0)
2696 av_log(s->avctx, AV_LOG_DEBUG,
2697 "VP version: %d\n", s->version);
2700 if (s->version || s->theora) {
2702 av_log(s->avctx, AV_LOG_ERROR,
2703 "Warning, unsupported keyframe coding type?!\n");
2704 skip_bits(&gb, 2); /* reserved? */
2706 #if CONFIG_VP4_DECODER
2707 if (s->version >= 2) {
2708 int mb_height, mb_width;
2709 int mb_width_mul, mb_width_div, mb_height_mul, mb_height_div;
2711 mb_height = get_bits(&gb, 8);
2712 mb_width = get_bits(&gb, 8);
2713 if (mb_height != s->macroblock_height ||
2714 mb_width != s->macroblock_width)
2715 avpriv_request_sample(s->avctx, "macroblock dimension mismatch");
2717 mb_width_mul = get_bits(&gb, 5);
2718 mb_width_div = get_bits(&gb, 3);
2719 mb_height_mul = get_bits(&gb, 5);
2720 mb_height_div = get_bits(&gb, 3);
2721 if (mb_width_mul != 1 || mb_width_div != 1 || mb_height_mul != 1 || mb_height_div != 1)
2722 avpriv_request_sample(s->avctx, "unexpected macroblock dimension multipler/divider");
2724 if (get_bits(&gb, 2))
2725 avpriv_request_sample(s->avctx, "unknown bits");
2730 if (!s->golden_frame.f->data[0]) {
2731 av_log(s->avctx, AV_LOG_WARNING,
2732 "vp3: first frame not a keyframe\n");
2734 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2735 if ((ret = ff_thread_get_buffer(avctx, &s->golden_frame,
2736 AV_GET_BUFFER_FLAG_REF)) < 0)
2738 ff_thread_release_buffer(avctx, &s->last_frame);
2739 if ((ret = ff_thread_ref_frame(&s->last_frame,
2740 &s->golden_frame)) < 0)
2742 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2746 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2747 ff_thread_finish_setup(avctx);
2749 if (s->version < 2) {
2750 if ((ret = unpack_superblocks(s, &gb)) < 0) {
2751 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2754 #if CONFIG_VP4_DECODER
2756 if ((ret = vp4_unpack_macroblocks(s, &gb)) < 0) {
2757 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_macroblocks\n");
2762 if ((ret = unpack_modes(s, &gb)) < 0) {
2763 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2766 if (ret = unpack_vectors(s, &gb)) {
2767 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2770 if ((ret = unpack_block_qpis(s, &gb)) < 0) {
2771 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2775 if (s->version < 2) {
2776 if ((ret = unpack_dct_coeffs(s, &gb)) < 0) {
2777 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2780 #if CONFIG_VP4_DECODER
2782 if ((ret = vp4_unpack_dct_coeffs(s, &gb)) < 0) {
2783 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_dct_coeffs\n");
2789 for (i = 0; i < 3; i++) {
2790 int height = s->height >> (i && s->chroma_y_shift);
2791 if (s->flipped_image)
2792 s->data_offset[i] = 0;
2794 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2797 s->last_slice_end = 0;
2798 for (i = 0; i < s->c_superblock_height; i++)
2801 // filter the last row
2803 for (i = 0; i < 3; i++) {
2804 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2805 apply_loop_filter(s, i, row, row + 1);
2807 vp3_draw_horiz_band(s, s->height);
2809 /* output frame, offset as needed */
2810 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2813 frame->crop_left = s->offset_x;
2814 frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
2815 frame->crop_top = s->offset_y;
2816 frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2820 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2821 ret = update_frames(avctx);
2829 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2831 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2832 av_frame_unref(s->current_frame.f);
2837 static int read_huffman_tree(HuffTable *huff, GetBitContext *gb, int length,
2838 AVCodecContext *avctx)
2840 if (get_bits1(gb)) {
2842 if (huff->nb_entries >= 32) { /* overflow */
2843 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2846 token = get_bits(gb, 5);
2847 ff_dlog(avctx, "code length %d, curr entry %d, token %d\n",
2848 length, huff->nb_entries, token);
2849 huff->entries[huff->nb_entries++] = (HuffEntry){ length, token };
2851 /* The following bound follows from the fact that nb_entries <= 32. */
2852 if (length >= 31) { /* overflow */
2853 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2857 if (read_huffman_tree(huff, gb, length, avctx))
2859 if (read_huffman_tree(huff, gb, length, avctx))
2865 #if CONFIG_THEORA_DECODER
2866 static const enum AVPixelFormat theora_pix_fmts[4] = {
2867 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2870 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2872 Vp3DecodeContext *s = avctx->priv_data;
2873 int visible_width, visible_height, colorspace;
2874 uint8_t offset_x = 0, offset_y = 0;
2876 AVRational fps, aspect;
2878 if (get_bits_left(gb) < 206)
2879 return AVERROR_INVALIDDATA;
2881 s->theora_header = 0;
2882 s->theora = get_bits(gb, 24);
2883 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2886 avpriv_request_sample(s->avctx, "theora 0");
2889 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2890 * but previous versions have the image flipped relative to vp3 */
2891 if (s->theora < 0x030200) {
2892 s->flipped_image = 1;
2893 av_log(avctx, AV_LOG_DEBUG,
2894 "Old (<alpha3) Theora bitstream, flipped image\n");
2898 s->width = get_bits(gb, 16) << 4;
2900 s->height = get_bits(gb, 16) << 4;
2902 if (s->theora >= 0x030200) {
2903 visible_width = get_bits(gb, 24);
2904 visible_height = get_bits(gb, 24);
2906 offset_x = get_bits(gb, 8); /* offset x */
2907 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2911 if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2912 visible_width + offset_x > s->width ||
2913 visible_height + offset_y > s->height) {
2914 av_log(avctx, AV_LOG_ERROR,
2915 "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2916 visible_width, visible_height, offset_x, offset_y,
2917 s->width, s->height);
2918 return AVERROR_INVALIDDATA;
2921 fps.num = get_bits_long(gb, 32);
2922 fps.den = get_bits_long(gb, 32);
2923 if (fps.num && fps.den) {
2924 if (fps.num < 0 || fps.den < 0) {
2925 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2926 return AVERROR_INVALIDDATA;
2928 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2929 fps.den, fps.num, 1 << 30);
2932 aspect.num = get_bits(gb, 24);
2933 aspect.den = get_bits(gb, 24);
2934 if (aspect.num && aspect.den) {
2935 av_reduce(&avctx->sample_aspect_ratio.num,
2936 &avctx->sample_aspect_ratio.den,
2937 aspect.num, aspect.den, 1 << 30);
2938 ff_set_sar(avctx, avctx->sample_aspect_ratio);
2941 if (s->theora < 0x030200)
2942 skip_bits(gb, 5); /* keyframe frequency force */
2943 colorspace = get_bits(gb, 8);
2944 skip_bits(gb, 24); /* bitrate */
2946 skip_bits(gb, 6); /* quality hint */
2948 if (s->theora >= 0x030200) {
2949 skip_bits(gb, 5); /* keyframe frequency force */
2950 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2951 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2952 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2953 return AVERROR_INVALIDDATA;
2955 skip_bits(gb, 3); /* reserved */
2957 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2959 ret = ff_set_dimensions(avctx, s->width, s->height);
2962 if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2963 avctx->width = visible_width;
2964 avctx->height = visible_height;
2965 // translate offsets from theora axis ([0,0] lower left)
2966 // to normal axis ([0,0] upper left)
2967 s->offset_x = offset_x;
2968 s->offset_y = s->height - visible_height - offset_y;
2971 if (colorspace == 1)
2972 avctx->color_primaries = AVCOL_PRI_BT470M;
2973 else if (colorspace == 2)
2974 avctx->color_primaries = AVCOL_PRI_BT470BG;
2976 if (colorspace == 1 || colorspace == 2) {
2977 avctx->colorspace = AVCOL_SPC_BT470BG;
2978 avctx->color_trc = AVCOL_TRC_BT709;
2981 s->theora_header = 1;
2985 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2987 Vp3DecodeContext *s = avctx->priv_data;
2988 int i, n, matrices, inter, plane, ret;
2990 if (!s->theora_header)
2991 return AVERROR_INVALIDDATA;
2993 if (s->theora >= 0x030200) {
2994 n = get_bits(gb, 3);
2995 /* loop filter limit values table */
2997 for (i = 0; i < 64; i++)
2998 s->filter_limit_values[i] = get_bits(gb, n);
3001 if (s->theora >= 0x030200)
3002 n = get_bits(gb, 4) + 1;
3005 /* quality threshold table */
3006 for (i = 0; i < 64; i++)
3007 s->coded_ac_scale_factor[i] = get_bits(gb, n);
3009 if (s->theora >= 0x030200)
3010 n = get_bits(gb, 4) + 1;
3013 /* dc scale factor table */
3014 for (i = 0; i < 64; i++)
3015 s->coded_dc_scale_factor[0][i] =
3016 s->coded_dc_scale_factor[1][i] = get_bits(gb, n);
3018 if (s->theora >= 0x030200)
3019 matrices = get_bits(gb, 9) + 1;
3023 if (matrices > 384) {
3024 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
3028 for (n = 0; n < matrices; n++)
3029 for (i = 0; i < 64; i++)
3030 s->base_matrix[n][i] = get_bits(gb, 8);
3032 for (inter = 0; inter <= 1; inter++) {
3033 for (plane = 0; plane <= 2; plane++) {
3035 if (inter || plane > 0)
3036 newqr = get_bits1(gb);
3039 if (inter && get_bits1(gb)) {
3043 qtj = (3 * inter + plane - 1) / 3;
3044 plj = (plane + 2) % 3;
3046 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
3047 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
3048 sizeof(s->qr_size[0][0]));
3049 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
3050 sizeof(s->qr_base[0][0]));
3056 i = get_bits(gb, av_log2(matrices - 1) + 1);
3057 if (i >= matrices) {
3058 av_log(avctx, AV_LOG_ERROR,
3059 "invalid base matrix index\n");
3062 s->qr_base[inter][plane][qri] = i;
3065 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
3066 s->qr_size[inter][plane][qri++] = i;
3071 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
3074 s->qr_count[inter][plane] = qri;
3079 /* Huffman tables */
3080 for (int i = 0; i < FF_ARRAY_ELEMS(s->huffman_table); i++) {
3081 s->huffman_table[i].nb_entries = 0;
3082 if ((ret = read_huffman_tree(&s->huffman_table[i], gb, 0, avctx)) < 0)
3086 s->theora_tables = 1;
3091 static av_cold int theora_decode_init(AVCodecContext *avctx)
3093 Vp3DecodeContext *s = avctx->priv_data;
3096 const uint8_t *header_start[3];
3101 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
3105 if (!avctx->extradata_size) {
3106 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
3110 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
3111 42, header_start, header_len) < 0) {
3112 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
3116 for (i = 0; i < 3; i++) {
3117 if (header_len[i] <= 0)
3119 ret = init_get_bits8(&gb, header_start[i], header_len[i]);
3123 ptype = get_bits(&gb, 8);
3125 if (!(ptype & 0x80)) {
3126 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
3130 // FIXME: Check for this as well.
3131 skip_bits_long(&gb, 6 * 8); /* "theora" */
3135 if (theora_decode_header(avctx, &gb) < 0)
3139 // FIXME: is this needed? it breaks sometimes
3140 // theora_decode_comments(avctx, gb);
3143 if (theora_decode_tables(avctx, &gb))
3147 av_log(avctx, AV_LOG_ERROR,
3148 "Unknown Theora config packet: %d\n", ptype & ~0x80);
3151 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
3152 av_log(avctx, AV_LOG_WARNING,
3153 "%d bits left in packet %X\n",
3154 8 * header_len[i] - get_bits_count(&gb), ptype);
3155 if (s->theora < 0x030200)
3159 return vp3_decode_init(avctx);
3162 const AVCodec ff_theora_decoder = {
3164 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
3165 .type = AVMEDIA_TYPE_VIDEO,
3166 .id = AV_CODEC_ID_THEORA,
3167 .priv_data_size = sizeof(Vp3DecodeContext),
3168 .init = theora_decode_init,
3169 .close = vp3_decode_end,
3170 .decode = vp3_decode_frame,
3171 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3172 AV_CODEC_CAP_FRAME_THREADS,
3173 .flush = vp3_decode_flush,
3174 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3175 .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING | FF_CODEC_CAP_ALLOCATE_PROGRESS |
3176 FF_CODEC_CAP_INIT_CLEANUP,
3180 const AVCodec ff_vp3_decoder = {
3182 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
3183 .type = AVMEDIA_TYPE_VIDEO,
3184 .id = AV_CODEC_ID_VP3,
3185 .priv_data_size = sizeof(Vp3DecodeContext),
3186 .init = vp3_decode_init,
3187 .close = vp3_decode_end,
3188 .decode = vp3_decode_frame,
3189 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3190 AV_CODEC_CAP_FRAME_THREADS,
3191 .flush = vp3_decode_flush,
3192 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3193 .caps_internal = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
3196 #if CONFIG_VP4_DECODER
3197 const AVCodec ff_vp4_decoder = {
3199 .long_name = NULL_IF_CONFIG_SMALL("On2 VP4"),
3200 .type = AVMEDIA_TYPE_VIDEO,
3201 .id = AV_CODEC_ID_VP4,
3202 .priv_data_size = sizeof(Vp3DecodeContext),
3203 .init = vp3_decode_init,
3204 .close = vp3_decode_end,
3205 .decode = vp3_decode_frame,
3206 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3207 AV_CODEC_CAP_FRAME_THREADS,
3208 .flush = vp3_decode_flush,
3209 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3210 .caps_internal = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,