2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
12 #include <stdlib.h> // qsort()
14 #include "./vp9_rtcd.h"
15 #include "./vpx_dsp_rtcd.h"
16 #include "./vpx_scale_rtcd.h"
18 #include "vpx_dsp/bitreader_buffer.h"
19 #include "vpx_dsp/bitreader.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_mem/vpx_mem.h"
22 #include "vpx_ports/mem.h"
23 #include "vpx_ports/mem_ops.h"
24 #include "vpx_scale/vpx_scale.h"
25 #include "vpx_util/vpx_thread.h"
27 #include "vp9/common/vp9_alloccommon.h"
28 #include "vp9/common/vp9_common.h"
29 #include "vp9/common/vp9_entropy.h"
30 #include "vp9/common/vp9_entropymode.h"
31 #include "vp9/common/vp9_idct.h"
32 #include "vp9/common/vp9_thread_common.h"
33 #include "vp9/common/vp9_pred_common.h"
34 #include "vp9/common/vp9_quant_common.h"
35 #include "vp9/common/vp9_reconintra.h"
36 #include "vp9/common/vp9_reconinter.h"
37 #include "vp9/common/vp9_seg_common.h"
38 #include "vp9/common/vp9_tile_common.h"
40 #include "vp9/decoder/vp9_decodeframe.h"
41 #include "vp9/decoder/vp9_detokenize.h"
42 #include "vp9/decoder/vp9_decodemv.h"
43 #include "vp9/decoder/vp9_decoder.h"
44 #include "vp9/decoder/vp9_dsubexp.h"
46 #define MAX_VP9_HEADER_SIZE 80
48 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
50 for (i = 1; i < REFS_PER_FRAME; ++i)
51 if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1])
57 static void setup_compound_reference_mode(VP9_COMMON *cm) {
58 if (cm->ref_frame_sign_bias[LAST_FRAME] ==
59 cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
60 cm->comp_fixed_ref = ALTREF_FRAME;
61 cm->comp_var_ref[0] = LAST_FRAME;
62 cm->comp_var_ref[1] = GOLDEN_FRAME;
63 } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
64 cm->ref_frame_sign_bias[ALTREF_FRAME]) {
65 cm->comp_fixed_ref = GOLDEN_FRAME;
66 cm->comp_var_ref[0] = LAST_FRAME;
67 cm->comp_var_ref[1] = ALTREF_FRAME;
69 cm->comp_fixed_ref = LAST_FRAME;
70 cm->comp_var_ref[0] = GOLDEN_FRAME;
71 cm->comp_var_ref[1] = ALTREF_FRAME;
75 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
76 return len != 0 && len <= (size_t)(end - start);
79 static int decode_unsigned_max(struct vpx_read_bit_buffer *rb, int max) {
80 const int data = vpx_rb_read_literal(rb, get_unsigned_bits(max));
81 return data > max ? max : data;
84 static TX_MODE read_tx_mode(vpx_reader *r) {
85 TX_MODE tx_mode = vpx_read_literal(r, 2);
86 if (tx_mode == ALLOW_32X32)
87 tx_mode += vpx_read_bit(r);
91 static void read_tx_mode_probs(struct tx_probs *tx_probs, vpx_reader *r) {
94 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
95 for (j = 0; j < TX_SIZES - 3; ++j)
96 vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
98 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
99 for (j = 0; j < TX_SIZES - 2; ++j)
100 vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
102 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
103 for (j = 0; j < TX_SIZES - 1; ++j)
104 vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
107 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
109 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
110 for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
111 vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
114 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
116 for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
117 for (j = 0; j < INTER_MODES - 1; ++j)
118 vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
121 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
123 if (is_compound_reference_allowed(cm)) {
124 return vpx_read_bit(r) ? (vpx_read_bit(r) ? REFERENCE_MODE_SELECT
125 : COMPOUND_REFERENCE)
128 return SINGLE_REFERENCE;
132 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vpx_reader *r) {
133 FRAME_CONTEXT *const fc = cm->fc;
136 if (cm->reference_mode == REFERENCE_MODE_SELECT)
137 for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
138 vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
140 if (cm->reference_mode != COMPOUND_REFERENCE)
141 for (i = 0; i < REF_CONTEXTS; ++i) {
142 vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
143 vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
146 if (cm->reference_mode != SINGLE_REFERENCE)
147 for (i = 0; i < REF_CONTEXTS; ++i)
148 vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
151 static void update_mv_probs(vpx_prob *p, int n, vpx_reader *r) {
153 for (i = 0; i < n; ++i)
154 if (vpx_read(r, MV_UPDATE_PROB))
155 p[i] = (vpx_read_literal(r, 7) << 1) | 1;
158 static void read_mv_probs(nmv_context *ctx, int allow_hp, vpx_reader *r) {
161 update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
163 for (i = 0; i < 2; ++i) {
164 nmv_component *const comp_ctx = &ctx->comps[i];
165 update_mv_probs(&comp_ctx->sign, 1, r);
166 update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
167 update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
168 update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
171 for (i = 0; i < 2; ++i) {
172 nmv_component *const comp_ctx = &ctx->comps[i];
173 for (j = 0; j < CLASS0_SIZE; ++j)
174 update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
175 update_mv_probs(comp_ctx->fp, 3, r);
179 for (i = 0; i < 2; ++i) {
180 nmv_component *const comp_ctx = &ctx->comps[i];
181 update_mv_probs(&comp_ctx->class0_hp, 1, r);
182 update_mv_probs(&comp_ctx->hp, 1, r);
187 static void inverse_transform_block_inter(MACROBLOCKD* xd, int plane,
188 const TX_SIZE tx_size,
189 uint8_t *dst, int stride,
191 struct macroblockd_plane *const pd = &xd->plane[plane];
193 tran_low_t *const dqcoeff = pd->dqcoeff;
194 #if CONFIG_VP9_HIGHBITDEPTH
195 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
197 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
201 vp9_highbd_idct4x4_add(dqcoeff, dst, stride, eob, xd->bd);
204 vp9_highbd_idct8x8_add(dqcoeff, dst, stride, eob, xd->bd);
207 vp9_highbd_idct16x16_add(dqcoeff, dst, stride, eob, xd->bd);
210 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
213 assert(0 && "Invalid transform size");
218 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
222 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
225 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
228 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
231 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
234 assert(0 && "Invalid transform size");
241 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
245 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
248 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
251 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
254 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
257 assert(0 && "Invalid transform size");
261 #endif // CONFIG_VP9_HIGHBITDEPTH
266 if (tx_size <= TX_16X16 && eob <= 10)
267 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
268 else if (tx_size == TX_32X32 && eob <= 34)
269 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
271 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
276 static void inverse_transform_block_intra(MACROBLOCKD* xd, int plane,
277 const TX_TYPE tx_type,
278 const TX_SIZE tx_size,
279 uint8_t *dst, int stride,
281 struct macroblockd_plane *const pd = &xd->plane[plane];
283 tran_low_t *const dqcoeff = pd->dqcoeff;
284 #if CONFIG_VP9_HIGHBITDEPTH
285 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
287 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
291 vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
294 vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
297 vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
300 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
303 assert(0 && "Invalid transform size");
308 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
312 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
315 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
318 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
321 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
324 assert(0 && "Invalid transform size");
331 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
335 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
338 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
341 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
344 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
347 assert(0 && "Invalid transform size");
351 #endif // CONFIG_VP9_HIGHBITDEPTH
356 if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
357 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
358 else if (tx_size == TX_32X32 && eob <= 34)
359 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
361 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
366 static void predict_and_reconstruct_intra_block(MACROBLOCKD *const xd,
368 MB_MODE_INFO *const mbmi,
372 struct macroblockd_plane *const pd = &xd->plane[plane];
373 PREDICTION_MODE mode = (plane == 0) ? mbmi->mode : mbmi->uv_mode;
375 dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
377 if (mbmi->sb_type < BLOCK_8X8)
379 mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
381 vp9_predict_intra_block(xd, pd->n4_wl, tx_size, mode,
382 dst, pd->dst.stride, dst, pd->dst.stride,
386 const TX_TYPE tx_type = (plane || xd->lossless) ?
387 DCT_DCT : intra_mode_to_tx_type_lookup[mode];
388 const scan_order *sc = (plane || xd->lossless) ?
389 &vp9_default_scan_orders[tx_size] : &vp9_scan_orders[tx_size][tx_type];
390 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size,
391 r, mbmi->segment_id);
392 inverse_transform_block_intra(xd, plane, tx_type, tx_size,
393 dst, pd->dst.stride, eob);
397 static int reconstruct_inter_block(MACROBLOCKD *const xd, vpx_reader *r,
398 MB_MODE_INFO *const mbmi, int plane,
399 int row, int col, TX_SIZE tx_size) {
400 struct macroblockd_plane *const pd = &xd->plane[plane];
401 const scan_order *sc = &vp9_default_scan_orders[tx_size];
402 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size, r,
405 inverse_transform_block_inter(xd, plane, tx_size,
406 &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
407 pd->dst.stride, eob);
411 static void build_mc_border(const uint8_t *src, int src_stride,
412 uint8_t *dst, int dst_stride,
413 int x, int y, int b_w, int b_h, int w, int h) {
414 // Get a pointer to the start of the real data for this row.
415 const uint8_t *ref_row = src - x - y * src_stride;
418 ref_row += (h - 1) * src_stride;
420 ref_row += y * src_stride;
424 int left = x < 0 ? -x : 0;
435 copy = b_w - left - right;
438 memset(dst, ref_row[0], left);
441 memcpy(dst + left, ref_row + x + left, copy);
444 memset(dst + left + copy, ref_row[w - 1], right);
450 ref_row += src_stride;
454 #if CONFIG_VP9_HIGHBITDEPTH
455 static void high_build_mc_border(const uint8_t *src8, int src_stride,
456 uint16_t *dst, int dst_stride,
457 int x, int y, int b_w, int b_h,
459 // Get a pointer to the start of the real data for this row.
460 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
461 const uint16_t *ref_row = src - x - y * src_stride;
464 ref_row += (h - 1) * src_stride;
466 ref_row += y * src_stride;
470 int left = x < 0 ? -x : 0;
481 copy = b_w - left - right;
484 vpx_memset16(dst, ref_row[0], left);
487 memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
490 vpx_memset16(dst + left + copy, ref_row[w - 1], right);
496 ref_row += src_stride;
499 #endif // CONFIG_VP9_HIGHBITDEPTH
501 #if CONFIG_VP9_HIGHBITDEPTH
502 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
503 int x0, int y0, int b_w, int b_h,
504 int frame_width, int frame_height,
506 uint8_t *const dst, int dst_buf_stride,
507 int subpel_x, int subpel_y,
508 const InterpKernel *kernel,
509 const struct scale_factors *sf,
511 int w, int h, int ref, int xs, int ys) {
512 DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
513 const uint8_t *buf_ptr;
515 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
516 high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w,
517 x0, y0, b_w, b_h, frame_width, frame_height);
518 buf_ptr = CONVERT_TO_BYTEPTR(mc_buf_high) + border_offset;
520 build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w,
521 x0, y0, b_w, b_h, frame_width, frame_height);
522 buf_ptr = ((uint8_t *)mc_buf_high) + border_offset;
525 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
526 high_inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
527 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
529 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
530 subpel_y, sf, w, h, ref, kernel, xs, ys);
534 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
535 int x0, int y0, int b_w, int b_h,
536 int frame_width, int frame_height,
538 uint8_t *const dst, int dst_buf_stride,
539 int subpel_x, int subpel_y,
540 const InterpKernel *kernel,
541 const struct scale_factors *sf,
542 int w, int h, int ref, int xs, int ys) {
543 DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
544 const uint8_t *buf_ptr;
546 build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w,
547 x0, y0, b_w, b_h, frame_width, frame_height);
548 buf_ptr = mc_buf + border_offset;
550 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
551 subpel_y, sf, w, h, ref, kernel, xs, ys);
553 #endif // CONFIG_VP9_HIGHBITDEPTH
555 static void dec_build_inter_predictors(VP9Decoder *const pbi, MACROBLOCKD *xd,
556 int plane, int bw, int bh, int x,
557 int y, int w, int h, int mi_x, int mi_y,
558 const InterpKernel *kernel,
559 const struct scale_factors *sf,
560 struct buf_2d *pre_buf,
561 struct buf_2d *dst_buf, const MV* mv,
562 RefCntBuffer *ref_frame_buf,
563 int is_scaled, int ref) {
564 struct macroblockd_plane *const pd = &xd->plane[plane];
565 uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
567 int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height,
568 buf_stride, subpel_x, subpel_y;
569 uint8_t *ref_frame, *buf_ptr;
571 // Get reference frame pointer, width and height.
573 frame_width = ref_frame_buf->buf.y_crop_width;
574 frame_height = ref_frame_buf->buf.y_crop_height;
575 ref_frame = ref_frame_buf->buf.y_buffer;
577 frame_width = ref_frame_buf->buf.uv_crop_width;
578 frame_height = ref_frame_buf->buf.uv_crop_height;
579 ref_frame = plane == 1 ? ref_frame_buf->buf.u_buffer
580 : ref_frame_buf->buf.v_buffer;
584 const MV mv_q4 = clamp_mv_to_umv_border_sb(xd, mv, bw, bh,
587 // Co-ordinate of containing block to pixel precision.
588 int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
589 int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
590 #if CONFIG_BETTER_HW_COMPATIBILITY
591 assert(xd->mi[0]->mbmi.sb_type != BLOCK_4X8 &&
592 xd->mi[0]->mbmi.sb_type != BLOCK_8X4);
593 assert(mv_q4.row == mv->row * (1 << (1 - pd->subsampling_y)) &&
594 mv_q4.col == mv->col * (1 << (1 - pd->subsampling_x)));
596 // Co-ordinate of the block to 1/16th pixel precision.
597 x0_16 = (x_start + x) << SUBPEL_BITS;
598 y0_16 = (y_start + y) << SUBPEL_BITS;
600 // Co-ordinate of current block in reference frame
601 // to 1/16th pixel precision.
602 x0_16 = sf->scale_value_x(x0_16, sf);
603 y0_16 = sf->scale_value_y(y0_16, sf);
605 // Map the top left corner of the block into the reference frame.
606 x0 = sf->scale_value_x(x_start + x, sf);
607 y0 = sf->scale_value_y(y_start + y, sf);
609 // Scale the MV and incorporate the sub-pixel offset of the block
610 // in the reference frame.
611 scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
615 // Co-ordinate of containing block to pixel precision.
616 x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
617 y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
619 // Co-ordinate of the block to 1/16th pixel precision.
620 x0_16 = x0 << SUBPEL_BITS;
621 y0_16 = y0 << SUBPEL_BITS;
623 scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
624 scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
627 subpel_x = scaled_mv.col & SUBPEL_MASK;
628 subpel_y = scaled_mv.row & SUBPEL_MASK;
630 // Calculate the top left corner of the best matching block in the
632 x0 += scaled_mv.col >> SUBPEL_BITS;
633 y0 += scaled_mv.row >> SUBPEL_BITS;
634 x0_16 += scaled_mv.col;
635 y0_16 += scaled_mv.row;
637 // Get reference block pointer.
638 buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
639 buf_stride = pre_buf->stride;
641 // Do border extension if there is motion or the
642 // width/height is not a multiple of 8 pixels.
643 if (is_scaled || scaled_mv.col || scaled_mv.row ||
644 (frame_width & 0x7) || (frame_height & 0x7)) {
645 int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
647 // Get reference block bottom right horizontal coordinate.
648 int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
649 int x_pad = 0, y_pad = 0;
651 if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
652 x0 -= VP9_INTERP_EXTEND - 1;
653 x1 += VP9_INTERP_EXTEND;
657 if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
658 y0 -= VP9_INTERP_EXTEND - 1;
659 y1 += VP9_INTERP_EXTEND;
663 // Wait until reference block is ready. Pad 7 more pixels as last 7
664 // pixels of each superblock row can be changed by next superblock row.
665 if (pbi->frame_parallel_decode)
666 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
667 VPXMAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
669 // Skip border extension if block is inside the frame.
670 if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
671 y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
672 // Extend the border.
673 const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
674 const int b_w = x1 - x0 + 1;
675 const int b_h = y1 - y0 + 1;
676 const int border_offset = y_pad * 3 * b_w + x_pad * 3;
678 extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h,
679 frame_width, frame_height, border_offset,
680 dst, dst_buf->stride,
683 #if CONFIG_VP9_HIGHBITDEPTH
690 // Wait until reference block is ready. Pad 7 more pixels as last 7
691 // pixels of each superblock row can be changed by next superblock row.
692 if (pbi->frame_parallel_decode) {
693 const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
694 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
695 VPXMAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
698 #if CONFIG_VP9_HIGHBITDEPTH
699 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
700 high_inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
701 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
703 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
704 subpel_y, sf, w, h, ref, kernel, xs, ys);
707 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
708 subpel_y, sf, w, h, ref, kernel, xs, ys);
709 #endif // CONFIG_VP9_HIGHBITDEPTH
712 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
714 int mi_row, int mi_col) {
716 const int mi_x = mi_col * MI_SIZE;
717 const int mi_y = mi_row * MI_SIZE;
718 const MODE_INFO *mi = xd->mi[0];
719 const InterpKernel *kernel = vp9_filter_kernels[mi->mbmi.interp_filter];
720 const BLOCK_SIZE sb_type = mi->mbmi.sb_type;
721 const int is_compound = has_second_ref(&mi->mbmi);
723 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
724 struct macroblockd_plane *const pd = &xd->plane[plane];
725 struct buf_2d *const dst_buf = &pd->dst;
726 const int num_4x4_w = pd->n4_w;
727 const int num_4x4_h = pd->n4_h;
729 const int n4w_x4 = 4 * num_4x4_w;
730 const int n4h_x4 = 4 * num_4x4_h;
733 for (ref = 0; ref < 1 + is_compound; ++ref) {
734 const struct scale_factors *const sf = &xd->block_refs[ref]->sf;
735 struct buf_2d *const pre_buf = &pd->pre[ref];
736 const int idx = xd->block_refs[ref]->idx;
737 BufferPool *const pool = pbi->common.buffer_pool;
738 RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
739 const int is_scaled = vp9_is_scaled(sf);
741 if (sb_type < BLOCK_8X8) {
743 for (y = 0; y < num_4x4_h; ++y) {
744 for (x = 0; x < num_4x4_w; ++x) {
745 const MV mv = average_split_mvs(pd, mi, ref, i++);
746 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
747 4 * x, 4 * y, 4, 4, mi_x, mi_y, kernel,
748 sf, pre_buf, dst_buf, &mv,
749 ref_frame_buf, is_scaled, ref);
753 const MV mv = mi->mbmi.mv[ref].as_mv;
754 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
755 0, 0, n4w_x4, n4h_x4, mi_x, mi_y, kernel,
756 sf, pre_buf, dst_buf, &mv, ref_frame_buf,
763 static INLINE TX_SIZE dec_get_uv_tx_size(const MB_MODE_INFO *mbmi,
764 int n4_wl, int n4_hl) {
765 // get minimum log2 num4x4s dimension
766 const int x = VPXMIN(n4_wl, n4_hl);
767 return VPXMIN(mbmi->tx_size, x);
770 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
772 for (i = 0; i < MAX_MB_PLANE; i++) {
773 struct macroblockd_plane *const pd = &xd->plane[i];
774 memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
775 memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
779 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
782 for (i = 0; i < MAX_MB_PLANE; i++) {
783 xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
784 xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
785 xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
786 xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
790 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
791 BLOCK_SIZE bsize, int mi_row, int mi_col,
792 int bw, int bh, int x_mis, int y_mis,
794 const int offset = mi_row * cm->mi_stride + mi_col;
796 const TileInfo *const tile = &xd->tile;
798 xd->mi = cm->mi_grid_visible + offset;
799 xd->mi[0] = &cm->mi[offset];
800 // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
801 // passing bsize from decode_partition().
802 xd->mi[0]->mbmi.sb_type = bsize;
803 for (y = 0; y < y_mis; ++y)
804 for (x = !y; x < x_mis; ++x) {
805 xd->mi[y * cm->mi_stride + x] = xd->mi[0];
808 set_plane_n4(xd, bw, bh, bwl, bhl);
810 set_skip_context(xd, mi_row, mi_col);
812 // Distance of Mb to the various image edges. These are specified to 8th pel
813 // as they are always compared to values that are in 1/8th pel units
814 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
816 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
817 return &xd->mi[0]->mbmi;
820 static void decode_block(VP9Decoder *const pbi, MACROBLOCKD *const xd,
821 int mi_row, int mi_col,
822 vpx_reader *r, BLOCK_SIZE bsize,
824 VP9_COMMON *const cm = &pbi->common;
825 const int less8x8 = bsize < BLOCK_8X8;
826 const int bw = 1 << (bwl - 1);
827 const int bh = 1 << (bhl - 1);
828 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
829 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
831 MB_MODE_INFO *mbmi = set_offsets(cm, xd, bsize, mi_row, mi_col,
832 bw, bh, x_mis, y_mis, bwl, bhl);
834 if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
835 const BLOCK_SIZE uv_subsize =
836 ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
837 if (uv_subsize == BLOCK_INVALID)
838 vpx_internal_error(xd->error_info,
839 VPX_CODEC_CORRUPT_FRAME, "Invalid block size.");
842 vpx_read_mode_info(pbi, xd, mi_row, mi_col, r, x_mis, y_mis);
845 dec_reset_skip_context(xd);
848 if (!is_inter_block(mbmi)) {
850 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
851 const struct macroblockd_plane *const pd = &xd->plane[plane];
852 const TX_SIZE tx_size =
853 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
855 const int num_4x4_w = pd->n4_w;
856 const int num_4x4_h = pd->n4_h;
857 const int step = (1 << tx_size);
859 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
860 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
861 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
862 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
864 for (row = 0; row < max_blocks_high; row += step)
865 for (col = 0; col < max_blocks_wide; col += step)
866 predict_and_reconstruct_intra_block(xd, r, mbmi, plane,
871 dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col);
878 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
879 const struct macroblockd_plane *const pd = &xd->plane[plane];
880 const TX_SIZE tx_size =
881 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
883 const int num_4x4_w = pd->n4_w;
884 const int num_4x4_h = pd->n4_h;
885 const int step = (1 << tx_size);
887 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
888 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
889 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
890 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
892 for (row = 0; row < max_blocks_high; row += step)
893 for (col = 0; col < max_blocks_wide; col += step)
894 eobtotal += reconstruct_inter_block(xd, r, mbmi, plane, row, col,
898 if (!less8x8 && eobtotal == 0)
899 mbmi->skip = 1; // skip loopfilter
903 xd->corrupted |= vpx_reader_has_error(r);
905 if (cm->lf.filter_level) {
906 vp9_build_mask(cm, mbmi, mi_row, mi_col, bw, bh);
910 static INLINE int dec_partition_plane_context(const MACROBLOCKD *xd,
911 int mi_row, int mi_col,
913 const PARTITION_CONTEXT *above_ctx = xd->above_seg_context + mi_col;
914 const PARTITION_CONTEXT *left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
915 int above = (*above_ctx >> bsl) & 1 , left = (*left_ctx >> bsl) & 1;
919 return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
922 static INLINE void dec_update_partition_context(MACROBLOCKD *xd,
923 int mi_row, int mi_col,
926 PARTITION_CONTEXT *const above_ctx = xd->above_seg_context + mi_col;
927 PARTITION_CONTEXT *const left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
929 // update the partition context at the end notes. set partition bits
930 // of block sizes larger than the current one to be one, and partition
931 // bits of smaller block sizes to be zero.
932 memset(above_ctx, partition_context_lookup[subsize].above, bw);
933 memset(left_ctx, partition_context_lookup[subsize].left, bw);
936 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
938 int has_rows, int has_cols, int bsl) {
939 const int ctx = dec_partition_plane_context(xd, mi_row, mi_col, bsl);
940 const vpx_prob *const probs = get_partition_probs(xd, ctx);
941 FRAME_COUNTS *counts = xd->counts;
944 if (has_rows && has_cols)
945 p = (PARTITION_TYPE)vpx_read_tree(r, vp9_partition_tree, probs);
946 else if (!has_rows && has_cols)
947 p = vpx_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
948 else if (has_rows && !has_cols)
949 p = vpx_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
954 ++counts->partition[ctx][p];
959 // TODO(slavarnway): eliminate bsize and subsize in future commits
960 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
961 int mi_row, int mi_col,
962 vpx_reader* r, BLOCK_SIZE bsize, int n4x4_l2) {
963 VP9_COMMON *const cm = &pbi->common;
964 const int n8x8_l2 = n4x4_l2 - 1;
965 const int num_8x8_wh = 1 << n8x8_l2;
966 const int hbs = num_8x8_wh >> 1;
967 PARTITION_TYPE partition;
969 const int has_rows = (mi_row + hbs) < cm->mi_rows;
970 const int has_cols = (mi_col + hbs) < cm->mi_cols;
972 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
975 partition = read_partition(xd, mi_row, mi_col, r, has_rows, has_cols,
977 subsize = subsize_lookup[partition][bsize]; // get_subsize(bsize, partition);
979 // calculate bmode block dimensions (log 2)
980 xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
981 xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
982 decode_block(pbi, xd, mi_row, mi_col, r, subsize, 1, 1);
986 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n4x4_l2);
989 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n8x8_l2);
991 decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize, n4x4_l2,
995 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2, n4x4_l2);
997 decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2,
1000 case PARTITION_SPLIT:
1001 decode_partition(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2);
1002 decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2);
1003 decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize, n8x8_l2);
1004 decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize,
1008 assert(0 && "Invalid partition type");
1012 // update partition context
1013 if (bsize >= BLOCK_8X8 &&
1014 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
1015 dec_update_partition_context(xd, mi_row, mi_col, subsize, num_8x8_wh);
1018 static void setup_token_decoder(const uint8_t *data,
1019 const uint8_t *data_end,
1021 struct vpx_internal_error_info *error_info,
1023 vpx_decrypt_cb decrypt_cb,
1024 void *decrypt_state) {
1025 // Validate the calculated partition length. If the buffer
1026 // described by the partition can't be fully read, then restrict
1027 // it to the portion that can be (for EC mode) or throw an error.
1028 if (!read_is_valid(data, read_size, data_end))
1029 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1030 "Truncated packet or corrupt tile length");
1032 if (vpx_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
1033 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
1034 "Failed to allocate bool decoder %d", 1);
1037 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
1041 if (vpx_read_bit(r))
1042 for (i = 0; i < PLANE_TYPES; ++i)
1043 for (j = 0; j < REF_TYPES; ++j)
1044 for (k = 0; k < COEF_BANDS; ++k)
1045 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1046 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
1047 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
1050 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
1052 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1054 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1055 read_coef_probs_common(fc->coef_probs[tx_size], r);
1058 static void setup_segmentation(struct segmentation *seg,
1059 struct vpx_read_bit_buffer *rb) {
1062 seg->update_map = 0;
1063 seg->update_data = 0;
1065 seg->enabled = vpx_rb_read_bit(rb);
1069 // Segmentation map update
1070 seg->update_map = vpx_rb_read_bit(rb);
1071 if (seg->update_map) {
1072 for (i = 0; i < SEG_TREE_PROBS; i++)
1073 seg->tree_probs[i] = vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8)
1076 seg->temporal_update = vpx_rb_read_bit(rb);
1077 if (seg->temporal_update) {
1078 for (i = 0; i < PREDICTION_PROBS; i++)
1079 seg->pred_probs[i] = vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8)
1082 for (i = 0; i < PREDICTION_PROBS; i++)
1083 seg->pred_probs[i] = MAX_PROB;
1087 // Segmentation data update
1088 seg->update_data = vpx_rb_read_bit(rb);
1089 if (seg->update_data) {
1090 seg->abs_delta = vpx_rb_read_bit(rb);
1092 vp9_clearall_segfeatures(seg);
1094 for (i = 0; i < MAX_SEGMENTS; i++) {
1095 for (j = 0; j < SEG_LVL_MAX; j++) {
1097 const int feature_enabled = vpx_rb_read_bit(rb);
1098 if (feature_enabled) {
1099 vp9_enable_segfeature(seg, i, j);
1100 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1101 if (vp9_is_segfeature_signed(j))
1102 data = vpx_rb_read_bit(rb) ? -data : data;
1104 vp9_set_segdata(seg, i, j, data);
1110 static void setup_loopfilter(struct loopfilter *lf,
1111 struct vpx_read_bit_buffer *rb) {
1112 lf->filter_level = vpx_rb_read_literal(rb, 6);
1113 lf->sharpness_level = vpx_rb_read_literal(rb, 3);
1115 // Read in loop filter deltas applied at the MB level based on mode or ref
1117 lf->mode_ref_delta_update = 0;
1119 lf->mode_ref_delta_enabled = vpx_rb_read_bit(rb);
1120 if (lf->mode_ref_delta_enabled) {
1121 lf->mode_ref_delta_update = vpx_rb_read_bit(rb);
1122 if (lf->mode_ref_delta_update) {
1125 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1126 if (vpx_rb_read_bit(rb))
1127 lf->ref_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1129 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1130 if (vpx_rb_read_bit(rb))
1131 lf->mode_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1136 static INLINE int read_delta_q(struct vpx_read_bit_buffer *rb) {
1137 return vpx_rb_read_bit(rb) ? vpx_rb_read_signed_literal(rb, 4) : 0;
1140 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1141 struct vpx_read_bit_buffer *rb) {
1142 cm->base_qindex = vpx_rb_read_literal(rb, QINDEX_BITS);
1143 cm->y_dc_delta_q = read_delta_q(rb);
1144 cm->uv_dc_delta_q = read_delta_q(rb);
1145 cm->uv_ac_delta_q = read_delta_q(rb);
1146 cm->dequant_bit_depth = cm->bit_depth;
1147 xd->lossless = cm->base_qindex == 0 &&
1148 cm->y_dc_delta_q == 0 &&
1149 cm->uv_dc_delta_q == 0 &&
1150 cm->uv_ac_delta_q == 0;
1152 #if CONFIG_VP9_HIGHBITDEPTH
1153 xd->bd = (int)cm->bit_depth;
1157 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1158 // Build y/uv dequant values based on segmentation.
1159 if (cm->seg.enabled) {
1161 for (i = 0; i < MAX_SEGMENTS; ++i) {
1162 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1163 cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
1165 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1166 cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1168 cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1172 const int qindex = cm->base_qindex;
1173 // When segmentation is disabled, only the first value is used. The
1174 // remaining are don't cares.
1175 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1176 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1177 cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1179 cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1184 static INTERP_FILTER read_interp_filter(struct vpx_read_bit_buffer *rb) {
1185 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1189 return vpx_rb_read_bit(rb) ? SWITCHABLE
1190 : literal_to_filter[vpx_rb_read_literal(rb, 2)];
1193 static void setup_render_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1194 cm->render_width = cm->width;
1195 cm->render_height = cm->height;
1196 if (vpx_rb_read_bit(rb))
1197 vp9_read_frame_size(rb, &cm->render_width, &cm->render_height);
1200 static void resize_mv_buffer(VP9_COMMON *cm) {
1201 vpx_free(cm->cur_frame->mvs);
1202 cm->cur_frame->mi_rows = cm->mi_rows;
1203 cm->cur_frame->mi_cols = cm->mi_cols;
1204 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1205 sizeof(*cm->cur_frame->mvs));
1208 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1209 #if CONFIG_SIZE_LIMIT
1210 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1211 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1212 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1213 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1215 if (cm->width != width || cm->height != height) {
1216 const int new_mi_rows =
1217 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1218 const int new_mi_cols =
1219 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1221 // Allocations in vp9_alloc_context_buffers() depend on individual
1222 // dimensions as well as the overall size.
1223 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1224 if (vp9_alloc_context_buffers(cm, width, height))
1225 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1226 "Failed to allocate context buffers");
1228 vp9_set_mb_mi(cm, width, height);
1230 vp9_init_context_buffers(cm);
1232 cm->height = height;
1234 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1235 cm->mi_cols > cm->cur_frame->mi_cols) {
1236 resize_mv_buffer(cm);
1240 static void setup_frame_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1242 BufferPool *const pool = cm->buffer_pool;
1243 vp9_read_frame_size(rb, &width, &height);
1244 resize_context_buffers(cm, width, height);
1245 setup_render_size(cm, rb);
1247 lock_buffer_pool(pool);
1248 if (vpx_realloc_frame_buffer(
1249 get_frame_new_buffer(cm), cm->width, cm->height,
1250 cm->subsampling_x, cm->subsampling_y,
1251 #if CONFIG_VP9_HIGHBITDEPTH
1252 cm->use_highbitdepth,
1254 VP9_DEC_BORDER_IN_PIXELS,
1256 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1258 unlock_buffer_pool(pool);
1259 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1260 "Failed to allocate frame buffer");
1262 unlock_buffer_pool(pool);
1264 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1265 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1266 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1267 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1268 pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1269 pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1270 pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1273 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1274 int ref_xss, int ref_yss,
1275 vpx_bit_depth_t this_bit_depth,
1276 int this_xss, int this_yss) {
1277 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1278 ref_yss == this_yss;
1281 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1282 struct vpx_read_bit_buffer *rb) {
1285 int has_valid_ref_frame = 0;
1286 BufferPool *const pool = cm->buffer_pool;
1287 for (i = 0; i < REFS_PER_FRAME; ++i) {
1288 if (vpx_rb_read_bit(rb)) {
1289 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1290 width = buf->y_crop_width;
1291 height = buf->y_crop_height;
1298 vp9_read_frame_size(rb, &width, &height);
1300 if (width <= 0 || height <= 0)
1301 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1302 "Invalid frame size");
1304 // Check to make sure at least one of frames that this frame references
1305 // has valid dimensions.
1306 for (i = 0; i < REFS_PER_FRAME; ++i) {
1307 RefBuffer *const ref_frame = &cm->frame_refs[i];
1308 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1309 ref_frame->buf->y_crop_height,
1312 if (!has_valid_ref_frame)
1313 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1314 "Referenced frame has invalid size");
1315 for (i = 0; i < REFS_PER_FRAME; ++i) {
1316 RefBuffer *const ref_frame = &cm->frame_refs[i];
1317 if (!valid_ref_frame_img_fmt(
1318 ref_frame->buf->bit_depth,
1319 ref_frame->buf->subsampling_x,
1320 ref_frame->buf->subsampling_y,
1324 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1325 "Referenced frame has incompatible color format");
1328 resize_context_buffers(cm, width, height);
1329 setup_render_size(cm, rb);
1331 lock_buffer_pool(pool);
1332 if (vpx_realloc_frame_buffer(
1333 get_frame_new_buffer(cm), cm->width, cm->height,
1334 cm->subsampling_x, cm->subsampling_y,
1335 #if CONFIG_VP9_HIGHBITDEPTH
1336 cm->use_highbitdepth,
1338 VP9_DEC_BORDER_IN_PIXELS,
1340 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1342 unlock_buffer_pool(pool);
1343 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1344 "Failed to allocate frame buffer");
1346 unlock_buffer_pool(pool);
1348 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1349 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1350 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1351 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1352 pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1353 pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1354 pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1357 static void setup_tile_info(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1358 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1359 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1362 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1363 cm->log2_tile_cols = min_log2_tile_cols;
1364 while (max_ones-- && vpx_rb_read_bit(rb))
1365 cm->log2_tile_cols++;
1367 if (cm->log2_tile_cols > 6)
1368 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1369 "Invalid number of tile columns");
1372 cm->log2_tile_rows = vpx_rb_read_bit(rb);
1373 if (cm->log2_tile_rows)
1374 cm->log2_tile_rows += vpx_rb_read_bit(rb);
1377 // Reads the next tile returning its size and adjusting '*data' accordingly
1378 // based on 'is_last'.
1379 static void get_tile_buffer(const uint8_t *const data_end,
1381 struct vpx_internal_error_info *error_info,
1382 const uint8_t **data,
1383 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1388 if (!read_is_valid(*data, 4, data_end))
1389 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1390 "Truncated packet or corrupt tile length");
1394 decrypt_cb(decrypt_state, *data, be_data, 4);
1395 size = mem_get_be32(be_data);
1397 size = mem_get_be32(*data);
1401 if (size > (size_t)(data_end - *data))
1402 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1403 "Truncated packet or corrupt tile size");
1405 size = data_end - *data;
1414 static void get_tile_buffers(VP9Decoder *pbi,
1415 const uint8_t *data, const uint8_t *data_end,
1416 int tile_cols, int tile_rows,
1417 TileBuffer (*tile_buffers)[1 << 6]) {
1420 for (r = 0; r < tile_rows; ++r) {
1421 for (c = 0; c < tile_cols; ++c) {
1422 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1423 TileBuffer *const buf = &tile_buffers[r][c];
1425 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1426 pbi->decrypt_cb, pbi->decrypt_state, buf);
1431 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1432 const uint8_t *data,
1433 const uint8_t *data_end) {
1434 VP9_COMMON *const cm = &pbi->common;
1435 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1436 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1437 const int tile_cols = 1 << cm->log2_tile_cols;
1438 const int tile_rows = 1 << cm->log2_tile_rows;
1439 TileBuffer tile_buffers[4][1 << 6];
1440 int tile_row, tile_col;
1442 TileData *tile_data = NULL;
1444 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1445 pbi->lf_worker.data1 == NULL) {
1446 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1447 vpx_memalign(32, sizeof(LFWorkerData)));
1448 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1449 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1450 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1451 "Loop filter thread creation failed");
1455 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1456 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1457 // Be sure to sync as we might be resuming after a failed frame decode.
1458 winterface->sync(&pbi->lf_worker);
1459 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1463 assert(tile_rows <= 4);
1464 assert(tile_cols <= (1 << 6));
1466 // Note: this memset assumes above_context[0], [1] and [2]
1467 // are allocated as part of the same buffer.
1468 memset(cm->above_context, 0,
1469 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1471 memset(cm->above_seg_context, 0,
1472 sizeof(*cm->above_seg_context) * aligned_cols);
1476 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1478 if (pbi->tile_data == NULL ||
1479 (tile_cols * tile_rows) != pbi->total_tiles) {
1480 vpx_free(pbi->tile_data);
1484 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1485 pbi->total_tiles = tile_rows * tile_cols;
1488 // Load all tile information into tile_data.
1489 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1490 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1491 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1492 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1494 tile_data->xd = pbi->mb;
1495 tile_data->xd.corrupted = 0;
1496 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1498 vp9_zero(tile_data->dqcoeff);
1499 vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1500 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1501 &tile_data->bit_reader, pbi->decrypt_cb,
1502 pbi->decrypt_state);
1503 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1507 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1509 vp9_tile_set_row(&tile, cm, tile_row);
1510 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1511 mi_row += MI_BLOCK_SIZE) {
1512 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1513 const int col = pbi->inv_tile_order ?
1514 tile_cols - tile_col - 1 : tile_col;
1515 tile_data = pbi->tile_data + tile_cols * tile_row + col;
1516 vp9_tile_set_col(&tile, tile_data->cm, col);
1517 vp9_zero(tile_data->xd.left_context);
1518 vp9_zero(tile_data->xd.left_seg_context);
1519 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1520 mi_col += MI_BLOCK_SIZE) {
1521 decode_partition(pbi, &tile_data->xd, mi_row,
1522 mi_col, &tile_data->bit_reader, BLOCK_64X64, 4);
1524 pbi->mb.corrupted |= tile_data->xd.corrupted;
1525 if (pbi->mb.corrupted)
1526 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1527 "Failed to decode tile data");
1529 // Loopfilter one row.
1530 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1531 const int lf_start = mi_row - MI_BLOCK_SIZE;
1532 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1534 // delay the loopfilter by 1 macroblock row.
1535 if (lf_start < 0) continue;
1537 // decoding has completed: finish up the loop filter in this thread.
1538 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1540 winterface->sync(&pbi->lf_worker);
1541 lf_data->start = lf_start;
1542 lf_data->stop = mi_row;
1543 if (pbi->max_threads > 1) {
1544 winterface->launch(&pbi->lf_worker);
1546 winterface->execute(&pbi->lf_worker);
1549 // After loopfiltering, the last 7 row pixels in each superblock row may
1550 // still be changed by the longest loopfilter of the next superblock
1552 if (pbi->frame_parallel_decode)
1553 vp9_frameworker_broadcast(pbi->cur_buf,
1554 mi_row << MI_BLOCK_SIZE_LOG2);
1558 // Loopfilter remaining rows in the frame.
1559 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1560 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1561 winterface->sync(&pbi->lf_worker);
1562 lf_data->start = lf_data->stop;
1563 lf_data->stop = cm->mi_rows;
1564 winterface->execute(&pbi->lf_worker);
1567 // Get last tile data.
1568 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1570 if (pbi->frame_parallel_decode)
1571 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1572 return vpx_reader_find_end(&tile_data->bit_reader);
1575 // On entry 'tile_data->data_end' points to the end of the input frame, on exit
1576 // it is updated to reflect the bitreader position of the final tile column if
1577 // present in the tile buffer group or NULL otherwise.
1578 static int tile_worker_hook(TileWorkerData *const tile_data,
1579 VP9Decoder *const pbi) {
1580 TileInfo *volatile tile = &tile_data->xd.tile;
1581 const int final_col = (1 << pbi->common.log2_tile_cols) - 1;
1582 const uint8_t *volatile bit_reader_end = NULL;
1583 volatile int n = tile_data->buf_start;
1584 tile_data->error_info.setjmp = 1;
1586 if (setjmp(tile_data->error_info.jmp)) {
1587 tile_data->error_info.setjmp = 0;
1588 tile_data->xd.corrupted = 1;
1589 tile_data->data_end = NULL;
1593 tile_data->xd.error_info = &tile_data->error_info;
1594 tile_data->xd.corrupted = 0;
1598 const TileBuffer *const buf = pbi->tile_buffers + n;
1599 vp9_zero(tile_data->dqcoeff);
1600 vp9_tile_init(tile, &pbi->common, 0, buf->col);
1601 setup_token_decoder(buf->data, tile_data->data_end, buf->size,
1602 &tile_data->error_info, &tile_data->bit_reader,
1603 pbi->decrypt_cb, pbi->decrypt_state);
1604 vp9_init_macroblockd(&pbi->common, &tile_data->xd, tile_data->dqcoeff);
1606 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1607 mi_row += MI_BLOCK_SIZE) {
1608 vp9_zero(tile_data->xd.left_context);
1609 vp9_zero(tile_data->xd.left_seg_context);
1610 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1611 mi_col += MI_BLOCK_SIZE) {
1612 decode_partition(pbi, &tile_data->xd, mi_row, mi_col,
1613 &tile_data->bit_reader, BLOCK_64X64, 4);
1617 if (buf->col == final_col) {
1618 bit_reader_end = vpx_reader_find_end(&tile_data->bit_reader);
1620 } while (!tile_data->xd.corrupted && ++n <= tile_data->buf_end);
1622 tile_data->data_end = bit_reader_end;
1623 return !tile_data->xd.corrupted;
1626 // sorts in descending order
1627 static int compare_tile_buffers(const void *a, const void *b) {
1628 const TileBuffer *const buf1 = (const TileBuffer*)a;
1629 const TileBuffer *const buf2 = (const TileBuffer*)b;
1630 return (int)(buf2->size - buf1->size);
1633 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1634 const uint8_t *data,
1635 const uint8_t *data_end) {
1636 VP9_COMMON *const cm = &pbi->common;
1637 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1638 const uint8_t *bit_reader_end = NULL;
1639 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1640 const int tile_cols = 1 << cm->log2_tile_cols;
1641 const int tile_rows = 1 << cm->log2_tile_rows;
1642 const int num_workers = VPXMIN(pbi->max_threads, tile_cols);
1645 assert(tile_cols <= (1 << 6));
1646 assert(tile_rows == 1);
1649 if (pbi->num_tile_workers == 0) {
1650 const int num_threads = pbi->max_threads;
1651 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1652 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1653 // Ensure tile data offsets will be properly aligned. This may fail on
1654 // platforms without DECLARE_ALIGNED().
1655 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1656 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1657 vpx_memalign(32, num_threads *
1658 sizeof(*pbi->tile_worker_data)));
1659 for (n = 0; n < num_threads; ++n) {
1660 VPxWorker *const worker = &pbi->tile_workers[n];
1661 ++pbi->num_tile_workers;
1663 winterface->init(worker);
1664 if (n < num_threads - 1 && !winterface->reset(worker)) {
1665 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1666 "Tile decoder thread creation failed");
1671 // Reset tile decoding hook
1672 for (n = 0; n < num_workers; ++n) {
1673 VPxWorker *const worker = &pbi->tile_workers[n];
1674 TileWorkerData *const tile_data = &pbi->tile_worker_data[n];
1675 winterface->sync(worker);
1676 tile_data->xd = pbi->mb;
1677 tile_data->xd.counts =
1678 cm->frame_parallel_decoding_mode ? NULL : &tile_data->counts;
1679 worker->hook = (VPxWorkerHook)tile_worker_hook;
1680 worker->data1 = tile_data;
1681 worker->data2 = pbi;
1684 // Note: this memset assumes above_context[0], [1] and [2]
1685 // are allocated as part of the same buffer.
1686 memset(cm->above_context, 0,
1687 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1688 memset(cm->above_seg_context, 0,
1689 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1693 // Load tile data into tile_buffers
1694 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows,
1695 &pbi->tile_buffers);
1697 // Sort the buffers based on size in descending order.
1698 qsort(pbi->tile_buffers, tile_cols, sizeof(pbi->tile_buffers[0]),
1699 compare_tile_buffers);
1701 if (num_workers == tile_cols) {
1702 // Rearrange the tile buffers such that the largest, and
1703 // presumably the most difficult, tile will be decoded in the main thread.
1704 // This should help minimize the number of instances where the main thread
1705 // is waiting for a worker to complete.
1706 const TileBuffer largest = pbi->tile_buffers[0];
1707 memmove(pbi->tile_buffers, pbi->tile_buffers + 1,
1708 (tile_cols - 1) * sizeof(pbi->tile_buffers[0]));
1709 pbi->tile_buffers[tile_cols - 1] = largest;
1711 int start = 0, end = tile_cols - 2;
1714 // Interleave the tiles to distribute the load between threads, assuming a
1715 // larger tile implies it is more difficult to decode.
1716 while (start < end) {
1717 tmp = pbi->tile_buffers[start];
1718 pbi->tile_buffers[start] = pbi->tile_buffers[end];
1719 pbi->tile_buffers[end] = tmp;
1725 // Initialize thread frame counts.
1726 if (!cm->frame_parallel_decoding_mode) {
1727 for (n = 0; n < num_workers; ++n) {
1728 TileWorkerData *const tile_data =
1729 (TileWorkerData*)pbi->tile_workers[n].data1;
1730 vp9_zero(tile_data->counts);
1735 const int base = tile_cols / num_workers;
1736 const int remain = tile_cols % num_workers;
1739 for (n = 0; n < num_workers; ++n) {
1740 const int count = base + (remain + n) / num_workers;
1741 VPxWorker *const worker = &pbi->tile_workers[n];
1742 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1744 tile_data->buf_start = buf_start;
1745 tile_data->buf_end = buf_start + count - 1;
1746 tile_data->data_end = data_end;
1749 worker->had_error = 0;
1750 if (n == num_workers - 1) {
1751 assert(tile_data->buf_end == tile_cols - 1);
1752 winterface->execute(worker);
1754 winterface->launch(worker);
1758 for (; n > 0; --n) {
1759 VPxWorker *const worker = &pbi->tile_workers[n - 1];
1760 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1761 // TODO(jzern): The tile may have specific error data associated with
1762 // its vpx_internal_error_info which could be propagated to the main info
1763 // in cm. Additionally once the threads have been synced and an error is
1764 // detected, there's no point in continuing to decode tiles.
1765 pbi->mb.corrupted |= !winterface->sync(worker);
1766 if (!bit_reader_end) bit_reader_end = tile_data->data_end;
1770 // Accumulate thread frame counts.
1771 if (!cm->frame_parallel_decoding_mode) {
1772 for (n = 0; n < num_workers; ++n) {
1773 TileWorkerData *const tile_data =
1774 (TileWorkerData*)pbi->tile_workers[n].data1;
1775 vp9_accumulate_frame_counts(&cm->counts, &tile_data->counts, 1);
1779 assert(bit_reader_end || pbi->mb.corrupted);
1780 return bit_reader_end;
1783 static void error_handler(void *data) {
1784 VP9_COMMON *const cm = (VP9_COMMON *)data;
1785 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1788 static void read_bitdepth_colorspace_sampling(
1789 VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1790 if (cm->profile >= PROFILE_2) {
1791 cm->bit_depth = vpx_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1792 #if CONFIG_VP9_HIGHBITDEPTH
1793 cm->use_highbitdepth = 1;
1796 cm->bit_depth = VPX_BITS_8;
1797 #if CONFIG_VP9_HIGHBITDEPTH
1798 cm->use_highbitdepth = 0;
1801 cm->color_space = vpx_rb_read_literal(rb, 3);
1802 if (cm->color_space != VPX_CS_SRGB) {
1803 cm->color_range = (vpx_color_range_t)vpx_rb_read_bit(rb);
1804 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1805 cm->subsampling_x = vpx_rb_read_bit(rb);
1806 cm->subsampling_y = vpx_rb_read_bit(rb);
1807 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1808 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1809 "4:2:0 color not supported in profile 1 or 3");
1810 if (vpx_rb_read_bit(rb))
1811 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1812 "Reserved bit set");
1814 cm->subsampling_y = cm->subsampling_x = 1;
1817 cm->color_range = VPX_CR_FULL_RANGE;
1818 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1819 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1820 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1821 cm->subsampling_y = cm->subsampling_x = 0;
1822 if (vpx_rb_read_bit(rb))
1823 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1824 "Reserved bit set");
1826 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1827 "4:4:4 color not supported in profile 0 or 2");
1832 static size_t read_uncompressed_header(VP9Decoder *pbi,
1833 struct vpx_read_bit_buffer *rb) {
1834 VP9_COMMON *const cm = &pbi->common;
1835 BufferPool *const pool = cm->buffer_pool;
1836 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1837 int i, mask, ref_index = 0;
1840 cm->last_frame_type = cm->frame_type;
1841 cm->last_intra_only = cm->intra_only;
1843 if (vpx_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1844 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1845 "Invalid frame marker");
1847 cm->profile = vp9_read_profile(rb);
1848 #if CONFIG_VP9_HIGHBITDEPTH
1849 if (cm->profile >= MAX_PROFILES)
1850 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1851 "Unsupported bitstream profile");
1853 if (cm->profile >= PROFILE_2)
1854 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1855 "Unsupported bitstream profile");
1858 cm->show_existing_frame = vpx_rb_read_bit(rb);
1859 if (cm->show_existing_frame) {
1860 // Show an existing frame directly.
1861 const int frame_to_show = cm->ref_frame_map[vpx_rb_read_literal(rb, 3)];
1862 lock_buffer_pool(pool);
1863 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1864 unlock_buffer_pool(pool);
1865 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1866 "Buffer %d does not contain a decoded frame",
1870 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1871 unlock_buffer_pool(pool);
1872 pbi->refresh_frame_flags = 0;
1873 cm->lf.filter_level = 0;
1876 if (pbi->frame_parallel_decode) {
1877 for (i = 0; i < REF_FRAMES; ++i)
1878 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1883 cm->frame_type = (FRAME_TYPE) vpx_rb_read_bit(rb);
1884 cm->show_frame = vpx_rb_read_bit(rb);
1885 cm->error_resilient_mode = vpx_rb_read_bit(rb);
1887 if (cm->frame_type == KEY_FRAME) {
1888 if (!vp9_read_sync_code(rb))
1889 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1890 "Invalid frame sync code");
1892 read_bitdepth_colorspace_sampling(cm, rb);
1893 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1895 for (i = 0; i < REFS_PER_FRAME; ++i) {
1896 cm->frame_refs[i].idx = INVALID_IDX;
1897 cm->frame_refs[i].buf = NULL;
1900 setup_frame_size(cm, rb);
1901 if (pbi->need_resync) {
1902 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1903 pbi->need_resync = 0;
1906 cm->intra_only = cm->show_frame ? 0 : vpx_rb_read_bit(rb);
1908 cm->reset_frame_context = cm->error_resilient_mode ?
1909 0 : vpx_rb_read_literal(rb, 2);
1911 if (cm->intra_only) {
1912 if (!vp9_read_sync_code(rb))
1913 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1914 "Invalid frame sync code");
1915 if (cm->profile > PROFILE_0) {
1916 read_bitdepth_colorspace_sampling(cm, rb);
1918 // NOTE: The intra-only frame header does not include the specification
1919 // of either the color format or color sub-sampling in profile 0. VP9
1920 // specifies that the default color format should be YUV 4:2:0 in this
1921 // case (normative).
1922 cm->color_space = VPX_CS_BT_601;
1923 cm->color_range = VPX_CR_STUDIO_RANGE;
1924 cm->subsampling_y = cm->subsampling_x = 1;
1925 cm->bit_depth = VPX_BITS_8;
1926 #if CONFIG_VP9_HIGHBITDEPTH
1927 cm->use_highbitdepth = 0;
1931 pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1932 setup_frame_size(cm, rb);
1933 if (pbi->need_resync) {
1934 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1935 pbi->need_resync = 0;
1937 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1938 pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1939 for (i = 0; i < REFS_PER_FRAME; ++i) {
1940 const int ref = vpx_rb_read_literal(rb, REF_FRAMES_LOG2);
1941 const int idx = cm->ref_frame_map[ref];
1942 RefBuffer *const ref_frame = &cm->frame_refs[i];
1943 ref_frame->idx = idx;
1944 ref_frame->buf = &frame_bufs[idx].buf;
1945 cm->ref_frame_sign_bias[LAST_FRAME + i] = vpx_rb_read_bit(rb);
1948 setup_frame_size_with_refs(cm, rb);
1950 cm->allow_high_precision_mv = vpx_rb_read_bit(rb);
1951 cm->interp_filter = read_interp_filter(rb);
1953 for (i = 0; i < REFS_PER_FRAME; ++i) {
1954 RefBuffer *const ref_buf = &cm->frame_refs[i];
1955 #if CONFIG_VP9_HIGHBITDEPTH
1956 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1957 ref_buf->buf->y_crop_width,
1958 ref_buf->buf->y_crop_height,
1959 cm->width, cm->height,
1960 cm->use_highbitdepth);
1962 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1963 ref_buf->buf->y_crop_width,
1964 ref_buf->buf->y_crop_height,
1965 cm->width, cm->height);
1970 #if CONFIG_VP9_HIGHBITDEPTH
1971 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1973 get_frame_new_buffer(cm)->color_space = cm->color_space;
1974 get_frame_new_buffer(cm)->color_range = cm->color_range;
1975 get_frame_new_buffer(cm)->render_width = cm->render_width;
1976 get_frame_new_buffer(cm)->render_height = cm->render_height;
1978 if (pbi->need_resync) {
1979 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1980 "Keyframe / intra-only frame required to reset decoder"
1984 if (!cm->error_resilient_mode) {
1985 cm->refresh_frame_context = vpx_rb_read_bit(rb);
1986 cm->frame_parallel_decoding_mode = vpx_rb_read_bit(rb);
1987 if (!cm->frame_parallel_decoding_mode)
1988 vp9_zero(cm->counts);
1990 cm->refresh_frame_context = 0;
1991 cm->frame_parallel_decoding_mode = 1;
1994 // This flag will be overridden by the call to vp9_setup_past_independence
1995 // below, forcing the use of context 0 for those frame types.
1996 cm->frame_context_idx = vpx_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1998 // Generate next_ref_frame_map.
1999 lock_buffer_pool(pool);
2000 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
2002 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
2003 ++frame_bufs[cm->new_fb_idx].ref_count;
2005 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2007 // Current thread holds the reference frame.
2008 if (cm->ref_frame_map[ref_index] >= 0)
2009 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2013 for (; ref_index < REF_FRAMES; ++ref_index) {
2014 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2015 // Current thread holds the reference frame.
2016 if (cm->ref_frame_map[ref_index] >= 0)
2017 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2019 unlock_buffer_pool(pool);
2020 pbi->hold_ref_buf = 1;
2022 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
2023 vp9_setup_past_independence(cm);
2025 setup_loopfilter(&cm->lf, rb);
2026 setup_quantization(cm, &pbi->mb, rb);
2027 setup_segmentation(&cm->seg, rb);
2028 setup_segmentation_dequant(cm);
2030 setup_tile_info(cm, rb);
2031 sz = vpx_rb_read_literal(rb, 16);
2034 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2035 "Invalid header size");
2040 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
2041 size_t partition_size) {
2042 VP9_COMMON *const cm = &pbi->common;
2043 MACROBLOCKD *const xd = &pbi->mb;
2044 FRAME_CONTEXT *const fc = cm->fc;
2048 if (vpx_reader_init(&r, data, partition_size, pbi->decrypt_cb,
2049 pbi->decrypt_state))
2050 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2051 "Failed to allocate bool decoder 0");
2053 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
2054 if (cm->tx_mode == TX_MODE_SELECT)
2055 read_tx_mode_probs(&fc->tx_probs, &r);
2056 read_coef_probs(fc, cm->tx_mode, &r);
2058 for (k = 0; k < SKIP_CONTEXTS; ++k)
2059 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
2061 if (!frame_is_intra_only(cm)) {
2062 nmv_context *const nmvc = &fc->nmvc;
2065 read_inter_mode_probs(fc, &r);
2067 if (cm->interp_filter == SWITCHABLE)
2068 read_switchable_interp_probs(fc, &r);
2070 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
2071 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
2073 cm->reference_mode = read_frame_reference_mode(cm, &r);
2074 if (cm->reference_mode != SINGLE_REFERENCE)
2075 setup_compound_reference_mode(cm);
2076 read_frame_reference_mode_probs(cm, &r);
2078 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
2079 for (i = 0; i < INTRA_MODES - 1; ++i)
2080 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
2082 for (j = 0; j < PARTITION_CONTEXTS; ++j)
2083 for (i = 0; i < PARTITION_TYPES - 1; ++i)
2084 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
2086 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2089 return vpx_reader_has_error(&r);
2092 static struct vpx_read_bit_buffer *init_read_bit_buffer(
2094 struct vpx_read_bit_buffer *rb,
2095 const uint8_t *data,
2096 const uint8_t *data_end,
2097 uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2099 rb->error_handler = error_handler;
2100 rb->error_handler_data = &pbi->common;
2101 if (pbi->decrypt_cb) {
2102 const int n = (int)VPXMIN(MAX_VP9_HEADER_SIZE, data_end - data);
2103 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2104 rb->bit_buffer = clear_data;
2105 rb->bit_buffer_end = clear_data + n;
2107 rb->bit_buffer = data;
2108 rb->bit_buffer_end = data_end;
2113 //------------------------------------------------------------------------------
2115 int vp9_read_sync_code(struct vpx_read_bit_buffer *const rb) {
2116 return vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2117 vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2118 vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2121 void vp9_read_frame_size(struct vpx_read_bit_buffer *rb,
2122 int *width, int *height) {
2123 *width = vpx_rb_read_literal(rb, 16) + 1;
2124 *height = vpx_rb_read_literal(rb, 16) + 1;
2127 BITSTREAM_PROFILE vp9_read_profile(struct vpx_read_bit_buffer *rb) {
2128 int profile = vpx_rb_read_bit(rb);
2129 profile |= vpx_rb_read_bit(rb) << 1;
2131 profile += vpx_rb_read_bit(rb);
2132 return (BITSTREAM_PROFILE) profile;
2135 void vp9_decode_frame(VP9Decoder *pbi,
2136 const uint8_t *data, const uint8_t *data_end,
2137 const uint8_t **p_data_end) {
2138 VP9_COMMON *const cm = &pbi->common;
2139 MACROBLOCKD *const xd = &pbi->mb;
2140 struct vpx_read_bit_buffer rb;
2141 int context_updated = 0;
2142 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2143 const size_t first_partition_size = read_uncompressed_header(pbi,
2144 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2145 const int tile_rows = 1 << cm->log2_tile_rows;
2146 const int tile_cols = 1 << cm->log2_tile_cols;
2147 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2148 xd->cur_buf = new_fb;
2150 if (!first_partition_size) {
2151 // showing a frame directly
2152 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2156 data += vpx_rb_bytes_read(&rb);
2157 if (!read_is_valid(data, first_partition_size, data_end))
2158 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2159 "Truncated packet or corrupt header length");
2161 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2162 cm->width == cm->last_width &&
2163 cm->height == cm->last_height &&
2164 !cm->last_intra_only &&
2165 cm->last_show_frame &&
2166 (cm->last_frame_type != KEY_FRAME);
2168 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2170 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2171 if (!cm->fc->initialized)
2172 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2173 "Uninitialized entropy context.");
2176 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2177 if (new_fb->corrupted)
2178 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2179 "Decode failed. Frame data header is corrupted.");
2181 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2182 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2185 // If encoded in frame parallel mode, frame context is ready after decoding
2186 // the frame header.
2187 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2188 VPxWorker *const worker = pbi->frame_worker_owner;
2189 FrameWorkerData *const frame_worker_data = worker->data1;
2190 if (cm->refresh_frame_context) {
2191 context_updated = 1;
2192 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2194 vp9_frameworker_lock_stats(worker);
2195 pbi->cur_buf->row = -1;
2196 pbi->cur_buf->col = -1;
2197 frame_worker_data->frame_context_ready = 1;
2198 // Signal the main thread that context is ready.
2199 vp9_frameworker_signal_stats(worker);
2200 vp9_frameworker_unlock_stats(worker);
2203 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2204 // Multi-threaded tile decoder
2205 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2206 if (!xd->corrupted) {
2207 if (!cm->skip_loop_filter) {
2208 // If multiple threads are used to decode tiles, then we use those
2209 // threads to do parallel loopfiltering.
2210 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2211 cm->lf.filter_level, 0, 0, pbi->tile_workers,
2212 pbi->num_tile_workers, &pbi->lf_row_sync);
2215 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2216 "Decode failed. Frame data is corrupted.");
2219 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2222 if (!xd->corrupted) {
2223 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2224 vp9_adapt_coef_probs(cm);
2226 if (!frame_is_intra_only(cm)) {
2227 vp9_adapt_mode_probs(cm);
2228 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2232 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2233 "Decode failed. Frame data is corrupted.");
2236 // Non frame parallel update frame context here.
2237 if (cm->refresh_frame_context && !context_updated)
2238 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;