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, block >> (tx_size << 1),
396 dst, pd->dst.stride, dst, pd->dst.stride,
399 if (!mi->mbmi.skip) {
400 const TX_TYPE tx_type = (plane || xd->lossless) ?
401 DCT_DCT : intra_mode_to_tx_type_lookup[mode];
402 const scan_order *sc = (plane || xd->lossless) ?
403 &vp9_default_scan_orders[tx_size] : &vp9_scan_orders[tx_size][tx_type];
404 const int eob = vp9_decode_block_tokens(xd, plane, sc, x, y, tx_size,
405 args->r, args->seg_id);
406 inverse_transform_block_intra(xd, plane, tx_type, tx_size,
407 dst, pd->dst.stride, eob);
411 static int reconstruct_inter_block(MACROBLOCKD *const xd, vp9_reader *r,
412 MB_MODE_INFO *const mbmi, int plane,
413 int row, int col, TX_SIZE tx_size) {
414 struct macroblockd_plane *const pd = &xd->plane[plane];
415 const scan_order *sc = &vp9_default_scan_orders[tx_size];
416 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size, r,
419 inverse_transform_block_inter(xd, plane, tx_size,
420 &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
421 pd->dst.stride, eob);
425 static void build_mc_border(const uint8_t *src, int src_stride,
426 uint8_t *dst, int dst_stride,
427 int x, int y, int b_w, int b_h, int w, int h) {
428 // Get a pointer to the start of the real data for this row.
429 const uint8_t *ref_row = src - x - y * src_stride;
432 ref_row += (h - 1) * src_stride;
434 ref_row += y * src_stride;
438 int left = x < 0 ? -x : 0;
449 copy = b_w - left - right;
452 memset(dst, ref_row[0], left);
455 memcpy(dst + left, ref_row + x + left, copy);
458 memset(dst + left + copy, ref_row[w - 1], right);
464 ref_row += src_stride;
468 #if CONFIG_VP9_HIGHBITDEPTH
469 static void high_build_mc_border(const uint8_t *src8, int src_stride,
470 uint16_t *dst, int dst_stride,
471 int x, int y, int b_w, int b_h,
473 // Get a pointer to the start of the real data for this row.
474 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
475 const uint16_t *ref_row = src - x - y * src_stride;
478 ref_row += (h - 1) * src_stride;
480 ref_row += y * src_stride;
484 int left = x < 0 ? -x : 0;
495 copy = b_w - left - right;
498 vpx_memset16(dst, ref_row[0], left);
501 memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
504 vpx_memset16(dst + left + copy, ref_row[w - 1], right);
510 ref_row += src_stride;
513 #endif // CONFIG_VP9_HIGHBITDEPTH
515 #if CONFIG_VP9_HIGHBITDEPTH
516 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
517 int x0, int y0, int b_w, int b_h,
518 int frame_width, int frame_height,
520 uint8_t *const dst, int dst_buf_stride,
521 int subpel_x, int subpel_y,
522 const InterpKernel *kernel,
523 const struct scale_factors *sf,
525 int w, int h, int ref, int xs, int ys) {
526 DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
527 const uint8_t *buf_ptr;
529 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
530 high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w,
531 x0, y0, b_w, b_h, frame_width, frame_height);
532 buf_ptr = CONVERT_TO_BYTEPTR(mc_buf_high) + border_offset;
534 build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w,
535 x0, y0, b_w, b_h, frame_width, frame_height);
536 buf_ptr = ((uint8_t *)mc_buf_high) + border_offset;
539 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
540 high_inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
541 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
543 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
544 subpel_y, sf, w, h, ref, kernel, xs, ys);
548 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
549 int x0, int y0, int b_w, int b_h,
550 int frame_width, int frame_height,
552 uint8_t *const dst, int dst_buf_stride,
553 int subpel_x, int subpel_y,
554 const InterpKernel *kernel,
555 const struct scale_factors *sf,
556 int w, int h, int ref, int xs, int ys) {
557 DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
558 const uint8_t *buf_ptr;
560 build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w,
561 x0, y0, b_w, b_h, frame_width, frame_height);
562 buf_ptr = mc_buf + border_offset;
564 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
565 subpel_y, sf, w, h, ref, kernel, xs, ys);
567 #endif // CONFIG_VP9_HIGHBITDEPTH
569 static void dec_build_inter_predictors(VP9Decoder *const pbi, MACROBLOCKD *xd,
570 int plane, int bw, int bh, int x,
571 int y, int w, int h, int mi_x, int mi_y,
572 const InterpKernel *kernel,
573 const struct scale_factors *sf,
574 struct buf_2d *pre_buf,
575 struct buf_2d *dst_buf, const MV* mv,
576 RefCntBuffer *ref_frame_buf,
577 int is_scaled, int ref) {
578 struct macroblockd_plane *const pd = &xd->plane[plane];
579 uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
581 int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height,
582 buf_stride, subpel_x, subpel_y;
583 uint8_t *ref_frame, *buf_ptr;
585 // Get reference frame pointer, width and height.
587 frame_width = ref_frame_buf->buf.y_crop_width;
588 frame_height = ref_frame_buf->buf.y_crop_height;
589 ref_frame = ref_frame_buf->buf.y_buffer;
591 frame_width = ref_frame_buf->buf.uv_crop_width;
592 frame_height = ref_frame_buf->buf.uv_crop_height;
593 ref_frame = plane == 1 ? ref_frame_buf->buf.u_buffer
594 : ref_frame_buf->buf.v_buffer;
598 const MV mv_q4 = clamp_mv_to_umv_border_sb(xd, mv, bw, bh,
601 // Co-ordinate of containing block to pixel precision.
602 int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
603 int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
605 // Co-ordinate of the block to 1/16th pixel precision.
606 x0_16 = (x_start + x) << SUBPEL_BITS;
607 y0_16 = (y_start + y) << SUBPEL_BITS;
609 // Co-ordinate of current block in reference frame
610 // to 1/16th pixel precision.
611 x0_16 = sf->scale_value_x(x0_16, sf);
612 y0_16 = sf->scale_value_y(y0_16, sf);
614 // Map the top left corner of the block into the reference frame.
615 x0 = sf->scale_value_x(x_start + x, sf);
616 y0 = sf->scale_value_y(y_start + y, sf);
618 // Scale the MV and incorporate the sub-pixel offset of the block
619 // in the reference frame.
620 scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
624 // Co-ordinate of containing block to pixel precision.
625 x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
626 y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
628 // Co-ordinate of the block to 1/16th pixel precision.
629 x0_16 = x0 << SUBPEL_BITS;
630 y0_16 = y0 << SUBPEL_BITS;
632 scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
633 scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
636 subpel_x = scaled_mv.col & SUBPEL_MASK;
637 subpel_y = scaled_mv.row & SUBPEL_MASK;
639 // Calculate the top left corner of the best matching block in the
641 x0 += scaled_mv.col >> SUBPEL_BITS;
642 y0 += scaled_mv.row >> SUBPEL_BITS;
643 x0_16 += scaled_mv.col;
644 y0_16 += scaled_mv.row;
646 // Get reference block pointer.
647 buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
648 buf_stride = pre_buf->stride;
650 // Do border extension if there is motion or the
651 // width/height is not a multiple of 8 pixels.
652 if (is_scaled || scaled_mv.col || scaled_mv.row ||
653 (frame_width & 0x7) || (frame_height & 0x7)) {
654 int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
656 // Get reference block bottom right horizontal coordinate.
657 int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
658 int x_pad = 0, y_pad = 0;
660 if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
661 x0 -= VP9_INTERP_EXTEND - 1;
662 x1 += VP9_INTERP_EXTEND;
666 if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
667 y0 -= VP9_INTERP_EXTEND - 1;
668 y1 += VP9_INTERP_EXTEND;
672 // Wait until reference block is ready. Pad 7 more pixels as last 7
673 // pixels of each superblock row can be changed by next superblock row.
674 if (pbi->frame_parallel_decode)
675 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
676 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
678 // Skip border extension if block is inside the frame.
679 if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
680 y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
681 // Extend the border.
682 const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
683 const int b_w = x1 - x0 + 1;
684 const int b_h = y1 - y0 + 1;
685 const int border_offset = y_pad * 3 * b_w + x_pad * 3;
687 extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h,
688 frame_width, frame_height, border_offset,
689 dst, dst_buf->stride,
692 #if CONFIG_VP9_HIGHBITDEPTH
699 // Wait until reference block is ready. Pad 7 more pixels as last 7
700 // pixels of each superblock row can be changed by next superblock row.
701 if (pbi->frame_parallel_decode) {
702 const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
703 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
704 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
707 #if CONFIG_VP9_HIGHBITDEPTH
708 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
709 high_inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
710 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
712 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
713 subpel_y, sf, w, h, ref, kernel, xs, ys);
716 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
717 subpel_y, sf, w, h, ref, kernel, xs, ys);
718 #endif // CONFIG_VP9_HIGHBITDEPTH
721 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
723 int mi_row, int mi_col) {
725 const int mi_x = mi_col * MI_SIZE;
726 const int mi_y = mi_row * MI_SIZE;
727 const MODE_INFO *mi = xd->mi[0];
728 const InterpKernel *kernel = vp9_filter_kernels[mi->mbmi.interp_filter];
729 const BLOCK_SIZE sb_type = mi->mbmi.sb_type;
730 const int is_compound = has_second_ref(&mi->mbmi);
732 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
733 struct macroblockd_plane *const pd = &xd->plane[plane];
734 struct buf_2d *const dst_buf = &pd->dst;
735 const int num_4x4_w = pd->n4_w;
736 const int num_4x4_h = pd->n4_h;
738 const int n4w_x4 = 4 * num_4x4_w;
739 const int n4h_x4 = 4 * num_4x4_h;
742 for (ref = 0; ref < 1 + is_compound; ++ref) {
743 const struct scale_factors *const sf = &xd->block_refs[ref]->sf;
744 struct buf_2d *const pre_buf = &pd->pre[ref];
745 const int idx = xd->block_refs[ref]->idx;
746 BufferPool *const pool = pbi->common.buffer_pool;
747 RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
748 const int is_scaled = vp9_is_scaled(sf);
750 if (sb_type < BLOCK_8X8) {
752 for (y = 0; y < num_4x4_h; ++y) {
753 for (x = 0; x < num_4x4_w; ++x) {
754 const MV mv = average_split_mvs(pd, mi, ref, i++);
755 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
756 4 * x, 4 * y, 4, 4, mi_x, mi_y, kernel,
757 sf, pre_buf, dst_buf, &mv,
758 ref_frame_buf, is_scaled, ref);
762 const MV mv = mi->mbmi.mv[ref].as_mv;
763 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
764 0, 0, n4w_x4, n4h_x4, mi_x, mi_y, kernel,
765 sf, pre_buf, dst_buf, &mv, ref_frame_buf,
772 static INLINE TX_SIZE dec_get_uv_tx_size(const MB_MODE_INFO *mbmi,
773 int n4_wl, int n4_hl) {
774 // get minimum log2 num4x4s dimension
775 const int x = MIN(n4_wl, n4_hl);
776 return MIN(mbmi->tx_size, x);
779 // TODO(slavarnway): Eliminate the foreach_ functions in future commits.
780 // NOTE: Jingning removed the foreach_ for recon inter in a previous commit.
782 typedef void (*dec_foreach_transformed_block_visitor)(int plane, int block,
786 static void dec_foreach_transformed_block_in_plane(
787 const MACROBLOCKD *const xd,
789 dec_foreach_transformed_block_visitor visit, void *arg) {
790 const struct macroblockd_plane *const pd = &xd->plane[plane];
791 const MB_MODE_INFO* mbmi = &xd->mi[0]->mbmi;
792 // block and transform sizes, in number of 4x4 blocks log 2 ("*_b")
793 // 4x4=0, 8x8=2, 16x16=4, 32x32=6, 64x64=8
794 // transform size varies per plane, look it up in a common way.
795 const TX_SIZE tx_size =
796 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
798 const int num_4x4_w = pd->n4_w;
799 const int num_4x4_h = pd->n4_h;
800 const int step = 1 << (tx_size << 1);
803 // If mb_to_right_edge is < 0 we are in a situation in which
804 // the current block size extends into the UMV and we won't
805 // visit the sub blocks that are wholly within the UMV.
806 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ? 0 :
807 xd->mb_to_right_edge >> (5 + pd->subsampling_x));
808 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ? 0 :
809 xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
811 // Keep track of the row and column of the blocks we use so that we know
812 // if we are in the unrestricted motion border.
813 for (r = 0; r < max_blocks_high; r += (1 << tx_size)) {
814 for (c = 0; c < num_4x4_w; c += (1 << tx_size)) {
815 // Skip visiting the sub blocks that are wholly within the UMV.
816 if (c < max_blocks_wide)
817 visit(plane, i, tx_size, arg);
823 static void dec_foreach_transformed_block(const MACROBLOCKD* const xd,
824 dec_foreach_transformed_block_visitor visit, void *arg) {
827 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
828 dec_foreach_transformed_block_in_plane(xd, plane, visit, arg);
831 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
833 for (i = 0; i < MAX_MB_PLANE; i++) {
834 struct macroblockd_plane *const pd = &xd->plane[i];
835 memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
836 memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
840 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
843 for (i = 0; i < MAX_MB_PLANE; i++) {
844 xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
845 xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
846 xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
847 xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
851 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
852 BLOCK_SIZE bsize, int mi_row, int mi_col,
853 int bw, int bh, int x_mis, int y_mis,
855 const int offset = mi_row * cm->mi_stride + mi_col;
857 const TileInfo *const tile = &xd->tile;
859 xd->mi = cm->mi_grid_visible + offset;
860 xd->mi[0] = &cm->mi[offset];
861 // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
862 // passing bsize from decode_partition().
863 xd->mi[0]->mbmi.sb_type = bsize;
864 for (y = 0; y < y_mis; ++y)
865 for (x = !y; x < x_mis; ++x) {
866 xd->mi[y * cm->mi_stride + x] = xd->mi[0];
869 set_plane_n4(xd, bw, bh, bwl, bhl);
871 set_skip_context(xd, mi_row, mi_col);
873 // Distance of Mb to the various image edges. These are specified to 8th pel
874 // as they are always compared to values that are in 1/8th pel units
875 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
877 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
878 return &xd->mi[0]->mbmi;
881 static void decode_block(VP9Decoder *const pbi, MACROBLOCKD *const xd,
882 int mi_row, int mi_col,
883 vp9_reader *r, BLOCK_SIZE bsize,
885 VP9_COMMON *const cm = &pbi->common;
886 const int less8x8 = bsize < BLOCK_8X8;
887 const int bw = 1 << (bwl - 1);
888 const int bh = 1 << (bhl - 1);
889 const int x_mis = MIN(bw, cm->mi_cols - mi_col);
890 const int y_mis = MIN(bh, cm->mi_rows - mi_row);
892 MB_MODE_INFO *mbmi = set_offsets(cm, xd, bsize, mi_row, mi_col,
893 bw, bh, x_mis, y_mis, bwl, bhl);
895 if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
896 const BLOCK_SIZE uv_subsize =
897 ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
898 if (uv_subsize == BLOCK_INVALID)
899 vpx_internal_error(xd->error_info,
900 VPX_CODEC_CORRUPT_FRAME, "Invalid block size.");
903 vp9_read_mode_info(pbi, xd, mi_row, mi_col, r, x_mis, y_mis);
906 dec_reset_skip_context(xd);
909 if (!is_inter_block(mbmi)) {
910 struct intra_args arg = {xd, r, mbmi->segment_id};
911 dec_foreach_transformed_block(xd,
912 predict_and_reconstruct_intra_block, &arg);
915 dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col);
922 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
923 const struct macroblockd_plane *const pd = &xd->plane[plane];
924 const TX_SIZE tx_size =
925 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
927 const int num_4x4_w = pd->n4_w;
928 const int num_4x4_h = pd->n4_h;
929 const int step = (1 << tx_size);
931 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
932 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
933 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
934 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
936 for (row = 0; row < max_blocks_high; row += step)
937 for (col = 0; col < max_blocks_wide; col += step)
938 eobtotal += reconstruct_inter_block(xd, r, mbmi, plane, row, col,
942 if (!less8x8 && eobtotal == 0)
943 mbmi->skip = 1; // skip loopfilter
947 xd->corrupted |= vp9_reader_has_error(r);
950 static INLINE int dec_partition_plane_context(const MACROBLOCKD *xd,
951 int mi_row, int mi_col,
953 const PARTITION_CONTEXT *above_ctx = xd->above_seg_context + mi_col;
954 const PARTITION_CONTEXT *left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
955 int above = (*above_ctx >> bsl) & 1 , left = (*left_ctx >> bsl) & 1;
959 return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
962 static INLINE void dec_update_partition_context(MACROBLOCKD *xd,
963 int mi_row, int mi_col,
966 PARTITION_CONTEXT *const above_ctx = xd->above_seg_context + mi_col;
967 PARTITION_CONTEXT *const left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
969 // update the partition context at the end notes. set partition bits
970 // of block sizes larger than the current one to be one, and partition
971 // bits of smaller block sizes to be zero.
972 memset(above_ctx, partition_context_lookup[subsize].above, bw);
973 memset(left_ctx, partition_context_lookup[subsize].left, bw);
976 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
978 int has_rows, int has_cols, int bsl) {
979 const int ctx = dec_partition_plane_context(xd, mi_row, mi_col, bsl);
980 const vp9_prob *const probs = get_partition_probs(xd, ctx);
981 FRAME_COUNTS *counts = xd->counts;
984 if (has_rows && has_cols)
985 p = (PARTITION_TYPE)vp9_read_tree(r, vp9_partition_tree, probs);
986 else if (!has_rows && has_cols)
987 p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
988 else if (has_rows && !has_cols)
989 p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
994 ++counts->partition[ctx][p];
999 // TODO(slavarnway): eliminate bsize and subsize in future commits
1000 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
1001 int mi_row, int mi_col,
1002 vp9_reader* r, BLOCK_SIZE bsize, int n4x4_l2) {
1003 VP9_COMMON *const cm = &pbi->common;
1004 const int n8x8_l2 = n4x4_l2 - 1;
1005 const int num_8x8_wh = 1 << n8x8_l2;
1006 const int hbs = num_8x8_wh >> 1;
1007 PARTITION_TYPE partition;
1009 const int has_rows = (mi_row + hbs) < cm->mi_rows;
1010 const int has_cols = (mi_col + hbs) < cm->mi_cols;
1012 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1015 partition = read_partition(xd, mi_row, mi_col, r, has_rows, has_cols,
1017 subsize = subsize_lookup[partition][bsize]; // get_subsize(bsize, partition);
1019 // calculate bmode block dimensions (log 2)
1020 xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
1021 xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
1022 decode_block(pbi, xd, mi_row, mi_col, r, subsize, 1, 1);
1024 switch (partition) {
1025 case PARTITION_NONE:
1026 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n4x4_l2);
1028 case PARTITION_HORZ:
1029 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n8x8_l2);
1031 decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize, n4x4_l2,
1034 case PARTITION_VERT:
1035 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2, n4x4_l2);
1037 decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2,
1040 case PARTITION_SPLIT:
1041 decode_partition(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2);
1042 decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2);
1043 decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize, n8x8_l2);
1044 decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize,
1048 assert(0 && "Invalid partition type");
1052 // update partition context
1053 if (bsize >= BLOCK_8X8 &&
1054 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
1055 dec_update_partition_context(xd, mi_row, mi_col, subsize, num_8x8_wh);
1058 static void setup_token_decoder(const uint8_t *data,
1059 const uint8_t *data_end,
1061 struct vpx_internal_error_info *error_info,
1063 vpx_decrypt_cb decrypt_cb,
1064 void *decrypt_state) {
1065 // Validate the calculated partition length. If the buffer
1066 // described by the partition can't be fully read, then restrict
1067 // it to the portion that can be (for EC mode) or throw an error.
1068 if (!read_is_valid(data, read_size, data_end))
1069 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1070 "Truncated packet or corrupt tile length");
1072 if (vp9_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
1073 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
1074 "Failed to allocate bool decoder %d", 1);
1077 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
1081 if (vp9_read_bit(r))
1082 for (i = 0; i < PLANE_TYPES; ++i)
1083 for (j = 0; j < REF_TYPES; ++j)
1084 for (k = 0; k < COEF_BANDS; ++k)
1085 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1086 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
1087 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
1090 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
1092 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1094 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1095 read_coef_probs_common(fc->coef_probs[tx_size], r);
1098 static void setup_segmentation(struct segmentation *seg,
1099 struct vp9_read_bit_buffer *rb) {
1102 seg->update_map = 0;
1103 seg->update_data = 0;
1105 seg->enabled = vp9_rb_read_bit(rb);
1109 // Segmentation map update
1110 seg->update_map = vp9_rb_read_bit(rb);
1111 if (seg->update_map) {
1112 for (i = 0; i < SEG_TREE_PROBS; i++)
1113 seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1116 seg->temporal_update = vp9_rb_read_bit(rb);
1117 if (seg->temporal_update) {
1118 for (i = 0; i < PREDICTION_PROBS; i++)
1119 seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1122 for (i = 0; i < PREDICTION_PROBS; i++)
1123 seg->pred_probs[i] = MAX_PROB;
1127 // Segmentation data update
1128 seg->update_data = vp9_rb_read_bit(rb);
1129 if (seg->update_data) {
1130 seg->abs_delta = vp9_rb_read_bit(rb);
1132 vp9_clearall_segfeatures(seg);
1134 for (i = 0; i < MAX_SEGMENTS; i++) {
1135 for (j = 0; j < SEG_LVL_MAX; j++) {
1137 const int feature_enabled = vp9_rb_read_bit(rb);
1138 if (feature_enabled) {
1139 vp9_enable_segfeature(seg, i, j);
1140 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1141 if (vp9_is_segfeature_signed(j))
1142 data = vp9_rb_read_bit(rb) ? -data : data;
1144 vp9_set_segdata(seg, i, j, data);
1150 static void setup_loopfilter(struct loopfilter *lf,
1151 struct vp9_read_bit_buffer *rb) {
1152 lf->filter_level = vp9_rb_read_literal(rb, 6);
1153 lf->sharpness_level = vp9_rb_read_literal(rb, 3);
1155 // Read in loop filter deltas applied at the MB level based on mode or ref
1157 lf->mode_ref_delta_update = 0;
1159 lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
1160 if (lf->mode_ref_delta_enabled) {
1161 lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
1162 if (lf->mode_ref_delta_update) {
1165 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1166 if (vp9_rb_read_bit(rb))
1167 lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1169 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1170 if (vp9_rb_read_bit(rb))
1171 lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1176 static INLINE int read_delta_q(struct vp9_read_bit_buffer *rb) {
1177 return vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
1180 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1181 struct vp9_read_bit_buffer *rb) {
1182 cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
1183 cm->y_dc_delta_q = read_delta_q(rb);
1184 cm->uv_dc_delta_q = read_delta_q(rb);
1185 cm->uv_ac_delta_q = read_delta_q(rb);
1186 cm->dequant_bit_depth = cm->bit_depth;
1187 xd->lossless = cm->base_qindex == 0 &&
1188 cm->y_dc_delta_q == 0 &&
1189 cm->uv_dc_delta_q == 0 &&
1190 cm->uv_ac_delta_q == 0;
1192 #if CONFIG_VP9_HIGHBITDEPTH
1193 xd->bd = (int)cm->bit_depth;
1197 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1198 // Build y/uv dequant values based on segmentation.
1199 if (cm->seg.enabled) {
1201 for (i = 0; i < MAX_SEGMENTS; ++i) {
1202 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1203 cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
1205 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1206 cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1208 cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1212 const int qindex = cm->base_qindex;
1213 // When segmentation is disabled, only the first value is used. The
1214 // remaining are don't cares.
1215 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1216 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1217 cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1219 cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1224 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
1225 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1229 return vp9_rb_read_bit(rb) ? SWITCHABLE
1230 : literal_to_filter[vp9_rb_read_literal(rb, 2)];
1233 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1234 cm->display_width = cm->width;
1235 cm->display_height = cm->height;
1236 if (vp9_rb_read_bit(rb))
1237 vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
1240 static void resize_mv_buffer(VP9_COMMON *cm) {
1241 vpx_free(cm->cur_frame->mvs);
1242 cm->cur_frame->mi_rows = cm->mi_rows;
1243 cm->cur_frame->mi_cols = cm->mi_cols;
1244 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1245 sizeof(*cm->cur_frame->mvs));
1248 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1249 #if CONFIG_SIZE_LIMIT
1250 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1251 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1252 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1253 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1255 if (cm->width != width || cm->height != height) {
1256 const int new_mi_rows =
1257 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1258 const int new_mi_cols =
1259 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1261 // Allocations in vp9_alloc_context_buffers() depend on individual
1262 // dimensions as well as the overall size.
1263 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1264 if (vp9_alloc_context_buffers(cm, width, height))
1265 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1266 "Failed to allocate context buffers");
1268 vp9_set_mb_mi(cm, width, height);
1270 vp9_init_context_buffers(cm);
1272 cm->height = height;
1274 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1275 cm->mi_cols > cm->cur_frame->mi_cols) {
1276 resize_mv_buffer(cm);
1280 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1282 BufferPool *const pool = cm->buffer_pool;
1283 vp9_read_frame_size(rb, &width, &height);
1284 resize_context_buffers(cm, width, height);
1285 setup_display_size(cm, rb);
1287 lock_buffer_pool(pool);
1288 if (vp9_realloc_frame_buffer(
1289 get_frame_new_buffer(cm), cm->width, cm->height,
1290 cm->subsampling_x, cm->subsampling_y,
1291 #if CONFIG_VP9_HIGHBITDEPTH
1292 cm->use_highbitdepth,
1294 VP9_DEC_BORDER_IN_PIXELS,
1296 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1298 unlock_buffer_pool(pool);
1299 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1300 "Failed to allocate frame buffer");
1302 unlock_buffer_pool(pool);
1304 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1305 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1306 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1307 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1310 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1311 int ref_xss, int ref_yss,
1312 vpx_bit_depth_t this_bit_depth,
1313 int this_xss, int this_yss) {
1314 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1315 ref_yss == this_yss;
1318 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1319 struct vp9_read_bit_buffer *rb) {
1322 int has_valid_ref_frame = 0;
1323 BufferPool *const pool = cm->buffer_pool;
1324 for (i = 0; i < REFS_PER_FRAME; ++i) {
1325 if (vp9_rb_read_bit(rb)) {
1326 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1327 width = buf->y_crop_width;
1328 height = buf->y_crop_height;
1335 vp9_read_frame_size(rb, &width, &height);
1337 if (width <= 0 || height <= 0)
1338 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1339 "Invalid frame size");
1341 // Check to make sure at least one of frames that this frame references
1342 // has valid dimensions.
1343 for (i = 0; i < REFS_PER_FRAME; ++i) {
1344 RefBuffer *const ref_frame = &cm->frame_refs[i];
1345 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1346 ref_frame->buf->y_crop_height,
1349 if (!has_valid_ref_frame)
1350 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1351 "Referenced frame has invalid size");
1352 for (i = 0; i < REFS_PER_FRAME; ++i) {
1353 RefBuffer *const ref_frame = &cm->frame_refs[i];
1354 if (!valid_ref_frame_img_fmt(
1355 ref_frame->buf->bit_depth,
1356 ref_frame->buf->subsampling_x,
1357 ref_frame->buf->subsampling_y,
1361 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1362 "Referenced frame has incompatible color format");
1365 resize_context_buffers(cm, width, height);
1366 setup_display_size(cm, rb);
1368 lock_buffer_pool(pool);
1369 if (vp9_realloc_frame_buffer(
1370 get_frame_new_buffer(cm), cm->width, cm->height,
1371 cm->subsampling_x, cm->subsampling_y,
1372 #if CONFIG_VP9_HIGHBITDEPTH
1373 cm->use_highbitdepth,
1375 VP9_DEC_BORDER_IN_PIXELS,
1377 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1379 unlock_buffer_pool(pool);
1380 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1381 "Failed to allocate frame buffer");
1383 unlock_buffer_pool(pool);
1385 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1386 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1387 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1388 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1391 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1392 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1393 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1396 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1397 cm->log2_tile_cols = min_log2_tile_cols;
1398 while (max_ones-- && vp9_rb_read_bit(rb))
1399 cm->log2_tile_cols++;
1401 if (cm->log2_tile_cols > 6)
1402 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1403 "Invalid number of tile columns");
1406 cm->log2_tile_rows = vp9_rb_read_bit(rb);
1407 if (cm->log2_tile_rows)
1408 cm->log2_tile_rows += vp9_rb_read_bit(rb);
1411 typedef struct TileBuffer {
1412 const uint8_t *data;
1414 int col; // only used with multi-threaded decoding
1417 // Reads the next tile returning its size and adjusting '*data' accordingly
1418 // based on 'is_last'.
1419 static void get_tile_buffer(const uint8_t *const data_end,
1421 struct vpx_internal_error_info *error_info,
1422 const uint8_t **data,
1423 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1428 if (!read_is_valid(*data, 4, data_end))
1429 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1430 "Truncated packet or corrupt tile length");
1434 decrypt_cb(decrypt_state, *data, be_data, 4);
1435 size = mem_get_be32(be_data);
1437 size = mem_get_be32(*data);
1441 if (size > (size_t)(data_end - *data))
1442 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1443 "Truncated packet or corrupt tile size");
1445 size = data_end - *data;
1454 static void get_tile_buffers(VP9Decoder *pbi,
1455 const uint8_t *data, const uint8_t *data_end,
1456 int tile_cols, int tile_rows,
1457 TileBuffer (*tile_buffers)[1 << 6]) {
1460 for (r = 0; r < tile_rows; ++r) {
1461 for (c = 0; c < tile_cols; ++c) {
1462 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1463 TileBuffer *const buf = &tile_buffers[r][c];
1465 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1466 pbi->decrypt_cb, pbi->decrypt_state, buf);
1471 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1472 const uint8_t *data,
1473 const uint8_t *data_end) {
1474 VP9_COMMON *const cm = &pbi->common;
1475 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1476 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1477 const int tile_cols = 1 << cm->log2_tile_cols;
1478 const int tile_rows = 1 << cm->log2_tile_rows;
1479 TileBuffer tile_buffers[4][1 << 6];
1480 int tile_row, tile_col;
1482 TileData *tile_data = NULL;
1484 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1485 pbi->lf_worker.data1 == NULL) {
1486 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1487 vpx_memalign(32, sizeof(LFWorkerData)));
1488 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1489 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1490 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1491 "Loop filter thread creation failed");
1495 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1496 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1497 // Be sure to sync as we might be resuming after a failed frame decode.
1498 winterface->sync(&pbi->lf_worker);
1499 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1503 assert(tile_rows <= 4);
1504 assert(tile_cols <= (1 << 6));
1506 // Note: this memset assumes above_context[0], [1] and [2]
1507 // are allocated as part of the same buffer.
1508 memset(cm->above_context, 0,
1509 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1511 memset(cm->above_seg_context, 0,
1512 sizeof(*cm->above_seg_context) * aligned_cols);
1514 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1516 if (pbi->tile_data == NULL ||
1517 (tile_cols * tile_rows) != pbi->total_tiles) {
1518 vpx_free(pbi->tile_data);
1522 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1523 pbi->total_tiles = tile_rows * tile_cols;
1526 // Load all tile information into tile_data.
1527 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1528 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1529 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1530 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1532 tile_data->xd = pbi->mb;
1533 tile_data->xd.corrupted = 0;
1534 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1536 vp9_zero(tile_data->dqcoeff);
1537 vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1538 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1539 &tile_data->bit_reader, pbi->decrypt_cb,
1540 pbi->decrypt_state);
1541 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1545 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1547 vp9_tile_set_row(&tile, cm, tile_row);
1548 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1549 mi_row += MI_BLOCK_SIZE) {
1550 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1551 const int col = pbi->inv_tile_order ?
1552 tile_cols - tile_col - 1 : tile_col;
1553 tile_data = pbi->tile_data + tile_cols * tile_row + col;
1554 vp9_tile_set_col(&tile, tile_data->cm, col);
1555 vp9_zero(tile_data->xd.left_context);
1556 vp9_zero(tile_data->xd.left_seg_context);
1557 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1558 mi_col += MI_BLOCK_SIZE) {
1559 decode_partition(pbi, &tile_data->xd, mi_row,
1560 mi_col, &tile_data->bit_reader, BLOCK_64X64, 4);
1562 pbi->mb.corrupted |= tile_data->xd.corrupted;
1563 if (pbi->mb.corrupted)
1564 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1565 "Failed to decode tile data");
1567 // Loopfilter one row.
1568 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1569 const int lf_start = mi_row - MI_BLOCK_SIZE;
1570 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1572 // delay the loopfilter by 1 macroblock row.
1573 if (lf_start < 0) continue;
1575 // decoding has completed: finish up the loop filter in this thread.
1576 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1578 winterface->sync(&pbi->lf_worker);
1579 lf_data->start = lf_start;
1580 lf_data->stop = mi_row;
1581 if (pbi->max_threads > 1) {
1582 winterface->launch(&pbi->lf_worker);
1584 winterface->execute(&pbi->lf_worker);
1587 // After loopfiltering, the last 7 row pixels in each superblock row may
1588 // still be changed by the longest loopfilter of the next superblock
1590 if (pbi->frame_parallel_decode)
1591 vp9_frameworker_broadcast(pbi->cur_buf,
1592 mi_row << MI_BLOCK_SIZE_LOG2);
1596 // Loopfilter remaining rows in the frame.
1597 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1598 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1599 winterface->sync(&pbi->lf_worker);
1600 lf_data->start = lf_data->stop;
1601 lf_data->stop = cm->mi_rows;
1602 winterface->execute(&pbi->lf_worker);
1605 // Get last tile data.
1606 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1608 if (pbi->frame_parallel_decode)
1609 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1610 return vp9_reader_find_end(&tile_data->bit_reader);
1613 static int tile_worker_hook(TileWorkerData *const tile_data,
1614 const TileInfo *const tile) {
1617 if (setjmp(tile_data->error_info.jmp)) {
1618 tile_data->error_info.setjmp = 0;
1619 tile_data->xd.corrupted = 1;
1623 tile_data->error_info.setjmp = 1;
1624 tile_data->xd.error_info = &tile_data->error_info;
1626 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1627 mi_row += MI_BLOCK_SIZE) {
1628 vp9_zero(tile_data->xd.left_context);
1629 vp9_zero(tile_data->xd.left_seg_context);
1630 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1631 mi_col += MI_BLOCK_SIZE) {
1632 decode_partition(tile_data->pbi, &tile_data->xd,
1633 mi_row, mi_col, &tile_data->bit_reader,
1637 return !tile_data->xd.corrupted;
1640 // sorts in descending order
1641 static int compare_tile_buffers(const void *a, const void *b) {
1642 const TileBuffer *const buf1 = (const TileBuffer*)a;
1643 const TileBuffer *const buf2 = (const TileBuffer*)b;
1644 return (int)(buf2->size - buf1->size);
1647 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1648 const uint8_t *data,
1649 const uint8_t *data_end) {
1650 VP9_COMMON *const cm = &pbi->common;
1651 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1652 const uint8_t *bit_reader_end = NULL;
1653 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1654 const int tile_cols = 1 << cm->log2_tile_cols;
1655 const int tile_rows = 1 << cm->log2_tile_rows;
1656 const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1657 TileBuffer tile_buffers[1][1 << 6];
1659 int final_worker = -1;
1661 assert(tile_cols <= (1 << 6));
1662 assert(tile_rows == 1);
1665 // TODO(jzern): See if we can remove the restriction of passing in max
1666 // threads to the decoder.
1667 if (pbi->num_tile_workers == 0) {
1668 const int num_threads = pbi->max_threads & ~1;
1670 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1671 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1672 // Ensure tile data offsets will be properly aligned. This may fail on
1673 // platforms without DECLARE_ALIGNED().
1674 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1675 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1676 vpx_memalign(32, num_threads *
1677 sizeof(*pbi->tile_worker_data)));
1678 CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1679 vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1680 for (i = 0; i < num_threads; ++i) {
1681 VPxWorker *const worker = &pbi->tile_workers[i];
1682 ++pbi->num_tile_workers;
1684 winterface->init(worker);
1685 if (i < num_threads - 1 && !winterface->reset(worker)) {
1686 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1687 "Tile decoder thread creation failed");
1692 // Reset tile decoding hook
1693 for (n = 0; n < num_workers; ++n) {
1694 VPxWorker *const worker = &pbi->tile_workers[n];
1695 winterface->sync(worker);
1696 worker->hook = (VPxWorkerHook)tile_worker_hook;
1697 worker->data1 = &pbi->tile_worker_data[n];
1698 worker->data2 = &pbi->tile_worker_info[n];
1701 // Note: this memset assumes above_context[0], [1] and [2]
1702 // are allocated as part of the same buffer.
1703 memset(cm->above_context, 0,
1704 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1705 memset(cm->above_seg_context, 0,
1706 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1708 // Load tile data into tile_buffers
1709 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1711 // Sort the buffers based on size in descending order.
1712 qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1713 compare_tile_buffers);
1715 // Rearrange the tile buffers such that per-tile group the largest, and
1716 // presumably the most difficult, tile will be decoded in the main thread.
1717 // This should help minimize the number of instances where the main thread is
1718 // waiting for a worker to complete.
1720 int group_start = 0;
1721 while (group_start < tile_cols) {
1722 const TileBuffer largest = tile_buffers[0][group_start];
1723 const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1724 memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1725 (group_end - group_start) * sizeof(tile_buffers[0][0]));
1726 tile_buffers[0][group_end] = largest;
1727 group_start = group_end + 1;
1731 // Initialize thread frame counts.
1732 if (!cm->frame_parallel_decoding_mode) {
1735 for (i = 0; i < num_workers; ++i) {
1736 TileWorkerData *const tile_data =
1737 (TileWorkerData*)pbi->tile_workers[i].data1;
1738 vp9_zero(tile_data->counts);
1743 while (n < tile_cols) {
1745 for (i = 0; i < num_workers && n < tile_cols; ++i) {
1746 VPxWorker *const worker = &pbi->tile_workers[i];
1747 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1748 TileInfo *const tile = (TileInfo*)worker->data2;
1749 TileBuffer *const buf = &tile_buffers[0][n];
1751 tile_data->pbi = pbi;
1752 tile_data->xd = pbi->mb;
1753 tile_data->xd.corrupted = 0;
1754 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1755 0 : &tile_data->counts;
1756 vp9_zero(tile_data->dqcoeff);
1757 vp9_tile_init(tile, cm, 0, buf->col);
1758 vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1759 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1760 &tile_data->bit_reader, pbi->decrypt_cb,
1761 pbi->decrypt_state);
1762 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1764 worker->had_error = 0;
1765 if (i == num_workers - 1 || n == tile_cols - 1) {
1766 winterface->execute(worker);
1768 winterface->launch(worker);
1771 if (buf->col == tile_cols - 1) {
1778 for (; i > 0; --i) {
1779 VPxWorker *const worker = &pbi->tile_workers[i - 1];
1780 // TODO(jzern): The tile may have specific error data associated with
1781 // its vpx_internal_error_info which could be propagated to the main info
1782 // in cm. Additionally once the threads have been synced and an error is
1783 // detected, there's no point in continuing to decode tiles.
1784 pbi->mb.corrupted |= !winterface->sync(worker);
1786 if (final_worker > -1) {
1787 TileWorkerData *const tile_data =
1788 (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1789 bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1793 // Accumulate thread frame counts.
1794 if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1795 for (i = 0; i < num_workers; ++i) {
1796 TileWorkerData *const tile_data =
1797 (TileWorkerData*)pbi->tile_workers[i].data1;
1798 vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1803 return bit_reader_end;
1806 static void error_handler(void *data) {
1807 VP9_COMMON *const cm = (VP9_COMMON *)data;
1808 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1811 static void read_bitdepth_colorspace_sampling(
1812 VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1813 if (cm->profile >= PROFILE_2) {
1814 cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1815 #if CONFIG_VP9_HIGHBITDEPTH
1816 cm->use_highbitdepth = 1;
1819 cm->bit_depth = VPX_BITS_8;
1820 #if CONFIG_VP9_HIGHBITDEPTH
1821 cm->use_highbitdepth = 0;
1824 cm->color_space = vp9_rb_read_literal(rb, 3);
1825 if (cm->color_space != VPX_CS_SRGB) {
1826 vp9_rb_read_bit(rb); // [16,235] (including xvycc) vs [0,255] range
1827 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1828 cm->subsampling_x = vp9_rb_read_bit(rb);
1829 cm->subsampling_y = vp9_rb_read_bit(rb);
1830 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1831 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1832 "4:2:0 color not supported in profile 1 or 3");
1833 if (vp9_rb_read_bit(rb))
1834 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1835 "Reserved bit set");
1837 cm->subsampling_y = cm->subsampling_x = 1;
1840 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1841 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1842 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1843 cm->subsampling_y = cm->subsampling_x = 0;
1844 if (vp9_rb_read_bit(rb))
1845 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1846 "Reserved bit set");
1848 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1849 "4:4:4 color not supported in profile 0 or 2");
1854 static size_t read_uncompressed_header(VP9Decoder *pbi,
1855 struct vp9_read_bit_buffer *rb) {
1856 VP9_COMMON *const cm = &pbi->common;
1857 BufferPool *const pool = cm->buffer_pool;
1858 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1859 int i, mask, ref_index = 0;
1862 cm->last_frame_type = cm->frame_type;
1863 cm->last_intra_only = cm->intra_only;
1865 if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1866 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1867 "Invalid frame marker");
1869 cm->profile = vp9_read_profile(rb);
1871 if (cm->profile >= MAX_PROFILES)
1872 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1873 "Unsupported bitstream profile");
1875 cm->show_existing_frame = vp9_rb_read_bit(rb);
1876 if (cm->show_existing_frame) {
1877 // Show an existing frame directly.
1878 const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1879 lock_buffer_pool(pool);
1880 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1881 unlock_buffer_pool(pool);
1882 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1883 "Buffer %d does not contain a decoded frame",
1887 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1888 unlock_buffer_pool(pool);
1889 pbi->refresh_frame_flags = 0;
1890 cm->lf.filter_level = 0;
1893 if (pbi->frame_parallel_decode) {
1894 for (i = 0; i < REF_FRAMES; ++i)
1895 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1900 cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1901 cm->show_frame = vp9_rb_read_bit(rb);
1902 cm->error_resilient_mode = vp9_rb_read_bit(rb);
1904 if (cm->frame_type == KEY_FRAME) {
1905 if (!vp9_read_sync_code(rb))
1906 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1907 "Invalid frame sync code");
1909 read_bitdepth_colorspace_sampling(cm, rb);
1910 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1912 for (i = 0; i < REFS_PER_FRAME; ++i) {
1913 cm->frame_refs[i].idx = INVALID_IDX;
1914 cm->frame_refs[i].buf = NULL;
1917 setup_frame_size(cm, rb);
1918 if (pbi->need_resync) {
1919 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1920 pbi->need_resync = 0;
1923 cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1925 cm->reset_frame_context = cm->error_resilient_mode ?
1926 0 : vp9_rb_read_literal(rb, 2);
1928 if (cm->intra_only) {
1929 if (!vp9_read_sync_code(rb))
1930 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1931 "Invalid frame sync code");
1932 if (cm->profile > PROFILE_0) {
1933 read_bitdepth_colorspace_sampling(cm, rb);
1935 // NOTE: The intra-only frame header does not include the specification
1936 // of either the color format or color sub-sampling in profile 0. VP9
1937 // specifies that the default color format should be YUV 4:2:0 in this
1938 // case (normative).
1939 cm->color_space = VPX_CS_BT_601;
1940 cm->subsampling_y = cm->subsampling_x = 1;
1941 cm->bit_depth = VPX_BITS_8;
1942 #if CONFIG_VP9_HIGHBITDEPTH
1943 cm->use_highbitdepth = 0;
1947 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1948 setup_frame_size(cm, rb);
1949 if (pbi->need_resync) {
1950 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1951 pbi->need_resync = 0;
1953 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1954 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1955 for (i = 0; i < REFS_PER_FRAME; ++i) {
1956 const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1957 const int idx = cm->ref_frame_map[ref];
1958 RefBuffer *const ref_frame = &cm->frame_refs[i];
1959 ref_frame->idx = idx;
1960 ref_frame->buf = &frame_bufs[idx].buf;
1961 cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1964 setup_frame_size_with_refs(cm, rb);
1966 cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1967 cm->interp_filter = read_interp_filter(rb);
1969 for (i = 0; i < REFS_PER_FRAME; ++i) {
1970 RefBuffer *const ref_buf = &cm->frame_refs[i];
1971 #if CONFIG_VP9_HIGHBITDEPTH
1972 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1973 ref_buf->buf->y_crop_width,
1974 ref_buf->buf->y_crop_height,
1975 cm->width, cm->height,
1976 cm->use_highbitdepth);
1978 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1979 ref_buf->buf->y_crop_width,
1980 ref_buf->buf->y_crop_height,
1981 cm->width, cm->height);
1986 #if CONFIG_VP9_HIGHBITDEPTH
1987 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1989 get_frame_new_buffer(cm)->color_space = cm->color_space;
1991 if (pbi->need_resync) {
1992 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1993 "Keyframe / intra-only frame required to reset decoder"
1997 if (!cm->error_resilient_mode) {
1998 cm->refresh_frame_context = vp9_rb_read_bit(rb);
1999 cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
2001 cm->refresh_frame_context = 0;
2002 cm->frame_parallel_decoding_mode = 1;
2005 // This flag will be overridden by the call to vp9_setup_past_independence
2006 // below, forcing the use of context 0 for those frame types.
2007 cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
2009 // Generate next_ref_frame_map.
2010 lock_buffer_pool(pool);
2011 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
2013 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
2014 ++frame_bufs[cm->new_fb_idx].ref_count;
2016 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2018 // Current thread holds the reference frame.
2019 if (cm->ref_frame_map[ref_index] >= 0)
2020 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2024 for (; ref_index < REF_FRAMES; ++ref_index) {
2025 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2026 // Current thread holds the reference frame.
2027 if (cm->ref_frame_map[ref_index] >= 0)
2028 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2030 unlock_buffer_pool(pool);
2031 pbi->hold_ref_buf = 1;
2033 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
2034 vp9_setup_past_independence(cm);
2036 setup_loopfilter(&cm->lf, rb);
2037 setup_quantization(cm, &pbi->mb, rb);
2038 setup_segmentation(&cm->seg, rb);
2039 setup_segmentation_dequant(cm);
2041 setup_tile_info(cm, rb);
2042 sz = vp9_rb_read_literal(rb, 16);
2045 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2046 "Invalid header size");
2051 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
2052 size_t partition_size) {
2053 VP9_COMMON *const cm = &pbi->common;
2054 MACROBLOCKD *const xd = &pbi->mb;
2055 FRAME_CONTEXT *const fc = cm->fc;
2059 if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
2060 pbi->decrypt_state))
2061 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2062 "Failed to allocate bool decoder 0");
2064 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
2065 if (cm->tx_mode == TX_MODE_SELECT)
2066 read_tx_mode_probs(&fc->tx_probs, &r);
2067 read_coef_probs(fc, cm->tx_mode, &r);
2069 for (k = 0; k < SKIP_CONTEXTS; ++k)
2070 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
2072 if (!frame_is_intra_only(cm)) {
2073 nmv_context *const nmvc = &fc->nmvc;
2076 read_inter_mode_probs(fc, &r);
2078 if (cm->interp_filter == SWITCHABLE)
2079 read_switchable_interp_probs(fc, &r);
2081 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
2082 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
2084 cm->reference_mode = read_frame_reference_mode(cm, &r);
2085 if (cm->reference_mode != SINGLE_REFERENCE)
2086 setup_compound_reference_mode(cm);
2087 read_frame_reference_mode_probs(cm, &r);
2089 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
2090 for (i = 0; i < INTRA_MODES - 1; ++i)
2091 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
2093 for (j = 0; j < PARTITION_CONTEXTS; ++j)
2094 for (i = 0; i < PARTITION_TYPES - 1; ++i)
2095 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
2097 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2100 return vp9_reader_has_error(&r);
2104 #define debug_check_frame_counts(cm) (void)0
2106 // Counts should only be incremented when frame_parallel_decoding_mode and
2107 // error_resilient_mode are disabled.
2108 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
2109 FRAME_COUNTS zero_counts;
2110 vp9_zero(zero_counts);
2111 assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
2112 assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
2113 sizeof(cm->counts.y_mode)));
2114 assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
2115 sizeof(cm->counts.uv_mode)));
2116 assert(!memcmp(cm->counts.partition, zero_counts.partition,
2117 sizeof(cm->counts.partition)));
2118 assert(!memcmp(cm->counts.coef, zero_counts.coef,
2119 sizeof(cm->counts.coef)));
2120 assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
2121 sizeof(cm->counts.eob_branch)));
2122 assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
2123 sizeof(cm->counts.switchable_interp)));
2124 assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
2125 sizeof(cm->counts.inter_mode)));
2126 assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
2127 sizeof(cm->counts.intra_inter)));
2128 assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
2129 sizeof(cm->counts.comp_inter)));
2130 assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
2131 sizeof(cm->counts.single_ref)));
2132 assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
2133 sizeof(cm->counts.comp_ref)));
2134 assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
2135 assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
2136 assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
2140 static struct vp9_read_bit_buffer *init_read_bit_buffer(
2142 struct vp9_read_bit_buffer *rb,
2143 const uint8_t *data,
2144 const uint8_t *data_end,
2145 uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2147 rb->error_handler = error_handler;
2148 rb->error_handler_data = &pbi->common;
2149 if (pbi->decrypt_cb) {
2150 const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
2151 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2152 rb->bit_buffer = clear_data;
2153 rb->bit_buffer_end = clear_data + n;
2155 rb->bit_buffer = data;
2156 rb->bit_buffer_end = data_end;
2161 //------------------------------------------------------------------------------
2163 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
2164 return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2165 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2166 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2169 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
2170 int *width, int *height) {
2171 *width = vp9_rb_read_literal(rb, 16) + 1;
2172 *height = vp9_rb_read_literal(rb, 16) + 1;
2175 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
2176 int profile = vp9_rb_read_bit(rb);
2177 profile |= vp9_rb_read_bit(rb) << 1;
2179 profile += vp9_rb_read_bit(rb);
2180 return (BITSTREAM_PROFILE) profile;
2183 void vp9_decode_frame(VP9Decoder *pbi,
2184 const uint8_t *data, const uint8_t *data_end,
2185 const uint8_t **p_data_end) {
2186 VP9_COMMON *const cm = &pbi->common;
2187 MACROBLOCKD *const xd = &pbi->mb;
2188 struct vp9_read_bit_buffer rb;
2189 int context_updated = 0;
2190 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2191 const size_t first_partition_size = read_uncompressed_header(pbi,
2192 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2193 const int tile_rows = 1 << cm->log2_tile_rows;
2194 const int tile_cols = 1 << cm->log2_tile_cols;
2195 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2196 xd->cur_buf = new_fb;
2198 if (!first_partition_size) {
2199 // showing a frame directly
2200 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2204 data += vp9_rb_bytes_read(&rb);
2205 if (!read_is_valid(data, first_partition_size, data_end))
2206 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2207 "Truncated packet or corrupt header length");
2209 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2210 cm->width == cm->last_width &&
2211 cm->height == cm->last_height &&
2212 !cm->last_intra_only &&
2213 cm->last_show_frame &&
2214 (cm->last_frame_type != KEY_FRAME);
2216 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2218 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2219 if (!cm->fc->initialized)
2220 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2221 "Uninitialized entropy context.");
2223 vp9_zero(cm->counts);
2226 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2227 if (new_fb->corrupted)
2228 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2229 "Decode failed. Frame data header is corrupted.");
2231 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2232 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2235 // If encoded in frame parallel mode, frame context is ready after decoding
2236 // the frame header.
2237 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2238 VPxWorker *const worker = pbi->frame_worker_owner;
2239 FrameWorkerData *const frame_worker_data = worker->data1;
2240 if (cm->refresh_frame_context) {
2241 context_updated = 1;
2242 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2244 vp9_frameworker_lock_stats(worker);
2245 pbi->cur_buf->row = -1;
2246 pbi->cur_buf->col = -1;
2247 frame_worker_data->frame_context_ready = 1;
2248 // Signal the main thread that context is ready.
2249 vp9_frameworker_signal_stats(worker);
2250 vp9_frameworker_unlock_stats(worker);
2253 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2254 // Multi-threaded tile decoder
2255 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2256 if (!xd->corrupted) {
2257 if (!cm->skip_loop_filter) {
2258 // If multiple threads are used to decode tiles, then we use those
2259 // threads to do parallel loopfiltering.
2260 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2261 cm->lf.filter_level, 0, 0, pbi->tile_workers,
2262 pbi->num_tile_workers, &pbi->lf_row_sync);
2265 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2266 "Decode failed. Frame data is corrupted.");
2270 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2273 if (!xd->corrupted) {
2274 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2275 vp9_adapt_coef_probs(cm);
2277 if (!frame_is_intra_only(cm)) {
2278 vp9_adapt_mode_probs(cm);
2279 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2282 debug_check_frame_counts(cm);
2285 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2286 "Decode failed. Frame data is corrupted.");
2289 // Non frame parallel update frame context here.
2290 if (cm->refresh_frame_context && !context_updated)
2291 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;