2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
12 #include <stdlib.h> // qsort()
14 #include "./vp9_rtcd.h"
15 #include "./vpx_scale_rtcd.h"
17 #include "vpx_mem/vpx_mem.h"
18 #include "vpx_ports/mem.h"
19 #include "vpx_ports/mem_ops.h"
20 #include "vpx_scale/vpx_scale.h"
21 #include "vpx_util/vpx_thread.h"
23 #include "vp9/common/vp9_alloccommon.h"
24 #include "vp9/common/vp9_common.h"
25 #include "vp9/common/vp9_entropy.h"
26 #include "vp9/common/vp9_entropymode.h"
27 #include "vp9/common/vp9_idct.h"
28 #include "vp9/common/vp9_thread_common.h"
29 #include "vp9/common/vp9_pred_common.h"
30 #include "vp9/common/vp9_quant_common.h"
31 #include "vp9/common/vp9_reconintra.h"
32 #include "vp9/common/vp9_reconinter.h"
33 #include "vp9/common/vp9_seg_common.h"
34 #include "vp9/common/vp9_tile_common.h"
36 #include "vp9/decoder/vp9_decodeframe.h"
37 #include "vp9/decoder/vp9_detokenize.h"
38 #include "vp9/decoder/vp9_decodemv.h"
39 #include "vp9/decoder/vp9_decoder.h"
40 #include "vp9/decoder/vp9_dsubexp.h"
41 #include "vp9/decoder/vp9_read_bit_buffer.h"
42 #include "vp9/decoder/vp9_reader.h"
44 #define MAX_VP9_HEADER_SIZE 80
46 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
48 for (i = 1; i < REFS_PER_FRAME; ++i)
49 if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1])
55 static void setup_compound_reference_mode(VP9_COMMON *cm) {
56 if (cm->ref_frame_sign_bias[LAST_FRAME] ==
57 cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
58 cm->comp_fixed_ref = ALTREF_FRAME;
59 cm->comp_var_ref[0] = LAST_FRAME;
60 cm->comp_var_ref[1] = GOLDEN_FRAME;
61 } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
62 cm->ref_frame_sign_bias[ALTREF_FRAME]) {
63 cm->comp_fixed_ref = GOLDEN_FRAME;
64 cm->comp_var_ref[0] = LAST_FRAME;
65 cm->comp_var_ref[1] = ALTREF_FRAME;
67 cm->comp_fixed_ref = LAST_FRAME;
68 cm->comp_var_ref[0] = GOLDEN_FRAME;
69 cm->comp_var_ref[1] = ALTREF_FRAME;
73 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
74 return len != 0 && len <= (size_t)(end - start);
77 static int decode_unsigned_max(struct vp9_read_bit_buffer *rb, int max) {
78 const int data = vp9_rb_read_literal(rb, get_unsigned_bits(max));
79 return data > max ? max : data;
82 static TX_MODE read_tx_mode(vp9_reader *r) {
83 TX_MODE tx_mode = vp9_read_literal(r, 2);
84 if (tx_mode == ALLOW_32X32)
85 tx_mode += vp9_read_bit(r);
89 static void read_tx_mode_probs(struct tx_probs *tx_probs, vp9_reader *r) {
92 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
93 for (j = 0; j < TX_SIZES - 3; ++j)
94 vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
96 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
97 for (j = 0; j < TX_SIZES - 2; ++j)
98 vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
100 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
101 for (j = 0; j < TX_SIZES - 1; ++j)
102 vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
105 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
107 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
108 for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
109 vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
112 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
114 for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
115 for (j = 0; j < INTER_MODES - 1; ++j)
116 vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
119 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
121 if (is_compound_reference_allowed(cm)) {
122 return vp9_read_bit(r) ? (vp9_read_bit(r) ? REFERENCE_MODE_SELECT
123 : COMPOUND_REFERENCE)
126 return SINGLE_REFERENCE;
130 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vp9_reader *r) {
131 FRAME_CONTEXT *const fc = cm->fc;
134 if (cm->reference_mode == REFERENCE_MODE_SELECT)
135 for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
136 vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
138 if (cm->reference_mode != COMPOUND_REFERENCE)
139 for (i = 0; i < REF_CONTEXTS; ++i) {
140 vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
141 vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
144 if (cm->reference_mode != SINGLE_REFERENCE)
145 for (i = 0; i < REF_CONTEXTS; ++i)
146 vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
149 static void update_mv_probs(vp9_prob *p, int n, vp9_reader *r) {
151 for (i = 0; i < n; ++i)
152 if (vp9_read(r, MV_UPDATE_PROB))
153 p[i] = (vp9_read_literal(r, 7) << 1) | 1;
156 static void read_mv_probs(nmv_context *ctx, int allow_hp, vp9_reader *r) {
159 update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
161 for (i = 0; i < 2; ++i) {
162 nmv_component *const comp_ctx = &ctx->comps[i];
163 update_mv_probs(&comp_ctx->sign, 1, r);
164 update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
165 update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
166 update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
169 for (i = 0; i < 2; ++i) {
170 nmv_component *const comp_ctx = &ctx->comps[i];
171 for (j = 0; j < CLASS0_SIZE; ++j)
172 update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
173 update_mv_probs(comp_ctx->fp, 3, r);
177 for (i = 0; i < 2; ++i) {
178 nmv_component *const comp_ctx = &ctx->comps[i];
179 update_mv_probs(&comp_ctx->class0_hp, 1, r);
180 update_mv_probs(&comp_ctx->hp, 1, r);
185 static void inverse_transform_block_inter(MACROBLOCKD* xd, int plane,
186 const TX_SIZE tx_size,
187 uint8_t *dst, int stride,
189 struct macroblockd_plane *const pd = &xd->plane[plane];
191 tran_low_t *const dqcoeff = pd->dqcoeff;
192 #if CONFIG_VP9_HIGHBITDEPTH
193 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
195 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
199 vp9_highbd_idct4x4_add(dqcoeff, dst, stride, eob, xd->bd);
202 vp9_highbd_idct8x8_add(dqcoeff, dst, stride, eob, xd->bd);
205 vp9_highbd_idct16x16_add(dqcoeff, dst, stride, eob, xd->bd);
208 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
211 assert(0 && "Invalid transform size");
216 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
220 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
223 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
226 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
229 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
232 assert(0 && "Invalid transform size");
239 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
243 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
246 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
249 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
252 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
255 assert(0 && "Invalid transform size");
259 #endif // CONFIG_VP9_HIGHBITDEPTH
264 if (tx_size <= TX_16X16 && eob <= 10)
265 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
266 else if (tx_size == TX_32X32 && eob <= 34)
267 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
269 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
274 static void inverse_transform_block_intra(MACROBLOCKD* xd, int plane,
275 const TX_TYPE tx_type,
276 const TX_SIZE tx_size,
277 uint8_t *dst, int stride,
279 struct macroblockd_plane *const pd = &xd->plane[plane];
281 tran_low_t *const dqcoeff = pd->dqcoeff;
282 #if CONFIG_VP9_HIGHBITDEPTH
283 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
285 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
289 vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
292 vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
295 vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
298 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
301 assert(0 && "Invalid transform size");
306 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
310 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
313 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
316 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
319 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
322 assert(0 && "Invalid transform size");
329 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
333 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
336 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
339 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
342 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
345 assert(0 && "Invalid transform size");
349 #endif // CONFIG_VP9_HIGHBITDEPTH
354 if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
355 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
356 else if (tx_size == TX_32X32 && eob <= 34)
357 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
359 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
370 static void predict_and_reconstruct_intra_block(int plane, int block,
371 BLOCK_SIZE plane_bsize,
372 TX_SIZE tx_size, void *arg) {
373 struct intra_args *const args = (struct intra_args *)arg;
374 MACROBLOCKD *const xd = args->xd;
375 struct macroblockd_plane *const pd = &xd->plane[plane];
376 MODE_INFO *const mi = xd->mi[0];
377 const PREDICTION_MODE mode = (plane == 0) ? get_y_mode(mi, block)
381 txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
382 dst = &pd->dst.buf[4 * y * pd->dst.stride + 4 * x];
384 vp9_predict_intra_block(xd, block >> (tx_size << 1),
385 b_width_log2_lookup[plane_bsize], tx_size, mode,
386 dst, pd->dst.stride, dst, pd->dst.stride,
389 if (!mi->mbmi.skip) {
390 const TX_TYPE tx_type = (plane || xd->lossless) ?
391 DCT_DCT : intra_mode_to_tx_type_lookup[mode];
392 const scan_order *sc = (plane || xd->lossless) ?
393 &vp9_default_scan_orders[tx_size] : &vp9_scan_orders[tx_size][tx_type];
394 const int eob = vp9_decode_block_tokens(xd, plane, sc,
395 plane_bsize, x, y, tx_size,
396 args->r, args->seg_id);
397 inverse_transform_block_intra(xd, plane, tx_type, tx_size,
398 dst, pd->dst.stride, eob);
409 static void reconstruct_inter_block(int plane, int block,
410 BLOCK_SIZE plane_bsize,
411 TX_SIZE tx_size, void *arg) {
412 struct inter_args *args = (struct inter_args *)arg;
413 MACROBLOCKD *const xd = args->xd;
414 struct macroblockd_plane *const pd = &xd->plane[plane];
416 const scan_order *sc = &vp9_default_scan_orders[tx_size];
417 txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
418 eob = vp9_decode_block_tokens(xd, plane, sc, plane_bsize,
419 x, y, tx_size, args->r, args->seg_id);
420 inverse_transform_block_inter(xd, plane, tx_size,
421 &pd->dst.buf[4 * y * pd->dst.stride + 4 * x],
422 pd->dst.stride, eob);
423 *args->eobtotal += eob;
426 static void build_mc_border(const uint8_t *src, int src_stride,
427 uint8_t *dst, int dst_stride,
428 int x, int y, int b_w, int b_h, int w, int h) {
429 // Get a pointer to the start of the real data for this row.
430 const uint8_t *ref_row = src - x - y * src_stride;
433 ref_row += (h - 1) * src_stride;
435 ref_row += y * src_stride;
439 int left = x < 0 ? -x : 0;
450 copy = b_w - left - right;
453 memset(dst, ref_row[0], left);
456 memcpy(dst + left, ref_row + x + left, copy);
459 memset(dst + left + copy, ref_row[w - 1], right);
465 ref_row += src_stride;
469 #if CONFIG_VP9_HIGHBITDEPTH
470 static void high_build_mc_border(const uint8_t *src8, int src_stride,
471 uint16_t *dst, int dst_stride,
472 int x, int y, int b_w, int b_h,
474 // Get a pointer to the start of the real data for this row.
475 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
476 const uint16_t *ref_row = src - x - y * src_stride;
479 ref_row += (h - 1) * src_stride;
481 ref_row += y * src_stride;
485 int left = x < 0 ? -x : 0;
496 copy = b_w - left - right;
499 vpx_memset16(dst, ref_row[0], left);
502 memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
505 vpx_memset16(dst + left + copy, ref_row[w - 1], right);
511 ref_row += src_stride;
514 #endif // CONFIG_VP9_HIGHBITDEPTH
516 #if CONFIG_VP9_HIGHBITDEPTH
517 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
518 int x0, int y0, int b_w, int b_h,
519 int frame_width, int frame_height,
521 uint8_t *const dst, int dst_buf_stride,
522 int subpel_x, int subpel_y,
523 const InterpKernel *kernel,
524 const struct scale_factors *sf,
526 int w, int h, int ref, int xs, int ys) {
527 DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
528 const uint8_t *buf_ptr;
530 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
531 high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w,
532 x0, y0, b_w, b_h, frame_width, frame_height);
533 buf_ptr = CONVERT_TO_BYTEPTR(mc_buf_high) + border_offset;
535 build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w,
536 x0, y0, b_w, b_h, frame_width, frame_height);
537 buf_ptr = ((uint8_t *)mc_buf_high) + border_offset;
540 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
541 high_inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
542 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
544 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
545 subpel_y, sf, w, h, ref, kernel, xs, ys);
549 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
550 int x0, int y0, int b_w, int b_h,
551 int frame_width, int frame_height,
553 uint8_t *const dst, int dst_buf_stride,
554 int subpel_x, int subpel_y,
555 const InterpKernel *kernel,
556 const struct scale_factors *sf,
557 int w, int h, int ref, int xs, int ys) {
558 DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
559 const uint8_t *buf_ptr;
561 build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w,
562 x0, y0, b_w, b_h, frame_width, frame_height);
563 buf_ptr = mc_buf + border_offset;
565 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
566 subpel_y, sf, w, h, ref, kernel, xs, ys);
568 #endif // CONFIG_VP9_HIGHBITDEPTH
570 static void dec_build_inter_predictors(VP9Decoder *const pbi, MACROBLOCKD *xd,
571 int plane, int bw, int bh, int x,
572 int y, int w, int h, int mi_x, int mi_y,
573 const InterpKernel *kernel,
574 const struct scale_factors *sf,
575 struct buf_2d *pre_buf,
576 struct buf_2d *dst_buf, const MV* mv,
577 RefCntBuffer *ref_frame_buf,
578 int is_scaled, int ref) {
579 struct macroblockd_plane *const pd = &xd->plane[plane];
580 uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
582 int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height,
583 buf_stride, subpel_x, subpel_y;
584 uint8_t *ref_frame, *buf_ptr;
586 // Get reference frame pointer, width and height.
588 frame_width = ref_frame_buf->buf.y_crop_width;
589 frame_height = ref_frame_buf->buf.y_crop_height;
590 ref_frame = ref_frame_buf->buf.y_buffer;
592 frame_width = ref_frame_buf->buf.uv_crop_width;
593 frame_height = ref_frame_buf->buf.uv_crop_height;
594 ref_frame = plane == 1 ? ref_frame_buf->buf.u_buffer
595 : ref_frame_buf->buf.v_buffer;
599 const MV mv_q4 = clamp_mv_to_umv_border_sb(xd, mv, bw, bh,
602 // Co-ordinate of containing block to pixel precision.
603 int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
604 int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
606 // Co-ordinate of the block to 1/16th pixel precision.
607 x0_16 = (x_start + x) << SUBPEL_BITS;
608 y0_16 = (y_start + y) << SUBPEL_BITS;
610 // Co-ordinate of current block in reference frame
611 // to 1/16th pixel precision.
612 x0_16 = sf->scale_value_x(x0_16, sf);
613 y0_16 = sf->scale_value_y(y0_16, sf);
615 // Map the top left corner of the block into the reference frame.
616 x0 = sf->scale_value_x(x_start + x, sf);
617 y0 = sf->scale_value_y(y_start + y, sf);
619 // Scale the MV and incorporate the sub-pixel offset of the block
620 // in the reference frame.
621 scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
625 // Co-ordinate of containing block to pixel precision.
626 x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
627 y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
629 // Co-ordinate of the block to 1/16th pixel precision.
630 x0_16 = x0 << SUBPEL_BITS;
631 y0_16 = y0 << SUBPEL_BITS;
633 scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
634 scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
637 subpel_x = scaled_mv.col & SUBPEL_MASK;
638 subpel_y = scaled_mv.row & SUBPEL_MASK;
640 // Calculate the top left corner of the best matching block in the
642 x0 += scaled_mv.col >> SUBPEL_BITS;
643 y0 += scaled_mv.row >> SUBPEL_BITS;
644 x0_16 += scaled_mv.col;
645 y0_16 += scaled_mv.row;
647 // Get reference block pointer.
648 buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
649 buf_stride = pre_buf->stride;
651 // Do border extension if there is motion or the
652 // width/height is not a multiple of 8 pixels.
653 if (is_scaled || scaled_mv.col || scaled_mv.row ||
654 (frame_width & 0x7) || (frame_height & 0x7)) {
655 int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
657 // Get reference block bottom right horizontal coordinate.
658 int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
659 int x_pad = 0, y_pad = 0;
661 if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
662 x0 -= VP9_INTERP_EXTEND - 1;
663 x1 += VP9_INTERP_EXTEND;
667 if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
668 y0 -= VP9_INTERP_EXTEND - 1;
669 y1 += VP9_INTERP_EXTEND;
673 // Wait until reference block is ready. Pad 7 more pixels as last 7
674 // pixels of each superblock row can be changed by next superblock row.
675 if (pbi->frame_parallel_decode)
676 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
677 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
679 // Skip border extension if block is inside the frame.
680 if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
681 y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
682 // Extend the border.
683 const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
684 const int b_w = x1 - x0 + 1;
685 const int b_h = y1 - y0 + 1;
686 const int border_offset = y_pad * 3 * b_w + x_pad * 3;
688 extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h,
689 frame_width, frame_height, border_offset,
690 dst, dst_buf->stride,
693 #if CONFIG_VP9_HIGHBITDEPTH
700 // Wait until reference block is ready. Pad 7 more pixels as last 7
701 // pixels of each superblock row can be changed by next superblock row.
702 if (pbi->frame_parallel_decode) {
703 const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
704 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
705 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
708 #if CONFIG_VP9_HIGHBITDEPTH
709 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
710 high_inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
711 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
713 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
714 subpel_y, sf, w, h, ref, kernel, xs, ys);
717 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
718 subpel_y, sf, w, h, ref, kernel, xs, ys);
719 #endif // CONFIG_VP9_HIGHBITDEPTH
722 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
724 int mi_row, int mi_col,
727 const int mi_x = mi_col * MI_SIZE;
728 const int mi_y = mi_row * MI_SIZE;
729 const MODE_INFO *mi = xd->mi[0];
730 const InterpKernel *kernel = vp9_filter_kernels[mi->mbmi.interp_filter];
731 const BLOCK_SIZE sb_type = mi->mbmi.sb_type;
732 const int is_compound = has_second_ref(&mi->mbmi);
734 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
735 const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize,
737 struct macroblockd_plane *const pd = &xd->plane[plane];
738 struct buf_2d *const dst_buf = &pd->dst;
739 const int num_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
740 const int num_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
742 const int bw = 4 * num_4x4_w;
743 const int bh = 4 * num_4x4_h;
746 for (ref = 0; ref < 1 + is_compound; ++ref) {
747 const struct scale_factors *const sf = &xd->block_refs[ref]->sf;
748 struct buf_2d *const pre_buf = &pd->pre[ref];
749 const int idx = xd->block_refs[ref]->idx;
750 BufferPool *const pool = pbi->common.buffer_pool;
751 RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
752 const int is_scaled = vp9_is_scaled(sf);
754 if (sb_type < BLOCK_8X8) {
756 assert(bsize == BLOCK_8X8);
757 for (y = 0; y < num_4x4_h; ++y) {
758 for (x = 0; x < num_4x4_w; ++x) {
759 const MV mv = average_split_mvs(pd, mi, ref, i++);
760 dec_build_inter_predictors(pbi, xd, plane, bw, bh,
761 4 * x, 4 * y, 4, 4, mi_x, mi_y, kernel,
762 sf, pre_buf, dst_buf, &mv,
763 ref_frame_buf, is_scaled, ref);
767 const MV mv = mi->mbmi.mv[ref].as_mv;
768 dec_build_inter_predictors(pbi, xd, plane, bw, bh,
769 0, 0, bw, bh, mi_x, mi_y, kernel,
770 sf, pre_buf, dst_buf, &mv, ref_frame_buf,
777 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
778 BLOCK_SIZE bsize, int mi_row, int mi_col) {
779 const int bw = num_8x8_blocks_wide_lookup[bsize];
780 const int bh = num_8x8_blocks_high_lookup[bsize];
781 const int x_mis = MIN(bw, cm->mi_cols - mi_col);
782 const int y_mis = MIN(bh, cm->mi_rows - mi_row);
783 const int offset = mi_row * cm->mi_stride + mi_col;
785 const TileInfo *const tile = &xd->tile;
787 xd->mi = cm->mi_grid_visible + offset;
788 xd->mi[0] = &cm->mi[offset];
789 xd->mi[0]->mbmi.sb_type = bsize;
790 for (y = 0; y < y_mis; ++y)
791 for (x = !y; x < x_mis; ++x) {
792 xd->mi[y * cm->mi_stride + x] = xd->mi[0];
795 set_skip_context(xd, mi_row, mi_col);
797 // Distance of Mb to the various image edges. These are specified to 8th pel
798 // as they are always compared to values that are in 1/8th pel units
799 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
801 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
802 return &xd->mi[0]->mbmi;
805 static void decode_block(VP9Decoder *const pbi, MACROBLOCKD *const xd,
806 int mi_row, int mi_col,
807 vp9_reader *r, BLOCK_SIZE bsize) {
808 VP9_COMMON *const cm = &pbi->common;
809 const int less8x8 = bsize < BLOCK_8X8;
810 MB_MODE_INFO *mbmi = set_offsets(cm, xd, bsize, mi_row, mi_col);
812 if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
813 const BLOCK_SIZE uv_subsize =
814 ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
815 if (uv_subsize == BLOCK_INVALID)
816 vpx_internal_error(xd->error_info,
817 VPX_CODEC_CORRUPT_FRAME, "Invalid block size.");
820 vp9_read_mode_info(pbi, xd, mi_row, mi_col, r);
826 reset_skip_context(xd, bsize);
829 if (!is_inter_block(mbmi)) {
830 struct intra_args arg = {xd, r, mbmi->segment_id};
831 vp9_foreach_transformed_block(xd, bsize,
832 predict_and_reconstruct_intra_block, &arg);
835 dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col, bsize);
840 struct inter_args arg = {xd, r, &eobtotal, mbmi->segment_id};
841 vp9_foreach_transformed_block(xd, bsize, reconstruct_inter_block, &arg);
842 if (!less8x8 && eobtotal == 0)
843 mbmi->skip = 1; // skip loopfilter
847 xd->corrupted |= vp9_reader_has_error(r);
850 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
851 BLOCK_SIZE bsize, vp9_reader *r,
852 int has_rows, int has_cols) {
853 const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
854 const vp9_prob *const probs = get_partition_probs(xd, ctx);
855 FRAME_COUNTS *counts = xd->counts;
858 if (has_rows && has_cols)
859 p = (PARTITION_TYPE)vp9_read_tree(r, vp9_partition_tree, probs);
860 else if (!has_rows && has_cols)
861 p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
862 else if (has_rows && !has_cols)
863 p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
868 ++counts->partition[ctx][p];
873 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
874 int mi_row, int mi_col,
875 vp9_reader* r, BLOCK_SIZE bsize) {
876 VP9_COMMON *const cm = &pbi->common;
877 const int hbs = num_8x8_blocks_wide_lookup[bsize] / 2;
878 PARTITION_TYPE partition;
880 const int has_rows = (mi_row + hbs) < cm->mi_rows;
881 const int has_cols = (mi_col + hbs) < cm->mi_cols;
883 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
886 partition = read_partition(xd, mi_row, mi_col, bsize, r, has_rows, has_cols);
887 subsize = get_subsize(bsize, partition);
888 if (bsize == BLOCK_8X8) {
889 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
893 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
896 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
898 decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize);
901 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
903 decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize);
905 case PARTITION_SPLIT:
906 decode_partition(pbi, xd, mi_row, mi_col, r, subsize);
907 decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize);
908 decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize);
909 decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize);
912 assert(0 && "Invalid partition type");
916 // update partition context
917 if (bsize >= BLOCK_8X8 &&
918 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
919 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
922 static void setup_token_decoder(const uint8_t *data,
923 const uint8_t *data_end,
925 struct vpx_internal_error_info *error_info,
927 vpx_decrypt_cb decrypt_cb,
928 void *decrypt_state) {
929 // Validate the calculated partition length. If the buffer
930 // described by the partition can't be fully read, then restrict
931 // it to the portion that can be (for EC mode) or throw an error.
932 if (!read_is_valid(data, read_size, data_end))
933 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
934 "Truncated packet or corrupt tile length");
936 if (vp9_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
937 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
938 "Failed to allocate bool decoder %d", 1);
941 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
946 for (i = 0; i < PLANE_TYPES; ++i)
947 for (j = 0; j < REF_TYPES; ++j)
948 for (k = 0; k < COEF_BANDS; ++k)
949 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
950 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
951 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
954 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
956 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
958 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
959 read_coef_probs_common(fc->coef_probs[tx_size], r);
962 static void setup_segmentation(struct segmentation *seg,
963 struct vp9_read_bit_buffer *rb) {
967 seg->update_data = 0;
969 seg->enabled = vp9_rb_read_bit(rb);
973 // Segmentation map update
974 seg->update_map = vp9_rb_read_bit(rb);
975 if (seg->update_map) {
976 for (i = 0; i < SEG_TREE_PROBS; i++)
977 seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
980 seg->temporal_update = vp9_rb_read_bit(rb);
981 if (seg->temporal_update) {
982 for (i = 0; i < PREDICTION_PROBS; i++)
983 seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
986 for (i = 0; i < PREDICTION_PROBS; i++)
987 seg->pred_probs[i] = MAX_PROB;
991 // Segmentation data update
992 seg->update_data = vp9_rb_read_bit(rb);
993 if (seg->update_data) {
994 seg->abs_delta = vp9_rb_read_bit(rb);
996 vp9_clearall_segfeatures(seg);
998 for (i = 0; i < MAX_SEGMENTS; i++) {
999 for (j = 0; j < SEG_LVL_MAX; j++) {
1001 const int feature_enabled = vp9_rb_read_bit(rb);
1002 if (feature_enabled) {
1003 vp9_enable_segfeature(seg, i, j);
1004 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1005 if (vp9_is_segfeature_signed(j))
1006 data = vp9_rb_read_bit(rb) ? -data : data;
1008 vp9_set_segdata(seg, i, j, data);
1014 static void setup_loopfilter(struct loopfilter *lf,
1015 struct vp9_read_bit_buffer *rb) {
1016 lf->filter_level = vp9_rb_read_literal(rb, 6);
1017 lf->sharpness_level = vp9_rb_read_literal(rb, 3);
1019 // Read in loop filter deltas applied at the MB level based on mode or ref
1021 lf->mode_ref_delta_update = 0;
1023 lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
1024 if (lf->mode_ref_delta_enabled) {
1025 lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
1026 if (lf->mode_ref_delta_update) {
1029 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1030 if (vp9_rb_read_bit(rb))
1031 lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1033 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1034 if (vp9_rb_read_bit(rb))
1035 lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1040 static INLINE int read_delta_q(struct vp9_read_bit_buffer *rb) {
1041 return vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
1044 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1045 struct vp9_read_bit_buffer *rb) {
1046 cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
1047 cm->y_dc_delta_q = read_delta_q(rb);
1048 cm->uv_dc_delta_q = read_delta_q(rb);
1049 cm->uv_ac_delta_q = read_delta_q(rb);
1050 cm->dequant_bit_depth = cm->bit_depth;
1051 xd->lossless = cm->base_qindex == 0 &&
1052 cm->y_dc_delta_q == 0 &&
1053 cm->uv_dc_delta_q == 0 &&
1054 cm->uv_ac_delta_q == 0;
1056 #if CONFIG_VP9_HIGHBITDEPTH
1057 xd->bd = (int)cm->bit_depth;
1061 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1062 // Build y/uv dequant values based on segmentation.
1063 if (cm->seg.enabled) {
1065 for (i = 0; i < MAX_SEGMENTS; ++i) {
1066 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1067 cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
1069 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1070 cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1072 cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1076 const int qindex = cm->base_qindex;
1077 // When segmentation is disabled, only the first value is used. The
1078 // remaining are don't cares.
1079 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1080 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1081 cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1083 cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1088 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
1089 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1093 return vp9_rb_read_bit(rb) ? SWITCHABLE
1094 : literal_to_filter[vp9_rb_read_literal(rb, 2)];
1097 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1098 cm->display_width = cm->width;
1099 cm->display_height = cm->height;
1100 if (vp9_rb_read_bit(rb))
1101 vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
1104 static void resize_mv_buffer(VP9_COMMON *cm) {
1105 vpx_free(cm->cur_frame->mvs);
1106 cm->cur_frame->mi_rows = cm->mi_rows;
1107 cm->cur_frame->mi_cols = cm->mi_cols;
1108 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1109 sizeof(*cm->cur_frame->mvs));
1112 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1113 #if CONFIG_SIZE_LIMIT
1114 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1115 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1116 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1117 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1119 if (cm->width != width || cm->height != height) {
1120 const int new_mi_rows =
1121 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1122 const int new_mi_cols =
1123 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1125 // Allocations in vp9_alloc_context_buffers() depend on individual
1126 // dimensions as well as the overall size.
1127 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1128 if (vp9_alloc_context_buffers(cm, width, height))
1129 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1130 "Failed to allocate context buffers");
1132 vp9_set_mb_mi(cm, width, height);
1134 vp9_init_context_buffers(cm);
1136 cm->height = height;
1138 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1139 cm->mi_cols > cm->cur_frame->mi_cols) {
1140 resize_mv_buffer(cm);
1144 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1146 BufferPool *const pool = cm->buffer_pool;
1147 vp9_read_frame_size(rb, &width, &height);
1148 resize_context_buffers(cm, width, height);
1149 setup_display_size(cm, rb);
1151 lock_buffer_pool(pool);
1152 if (vp9_realloc_frame_buffer(
1153 get_frame_new_buffer(cm), cm->width, cm->height,
1154 cm->subsampling_x, cm->subsampling_y,
1155 #if CONFIG_VP9_HIGHBITDEPTH
1156 cm->use_highbitdepth,
1158 VP9_DEC_BORDER_IN_PIXELS,
1160 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1162 unlock_buffer_pool(pool);
1163 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1164 "Failed to allocate frame buffer");
1166 unlock_buffer_pool(pool);
1168 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1169 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1170 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1171 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1174 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1175 int ref_xss, int ref_yss,
1176 vpx_bit_depth_t this_bit_depth,
1177 int this_xss, int this_yss) {
1178 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1179 ref_yss == this_yss;
1182 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1183 struct vp9_read_bit_buffer *rb) {
1186 int has_valid_ref_frame = 0;
1187 BufferPool *const pool = cm->buffer_pool;
1188 for (i = 0; i < REFS_PER_FRAME; ++i) {
1189 if (vp9_rb_read_bit(rb)) {
1190 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1191 width = buf->y_crop_width;
1192 height = buf->y_crop_height;
1199 vp9_read_frame_size(rb, &width, &height);
1201 if (width <= 0 || height <= 0)
1202 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1203 "Invalid frame size");
1205 // Check to make sure at least one of frames that this frame references
1206 // has valid dimensions.
1207 for (i = 0; i < REFS_PER_FRAME; ++i) {
1208 RefBuffer *const ref_frame = &cm->frame_refs[i];
1209 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1210 ref_frame->buf->y_crop_height,
1213 if (!has_valid_ref_frame)
1214 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1215 "Referenced frame has invalid size");
1216 for (i = 0; i < REFS_PER_FRAME; ++i) {
1217 RefBuffer *const ref_frame = &cm->frame_refs[i];
1218 if (!valid_ref_frame_img_fmt(
1219 ref_frame->buf->bit_depth,
1220 ref_frame->buf->subsampling_x,
1221 ref_frame->buf->subsampling_y,
1225 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1226 "Referenced frame has incompatible color format");
1229 resize_context_buffers(cm, width, height);
1230 setup_display_size(cm, rb);
1232 lock_buffer_pool(pool);
1233 if (vp9_realloc_frame_buffer(
1234 get_frame_new_buffer(cm), cm->width, cm->height,
1235 cm->subsampling_x, cm->subsampling_y,
1236 #if CONFIG_VP9_HIGHBITDEPTH
1237 cm->use_highbitdepth,
1239 VP9_DEC_BORDER_IN_PIXELS,
1241 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1243 unlock_buffer_pool(pool);
1244 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1245 "Failed to allocate frame buffer");
1247 unlock_buffer_pool(pool);
1249 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1250 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1251 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1252 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1255 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1256 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1257 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1260 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1261 cm->log2_tile_cols = min_log2_tile_cols;
1262 while (max_ones-- && vp9_rb_read_bit(rb))
1263 cm->log2_tile_cols++;
1265 if (cm->log2_tile_cols > 6)
1266 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1267 "Invalid number of tile columns");
1270 cm->log2_tile_rows = vp9_rb_read_bit(rb);
1271 if (cm->log2_tile_rows)
1272 cm->log2_tile_rows += vp9_rb_read_bit(rb);
1275 typedef struct TileBuffer {
1276 const uint8_t *data;
1278 int col; // only used with multi-threaded decoding
1281 // Reads the next tile returning its size and adjusting '*data' accordingly
1282 // based on 'is_last'.
1283 static void get_tile_buffer(const uint8_t *const data_end,
1285 struct vpx_internal_error_info *error_info,
1286 const uint8_t **data,
1287 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1292 if (!read_is_valid(*data, 4, data_end))
1293 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1294 "Truncated packet or corrupt tile length");
1298 decrypt_cb(decrypt_state, *data, be_data, 4);
1299 size = mem_get_be32(be_data);
1301 size = mem_get_be32(*data);
1305 if (size > (size_t)(data_end - *data))
1306 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1307 "Truncated packet or corrupt tile size");
1309 size = data_end - *data;
1318 static void get_tile_buffers(VP9Decoder *pbi,
1319 const uint8_t *data, const uint8_t *data_end,
1320 int tile_cols, int tile_rows,
1321 TileBuffer (*tile_buffers)[1 << 6]) {
1324 for (r = 0; r < tile_rows; ++r) {
1325 for (c = 0; c < tile_cols; ++c) {
1326 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1327 TileBuffer *const buf = &tile_buffers[r][c];
1329 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1330 pbi->decrypt_cb, pbi->decrypt_state, buf);
1335 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1336 const uint8_t *data,
1337 const uint8_t *data_end) {
1338 VP9_COMMON *const cm = &pbi->common;
1339 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1340 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1341 const int tile_cols = 1 << cm->log2_tile_cols;
1342 const int tile_rows = 1 << cm->log2_tile_rows;
1343 TileBuffer tile_buffers[4][1 << 6];
1344 int tile_row, tile_col;
1346 TileData *tile_data = NULL;
1348 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1349 pbi->lf_worker.data1 == NULL) {
1350 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1351 vpx_memalign(32, sizeof(LFWorkerData)));
1352 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1353 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1354 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1355 "Loop filter thread creation failed");
1359 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1360 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1361 // Be sure to sync as we might be resuming after a failed frame decode.
1362 winterface->sync(&pbi->lf_worker);
1363 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1367 assert(tile_rows <= 4);
1368 assert(tile_cols <= (1 << 6));
1370 // Note: this memset assumes above_context[0], [1] and [2]
1371 // are allocated as part of the same buffer.
1372 memset(cm->above_context, 0,
1373 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1375 memset(cm->above_seg_context, 0,
1376 sizeof(*cm->above_seg_context) * aligned_cols);
1378 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1380 if (pbi->tile_data == NULL ||
1381 (tile_cols * tile_rows) != pbi->total_tiles) {
1382 vpx_free(pbi->tile_data);
1386 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1387 pbi->total_tiles = tile_rows * tile_cols;
1390 // Load all tile information into tile_data.
1391 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1392 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1393 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1394 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1396 tile_data->xd = pbi->mb;
1397 tile_data->xd.corrupted = 0;
1398 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1400 vp9_zero(tile_data->dqcoeff);
1401 vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1402 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1403 &tile_data->bit_reader, pbi->decrypt_cb,
1404 pbi->decrypt_state);
1405 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1409 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1411 vp9_tile_set_row(&tile, cm, tile_row);
1412 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1413 mi_row += MI_BLOCK_SIZE) {
1414 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1415 const int col = pbi->inv_tile_order ?
1416 tile_cols - tile_col - 1 : tile_col;
1417 tile_data = pbi->tile_data + tile_cols * tile_row + col;
1418 vp9_tile_set_col(&tile, tile_data->cm, col);
1419 vp9_zero(tile_data->xd.left_context);
1420 vp9_zero(tile_data->xd.left_seg_context);
1421 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1422 mi_col += MI_BLOCK_SIZE) {
1423 decode_partition(pbi, &tile_data->xd, mi_row, mi_col,
1424 &tile_data->bit_reader, BLOCK_64X64);
1426 pbi->mb.corrupted |= tile_data->xd.corrupted;
1427 if (pbi->mb.corrupted)
1428 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1429 "Failed to decode tile data");
1431 // Loopfilter one row.
1432 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1433 const int lf_start = mi_row - MI_BLOCK_SIZE;
1434 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1436 // delay the loopfilter by 1 macroblock row.
1437 if (lf_start < 0) continue;
1439 // decoding has completed: finish up the loop filter in this thread.
1440 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1442 winterface->sync(&pbi->lf_worker);
1443 lf_data->start = lf_start;
1444 lf_data->stop = mi_row;
1445 if (pbi->max_threads > 1) {
1446 winterface->launch(&pbi->lf_worker);
1448 winterface->execute(&pbi->lf_worker);
1451 // After loopfiltering, the last 7 row pixels in each superblock row may
1452 // still be changed by the longest loopfilter of the next superblock
1454 if (pbi->frame_parallel_decode)
1455 vp9_frameworker_broadcast(pbi->cur_buf,
1456 mi_row << MI_BLOCK_SIZE_LOG2);
1460 // Loopfilter remaining rows in the frame.
1461 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1462 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1463 winterface->sync(&pbi->lf_worker);
1464 lf_data->start = lf_data->stop;
1465 lf_data->stop = cm->mi_rows;
1466 winterface->execute(&pbi->lf_worker);
1469 // Get last tile data.
1470 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1472 if (pbi->frame_parallel_decode)
1473 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1474 return vp9_reader_find_end(&tile_data->bit_reader);
1477 static int tile_worker_hook(TileWorkerData *const tile_data,
1478 const TileInfo *const tile) {
1481 if (setjmp(tile_data->error_info.jmp)) {
1482 tile_data->error_info.setjmp = 0;
1483 tile_data->xd.corrupted = 1;
1487 tile_data->error_info.setjmp = 1;
1488 tile_data->xd.error_info = &tile_data->error_info;
1490 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1491 mi_row += MI_BLOCK_SIZE) {
1492 vp9_zero(tile_data->xd.left_context);
1493 vp9_zero(tile_data->xd.left_seg_context);
1494 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1495 mi_col += MI_BLOCK_SIZE) {
1496 decode_partition(tile_data->pbi, &tile_data->xd,
1497 mi_row, mi_col, &tile_data->bit_reader,
1501 return !tile_data->xd.corrupted;
1504 // sorts in descending order
1505 static int compare_tile_buffers(const void *a, const void *b) {
1506 const TileBuffer *const buf1 = (const TileBuffer*)a;
1507 const TileBuffer *const buf2 = (const TileBuffer*)b;
1508 return (int)(buf2->size - buf1->size);
1511 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1512 const uint8_t *data,
1513 const uint8_t *data_end) {
1514 VP9_COMMON *const cm = &pbi->common;
1515 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1516 const uint8_t *bit_reader_end = NULL;
1517 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1518 const int tile_cols = 1 << cm->log2_tile_cols;
1519 const int tile_rows = 1 << cm->log2_tile_rows;
1520 const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1521 TileBuffer tile_buffers[1][1 << 6];
1523 int final_worker = -1;
1525 assert(tile_cols <= (1 << 6));
1526 assert(tile_rows == 1);
1529 // TODO(jzern): See if we can remove the restriction of passing in max
1530 // threads to the decoder.
1531 if (pbi->num_tile_workers == 0) {
1532 const int num_threads = pbi->max_threads & ~1;
1534 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1535 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1536 // Ensure tile data offsets will be properly aligned. This may fail on
1537 // platforms without DECLARE_ALIGNED().
1538 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1539 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1540 vpx_memalign(32, num_threads *
1541 sizeof(*pbi->tile_worker_data)));
1542 CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1543 vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1544 for (i = 0; i < num_threads; ++i) {
1545 VPxWorker *const worker = &pbi->tile_workers[i];
1546 ++pbi->num_tile_workers;
1548 winterface->init(worker);
1549 if (i < num_threads - 1 && !winterface->reset(worker)) {
1550 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1551 "Tile decoder thread creation failed");
1556 // Reset tile decoding hook
1557 for (n = 0; n < num_workers; ++n) {
1558 VPxWorker *const worker = &pbi->tile_workers[n];
1559 winterface->sync(worker);
1560 worker->hook = (VPxWorkerHook)tile_worker_hook;
1561 worker->data1 = &pbi->tile_worker_data[n];
1562 worker->data2 = &pbi->tile_worker_info[n];
1565 // Note: this memset assumes above_context[0], [1] and [2]
1566 // are allocated as part of the same buffer.
1567 memset(cm->above_context, 0,
1568 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1569 memset(cm->above_seg_context, 0,
1570 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1572 // Load tile data into tile_buffers
1573 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1575 // Sort the buffers based on size in descending order.
1576 qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1577 compare_tile_buffers);
1579 // Rearrange the tile buffers such that per-tile group the largest, and
1580 // presumably the most difficult, tile will be decoded in the main thread.
1581 // This should help minimize the number of instances where the main thread is
1582 // waiting for a worker to complete.
1584 int group_start = 0;
1585 while (group_start < tile_cols) {
1586 const TileBuffer largest = tile_buffers[0][group_start];
1587 const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1588 memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1589 (group_end - group_start) * sizeof(tile_buffers[0][0]));
1590 tile_buffers[0][group_end] = largest;
1591 group_start = group_end + 1;
1595 // Initialize thread frame counts.
1596 if (!cm->frame_parallel_decoding_mode) {
1599 for (i = 0; i < num_workers; ++i) {
1600 TileWorkerData *const tile_data =
1601 (TileWorkerData*)pbi->tile_workers[i].data1;
1602 vp9_zero(tile_data->counts);
1607 while (n < tile_cols) {
1609 for (i = 0; i < num_workers && n < tile_cols; ++i) {
1610 VPxWorker *const worker = &pbi->tile_workers[i];
1611 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1612 TileInfo *const tile = (TileInfo*)worker->data2;
1613 TileBuffer *const buf = &tile_buffers[0][n];
1615 tile_data->pbi = pbi;
1616 tile_data->xd = pbi->mb;
1617 tile_data->xd.corrupted = 0;
1618 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1619 0 : &tile_data->counts;
1620 vp9_zero(tile_data->dqcoeff);
1621 vp9_tile_init(tile, cm, 0, buf->col);
1622 vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1623 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1624 &tile_data->bit_reader, pbi->decrypt_cb,
1625 pbi->decrypt_state);
1626 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1628 worker->had_error = 0;
1629 if (i == num_workers - 1 || n == tile_cols - 1) {
1630 winterface->execute(worker);
1632 winterface->launch(worker);
1635 if (buf->col == tile_cols - 1) {
1642 for (; i > 0; --i) {
1643 VPxWorker *const worker = &pbi->tile_workers[i - 1];
1644 // TODO(jzern): The tile may have specific error data associated with
1645 // its vpx_internal_error_info which could be propagated to the main info
1646 // in cm. Additionally once the threads have been synced and an error is
1647 // detected, there's no point in continuing to decode tiles.
1648 pbi->mb.corrupted |= !winterface->sync(worker);
1650 if (final_worker > -1) {
1651 TileWorkerData *const tile_data =
1652 (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1653 bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1657 // Accumulate thread frame counts.
1658 if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1659 for (i = 0; i < num_workers; ++i) {
1660 TileWorkerData *const tile_data =
1661 (TileWorkerData*)pbi->tile_workers[i].data1;
1662 vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1667 return bit_reader_end;
1670 static void error_handler(void *data) {
1671 VP9_COMMON *const cm = (VP9_COMMON *)data;
1672 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1675 static void read_bitdepth_colorspace_sampling(
1676 VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1677 if (cm->profile >= PROFILE_2) {
1678 cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1679 #if CONFIG_VP9_HIGHBITDEPTH
1680 cm->use_highbitdepth = 1;
1683 cm->bit_depth = VPX_BITS_8;
1684 #if CONFIG_VP9_HIGHBITDEPTH
1685 cm->use_highbitdepth = 0;
1688 cm->color_space = vp9_rb_read_literal(rb, 3);
1689 if (cm->color_space != VPX_CS_SRGB) {
1690 vp9_rb_read_bit(rb); // [16,235] (including xvycc) vs [0,255] range
1691 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1692 cm->subsampling_x = vp9_rb_read_bit(rb);
1693 cm->subsampling_y = vp9_rb_read_bit(rb);
1694 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1695 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1696 "4:2:0 color not supported in profile 1 or 3");
1697 if (vp9_rb_read_bit(rb))
1698 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1699 "Reserved bit set");
1701 cm->subsampling_y = cm->subsampling_x = 1;
1704 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1705 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1706 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1707 cm->subsampling_y = cm->subsampling_x = 0;
1708 if (vp9_rb_read_bit(rb))
1709 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1710 "Reserved bit set");
1712 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1713 "4:4:4 color not supported in profile 0 or 2");
1718 static size_t read_uncompressed_header(VP9Decoder *pbi,
1719 struct vp9_read_bit_buffer *rb) {
1720 VP9_COMMON *const cm = &pbi->common;
1721 BufferPool *const pool = cm->buffer_pool;
1722 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1723 int i, mask, ref_index = 0;
1726 cm->last_frame_type = cm->frame_type;
1727 cm->last_intra_only = cm->intra_only;
1729 if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1730 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1731 "Invalid frame marker");
1733 cm->profile = vp9_read_profile(rb);
1735 if (cm->profile >= MAX_PROFILES)
1736 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1737 "Unsupported bitstream profile");
1739 cm->show_existing_frame = vp9_rb_read_bit(rb);
1740 if (cm->show_existing_frame) {
1741 // Show an existing frame directly.
1742 const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1743 lock_buffer_pool(pool);
1744 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1745 unlock_buffer_pool(pool);
1746 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1747 "Buffer %d does not contain a decoded frame",
1751 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1752 unlock_buffer_pool(pool);
1753 pbi->refresh_frame_flags = 0;
1754 cm->lf.filter_level = 0;
1757 if (pbi->frame_parallel_decode) {
1758 for (i = 0; i < REF_FRAMES; ++i)
1759 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1764 cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1765 cm->show_frame = vp9_rb_read_bit(rb);
1766 cm->error_resilient_mode = vp9_rb_read_bit(rb);
1768 if (cm->frame_type == KEY_FRAME) {
1769 if (!vp9_read_sync_code(rb))
1770 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1771 "Invalid frame sync code");
1773 read_bitdepth_colorspace_sampling(cm, rb);
1774 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1776 for (i = 0; i < REFS_PER_FRAME; ++i) {
1777 cm->frame_refs[i].idx = INVALID_IDX;
1778 cm->frame_refs[i].buf = NULL;
1781 setup_frame_size(cm, rb);
1782 if (pbi->need_resync) {
1783 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1784 pbi->need_resync = 0;
1787 cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1789 cm->reset_frame_context = cm->error_resilient_mode ?
1790 0 : vp9_rb_read_literal(rb, 2);
1792 if (cm->intra_only) {
1793 if (!vp9_read_sync_code(rb))
1794 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1795 "Invalid frame sync code");
1796 if (cm->profile > PROFILE_0) {
1797 read_bitdepth_colorspace_sampling(cm, rb);
1799 // NOTE: The intra-only frame header does not include the specification
1800 // of either the color format or color sub-sampling in profile 0. VP9
1801 // specifies that the default color format should be YUV 4:2:0 in this
1802 // case (normative).
1803 cm->color_space = VPX_CS_BT_601;
1804 cm->subsampling_y = cm->subsampling_x = 1;
1805 cm->bit_depth = VPX_BITS_8;
1806 #if CONFIG_VP9_HIGHBITDEPTH
1807 cm->use_highbitdepth = 0;
1811 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1812 setup_frame_size(cm, rb);
1813 if (pbi->need_resync) {
1814 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1815 pbi->need_resync = 0;
1817 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1818 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1819 for (i = 0; i < REFS_PER_FRAME; ++i) {
1820 const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1821 const int idx = cm->ref_frame_map[ref];
1822 RefBuffer *const ref_frame = &cm->frame_refs[i];
1823 ref_frame->idx = idx;
1824 ref_frame->buf = &frame_bufs[idx].buf;
1825 cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1828 setup_frame_size_with_refs(cm, rb);
1830 cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1831 cm->interp_filter = read_interp_filter(rb);
1833 for (i = 0; i < REFS_PER_FRAME; ++i) {
1834 RefBuffer *const ref_buf = &cm->frame_refs[i];
1835 #if CONFIG_VP9_HIGHBITDEPTH
1836 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1837 ref_buf->buf->y_crop_width,
1838 ref_buf->buf->y_crop_height,
1839 cm->width, cm->height,
1840 cm->use_highbitdepth);
1842 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1843 ref_buf->buf->y_crop_width,
1844 ref_buf->buf->y_crop_height,
1845 cm->width, cm->height);
1850 #if CONFIG_VP9_HIGHBITDEPTH
1851 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1853 get_frame_new_buffer(cm)->color_space = cm->color_space;
1855 if (pbi->need_resync) {
1856 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1857 "Keyframe / intra-only frame required to reset decoder"
1861 if (!cm->error_resilient_mode) {
1862 cm->refresh_frame_context = vp9_rb_read_bit(rb);
1863 cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1865 cm->refresh_frame_context = 0;
1866 cm->frame_parallel_decoding_mode = 1;
1869 // This flag will be overridden by the call to vp9_setup_past_independence
1870 // below, forcing the use of context 0 for those frame types.
1871 cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1873 // Generate next_ref_frame_map.
1874 lock_buffer_pool(pool);
1875 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1877 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1878 ++frame_bufs[cm->new_fb_idx].ref_count;
1880 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1882 // Current thread holds the reference frame.
1883 if (cm->ref_frame_map[ref_index] >= 0)
1884 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1888 for (; ref_index < REF_FRAMES; ++ref_index) {
1889 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1890 // Current thread holds the reference frame.
1891 if (cm->ref_frame_map[ref_index] >= 0)
1892 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1894 unlock_buffer_pool(pool);
1895 pbi->hold_ref_buf = 1;
1897 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1898 vp9_setup_past_independence(cm);
1900 setup_loopfilter(&cm->lf, rb);
1901 setup_quantization(cm, &pbi->mb, rb);
1902 setup_segmentation(&cm->seg, rb);
1903 setup_segmentation_dequant(cm);
1905 setup_tile_info(cm, rb);
1906 sz = vp9_rb_read_literal(rb, 16);
1909 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1910 "Invalid header size");
1915 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1916 size_t partition_size) {
1917 VP9_COMMON *const cm = &pbi->common;
1918 MACROBLOCKD *const xd = &pbi->mb;
1919 FRAME_CONTEXT *const fc = cm->fc;
1923 if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1924 pbi->decrypt_state))
1925 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1926 "Failed to allocate bool decoder 0");
1928 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1929 if (cm->tx_mode == TX_MODE_SELECT)
1930 read_tx_mode_probs(&fc->tx_probs, &r);
1931 read_coef_probs(fc, cm->tx_mode, &r);
1933 for (k = 0; k < SKIP_CONTEXTS; ++k)
1934 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1936 if (!frame_is_intra_only(cm)) {
1937 nmv_context *const nmvc = &fc->nmvc;
1940 read_inter_mode_probs(fc, &r);
1942 if (cm->interp_filter == SWITCHABLE)
1943 read_switchable_interp_probs(fc, &r);
1945 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1946 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1948 cm->reference_mode = read_frame_reference_mode(cm, &r);
1949 if (cm->reference_mode != SINGLE_REFERENCE)
1950 setup_compound_reference_mode(cm);
1951 read_frame_reference_mode_probs(cm, &r);
1953 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1954 for (i = 0; i < INTRA_MODES - 1; ++i)
1955 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1957 for (j = 0; j < PARTITION_CONTEXTS; ++j)
1958 for (i = 0; i < PARTITION_TYPES - 1; ++i)
1959 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1961 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
1964 return vp9_reader_has_error(&r);
1968 #define debug_check_frame_counts(cm) (void)0
1970 // Counts should only be incremented when frame_parallel_decoding_mode and
1971 // error_resilient_mode are disabled.
1972 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
1973 FRAME_COUNTS zero_counts;
1974 vp9_zero(zero_counts);
1975 assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
1976 assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
1977 sizeof(cm->counts.y_mode)));
1978 assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
1979 sizeof(cm->counts.uv_mode)));
1980 assert(!memcmp(cm->counts.partition, zero_counts.partition,
1981 sizeof(cm->counts.partition)));
1982 assert(!memcmp(cm->counts.coef, zero_counts.coef,
1983 sizeof(cm->counts.coef)));
1984 assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
1985 sizeof(cm->counts.eob_branch)));
1986 assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
1987 sizeof(cm->counts.switchable_interp)));
1988 assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
1989 sizeof(cm->counts.inter_mode)));
1990 assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
1991 sizeof(cm->counts.intra_inter)));
1992 assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
1993 sizeof(cm->counts.comp_inter)));
1994 assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
1995 sizeof(cm->counts.single_ref)));
1996 assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
1997 sizeof(cm->counts.comp_ref)));
1998 assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
1999 assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
2000 assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
2004 static struct vp9_read_bit_buffer *init_read_bit_buffer(
2006 struct vp9_read_bit_buffer *rb,
2007 const uint8_t *data,
2008 const uint8_t *data_end,
2009 uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2011 rb->error_handler = error_handler;
2012 rb->error_handler_data = &pbi->common;
2013 if (pbi->decrypt_cb) {
2014 const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
2015 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2016 rb->bit_buffer = clear_data;
2017 rb->bit_buffer_end = clear_data + n;
2019 rb->bit_buffer = data;
2020 rb->bit_buffer_end = data_end;
2025 //------------------------------------------------------------------------------
2027 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
2028 return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2029 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2030 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2033 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
2034 int *width, int *height) {
2035 *width = vp9_rb_read_literal(rb, 16) + 1;
2036 *height = vp9_rb_read_literal(rb, 16) + 1;
2039 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
2040 int profile = vp9_rb_read_bit(rb);
2041 profile |= vp9_rb_read_bit(rb) << 1;
2043 profile += vp9_rb_read_bit(rb);
2044 return (BITSTREAM_PROFILE) profile;
2047 void vp9_decode_frame(VP9Decoder *pbi,
2048 const uint8_t *data, const uint8_t *data_end,
2049 const uint8_t **p_data_end) {
2050 VP9_COMMON *const cm = &pbi->common;
2051 MACROBLOCKD *const xd = &pbi->mb;
2052 struct vp9_read_bit_buffer rb;
2053 int context_updated = 0;
2054 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2055 const size_t first_partition_size = read_uncompressed_header(pbi,
2056 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2057 const int tile_rows = 1 << cm->log2_tile_rows;
2058 const int tile_cols = 1 << cm->log2_tile_cols;
2059 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2060 xd->cur_buf = new_fb;
2062 if (!first_partition_size) {
2063 // showing a frame directly
2064 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2068 data += vp9_rb_bytes_read(&rb);
2069 if (!read_is_valid(data, first_partition_size, data_end))
2070 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2071 "Truncated packet or corrupt header length");
2073 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2074 cm->width == cm->last_width &&
2075 cm->height == cm->last_height &&
2076 !cm->last_intra_only &&
2077 cm->last_show_frame &&
2078 (cm->last_frame_type != KEY_FRAME);
2080 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2082 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2083 if (!cm->fc->initialized)
2084 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2085 "Uninitialized entropy context.");
2087 vp9_zero(cm->counts);
2090 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2091 if (new_fb->corrupted)
2092 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2093 "Decode failed. Frame data header is corrupted.");
2095 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2096 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2099 // If encoded in frame parallel mode, frame context is ready after decoding
2100 // the frame header.
2101 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2102 VPxWorker *const worker = pbi->frame_worker_owner;
2103 FrameWorkerData *const frame_worker_data = worker->data1;
2104 if (cm->refresh_frame_context) {
2105 context_updated = 1;
2106 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2108 vp9_frameworker_lock_stats(worker);
2109 pbi->cur_buf->row = -1;
2110 pbi->cur_buf->col = -1;
2111 frame_worker_data->frame_context_ready = 1;
2112 // Signal the main thread that context is ready.
2113 vp9_frameworker_signal_stats(worker);
2114 vp9_frameworker_unlock_stats(worker);
2117 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2118 // Multi-threaded tile decoder
2119 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2120 if (!xd->corrupted) {
2121 if (!cm->skip_loop_filter) {
2122 // If multiple threads are used to decode tiles, then we use those
2123 // threads to do parallel loopfiltering.
2124 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2125 cm->lf.filter_level, 0, 0, pbi->tile_workers,
2126 pbi->num_tile_workers, &pbi->lf_row_sync);
2129 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2130 "Decode failed. Frame data is corrupted.");
2134 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2137 if (!xd->corrupted) {
2138 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2139 vp9_adapt_coef_probs(cm);
2141 if (!frame_is_intra_only(cm)) {
2142 vp9_adapt_mode_probs(cm);
2143 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2146 debug_check_frame_counts(cm);
2149 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2150 "Decode failed. Frame data is corrupted.");
2153 // Non frame parallel update frame context here.
2154 if (cm->refresh_frame_context && !context_updated)
2155 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;