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 row, int col,
410 BLOCK_SIZE plane_bsize,
411 TX_SIZE tx_size, struct inter_args *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 eob = vp9_decode_block_tokens(xd, plane, sc, plane_bsize,
418 col, row, tx_size, args->r, args->seg_id);
420 inverse_transform_block_inter(xd, plane, tx_size,
421 &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
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};
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 = plane ? get_uv_tx_size(mbmi, pd)
847 const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, pd);
848 const int num_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
849 const int num_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
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 (r = 0; r < max_blocks_high; r += step)
858 for (c = 0; c < max_blocks_wide; c += step)
859 reconstruct_inter_block(plane, r, c, plane_bsize, tx_size, &arg);
862 if (!less8x8 && eobtotal == 0)
863 mbmi->skip = 1; // skip loopfilter
867 xd->corrupted |= vp9_reader_has_error(r);
870 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
871 BLOCK_SIZE bsize, vp9_reader *r,
872 int has_rows, int has_cols) {
873 const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
874 const vp9_prob *const probs = get_partition_probs(xd, ctx);
875 FRAME_COUNTS *counts = xd->counts;
878 if (has_rows && has_cols)
879 p = (PARTITION_TYPE)vp9_read_tree(r, vp9_partition_tree, probs);
880 else if (!has_rows && has_cols)
881 p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
882 else if (has_rows && !has_cols)
883 p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
888 ++counts->partition[ctx][p];
893 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
894 int mi_row, int mi_col,
895 vp9_reader* r, BLOCK_SIZE bsize) {
896 VP9_COMMON *const cm = &pbi->common;
897 const int hbs = num_8x8_blocks_wide_lookup[bsize] / 2;
898 PARTITION_TYPE partition;
900 const int has_rows = (mi_row + hbs) < cm->mi_rows;
901 const int has_cols = (mi_col + hbs) < cm->mi_cols;
903 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
906 partition = read_partition(xd, mi_row, mi_col, bsize, r, has_rows, has_cols);
907 subsize = get_subsize(bsize, partition);
908 if (bsize == BLOCK_8X8) {
909 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
913 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
916 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
918 decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize);
921 decode_block(pbi, xd, mi_row, mi_col, r, subsize);
923 decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize);
925 case PARTITION_SPLIT:
926 decode_partition(pbi, xd, mi_row, mi_col, r, subsize);
927 decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize);
928 decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize);
929 decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize);
932 assert(0 && "Invalid partition type");
936 // update partition context
937 if (bsize >= BLOCK_8X8 &&
938 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
939 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
942 static void setup_token_decoder(const uint8_t *data,
943 const uint8_t *data_end,
945 struct vpx_internal_error_info *error_info,
947 vpx_decrypt_cb decrypt_cb,
948 void *decrypt_state) {
949 // Validate the calculated partition length. If the buffer
950 // described by the partition can't be fully read, then restrict
951 // it to the portion that can be (for EC mode) or throw an error.
952 if (!read_is_valid(data, read_size, data_end))
953 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
954 "Truncated packet or corrupt tile length");
956 if (vp9_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
957 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
958 "Failed to allocate bool decoder %d", 1);
961 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
966 for (i = 0; i < PLANE_TYPES; ++i)
967 for (j = 0; j < REF_TYPES; ++j)
968 for (k = 0; k < COEF_BANDS; ++k)
969 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
970 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
971 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
974 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
976 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
978 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
979 read_coef_probs_common(fc->coef_probs[tx_size], r);
982 static void setup_segmentation(struct segmentation *seg,
983 struct vp9_read_bit_buffer *rb) {
987 seg->update_data = 0;
989 seg->enabled = vp9_rb_read_bit(rb);
993 // Segmentation map update
994 seg->update_map = vp9_rb_read_bit(rb);
995 if (seg->update_map) {
996 for (i = 0; i < SEG_TREE_PROBS; i++)
997 seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1000 seg->temporal_update = vp9_rb_read_bit(rb);
1001 if (seg->temporal_update) {
1002 for (i = 0; i < PREDICTION_PROBS; i++)
1003 seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
1006 for (i = 0; i < PREDICTION_PROBS; i++)
1007 seg->pred_probs[i] = MAX_PROB;
1011 // Segmentation data update
1012 seg->update_data = vp9_rb_read_bit(rb);
1013 if (seg->update_data) {
1014 seg->abs_delta = vp9_rb_read_bit(rb);
1016 vp9_clearall_segfeatures(seg);
1018 for (i = 0; i < MAX_SEGMENTS; i++) {
1019 for (j = 0; j < SEG_LVL_MAX; j++) {
1021 const int feature_enabled = vp9_rb_read_bit(rb);
1022 if (feature_enabled) {
1023 vp9_enable_segfeature(seg, i, j);
1024 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1025 if (vp9_is_segfeature_signed(j))
1026 data = vp9_rb_read_bit(rb) ? -data : data;
1028 vp9_set_segdata(seg, i, j, data);
1034 static void setup_loopfilter(struct loopfilter *lf,
1035 struct vp9_read_bit_buffer *rb) {
1036 lf->filter_level = vp9_rb_read_literal(rb, 6);
1037 lf->sharpness_level = vp9_rb_read_literal(rb, 3);
1039 // Read in loop filter deltas applied at the MB level based on mode or ref
1041 lf->mode_ref_delta_update = 0;
1043 lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
1044 if (lf->mode_ref_delta_enabled) {
1045 lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
1046 if (lf->mode_ref_delta_update) {
1049 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1050 if (vp9_rb_read_bit(rb))
1051 lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1053 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1054 if (vp9_rb_read_bit(rb))
1055 lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
1060 static INLINE int read_delta_q(struct vp9_read_bit_buffer *rb) {
1061 return vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
1064 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1065 struct vp9_read_bit_buffer *rb) {
1066 cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
1067 cm->y_dc_delta_q = read_delta_q(rb);
1068 cm->uv_dc_delta_q = read_delta_q(rb);
1069 cm->uv_ac_delta_q = read_delta_q(rb);
1070 cm->dequant_bit_depth = cm->bit_depth;
1071 xd->lossless = cm->base_qindex == 0 &&
1072 cm->y_dc_delta_q == 0 &&
1073 cm->uv_dc_delta_q == 0 &&
1074 cm->uv_ac_delta_q == 0;
1076 #if CONFIG_VP9_HIGHBITDEPTH
1077 xd->bd = (int)cm->bit_depth;
1081 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1082 // Build y/uv dequant values based on segmentation.
1083 if (cm->seg.enabled) {
1085 for (i = 0; i < MAX_SEGMENTS; ++i) {
1086 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1087 cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
1089 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1090 cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1092 cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1096 const int qindex = cm->base_qindex;
1097 // When segmentation is disabled, only the first value is used. The
1098 // remaining are don't cares.
1099 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1100 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1101 cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1103 cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1108 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
1109 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1113 return vp9_rb_read_bit(rb) ? SWITCHABLE
1114 : literal_to_filter[vp9_rb_read_literal(rb, 2)];
1117 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1118 cm->display_width = cm->width;
1119 cm->display_height = cm->height;
1120 if (vp9_rb_read_bit(rb))
1121 vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
1124 static void resize_mv_buffer(VP9_COMMON *cm) {
1125 vpx_free(cm->cur_frame->mvs);
1126 cm->cur_frame->mi_rows = cm->mi_rows;
1127 cm->cur_frame->mi_cols = cm->mi_cols;
1128 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1129 sizeof(*cm->cur_frame->mvs));
1132 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1133 #if CONFIG_SIZE_LIMIT
1134 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1135 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1136 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1137 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1139 if (cm->width != width || cm->height != height) {
1140 const int new_mi_rows =
1141 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1142 const int new_mi_cols =
1143 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1145 // Allocations in vp9_alloc_context_buffers() depend on individual
1146 // dimensions as well as the overall size.
1147 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1148 if (vp9_alloc_context_buffers(cm, width, height))
1149 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1150 "Failed to allocate context buffers");
1152 vp9_set_mb_mi(cm, width, height);
1154 vp9_init_context_buffers(cm);
1156 cm->height = height;
1158 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1159 cm->mi_cols > cm->cur_frame->mi_cols) {
1160 resize_mv_buffer(cm);
1164 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1166 BufferPool *const pool = cm->buffer_pool;
1167 vp9_read_frame_size(rb, &width, &height);
1168 resize_context_buffers(cm, width, height);
1169 setup_display_size(cm, rb);
1171 lock_buffer_pool(pool);
1172 if (vp9_realloc_frame_buffer(
1173 get_frame_new_buffer(cm), cm->width, cm->height,
1174 cm->subsampling_x, cm->subsampling_y,
1175 #if CONFIG_VP9_HIGHBITDEPTH
1176 cm->use_highbitdepth,
1178 VP9_DEC_BORDER_IN_PIXELS,
1180 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1182 unlock_buffer_pool(pool);
1183 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1184 "Failed to allocate frame buffer");
1186 unlock_buffer_pool(pool);
1188 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1189 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1190 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1191 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1194 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1195 int ref_xss, int ref_yss,
1196 vpx_bit_depth_t this_bit_depth,
1197 int this_xss, int this_yss) {
1198 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1199 ref_yss == this_yss;
1202 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1203 struct vp9_read_bit_buffer *rb) {
1206 int has_valid_ref_frame = 0;
1207 BufferPool *const pool = cm->buffer_pool;
1208 for (i = 0; i < REFS_PER_FRAME; ++i) {
1209 if (vp9_rb_read_bit(rb)) {
1210 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1211 width = buf->y_crop_width;
1212 height = buf->y_crop_height;
1219 vp9_read_frame_size(rb, &width, &height);
1221 if (width <= 0 || height <= 0)
1222 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1223 "Invalid frame size");
1225 // Check to make sure at least one of frames that this frame references
1226 // has valid dimensions.
1227 for (i = 0; i < REFS_PER_FRAME; ++i) {
1228 RefBuffer *const ref_frame = &cm->frame_refs[i];
1229 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1230 ref_frame->buf->y_crop_height,
1233 if (!has_valid_ref_frame)
1234 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1235 "Referenced frame has invalid size");
1236 for (i = 0; i < REFS_PER_FRAME; ++i) {
1237 RefBuffer *const ref_frame = &cm->frame_refs[i];
1238 if (!valid_ref_frame_img_fmt(
1239 ref_frame->buf->bit_depth,
1240 ref_frame->buf->subsampling_x,
1241 ref_frame->buf->subsampling_y,
1245 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1246 "Referenced frame has incompatible color format");
1249 resize_context_buffers(cm, width, height);
1250 setup_display_size(cm, rb);
1252 lock_buffer_pool(pool);
1253 if (vp9_realloc_frame_buffer(
1254 get_frame_new_buffer(cm), cm->width, cm->height,
1255 cm->subsampling_x, cm->subsampling_y,
1256 #if CONFIG_VP9_HIGHBITDEPTH
1257 cm->use_highbitdepth,
1259 VP9_DEC_BORDER_IN_PIXELS,
1261 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1263 unlock_buffer_pool(pool);
1264 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1265 "Failed to allocate frame buffer");
1267 unlock_buffer_pool(pool);
1269 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1270 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1271 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1272 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1275 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1276 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1277 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1280 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1281 cm->log2_tile_cols = min_log2_tile_cols;
1282 while (max_ones-- && vp9_rb_read_bit(rb))
1283 cm->log2_tile_cols++;
1285 if (cm->log2_tile_cols > 6)
1286 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1287 "Invalid number of tile columns");
1290 cm->log2_tile_rows = vp9_rb_read_bit(rb);
1291 if (cm->log2_tile_rows)
1292 cm->log2_tile_rows += vp9_rb_read_bit(rb);
1295 typedef struct TileBuffer {
1296 const uint8_t *data;
1298 int col; // only used with multi-threaded decoding
1301 // Reads the next tile returning its size and adjusting '*data' accordingly
1302 // based on 'is_last'.
1303 static void get_tile_buffer(const uint8_t *const data_end,
1305 struct vpx_internal_error_info *error_info,
1306 const uint8_t **data,
1307 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1312 if (!read_is_valid(*data, 4, data_end))
1313 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1314 "Truncated packet or corrupt tile length");
1318 decrypt_cb(decrypt_state, *data, be_data, 4);
1319 size = mem_get_be32(be_data);
1321 size = mem_get_be32(*data);
1325 if (size > (size_t)(data_end - *data))
1326 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1327 "Truncated packet or corrupt tile size");
1329 size = data_end - *data;
1338 static void get_tile_buffers(VP9Decoder *pbi,
1339 const uint8_t *data, const uint8_t *data_end,
1340 int tile_cols, int tile_rows,
1341 TileBuffer (*tile_buffers)[1 << 6]) {
1344 for (r = 0; r < tile_rows; ++r) {
1345 for (c = 0; c < tile_cols; ++c) {
1346 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1347 TileBuffer *const buf = &tile_buffers[r][c];
1349 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1350 pbi->decrypt_cb, pbi->decrypt_state, buf);
1355 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1356 const uint8_t *data,
1357 const uint8_t *data_end) {
1358 VP9_COMMON *const cm = &pbi->common;
1359 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1360 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1361 const int tile_cols = 1 << cm->log2_tile_cols;
1362 const int tile_rows = 1 << cm->log2_tile_rows;
1363 TileBuffer tile_buffers[4][1 << 6];
1364 int tile_row, tile_col;
1366 TileData *tile_data = NULL;
1368 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1369 pbi->lf_worker.data1 == NULL) {
1370 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1371 vpx_memalign(32, sizeof(LFWorkerData)));
1372 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1373 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1374 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1375 "Loop filter thread creation failed");
1379 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1380 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1381 // Be sure to sync as we might be resuming after a failed frame decode.
1382 winterface->sync(&pbi->lf_worker);
1383 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1387 assert(tile_rows <= 4);
1388 assert(tile_cols <= (1 << 6));
1390 // Note: this memset assumes above_context[0], [1] and [2]
1391 // are allocated as part of the same buffer.
1392 memset(cm->above_context, 0,
1393 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1395 memset(cm->above_seg_context, 0,
1396 sizeof(*cm->above_seg_context) * aligned_cols);
1398 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1400 if (pbi->tile_data == NULL ||
1401 (tile_cols * tile_rows) != pbi->total_tiles) {
1402 vpx_free(pbi->tile_data);
1406 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1407 pbi->total_tiles = tile_rows * tile_cols;
1410 // Load all tile information into tile_data.
1411 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1412 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1413 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1414 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1416 tile_data->xd = pbi->mb;
1417 tile_data->xd.corrupted = 0;
1418 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1420 vp9_zero(tile_data->dqcoeff);
1421 vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1422 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1423 &tile_data->bit_reader, pbi->decrypt_cb,
1424 pbi->decrypt_state);
1425 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1429 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1431 vp9_tile_set_row(&tile, cm, tile_row);
1432 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1433 mi_row += MI_BLOCK_SIZE) {
1434 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1435 const int col = pbi->inv_tile_order ?
1436 tile_cols - tile_col - 1 : tile_col;
1437 tile_data = pbi->tile_data + tile_cols * tile_row + col;
1438 vp9_tile_set_col(&tile, tile_data->cm, col);
1439 vp9_zero(tile_data->xd.left_context);
1440 vp9_zero(tile_data->xd.left_seg_context);
1441 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1442 mi_col += MI_BLOCK_SIZE) {
1443 decode_partition(pbi, &tile_data->xd, mi_row, mi_col,
1444 &tile_data->bit_reader, BLOCK_64X64);
1446 pbi->mb.corrupted |= tile_data->xd.corrupted;
1447 if (pbi->mb.corrupted)
1448 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1449 "Failed to decode tile data");
1451 // Loopfilter one row.
1452 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1453 const int lf_start = mi_row - MI_BLOCK_SIZE;
1454 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1456 // delay the loopfilter by 1 macroblock row.
1457 if (lf_start < 0) continue;
1459 // decoding has completed: finish up the loop filter in this thread.
1460 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1462 winterface->sync(&pbi->lf_worker);
1463 lf_data->start = lf_start;
1464 lf_data->stop = mi_row;
1465 if (pbi->max_threads > 1) {
1466 winterface->launch(&pbi->lf_worker);
1468 winterface->execute(&pbi->lf_worker);
1471 // After loopfiltering, the last 7 row pixels in each superblock row may
1472 // still be changed by the longest loopfilter of the next superblock
1474 if (pbi->frame_parallel_decode)
1475 vp9_frameworker_broadcast(pbi->cur_buf,
1476 mi_row << MI_BLOCK_SIZE_LOG2);
1480 // Loopfilter remaining rows in the frame.
1481 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1482 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1483 winterface->sync(&pbi->lf_worker);
1484 lf_data->start = lf_data->stop;
1485 lf_data->stop = cm->mi_rows;
1486 winterface->execute(&pbi->lf_worker);
1489 // Get last tile data.
1490 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1492 if (pbi->frame_parallel_decode)
1493 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1494 return vp9_reader_find_end(&tile_data->bit_reader);
1497 static int tile_worker_hook(TileWorkerData *const tile_data,
1498 const TileInfo *const tile) {
1501 if (setjmp(tile_data->error_info.jmp)) {
1502 tile_data->error_info.setjmp = 0;
1503 tile_data->xd.corrupted = 1;
1507 tile_data->error_info.setjmp = 1;
1508 tile_data->xd.error_info = &tile_data->error_info;
1510 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1511 mi_row += MI_BLOCK_SIZE) {
1512 vp9_zero(tile_data->xd.left_context);
1513 vp9_zero(tile_data->xd.left_seg_context);
1514 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1515 mi_col += MI_BLOCK_SIZE) {
1516 decode_partition(tile_data->pbi, &tile_data->xd,
1517 mi_row, mi_col, &tile_data->bit_reader,
1521 return !tile_data->xd.corrupted;
1524 // sorts in descending order
1525 static int compare_tile_buffers(const void *a, const void *b) {
1526 const TileBuffer *const buf1 = (const TileBuffer*)a;
1527 const TileBuffer *const buf2 = (const TileBuffer*)b;
1528 return (int)(buf2->size - buf1->size);
1531 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1532 const uint8_t *data,
1533 const uint8_t *data_end) {
1534 VP9_COMMON *const cm = &pbi->common;
1535 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1536 const uint8_t *bit_reader_end = NULL;
1537 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1538 const int tile_cols = 1 << cm->log2_tile_cols;
1539 const int tile_rows = 1 << cm->log2_tile_rows;
1540 const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1541 TileBuffer tile_buffers[1][1 << 6];
1543 int final_worker = -1;
1545 assert(tile_cols <= (1 << 6));
1546 assert(tile_rows == 1);
1549 // TODO(jzern): See if we can remove the restriction of passing in max
1550 // threads to the decoder.
1551 if (pbi->num_tile_workers == 0) {
1552 const int num_threads = pbi->max_threads & ~1;
1554 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1555 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1556 // Ensure tile data offsets will be properly aligned. This may fail on
1557 // platforms without DECLARE_ALIGNED().
1558 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1559 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1560 vpx_memalign(32, num_threads *
1561 sizeof(*pbi->tile_worker_data)));
1562 CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1563 vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1564 for (i = 0; i < num_threads; ++i) {
1565 VPxWorker *const worker = &pbi->tile_workers[i];
1566 ++pbi->num_tile_workers;
1568 winterface->init(worker);
1569 if (i < num_threads - 1 && !winterface->reset(worker)) {
1570 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1571 "Tile decoder thread creation failed");
1576 // Reset tile decoding hook
1577 for (n = 0; n < num_workers; ++n) {
1578 VPxWorker *const worker = &pbi->tile_workers[n];
1579 winterface->sync(worker);
1580 worker->hook = (VPxWorkerHook)tile_worker_hook;
1581 worker->data1 = &pbi->tile_worker_data[n];
1582 worker->data2 = &pbi->tile_worker_info[n];
1585 // Note: this memset assumes above_context[0], [1] and [2]
1586 // are allocated as part of the same buffer.
1587 memset(cm->above_context, 0,
1588 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1589 memset(cm->above_seg_context, 0,
1590 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1592 // Load tile data into tile_buffers
1593 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1595 // Sort the buffers based on size in descending order.
1596 qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1597 compare_tile_buffers);
1599 // Rearrange the tile buffers such that per-tile group the largest, and
1600 // presumably the most difficult, tile will be decoded in the main thread.
1601 // This should help minimize the number of instances where the main thread is
1602 // waiting for a worker to complete.
1604 int group_start = 0;
1605 while (group_start < tile_cols) {
1606 const TileBuffer largest = tile_buffers[0][group_start];
1607 const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1608 memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1609 (group_end - group_start) * sizeof(tile_buffers[0][0]));
1610 tile_buffers[0][group_end] = largest;
1611 group_start = group_end + 1;
1615 // Initialize thread frame counts.
1616 if (!cm->frame_parallel_decoding_mode) {
1619 for (i = 0; i < num_workers; ++i) {
1620 TileWorkerData *const tile_data =
1621 (TileWorkerData*)pbi->tile_workers[i].data1;
1622 vp9_zero(tile_data->counts);
1627 while (n < tile_cols) {
1629 for (i = 0; i < num_workers && n < tile_cols; ++i) {
1630 VPxWorker *const worker = &pbi->tile_workers[i];
1631 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1632 TileInfo *const tile = (TileInfo*)worker->data2;
1633 TileBuffer *const buf = &tile_buffers[0][n];
1635 tile_data->pbi = pbi;
1636 tile_data->xd = pbi->mb;
1637 tile_data->xd.corrupted = 0;
1638 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1639 0 : &tile_data->counts;
1640 vp9_zero(tile_data->dqcoeff);
1641 vp9_tile_init(tile, cm, 0, buf->col);
1642 vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1643 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1644 &tile_data->bit_reader, pbi->decrypt_cb,
1645 pbi->decrypt_state);
1646 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1648 worker->had_error = 0;
1649 if (i == num_workers - 1 || n == tile_cols - 1) {
1650 winterface->execute(worker);
1652 winterface->launch(worker);
1655 if (buf->col == tile_cols - 1) {
1662 for (; i > 0; --i) {
1663 VPxWorker *const worker = &pbi->tile_workers[i - 1];
1664 // TODO(jzern): The tile may have specific error data associated with
1665 // its vpx_internal_error_info which could be propagated to the main info
1666 // in cm. Additionally once the threads have been synced and an error is
1667 // detected, there's no point in continuing to decode tiles.
1668 pbi->mb.corrupted |= !winterface->sync(worker);
1670 if (final_worker > -1) {
1671 TileWorkerData *const tile_data =
1672 (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1673 bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1677 // Accumulate thread frame counts.
1678 if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1679 for (i = 0; i < num_workers; ++i) {
1680 TileWorkerData *const tile_data =
1681 (TileWorkerData*)pbi->tile_workers[i].data1;
1682 vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1687 return bit_reader_end;
1690 static void error_handler(void *data) {
1691 VP9_COMMON *const cm = (VP9_COMMON *)data;
1692 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1695 static void read_bitdepth_colorspace_sampling(
1696 VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1697 if (cm->profile >= PROFILE_2) {
1698 cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1699 #if CONFIG_VP9_HIGHBITDEPTH
1700 cm->use_highbitdepth = 1;
1703 cm->bit_depth = VPX_BITS_8;
1704 #if CONFIG_VP9_HIGHBITDEPTH
1705 cm->use_highbitdepth = 0;
1708 cm->color_space = vp9_rb_read_literal(rb, 3);
1709 if (cm->color_space != VPX_CS_SRGB) {
1710 vp9_rb_read_bit(rb); // [16,235] (including xvycc) vs [0,255] range
1711 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1712 cm->subsampling_x = vp9_rb_read_bit(rb);
1713 cm->subsampling_y = vp9_rb_read_bit(rb);
1714 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1715 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1716 "4:2:0 color not supported in profile 1 or 3");
1717 if (vp9_rb_read_bit(rb))
1718 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1719 "Reserved bit set");
1721 cm->subsampling_y = cm->subsampling_x = 1;
1724 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1725 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1726 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1727 cm->subsampling_y = cm->subsampling_x = 0;
1728 if (vp9_rb_read_bit(rb))
1729 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1730 "Reserved bit set");
1732 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1733 "4:4:4 color not supported in profile 0 or 2");
1738 static size_t read_uncompressed_header(VP9Decoder *pbi,
1739 struct vp9_read_bit_buffer *rb) {
1740 VP9_COMMON *const cm = &pbi->common;
1741 BufferPool *const pool = cm->buffer_pool;
1742 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1743 int i, mask, ref_index = 0;
1746 cm->last_frame_type = cm->frame_type;
1747 cm->last_intra_only = cm->intra_only;
1749 if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1750 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1751 "Invalid frame marker");
1753 cm->profile = vp9_read_profile(rb);
1755 if (cm->profile >= MAX_PROFILES)
1756 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1757 "Unsupported bitstream profile");
1759 cm->show_existing_frame = vp9_rb_read_bit(rb);
1760 if (cm->show_existing_frame) {
1761 // Show an existing frame directly.
1762 const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1763 lock_buffer_pool(pool);
1764 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1765 unlock_buffer_pool(pool);
1766 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1767 "Buffer %d does not contain a decoded frame",
1771 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1772 unlock_buffer_pool(pool);
1773 pbi->refresh_frame_flags = 0;
1774 cm->lf.filter_level = 0;
1777 if (pbi->frame_parallel_decode) {
1778 for (i = 0; i < REF_FRAMES; ++i)
1779 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1784 cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1785 cm->show_frame = vp9_rb_read_bit(rb);
1786 cm->error_resilient_mode = vp9_rb_read_bit(rb);
1788 if (cm->frame_type == KEY_FRAME) {
1789 if (!vp9_read_sync_code(rb))
1790 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1791 "Invalid frame sync code");
1793 read_bitdepth_colorspace_sampling(cm, rb);
1794 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1796 for (i = 0; i < REFS_PER_FRAME; ++i) {
1797 cm->frame_refs[i].idx = INVALID_IDX;
1798 cm->frame_refs[i].buf = NULL;
1801 setup_frame_size(cm, rb);
1802 if (pbi->need_resync) {
1803 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1804 pbi->need_resync = 0;
1807 cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1809 cm->reset_frame_context = cm->error_resilient_mode ?
1810 0 : vp9_rb_read_literal(rb, 2);
1812 if (cm->intra_only) {
1813 if (!vp9_read_sync_code(rb))
1814 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1815 "Invalid frame sync code");
1816 if (cm->profile > PROFILE_0) {
1817 read_bitdepth_colorspace_sampling(cm, rb);
1819 // NOTE: The intra-only frame header does not include the specification
1820 // of either the color format or color sub-sampling in profile 0. VP9
1821 // specifies that the default color format should be YUV 4:2:0 in this
1822 // case (normative).
1823 cm->color_space = VPX_CS_BT_601;
1824 cm->subsampling_y = cm->subsampling_x = 1;
1825 cm->bit_depth = VPX_BITS_8;
1826 #if CONFIG_VP9_HIGHBITDEPTH
1827 cm->use_highbitdepth = 0;
1831 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1832 setup_frame_size(cm, rb);
1833 if (pbi->need_resync) {
1834 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1835 pbi->need_resync = 0;
1837 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1838 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1839 for (i = 0; i < REFS_PER_FRAME; ++i) {
1840 const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1841 const int idx = cm->ref_frame_map[ref];
1842 RefBuffer *const ref_frame = &cm->frame_refs[i];
1843 ref_frame->idx = idx;
1844 ref_frame->buf = &frame_bufs[idx].buf;
1845 cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1848 setup_frame_size_with_refs(cm, rb);
1850 cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1851 cm->interp_filter = read_interp_filter(rb);
1853 for (i = 0; i < REFS_PER_FRAME; ++i) {
1854 RefBuffer *const ref_buf = &cm->frame_refs[i];
1855 #if CONFIG_VP9_HIGHBITDEPTH
1856 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1857 ref_buf->buf->y_crop_width,
1858 ref_buf->buf->y_crop_height,
1859 cm->width, cm->height,
1860 cm->use_highbitdepth);
1862 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1863 ref_buf->buf->y_crop_width,
1864 ref_buf->buf->y_crop_height,
1865 cm->width, cm->height);
1870 #if CONFIG_VP9_HIGHBITDEPTH
1871 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1873 get_frame_new_buffer(cm)->color_space = cm->color_space;
1875 if (pbi->need_resync) {
1876 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1877 "Keyframe / intra-only frame required to reset decoder"
1881 if (!cm->error_resilient_mode) {
1882 cm->refresh_frame_context = vp9_rb_read_bit(rb);
1883 cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1885 cm->refresh_frame_context = 0;
1886 cm->frame_parallel_decoding_mode = 1;
1889 // This flag will be overridden by the call to vp9_setup_past_independence
1890 // below, forcing the use of context 0 for those frame types.
1891 cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1893 // Generate next_ref_frame_map.
1894 lock_buffer_pool(pool);
1895 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1897 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1898 ++frame_bufs[cm->new_fb_idx].ref_count;
1900 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1902 // Current thread holds the reference frame.
1903 if (cm->ref_frame_map[ref_index] >= 0)
1904 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1908 for (; ref_index < REF_FRAMES; ++ref_index) {
1909 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1910 // Current thread holds the reference frame.
1911 if (cm->ref_frame_map[ref_index] >= 0)
1912 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1914 unlock_buffer_pool(pool);
1915 pbi->hold_ref_buf = 1;
1917 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1918 vp9_setup_past_independence(cm);
1920 setup_loopfilter(&cm->lf, rb);
1921 setup_quantization(cm, &pbi->mb, rb);
1922 setup_segmentation(&cm->seg, rb);
1923 setup_segmentation_dequant(cm);
1925 setup_tile_info(cm, rb);
1926 sz = vp9_rb_read_literal(rb, 16);
1929 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1930 "Invalid header size");
1935 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1936 size_t partition_size) {
1937 VP9_COMMON *const cm = &pbi->common;
1938 MACROBLOCKD *const xd = &pbi->mb;
1939 FRAME_CONTEXT *const fc = cm->fc;
1943 if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1944 pbi->decrypt_state))
1945 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1946 "Failed to allocate bool decoder 0");
1948 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1949 if (cm->tx_mode == TX_MODE_SELECT)
1950 read_tx_mode_probs(&fc->tx_probs, &r);
1951 read_coef_probs(fc, cm->tx_mode, &r);
1953 for (k = 0; k < SKIP_CONTEXTS; ++k)
1954 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1956 if (!frame_is_intra_only(cm)) {
1957 nmv_context *const nmvc = &fc->nmvc;
1960 read_inter_mode_probs(fc, &r);
1962 if (cm->interp_filter == SWITCHABLE)
1963 read_switchable_interp_probs(fc, &r);
1965 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1966 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1968 cm->reference_mode = read_frame_reference_mode(cm, &r);
1969 if (cm->reference_mode != SINGLE_REFERENCE)
1970 setup_compound_reference_mode(cm);
1971 read_frame_reference_mode_probs(cm, &r);
1973 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1974 for (i = 0; i < INTRA_MODES - 1; ++i)
1975 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1977 for (j = 0; j < PARTITION_CONTEXTS; ++j)
1978 for (i = 0; i < PARTITION_TYPES - 1; ++i)
1979 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1981 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
1984 return vp9_reader_has_error(&r);
1988 #define debug_check_frame_counts(cm) (void)0
1990 // Counts should only be incremented when frame_parallel_decoding_mode and
1991 // error_resilient_mode are disabled.
1992 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
1993 FRAME_COUNTS zero_counts;
1994 vp9_zero(zero_counts);
1995 assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
1996 assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
1997 sizeof(cm->counts.y_mode)));
1998 assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
1999 sizeof(cm->counts.uv_mode)));
2000 assert(!memcmp(cm->counts.partition, zero_counts.partition,
2001 sizeof(cm->counts.partition)));
2002 assert(!memcmp(cm->counts.coef, zero_counts.coef,
2003 sizeof(cm->counts.coef)));
2004 assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
2005 sizeof(cm->counts.eob_branch)));
2006 assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
2007 sizeof(cm->counts.switchable_interp)));
2008 assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
2009 sizeof(cm->counts.inter_mode)));
2010 assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
2011 sizeof(cm->counts.intra_inter)));
2012 assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
2013 sizeof(cm->counts.comp_inter)));
2014 assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
2015 sizeof(cm->counts.single_ref)));
2016 assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
2017 sizeof(cm->counts.comp_ref)));
2018 assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
2019 assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
2020 assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
2024 static struct vp9_read_bit_buffer *init_read_bit_buffer(
2026 struct vp9_read_bit_buffer *rb,
2027 const uint8_t *data,
2028 const uint8_t *data_end,
2029 uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2031 rb->error_handler = error_handler;
2032 rb->error_handler_data = &pbi->common;
2033 if (pbi->decrypt_cb) {
2034 const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
2035 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2036 rb->bit_buffer = clear_data;
2037 rb->bit_buffer_end = clear_data + n;
2039 rb->bit_buffer = data;
2040 rb->bit_buffer_end = data_end;
2045 //------------------------------------------------------------------------------
2047 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
2048 return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2049 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2050 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2053 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
2054 int *width, int *height) {
2055 *width = vp9_rb_read_literal(rb, 16) + 1;
2056 *height = vp9_rb_read_literal(rb, 16) + 1;
2059 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
2060 int profile = vp9_rb_read_bit(rb);
2061 profile |= vp9_rb_read_bit(rb) << 1;
2063 profile += vp9_rb_read_bit(rb);
2064 return (BITSTREAM_PROFILE) profile;
2067 void vp9_decode_frame(VP9Decoder *pbi,
2068 const uint8_t *data, const uint8_t *data_end,
2069 const uint8_t **p_data_end) {
2070 VP9_COMMON *const cm = &pbi->common;
2071 MACROBLOCKD *const xd = &pbi->mb;
2072 struct vp9_read_bit_buffer rb;
2073 int context_updated = 0;
2074 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2075 const size_t first_partition_size = read_uncompressed_header(pbi,
2076 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2077 const int tile_rows = 1 << cm->log2_tile_rows;
2078 const int tile_cols = 1 << cm->log2_tile_cols;
2079 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2080 xd->cur_buf = new_fb;
2082 if (!first_partition_size) {
2083 // showing a frame directly
2084 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2088 data += vp9_rb_bytes_read(&rb);
2089 if (!read_is_valid(data, first_partition_size, data_end))
2090 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2091 "Truncated packet or corrupt header length");
2093 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2094 cm->width == cm->last_width &&
2095 cm->height == cm->last_height &&
2096 !cm->last_intra_only &&
2097 cm->last_show_frame &&
2098 (cm->last_frame_type != KEY_FRAME);
2100 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2102 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2103 if (!cm->fc->initialized)
2104 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2105 "Uninitialized entropy context.");
2107 vp9_zero(cm->counts);
2110 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2111 if (new_fb->corrupted)
2112 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2113 "Decode failed. Frame data header is corrupted.");
2115 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2116 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2119 // If encoded in frame parallel mode, frame context is ready after decoding
2120 // the frame header.
2121 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2122 VPxWorker *const worker = pbi->frame_worker_owner;
2123 FrameWorkerData *const frame_worker_data = worker->data1;
2124 if (cm->refresh_frame_context) {
2125 context_updated = 1;
2126 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2128 vp9_frameworker_lock_stats(worker);
2129 pbi->cur_buf->row = -1;
2130 pbi->cur_buf->col = -1;
2131 frame_worker_data->frame_context_ready = 1;
2132 // Signal the main thread that context is ready.
2133 vp9_frameworker_signal_stats(worker);
2134 vp9_frameworker_unlock_stats(worker);
2137 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2138 // Multi-threaded tile decoder
2139 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2140 if (!xd->corrupted) {
2141 if (!cm->skip_loop_filter) {
2142 // If multiple threads are used to decode tiles, then we use those
2143 // threads to do parallel loopfiltering.
2144 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2145 cm->lf.filter_level, 0, 0, pbi->tile_workers,
2146 pbi->num_tile_workers, &pbi->lf_row_sync);
2149 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2150 "Decode failed. Frame data is corrupted.");
2154 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2157 if (!xd->corrupted) {
2158 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2159 vp9_adapt_coef_probs(cm);
2161 if (!frame_is_intra_only(cm)) {
2162 vp9_adapt_mode_probs(cm);
2163 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2166 debug_check_frame_counts(cm);
2169 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2170 "Decode failed. Frame data is corrupted.");
2173 // Non frame parallel update frame context here.
2174 if (cm->refresh_frame_context && !context_updated)
2175 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;