/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree.
*/
#if !CONFIG_REALTIME_ONLY // Planewise build inter prediction and compute rdcost with early termination // option staticint build_inter_pred_model_rd_earlyterm(
VP9_COMP *cpi, int mi_row, int mi_col, BLOCK_SIZE bsize, MACROBLOCK *x,
MACROBLOCKD *xd, int *out_rate_sum, int64_t *out_dist_sum, int *skip_txfm_sb, int64_t *skip_sse_sb, int do_earlyterm,
int64_t best_rd) { // Note our transform coeffs are 8 times an orthogonal transform. // Hence quantizer step is also 8 times. To get effective quantizer // we need to divide by 8 before sending to modeling function. int i;
int64_t rate_sum = 0;
int64_t dist_sum = 0; constint ref = xd->mi[0]->ref_frame[0]; unsignedint sse; unsignedint var = 0;
int64_t total_sse = 0; int skip_flag = 1; constint shift = 6; constint dequant_shift = #if CONFIG_VP9_HIGHBITDEPTH
(xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd - 5 : #endif// CONFIG_VP9_HIGHBITDEPTH
3;
x->pred_sse[ref] = 0;
// Build prediction signal, compute stats and RD cost on per-plane basis for (i = 0; i < MAX_MB_PLANE; ++i) { struct macroblock_plane *const p = &x->plane[i]; struct macroblockd_plane *const pd = &xd->plane[i]; const BLOCK_SIZE bs = get_plane_block_size(bsize, pd); const TX_SIZE max_tx_size = max_txsize_lookup[bs]; const BLOCK_SIZE unit_size = txsize_to_bsize[max_tx_size]; const int64_t dc_thr = p->quant_thred[0] >> shift; const int64_t ac_thr = p->quant_thred[1] >> shift; unsignedint sum_sse = 0; // The low thresholds are used to measure if the prediction errors are // low enough so that we can skip the mode search. const int64_t low_dc_thr = VPXMIN(50, dc_thr >> 2); const int64_t low_ac_thr = VPXMIN(80, ac_thr >> 2); int bw = 1 << (b_width_log2_lookup[bs] - b_width_log2_lookup[unit_size]); int bh = 1 << (b_height_log2_lookup[bs] - b_width_log2_lookup[unit_size]); int idx, idy; int lw = b_width_log2_lookup[unit_size] + 2; int lh = b_height_log2_lookup[unit_size] + 2; unsignedint qstep; unsignedint nlog2;
int64_t dist = 0;
// Build inter predictor
vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, i);
x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_NONE; if (!x->select_tx_size) { // Check if all ac coefficients can be quantized to zero. if (var < ac_thr || var == 0) {
x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_ONLY;
// Check if dc coefficient can be quantized to zero. if (sse - var < dc_thr || sse == var) {
x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_DC;
if (!sse || (var < low_ac_thr && sse - var < low_dc_thr))
low_err_skip = 1;
}
}
}
for (i = 0; i < block_size; i++) { constint diff = coeff[i] - dqcoeff[i];
error += diff * diff;
sqcoeff += coeff[i] * coeff[i];
}
*ssz = sqcoeff; return error;
}
int64_t vp9_block_error_fp_c(const tran_low_t *coeff, const tran_low_t *dqcoeff, int block_size) { int i;
int64_t error = 0;
for (i = 0; i < block_size; i++) { constint diff = coeff[i] - dqcoeff[i];
error += diff * diff;
}
return error;
}
/* The trailing '0' is a terminator which is used inside cost_coeffs() to * decide whether to include cost of a trailing EOB node or not (i.e. we * can skip this if the last coefficient in this transform block, e.g. the * 16th coefficient in a 4x4 block or the 64th coefficient in a 8x8 block,
* were non-zero). */ staticconst int16_t band_counts[TX_SIZES][8] = {
{ 1, 2, 3, 4, 3, 16 - 13, 0 },
{ 1, 2, 3, 4, 11, 64 - 21, 0 },
{ 1, 2, 3, 4, 11, 256 - 21, 0 },
{ 1, 2, 3, 4, 11, 1024 - 21, 0 },
}; staticint cost_coeffs(MACROBLOCK *x, int plane, int block, TX_SIZE tx_size, int pt, const int16_t *scan, const int16_t *nb, int use_fast_coef_costing) {
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *mi = xd->mi[0]; conststruct macroblock_plane *p = &x->plane[plane]; const PLANE_TYPE type = get_plane_type(plane); const int16_t *band_count = &band_counts[tx_size][1]; constint eob = p->eobs[block]; const tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block); unsignedint(*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
x->token_costs[tx_size][type][is_inter_block(mi)];
uint8_t token_cache[32 * 32]; int cost; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *cat6_high_cost = vp9_get_high_cost_table(xd->bd); #else const uint16_t *cat6_high_cost = vp9_get_high_cost_table(8); #endif
// Check for consistency of tx_size with mode info
assert(type == PLANE_TYPE_Y
? mi->tx_size == tx_size
: get_uv_tx_size(mi, &xd->plane[plane]) == tx_size);
if (eob == 0) { // single eob token
cost = token_costs[0][0][pt][EOB_TOKEN];
} else { if (use_fast_coef_costing) { int band_left = *band_count++; int c;
// dc token int v = qcoeff[0];
int16_t prev_t;
cost = vp9_get_token_cost(v, &prev_t, cat6_high_cost);
cost += (*token_costs)[0][pt][prev_t];
// This reduces the risk of bad perceptual quality due to bad prediction. // We always force the encoder to perform transform and quantization. if (!args->cpi->sf.allow_skip_txfm_ac_dc &&
skip_txfm_flag == SKIP_TXFM_AC_DC) {
skip_txfm_flag = SKIP_TXFM_NONE;
}
#if CONFIG_VP9_HIGHBITDEPTH if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) { for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
int64_t this_rd; int ratey = 0;
int64_t distortion = 0; int rate = bmode_costs[mode];
if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
// Only do the oblique modes if the best so far is // one of the neighboring directional modes if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) { if (conditional_skipintra(mode, *best_mode)) continue;
}
memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
int64_t this_rd; int ratey = 0;
int64_t distortion = 0; int rate = bmode_costs[mode];
if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
// Only do the oblique modes if the best so far is // one of the neighboring directional modes if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) { if (conditional_skipintra(mode, *best_mode)) continue;
}
memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
// This function is used only for intra_only frames static int64_t rd_pick_intra_sby_mode(VP9_COMP *cpi, MACROBLOCK *x, int *rate, int *rate_tokenonly, int64_t *distortion, int *skippable, BLOCK_SIZE bsize,
int64_t best_rd) {
PREDICTION_MODE mode;
PREDICTION_MODE mode_selected = DC_PRED;
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mic = xd->mi[0]; int this_rate, this_rate_tokenonly, s;
int64_t this_distortion, this_rd;
TX_SIZE best_tx = TX_4X4; int *bmode_costs; const MODE_INFO *above_mi = xd->above_mi; const MODE_INFO *left_mi = xd->left_mi; const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0); const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
bmode_costs = cpi->y_mode_costs[A][L];
memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm)); /* Y Search for intra prediction mode */ for (mode = DC_PRED; mode <= TM_PRED; mode++) { if (cpi->sf.use_nonrd_pick_mode) { // These speed features are turned on in hybrid non-RD and RD mode // for key frame coding in the context of real-time setting. if (conditional_skipintra(mode, mode_selected)) continue; if (*skippable) break;
}
staticvoid choose_intra_uv_mode(VP9_COMP *cpi, MACROBLOCK *const x,
PICK_MODE_CONTEXT *ctx, BLOCK_SIZE bsize,
TX_SIZE max_tx_size, int *rate_uv, int *rate_uv_tokenonly, int64_t *dist_uv, int *skip_uv, PREDICTION_MODE *mode_uv) { // Use an estimated rd for uv_intra based on DC_PRED if the // appropriate speed flag is set. if (cpi->sf.use_uv_intra_rd_estimate) {
rd_sbuv_dcpred(cpi, x, rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize); // Else do a proper rd search for each possible transform size that may // be considered in the main rd loop.
} else {
rd_pick_intra_sbuv_mode(cpi, x, ctx, rate_uv, rate_uv_tokenonly, dist_uv,
skip_uv, bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
max_tx_size);
}
*mode_uv = x->e_mbd.mi[0]->uv_mode;
}
// Check if NEARESTMV/NEARMV/ZEROMV is the cheapest way encode zero motion. // TODO(aconverse): Find out if this is still productive then clean up or remove staticint check_best_zero_mv(const VP9_COMP *cpi, const uint8_t mode_context[MAX_REF_FRAMES],
int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES], int this_mode, const MV_REFERENCE_FRAME ref_frames[2]) { if ((this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
frame_mv[this_mode][ref_frames[0]].as_int == 0 &&
(ref_frames[1] == NO_REF_FRAME ||
frame_mv[this_mode][ref_frames[1]].as_int == 0)) { int rfc = mode_context[ref_frames[0]]; int c1 = cost_mv_ref(cpi, NEARMV, rfc); int c2 = cost_mv_ref(cpi, NEARESTMV, rfc); int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
// Compares motion vector and mode rate of current mode and given mode. staticINLINEint compare_mv_mode_rate(MV this_mv, MV mode_mv, int this_mode_rate, int mode_rate, int mv_thresh) { constint mv_diff =
abs(mode_mv.col - this_mv.col) + abs(mode_mv.row - this_mv.row); if (mv_diff <= mv_thresh && mode_rate < this_mode_rate) return 1; return 0;
}
// Skips single reference inter modes NEARMV and ZEROMV based on motion vector // difference and mode rate. staticINLINEint skip_single_mode_based_on_mode_rate(
int_mv (*mode_mv)[MAX_REF_FRAMES], int *single_mode_rate, int this_mode, int ref0, int this_mode_rate, int best_mode_index) {
MV this_mv = mode_mv[this_mode][ref0].as_mv; constint mv_thresh = 3;
// Pruning is not applicable for NEARESTMV or NEWMV modes. if (this_mode == NEARESTMV || this_mode == NEWMV) return 0; // Pruning is not done when reference frame of the mode is same as best // reference so far. if (best_mode_index > 0 &&
ref0 == vp9_mode_order[best_mode_index].ref_frame[0]) return 0;
// Check absolute mv difference and mode rate of current mode w.r.t NEARESTMV if (compare_mv_mode_rate(
this_mv, mode_mv[NEARESTMV][ref0].as_mv, this_mode_rate,
single_mode_rate[INTER_OFFSET(NEARESTMV)], mv_thresh)) return 1;
// Check absolute mv difference and mode rate of current mode w.r.t NEWMV if (compare_mv_mode_rate(this_mv, mode_mv[NEWMV][ref0].as_mv, this_mode_rate,
single_mode_rate[INTER_OFFSET(NEWMV)], mv_thresh)) return 1;
// Pruning w.r.t NEARMV is applicable only for ZEROMV mode if (this_mode == NEARMV) return 0; // Check absolute mv difference and mode rate of current mode w.r.t NEARMV if (compare_mv_mode_rate(this_mv, mode_mv[NEARMV][ref0].as_mv, this_mode_rate,
single_mode_rate[INTER_OFFSET(NEARMV)], mv_thresh)) return 1; return 0;
}
if (scaled_ref_frame[ref]) { int i; // Swap out the reference frame for a version that's been scaled to // match the resolution of the current frame, allowing the existing // motion search code to be used without additional modifications. for (i = 0; i < MAX_MB_PLANE; i++)
backup_yv12[ref][i] = xd->plane[i].pre[ref];
vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
NULL);
}
// Since we have scaled the reference frames to match the size of the current // frame we must use a unit scaling factor during mode selection. #if CONFIG_VP9_HIGHBITDEPTH
vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
cm->height, cm->use_highbitdepth); #else
vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
cm->height); #endif// CONFIG_VP9_HIGHBITDEPTH
// Allow joint search multiple times iteratively for each reference frame // and break out of the search loop if it couldn't find a better mv. for (ite = 0; ite < num_iters; ite++) { struct buf_2d ref_yv12[2];
uint32_t bestsme = UINT_MAX; int sadpb = x->sadperbit16;
MV tmp_mv; int search_range = 3;
const MvLimits tmp_mv_limits = x->mv_limits; int id = ite % 2; // Even iterations search in the first reference frame, // odd iterations search in the second. The predictor // found for the 'other' reference frame is factored in.
// Skip further iterations of search if in the previous iteration, the // motion vector of the searched ref frame is unchanged, and the other ref // frame's full-pixel mv is unchanged. if (skip_iters(iter_mvs, ite, id)) break;
// Initialized here because of compiler problem in Visual Studio.
ref_yv12[0] = xd->plane[0].pre[0];
ref_yv12[1] = xd->plane[0].pre[1];
// Do compound motion search on the current reference frame. if (id) xd->plane[0].pre[0] = ref_yv12[id];
vp9_set_mv_search_range(&x->mv_limits, &ref_mv[id].as_mv);
// Use the mv result from the single mode as mv predictor.
tmp_mv = frame_mv[refs[id]].as_mv;
for (ref = 0; ref < 2; ++ref) { if (scaled_ref_frame[ref]) { // Restore the prediction frame pointers to their unscaled versions. int i; for (i = 0; i < MAX_MB_PLANE; i++)
xd->plane[i].pre[ref] = backup_yv12[ref][i];
}
// 64 makes this threshold really big effectively // making it so that we very rarely check mvs on // segments. setting this to 1 would make mv thresh // roughly equal to what it is for macroblocks
label_mv_thresh = 1 * bsi->mvthresh / label_count;
// Segmentation method overheads for (idy = 0; idy < 2; idy += num_4x4_blocks_high) { for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) { // TODO(jingning,rbultje): rewrite the rate-distortion optimization // loop for 4x4/4x8/8x4 block coding. to be replaced with new rd loop
int_mv mode_mv[MB_MODE_COUNT][2];
int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
PREDICTION_MODE mode_selected = ZEROMV;
int64_t best_rd = INT64_MAX; constint block = idy * 2 + idx; int ref;
// search for the best motion vector on this segment for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) { conststruct buf_2d orig_src = x->plane[0].src; struct buf_2d orig_pre[2];
// motion search for newmv (single predictor case only) if (!has_second_rf && this_mode == NEWMV &&
seg_mvs[block][mi->ref_frame[0]].as_int == INVALID_MV) {
MV *const new_mv = &mode_mv[NEWMV][0].as_mv; int step_param = 0;
uint32_t bestsme = UINT_MAX; int sadpb = x->sadperbit4;
MV mvp_full; int max_mv; int cost_list[5]; const MvLimits tmp_mv_limits = x->mv_limits;
/* Is the best so far sufficiently good that we can't justify doing
* and new motion search. */ if (best_rd < label_mv_thresh) break;
if (cpi->oxcf.mode != BEST) { // use previous block's result as next block's MV predictor. if (block > 0) {
bsi->mvp.as_int = mi->bmi[block - 1].as_mv[0].as_int; if (block == 2)
bsi->mvp.as_int = mi->bmi[block - 2].as_mv[0].as_int;
}
} if (block == 0)
max_mv = x->max_mv_context[mi->ref_frame[0]]; else
max_mv =
VPXMAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
if (sf->mv.auto_mv_step_size && cm->show_frame) { // Take wtd average of the step_params based on the last frame's // max mv magnitude and the best ref mvs of the current block for // the given reference.
step_param =
(vp9_init_search_range(max_mv) + cpi->mv_step_param) / 2;
} else {
step_param = cpi->mv_step_param;
}
// update the coding decisions for (k = 0; k < 4; ++k) bsi->modes[k] = mi->bmi[k].as_mode;
if (bsi->segment_rd > best_rd_so_far) return INT64_MAX; /* set it to the best */ for (i = 0; i < 4; i++) {
mode_idx = INTER_OFFSET(bsi->modes[i]);
mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int; if (has_second_ref(mi))
mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
mi->bmi[i].as_mode = bsi->modes[i];
}
/* * used to set mbmi->mv.as_int
*/
*returntotrate = bsi->r;
*returndistortion = bsi->d;
*returnyrate = bsi->segment_yrate;
*skippable = vp9_is_skippable_in_plane(x, BLOCK_8X8, 0);
*psse = bsi->sse;
mi->mode = bsi->modes[3];
staticvoid store_coding_context(
MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int mode_index,
int64_t comp_pred_diff[REFERENCE_MODES],
int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS], int skippable) {
MACROBLOCKD *const xd = &x->e_mbd;
// Take a snapshot of the coding context so it can be // restored if we decide to encode this way
ctx->skip = x->skip;
ctx->skippable = skippable;
ctx->best_mode_index = mode_index;
ctx->mic = *xd->mi[0];
ctx->mbmi_ext = *x->mbmi_ext;
ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
ctx->comp_pred_diff = (int)comp_pred_diff[COMPOUND_REFERENCE];
ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
// TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this // use the UV scaling factors.
vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
// Gets an initial list of candidate vectors from neighbours and orders them
vp9_find_mv_refs(cm, xd, mi, ref_frame, candidates, mi_row, mi_col,
mbmi_ext->mode_context);
// Candidate refinement carried out at encoder and decoder
vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
&frame_nearest_mv[ref_frame],
&frame_near_mv[ref_frame]);
// Further refinement that is encode side only to test the top few candidates // in full and choose the best as the centre point for subsequent searches. // The current implementation doesn't support scaling. if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
block_size);
}
if (scaled_ref_frame) { int i; // Swap out the reference frame for a version that's been scaled to // match the resolution of the current frame, allowing the existing // motion search code to be used without additional modifications. for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
// Work out the size of the first step in the mv step search. // 0 here is maximum length first step. 1 is VPXMAX >> 1 etc. if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) { // Take wtd average of the step_params based on the last frame's // max mv magnitude and that based on the best ref mvs of the current // block for the given reference.
step_param =
(vp9_init_search_range(x->max_mv_context[ref]) + cpi->mv_step_param) /
2;
} else {
step_param = cpi->mv_step_param;
}
if (cpi->sf.adaptive_motion_search) { int bwl = b_width_log2_lookup[bsize]; int bhl = b_height_log2_lookup[bsize]; int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
if (tlevel < 5) step_param += 2;
// prev_mv_sad is not setup for dynamically scaled frames. if (cpi->oxcf.resize_mode != RESIZE_DYNAMIC) { int i; for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) { if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
x->pred_mv[ref].row = INT16_MAX;
x->pred_mv[ref].col = INT16_MAX;
tmp_mv->as_int = INVALID_MV;
if (scaled_ref_frame) { int j; for (j = 0; j < MAX_MB_PLANE; ++j)
xd->plane[j].pre[0] = backup_yv12[j];
} return;
}
}
}
}
// Note: MV limits are modified here. Always restore the original values // after full-pixel motion search.
vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
if (scaled_ref_frame) { int i; for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
}
}
staticINLINEvoid restore_dst_buf(MACROBLOCKD *xd,
uint8_t *orig_dst[MAX_MB_PLANE], int orig_dst_stride[MAX_MB_PLANE]) { int i; for (i = 0; i < MAX_MB_PLANE; i++) {
xd->plane[i].dst.buf = orig_dst[i];
xd->plane[i].dst.stride = orig_dst_stride[i];
}
}
// In some situations we want to discount tha pparent cost of a new motion // vector. Where there is a subtle motion field and especially where there is // low spatial complexity then it can be hard to cover the cost of a new motion // vector in a single block, even if that motion vector reduces distortion. // However, once established that vector may be usable through the nearest and // near mv modes to reduce distortion in subsequent blocks and also improve // visual quality. staticint discount_newmv_test(VP9_COMP *cpi, int this_mode, int_mv this_mv,
int_mv (*mode_mv)[MAX_REF_FRAMES], int ref_frame, int mi_row, int mi_col, BLOCK_SIZE bsize) { #if CONFIG_NON_GREEDY_MV
(void)mode_mv;
(void)this_mv; if (this_mode == NEWMV && bsize >= BLOCK_8X8 && cpi->tpl_ready) { constint gf_group_idx = cpi->twopass.gf_group.index; constint gf_rf_idx = ref_frame_to_gf_rf_idx(ref_frame); const TplDepFrame tpl_frame = cpi->tpl_stats[gf_group_idx]; const MotionField *motion_field = vp9_motion_field_info_get_motion_field(
&cpi->motion_field_info, gf_group_idx, gf_rf_idx, cpi->tpl_bsize); constint tpl_block_mi_h = num_8x8_blocks_high_lookup[cpi->tpl_bsize]; constint tpl_block_mi_w = num_8x8_blocks_wide_lookup[cpi->tpl_bsize]; constint tpl_mi_row = mi_row - (mi_row % tpl_block_mi_h); constint tpl_mi_col = mi_col - (mi_col % tpl_block_mi_w); constint mv_mode =
tpl_frame
.mv_mode_arr[gf_rf_idx][tpl_mi_row * tpl_frame.stride + tpl_mi_col]; if (mv_mode == NEW_MV_MODE) {
int_mv tpl_new_mv =
vp9_motion_field_mi_get_mv(motion_field, tpl_mi_row, tpl_mi_col); int row_diff = abs(tpl_new_mv.as_mv.row - this_mv.as_mv.row); int col_diff = abs(tpl_new_mv.as_mv.col - this_mv.as_mv.col); if (VPXMAX(row_diff, col_diff) <= 8) { return 1;
} else { return 0;
}
} else { return 0;
}
} else { return 0;
} #else
(void)mi_row;
(void)mi_col;
(void)bsize; return (!cpi->rc.is_src_frame_alt_ref && (this_mode == NEWMV) &&
(this_mv.as_int != 0) &&
((mode_mv[NEARESTMV][ref_frame].as_int == 0) ||
(mode_mv[NEARESTMV][ref_frame].as_int == INVALID_MV)) &&
((mode_mv[NEARMV][ref_frame].as_int == 0) ||
(mode_mv[NEARMV][ref_frame].as_int == INVALID_MV))); #endif
}
static int64_t handle_inter_mode(
VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int *rate2,
int64_t *distortion, int *skippable, int *rate_y, int *rate_uv, struct buf_2d *recon, int *disable_skip, int_mv (*mode_mv)[MAX_REF_FRAMES], int mi_row, int mi_col, int_mv single_newmv[MAX_REF_FRAMES],
INTERP_FILTER (*single_filter)[MAX_REF_FRAMES], int (*single_skippable)[MAX_REF_FRAMES], int *single_mode_rate,
int64_t *psse, const int64_t ref_best_rd, int64_t *mask_filter,
int64_t filter_cache[], int best_mode_index) {
VP9_COMMON *cm = &cpi->common;
MACROBLOCKD *xd = &x->e_mbd;
MODE_INFO *mi = xd->mi[0];
MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext; constint is_comp_pred = has_second_ref(mi); constint this_mode = mi->mode;
int_mv *frame_mv = mode_mv[this_mode]; int i; int refs[2] = { mi->ref_frame[0],
(mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1]) };
int_mv cur_mv[2]; #if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, tmp_buf16[MAX_MB_PLANE * 64 * 64]);
uint8_t *tmp_buf; #else
DECLARE_ALIGNED(16, uint8_t, tmp_buf[MAX_MB_PLANE * 64 * 64]); #endif// CONFIG_VP9_HIGHBITDEPTH int intpel_mv;
int64_t rd, tmp_rd = INT64_MAX, best_rd = INT64_MAX; int best_needs_copy = 0;
uint8_t *orig_dst[MAX_MB_PLANE]; int orig_dst_stride[MAX_MB_PLANE]; int rs = 0;
INTERP_FILTER best_filter = SWITCHABLE;
uint8_t skip_txfm[MAX_MB_PLANE << 2] = { 0 };
int64_t bsse[MAX_MB_PLANE << 2] = { 0 };
if (pred_filter_search) {
INTERP_FILTER af = SWITCHABLE, lf = SWITCHABLE; if (xd->above_mi && is_inter_block(xd->above_mi))
af = xd->above_mi->interp_filter; if (xd->left_mi && is_inter_block(xd->left_mi))
lf = xd->left_mi->interp_filter;
if (is_comp_pred) { if (frame_mv[refs[0]].as_int == INVALID_MV ||
frame_mv[refs[1]].as_int == INVALID_MV) return INT64_MAX;
if (cpi->sf.adaptive_mode_search) { if (single_filter[this_mode][refs[0]] ==
single_filter[this_mode][refs[1]])
best_filter = single_filter[this_mode][refs[0]];
}
}
if (this_mode == NEWMV) { int rate_mv; if (is_comp_pred) { // Decide number of joint motion search iterations constint num_joint_search_iters = get_joint_search_iters(
cpi->sf.comp_inter_joint_search_iter_level, bsize);
// Initialize mv using single prediction mode result.
frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
// Estimate the rate implications of a new mv but discount this // under certain circumstances where we want to help initiate a weak // motion field, where the distortion gain for a single block may not // be enough to overcome the cost of a new mv. if (discount_newmv_test(cpi, this_mode, tmp_mv, mode_mv, refs[0], mi_row,
mi_col, bsize)) {
*rate2 += VPXMAX((rate_mv / NEW_MV_DISCOUNT_FACTOR), 1);
} else {
*rate2 += rate_mv;
}
}
}
for (i = 0; i < is_comp_pred + 1; ++i) {
cur_mv[i] = frame_mv[refs[i]]; // Clip "next_nearest" so that it does not extend to far out of image if (this_mode != NEWMV) clamp_mv2(&cur_mv[i].as_mv, xd);
if (mv_check_bounds(&x->mv_limits, &cur_mv[i].as_mv)) return INT64_MAX;
mi->mv[i].as_int = cur_mv[i].as_int;
}
// do first prediction into the destination buffer. Do the next // prediction into a temporary buffer. Then keep track of which one // of these currently holds the best predictor, and use the other // one for future predictions. In the end, copy from tmp_buf to // dst if necessary. for (i = 0; i < MAX_MB_PLANE; i++) {
orig_dst[i] = xd->plane[i].dst.buf;
orig_dst_stride[i] = xd->plane[i].dst.stride;
}
// We don't include the cost of the second reference here, because there // are only two options: Last/ARF or Golden/ARF; The second one is always // known, which is ARF. // // Under some circumstances we discount the cost of new mv mode to encourage // initiation of a motion field. if (discount_newmv_test(cpi, this_mode, frame_mv[refs[0]], mode_mv, refs[0],
mi_row, mi_col, bsize)) {
*rate2 +=
VPXMIN(cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]),
cost_mv_ref(cpi, NEARESTMV, mbmi_ext->mode_context[refs[0]]));
} else {
*rate2 += cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]);
}
if (!is_comp_pred && cpi->sf.prune_single_mode_based_on_mv_diff_mode_rate) {
single_mode_rate[INTER_OFFSET(this_mode)] = *rate2; // Prune NEARMV and ZEROMV modes based on motion vector difference and mode // rate. if (skip_single_mode_based_on_mode_rate(mode_mv, single_mode_rate,
this_mode, refs[0], *rate2,
best_mode_index)) { // Check when the single inter mode is pruned, NEARESTMV or NEWMV modes // are not early terminated. This ensures all single modes are not getting // skipped when the speed feature is enabled.
assert(single_mode_rate[INTER_OFFSET(NEARESTMV)] != INT_MAX ||
single_mode_rate[INTER_OFFSET(NEWMV)] != INT_MAX); return INT64_MAX;
}
} if (RDCOST(x->rdmult, x->rddiv, *rate2, 0) > ref_best_rd &&
mi->mode != NEARESTMV) return INT64_MAX;
// Are all MVs integer pel for Y and UV
intpel_mv = !mv_has_subpel(&mi->mv[0].as_mv); if (is_comp_pred) intpel_mv &= !mv_has_subpel(&mi->mv[1].as_mv);
#if CONFIG_COLLECT_COMPONENT_TIMING
start_timing(cpi, interp_filter_time); #endif // Search for best switchable filter by checking the variance of // pred error irrespective of whether the filter will be used for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
if (cm->interp_filter != BILINEAR) { // Use cb pattern for filter eval when filter is not switchable constint enable_interp_search =
(cpi->sf.cb_pred_filter_search && cm->interp_filter != SWITCHABLE)
? blk_parity
: 1; if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
best_filter = EIGHTTAP;
} elseif (best_filter == SWITCHABLE && enable_interp_search) { int newbest; int tmp_rate_sum = 0;
int64_t tmp_dist_sum = 0;
for (i = 0; i < SWITCHABLE_FILTERS; ++i) { int j;
int64_t rs_rd; int tmp_skip_sb = 0;
int64_t tmp_skip_sse = INT64_MAX; constint enable_earlyterm =
cpi->sf.early_term_interp_search_plane_rd && cm->interp_filter != i;
int64_t filt_best_rd;
if (tmp_rd != INT64_MAX) { if (best_needs_copy) { // again temporarily set the buffers to local memory to prevent a memcpy for (i = 0; i < MAX_MB_PLANE; i++) {
xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
xd->plane[i].dst.stride = 64;
}
}
rd = tmp_rd + RDCOST(x->rdmult, x->rddiv, rs, 0);
} else { int tmp_rate;
int64_t tmp_dist; // Handles the special case when a filter that is not in the // switchable list (ex. bilinear) is indicated at the frame level, or // skip condition holds.
build_inter_pred_model_rd_earlyterm(
cpi, mi_row, mi_col, bsize, x, xd, &tmp_rate, &tmp_dist, &skip_txfm_sb,
&skip_sse_sb, 0 /*do_earlyterm*/, INT64_MAX);
rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
memcpy(bsse, x->bsse, sizeof(bsse));
}
if (!is_comp_pred) single_filter[this_mode][refs[0]] = mi->interp_filter;
if (cpi->sf.adaptive_mode_search) if (is_comp_pred) if (single_skippable[this_mode][refs[0]] &&
single_skippable[this_mode][refs[1]])
memset(skip_txfm, SKIP_TXFM_AC_DC, sizeof(skip_txfm));
if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) { // if current pred_error modeled rd is substantially more than the best // so far, do not bother doing full rd if (rd / 2 > ref_best_rd) {
restore_dst_buf(xd, orig_dst, orig_dst_stride); return INT64_MAX;
}
}
if (cm->interp_filter == SWITCHABLE) *rate2 += rs;
// The cost of skip bit needs to be added.
*rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
*distortion = skip_sse_sb;
}
if (!is_comp_pred) single_skippable[this_mode][refs[0]] = *skippable;
restore_dst_buf(xd, orig_dst, orig_dst_stride); return 0; // The rate-distortion cost will be re-calculated by caller.
} #endif// !CONFIG_REALTIME_ONLY
void vp9_rd_pick_intra_mode_sb(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *rd_cost,
BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
int64_t best_rd) {
VP9_COMMON *const cm = &cpi->common;
MACROBLOCKD *const xd = &x->e_mbd; struct macroblockd_plane *const pd = xd->plane; int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0; int y_skip = 0, uv_skip = 0;
int64_t dist_y = 0, dist_uv = 0;
TX_SIZE max_uv_tx_size;
x->skip_encode = 0;
ctx->skip = 0;
xd->mi[0]->ref_frame[0] = INTRA_FRAME;
xd->mi[0]->ref_frame[1] = NO_REF_FRAME; // Initialize interp_filter here so we do not have to check for inter block // modes in get_pred_context_switchable_interp()
xd->mi[0]->interp_filter = SWITCHABLE_FILTERS;
#if !CONFIG_REALTIME_ONLY // This function is designed to apply a bias or adjustment to an rd value based // on the relative variance of the source and reconstruction. #define LOW_VAR_THRESH 250 #define VAR_MULT 250 staticunsignedint max_var_adjust[VP9E_CONTENT_INVALID] = { 16, 16, 250 };
// Lower of source (raw per pixel value) and recon variance. Note that // if the source per pixel is 0 then the recon value here will not be per // pixel (see above) so will likely be much larger.
src_rec_min = VPXMIN(src_variance, rec_variance);
if (src_rec_min > low_var_thresh) return;
// We care more when the reconstruction has lower variance so give this case // a stronger weighting.
var_diff = (src_variance > rec_variance) ? (src_variance - rec_variance) * 2
: (rec_variance - src_variance) / 2;
// Do we have an internal image edge (e.g. formatting bars). int vp9_internal_image_edge(VP9_COMP *cpi) { return (cpi->oxcf.pass == 2) &&
((cpi->twopass.this_frame_stats.inactive_zone_rows > 0) ||
(cpi->twopass.this_frame_stats.inactive_zone_cols > 0));
}
// Checks to see if a super block is on a horizontal image edge. // In most cases this is the "real" edge unless there are formatting // bars embedded in the stream. int vp9_active_h_edge(VP9_COMP *cpi, int mi_row, int mi_step) { int top_edge = 0; int bottom_edge = cpi->common.mi_rows; int is_active_h_edge = 0;
// For two pass account for any formatting bars detected. if (cpi->oxcf.pass == 2) {
TWO_PASS *twopass = &cpi->twopass;
vpx_clear_system_state();
// The inactive region is specified in MBs not mi units. // The image edge is in the following MB row.
top_edge += (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
// Checks to see if a super block is on a vertical image edge. // In most cases this is the "real" edge unless there are formatting // bars embedded in the stream. int vp9_active_v_edge(VP9_COMP *cpi, int mi_col, int mi_step) { int left_edge = 0; int right_edge = cpi->common.mi_cols; int is_active_v_edge = 0;
// For two pass account for any formatting bars detected. if (cpi->oxcf.pass == 2) {
TWO_PASS *twopass = &cpi->twopass;
vpx_clear_system_state();
// The inactive region is specified in MBs not mi units. // The image edge is in the following MB row.
left_edge += (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
// Checks to see if a super block is at the edge of the active image. // In most cases this is the "real" edge unless there are formatting // bars embedded in the stream. int vp9_active_edge_sb(VP9_COMP *cpi, int mi_row, int mi_col) { return vp9_active_h_edge(cpi, mi_row, MI_BLOCK_SIZE) ||
vp9_active_v_edge(cpi, mi_col, MI_BLOCK_SIZE);
}
for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX; for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = INT64_MAX; for (i = 0; i < TX_SIZES; i++) rate_uv_intra[i] = INT_MAX; for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX; for (i = 0; i < MB_MODE_COUNT; ++i) { for (k = 0; k < MAX_REF_FRAMES; ++k) {
single_inter_filter[i][k] = SWITCHABLE;
single_skippable[i][k] = 0;
}
}
for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
if (!(cpi->ref_frame_flags & ref_frame_to_flag(ref_frame))) {
// Skip checking missing references in both single and compound reference
// modes. Note that a mode will be skipped if both reference frames
// are masked out.
ref_frame_skip_mask[0] |= (1 << ref_frame);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
} else if (sf->reference_masking) {
for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
// Skip fixed mv modes for poor references
if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
mode_skip_mask[ref_frame] |= INTER_NEAREST_NEAR_ZERO;
break;
}
}
}
// If the segment reference frame feature is enabled....
// then do nothing if the current ref frame is not allowed..
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
ref_frame_skip_mask[0] |= (1 << ref_frame);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
}
}
// Disable this drop out case if the ref frame
// segment level feature is enabled for this segment. This is to
// prevent the possibility that we end up unable to pick any mode.
if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
// Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
// unless ARNR filtering is enabled in which case we want
// an unfiltered alternative. We allow near/nearest as well
// because they may result in zero-zero MVs but be cheaper.
if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
ref_frame_skip_mask[0] = (1 << LAST_FRAME) | (1 << GOLDEN_FRAME);
ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
mode_skip_mask[ALTREF_FRAME] = ~INTER_NEAREST_NEAR_ZERO;
if (frame_mv[NEARMV][ALTREF_FRAME].as_int != 0)
mode_skip_mask[ALTREF_FRAME] |= (1 << NEARMV);
if (frame_mv[NEARESTMV][ALTREF_FRAME].as_int != 0)
mode_skip_mask[ALTREF_FRAME] |= (1 << NEARESTMV);
}
}
if (is_rect_partition) {
if (ctx->skip_ref_frame_mask & (1 << ref_frame)) continue;
if (second_ref_frame > 0 &&
(ctx->skip_ref_frame_mask & (1 << second_ref_frame)))
continue;
}
// Look at the reference frame of the best mode so far and set the
// skip mask to look at a subset of the remaining modes.
if (midx == mode_skip_start && best_mode_index >= 0) {
switch (best_mbmode.ref_frame[0]) {
case INTRA_FRAME: break;
case LAST_FRAME: ref_frame_skip_mask[0] |= LAST_FRAME_MODE_MASK; break;
case GOLDEN_FRAME:
ref_frame_skip_mask[0] |= GOLDEN_FRAME_MODE_MASK;
break;
case ALTREF_FRAME: ref_frame_skip_mask[0] |= ALT_REF_MODE_MASK; break;
case NO_REF_FRAME:
case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
}
}
if ((mi_col - 1) >= tile_info->mi_col_start) {
if (ref_mv.as_int == INVALID_MV) ref_mv = xd->mi[-1]->mv[0];
if (rf == NO_REF_FRAME) rf = xd->mi[-1]->ref_frame[0];
for (i = 0; i < mi_height; ++i) {
ref_mi = xd->mi[i * xd->mi_stride - 1];
const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
(ref_frame == ref_mi->ref_frame[0]);
skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
}
}
if (skip_ref_frame && this_mode != NEARESTMV && this_mode != NEWMV)
if (rf > INTRA_FRAME)
if (ref_frame != rf) continue;
if (const_motion)
if (this_mode == NEARMV || this_mode == ZEROMV) continue;
}
if (comp_pred) {
if (!cpi->allow_comp_inter_inter) continue;
if (cm->ref_frame_sign_bias[ref_frame] ==
cm->ref_frame_sign_bias[second_ref_frame])
continue;
// Skip compound inter modes if ARF is not available.
if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
continue;
// Do not allow compound prediction if the segment level reference frame
// feature is in use as in this case there can only be one reference.
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
if (ref_frame == INTRA_FRAME) {
if (sf->adaptive_mode_search)
if ((x->source_variance << num_pels_log2_lookup[bsize]) > best_pred_sse)
continue;
if (this_mode != DC_PRED) {
// Disable intra modes other than DC_PRED for blocks with low variance
// Threshold for intra skipping based on source variance
// TODO(debargha): Specialize the threshold for super block sizes
const unsigned int skip_intra_var_thresh =
(cpi->oxcf.content == VP9E_CONTENT_FILM) ? 0 : 64;
if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
x->source_variance < skip_intra_var_thresh)
continue;
// Only search the oblique modes if the best so far is
// one of the neighboring directional modes
if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
(this_mode >= D45_PRED && this_mode <= TM_PRED)) {
if (best_mode_index >= 0 && best_mbmode.ref_frame[0] > INTRA_FRAME)
continue;
}
if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
if (conditional_skipintra(this_mode, best_intra_mode)) continue;
}
}
} else {
const MV_REFERENCE_FRAME ref_frames[2] = { ref_frame, second_ref_frame };
if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv, this_mode,
ref_frames))
continue;
}
mi->mode = this_mode;
mi->uv_mode = DC_PRED;
mi->ref_frame[0] = ref_frame;
mi->ref_frame[1] = second_ref_frame;
// Evaluate all sub-pel filters irrespective of whether we can use
// them for this frame.
mi->interp_filter =
cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
mi->mv[0].as_int = mi->mv[1].as_int = 0;
if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
}
// Estimate the reference frame signaling cost and add it
// to the rolling cost variable.
if (comp_pred) {
rate2 += ref_costs_comp[ref_frame];
} else {
rate2 += ref_costs_single[ref_frame];
}
if (!disable_skip) {
const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
if (skippable) {
// Back out the coefficient coding costs
rate2 -= (rate_y + rate_uv);
// Cost the skip mb case
rate2 += skip_cost1;
} else if (ref_frame != INTRA_FRAME && !xd->lossless &&
!cpi->oxcf.sharpness) {
if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
distortion2) <
RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
} else {
// FIXME(rbultje) make this work for splitmv also
assert(total_sse >= 0);
rate2 += skip_cost1;
distortion2 = total_sse;
rate2 -= (rate_y + rate_uv);
this_skip2 = 1;
}
} else {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
}
// Calculate the final RD estimate for this mode.
this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
}
if (recon) {
// In film mode bias against DC pred and other intra if there is a
// significant difference between the variance of the sub blocks in the
// the source. Also apply some bias against compound modes which also
// tend to blur fine texture such as film grain over time.
//
// The sub block test here acts in the case where one or more sub
// blocks have high relatively variance but others relatively low
// variance. Here the high variance sub blocks may push the
// total variance for the current block size over the thresholds
// used in rd_variance_adjustment() below.
if (cpi->oxcf.content == VP9E_CONTENT_FILM) {
if (bsize >= BLOCK_16X16) {
int min_energy, max_energy;
vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
&max_energy);
if (max_energy > min_energy) {
if (ref_frame == INTRA_FRAME) {
if (this_mode == DC_PRED)
this_rd += (this_rd * (max_energy - min_energy));
else
this_rd += (this_rd * (max_energy - min_energy)) / 4;
} else if (second_ref_frame > INTRA_FRAME) {
this_rd += this_rd / 4;
}
}
}
}
// Apply an adjustment to the rd value based on the similarity of the
// source variance and reconstructed variance.
rd_variance_adjustment(cpi, x, bsize, &this_rd, recon, ref_frame,
second_ref_frame, this_mode);
}
if (ref_frame == INTRA_FRAME) {
// Keep record of best intra rd
if (this_rd < best_intra_rd) {
best_intra_rd = this_rd;
best_intra_mode = mi->mode;
}
}
if (!disable_skip && ref_frame == INTRA_FRAME) {
for (i = 0; i < REFERENCE_MODES; ++i)
best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
}
// Did this mode help.. i.e. is it the new best mode
if (this_rd < best_rd || x->skip) {
int max_plane = MAX_MB_PLANE;
if (!mode_excluded) {
// Note index of best mode so far
best_mode_index = mode_index;
if (ref_frame == INTRA_FRAME) {
/* required for left and above block mv */
mi->mv[0].as_int = 0;
max_plane = 1;
// Initialize interp_filter here so we do not have to check for
// inter block modes in get_pred_context_switchable_interp()
mi->interp_filter = SWITCHABLE_FILTERS;
} else {
best_pred_sse = x->pred_sse[ref_frame];
}
// TODO(debargha): enhance this test with a better distortion prediction
// based on qp, activity mask and history
if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
(mode_index > MIN_EARLY_TERM_INDEX)) {
int qstep = xd->plane[0].dequant[1];
// TODO(debargha): Enhance this by specializing for each mode_index
int scale = 4;
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
qstep >>= (xd->bd - 8);
}
#endif // CONFIG_VP9_HIGHBITDEPTH
if (x->source_variance < UINT_MAX) {
const int var_adjust = (x->source_variance < 16);
scale -= var_adjust;
}
if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
early_term = 1;
}
}
}
}
/* keep record of best compound/single-only prediction */
if (!disable_skip && ref_frame != INTRA_FRAME) {
int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
if (!comp_pred) {
if (single_rd < best_pred_rd[SINGLE_REFERENCE])
best_pred_rd[SINGLE_REFERENCE] = single_rd;
} else {
if (single_rd < best_pred_rd[COMPOUND_REFERENCE])
best_pred_rd[COMPOUND_REFERENCE] = single_rd;
}
if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
/* keep record of best filter type */
if (!mode_excluded && cm->interp_filter != BILINEAR) {
int64_t ref =
filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
: cm->interp_filter];
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
int64_t adj_rd;
if (ref == INT64_MAX)
adj_rd = 0;
else if (filter_cache[i] == INT64_MAX)
// when early termination is triggered, the encoder does not have
// access to the rate-distortion cost. it only knows that the cost
// should be above the maximum valid value. hence it takes the known
// maximum plus an arbitrary constant as the rate-distortion cost.
adj_rd = mask_filter - ref + 10;
else
adj_rd = filter_cache[i] - ref;
// The inter modes' rate costs are not calculated precisely in some cases.
// Therefore, sometimes, NEWMV is chosen instead of NEARESTMV, NEARMV, and
// ZEROMV. Here, checks are added for those cases, and the mode decisions
// are corrected.
if (best_mbmode.mode == NEWMV) {
const MV_REFERENCE_FRAME refs[2] = { best_mbmode.ref_frame[0],
best_mbmode.ref_frame[1] };
int comp_pred_mode = refs[1] > INTRA_FRAME;
if (best_mode_index < 0 || best_rd >= best_rd_so_far) {
// If adaptive interp filter is enabled, then the current leaf node of 8x8
// data is needed for sub8x8. Hence preserve the context.
if (bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
rd_cost->rate = INT_MAX;
rd_cost->rdcost = INT64_MAX;
return;
}
// If we used an estimate for the uv intra rd in the loop above...
if (sf->use_uv_intra_rd_estimate) {
// Do Intra UV best rd mode selection if best mode choice above was intra.
if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
TX_SIZE uv_tx_size;
*mi = best_mbmode;
uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
&rate_uv_tokenonly[uv_tx_size],
&dist_uv[uv_tx_size], &skip_uv[uv_tx_size],
bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
uv_tx_size);
}
}
for (i = 0; i < REFERENCE_MODES; ++i) {
if (best_pred_rd[i] == INT64_MAX)
best_pred_diff[i] = INT_MIN;
else
best_pred_diff[i] = best_rd - best_pred_rd[i];
}
if (!x->skip) {
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
if (best_filter_rd[i] == INT64_MAX)
best_filter_diff[i] = 0;
else
best_filter_diff[i] = best_rd - best_filter_rd[i];
}
if (cm->interp_filter == SWITCHABLE)
assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
} else {
vp9_zero(best_filter_diff);
}
// TODO(yunqingwang): Moving this line in front of the above best_filter_diff
// updating code causes PSNR loss. Need to figure out the confliction.
x->skip |= best_mode_skippable;
if (!x->skip && !x->select_tx_size) {
int has_high_freq_coeff = 0;
int plane;
int max_plane = is_inter_block(xd->mi[0]) ? MAX_MB_PLANE : 1;
for (plane = 0; plane < max_plane; ++plane) {
x->plane[plane].eobs = ctx->eobs_pbuf[plane][1];
has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
}
if (cm->interp_filter != BILINEAR) {
best_filter = EIGHTTAP;
if (cm->interp_filter == SWITCHABLE &&
x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
int rs;
int best_rs = INT_MAX;
for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
mi->interp_filter = i;
rs = vp9_get_switchable_rate(cpi, xd);
if (rs < best_rs) {
best_rs = rs;
best_filter = mi->interp_filter;
}
}
}
}
// Set the appropriate filter
if (cm->interp_filter == SWITCHABLE) {
mi->interp_filter = best_filter;
rate2 += vp9_get_switchable_rate(cpi, xd);
} else {
mi->interp_filter = cm->interp_filter;
}
if (cm->reference_mode == REFERENCE_MODE_SELECT)
rate2 += vp9_cost_bit(comp_mode_p, comp_pred);
// Estimate the reference frame signaling cost and add it
// to the rolling cost variable.
rate2 += ref_costs_single[LAST_FRAME];
this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = INT64_MAX;
rate_uv_intra = INT_MAX;
#if CONFIG_BETTER_HW_COMPATIBILITY
// forbid 8X4 and 4X8 partitions if any reference frame is scaled.
if (bsize == BLOCK_8X4 || bsize == BLOCK_4X8) {
int ref_scaled = ref_frame > INTRA_FRAME &&
vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf);
if (second_ref_frame > INTRA_FRAME)
ref_scaled += vp9_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf);
if (ref_scaled) continue;
}
#endif
// Look at the reference frame of the best mode so far and set the
// skip mask to look at a subset of the remaining modes.
if (ref_index > 2 && sf->mode_skip_start < MAX_MODES) {
if (ref_index == 3) {
switch (best_mbmode.ref_frame[0]) {
case INTRA_FRAME: break;
case LAST_FRAME:
ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
break;
case GOLDEN_FRAME:
ref_frame_skip_mask[0] |= (1 << LAST_FRAME) | (1 << ALTREF_FRAME);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
break;
case ALTREF_FRAME:
ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << LAST_FRAME);
break;
case NO_REF_FRAME:
case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
}
}
}
// Test best rd so far against threshold for trying this mode.
if (!internal_active_edge &&
rd_less_than_thresh(best_rd,
rd_opt->threshes[segment_id][bsize][ref_index],
&rd_thresh_freq_fact[ref_index]))
continue;
// This is only used in motion vector unit test.
if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
comp_pred = second_ref_frame > INTRA_FRAME;
if (comp_pred) {
if (!cpi->allow_comp_inter_inter) continue;
if (cm->ref_frame_sign_bias[ref_frame] ==
cm->ref_frame_sign_bias[second_ref_frame])
continue;
if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
continue;
// Do not allow compound prediction if the segment level reference frame
// feature is in use as in this case there can only be one reference.
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
if ((sf->mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
best_mbmode.ref_frame[0] == INTRA_FRAME)
continue;
}
if (comp_pred)
mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
else if (ref_frame != INTRA_FRAME)
mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
// If the segment reference frame feature is enabled....
// then do nothing if the current ref frame is not allowed..
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
continue;
// Disable this drop out case if the ref frame
// segment level feature is enabled for this segment. This is to
// prevent the possibility that we end up unable to pick any mode.
} else if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
// Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
// unless ARNR filtering is enabled in which case we want
// an unfiltered alternative. We allow near/nearest as well
// because they may result in zero-zero MVs but be cheaper.
if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
continue;
}
mi->tx_size = TX_4X4;
mi->uv_mode = DC_PRED;
mi->ref_frame[0] = ref_frame;
mi->ref_frame[1] = second_ref_frame;
// Evaluate all sub-pel filters irrespective of whether we can use
// them for this frame.
mi->interp_filter =
cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
x->skip = 0;
set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
// Select prediction reference frames.
for (i = 0; i < MAX_MB_PLANE; i++) {
xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
}
if (ref_frame == INTRA_FRAME) {
int rate;
if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y, &distortion_y,
best_rd) >= best_rd)
continue;
rate2 += rate;
rate2 += intra_cost_penalty;
distortion2 += distortion_y;
if (scaled_ref_frame[ref]) {
// Swap out the reference frame for a version that's been scaled to
// match the resolution of the current frame, allowing the existing
// motion search code to be used without additional modifications.
for (i = 0; i < MAX_MB_PLANE; i++)
backup_yv12[ref][i] = xd->plane[i].pre[ref];
vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
NULL);
}
}
this_rd_thresh = (ref_frame == LAST_FRAME)
? rd_opt->threshes[segment_id][bsize][THR_LAST]
: rd_opt->threshes[segment_id][bsize][THR_ALTR];
this_rd_thresh = (ref_frame == GOLDEN_FRAME)
? rd_opt->threshes[segment_id][bsize][THR_GOLD]
: this_rd_thresh;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
filter_cache[i] = INT64_MAX;
if (tmp_best_rdu > 0) {
// If even the 'Y' rd value of split is higher than best so far
// then don't bother looking at UV
vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col, BLOCK_8X8);
memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
if (!super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
&uv_sse, BLOCK_8X8, tmp_best_rdu)) {
for (ref = 0; ref < 2; ++ref) {
if (scaled_ref_frame[ref]) {
for (i = 0; i < MAX_MB_PLANE; ++i)
xd->plane[i].pre[ref] = backup_yv12[ref][i];
}
}
continue;
}
for (ref = 0; ref < 2; ++ref) {
if (scaled_ref_frame[ref]) {
// Restore the prediction frame pointers to their unscaled versions.
for (i = 0; i < MAX_MB_PLANE; ++i)
xd->plane[i].pre[ref] = backup_yv12[ref][i];
}
}
}
if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
// Estimate the reference frame signaling cost and add it
// to the rolling cost variable.
if (second_ref_frame > INTRA_FRAME) {
rate2 += ref_costs_comp[ref_frame];
} else {
rate2 += ref_costs_single[ref_frame];
}
if (!disable_skip) {
const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
// Skip is never coded at the segment level for sub8x8 blocks and instead
// always coded in the bitstream at the mode info level.
if (ref_frame != INTRA_FRAME && !xd->lossless) {
if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
distortion2) <
RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
} else {
// FIXME(rbultje) make this work for splitmv also
rate2 += skip_cost1;
distortion2 = total_sse;
assert(total_sse >= 0);
rate2 -= (rate_y + rate_uv);
rate_y = 0;
rate_uv = 0;
this_skip2 = 1;
}
} else {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
}
// Calculate the final RD estimate for this mode.
this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
}
if (!disable_skip && ref_frame == INTRA_FRAME) {
for (i = 0; i < REFERENCE_MODES; ++i)
best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
}
// Did this mode help.. i.e. is it the new best mode
if (this_rd < best_rd || x->skip) {
if (!mode_excluded) {
int max_plane = MAX_MB_PLANE;
// Note index of best mode so far
best_ref_index = ref_index;
if (ref_frame == INTRA_FRAME) {
/* required for left and above block mv */
mi->mv[0].as_int = 0;
max_plane = 1;
// Initialize interp_filter here so we do not have to check for
// inter block modes in get_pred_context_switchable_interp()
mi->interp_filter = SWITCHABLE_FILTERS;
}
for (i = 0; i < 4; i++) best_bmodes[i] = xd->mi[0]->bmi[i];
// TODO(debargha): enhance this test with a better distortion prediction
// based on qp, activity mask and history
if ((sf->mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
(ref_index > MIN_EARLY_TERM_INDEX)) {
int qstep = xd->plane[0].dequant[1];
// TODO(debargha): Enhance this by specializing for each mode_index
int scale = 4;
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
qstep >>= (xd->bd - 8);
}
#endif // CONFIG_VP9_HIGHBITDEPTH
if (x->source_variance < UINT_MAX) {
const int var_adjust = (x->source_variance < 16);
scale -= var_adjust;
}
if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
early_term = 1;
}
}
}
}
/* keep record of best compound/single-only prediction */
if (!disable_skip && ref_frame != INTRA_FRAME) {
int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE])
best_pred_rd[SINGLE_REFERENCE] = single_rd;
else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE])
best_pred_rd[COMPOUND_REFERENCE] = single_rd;
if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
}
/* keep record of best filter type */
if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
cm->interp_filter != BILINEAR) {
int64_t ref =
filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
: cm->interp_filter];
int64_t adj_rd;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
if (ref == INT64_MAX)
adj_rd = 0;
else if (filter_cache[i] == INT64_MAX)
// when early termination is triggered, the encoder does not have
// access to the rate-distortion cost. it only knows that the cost
// should be above the maximum valid value. hence it takes the known
// maximum plus an arbitrary constant as the rate-distortion cost.
adj_rd = mask_filter - ref + 10;
else
adj_rd = filter_cache[i] - ref;
// If we used an estimate for the uv intra rd in the loop above...
if (sf->use_uv_intra_rd_estimate) {
// Do Intra UV best rd mode selection if best mode choice above was intra.
if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
*mi = best_mbmode;
rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra, &rate_uv_tokenonly,
&dist_uv, &skip_uv, BLOCK_8X8, TX_4X4);
}
}
// macroblock modes
*mi = best_mbmode;
x->skip |= best_skip2;
if (!is_inter_block(&best_mbmode)) {
for (i = 0; i < 4; i++) xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
} else {
for (i = 0; i < 4; ++i)
memcpy(&xd->mi[0]->bmi[i], &best_bmodes[i], sizeof(b_mode_info));
mi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
mi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
}
// If the second reference does not exist, set the corresponding mv to zero.
if (mi->ref_frame[1] == NO_REF_FRAME) {
mi->mv[1].as_int = 0;
for (i = 0; i < 4; ++i) {
mi->bmi[i].as_mv[1].as_int = 0;
}
}
for (i = 0; i < REFERENCE_MODES; ++i) {
if (best_pred_rd[i] == INT64_MAX)
best_pred_diff[i] = INT_MIN;
else
best_pred_diff[i] = best_rd - best_pred_rd[i];
}
if (!x->skip) {
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
if (best_filter_rd[i] == INT64_MAX)
best_filter_diff[i] = 0;
else
best_filter_diff[i] = best_rd - best_filter_rd[i];
}
if (cm->interp_filter == SWITCHABLE)
assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
} else {
vp9_zero(best_filter_diff);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.