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_mem/vpx_mem.h"
21 #include "vpx_ports/mem.h"
22 #include "vpx_ports/mem_ops.h"
23 #include "vpx_scale/vpx_scale.h"
24 #include "vpx_util/vpx_thread.h"
26 #include "vp9/common/vp9_alloccommon.h"
27 #include "vp9/common/vp9_common.h"
28 #include "vp9/common/vp9_entropy.h"
29 #include "vp9/common/vp9_entropymode.h"
30 #include "vp9/common/vp9_idct.h"
31 #include "vp9/common/vp9_thread_common.h"
32 #include "vp9/common/vp9_pred_common.h"
33 #include "vp9/common/vp9_quant_common.h"
34 #include "vp9/common/vp9_reconintra.h"
35 #include "vp9/common/vp9_reconinter.h"
36 #include "vp9/common/vp9_seg_common.h"
37 #include "vp9/common/vp9_tile_common.h"
39 #include "vp9/decoder/vp9_decodeframe.h"
40 #include "vp9/decoder/vp9_detokenize.h"
41 #include "vp9/decoder/vp9_decodemv.h"
42 #include "vp9/decoder/vp9_decoder.h"
43 #include "vp9/decoder/vp9_dsubexp.h"
45 #define MAX_VP9_HEADER_SIZE 80
47 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
49 for (i = 1; i < REFS_PER_FRAME; ++i)
50 if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1])
56 static void setup_compound_reference_mode(VP9_COMMON *cm) {
57 if (cm->ref_frame_sign_bias[LAST_FRAME] ==
58 cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
59 cm->comp_fixed_ref = ALTREF_FRAME;
60 cm->comp_var_ref[0] = LAST_FRAME;
61 cm->comp_var_ref[1] = GOLDEN_FRAME;
62 } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
63 cm->ref_frame_sign_bias[ALTREF_FRAME]) {
64 cm->comp_fixed_ref = GOLDEN_FRAME;
65 cm->comp_var_ref[0] = LAST_FRAME;
66 cm->comp_var_ref[1] = ALTREF_FRAME;
68 cm->comp_fixed_ref = LAST_FRAME;
69 cm->comp_var_ref[0] = GOLDEN_FRAME;
70 cm->comp_var_ref[1] = ALTREF_FRAME;
74 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
75 return len != 0 && len <= (size_t)(end - start);
78 static int decode_unsigned_max(struct vpx_read_bit_buffer *rb, int max) {
79 const int data = vpx_rb_read_literal(rb, get_unsigned_bits(max));
80 return data > max ? max : data;
83 static TX_MODE read_tx_mode(vpx_reader *r) {
84 TX_MODE tx_mode = vpx_read_literal(r, 2);
85 if (tx_mode == ALLOW_32X32)
86 tx_mode += vpx_read_bit(r);
90 static void read_tx_mode_probs(struct tx_probs *tx_probs, vpx_reader *r) {
93 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
94 for (j = 0; j < TX_SIZES - 3; ++j)
95 vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
97 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
98 for (j = 0; j < TX_SIZES - 2; ++j)
99 vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
101 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
102 for (j = 0; j < TX_SIZES - 1; ++j)
103 vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
106 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
108 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
109 for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
110 vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
113 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
115 for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
116 for (j = 0; j < INTER_MODES - 1; ++j)
117 vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
120 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
122 if (is_compound_reference_allowed(cm)) {
123 return vpx_read_bit(r) ? (vpx_read_bit(r) ? REFERENCE_MODE_SELECT
124 : COMPOUND_REFERENCE)
127 return SINGLE_REFERENCE;
131 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vpx_reader *r) {
132 FRAME_CONTEXT *const fc = cm->fc;
135 if (cm->reference_mode == REFERENCE_MODE_SELECT)
136 for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
137 vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
139 if (cm->reference_mode != COMPOUND_REFERENCE)
140 for (i = 0; i < REF_CONTEXTS; ++i) {
141 vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
142 vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
145 if (cm->reference_mode != SINGLE_REFERENCE)
146 for (i = 0; i < REF_CONTEXTS; ++i)
147 vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
150 static void update_mv_probs(vpx_prob *p, int n, vpx_reader *r) {
152 for (i = 0; i < n; ++i)
153 if (vpx_read(r, MV_UPDATE_PROB))
154 p[i] = (vpx_read_literal(r, 7) << 1) | 1;
157 static void read_mv_probs(nmv_context *ctx, int allow_hp, vpx_reader *r) {
160 update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
162 for (i = 0; i < 2; ++i) {
163 nmv_component *const comp_ctx = &ctx->comps[i];
164 update_mv_probs(&comp_ctx->sign, 1, r);
165 update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
166 update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
167 update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
170 for (i = 0; i < 2; ++i) {
171 nmv_component *const comp_ctx = &ctx->comps[i];
172 for (j = 0; j < CLASS0_SIZE; ++j)
173 update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
174 update_mv_probs(comp_ctx->fp, 3, r);
178 for (i = 0; i < 2; ++i) {
179 nmv_component *const comp_ctx = &ctx->comps[i];
180 update_mv_probs(&comp_ctx->class0_hp, 1, r);
181 update_mv_probs(&comp_ctx->hp, 1, r);
186 static void inverse_transform_block_inter(MACROBLOCKD* xd, int plane,
187 const TX_SIZE tx_size,
188 uint8_t *dst, int stride,
190 struct macroblockd_plane *const pd = &xd->plane[plane];
192 tran_low_t *const dqcoeff = pd->dqcoeff;
193 #if CONFIG_VP9_HIGHBITDEPTH
194 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
196 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
200 vp9_highbd_idct4x4_add(dqcoeff, dst, stride, eob, xd->bd);
203 vp9_highbd_idct8x8_add(dqcoeff, dst, stride, eob, xd->bd);
206 vp9_highbd_idct16x16_add(dqcoeff, dst, stride, eob, xd->bd);
209 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
212 assert(0 && "Invalid transform size");
217 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
221 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
224 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
227 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
230 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
233 assert(0 && "Invalid transform size");
240 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
244 vp9_idct4x4_add(dqcoeff, dst, stride, eob);
247 vp9_idct8x8_add(dqcoeff, dst, stride, eob);
250 vp9_idct16x16_add(dqcoeff, dst, stride, eob);
253 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
256 assert(0 && "Invalid transform size");
260 #endif // CONFIG_VP9_HIGHBITDEPTH
265 if (tx_size <= TX_16X16 && eob <= 10)
266 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
267 else if (tx_size == TX_32X32 && eob <= 34)
268 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
270 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
275 static void inverse_transform_block_intra(MACROBLOCKD* xd, int plane,
276 const TX_TYPE tx_type,
277 const TX_SIZE tx_size,
278 uint8_t *dst, int stride,
280 struct macroblockd_plane *const pd = &xd->plane[plane];
282 tran_low_t *const dqcoeff = pd->dqcoeff;
283 #if CONFIG_VP9_HIGHBITDEPTH
284 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
286 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
290 vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
293 vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
296 vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
299 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
302 assert(0 && "Invalid transform size");
307 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
311 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
314 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
317 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
320 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
323 assert(0 && "Invalid transform size");
330 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
334 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
337 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
340 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
343 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
346 assert(0 && "Invalid transform size");
350 #endif // CONFIG_VP9_HIGHBITDEPTH
355 if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
356 memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
357 else if (tx_size == TX_32X32 && eob <= 34)
358 memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
360 memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
365 static void predict_and_reconstruct_intra_block(MACROBLOCKD *const xd,
367 MB_MODE_INFO *const mbmi,
371 struct macroblockd_plane *const pd = &xd->plane[plane];
372 PREDICTION_MODE mode = (plane == 0) ? mbmi->mode : mbmi->uv_mode;
374 dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
376 if (mbmi->sb_type < BLOCK_8X8)
378 mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
380 vp9_predict_intra_block(xd, pd->n4_wl, tx_size, mode,
381 dst, pd->dst.stride, dst, pd->dst.stride,
385 const TX_TYPE tx_type = (plane || xd->lossless) ?
386 DCT_DCT : intra_mode_to_tx_type_lookup[mode];
387 const scan_order *sc = (plane || xd->lossless) ?
388 &vp9_default_scan_orders[tx_size] : &vp9_scan_orders[tx_size][tx_type];
389 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size,
390 r, mbmi->segment_id);
391 inverse_transform_block_intra(xd, plane, tx_type, tx_size,
392 dst, pd->dst.stride, eob);
396 static int reconstruct_inter_block(MACROBLOCKD *const xd, vpx_reader *r,
397 MB_MODE_INFO *const mbmi, int plane,
398 int row, int col, TX_SIZE tx_size) {
399 struct macroblockd_plane *const pd = &xd->plane[plane];
400 const scan_order *sc = &vp9_default_scan_orders[tx_size];
401 const int eob = vp9_decode_block_tokens(xd, plane, sc, col, row, tx_size, r,
404 inverse_transform_block_inter(xd, plane, tx_size,
405 &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
406 pd->dst.stride, eob);
410 static void build_mc_border(const uint8_t *src, int src_stride,
411 uint8_t *dst, int dst_stride,
412 int x, int y, int b_w, int b_h, int w, int h) {
413 // Get a pointer to the start of the real data for this row.
414 const uint8_t *ref_row = src - x - y * src_stride;
417 ref_row += (h - 1) * src_stride;
419 ref_row += y * src_stride;
423 int left = x < 0 ? -x : 0;
434 copy = b_w - left - right;
437 memset(dst, ref_row[0], left);
440 memcpy(dst + left, ref_row + x + left, copy);
443 memset(dst + left + copy, ref_row[w - 1], right);
449 ref_row += src_stride;
453 #if CONFIG_VP9_HIGHBITDEPTH
454 static void high_build_mc_border(const uint8_t *src8, int src_stride,
455 uint16_t *dst, int dst_stride,
456 int x, int y, int b_w, int b_h,
458 // Get a pointer to the start of the real data for this row.
459 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
460 const uint16_t *ref_row = src - x - y * src_stride;
463 ref_row += (h - 1) * src_stride;
465 ref_row += y * src_stride;
469 int left = x < 0 ? -x : 0;
480 copy = b_w - left - right;
483 vpx_memset16(dst, ref_row[0], left);
486 memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
489 vpx_memset16(dst + left + copy, ref_row[w - 1], right);
495 ref_row += src_stride;
498 #endif // CONFIG_VP9_HIGHBITDEPTH
500 #if CONFIG_VP9_HIGHBITDEPTH
501 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
502 int x0, int y0, int b_w, int b_h,
503 int frame_width, int frame_height,
505 uint8_t *const dst, int dst_buf_stride,
506 int subpel_x, int subpel_y,
507 const InterpKernel *kernel,
508 const struct scale_factors *sf,
510 int w, int h, int ref, int xs, int ys) {
511 DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
512 const uint8_t *buf_ptr;
514 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
515 high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w,
516 x0, y0, b_w, b_h, frame_width, frame_height);
517 buf_ptr = CONVERT_TO_BYTEPTR(mc_buf_high) + border_offset;
519 build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w,
520 x0, y0, b_w, b_h, frame_width, frame_height);
521 buf_ptr = ((uint8_t *)mc_buf_high) + border_offset;
524 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
525 high_inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
526 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
528 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
529 subpel_y, sf, w, h, ref, kernel, xs, ys);
533 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
534 int x0, int y0, int b_w, int b_h,
535 int frame_width, int frame_height,
537 uint8_t *const dst, int dst_buf_stride,
538 int subpel_x, int subpel_y,
539 const InterpKernel *kernel,
540 const struct scale_factors *sf,
541 int w, int h, int ref, int xs, int ys) {
542 DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
543 const uint8_t *buf_ptr;
545 build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w,
546 x0, y0, b_w, b_h, frame_width, frame_height);
547 buf_ptr = mc_buf + border_offset;
549 inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
550 subpel_y, sf, w, h, ref, kernel, xs, ys);
552 #endif // CONFIG_VP9_HIGHBITDEPTH
554 static void dec_build_inter_predictors(VP9Decoder *const pbi, MACROBLOCKD *xd,
555 int plane, int bw, int bh, int x,
556 int y, int w, int h, int mi_x, int mi_y,
557 const InterpKernel *kernel,
558 const struct scale_factors *sf,
559 struct buf_2d *pre_buf,
560 struct buf_2d *dst_buf, const MV* mv,
561 RefCntBuffer *ref_frame_buf,
562 int is_scaled, int ref) {
563 struct macroblockd_plane *const pd = &xd->plane[plane];
564 uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
566 int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height,
567 buf_stride, subpel_x, subpel_y;
568 uint8_t *ref_frame, *buf_ptr;
570 // Get reference frame pointer, width and height.
572 frame_width = ref_frame_buf->buf.y_crop_width;
573 frame_height = ref_frame_buf->buf.y_crop_height;
574 ref_frame = ref_frame_buf->buf.y_buffer;
576 frame_width = ref_frame_buf->buf.uv_crop_width;
577 frame_height = ref_frame_buf->buf.uv_crop_height;
578 ref_frame = plane == 1 ? ref_frame_buf->buf.u_buffer
579 : ref_frame_buf->buf.v_buffer;
583 const MV mv_q4 = clamp_mv_to_umv_border_sb(xd, mv, bw, bh,
586 // Co-ordinate of containing block to pixel precision.
587 int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
588 int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
590 // Co-ordinate of the block to 1/16th pixel precision.
591 x0_16 = (x_start + x) << SUBPEL_BITS;
592 y0_16 = (y_start + y) << SUBPEL_BITS;
594 // Co-ordinate of current block in reference frame
595 // to 1/16th pixel precision.
596 x0_16 = sf->scale_value_x(x0_16, sf);
597 y0_16 = sf->scale_value_y(y0_16, sf);
599 // Map the top left corner of the block into the reference frame.
600 x0 = sf->scale_value_x(x_start + x, sf);
601 y0 = sf->scale_value_y(y_start + y, sf);
603 // Scale the MV and incorporate the sub-pixel offset of the block
604 // in the reference frame.
605 scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
609 // Co-ordinate of containing block to pixel precision.
610 x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
611 y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
613 // Co-ordinate of the block to 1/16th pixel precision.
614 x0_16 = x0 << SUBPEL_BITS;
615 y0_16 = y0 << SUBPEL_BITS;
617 scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
618 scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
621 subpel_x = scaled_mv.col & SUBPEL_MASK;
622 subpel_y = scaled_mv.row & SUBPEL_MASK;
624 // Calculate the top left corner of the best matching block in the
626 x0 += scaled_mv.col >> SUBPEL_BITS;
627 y0 += scaled_mv.row >> SUBPEL_BITS;
628 x0_16 += scaled_mv.col;
629 y0_16 += scaled_mv.row;
631 // Get reference block pointer.
632 buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
633 buf_stride = pre_buf->stride;
635 // Do border extension if there is motion or the
636 // width/height is not a multiple of 8 pixels.
637 if (is_scaled || scaled_mv.col || scaled_mv.row ||
638 (frame_width & 0x7) || (frame_height & 0x7)) {
639 int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
641 // Get reference block bottom right horizontal coordinate.
642 int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
643 int x_pad = 0, y_pad = 0;
645 if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
646 x0 -= VP9_INTERP_EXTEND - 1;
647 x1 += VP9_INTERP_EXTEND;
651 if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
652 y0 -= VP9_INTERP_EXTEND - 1;
653 y1 += VP9_INTERP_EXTEND;
657 // Wait until reference block is ready. Pad 7 more pixels as last 7
658 // pixels of each superblock row can be changed by next superblock row.
659 if (pbi->frame_parallel_decode)
660 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
661 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
663 // Skip border extension if block is inside the frame.
664 if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
665 y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
666 // Extend the border.
667 const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
668 const int b_w = x1 - x0 + 1;
669 const int b_h = y1 - y0 + 1;
670 const int border_offset = y_pad * 3 * b_w + x_pad * 3;
672 extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h,
673 frame_width, frame_height, border_offset,
674 dst, dst_buf->stride,
677 #if CONFIG_VP9_HIGHBITDEPTH
684 // Wait until reference block is ready. Pad 7 more pixels as last 7
685 // pixels of each superblock row can be changed by next superblock row.
686 if (pbi->frame_parallel_decode) {
687 const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
688 vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
689 MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
692 #if CONFIG_VP9_HIGHBITDEPTH
693 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
694 high_inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
695 subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
697 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
698 subpel_y, sf, w, h, ref, kernel, xs, ys);
701 inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
702 subpel_y, sf, w, h, ref, kernel, xs, ys);
703 #endif // CONFIG_VP9_HIGHBITDEPTH
706 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
708 int mi_row, int mi_col) {
710 const int mi_x = mi_col * MI_SIZE;
711 const int mi_y = mi_row * MI_SIZE;
712 const MODE_INFO *mi = xd->mi[0];
713 const InterpKernel *kernel = vp9_filter_kernels[mi->mbmi.interp_filter];
714 const BLOCK_SIZE sb_type = mi->mbmi.sb_type;
715 const int is_compound = has_second_ref(&mi->mbmi);
717 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
718 struct macroblockd_plane *const pd = &xd->plane[plane];
719 struct buf_2d *const dst_buf = &pd->dst;
720 const int num_4x4_w = pd->n4_w;
721 const int num_4x4_h = pd->n4_h;
723 const int n4w_x4 = 4 * num_4x4_w;
724 const int n4h_x4 = 4 * num_4x4_h;
727 for (ref = 0; ref < 1 + is_compound; ++ref) {
728 const struct scale_factors *const sf = &xd->block_refs[ref]->sf;
729 struct buf_2d *const pre_buf = &pd->pre[ref];
730 const int idx = xd->block_refs[ref]->idx;
731 BufferPool *const pool = pbi->common.buffer_pool;
732 RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
733 const int is_scaled = vp9_is_scaled(sf);
735 if (sb_type < BLOCK_8X8) {
737 for (y = 0; y < num_4x4_h; ++y) {
738 for (x = 0; x < num_4x4_w; ++x) {
739 const MV mv = average_split_mvs(pd, mi, ref, i++);
740 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
741 4 * x, 4 * y, 4, 4, mi_x, mi_y, kernel,
742 sf, pre_buf, dst_buf, &mv,
743 ref_frame_buf, is_scaled, ref);
747 const MV mv = mi->mbmi.mv[ref].as_mv;
748 dec_build_inter_predictors(pbi, xd, plane, n4w_x4, n4h_x4,
749 0, 0, n4w_x4, n4h_x4, mi_x, mi_y, kernel,
750 sf, pre_buf, dst_buf, &mv, ref_frame_buf,
757 static INLINE TX_SIZE dec_get_uv_tx_size(const MB_MODE_INFO *mbmi,
758 int n4_wl, int n4_hl) {
759 // get minimum log2 num4x4s dimension
760 const int x = MIN(n4_wl, n4_hl);
761 return MIN(mbmi->tx_size, x);
764 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
766 for (i = 0; i < MAX_MB_PLANE; i++) {
767 struct macroblockd_plane *const pd = &xd->plane[i];
768 memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
769 memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
773 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
776 for (i = 0; i < MAX_MB_PLANE; i++) {
777 xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
778 xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
779 xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
780 xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
784 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
785 BLOCK_SIZE bsize, int mi_row, int mi_col,
786 int bw, int bh, int x_mis, int y_mis,
788 const int offset = mi_row * cm->mi_stride + mi_col;
790 const TileInfo *const tile = &xd->tile;
792 xd->mi = cm->mi_grid_visible + offset;
793 xd->mi[0] = &cm->mi[offset];
794 // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
795 // passing bsize from decode_partition().
796 xd->mi[0]->mbmi.sb_type = bsize;
797 for (y = 0; y < y_mis; ++y)
798 for (x = !y; x < x_mis; ++x) {
799 xd->mi[y * cm->mi_stride + x] = xd->mi[0];
802 set_plane_n4(xd, bw, bh, bwl, bhl);
804 set_skip_context(xd, mi_row, mi_col);
806 // Distance of Mb to the various image edges. These are specified to 8th pel
807 // as they are always compared to values that are in 1/8th pel units
808 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
810 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
811 return &xd->mi[0]->mbmi;
814 static void decode_block(VP9Decoder *const pbi, MACROBLOCKD *const xd,
815 int mi_row, int mi_col,
816 vpx_reader *r, BLOCK_SIZE bsize,
818 VP9_COMMON *const cm = &pbi->common;
819 const int less8x8 = bsize < BLOCK_8X8;
820 const int bw = 1 << (bwl - 1);
821 const int bh = 1 << (bhl - 1);
822 const int x_mis = MIN(bw, cm->mi_cols - mi_col);
823 const int y_mis = MIN(bh, cm->mi_rows - mi_row);
825 MB_MODE_INFO *mbmi = set_offsets(cm, xd, bsize, mi_row, mi_col,
826 bw, bh, x_mis, y_mis, bwl, bhl);
828 if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
829 const BLOCK_SIZE uv_subsize =
830 ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
831 if (uv_subsize == BLOCK_INVALID)
832 vpx_internal_error(xd->error_info,
833 VPX_CODEC_CORRUPT_FRAME, "Invalid block size.");
836 vpx_read_mode_info(pbi, xd, mi_row, mi_col, r, x_mis, y_mis);
839 dec_reset_skip_context(xd);
842 if (!is_inter_block(mbmi)) {
844 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
845 const struct macroblockd_plane *const pd = &xd->plane[plane];
846 const TX_SIZE tx_size =
847 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
849 const int num_4x4_w = pd->n4_w;
850 const int num_4x4_h = pd->n4_h;
851 const int step = (1 << tx_size);
853 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
854 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
855 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
856 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
858 for (row = 0; row < max_blocks_high; row += step)
859 for (col = 0; col < max_blocks_wide; col += step)
860 predict_and_reconstruct_intra_block(xd, r, mbmi, plane,
865 dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col);
872 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
873 const struct macroblockd_plane *const pd = &xd->plane[plane];
874 const TX_SIZE tx_size =
875 plane ? dec_get_uv_tx_size(mbmi, pd->n4_wl, pd->n4_hl)
877 const int num_4x4_w = pd->n4_w;
878 const int num_4x4_h = pd->n4_h;
879 const int step = (1 << tx_size);
881 const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ?
882 0 : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
883 const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ?
884 0 : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
886 for (row = 0; row < max_blocks_high; row += step)
887 for (col = 0; col < max_blocks_wide; col += step)
888 eobtotal += reconstruct_inter_block(xd, r, mbmi, plane, row, col,
892 if (!less8x8 && eobtotal == 0)
893 mbmi->skip = 1; // skip loopfilter
897 xd->corrupted |= vpx_reader_has_error(r);
900 static INLINE int dec_partition_plane_context(const MACROBLOCKD *xd,
901 int mi_row, int mi_col,
903 const PARTITION_CONTEXT *above_ctx = xd->above_seg_context + mi_col;
904 const PARTITION_CONTEXT *left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
905 int above = (*above_ctx >> bsl) & 1 , left = (*left_ctx >> bsl) & 1;
909 return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
912 static INLINE void dec_update_partition_context(MACROBLOCKD *xd,
913 int mi_row, int mi_col,
916 PARTITION_CONTEXT *const above_ctx = xd->above_seg_context + mi_col;
917 PARTITION_CONTEXT *const left_ctx = xd->left_seg_context + (mi_row & MI_MASK);
919 // update the partition context at the end notes. set partition bits
920 // of block sizes larger than the current one to be one, and partition
921 // bits of smaller block sizes to be zero.
922 memset(above_ctx, partition_context_lookup[subsize].above, bw);
923 memset(left_ctx, partition_context_lookup[subsize].left, bw);
926 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
928 int has_rows, int has_cols, int bsl) {
929 const int ctx = dec_partition_plane_context(xd, mi_row, mi_col, bsl);
930 const vpx_prob *const probs = get_partition_probs(xd, ctx);
931 FRAME_COUNTS *counts = xd->counts;
934 if (has_rows && has_cols)
935 p = (PARTITION_TYPE)vpx_read_tree(r, vp9_partition_tree, probs);
936 else if (!has_rows && has_cols)
937 p = vpx_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
938 else if (has_rows && !has_cols)
939 p = vpx_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
944 ++counts->partition[ctx][p];
949 // TODO(slavarnway): eliminate bsize and subsize in future commits
950 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
951 int mi_row, int mi_col,
952 vpx_reader* r, BLOCK_SIZE bsize, int n4x4_l2) {
953 VP9_COMMON *const cm = &pbi->common;
954 const int n8x8_l2 = n4x4_l2 - 1;
955 const int num_8x8_wh = 1 << n8x8_l2;
956 const int hbs = num_8x8_wh >> 1;
957 PARTITION_TYPE partition;
959 const int has_rows = (mi_row + hbs) < cm->mi_rows;
960 const int has_cols = (mi_col + hbs) < cm->mi_cols;
962 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
965 partition = read_partition(xd, mi_row, mi_col, r, has_rows, has_cols,
967 subsize = subsize_lookup[partition][bsize]; // get_subsize(bsize, partition);
969 // calculate bmode block dimensions (log 2)
970 xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
971 xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
972 decode_block(pbi, xd, mi_row, mi_col, r, subsize, 1, 1);
976 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n4x4_l2);
979 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n4x4_l2, n8x8_l2);
981 decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize, n4x4_l2,
985 decode_block(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2, n4x4_l2);
987 decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2,
990 case PARTITION_SPLIT:
991 decode_partition(pbi, xd, mi_row, mi_col, r, subsize, n8x8_l2);
992 decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize, n8x8_l2);
993 decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize, n8x8_l2);
994 decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize,
998 assert(0 && "Invalid partition type");
1002 // update partition context
1003 if (bsize >= BLOCK_8X8 &&
1004 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
1005 dec_update_partition_context(xd, mi_row, mi_col, subsize, num_8x8_wh);
1008 static void setup_token_decoder(const uint8_t *data,
1009 const uint8_t *data_end,
1011 struct vpx_internal_error_info *error_info,
1013 vpx_decrypt_cb decrypt_cb,
1014 void *decrypt_state) {
1015 // Validate the calculated partition length. If the buffer
1016 // described by the partition can't be fully read, then restrict
1017 // it to the portion that can be (for EC mode) or throw an error.
1018 if (!read_is_valid(data, read_size, data_end))
1019 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1020 "Truncated packet or corrupt tile length");
1022 if (vpx_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
1023 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
1024 "Failed to allocate bool decoder %d", 1);
1027 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
1031 if (vpx_read_bit(r))
1032 for (i = 0; i < PLANE_TYPES; ++i)
1033 for (j = 0; j < REF_TYPES; ++j)
1034 for (k = 0; k < COEF_BANDS; ++k)
1035 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1036 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
1037 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
1040 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
1042 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1044 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1045 read_coef_probs_common(fc->coef_probs[tx_size], r);
1048 static void setup_segmentation(struct segmentation *seg,
1049 struct vpx_read_bit_buffer *rb) {
1052 seg->update_map = 0;
1053 seg->update_data = 0;
1055 seg->enabled = vpx_rb_read_bit(rb);
1059 // Segmentation map update
1060 seg->update_map = vpx_rb_read_bit(rb);
1061 if (seg->update_map) {
1062 for (i = 0; i < SEG_TREE_PROBS; i++)
1063 seg->tree_probs[i] = vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8)
1066 seg->temporal_update = vpx_rb_read_bit(rb);
1067 if (seg->temporal_update) {
1068 for (i = 0; i < PREDICTION_PROBS; i++)
1069 seg->pred_probs[i] = vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8)
1072 for (i = 0; i < PREDICTION_PROBS; i++)
1073 seg->pred_probs[i] = MAX_PROB;
1077 // Segmentation data update
1078 seg->update_data = vpx_rb_read_bit(rb);
1079 if (seg->update_data) {
1080 seg->abs_delta = vpx_rb_read_bit(rb);
1082 vp9_clearall_segfeatures(seg);
1084 for (i = 0; i < MAX_SEGMENTS; i++) {
1085 for (j = 0; j < SEG_LVL_MAX; j++) {
1087 const int feature_enabled = vpx_rb_read_bit(rb);
1088 if (feature_enabled) {
1089 vp9_enable_segfeature(seg, i, j);
1090 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1091 if (vp9_is_segfeature_signed(j))
1092 data = vpx_rb_read_bit(rb) ? -data : data;
1094 vp9_set_segdata(seg, i, j, data);
1100 static void setup_loopfilter(struct loopfilter *lf,
1101 struct vpx_read_bit_buffer *rb) {
1102 lf->filter_level = vpx_rb_read_literal(rb, 6);
1103 lf->sharpness_level = vpx_rb_read_literal(rb, 3);
1105 // Read in loop filter deltas applied at the MB level based on mode or ref
1107 lf->mode_ref_delta_update = 0;
1109 lf->mode_ref_delta_enabled = vpx_rb_read_bit(rb);
1110 if (lf->mode_ref_delta_enabled) {
1111 lf->mode_ref_delta_update = vpx_rb_read_bit(rb);
1112 if (lf->mode_ref_delta_update) {
1115 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1116 if (vpx_rb_read_bit(rb))
1117 lf->ref_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1119 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1120 if (vpx_rb_read_bit(rb))
1121 lf->mode_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1126 static INLINE int read_delta_q(struct vpx_read_bit_buffer *rb) {
1127 return vpx_rb_read_bit(rb) ? vpx_rb_read_signed_literal(rb, 4) : 0;
1130 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1131 struct vpx_read_bit_buffer *rb) {
1132 cm->base_qindex = vpx_rb_read_literal(rb, QINDEX_BITS);
1133 cm->y_dc_delta_q = read_delta_q(rb);
1134 cm->uv_dc_delta_q = read_delta_q(rb);
1135 cm->uv_ac_delta_q = read_delta_q(rb);
1136 cm->dequant_bit_depth = cm->bit_depth;
1137 xd->lossless = cm->base_qindex == 0 &&
1138 cm->y_dc_delta_q == 0 &&
1139 cm->uv_dc_delta_q == 0 &&
1140 cm->uv_ac_delta_q == 0;
1142 #if CONFIG_VP9_HIGHBITDEPTH
1143 xd->bd = (int)cm->bit_depth;
1147 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1148 // Build y/uv dequant values based on segmentation.
1149 if (cm->seg.enabled) {
1151 for (i = 0; i < MAX_SEGMENTS; ++i) {
1152 const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1153 cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
1155 cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1156 cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1158 cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1162 const int qindex = cm->base_qindex;
1163 // When segmentation is disabled, only the first value is used. The
1164 // remaining are don't cares.
1165 cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1166 cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1167 cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1169 cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1174 static INTERP_FILTER read_interp_filter(struct vpx_read_bit_buffer *rb) {
1175 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1179 return vpx_rb_read_bit(rb) ? SWITCHABLE
1180 : literal_to_filter[vpx_rb_read_literal(rb, 2)];
1183 static void setup_display_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1184 cm->display_width = cm->width;
1185 cm->display_height = cm->height;
1186 if (vpx_rb_read_bit(rb))
1187 vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
1190 static void resize_mv_buffer(VP9_COMMON *cm) {
1191 vpx_free(cm->cur_frame->mvs);
1192 cm->cur_frame->mi_rows = cm->mi_rows;
1193 cm->cur_frame->mi_cols = cm->mi_cols;
1194 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1195 sizeof(*cm->cur_frame->mvs));
1198 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1199 #if CONFIG_SIZE_LIMIT
1200 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1201 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1202 "Dimensions of %dx%d beyond allowed size of %dx%d.",
1203 width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1205 if (cm->width != width || cm->height != height) {
1206 const int new_mi_rows =
1207 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1208 const int new_mi_cols =
1209 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1211 // Allocations in vp9_alloc_context_buffers() depend on individual
1212 // dimensions as well as the overall size.
1213 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1214 if (vp9_alloc_context_buffers(cm, width, height))
1215 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1216 "Failed to allocate context buffers");
1218 vp9_set_mb_mi(cm, width, height);
1220 vp9_init_context_buffers(cm);
1222 cm->height = height;
1224 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1225 cm->mi_cols > cm->cur_frame->mi_cols) {
1226 resize_mv_buffer(cm);
1230 static void setup_frame_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1232 BufferPool *const pool = cm->buffer_pool;
1233 vp9_read_frame_size(rb, &width, &height);
1234 resize_context_buffers(cm, width, height);
1235 setup_display_size(cm, rb);
1237 lock_buffer_pool(pool);
1238 if (vpx_realloc_frame_buffer(
1239 get_frame_new_buffer(cm), cm->width, cm->height,
1240 cm->subsampling_x, cm->subsampling_y,
1241 #if CONFIG_VP9_HIGHBITDEPTH
1242 cm->use_highbitdepth,
1244 VP9_DEC_BORDER_IN_PIXELS,
1246 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1248 unlock_buffer_pool(pool);
1249 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1250 "Failed to allocate frame buffer");
1252 unlock_buffer_pool(pool);
1254 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1255 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1256 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1257 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1260 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1261 int ref_xss, int ref_yss,
1262 vpx_bit_depth_t this_bit_depth,
1263 int this_xss, int this_yss) {
1264 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1265 ref_yss == this_yss;
1268 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1269 struct vpx_read_bit_buffer *rb) {
1272 int has_valid_ref_frame = 0;
1273 BufferPool *const pool = cm->buffer_pool;
1274 for (i = 0; i < REFS_PER_FRAME; ++i) {
1275 if (vpx_rb_read_bit(rb)) {
1276 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1277 width = buf->y_crop_width;
1278 height = buf->y_crop_height;
1285 vp9_read_frame_size(rb, &width, &height);
1287 if (width <= 0 || height <= 0)
1288 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1289 "Invalid frame size");
1291 // Check to make sure at least one of frames that this frame references
1292 // has valid dimensions.
1293 for (i = 0; i < REFS_PER_FRAME; ++i) {
1294 RefBuffer *const ref_frame = &cm->frame_refs[i];
1295 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1296 ref_frame->buf->y_crop_height,
1299 if (!has_valid_ref_frame)
1300 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1301 "Referenced frame has invalid size");
1302 for (i = 0; i < REFS_PER_FRAME; ++i) {
1303 RefBuffer *const ref_frame = &cm->frame_refs[i];
1304 if (!valid_ref_frame_img_fmt(
1305 ref_frame->buf->bit_depth,
1306 ref_frame->buf->subsampling_x,
1307 ref_frame->buf->subsampling_y,
1311 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1312 "Referenced frame has incompatible color format");
1315 resize_context_buffers(cm, width, height);
1316 setup_display_size(cm, rb);
1318 lock_buffer_pool(pool);
1319 if (vpx_realloc_frame_buffer(
1320 get_frame_new_buffer(cm), cm->width, cm->height,
1321 cm->subsampling_x, cm->subsampling_y,
1322 #if CONFIG_VP9_HIGHBITDEPTH
1323 cm->use_highbitdepth,
1325 VP9_DEC_BORDER_IN_PIXELS,
1327 &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1329 unlock_buffer_pool(pool);
1330 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1331 "Failed to allocate frame buffer");
1333 unlock_buffer_pool(pool);
1335 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1336 pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1337 pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1338 pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1341 static void setup_tile_info(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1342 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1343 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1346 max_ones = max_log2_tile_cols - min_log2_tile_cols;
1347 cm->log2_tile_cols = min_log2_tile_cols;
1348 while (max_ones-- && vpx_rb_read_bit(rb))
1349 cm->log2_tile_cols++;
1351 if (cm->log2_tile_cols > 6)
1352 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1353 "Invalid number of tile columns");
1356 cm->log2_tile_rows = vpx_rb_read_bit(rb);
1357 if (cm->log2_tile_rows)
1358 cm->log2_tile_rows += vpx_rb_read_bit(rb);
1361 typedef struct TileBuffer {
1362 const uint8_t *data;
1364 int col; // only used with multi-threaded decoding
1367 // Reads the next tile returning its size and adjusting '*data' accordingly
1368 // based on 'is_last'.
1369 static void get_tile_buffer(const uint8_t *const data_end,
1371 struct vpx_internal_error_info *error_info,
1372 const uint8_t **data,
1373 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1378 if (!read_is_valid(*data, 4, data_end))
1379 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1380 "Truncated packet or corrupt tile length");
1384 decrypt_cb(decrypt_state, *data, be_data, 4);
1385 size = mem_get_be32(be_data);
1387 size = mem_get_be32(*data);
1391 if (size > (size_t)(data_end - *data))
1392 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1393 "Truncated packet or corrupt tile size");
1395 size = data_end - *data;
1404 static void get_tile_buffers(VP9Decoder *pbi,
1405 const uint8_t *data, const uint8_t *data_end,
1406 int tile_cols, int tile_rows,
1407 TileBuffer (*tile_buffers)[1 << 6]) {
1410 for (r = 0; r < tile_rows; ++r) {
1411 for (c = 0; c < tile_cols; ++c) {
1412 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1413 TileBuffer *const buf = &tile_buffers[r][c];
1415 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1416 pbi->decrypt_cb, pbi->decrypt_state, buf);
1421 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1422 const uint8_t *data,
1423 const uint8_t *data_end) {
1424 VP9_COMMON *const cm = &pbi->common;
1425 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1426 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1427 const int tile_cols = 1 << cm->log2_tile_cols;
1428 const int tile_rows = 1 << cm->log2_tile_rows;
1429 TileBuffer tile_buffers[4][1 << 6];
1430 int tile_row, tile_col;
1432 TileData *tile_data = NULL;
1434 if (cm->lf.filter_level && !cm->skip_loop_filter &&
1435 pbi->lf_worker.data1 == NULL) {
1436 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1437 vpx_memalign(32, sizeof(LFWorkerData)));
1438 pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1439 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1440 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1441 "Loop filter thread creation failed");
1445 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1446 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1447 // Be sure to sync as we might be resuming after a failed frame decode.
1448 winterface->sync(&pbi->lf_worker);
1449 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1453 assert(tile_rows <= 4);
1454 assert(tile_cols <= (1 << 6));
1456 // Note: this memset assumes above_context[0], [1] and [2]
1457 // are allocated as part of the same buffer.
1458 memset(cm->above_context, 0,
1459 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1461 memset(cm->above_seg_context, 0,
1462 sizeof(*cm->above_seg_context) * aligned_cols);
1464 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1466 if (pbi->tile_data == NULL ||
1467 (tile_cols * tile_rows) != pbi->total_tiles) {
1468 vpx_free(pbi->tile_data);
1472 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1473 pbi->total_tiles = tile_rows * tile_cols;
1476 // Load all tile information into tile_data.
1477 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1478 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1479 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1480 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1482 tile_data->xd = pbi->mb;
1483 tile_data->xd.corrupted = 0;
1484 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1486 vp9_zero(tile_data->dqcoeff);
1487 vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1488 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1489 &tile_data->bit_reader, pbi->decrypt_cb,
1490 pbi->decrypt_state);
1491 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1495 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1497 vp9_tile_set_row(&tile, cm, tile_row);
1498 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1499 mi_row += MI_BLOCK_SIZE) {
1500 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1501 const int col = pbi->inv_tile_order ?
1502 tile_cols - tile_col - 1 : tile_col;
1503 tile_data = pbi->tile_data + tile_cols * tile_row + col;
1504 vp9_tile_set_col(&tile, tile_data->cm, col);
1505 vp9_zero(tile_data->xd.left_context);
1506 vp9_zero(tile_data->xd.left_seg_context);
1507 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1508 mi_col += MI_BLOCK_SIZE) {
1509 decode_partition(pbi, &tile_data->xd, mi_row,
1510 mi_col, &tile_data->bit_reader, BLOCK_64X64, 4);
1512 pbi->mb.corrupted |= tile_data->xd.corrupted;
1513 if (pbi->mb.corrupted)
1514 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1515 "Failed to decode tile data");
1517 // Loopfilter one row.
1518 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1519 const int lf_start = mi_row - MI_BLOCK_SIZE;
1520 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1522 // delay the loopfilter by 1 macroblock row.
1523 if (lf_start < 0) continue;
1525 // decoding has completed: finish up the loop filter in this thread.
1526 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1528 winterface->sync(&pbi->lf_worker);
1529 lf_data->start = lf_start;
1530 lf_data->stop = mi_row;
1531 if (pbi->max_threads > 1) {
1532 winterface->launch(&pbi->lf_worker);
1534 winterface->execute(&pbi->lf_worker);
1537 // After loopfiltering, the last 7 row pixels in each superblock row may
1538 // still be changed by the longest loopfilter of the next superblock
1540 if (pbi->frame_parallel_decode)
1541 vp9_frameworker_broadcast(pbi->cur_buf,
1542 mi_row << MI_BLOCK_SIZE_LOG2);
1546 // Loopfilter remaining rows in the frame.
1547 if (cm->lf.filter_level && !cm->skip_loop_filter) {
1548 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1549 winterface->sync(&pbi->lf_worker);
1550 lf_data->start = lf_data->stop;
1551 lf_data->stop = cm->mi_rows;
1552 winterface->execute(&pbi->lf_worker);
1555 // Get last tile data.
1556 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1558 if (pbi->frame_parallel_decode)
1559 vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1560 return vpx_reader_find_end(&tile_data->bit_reader);
1563 static int tile_worker_hook(TileWorkerData *const tile_data,
1564 const TileInfo *const tile) {
1567 if (setjmp(tile_data->error_info.jmp)) {
1568 tile_data->error_info.setjmp = 0;
1569 tile_data->xd.corrupted = 1;
1573 tile_data->error_info.setjmp = 1;
1574 tile_data->xd.error_info = &tile_data->error_info;
1576 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1577 mi_row += MI_BLOCK_SIZE) {
1578 vp9_zero(tile_data->xd.left_context);
1579 vp9_zero(tile_data->xd.left_seg_context);
1580 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1581 mi_col += MI_BLOCK_SIZE) {
1582 decode_partition(tile_data->pbi, &tile_data->xd,
1583 mi_row, mi_col, &tile_data->bit_reader,
1587 return !tile_data->xd.corrupted;
1590 // sorts in descending order
1591 static int compare_tile_buffers(const void *a, const void *b) {
1592 const TileBuffer *const buf1 = (const TileBuffer*)a;
1593 const TileBuffer *const buf2 = (const TileBuffer*)b;
1594 return (int)(buf2->size - buf1->size);
1597 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1598 const uint8_t *data,
1599 const uint8_t *data_end) {
1600 VP9_COMMON *const cm = &pbi->common;
1601 const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1602 const uint8_t *bit_reader_end = NULL;
1603 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1604 const int tile_cols = 1 << cm->log2_tile_cols;
1605 const int tile_rows = 1 << cm->log2_tile_rows;
1606 const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1607 TileBuffer tile_buffers[1][1 << 6];
1609 int final_worker = -1;
1611 assert(tile_cols <= (1 << 6));
1612 assert(tile_rows == 1);
1615 // TODO(jzern): See if we can remove the restriction of passing in max
1616 // threads to the decoder.
1617 if (pbi->num_tile_workers == 0) {
1618 const int num_threads = pbi->max_threads & ~1;
1620 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1621 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1622 // Ensure tile data offsets will be properly aligned. This may fail on
1623 // platforms without DECLARE_ALIGNED().
1624 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1625 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1626 vpx_memalign(32, num_threads *
1627 sizeof(*pbi->tile_worker_data)));
1628 CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1629 vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1630 for (i = 0; i < num_threads; ++i) {
1631 VPxWorker *const worker = &pbi->tile_workers[i];
1632 ++pbi->num_tile_workers;
1634 winterface->init(worker);
1635 if (i < num_threads - 1 && !winterface->reset(worker)) {
1636 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1637 "Tile decoder thread creation failed");
1642 // Reset tile decoding hook
1643 for (n = 0; n < num_workers; ++n) {
1644 VPxWorker *const worker = &pbi->tile_workers[n];
1645 winterface->sync(worker);
1646 worker->hook = (VPxWorkerHook)tile_worker_hook;
1647 worker->data1 = &pbi->tile_worker_data[n];
1648 worker->data2 = &pbi->tile_worker_info[n];
1651 // Note: this memset assumes above_context[0], [1] and [2]
1652 // are allocated as part of the same buffer.
1653 memset(cm->above_context, 0,
1654 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1655 memset(cm->above_seg_context, 0,
1656 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1658 // Load tile data into tile_buffers
1659 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1661 // Sort the buffers based on size in descending order.
1662 qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1663 compare_tile_buffers);
1665 // Rearrange the tile buffers such that per-tile group the largest, and
1666 // presumably the most difficult, tile will be decoded in the main thread.
1667 // This should help minimize the number of instances where the main thread is
1668 // waiting for a worker to complete.
1670 int group_start = 0;
1671 while (group_start < tile_cols) {
1672 const TileBuffer largest = tile_buffers[0][group_start];
1673 const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1674 memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1675 (group_end - group_start) * sizeof(tile_buffers[0][0]));
1676 tile_buffers[0][group_end] = largest;
1677 group_start = group_end + 1;
1681 // Initialize thread frame counts.
1682 if (!cm->frame_parallel_decoding_mode) {
1685 for (i = 0; i < num_workers; ++i) {
1686 TileWorkerData *const tile_data =
1687 (TileWorkerData*)pbi->tile_workers[i].data1;
1688 vp9_zero(tile_data->counts);
1693 while (n < tile_cols) {
1695 for (i = 0; i < num_workers && n < tile_cols; ++i) {
1696 VPxWorker *const worker = &pbi->tile_workers[i];
1697 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1698 TileInfo *const tile = (TileInfo*)worker->data2;
1699 TileBuffer *const buf = &tile_buffers[0][n];
1701 tile_data->pbi = pbi;
1702 tile_data->xd = pbi->mb;
1703 tile_data->xd.corrupted = 0;
1704 tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1705 0 : &tile_data->counts;
1706 vp9_zero(tile_data->dqcoeff);
1707 vp9_tile_init(tile, cm, 0, buf->col);
1708 vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1709 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1710 &tile_data->bit_reader, pbi->decrypt_cb,
1711 pbi->decrypt_state);
1712 vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1714 worker->had_error = 0;
1715 if (i == num_workers - 1 || n == tile_cols - 1) {
1716 winterface->execute(worker);
1718 winterface->launch(worker);
1721 if (buf->col == tile_cols - 1) {
1728 for (; i > 0; --i) {
1729 VPxWorker *const worker = &pbi->tile_workers[i - 1];
1730 // TODO(jzern): The tile may have specific error data associated with
1731 // its vpx_internal_error_info which could be propagated to the main info
1732 // in cm. Additionally once the threads have been synced and an error is
1733 // detected, there's no point in continuing to decode tiles.
1734 pbi->mb.corrupted |= !winterface->sync(worker);
1736 if (final_worker > -1) {
1737 TileWorkerData *const tile_data =
1738 (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1739 bit_reader_end = vpx_reader_find_end(&tile_data->bit_reader);
1743 // Accumulate thread frame counts.
1744 if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1745 for (i = 0; i < num_workers; ++i) {
1746 TileWorkerData *const tile_data =
1747 (TileWorkerData*)pbi->tile_workers[i].data1;
1748 vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1753 return bit_reader_end;
1756 static void error_handler(void *data) {
1757 VP9_COMMON *const cm = (VP9_COMMON *)data;
1758 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1761 static void read_bitdepth_colorspace_sampling(
1762 VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1763 if (cm->profile >= PROFILE_2) {
1764 cm->bit_depth = vpx_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1765 #if CONFIG_VP9_HIGHBITDEPTH
1766 cm->use_highbitdepth = 1;
1769 cm->bit_depth = VPX_BITS_8;
1770 #if CONFIG_VP9_HIGHBITDEPTH
1771 cm->use_highbitdepth = 0;
1774 cm->color_space = vpx_rb_read_literal(rb, 3);
1775 if (cm->color_space != VPX_CS_SRGB) {
1776 vpx_rb_read_bit(rb); // [16,235] (including xvycc) vs [0,255] range
1777 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1778 cm->subsampling_x = vpx_rb_read_bit(rb);
1779 cm->subsampling_y = vpx_rb_read_bit(rb);
1780 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1781 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1782 "4:2:0 color not supported in profile 1 or 3");
1783 if (vpx_rb_read_bit(rb))
1784 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1785 "Reserved bit set");
1787 cm->subsampling_y = cm->subsampling_x = 1;
1790 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1791 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1792 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1793 cm->subsampling_y = cm->subsampling_x = 0;
1794 if (vpx_rb_read_bit(rb))
1795 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1796 "Reserved bit set");
1798 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1799 "4:4:4 color not supported in profile 0 or 2");
1804 static size_t read_uncompressed_header(VP9Decoder *pbi,
1805 struct vpx_read_bit_buffer *rb) {
1806 VP9_COMMON *const cm = &pbi->common;
1807 BufferPool *const pool = cm->buffer_pool;
1808 RefCntBuffer *const frame_bufs = pool->frame_bufs;
1809 int i, mask, ref_index = 0;
1812 cm->last_frame_type = cm->frame_type;
1813 cm->last_intra_only = cm->intra_only;
1815 if (vpx_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1816 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1817 "Invalid frame marker");
1819 cm->profile = vp9_read_profile(rb);
1820 #if CONFIG_VP9_HIGHBITDEPTH
1821 if (cm->profile >= MAX_PROFILES)
1822 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1823 "Unsupported bitstream profile");
1825 if (cm->profile >= PROFILE_2)
1826 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1827 "Unsupported bitstream profile");
1830 cm->show_existing_frame = vpx_rb_read_bit(rb);
1831 if (cm->show_existing_frame) {
1832 // Show an existing frame directly.
1833 const int frame_to_show = cm->ref_frame_map[vpx_rb_read_literal(rb, 3)];
1834 lock_buffer_pool(pool);
1835 if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1836 unlock_buffer_pool(pool);
1837 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1838 "Buffer %d does not contain a decoded frame",
1842 ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1843 unlock_buffer_pool(pool);
1844 pbi->refresh_frame_flags = 0;
1845 cm->lf.filter_level = 0;
1848 if (pbi->frame_parallel_decode) {
1849 for (i = 0; i < REF_FRAMES; ++i)
1850 cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1855 cm->frame_type = (FRAME_TYPE) vpx_rb_read_bit(rb);
1856 cm->show_frame = vpx_rb_read_bit(rb);
1857 cm->error_resilient_mode = vpx_rb_read_bit(rb);
1859 if (cm->frame_type == KEY_FRAME) {
1860 if (!vp9_read_sync_code(rb))
1861 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1862 "Invalid frame sync code");
1864 read_bitdepth_colorspace_sampling(cm, rb);
1865 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1867 for (i = 0; i < REFS_PER_FRAME; ++i) {
1868 cm->frame_refs[i].idx = INVALID_IDX;
1869 cm->frame_refs[i].buf = NULL;
1872 setup_frame_size(cm, rb);
1873 if (pbi->need_resync) {
1874 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1875 pbi->need_resync = 0;
1878 cm->intra_only = cm->show_frame ? 0 : vpx_rb_read_bit(rb);
1880 cm->reset_frame_context = cm->error_resilient_mode ?
1881 0 : vpx_rb_read_literal(rb, 2);
1883 if (cm->intra_only) {
1884 if (!vp9_read_sync_code(rb))
1885 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1886 "Invalid frame sync code");
1887 if (cm->profile > PROFILE_0) {
1888 read_bitdepth_colorspace_sampling(cm, rb);
1890 // NOTE: The intra-only frame header does not include the specification
1891 // of either the color format or color sub-sampling in profile 0. VP9
1892 // specifies that the default color format should be YUV 4:2:0 in this
1893 // case (normative).
1894 cm->color_space = VPX_CS_BT_601;
1895 cm->subsampling_y = cm->subsampling_x = 1;
1896 cm->bit_depth = VPX_BITS_8;
1897 #if CONFIG_VP9_HIGHBITDEPTH
1898 cm->use_highbitdepth = 0;
1902 pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1903 setup_frame_size(cm, rb);
1904 if (pbi->need_resync) {
1905 memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1906 pbi->need_resync = 0;
1908 } else if (pbi->need_resync != 1) { /* Skip if need resync */
1909 pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1910 for (i = 0; i < REFS_PER_FRAME; ++i) {
1911 const int ref = vpx_rb_read_literal(rb, REF_FRAMES_LOG2);
1912 const int idx = cm->ref_frame_map[ref];
1913 RefBuffer *const ref_frame = &cm->frame_refs[i];
1914 ref_frame->idx = idx;
1915 ref_frame->buf = &frame_bufs[idx].buf;
1916 cm->ref_frame_sign_bias[LAST_FRAME + i] = vpx_rb_read_bit(rb);
1919 setup_frame_size_with_refs(cm, rb);
1921 cm->allow_high_precision_mv = vpx_rb_read_bit(rb);
1922 cm->interp_filter = read_interp_filter(rb);
1924 for (i = 0; i < REFS_PER_FRAME; ++i) {
1925 RefBuffer *const ref_buf = &cm->frame_refs[i];
1926 #if CONFIG_VP9_HIGHBITDEPTH
1927 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1928 ref_buf->buf->y_crop_width,
1929 ref_buf->buf->y_crop_height,
1930 cm->width, cm->height,
1931 cm->use_highbitdepth);
1933 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1934 ref_buf->buf->y_crop_width,
1935 ref_buf->buf->y_crop_height,
1936 cm->width, cm->height);
1941 #if CONFIG_VP9_HIGHBITDEPTH
1942 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1944 get_frame_new_buffer(cm)->color_space = cm->color_space;
1946 if (pbi->need_resync) {
1947 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1948 "Keyframe / intra-only frame required to reset decoder"
1952 if (!cm->error_resilient_mode) {
1953 cm->refresh_frame_context = vpx_rb_read_bit(rb);
1954 cm->frame_parallel_decoding_mode = vpx_rb_read_bit(rb);
1956 cm->refresh_frame_context = 0;
1957 cm->frame_parallel_decoding_mode = 1;
1960 // This flag will be overridden by the call to vp9_setup_past_independence
1961 // below, forcing the use of context 0 for those frame types.
1962 cm->frame_context_idx = vpx_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1964 // Generate next_ref_frame_map.
1965 lock_buffer_pool(pool);
1966 for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1968 cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1969 ++frame_bufs[cm->new_fb_idx].ref_count;
1971 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1973 // Current thread holds the reference frame.
1974 if (cm->ref_frame_map[ref_index] >= 0)
1975 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1979 for (; ref_index < REF_FRAMES; ++ref_index) {
1980 cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1981 // Current thread holds the reference frame.
1982 if (cm->ref_frame_map[ref_index] >= 0)
1983 ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1985 unlock_buffer_pool(pool);
1986 pbi->hold_ref_buf = 1;
1988 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1989 vp9_setup_past_independence(cm);
1991 setup_loopfilter(&cm->lf, rb);
1992 setup_quantization(cm, &pbi->mb, rb);
1993 setup_segmentation(&cm->seg, rb);
1994 setup_segmentation_dequant(cm);
1996 setup_tile_info(cm, rb);
1997 sz = vpx_rb_read_literal(rb, 16);
2000 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2001 "Invalid header size");
2006 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
2007 size_t partition_size) {
2008 VP9_COMMON *const cm = &pbi->common;
2009 MACROBLOCKD *const xd = &pbi->mb;
2010 FRAME_CONTEXT *const fc = cm->fc;
2014 if (vpx_reader_init(&r, data, partition_size, pbi->decrypt_cb,
2015 pbi->decrypt_state))
2016 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2017 "Failed to allocate bool decoder 0");
2019 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
2020 if (cm->tx_mode == TX_MODE_SELECT)
2021 read_tx_mode_probs(&fc->tx_probs, &r);
2022 read_coef_probs(fc, cm->tx_mode, &r);
2024 for (k = 0; k < SKIP_CONTEXTS; ++k)
2025 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
2027 if (!frame_is_intra_only(cm)) {
2028 nmv_context *const nmvc = &fc->nmvc;
2031 read_inter_mode_probs(fc, &r);
2033 if (cm->interp_filter == SWITCHABLE)
2034 read_switchable_interp_probs(fc, &r);
2036 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
2037 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
2039 cm->reference_mode = read_frame_reference_mode(cm, &r);
2040 if (cm->reference_mode != SINGLE_REFERENCE)
2041 setup_compound_reference_mode(cm);
2042 read_frame_reference_mode_probs(cm, &r);
2044 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
2045 for (i = 0; i < INTRA_MODES - 1; ++i)
2046 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
2048 for (j = 0; j < PARTITION_CONTEXTS; ++j)
2049 for (i = 0; i < PARTITION_TYPES - 1; ++i)
2050 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
2052 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2055 return vpx_reader_has_error(&r);
2059 #define debug_check_frame_counts(cm) (void)0
2061 // Counts should only be incremented when frame_parallel_decoding_mode and
2062 // error_resilient_mode are disabled.
2063 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
2064 FRAME_COUNTS zero_counts;
2065 vp9_zero(zero_counts);
2066 assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
2067 assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
2068 sizeof(cm->counts.y_mode)));
2069 assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
2070 sizeof(cm->counts.uv_mode)));
2071 assert(!memcmp(cm->counts.partition, zero_counts.partition,
2072 sizeof(cm->counts.partition)));
2073 assert(!memcmp(cm->counts.coef, zero_counts.coef,
2074 sizeof(cm->counts.coef)));
2075 assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
2076 sizeof(cm->counts.eob_branch)));
2077 assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
2078 sizeof(cm->counts.switchable_interp)));
2079 assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
2080 sizeof(cm->counts.inter_mode)));
2081 assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
2082 sizeof(cm->counts.intra_inter)));
2083 assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
2084 sizeof(cm->counts.comp_inter)));
2085 assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
2086 sizeof(cm->counts.single_ref)));
2087 assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
2088 sizeof(cm->counts.comp_ref)));
2089 assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
2090 assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
2091 assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
2095 static struct vpx_read_bit_buffer *init_read_bit_buffer(
2097 struct vpx_read_bit_buffer *rb,
2098 const uint8_t *data,
2099 const uint8_t *data_end,
2100 uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2102 rb->error_handler = error_handler;
2103 rb->error_handler_data = &pbi->common;
2104 if (pbi->decrypt_cb) {
2105 const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
2106 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2107 rb->bit_buffer = clear_data;
2108 rb->bit_buffer_end = clear_data + n;
2110 rb->bit_buffer = data;
2111 rb->bit_buffer_end = data_end;
2116 //------------------------------------------------------------------------------
2118 int vp9_read_sync_code(struct vpx_read_bit_buffer *const rb) {
2119 return vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2120 vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2121 vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2124 void vp9_read_frame_size(struct vpx_read_bit_buffer *rb,
2125 int *width, int *height) {
2126 *width = vpx_rb_read_literal(rb, 16) + 1;
2127 *height = vpx_rb_read_literal(rb, 16) + 1;
2130 BITSTREAM_PROFILE vp9_read_profile(struct vpx_read_bit_buffer *rb) {
2131 int profile = vpx_rb_read_bit(rb);
2132 profile |= vpx_rb_read_bit(rb) << 1;
2134 profile += vpx_rb_read_bit(rb);
2135 return (BITSTREAM_PROFILE) profile;
2138 void vp9_decode_frame(VP9Decoder *pbi,
2139 const uint8_t *data, const uint8_t *data_end,
2140 const uint8_t **p_data_end) {
2141 VP9_COMMON *const cm = &pbi->common;
2142 MACROBLOCKD *const xd = &pbi->mb;
2143 struct vpx_read_bit_buffer rb;
2144 int context_updated = 0;
2145 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2146 const size_t first_partition_size = read_uncompressed_header(pbi,
2147 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2148 const int tile_rows = 1 << cm->log2_tile_rows;
2149 const int tile_cols = 1 << cm->log2_tile_cols;
2150 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2151 xd->cur_buf = new_fb;
2153 if (!first_partition_size) {
2154 // showing a frame directly
2155 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2159 data += vpx_rb_bytes_read(&rb);
2160 if (!read_is_valid(data, first_partition_size, data_end))
2161 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2162 "Truncated packet or corrupt header length");
2164 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2165 cm->width == cm->last_width &&
2166 cm->height == cm->last_height &&
2167 !cm->last_intra_only &&
2168 cm->last_show_frame &&
2169 (cm->last_frame_type != KEY_FRAME);
2171 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2173 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2174 if (!cm->fc->initialized)
2175 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2176 "Uninitialized entropy context.");
2178 vp9_zero(cm->counts);
2181 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2182 if (new_fb->corrupted)
2183 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2184 "Decode failed. Frame data header is corrupted.");
2186 if (cm->lf.filter_level && !cm->skip_loop_filter) {
2187 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2190 // If encoded in frame parallel mode, frame context is ready after decoding
2191 // the frame header.
2192 if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2193 VPxWorker *const worker = pbi->frame_worker_owner;
2194 FrameWorkerData *const frame_worker_data = worker->data1;
2195 if (cm->refresh_frame_context) {
2196 context_updated = 1;
2197 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2199 vp9_frameworker_lock_stats(worker);
2200 pbi->cur_buf->row = -1;
2201 pbi->cur_buf->col = -1;
2202 frame_worker_data->frame_context_ready = 1;
2203 // Signal the main thread that context is ready.
2204 vp9_frameworker_signal_stats(worker);
2205 vp9_frameworker_unlock_stats(worker);
2208 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2209 // Multi-threaded tile decoder
2210 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2211 if (!xd->corrupted) {
2212 if (!cm->skip_loop_filter) {
2213 // If multiple threads are used to decode tiles, then we use those
2214 // threads to do parallel loopfiltering.
2215 vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2216 cm->lf.filter_level, 0, 0, pbi->tile_workers,
2217 pbi->num_tile_workers, &pbi->lf_row_sync);
2220 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2221 "Decode failed. Frame data is corrupted.");
2224 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2227 if (!xd->corrupted) {
2228 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2229 vp9_adapt_coef_probs(cm);
2231 if (!frame_is_intra_only(cm)) {
2232 vp9_adapt_mode_probs(cm);
2233 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2236 debug_check_frame_counts(cm);
2239 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2240 "Decode failed. Frame data is corrupted.");
2243 // Non frame parallel update frame context here.
2244 if (cm->refresh_frame_context && !context_updated)
2245 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;