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_dsp_rtcd.h"
16 #include "./vpx_scale_rtcd.h"
18 #include "vpx_dsp/bitreader_buffer.h"
19 #include "vpx_dsp/bitreader.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_mem/vpx_mem.h"
22 #include "vpx_ports/mem.h"
23 #include "vpx_ports/mem_ops.h"
24 #include "vpx_scale/vpx_scale.h"
25 #include "vpx_util/vpx_thread.h"
27 #include "vp9/common/vp9_alloccommon.h"
28 #include "vp9/common/vp9_common.h"
29 #include "vp9/common/vp9_entropy.h"
30 #include "vp9/common/vp9_entropymode.h"
31 #include "vp9/common/vp9_idct.h"
32 #include "vp9/common/vp9_thread_common.h"
33 #include "vp9/common/vp9_pred_common.h"
34 #include "vp9/common/vp9_quant_common.h"
35 #include "vp9/common/vp9_reconintra.h"
36 #include "vp9/common/vp9_reconinter.h"
37 #include "vp9/common/vp9_seg_common.h"
38 #include "vp9/common/vp9_tile_common.h"
40 #include "vp9/decoder/vp9_decodeframe.h"
41 #include "vp9/decoder/vp9_detokenize.h"
42 #include "vp9/decoder/vp9_decodemv.h"
43 #include "vp9/decoder/vp9_decoder.h"
44 #include "vp9/decoder/vp9_dsubexp.h"
46 #define MAX_VP9_HEADER_SIZE 80
48 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
50 for (i = 1; i < REFS_PER_FRAME; ++i)
51 if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1]) return 1;
56 static void setup_compound_reference_mode(VP9_COMMON *cm) {
57 if (cm->ref_frame_sign_bias[LAST_FRAME] ==
58 cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
59 cm->comp_fixed_ref = ALTREF_FRAME;
60 cm->comp_var_ref[0] = LAST_FRAME;
61 cm->comp_var_ref[1] = GOLDEN_FRAME;
62 } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
63 cm->ref_frame_sign_bias[ALTREF_FRAME]) {
64 cm->comp_fixed_ref = GOLDEN_FRAME;
65 cm->comp_var_ref[0] = LAST_FRAME;
66 cm->comp_var_ref[1] = ALTREF_FRAME;
68 cm->comp_fixed_ref = LAST_FRAME;
69 cm->comp_var_ref[0] = GOLDEN_FRAME;
70 cm->comp_var_ref[1] = ALTREF_FRAME;
74 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
75 return len != 0 && len <= (size_t)(end - start);
78 static int decode_unsigned_max(struct vpx_read_bit_buffer *rb, int max) {
79 const int data = vpx_rb_read_literal(rb, get_unsigned_bits(max));
80 return data > max ? max : data;
83 static TX_MODE read_tx_mode(vpx_reader *r) {
84 TX_MODE tx_mode = vpx_read_literal(r, 2);
85 if (tx_mode == ALLOW_32X32) tx_mode += vpx_read_bit(r);
89 static void read_tx_mode_probs(struct tx_probs *tx_probs, vpx_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, vpx_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, vpx_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 vpx_read_bit(r)
123 ? (vpx_read_bit(r) ? REFERENCE_MODE_SELECT : COMPOUND_REFERENCE)
126 return SINGLE_REFERENCE;
130 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vpx_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(vpx_prob *p, int n, vpx_reader *r) {
151 for (i = 0; i < n; ++i)
152 if (vpx_read(r, MV_UPDATE_PROB)) p[i] = (vpx_read_literal(r, 7) << 1) | 1;
155 static void read_mv_probs(nmv_context *ctx, int allow_hp, vpx_reader *r) {
158 update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
160 for (i = 0; i < 2; ++i) {
161 nmv_component *const comp_ctx = &ctx->comps[i];
162 update_mv_probs(&comp_ctx->sign, 1, r);
163 update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
164 update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
165 update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
168 for (i = 0; i < 2; ++i) {
169 nmv_component *const comp_ctx = &ctx->comps[i];
170 for (j = 0; j < CLASS0_SIZE; ++j)
171 update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
172 update_mv_probs(comp_ctx->fp, 3, r);
176 for (i = 0; i < 2; ++i) {
177 nmv_component *const comp_ctx = &ctx->comps[i];
178 update_mv_probs(&comp_ctx->class0_hp, 1, r);
179 update_mv_probs(&comp_ctx->hp, 1, r);
184 static void inverse_transform_block_inter(MACROBLOCKD *xd, int plane,
185 const TX_SIZE tx_size, uint8_t *dst,
186 int stride, int eob) {
187 struct macroblockd_plane *const pd = &xd->plane[plane];
188 tran_low_t *const dqcoeff = pd->dqcoeff;
190 #if CONFIG_VP9_HIGHBITDEPTH
191 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
193 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
197 vp9_highbd_idct4x4_add(dqcoeff, dst, stride, eob, xd->bd);
200 vp9_highbd_idct8x8_add(dqcoeff, dst, stride, eob, xd->bd);
203 vp9_highbd_idct16x16_add(dqcoeff, dst, stride, eob, xd->bd);
206 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
208 default: assert(0 && "Invalid transform size");
213 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
216 case TX_4X4: vp9_idct4x4_add(dqcoeff, dst, stride, eob); break;
217 case TX_8X8: vp9_idct8x8_add(dqcoeff, dst, stride, eob); break;
218 case TX_16X16: vp9_idct16x16_add(dqcoeff, dst, stride, eob); break;
219 case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
220 default: assert(0 && "Invalid transform size"); return;
226 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
229 case TX_4X4: vp9_idct4x4_add(dqcoeff, dst, stride, eob); break;
230 case TX_8X8: vp9_idct8x8_add(dqcoeff, dst, stride, eob); break;
231 case TX_16X16: vp9_idct16x16_add(dqcoeff, dst, stride, eob); break;
232 case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
233 default: assert(0 && "Invalid transform size"); return;
236 #endif // CONFIG_VP9_HIGHBITDEPTH
241 if (tx_size <= TX_16X16 && eob <= 10)
242 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
243 else if (tx_size == TX_32X32 && eob <= 34)
244 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
246 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
250 static void inverse_transform_block_intra(MACROBLOCKD *xd, int plane,
251 const TX_TYPE tx_type,
252 const TX_SIZE tx_size, uint8_t *dst,
253 int stride, int eob) {
254 struct macroblockd_plane *const pd = &xd->plane[plane];
255 tran_low_t *const dqcoeff = pd->dqcoeff;
257 #if CONFIG_VP9_HIGHBITDEPTH
258 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
260 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
264 vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
267 vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
270 vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
273 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
275 default: assert(0 && "Invalid transform size");
280 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
283 case TX_4X4: vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob); break;
284 case TX_8X8: vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob); break;
286 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
288 case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
289 default: assert(0 && "Invalid transform size"); return;
295 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
298 case TX_4X4: vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob); break;
299 case TX_8X8: vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob); break;
301 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
303 case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
304 default: assert(0 && "Invalid transform size"); return;
307 #endif // CONFIG_VP9_HIGHBITDEPTH
312 if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
313 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
314 else if (tx_size == TX_32X32 && eob <= 34)
315 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
317 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
321 static void predict_and_reconstruct_intra_block(TileWorkerData *twd,
322 MODE_INFO *const mi, int plane,
325 MACROBLOCKD *const xd = &twd->xd;
326 struct macroblockd_plane *const pd = &xd->plane[plane];
327 PREDICTION_MODE mode = (plane == 0) ? mi->mode : mi->uv_mode;
329 dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
331 if (mi->sb_type < BLOCK_8X8)
332 if (plane == 0) mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
334 vp9_predict_intra_block(xd, pd->n4_wl, tx_size, mode, dst, pd->dst.stride,
335 dst, pd->dst.stride, col, row, plane);
338 const TX_TYPE tx_type =
339 (plane || xd->lossless) ? DCT_DCT : intra_mode_to_tx_type_lookup[mode];
340 const scan_order *sc = (plane || xd->lossless)
341 ? &vp9_default_scan_orders[tx_size]
342 : &vp9_scan_orders[tx_size][tx_type];
343 const int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
346 inverse_transform_block_intra(xd, plane, tx_type, tx_size, dst,
347 pd->dst.stride, eob);
352 static int reconstruct_inter_block(TileWorkerData *twd, MODE_INFO *const mi,
353 int plane, int row, int col,
355 MACROBLOCKD *const xd = &twd->xd;
356 struct macroblockd_plane *const pd = &xd->plane[plane];
357 const scan_order *sc = &vp9_default_scan_orders[tx_size];
358 const int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
362 inverse_transform_block_inter(
363 xd, plane, tx_size, &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
364 pd->dst.stride, eob);
369 static void build_mc_border(const uint8_t *src, int src_stride, uint8_t *dst,
370 int dst_stride, int x, int y, int b_w, int b_h,
372 // Get a pointer to the start of the real data for this row.
373 const uint8_t *ref_row = src - x - y * src_stride;
376 ref_row += (h - 1) * src_stride;
378 ref_row += y * src_stride;
382 int left = x < 0 ? -x : 0;
384 if (left > b_w) left = b_w;
386 if (x + b_w > w) right = x + b_w - w;
388 if (right > b_w) right = b_w;
390 copy = b_w - left - right;
392 if (left) memset(dst, ref_row[0], left);
394 if (copy) memcpy(dst + left, ref_row + x + left, copy);
396 if (right) memset(dst + left + copy, ref_row[w - 1], right);
401 if (y > 0 && y < h) ref_row += src_stride;
405 #if CONFIG_VP9_HIGHBITDEPTH
406 static void high_build_mc_border(const uint8_t *src8, int src_stride,
407 uint16_t *dst, int dst_stride, int x, int y,
408 int b_w, int b_h, int w, int h) {
409 // Get a pointer to the start of the real data for this row.
410 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
411 const uint16_t *ref_row = src - x - y * src_stride;
414 ref_row += (h - 1) * src_stride;
416 ref_row += y * src_stride;
420 int left = x < 0 ? -x : 0;
422 if (left > b_w) left = b_w;
424 if (x + b_w > w) right = x + b_w - w;
426 if (right > b_w) right = b_w;
428 copy = b_w - left - right;
430 if (left) vpx_memset16(dst, ref_row[0], left);
432 if (copy) memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
434 if (right) vpx_memset16(dst + left + copy, ref_row[w - 1], right);
439 if (y > 0 && y < h) ref_row += src_stride;
442 #endif // CONFIG_VP9_HIGHBITDEPTH
444 #if CONFIG_VP9_HIGHBITDEPTH
445 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
446 int x0, int y0, int b_w, int b_h,
447 int frame_width, int frame_height,
448 int border_offset, uint8_t *const dst,
449 int dst_buf_stride, int subpel_x, int subpel_y,
450 const InterpKernel *kernel,
451 const struct scale_factors *sf, MACROBLOCKD *xd,
452 int w, int h, int ref, int xs, int ys) {
453 DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
455 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
456 high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w, x0, y0,
457 b_w, b_h, frame_width, frame_height);
458 highbd_inter_predictor(mc_buf_high + border_offset, b_w,
459 CONVERT_TO_SHORTPTR(dst), dst_buf_stride, subpel_x,
460 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
462 build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w, x0,
463 y0, b_w, b_h, frame_width, frame_height);
464 inter_predictor(((uint8_t *)mc_buf_high) + border_offset, b_w, dst,
465 dst_buf_stride, subpel_x, subpel_y, sf, w, h, ref, kernel,
470 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
471 int x0, int y0, int b_w, int b_h,
472 int frame_width, int frame_height,
473 int border_offset, uint8_t *const dst,
474 int dst_buf_stride, int subpel_x, int subpel_y,
475 const InterpKernel *kernel,
476 const struct scale_factors *sf, int w, int h,
477 int ref, int xs, int ys) {
478 DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
479 const uint8_t *buf_ptr;
481 build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w, x0, y0, b_w, b_h,
482 frame_width, frame_height);
483 buf_ptr = mc_buf + border_offset;
485 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x, subpel_y, sf, w,
486 h, ref, kernel, xs, ys);
488 #endif // CONFIG_VP9_HIGHBITDEPTH
490 static void dec_build_inter_predictors(
491 VPxWorker *const worker, MACROBLOCKD *xd, int plane, int bw, int bh, int x,
492 int y, int w, int h, int mi_x, int mi_y, const InterpKernel *kernel,
493 const struct scale_factors *sf, struct buf_2d *pre_buf,
494 struct buf_2d *dst_buf, const MV *mv, RefCntBuffer *ref_frame_buf,
495 int is_scaled, int ref) {
496 struct macroblockd_plane *const pd = &xd->plane[plane];
497 uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
499 int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height, buf_stride,
501 uint8_t *ref_frame, *buf_ptr;
503 // Get reference frame pointer, width and height.
505 frame_width = ref_frame_buf->buf.y_crop_width;
506 frame_height = ref_frame_buf->buf.y_crop_height;
507 ref_frame = ref_frame_buf->buf.y_buffer;
509 frame_width = ref_frame_buf->buf.uv_crop_width;
510 frame_height = ref_frame_buf->buf.uv_crop_height;
512 plane == 1 ? ref_frame_buf->buf.u_buffer : ref_frame_buf->buf.v_buffer;
516 const MV mv_q4 = clamp_mv_to_umv_border_sb(
517 xd, mv, bw, bh, pd->subsampling_x, pd->subsampling_y);
518 // Co-ordinate of containing block to pixel precision.
519 int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
520 int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
521 #if 0 // CONFIG_BETTER_HW_COMPATIBILITY
522 assert(xd->mi[0]->sb_type != BLOCK_4X8 &&
523 xd->mi[0]->sb_type != BLOCK_8X4);
524 assert(mv_q4.row == mv->row * (1 << (1 - pd->subsampling_y)) &&
525 mv_q4.col == mv->col * (1 << (1 - pd->subsampling_x)));
527 // Co-ordinate of the block to 1/16th pixel precision.
528 x0_16 = (x_start + x) << SUBPEL_BITS;
529 y0_16 = (y_start + y) << SUBPEL_BITS;
531 // Co-ordinate of current block in reference frame
532 // to 1/16th pixel precision.
533 x0_16 = sf->scale_value_x(x0_16, sf);
534 y0_16 = sf->scale_value_y(y0_16, sf);
536 // Map the top left corner of the block into the reference frame.
537 x0 = sf->scale_value_x(x_start + x, sf);
538 y0 = sf->scale_value_y(y_start + y, sf);
540 // Scale the MV and incorporate the sub-pixel offset of the block
541 // in the reference frame.
542 scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
546 // Co-ordinate of containing block to pixel precision.
547 x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
548 y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
550 // Co-ordinate of the block to 1/16th pixel precision.
551 x0_16 = x0 << SUBPEL_BITS;
552 y0_16 = y0 << SUBPEL_BITS;
554 scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
555 scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
558 subpel_x = scaled_mv.col & SUBPEL_MASK;
559 subpel_y = scaled_mv.row & SUBPEL_MASK;
561 // Calculate the top left corner of the best matching block in the
563 x0 += scaled_mv.col >> SUBPEL_BITS;
564 y0 += scaled_mv.row >> SUBPEL_BITS;
565 x0_16 += scaled_mv.col;
566 y0_16 += scaled_mv.row;
568 // Get reference block pointer.
569 buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
570 buf_stride = pre_buf->stride;
572 // Do border extension if there is motion or the
573 // width/height is not a multiple of 8 pixels.
574 if (is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 0x7) ||
575 (frame_height & 0x7)) {
576 int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
578 // Get reference block bottom right horizontal coordinate.
579 int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
580 int x_pad = 0, y_pad = 0;
582 if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
583 x0 -= VP9_INTERP_EXTEND - 1;
584 x1 += VP9_INTERP_EXTEND;
588 if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
589 y0 -= VP9_INTERP_EXTEND - 1;
590 y1 += VP9_INTERP_EXTEND;
594 // Wait until reference block is ready. Pad 7 more pixels as last 7
595 // pixels of each superblock row can be changed by next superblock row.
597 vp9_frameworker_wait(worker, ref_frame_buf, VPXMAX(0, (y1 + 7))
598 << (plane == 0 ? 0 : 1));
600 // Skip border extension if block is inside the frame.
601 if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
602 y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
603 // Extend the border.
604 const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
605 const int b_w = x1 - x0 + 1;
606 const int b_h = y1 - y0 + 1;
607 const int border_offset = y_pad * 3 * b_w + x_pad * 3;
609 extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h, frame_width,
610 frame_height, border_offset, dst, dst_buf->stride,
611 subpel_x, subpel_y, kernel, sf,
612 #if CONFIG_VP9_HIGHBITDEPTH
619 // Wait until reference block is ready. Pad 7 more pixels as last 7
620 // pixels of each superblock row can be changed by next superblock row.
621 if (worker != NULL) {
622 const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
623 vp9_frameworker_wait(worker, ref_frame_buf, VPXMAX(0, (y1 + 7))
624 << (plane == 0 ? 0 : 1));
627 #if CONFIG_VP9_HIGHBITDEPTH
628 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
629 highbd_inter_predictor(CONVERT_TO_SHORTPTR(buf_ptr), buf_stride,
630 CONVERT_TO_SHORTPTR(dst), dst_buf->stride, subpel_x,
631 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
633 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
634 subpel_y, sf, w, h, ref, kernel, xs, ys);
637 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x, subpel_y,
638 sf, w, h, ref, kernel, xs, ys);
639 #endif // CONFIG_VP9_HIGHBITDEPTH
642 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
643 MACROBLOCKD *xd, int mi_row,
646 const int mi_x = mi_col * MI_SIZE;
647 const int mi_y = mi_row * MI_SIZE;
648 const MODE_INFO *mi = xd->mi[0];
649 const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
650 const BLOCK_SIZE sb_type = mi->sb_type;
651 const int is_compound = has_second_ref(mi);
654 VPxWorker *const fwo =
655 pbi->frame_parallel_decode ? pbi->frame_worker_owner : NULL;
657 for (ref = 0; ref < 1 + is_compound; ++ref) {
658 const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
659 RefBuffer *ref_buf = &pbi->common.frame_refs[frame - LAST_FRAME];
660 const struct scale_factors *const sf = &ref_buf->sf;
661 const int idx = ref_buf->idx;
662 BufferPool *const pool = pbi->common.buffer_pool;
663 RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
665 if (!vp9_is_valid_scale(sf))
666 vpx_internal_error(xd->error_info, VPX_CODEC_UNSUP_BITSTREAM,
667 "Reference frame has invalid dimensions");
669 is_scaled = vp9_is_scaled(sf);
670 vp9_setup_pre_planes(xd, ref, ref_buf->buf, mi_row, mi_col,
671 is_scaled ? sf : NULL);
672 xd->block_refs[ref] = ref_buf;
674 if (sb_type < BLOCK_8X8) {
675 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
676 struct macroblockd_plane *const pd = &xd->plane[plane];
677 struct buf_2d *const dst_buf = &pd->dst;
678 const int num_4x4_w = pd->n4_w;
679 const int num_4x4_h = pd->n4_h;
680 const int n4w_x4 = 4 * num_4x4_w;
681 const int n4h_x4 = 4 * num_4x4_h;
682 struct buf_2d *const pre_buf = &pd->pre[ref];
684 for (y = 0; y < num_4x4_h; ++y) {
685 for (x = 0; x < num_4x4_w; ++x) {
686 const MV mv = average_split_mvs(pd, mi, ref, i++);
687 dec_build_inter_predictors(fwo, xd, plane, n4w_x4, n4h_x4, 4 * x,
688 4 * y, 4, 4, mi_x, mi_y, kernel, sf,
689 pre_buf, dst_buf, &mv, ref_frame_buf,
695 const MV mv = mi->mv[ref].as_mv;
696 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
697 struct macroblockd_plane *const pd = &xd->plane[plane];
698 struct buf_2d *const dst_buf = &pd->dst;
699 const int num_4x4_w = pd->n4_w;
700 const int num_4x4_h = pd->n4_h;
701 const int n4w_x4 = 4 * num_4x4_w;
702 const int n4h_x4 = 4 * num_4x4_h;
703 struct buf_2d *const pre_buf = &pd->pre[ref];
704 dec_build_inter_predictors(fwo, xd, plane, n4w_x4, n4h_x4, 0, 0, n4w_x4,
705 n4h_x4, mi_x, mi_y, kernel, sf, pre_buf,
706 dst_buf, &mv, ref_frame_buf, is_scaled, ref);
712 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
714 for (i = 0; i < MAX_MB_PLANE; i++) {
715 struct macroblockd_plane *const pd = &xd->plane[i];
716 memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
717 memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
721 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
724 for (i = 0; i < MAX_MB_PLANE; i++) {
725 xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
726 xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
727 xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
728 xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
732 static MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
733 BLOCK_SIZE bsize, int mi_row, int mi_col, int bw,
734 int bh, int x_mis, int y_mis, int bwl, int bhl) {
735 const int offset = mi_row * cm->mi_stride + mi_col;
737 const TileInfo *const tile = &xd->tile;
739 xd->mi = cm->mi_grid_visible + offset;
740 xd->mi[0] = &cm->mi[offset];
741 // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
742 // passing bsize from decode_partition().
743 xd->mi[0]->sb_type = bsize;
744 for (y = 0; y < y_mis; ++y)
745 for (x = !y; x < x_mis; ++x) {
746 xd->mi[y * cm->mi_stride + x] = xd->mi[0];
749 set_plane_n4(xd, bw, bh, bwl, bhl);
751 set_skip_context(xd, mi_row, mi_col);
753 // Distance of Mb to the various image edges. These are specified to 8th pel
754 // as they are always compared to values that are in 1/8th pel units
755 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
757 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
761 static void decode_block(TileWorkerData *twd, VP9Decoder *const pbi, int mi_row,
762 int mi_col, BLOCK_SIZE bsize, int bwl, int bhl) {
763 VP9_COMMON *const cm = &pbi->common;
764 const int less8x8 = bsize < BLOCK_8X8;
765 const int bw = 1 << (bwl - 1);
766 const int bh = 1 << (bhl - 1);
767 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
768 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
769 vpx_reader *r = &twd->bit_reader;
770 MACROBLOCKD *const xd = &twd->xd;
772 MODE_INFO *mi = set_offsets(cm, xd, bsize, mi_row, mi_col, bw, bh, x_mis,
775 if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
776 const BLOCK_SIZE uv_subsize =
777 ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
778 if (uv_subsize == BLOCK_INVALID)
779 vpx_internal_error(xd->error_info, VPX_CODEC_CORRUPT_FRAME,
780 "Invalid block size.");
783 vp9_read_mode_info(twd, pbi, mi_row, mi_col, x_mis, y_mis);
786 dec_reset_skip_context(xd);
789 if (!is_inter_block(mi)) {
791 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
792 const struct macroblockd_plane *const pd = &xd->plane[plane];
793 const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
794 const int num_4x4_w = pd->n4_w;
795 const int num_4x4_h = pd->n4_h;
796 const int step = (1 << tx_size);
798 const int max_blocks_wide =
799 num_4x4_w + (xd->mb_to_right_edge >= 0
801 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
802 const int max_blocks_high =
803 num_4x4_h + (xd->mb_to_bottom_edge >= 0
805 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
807 xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
808 xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
810 for (row = 0; row < max_blocks_high; row += step)
811 for (col = 0; col < max_blocks_wide; col += step)
812 predict_and_reconstruct_intra_block(twd, mi, plane, row, col,
817 dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col);
824 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
825 const struct macroblockd_plane *const pd = &xd->plane[plane];
826 const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
827 const int num_4x4_w = pd->n4_w;
828 const int num_4x4_h = pd->n4_h;
829 const int step = (1 << tx_size);
831 const int max_blocks_wide =
832 num_4x4_w + (xd->mb_to_right_edge >= 0
834 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
835 const int max_blocks_high =
837 (xd->mb_to_bottom_edge >= 0
839 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
841 xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
842 xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
844 for (row = 0; row < max_blocks_high; row += step)
845 for (col = 0; col < max_blocks_wide; col += step)
847 reconstruct_inter_block(twd, mi, plane, row, col, tx_size);
850 if (!less8x8 && eobtotal == 0) mi->skip = 1; // skip loopfilter
854 xd->corrupted |= vpx_reader_has_error(r);
856 if (cm->lf.filter_level) {
857 vp9_build_mask(cm, mi, mi_row, mi_col, bw, bh);
861 static INLINE int dec_partition_plane_context(TileWorkerData *twd, int mi_row,
862 int mi_col, int bsl) {
863 const PARTITION_CONTEXT *above_ctx = twd->xd.above_seg_context + mi_col;
864 const PARTITION_CONTEXT *left_ctx =
865 twd->xd.left_seg_context + (mi_row & MI_MASK);
866 int above = (*above_ctx >> bsl) & 1, left = (*left_ctx >> bsl) & 1;
870 return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
873 static INLINE void dec_update_partition_context(TileWorkerData *twd, int mi_row,
874 int mi_col, BLOCK_SIZE subsize,
876 PARTITION_CONTEXT *const above_ctx = twd->xd.above_seg_context + mi_col;
877 PARTITION_CONTEXT *const left_ctx =
878 twd->xd.left_seg_context + (mi_row & MI_MASK);
880 // update the partition context at the end notes. set partition bits
881 // of block sizes larger than the current one to be one, and partition
882 // bits of smaller block sizes to be zero.
883 memset(above_ctx, partition_context_lookup[subsize].above, bw);
884 memset(left_ctx, partition_context_lookup[subsize].left, bw);
887 static PARTITION_TYPE read_partition(TileWorkerData *twd, int mi_row,
888 int mi_col, int has_rows, int has_cols,
890 const int ctx = dec_partition_plane_context(twd, mi_row, mi_col, bsl);
891 const vpx_prob *const probs = twd->xd.partition_probs[ctx];
892 FRAME_COUNTS *counts = twd->xd.counts;
894 vpx_reader *r = &twd->bit_reader;
896 if (has_rows && has_cols)
897 p = (PARTITION_TYPE)vpx_read_tree(r, vp9_partition_tree, probs);
898 else if (!has_rows && has_cols)
899 p = vpx_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
900 else if (has_rows && !has_cols)
901 p = vpx_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
905 if (counts) ++counts->partition[ctx][p];
910 // TODO(slavarnway): eliminate bsize and subsize in future commits
911 static void decode_partition(TileWorkerData *twd, VP9Decoder *const pbi,
912 int mi_row, int mi_col, BLOCK_SIZE bsize,
914 VP9_COMMON *const cm = &pbi->common;
915 const int n8x8_l2 = n4x4_l2 - 1;
916 const int num_8x8_wh = 1 << n8x8_l2;
917 const int hbs = num_8x8_wh >> 1;
918 PARTITION_TYPE partition;
920 const int has_rows = (mi_row + hbs) < cm->mi_rows;
921 const int has_cols = (mi_col + hbs) < cm->mi_cols;
922 MACROBLOCKD *const xd = &twd->xd;
924 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
926 partition = read_partition(twd, mi_row, mi_col, has_rows, has_cols, n8x8_l2);
927 subsize = subsize_lookup[partition][bsize]; // get_subsize(bsize, partition);
929 // calculate bmode block dimensions (log 2)
930 xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
931 xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
932 decode_block(twd, pbi, mi_row, mi_col, subsize, 1, 1);
936 decode_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n4x4_l2);
939 decode_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n8x8_l2);
941 decode_block(twd, pbi, mi_row + hbs, mi_col, subsize, n4x4_l2,
945 decode_block(twd, pbi, mi_row, mi_col, subsize, n8x8_l2, n4x4_l2);
947 decode_block(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2,
950 case PARTITION_SPLIT:
951 decode_partition(twd, pbi, mi_row, mi_col, subsize, n8x8_l2);
952 decode_partition(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2);
953 decode_partition(twd, pbi, mi_row + hbs, mi_col, subsize, n8x8_l2);
954 decode_partition(twd, pbi, mi_row + hbs, mi_col + hbs, subsize,
957 default: assert(0 && "Invalid partition type");
961 // update partition context
962 if (bsize >= BLOCK_8X8 &&
963 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
964 dec_update_partition_context(twd, mi_row, mi_col, subsize, num_8x8_wh);
967 static void setup_token_decoder(const uint8_t *data, const uint8_t *data_end,
969 struct vpx_internal_error_info *error_info,
970 vpx_reader *r, vpx_decrypt_cb decrypt_cb,
971 void *decrypt_state) {
972 // Validate the calculated partition length. If the buffer
973 // described by the partition can't be fully read, then restrict
974 // it to the portion that can be (for EC mode) or throw an error.
975 if (!read_is_valid(data, read_size, data_end))
976 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
977 "Truncated packet or corrupt tile length");
979 if (vpx_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
980 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
981 "Failed to allocate bool decoder %d", 1);
984 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
989 for (i = 0; i < PLANE_TYPES; ++i)
990 for (j = 0; j < REF_TYPES; ++j)
991 for (k = 0; k < COEF_BANDS; ++k)
992 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
993 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
994 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
997 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode, vpx_reader *r) {
998 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1000 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1001 read_coef_probs_common(fc->coef_probs[tx_size], r);
1004 static void setup_segmentation(struct segmentation *seg,
1005 struct vpx_read_bit_buffer *rb) {
1008 seg->update_map = 0;
1009 seg->update_data = 0;
1011 seg->enabled = vpx_rb_read_bit(rb);
1012 if (!seg->enabled) return;
1014 // Segmentation map update
1015 seg->update_map = vpx_rb_read_bit(rb);
1016 if (seg->update_map) {
1017 for (i = 0; i < SEG_TREE_PROBS; i++)
1018 seg->tree_probs[i] =
1019 vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1021 seg->temporal_update = vpx_rb_read_bit(rb);
1022 if (seg->temporal_update) {
1023 for (i = 0; i < PREDICTION_PROBS; i++)
1024 seg->pred_probs[i] =
1025 vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1027 for (i = 0; i < PREDICTION_PROBS; i++) seg->pred_probs[i] = MAX_PROB;
1031 // Segmentation data update
1032 seg->update_data = vpx_rb_read_bit(rb);
1033 if (seg->update_data) {
1034 seg->abs_delta = vpx_rb_read_bit(rb);
1036 vp9_clearall_segfeatures(seg);
1038 for (i = 0; i < MAX_SEGMENTS; i++) {
1039 for (j = 0; j < SEG_LVL_MAX; j++) {
1041 const int feature_enabled = vpx_rb_read_bit(rb);
1042 if (feature_enabled) {
1043 vp9_enable_segfeature(seg, i, j);
1044 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1045 if (vp9_is_segfeature_signed(j))
1046 data = vpx_rb_read_bit(rb) ? -data : data;
1048 vp9_set_segdata(seg, i, j, data);
1054 static void setup_loopfilter(struct loopfilter *lf,
1055 struct vpx_read_bit_buffer *rb) {
1056 lf->filter_level = vpx_rb_read_literal(rb, 6);
1057 lf->sharpness_level = vpx_rb_read_literal(rb, 3);
1059 // Read in loop filter deltas applied at the MB level based on mode or ref
1061 lf->mode_ref_delta_update = 0;
1063 lf->mode_ref_delta_enabled = vpx_rb_read_bit(rb);
1064 if (lf->mode_ref_delta_enabled) {
1065 lf->mode_ref_delta_update = vpx_rb_read_bit(rb);
1066 if (lf->mode_ref_delta_update) {
1069 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1070 if (vpx_rb_read_bit(rb))
1071 lf->ref_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1073 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1074 if (vpx_rb_read_bit(rb))
1075 lf->mode_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1080 static INLINE int read_delta_q(struct vpx_read_bit_buffer *rb) {
1081 return vpx_rb_read_bit(rb) ? vpx_rb_read_signed_literal(rb, 4) : 0;
1084 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1085 struct vpx_read_bit_buffer *rb) {
1086 cm->base_qindex = vpx_rb_read_literal(rb, QINDEX_BITS);
1087 cm->y_dc_delta_q = read_delta_q(rb);
1088 cm->uv_dc_delta_q = read_delta_q(rb);
1089 cm->uv_ac_delta_q = read_delta_q(rb);
1090 cm->dequant_bit_depth = cm->bit_depth;
1091 xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
1092 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
1094 #if CONFIG_VP9_HIGHBITDEPTH
1095 xd->bd = (int)cm->bit_depth;
1099 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1100 // Build y/uv dequant values based on segmentation.
1101 if (cm->seg.enabled) {
1103 for (i = 0; i < MAX_SEGMENTS; ++i) {
1104 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1105 cm->y_dequant[i][0] =
1106 vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1107 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1108 cm->uv_dequant[i][0] =
1109 vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1110 cm->uv_dequant[i][1] =
1111 vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1114 const int qindex = cm->base_qindex;
1115 // When segmentation is disabled, only the first value is used. The
1116 // remaining are don't cares.
1117 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1118 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1119 cm->uv_dequant[0][0] =
1120 vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1121 cm->uv_dequant[0][1] =
1122 vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1126 static INTERP_FILTER read_interp_filter(struct vpx_read_bit_buffer *rb) {
1127 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH, EIGHTTAP,
1128 EIGHTTAP_SHARP, BILINEAR };
1129 return vpx_rb_read_bit(rb) ? SWITCHABLE
1130 : literal_to_filter[vpx_rb_read_literal(rb, 2)];
1133 static void setup_render_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1134 cm->render_width = cm->width;
1135 cm->render_height = cm->height;
1136 if (vpx_rb_read_bit(rb))
1137 vp9_read_frame_size(rb, &cm->render_width, &cm->render_height);
1140 static void resize_mv_buffer(VP9_COMMON *cm) {
1141 vpx_free(cm->cur_frame->mvs);
1142 cm->cur_frame->mi_rows = cm->mi_rows;
1143 cm->cur_frame->mi_cols = cm->mi_cols;
1144 CHECK_MEM_ERROR(cm, cm->cur_frame->mvs,
1145 (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1146 sizeof(*cm->cur_frame->mvs)));
1149 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1150 #if CONFIG_SIZE_LIMIT
1151 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1152 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1153 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1154 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1156 if (cm->width != width || cm->height != height) {
1157 const int new_mi_rows =
1158 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1159 const int new_mi_cols =
1160 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1162 // Allocations in vp9_alloc_context_buffers() depend on individual
1163 // dimensions as well as the overall size.
1164 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1165 if (vp9_alloc_context_buffers(cm, width, height))
1166 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1167 "Failed to allocate context buffers");
1169 vp9_set_mb_mi(cm, width, height);
1171 vp9_init_context_buffers(cm);
1173 cm->height = height;
1175 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1176 cm->mi_cols > cm->cur_frame->mi_cols) {
1177 resize_mv_buffer(cm);
1181 static void setup_frame_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1183 BufferPool *const pool = cm->buffer_pool;
1184 vp9_read_frame_size(rb, &width, &height);
1185 resize_context_buffers(cm, width, height);
1186 setup_render_size(cm, rb);
1188 lock_buffer_pool(pool);
1189 if (vpx_realloc_frame_buffer(
1190 get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1192 #if CONFIG_VP9_HIGHBITDEPTH
1193 cm->use_highbitdepth,
1195 VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1196 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1198 unlock_buffer_pool(pool);
1199 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1200 "Failed to allocate frame buffer");
1202 unlock_buffer_pool(pool);
1204 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1205 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1206 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1207 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1208 pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1209 pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1210 pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1213 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1214 int ref_xss, int ref_yss,
1215 vpx_bit_depth_t this_bit_depth,
1216 int this_xss, int this_yss) {
1217 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1218 ref_yss == this_yss;
1221 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1222 struct vpx_read_bit_buffer *rb) {
1225 int has_valid_ref_frame = 0;
1226 BufferPool *const pool = cm->buffer_pool;
1227 for (i = 0; i < REFS_PER_FRAME; ++i) {
1228 if (vpx_rb_read_bit(rb)) {
1229 if (cm->frame_refs[i].idx != INVALID_IDX) {
1230 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1231 width = buf->y_crop_width;
1232 height = buf->y_crop_height;
1236 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1237 "Failed to decode frame size");
1242 if (!found) vp9_read_frame_size(rb, &width, &height);
1244 if (width <= 0 || height <= 0)
1245 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1246 "Invalid frame size");
1248 // Check to make sure at least one of frames that this frame references
1249 // has valid dimensions.
1250 for (i = 0; i < REFS_PER_FRAME; ++i) {
1251 RefBuffer *const ref_frame = &cm->frame_refs[i];
1252 has_valid_ref_frame |=
1253 (ref_frame->idx != INVALID_IDX &&
1254 valid_ref_frame_size(ref_frame->buf->y_crop_width,
1255 ref_frame->buf->y_crop_height, width, height));
1257 if (!has_valid_ref_frame)
1258 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1259 "Referenced frame has invalid size");
1260 for (i = 0; i < REFS_PER_FRAME; ++i) {
1261 RefBuffer *const ref_frame = &cm->frame_refs[i];
1262 if (ref_frame->idx == INVALID_IDX ||
1263 !valid_ref_frame_img_fmt(ref_frame->buf->bit_depth,
1264 ref_frame->buf->subsampling_x,
1265 ref_frame->buf->subsampling_y, cm->bit_depth,
1266 cm->subsampling_x, cm->subsampling_y))
1267 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1268 "Referenced frame has incompatible color format");
1271 resize_context_buffers(cm, width, height);
1272 setup_render_size(cm, rb);
1274 lock_buffer_pool(pool);
1275 if (vpx_realloc_frame_buffer(
1276 get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1278 #if CONFIG_VP9_HIGHBITDEPTH
1279 cm->use_highbitdepth,
1281 VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1282 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1284 unlock_buffer_pool(pool);
1285 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1286 "Failed to allocate frame buffer");
1288 unlock_buffer_pool(pool);
1290 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1291 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1292 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1293 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1294 pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1295 pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1296 pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1299 static void setup_tile_info(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1300 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1301 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1304 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1305 cm->log2_tile_cols = min_log2_tile_cols;
1306 while (max_ones-- && vpx_rb_read_bit(rb)) cm->log2_tile_cols++;
1308 if (cm->log2_tile_cols > 6)
1309 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1310 "Invalid number of tile columns");
1313 cm->log2_tile_rows = vpx_rb_read_bit(rb);
1314 if (cm->log2_tile_rows) cm->log2_tile_rows += vpx_rb_read_bit(rb);
1317 // Reads the next tile returning its size and adjusting '*data' accordingly
1318 // based on 'is_last'.
1319 static void get_tile_buffer(const uint8_t *const data_end, int is_last,
1320 struct vpx_internal_error_info *error_info,
1321 const uint8_t **data, vpx_decrypt_cb decrypt_cb,
1322 void *decrypt_state, TileBuffer *buf) {
1326 if (!read_is_valid(*data, 4, data_end))
1327 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1328 "Truncated packet or corrupt tile length");
1332 decrypt_cb(decrypt_state, *data, be_data, 4);
1333 size = mem_get_be32(be_data);
1335 size = mem_get_be32(*data);
1339 if (size > (size_t)(data_end - *data))
1340 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1341 "Truncated packet or corrupt tile size");
1343 size = data_end - *data;
1352 static void get_tile_buffers(VP9Decoder *pbi, const uint8_t *data,
1353 const uint8_t *data_end, int tile_cols,
1355 TileBuffer (*tile_buffers)[1 << 6]) {
1358 for (r = 0; r < tile_rows; ++r) {
1359 for (c = 0; c < tile_cols; ++c) {
1360 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1361 TileBuffer *const buf = &tile_buffers[r][c];
1363 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1364 pbi->decrypt_cb, pbi->decrypt_state, buf);
1369 static const uint8_t *decode_tiles(VP9Decoder *pbi, const uint8_t *data,
1370 const uint8_t *data_end) {
1371 VP9_COMMON *const cm = &pbi->common;
1372 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1373 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1374 const int tile_cols = 1 << cm->log2_tile_cols;
1375 const int tile_rows = 1 << cm->log2_tile_rows;
1376 TileBuffer tile_buffers[4][1 << 6];
1377 int tile_row, tile_col;
1379 TileWorkerData *tile_data = NULL;
1381 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1382 pbi->lf_worker.data1 == NULL) {
1383 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1384 vpx_memalign(32, sizeof(LFWorkerData)));
1385 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1386 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1387 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1388 "Loop filter thread creation failed");
1392 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1393 LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
1394 // Be sure to sync as we might be resuming after a failed frame decode.
1395 winterface->sync(&pbi->lf_worker);
1396 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1400 assert(tile_rows <= 4);
1401 assert(tile_cols <= (1 << 6));
1403 // Note: this memset assumes above_context[0], [1] and [2]
1404 // are allocated as part of the same buffer.
1405 memset(cm->above_context, 0,
1406 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1408 memset(cm->above_seg_context, 0,
1409 sizeof(*cm->above_seg_context) * aligned_cols);
1413 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1415 // Load all tile information into tile_data.
1416 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1417 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1418 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1419 tile_data = pbi->tile_worker_data + tile_cols * tile_row + tile_col;
1420 tile_data->xd = pbi->mb;
1421 tile_data->xd.corrupted = 0;
1422 tile_data->xd.counts =
1423 cm->frame_parallel_decoding_mode ? NULL : &cm->counts;
1424 vp9_zero(tile_data->dqcoeff);
1425 vp9_tile_init(&tile_data->xd.tile, cm, tile_row, tile_col);
1426 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1427 &tile_data->bit_reader, pbi->decrypt_cb,
1428 pbi->decrypt_state);
1429 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1433 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1435 vp9_tile_set_row(&tile, cm, tile_row);
1436 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1437 mi_row += MI_BLOCK_SIZE) {
1438 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1440 pbi->inv_tile_order ? tile_cols - tile_col - 1 : tile_col;
1441 tile_data = pbi->tile_worker_data + tile_cols * tile_row + col;
1442 vp9_tile_set_col(&tile, cm, col);
1443 vp9_zero(tile_data->xd.left_context);
1444 vp9_zero(tile_data->xd.left_seg_context);
1445 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1446 mi_col += MI_BLOCK_SIZE) {
1447 decode_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4);
1449 pbi->mb.corrupted |= tile_data->xd.corrupted;
1450 if (pbi->mb.corrupted)
1451 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1452 "Failed to decode tile data");
1454 // Loopfilter one row.
1455 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1456 const int lf_start = mi_row - MI_BLOCK_SIZE;
1457 LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
1459 // delay the loopfilter by 1 macroblock row.
1460 if (lf_start < 0) continue;
1462 // decoding has completed: finish up the loop filter in this thread.
1463 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1465 winterface->sync(&pbi->lf_worker);
1466 lf_data->start = lf_start;
1467 lf_data->stop = mi_row;
1468 if (pbi->max_threads > 1) {
1469 winterface->launch(&pbi->lf_worker);
1471 winterface->execute(&pbi->lf_worker);
1474 // After loopfiltering, the last 7 row pixels in each superblock row may
1475 // still be changed by the longest loopfilter of the next superblock
1477 if (pbi->frame_parallel_decode)
1478 vp9_frameworker_broadcast(pbi->cur_buf, mi_row << MI_BLOCK_SIZE_LOG2);
1482 // Loopfilter remaining rows in the frame.
1483 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1484 LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
1485 winterface->sync(&pbi->lf_worker);
1486 lf_data->start = lf_data->stop;
1487 lf_data->stop = cm->mi_rows;
1488 winterface->execute(&pbi->lf_worker);
1491 // Get last tile data.
1492 tile_data = pbi->tile_worker_data + tile_cols * tile_rows - 1;
1494 if (pbi->frame_parallel_decode)
1495 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1496 return vpx_reader_find_end(&tile_data->bit_reader);
1499 // On entry 'tile_data->data_end' points to the end of the input frame, on exit
1500 // it is updated to reflect the bitreader position of the final tile column if
1501 // present in the tile buffer group or NULL otherwise.
1502 static int tile_worker_hook(TileWorkerData *const tile_data,
1503 VP9Decoder *const pbi) {
1504 TileInfo *volatile tile = &tile_data->xd.tile;
1505 const int final_col = (1 << pbi->common.log2_tile_cols) - 1;
1506 const uint8_t *volatile bit_reader_end = NULL;
1507 volatile int n = tile_data->buf_start;
1508 tile_data->error_info.setjmp = 1;
1510 if (setjmp(tile_data->error_info.jmp)) {
1511 tile_data->error_info.setjmp = 0;
1512 tile_data->xd.corrupted = 1;
1513 tile_data->data_end = NULL;
1517 tile_data->xd.corrupted = 0;
1521 const TileBuffer *const buf = pbi->tile_buffers + n;
1522 vp9_zero(tile_data->dqcoeff);
1523 vp9_tile_init(tile, &pbi->common, 0, buf->col);
1524 setup_token_decoder(buf->data, tile_data->data_end, buf->size,
1525 &tile_data->error_info, &tile_data->bit_reader,
1526 pbi->decrypt_cb, pbi->decrypt_state);
1527 vp9_init_macroblockd(&pbi->common, &tile_data->xd, tile_data->dqcoeff);
1528 // init resets xd.error_info
1529 tile_data->xd.error_info = &tile_data->error_info;
1531 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1532 mi_row += MI_BLOCK_SIZE) {
1533 vp9_zero(tile_data->xd.left_context);
1534 vp9_zero(tile_data->xd.left_seg_context);
1535 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1536 mi_col += MI_BLOCK_SIZE) {
1537 decode_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4);
1541 if (buf->col == final_col) {
1542 bit_reader_end = vpx_reader_find_end(&tile_data->bit_reader);
1544 } while (!tile_data->xd.corrupted && ++n <= tile_data->buf_end);
1546 tile_data->data_end = bit_reader_end;
1547 return !tile_data->xd.corrupted;
1550 // sorts in descending order
1551 static int compare_tile_buffers(const void *a, const void *b) {
1552 const TileBuffer *const buf1 = (const TileBuffer *)a;
1553 const TileBuffer *const buf2 = (const TileBuffer *)b;
1554 return (int)(buf2->size - buf1->size);
1557 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi, const uint8_t *data,
1558 const uint8_t *data_end) {
1559 VP9_COMMON *const cm = &pbi->common;
1560 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1561 const uint8_t *bit_reader_end = NULL;
1562 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1563 const int tile_cols = 1 << cm->log2_tile_cols;
1564 const int tile_rows = 1 << cm->log2_tile_rows;
1565 const int num_workers = VPXMIN(pbi->max_threads, tile_cols);
1568 assert(tile_cols <= (1 << 6));
1569 assert(tile_rows == 1);
1572 if (pbi->num_tile_workers == 0) {
1573 const int num_threads = pbi->max_threads;
1574 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1575 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1576 for (n = 0; n < num_threads; ++n) {
1577 VPxWorker *const worker = &pbi->tile_workers[n];
1578 ++pbi->num_tile_workers;
1580 winterface->init(worker);
1581 if (n < num_threads - 1 && !winterface->reset(worker)) {
1582 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1583 "Tile decoder thread creation failed");
1588 // Reset tile decoding hook
1589 for (n = 0; n < num_workers; ++n) {
1590 VPxWorker *const worker = &pbi->tile_workers[n];
1591 TileWorkerData *const tile_data =
1592 &pbi->tile_worker_data[n + pbi->total_tiles];
1593 winterface->sync(worker);
1594 tile_data->xd = pbi->mb;
1595 tile_data->xd.counts =
1596 cm->frame_parallel_decoding_mode ? NULL : &tile_data->counts;
1597 worker->hook = (VPxWorkerHook)tile_worker_hook;
1598 worker->data1 = tile_data;
1599 worker->data2 = pbi;
1602 // Note: this memset assumes above_context[0], [1] and [2]
1603 // are allocated as part of the same buffer.
1604 memset(cm->above_context, 0,
1605 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1606 memset(cm->above_seg_context, 0,
1607 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1611 // Load tile data into tile_buffers
1612 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows,
1613 &pbi->tile_buffers);
1615 // Sort the buffers based on size in descending order.
1616 qsort(pbi->tile_buffers, tile_cols, sizeof(pbi->tile_buffers[0]),
1617 compare_tile_buffers);
1619 if (num_workers == tile_cols) {
1620 // Rearrange the tile buffers such that the largest, and
1621 // presumably the most difficult, tile will be decoded in the main thread.
1622 // This should help minimize the number of instances where the main thread
1623 // is waiting for a worker to complete.
1624 const TileBuffer largest = pbi->tile_buffers[0];
1625 memmove(pbi->tile_buffers, pbi->tile_buffers + 1,
1626 (tile_cols - 1) * sizeof(pbi->tile_buffers[0]));
1627 pbi->tile_buffers[tile_cols - 1] = largest;
1629 int start = 0, end = tile_cols - 2;
1632 // Interleave the tiles to distribute the load between threads, assuming a
1633 // larger tile implies it is more difficult to decode.
1634 while (start < end) {
1635 tmp = pbi->tile_buffers[start];
1636 pbi->tile_buffers[start] = pbi->tile_buffers[end];
1637 pbi->tile_buffers[end] = tmp;
1643 // Initialize thread frame counts.
1644 if (!cm->frame_parallel_decoding_mode) {
1645 for (n = 0; n < num_workers; ++n) {
1646 TileWorkerData *const tile_data =
1647 (TileWorkerData *)pbi->tile_workers[n].data1;
1648 vp9_zero(tile_data->counts);
1653 const int base = tile_cols / num_workers;
1654 const int remain = tile_cols % num_workers;
1657 for (n = 0; n < num_workers; ++n) {
1658 const int count = base + (remain + n) / num_workers;
1659 VPxWorker *const worker = &pbi->tile_workers[n];
1660 TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
1662 tile_data->buf_start = buf_start;
1663 tile_data->buf_end = buf_start + count - 1;
1664 tile_data->data_end = data_end;
1667 worker->had_error = 0;
1668 if (n == num_workers - 1) {
1669 assert(tile_data->buf_end == tile_cols - 1);
1670 winterface->execute(worker);
1672 winterface->launch(worker);
1676 for (; n > 0; --n) {
1677 VPxWorker *const worker = &pbi->tile_workers[n - 1];
1678 TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
1679 // TODO(jzern): The tile may have specific error data associated with
1680 // its vpx_internal_error_info which could be propagated to the main info
1681 // in cm. Additionally once the threads have been synced and an error is
1682 // detected, there's no point in continuing to decode tiles.
1683 pbi->mb.corrupted |= !winterface->sync(worker);
1684 if (!bit_reader_end) bit_reader_end = tile_data->data_end;
1688 // Accumulate thread frame counts.
1689 if (!cm->frame_parallel_decoding_mode) {
1690 for (n = 0; n < num_workers; ++n) {
1691 TileWorkerData *const tile_data =
1692 (TileWorkerData *)pbi->tile_workers[n].data1;
1693 vp9_accumulate_frame_counts(&cm->counts, &tile_data->counts, 1);
1697 assert(bit_reader_end || pbi->mb.corrupted);
1698 return bit_reader_end;
1701 static void error_handler(void *data) {
1702 VP9_COMMON *const cm = (VP9_COMMON *)data;
1703 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1706 static void read_bitdepth_colorspace_sampling(VP9_COMMON *cm,
1707 struct vpx_read_bit_buffer *rb) {
1708 if (cm->profile >= PROFILE_2) {
1709 cm->bit_depth = vpx_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1710 #if CONFIG_VP9_HIGHBITDEPTH
1711 cm->use_highbitdepth = 1;
1714 cm->bit_depth = VPX_BITS_8;
1715 #if CONFIG_VP9_HIGHBITDEPTH
1716 cm->use_highbitdepth = 0;
1719 cm->color_space = vpx_rb_read_literal(rb, 3);
1720 if (cm->color_space != VPX_CS_SRGB) {
1721 cm->color_range = (vpx_color_range_t)vpx_rb_read_bit(rb);
1722 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1723 cm->subsampling_x = vpx_rb_read_bit(rb);
1724 cm->subsampling_y = vpx_rb_read_bit(rb);
1725 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1726 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1727 "4:2:0 color not supported in profile 1 or 3");
1728 if (vpx_rb_read_bit(rb))
1729 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1730 "Reserved bit set");
1732 cm->subsampling_y = cm->subsampling_x = 1;
1735 cm->color_range = VPX_CR_FULL_RANGE;
1736 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1737 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1738 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1739 cm->subsampling_y = cm->subsampling_x = 0;
1740 if (vpx_rb_read_bit(rb))
1741 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1742 "Reserved bit set");
1744 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1745 "4:4:4 color not supported in profile 0 or 2");
1750 static size_t read_uncompressed_header(VP9Decoder *pbi,
1751 struct vpx_read_bit_buffer *rb) {
1752 VP9_COMMON *const cm = &pbi->common;
1753 BufferPool *const pool = cm->buffer_pool;
1754 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1755 int i, mask, ref_index = 0;
1758 cm->last_frame_type = cm->frame_type;
1759 cm->last_intra_only = cm->intra_only;
1761 if (vpx_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1762 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1763 "Invalid frame marker");
1765 cm->profile = vp9_read_profile(rb);
1766 #if CONFIG_VP9_HIGHBITDEPTH
1767 if (cm->profile >= MAX_PROFILES)
1768 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1769 "Unsupported bitstream profile");
1771 if (cm->profile >= PROFILE_2)
1772 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1773 "Unsupported bitstream profile");
1776 cm->show_existing_frame = vpx_rb_read_bit(rb);
1777 if (cm->show_existing_frame) {
1778 // Show an existing frame directly.
1779 const int frame_to_show = cm->ref_frame_map[vpx_rb_read_literal(rb, 3)];
1780 lock_buffer_pool(pool);
1781 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1782 unlock_buffer_pool(pool);
1783 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1784 "Buffer %d does not contain a decoded frame",
1788 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1789 unlock_buffer_pool(pool);
1790 pbi->refresh_frame_flags = 0;
1791 cm->lf.filter_level = 0;
1794 if (pbi->frame_parallel_decode) {
1795 for (i = 0; i < REF_FRAMES; ++i)
1796 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1801 cm->frame_type = (FRAME_TYPE)vpx_rb_read_bit(rb);
1802 cm->show_frame = vpx_rb_read_bit(rb);
1803 cm->error_resilient_mode = vpx_rb_read_bit(rb);
1805 if (cm->frame_type == KEY_FRAME) {
1806 if (!vp9_read_sync_code(rb))
1807 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1808 "Invalid frame sync code");
1810 read_bitdepth_colorspace_sampling(cm, rb);
1811 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1813 for (i = 0; i < REFS_PER_FRAME; ++i) {
1814 cm->frame_refs[i].idx = INVALID_IDX;
1815 cm->frame_refs[i].buf = NULL;
1818 setup_frame_size(cm, rb);
1819 if (pbi->need_resync) {
1820 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1821 pbi->need_resync = 0;
1824 cm->intra_only = cm->show_frame ? 0 : vpx_rb_read_bit(rb);
1826 cm->reset_frame_context =
1827 cm->error_resilient_mode ? 0 : vpx_rb_read_literal(rb, 2);
1829 if (cm->intra_only) {
1830 if (!vp9_read_sync_code(rb))
1831 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1832 "Invalid frame sync code");
1833 if (cm->profile > PROFILE_0) {
1834 read_bitdepth_colorspace_sampling(cm, rb);
1836 // NOTE: The intra-only frame header does not include the specification
1837 // of either the color format or color sub-sampling in profile 0. VP9
1838 // specifies that the default color format should be YUV 4:2:0 in this
1839 // case (normative).
1840 cm->color_space = VPX_CS_BT_601;
1841 cm->color_range = VPX_CR_STUDIO_RANGE;
1842 cm->subsampling_y = cm->subsampling_x = 1;
1843 cm->bit_depth = VPX_BITS_8;
1844 #if CONFIG_VP9_HIGHBITDEPTH
1845 cm->use_highbitdepth = 0;
1849 pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1850 setup_frame_size(cm, rb);
1851 if (pbi->need_resync) {
1852 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1853 pbi->need_resync = 0;
1855 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1856 pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1857 for (i = 0; i < REFS_PER_FRAME; ++i) {
1858 const int ref = vpx_rb_read_literal(rb, REF_FRAMES_LOG2);
1859 const int idx = cm->ref_frame_map[ref];
1860 RefBuffer *const ref_frame = &cm->frame_refs[i];
1861 ref_frame->idx = idx;
1862 ref_frame->buf = &frame_bufs[idx].buf;
1863 cm->ref_frame_sign_bias[LAST_FRAME + i] = vpx_rb_read_bit(rb);
1866 setup_frame_size_with_refs(cm, rb);
1868 cm->allow_high_precision_mv = vpx_rb_read_bit(rb);
1869 cm->interp_filter = read_interp_filter(rb);
1871 for (i = 0; i < REFS_PER_FRAME; ++i) {
1872 RefBuffer *const ref_buf = &cm->frame_refs[i];
1873 #if CONFIG_VP9_HIGHBITDEPTH
1874 vp9_setup_scale_factors_for_frame(
1875 &ref_buf->sf, ref_buf->buf->y_crop_width,
1876 ref_buf->buf->y_crop_height, cm->width, cm->height,
1877 cm->use_highbitdepth);
1879 vp9_setup_scale_factors_for_frame(
1880 &ref_buf->sf, ref_buf->buf->y_crop_width,
1881 ref_buf->buf->y_crop_height, cm->width, cm->height);
1886 #if CONFIG_VP9_HIGHBITDEPTH
1887 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1889 get_frame_new_buffer(cm)->color_space = cm->color_space;
1890 get_frame_new_buffer(cm)->color_range = cm->color_range;
1891 get_frame_new_buffer(cm)->render_width = cm->render_width;
1892 get_frame_new_buffer(cm)->render_height = cm->render_height;
1894 if (pbi->need_resync) {
1895 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1896 "Keyframe / intra-only frame required to reset decoder"
1900 if (!cm->error_resilient_mode) {
1901 cm->refresh_frame_context = vpx_rb_read_bit(rb);
1902 cm->frame_parallel_decoding_mode = vpx_rb_read_bit(rb);
1903 if (!cm->frame_parallel_decoding_mode) vp9_zero(cm->counts);
1905 cm->refresh_frame_context = 0;
1906 cm->frame_parallel_decoding_mode = 1;
1909 // This flag will be overridden by the call to vp9_setup_past_independence
1910 // below, forcing the use of context 0 for those frame types.
1911 cm->frame_context_idx = vpx_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1913 // Generate next_ref_frame_map.
1914 lock_buffer_pool(pool);
1915 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1917 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1918 ++frame_bufs[cm->new_fb_idx].ref_count;
1920 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1922 // Current thread holds the reference frame.
1923 if (cm->ref_frame_map[ref_index] >= 0)
1924 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1928 for (; ref_index < REF_FRAMES; ++ref_index) {
1929 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1930 // Current thread holds the reference frame.
1931 if (cm->ref_frame_map[ref_index] >= 0)
1932 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1934 unlock_buffer_pool(pool);
1935 pbi->hold_ref_buf = 1;
1937 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1938 vp9_setup_past_independence(cm);
1940 setup_loopfilter(&cm->lf, rb);
1941 setup_quantization(cm, &pbi->mb, rb);
1942 setup_segmentation(&cm->seg, rb);
1943 setup_segmentation_dequant(cm);
1945 setup_tile_info(cm, rb);
1946 sz = vpx_rb_read_literal(rb, 16);
1949 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1950 "Invalid header size");
1955 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1956 size_t partition_size) {
1957 VP9_COMMON *const cm = &pbi->common;
1958 MACROBLOCKD *const xd = &pbi->mb;
1959 FRAME_CONTEXT *const fc = cm->fc;
1963 if (vpx_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1964 pbi->decrypt_state))
1965 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1966 "Failed to allocate bool decoder 0");
1968 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1969 if (cm->tx_mode == TX_MODE_SELECT) read_tx_mode_probs(&fc->tx_probs, &r);
1970 read_coef_probs(fc, cm->tx_mode, &r);
1972 for (k = 0; k < SKIP_CONTEXTS; ++k)
1973 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1975 if (!frame_is_intra_only(cm)) {
1976 nmv_context *const nmvc = &fc->nmvc;
1979 read_inter_mode_probs(fc, &r);
1981 if (cm->interp_filter == SWITCHABLE) read_switchable_interp_probs(fc, &r);
1983 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1984 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1986 cm->reference_mode = read_frame_reference_mode(cm, &r);
1987 if (cm->reference_mode != SINGLE_REFERENCE)
1988 setup_compound_reference_mode(cm);
1989 read_frame_reference_mode_probs(cm, &r);
1991 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1992 for (i = 0; i < INTRA_MODES - 1; ++i)
1993 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1995 for (j = 0; j < PARTITION_CONTEXTS; ++j)
1996 for (i = 0; i < PARTITION_TYPES - 1; ++i)
1997 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1999 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2002 return vpx_reader_has_error(&r);
2005 static struct vpx_read_bit_buffer *init_read_bit_buffer(
2006 VP9Decoder *pbi, struct vpx_read_bit_buffer *rb, const uint8_t *data,
2007 const uint8_t *data_end, uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2009 rb->error_handler = error_handler;
2010 rb->error_handler_data = &pbi->common;
2011 if (pbi->decrypt_cb) {
2012 const int n = (int)VPXMIN(MAX_VP9_HEADER_SIZE, data_end - data);
2013 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2014 rb->bit_buffer = clear_data;
2015 rb->bit_buffer_end = clear_data + n;
2017 rb->bit_buffer = data;
2018 rb->bit_buffer_end = data_end;
2023 //------------------------------------------------------------------------------
2025 int vp9_read_sync_code(struct vpx_read_bit_buffer *const rb) {
2026 return vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2027 vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2028 vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2031 void vp9_read_frame_size(struct vpx_read_bit_buffer *rb, int *width,
2033 *width = vpx_rb_read_literal(rb, 16) + 1;
2034 *height = vpx_rb_read_literal(rb, 16) + 1;
2037 BITSTREAM_PROFILE vp9_read_profile(struct vpx_read_bit_buffer *rb) {
2038 int profile = vpx_rb_read_bit(rb);
2039 profile |= vpx_rb_read_bit(rb) << 1;
2040 if (profile > 2) profile += vpx_rb_read_bit(rb);
2041 return (BITSTREAM_PROFILE)profile;
2044 void vp9_decode_frame(VP9Decoder *pbi, const uint8_t *data,
2045 const uint8_t *data_end, const uint8_t **p_data_end) {
2046 VP9_COMMON *const cm = &pbi->common;
2047 MACROBLOCKD *const xd = &pbi->mb;
2048 struct vpx_read_bit_buffer rb;
2049 int context_updated = 0;
2050 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2051 const size_t first_partition_size = read_uncompressed_header(
2052 pbi, init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2053 const int tile_rows = 1 << cm->log2_tile_rows;
2054 const int tile_cols = 1 << cm->log2_tile_cols;
2055 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2056 xd->cur_buf = new_fb;
2058 if (!first_partition_size) {
2059 // showing a frame directly
2060 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2064 data += vpx_rb_bytes_read(&rb);
2065 if (!read_is_valid(data, first_partition_size, data_end))
2066 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2067 "Truncated packet or corrupt header length");
2069 cm->use_prev_frame_mvs =
2070 !cm->error_resilient_mode && cm->width == cm->last_width &&
2071 cm->height == cm->last_height && !cm->last_intra_only &&
2072 cm->last_show_frame && (cm->last_frame_type != KEY_FRAME);
2074 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2076 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2077 if (!cm->fc->initialized)
2078 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2079 "Uninitialized entropy context.");
2082 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2083 if (new_fb->corrupted)
2084 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2085 "Decode failed. Frame data header is corrupted.");
2087 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2088 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2091 // If encoded in frame parallel mode, frame context is ready after decoding
2092 // the frame header.
2093 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2094 VPxWorker *const worker = pbi->frame_worker_owner;
2095 FrameWorkerData *const frame_worker_data = worker->data1;
2096 if (cm->refresh_frame_context) {
2097 context_updated = 1;
2098 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2100 vp9_frameworker_lock_stats(worker);
2101 pbi->cur_buf->row = -1;
2102 pbi->cur_buf->col = -1;
2103 frame_worker_data->frame_context_ready = 1;
2104 // Signal the main thread that context is ready.
2105 vp9_frameworker_signal_stats(worker);
2106 vp9_frameworker_unlock_stats(worker);
2109 if (pbi->tile_worker_data == NULL ||
2110 (tile_cols * tile_rows) != pbi->total_tiles) {
2111 const int num_tile_workers =
2112 tile_cols * tile_rows + ((pbi->max_threads > 1) ? pbi->max_threads : 0);
2113 const size_t twd_size = num_tile_workers * sizeof(*pbi->tile_worker_data);
2114 // Ensure tile data offsets will be properly aligned. This may fail on
2115 // platforms without DECLARE_ALIGNED().
2116 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
2117 vpx_free(pbi->tile_worker_data);
2118 CHECK_MEM_ERROR(cm, pbi->tile_worker_data, vpx_memalign(32, twd_size));
2119 pbi->total_tiles = tile_rows * tile_cols;
2122 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2123 // Multi-threaded tile decoder
2124 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2125 if (!xd->corrupted) {
2126 if (!cm->skip_loop_filter) {
2127 // If multiple threads are used to decode tiles, then we use those
2128 // threads to do parallel loopfiltering.
2129 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane, cm->lf.filter_level,
2130 0, 0, pbi->tile_workers, pbi->num_tile_workers,
2134 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2135 "Decode failed. Frame data is corrupted.");
2138 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2141 if (!xd->corrupted) {
2142 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2143 vp9_adapt_coef_probs(cm);
2145 if (!frame_is_intra_only(cm)) {
2146 vp9_adapt_mode_probs(cm);
2147 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2151 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2152 "Decode failed. Frame data is corrupted.");
2155 // Non frame parallel update frame context here.
2156 if (cm->refresh_frame_context && !context_updated)
2157 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;