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_dsp/bitreader_buffer.h"
18 #include "vpx_dsp/bitreader.h"
19 #include "vpx_mem/vpx_mem.h"
20 #include "vpx_ports/mem.h"
21 #include "vpx_ports/mem_ops.h"
22 #include "vpx_scale/vpx_scale.h"
23 #include "vpx_util/vpx_thread.h"
25 #include "vp9/common/vp9_alloccommon.h"
26 #include "vp9/common/vp9_common.h"
27 #include "vp9/common/vp9_entropy.h"
28 #include "vp9/common/vp9_entropymode.h"
29 #include "vp9/common/vp9_idct.h"
30 #include "vp9/common/vp9_thread_common.h"
31 #include "vp9/common/vp9_pred_common.h"
32 #include "vp9/common/vp9_quant_common.h"
33 #include "vp9/common/vp9_reconintra.h"
34 #include "vp9/common/vp9_reconinter.h"
35 #include "vp9/common/vp9_seg_common.h"
36 #include "vp9/common/vp9_tile_common.h"
38 #include "vp9/decoder/vp9_decodeframe.h"
39 #include "vp9/decoder/vp9_detokenize.h"
40 #include "vp9/decoder/vp9_decodemv.h"
41 #include "vp9/decoder/vp9_decoder.h"
42 #include "vp9/decoder/vp9_dsubexp.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 void predict_and_reconstruct_intra_block(MACROBLOCKD *const xd,
366 MB_MODE_INFO *const mbmi,
370 struct macroblockd_plane *const pd = &xd->plane[plane];
371 PREDICTION_MODE mode = (plane == 0) ? mbmi->mode : mbmi->uv_mode;
373 dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
375 if (mbmi->sb_type < BLOCK_8X8)
377 mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
379 vp9_predict_intra_block(xd, pd->n4_wl, tx_size, mode,
380 dst, pd->dst.stride, dst, pd->dst.stride,
384 const TX_TYPE tx_type = (plane || xd->lossless) ?
385 DCT_DCT : intra_mode_to_tx_type_lookup[mode];
386 const scan_order *sc = (plane || xd->lossless) ?
387 &vp9_default_scan_orders[tx_size] : &vp9_scan_orders[tx_size][tx_type];
388 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size,
389 r, mbmi->segment_id);
390 inverse_transform_block_intra(xd, plane, tx_type, tx_size,
391 dst, pd->dst.stride, eob);
395 static int reconstruct_inter_block(MACROBLOCKD *const xd, vp9_reader *r,
396 MB_MODE_INFO *const mbmi, int plane,
397 int row, int col, TX_SIZE tx_size) {
398 struct macroblockd_plane *const pd = &xd->plane[plane];
399 const scan_order *sc = &vp9_default_scan_orders[tx_size];
400 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size, r,
403 inverse_transform_block_inter(xd, plane, tx_size,
404 &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
405 pd->dst.stride, eob);
409 static void build_mc_border(const uint8_t *src, int src_stride,
410 uint8_t *dst, int dst_stride,
411 int x, int y, int b_w, int b_h, int w, int h) {
412 // Get a pointer to the start of the real data for this row.
413 const uint8_t *ref_row = src - x - y * src_stride;
416 ref_row += (h - 1) * src_stride;
418 ref_row += y * src_stride;
422 int left = x < 0 ? -x : 0;
433 copy = b_w - left - right;
436 memset(dst, ref_row[0], left);
439 memcpy(dst + left, ref_row + x + left, copy);
442 memset(dst + left + copy, ref_row[w - 1], right);
448 ref_row += src_stride;
452 #if CONFIG_VP9_HIGHBITDEPTH
453 static void high_build_mc_border(const uint8_t *src8, int src_stride,
454 uint16_t *dst, int dst_stride,
455 int x, int y, int b_w, int b_h,
457 // Get a pointer to the start of the real data for this row.
458 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
459 const uint16_t *ref_row = src - x - y * src_stride;
462 ref_row += (h - 1) * src_stride;
464 ref_row += y * src_stride;
468 int left = x < 0 ? -x : 0;
479 copy = b_w - left - right;
482 vpx_memset16(dst, ref_row[0], left);
485 memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
488 vpx_memset16(dst + left + copy, ref_row[w - 1], right);
494 ref_row += src_stride;
497 #endif // CONFIG_VP9_HIGHBITDEPTH
499 #if CONFIG_VP9_HIGHBITDEPTH
500 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
501 int x0, int y0, int b_w, int b_h,
502 int frame_width, int frame_height,
504 uint8_t *const dst, int dst_buf_stride,
505 int subpel_x, int subpel_y,
506 const InterpKernel *kernel,
507 const struct scale_factors *sf,
509 int w, int h, int ref, int xs, int ys) {
510 DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
511 const uint8_t *buf_ptr;
513 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
514 high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w,
515 x0, y0, b_w, b_h, frame_width, frame_height);
516 buf_ptr = CONVERT_TO_BYTEPTR(mc_buf_high) + border_offset;
518 build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w,
519 x0, y0, b_w, b_h, frame_width, frame_height);
520 buf_ptr = ((uint8_t *)mc_buf_high) + border_offset;
523 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
524 high_inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
525 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
527 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
528 subpel_y, sf, w, h, ref, kernel, xs, ys);
532 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
533 int x0, int y0, int b_w, int b_h,
534 int frame_width, int frame_height,
536 uint8_t *const dst, int dst_buf_stride,
537 int subpel_x, int subpel_y,
538 const InterpKernel *kernel,
539 const struct scale_factors *sf,
540 int w, int h, int ref, int xs, int ys) {
541 DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
542 const uint8_t *buf_ptr;
544 build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w,
545 x0, y0, b_w, b_h, frame_width, frame_height);
546 buf_ptr = mc_buf + border_offset;
548 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
549 subpel_y, sf, w, h, ref, kernel, xs, ys);
551 #endif // CONFIG_VP9_HIGHBITDEPTH
553 static void dec_build_inter_predictors(VP9Decoder *const pbi, MACROBLOCKD *xd,
554 int plane, int bw, int bh, int x,
555 int y, int w, int h, int mi_x, int mi_y,
556 const InterpKernel *kernel,
557 const struct scale_factors *sf,
558 struct buf_2d *pre_buf,
559 struct buf_2d *dst_buf, const MV* mv,
560 RefCntBuffer *ref_frame_buf,
561 int is_scaled, int ref) {
562 struct macroblockd_plane *const pd = &xd->plane[plane];
563 uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
565 int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height,
566 buf_stride, subpel_x, subpel_y;
567 uint8_t *ref_frame, *buf_ptr;
569 // Get reference frame pointer, width and height.
571 frame_width = ref_frame_buf->buf.y_crop_width;
572 frame_height = ref_frame_buf->buf.y_crop_height;
573 ref_frame = ref_frame_buf->buf.y_buffer;
575 frame_width = ref_frame_buf->buf.uv_crop_width;
576 frame_height = ref_frame_buf->buf.uv_crop_height;
577 ref_frame = plane == 1 ? ref_frame_buf->buf.u_buffer
578 : ref_frame_buf->buf.v_buffer;
582 const MV mv_q4 = clamp_mv_to_umv_border_sb(xd, mv, bw, bh,
585 // Co-ordinate of containing block to pixel precision.
586 int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
587 int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
589 // Co-ordinate of the block to 1/16th pixel precision.
590 x0_16 = (x_start + x) << SUBPEL_BITS;
591 y0_16 = (y_start + y) << SUBPEL_BITS;
593 // Co-ordinate of current block in reference frame
594 // to 1/16th pixel precision.
595 x0_16 = sf->scale_value_x(x0_16, sf);
596 y0_16 = sf->scale_value_y(y0_16, sf);
598 // Map the top left corner of the block into the reference frame.
599 x0 = sf->scale_value_x(x_start + x, sf);
600 y0 = sf->scale_value_y(y_start + y, sf);
602 // Scale the MV and incorporate the sub-pixel offset of the block
603 // in the reference frame.
604 scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
608 // Co-ordinate of containing block to pixel precision.
609 x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
610 y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
612 // Co-ordinate of the block to 1/16th pixel precision.
613 x0_16 = x0 << SUBPEL_BITS;
614 y0_16 = y0 << SUBPEL_BITS;
616 scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
617 scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
620 subpel_x = scaled_mv.col & SUBPEL_MASK;
621 subpel_y = scaled_mv.row & SUBPEL_MASK;
623 // Calculate the top left corner of the best matching block in the
625 x0 += scaled_mv.col >> SUBPEL_BITS;
626 y0 += scaled_mv.row >> SUBPEL_BITS;
627 x0_16 += scaled_mv.col;
628 y0_16 += scaled_mv.row;
630 // Get reference block pointer.
631 buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
632 buf_stride = pre_buf->stride;
634 // Do border extension if there is motion or the
635 // width/height is not a multiple of 8 pixels.
636 if (is_scaled || scaled_mv.col || scaled_mv.row ||
637 (frame_width & 0x7) || (frame_height & 0x7)) {
638 int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
640 // Get reference block bottom right horizontal coordinate.
641 int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
642 int x_pad = 0, y_pad = 0;
644 if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
645 x0 -= VP9_INTERP_EXTEND - 1;
646 x1 += VP9_INTERP_EXTEND;
650 if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
651 y0 -= VP9_INTERP_EXTEND - 1;
652 y1 += VP9_INTERP_EXTEND;
656 // Wait until reference block is ready. Pad 7 more pixels as last 7
657 // pixels of each superblock row can be changed by next superblock row.
658 if (pbi->frame_parallel_decode)
659 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
660 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
662 // Skip border extension if block is inside the frame.
663 if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
664 y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
665 // Extend the border.
666 const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
667 const int b_w = x1 - x0 + 1;
668 const int b_h = y1 - y0 + 1;
669 const int border_offset = y_pad * 3 * b_w + x_pad * 3;
671 extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h,
672 frame_width, frame_height, border_offset,
673 dst, dst_buf->stride,
676 #if CONFIG_VP9_HIGHBITDEPTH
683 // Wait until reference block is ready. Pad 7 more pixels as last 7
684 // pixels of each superblock row can be changed by next superblock row.
685 if (pbi->frame_parallel_decode) {
686 const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
687 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
688 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
691 #if CONFIG_VP9_HIGHBITDEPTH
692 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
693 high_inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
694 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
696 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
697 subpel_y, sf, w, h, ref, kernel, xs, ys);
700 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
701 subpel_y, sf, w, h, ref, kernel, xs, ys);
702 #endif // CONFIG_VP9_HIGHBITDEPTH
705 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
707 int mi_row, int mi_col) {
709 const int mi_x = mi_col * MI_SIZE;
710 const int mi_y = mi_row * MI_SIZE;
711 const MODE_INFO *mi = xd->mi[0];
712 const InterpKernel *kernel = vp9_filter_kernels[mi->mbmi.interp_filter];
713 const BLOCK_SIZE sb_type = mi->mbmi.sb_type;
714 const int is_compound = has_second_ref(&mi->mbmi);
716 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
717 struct macroblockd_plane *const pd = &xd->plane[plane];
718 struct buf_2d *const dst_buf = &pd->dst;
719 const int num_4x4_w = pd->n4_w;
720 const int num_4x4_h = pd->n4_h;
722 const int n4w_x4 = 4 * num_4x4_w;
723 const int n4h_x4 = 4 * num_4x4_h;
726 for (ref = 0; ref < 1 + is_compound; ++ref) {
727 const struct scale_factors *const sf = &xd->block_refs[ref]->sf;
728 struct buf_2d *const pre_buf = &pd->pre[ref];
729 const int idx = xd->block_refs[ref]->idx;
730 BufferPool *const pool = pbi->common.buffer_pool;
731 RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
732 const int is_scaled = vp9_is_scaled(sf);
734 if (sb_type < BLOCK_8X8) {
736 for (y = 0; y < num_4x4_h; ++y) {
737 for (x = 0; x < num_4x4_w; ++x) {
738 const MV mv = average_split_mvs(pd, mi, ref, i++);
739 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
740 4 * x, 4 * y, 4, 4, mi_x, mi_y, kernel,
741 sf, pre_buf, dst_buf, &mv,
742 ref_frame_buf, is_scaled, ref);
746 const MV mv = mi->mbmi.mv[ref].as_mv;
747 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
748 0, 0, n4w_x4, n4h_x4, mi_x, mi_y, kernel,
749 sf, pre_buf, dst_buf, &mv, ref_frame_buf,
756 static INLINE TX_SIZE dec_get_uv_tx_size(const MB_MODE_INFO *mbmi,
757 int n4_wl, int n4_hl) {
758 // get minimum log2 num4x4s dimension
759 const int x = MIN(n4_wl, n4_hl);
760 return MIN(mbmi->tx_size, x);
763 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
765 for (i = 0; i < MAX_MB_PLANE; i++) {
766 struct macroblockd_plane *const pd = &xd->plane[i];
767 memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
768 memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
772 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
775 for (i = 0; i < MAX_MB_PLANE; i++) {
776 xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
777 xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
778 xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
779 xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
783 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
784 BLOCK_SIZE bsize, int mi_row, int mi_col,
785 int bw, int bh, int x_mis, int y_mis,
787 const int offset = mi_row * cm->mi_stride + mi_col;
789 const TileInfo *const tile = &xd->tile;
791 xd->mi = cm->mi_grid_visible + offset;
792 xd->mi[0] = &cm->mi[offset];
793 // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
794 // passing bsize from decode_partition().
795 xd->mi[0]->mbmi.sb_type = bsize;
796 for (y = 0; y < y_mis; ++y)
797 for (x = !y; x < x_mis; ++x) {
798 xd->mi[y * cm->mi_stride + x] = xd->mi[0];
801 set_plane_n4(xd, bw, bh, bwl, bhl);
803 set_skip_context(xd, mi_row, mi_col);
805 // Distance of Mb to the various image edges. These are specified to 8th pel
806 // as they are always compared to values that are in 1/8th pel units
807 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
809 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
810 return &xd->mi[0]->mbmi;
813 static void decode_block(VP9Decoder *const pbi, MACROBLOCKD *const xd,
814 int mi_row, int mi_col,
815 vp9_reader *r, BLOCK_SIZE bsize,
817 VP9_COMMON *const cm = &pbi->common;
818 const int less8x8 = bsize < BLOCK_8X8;
819 const int bw = 1 << (bwl - 1);
820 const int bh = 1 << (bhl - 1);
821 const int x_mis = MIN(bw, cm->mi_cols - mi_col);
822 const int y_mis = MIN(bh, cm->mi_rows - mi_row);
824 MB_MODE_INFO *mbmi = set_offsets(cm, xd, bsize, mi_row, mi_col,
825 bw, bh, x_mis, y_mis, bwl, bhl);
827 if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
828 const BLOCK_SIZE uv_subsize =
829 ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
830 if (uv_subsize == BLOCK_INVALID)
831 vpx_internal_error(xd->error_info,
832 VPX_CODEC_CORRUPT_FRAME, "Invalid block size.");
835 vp9_read_mode_info(pbi, xd, mi_row, mi_col, r, x_mis, y_mis);
838 dec_reset_skip_context(xd);
841 if (!is_inter_block(mbmi)) {
843 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
844 const struct macroblockd_plane *const pd = &xd->plane[plane];
845 const TX_SIZE tx_size =
846 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
848 const int num_4x4_w = pd->n4_w;
849 const int num_4x4_h = pd->n4_h;
850 const int step = (1 << tx_size);
852 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
853 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
854 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
855 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
857 for (row = 0; row < max_blocks_high; row += step)
858 for (col = 0; col < max_blocks_wide; col += step)
859 predict_and_reconstruct_intra_block(xd, r, mbmi, plane,
864 dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col);
871 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
872 const struct macroblockd_plane *const pd = &xd->plane[plane];
873 const TX_SIZE tx_size =
874 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
876 const int num_4x4_w = pd->n4_w;
877 const int num_4x4_h = pd->n4_h;
878 const int step = (1 << tx_size);
880 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
881 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
882 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
883 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
885 for (row = 0; row < max_blocks_high; row += step)
886 for (col = 0; col < max_blocks_wide; col += step)
887 eobtotal += reconstruct_inter_block(xd, r, mbmi, plane, row, col,
891 if (!less8x8 && eobtotal == 0)
892 mbmi->skip = 1; // skip loopfilter
896 xd->corrupted |= vp9_reader_has_error(r);
899 static INLINE int dec_partition_plane_context(const MACROBLOCKD *xd,
900 int mi_row, int mi_col,
902 const PARTITION_CONTEXT *above_ctx = xd->above_seg_context + mi_col;
903 const PARTITION_CONTEXT *left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
904 int above = (*above_ctx >> bsl) & 1 , left = (*left_ctx >> bsl) & 1;
908 return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
911 static INLINE void dec_update_partition_context(MACROBLOCKD *xd,
912 int mi_row, int mi_col,
915 PARTITION_CONTEXT *const above_ctx = xd->above_seg_context + mi_col;
916 PARTITION_CONTEXT *const left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
918 // update the partition context at the end notes. set partition bits
919 // of block sizes larger than the current one to be one, and partition
920 // bits of smaller block sizes to be zero.
921 memset(above_ctx, partition_context_lookup[subsize].above, bw);
922 memset(left_ctx, partition_context_lookup[subsize].left, bw);
925 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
927 int has_rows, int has_cols, int bsl) {
928 const int ctx = dec_partition_plane_context(xd, mi_row, mi_col, bsl);
929 const vp9_prob *const probs = get_partition_probs(xd, ctx);
930 FRAME_COUNTS *counts = xd->counts;
933 if (has_rows && has_cols)
934 p = (PARTITION_TYPE)vp9_read_tree(r, vp9_partition_tree, probs);
935 else if (!has_rows && has_cols)
936 p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
937 else if (has_rows && !has_cols)
938 p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
943 ++counts->partition[ctx][p];
948 // TODO(slavarnway): eliminate bsize and subsize in future commits
949 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
950 int mi_row, int mi_col,
951 vp9_reader* r, BLOCK_SIZE bsize, int n4x4_l2) {
952 VP9_COMMON *const cm = &pbi->common;
953 const int n8x8_l2 = n4x4_l2 - 1;
954 const int num_8x8_wh = 1 << n8x8_l2;
955 const int hbs = num_8x8_wh >> 1;
956 PARTITION_TYPE partition;
958 const int has_rows = (mi_row + hbs) < cm->mi_rows;
959 const int has_cols = (mi_col + hbs) < cm->mi_cols;
961 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
964 partition = read_partition(xd, mi_row, mi_col, r, has_rows, has_cols,
966 subsize = subsize_lookup[partition][bsize]; // get_subsize(bsize, partition);
968 // calculate bmode block dimensions (log 2)
969 xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
970 xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
971 decode_block(pbi, xd, mi_row, mi_col, r, subsize, 1, 1);
975 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n4x4_l2);
978 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n8x8_l2);
980 decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize, n4x4_l2,
984 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2, n4x4_l2);
986 decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2,
989 case PARTITION_SPLIT:
990 decode_partition(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2);
991 decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2);
992 decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize, n8x8_l2);
993 decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize,
997 assert(0 && "Invalid partition type");
1001 // update partition context
1002 if (bsize >= BLOCK_8X8 &&
1003 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
1004 dec_update_partition_context(xd, mi_row, mi_col, subsize, num_8x8_wh);
1007 static void setup_token_decoder(const uint8_t *data,
1008 const uint8_t *data_end,
1010 struct vpx_internal_error_info *error_info,
1012 vpx_decrypt_cb decrypt_cb,
1013 void *decrypt_state) {
1014 // Validate the calculated partition length. If the buffer
1015 // described by the partition can't be fully read, then restrict
1016 // it to the portion that can be (for EC mode) or throw an error.
1017 if (!read_is_valid(data, read_size, data_end))
1018 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1019 "Truncated packet or corrupt tile length");
1021 if (vp9_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
1022 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
1023 "Failed to allocate bool decoder %d", 1);
1026 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
1030 if (vp9_read_bit(r))
1031 for (i = 0; i < PLANE_TYPES; ++i)
1032 for (j = 0; j < REF_TYPES; ++j)
1033 for (k = 0; k < COEF_BANDS; ++k)
1034 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1035 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
1036 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
1039 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
1041 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1043 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1044 read_coef_probs_common(fc->coef_probs[tx_size], r);
1047 static void setup_segmentation(struct segmentation *seg,
1048 struct vp9_read_bit_buffer *rb) {
1051 seg->update_map = 0;
1052 seg->update_data = 0;
1054 seg->enabled = vp9_rb_read_bit(rb);
1058 // Segmentation map update
1059 seg->update_map = vp9_rb_read_bit(rb);
1060 if (seg->update_map) {
1061 for (i = 0; i < SEG_TREE_PROBS; i++)
1062 seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1065 seg->temporal_update = vp9_rb_read_bit(rb);
1066 if (seg->temporal_update) {
1067 for (i = 0; i < PREDICTION_PROBS; i++)
1068 seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1071 for (i = 0; i < PREDICTION_PROBS; i++)
1072 seg->pred_probs[i] = MAX_PROB;
1076 // Segmentation data update
1077 seg->update_data = vp9_rb_read_bit(rb);
1078 if (seg->update_data) {
1079 seg->abs_delta = vp9_rb_read_bit(rb);
1081 vp9_clearall_segfeatures(seg);
1083 for (i = 0; i < MAX_SEGMENTS; i++) {
1084 for (j = 0; j < SEG_LVL_MAX; j++) {
1086 const int feature_enabled = vp9_rb_read_bit(rb);
1087 if (feature_enabled) {
1088 vp9_enable_segfeature(seg, i, j);
1089 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1090 if (vp9_is_segfeature_signed(j))
1091 data = vp9_rb_read_bit(rb) ? -data : data;
1093 vp9_set_segdata(seg, i, j, data);
1099 static void setup_loopfilter(struct loopfilter *lf,
1100 struct vp9_read_bit_buffer *rb) {
1101 lf->filter_level = vp9_rb_read_literal(rb, 6);
1102 lf->sharpness_level = vp9_rb_read_literal(rb, 3);
1104 // Read in loop filter deltas applied at the MB level based on mode or ref
1106 lf->mode_ref_delta_update = 0;
1108 lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
1109 if (lf->mode_ref_delta_enabled) {
1110 lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
1111 if (lf->mode_ref_delta_update) {
1114 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1115 if (vp9_rb_read_bit(rb))
1116 lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1118 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1119 if (vp9_rb_read_bit(rb))
1120 lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1125 static INLINE int read_delta_q(struct vp9_read_bit_buffer *rb) {
1126 return vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
1129 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1130 struct vp9_read_bit_buffer *rb) {
1131 cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
1132 cm->y_dc_delta_q = read_delta_q(rb);
1133 cm->uv_dc_delta_q = read_delta_q(rb);
1134 cm->uv_ac_delta_q = read_delta_q(rb);
1135 cm->dequant_bit_depth = cm->bit_depth;
1136 xd->lossless = cm->base_qindex == 0 &&
1137 cm->y_dc_delta_q == 0 &&
1138 cm->uv_dc_delta_q == 0 &&
1139 cm->uv_ac_delta_q == 0;
1141 #if CONFIG_VP9_HIGHBITDEPTH
1142 xd->bd = (int)cm->bit_depth;
1146 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1147 // Build y/uv dequant values based on segmentation.
1148 if (cm->seg.enabled) {
1150 for (i = 0; i < MAX_SEGMENTS; ++i) {
1151 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1152 cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
1154 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1155 cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1157 cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1161 const int qindex = cm->base_qindex;
1162 // When segmentation is disabled, only the first value is used. The
1163 // remaining are don't cares.
1164 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1165 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1166 cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1168 cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1173 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
1174 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1178 return vp9_rb_read_bit(rb) ? SWITCHABLE
1179 : literal_to_filter[vp9_rb_read_literal(rb, 2)];
1182 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1183 cm->display_width = cm->width;
1184 cm->display_height = cm->height;
1185 if (vp9_rb_read_bit(rb))
1186 vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
1189 static void resize_mv_buffer(VP9_COMMON *cm) {
1190 vpx_free(cm->cur_frame->mvs);
1191 cm->cur_frame->mi_rows = cm->mi_rows;
1192 cm->cur_frame->mi_cols = cm->mi_cols;
1193 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1194 sizeof(*cm->cur_frame->mvs));
1197 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1198 #if CONFIG_SIZE_LIMIT
1199 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1200 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1201 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1202 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1204 if (cm->width != width || cm->height != height) {
1205 const int new_mi_rows =
1206 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1207 const int new_mi_cols =
1208 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1210 // Allocations in vp9_alloc_context_buffers() depend on individual
1211 // dimensions as well as the overall size.
1212 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1213 if (vp9_alloc_context_buffers(cm, width, height))
1214 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1215 "Failed to allocate context buffers");
1217 vp9_set_mb_mi(cm, width, height);
1219 vp9_init_context_buffers(cm);
1221 cm->height = height;
1223 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1224 cm->mi_cols > cm->cur_frame->mi_cols) {
1225 resize_mv_buffer(cm);
1229 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1231 BufferPool *const pool = cm->buffer_pool;
1232 vp9_read_frame_size(rb, &width, &height);
1233 resize_context_buffers(cm, width, height);
1234 setup_display_size(cm, rb);
1236 lock_buffer_pool(pool);
1237 if (vp9_realloc_frame_buffer(
1238 get_frame_new_buffer(cm), cm->width, cm->height,
1239 cm->subsampling_x, cm->subsampling_y,
1240 #if CONFIG_VP9_HIGHBITDEPTH
1241 cm->use_highbitdepth,
1243 VP9_DEC_BORDER_IN_PIXELS,
1245 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1247 unlock_buffer_pool(pool);
1248 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1249 "Failed to allocate frame buffer");
1251 unlock_buffer_pool(pool);
1253 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1254 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1255 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1256 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1259 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1260 int ref_xss, int ref_yss,
1261 vpx_bit_depth_t this_bit_depth,
1262 int this_xss, int this_yss) {
1263 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1264 ref_yss == this_yss;
1267 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1268 struct vp9_read_bit_buffer *rb) {
1271 int has_valid_ref_frame = 0;
1272 BufferPool *const pool = cm->buffer_pool;
1273 for (i = 0; i < REFS_PER_FRAME; ++i) {
1274 if (vp9_rb_read_bit(rb)) {
1275 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1276 width = buf->y_crop_width;
1277 height = buf->y_crop_height;
1284 vp9_read_frame_size(rb, &width, &height);
1286 if (width <= 0 || height <= 0)
1287 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1288 "Invalid frame size");
1290 // Check to make sure at least one of frames that this frame references
1291 // has valid dimensions.
1292 for (i = 0; i < REFS_PER_FRAME; ++i) {
1293 RefBuffer *const ref_frame = &cm->frame_refs[i];
1294 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1295 ref_frame->buf->y_crop_height,
1298 if (!has_valid_ref_frame)
1299 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1300 "Referenced frame has invalid size");
1301 for (i = 0; i < REFS_PER_FRAME; ++i) {
1302 RefBuffer *const ref_frame = &cm->frame_refs[i];
1303 if (!valid_ref_frame_img_fmt(
1304 ref_frame->buf->bit_depth,
1305 ref_frame->buf->subsampling_x,
1306 ref_frame->buf->subsampling_y,
1310 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1311 "Referenced frame has incompatible color format");
1314 resize_context_buffers(cm, width, height);
1315 setup_display_size(cm, rb);
1317 lock_buffer_pool(pool);
1318 if (vp9_realloc_frame_buffer(
1319 get_frame_new_buffer(cm), cm->width, cm->height,
1320 cm->subsampling_x, cm->subsampling_y,
1321 #if CONFIG_VP9_HIGHBITDEPTH
1322 cm->use_highbitdepth,
1324 VP9_DEC_BORDER_IN_PIXELS,
1326 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1328 unlock_buffer_pool(pool);
1329 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1330 "Failed to allocate frame buffer");
1332 unlock_buffer_pool(pool);
1334 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1335 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1336 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1337 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1340 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1341 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1342 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1345 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1346 cm->log2_tile_cols = min_log2_tile_cols;
1347 while (max_ones-- && vp9_rb_read_bit(rb))
1348 cm->log2_tile_cols++;
1350 if (cm->log2_tile_cols > 6)
1351 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1352 "Invalid number of tile columns");
1355 cm->log2_tile_rows = vp9_rb_read_bit(rb);
1356 if (cm->log2_tile_rows)
1357 cm->log2_tile_rows += vp9_rb_read_bit(rb);
1360 typedef struct TileBuffer {
1361 const uint8_t *data;
1363 int col; // only used with multi-threaded decoding
1366 // Reads the next tile returning its size and adjusting '*data' accordingly
1367 // based on 'is_last'.
1368 static void get_tile_buffer(const uint8_t *const data_end,
1370 struct vpx_internal_error_info *error_info,
1371 const uint8_t **data,
1372 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1377 if (!read_is_valid(*data, 4, data_end))
1378 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1379 "Truncated packet or corrupt tile length");
1383 decrypt_cb(decrypt_state, *data, be_data, 4);
1384 size = mem_get_be32(be_data);
1386 size = mem_get_be32(*data);
1390 if (size > (size_t)(data_end - *data))
1391 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1392 "Truncated packet or corrupt tile size");
1394 size = data_end - *data;
1403 static void get_tile_buffers(VP9Decoder *pbi,
1404 const uint8_t *data, const uint8_t *data_end,
1405 int tile_cols, int tile_rows,
1406 TileBuffer (*tile_buffers)[1 << 6]) {
1409 for (r = 0; r < tile_rows; ++r) {
1410 for (c = 0; c < tile_cols; ++c) {
1411 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1412 TileBuffer *const buf = &tile_buffers[r][c];
1414 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1415 pbi->decrypt_cb, pbi->decrypt_state, buf);
1420 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1421 const uint8_t *data,
1422 const uint8_t *data_end) {
1423 VP9_COMMON *const cm = &pbi->common;
1424 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1425 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1426 const int tile_cols = 1 << cm->log2_tile_cols;
1427 const int tile_rows = 1 << cm->log2_tile_rows;
1428 TileBuffer tile_buffers[4][1 << 6];
1429 int tile_row, tile_col;
1431 TileData *tile_data = NULL;
1433 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1434 pbi->lf_worker.data1 == NULL) {
1435 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1436 vpx_memalign(32, sizeof(LFWorkerData)));
1437 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1438 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1439 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1440 "Loop filter thread creation failed");
1444 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1445 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1446 // Be sure to sync as we might be resuming after a failed frame decode.
1447 winterface->sync(&pbi->lf_worker);
1448 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1452 assert(tile_rows <= 4);
1453 assert(tile_cols <= (1 << 6));
1455 // Note: this memset assumes above_context[0], [1] and [2]
1456 // are allocated as part of the same buffer.
1457 memset(cm->above_context, 0,
1458 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1460 memset(cm->above_seg_context, 0,
1461 sizeof(*cm->above_seg_context) * aligned_cols);
1463 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1465 if (pbi->tile_data == NULL ||
1466 (tile_cols * tile_rows) != pbi->total_tiles) {
1467 vpx_free(pbi->tile_data);
1471 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1472 pbi->total_tiles = tile_rows * tile_cols;
1475 // Load all tile information into tile_data.
1476 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1477 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1478 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1479 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1481 tile_data->xd = pbi->mb;
1482 tile_data->xd.corrupted = 0;
1483 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1485 vp9_zero(tile_data->dqcoeff);
1486 vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1487 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1488 &tile_data->bit_reader, pbi->decrypt_cb,
1489 pbi->decrypt_state);
1490 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1494 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1496 vp9_tile_set_row(&tile, cm, tile_row);
1497 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1498 mi_row += MI_BLOCK_SIZE) {
1499 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1500 const int col = pbi->inv_tile_order ?
1501 tile_cols - tile_col - 1 : tile_col;
1502 tile_data = pbi->tile_data + tile_cols * tile_row + col;
1503 vp9_tile_set_col(&tile, tile_data->cm, col);
1504 vp9_zero(tile_data->xd.left_context);
1505 vp9_zero(tile_data->xd.left_seg_context);
1506 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1507 mi_col += MI_BLOCK_SIZE) {
1508 decode_partition(pbi, &tile_data->xd, mi_row,
1509 mi_col, &tile_data->bit_reader, BLOCK_64X64, 4);
1511 pbi->mb.corrupted |= tile_data->xd.corrupted;
1512 if (pbi->mb.corrupted)
1513 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1514 "Failed to decode tile data");
1516 // Loopfilter one row.
1517 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1518 const int lf_start = mi_row - MI_BLOCK_SIZE;
1519 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1521 // delay the loopfilter by 1 macroblock row.
1522 if (lf_start < 0) continue;
1524 // decoding has completed: finish up the loop filter in this thread.
1525 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1527 winterface->sync(&pbi->lf_worker);
1528 lf_data->start = lf_start;
1529 lf_data->stop = mi_row;
1530 if (pbi->max_threads > 1) {
1531 winterface->launch(&pbi->lf_worker);
1533 winterface->execute(&pbi->lf_worker);
1536 // After loopfiltering, the last 7 row pixels in each superblock row may
1537 // still be changed by the longest loopfilter of the next superblock
1539 if (pbi->frame_parallel_decode)
1540 vp9_frameworker_broadcast(pbi->cur_buf,
1541 mi_row << MI_BLOCK_SIZE_LOG2);
1545 // Loopfilter remaining rows in the frame.
1546 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1547 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1548 winterface->sync(&pbi->lf_worker);
1549 lf_data->start = lf_data->stop;
1550 lf_data->stop = cm->mi_rows;
1551 winterface->execute(&pbi->lf_worker);
1554 // Get last tile data.
1555 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1557 if (pbi->frame_parallel_decode)
1558 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1559 return vp9_reader_find_end(&tile_data->bit_reader);
1562 static int tile_worker_hook(TileWorkerData *const tile_data,
1563 const TileInfo *const tile) {
1566 if (setjmp(tile_data->error_info.jmp)) {
1567 tile_data->error_info.setjmp = 0;
1568 tile_data->xd.corrupted = 1;
1572 tile_data->error_info.setjmp = 1;
1573 tile_data->xd.error_info = &tile_data->error_info;
1575 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1576 mi_row += MI_BLOCK_SIZE) {
1577 vp9_zero(tile_data->xd.left_context);
1578 vp9_zero(tile_data->xd.left_seg_context);
1579 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1580 mi_col += MI_BLOCK_SIZE) {
1581 decode_partition(tile_data->pbi, &tile_data->xd,
1582 mi_row, mi_col, &tile_data->bit_reader,
1586 return !tile_data->xd.corrupted;
1589 // sorts in descending order
1590 static int compare_tile_buffers(const void *a, const void *b) {
1591 const TileBuffer *const buf1 = (const TileBuffer*)a;
1592 const TileBuffer *const buf2 = (const TileBuffer*)b;
1593 return (int)(buf2->size - buf1->size);
1596 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1597 const uint8_t *data,
1598 const uint8_t *data_end) {
1599 VP9_COMMON *const cm = &pbi->common;
1600 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1601 const uint8_t *bit_reader_end = NULL;
1602 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1603 const int tile_cols = 1 << cm->log2_tile_cols;
1604 const int tile_rows = 1 << cm->log2_tile_rows;
1605 const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1606 TileBuffer tile_buffers[1][1 << 6];
1608 int final_worker = -1;
1610 assert(tile_cols <= (1 << 6));
1611 assert(tile_rows == 1);
1614 // TODO(jzern): See if we can remove the restriction of passing in max
1615 // threads to the decoder.
1616 if (pbi->num_tile_workers == 0) {
1617 const int num_threads = pbi->max_threads & ~1;
1619 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1620 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1621 // Ensure tile data offsets will be properly aligned. This may fail on
1622 // platforms without DECLARE_ALIGNED().
1623 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1624 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1625 vpx_memalign(32, num_threads *
1626 sizeof(*pbi->tile_worker_data)));
1627 CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1628 vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1629 for (i = 0; i < num_threads; ++i) {
1630 VPxWorker *const worker = &pbi->tile_workers[i];
1631 ++pbi->num_tile_workers;
1633 winterface->init(worker);
1634 if (i < num_threads - 1 && !winterface->reset(worker)) {
1635 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1636 "Tile decoder thread creation failed");
1641 // Reset tile decoding hook
1642 for (n = 0; n < num_workers; ++n) {
1643 VPxWorker *const worker = &pbi->tile_workers[n];
1644 winterface->sync(worker);
1645 worker->hook = (VPxWorkerHook)tile_worker_hook;
1646 worker->data1 = &pbi->tile_worker_data[n];
1647 worker->data2 = &pbi->tile_worker_info[n];
1650 // Note: this memset assumes above_context[0], [1] and [2]
1651 // are allocated as part of the same buffer.
1652 memset(cm->above_context, 0,
1653 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1654 memset(cm->above_seg_context, 0,
1655 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1657 // Load tile data into tile_buffers
1658 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1660 // Sort the buffers based on size in descending order.
1661 qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1662 compare_tile_buffers);
1664 // Rearrange the tile buffers such that per-tile group the largest, and
1665 // presumably the most difficult, tile will be decoded in the main thread.
1666 // This should help minimize the number of instances where the main thread is
1667 // waiting for a worker to complete.
1669 int group_start = 0;
1670 while (group_start < tile_cols) {
1671 const TileBuffer largest = tile_buffers[0][group_start];
1672 const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1673 memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1674 (group_end - group_start) * sizeof(tile_buffers[0][0]));
1675 tile_buffers[0][group_end] = largest;
1676 group_start = group_end + 1;
1680 // Initialize thread frame counts.
1681 if (!cm->frame_parallel_decoding_mode) {
1684 for (i = 0; i < num_workers; ++i) {
1685 TileWorkerData *const tile_data =
1686 (TileWorkerData*)pbi->tile_workers[i].data1;
1687 vp9_zero(tile_data->counts);
1692 while (n < tile_cols) {
1694 for (i = 0; i < num_workers && n < tile_cols; ++i) {
1695 VPxWorker *const worker = &pbi->tile_workers[i];
1696 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1697 TileInfo *const tile = (TileInfo*)worker->data2;
1698 TileBuffer *const buf = &tile_buffers[0][n];
1700 tile_data->pbi = pbi;
1701 tile_data->xd = pbi->mb;
1702 tile_data->xd.corrupted = 0;
1703 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1704 0 : &tile_data->counts;
1705 vp9_zero(tile_data->dqcoeff);
1706 vp9_tile_init(tile, cm, 0, buf->col);
1707 vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1708 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1709 &tile_data->bit_reader, pbi->decrypt_cb,
1710 pbi->decrypt_state);
1711 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1713 worker->had_error = 0;
1714 if (i == num_workers - 1 || n == tile_cols - 1) {
1715 winterface->execute(worker);
1717 winterface->launch(worker);
1720 if (buf->col == tile_cols - 1) {
1727 for (; i > 0; --i) {
1728 VPxWorker *const worker = &pbi->tile_workers[i - 1];
1729 // TODO(jzern): The tile may have specific error data associated with
1730 // its vpx_internal_error_info which could be propagated to the main info
1731 // in cm. Additionally once the threads have been synced and an error is
1732 // detected, there's no point in continuing to decode tiles.
1733 pbi->mb.corrupted |= !winterface->sync(worker);
1735 if (final_worker > -1) {
1736 TileWorkerData *const tile_data =
1737 (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1738 bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1742 // Accumulate thread frame counts.
1743 if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1744 for (i = 0; i < num_workers; ++i) {
1745 TileWorkerData *const tile_data =
1746 (TileWorkerData*)pbi->tile_workers[i].data1;
1747 vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1752 return bit_reader_end;
1755 static void error_handler(void *data) {
1756 VP9_COMMON *const cm = (VP9_COMMON *)data;
1757 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1760 static void read_bitdepth_colorspace_sampling(
1761 VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1762 if (cm->profile >= PROFILE_2) {
1763 cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1764 #if CONFIG_VP9_HIGHBITDEPTH
1765 cm->use_highbitdepth = 1;
1768 cm->bit_depth = VPX_BITS_8;
1769 #if CONFIG_VP9_HIGHBITDEPTH
1770 cm->use_highbitdepth = 0;
1773 cm->color_space = vp9_rb_read_literal(rb, 3);
1774 if (cm->color_space != VPX_CS_SRGB) {
1775 vp9_rb_read_bit(rb); // [16,235] (including xvycc) vs [0,255] range
1776 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1777 cm->subsampling_x = vp9_rb_read_bit(rb);
1778 cm->subsampling_y = vp9_rb_read_bit(rb);
1779 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1780 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1781 "4:2:0 color not supported in profile 1 or 3");
1782 if (vp9_rb_read_bit(rb))
1783 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1784 "Reserved bit set");
1786 cm->subsampling_y = cm->subsampling_x = 1;
1789 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1790 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1791 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1792 cm->subsampling_y = cm->subsampling_x = 0;
1793 if (vp9_rb_read_bit(rb))
1794 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1795 "Reserved bit set");
1797 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1798 "4:4:4 color not supported in profile 0 or 2");
1803 static size_t read_uncompressed_header(VP9Decoder *pbi,
1804 struct vp9_read_bit_buffer *rb) {
1805 VP9_COMMON *const cm = &pbi->common;
1806 BufferPool *const pool = cm->buffer_pool;
1807 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1808 int i, mask, ref_index = 0;
1811 cm->last_frame_type = cm->frame_type;
1812 cm->last_intra_only = cm->intra_only;
1814 if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1815 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1816 "Invalid frame marker");
1818 cm->profile = vp9_read_profile(rb);
1820 if (cm->profile >= MAX_PROFILES)
1821 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1822 "Unsupported bitstream profile");
1824 cm->show_existing_frame = vp9_rb_read_bit(rb);
1825 if (cm->show_existing_frame) {
1826 // Show an existing frame directly.
1827 const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1828 lock_buffer_pool(pool);
1829 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1830 unlock_buffer_pool(pool);
1831 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1832 "Buffer %d does not contain a decoded frame",
1836 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1837 unlock_buffer_pool(pool);
1838 pbi->refresh_frame_flags = 0;
1839 cm->lf.filter_level = 0;
1842 if (pbi->frame_parallel_decode) {
1843 for (i = 0; i < REF_FRAMES; ++i)
1844 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1849 cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1850 cm->show_frame = vp9_rb_read_bit(rb);
1851 cm->error_resilient_mode = vp9_rb_read_bit(rb);
1853 if (cm->frame_type == KEY_FRAME) {
1854 if (!vp9_read_sync_code(rb))
1855 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1856 "Invalid frame sync code");
1858 read_bitdepth_colorspace_sampling(cm, rb);
1859 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1861 for (i = 0; i < REFS_PER_FRAME; ++i) {
1862 cm->frame_refs[i].idx = INVALID_IDX;
1863 cm->frame_refs[i].buf = NULL;
1866 setup_frame_size(cm, rb);
1867 if (pbi->need_resync) {
1868 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1869 pbi->need_resync = 0;
1872 cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1874 cm->reset_frame_context = cm->error_resilient_mode ?
1875 0 : vp9_rb_read_literal(rb, 2);
1877 if (cm->intra_only) {
1878 if (!vp9_read_sync_code(rb))
1879 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1880 "Invalid frame sync code");
1881 if (cm->profile > PROFILE_0) {
1882 read_bitdepth_colorspace_sampling(cm, rb);
1884 // NOTE: The intra-only frame header does not include the specification
1885 // of either the color format or color sub-sampling in profile 0. VP9
1886 // specifies that the default color format should be YUV 4:2:0 in this
1887 // case (normative).
1888 cm->color_space = VPX_CS_BT_601;
1889 cm->subsampling_y = cm->subsampling_x = 1;
1890 cm->bit_depth = VPX_BITS_8;
1891 #if CONFIG_VP9_HIGHBITDEPTH
1892 cm->use_highbitdepth = 0;
1896 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1897 setup_frame_size(cm, rb);
1898 if (pbi->need_resync) {
1899 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1900 pbi->need_resync = 0;
1902 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1903 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1904 for (i = 0; i < REFS_PER_FRAME; ++i) {
1905 const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1906 const int idx = cm->ref_frame_map[ref];
1907 RefBuffer *const ref_frame = &cm->frame_refs[i];
1908 ref_frame->idx = idx;
1909 ref_frame->buf = &frame_bufs[idx].buf;
1910 cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1913 setup_frame_size_with_refs(cm, rb);
1915 cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1916 cm->interp_filter = read_interp_filter(rb);
1918 for (i = 0; i < REFS_PER_FRAME; ++i) {
1919 RefBuffer *const ref_buf = &cm->frame_refs[i];
1920 #if CONFIG_VP9_HIGHBITDEPTH
1921 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1922 ref_buf->buf->y_crop_width,
1923 ref_buf->buf->y_crop_height,
1924 cm->width, cm->height,
1925 cm->use_highbitdepth);
1927 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1928 ref_buf->buf->y_crop_width,
1929 ref_buf->buf->y_crop_height,
1930 cm->width, cm->height);
1935 #if CONFIG_VP9_HIGHBITDEPTH
1936 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1938 get_frame_new_buffer(cm)->color_space = cm->color_space;
1940 if (pbi->need_resync) {
1941 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1942 "Keyframe / intra-only frame required to reset decoder"
1946 if (!cm->error_resilient_mode) {
1947 cm->refresh_frame_context = vp9_rb_read_bit(rb);
1948 cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1950 cm->refresh_frame_context = 0;
1951 cm->frame_parallel_decoding_mode = 1;
1954 // This flag will be overridden by the call to vp9_setup_past_independence
1955 // below, forcing the use of context 0 for those frame types.
1956 cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1958 // Generate next_ref_frame_map.
1959 lock_buffer_pool(pool);
1960 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1962 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1963 ++frame_bufs[cm->new_fb_idx].ref_count;
1965 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1967 // Current thread holds the reference frame.
1968 if (cm->ref_frame_map[ref_index] >= 0)
1969 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1973 for (; ref_index < REF_FRAMES; ++ref_index) {
1974 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1975 // Current thread holds the reference frame.
1976 if (cm->ref_frame_map[ref_index] >= 0)
1977 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1979 unlock_buffer_pool(pool);
1980 pbi->hold_ref_buf = 1;
1982 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1983 vp9_setup_past_independence(cm);
1985 setup_loopfilter(&cm->lf, rb);
1986 setup_quantization(cm, &pbi->mb, rb);
1987 setup_segmentation(&cm->seg, rb);
1988 setup_segmentation_dequant(cm);
1990 setup_tile_info(cm, rb);
1991 sz = vp9_rb_read_literal(rb, 16);
1994 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1995 "Invalid header size");
2000 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
2001 size_t partition_size) {
2002 VP9_COMMON *const cm = &pbi->common;
2003 MACROBLOCKD *const xd = &pbi->mb;
2004 FRAME_CONTEXT *const fc = cm->fc;
2008 if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
2009 pbi->decrypt_state))
2010 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2011 "Failed to allocate bool decoder 0");
2013 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
2014 if (cm->tx_mode == TX_MODE_SELECT)
2015 read_tx_mode_probs(&fc->tx_probs, &r);
2016 read_coef_probs(fc, cm->tx_mode, &r);
2018 for (k = 0; k < SKIP_CONTEXTS; ++k)
2019 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
2021 if (!frame_is_intra_only(cm)) {
2022 nmv_context *const nmvc = &fc->nmvc;
2025 read_inter_mode_probs(fc, &r);
2027 if (cm->interp_filter == SWITCHABLE)
2028 read_switchable_interp_probs(fc, &r);
2030 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
2031 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
2033 cm->reference_mode = read_frame_reference_mode(cm, &r);
2034 if (cm->reference_mode != SINGLE_REFERENCE)
2035 setup_compound_reference_mode(cm);
2036 read_frame_reference_mode_probs(cm, &r);
2038 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
2039 for (i = 0; i < INTRA_MODES - 1; ++i)
2040 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
2042 for (j = 0; j < PARTITION_CONTEXTS; ++j)
2043 for (i = 0; i < PARTITION_TYPES - 1; ++i)
2044 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
2046 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2049 return vp9_reader_has_error(&r);
2053 #define debug_check_frame_counts(cm) (void)0
2055 // Counts should only be incremented when frame_parallel_decoding_mode and
2056 // error_resilient_mode are disabled.
2057 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
2058 FRAME_COUNTS zero_counts;
2059 vp9_zero(zero_counts);
2060 assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
2061 assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
2062 sizeof(cm->counts.y_mode)));
2063 assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
2064 sizeof(cm->counts.uv_mode)));
2065 assert(!memcmp(cm->counts.partition, zero_counts.partition,
2066 sizeof(cm->counts.partition)));
2067 assert(!memcmp(cm->counts.coef, zero_counts.coef,
2068 sizeof(cm->counts.coef)));
2069 assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
2070 sizeof(cm->counts.eob_branch)));
2071 assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
2072 sizeof(cm->counts.switchable_interp)));
2073 assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
2074 sizeof(cm->counts.inter_mode)));
2075 assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
2076 sizeof(cm->counts.intra_inter)));
2077 assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
2078 sizeof(cm->counts.comp_inter)));
2079 assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
2080 sizeof(cm->counts.single_ref)));
2081 assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
2082 sizeof(cm->counts.comp_ref)));
2083 assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
2084 assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
2085 assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
2089 static struct vp9_read_bit_buffer *init_read_bit_buffer(
2091 struct vp9_read_bit_buffer *rb,
2092 const uint8_t *data,
2093 const uint8_t *data_end,
2094 uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2096 rb->error_handler = error_handler;
2097 rb->error_handler_data = &pbi->common;
2098 if (pbi->decrypt_cb) {
2099 const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
2100 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2101 rb->bit_buffer = clear_data;
2102 rb->bit_buffer_end = clear_data + n;
2104 rb->bit_buffer = data;
2105 rb->bit_buffer_end = data_end;
2110 //------------------------------------------------------------------------------
2112 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
2113 return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2114 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2115 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2118 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
2119 int *width, int *height) {
2120 *width = vp9_rb_read_literal(rb, 16) + 1;
2121 *height = vp9_rb_read_literal(rb, 16) + 1;
2124 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
2125 int profile = vp9_rb_read_bit(rb);
2126 profile |= vp9_rb_read_bit(rb) << 1;
2128 profile += vp9_rb_read_bit(rb);
2129 return (BITSTREAM_PROFILE) profile;
2132 void vp9_decode_frame(VP9Decoder *pbi,
2133 const uint8_t *data, const uint8_t *data_end,
2134 const uint8_t **p_data_end) {
2135 VP9_COMMON *const cm = &pbi->common;
2136 MACROBLOCKD *const xd = &pbi->mb;
2137 struct vp9_read_bit_buffer rb;
2138 int context_updated = 0;
2139 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2140 const size_t first_partition_size = read_uncompressed_header(pbi,
2141 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2142 const int tile_rows = 1 << cm->log2_tile_rows;
2143 const int tile_cols = 1 << cm->log2_tile_cols;
2144 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2145 xd->cur_buf = new_fb;
2147 if (!first_partition_size) {
2148 // showing a frame directly
2149 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2153 data += vp9_rb_bytes_read(&rb);
2154 if (!read_is_valid(data, first_partition_size, data_end))
2155 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2156 "Truncated packet or corrupt header length");
2158 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2159 cm->width == cm->last_width &&
2160 cm->height == cm->last_height &&
2161 !cm->last_intra_only &&
2162 cm->last_show_frame &&
2163 (cm->last_frame_type != KEY_FRAME);
2165 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2167 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2168 if (!cm->fc->initialized)
2169 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2170 "Uninitialized entropy context.");
2172 vp9_zero(cm->counts);
2175 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2176 if (new_fb->corrupted)
2177 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2178 "Decode failed. Frame data header is corrupted.");
2180 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2181 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2184 // If encoded in frame parallel mode, frame context is ready after decoding
2185 // the frame header.
2186 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2187 VPxWorker *const worker = pbi->frame_worker_owner;
2188 FrameWorkerData *const frame_worker_data = worker->data1;
2189 if (cm->refresh_frame_context) {
2190 context_updated = 1;
2191 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2193 vp9_frameworker_lock_stats(worker);
2194 pbi->cur_buf->row = -1;
2195 pbi->cur_buf->col = -1;
2196 frame_worker_data->frame_context_ready = 1;
2197 // Signal the main thread that context is ready.
2198 vp9_frameworker_signal_stats(worker);
2199 vp9_frameworker_unlock_stats(worker);
2202 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2203 // Multi-threaded tile decoder
2204 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2205 if (!xd->corrupted) {
2206 if (!cm->skip_loop_filter) {
2207 // If multiple threads are used to decode tiles, then we use those
2208 // threads to do parallel loopfiltering.
2209 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2210 cm->lf.filter_level, 0, 0, pbi->tile_workers,
2211 pbi->num_tile_workers, &pbi->lf_row_sync);
2214 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2215 "Decode failed. Frame data is corrupted.");
2219 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2222 if (!xd->corrupted) {
2223 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2224 vp9_adapt_coef_probs(cm);
2226 if (!frame_is_intra_only(cm)) {
2227 vp9_adapt_mode_probs(cm);
2228 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2231 debug_check_frame_counts(cm);
2234 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2235 "Decode failed. Frame data is corrupted.");
2238 // Non frame parallel update frame context here.
2239 if (cm->refresh_frame_context && !context_updated)
2240 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;