2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
12 #include <stdlib.h> // qsort()
14 #include "./vp9_rtcd.h"
15 #include "./vpx_scale_rtcd.h"
17 #include "vpx_mem/vpx_mem.h"
18 #include "vpx_ports/mem.h"
19 #include "vpx_ports/mem_ops.h"
20 #include "vpx_scale/vpx_scale.h"
21 #include "vpx_util/vpx_thread.h"
23 #include "vp9/common/vp9_alloccommon.h"
24 #include "vp9/common/vp9_common.h"
25 #include "vp9/common/vp9_entropy.h"
26 #include "vp9/common/vp9_entropymode.h"
27 #include "vp9/common/vp9_idct.h"
28 #include "vp9/common/vp9_thread_common.h"
29 #include "vp9/common/vp9_pred_common.h"
30 #include "vp9/common/vp9_quant_common.h"
31 #include "vp9/common/vp9_reconintra.h"
32 #include "vp9/common/vp9_reconinter.h"
33 #include "vp9/common/vp9_seg_common.h"
34 #include "vp9/common/vp9_tile_common.h"
36 #include "vp9/decoder/vp9_decodeframe.h"
37 #include "vp9/decoder/vp9_detokenize.h"
38 #include "vp9/decoder/vp9_decodemv.h"
39 #include "vp9/decoder/vp9_decoder.h"
40 #include "vp9/decoder/vp9_dsubexp.h"
41 #include "vp9/decoder/vp9_read_bit_buffer.h"
42 #include "vp9/decoder/vp9_reader.h"
44 #define MAX_VP9_HEADER_SIZE 80
46 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
48 for (i = 1; i < REFS_PER_FRAME; ++i)
49 if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1])
55 static void setup_compound_reference_mode(VP9_COMMON *cm) {
56 if (cm->ref_frame_sign_bias[LAST_FRAME] ==
57 cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
58 cm->comp_fixed_ref = ALTREF_FRAME;
59 cm->comp_var_ref[0] = LAST_FRAME;
60 cm->comp_var_ref[1] = GOLDEN_FRAME;
61 } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
62 cm->ref_frame_sign_bias[ALTREF_FRAME]) {
63 cm->comp_fixed_ref = GOLDEN_FRAME;
64 cm->comp_var_ref[0] = LAST_FRAME;
65 cm->comp_var_ref[1] = ALTREF_FRAME;
67 cm->comp_fixed_ref = LAST_FRAME;
68 cm->comp_var_ref[0] = GOLDEN_FRAME;
69 cm->comp_var_ref[1] = ALTREF_FRAME;
73 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
74 return len != 0 && len <= (size_t)(end - start);
77 static int decode_unsigned_max(struct vp9_read_bit_buffer *rb, int max) {
78 const int data = vp9_rb_read_literal(rb, get_unsigned_bits(max));
79 return data > max ? max : data;
82 static TX_MODE read_tx_mode(vp9_reader *r) {
83 TX_MODE tx_mode = vp9_read_literal(r, 2);
84 if (tx_mode == ALLOW_32X32)
85 tx_mode += vp9_read_bit(r);
89 static void read_tx_mode_probs(struct tx_probs *tx_probs, vp9_reader *r) {
92 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
93 for (j = 0; j < TX_SIZES - 3; ++j)
94 vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
96 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
97 for (j = 0; j < TX_SIZES - 2; ++j)
98 vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
100 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
101 for (j = 0; j < TX_SIZES - 1; ++j)
102 vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
105 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
107 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
108 for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
109 vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
112 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
114 for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
115 for (j = 0; j < INTER_MODES - 1; ++j)
116 vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
119 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
121 if (is_compound_reference_allowed(cm)) {
122 return vp9_read_bit(r) ? (vp9_read_bit(r) ? REFERENCE_MODE_SELECT
123 : COMPOUND_REFERENCE)
126 return SINGLE_REFERENCE;
130 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vp9_reader *r) {
131 FRAME_CONTEXT *const fc = cm->fc;
134 if (cm->reference_mode == REFERENCE_MODE_SELECT)
135 for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
136 vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
138 if (cm->reference_mode != COMPOUND_REFERENCE)
139 for (i = 0; i < REF_CONTEXTS; ++i) {
140 vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
141 vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
144 if (cm->reference_mode != SINGLE_REFERENCE)
145 for (i = 0; i < REF_CONTEXTS; ++i)
146 vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
149 static void update_mv_probs(vp9_prob *p, int n, vp9_reader *r) {
151 for (i = 0; i < n; ++i)
152 if (vp9_read(r, MV_UPDATE_PROB))
153 p[i] = (vp9_read_literal(r, 7) << 1) | 1;
156 static void read_mv_probs(nmv_context *ctx, int allow_hp, vp9_reader *r) {
159 update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
161 for (i = 0; i < 2; ++i) {
162 nmv_component *const comp_ctx = &ctx->comps[i];
163 update_mv_probs(&comp_ctx->sign, 1, r);
164 update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
165 update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
166 update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
169 for (i = 0; i < 2; ++i) {
170 nmv_component *const comp_ctx = &ctx->comps[i];
171 for (j = 0; j < CLASS0_SIZE; ++j)
172 update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
173 update_mv_probs(comp_ctx->fp, 3, r);
177 for (i = 0; i < 2; ++i) {
178 nmv_component *const comp_ctx = &ctx->comps[i];
179 update_mv_probs(&comp_ctx->class0_hp, 1, r);
180 update_mv_probs(&comp_ctx->hp, 1, r);
185 static void inverse_transform_block_inter(MACROBLOCKD* xd, int plane,
186 const TX_SIZE tx_size,
187 uint8_t *dst, int stride,
189 struct macroblockd_plane *const pd = &xd->plane[plane];
191 tran_low_t *const dqcoeff = pd->dqcoeff;
192 #if CONFIG_VP9_HIGHBITDEPTH
193 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
195 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
199 vp9_highbd_idct4x4_add(dqcoeff, dst, stride, eob, xd->bd);
202 vp9_highbd_idct8x8_add(dqcoeff, dst, stride, eob, xd->bd);
205 vp9_highbd_idct16x16_add(dqcoeff, dst, stride, eob, xd->bd);
208 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
211 assert(0 && "Invalid transform size");
216 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
220 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
223 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
226 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
229 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
232 assert(0 && "Invalid transform size");
239 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
243 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
246 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
249 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
252 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
255 assert(0 && "Invalid transform size");
259 #endif // CONFIG_VP9_HIGHBITDEPTH
264 if (tx_size <= TX_16X16 && eob <= 10)
265 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
266 else if (tx_size == TX_32X32 && eob <= 34)
267 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
269 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
274 static void inverse_transform_block_intra(MACROBLOCKD* xd, int plane,
275 const TX_TYPE tx_type,
276 const TX_SIZE tx_size,
277 uint8_t *dst, int stride,
279 struct macroblockd_plane *const pd = &xd->plane[plane];
281 tran_low_t *const dqcoeff = pd->dqcoeff;
282 #if CONFIG_VP9_HIGHBITDEPTH
283 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
285 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
289 vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
292 vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
295 vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
298 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
301 assert(0 && "Invalid transform size");
306 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
310 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
313 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
316 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
319 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
322 assert(0 && "Invalid transform size");
329 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
333 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
336 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
339 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
342 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
345 assert(0 && "Invalid transform size");
349 #endif // CONFIG_VP9_HIGHBITDEPTH
354 if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
355 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
356 else if (tx_size == TX_32X32 && eob <= 34)
357 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
359 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
364 static INLINE void dec_txfrm_block_to_raster_xy(int bwl,
365 TX_SIZE tx_size, int block,
367 const int tx_cols_log2 = bwl - tx_size;
368 const int tx_cols = 1 << tx_cols_log2;
369 const int raster_mb = block >> (tx_size << 1);
370 *x = (raster_mb & (tx_cols - 1)) << tx_size;
371 *y = (raster_mb >> tx_cols_log2) << tx_size;
380 static void predict_and_reconstruct_intra_block(int plane, int block,
381 TX_SIZE tx_size, void *arg) {
382 struct intra_args *const args = (struct intra_args *)arg;
383 MACROBLOCKD *const xd = args->xd;
384 struct macroblockd_plane *const pd = &xd->plane[plane];
385 MODE_INFO *const mi = xd->mi[0];
386 const PREDICTION_MODE mode = (plane == 0) ? get_y_mode(mi, block)
390 const int bwl = pd->n4_wl;
391 dec_txfrm_block_to_raster_xy(bwl, tx_size, block, &x, &y);
392 dst = &pd->dst.buf[4 * y * pd->dst.stride + 4 * x];
394 vp9_predict_intra_block(xd, bwl, tx_size, mode,
395 dst, pd->dst.stride, dst, pd->dst.stride,
398 if (!mi->mbmi.skip) {
399 const TX_TYPE tx_type = (plane || xd->lossless) ?
400 DCT_DCT : intra_mode_to_tx_type_lookup[mode];
401 const scan_order *sc = (plane || xd->lossless) ?
402 &vp9_default_scan_orders[tx_size] : &vp9_scan_orders[tx_size][tx_type];
403 const int eob = vp9_decode_block_tokens(xd, plane, sc, x, y, tx_size,
404 args->r, args->seg_id);
405 inverse_transform_block_intra(xd, plane, tx_type, tx_size,
406 dst, pd->dst.stride, eob);
410 static int reconstruct_inter_block(MACROBLOCKD *const xd, vp9_reader *r,
411 MB_MODE_INFO *const mbmi, int plane,
412 int row, int col, TX_SIZE tx_size) {
413 struct macroblockd_plane *const pd = &xd->plane[plane];
414 const scan_order *sc = &vp9_default_scan_orders[tx_size];
415 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size, r,
418 inverse_transform_block_inter(xd, plane, tx_size,
419 &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
420 pd->dst.stride, eob);
424 static void build_mc_border(const uint8_t *src, int src_stride,
425 uint8_t *dst, int dst_stride,
426 int x, int y, int b_w, int b_h, int w, int h) {
427 // Get a pointer to the start of the real data for this row.
428 const uint8_t *ref_row = src - x - y * src_stride;
431 ref_row += (h - 1) * src_stride;
433 ref_row += y * src_stride;
437 int left = x < 0 ? -x : 0;
448 copy = b_w - left - right;
451 memset(dst, ref_row[0], left);
454 memcpy(dst + left, ref_row + x + left, copy);
457 memset(dst + left + copy, ref_row[w - 1], right);
463 ref_row += src_stride;
467 #if CONFIG_VP9_HIGHBITDEPTH
468 static void high_build_mc_border(const uint8_t *src8, int src_stride,
469 uint16_t *dst, int dst_stride,
470 int x, int y, int b_w, int b_h,
472 // Get a pointer to the start of the real data for this row.
473 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
474 const uint16_t *ref_row = src - x - y * src_stride;
477 ref_row += (h - 1) * src_stride;
479 ref_row += y * src_stride;
483 int left = x < 0 ? -x : 0;
494 copy = b_w - left - right;
497 vpx_memset16(dst, ref_row[0], left);
500 memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
503 vpx_memset16(dst + left + copy, ref_row[w - 1], right);
509 ref_row += src_stride;
512 #endif // CONFIG_VP9_HIGHBITDEPTH
514 #if CONFIG_VP9_HIGHBITDEPTH
515 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
516 int x0, int y0, int b_w, int b_h,
517 int frame_width, int frame_height,
519 uint8_t *const dst, int dst_buf_stride,
520 int subpel_x, int subpel_y,
521 const InterpKernel *kernel,
522 const struct scale_factors *sf,
524 int w, int h, int ref, int xs, int ys) {
525 DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
526 const uint8_t *buf_ptr;
528 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
529 high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w,
530 x0, y0, b_w, b_h, frame_width, frame_height);
531 buf_ptr = CONVERT_TO_BYTEPTR(mc_buf_high) + border_offset;
533 build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w,
534 x0, y0, b_w, b_h, frame_width, frame_height);
535 buf_ptr = ((uint8_t *)mc_buf_high) + border_offset;
538 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
539 high_inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
540 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
542 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
543 subpel_y, sf, w, h, ref, kernel, xs, ys);
547 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
548 int x0, int y0, int b_w, int b_h,
549 int frame_width, int frame_height,
551 uint8_t *const dst, int dst_buf_stride,
552 int subpel_x, int subpel_y,
553 const InterpKernel *kernel,
554 const struct scale_factors *sf,
555 int w, int h, int ref, int xs, int ys) {
556 DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
557 const uint8_t *buf_ptr;
559 build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w,
560 x0, y0, b_w, b_h, frame_width, frame_height);
561 buf_ptr = mc_buf + border_offset;
563 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
564 subpel_y, sf, w, h, ref, kernel, xs, ys);
566 #endif // CONFIG_VP9_HIGHBITDEPTH
568 static void dec_build_inter_predictors(VP9Decoder *const pbi, MACROBLOCKD *xd,
569 int plane, int bw, int bh, int x,
570 int y, int w, int h, int mi_x, int mi_y,
571 const InterpKernel *kernel,
572 const struct scale_factors *sf,
573 struct buf_2d *pre_buf,
574 struct buf_2d *dst_buf, const MV* mv,
575 RefCntBuffer *ref_frame_buf,
576 int is_scaled, int ref) {
577 struct macroblockd_plane *const pd = &xd->plane[plane];
578 uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
580 int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height,
581 buf_stride, subpel_x, subpel_y;
582 uint8_t *ref_frame, *buf_ptr;
584 // Get reference frame pointer, width and height.
586 frame_width = ref_frame_buf->buf.y_crop_width;
587 frame_height = ref_frame_buf->buf.y_crop_height;
588 ref_frame = ref_frame_buf->buf.y_buffer;
590 frame_width = ref_frame_buf->buf.uv_crop_width;
591 frame_height = ref_frame_buf->buf.uv_crop_height;
592 ref_frame = plane == 1 ? ref_frame_buf->buf.u_buffer
593 : ref_frame_buf->buf.v_buffer;
597 const MV mv_q4 = clamp_mv_to_umv_border_sb(xd, mv, bw, bh,
600 // Co-ordinate of containing block to pixel precision.
601 int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
602 int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
604 // Co-ordinate of the block to 1/16th pixel precision.
605 x0_16 = (x_start + x) << SUBPEL_BITS;
606 y0_16 = (y_start + y) << SUBPEL_BITS;
608 // Co-ordinate of current block in reference frame
609 // to 1/16th pixel precision.
610 x0_16 = sf->scale_value_x(x0_16, sf);
611 y0_16 = sf->scale_value_y(y0_16, sf);
613 // Map the top left corner of the block into the reference frame.
614 x0 = sf->scale_value_x(x_start + x, sf);
615 y0 = sf->scale_value_y(y_start + y, sf);
617 // Scale the MV and incorporate the sub-pixel offset of the block
618 // in the reference frame.
619 scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
623 // Co-ordinate of containing block to pixel precision.
624 x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
625 y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
627 // Co-ordinate of the block to 1/16th pixel precision.
628 x0_16 = x0 << SUBPEL_BITS;
629 y0_16 = y0 << SUBPEL_BITS;
631 scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
632 scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
635 subpel_x = scaled_mv.col & SUBPEL_MASK;
636 subpel_y = scaled_mv.row & SUBPEL_MASK;
638 // Calculate the top left corner of the best matching block in the
640 x0 += scaled_mv.col >> SUBPEL_BITS;
641 y0 += scaled_mv.row >> SUBPEL_BITS;
642 x0_16 += scaled_mv.col;
643 y0_16 += scaled_mv.row;
645 // Get reference block pointer.
646 buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
647 buf_stride = pre_buf->stride;
649 // Do border extension if there is motion or the
650 // width/height is not a multiple of 8 pixels.
651 if (is_scaled || scaled_mv.col || scaled_mv.row ||
652 (frame_width & 0x7) || (frame_height & 0x7)) {
653 int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
655 // Get reference block bottom right horizontal coordinate.
656 int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
657 int x_pad = 0, y_pad = 0;
659 if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
660 x0 -= VP9_INTERP_EXTEND - 1;
661 x1 += VP9_INTERP_EXTEND;
665 if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
666 y0 -= VP9_INTERP_EXTEND - 1;
667 y1 += VP9_INTERP_EXTEND;
671 // Wait until reference block is ready. Pad 7 more pixels as last 7
672 // pixels of each superblock row can be changed by next superblock row.
673 if (pbi->frame_parallel_decode)
674 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
675 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
677 // Skip border extension if block is inside the frame.
678 if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
679 y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
680 // Extend the border.
681 const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
682 const int b_w = x1 - x0 + 1;
683 const int b_h = y1 - y0 + 1;
684 const int border_offset = y_pad * 3 * b_w + x_pad * 3;
686 extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h,
687 frame_width, frame_height, border_offset,
688 dst, dst_buf->stride,
691 #if CONFIG_VP9_HIGHBITDEPTH
698 // Wait until reference block is ready. Pad 7 more pixels as last 7
699 // pixels of each superblock row can be changed by next superblock row.
700 if (pbi->frame_parallel_decode) {
701 const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
702 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
703 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
706 #if CONFIG_VP9_HIGHBITDEPTH
707 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
708 high_inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
709 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
711 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
712 subpel_y, sf, w, h, ref, kernel, xs, ys);
715 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
716 subpel_y, sf, w, h, ref, kernel, xs, ys);
717 #endif // CONFIG_VP9_HIGHBITDEPTH
720 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
722 int mi_row, int mi_col) {
724 const int mi_x = mi_col * MI_SIZE;
725 const int mi_y = mi_row * MI_SIZE;
726 const MODE_INFO *mi = xd->mi[0];
727 const InterpKernel *kernel = vp9_filter_kernels[mi->mbmi.interp_filter];
728 const BLOCK_SIZE sb_type = mi->mbmi.sb_type;
729 const int is_compound = has_second_ref(&mi->mbmi);
731 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
732 struct macroblockd_plane *const pd = &xd->plane[plane];
733 struct buf_2d *const dst_buf = &pd->dst;
734 const int num_4x4_w = pd->n4_w;
735 const int num_4x4_h = pd->n4_h;
737 const int n4w_x4 = 4 * num_4x4_w;
738 const int n4h_x4 = 4 * num_4x4_h;
741 for (ref = 0; ref < 1 + is_compound; ++ref) {
742 const struct scale_factors *const sf = &xd->block_refs[ref]->sf;
743 struct buf_2d *const pre_buf = &pd->pre[ref];
744 const int idx = xd->block_refs[ref]->idx;
745 BufferPool *const pool = pbi->common.buffer_pool;
746 RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
747 const int is_scaled = vp9_is_scaled(sf);
749 if (sb_type < BLOCK_8X8) {
751 for (y = 0; y < num_4x4_h; ++y) {
752 for (x = 0; x < num_4x4_w; ++x) {
753 const MV mv = average_split_mvs(pd, mi, ref, i++);
754 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
755 4 * x, 4 * y, 4, 4, mi_x, mi_y, kernel,
756 sf, pre_buf, dst_buf, &mv,
757 ref_frame_buf, is_scaled, ref);
761 const MV mv = mi->mbmi.mv[ref].as_mv;
762 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
763 0, 0, n4w_x4, n4h_x4, mi_x, mi_y, kernel,
764 sf, pre_buf, dst_buf, &mv, ref_frame_buf,
771 static INLINE TX_SIZE dec_get_uv_tx_size(const MB_MODE_INFO *mbmi,
772 int n4_wl, int n4_hl) {
773 // get minimum log2 num4x4s dimension
774 const int x = MIN(n4_wl, n4_hl);
775 return MIN(mbmi->tx_size, x);
778 // TODO(slavarnway): Eliminate the foreach_ functions in future commits.
779 // NOTE: Jingning removed the foreach_ for recon inter in a previous commit.
781 typedef void (*dec_foreach_transformed_block_visitor)(int plane, int block,
785 static void dec_foreach_transformed_block_in_plane(
786 const MACROBLOCKD *const xd,
788 dec_foreach_transformed_block_visitor visit, void *arg) {
789 const struct macroblockd_plane *const pd = &xd->plane[plane];
790 const MB_MODE_INFO* mbmi = &xd->mi[0]->mbmi;
791 // block and transform sizes, in number of 4x4 blocks log 2 ("*_b")
792 // 4x4=0, 8x8=2, 16x16=4, 32x32=6, 64x64=8
793 // transform size varies per plane, look it up in a common way.
794 const TX_SIZE tx_size =
795 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
797 const int num_4x4_w = pd->n4_w;
798 const int num_4x4_h = pd->n4_h;
799 const int step = 1 << (tx_size << 1);
802 // If mb_to_right_edge is < 0 we are in a situation in which
803 // the current block size extends into the UMV and we won't
804 // visit the sub blocks that are wholly within the UMV.
805 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ? 0 :
806 xd->mb_to_right_edge >> (5 + pd->subsampling_x));
807 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ? 0 :
808 xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
810 // Keep track of the row and column of the blocks we use so that we know
811 // if we are in the unrestricted motion border.
812 for (r = 0; r < max_blocks_high; r += (1 << tx_size)) {
813 for (c = 0; c < num_4x4_w; c += (1 << tx_size)) {
814 // Skip visiting the sub blocks that are wholly within the UMV.
815 if (c < max_blocks_wide)
816 visit(plane, i, tx_size, arg);
822 static void dec_foreach_transformed_block(const MACROBLOCKD* const xd,
823 dec_foreach_transformed_block_visitor visit, void *arg) {
826 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
827 dec_foreach_transformed_block_in_plane(xd, plane, visit, arg);
830 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
832 for (i = 0; i < MAX_MB_PLANE; i++) {
833 struct macroblockd_plane *const pd = &xd->plane[i];
834 memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
835 memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
839 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
842 for (i = 0; i < MAX_MB_PLANE; i++) {
843 xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
844 xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
845 xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
846 xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
850 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
851 BLOCK_SIZE bsize, int mi_row, int mi_col,
852 int bw, int bh, int x_mis, int y_mis,
854 const int offset = mi_row * cm->mi_stride + mi_col;
856 const TileInfo *const tile = &xd->tile;
858 xd->mi = cm->mi_grid_visible + offset;
859 xd->mi[0] = &cm->mi[offset];
860 // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
861 // passing bsize from decode_partition().
862 xd->mi[0]->mbmi.sb_type = bsize;
863 for (y = 0; y < y_mis; ++y)
864 for (x = !y; x < x_mis; ++x) {
865 xd->mi[y * cm->mi_stride + x] = xd->mi[0];
868 set_plane_n4(xd, bw, bh, bwl, bhl);
870 set_skip_context(xd, mi_row, mi_col);
872 // Distance of Mb to the various image edges. These are specified to 8th pel
873 // as they are always compared to values that are in 1/8th pel units
874 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
876 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
877 return &xd->mi[0]->mbmi;
880 static void decode_block(VP9Decoder *const pbi, MACROBLOCKD *const xd,
881 int mi_row, int mi_col,
882 vp9_reader *r, BLOCK_SIZE bsize,
884 VP9_COMMON *const cm = &pbi->common;
885 const int less8x8 = bsize < BLOCK_8X8;
886 const int bw = 1 << (bwl - 1);
887 const int bh = 1 << (bhl - 1);
888 const int x_mis = MIN(bw, cm->mi_cols - mi_col);
889 const int y_mis = MIN(bh, cm->mi_rows - mi_row);
891 MB_MODE_INFO *mbmi = set_offsets(cm, xd, bsize, mi_row, mi_col,
892 bw, bh, x_mis, y_mis, bwl, bhl);
894 if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
895 const BLOCK_SIZE uv_subsize =
896 ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
897 if (uv_subsize == BLOCK_INVALID)
898 vpx_internal_error(xd->error_info,
899 VPX_CODEC_CORRUPT_FRAME, "Invalid block size.");
902 vp9_read_mode_info(pbi, xd, mi_row, mi_col, r, x_mis, y_mis);
905 dec_reset_skip_context(xd);
908 if (!is_inter_block(mbmi)) {
909 struct intra_args arg = {xd, r, mbmi->segment_id};
910 dec_foreach_transformed_block(xd,
911 predict_and_reconstruct_intra_block, &arg);
914 dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col);
921 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
922 const struct macroblockd_plane *const pd = &xd->plane[plane];
923 const TX_SIZE tx_size =
924 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
926 const int num_4x4_w = pd->n4_w;
927 const int num_4x4_h = pd->n4_h;
928 const int step = (1 << tx_size);
930 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
931 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
932 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
933 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
935 for (row = 0; row < max_blocks_high; row += step)
936 for (col = 0; col < max_blocks_wide; col += step)
937 eobtotal += reconstruct_inter_block(xd, r, mbmi, plane, row, col,
941 if (!less8x8 && eobtotal == 0)
942 mbmi->skip = 1; // skip loopfilter
946 xd->corrupted |= vp9_reader_has_error(r);
949 static INLINE int dec_partition_plane_context(const MACROBLOCKD *xd,
950 int mi_row, int mi_col,
952 const PARTITION_CONTEXT *above_ctx = xd->above_seg_context + mi_col;
953 const PARTITION_CONTEXT *left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
954 int above = (*above_ctx >> bsl) & 1 , left = (*left_ctx >> bsl) & 1;
958 return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
961 static INLINE void dec_update_partition_context(MACROBLOCKD *xd,
962 int mi_row, int mi_col,
965 PARTITION_CONTEXT *const above_ctx = xd->above_seg_context + mi_col;
966 PARTITION_CONTEXT *const left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
968 // update the partition context at the end notes. set partition bits
969 // of block sizes larger than the current one to be one, and partition
970 // bits of smaller block sizes to be zero.
971 memset(above_ctx, partition_context_lookup[subsize].above, bw);
972 memset(left_ctx, partition_context_lookup[subsize].left, bw);
975 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
977 int has_rows, int has_cols, int bsl) {
978 const int ctx = dec_partition_plane_context(xd, mi_row, mi_col, bsl);
979 const vp9_prob *const probs = get_partition_probs(xd, ctx);
980 FRAME_COUNTS *counts = xd->counts;
983 if (has_rows && has_cols)
984 p = (PARTITION_TYPE)vp9_read_tree(r, vp9_partition_tree, probs);
985 else if (!has_rows && has_cols)
986 p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
987 else if (has_rows && !has_cols)
988 p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
993 ++counts->partition[ctx][p];
998 // TODO(slavarnway): eliminate bsize and subsize in future commits
999 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
1000 int mi_row, int mi_col,
1001 vp9_reader* r, BLOCK_SIZE bsize, int n4x4_l2) {
1002 VP9_COMMON *const cm = &pbi->common;
1003 const int n8x8_l2 = n4x4_l2 - 1;
1004 const int num_8x8_wh = 1 << n8x8_l2;
1005 const int hbs = num_8x8_wh >> 1;
1006 PARTITION_TYPE partition;
1008 const int has_rows = (mi_row + hbs) < cm->mi_rows;
1009 const int has_cols = (mi_col + hbs) < cm->mi_cols;
1011 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1014 partition = read_partition(xd, mi_row, mi_col, r, has_rows, has_cols,
1016 subsize = subsize_lookup[partition][bsize]; // get_subsize(bsize, partition);
1018 // calculate bmode block dimensions (log 2)
1019 xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
1020 xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
1021 decode_block(pbi, xd, mi_row, mi_col, r, subsize, 1, 1);
1023 switch (partition) {
1024 case PARTITION_NONE:
1025 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n4x4_l2);
1027 case PARTITION_HORZ:
1028 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n8x8_l2);
1030 decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize, n4x4_l2,
1033 case PARTITION_VERT:
1034 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2, n4x4_l2);
1036 decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2,
1039 case PARTITION_SPLIT:
1040 decode_partition(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2);
1041 decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2);
1042 decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize, n8x8_l2);
1043 decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize,
1047 assert(0 && "Invalid partition type");
1051 // update partition context
1052 if (bsize >= BLOCK_8X8 &&
1053 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
1054 dec_update_partition_context(xd, mi_row, mi_col, subsize, num_8x8_wh);
1057 static void setup_token_decoder(const uint8_t *data,
1058 const uint8_t *data_end,
1060 struct vpx_internal_error_info *error_info,
1062 vpx_decrypt_cb decrypt_cb,
1063 void *decrypt_state) {
1064 // Validate the calculated partition length. If the buffer
1065 // described by the partition can't be fully read, then restrict
1066 // it to the portion that can be (for EC mode) or throw an error.
1067 if (!read_is_valid(data, read_size, data_end))
1068 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1069 "Truncated packet or corrupt tile length");
1071 if (vp9_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
1072 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
1073 "Failed to allocate bool decoder %d", 1);
1076 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
1080 if (vp9_read_bit(r))
1081 for (i = 0; i < PLANE_TYPES; ++i)
1082 for (j = 0; j < REF_TYPES; ++j)
1083 for (k = 0; k < COEF_BANDS; ++k)
1084 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1085 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
1086 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
1089 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
1091 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1093 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1094 read_coef_probs_common(fc->coef_probs[tx_size], r);
1097 static void setup_segmentation(struct segmentation *seg,
1098 struct vp9_read_bit_buffer *rb) {
1101 seg->update_map = 0;
1102 seg->update_data = 0;
1104 seg->enabled = vp9_rb_read_bit(rb);
1108 // Segmentation map update
1109 seg->update_map = vp9_rb_read_bit(rb);
1110 if (seg->update_map) {
1111 for (i = 0; i < SEG_TREE_PROBS; i++)
1112 seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1115 seg->temporal_update = vp9_rb_read_bit(rb);
1116 if (seg->temporal_update) {
1117 for (i = 0; i < PREDICTION_PROBS; i++)
1118 seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1121 for (i = 0; i < PREDICTION_PROBS; i++)
1122 seg->pred_probs[i] = MAX_PROB;
1126 // Segmentation data update
1127 seg->update_data = vp9_rb_read_bit(rb);
1128 if (seg->update_data) {
1129 seg->abs_delta = vp9_rb_read_bit(rb);
1131 vp9_clearall_segfeatures(seg);
1133 for (i = 0; i < MAX_SEGMENTS; i++) {
1134 for (j = 0; j < SEG_LVL_MAX; j++) {
1136 const int feature_enabled = vp9_rb_read_bit(rb);
1137 if (feature_enabled) {
1138 vp9_enable_segfeature(seg, i, j);
1139 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1140 if (vp9_is_segfeature_signed(j))
1141 data = vp9_rb_read_bit(rb) ? -data : data;
1143 vp9_set_segdata(seg, i, j, data);
1149 static void setup_loopfilter(struct loopfilter *lf,
1150 struct vp9_read_bit_buffer *rb) {
1151 lf->filter_level = vp9_rb_read_literal(rb, 6);
1152 lf->sharpness_level = vp9_rb_read_literal(rb, 3);
1154 // Read in loop filter deltas applied at the MB level based on mode or ref
1156 lf->mode_ref_delta_update = 0;
1158 lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
1159 if (lf->mode_ref_delta_enabled) {
1160 lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
1161 if (lf->mode_ref_delta_update) {
1164 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1165 if (vp9_rb_read_bit(rb))
1166 lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1168 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1169 if (vp9_rb_read_bit(rb))
1170 lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1175 static INLINE int read_delta_q(struct vp9_read_bit_buffer *rb) {
1176 return vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
1179 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1180 struct vp9_read_bit_buffer *rb) {
1181 cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
1182 cm->y_dc_delta_q = read_delta_q(rb);
1183 cm->uv_dc_delta_q = read_delta_q(rb);
1184 cm->uv_ac_delta_q = read_delta_q(rb);
1185 cm->dequant_bit_depth = cm->bit_depth;
1186 xd->lossless = cm->base_qindex == 0 &&
1187 cm->y_dc_delta_q == 0 &&
1188 cm->uv_dc_delta_q == 0 &&
1189 cm->uv_ac_delta_q == 0;
1191 #if CONFIG_VP9_HIGHBITDEPTH
1192 xd->bd = (int)cm->bit_depth;
1196 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1197 // Build y/uv dequant values based on segmentation.
1198 if (cm->seg.enabled) {
1200 for (i = 0; i < MAX_SEGMENTS; ++i) {
1201 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1202 cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
1204 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1205 cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1207 cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1211 const int qindex = cm->base_qindex;
1212 // When segmentation is disabled, only the first value is used. The
1213 // remaining are don't cares.
1214 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1215 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1216 cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1218 cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1223 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
1224 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1228 return vp9_rb_read_bit(rb) ? SWITCHABLE
1229 : literal_to_filter[vp9_rb_read_literal(rb, 2)];
1232 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1233 cm->display_width = cm->width;
1234 cm->display_height = cm->height;
1235 if (vp9_rb_read_bit(rb))
1236 vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
1239 static void resize_mv_buffer(VP9_COMMON *cm) {
1240 vpx_free(cm->cur_frame->mvs);
1241 cm->cur_frame->mi_rows = cm->mi_rows;
1242 cm->cur_frame->mi_cols = cm->mi_cols;
1243 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1244 sizeof(*cm->cur_frame->mvs));
1247 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1248 #if CONFIG_SIZE_LIMIT
1249 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1250 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1251 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1252 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1254 if (cm->width != width || cm->height != height) {
1255 const int new_mi_rows =
1256 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1257 const int new_mi_cols =
1258 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1260 // Allocations in vp9_alloc_context_buffers() depend on individual
1261 // dimensions as well as the overall size.
1262 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1263 if (vp9_alloc_context_buffers(cm, width, height))
1264 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1265 "Failed to allocate context buffers");
1267 vp9_set_mb_mi(cm, width, height);
1269 vp9_init_context_buffers(cm);
1271 cm->height = height;
1273 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1274 cm->mi_cols > cm->cur_frame->mi_cols) {
1275 resize_mv_buffer(cm);
1279 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1281 BufferPool *const pool = cm->buffer_pool;
1282 vp9_read_frame_size(rb, &width, &height);
1283 resize_context_buffers(cm, width, height);
1284 setup_display_size(cm, rb);
1286 lock_buffer_pool(pool);
1287 if (vp9_realloc_frame_buffer(
1288 get_frame_new_buffer(cm), cm->width, cm->height,
1289 cm->subsampling_x, cm->subsampling_y,
1290 #if CONFIG_VP9_HIGHBITDEPTH
1291 cm->use_highbitdepth,
1293 VP9_DEC_BORDER_IN_PIXELS,
1295 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1297 unlock_buffer_pool(pool);
1298 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1299 "Failed to allocate frame buffer");
1301 unlock_buffer_pool(pool);
1303 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1304 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1305 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1306 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1309 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1310 int ref_xss, int ref_yss,
1311 vpx_bit_depth_t this_bit_depth,
1312 int this_xss, int this_yss) {
1313 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1314 ref_yss == this_yss;
1317 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1318 struct vp9_read_bit_buffer *rb) {
1321 int has_valid_ref_frame = 0;
1322 BufferPool *const pool = cm->buffer_pool;
1323 for (i = 0; i < REFS_PER_FRAME; ++i) {
1324 if (vp9_rb_read_bit(rb)) {
1325 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1326 width = buf->y_crop_width;
1327 height = buf->y_crop_height;
1334 vp9_read_frame_size(rb, &width, &height);
1336 if (width <= 0 || height <= 0)
1337 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1338 "Invalid frame size");
1340 // Check to make sure at least one of frames that this frame references
1341 // has valid dimensions.
1342 for (i = 0; i < REFS_PER_FRAME; ++i) {
1343 RefBuffer *const ref_frame = &cm->frame_refs[i];
1344 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1345 ref_frame->buf->y_crop_height,
1348 if (!has_valid_ref_frame)
1349 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1350 "Referenced frame has invalid size");
1351 for (i = 0; i < REFS_PER_FRAME; ++i) {
1352 RefBuffer *const ref_frame = &cm->frame_refs[i];
1353 if (!valid_ref_frame_img_fmt(
1354 ref_frame->buf->bit_depth,
1355 ref_frame->buf->subsampling_x,
1356 ref_frame->buf->subsampling_y,
1360 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1361 "Referenced frame has incompatible color format");
1364 resize_context_buffers(cm, width, height);
1365 setup_display_size(cm, rb);
1367 lock_buffer_pool(pool);
1368 if (vp9_realloc_frame_buffer(
1369 get_frame_new_buffer(cm), cm->width, cm->height,
1370 cm->subsampling_x, cm->subsampling_y,
1371 #if CONFIG_VP9_HIGHBITDEPTH
1372 cm->use_highbitdepth,
1374 VP9_DEC_BORDER_IN_PIXELS,
1376 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1378 unlock_buffer_pool(pool);
1379 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1380 "Failed to allocate frame buffer");
1382 unlock_buffer_pool(pool);
1384 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1385 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1386 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1387 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1390 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1391 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1392 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1395 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1396 cm->log2_tile_cols = min_log2_tile_cols;
1397 while (max_ones-- && vp9_rb_read_bit(rb))
1398 cm->log2_tile_cols++;
1400 if (cm->log2_tile_cols > 6)
1401 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1402 "Invalid number of tile columns");
1405 cm->log2_tile_rows = vp9_rb_read_bit(rb);
1406 if (cm->log2_tile_rows)
1407 cm->log2_tile_rows += vp9_rb_read_bit(rb);
1410 typedef struct TileBuffer {
1411 const uint8_t *data;
1413 int col; // only used with multi-threaded decoding
1416 // Reads the next tile returning its size and adjusting '*data' accordingly
1417 // based on 'is_last'.
1418 static void get_tile_buffer(const uint8_t *const data_end,
1420 struct vpx_internal_error_info *error_info,
1421 const uint8_t **data,
1422 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1427 if (!read_is_valid(*data, 4, data_end))
1428 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1429 "Truncated packet or corrupt tile length");
1433 decrypt_cb(decrypt_state, *data, be_data, 4);
1434 size = mem_get_be32(be_data);
1436 size = mem_get_be32(*data);
1440 if (size > (size_t)(data_end - *data))
1441 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1442 "Truncated packet or corrupt tile size");
1444 size = data_end - *data;
1453 static void get_tile_buffers(VP9Decoder *pbi,
1454 const uint8_t *data, const uint8_t *data_end,
1455 int tile_cols, int tile_rows,
1456 TileBuffer (*tile_buffers)[1 << 6]) {
1459 for (r = 0; r < tile_rows; ++r) {
1460 for (c = 0; c < tile_cols; ++c) {
1461 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1462 TileBuffer *const buf = &tile_buffers[r][c];
1464 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1465 pbi->decrypt_cb, pbi->decrypt_state, buf);
1470 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1471 const uint8_t *data,
1472 const uint8_t *data_end) {
1473 VP9_COMMON *const cm = &pbi->common;
1474 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1475 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1476 const int tile_cols = 1 << cm->log2_tile_cols;
1477 const int tile_rows = 1 << cm->log2_tile_rows;
1478 TileBuffer tile_buffers[4][1 << 6];
1479 int tile_row, tile_col;
1481 TileData *tile_data = NULL;
1483 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1484 pbi->lf_worker.data1 == NULL) {
1485 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1486 vpx_memalign(32, sizeof(LFWorkerData)));
1487 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1488 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1489 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1490 "Loop filter thread creation failed");
1494 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1495 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1496 // Be sure to sync as we might be resuming after a failed frame decode.
1497 winterface->sync(&pbi->lf_worker);
1498 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1502 assert(tile_rows <= 4);
1503 assert(tile_cols <= (1 << 6));
1505 // Note: this memset assumes above_context[0], [1] and [2]
1506 // are allocated as part of the same buffer.
1507 memset(cm->above_context, 0,
1508 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1510 memset(cm->above_seg_context, 0,
1511 sizeof(*cm->above_seg_context) * aligned_cols);
1513 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1515 if (pbi->tile_data == NULL ||
1516 (tile_cols * tile_rows) != pbi->total_tiles) {
1517 vpx_free(pbi->tile_data);
1521 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1522 pbi->total_tiles = tile_rows * tile_cols;
1525 // Load all tile information into tile_data.
1526 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1527 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1528 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1529 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1531 tile_data->xd = pbi->mb;
1532 tile_data->xd.corrupted = 0;
1533 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1535 vp9_zero(tile_data->dqcoeff);
1536 vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1537 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1538 &tile_data->bit_reader, pbi->decrypt_cb,
1539 pbi->decrypt_state);
1540 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1544 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1546 vp9_tile_set_row(&tile, cm, tile_row);
1547 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1548 mi_row += MI_BLOCK_SIZE) {
1549 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1550 const int col = pbi->inv_tile_order ?
1551 tile_cols - tile_col - 1 : tile_col;
1552 tile_data = pbi->tile_data + tile_cols * tile_row + col;
1553 vp9_tile_set_col(&tile, tile_data->cm, col);
1554 vp9_zero(tile_data->xd.left_context);
1555 vp9_zero(tile_data->xd.left_seg_context);
1556 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1557 mi_col += MI_BLOCK_SIZE) {
1558 decode_partition(pbi, &tile_data->xd, mi_row,
1559 mi_col, &tile_data->bit_reader, BLOCK_64X64, 4);
1561 pbi->mb.corrupted |= tile_data->xd.corrupted;
1562 if (pbi->mb.corrupted)
1563 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1564 "Failed to decode tile data");
1566 // Loopfilter one row.
1567 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1568 const int lf_start = mi_row - MI_BLOCK_SIZE;
1569 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1571 // delay the loopfilter by 1 macroblock row.
1572 if (lf_start < 0) continue;
1574 // decoding has completed: finish up the loop filter in this thread.
1575 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1577 winterface->sync(&pbi->lf_worker);
1578 lf_data->start = lf_start;
1579 lf_data->stop = mi_row;
1580 if (pbi->max_threads > 1) {
1581 winterface->launch(&pbi->lf_worker);
1583 winterface->execute(&pbi->lf_worker);
1586 // After loopfiltering, the last 7 row pixels in each superblock row may
1587 // still be changed by the longest loopfilter of the next superblock
1589 if (pbi->frame_parallel_decode)
1590 vp9_frameworker_broadcast(pbi->cur_buf,
1591 mi_row << MI_BLOCK_SIZE_LOG2);
1595 // Loopfilter remaining rows in the frame.
1596 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1597 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1598 winterface->sync(&pbi->lf_worker);
1599 lf_data->start = lf_data->stop;
1600 lf_data->stop = cm->mi_rows;
1601 winterface->execute(&pbi->lf_worker);
1604 // Get last tile data.
1605 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1607 if (pbi->frame_parallel_decode)
1608 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1609 return vp9_reader_find_end(&tile_data->bit_reader);
1612 static int tile_worker_hook(TileWorkerData *const tile_data,
1613 const TileInfo *const tile) {
1616 if (setjmp(tile_data->error_info.jmp)) {
1617 tile_data->error_info.setjmp = 0;
1618 tile_data->xd.corrupted = 1;
1622 tile_data->error_info.setjmp = 1;
1623 tile_data->xd.error_info = &tile_data->error_info;
1625 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1626 mi_row += MI_BLOCK_SIZE) {
1627 vp9_zero(tile_data->xd.left_context);
1628 vp9_zero(tile_data->xd.left_seg_context);
1629 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1630 mi_col += MI_BLOCK_SIZE) {
1631 decode_partition(tile_data->pbi, &tile_data->xd,
1632 mi_row, mi_col, &tile_data->bit_reader,
1636 return !tile_data->xd.corrupted;
1639 // sorts in descending order
1640 static int compare_tile_buffers(const void *a, const void *b) {
1641 const TileBuffer *const buf1 = (const TileBuffer*)a;
1642 const TileBuffer *const buf2 = (const TileBuffer*)b;
1643 return (int)(buf2->size - buf1->size);
1646 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1647 const uint8_t *data,
1648 const uint8_t *data_end) {
1649 VP9_COMMON *const cm = &pbi->common;
1650 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1651 const uint8_t *bit_reader_end = NULL;
1652 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1653 const int tile_cols = 1 << cm->log2_tile_cols;
1654 const int tile_rows = 1 << cm->log2_tile_rows;
1655 const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1656 TileBuffer tile_buffers[1][1 << 6];
1658 int final_worker = -1;
1660 assert(tile_cols <= (1 << 6));
1661 assert(tile_rows == 1);
1664 // TODO(jzern): See if we can remove the restriction of passing in max
1665 // threads to the decoder.
1666 if (pbi->num_tile_workers == 0) {
1667 const int num_threads = pbi->max_threads & ~1;
1669 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1670 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1671 // Ensure tile data offsets will be properly aligned. This may fail on
1672 // platforms without DECLARE_ALIGNED().
1673 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1674 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1675 vpx_memalign(32, num_threads *
1676 sizeof(*pbi->tile_worker_data)));
1677 CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1678 vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1679 for (i = 0; i < num_threads; ++i) {
1680 VPxWorker *const worker = &pbi->tile_workers[i];
1681 ++pbi->num_tile_workers;
1683 winterface->init(worker);
1684 if (i < num_threads - 1 && !winterface->reset(worker)) {
1685 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1686 "Tile decoder thread creation failed");
1691 // Reset tile decoding hook
1692 for (n = 0; n < num_workers; ++n) {
1693 VPxWorker *const worker = &pbi->tile_workers[n];
1694 winterface->sync(worker);
1695 worker->hook = (VPxWorkerHook)tile_worker_hook;
1696 worker->data1 = &pbi->tile_worker_data[n];
1697 worker->data2 = &pbi->tile_worker_info[n];
1700 // Note: this memset assumes above_context[0], [1] and [2]
1701 // are allocated as part of the same buffer.
1702 memset(cm->above_context, 0,
1703 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1704 memset(cm->above_seg_context, 0,
1705 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1707 // Load tile data into tile_buffers
1708 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1710 // Sort the buffers based on size in descending order.
1711 qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1712 compare_tile_buffers);
1714 // Rearrange the tile buffers such that per-tile group the largest, and
1715 // presumably the most difficult, tile will be decoded in the main thread.
1716 // This should help minimize the number of instances where the main thread is
1717 // waiting for a worker to complete.
1719 int group_start = 0;
1720 while (group_start < tile_cols) {
1721 const TileBuffer largest = tile_buffers[0][group_start];
1722 const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1723 memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1724 (group_end - group_start) * sizeof(tile_buffers[0][0]));
1725 tile_buffers[0][group_end] = largest;
1726 group_start = group_end + 1;
1730 // Initialize thread frame counts.
1731 if (!cm->frame_parallel_decoding_mode) {
1734 for (i = 0; i < num_workers; ++i) {
1735 TileWorkerData *const tile_data =
1736 (TileWorkerData*)pbi->tile_workers[i].data1;
1737 vp9_zero(tile_data->counts);
1742 while (n < tile_cols) {
1744 for (i = 0; i < num_workers && n < tile_cols; ++i) {
1745 VPxWorker *const worker = &pbi->tile_workers[i];
1746 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1747 TileInfo *const tile = (TileInfo*)worker->data2;
1748 TileBuffer *const buf = &tile_buffers[0][n];
1750 tile_data->pbi = pbi;
1751 tile_data->xd = pbi->mb;
1752 tile_data->xd.corrupted = 0;
1753 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1754 0 : &tile_data->counts;
1755 vp9_zero(tile_data->dqcoeff);
1756 vp9_tile_init(tile, cm, 0, buf->col);
1757 vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1758 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1759 &tile_data->bit_reader, pbi->decrypt_cb,
1760 pbi->decrypt_state);
1761 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1763 worker->had_error = 0;
1764 if (i == num_workers - 1 || n == tile_cols - 1) {
1765 winterface->execute(worker);
1767 winterface->launch(worker);
1770 if (buf->col == tile_cols - 1) {
1777 for (; i > 0; --i) {
1778 VPxWorker *const worker = &pbi->tile_workers[i - 1];
1779 // TODO(jzern): The tile may have specific error data associated with
1780 // its vpx_internal_error_info which could be propagated to the main info
1781 // in cm. Additionally once the threads have been synced and an error is
1782 // detected, there's no point in continuing to decode tiles.
1783 pbi->mb.corrupted |= !winterface->sync(worker);
1785 if (final_worker > -1) {
1786 TileWorkerData *const tile_data =
1787 (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1788 bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1792 // Accumulate thread frame counts.
1793 if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1794 for (i = 0; i < num_workers; ++i) {
1795 TileWorkerData *const tile_data =
1796 (TileWorkerData*)pbi->tile_workers[i].data1;
1797 vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1802 return bit_reader_end;
1805 static void error_handler(void *data) {
1806 VP9_COMMON *const cm = (VP9_COMMON *)data;
1807 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1810 static void read_bitdepth_colorspace_sampling(
1811 VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1812 if (cm->profile >= PROFILE_2) {
1813 cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1814 #if CONFIG_VP9_HIGHBITDEPTH
1815 cm->use_highbitdepth = 1;
1818 cm->bit_depth = VPX_BITS_8;
1819 #if CONFIG_VP9_HIGHBITDEPTH
1820 cm->use_highbitdepth = 0;
1823 cm->color_space = vp9_rb_read_literal(rb, 3);
1824 if (cm->color_space != VPX_CS_SRGB) {
1825 vp9_rb_read_bit(rb); // [16,235] (including xvycc) vs [0,255] range
1826 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1827 cm->subsampling_x = vp9_rb_read_bit(rb);
1828 cm->subsampling_y = vp9_rb_read_bit(rb);
1829 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1830 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1831 "4:2:0 color not supported in profile 1 or 3");
1832 if (vp9_rb_read_bit(rb))
1833 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1834 "Reserved bit set");
1836 cm->subsampling_y = cm->subsampling_x = 1;
1839 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1840 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1841 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1842 cm->subsampling_y = cm->subsampling_x = 0;
1843 if (vp9_rb_read_bit(rb))
1844 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1845 "Reserved bit set");
1847 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1848 "4:4:4 color not supported in profile 0 or 2");
1853 static size_t read_uncompressed_header(VP9Decoder *pbi,
1854 struct vp9_read_bit_buffer *rb) {
1855 VP9_COMMON *const cm = &pbi->common;
1856 BufferPool *const pool = cm->buffer_pool;
1857 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1858 int i, mask, ref_index = 0;
1861 cm->last_frame_type = cm->frame_type;
1862 cm->last_intra_only = cm->intra_only;
1864 if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1865 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1866 "Invalid frame marker");
1868 cm->profile = vp9_read_profile(rb);
1870 if (cm->profile >= MAX_PROFILES)
1871 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1872 "Unsupported bitstream profile");
1874 cm->show_existing_frame = vp9_rb_read_bit(rb);
1875 if (cm->show_existing_frame) {
1876 // Show an existing frame directly.
1877 const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1878 lock_buffer_pool(pool);
1879 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1880 unlock_buffer_pool(pool);
1881 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1882 "Buffer %d does not contain a decoded frame",
1886 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1887 unlock_buffer_pool(pool);
1888 pbi->refresh_frame_flags = 0;
1889 cm->lf.filter_level = 0;
1892 if (pbi->frame_parallel_decode) {
1893 for (i = 0; i < REF_FRAMES; ++i)
1894 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1899 cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1900 cm->show_frame = vp9_rb_read_bit(rb);
1901 cm->error_resilient_mode = vp9_rb_read_bit(rb);
1903 if (cm->frame_type == KEY_FRAME) {
1904 if (!vp9_read_sync_code(rb))
1905 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1906 "Invalid frame sync code");
1908 read_bitdepth_colorspace_sampling(cm, rb);
1909 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1911 for (i = 0; i < REFS_PER_FRAME; ++i) {
1912 cm->frame_refs[i].idx = INVALID_IDX;
1913 cm->frame_refs[i].buf = NULL;
1916 setup_frame_size(cm, rb);
1917 if (pbi->need_resync) {
1918 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1919 pbi->need_resync = 0;
1922 cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1924 cm->reset_frame_context = cm->error_resilient_mode ?
1925 0 : vp9_rb_read_literal(rb, 2);
1927 if (cm->intra_only) {
1928 if (!vp9_read_sync_code(rb))
1929 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1930 "Invalid frame sync code");
1931 if (cm->profile > PROFILE_0) {
1932 read_bitdepth_colorspace_sampling(cm, rb);
1934 // NOTE: The intra-only frame header does not include the specification
1935 // of either the color format or color sub-sampling in profile 0. VP9
1936 // specifies that the default color format should be YUV 4:2:0 in this
1937 // case (normative).
1938 cm->color_space = VPX_CS_BT_601;
1939 cm->subsampling_y = cm->subsampling_x = 1;
1940 cm->bit_depth = VPX_BITS_8;
1941 #if CONFIG_VP9_HIGHBITDEPTH
1942 cm->use_highbitdepth = 0;
1946 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1947 setup_frame_size(cm, rb);
1948 if (pbi->need_resync) {
1949 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1950 pbi->need_resync = 0;
1952 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1953 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1954 for (i = 0; i < REFS_PER_FRAME; ++i) {
1955 const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1956 const int idx = cm->ref_frame_map[ref];
1957 RefBuffer *const ref_frame = &cm->frame_refs[i];
1958 ref_frame->idx = idx;
1959 ref_frame->buf = &frame_bufs[idx].buf;
1960 cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1963 setup_frame_size_with_refs(cm, rb);
1965 cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1966 cm->interp_filter = read_interp_filter(rb);
1968 for (i = 0; i < REFS_PER_FRAME; ++i) {
1969 RefBuffer *const ref_buf = &cm->frame_refs[i];
1970 #if CONFIG_VP9_HIGHBITDEPTH
1971 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1972 ref_buf->buf->y_crop_width,
1973 ref_buf->buf->y_crop_height,
1974 cm->width, cm->height,
1975 cm->use_highbitdepth);
1977 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1978 ref_buf->buf->y_crop_width,
1979 ref_buf->buf->y_crop_height,
1980 cm->width, cm->height);
1985 #if CONFIG_VP9_HIGHBITDEPTH
1986 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1988 get_frame_new_buffer(cm)->color_space = cm->color_space;
1990 if (pbi->need_resync) {
1991 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1992 "Keyframe / intra-only frame required to reset decoder"
1996 if (!cm->error_resilient_mode) {
1997 cm->refresh_frame_context = vp9_rb_read_bit(rb);
1998 cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
2000 cm->refresh_frame_context = 0;
2001 cm->frame_parallel_decoding_mode = 1;
2004 // This flag will be overridden by the call to vp9_setup_past_independence
2005 // below, forcing the use of context 0 for those frame types.
2006 cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
2008 // Generate next_ref_frame_map.
2009 lock_buffer_pool(pool);
2010 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
2012 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
2013 ++frame_bufs[cm->new_fb_idx].ref_count;
2015 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2017 // Current thread holds the reference frame.
2018 if (cm->ref_frame_map[ref_index] >= 0)
2019 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2023 for (; ref_index < REF_FRAMES; ++ref_index) {
2024 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2025 // Current thread holds the reference frame.
2026 if (cm->ref_frame_map[ref_index] >= 0)
2027 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2029 unlock_buffer_pool(pool);
2030 pbi->hold_ref_buf = 1;
2032 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
2033 vp9_setup_past_independence(cm);
2035 setup_loopfilter(&cm->lf, rb);
2036 setup_quantization(cm, &pbi->mb, rb);
2037 setup_segmentation(&cm->seg, rb);
2038 setup_segmentation_dequant(cm);
2040 setup_tile_info(cm, rb);
2041 sz = vp9_rb_read_literal(rb, 16);
2044 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2045 "Invalid header size");
2050 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
2051 size_t partition_size) {
2052 VP9_COMMON *const cm = &pbi->common;
2053 MACROBLOCKD *const xd = &pbi->mb;
2054 FRAME_CONTEXT *const fc = cm->fc;
2058 if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
2059 pbi->decrypt_state))
2060 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2061 "Failed to allocate bool decoder 0");
2063 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
2064 if (cm->tx_mode == TX_MODE_SELECT)
2065 read_tx_mode_probs(&fc->tx_probs, &r);
2066 read_coef_probs(fc, cm->tx_mode, &r);
2068 for (k = 0; k < SKIP_CONTEXTS; ++k)
2069 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
2071 if (!frame_is_intra_only(cm)) {
2072 nmv_context *const nmvc = &fc->nmvc;
2075 read_inter_mode_probs(fc, &r);
2077 if (cm->interp_filter == SWITCHABLE)
2078 read_switchable_interp_probs(fc, &r);
2080 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
2081 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
2083 cm->reference_mode = read_frame_reference_mode(cm, &r);
2084 if (cm->reference_mode != SINGLE_REFERENCE)
2085 setup_compound_reference_mode(cm);
2086 read_frame_reference_mode_probs(cm, &r);
2088 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
2089 for (i = 0; i < INTRA_MODES - 1; ++i)
2090 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
2092 for (j = 0; j < PARTITION_CONTEXTS; ++j)
2093 for (i = 0; i < PARTITION_TYPES - 1; ++i)
2094 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
2096 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2099 return vp9_reader_has_error(&r);
2103 #define debug_check_frame_counts(cm) (void)0
2105 // Counts should only be incremented when frame_parallel_decoding_mode and
2106 // error_resilient_mode are disabled.
2107 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
2108 FRAME_COUNTS zero_counts;
2109 vp9_zero(zero_counts);
2110 assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
2111 assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
2112 sizeof(cm->counts.y_mode)));
2113 assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
2114 sizeof(cm->counts.uv_mode)));
2115 assert(!memcmp(cm->counts.partition, zero_counts.partition,
2116 sizeof(cm->counts.partition)));
2117 assert(!memcmp(cm->counts.coef, zero_counts.coef,
2118 sizeof(cm->counts.coef)));
2119 assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
2120 sizeof(cm->counts.eob_branch)));
2121 assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
2122 sizeof(cm->counts.switchable_interp)));
2123 assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
2124 sizeof(cm->counts.inter_mode)));
2125 assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
2126 sizeof(cm->counts.intra_inter)));
2127 assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
2128 sizeof(cm->counts.comp_inter)));
2129 assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
2130 sizeof(cm->counts.single_ref)));
2131 assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
2132 sizeof(cm->counts.comp_ref)));
2133 assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
2134 assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
2135 assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
2139 static struct vp9_read_bit_buffer *init_read_bit_buffer(
2141 struct vp9_read_bit_buffer *rb,
2142 const uint8_t *data,
2143 const uint8_t *data_end,
2144 uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2146 rb->error_handler = error_handler;
2147 rb->error_handler_data = &pbi->common;
2148 if (pbi->decrypt_cb) {
2149 const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
2150 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2151 rb->bit_buffer = clear_data;
2152 rb->bit_buffer_end = clear_data + n;
2154 rb->bit_buffer = data;
2155 rb->bit_buffer_end = data_end;
2160 //------------------------------------------------------------------------------
2162 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
2163 return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2164 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2165 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2168 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
2169 int *width, int *height) {
2170 *width = vp9_rb_read_literal(rb, 16) + 1;
2171 *height = vp9_rb_read_literal(rb, 16) + 1;
2174 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
2175 int profile = vp9_rb_read_bit(rb);
2176 profile |= vp9_rb_read_bit(rb) << 1;
2178 profile += vp9_rb_read_bit(rb);
2179 return (BITSTREAM_PROFILE) profile;
2182 void vp9_decode_frame(VP9Decoder *pbi,
2183 const uint8_t *data, const uint8_t *data_end,
2184 const uint8_t **p_data_end) {
2185 VP9_COMMON *const cm = &pbi->common;
2186 MACROBLOCKD *const xd = &pbi->mb;
2187 struct vp9_read_bit_buffer rb;
2188 int context_updated = 0;
2189 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2190 const size_t first_partition_size = read_uncompressed_header(pbi,
2191 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2192 const int tile_rows = 1 << cm->log2_tile_rows;
2193 const int tile_cols = 1 << cm->log2_tile_cols;
2194 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2195 xd->cur_buf = new_fb;
2197 if (!first_partition_size) {
2198 // showing a frame directly
2199 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2203 data += vp9_rb_bytes_read(&rb);
2204 if (!read_is_valid(data, first_partition_size, data_end))
2205 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2206 "Truncated packet or corrupt header length");
2208 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2209 cm->width == cm->last_width &&
2210 cm->height == cm->last_height &&
2211 !cm->last_intra_only &&
2212 cm->last_show_frame &&
2213 (cm->last_frame_type != KEY_FRAME);
2215 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2217 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2218 if (!cm->fc->initialized)
2219 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2220 "Uninitialized entropy context.");
2222 vp9_zero(cm->counts);
2225 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2226 if (new_fb->corrupted)
2227 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2228 "Decode failed. Frame data header is corrupted.");
2230 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2231 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2234 // If encoded in frame parallel mode, frame context is ready after decoding
2235 // the frame header.
2236 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2237 VPxWorker *const worker = pbi->frame_worker_owner;
2238 FrameWorkerData *const frame_worker_data = worker->data1;
2239 if (cm->refresh_frame_context) {
2240 context_updated = 1;
2241 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2243 vp9_frameworker_lock_stats(worker);
2244 pbi->cur_buf->row = -1;
2245 pbi->cur_buf->col = -1;
2246 frame_worker_data->frame_context_ready = 1;
2247 // Signal the main thread that context is ready.
2248 vp9_frameworker_signal_stats(worker);
2249 vp9_frameworker_unlock_stats(worker);
2252 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2253 // Multi-threaded tile decoder
2254 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2255 if (!xd->corrupted) {
2256 if (!cm->skip_loop_filter) {
2257 // If multiple threads are used to decode tiles, then we use those
2258 // threads to do parallel loopfiltering.
2259 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2260 cm->lf.filter_level, 0, 0, pbi->tile_workers,
2261 pbi->num_tile_workers, &pbi->lf_row_sync);
2264 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2265 "Decode failed. Frame data is corrupted.");
2269 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2272 if (!xd->corrupted) {
2273 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2274 vp9_adapt_coef_probs(cm);
2276 if (!frame_is_intra_only(cm)) {
2277 vp9_adapt_mode_probs(cm);
2278 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2281 debug_check_frame_counts(cm);
2284 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2285 "Decode failed. Frame data is corrupted.");
2288 // Non frame parallel update frame context here.
2289 if (cm->refresh_frame_context && !context_updated)
2290 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;