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 VP3_MV_VLC_BITS 6
52 #define VP4_MV_VLC_BITS 6
53 #define SUPERBLOCK_VLC_BITS 6
55 #define FRAGMENT_PIXELS 8
57 // FIXME split things out into their own arrays
58 typedef struct Vp3Fragment {
60 uint8_t coding_method;
64 #define SB_NOT_CODED 0
65 #define SB_PARTIALLY_CODED 1
66 #define SB_FULLY_CODED 2
68 // This is the maximum length of a single long bit run that can be encoded
69 // for superblock coding or block qps. Theora special-cases this to read a
70 // bit instead of flipping the current bit to allow for runs longer than 4129.
71 #define MAXIMUM_LONG_BIT_RUN 4129
73 #define MODE_INTER_NO_MV 0
75 #define MODE_INTER_PLUS_MV 2
76 #define MODE_INTER_LAST_MV 3
77 #define MODE_INTER_PRIOR_LAST 4
78 #define MODE_USING_GOLDEN 5
79 #define MODE_GOLDEN_MV 6
80 #define MODE_INTER_FOURMV 7
81 #define CODING_MODE_COUNT 8
83 /* special internal mode */
86 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
87 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
90 /* There are 6 preset schemes, plus a free-form scheme */
91 static const int ModeAlphabet[6][CODING_MODE_COUNT] = {
92 /* scheme 1: Last motion vector dominates */
93 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
94 MODE_INTER_PLUS_MV, MODE_INTER_NO_MV,
95 MODE_INTRA, MODE_USING_GOLDEN,
96 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
99 { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
100 MODE_INTER_NO_MV, MODE_INTER_PLUS_MV,
101 MODE_INTRA, MODE_USING_GOLDEN,
102 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
105 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
106 MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
107 MODE_INTRA, MODE_USING_GOLDEN,
108 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
111 { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
112 MODE_INTER_NO_MV, MODE_INTER_PRIOR_LAST,
113 MODE_INTRA, MODE_USING_GOLDEN,
114 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
116 /* scheme 5: No motion vector dominates */
117 { MODE_INTER_NO_MV, MODE_INTER_LAST_MV,
118 MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
119 MODE_INTRA, MODE_USING_GOLDEN,
120 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
123 { MODE_INTER_NO_MV, MODE_USING_GOLDEN,
124 MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
125 MODE_INTER_PLUS_MV, MODE_INTRA,
126 MODE_GOLDEN_MV, MODE_INTER_FOURMV },
129 static const uint8_t hilbert_offset[16][2] = {
130 { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
131 { 0, 2 }, { 0, 3 }, { 1, 3 }, { 1, 2 },
132 { 2, 2 }, { 2, 3 }, { 3, 3 }, { 3, 2 },
133 { 3, 1 }, { 2, 1 }, { 2, 0 }, { 3, 0 }
141 VP4_DC_UNDEFINED = NB_VP4_DC_TYPES
144 static const uint8_t vp4_pred_block_type_map[8] = {
145 [MODE_INTER_NO_MV] = VP4_DC_INTER,
146 [MODE_INTRA] = VP4_DC_INTRA,
147 [MODE_INTER_PLUS_MV] = VP4_DC_INTER,
148 [MODE_INTER_LAST_MV] = VP4_DC_INTER,
149 [MODE_INTER_PRIOR_LAST] = VP4_DC_INTER,
150 [MODE_USING_GOLDEN] = VP4_DC_GOLDEN,
151 [MODE_GOLDEN_MV] = VP4_DC_GOLDEN,
152 [MODE_INTER_FOURMV] = VP4_DC_INTER,
160 #define MIN_DEQUANT_VAL 2
162 typedef struct HuffEntry {
166 typedef struct HuffTable {
167 HuffEntry entries[32];
171 typedef struct Vp3DecodeContext {
172 AVCodecContext *avctx;
173 int theora, theora_tables, theora_header;
176 int chroma_x_shift, chroma_y_shift;
177 ThreadFrame golden_frame;
178 ThreadFrame last_frame;
179 ThreadFrame current_frame;
181 uint8_t idct_permutation[64];
182 uint8_t idct_scantable[64];
184 VideoDSPContext vdsp;
185 VP3DSPContext vp3dsp;
186 DECLARE_ALIGNED(16, int16_t, block)[64];
189 int skip_loop_filter;
195 int superblock_count;
196 int y_superblock_width;
197 int y_superblock_height;
198 int y_superblock_count;
199 int c_superblock_width;
200 int c_superblock_height;
201 int c_superblock_count;
202 int u_superblock_start;
203 int v_superblock_start;
204 unsigned char *superblock_coding;
206 int macroblock_count; /* y macroblock count */
207 int macroblock_width;
208 int macroblock_height;
209 int c_macroblock_count;
210 int c_macroblock_width;
211 int c_macroblock_height;
212 int yuv_macroblock_count; /* y+u+v macroblock count */
215 int fragment_width[2];
216 int fragment_height[2];
218 Vp3Fragment *all_fragments;
219 int fragment_start[3];
225 int8_t (*motion_val[2])[2];
228 uint16_t coded_dc_scale_factor[2][64];
229 uint32_t coded_ac_scale_factor[64];
230 uint8_t base_matrix[384][64];
231 uint8_t qr_count[2][3];
232 uint8_t qr_size[2][3][64];
233 uint16_t qr_base[2][3][64];
236 * This is a list of all tokens in bitstream order. Reordering takes place
237 * by pulling from each level during IDCT. As a consequence, IDCT must be
238 * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
239 * otherwise. The 32 different tokens with up to 12 bits of extradata are
240 * collapsed into 3 types, packed as follows:
241 * (from the low to high bits)
243 * 2 bits: type (0,1,2)
244 * 0: EOB run, 14 bits for run length (12 needed)
245 * 1: zero run, 7 bits for run length
246 * 7 bits for the next coefficient (3 needed)
247 * 2: coefficient, 14 bits (11 needed)
249 * Coefficients are signed, so are packed in the highest bits for automatic
252 int16_t *dct_tokens[3][64];
253 int16_t *dct_tokens_base;
254 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
255 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
256 #define TOKEN_COEFF(coeff) (((coeff) * 4) + 2)
259 * number of blocks that contain DCT coefficients at
260 * the given level or higher
262 int num_coded_frags[3][64];
263 int total_num_coded_frags;
265 /* this is a list of indexes into the all_fragments array indicating
266 * which of the fragments are coded */
267 int *coded_fragment_list[3];
269 int *kf_coded_fragment_list;
270 int *nkf_coded_fragment_list;
271 int num_kf_coded_fragment[3];
273 /* The first 16 of the following VLCs are for the dc coefficients;
274 the others are four groups of 16 VLCs each for ac coefficients. */
275 VLC coeff_vlc[5 * 16];
277 VLC superblock_run_length_vlc; /* version < 2 */
278 VLC fragment_run_length_vlc; /* version < 2 */
279 VLC block_pattern_vlc[2]; /* version >= 2*/
281 VLC motion_vector_vlc; /* version < 2 */
282 VLC vp4_mv_vlc[2][7]; /* version >=2 */
284 /* these arrays need to be on 16-byte boundaries since SSE2 operations
286 DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
288 /* This table contains superblock_count * 16 entries. Each set of 16
289 * numbers corresponds to the fragment indexes 0..15 of the superblock.
290 * An entry will be -1 to indicate that no entry corresponds to that
292 int *superblock_fragments;
294 /* This is an array that indicates how a particular macroblock
296 unsigned char *macroblock_coding;
298 uint8_t *edge_emu_buffer;
301 HuffTable huffman_table[5 * 16];
303 uint8_t filter_limit_values[64];
304 DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
306 VP4Predictor * dc_pred_row; /* dc_pred_row[y_superblock_width * 4] */
309 /************************************************************************
310 * VP3 specific functions
311 ************************************************************************/
313 static av_cold void free_tables(AVCodecContext *avctx)
315 Vp3DecodeContext *s = avctx->priv_data;
317 av_freep(&s->superblock_coding);
318 av_freep(&s->all_fragments);
319 av_freep(&s->nkf_coded_fragment_list);
320 av_freep(&s->kf_coded_fragment_list);
321 av_freep(&s->dct_tokens_base);
322 av_freep(&s->superblock_fragments);
323 av_freep(&s->macroblock_coding);
324 av_freep(&s->dc_pred_row);
325 av_freep(&s->motion_val[0]);
326 av_freep(&s->motion_val[1]);
329 static void vp3_decode_flush(AVCodecContext *avctx)
331 Vp3DecodeContext *s = avctx->priv_data;
333 if (s->golden_frame.f)
334 ff_thread_release_buffer(avctx, &s->golden_frame);
336 ff_thread_release_buffer(avctx, &s->last_frame);
337 if (s->current_frame.f)
338 ff_thread_release_buffer(avctx, &s->current_frame);
341 static av_cold int vp3_decode_end(AVCodecContext *avctx)
343 Vp3DecodeContext *s = avctx->priv_data;
347 av_freep(&s->edge_emu_buffer);
349 s->theora_tables = 0;
351 /* release all frames */
352 vp3_decode_flush(avctx);
353 av_frame_free(&s->current_frame.f);
354 av_frame_free(&s->last_frame.f);
355 av_frame_free(&s->golden_frame.f);
357 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++)
358 ff_free_vlc(&s->coeff_vlc[i]);
360 ff_free_vlc(&s->superblock_run_length_vlc);
361 ff_free_vlc(&s->fragment_run_length_vlc);
362 ff_free_vlc(&s->mode_code_vlc);
363 ff_free_vlc(&s->motion_vector_vlc);
365 for (j = 0; j < 2; j++)
366 for (i = 0; i < 7; i++)
367 ff_free_vlc(&s->vp4_mv_vlc[j][i]);
369 for (i = 0; i < 2; i++)
370 ff_free_vlc(&s->block_pattern_vlc[i]);
375 * This function sets up all of the various blocks mappings:
376 * superblocks <-> fragments, macroblocks <-> fragments,
377 * superblocks <-> macroblocks
379 * @return 0 is successful; returns 1 if *anything* went wrong.
381 static int init_block_mapping(Vp3DecodeContext *s)
383 int sb_x, sb_y, plane;
386 for (plane = 0; plane < 3; plane++) {
387 int sb_width = plane ? s->c_superblock_width
388 : s->y_superblock_width;
389 int sb_height = plane ? s->c_superblock_height
390 : s->y_superblock_height;
391 int frag_width = s->fragment_width[!!plane];
392 int frag_height = s->fragment_height[!!plane];
394 for (sb_y = 0; sb_y < sb_height; sb_y++)
395 for (sb_x = 0; sb_x < sb_width; sb_x++)
396 for (i = 0; i < 16; i++) {
397 x = 4 * sb_x + hilbert_offset[i][0];
398 y = 4 * sb_y + hilbert_offset[i][1];
400 if (x < frag_width && y < frag_height)
401 s->superblock_fragments[j++] = s->fragment_start[plane] +
404 s->superblock_fragments[j++] = -1;
408 return 0; /* successful path out */
412 * This function sets up the dequantization tables used for a particular
415 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
417 int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
418 int i, plane, inter, qri, bmi, bmj, qistart;
420 for (inter = 0; inter < 2; inter++) {
421 for (plane = 0; plane < 3; plane++) {
422 int dc_scale_factor = s->coded_dc_scale_factor[!!plane][s->qps[qpi]];
424 for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
425 sum += s->qr_size[inter][plane][qri];
426 if (s->qps[qpi] <= sum)
429 qistart = sum - s->qr_size[inter][plane][qri];
430 bmi = s->qr_base[inter][plane][qri];
431 bmj = s->qr_base[inter][plane][qri + 1];
432 for (i = 0; i < 64; i++) {
433 int coeff = (2 * (sum - s->qps[qpi]) * s->base_matrix[bmi][i] -
434 2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
435 s->qr_size[inter][plane][qri]) /
436 (2 * s->qr_size[inter][plane][qri]);
438 int qmin = 8 << (inter + !i);
439 int qscale = i ? ac_scale_factor : dc_scale_factor;
440 int qbias = (1 + inter) * 3;
441 s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
442 (i == 0 || s->version < 2) ? av_clip((qscale * coeff) / 100 * 4, qmin, 4096)
443 : (qscale * (coeff - qbias) / 100 + qbias) * 4;
445 /* all DC coefficients use the same quant so as not to interfere
446 * with DC prediction */
447 s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
453 * This function initializes the loop filter boundary limits if the frame's
454 * quality index is different from the previous frame's.
456 * The filter_limit_values may not be larger than 127.
458 static void init_loop_filter(Vp3DecodeContext *s)
460 ff_vp3dsp_set_bounding_values(s->bounding_values_array, s->filter_limit_values[s->qps[0]]);
464 * This function unpacks all of the superblock/macroblock/fragment coding
465 * information from the bitstream.
467 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
469 int superblock_starts[3] = {
470 0, s->u_superblock_start, s->v_superblock_start
473 int current_superblock = 0;
475 int num_partial_superblocks = 0;
478 int current_fragment;
480 int plane0_num_coded_frags = 0;
483 memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
485 /* unpack the list of partially-coded superblocks */
486 bit = get_bits1(gb) ^ 1;
489 while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
490 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
495 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
496 SUPERBLOCK_VLC_BITS, 2);
497 if (current_run == 34)
498 current_run += get_bits(gb, 12);
500 if (current_run > s->superblock_count - current_superblock) {
501 av_log(s->avctx, AV_LOG_ERROR,
502 "Invalid partially coded superblock run length\n");
506 memset(s->superblock_coding + current_superblock, bit, current_run);
508 current_superblock += current_run;
510 num_partial_superblocks += current_run;
513 /* unpack the list of fully coded superblocks if any of the blocks were
514 * not marked as partially coded in the previous step */
515 if (num_partial_superblocks < s->superblock_count) {
516 int superblocks_decoded = 0;
518 current_superblock = 0;
519 bit = get_bits1(gb) ^ 1;
522 while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
523 get_bits_left(gb) > 0) {
524 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
529 current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
530 SUPERBLOCK_VLC_BITS, 2);
531 if (current_run == 34)
532 current_run += get_bits(gb, 12);
534 for (j = 0; j < current_run; current_superblock++) {
535 if (current_superblock >= s->superblock_count) {
536 av_log(s->avctx, AV_LOG_ERROR,
537 "Invalid fully coded superblock run length\n");
541 /* skip any superblocks already marked as partially coded */
542 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
543 s->superblock_coding[current_superblock] = 2 * bit;
547 superblocks_decoded += current_run;
551 /* if there were partial blocks, initialize bitstream for
552 * unpacking fragment codings */
553 if (num_partial_superblocks) {
556 /* toggle the bit because as soon as the first run length is
557 * fetched the bit will be toggled again */
562 /* figure out which fragments are coded; iterate through each
563 * superblock (all planes) */
564 s->total_num_coded_frags = 0;
565 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
567 s->coded_fragment_list[0] = s->keyframe ? s->kf_coded_fragment_list
568 : s->nkf_coded_fragment_list;
570 for (plane = 0; plane < 3; plane++) {
571 int sb_start = superblock_starts[plane];
572 int sb_end = sb_start + (plane ? s->c_superblock_count
573 : s->y_superblock_count);
574 int num_coded_frags = 0;
577 if (s->num_kf_coded_fragment[plane] == -1) {
578 for (i = sb_start; i < sb_end; i++) {
579 /* iterate through all 16 fragments in a superblock */
580 for (j = 0; j < 16; j++) {
581 /* if the fragment is in bounds, check its coding status */
582 current_fragment = s->superblock_fragments[i * 16 + j];
583 if (current_fragment != -1) {
584 s->coded_fragment_list[plane][num_coded_frags++] =
589 s->num_kf_coded_fragment[plane] = num_coded_frags;
591 num_coded_frags = s->num_kf_coded_fragment[plane];
593 for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
594 if (get_bits_left(gb) < plane0_num_coded_frags >> 2) {
595 return AVERROR_INVALIDDATA;
597 /* iterate through all 16 fragments in a superblock */
598 for (j = 0; j < 16; j++) {
599 /* if the fragment is in bounds, check its coding status */
600 current_fragment = s->superblock_fragments[i * 16 + j];
601 if (current_fragment != -1) {
602 int coded = s->superblock_coding[i];
604 if (coded == SB_PARTIALLY_CODED) {
605 /* fragment may or may not be coded; this is the case
606 * that cares about the fragment coding runs */
607 if (current_run-- == 0) {
609 current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
615 /* default mode; actual mode will be decoded in
617 s->all_fragments[current_fragment].coding_method =
619 s->coded_fragment_list[plane][num_coded_frags++] =
622 /* not coded; copy this fragment from the prior frame */
623 s->all_fragments[current_fragment].coding_method =
631 plane0_num_coded_frags = num_coded_frags;
632 s->total_num_coded_frags += num_coded_frags;
633 for (i = 0; i < 64; i++)
634 s->num_coded_frags[plane][i] = num_coded_frags;
636 s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
642 #define BLOCK_X (2 * mb_x + (k & 1))
643 #define BLOCK_Y (2 * mb_y + (k >> 1))
645 #if CONFIG_VP4_DECODER
647 * @return number of blocks, or > yuv_macroblock_count on error.
648 * return value is always >= 1.
650 static int vp4_get_mb_count(Vp3DecodeContext *s, GetBitContext *gb)
654 while ((bits = show_bits(gb, 9)) == 0x1ff) {
657 if (v > s->yuv_macroblock_count) {
658 av_log(s->avctx, AV_LOG_ERROR, "Invalid run length\n");
663 skip_bits(gb, 2 + n); \
664 v += (1 << n) + get_bits(gb, n); }
665 #define thresh(n) (0x200 - (0x80 >> n))
666 #define else_if(n) else if (bits < thresh(n)) body(n)
669 } else if (bits < thresh(0)) {
686 static int vp4_get_block_pattern(Vp3DecodeContext *s, GetBitContext *gb, int *next_block_pattern_table)
688 int v = get_vlc2(gb, s->block_pattern_vlc[*next_block_pattern_table].table, 3, 2);
689 *next_block_pattern_table = vp4_block_pattern_table_selector[v];
693 static int vp4_unpack_macroblocks(Vp3DecodeContext *s, GetBitContext *gb)
695 int plane, i, j, k, fragment;
696 int next_block_pattern_table;
697 int bit, current_run, has_partial;
699 memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
706 for (i = 0; i < s->yuv_macroblock_count; i += current_run) {
707 if (get_bits_left(gb) <= 0)
708 return AVERROR_INVALIDDATA;
709 current_run = vp4_get_mb_count(s, gb);
710 if (current_run > s->yuv_macroblock_count - i)
712 memset(s->superblock_coding + i, 2 * bit, current_run);
718 if (get_bits_left(gb) <= 0)
719 return AVERROR_INVALIDDATA;
721 current_run = vp4_get_mb_count(s, gb);
722 for (i = 0; i < s->yuv_macroblock_count; i++) {
723 if (!s->superblock_coding[i]) {
726 current_run = vp4_get_mb_count(s, gb);
728 s->superblock_coding[i] = bit;
732 if (current_run) /* handle situation when vp4_get_mb_count() fails */
736 next_block_pattern_table = 0;
738 for (plane = 0; plane < 3; plane++) {
740 int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
741 int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
742 int mb_width = plane ? s->c_macroblock_width : s->macroblock_width;
743 int mb_height = plane ? s->c_macroblock_height : s->macroblock_height;
744 int fragment_width = s->fragment_width[!!plane];
745 int fragment_height = s->fragment_height[!!plane];
747 for (sb_y = 0; sb_y < sb_height; sb_y++) {
748 for (sb_x = 0; sb_x < sb_width; sb_x++) {
749 for (j = 0; j < 4; j++) {
750 int mb_x = 2 * sb_x + (j >> 1);
751 int mb_y = 2 * sb_y + (j >> 1) ^ (j & 1);
752 int mb_coded, pattern, coded;
754 if (mb_x >= mb_width || mb_y >= mb_height)
757 mb_coded = s->superblock_coding[i++];
759 if (mb_coded == SB_FULLY_CODED)
761 else if (mb_coded == SB_PARTIALLY_CODED)
762 pattern = vp4_get_block_pattern(s, gb, &next_block_pattern_table);
766 for (k = 0; k < 4; k++) {
767 if (BLOCK_X >= fragment_width || BLOCK_Y >= fragment_height)
769 fragment = s->fragment_start[plane] + BLOCK_Y * fragment_width + BLOCK_X;
770 coded = pattern & (8 >> k);
771 /* MODE_INTER_NO_MV is the default for coded fragments.
772 the actual method is decoded in the next phase. */
773 s->all_fragments[fragment].coding_method = coded ? MODE_INTER_NO_MV : MODE_COPY;
784 * This function unpacks all the coding mode data for individual macroblocks
785 * from the bitstream.
787 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
789 int i, j, k, sb_x, sb_y;
791 int current_macroblock;
792 int current_fragment;
794 int custom_mode_alphabet[CODING_MODE_COUNT];
799 for (i = 0; i < s->fragment_count; i++)
800 s->all_fragments[i].coding_method = MODE_INTRA;
802 /* fetch the mode coding scheme for this frame */
803 scheme = get_bits(gb, 3);
805 /* is it a custom coding scheme? */
807 for (i = 0; i < 8; i++)
808 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
809 for (i = 0; i < 8; i++)
810 custom_mode_alphabet[get_bits(gb, 3)] = i;
811 alphabet = custom_mode_alphabet;
813 alphabet = ModeAlphabet[scheme - 1];
815 /* iterate through all of the macroblocks that contain 1 or more
817 for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
818 for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
819 if (get_bits_left(gb) <= 0)
822 for (j = 0; j < 4; j++) {
823 int mb_x = 2 * sb_x + (j >> 1);
824 int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
825 current_macroblock = mb_y * s->macroblock_width + mb_x;
827 if (mb_x >= s->macroblock_width ||
828 mb_y >= s->macroblock_height)
831 /* coding modes are only stored if the macroblock has
832 * at least one luma block coded, otherwise it must be
834 for (k = 0; k < 4; k++) {
835 current_fragment = BLOCK_Y *
836 s->fragment_width[0] + BLOCK_X;
837 if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
841 s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
845 /* mode 7 means get 3 bits for each coding mode */
847 coding_mode = get_bits(gb, 3);
849 coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
851 s->macroblock_coding[current_macroblock] = coding_mode;
852 for (k = 0; k < 4; k++) {
853 frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
854 if (frag->coding_method != MODE_COPY)
855 frag->coding_method = coding_mode;
858 #define SET_CHROMA_MODES \
859 if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
860 frag[s->fragment_start[1]].coding_method = coding_mode; \
861 if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
862 frag[s->fragment_start[2]].coding_method = coding_mode;
864 if (s->chroma_y_shift) {
865 frag = s->all_fragments + mb_y *
866 s->fragment_width[1] + mb_x;
868 } else if (s->chroma_x_shift) {
869 frag = s->all_fragments +
870 2 * mb_y * s->fragment_width[1] + mb_x;
871 for (k = 0; k < 2; k++) {
873 frag += s->fragment_width[1];
876 for (k = 0; k < 4; k++) {
877 frag = s->all_fragments +
878 BLOCK_Y * s->fragment_width[1] + BLOCK_X;
890 static int vp4_get_mv(Vp3DecodeContext *s, GetBitContext *gb, int axis, int last_motion)
892 int v = get_vlc2(gb, s->vp4_mv_vlc[axis][vp4_mv_table_selector[FFABS(last_motion)]].table,
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] = get_vlc2(gb, s->motion_vector_vlc.table,
952 motion_y[0] = get_vlc2(gb, s->motion_vector_vlc.table,
954 } else if (coding_mode == 1) {
955 motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
956 motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
958 motion_x[0] = vp4_get_mv(s, gb, 0, last_motion_x);
959 motion_y[0] = vp4_get_mv(s, gb, 1, last_motion_y);
962 /* vector maintenance, only on MODE_INTER_PLUS_MV */
963 if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
964 prior_last_motion_x = last_motion_x;
965 prior_last_motion_y = last_motion_y;
966 last_motion_x = motion_x[0];
967 last_motion_y = motion_y[0];
971 case MODE_INTER_FOURMV:
972 /* vector maintenance */
973 prior_last_motion_x = last_motion_x;
974 prior_last_motion_y = last_motion_y;
976 /* fetch 4 vectors from the bitstream, one for each
977 * Y fragment, then average for the C fragment vectors */
978 for (k = 0; k < 4; k++) {
979 current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
980 if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
981 if (coding_mode == 0) {
982 motion_x[k] = get_vlc2(gb, s->motion_vector_vlc.table,
984 motion_y[k] = get_vlc2(gb, s->motion_vector_vlc.table,
986 } else if (coding_mode == 1) {
987 motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
988 motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
990 motion_x[k] = vp4_get_mv(s, gb, 0, prior_last_motion_x);
991 motion_y[k] = vp4_get_mv(s, gb, 1, prior_last_motion_y);
993 last_motion_x = motion_x[k];
994 last_motion_y = motion_y[k];
1002 case MODE_INTER_LAST_MV:
1003 /* all 6 fragments use the last motion vector */
1004 motion_x[0] = last_motion_x;
1005 motion_y[0] = last_motion_y;
1007 /* no vector maintenance (last vector remains the
1011 case MODE_INTER_PRIOR_LAST:
1012 /* all 6 fragments use the motion vector prior to the
1013 * last motion vector */
1014 motion_x[0] = prior_last_motion_x;
1015 motion_y[0] = prior_last_motion_y;
1017 /* vector maintenance */
1018 prior_last_motion_x = last_motion_x;
1019 prior_last_motion_y = last_motion_y;
1020 last_motion_x = motion_x[0];
1021 last_motion_y = motion_y[0];
1025 /* covers intra, inter without MV, golden without MV */
1029 /* no vector maintenance */
1033 /* assign the motion vectors to the correct fragments */
1034 for (k = 0; k < 4; k++) {
1036 BLOCK_Y * s->fragment_width[0] + BLOCK_X;
1037 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1038 s->motion_val[0][current_fragment][0] = motion_x[k];
1039 s->motion_val[0][current_fragment][1] = motion_y[k];
1041 s->motion_val[0][current_fragment][0] = motion_x[0];
1042 s->motion_val[0][current_fragment][1] = motion_y[0];
1046 if (s->chroma_y_shift) {
1047 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1048 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
1049 motion_x[2] + motion_x[3], 2);
1050 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
1051 motion_y[2] + motion_y[3], 2);
1053 if (s->version <= 2) {
1054 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1055 motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
1057 frag = mb_y * s->fragment_width[1] + mb_x;
1058 s->motion_val[1][frag][0] = motion_x[0];
1059 s->motion_val[1][frag][1] = motion_y[0];
1060 } else if (s->chroma_x_shift) {
1061 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1062 motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
1063 motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
1064 motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
1065 motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
1067 motion_x[1] = motion_x[0];
1068 motion_y[1] = motion_y[0];
1070 if (s->version <= 2) {
1071 motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1072 motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
1074 frag = 2 * mb_y * s->fragment_width[1] + mb_x;
1075 for (k = 0; k < 2; k++) {
1076 s->motion_val[1][frag][0] = motion_x[k];
1077 s->motion_val[1][frag][1] = motion_y[k];
1078 frag += s->fragment_width[1];
1081 for (k = 0; k < 4; k++) {
1082 frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
1083 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1084 s->motion_val[1][frag][0] = motion_x[k];
1085 s->motion_val[1][frag][1] = motion_y[k];
1087 s->motion_val[1][frag][0] = motion_x[0];
1088 s->motion_val[1][frag][1] = motion_y[0];
1099 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
1101 int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
1102 int num_blocks = s->total_num_coded_frags;
1104 for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
1105 i = blocks_decoded = num_blocks_at_qpi = 0;
1107 bit = get_bits1(gb) ^ 1;
1111 if (run_length == MAXIMUM_LONG_BIT_RUN)
1112 bit = get_bits1(gb);
1116 run_length = get_vlc2(gb, s->superblock_run_length_vlc.table,
1117 SUPERBLOCK_VLC_BITS, 2);
1118 if (run_length == 34)
1119 run_length += get_bits(gb, 12);
1120 blocks_decoded += run_length;
1123 num_blocks_at_qpi += run_length;
1125 for (j = 0; j < run_length; i++) {
1126 if (i >= s->total_num_coded_frags)
1129 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
1130 s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
1134 } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
1136 num_blocks -= num_blocks_at_qpi;
1142 static inline int get_eob_run(GetBitContext *gb, int token)
1144 int v = eob_run_table[token].base;
1145 if (eob_run_table[token].bits)
1146 v += get_bits(gb, eob_run_table[token].bits);
1150 static inline int get_coeff(GetBitContext *gb, int token, int16_t *coeff)
1152 int bits_to_get, zero_run;
1154 bits_to_get = coeff_get_bits[token];
1156 bits_to_get = get_bits(gb, bits_to_get);
1157 *coeff = coeff_tables[token][bits_to_get];
1159 zero_run = zero_run_base[token];
1160 if (zero_run_get_bits[token])
1161 zero_run += get_bits(gb, zero_run_get_bits[token]);
1167 * This function is called by unpack_dct_coeffs() to extract the VLCs from
1168 * the bitstream. The VLCs encode tokens which are used to unpack DCT
1169 * data. This function unpacks all the VLCs for either the Y plane or both
1170 * C planes, and is called for DC coefficients or different AC coefficient
1171 * levels (since different coefficient types require different VLC tables.
1173 * This function returns a residual eob run. E.g, if a particular token gave
1174 * instructions to EOB the next 5 fragments and there were only 2 fragments
1175 * left in the current fragment range, 3 would be returned so that it could
1176 * be passed into the next call to this same function.
1178 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1179 VLC *table, int coeff_index,
1189 int num_coeffs = s->num_coded_frags[plane][coeff_index];
1190 int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
1192 /* local references to structure members to avoid repeated dereferences */
1193 int *coded_fragment_list = s->coded_fragment_list[plane];
1194 Vp3Fragment *all_fragments = s->all_fragments;
1195 VLC_TYPE(*vlc_table)[2] = table->table;
1197 if (num_coeffs < 0) {
1198 av_log(s->avctx, AV_LOG_ERROR,
1199 "Invalid number of coefficients at level %d\n", coeff_index);
1200 return AVERROR_INVALIDDATA;
1203 if (eob_run > num_coeffs) {
1205 blocks_ended = num_coeffs;
1206 eob_run -= num_coeffs;
1209 blocks_ended = eob_run;
1213 // insert fake EOB token to cover the split between planes or zzi
1215 dct_tokens[j++] = blocks_ended << 2;
1217 while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1218 /* decode a VLC into a token */
1219 token = get_vlc2(gb, vlc_table, 11, 3);
1220 /* use the token to get a zero run, a coefficient, and an eob run */
1221 if ((unsigned) token <= 6U) {
1222 eob_run = get_eob_run(gb, token);
1226 // record only the number of blocks ended in this plane,
1227 // any spill will be recorded in the next plane.
1228 if (eob_run > num_coeffs - coeff_i) {
1229 dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1230 blocks_ended += num_coeffs - coeff_i;
1231 eob_run -= num_coeffs - coeff_i;
1232 coeff_i = num_coeffs;
1234 dct_tokens[j++] = TOKEN_EOB(eob_run);
1235 blocks_ended += eob_run;
1239 } else if (token >= 0) {
1240 zero_run = get_coeff(gb, token, &coeff);
1243 dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1245 // Save DC into the fragment structure. DC prediction is
1246 // done in raster order, so the actual DC can't be in with
1247 // other tokens. We still need the token in dct_tokens[]
1248 // however, or else the structure collapses on itself.
1250 all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1252 dct_tokens[j++] = TOKEN_COEFF(coeff);
1255 if (coeff_index + zero_run > 64) {
1256 av_log(s->avctx, AV_LOG_DEBUG,
1257 "Invalid zero run of %d with %d coeffs left\n",
1258 zero_run, 64 - coeff_index);
1259 zero_run = 64 - coeff_index;
1262 // zero runs code multiple coefficients,
1263 // so don't try to decode coeffs for those higher levels
1264 for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1265 s->num_coded_frags[plane][i]--;
1268 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1273 if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1274 av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1276 // decrement the number of blocks that have higher coefficients for each
1277 // EOB run at this level
1279 for (i = coeff_index + 1; i < 64; i++)
1280 s->num_coded_frags[plane][i] -= blocks_ended;
1282 // setup the next buffer
1284 s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1285 else if (coeff_index < 63)
1286 s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1291 static void reverse_dc_prediction(Vp3DecodeContext *s,
1294 int fragment_height);
1296 * This function unpacks all of the DCT coefficient data from the
1299 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1306 int residual_eob_run = 0;
1310 s->dct_tokens[0][0] = s->dct_tokens_base;
1312 if (get_bits_left(gb) < 16)
1313 return AVERROR_INVALIDDATA;
1315 /* fetch the DC table indexes */
1316 dc_y_table = get_bits(gb, 4);
1317 dc_c_table = get_bits(gb, 4);
1319 /* unpack the Y plane DC coefficients */
1320 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_y_table], 0,
1321 0, residual_eob_run);
1322 if (residual_eob_run < 0)
1323 return residual_eob_run;
1324 if (get_bits_left(gb) < 8)
1325 return AVERROR_INVALIDDATA;
1327 /* reverse prediction of the Y-plane DC coefficients */
1328 reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1330 /* unpack the C plane DC coefficients */
1331 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1332 1, residual_eob_run);
1333 if (residual_eob_run < 0)
1334 return residual_eob_run;
1335 residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1336 2, residual_eob_run);
1337 if (residual_eob_run < 0)
1338 return residual_eob_run;
1340 /* reverse prediction of the C-plane DC coefficients */
1341 if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1342 reverse_dc_prediction(s, s->fragment_start[1],
1343 s->fragment_width[1], s->fragment_height[1]);
1344 reverse_dc_prediction(s, s->fragment_start[2],
1345 s->fragment_width[1], s->fragment_height[1]);
1348 if (get_bits_left(gb) < 8)
1349 return AVERROR_INVALIDDATA;
1350 /* fetch the AC table indexes */
1351 ac_y_table = get_bits(gb, 4);
1352 ac_c_table = get_bits(gb, 4);
1354 /* build tables of AC VLC tables */
1355 for (i = 1; i <= 5; i++) {
1356 /* AC VLC table group 1 */
1357 y_tables[i] = &s->coeff_vlc[ac_y_table + 16];
1358 c_tables[i] = &s->coeff_vlc[ac_c_table + 16];
1360 for (i = 6; i <= 14; i++) {
1361 /* AC VLC table group 2 */
1362 y_tables[i] = &s->coeff_vlc[ac_y_table + 32];
1363 c_tables[i] = &s->coeff_vlc[ac_c_table + 32];
1365 for (i = 15; i <= 27; i++) {
1366 /* AC VLC table group 3 */
1367 y_tables[i] = &s->coeff_vlc[ac_y_table + 48];
1368 c_tables[i] = &s->coeff_vlc[ac_c_table + 48];
1370 for (i = 28; i <= 63; i++) {
1371 /* AC VLC table group 4 */
1372 y_tables[i] = &s->coeff_vlc[ac_y_table + 64];
1373 c_tables[i] = &s->coeff_vlc[ac_c_table + 64];
1376 /* decode all AC coefficients */
1377 for (i = 1; i <= 63; i++) {
1378 residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1379 0, residual_eob_run);
1380 if (residual_eob_run < 0)
1381 return residual_eob_run;
1383 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1384 1, residual_eob_run);
1385 if (residual_eob_run < 0)
1386 return residual_eob_run;
1387 residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1388 2, residual_eob_run);
1389 if (residual_eob_run < 0)
1390 return residual_eob_run;
1396 #if CONFIG_VP4_DECODER
1398 * eob_tracker[] is instead of TOKEN_EOB(value)
1399 * a dummy TOKEN_EOB(0) value is used to make vp3_dequant work
1401 * @return < 0 on error
1403 static int vp4_unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1404 VLC *vlc_tables[64],
1405 int plane, int eob_tracker[64], int fragment)
1413 while (!eob_tracker[coeff_i]) {
1414 if (get_bits_left(gb) < 1)
1415 return AVERROR_INVALIDDATA;
1417 token = get_vlc2(gb, vlc_tables[coeff_i]->table, 11, 3);
1419 /* use the token to get a zero run, a coefficient, and an eob run */
1420 if ((unsigned) token <= 6U) {
1421 eob_run = get_eob_run(gb, token);
1422 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1423 eob_tracker[coeff_i] = eob_run - 1;
1425 } else if (token >= 0) {
1426 zero_run = get_coeff(gb, token, &coeff);
1429 if (coeff_i + zero_run > 64) {
1430 av_log(s->avctx, AV_LOG_DEBUG,
1431 "Invalid zero run of %d with %d coeffs left\n",
1432 zero_run, 64 - coeff_i);
1433 zero_run = 64 - coeff_i;
1435 *s->dct_tokens[plane][coeff_i]++ = TOKEN_ZERO_RUN(coeff, zero_run);
1436 coeff_i += zero_run;
1439 s->all_fragments[fragment].dc = coeff;
1441 *s->dct_tokens[plane][coeff_i]++ = TOKEN_COEFF(coeff);
1444 if (coeff_i >= 64) /* > 64 occurs when there is a zero_run overflow */
1445 return 0; /* stop */
1447 av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1451 *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1452 eob_tracker[coeff_i]--;
1456 static void vp4_dc_predictor_reset(VP4Predictor *p)
1459 p->type = VP4_DC_UNDEFINED;
1462 static void vp4_dc_pred_before(const Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1466 for (i = 0; i < 4; i++)
1467 dc_pred[0][i + 1] = s->dc_pred_row[sb_x * 4 + i];
1469 for (j = 1; j < 5; j++)
1470 for (i = 0; i < 4; i++)
1471 vp4_dc_predictor_reset(&dc_pred[j][i + 1]);
1474 static void vp4_dc_pred_after(Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1478 for (i = 0; i < 4; i++)
1479 s->dc_pred_row[sb_x * 4 + i] = dc_pred[4][i + 1];
1481 for (i = 1; i < 5; i++)
1482 dc_pred[i][0] = dc_pred[i][4];
1485 /* note: dc_pred points to the current block */
1486 static int vp4_dc_pred(const Vp3DecodeContext *s, const VP4Predictor * dc_pred, const int * last_dc, int type, int plane)
1491 if (dc_pred[-6].type == type) {
1492 dc += dc_pred[-6].dc;
1496 if (dc_pred[6].type == type) {
1497 dc += dc_pred[6].dc;
1501 if (count != 2 && dc_pred[-1].type == type) {
1502 dc += dc_pred[-1].dc;
1506 if (count != 2 && dc_pred[1].type == type) {
1507 dc += dc_pred[1].dc;
1511 /* using division instead of shift to correctly handle negative values */
1512 return count == 2 ? dc / 2 : last_dc[type];
1515 static void vp4_set_tokens_base(Vp3DecodeContext *s)
1518 int16_t *base = s->dct_tokens_base;
1519 for (plane = 0; plane < 3; plane++) {
1520 for (i = 0; i < 64; i++) {
1521 s->dct_tokens[plane][i] = base;
1522 base += s->fragment_width[!!plane] * s->fragment_height[!!plane];
1527 static int vp4_unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1535 int plane, sb_y, sb_x;
1536 int eob_tracker[64];
1537 VP4Predictor dc_pred[6][6];
1538 int last_dc[NB_VP4_DC_TYPES];
1540 if (get_bits_left(gb) < 16)
1541 return AVERROR_INVALIDDATA;
1543 /* fetch the DC table indexes */
1544 dc_y_table = get_bits(gb, 4);
1545 dc_c_table = get_bits(gb, 4);
1547 ac_y_table = get_bits(gb, 4);
1548 ac_c_table = get_bits(gb, 4);
1550 /* build tables of DC/AC VLC tables */
1552 /* DC table group */
1553 tables[0][0] = &s->coeff_vlc[dc_y_table];
1554 tables[1][0] = &s->coeff_vlc[dc_c_table];
1555 for (i = 1; i <= 5; i++) {
1556 /* AC VLC table group 1 */
1557 tables[0][i] = &s->coeff_vlc[ac_y_table + 16];
1558 tables[1][i] = &s->coeff_vlc[ac_c_table + 16];
1560 for (i = 6; i <= 14; i++) {
1561 /* AC VLC table group 2 */
1562 tables[0][i] = &s->coeff_vlc[ac_y_table + 32];
1563 tables[1][i] = &s->coeff_vlc[ac_c_table + 32];
1565 for (i = 15; i <= 27; i++) {
1566 /* AC VLC table group 3 */
1567 tables[0][i] = &s->coeff_vlc[ac_y_table + 48];
1568 tables[1][i] = &s->coeff_vlc[ac_c_table + 48];
1570 for (i = 28; i <= 63; i++) {
1571 /* AC VLC table group 4 */
1572 tables[0][i] = &s->coeff_vlc[ac_y_table + 64];
1573 tables[1][i] = &s->coeff_vlc[ac_c_table + 64];
1576 vp4_set_tokens_base(s);
1578 memset(last_dc, 0, sizeof(last_dc));
1580 for (plane = 0; plane < ((s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 1 : 3); plane++) {
1581 memset(eob_tracker, 0, sizeof(eob_tracker));
1583 /* initialise dc prediction */
1584 for (i = 0; i < s->fragment_width[!!plane]; i++)
1585 vp4_dc_predictor_reset(&s->dc_pred_row[i]);
1587 for (j = 0; j < 6; j++)
1588 for (i = 0; i < 6; i++)
1589 vp4_dc_predictor_reset(&dc_pred[j][i]);
1591 for (sb_y = 0; sb_y * 4 < s->fragment_height[!!plane]; sb_y++) {
1592 for (sb_x = 0; sb_x *4 < s->fragment_width[!!plane]; sb_x++) {
1593 vp4_dc_pred_before(s, dc_pred, sb_x);
1594 for (j = 0; j < 16; j++) {
1595 int hx = hilbert_offset[j][0];
1596 int hy = hilbert_offset[j][1];
1597 int x = 4 * sb_x + hx;
1598 int y = 4 * sb_y + hy;
1599 VP4Predictor *this_dc_pred = &dc_pred[hy + 1][hx + 1];
1600 int fragment, dc_block_type;
1602 if (x >= s->fragment_width[!!plane] || y >= s->fragment_height[!!plane])
1605 fragment = s->fragment_start[plane] + y * s->fragment_width[!!plane] + x;
1607 if (s->all_fragments[fragment].coding_method == MODE_COPY)
1610 if (vp4_unpack_vlcs(s, gb, tables[!!plane], plane, eob_tracker, fragment) < 0)
1613 dc_block_type = vp4_pred_block_type_map[s->all_fragments[fragment].coding_method];
1615 s->all_fragments[fragment].dc +=
1616 vp4_dc_pred(s, this_dc_pred, last_dc, dc_block_type, plane);
1618 this_dc_pred->type = dc_block_type,
1619 this_dc_pred->dc = last_dc[dc_block_type] = s->all_fragments[fragment].dc;
1621 vp4_dc_pred_after(s, dc_pred, sb_x);
1626 vp4_set_tokens_base(s);
1633 * This function reverses the DC prediction for each coded fragment in
1634 * the frame. Much of this function is adapted directly from the original
1637 #define COMPATIBLE_FRAME(x) \
1638 (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1639 #define DC_COEFF(u) s->all_fragments[u].dc
1641 static void reverse_dc_prediction(Vp3DecodeContext *s,
1644 int fragment_height)
1652 int i = first_fragment;
1656 /* DC values for the left, up-left, up, and up-right fragments */
1657 int vl, vul, vu, vur;
1659 /* indexes for the left, up-left, up, and up-right fragments */
1663 * The 6 fields mean:
1664 * 0: up-left multiplier
1666 * 2: up-right multiplier
1667 * 3: left multiplier
1669 static const int predictor_transform[16][4] = {
1671 { 0, 0, 0, 128 }, // PL
1672 { 0, 0, 128, 0 }, // PUR
1673 { 0, 0, 53, 75 }, // PUR|PL
1674 { 0, 128, 0, 0 }, // PU
1675 { 0, 64, 0, 64 }, // PU |PL
1676 { 0, 128, 0, 0 }, // PU |PUR
1677 { 0, 0, 53, 75 }, // PU |PUR|PL
1678 { 128, 0, 0, 0 }, // PUL
1679 { 0, 0, 0, 128 }, // PUL|PL
1680 { 64, 0, 64, 0 }, // PUL|PUR
1681 { 0, 0, 53, 75 }, // PUL|PUR|PL
1682 { 0, 128, 0, 0 }, // PUL|PU
1683 { -104, 116, 0, 116 }, // PUL|PU |PL
1684 { 24, 80, 24, 0 }, // PUL|PU |PUR
1685 { -104, 116, 0, 116 } // PUL|PU |PUR|PL
1688 /* This table shows which types of blocks can use other blocks for
1689 * prediction. For example, INTRA is the only mode in this table to
1690 * have a frame number of 0. That means INTRA blocks can only predict
1691 * from other INTRA blocks. There are 2 golden frame coding types;
1692 * blocks encoding in these modes can only predict from other blocks
1693 * that were encoded with these 1 of these 2 modes. */
1694 static const unsigned char compatible_frame[9] = {
1695 1, /* MODE_INTER_NO_MV */
1697 1, /* MODE_INTER_PLUS_MV */
1698 1, /* MODE_INTER_LAST_MV */
1699 1, /* MODE_INTER_PRIOR_MV */
1700 2, /* MODE_USING_GOLDEN */
1701 2, /* MODE_GOLDEN_MV */
1702 1, /* MODE_INTER_FOUR_MV */
1705 int current_frame_type;
1707 /* there is a last DC predictor for each of the 3 frame types */
1720 /* for each fragment row... */
1721 for (y = 0; y < fragment_height; y++) {
1722 /* for each fragment in a row... */
1723 for (x = 0; x < fragment_width; x++, i++) {
1725 /* reverse prediction if this block was coded */
1726 if (s->all_fragments[i].coding_method != MODE_COPY) {
1727 current_frame_type =
1728 compatible_frame[s->all_fragments[i].coding_method];
1734 if (COMPATIBLE_FRAME(l))
1738 u = i - fragment_width;
1740 if (COMPATIBLE_FRAME(u))
1743 ul = i - fragment_width - 1;
1745 if (COMPATIBLE_FRAME(ul))
1748 if (x + 1 < fragment_width) {
1749 ur = i - fragment_width + 1;
1751 if (COMPATIBLE_FRAME(ur))
1756 if (transform == 0) {
1757 /* if there were no fragments to predict from, use last
1759 predicted_dc = last_dc[current_frame_type];
1761 /* apply the appropriate predictor transform */
1763 (predictor_transform[transform][0] * vul) +
1764 (predictor_transform[transform][1] * vu) +
1765 (predictor_transform[transform][2] * vur) +
1766 (predictor_transform[transform][3] * vl);
1768 predicted_dc /= 128;
1770 /* check for outranging on the [ul u l] and
1771 * [ul u ur l] predictors */
1772 if ((transform == 15) || (transform == 13)) {
1773 if (FFABS(predicted_dc - vu) > 128)
1775 else if (FFABS(predicted_dc - vl) > 128)
1777 else if (FFABS(predicted_dc - vul) > 128)
1782 /* at long last, apply the predictor */
1783 DC_COEFF(i) += predicted_dc;
1785 last_dc[current_frame_type] = DC_COEFF(i);
1791 static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1792 int ystart, int yend)
1795 int *bounding_values = s->bounding_values_array + 127;
1797 int width = s->fragment_width[!!plane];
1798 int height = s->fragment_height[!!plane];
1799 int fragment = s->fragment_start[plane] + ystart * width;
1800 ptrdiff_t stride = s->current_frame.f->linesize[plane];
1801 uint8_t *plane_data = s->current_frame.f->data[plane];
1802 if (!s->flipped_image)
1804 plane_data += s->data_offset[plane] + 8 * ystart * stride;
1806 for (y = ystart; y < yend; y++) {
1807 for (x = 0; x < width; x++) {
1808 /* This code basically just deblocks on the edges of coded blocks.
1809 * However, it has to be much more complicated because of the
1810 * brain damaged deblock ordering used in VP3/Theora. Order matters
1811 * because some pixels get filtered twice. */
1812 if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1813 /* do not perform left edge filter for left columns frags */
1815 s->vp3dsp.h_loop_filter(
1817 stride, bounding_values);
1820 /* do not perform top edge filter for top row fragments */
1822 s->vp3dsp.v_loop_filter(
1824 stride, bounding_values);
1827 /* do not perform right edge filter for right column
1828 * fragments or if right fragment neighbor is also coded
1829 * in this frame (it will be filtered in next iteration) */
1830 if ((x < width - 1) &&
1831 (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1832 s->vp3dsp.h_loop_filter(
1833 plane_data + 8 * x + 8,
1834 stride, bounding_values);
1837 /* do not perform bottom edge filter for bottom row
1838 * fragments or if bottom fragment neighbor is also coded
1839 * in this frame (it will be filtered in the next row) */
1840 if ((y < height - 1) &&
1841 (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1842 s->vp3dsp.v_loop_filter(
1843 plane_data + 8 * x + 8 * stride,
1844 stride, bounding_values);
1850 plane_data += 8 * stride;
1855 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1856 * for the next block in coding order
1858 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1859 int plane, int inter, int16_t block[64])
1861 int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1862 uint8_t *perm = s->idct_scantable;
1866 int token = *s->dct_tokens[plane][i];
1867 switch (token & 3) {
1869 if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1870 s->dct_tokens[plane][i]++;
1872 *s->dct_tokens[plane][i] = token & ~3;
1875 s->dct_tokens[plane][i]++;
1876 i += (token >> 2) & 0x7f;
1878 av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1881 block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1885 block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1886 s->dct_tokens[plane][i++]++;
1888 default: // shouldn't happen
1892 // return value is expected to be a valid level
1895 // the actual DC+prediction is in the fragment structure
1896 block[0] = frag->dc * s->qmat[0][inter][plane][0];
1901 * called when all pixels up to row y are complete
1903 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1906 int offset[AV_NUM_DATA_POINTERS];
1908 if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1909 int y_flipped = s->flipped_image ? s->height - y : y;
1911 /* At the end of the frame, report INT_MAX instead of the height of
1912 * the frame. This makes the other threads' ff_thread_await_progress()
1913 * calls cheaper, because they don't have to clip their values. */
1914 ff_thread_report_progress(&s->current_frame,
1915 y_flipped == s->height ? INT_MAX
1920 if (!s->avctx->draw_horiz_band)
1923 h = y - s->last_slice_end;
1924 s->last_slice_end = y;
1927 if (!s->flipped_image)
1928 y = s->height - y - h;
1930 cy = y >> s->chroma_y_shift;
1931 offset[0] = s->current_frame.f->linesize[0] * y;
1932 offset[1] = s->current_frame.f->linesize[1] * cy;
1933 offset[2] = s->current_frame.f->linesize[2] * cy;
1934 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1938 s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1942 * Wait for the reference frame of the current fragment.
1943 * The progress value is in luma pixel rows.
1945 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1946 int motion_y, int y)
1948 ThreadFrame *ref_frame;
1950 int border = motion_y & 1;
1952 if (fragment->coding_method == MODE_USING_GOLDEN ||
1953 fragment->coding_method == MODE_GOLDEN_MV)
1954 ref_frame = &s->golden_frame;
1956 ref_frame = &s->last_frame;
1958 ref_row = y + (motion_y >> 1);
1959 ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1961 ff_thread_await_progress(ref_frame, ref_row, 0);
1964 #if CONFIG_VP4_DECODER
1966 * @return non-zero if temp (edge_emu_buffer) was populated
1968 static int vp4_mc_loop_filter(Vp3DecodeContext *s, int plane, int motion_x, int motion_y, int bx, int by,
1969 uint8_t * motion_source, int stride, int src_x, int src_y, uint8_t *temp)
1971 int motion_shift = plane ? 4 : 2;
1972 int subpel_mask = plane ? 3 : 1;
1973 int *bounding_values = s->bounding_values_array + 127;
1978 int x_subpel, y_subpel;
1979 int x_offset, y_offset;
1981 int block_width = plane ? 8 : 16;
1982 int plane_width = s->width >> (plane && s->chroma_x_shift);
1983 int plane_height = s->height >> (plane && s->chroma_y_shift);
1985 #define loop_stride 12
1986 uint8_t loop[12 * loop_stride];
1988 /* using division instead of shift to correctly handle negative values */
1989 x = 8 * bx + motion_x / motion_shift;
1990 y = 8 * by + motion_y / motion_shift;
1992 x_subpel = motion_x & subpel_mask;
1993 y_subpel = motion_y & subpel_mask;
1995 if (x_subpel || y_subpel) {
2000 x = FFMIN(x, x + FFSIGN(motion_x));
2003 y = FFMIN(y, y + FFSIGN(motion_y));
2005 x2 = x + block_width;
2006 y2 = y + block_width;
2008 if (x2 < 0 || x2 >= plane_width || y2 < 0 || y2 >= plane_height)
2011 x_offset = (-(x + 2) & 7) + 2;
2012 y_offset = (-(y + 2) & 7) + 2;
2014 if (x_offset > 8 + x_subpel && y_offset > 8 + y_subpel)
2017 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2018 loop_stride, stride,
2019 12, 12, src_x - 1, src_y - 1,
2023 if (x_offset <= 8 + x_subpel)
2024 ff_vp3dsp_h_loop_filter_12(loop + x_offset, loop_stride, bounding_values);
2026 if (y_offset <= 8 + y_subpel)
2027 ff_vp3dsp_v_loop_filter_12(loop + y_offset*loop_stride, loop_stride, bounding_values);
2034 if (!x_offset && !y_offset)
2037 s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2038 loop_stride, stride,
2039 12, 12, src_x - 1, src_y - 1,
2043 #define safe_loop_filter(name, ptr, stride, bounding_values) \
2044 if ((uintptr_t)(ptr) & 7) \
2045 s->vp3dsp.name##_unaligned(ptr, stride, bounding_values); \
2047 s->vp3dsp.name(ptr, stride, bounding_values);
2050 safe_loop_filter(h_loop_filter, loop + loop_stride + x_offset + 1, loop_stride, bounding_values);
2053 safe_loop_filter(v_loop_filter, loop + (y_offset + 1)*loop_stride + 1, loop_stride, bounding_values);
2056 for (i = 0; i < 9; i++)
2057 memcpy(temp + i*stride, loop + (i + 1) * loop_stride + 1, 9);
2064 * Perform the final rendering for a particular slice of data.
2065 * The slice number ranges from 0..(c_superblock_height - 1).
2067 static void render_slice(Vp3DecodeContext *s, int slice)
2069 int x, y, i, j, fragment;
2070 int16_t *block = s->block;
2071 int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
2072 int motion_halfpel_index;
2073 uint8_t *motion_source;
2074 int plane, first_pixel;
2076 if (slice >= s->c_superblock_height)
2079 for (plane = 0; plane < 3; plane++) {
2080 uint8_t *output_plane = s->current_frame.f->data[plane] +
2081 s->data_offset[plane];
2082 uint8_t *last_plane = s->last_frame.f->data[plane] +
2083 s->data_offset[plane];
2084 uint8_t *golden_plane = s->golden_frame.f->data[plane] +
2085 s->data_offset[plane];
2086 ptrdiff_t stride = s->current_frame.f->linesize[plane];
2087 int plane_width = s->width >> (plane && s->chroma_x_shift);
2088 int plane_height = s->height >> (plane && s->chroma_y_shift);
2089 int8_t(*motion_val)[2] = s->motion_val[!!plane];
2091 int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
2092 int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
2093 int slice_width = plane ? s->c_superblock_width
2094 : s->y_superblock_width;
2096 int fragment_width = s->fragment_width[!!plane];
2097 int fragment_height = s->fragment_height[!!plane];
2098 int fragment_start = s->fragment_start[plane];
2100 int do_await = !plane && HAVE_THREADS &&
2101 (s->avctx->active_thread_type & FF_THREAD_FRAME);
2103 if (!s->flipped_image)
2105 if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
2108 /* for each superblock row in the slice (both of them)... */
2109 for (; sb_y < slice_height; sb_y++) {
2110 /* for each superblock in a row... */
2111 for (sb_x = 0; sb_x < slice_width; sb_x++) {
2112 /* for each block in a superblock... */
2113 for (j = 0; j < 16; j++) {
2114 x = 4 * sb_x + hilbert_offset[j][0];
2115 y = 4 * sb_y + hilbert_offset[j][1];
2116 fragment = y * fragment_width + x;
2118 i = fragment_start + fragment;
2121 if (x >= fragment_width || y >= fragment_height)
2124 first_pixel = 8 * y * stride + 8 * x;
2127 s->all_fragments[i].coding_method != MODE_INTRA)
2128 await_reference_row(s, &s->all_fragments[i],
2129 motion_val[fragment][1],
2130 (16 * y) >> s->chroma_y_shift);
2132 /* transform if this block was coded */
2133 if (s->all_fragments[i].coding_method != MODE_COPY) {
2134 if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2135 (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
2136 motion_source = golden_plane;
2138 motion_source = last_plane;
2140 motion_source += first_pixel;
2141 motion_halfpel_index = 0;
2143 /* sort out the motion vector if this fragment is coded
2144 * using a motion vector method */
2145 if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
2146 (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
2148 int standard_mc = 1;
2149 motion_x = motion_val[fragment][0];
2150 motion_y = motion_val[fragment][1];
2151 #if CONFIG_VP4_DECODER
2152 if (plane && s->version >= 2) {
2153 motion_x = (motion_x >> 1) | (motion_x & 1);
2154 motion_y = (motion_y >> 1) | (motion_y & 1);
2158 src_x = (motion_x >> 1) + 8 * x;
2159 src_y = (motion_y >> 1) + 8 * y;
2161 motion_halfpel_index = motion_x & 0x01;
2162 motion_source += (motion_x >> 1);
2164 motion_halfpel_index |= (motion_y & 0x01) << 1;
2165 motion_source += ((motion_y >> 1) * stride);
2167 #if CONFIG_VP4_DECODER
2168 if (s->version >= 2) {
2169 uint8_t *temp = s->edge_emu_buffer;
2172 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)) {
2173 motion_source = temp;
2179 if (standard_mc && (
2180 src_x < 0 || src_y < 0 ||
2181 src_x + 9 >= plane_width ||
2182 src_y + 9 >= plane_height)) {
2183 uint8_t *temp = s->edge_emu_buffer;
2187 s->vdsp.emulated_edge_mc(temp, motion_source,
2192 motion_source = temp;
2196 /* first, take care of copying a block from either the
2197 * previous or the golden frame */
2198 if (s->all_fragments[i].coding_method != MODE_INTRA) {
2199 /* Note, it is possible to implement all MC cases
2200 * with put_no_rnd_pixels_l2 which would look more
2201 * like the VP3 source but this would be slower as
2202 * put_no_rnd_pixels_tab is better optimized */
2203 if (motion_halfpel_index != 3) {
2204 s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
2205 output_plane + first_pixel,
2206 motion_source, stride, 8);
2208 /* d is 0 if motion_x and _y have the same sign,
2210 int d = (motion_x ^ motion_y) >> 31;
2211 s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
2213 motion_source + stride + 1 + d,
2218 /* invert DCT and place (or add) in final output */
2220 if (s->all_fragments[i].coding_method == MODE_INTRA) {
2221 vp3_dequant(s, s->all_fragments + i,
2223 s->vp3dsp.idct_put(output_plane + first_pixel,
2227 if (vp3_dequant(s, s->all_fragments + i,
2229 s->vp3dsp.idct_add(output_plane + first_pixel,
2233 s->vp3dsp.idct_dc_add(output_plane + first_pixel,
2238 /* copy directly from the previous frame */
2239 s->hdsp.put_pixels_tab[1][0](
2240 output_plane + first_pixel,
2241 last_plane + first_pixel,
2247 // Filter up to the last row in the superblock row
2248 if (s->version < 2 && !s->skip_loop_filter)
2249 apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
2250 FFMIN(4 * sb_y + 3, fragment_height - 1));
2254 /* this looks like a good place for slice dispatch... */
2256 * if (slice == s->macroblock_height - 1)
2257 * dispatch (both last slice & 2nd-to-last slice);
2258 * else if (slice > 0)
2259 * dispatch (slice - 1);
2262 vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
2266 /// Allocate tables for per-frame data in Vp3DecodeContext
2267 static av_cold int allocate_tables(AVCodecContext *avctx)
2269 Vp3DecodeContext *s = avctx->priv_data;
2270 int y_fragment_count, c_fragment_count;
2274 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2275 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2277 /* superblock_coding is used by unpack_superblocks (VP3/Theora) and vp4_unpack_macroblocks (VP4) */
2278 s->superblock_coding = av_mallocz(FFMAX(s->superblock_count, s->yuv_macroblock_count));
2279 s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
2281 s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2282 s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2283 memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
2285 s->dct_tokens_base = av_mallocz_array(s->fragment_count,
2286 64 * sizeof(*s->dct_tokens_base));
2287 s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
2288 s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
2290 /* work out the block mapping tables */
2291 s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
2292 s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
2294 s->dc_pred_row = av_malloc_array(s->y_superblock_width * 4, sizeof(*s->dc_pred_row));
2296 if (!s->superblock_coding || !s->all_fragments ||
2297 !s->dct_tokens_base || !s->kf_coded_fragment_list ||
2298 !s->nkf_coded_fragment_list ||
2299 !s->superblock_fragments || !s->macroblock_coding ||
2301 !s->motion_val[0] || !s->motion_val[1]) {
2305 init_block_mapping(s);
2310 static av_cold int init_frames(Vp3DecodeContext *s)
2312 s->current_frame.f = av_frame_alloc();
2313 s->last_frame.f = av_frame_alloc();
2314 s->golden_frame.f = av_frame_alloc();
2316 if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f)
2317 return AVERROR(ENOMEM);
2322 static av_cold int vp3_decode_init(AVCodecContext *avctx)
2324 Vp3DecodeContext *s = avctx->priv_data;
2325 int i, inter, plane, ret;
2328 int y_fragment_count, c_fragment_count;
2329 #if CONFIG_VP4_DECODER
2333 ret = init_frames(s);
2337 if (avctx->codec_tag == MKTAG('V', 'P', '4', '0'))
2339 else if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
2345 s->width = FFALIGN(avctx->coded_width, 16);
2346 s->height = FFALIGN(avctx->coded_height, 16);
2347 if (avctx->codec_id != AV_CODEC_ID_THEORA)
2348 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2349 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
2350 ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
2351 ff_videodsp_init(&s->vdsp, 8);
2352 ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
2354 for (i = 0; i < 64; i++) {
2355 #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
2356 s->idct_permutation[i] = TRANSPOSE(i);
2357 s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
2361 /* initialize to an impossible value which will force a recalculation
2362 * in the first frame decode */
2363 for (i = 0; i < 3; i++)
2366 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
2370 s->y_superblock_width = (s->width + 31) / 32;
2371 s->y_superblock_height = (s->height + 31) / 32;
2372 s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
2374 /* work out the dimensions for the C planes */
2375 c_width = s->width >> s->chroma_x_shift;
2376 c_height = s->height >> s->chroma_y_shift;
2377 s->c_superblock_width = (c_width + 31) / 32;
2378 s->c_superblock_height = (c_height + 31) / 32;
2379 s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
2381 s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
2382 s->u_superblock_start = s->y_superblock_count;
2383 s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
2385 s->macroblock_width = (s->width + 15) / 16;
2386 s->macroblock_height = (s->height + 15) / 16;
2387 s->macroblock_count = s->macroblock_width * s->macroblock_height;
2388 s->c_macroblock_width = (c_width + 15) / 16;
2389 s->c_macroblock_height = (c_height + 15) / 16;
2390 s->c_macroblock_count = s->c_macroblock_width * s->c_macroblock_height;
2391 s->yuv_macroblock_count = s->macroblock_count + 2 * s->c_macroblock_count;
2393 s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
2394 s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
2395 s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
2396 s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
2398 /* fragment count covers all 8x8 blocks for all 3 planes */
2399 y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2400 c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2401 s->fragment_count = y_fragment_count + 2 * c_fragment_count;
2402 s->fragment_start[1] = y_fragment_count;
2403 s->fragment_start[2] = y_fragment_count + c_fragment_count;
2405 if (!s->theora_tables) {
2406 for (i = 0; i < 64; i++) {
2407 s->coded_dc_scale_factor[0][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_y_dc_scale_factor[i];
2408 s->coded_dc_scale_factor[1][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_uv_dc_scale_factor[i];
2409 s->coded_ac_scale_factor[i] = s->version < 2 ? vp31_ac_scale_factor[i] : vp4_ac_scale_factor[i];
2410 s->base_matrix[0][i] = s->version < 2 ? vp31_intra_y_dequant[i] : vp4_generic_dequant[i];
2411 s->base_matrix[1][i] = s->version < 2 ? vp31_intra_c_dequant[i] : vp4_generic_dequant[i];
2412 s->base_matrix[2][i] = s->version < 2 ? vp31_inter_dequant[i] : vp4_generic_dequant[i];
2413 s->filter_limit_values[i] = s->version < 2 ? vp31_filter_limit_values[i] : vp4_filter_limit_values[i];
2416 for (inter = 0; inter < 2; inter++) {
2417 for (plane = 0; plane < 3; plane++) {
2418 s->qr_count[inter][plane] = 1;
2419 s->qr_size[inter][plane][0] = 63;
2420 s->qr_base[inter][plane][0] =
2421 s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
2425 /* init VLC tables */
2426 if (s->version < 2) {
2427 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2428 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, 32,
2429 &vp3_bias[i][0][1], 2,
2430 &vp3_bias[i][0][0], 2, 1,
2435 #if CONFIG_VP4_DECODER
2436 } else { /* version >= 2 */
2437 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2438 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, 32,
2439 &vp4_bias[i][0][1], 2,
2440 &vp4_bias[i][0][0], 2, 1,
2448 for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2449 const HuffTable *tab = &s->huffman_table[i];
2451 ret = ff_init_vlc_from_lengths(&s->coeff_vlc[i], 11, tab->nb_entries,
2452 &tab->entries[0].len, sizeof(*tab->entries),
2453 &tab->entries[0].sym, sizeof(*tab->entries), 1,
2460 ret = ff_init_vlc_from_lengths(&s->superblock_run_length_vlc, SUPERBLOCK_VLC_BITS, 34,
2461 superblock_run_length_vlc_lens, 1,
2462 NULL, 0, 0, 1, 0, avctx);
2466 ret = ff_init_vlc_from_lengths(&s->fragment_run_length_vlc, 5, 30,
2467 fragment_run_length_vlc_len, 1,
2468 NULL, 0, 0, 0, 0, avctx);
2472 ret = ff_init_vlc_from_lengths(&s->mode_code_vlc, 3, 8,
2473 mode_code_vlc_len, 1,
2474 NULL, 0, 0, 0, 0, avctx);
2478 ret = ff_init_vlc_from_lengths(&s->motion_vector_vlc, VP3_MV_VLC_BITS, 63,
2479 &motion_vector_vlc_table[0][1], 2,
2480 &motion_vector_vlc_table[0][0], 2, 1,
2485 #if CONFIG_VP4_DECODER
2486 for (j = 0; j < 2; j++)
2487 for (i = 0; i < 7; i++) {
2488 ret = ff_init_vlc_from_lengths(&s->vp4_mv_vlc[j][i], VP4_MV_VLC_BITS, 63,
2489 &vp4_mv_vlc[j][i][0][1], 2,
2490 &vp4_mv_vlc[j][i][0][0], 2, 1, -31,
2497 for (i = 0; i < 2; i++)
2498 if ((ret = init_vlc(&s->block_pattern_vlc[i], 3, 14,
2499 &vp4_block_pattern_vlc[i][0][1], 2, 1,
2500 &vp4_block_pattern_vlc[i][0][0], 2, 1, 0)) < 0)
2504 return allocate_tables(avctx);
2507 /// Release and shuffle frames after decode finishes
2508 static int update_frames(AVCodecContext *avctx)
2510 Vp3DecodeContext *s = avctx->priv_data;
2513 /* shuffle frames (last = current) */
2514 ff_thread_release_buffer(avctx, &s->last_frame);
2515 ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
2520 ff_thread_release_buffer(avctx, &s->golden_frame);
2521 ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
2525 ff_thread_release_buffer(avctx, &s->current_frame);
2530 static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
2532 ff_thread_release_buffer(s->avctx, dst);
2533 if (src->f->data[0])
2534 return ff_thread_ref_frame(dst, src);
2538 static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
2541 if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
2542 (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
2543 (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
2548 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
2550 Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
2551 int qps_changed = 0, i, err;
2553 if (!s1->current_frame.f->data[0] ||
2554 s->width != s1->width || s->height != s1->height) {
2561 // copy previous frame data
2562 if ((err = ref_frames(s, s1)) < 0)
2565 s->keyframe = s1->keyframe;
2567 // copy qscale data if necessary
2568 for (i = 0; i < 3; i++) {
2569 if (s->qps[i] != s1->qps[1]) {
2571 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2575 if (s->qps[0] != s1->qps[0])
2576 memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2577 sizeof(s->bounding_values_array));
2580 memcpy(s->qps, s1->qps, sizeof(s->qps));
2581 memcpy(s->last_qps, s1->last_qps, sizeof(s->last_qps));
2586 return update_frames(dst);
2590 static int vp3_decode_frame(AVCodecContext *avctx,
2591 void *data, int *got_frame,
2594 AVFrame *frame = data;
2595 const uint8_t *buf = avpkt->data;
2596 int buf_size = avpkt->size;
2597 Vp3DecodeContext *s = avctx->priv_data;
2601 if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2604 #if CONFIG_THEORA_DECODER
2605 if (s->theora && get_bits1(&gb)) {
2606 int type = get_bits(&gb, 7);
2607 skip_bits_long(&gb, 6*8); /* "theora" */
2609 if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2610 av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2611 return AVERROR_PATCHWELCOME;
2614 vp3_decode_end(avctx);
2615 ret = theora_decode_header(avctx, &gb);
2618 ret = vp3_decode_init(avctx);
2620 vp3_decode_end(avctx);
2624 } else if (type == 2) {
2625 vp3_decode_end(avctx);
2626 ret = theora_decode_tables(avctx, &gb);
2628 ret = vp3_decode_init(avctx);
2630 vp3_decode_end(avctx);
2636 av_log(avctx, AV_LOG_ERROR,
2637 "Header packet passed to frame decoder, skipping\n");
2642 s->keyframe = !get_bits1(&gb);
2643 if (!s->all_fragments) {
2644 av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2649 for (i = 0; i < 3; i++)
2650 s->last_qps[i] = s->qps[i];
2654 s->qps[s->nqps++] = get_bits(&gb, 6);
2655 } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2656 for (i = s->nqps; i < 3; i++)
2659 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2660 av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2661 s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2663 s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2664 avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2665 : AVDISCARD_NONKEY);
2667 if (s->qps[0] != s->last_qps[0])
2668 init_loop_filter(s);
2670 for (i = 0; i < s->nqps; i++)
2671 // reinit all dequantizers if the first one changed, because
2672 // the DC of the first quantizer must be used for all matrices
2673 if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2674 init_dequantizer(s, i);
2676 if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2679 s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2680 : AV_PICTURE_TYPE_P;
2681 s->current_frame.f->key_frame = s->keyframe;
2682 if ((ret = ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
2685 if (!s->edge_emu_buffer)
2686 s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2690 skip_bits(&gb, 4); /* width code */
2691 skip_bits(&gb, 4); /* height code */
2693 s->version = get_bits(&gb, 5);
2694 if (avctx->frame_number == 0)
2695 av_log(s->avctx, AV_LOG_DEBUG,
2696 "VP version: %d\n", s->version);
2699 if (s->version || s->theora) {
2701 av_log(s->avctx, AV_LOG_ERROR,
2702 "Warning, unsupported keyframe coding type?!\n");
2703 skip_bits(&gb, 2); /* reserved? */
2705 #if CONFIG_VP4_DECODER
2706 if (s->version >= 2) {
2707 int mb_height, mb_width;
2708 int mb_width_mul, mb_width_div, mb_height_mul, mb_height_div;
2710 mb_height = get_bits(&gb, 8);
2711 mb_width = get_bits(&gb, 8);
2712 if (mb_height != s->macroblock_height ||
2713 mb_width != s->macroblock_width)
2714 avpriv_request_sample(s->avctx, "macroblock dimension mismatch");
2716 mb_width_mul = get_bits(&gb, 5);
2717 mb_width_div = get_bits(&gb, 3);
2718 mb_height_mul = get_bits(&gb, 5);
2719 mb_height_div = get_bits(&gb, 3);
2720 if (mb_width_mul != 1 || mb_width_div != 1 || mb_height_mul != 1 || mb_height_div != 1)
2721 avpriv_request_sample(s->avctx, "unexpected macroblock dimension multipler/divider");
2723 if (get_bits(&gb, 2))
2724 avpriv_request_sample(s->avctx, "unknown bits");
2729 if (!s->golden_frame.f->data[0]) {
2730 av_log(s->avctx, AV_LOG_WARNING,
2731 "vp3: first frame not a keyframe\n");
2733 s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2734 if ((ret = ff_thread_get_buffer(avctx, &s->golden_frame,
2735 AV_GET_BUFFER_FLAG_REF)) < 0)
2737 ff_thread_release_buffer(avctx, &s->last_frame);
2738 if ((ret = ff_thread_ref_frame(&s->last_frame,
2739 &s->golden_frame)) < 0)
2741 ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2745 memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2746 ff_thread_finish_setup(avctx);
2748 if (s->version < 2) {
2749 if ((ret = unpack_superblocks(s, &gb)) < 0) {
2750 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2753 #if CONFIG_VP4_DECODER
2755 if ((ret = vp4_unpack_macroblocks(s, &gb)) < 0) {
2756 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_macroblocks\n");
2761 if ((ret = unpack_modes(s, &gb)) < 0) {
2762 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2765 if (ret = unpack_vectors(s, &gb)) {
2766 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2769 if ((ret = unpack_block_qpis(s, &gb)) < 0) {
2770 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2774 if (s->version < 2) {
2775 if ((ret = unpack_dct_coeffs(s, &gb)) < 0) {
2776 av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2779 #if CONFIG_VP4_DECODER
2781 if ((ret = vp4_unpack_dct_coeffs(s, &gb)) < 0) {
2782 av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_dct_coeffs\n");
2788 for (i = 0; i < 3; i++) {
2789 int height = s->height >> (i && s->chroma_y_shift);
2790 if (s->flipped_image)
2791 s->data_offset[i] = 0;
2793 s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2796 s->last_slice_end = 0;
2797 for (i = 0; i < s->c_superblock_height; i++)
2800 // filter the last row
2802 for (i = 0; i < 3; i++) {
2803 int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2804 apply_loop_filter(s, i, row, row + 1);
2806 vp3_draw_horiz_band(s, s->height);
2808 /* output frame, offset as needed */
2809 if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2812 frame->crop_left = s->offset_x;
2813 frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
2814 frame->crop_top = s->offset_y;
2815 frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2819 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2820 ret = update_frames(avctx);
2828 ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2830 if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2831 av_frame_unref(s->current_frame.f);
2836 static int read_huffman_tree(HuffTable *huff, GetBitContext *gb, int length,
2837 AVCodecContext *avctx)
2839 if (get_bits1(gb)) {
2841 if (huff->nb_entries >= 32) { /* overflow */
2842 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2845 token = get_bits(gb, 5);
2846 ff_dlog(avctx, "code length %d, curr entry %d, token %d\n",
2847 length, huff->nb_entries, token);
2848 huff->entries[huff->nb_entries++] = (HuffEntry){ length, token };
2850 /* The following bound follows from the fact that nb_entries <= 32. */
2851 if (length >= 31) { /* overflow */
2852 av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2856 if (read_huffman_tree(huff, gb, length, avctx))
2858 if (read_huffman_tree(huff, gb, length, avctx))
2864 #if CONFIG_THEORA_DECODER
2865 static const enum AVPixelFormat theora_pix_fmts[4] = {
2866 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2869 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2871 Vp3DecodeContext *s = avctx->priv_data;
2872 int visible_width, visible_height, colorspace;
2873 uint8_t offset_x = 0, offset_y = 0;
2875 AVRational fps, aspect;
2877 s->theora_header = 0;
2878 s->theora = get_bits(gb, 24);
2879 av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2882 avpriv_request_sample(s->avctx, "theora 0");
2885 /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2886 * but previous versions have the image flipped relative to vp3 */
2887 if (s->theora < 0x030200) {
2888 s->flipped_image = 1;
2889 av_log(avctx, AV_LOG_DEBUG,
2890 "Old (<alpha3) Theora bitstream, flipped image\n");
2894 s->width = get_bits(gb, 16) << 4;
2896 s->height = get_bits(gb, 16) << 4;
2898 if (s->theora >= 0x030200) {
2899 visible_width = get_bits(gb, 24);
2900 visible_height = get_bits(gb, 24);
2902 offset_x = get_bits(gb, 8); /* offset x */
2903 offset_y = get_bits(gb, 8); /* offset y, from bottom */
2907 if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2908 visible_width + offset_x > s->width ||
2909 visible_height + offset_y > s->height) {
2910 av_log(avctx, AV_LOG_ERROR,
2911 "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2912 visible_width, visible_height, offset_x, offset_y,
2913 s->width, s->height);
2914 return AVERROR_INVALIDDATA;
2917 fps.num = get_bits_long(gb, 32);
2918 fps.den = get_bits_long(gb, 32);
2919 if (fps.num && fps.den) {
2920 if (fps.num < 0 || fps.den < 0) {
2921 av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2922 return AVERROR_INVALIDDATA;
2924 av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2925 fps.den, fps.num, 1 << 30);
2928 aspect.num = get_bits(gb, 24);
2929 aspect.den = get_bits(gb, 24);
2930 if (aspect.num && aspect.den) {
2931 av_reduce(&avctx->sample_aspect_ratio.num,
2932 &avctx->sample_aspect_ratio.den,
2933 aspect.num, aspect.den, 1 << 30);
2934 ff_set_sar(avctx, avctx->sample_aspect_ratio);
2937 if (s->theora < 0x030200)
2938 skip_bits(gb, 5); /* keyframe frequency force */
2939 colorspace = get_bits(gb, 8);
2940 skip_bits(gb, 24); /* bitrate */
2942 skip_bits(gb, 6); /* quality hint */
2944 if (s->theora >= 0x030200) {
2945 skip_bits(gb, 5); /* keyframe frequency force */
2946 avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2947 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2948 av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2949 return AVERROR_INVALIDDATA;
2951 skip_bits(gb, 3); /* reserved */
2953 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2955 ret = ff_set_dimensions(avctx, s->width, s->height);
2958 if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2959 avctx->width = visible_width;
2960 avctx->height = visible_height;
2961 // translate offsets from theora axis ([0,0] lower left)
2962 // to normal axis ([0,0] upper left)
2963 s->offset_x = offset_x;
2964 s->offset_y = s->height - visible_height - offset_y;
2967 if (colorspace == 1)
2968 avctx->color_primaries = AVCOL_PRI_BT470M;
2969 else if (colorspace == 2)
2970 avctx->color_primaries = AVCOL_PRI_BT470BG;
2972 if (colorspace == 1 || colorspace == 2) {
2973 avctx->colorspace = AVCOL_SPC_BT470BG;
2974 avctx->color_trc = AVCOL_TRC_BT709;
2977 s->theora_header = 1;
2981 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2983 Vp3DecodeContext *s = avctx->priv_data;
2984 int i, n, matrices, inter, plane, ret;
2986 if (!s->theora_header)
2987 return AVERROR_INVALIDDATA;
2989 if (s->theora >= 0x030200) {
2990 n = get_bits(gb, 3);
2991 /* loop filter limit values table */
2993 for (i = 0; i < 64; i++)
2994 s->filter_limit_values[i] = get_bits(gb, n);
2997 if (s->theora >= 0x030200)
2998 n = get_bits(gb, 4) + 1;
3001 /* quality threshold table */
3002 for (i = 0; i < 64; i++)
3003 s->coded_ac_scale_factor[i] = get_bits(gb, n);
3005 if (s->theora >= 0x030200)
3006 n = get_bits(gb, 4) + 1;
3009 /* dc scale factor table */
3010 for (i = 0; i < 64; i++)
3011 s->coded_dc_scale_factor[0][i] =
3012 s->coded_dc_scale_factor[1][i] = get_bits(gb, n);
3014 if (s->theora >= 0x030200)
3015 matrices = get_bits(gb, 9) + 1;
3019 if (matrices > 384) {
3020 av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
3024 for (n = 0; n < matrices; n++)
3025 for (i = 0; i < 64; i++)
3026 s->base_matrix[n][i] = get_bits(gb, 8);
3028 for (inter = 0; inter <= 1; inter++) {
3029 for (plane = 0; plane <= 2; plane++) {
3031 if (inter || plane > 0)
3032 newqr = get_bits1(gb);
3035 if (inter && get_bits1(gb)) {
3039 qtj = (3 * inter + plane - 1) / 3;
3040 plj = (plane + 2) % 3;
3042 s->qr_count[inter][plane] = s->qr_count[qtj][plj];
3043 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
3044 sizeof(s->qr_size[0][0]));
3045 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
3046 sizeof(s->qr_base[0][0]));
3052 i = get_bits(gb, av_log2(matrices - 1) + 1);
3053 if (i >= matrices) {
3054 av_log(avctx, AV_LOG_ERROR,
3055 "invalid base matrix index\n");
3058 s->qr_base[inter][plane][qri] = i;
3061 i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
3062 s->qr_size[inter][plane][qri++] = i;
3067 av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
3070 s->qr_count[inter][plane] = qri;
3075 /* Huffman tables */
3076 for (int i = 0; i < FF_ARRAY_ELEMS(s->huffman_table); i++) {
3077 s->huffman_table[i].nb_entries = 0;
3078 if ((ret = read_huffman_tree(&s->huffman_table[i], gb, 0, avctx)) < 0)
3082 s->theora_tables = 1;
3087 static av_cold int theora_decode_init(AVCodecContext *avctx)
3089 Vp3DecodeContext *s = avctx->priv_data;
3092 const uint8_t *header_start[3];
3097 avctx->pix_fmt = AV_PIX_FMT_YUV420P;
3101 if (!avctx->extradata_size) {
3102 av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
3106 if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
3107 42, header_start, header_len) < 0) {
3108 av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
3112 for (i = 0; i < 3; i++) {
3113 if (header_len[i] <= 0)
3115 ret = init_get_bits8(&gb, header_start[i], header_len[i]);
3119 ptype = get_bits(&gb, 8);
3121 if (!(ptype & 0x80)) {
3122 av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
3126 // FIXME: Check for this as well.
3127 skip_bits_long(&gb, 6 * 8); /* "theora" */
3131 if (theora_decode_header(avctx, &gb) < 0)
3135 // FIXME: is this needed? it breaks sometimes
3136 // theora_decode_comments(avctx, gb);
3139 if (theora_decode_tables(avctx, &gb))
3143 av_log(avctx, AV_LOG_ERROR,
3144 "Unknown Theora config packet: %d\n", ptype & ~0x80);
3147 if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
3148 av_log(avctx, AV_LOG_WARNING,
3149 "%d bits left in packet %X\n",
3150 8 * header_len[i] - get_bits_count(&gb), ptype);
3151 if (s->theora < 0x030200)
3155 return vp3_decode_init(avctx);
3158 AVCodec ff_theora_decoder = {
3160 .long_name = NULL_IF_CONFIG_SMALL("Theora"),
3161 .type = AVMEDIA_TYPE_VIDEO,
3162 .id = AV_CODEC_ID_THEORA,
3163 .priv_data_size = sizeof(Vp3DecodeContext),
3164 .init = theora_decode_init,
3165 .close = vp3_decode_end,
3166 .decode = vp3_decode_frame,
3167 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3168 AV_CODEC_CAP_FRAME_THREADS,
3169 .flush = vp3_decode_flush,
3170 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3171 .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING | FF_CODEC_CAP_ALLOCATE_PROGRESS |
3172 FF_CODEC_CAP_INIT_CLEANUP,
3176 AVCodec ff_vp3_decoder = {
3178 .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
3179 .type = AVMEDIA_TYPE_VIDEO,
3180 .id = AV_CODEC_ID_VP3,
3181 .priv_data_size = sizeof(Vp3DecodeContext),
3182 .init = vp3_decode_init,
3183 .close = vp3_decode_end,
3184 .decode = vp3_decode_frame,
3185 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3186 AV_CODEC_CAP_FRAME_THREADS,
3187 .flush = vp3_decode_flush,
3188 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3189 .caps_internal = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
3192 #if CONFIG_VP4_DECODER
3193 AVCodec ff_vp4_decoder = {
3195 .long_name = NULL_IF_CONFIG_SMALL("On2 VP4"),
3196 .type = AVMEDIA_TYPE_VIDEO,
3197 .id = AV_CODEC_ID_VP4,
3198 .priv_data_size = sizeof(Vp3DecodeContext),
3199 .init = vp3_decode_init,
3200 .close = vp3_decode_end,
3201 .decode = vp3_decode_frame,
3202 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3203 AV_CODEC_CAP_FRAME_THREADS,
3204 .flush = vp3_decode_flush,
3205 .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3206 .caps_internal = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,