media/libvpx/vp9/encoder/vp9_rdopt.c

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/media/libvpx/vp9/encoder/vp9_rdopt.c	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,4582 @@
     1.4 +/*
     1.5 + *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
     1.6 + *
     1.7 + *  Use of this source code is governed by a BSD-style license
     1.8 + *  that can be found in the LICENSE file in the root of the source
     1.9 + *  tree. An additional intellectual property rights grant can be found
    1.10 + *  in the file PATENTS.  All contributing project authors may
    1.11 + *  be found in the AUTHORS file in the root of the source tree.
    1.12 + */
    1.13 +
    1.14 +#include <stdio.h>
    1.15 +#include <math.h>
    1.16 +#include <limits.h>
    1.17 +#include <assert.h>
    1.18 +
    1.19 +#include "vp9/common/vp9_pragmas.h"
    1.20 +#include "vp9/encoder/vp9_tokenize.h"
    1.21 +#include "vp9/encoder/vp9_treewriter.h"
    1.22 +#include "vp9/encoder/vp9_onyx_int.h"
    1.23 +#include "vp9/encoder/vp9_modecosts.h"
    1.24 +#include "vp9/encoder/vp9_encodeintra.h"
    1.25 +#include "vp9/common/vp9_entropymode.h"
    1.26 +#include "vp9/common/vp9_reconinter.h"
    1.27 +#include "vp9/common/vp9_reconintra.h"
    1.28 +#include "vp9/common/vp9_findnearmv.h"
    1.29 +#include "vp9/common/vp9_quant_common.h"
    1.30 +#include "vp9/encoder/vp9_encodemb.h"
    1.31 +#include "vp9/encoder/vp9_quantize.h"
    1.32 +#include "vp9/encoder/vp9_variance.h"
    1.33 +#include "vp9/encoder/vp9_mcomp.h"
    1.34 +#include "vp9/encoder/vp9_rdopt.h"
    1.35 +#include "vp9/encoder/vp9_ratectrl.h"
    1.36 +#include "vpx_mem/vpx_mem.h"
    1.37 +#include "vp9/common/vp9_systemdependent.h"
    1.38 +#include "vp9/encoder/vp9_encodemv.h"
    1.39 +#include "vp9/common/vp9_seg_common.h"
    1.40 +#include "vp9/common/vp9_pred_common.h"
    1.41 +#include "vp9/common/vp9_entropy.h"
    1.42 +#include "./vp9_rtcd.h"
    1.43 +#include "vp9/common/vp9_mvref_common.h"
    1.44 +#include "vp9/common/vp9_common.h"
    1.45 +
    1.46 +#define INVALID_MV 0x80008000
    1.47 +
    1.48 +/* Factor to weigh the rate for switchable interp filters */
    1.49 +#define SWITCHABLE_INTERP_RATE_FACTOR 1
    1.50 +
    1.51 +#define LAST_FRAME_MODE_MASK    0xFFEDCD60
    1.52 +#define GOLDEN_FRAME_MODE_MASK  0xFFDA3BB0
    1.53 +#define ALT_REF_MODE_MASK       0xFFC648D0
    1.54 +
    1.55 +#define MIN_EARLY_TERM_INDEX    3
    1.56 +
    1.57 +const MODE_DEFINITION vp9_mode_order[MAX_MODES] = {
    1.58 +  {NEARESTMV, LAST_FRAME,   NONE},
    1.59 +  {NEARESTMV, ALTREF_FRAME, NONE},
    1.60 +  {NEARESTMV, GOLDEN_FRAME, NONE},
    1.61 +
    1.62 +  {DC_PRED,   INTRA_FRAME,  NONE},
    1.63 +
    1.64 +  {NEWMV,     LAST_FRAME,   NONE},
    1.65 +  {NEWMV,     ALTREF_FRAME, NONE},
    1.66 +  {NEWMV,     GOLDEN_FRAME, NONE},
    1.67 +
    1.68 +  {NEARMV,    LAST_FRAME,   NONE},
    1.69 +  {NEARMV,    ALTREF_FRAME, NONE},
    1.70 +  {NEARESTMV, LAST_FRAME,   ALTREF_FRAME},
    1.71 +  {NEARESTMV, GOLDEN_FRAME, ALTREF_FRAME},
    1.72 +
    1.73 +  {TM_PRED,   INTRA_FRAME,  NONE},
    1.74 +
    1.75 +  {NEARMV,    LAST_FRAME,   ALTREF_FRAME},
    1.76 +  {NEWMV,     LAST_FRAME,   ALTREF_FRAME},
    1.77 +  {NEARMV,    GOLDEN_FRAME, NONE},
    1.78 +  {NEARMV,    GOLDEN_FRAME, ALTREF_FRAME},
    1.79 +  {NEWMV,     GOLDEN_FRAME, ALTREF_FRAME},
    1.80 +
    1.81 +  {ZEROMV,    LAST_FRAME,   NONE},
    1.82 +  {ZEROMV,    GOLDEN_FRAME, NONE},
    1.83 +  {ZEROMV,    ALTREF_FRAME, NONE},
    1.84 +  {ZEROMV,    LAST_FRAME,   ALTREF_FRAME},
    1.85 +  {ZEROMV,    GOLDEN_FRAME, ALTREF_FRAME},
    1.86 +
    1.87 +  {H_PRED,    INTRA_FRAME,  NONE},
    1.88 +  {V_PRED,    INTRA_FRAME,  NONE},
    1.89 +  {D135_PRED, INTRA_FRAME,  NONE},
    1.90 +  {D207_PRED, INTRA_FRAME,  NONE},
    1.91 +  {D153_PRED, INTRA_FRAME,  NONE},
    1.92 +  {D63_PRED,  INTRA_FRAME,  NONE},
    1.93 +  {D117_PRED, INTRA_FRAME,  NONE},
    1.94 +  {D45_PRED,  INTRA_FRAME,  NONE},
    1.95 +};
    1.96 +
    1.97 +const REF_DEFINITION vp9_ref_order[MAX_REFS] = {
    1.98 +  {LAST_FRAME,   NONE},
    1.99 +  {GOLDEN_FRAME, NONE},
   1.100 +  {ALTREF_FRAME, NONE},
   1.101 +  {LAST_FRAME,   ALTREF_FRAME},
   1.102 +  {GOLDEN_FRAME, ALTREF_FRAME},
   1.103 +  {INTRA_FRAME,  NONE},
   1.104 +};
   1.105 +
   1.106 +// The baseline rd thresholds for breaking out of the rd loop for
   1.107 +// certain modes are assumed to be based on 8x8 blocks.
   1.108 +// This table is used to correct for blocks size.
   1.109 +// The factors here are << 2 (2 = x0.5, 32 = x8 etc).
   1.110 +static int rd_thresh_block_size_factor[BLOCK_SIZES] =
   1.111 +  {2, 3, 3, 4, 6, 6, 8, 12, 12, 16, 24, 24, 32};
   1.112 +
   1.113 +#define RD_THRESH_MAX_FACT 64
   1.114 +#define RD_THRESH_INC      1
   1.115 +#define RD_THRESH_POW      1.25
   1.116 +#define RD_MULT_EPB_RATIO  64
   1.117 +
   1.118 +#define MV_COST_WEIGHT      108
   1.119 +#define MV_COST_WEIGHT_SUB  120
   1.120 +
   1.121 +static void fill_token_costs(vp9_coeff_cost *c,
   1.122 +                             vp9_coeff_probs_model (*p)[BLOCK_TYPES]) {
   1.123 +  int i, j, k, l;
   1.124 +  TX_SIZE t;
   1.125 +  for (t = TX_4X4; t <= TX_32X32; t++)
   1.126 +    for (i = 0; i < BLOCK_TYPES; i++)
   1.127 +      for (j = 0; j < REF_TYPES; j++)
   1.128 +        for (k = 0; k < COEF_BANDS; k++)
   1.129 +          for (l = 0; l < PREV_COEF_CONTEXTS; l++) {
   1.130 +            vp9_prob probs[ENTROPY_NODES];
   1.131 +            vp9_model_to_full_probs(p[t][i][j][k][l], probs);
   1.132 +            vp9_cost_tokens((int *)c[t][i][j][k][0][l], probs,
   1.133 +                            vp9_coef_tree);
   1.134 +            vp9_cost_tokens_skip((int *)c[t][i][j][k][1][l], probs,
   1.135 +                                 vp9_coef_tree);
   1.136 +            assert(c[t][i][j][k][0][l][DCT_EOB_TOKEN] ==
   1.137 +                   c[t][i][j][k][1][l][DCT_EOB_TOKEN]);
   1.138 +          }
   1.139 +}
   1.140 +
   1.141 +static const int rd_iifactor[32] = {
   1.142 +  4, 4, 3, 2, 1, 0, 0, 0,
   1.143 +  0, 0, 0, 0, 0, 0, 0, 0,
   1.144 +  0, 0, 0, 0, 0, 0, 0, 0,
   1.145 +  0, 0, 0, 0, 0, 0, 0, 0,
   1.146 +};
   1.147 +
   1.148 +// 3* dc_qlookup[Q]*dc_qlookup[Q];
   1.149 +
   1.150 +/* values are now correlated to quantizer */
   1.151 +static int sad_per_bit16lut[QINDEX_RANGE];
   1.152 +static int sad_per_bit4lut[QINDEX_RANGE];
   1.153 +
   1.154 +void vp9_init_me_luts() {
   1.155 +  int i;
   1.156 +
   1.157 +  // Initialize the sad lut tables using a formulaic calculation for now
   1.158 +  // This is to make it easier to resolve the impact of experimental changes
   1.159 +  // to the quantizer tables.
   1.160 +  for (i = 0; i < QINDEX_RANGE; i++) {
   1.161 +    sad_per_bit16lut[i] =
   1.162 +      (int)((0.0418 * vp9_convert_qindex_to_q(i)) + 2.4107);
   1.163 +    sad_per_bit4lut[i] = (int)(0.063 * vp9_convert_qindex_to_q(i) + 2.742);
   1.164 +  }
   1.165 +}
   1.166 +
   1.167 +int vp9_compute_rd_mult(VP9_COMP *cpi, int qindex) {
   1.168 +  const int q = vp9_dc_quant(qindex, 0);
   1.169 +  // TODO(debargha): Adjust the function below
   1.170 +  int rdmult = 88 * q * q / 25;
   1.171 +  if (cpi->pass == 2 && (cpi->common.frame_type != KEY_FRAME)) {
   1.172 +    if (cpi->twopass.next_iiratio > 31)
   1.173 +      rdmult += (rdmult * rd_iifactor[31]) >> 4;
   1.174 +    else
   1.175 +      rdmult += (rdmult * rd_iifactor[cpi->twopass.next_iiratio]) >> 4;
   1.176 +  }
   1.177 +  return rdmult;
   1.178 +}
   1.179 +
   1.180 +static int compute_rd_thresh_factor(int qindex) {
   1.181 +  int q;
   1.182 +  // TODO(debargha): Adjust the function below
   1.183 +  q = (int)(pow(vp9_dc_quant(qindex, 0) / 4.0, RD_THRESH_POW) * 5.12);
   1.184 +  if (q < 8)
   1.185 +    q = 8;
   1.186 +  return q;
   1.187 +}
   1.188 +
   1.189 +void vp9_initialize_me_consts(VP9_COMP *cpi, int qindex) {
   1.190 +  cpi->mb.sadperbit16 = sad_per_bit16lut[qindex];
   1.191 +  cpi->mb.sadperbit4 = sad_per_bit4lut[qindex];
   1.192 +}
   1.193 +
   1.194 +static void set_block_thresholds(VP9_COMP *cpi) {
   1.195 +  int i, bsize, segment_id;
   1.196 +  VP9_COMMON *cm = &cpi->common;
   1.197 +
   1.198 +  for (segment_id = 0; segment_id < MAX_SEGMENTS; ++segment_id) {
   1.199 +    int q;
   1.200 +    int segment_qindex = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
   1.201 +    segment_qindex = clamp(segment_qindex + cm->y_dc_delta_q, 0, MAXQ);
   1.202 +    q = compute_rd_thresh_factor(segment_qindex);
   1.203 +
   1.204 +    for (bsize = 0; bsize < BLOCK_SIZES; ++bsize) {
   1.205 +      // Threshold here seem unecessarily harsh but fine given actual
   1.206 +      // range of values used for cpi->sf.thresh_mult[]
   1.207 +      int thresh_max = INT_MAX / (q * rd_thresh_block_size_factor[bsize]);
   1.208 +
   1.209 +      for (i = 0; i < MAX_MODES; ++i) {
   1.210 +        if (cpi->sf.thresh_mult[i] < thresh_max) {
   1.211 +          cpi->rd_threshes[segment_id][bsize][i] =
   1.212 +              cpi->sf.thresh_mult[i] * q *
   1.213 +              rd_thresh_block_size_factor[bsize] / 4;
   1.214 +        } else {
   1.215 +          cpi->rd_threshes[segment_id][bsize][i] = INT_MAX;
   1.216 +        }
   1.217 +      }
   1.218 +
   1.219 +      for (i = 0; i < MAX_REFS; ++i) {
   1.220 +        if (cpi->sf.thresh_mult_sub8x8[i] < thresh_max) {
   1.221 +          cpi->rd_thresh_sub8x8[segment_id][bsize][i] =
   1.222 +              cpi->sf.thresh_mult_sub8x8[i] * q *
   1.223 +              rd_thresh_block_size_factor[bsize] / 4;
   1.224 +        } else {
   1.225 +          cpi->rd_thresh_sub8x8[segment_id][bsize][i] = INT_MAX;
   1.226 +        }
   1.227 +      }
   1.228 +    }
   1.229 +  }
   1.230 +}
   1.231 +
   1.232 +void vp9_initialize_rd_consts(VP9_COMP *cpi) {
   1.233 +  VP9_COMMON *cm = &cpi->common;
   1.234 +  int qindex, i;
   1.235 +
   1.236 +  vp9_clear_system_state();  // __asm emms;
   1.237 +
   1.238 +  // Further tests required to see if optimum is different
   1.239 +  // for key frames, golden frames and arf frames.
   1.240 +  // if (cpi->common.refresh_golden_frame ||
   1.241 +  //     cpi->common.refresh_alt_ref_frame)
   1.242 +  qindex = clamp(cm->base_qindex + cm->y_dc_delta_q, 0, MAXQ);
   1.243 +
   1.244 +  cpi->RDDIV = RDDIV_BITS;  // in bits (to multiply D by 128)
   1.245 +  cpi->RDMULT = vp9_compute_rd_mult(cpi, qindex);
   1.246 +
   1.247 +  cpi->mb.errorperbit = cpi->RDMULT / RD_MULT_EPB_RATIO;
   1.248 +  cpi->mb.errorperbit += (cpi->mb.errorperbit == 0);
   1.249 +
   1.250 +  vp9_set_speed_features(cpi);
   1.251 +
   1.252 +  cpi->mb.select_txfm_size = (cpi->sf.tx_size_search_method == USE_LARGESTALL &&
   1.253 +                              cm->frame_type != KEY_FRAME) ?
   1.254 +                             0 : 1;
   1.255 +
   1.256 +  set_block_thresholds(cpi);
   1.257 +
   1.258 +  fill_token_costs(cpi->mb.token_costs, cm->fc.coef_probs);
   1.259 +
   1.260 +  for (i = 0; i < PARTITION_CONTEXTS; i++)
   1.261 +    vp9_cost_tokens(cpi->mb.partition_cost[i], get_partition_probs(cm, i),
   1.262 +                    vp9_partition_tree);
   1.263 +
   1.264 +  /*rough estimate for costing*/
   1.265 +  vp9_init_mode_costs(cpi);
   1.266 +
   1.267 +  if (!frame_is_intra_only(cm)) {
   1.268 +    vp9_build_nmv_cost_table(
   1.269 +        cpi->mb.nmvjointcost,
   1.270 +        cm->allow_high_precision_mv ? cpi->mb.nmvcost_hp : cpi->mb.nmvcost,
   1.271 +        &cm->fc.nmvc,
   1.272 +        cm->allow_high_precision_mv, 1, 1);
   1.273 +
   1.274 +    for (i = 0; i < INTER_MODE_CONTEXTS; i++) {
   1.275 +      MB_PREDICTION_MODE m;
   1.276 +
   1.277 +      for (m = NEARESTMV; m < MB_MODE_COUNT; m++)
   1.278 +        cpi->mb.inter_mode_cost[i][INTER_OFFSET(m)] =
   1.279 +            cost_token(vp9_inter_mode_tree,
   1.280 +                       cm->fc.inter_mode_probs[i],
   1.281 +                       &vp9_inter_mode_encodings[INTER_OFFSET(m)]);
   1.282 +    }
   1.283 +  }
   1.284 +}
   1.285 +
   1.286 +static INLINE void linear_interpolate2(double x, int ntab, int inv_step,
   1.287 +                                       const double *tab1, const double *tab2,
   1.288 +                                       double *v1, double *v2) {
   1.289 +  double y = x * inv_step;
   1.290 +  int d = (int) y;
   1.291 +  if (d >= ntab - 1) {
   1.292 +    *v1 = tab1[ntab - 1];
   1.293 +    *v2 = tab2[ntab - 1];
   1.294 +  } else {
   1.295 +    double a = y - d;
   1.296 +    *v1 = tab1[d] * (1 - a) + tab1[d + 1] * a;
   1.297 +    *v2 = tab2[d] * (1 - a) + tab2[d + 1] * a;
   1.298 +  }
   1.299 +}
   1.300 +
   1.301 +static void model_rd_norm(double x, double *R, double *D) {
   1.302 +  static const int inv_tab_step = 8;
   1.303 +  static const int tab_size = 120;
   1.304 +  // NOTE: The tables below must be of the same size
   1.305 +  //
   1.306 +  // Normalized rate
   1.307 +  // This table models the rate for a Laplacian source
   1.308 +  // source with given variance when quantized with a uniform quantizer
   1.309 +  // with given stepsize. The closed form expression is:
   1.310 +  // Rn(x) = H(sqrt(r)) + sqrt(r)*[1 + H(r)/(1 - r)],
   1.311 +  // where r = exp(-sqrt(2) * x) and x = qpstep / sqrt(variance),
   1.312 +  // and H(x) is the binary entropy function.
   1.313 +  static const double rate_tab[] = {
   1.314 +    64.00, 4.944, 3.949, 3.372, 2.966, 2.655, 2.403, 2.194,
   1.315 +    2.014, 1.858, 1.720, 1.596, 1.485, 1.384, 1.291, 1.206,
   1.316 +    1.127, 1.054, 0.986, 0.923, 0.863, 0.808, 0.756, 0.708,
   1.317 +    0.662, 0.619, 0.579, 0.541, 0.506, 0.473, 0.442, 0.412,
   1.318 +    0.385, 0.359, 0.335, 0.313, 0.291, 0.272, 0.253, 0.236,
   1.319 +    0.220, 0.204, 0.190, 0.177, 0.165, 0.153, 0.142, 0.132,
   1.320 +    0.123, 0.114, 0.106, 0.099, 0.091, 0.085, 0.079, 0.073,
   1.321 +    0.068, 0.063, 0.058, 0.054, 0.050, 0.047, 0.043, 0.040,
   1.322 +    0.037, 0.034, 0.032, 0.029, 0.027, 0.025, 0.023, 0.022,
   1.323 +    0.020, 0.019, 0.017, 0.016, 0.015, 0.014, 0.013, 0.012,
   1.324 +    0.011, 0.010, 0.009, 0.008, 0.008, 0.007, 0.007, 0.006,
   1.325 +    0.006, 0.005, 0.005, 0.005, 0.004, 0.004, 0.004, 0.003,
   1.326 +    0.003, 0.003, 0.003, 0.002, 0.002, 0.002, 0.002, 0.002,
   1.327 +    0.002, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001,
   1.328 +    0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000,
   1.329 +  };
   1.330 +  // Normalized distortion
   1.331 +  // This table models the normalized distortion for a Laplacian source
   1.332 +  // source with given variance when quantized with a uniform quantizer
   1.333 +  // with given stepsize. The closed form expression is:
   1.334 +  // Dn(x) = 1 - 1/sqrt(2) * x / sinh(x/sqrt(2))
   1.335 +  // where x = qpstep / sqrt(variance)
   1.336 +  // Note the actual distortion is Dn * variance.
   1.337 +  static const double dist_tab[] = {
   1.338 +    0.000, 0.001, 0.005, 0.012, 0.021, 0.032, 0.045, 0.061,
   1.339 +    0.079, 0.098, 0.119, 0.142, 0.166, 0.190, 0.216, 0.242,
   1.340 +    0.269, 0.296, 0.324, 0.351, 0.378, 0.405, 0.432, 0.458,
   1.341 +    0.484, 0.509, 0.534, 0.557, 0.580, 0.603, 0.624, 0.645,
   1.342 +    0.664, 0.683, 0.702, 0.719, 0.735, 0.751, 0.766, 0.780,
   1.343 +    0.794, 0.807, 0.819, 0.830, 0.841, 0.851, 0.861, 0.870,
   1.344 +    0.878, 0.886, 0.894, 0.901, 0.907, 0.913, 0.919, 0.925,
   1.345 +    0.930, 0.935, 0.939, 0.943, 0.947, 0.951, 0.954, 0.957,
   1.346 +    0.960, 0.963, 0.966, 0.968, 0.971, 0.973, 0.975, 0.976,
   1.347 +    0.978, 0.980, 0.981, 0.982, 0.984, 0.985, 0.986, 0.987,
   1.348 +    0.988, 0.989, 0.990, 0.990, 0.991, 0.992, 0.992, 0.993,
   1.349 +    0.993, 0.994, 0.994, 0.995, 0.995, 0.996, 0.996, 0.996,
   1.350 +    0.996, 0.997, 0.997, 0.997, 0.997, 0.998, 0.998, 0.998,
   1.351 +    0.998, 0.998, 0.998, 0.999, 0.999, 0.999, 0.999, 0.999,
   1.352 +    0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 1.000,
   1.353 +  };
   1.354 +  /*
   1.355 +  assert(sizeof(rate_tab) == tab_size * sizeof(rate_tab[0]);
   1.356 +  assert(sizeof(dist_tab) == tab_size * sizeof(dist_tab[0]);
   1.357 +  assert(sizeof(rate_tab) == sizeof(dist_tab));
   1.358 +  */
   1.359 +  assert(x >= 0.0);
   1.360 +  linear_interpolate2(x, tab_size, inv_tab_step,
   1.361 +                      rate_tab, dist_tab, R, D);
   1.362 +}
   1.363 +
   1.364 +static void model_rd_from_var_lapndz(int var, int n, int qstep,
   1.365 +                                     int *rate, int64_t *dist) {
   1.366 +  // This function models the rate and distortion for a Laplacian
   1.367 +  // source with given variance when quantized with a uniform quantizer
   1.368 +  // with given stepsize. The closed form expressions are in:
   1.369 +  // Hang and Chen, "Source Model for transform video coder and its
   1.370 +  // application - Part I: Fundamental Theory", IEEE Trans. Circ.
   1.371 +  // Sys. for Video Tech., April 1997.
   1.372 +  vp9_clear_system_state();
   1.373 +  if (var == 0 || n == 0) {
   1.374 +    *rate = 0;
   1.375 +    *dist = 0;
   1.376 +  } else {
   1.377 +    double D, R;
   1.378 +    double s2 = (double) var / n;
   1.379 +    double x = qstep / sqrt(s2);
   1.380 +    model_rd_norm(x, &R, &D);
   1.381 +    *rate = (int)((n << 8) * R + 0.5);
   1.382 +    *dist = (int)(var * D + 0.5);
   1.383 +  }
   1.384 +  vp9_clear_system_state();
   1.385 +}
   1.386 +
   1.387 +static void model_rd_for_sb(VP9_COMP *cpi, BLOCK_SIZE bsize,
   1.388 +                            MACROBLOCK *x, MACROBLOCKD *xd,
   1.389 +                            int *out_rate_sum, int64_t *out_dist_sum) {
   1.390 +  // Note our transform coeffs are 8 times an orthogonal transform.
   1.391 +  // Hence quantizer step is also 8 times. To get effective quantizer
   1.392 +  // we need to divide by 8 before sending to modeling function.
   1.393 +  int i, rate_sum = 0, dist_sum = 0;
   1.394 +
   1.395 +  for (i = 0; i < MAX_MB_PLANE; ++i) {
   1.396 +    struct macroblock_plane *const p = &x->plane[i];
   1.397 +    struct macroblockd_plane *const pd = &xd->plane[i];
   1.398 +    const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
   1.399 +    unsigned int sse;
   1.400 +    int rate;
   1.401 +    int64_t dist;
   1.402 +    (void) cpi->fn_ptr[bs].vf(p->src.buf, p->src.stride,
   1.403 +                              pd->dst.buf, pd->dst.stride, &sse);
   1.404 +    // sse works better than var, since there is no dc prediction used
   1.405 +    model_rd_from_var_lapndz(sse, 1 << num_pels_log2_lookup[bs],
   1.406 +                             pd->dequant[1] >> 3, &rate, &dist);
   1.407 +
   1.408 +    rate_sum += rate;
   1.409 +    dist_sum += (int)dist;
   1.410 +  }
   1.411 +
   1.412 +  *out_rate_sum = rate_sum;
   1.413 +  *out_dist_sum = dist_sum << 4;
   1.414 +}
   1.415 +
   1.416 +static void model_rd_for_sb_y_tx(VP9_COMP *cpi, BLOCK_SIZE bsize,
   1.417 +                                 TX_SIZE tx_size,
   1.418 +                                 MACROBLOCK *x, MACROBLOCKD *xd,
   1.419 +                                 int *out_rate_sum, int64_t *out_dist_sum,
   1.420 +                                 int *out_skip) {
   1.421 +  int j, k;
   1.422 +  BLOCK_SIZE bs;
   1.423 +  struct macroblock_plane *const p = &x->plane[0];
   1.424 +  struct macroblockd_plane *const pd = &xd->plane[0];
   1.425 +  const int width = 4 << num_4x4_blocks_wide_lookup[bsize];
   1.426 +  const int height = 4 << num_4x4_blocks_high_lookup[bsize];
   1.427 +  int rate_sum = 0;
   1.428 +  int64_t dist_sum = 0;
   1.429 +  const int t = 4 << tx_size;
   1.430 +
   1.431 +  if (tx_size == TX_4X4) {
   1.432 +    bs = BLOCK_4X4;
   1.433 +  } else if (tx_size == TX_8X8) {
   1.434 +    bs = BLOCK_8X8;
   1.435 +  } else if (tx_size == TX_16X16) {
   1.436 +    bs = BLOCK_16X16;
   1.437 +  } else if (tx_size == TX_32X32) {
   1.438 +    bs = BLOCK_32X32;
   1.439 +  } else {
   1.440 +    assert(0);
   1.441 +  }
   1.442 +
   1.443 +  *out_skip = 1;
   1.444 +  for (j = 0; j < height; j += t) {
   1.445 +    for (k = 0; k < width; k += t) {
   1.446 +      int rate;
   1.447 +      int64_t dist;
   1.448 +      unsigned int sse;
   1.449 +      cpi->fn_ptr[bs].vf(&p->src.buf[j * p->src.stride + k], p->src.stride,
   1.450 +                         &pd->dst.buf[j * pd->dst.stride + k], pd->dst.stride,
   1.451 +                         &sse);
   1.452 +      // sse works better than var, since there is no dc prediction used
   1.453 +      model_rd_from_var_lapndz(sse, t * t, pd->dequant[1] >> 3, &rate, &dist);
   1.454 +      rate_sum += rate;
   1.455 +      dist_sum += dist;
   1.456 +      *out_skip &= (rate < 1024);
   1.457 +    }
   1.458 +  }
   1.459 +
   1.460 +  *out_rate_sum = rate_sum;
   1.461 +  *out_dist_sum = dist_sum << 4;
   1.462 +}
   1.463 +
   1.464 +int64_t vp9_block_error_c(int16_t *coeff, int16_t *dqcoeff,
   1.465 +                          intptr_t block_size, int64_t *ssz) {
   1.466 +  int i;
   1.467 +  int64_t error = 0, sqcoeff = 0;
   1.468 +
   1.469 +  for (i = 0; i < block_size; i++) {
   1.470 +    int this_diff = coeff[i] - dqcoeff[i];
   1.471 +    error += (unsigned)this_diff * this_diff;
   1.472 +    sqcoeff += (unsigned) coeff[i] * coeff[i];
   1.473 +  }
   1.474 +
   1.475 +  *ssz = sqcoeff;
   1.476 +  return error;
   1.477 +}
   1.478 +
   1.479 +/* The trailing '0' is a terminator which is used inside cost_coeffs() to
   1.480 + * decide whether to include cost of a trailing EOB node or not (i.e. we
   1.481 + * can skip this if the last coefficient in this transform block, e.g. the
   1.482 + * 16th coefficient in a 4x4 block or the 64th coefficient in a 8x8 block,
   1.483 + * were non-zero). */
   1.484 +static const int16_t band_counts[TX_SIZES][8] = {
   1.485 +  { 1, 2, 3, 4,  3,   16 - 13, 0 },
   1.486 +  { 1, 2, 3, 4, 11,   64 - 21, 0 },
   1.487 +  { 1, 2, 3, 4, 11,  256 - 21, 0 },
   1.488 +  { 1, 2, 3, 4, 11, 1024 - 21, 0 },
   1.489 +};
   1.490 +
   1.491 +static INLINE int cost_coeffs(MACROBLOCK *x,
   1.492 +                              int plane, int block,
   1.493 +                              ENTROPY_CONTEXT *A, ENTROPY_CONTEXT *L,
   1.494 +                              TX_SIZE tx_size,
   1.495 +                              const int16_t *scan, const int16_t *nb) {
   1.496 +  MACROBLOCKD *const xd = &x->e_mbd;
   1.497 +  MB_MODE_INFO *mbmi = &xd->mi_8x8[0]->mbmi;
   1.498 +  struct macroblockd_plane *pd = &xd->plane[plane];
   1.499 +  const PLANE_TYPE type = pd->plane_type;
   1.500 +  const int16_t *band_count = &band_counts[tx_size][1];
   1.501 +  const int eob = pd->eobs[block];
   1.502 +  const int16_t *const qcoeff_ptr = BLOCK_OFFSET(pd->qcoeff, block);
   1.503 +  const int ref = mbmi->ref_frame[0] != INTRA_FRAME;
   1.504 +  unsigned int (*token_costs)[2][PREV_COEF_CONTEXTS][MAX_ENTROPY_TOKENS] =
   1.505 +                   x->token_costs[tx_size][type][ref];
   1.506 +  const ENTROPY_CONTEXT above_ec = !!*A, left_ec = !!*L;
   1.507 +  uint8_t *p_tok = x->token_cache;
   1.508 +  int pt = combine_entropy_contexts(above_ec, left_ec);
   1.509 +  int c, cost;
   1.510 +
   1.511 +  // Check for consistency of tx_size with mode info
   1.512 +  assert(type == PLANE_TYPE_Y_WITH_DC ? mbmi->tx_size == tx_size
   1.513 +                                      : get_uv_tx_size(mbmi) == tx_size);
   1.514 +
   1.515 +  if (eob == 0) {
   1.516 +    // single eob token
   1.517 +    cost = token_costs[0][0][pt][DCT_EOB_TOKEN];
   1.518 +    c = 0;
   1.519 +  } else {
   1.520 +    int band_left = *band_count++;
   1.521 +
   1.522 +    // dc token
   1.523 +    int v = qcoeff_ptr[0];
   1.524 +    int prev_t = vp9_dct_value_tokens_ptr[v].token;
   1.525 +    cost = (*token_costs)[0][pt][prev_t] + vp9_dct_value_cost_ptr[v];
   1.526 +    p_tok[0] = vp9_pt_energy_class[prev_t];
   1.527 +    ++token_costs;
   1.528 +
   1.529 +    // ac tokens
   1.530 +    for (c = 1; c < eob; c++) {
   1.531 +      const int rc = scan[c];
   1.532 +      int t;
   1.533 +
   1.534 +      v = qcoeff_ptr[rc];
   1.535 +      t = vp9_dct_value_tokens_ptr[v].token;
   1.536 +      pt = get_coef_context(nb, p_tok, c);
   1.537 +      cost += (*token_costs)[!prev_t][pt][t] + vp9_dct_value_cost_ptr[v];
   1.538 +      p_tok[rc] = vp9_pt_energy_class[t];
   1.539 +      prev_t = t;
   1.540 +      if (!--band_left) {
   1.541 +        band_left = *band_count++;
   1.542 +        ++token_costs;
   1.543 +      }
   1.544 +    }
   1.545 +
   1.546 +    // eob token
   1.547 +    if (band_left) {
   1.548 +      pt = get_coef_context(nb, p_tok, c);
   1.549 +      cost += (*token_costs)[0][pt][DCT_EOB_TOKEN];
   1.550 +    }
   1.551 +  }
   1.552 +
   1.553 +  // is eob first coefficient;
   1.554 +  *A = *L = (c > 0);
   1.555 +
   1.556 +  return cost;
   1.557 +}
   1.558 +
   1.559 +static void dist_block(int plane, int block, TX_SIZE tx_size, void *arg) {
   1.560 +  const int ss_txfrm_size = tx_size << 1;
   1.561 +  struct rdcost_block_args* args = arg;
   1.562 +  MACROBLOCK* const x = args->x;
   1.563 +  MACROBLOCKD* const xd = &x->e_mbd;
   1.564 +  struct macroblock_plane *const p = &x->plane[plane];
   1.565 +  struct macroblockd_plane *const pd = &xd->plane[plane];
   1.566 +  int64_t this_sse;
   1.567 +  int shift = args->tx_size == TX_32X32 ? 0 : 2;
   1.568 +  int16_t *const coeff = BLOCK_OFFSET(p->coeff, block);
   1.569 +  int16_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
   1.570 +  args->dist = vp9_block_error(coeff, dqcoeff, 16 << ss_txfrm_size,
   1.571 +                               &this_sse) >> shift;
   1.572 +  args->sse  = this_sse >> shift;
   1.573 +
   1.574 +  if (x->skip_encode &&
   1.575 +      xd->mi_8x8[0]->mbmi.ref_frame[0] == INTRA_FRAME) {
   1.576 +    // TODO(jingning): tune the model to better capture the distortion.
   1.577 +    int64_t p = (pd->dequant[1] * pd->dequant[1] *
   1.578 +                    (1 << ss_txfrm_size)) >> (shift + 2);
   1.579 +    args->dist += (p >> 4);
   1.580 +    args->sse  += p;
   1.581 +  }
   1.582 +}
   1.583 +
   1.584 +static void rate_block(int plane, int block, BLOCK_SIZE plane_bsize,
   1.585 +                       TX_SIZE tx_size, void *arg) {
   1.586 +  struct rdcost_block_args* args = arg;
   1.587 +
   1.588 +  int x_idx, y_idx;
   1.589 +  txfrm_block_to_raster_xy(plane_bsize, args->tx_size, block, &x_idx, &y_idx);
   1.590 +
   1.591 +  args->rate = cost_coeffs(args->x, plane, block, args->t_above + x_idx,
   1.592 +                           args->t_left + y_idx, args->tx_size,
   1.593 +                           args->scan, args->nb);
   1.594 +}
   1.595 +
   1.596 +static void block_yrd_txfm(int plane, int block, BLOCK_SIZE plane_bsize,
   1.597 +                           TX_SIZE tx_size, void *arg) {
   1.598 +  struct rdcost_block_args *args = arg;
   1.599 +  MACROBLOCK *const x = args->x;
   1.600 +  MACROBLOCKD *const xd = &x->e_mbd;
   1.601 +  struct encode_b_args encode_args = {x, NULL};
   1.602 +  int64_t rd1, rd2, rd;
   1.603 +
   1.604 +  if (args->skip)
   1.605 +    return;
   1.606 +
   1.607 +  if (!is_inter_block(&xd->mi_8x8[0]->mbmi))
   1.608 +    vp9_encode_block_intra(plane, block, plane_bsize, tx_size, &encode_args);
   1.609 +  else
   1.610 +    vp9_xform_quant(plane, block, plane_bsize, tx_size, &encode_args);
   1.611 +
   1.612 +  dist_block(plane, block, tx_size, args);
   1.613 +  rate_block(plane, block, plane_bsize, tx_size, args);
   1.614 +  rd1 = RDCOST(x->rdmult, x->rddiv, args->rate, args->dist);
   1.615 +  rd2 = RDCOST(x->rdmult, x->rddiv, 0, args->sse);
   1.616 +
   1.617 +  // TODO(jingning): temporarily enabled only for luma component
   1.618 +  rd = MIN(rd1, rd2);
   1.619 +  if (!xd->lossless && plane == 0)
   1.620 +    x->zcoeff_blk[tx_size][block] = rd1 > rd2 || !xd->plane[plane].eobs[block];
   1.621 +
   1.622 +  args->this_rate += args->rate;
   1.623 +  args->this_dist += args->dist;
   1.624 +  args->this_sse  += args->sse;
   1.625 +  args->this_rd += rd;
   1.626 +
   1.627 +  if (args->this_rd > args->best_rd) {
   1.628 +    args->skip = 1;
   1.629 +    return;
   1.630 +  }
   1.631 +}
   1.632 +
   1.633 +void vp9_get_entropy_contexts(TX_SIZE tx_size,
   1.634 +    ENTROPY_CONTEXT t_above[16], ENTROPY_CONTEXT t_left[16],
   1.635 +    const ENTROPY_CONTEXT *above, const ENTROPY_CONTEXT *left,
   1.636 +    int num_4x4_w, int num_4x4_h) {
   1.637 +  int i;
   1.638 +  switch (tx_size) {
   1.639 +    case TX_4X4:
   1.640 +      vpx_memcpy(t_above, above, sizeof(ENTROPY_CONTEXT) * num_4x4_w);
   1.641 +      vpx_memcpy(t_left, left, sizeof(ENTROPY_CONTEXT) * num_4x4_h);
   1.642 +      break;
   1.643 +    case TX_8X8:
   1.644 +      for (i = 0; i < num_4x4_w; i += 2)
   1.645 +        t_above[i] = !!*(const uint16_t *)&above[i];
   1.646 +      for (i = 0; i < num_4x4_h; i += 2)
   1.647 +        t_left[i] = !!*(const uint16_t *)&left[i];
   1.648 +      break;
   1.649 +    case TX_16X16:
   1.650 +      for (i = 0; i < num_4x4_w; i += 4)
   1.651 +        t_above[i] = !!*(const uint32_t *)&above[i];
   1.652 +      for (i = 0; i < num_4x4_h; i += 4)
   1.653 +        t_left[i] = !!*(const uint32_t *)&left[i];
   1.654 +      break;
   1.655 +    case TX_32X32:
   1.656 +      for (i = 0; i < num_4x4_w; i += 8)
   1.657 +        t_above[i] = !!*(const uint64_t *)&above[i];
   1.658 +      for (i = 0; i < num_4x4_h; i += 8)
   1.659 +        t_left[i] = !!*(const uint64_t *)&left[i];
   1.660 +      break;
   1.661 +    default:
   1.662 +      assert(!"Invalid transform size.");
   1.663 +  }
   1.664 +}
   1.665 +
   1.666 +static void init_rdcost_stack(MACROBLOCK *x, TX_SIZE tx_size,
   1.667 +                              const int num_4x4_w, const int num_4x4_h,
   1.668 +                              const int64_t ref_rdcost,
   1.669 +                              struct rdcost_block_args *arg) {
   1.670 +  vpx_memset(arg, 0, sizeof(struct rdcost_block_args));
   1.671 +  arg->x = x;
   1.672 +  arg->tx_size = tx_size;
   1.673 +  arg->bw = num_4x4_w;
   1.674 +  arg->bh = num_4x4_h;
   1.675 +  arg->best_rd = ref_rdcost;
   1.676 +}
   1.677 +
   1.678 +static void txfm_rd_in_plane(MACROBLOCK *x,
   1.679 +                             struct rdcost_block_args *rd_stack,
   1.680 +                             int *rate, int64_t *distortion,
   1.681 +                             int *skippable, int64_t *sse,
   1.682 +                             int64_t ref_best_rd, int plane,
   1.683 +                             BLOCK_SIZE bsize, TX_SIZE tx_size) {
   1.684 +  MACROBLOCKD *const xd = &x->e_mbd;
   1.685 +  struct macroblockd_plane *const pd = &xd->plane[plane];
   1.686 +  const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
   1.687 +  const int num_4x4_w = num_4x4_blocks_wide_lookup[bs];
   1.688 +  const int num_4x4_h = num_4x4_blocks_high_lookup[bs];
   1.689 +
   1.690 +  init_rdcost_stack(x, tx_size, num_4x4_w, num_4x4_h,
   1.691 +                    ref_best_rd, rd_stack);
   1.692 +  if (plane == 0)
   1.693 +    xd->mi_8x8[0]->mbmi.tx_size = tx_size;
   1.694 +
   1.695 +  vp9_get_entropy_contexts(tx_size, rd_stack->t_above, rd_stack->t_left,
   1.696 +                           pd->above_context, pd->left_context,
   1.697 +                           num_4x4_w, num_4x4_h);
   1.698 +
   1.699 +  get_scan(xd, tx_size, pd->plane_type, 0, &rd_stack->scan, &rd_stack->nb);
   1.700 +
   1.701 +  foreach_transformed_block_in_plane(xd, bsize, plane,
   1.702 +                                     block_yrd_txfm, rd_stack);
   1.703 +  if (rd_stack->skip) {
   1.704 +    *rate       = INT_MAX;
   1.705 +    *distortion = INT64_MAX;
   1.706 +    *sse        = INT64_MAX;
   1.707 +    *skippable  = 0;
   1.708 +  } else {
   1.709 +    *distortion = rd_stack->this_dist;
   1.710 +    *rate       = rd_stack->this_rate;
   1.711 +    *sse        = rd_stack->this_sse;
   1.712 +    *skippable  = vp9_is_skippable_in_plane(xd, bsize, plane);
   1.713 +  }
   1.714 +}
   1.715 +
   1.716 +static void choose_largest_txfm_size(VP9_COMP *cpi, MACROBLOCK *x,
   1.717 +                                     int *rate, int64_t *distortion,
   1.718 +                                     int *skip, int64_t *sse,
   1.719 +                                     int64_t ref_best_rd,
   1.720 +                                     BLOCK_SIZE bs) {
   1.721 +  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
   1.722 +  VP9_COMMON *const cm = &cpi->common;
   1.723 +  const TX_SIZE largest_tx_size = tx_mode_to_biggest_tx_size[cm->tx_mode];
   1.724 +  MACROBLOCKD *const xd = &x->e_mbd;
   1.725 +  MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
   1.726 +
   1.727 +  mbmi->tx_size = MIN(max_tx_size, largest_tx_size);
   1.728 +
   1.729 +  txfm_rd_in_plane(x, &cpi->rdcost_stack, rate, distortion, skip,
   1.730 +                   &sse[mbmi->tx_size], ref_best_rd, 0, bs,
   1.731 +                   mbmi->tx_size);
   1.732 +  cpi->tx_stepdown_count[0]++;
   1.733 +}
   1.734 +
   1.735 +static void choose_txfm_size_from_rd(VP9_COMP *cpi, MACROBLOCK *x,
   1.736 +                                     int (*r)[2], int *rate,
   1.737 +                                     int64_t *d, int64_t *distortion,
   1.738 +                                     int *s, int *skip,
   1.739 +                                     int64_t tx_cache[TX_MODES],
   1.740 +                                     BLOCK_SIZE bs) {
   1.741 +  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
   1.742 +  VP9_COMMON *const cm = &cpi->common;
   1.743 +  MACROBLOCKD *const xd = &x->e_mbd;
   1.744 +  MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
   1.745 +  vp9_prob skip_prob = vp9_get_pred_prob_mbskip(cm, xd);
   1.746 +  int64_t rd[TX_SIZES][2];
   1.747 +  int n, m;
   1.748 +  int s0, s1;
   1.749 +
   1.750 +  const vp9_prob *tx_probs = get_tx_probs2(max_tx_size, xd, &cm->fc.tx_probs);
   1.751 +
   1.752 +  for (n = TX_4X4; n <= max_tx_size; n++) {
   1.753 +    r[n][1] = r[n][0];
   1.754 +    if (r[n][0] == INT_MAX)
   1.755 +      continue;
   1.756 +    for (m = 0; m <= n - (n == max_tx_size); m++) {
   1.757 +      if (m == n)
   1.758 +        r[n][1] += vp9_cost_zero(tx_probs[m]);
   1.759 +      else
   1.760 +        r[n][1] += vp9_cost_one(tx_probs[m]);
   1.761 +    }
   1.762 +  }
   1.763 +
   1.764 +  assert(skip_prob > 0);
   1.765 +  s0 = vp9_cost_bit(skip_prob, 0);
   1.766 +  s1 = vp9_cost_bit(skip_prob, 1);
   1.767 +
   1.768 +  for (n = TX_4X4; n <= max_tx_size; n++) {
   1.769 +    if (d[n] == INT64_MAX) {
   1.770 +      rd[n][0] = rd[n][1] = INT64_MAX;
   1.771 +      continue;
   1.772 +    }
   1.773 +    if (s[n]) {
   1.774 +      rd[n][0] = rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1, d[n]);
   1.775 +    } else {
   1.776 +      rd[n][0] = RDCOST(x->rdmult, x->rddiv, r[n][0] + s0, d[n]);
   1.777 +      rd[n][1] = RDCOST(x->rdmult, x->rddiv, r[n][1] + s0, d[n]);
   1.778 +    }
   1.779 +  }
   1.780 +
   1.781 +  if (max_tx_size == TX_32X32 &&
   1.782 +      (cm->tx_mode == ALLOW_32X32 ||
   1.783 +       (cm->tx_mode == TX_MODE_SELECT &&
   1.784 +        rd[TX_32X32][1] < rd[TX_16X16][1] && rd[TX_32X32][1] < rd[TX_8X8][1] &&
   1.785 +        rd[TX_32X32][1] < rd[TX_4X4][1]))) {
   1.786 +    mbmi->tx_size = TX_32X32;
   1.787 +  } else if (max_tx_size >= TX_16X16 &&
   1.788 +             (cm->tx_mode == ALLOW_16X16 ||
   1.789 +              cm->tx_mode == ALLOW_32X32 ||
   1.790 +              (cm->tx_mode == TX_MODE_SELECT &&
   1.791 +               rd[TX_16X16][1] < rd[TX_8X8][1] &&
   1.792 +               rd[TX_16X16][1] < rd[TX_4X4][1]))) {
   1.793 +    mbmi->tx_size = TX_16X16;
   1.794 +  } else if (cm->tx_mode == ALLOW_8X8 ||
   1.795 +             cm->tx_mode == ALLOW_16X16 ||
   1.796 +             cm->tx_mode == ALLOW_32X32 ||
   1.797 +           (cm->tx_mode == TX_MODE_SELECT && rd[TX_8X8][1] < rd[TX_4X4][1])) {
   1.798 +    mbmi->tx_size = TX_8X8;
   1.799 +  } else {
   1.800 +    mbmi->tx_size = TX_4X4;
   1.801 +  }
   1.802 +
   1.803 +  *distortion = d[mbmi->tx_size];
   1.804 +  *rate       = r[mbmi->tx_size][cm->tx_mode == TX_MODE_SELECT];
   1.805 +  *skip       = s[mbmi->tx_size];
   1.806 +
   1.807 +  tx_cache[ONLY_4X4] = rd[TX_4X4][0];
   1.808 +  tx_cache[ALLOW_8X8] = rd[TX_8X8][0];
   1.809 +  tx_cache[ALLOW_16X16] = rd[MIN(max_tx_size, TX_16X16)][0];
   1.810 +  tx_cache[ALLOW_32X32] = rd[MIN(max_tx_size, TX_32X32)][0];
   1.811 +  if (max_tx_size == TX_32X32 &&
   1.812 +      rd[TX_32X32][1] < rd[TX_16X16][1] && rd[TX_32X32][1] < rd[TX_8X8][1] &&
   1.813 +      rd[TX_32X32][1] < rd[TX_4X4][1])
   1.814 +    tx_cache[TX_MODE_SELECT] = rd[TX_32X32][1];
   1.815 +  else if (max_tx_size >= TX_16X16 &&
   1.816 +           rd[TX_16X16][1] < rd[TX_8X8][1] && rd[TX_16X16][1] < rd[TX_4X4][1])
   1.817 +    tx_cache[TX_MODE_SELECT] = rd[TX_16X16][1];
   1.818 +  else
   1.819 +    tx_cache[TX_MODE_SELECT] = rd[TX_4X4][1] < rd[TX_8X8][1] ?
   1.820 +                                 rd[TX_4X4][1] : rd[TX_8X8][1];
   1.821 +
   1.822 +  if (max_tx_size == TX_32X32 &&
   1.823 +      rd[TX_32X32][1] < rd[TX_16X16][1] &&
   1.824 +      rd[TX_32X32][1] < rd[TX_8X8][1] &&
   1.825 +      rd[TX_32X32][1] < rd[TX_4X4][1]) {
   1.826 +    cpi->tx_stepdown_count[0]++;
   1.827 +  } else if (max_tx_size >= TX_16X16 &&
   1.828 +             rd[TX_16X16][1] < rd[TX_8X8][1] &&
   1.829 +             rd[TX_16X16][1] < rd[TX_4X4][1]) {
   1.830 +    cpi->tx_stepdown_count[max_tx_size - TX_16X16]++;
   1.831 +  } else if (rd[TX_8X8][1] < rd[TX_4X4][1]) {
   1.832 +    cpi->tx_stepdown_count[max_tx_size - TX_8X8]++;
   1.833 +  } else {
   1.834 +    cpi->tx_stepdown_count[max_tx_size - TX_4X4]++;
   1.835 +  }
   1.836 +}
   1.837 +
   1.838 +static void choose_txfm_size_from_modelrd(VP9_COMP *cpi, MACROBLOCK *x,
   1.839 +                                          int (*r)[2], int *rate,
   1.840 +                                          int64_t *d, int64_t *distortion,
   1.841 +                                          int *s, int *skip, int64_t *sse,
   1.842 +                                          int64_t ref_best_rd,
   1.843 +                                          BLOCK_SIZE bs) {
   1.844 +  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
   1.845 +  VP9_COMMON *const cm = &cpi->common;
   1.846 +  MACROBLOCKD *const xd = &x->e_mbd;
   1.847 +  MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
   1.848 +  vp9_prob skip_prob = vp9_get_pred_prob_mbskip(cm, xd);
   1.849 +  int64_t rd[TX_SIZES][2];
   1.850 +  int n, m;
   1.851 +  int s0, s1;
   1.852 +  double scale_rd[TX_SIZES] = {1.73, 1.44, 1.20, 1.00};
   1.853 +  // double scale_r[TX_SIZES] = {2.82, 2.00, 1.41, 1.00};
   1.854 +
   1.855 +  const vp9_prob *tx_probs = get_tx_probs2(max_tx_size, xd, &cm->fc.tx_probs);
   1.856 +
   1.857 +  // for (n = TX_4X4; n <= max_txfm_size; n++)
   1.858 +  //   r[n][0] = (r[n][0] * scale_r[n]);
   1.859 +
   1.860 +  for (n = TX_4X4; n <= max_tx_size; n++) {
   1.861 +    r[n][1] = r[n][0];
   1.862 +    for (m = 0; m <= n - (n == max_tx_size); m++) {
   1.863 +      if (m == n)
   1.864 +        r[n][1] += vp9_cost_zero(tx_probs[m]);
   1.865 +      else
   1.866 +        r[n][1] += vp9_cost_one(tx_probs[m]);
   1.867 +    }
   1.868 +  }
   1.869 +
   1.870 +  assert(skip_prob > 0);
   1.871 +  s0 = vp9_cost_bit(skip_prob, 0);
   1.872 +  s1 = vp9_cost_bit(skip_prob, 1);
   1.873 +
   1.874 +  for (n = TX_4X4; n <= max_tx_size; n++) {
   1.875 +    if (s[n]) {
   1.876 +      rd[n][0] = rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1, d[n]);
   1.877 +    } else {
   1.878 +      rd[n][0] = RDCOST(x->rdmult, x->rddiv, r[n][0] + s0, d[n]);
   1.879 +      rd[n][1] = RDCOST(x->rdmult, x->rddiv, r[n][1] + s0, d[n]);
   1.880 +    }
   1.881 +  }
   1.882 +  for (n = TX_4X4; n <= max_tx_size; n++) {
   1.883 +    rd[n][0] = (int64_t)(scale_rd[n] * rd[n][0]);
   1.884 +    rd[n][1] = (int64_t)(scale_rd[n] * rd[n][1]);
   1.885 +  }
   1.886 +
   1.887 +  if (max_tx_size == TX_32X32 &&
   1.888 +      (cm->tx_mode == ALLOW_32X32 ||
   1.889 +       (cm->tx_mode == TX_MODE_SELECT &&
   1.890 +        rd[TX_32X32][1] <= rd[TX_16X16][1] &&
   1.891 +        rd[TX_32X32][1] <= rd[TX_8X8][1] &&
   1.892 +        rd[TX_32X32][1] <= rd[TX_4X4][1]))) {
   1.893 +    mbmi->tx_size = TX_32X32;
   1.894 +  } else if (max_tx_size >= TX_16X16 &&
   1.895 +             (cm->tx_mode == ALLOW_16X16 ||
   1.896 +              cm->tx_mode == ALLOW_32X32 ||
   1.897 +              (cm->tx_mode == TX_MODE_SELECT &&
   1.898 +               rd[TX_16X16][1] <= rd[TX_8X8][1] &&
   1.899 +               rd[TX_16X16][1] <= rd[TX_4X4][1]))) {
   1.900 +    mbmi->tx_size = TX_16X16;
   1.901 +  } else if (cm->tx_mode == ALLOW_8X8 ||
   1.902 +             cm->tx_mode == ALLOW_16X16 ||
   1.903 +             cm->tx_mode == ALLOW_32X32 ||
   1.904 +           (cm->tx_mode == TX_MODE_SELECT &&
   1.905 +            rd[TX_8X8][1] <= rd[TX_4X4][1])) {
   1.906 +    mbmi->tx_size = TX_8X8;
   1.907 +  } else {
   1.908 +    mbmi->tx_size = TX_4X4;
   1.909 +  }
   1.910 +
   1.911 +  // Actually encode using the chosen mode if a model was used, but do not
   1.912 +  // update the r, d costs
   1.913 +  txfm_rd_in_plane(x, &cpi->rdcost_stack, rate, distortion, skip,
   1.914 +                   &sse[mbmi->tx_size], ref_best_rd, 0, bs, mbmi->tx_size);
   1.915 +
   1.916 +  if (max_tx_size == TX_32X32 &&
   1.917 +      rd[TX_32X32][1] <= rd[TX_16X16][1] &&
   1.918 +      rd[TX_32X32][1] <= rd[TX_8X8][1] &&
   1.919 +      rd[TX_32X32][1] <= rd[TX_4X4][1]) {
   1.920 +    cpi->tx_stepdown_count[0]++;
   1.921 +  } else if (max_tx_size >= TX_16X16 &&
   1.922 +             rd[TX_16X16][1] <= rd[TX_8X8][1] &&
   1.923 +             rd[TX_16X16][1] <= rd[TX_4X4][1]) {
   1.924 +    cpi->tx_stepdown_count[max_tx_size - TX_16X16]++;
   1.925 +  } else if (rd[TX_8X8][1] <= rd[TX_4X4][1]) {
   1.926 +    cpi->tx_stepdown_count[max_tx_size - TX_8X8]++;
   1.927 +  } else {
   1.928 +    cpi->tx_stepdown_count[max_tx_size - TX_4X4]++;
   1.929 +  }
   1.930 +}
   1.931 +
   1.932 +static void super_block_yrd(VP9_COMP *cpi,
   1.933 +                            MACROBLOCK *x, int *rate, int64_t *distortion,
   1.934 +                            int *skip, int64_t *psse, BLOCK_SIZE bs,
   1.935 +                            int64_t txfm_cache[TX_MODES],
   1.936 +                            int64_t ref_best_rd) {
   1.937 +  int r[TX_SIZES][2], s[TX_SIZES];
   1.938 +  int64_t d[TX_SIZES], sse[TX_SIZES];
   1.939 +  MACROBLOCKD *xd = &x->e_mbd;
   1.940 +  MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
   1.941 +  struct rdcost_block_args *rdcost_stack = &cpi->rdcost_stack;
   1.942 +  const int b_inter_mode = is_inter_block(mbmi);
   1.943 +
   1.944 +  assert(bs == mbmi->sb_type);
   1.945 +  if (b_inter_mode)
   1.946 +    vp9_subtract_sby(x, bs);
   1.947 +
   1.948 +  if (cpi->sf.tx_size_search_method == USE_LARGESTALL ||
   1.949 +      (cpi->sf.tx_size_search_method != USE_FULL_RD &&
   1.950 +       !b_inter_mode)) {
   1.951 +    vpx_memset(txfm_cache, 0, TX_MODES * sizeof(int64_t));
   1.952 +    choose_largest_txfm_size(cpi, x, rate, distortion, skip, sse,
   1.953 +                             ref_best_rd, bs);
   1.954 +    if (psse)
   1.955 +      *psse = sse[mbmi->tx_size];
   1.956 +    return;
   1.957 +  }
   1.958 +
   1.959 +  if (cpi->sf.tx_size_search_method == USE_LARGESTINTRA_MODELINTER &&
   1.960 +      b_inter_mode) {
   1.961 +    if (bs >= BLOCK_32X32)
   1.962 +      model_rd_for_sb_y_tx(cpi, bs, TX_32X32, x, xd,
   1.963 +                           &r[TX_32X32][0], &d[TX_32X32], &s[TX_32X32]);
   1.964 +    if (bs >= BLOCK_16X16)
   1.965 +      model_rd_for_sb_y_tx(cpi, bs, TX_16X16, x, xd,
   1.966 +                           &r[TX_16X16][0], &d[TX_16X16], &s[TX_16X16]);
   1.967 +
   1.968 +    model_rd_for_sb_y_tx(cpi, bs, TX_8X8, x, xd,
   1.969 +                         &r[TX_8X8][0], &d[TX_8X8], &s[TX_8X8]);
   1.970 +
   1.971 +    model_rd_for_sb_y_tx(cpi, bs, TX_4X4, x, xd,
   1.972 +                         &r[TX_4X4][0], &d[TX_4X4], &s[TX_4X4]);
   1.973 +
   1.974 +    choose_txfm_size_from_modelrd(cpi, x, r, rate, d, distortion, s,
   1.975 +                                  skip, sse, ref_best_rd, bs);
   1.976 +  } else {
   1.977 +    if (bs >= BLOCK_32X32)
   1.978 +      txfm_rd_in_plane(x, rdcost_stack, &r[TX_32X32][0], &d[TX_32X32],
   1.979 +                       &s[TX_32X32], &sse[TX_32X32],
   1.980 +                       ref_best_rd, 0, bs, TX_32X32);
   1.981 +    if (bs >= BLOCK_16X16)
   1.982 +      txfm_rd_in_plane(x, rdcost_stack, &r[TX_16X16][0], &d[TX_16X16],
   1.983 +                       &s[TX_16X16], &sse[TX_16X16],
   1.984 +                       ref_best_rd, 0, bs, TX_16X16);
   1.985 +    txfm_rd_in_plane(x, rdcost_stack, &r[TX_8X8][0], &d[TX_8X8], &s[TX_8X8],
   1.986 +                     &sse[TX_8X8], ref_best_rd, 0, bs, TX_8X8);
   1.987 +    txfm_rd_in_plane(x, rdcost_stack, &r[TX_4X4][0], &d[TX_4X4], &s[TX_4X4],
   1.988 +                     &sse[TX_4X4], ref_best_rd, 0, bs, TX_4X4);
   1.989 +    choose_txfm_size_from_rd(cpi, x, r, rate, d, distortion, s,
   1.990 +                             skip, txfm_cache, bs);
   1.991 +  }
   1.992 +  if (psse)
   1.993 +    *psse = sse[mbmi->tx_size];
   1.994 +}
   1.995 +
   1.996 +static int conditional_skipintra(MB_PREDICTION_MODE mode,
   1.997 +                                 MB_PREDICTION_MODE best_intra_mode) {
   1.998 +  if (mode == D117_PRED &&
   1.999 +      best_intra_mode != V_PRED &&
  1.1000 +      best_intra_mode != D135_PRED)
  1.1001 +    return 1;
  1.1002 +  if (mode == D63_PRED &&
  1.1003 +      best_intra_mode != V_PRED &&
  1.1004 +      best_intra_mode != D45_PRED)
  1.1005 +    return 1;
  1.1006 +  if (mode == D207_PRED &&
  1.1007 +      best_intra_mode != H_PRED &&
  1.1008 +      best_intra_mode != D45_PRED)
  1.1009 +    return 1;
  1.1010 +  if (mode == D153_PRED &&
  1.1011 +      best_intra_mode != H_PRED &&
  1.1012 +      best_intra_mode != D135_PRED)
  1.1013 +    return 1;
  1.1014 +  return 0;
  1.1015 +}
  1.1016 +
  1.1017 +static int64_t rd_pick_intra4x4block(VP9_COMP *cpi, MACROBLOCK *x, int ib,
  1.1018 +                                     MB_PREDICTION_MODE *best_mode,
  1.1019 +                                     int *bmode_costs,
  1.1020 +                                     ENTROPY_CONTEXT *a, ENTROPY_CONTEXT *l,
  1.1021 +                                     int *bestrate, int *bestratey,
  1.1022 +                                     int64_t *bestdistortion,
  1.1023 +                                     BLOCK_SIZE bsize, int64_t rd_thresh) {
  1.1024 +  MB_PREDICTION_MODE mode;
  1.1025 +  MACROBLOCKD *xd = &x->e_mbd;
  1.1026 +  int64_t best_rd = rd_thresh;
  1.1027 +  int rate = 0;
  1.1028 +  int64_t distortion;
  1.1029 +  struct macroblock_plane *p = &x->plane[0];
  1.1030 +  struct macroblockd_plane *pd = &xd->plane[0];
  1.1031 +  const int src_stride = p->src.stride;
  1.1032 +  const int dst_stride = pd->dst.stride;
  1.1033 +  uint8_t *src_init = raster_block_offset_uint8(BLOCK_8X8, ib,
  1.1034 +                                                p->src.buf, src_stride);
  1.1035 +  uint8_t *dst_init = raster_block_offset_uint8(BLOCK_8X8, ib,
  1.1036 +                                                pd->dst.buf, dst_stride);
  1.1037 +  int16_t *src_diff, *coeff;
  1.1038 +
  1.1039 +  ENTROPY_CONTEXT ta[2], tempa[2];
  1.1040 +  ENTROPY_CONTEXT tl[2], templ[2];
  1.1041 +
  1.1042 +  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
  1.1043 +  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
  1.1044 +  int idx, idy;
  1.1045 +  uint8_t best_dst[8 * 8];
  1.1046 +
  1.1047 +  assert(ib < 4);
  1.1048 +
  1.1049 +  vpx_memcpy(ta, a, sizeof(ta));
  1.1050 +  vpx_memcpy(tl, l, sizeof(tl));
  1.1051 +  xd->mi_8x8[0]->mbmi.tx_size = TX_4X4;
  1.1052 +
  1.1053 +  for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
  1.1054 +    int64_t this_rd;
  1.1055 +    int ratey = 0;
  1.1056 +
  1.1057 +    if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode)))
  1.1058 +      continue;
  1.1059 +
  1.1060 +    // Only do the oblique modes if the best so far is
  1.1061 +    // one of the neighboring directional modes
  1.1062 +    if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
  1.1063 +      if (conditional_skipintra(mode, *best_mode))
  1.1064 +          continue;
  1.1065 +    }
  1.1066 +
  1.1067 +    rate = bmode_costs[mode];
  1.1068 +    distortion = 0;
  1.1069 +
  1.1070 +    vpx_memcpy(tempa, ta, sizeof(ta));
  1.1071 +    vpx_memcpy(templ, tl, sizeof(tl));
  1.1072 +
  1.1073 +    for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
  1.1074 +      for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
  1.1075 +        int64_t ssz;
  1.1076 +        const int16_t *scan;
  1.1077 +        const int16_t *nb;
  1.1078 +        uint8_t *src = src_init + idx * 4 + idy * 4 * src_stride;
  1.1079 +        uint8_t *dst = dst_init + idx * 4 + idy * 4 * dst_stride;
  1.1080 +        const int block = ib + idy * 2 + idx;
  1.1081 +        TX_TYPE tx_type;
  1.1082 +        xd->mi_8x8[0]->bmi[block].as_mode = mode;
  1.1083 +        src_diff = raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
  1.1084 +        coeff = BLOCK_OFFSET(x->plane[0].coeff, block);
  1.1085 +        vp9_predict_intra_block(xd, block, 1,
  1.1086 +                                TX_4X4, mode,
  1.1087 +                                x->skip_encode ? src : dst,
  1.1088 +                                x->skip_encode ? src_stride : dst_stride,
  1.1089 +                                dst, dst_stride);
  1.1090 +        vp9_subtract_block(4, 4, src_diff, 8,
  1.1091 +                           src, src_stride,
  1.1092 +                           dst, dst_stride);
  1.1093 +
  1.1094 +        tx_type = get_tx_type_4x4(PLANE_TYPE_Y_WITH_DC, xd, block);
  1.1095 +        get_scan_nb_4x4(tx_type, &scan, &nb);
  1.1096 +
  1.1097 +        if (tx_type != DCT_DCT)
  1.1098 +          vp9_short_fht4x4(src_diff, coeff, 8, tx_type);
  1.1099 +        else
  1.1100 +          x->fwd_txm4x4(src_diff, coeff, 8);
  1.1101 +
  1.1102 +        vp9_regular_quantize_b_4x4(x, 4, block, scan, get_iscan_4x4(tx_type));
  1.1103 +
  1.1104 +        ratey += cost_coeffs(x, 0, block,
  1.1105 +                             tempa + idx, templ + idy, TX_4X4, scan, nb);
  1.1106 +        distortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, block),
  1.1107 +                                      16, &ssz) >> 2;
  1.1108 +        if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
  1.1109 +          goto next;
  1.1110 +
  1.1111 +        if (tx_type != DCT_DCT)
  1.1112 +          vp9_iht4x4_16_add(BLOCK_OFFSET(pd->dqcoeff, block),
  1.1113 +                               dst, pd->dst.stride, tx_type);
  1.1114 +        else
  1.1115 +          xd->itxm_add(BLOCK_OFFSET(pd->dqcoeff, block), dst, pd->dst.stride,
  1.1116 +                       16);
  1.1117 +      }
  1.1118 +    }
  1.1119 +
  1.1120 +    rate += ratey;
  1.1121 +    this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
  1.1122 +
  1.1123 +    if (this_rd < best_rd) {
  1.1124 +      *bestrate = rate;
  1.1125 +      *bestratey = ratey;
  1.1126 +      *bestdistortion = distortion;
  1.1127 +      best_rd = this_rd;
  1.1128 +      *best_mode = mode;
  1.1129 +      vpx_memcpy(a, tempa, sizeof(tempa));
  1.1130 +      vpx_memcpy(l, templ, sizeof(templ));
  1.1131 +      for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
  1.1132 +        vpx_memcpy(best_dst + idy * 8, dst_init + idy * dst_stride,
  1.1133 +                   num_4x4_blocks_wide * 4);
  1.1134 +    }
  1.1135 +  next:
  1.1136 +    {}
  1.1137 +  }
  1.1138 +
  1.1139 +  if (best_rd >= rd_thresh || x->skip_encode)
  1.1140 +    return best_rd;
  1.1141 +
  1.1142 +  for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
  1.1143 +    vpx_memcpy(dst_init + idy * dst_stride, best_dst + idy * 8,
  1.1144 +               num_4x4_blocks_wide * 4);
  1.1145 +
  1.1146 +  return best_rd;
  1.1147 +}
  1.1148 +
  1.1149 +static int64_t rd_pick_intra_sub_8x8_y_mode(VP9_COMP * const cpi,
  1.1150 +                                            MACROBLOCK * const mb,
  1.1151 +                                            int * const rate,
  1.1152 +                                            int * const rate_y,
  1.1153 +                                            int64_t * const distortion,
  1.1154 +                                            int64_t best_rd) {
  1.1155 +  int i, j;
  1.1156 +  MACROBLOCKD *const xd = &mb->e_mbd;
  1.1157 +  MODE_INFO *const mic = xd->mi_8x8[0];
  1.1158 +  const MODE_INFO *above_mi = xd->mi_8x8[-xd->mode_info_stride];
  1.1159 +  const MODE_INFO *left_mi = xd->left_available ? xd->mi_8x8[-1] : NULL;
  1.1160 +  const BLOCK_SIZE bsize = xd->mi_8x8[0]->mbmi.sb_type;
  1.1161 +  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
  1.1162 +  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
  1.1163 +  int idx, idy;
  1.1164 +  int cost = 0;
  1.1165 +  int64_t total_distortion = 0;
  1.1166 +  int tot_rate_y = 0;
  1.1167 +  int64_t total_rd = 0;
  1.1168 +  ENTROPY_CONTEXT t_above[4], t_left[4];
  1.1169 +  int *bmode_costs;
  1.1170 +
  1.1171 +  vpx_memcpy(t_above, xd->plane[0].above_context, sizeof(t_above));
  1.1172 +  vpx_memcpy(t_left, xd->plane[0].left_context, sizeof(t_left));
  1.1173 +
  1.1174 +  bmode_costs = mb->mbmode_cost;
  1.1175 +
  1.1176 +  // Pick modes for each sub-block (of size 4x4, 4x8, or 8x4) in an 8x8 block.
  1.1177 +  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
  1.1178 +    for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
  1.1179 +      MB_PREDICTION_MODE best_mode = DC_PRED;
  1.1180 +      int r = INT_MAX, ry = INT_MAX;
  1.1181 +      int64_t d = INT64_MAX, this_rd = INT64_MAX;
  1.1182 +      i = idy * 2 + idx;
  1.1183 +      if (cpi->common.frame_type == KEY_FRAME) {
  1.1184 +        const MB_PREDICTION_MODE A = above_block_mode(mic, above_mi, i);
  1.1185 +        const MB_PREDICTION_MODE L = left_block_mode(mic, left_mi, i);
  1.1186 +
  1.1187 +        bmode_costs  = mb->y_mode_costs[A][L];
  1.1188 +      }
  1.1189 +
  1.1190 +      this_rd = rd_pick_intra4x4block(cpi, mb, i, &best_mode, bmode_costs,
  1.1191 +                                      t_above + idx, t_left + idy, &r, &ry, &d,
  1.1192 +                                      bsize, best_rd - total_rd);
  1.1193 +      if (this_rd >= best_rd - total_rd)
  1.1194 +        return INT64_MAX;
  1.1195 +
  1.1196 +      total_rd += this_rd;
  1.1197 +      cost += r;
  1.1198 +      total_distortion += d;
  1.1199 +      tot_rate_y += ry;
  1.1200 +
  1.1201 +      mic->bmi[i].as_mode = best_mode;
  1.1202 +      for (j = 1; j < num_4x4_blocks_high; ++j)
  1.1203 +        mic->bmi[i + j * 2].as_mode = best_mode;
  1.1204 +      for (j = 1; j < num_4x4_blocks_wide; ++j)
  1.1205 +        mic->bmi[i + j].as_mode = best_mode;
  1.1206 +
  1.1207 +      if (total_rd >= best_rd)
  1.1208 +        return INT64_MAX;
  1.1209 +    }
  1.1210 +  }
  1.1211 +
  1.1212 +  *rate = cost;
  1.1213 +  *rate_y = tot_rate_y;
  1.1214 +  *distortion = total_distortion;
  1.1215 +  mic->mbmi.mode = mic->bmi[3].as_mode;
  1.1216 +
  1.1217 +  return RDCOST(mb->rdmult, mb->rddiv, cost, total_distortion);
  1.1218 +}
  1.1219 +
  1.1220 +static int64_t rd_pick_intra_sby_mode(VP9_COMP *cpi, MACROBLOCK *x,
  1.1221 +                                      int *rate, int *rate_tokenonly,
  1.1222 +                                      int64_t *distortion, int *skippable,
  1.1223 +                                      BLOCK_SIZE bsize,
  1.1224 +                                      int64_t tx_cache[TX_MODES],
  1.1225 +                                      int64_t best_rd) {
  1.1226 +  MB_PREDICTION_MODE mode;
  1.1227 +  MB_PREDICTION_MODE mode_selected = DC_PRED;
  1.1228 +  MACROBLOCKD *const xd = &x->e_mbd;
  1.1229 +  MODE_INFO *const mic = xd->mi_8x8[0];
  1.1230 +  int this_rate, this_rate_tokenonly, s;
  1.1231 +  int64_t this_distortion, this_rd;
  1.1232 +  TX_SIZE best_tx = TX_4X4;
  1.1233 +  int i;
  1.1234 +  int *bmode_costs = x->mbmode_cost;
  1.1235 +
  1.1236 +  if (cpi->sf.tx_size_search_method == USE_FULL_RD)
  1.1237 +    for (i = 0; i < TX_MODES; i++)
  1.1238 +      tx_cache[i] = INT64_MAX;
  1.1239 +
  1.1240 +  /* Y Search for intra prediction mode */
  1.1241 +  for (mode = DC_PRED; mode <= TM_PRED; mode++) {
  1.1242 +    int64_t local_tx_cache[TX_MODES];
  1.1243 +    MODE_INFO *above_mi = xd->mi_8x8[-xd->mode_info_stride];
  1.1244 +    MODE_INFO *left_mi = xd->left_available ? xd->mi_8x8[-1] : NULL;
  1.1245 +
  1.1246 +    if (!(cpi->sf.intra_y_mode_mask[max_txsize_lookup[bsize]] & (1 << mode)))
  1.1247 +      continue;
  1.1248 +
  1.1249 +    if (cpi->common.frame_type == KEY_FRAME) {
  1.1250 +      const MB_PREDICTION_MODE A = above_block_mode(mic, above_mi, 0);
  1.1251 +      const MB_PREDICTION_MODE L = left_block_mode(mic, left_mi, 0);
  1.1252 +
  1.1253 +      bmode_costs = x->y_mode_costs[A][L];
  1.1254 +    }
  1.1255 +    mic->mbmi.mode = mode;
  1.1256 +
  1.1257 +    super_block_yrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s, NULL,
  1.1258 +                    bsize, local_tx_cache, best_rd);
  1.1259 +
  1.1260 +    if (this_rate_tokenonly == INT_MAX)
  1.1261 +      continue;
  1.1262 +
  1.1263 +    this_rate = this_rate_tokenonly + bmode_costs[mode];
  1.1264 +    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
  1.1265 +
  1.1266 +    if (this_rd < best_rd) {
  1.1267 +      mode_selected   = mode;
  1.1268 +      best_rd         = this_rd;
  1.1269 +      best_tx         = mic->mbmi.tx_size;
  1.1270 +      *rate           = this_rate;
  1.1271 +      *rate_tokenonly = this_rate_tokenonly;
  1.1272 +      *distortion     = this_distortion;
  1.1273 +      *skippable      = s;
  1.1274 +    }
  1.1275 +
  1.1276 +    if (cpi->sf.tx_size_search_method == USE_FULL_RD && this_rd < INT64_MAX) {
  1.1277 +      for (i = 0; i < TX_MODES && local_tx_cache[i] < INT64_MAX; i++) {
  1.1278 +        const int64_t adj_rd = this_rd + local_tx_cache[i] -
  1.1279 +            local_tx_cache[cpi->common.tx_mode];
  1.1280 +        if (adj_rd < tx_cache[i]) {
  1.1281 +          tx_cache[i] = adj_rd;
  1.1282 +        }
  1.1283 +      }
  1.1284 +    }
  1.1285 +  }
  1.1286 +
  1.1287 +  mic->mbmi.mode = mode_selected;
  1.1288 +  mic->mbmi.tx_size = best_tx;
  1.1289 +
  1.1290 +  return best_rd;
  1.1291 +}
  1.1292 +
  1.1293 +static void super_block_uvrd(VP9_COMP *const cpi, MACROBLOCK *x,
  1.1294 +                             int *rate, int64_t *distortion, int *skippable,
  1.1295 +                             int64_t *sse, BLOCK_SIZE bsize,
  1.1296 +                             int64_t ref_best_rd) {
  1.1297 +  MACROBLOCKD *const xd = &x->e_mbd;
  1.1298 +  MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
  1.1299 +  TX_SIZE uv_txfm_size = get_uv_tx_size(mbmi);
  1.1300 +  int plane;
  1.1301 +  int pnrate = 0, pnskip = 1;
  1.1302 +  int64_t pndist = 0, pnsse = 0;
  1.1303 +
  1.1304 +  if (ref_best_rd < 0)
  1.1305 +    goto term;
  1.1306 +
  1.1307 +  if (is_inter_block(mbmi))
  1.1308 +    vp9_subtract_sbuv(x, bsize);
  1.1309 +
  1.1310 +  *rate = 0;
  1.1311 +  *distortion = 0;
  1.1312 +  *sse = 0;
  1.1313 +  *skippable = 1;
  1.1314 +
  1.1315 +  for (plane = 1; plane < MAX_MB_PLANE; ++plane) {
  1.1316 +    txfm_rd_in_plane(x, &cpi->rdcost_stack, &pnrate, &pndist, &pnskip, &pnsse,
  1.1317 +                     ref_best_rd, plane, bsize, uv_txfm_size);
  1.1318 +    if (pnrate == INT_MAX)
  1.1319 +      goto term;
  1.1320 +    *rate += pnrate;
  1.1321 +    *distortion += pndist;
  1.1322 +    *sse += pnsse;
  1.1323 +    *skippable &= pnskip;
  1.1324 +  }
  1.1325 +  return;
  1.1326 +
  1.1327 +  term:
  1.1328 +  *rate = INT_MAX;
  1.1329 +  *distortion = INT64_MAX;
  1.1330 +  *sse = INT64_MAX;
  1.1331 +  *skippable = 0;
  1.1332 +  return;
  1.1333 +}
  1.1334 +
  1.1335 +static int64_t rd_pick_intra_sbuv_mode(VP9_COMP *cpi, MACROBLOCK *x,
  1.1336 +                                       PICK_MODE_CONTEXT *ctx,
  1.1337 +                                       int *rate, int *rate_tokenonly,
  1.1338 +                                       int64_t *distortion, int *skippable,
  1.1339 +                                       BLOCK_SIZE bsize) {
  1.1340 +  MB_PREDICTION_MODE mode;
  1.1341 +  MB_PREDICTION_MODE mode_selected = DC_PRED;
  1.1342 +  int64_t best_rd = INT64_MAX, this_rd;
  1.1343 +  int this_rate_tokenonly, this_rate, s;
  1.1344 +  int64_t this_distortion, this_sse;
  1.1345 +
  1.1346 +  // int mode_mask = (bsize <= BLOCK_8X8)
  1.1347 +  //                ? ALL_INTRA_MODES : cpi->sf.intra_uv_mode_mask;
  1.1348 +
  1.1349 +  for (mode = DC_PRED; mode <= TM_PRED; mode ++) {
  1.1350 +    // if (!(mode_mask & (1 << mode)))
  1.1351 +    if (!(cpi->sf.intra_uv_mode_mask[max_uv_txsize_lookup[bsize]]
  1.1352 +          & (1 << mode)))
  1.1353 +      continue;
  1.1354 +
  1.1355 +    x->e_mbd.mi_8x8[0]->mbmi.uv_mode = mode;
  1.1356 +
  1.1357 +    super_block_uvrd(cpi, x, &this_rate_tokenonly,
  1.1358 +                     &this_distortion, &s, &this_sse, bsize, best_rd);
  1.1359 +    if (this_rate_tokenonly == INT_MAX)
  1.1360 +      continue;
  1.1361 +    this_rate = this_rate_tokenonly +
  1.1362 +                x->intra_uv_mode_cost[cpi->common.frame_type][mode];
  1.1363 +    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
  1.1364 +
  1.1365 +    if (this_rd < best_rd) {
  1.1366 +      mode_selected   = mode;
  1.1367 +      best_rd         = this_rd;
  1.1368 +      *rate           = this_rate;
  1.1369 +      *rate_tokenonly = this_rate_tokenonly;
  1.1370 +      *distortion     = this_distortion;
  1.1371 +      *skippable      = s;
  1.1372 +      if (!x->select_txfm_size) {
  1.1373 +        int i;
  1.1374 +        struct macroblock_plane *const p = x->plane;
  1.1375 +        struct macroblockd_plane *const pd = x->e_mbd.plane;
  1.1376 +        for (i = 1; i < MAX_MB_PLANE; ++i) {
  1.1377 +          p[i].coeff    = ctx->coeff_pbuf[i][2];
  1.1378 +          pd[i].qcoeff  = ctx->qcoeff_pbuf[i][2];
  1.1379 +          pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
  1.1380 +          pd[i].eobs    = ctx->eobs_pbuf[i][2];
  1.1381 +
  1.1382 +          ctx->coeff_pbuf[i][2]   = ctx->coeff_pbuf[i][0];
  1.1383 +          ctx->qcoeff_pbuf[i][2]  = ctx->qcoeff_pbuf[i][0];
  1.1384 +          ctx->dqcoeff_pbuf[i][2] = ctx->dqcoeff_pbuf[i][0];
  1.1385 +          ctx->eobs_pbuf[i][2]    = ctx->eobs_pbuf[i][0];
  1.1386 +
  1.1387 +          ctx->coeff_pbuf[i][0]   = p[i].coeff;
  1.1388 +          ctx->qcoeff_pbuf[i][0]  = pd[i].qcoeff;
  1.1389 +          ctx->dqcoeff_pbuf[i][0] = pd[i].dqcoeff;
  1.1390 +          ctx->eobs_pbuf[i][0]    = pd[i].eobs;
  1.1391 +        }
  1.1392 +      }
  1.1393 +    }
  1.1394 +  }
  1.1395 +
  1.1396 +  x->e_mbd.mi_8x8[0]->mbmi.uv_mode = mode_selected;
  1.1397 +
  1.1398 +  return best_rd;
  1.1399 +}
  1.1400 +
  1.1401 +static int64_t rd_sbuv_dcpred(VP9_COMP *cpi, MACROBLOCK *x,
  1.1402 +                              int *rate, int *rate_tokenonly,
  1.1403 +                              int64_t *distortion, int *skippable,
  1.1404 +                              BLOCK_SIZE bsize) {
  1.1405 +  int64_t this_rd;
  1.1406 +  int64_t this_sse;
  1.1407 +
  1.1408 +  x->e_mbd.mi_8x8[0]->mbmi.uv_mode = DC_PRED;
  1.1409 +  super_block_uvrd(cpi, x, rate_tokenonly, distortion,
  1.1410 +                   skippable, &this_sse, bsize, INT64_MAX);
  1.1411 +  *rate = *rate_tokenonly +
  1.1412 +          x->intra_uv_mode_cost[cpi->common.frame_type][DC_PRED];
  1.1413 +  this_rd = RDCOST(x->rdmult, x->rddiv, *rate, *distortion);
  1.1414 +
  1.1415 +  return this_rd;
  1.1416 +}
  1.1417 +
  1.1418 +static void choose_intra_uv_mode(VP9_COMP *cpi, PICK_MODE_CONTEXT *ctx,
  1.1419 +                                 BLOCK_SIZE bsize, int *rate_uv,
  1.1420 +                                 int *rate_uv_tokenonly,
  1.1421 +                                 int64_t *dist_uv, int *skip_uv,
  1.1422 +                                 MB_PREDICTION_MODE *mode_uv) {
  1.1423 +  MACROBLOCK *const x = &cpi->mb;
  1.1424 +
  1.1425 +  // Use an estimated rd for uv_intra based on DC_PRED if the
  1.1426 +  // appropriate speed flag is set.
  1.1427 +  if (cpi->sf.use_uv_intra_rd_estimate) {
  1.1428 +    rd_sbuv_dcpred(cpi, x, rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
  1.1429 +                   bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
  1.1430 +  // Else do a proper rd search for each possible transform size that may
  1.1431 +  // be considered in the main rd loop.
  1.1432 +  } else {
  1.1433 +    rd_pick_intra_sbuv_mode(cpi, x, ctx,
  1.1434 +                            rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
  1.1435 +                            bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
  1.1436 +  }
  1.1437 +  *mode_uv = x->e_mbd.mi_8x8[0]->mbmi.uv_mode;
  1.1438 +}
  1.1439 +
  1.1440 +static int cost_mv_ref(VP9_COMP *cpi, MB_PREDICTION_MODE mode,
  1.1441 +                       int mode_context) {
  1.1442 +  MACROBLOCK *const x = &cpi->mb;
  1.1443 +  MACROBLOCKD *const xd = &x->e_mbd;
  1.1444 +  const int segment_id = xd->mi_8x8[0]->mbmi.segment_id;
  1.1445 +
  1.1446 +  // Don't account for mode here if segment skip is enabled.
  1.1447 +  if (!vp9_segfeature_active(&cpi->common.seg, segment_id, SEG_LVL_SKIP)) {
  1.1448 +    assert(is_inter_mode(mode));
  1.1449 +    return x->inter_mode_cost[mode_context][INTER_OFFSET(mode)];
  1.1450 +  } else {
  1.1451 +    return 0;
  1.1452 +  }
  1.1453 +}
  1.1454 +
  1.1455 +void vp9_set_mbmode_and_mvs(MACROBLOCK *x, MB_PREDICTION_MODE mb, int_mv *mv) {
  1.1456 +  x->e_mbd.mi_8x8[0]->mbmi.mode = mb;
  1.1457 +  x->e_mbd.mi_8x8[0]->mbmi.mv[0].as_int = mv->as_int;
  1.1458 +}
  1.1459 +
  1.1460 +static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
  1.1461 +                                BLOCK_SIZE bsize,
  1.1462 +                                int_mv *frame_mv,
  1.1463 +                                int mi_row, int mi_col,
  1.1464 +                                int_mv single_newmv[MAX_REF_FRAMES],
  1.1465 +                                int *rate_mv);
  1.1466 +
  1.1467 +static int labels2mode(MACROBLOCK *x, int i,
  1.1468 +                       MB_PREDICTION_MODE this_mode,
  1.1469 +                       int_mv *this_mv, int_mv *this_second_mv,
  1.1470 +                       int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
  1.1471 +                       int_mv seg_mvs[MAX_REF_FRAMES],
  1.1472 +                       int_mv *best_ref_mv,
  1.1473 +                       int_mv *second_best_ref_mv,
  1.1474 +                       int *mvjcost, int *mvcost[2], VP9_COMP *cpi) {
  1.1475 +  MACROBLOCKD *const xd = &x->e_mbd;
  1.1476 +  MODE_INFO *const mic = xd->mi_8x8[0];
  1.1477 +  MB_MODE_INFO *mbmi = &mic->mbmi;
  1.1478 +  int cost = 0, thismvcost = 0;
  1.1479 +  int idx, idy;
  1.1480 +  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[mbmi->sb_type];
  1.1481 +  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[mbmi->sb_type];
  1.1482 +  const int has_second_rf = has_second_ref(mbmi);
  1.1483 +
  1.1484 +  /* We have to be careful retrieving previously-encoded motion vectors.
  1.1485 +   Ones from this macroblock have to be pulled from the BLOCKD array
  1.1486 +   as they have not yet made it to the bmi array in our MB_MODE_INFO. */
  1.1487 +  MB_PREDICTION_MODE m;
  1.1488 +
  1.1489 +  // the only time we should do costing for new motion vector or mode
  1.1490 +  // is when we are on a new label  (jbb May 08, 2007)
  1.1491 +  switch (m = this_mode) {
  1.1492 +    case NEWMV:
  1.1493 +      this_mv->as_int = seg_mvs[mbmi->ref_frame[0]].as_int;
  1.1494 +      thismvcost  = vp9_mv_bit_cost(&this_mv->as_mv, &best_ref_mv->as_mv,
  1.1495 +                                    mvjcost, mvcost, MV_COST_WEIGHT_SUB);
  1.1496 +      if (has_second_rf) {
  1.1497 +        this_second_mv->as_int = seg_mvs[mbmi->ref_frame[1]].as_int;
  1.1498 +        thismvcost += vp9_mv_bit_cost(&this_second_mv->as_mv,
  1.1499 +                                      &second_best_ref_mv->as_mv,
  1.1500 +                                      mvjcost, mvcost, MV_COST_WEIGHT_SUB);
  1.1501 +      }
  1.1502 +      break;
  1.1503 +    case NEARESTMV:
  1.1504 +      this_mv->as_int = frame_mv[NEARESTMV][mbmi->ref_frame[0]].as_int;
  1.1505 +      if (has_second_rf)
  1.1506 +        this_second_mv->as_int =
  1.1507 +            frame_mv[NEARESTMV][mbmi->ref_frame[1]].as_int;
  1.1508 +      break;
  1.1509 +    case NEARMV:
  1.1510 +      this_mv->as_int = frame_mv[NEARMV][mbmi->ref_frame[0]].as_int;
  1.1511 +      if (has_second_rf)
  1.1512 +        this_second_mv->as_int =
  1.1513 +            frame_mv[NEARMV][mbmi->ref_frame[1]].as_int;
  1.1514 +      break;
  1.1515 +    case ZEROMV:
  1.1516 +      this_mv->as_int = 0;
  1.1517 +      if (has_second_rf)
  1.1518 +        this_second_mv->as_int = 0;
  1.1519 +      break;
  1.1520 +    default:
  1.1521 +      break;
  1.1522 +  }
  1.1523 +
  1.1524 +  cost = cost_mv_ref(cpi, this_mode,
  1.1525 +                     mbmi->mode_context[mbmi->ref_frame[0]]);
  1.1526 +
  1.1527 +  mic->bmi[i].as_mv[0].as_int = this_mv->as_int;
  1.1528 +  if (has_second_rf)
  1.1529 +    mic->bmi[i].as_mv[1].as_int = this_second_mv->as_int;
  1.1530 +
  1.1531 +  mic->bmi[i].as_mode = m;
  1.1532 +
  1.1533 +  for (idy = 0; idy < num_4x4_blocks_high; ++idy)
  1.1534 +    for (idx = 0; idx < num_4x4_blocks_wide; ++idx)
  1.1535 +      vpx_memcpy(&mic->bmi[i + idy * 2 + idx],
  1.1536 +                 &mic->bmi[i], sizeof(mic->bmi[i]));
  1.1537 +
  1.1538 +  cost += thismvcost;
  1.1539 +  return cost;
  1.1540 +}
  1.1541 +
  1.1542 +static int64_t encode_inter_mb_segment(VP9_COMP *cpi,
  1.1543 +                                       MACROBLOCK *x,
  1.1544 +                                       int64_t best_yrd,
  1.1545 +                                       int i,
  1.1546 +                                       int *labelyrate,
  1.1547 +                                       int64_t *distortion, int64_t *sse,
  1.1548 +                                       ENTROPY_CONTEXT *ta,
  1.1549 +                                       ENTROPY_CONTEXT *tl) {
  1.1550 +  int k;
  1.1551 +  MACROBLOCKD *xd = &x->e_mbd;
  1.1552 +  struct macroblockd_plane *const pd = &xd->plane[0];
  1.1553 +  struct macroblock_plane *const p = &x->plane[0];
  1.1554 +  MODE_INFO *const mi = xd->mi_8x8[0];
  1.1555 +  const BLOCK_SIZE bsize = mi->mbmi.sb_type;
  1.1556 +  const int width = plane_block_width(bsize, pd);
  1.1557 +  const int height = plane_block_height(bsize, pd);
  1.1558 +  int idx, idy;
  1.1559 +
  1.1560 +  uint8_t *const src = raster_block_offset_uint8(BLOCK_8X8, i,
  1.1561 +                                                 p->src.buf, p->src.stride);
  1.1562 +  uint8_t *const dst = raster_block_offset_uint8(BLOCK_8X8, i,
  1.1563 +                                                 pd->dst.buf, pd->dst.stride);
  1.1564 +  int64_t thisdistortion = 0, thissse = 0;
  1.1565 +  int thisrate = 0, ref;
  1.1566 +  const int is_compound = has_second_ref(&mi->mbmi);
  1.1567 +  for (ref = 0; ref < 1 + is_compound; ++ref) {
  1.1568 +    const uint8_t *pre = raster_block_offset_uint8(BLOCK_8X8, i,
  1.1569 +                                     pd->pre[ref].buf, pd->pre[ref].stride);
  1.1570 +    vp9_build_inter_predictor(pre, pd->pre[ref].stride,
  1.1571 +                              dst, pd->dst.stride,
  1.1572 +                              &mi->bmi[i].as_mv[ref].as_mv,
  1.1573 +                              &xd->scale_factor[ref],
  1.1574 +                              width, height, ref, &xd->subpix, MV_PRECISION_Q3);
  1.1575 +  }
  1.1576 +
  1.1577 +  vp9_subtract_block(height, width,
  1.1578 +                     raster_block_offset_int16(BLOCK_8X8, i, p->src_diff), 8,
  1.1579 +                     src, p->src.stride,
  1.1580 +                     dst, pd->dst.stride);
  1.1581 +
  1.1582 +  k = i;
  1.1583 +  for (idy = 0; idy < height / 4; ++idy) {
  1.1584 +    for (idx = 0; idx < width / 4; ++idx) {
  1.1585 +      int64_t ssz, rd, rd1, rd2;
  1.1586 +      int16_t* coeff;
  1.1587 +
  1.1588 +      k += (idy * 2 + idx);
  1.1589 +      coeff = BLOCK_OFFSET(p->coeff, k);
  1.1590 +      x->fwd_txm4x4(raster_block_offset_int16(BLOCK_8X8, k, p->src_diff),
  1.1591 +                    coeff, 8);
  1.1592 +      vp9_regular_quantize_b_4x4(x, 4, k, get_scan_4x4(DCT_DCT),
  1.1593 +                                 get_iscan_4x4(DCT_DCT));
  1.1594 +      thisdistortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, k),
  1.1595 +                                        16, &ssz);
  1.1596 +      thissse += ssz;
  1.1597 +      thisrate += cost_coeffs(x, 0, k,
  1.1598 +                              ta + (k & 1),
  1.1599 +                              tl + (k >> 1), TX_4X4,
  1.1600 +                              vp9_default_scan_4x4,
  1.1601 +                              vp9_default_scan_4x4_neighbors);
  1.1602 +      rd1 = RDCOST(x->rdmult, x->rddiv, thisrate, thisdistortion >> 2);
  1.1603 +      rd2 = RDCOST(x->rdmult, x->rddiv, 0, thissse >> 2);
  1.1604 +      rd = MIN(rd1, rd2);
  1.1605 +      if (rd >= best_yrd)
  1.1606 +        return INT64_MAX;
  1.1607 +    }
  1.1608 +  }
  1.1609 +
  1.1610 +  *distortion = thisdistortion >> 2;
  1.1611 +  *labelyrate = thisrate;
  1.1612 +  *sse = thissse >> 2;
  1.1613 +
  1.1614 +  return RDCOST(x->rdmult, x->rddiv, *labelyrate, *distortion);
  1.1615 +}
  1.1616 +
  1.1617 +typedef struct {
  1.1618 +  int eobs;
  1.1619 +  int brate;
  1.1620 +  int byrate;
  1.1621 +  int64_t bdist;
  1.1622 +  int64_t bsse;
  1.1623 +  int64_t brdcost;
  1.1624 +  int_mv mvs[2];
  1.1625 +  ENTROPY_CONTEXT ta[2];
  1.1626 +  ENTROPY_CONTEXT tl[2];
  1.1627 +} SEG_RDSTAT;
  1.1628 +
  1.1629 +typedef struct {
  1.1630 +  int_mv *ref_mv, *second_ref_mv;
  1.1631 +  int_mv mvp;
  1.1632 +
  1.1633 +  int64_t segment_rd;
  1.1634 +  int r;
  1.1635 +  int64_t d;
  1.1636 +  int64_t sse;
  1.1637 +  int segment_yrate;
  1.1638 +  MB_PREDICTION_MODE modes[4];
  1.1639 +  SEG_RDSTAT rdstat[4][INTER_MODES];
  1.1640 +  int mvthresh;
  1.1641 +} BEST_SEG_INFO;
  1.1642 +
  1.1643 +static INLINE int mv_check_bounds(MACROBLOCK *x, int_mv *mv) {
  1.1644 +  int r = 0;
  1.1645 +  r |= (mv->as_mv.row >> 3) < x->mv_row_min;
  1.1646 +  r |= (mv->as_mv.row >> 3) > x->mv_row_max;
  1.1647 +  r |= (mv->as_mv.col >> 3) < x->mv_col_min;
  1.1648 +  r |= (mv->as_mv.col >> 3) > x->mv_col_max;
  1.1649 +  return r;
  1.1650 +}
  1.1651 +
  1.1652 +static INLINE void mi_buf_shift(MACROBLOCK *x, int i) {
  1.1653 +  MB_MODE_INFO *const mbmi = &x->e_mbd.mi_8x8[0]->mbmi;
  1.1654 +  struct macroblock_plane *const p = &x->plane[0];
  1.1655 +  struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
  1.1656 +
  1.1657 +  p->src.buf = raster_block_offset_uint8(BLOCK_8X8, i, p->src.buf,
  1.1658 +                                         p->src.stride);
  1.1659 +  assert(((intptr_t)pd->pre[0].buf & 0x7) == 0);
  1.1660 +  pd->pre[0].buf = raster_block_offset_uint8(BLOCK_8X8, i, pd->pre[0].buf,
  1.1661 +                                             pd->pre[0].stride);
  1.1662 +  if (has_second_ref(mbmi))
  1.1663 +    pd->pre[1].buf = raster_block_offset_uint8(BLOCK_8X8, i, pd->pre[1].buf,
  1.1664 +                                               pd->pre[1].stride);
  1.1665 +}
  1.1666 +
  1.1667 +static INLINE void mi_buf_restore(MACROBLOCK *x, struct buf_2d orig_src,
  1.1668 +                                  struct buf_2d orig_pre[2]) {
  1.1669 +  MB_MODE_INFO *mbmi = &x->e_mbd.mi_8x8[0]->mbmi;
  1.1670 +  x->plane[0].src = orig_src;
  1.1671 +  x->e_mbd.plane[0].pre[0] = orig_pre[0];
  1.1672 +  if (has_second_ref(mbmi))
  1.1673 +    x->e_mbd.plane[0].pre[1] = orig_pre[1];
  1.1674 +}
  1.1675 +
  1.1676 +static void rd_check_segment_txsize(VP9_COMP *cpi, MACROBLOCK *x,
  1.1677 +                                    const TileInfo *const tile,
  1.1678 +                                    BEST_SEG_INFO *bsi_buf, int filter_idx,
  1.1679 +                                    int_mv seg_mvs[4][MAX_REF_FRAMES],
  1.1680 +                                    int mi_row, int mi_col) {
  1.1681 +  int i, br = 0, idx, idy;
  1.1682 +  int64_t bd = 0, block_sse = 0;
  1.1683 +  MB_PREDICTION_MODE this_mode;
  1.1684 +  MODE_INFO *mi = x->e_mbd.mi_8x8[0];
  1.1685 +  MB_MODE_INFO *const mbmi = &mi->mbmi;
  1.1686 +  struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
  1.1687 +  const int label_count = 4;
  1.1688 +  int64_t this_segment_rd = 0;
  1.1689 +  int label_mv_thresh;
  1.1690 +  int segmentyrate = 0;
  1.1691 +  const BLOCK_SIZE bsize = mbmi->sb_type;
  1.1692 +  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
  1.1693 +  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
  1.1694 +  vp9_variance_fn_ptr_t *v_fn_ptr;
  1.1695 +  ENTROPY_CONTEXT t_above[2], t_left[2];
  1.1696 +  BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
  1.1697 +  int mode_idx;
  1.1698 +  int subpelmv = 1, have_ref = 0;
  1.1699 +  const int has_second_rf = has_second_ref(mbmi);
  1.1700 +
  1.1701 +  vpx_memcpy(t_above, pd->above_context, sizeof(t_above));
  1.1702 +  vpx_memcpy(t_left, pd->left_context, sizeof(t_left));
  1.1703 +
  1.1704 +  v_fn_ptr = &cpi->fn_ptr[bsize];
  1.1705 +
  1.1706 +  // 64 makes this threshold really big effectively
  1.1707 +  // making it so that we very rarely check mvs on
  1.1708 +  // segments.   setting this to 1 would make mv thresh
  1.1709 +  // roughly equal to what it is for macroblocks
  1.1710 +  label_mv_thresh = 1 * bsi->mvthresh / label_count;
  1.1711 +
  1.1712 +  // Segmentation method overheads
  1.1713 +  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
  1.1714 +    for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
  1.1715 +      // TODO(jingning,rbultje): rewrite the rate-distortion optimization
  1.1716 +      // loop for 4x4/4x8/8x4 block coding. to be replaced with new rd loop
  1.1717 +      int_mv mode_mv[MB_MODE_COUNT], second_mode_mv[MB_MODE_COUNT];
  1.1718 +      int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
  1.1719 +      MB_PREDICTION_MODE mode_selected = ZEROMV;
  1.1720 +      int64_t best_rd = INT64_MAX;
  1.1721 +      i = idy * 2 + idx;
  1.1722 +
  1.1723 +      frame_mv[ZEROMV][mbmi->ref_frame[0]].as_int = 0;
  1.1724 +      vp9_append_sub8x8_mvs_for_idx(&cpi->common, &x->e_mbd, tile,
  1.1725 +                                    &frame_mv[NEARESTMV][mbmi->ref_frame[0]],
  1.1726 +                                    &frame_mv[NEARMV][mbmi->ref_frame[0]],
  1.1727 +                                    i, 0, mi_row, mi_col);
  1.1728 +      if (has_second_rf) {
  1.1729 +        frame_mv[ZEROMV][mbmi->ref_frame[1]].as_int = 0;
  1.1730 +        vp9_append_sub8x8_mvs_for_idx(&cpi->common, &x->e_mbd, tile,
  1.1731 +                                      &frame_mv[NEARESTMV][mbmi->ref_frame[1]],
  1.1732 +                                      &frame_mv[NEARMV][mbmi->ref_frame[1]],
  1.1733 +                                      i, 1, mi_row, mi_col);
  1.1734 +      }
  1.1735 +      // search for the best motion vector on this segment
  1.1736 +      for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
  1.1737 +        const struct buf_2d orig_src = x->plane[0].src;
  1.1738 +        struct buf_2d orig_pre[2];
  1.1739 +
  1.1740 +        mode_idx = INTER_OFFSET(this_mode);
  1.1741 +        bsi->rdstat[i][mode_idx].brdcost = INT64_MAX;
  1.1742 +
  1.1743 +        // if we're near/nearest and mv == 0,0, compare to zeromv
  1.1744 +        if ((this_mode == NEARMV || this_mode == NEARESTMV ||
  1.1745 +             this_mode == ZEROMV) &&
  1.1746 +            frame_mv[this_mode][mbmi->ref_frame[0]].as_int == 0 &&
  1.1747 +            (!has_second_rf ||
  1.1748 +             frame_mv[this_mode][mbmi->ref_frame[1]].as_int == 0)) {
  1.1749 +          int rfc = mbmi->mode_context[mbmi->ref_frame[0]];
  1.1750 +          int c1 = cost_mv_ref(cpi, NEARMV, rfc);
  1.1751 +          int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
  1.1752 +          int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
  1.1753 +
  1.1754 +          if (this_mode == NEARMV) {
  1.1755 +            if (c1 > c3)
  1.1756 +              continue;
  1.1757 +          } else if (this_mode == NEARESTMV) {
  1.1758 +            if (c2 > c3)
  1.1759 +              continue;
  1.1760 +          } else {
  1.1761 +            assert(this_mode == ZEROMV);
  1.1762 +            if (!has_second_rf) {
  1.1763 +              if ((c3 >= c2 &&
  1.1764 +                   frame_mv[NEARESTMV][mbmi->ref_frame[0]].as_int == 0) ||
  1.1765 +                  (c3 >= c1 &&
  1.1766 +                   frame_mv[NEARMV][mbmi->ref_frame[0]].as_int == 0))
  1.1767 +                continue;
  1.1768 +            } else {
  1.1769 +              if ((c3 >= c2 &&
  1.1770 +                   frame_mv[NEARESTMV][mbmi->ref_frame[0]].as_int == 0 &&
  1.1771 +                   frame_mv[NEARESTMV][mbmi->ref_frame[1]].as_int == 0) ||
  1.1772 +                  (c3 >= c1 &&
  1.1773 +                   frame_mv[NEARMV][mbmi->ref_frame[0]].as_int == 0 &&
  1.1774 +                   frame_mv[NEARMV][mbmi->ref_frame[1]].as_int == 0))
  1.1775 +                continue;
  1.1776 +            }
  1.1777 +          }
  1.1778 +        }
  1.1779 +
  1.1780 +        vpx_memcpy(orig_pre, pd->pre, sizeof(orig_pre));
  1.1781 +        vpx_memcpy(bsi->rdstat[i][mode_idx].ta, t_above,
  1.1782 +                   sizeof(bsi->rdstat[i][mode_idx].ta));
  1.1783 +        vpx_memcpy(bsi->rdstat[i][mode_idx].tl, t_left,
  1.1784 +                   sizeof(bsi->rdstat[i][mode_idx].tl));
  1.1785 +
  1.1786 +        // motion search for newmv (single predictor case only)
  1.1787 +        if (!has_second_rf && this_mode == NEWMV &&
  1.1788 +            seg_mvs[i][mbmi->ref_frame[0]].as_int == INVALID_MV) {
  1.1789 +          int step_param = 0;
  1.1790 +          int further_steps;
  1.1791 +          int thissme, bestsme = INT_MAX;
  1.1792 +          int sadpb = x->sadperbit4;
  1.1793 +          int_mv mvp_full;
  1.1794 +          int max_mv;
  1.1795 +
  1.1796 +          /* Is the best so far sufficiently good that we cant justify doing
  1.1797 +           * and new motion search. */
  1.1798 +          if (best_rd < label_mv_thresh)
  1.1799 +            break;
  1.1800 +
  1.1801 +          if (cpi->compressor_speed) {
  1.1802 +            // use previous block's result as next block's MV predictor.
  1.1803 +            if (i > 0) {
  1.1804 +              bsi->mvp.as_int = mi->bmi[i - 1].as_mv[0].as_int;
  1.1805 +              if (i == 2)
  1.1806 +                bsi->mvp.as_int = mi->bmi[i - 2].as_mv[0].as_int;
  1.1807 +            }
  1.1808 +          }
  1.1809 +          if (i == 0)
  1.1810 +            max_mv = x->max_mv_context[mbmi->ref_frame[0]];
  1.1811 +          else
  1.1812 +            max_mv = MAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
  1.1813 +
  1.1814 +          if (cpi->sf.auto_mv_step_size && cpi->common.show_frame) {
  1.1815 +            // Take wtd average of the step_params based on the last frame's
  1.1816 +            // max mv magnitude and the best ref mvs of the current block for
  1.1817 +            // the given reference.
  1.1818 +            step_param = (vp9_init_search_range(cpi, max_mv) +
  1.1819 +                          cpi->mv_step_param) >> 1;
  1.1820 +          } else {
  1.1821 +            step_param = cpi->mv_step_param;
  1.1822 +          }
  1.1823 +
  1.1824 +          mvp_full.as_mv.row = bsi->mvp.as_mv.row >> 3;
  1.1825 +          mvp_full.as_mv.col = bsi->mvp.as_mv.col >> 3;
  1.1826 +
  1.1827 +          if (cpi->sf.adaptive_motion_search && cpi->common.show_frame) {
  1.1828 +            mvp_full.as_mv.row = x->pred_mv[mbmi->ref_frame[0]].as_mv.row >> 3;
  1.1829 +            mvp_full.as_mv.col = x->pred_mv[mbmi->ref_frame[0]].as_mv.col >> 3;
  1.1830 +            step_param = MAX(step_param, 8);
  1.1831 +          }
  1.1832 +
  1.1833 +          further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
  1.1834 +          // adjust src pointer for this block
  1.1835 +          mi_buf_shift(x, i);
  1.1836 +          if (cpi->sf.search_method == HEX) {
  1.1837 +            bestsme = vp9_hex_search(x, &mvp_full.as_mv,
  1.1838 +                                     step_param,
  1.1839 +                                     sadpb, 1, v_fn_ptr, 1,
  1.1840 +                                     &bsi->ref_mv->as_mv,
  1.1841 +                                     &mode_mv[NEWMV].as_mv);
  1.1842 +          } else if (cpi->sf.search_method == SQUARE) {
  1.1843 +            bestsme = vp9_square_search(x, &mvp_full.as_mv,
  1.1844 +                                        step_param,
  1.1845 +                                        sadpb, 1, v_fn_ptr, 1,
  1.1846 +                                        &bsi->ref_mv->as_mv,
  1.1847 +                                        &mode_mv[NEWMV].as_mv);
  1.1848 +          } else if (cpi->sf.search_method == BIGDIA) {
  1.1849 +            bestsme = vp9_bigdia_search(x, &mvp_full.as_mv,
  1.1850 +                                        step_param,
  1.1851 +                                        sadpb, 1, v_fn_ptr, 1,
  1.1852 +                                        &bsi->ref_mv->as_mv,
  1.1853 +                                        &mode_mv[NEWMV].as_mv);
  1.1854 +          } else {
  1.1855 +            bestsme = vp9_full_pixel_diamond(cpi, x, &mvp_full, step_param,
  1.1856 +                                             sadpb, further_steps, 0, v_fn_ptr,
  1.1857 +                                             bsi->ref_mv, &mode_mv[NEWMV]);
  1.1858 +          }
  1.1859 +
  1.1860 +          // Should we do a full search (best quality only)
  1.1861 +          if (cpi->compressor_speed == 0) {
  1.1862 +            /* Check if mvp_full is within the range. */
  1.1863 +            clamp_mv(&mvp_full.as_mv, x->mv_col_min, x->mv_col_max,
  1.1864 +                     x->mv_row_min, x->mv_row_max);
  1.1865 +
  1.1866 +            thissme = cpi->full_search_sad(x, &mvp_full,
  1.1867 +                                           sadpb, 16, v_fn_ptr,
  1.1868 +                                           x->nmvjointcost, x->mvcost,
  1.1869 +                                           bsi->ref_mv, i);
  1.1870 +
  1.1871 +            if (thissme < bestsme) {
  1.1872 +              bestsme = thissme;
  1.1873 +              mode_mv[NEWMV].as_int = mi->bmi[i].as_mv[0].as_int;
  1.1874 +            } else {
  1.1875 +              /* The full search result is actually worse so re-instate the
  1.1876 +               * previous best vector */
  1.1877 +              mi->bmi[i].as_mv[0].as_int = mode_mv[NEWMV].as_int;
  1.1878 +            }
  1.1879 +          }
  1.1880 +
  1.1881 +          if (bestsme < INT_MAX) {
  1.1882 +            int distortion;
  1.1883 +            unsigned int sse;
  1.1884 +            cpi->find_fractional_mv_step(x,
  1.1885 +                                         &mode_mv[NEWMV].as_mv,
  1.1886 +                                         &bsi->ref_mv->as_mv,
  1.1887 +                                         cpi->common.allow_high_precision_mv,
  1.1888 +                                         x->errorperbit, v_fn_ptr,
  1.1889 +                                         0, cpi->sf.subpel_iters_per_step,
  1.1890 +                                         x->nmvjointcost, x->mvcost,
  1.1891 +                                         &distortion, &sse);
  1.1892 +
  1.1893 +            // save motion search result for use in compound prediction
  1.1894 +            seg_mvs[i][mbmi->ref_frame[0]].as_int = mode_mv[NEWMV].as_int;
  1.1895 +          }
  1.1896 +
  1.1897 +          if (cpi->sf.adaptive_motion_search)
  1.1898 +            x->pred_mv[mbmi->ref_frame[0]].as_int = mode_mv[NEWMV].as_int;
  1.1899 +
  1.1900 +          // restore src pointers
  1.1901 +          mi_buf_restore(x, orig_src, orig_pre);
  1.1902 +        }
  1.1903 +
  1.1904 +        if (has_second_rf) {
  1.1905 +          if (seg_mvs[i][mbmi->ref_frame[1]].as_int == INVALID_MV ||
  1.1906 +              seg_mvs[i][mbmi->ref_frame[0]].as_int == INVALID_MV)
  1.1907 +            continue;
  1.1908 +        }
  1.1909 +
  1.1910 +        if (has_second_rf && this_mode == NEWMV &&
  1.1911 +            mbmi->interp_filter == EIGHTTAP) {
  1.1912 +          // adjust src pointers
  1.1913 +          mi_buf_shift(x, i);
  1.1914 +          if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
  1.1915 +            int rate_mv;
  1.1916 +            joint_motion_search(cpi, x, bsize, frame_mv[this_mode],
  1.1917 +                                mi_row, mi_col, seg_mvs[i],
  1.1918 +                                &rate_mv);
  1.1919 +            seg_mvs[i][mbmi->ref_frame[0]].as_int =
  1.1920 +                frame_mv[this_mode][mbmi->ref_frame[0]].as_int;
  1.1921 +            seg_mvs[i][mbmi->ref_frame[1]].as_int =
  1.1922 +                frame_mv[this_mode][mbmi->ref_frame[1]].as_int;
  1.1923 +          }
  1.1924 +          // restore src pointers
  1.1925 +          mi_buf_restore(x, orig_src, orig_pre);
  1.1926 +        }
  1.1927 +
  1.1928 +        bsi->rdstat[i][mode_idx].brate =
  1.1929 +            labels2mode(x, i, this_mode, &mode_mv[this_mode],
  1.1930 +                        &second_mode_mv[this_mode], frame_mv, seg_mvs[i],
  1.1931 +                        bsi->ref_mv, bsi->second_ref_mv, x->nmvjointcost,
  1.1932 +                        x->mvcost, cpi);
  1.1933 +
  1.1934 +
  1.1935 +        bsi->rdstat[i][mode_idx].mvs[0].as_int = mode_mv[this_mode].as_int;
  1.1936 +        if (num_4x4_blocks_wide > 1)
  1.1937 +          bsi->rdstat[i + 1][mode_idx].mvs[0].as_int =
  1.1938 +              mode_mv[this_mode].as_int;
  1.1939 +        if (num_4x4_blocks_high > 1)
  1.1940 +          bsi->rdstat[i + 2][mode_idx].mvs[0].as_int =
  1.1941 +              mode_mv[this_mode].as_int;
  1.1942 +        if (has_second_rf) {
  1.1943 +          bsi->rdstat[i][mode_idx].mvs[1].as_int =
  1.1944 +              second_mode_mv[this_mode].as_int;
  1.1945 +          if (num_4x4_blocks_wide > 1)
  1.1946 +            bsi->rdstat[i + 1][mode_idx].mvs[1].as_int =
  1.1947 +                second_mode_mv[this_mode].as_int;
  1.1948 +          if (num_4x4_blocks_high > 1)
  1.1949 +            bsi->rdstat[i + 2][mode_idx].mvs[1].as_int =
  1.1950 +                second_mode_mv[this_mode].as_int;
  1.1951 +        }
  1.1952 +
  1.1953 +        // Trap vectors that reach beyond the UMV borders
  1.1954 +        if (mv_check_bounds(x, &mode_mv[this_mode]))
  1.1955 +          continue;
  1.1956 +        if (has_second_rf &&
  1.1957 +            mv_check_bounds(x, &second_mode_mv[this_mode]))
  1.1958 +          continue;
  1.1959 +
  1.1960 +        if (filter_idx > 0) {
  1.1961 +          BEST_SEG_INFO *ref_bsi = bsi_buf;
  1.1962 +          subpelmv = (mode_mv[this_mode].as_mv.row & 0x0f) ||
  1.1963 +                     (mode_mv[this_mode].as_mv.col & 0x0f);
  1.1964 +          have_ref = mode_mv[this_mode].as_int ==
  1.1965 +                     ref_bsi->rdstat[i][mode_idx].mvs[0].as_int;
  1.1966 +          if (has_second_rf) {
  1.1967 +            subpelmv |= (second_mode_mv[this_mode].as_mv.row & 0x0f) ||
  1.1968 +                        (second_mode_mv[this_mode].as_mv.col & 0x0f);
  1.1969 +            have_ref  &= second_mode_mv[this_mode].as_int ==
  1.1970 +                         ref_bsi->rdstat[i][mode_idx].mvs[1].as_int;
  1.1971 +          }
  1.1972 +
  1.1973 +          if (filter_idx > 1 && !subpelmv && !have_ref) {
  1.1974 +            ref_bsi = bsi_buf + 1;
  1.1975 +            have_ref = mode_mv[this_mode].as_int ==
  1.1976 +                       ref_bsi->rdstat[i][mode_idx].mvs[0].as_int;
  1.1977 +            if (has_second_rf) {
  1.1978 +              have_ref  &= second_mode_mv[this_mode].as_int ==
  1.1979 +                           ref_bsi->rdstat[i][mode_idx].mvs[1].as_int;
  1.1980 +            }
  1.1981 +          }
  1.1982 +
  1.1983 +          if (!subpelmv && have_ref &&
  1.1984 +              ref_bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
  1.1985 +            vpx_memcpy(&bsi->rdstat[i][mode_idx], &ref_bsi->rdstat[i][mode_idx],
  1.1986 +                       sizeof(SEG_RDSTAT));
  1.1987 +            if (num_4x4_blocks_wide > 1)
  1.1988 +              bsi->rdstat[i + 1][mode_idx].eobs =
  1.1989 +                  ref_bsi->rdstat[i + 1][mode_idx].eobs;
  1.1990 +            if (num_4x4_blocks_high > 1)
  1.1991 +              bsi->rdstat[i + 2][mode_idx].eobs =
  1.1992 +                  ref_bsi->rdstat[i + 2][mode_idx].eobs;
  1.1993 +
  1.1994 +            if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
  1.1995 +              mode_selected = this_mode;
  1.1996 +              best_rd = bsi->rdstat[i][mode_idx].brdcost;
  1.1997 +            }
  1.1998 +            continue;
  1.1999 +          }
  1.2000 +        }
  1.2001 +
  1.2002 +        bsi->rdstat[i][mode_idx].brdcost =
  1.2003 +            encode_inter_mb_segment(cpi, x,
  1.2004 +                                    bsi->segment_rd - this_segment_rd, i,
  1.2005 +                                    &bsi->rdstat[i][mode_idx].byrate,
  1.2006 +                                    &bsi->rdstat[i][mode_idx].bdist,
  1.2007 +                                    &bsi->rdstat[i][mode_idx].bsse,
  1.2008 +                                    bsi->rdstat[i][mode_idx].ta,
  1.2009 +                                    bsi->rdstat[i][mode_idx].tl);
  1.2010 +        if (bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
  1.2011 +          bsi->rdstat[i][mode_idx].brdcost += RDCOST(x->rdmult, x->rddiv,
  1.2012 +                                            bsi->rdstat[i][mode_idx].brate, 0);
  1.2013 +          bsi->rdstat[i][mode_idx].brate += bsi->rdstat[i][mode_idx].byrate;
  1.2014 +          bsi->rdstat[i][mode_idx].eobs = pd->eobs[i];
  1.2015 +          if (num_4x4_blocks_wide > 1)
  1.2016 +            bsi->rdstat[i + 1][mode_idx].eobs = pd->eobs[i + 1];
  1.2017 +          if (num_4x4_blocks_high > 1)
  1.2018 +            bsi->rdstat[i + 2][mode_idx].eobs = pd->eobs[i + 2];
  1.2019 +        }
  1.2020 +
  1.2021 +        if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
  1.2022 +          mode_selected = this_mode;
  1.2023 +          best_rd = bsi->rdstat[i][mode_idx].brdcost;
  1.2024 +        }
  1.2025 +      } /*for each 4x4 mode*/
  1.2026 +
  1.2027 +      if (best_rd == INT64_MAX) {
  1.2028 +        int iy, midx;
  1.2029 +        for (iy = i + 1; iy < 4; ++iy)
  1.2030 +          for (midx = 0; midx < INTER_MODES; ++midx)
  1.2031 +            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
  1.2032 +        bsi->segment_rd = INT64_MAX;
  1.2033 +        return;
  1.2034 +      }
  1.2035 +
  1.2036 +      mode_idx = INTER_OFFSET(mode_selected);
  1.2037 +      vpx_memcpy(t_above, bsi->rdstat[i][mode_idx].ta, sizeof(t_above));
  1.2038 +      vpx_memcpy(t_left, bsi->rdstat[i][mode_idx].tl, sizeof(t_left));
  1.2039 +
  1.2040 +      labels2mode(x, i, mode_selected, &mode_mv[mode_selected],
  1.2041 +                  &second_mode_mv[mode_selected], frame_mv, seg_mvs[i],
  1.2042 +                  bsi->ref_mv, bsi->second_ref_mv, x->nmvjointcost,
  1.2043 +                  x->mvcost, cpi);
  1.2044 +
  1.2045 +      br += bsi->rdstat[i][mode_idx].brate;
  1.2046 +      bd += bsi->rdstat[i][mode_idx].bdist;
  1.2047 +      block_sse += bsi->rdstat[i][mode_idx].bsse;
  1.2048 +      segmentyrate += bsi->rdstat[i][mode_idx].byrate;
  1.2049 +      this_segment_rd += bsi->rdstat[i][mode_idx].brdcost;
  1.2050 +
  1.2051 +      if (this_segment_rd > bsi->segment_rd) {
  1.2052 +        int iy, midx;
  1.2053 +        for (iy = i + 1; iy < 4; ++iy)
  1.2054 +          for (midx = 0; midx < INTER_MODES; ++midx)
  1.2055 +            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
  1.2056 +        bsi->segment_rd = INT64_MAX;
  1.2057 +        return;
  1.2058 +      }
  1.2059 +    }
  1.2060 +  } /* for each label */
  1.2061 +
  1.2062 +  bsi->r = br;
  1.2063 +  bsi->d = bd;
  1.2064 +  bsi->segment_yrate = segmentyrate;
  1.2065 +  bsi->segment_rd = this_segment_rd;
  1.2066 +  bsi->sse = block_sse;
  1.2067 +
  1.2068 +  // update the coding decisions
  1.2069 +  for (i = 0; i < 4; ++i)
  1.2070 +    bsi->modes[i] = mi->bmi[i].as_mode;
  1.2071 +}
  1.2072 +
  1.2073 +static int64_t rd_pick_best_mbsegmentation(VP9_COMP *cpi, MACROBLOCK *x,
  1.2074 +                                           const TileInfo *const tile,
  1.2075 +                                           int_mv *best_ref_mv,
  1.2076 +                                           int_mv *second_best_ref_mv,
  1.2077 +                                           int64_t best_rd,
  1.2078 +                                           int *returntotrate,
  1.2079 +                                           int *returnyrate,
  1.2080 +                                           int64_t *returndistortion,
  1.2081 +                                           int *skippable, int64_t *psse,
  1.2082 +                                           int mvthresh,
  1.2083 +                                           int_mv seg_mvs[4][MAX_REF_FRAMES],
  1.2084 +                                           BEST_SEG_INFO *bsi_buf,
  1.2085 +                                           int filter_idx,
  1.2086 +                                           int mi_row, int mi_col) {
  1.2087 +  int i;
  1.2088 +  BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
  1.2089 +  MACROBLOCKD *xd = &x->e_mbd;
  1.2090 +  MODE_INFO *mi = xd->mi_8x8[0];
  1.2091 +  MB_MODE_INFO *mbmi = &mi->mbmi;
  1.2092 +  int mode_idx;
  1.2093 +
  1.2094 +  vp9_zero(*bsi);
  1.2095 +
  1.2096 +  bsi->segment_rd = best_rd;
  1.2097 +  bsi->ref_mv = best_ref_mv;
  1.2098 +  bsi->second_ref_mv = second_best_ref_mv;
  1.2099 +  bsi->mvp.as_int = best_ref_mv->as_int;
  1.2100 +  bsi->mvthresh = mvthresh;
  1.2101 +
  1.2102 +  for (i = 0; i < 4; i++)
  1.2103 +    bsi->modes[i] = ZEROMV;
  1.2104 +
  1.2105 +  rd_check_segment_txsize(cpi, x, tile, bsi_buf, filter_idx, seg_mvs,
  1.2106 +                          mi_row, mi_col);
  1.2107 +
  1.2108 +  if (bsi->segment_rd > best_rd)
  1.2109 +    return INT64_MAX;
  1.2110 +  /* set it to the best */
  1.2111 +  for (i = 0; i < 4; i++) {
  1.2112 +    mode_idx = INTER_OFFSET(bsi->modes[i]);
  1.2113 +    mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
  1.2114 +    if (has_second_ref(mbmi))
  1.2115 +      mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
  1.2116 +    xd->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
  1.2117 +    mi->bmi[i].as_mode = bsi->modes[i];
  1.2118 +  }
  1.2119 +
  1.2120 +  /*
  1.2121 +   * used to set mbmi->mv.as_int
  1.2122 +   */
  1.2123 +  *returntotrate = bsi->r;
  1.2124 +  *returndistortion = bsi->d;
  1.2125 +  *returnyrate = bsi->segment_yrate;
  1.2126 +  *skippable = vp9_is_skippable_in_plane(&x->e_mbd, BLOCK_8X8, 0);
  1.2127 +  *psse = bsi->sse;
  1.2128 +  mbmi->mode = bsi->modes[3];
  1.2129 +
  1.2130 +  return bsi->segment_rd;
  1.2131 +}
  1.2132 +
  1.2133 +static void mv_pred(VP9_COMP *cpi, MACROBLOCK *x,
  1.2134 +                    uint8_t *ref_y_buffer, int ref_y_stride,
  1.2135 +                    int ref_frame, BLOCK_SIZE block_size ) {
  1.2136 +  MACROBLOCKD *xd = &x->e_mbd;
  1.2137 +  MB_MODE_INFO *mbmi = &xd->mi_8x8[0]->mbmi;
  1.2138 +  int_mv this_mv;
  1.2139 +  int i;
  1.2140 +  int zero_seen = 0;
  1.2141 +  int best_index = 0;
  1.2142 +  int best_sad = INT_MAX;
  1.2143 +  int this_sad = INT_MAX;
  1.2144 +  unsigned int max_mv = 0;
  1.2145 +
  1.2146 +  uint8_t *src_y_ptr = x->plane[0].src.buf;
  1.2147 +  uint8_t *ref_y_ptr;
  1.2148 +  int row_offset, col_offset;
  1.2149 +  int num_mv_refs = MAX_MV_REF_CANDIDATES +
  1.2150 +                    (cpi->sf.adaptive_motion_search &&
  1.2151 +                     cpi->common.show_frame &&
  1.2152 +                     block_size < cpi->sf.max_partition_size);
  1.2153 +
  1.2154 +  // Get the sad for each candidate reference mv
  1.2155 +  for (i = 0; i < num_mv_refs; i++) {
  1.2156 +    this_mv.as_int = (i < MAX_MV_REF_CANDIDATES) ?
  1.2157 +        mbmi->ref_mvs[ref_frame][i].as_int : x->pred_mv[ref_frame].as_int;
  1.2158 +
  1.2159 +    max_mv = MAX(max_mv,
  1.2160 +                 MAX(abs(this_mv.as_mv.row), abs(this_mv.as_mv.col)) >> 3);
  1.2161 +    // The list is at an end if we see 0 for a second time.
  1.2162 +    if (!this_mv.as_int && zero_seen)
  1.2163 +      break;
  1.2164 +    zero_seen = zero_seen || !this_mv.as_int;
  1.2165 +
  1.2166 +    row_offset = this_mv.as_mv.row >> 3;
  1.2167 +    col_offset = this_mv.as_mv.col >> 3;
  1.2168 +    ref_y_ptr = ref_y_buffer + (ref_y_stride * row_offset) + col_offset;
  1.2169 +
  1.2170 +    // Find sad for current vector.
  1.2171 +    this_sad = cpi->fn_ptr[block_size].sdf(src_y_ptr, x->plane[0].src.stride,
  1.2172 +                                           ref_y_ptr, ref_y_stride,
  1.2173 +                                           0x7fffffff);
  1.2174 +
  1.2175 +    // Note if it is the best so far.
  1.2176 +    if (this_sad < best_sad) {
  1.2177 +      best_sad = this_sad;
  1.2178 +      best_index = i;
  1.2179 +    }
  1.2180 +  }
  1.2181 +
  1.2182 +  // Note the index of the mv that worked best in the reference list.
  1.2183 +  x->mv_best_ref_index[ref_frame] = best_index;
  1.2184 +  x->max_mv_context[ref_frame] = max_mv;
  1.2185 +}
  1.2186 +
  1.2187 +static void estimate_ref_frame_costs(VP9_COMP *cpi, int segment_id,
  1.2188 +                                     unsigned int *ref_costs_single,
  1.2189 +                                     unsigned int *ref_costs_comp,
  1.2190 +                                     vp9_prob *comp_mode_p) {
  1.2191 +  VP9_COMMON *const cm = &cpi->common;
  1.2192 +  MACROBLOCKD *const xd = &cpi->mb.e_mbd;
  1.2193 +  int seg_ref_active = vp9_segfeature_active(&cm->seg, segment_id,
  1.2194 +                                             SEG_LVL_REF_FRAME);
  1.2195 +  if (seg_ref_active) {
  1.2196 +    vpx_memset(ref_costs_single, 0, MAX_REF_FRAMES * sizeof(*ref_costs_single));
  1.2197 +    vpx_memset(ref_costs_comp,   0, MAX_REF_FRAMES * sizeof(*ref_costs_comp));
  1.2198 +    *comp_mode_p = 128;
  1.2199 +  } else {
  1.2200 +    vp9_prob intra_inter_p = vp9_get_pred_prob_intra_inter(cm, xd);
  1.2201 +    vp9_prob comp_inter_p = 128;
  1.2202 +
  1.2203 +    if (cm->comp_pred_mode == HYBRID_PREDICTION) {
  1.2204 +      comp_inter_p = vp9_get_pred_prob_comp_inter_inter(cm, xd);
  1.2205 +      *comp_mode_p = comp_inter_p;
  1.2206 +    } else {
  1.2207 +      *comp_mode_p = 128;
  1.2208 +    }
  1.2209 +
  1.2210 +    ref_costs_single[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
  1.2211 +
  1.2212 +    if (cm->comp_pred_mode != COMP_PREDICTION_ONLY) {
  1.2213 +      vp9_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
  1.2214 +      vp9_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
  1.2215 +      unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
  1.2216 +
  1.2217 +      if (cm->comp_pred_mode == HYBRID_PREDICTION)
  1.2218 +        base_cost += vp9_cost_bit(comp_inter_p, 0);
  1.2219 +
  1.2220 +      ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
  1.2221 +          ref_costs_single[ALTREF_FRAME] = base_cost;
  1.2222 +      ref_costs_single[LAST_FRAME]   += vp9_cost_bit(ref_single_p1, 0);
  1.2223 +      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
  1.2224 +      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
  1.2225 +      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
  1.2226 +      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
  1.2227 +    } else {
  1.2228 +      ref_costs_single[LAST_FRAME]   = 512;
  1.2229 +      ref_costs_single[GOLDEN_FRAME] = 512;
  1.2230 +      ref_costs_single[ALTREF_FRAME] = 512;
  1.2231 +    }
  1.2232 +    if (cm->comp_pred_mode != SINGLE_PREDICTION_ONLY) {
  1.2233 +      vp9_prob ref_comp_p = vp9_get_pred_prob_comp_ref_p(cm, xd);
  1.2234 +      unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
  1.2235 +
  1.2236 +      if (cm->comp_pred_mode == HYBRID_PREDICTION)
  1.2237 +        base_cost += vp9_cost_bit(comp_inter_p, 1);
  1.2238 +
  1.2239 +      ref_costs_comp[LAST_FRAME]   = base_cost + vp9_cost_bit(ref_comp_p, 0);
  1.2240 +      ref_costs_comp[GOLDEN_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 1);
  1.2241 +    } else {
  1.2242 +      ref_costs_comp[LAST_FRAME]   = 512;
  1.2243 +      ref_costs_comp[GOLDEN_FRAME] = 512;
  1.2244 +    }
  1.2245 +  }
  1.2246 +}
  1.2247 +
  1.2248 +static void store_coding_context(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx,
  1.2249 +                         int mode_index,
  1.2250 +                         int_mv *ref_mv,
  1.2251 +                         int_mv *second_ref_mv,
  1.2252 +                         int64_t comp_pred_diff[NB_PREDICTION_TYPES],
  1.2253 +                         int64_t tx_size_diff[TX_MODES],
  1.2254 +                         int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS]) {
  1.2255 +  MACROBLOCKD *const xd = &x->e_mbd;
  1.2256 +
  1.2257 +  // Take a snapshot of the coding context so it can be
  1.2258 +  // restored if we decide to encode this way
  1.2259 +  ctx->skip = x->skip;
  1.2260 +  ctx->best_mode_index = mode_index;
  1.2261 +  ctx->mic = *xd->mi_8x8[0];
  1.2262 +
  1.2263 +  ctx->best_ref_mv.as_int = ref_mv->as_int;
  1.2264 +  ctx->second_best_ref_mv.as_int = second_ref_mv->as_int;
  1.2265 +
  1.2266 +  ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_PREDICTION_ONLY];
  1.2267 +  ctx->comp_pred_diff   = (int)comp_pred_diff[COMP_PREDICTION_ONLY];
  1.2268 +  ctx->hybrid_pred_diff = (int)comp_pred_diff[HYBRID_PREDICTION];
  1.2269 +
  1.2270 +  vpx_memcpy(ctx->tx_rd_diff, tx_size_diff, sizeof(ctx->tx_rd_diff));
  1.2271 +  vpx_memcpy(ctx->best_filter_diff, best_filter_diff,
  1.2272 +             sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
  1.2273 +}
  1.2274 +
  1.2275 +static void setup_pred_block(const MACROBLOCKD *xd,
  1.2276 +                             struct buf_2d dst[MAX_MB_PLANE],
  1.2277 +                             const YV12_BUFFER_CONFIG *src,
  1.2278 +                             int mi_row, int mi_col,
  1.2279 +                             const struct scale_factors *scale,
  1.2280 +                             const struct scale_factors *scale_uv) {
  1.2281 +  int i;
  1.2282 +
  1.2283 +  dst[0].buf = src->y_buffer;
  1.2284 +  dst[0].stride = src->y_stride;
  1.2285 +  dst[1].buf = src->u_buffer;
  1.2286 +  dst[2].buf = src->v_buffer;
  1.2287 +  dst[1].stride = dst[2].stride = src->uv_stride;
  1.2288 +#if CONFIG_ALPHA
  1.2289 +  dst[3].buf = src->alpha_buffer;
  1.2290 +  dst[3].stride = src->alpha_stride;
  1.2291 +#endif
  1.2292 +
  1.2293 +  // TODO(jkoleszar): Make scale factors per-plane data
  1.2294 +  for (i = 0; i < MAX_MB_PLANE; i++) {
  1.2295 +    setup_pred_plane(dst + i, dst[i].buf, dst[i].stride, mi_row, mi_col,
  1.2296 +                     i ? scale_uv : scale,
  1.2297 +                     xd->plane[i].subsampling_x, xd->plane[i].subsampling_y);
  1.2298 +  }
  1.2299 +}
  1.2300 +
  1.2301 +static void setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
  1.2302 +                               const TileInfo *const tile,
  1.2303 +                               int idx, MV_REFERENCE_FRAME frame_type,
  1.2304 +                               BLOCK_SIZE block_size,
  1.2305 +                               int mi_row, int mi_col,
  1.2306 +                               int_mv frame_nearest_mv[MAX_REF_FRAMES],
  1.2307 +                               int_mv frame_near_mv[MAX_REF_FRAMES],
  1.2308 +                               struct buf_2d yv12_mb[4][MAX_MB_PLANE],
  1.2309 +                               struct scale_factors scale[MAX_REF_FRAMES]) {
  1.2310 +  VP9_COMMON *cm = &cpi->common;
  1.2311 +  YV12_BUFFER_CONFIG *yv12 = &cm->yv12_fb[cpi->common.ref_frame_map[idx]];
  1.2312 +  MACROBLOCKD *const xd = &x->e_mbd;
  1.2313 +  MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
  1.2314 +
  1.2315 +  // set up scaling factors
  1.2316 +  scale[frame_type] = cpi->common.active_ref_scale[frame_type - 1];
  1.2317 +
  1.2318 +  scale[frame_type].sfc->set_scaled_offsets(&scale[frame_type],
  1.2319 +                                            mi_row * MI_SIZE, mi_col * MI_SIZE);
  1.2320 +
  1.2321 +  // TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
  1.2322 +  // use the UV scaling factors.
  1.2323 +  setup_pred_block(xd, yv12_mb[frame_type], yv12, mi_row, mi_col,
  1.2324 +                   &scale[frame_type], &scale[frame_type]);
  1.2325 +
  1.2326 +  // Gets an initial list of candidate vectors from neighbours and orders them
  1.2327 +  vp9_find_mv_refs(cm, xd, tile, xd->mi_8x8[0],
  1.2328 +                   xd->last_mi,
  1.2329 +                   frame_type,
  1.2330 +                   mbmi->ref_mvs[frame_type], mi_row, mi_col);
  1.2331 +
  1.2332 +  // Candidate refinement carried out at encoder and decoder
  1.2333 +  vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv,
  1.2334 +                        mbmi->ref_mvs[frame_type],
  1.2335 +                        &frame_nearest_mv[frame_type],
  1.2336 +                        &frame_near_mv[frame_type]);
  1.2337 +
  1.2338 +  // Further refinement that is encode side only to test the top few candidates
  1.2339 +  // in full and choose the best as the centre point for subsequent searches.
  1.2340 +  // The current implementation doesn't support scaling.
  1.2341 +  if (!vp9_is_scaled(scale[frame_type].sfc) && block_size >= BLOCK_8X8)
  1.2342 +    mv_pred(cpi, x, yv12_mb[frame_type][0].buf, yv12->y_stride,
  1.2343 +            frame_type, block_size);
  1.2344 +}
  1.2345 +
  1.2346 +static YV12_BUFFER_CONFIG *get_scaled_ref_frame(VP9_COMP *cpi, int ref_frame) {
  1.2347 +  YV12_BUFFER_CONFIG *scaled_ref_frame = NULL;
  1.2348 +  int fb = get_ref_frame_idx(cpi, ref_frame);
  1.2349 +  int fb_scale = get_scale_ref_frame_idx(cpi, ref_frame);
  1.2350 +  if (cpi->scaled_ref_idx[fb_scale] != cpi->common.ref_frame_map[fb])
  1.2351 +    scaled_ref_frame = &cpi->common.yv12_fb[cpi->scaled_ref_idx[fb_scale]];
  1.2352 +  return scaled_ref_frame;
  1.2353 +}
  1.2354 +
  1.2355 +static INLINE int get_switchable_rate(const MACROBLOCK *x) {
  1.2356 +  const MACROBLOCKD *const xd = &x->e_mbd;
  1.2357 +  const MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
  1.2358 +  const int ctx = vp9_get_pred_context_switchable_interp(xd);
  1.2359 +  return SWITCHABLE_INTERP_RATE_FACTOR *
  1.2360 +             x->switchable_interp_costs[ctx][mbmi->interp_filter];
  1.2361 +}
  1.2362 +
  1.2363 +static void single_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
  1.2364 +                                 const TileInfo *const tile,
  1.2365 +                                 BLOCK_SIZE bsize,
  1.2366 +                                 int mi_row, int mi_col,
  1.2367 +                                 int_mv *tmp_mv, int *rate_mv) {
  1.2368 +  MACROBLOCKD *xd = &x->e_mbd;
  1.2369 +  VP9_COMMON *cm = &cpi->common;
  1.2370 +  MB_MODE_INFO *mbmi = &xd->mi_8x8[0]->mbmi;
  1.2371 +  struct buf_2d backup_yv12[MAX_MB_PLANE] = {{0}};
  1.2372 +  int bestsme = INT_MAX;
  1.2373 +  int further_steps, step_param;
  1.2374 +  int sadpb = x->sadperbit16;
  1.2375 +  int_mv mvp_full;
  1.2376 +  int ref = mbmi->ref_frame[0];
  1.2377 +  int_mv ref_mv = mbmi->ref_mvs[ref][0];
  1.2378 +  const BLOCK_SIZE block_size = get_plane_block_size(bsize, &xd->plane[0]);
  1.2379 +
  1.2380 +  int tmp_col_min = x->mv_col_min;
  1.2381 +  int tmp_col_max = x->mv_col_max;
  1.2382 +  int tmp_row_min = x->mv_row_min;
  1.2383 +  int tmp_row_max = x->mv_row_max;
  1.2384 +
  1.2385 +  YV12_BUFFER_CONFIG *scaled_ref_frame = get_scaled_ref_frame(cpi, ref);
  1.2386 +
  1.2387 +  if (scaled_ref_frame) {
  1.2388 +    int i;
  1.2389 +    // Swap out the reference frame for a version that's been scaled to
  1.2390 +    // match the resolution of the current frame, allowing the existing
  1.2391 +    // motion search code to be used without additional modifications.
  1.2392 +    for (i = 0; i < MAX_MB_PLANE; i++)
  1.2393 +      backup_yv12[i] = xd->plane[i].pre[0];
  1.2394 +
  1.2395 +    setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
  1.2396 +  }
  1.2397 +
  1.2398 +  vp9_clamp_mv_min_max(x, &ref_mv.as_mv);
  1.2399 +
  1.2400 +  // Adjust search parameters based on small partitions' result.
  1.2401 +  if (x->fast_ms) {
  1.2402 +    // && abs(mvp_full.as_mv.row - x->pred_mv.as_mv.row) < 24 &&
  1.2403 +    // abs(mvp_full.as_mv.col - x->pred_mv.as_mv.col) < 24) {
  1.2404 +    // adjust search range
  1.2405 +    step_param = 6;
  1.2406 +    if (x->fast_ms > 1)
  1.2407 +      step_param = 8;
  1.2408 +
  1.2409 +    // Get prediction MV.
  1.2410 +    mvp_full.as_int = x->pred_mv[ref].as_int;
  1.2411 +
  1.2412 +    // Adjust MV sign if needed.
  1.2413 +    if (cm->ref_frame_sign_bias[ref]) {
  1.2414 +      mvp_full.as_mv.col *= -1;
  1.2415 +      mvp_full.as_mv.row *= -1;
  1.2416 +    }
  1.2417 +  } else {
  1.2418 +    // Work out the size of the first step in the mv step search.
  1.2419 +    // 0 here is maximum length first step. 1 is MAX >> 1 etc.
  1.2420 +    if (cpi->sf.auto_mv_step_size && cpi->common.show_frame) {
  1.2421 +      // Take wtd average of the step_params based on the last frame's
  1.2422 +      // max mv magnitude and that based on the best ref mvs of the current
  1.2423 +      // block for the given reference.
  1.2424 +      step_param = (vp9_init_search_range(cpi, x->max_mv_context[ref]) +
  1.2425 +                    cpi->mv_step_param) >> 1;
  1.2426 +    } else {
  1.2427 +      step_param = cpi->mv_step_param;
  1.2428 +    }
  1.2429 +  }
  1.2430 +
  1.2431 +  if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64 &&
  1.2432 +      cpi->common.show_frame) {
  1.2433 +    int boffset = 2 * (b_width_log2(BLOCK_64X64) - MIN(b_height_log2(bsize),
  1.2434 +                                                       b_width_log2(bsize)));
  1.2435 +    step_param = MAX(step_param, boffset);
  1.2436 +  }
  1.2437 +
  1.2438 +  mvp_full.as_int = x->mv_best_ref_index[ref] < MAX_MV_REF_CANDIDATES ?
  1.2439 +      mbmi->ref_mvs[ref][x->mv_best_ref_index[ref]].as_int :
  1.2440 +      x->pred_mv[ref].as_int;
  1.2441 +
  1.2442 +  mvp_full.as_mv.col >>= 3;
  1.2443 +  mvp_full.as_mv.row >>= 3;
  1.2444 +
  1.2445 +  // Further step/diamond searches as necessary
  1.2446 +  further_steps = (cpi->sf.max_step_search_steps - 1) - step_param;
  1.2447 +
  1.2448 +  if (cpi->sf.search_method == HEX) {
  1.2449 +    bestsme = vp9_hex_search(x, &mvp_full.as_mv,
  1.2450 +                             step_param,
  1.2451 +                             sadpb, 1,
  1.2452 +                             &cpi->fn_ptr[block_size], 1,
  1.2453 +                             &ref_mv.as_mv, &tmp_mv->as_mv);
  1.2454 +  } else if (cpi->sf.search_method == SQUARE) {
  1.2455 +    bestsme = vp9_square_search(x, &mvp_full.as_mv,
  1.2456 +                                step_param,
  1.2457 +                                sadpb, 1,
  1.2458 +                                &cpi->fn_ptr[block_size], 1,
  1.2459 +                                &ref_mv.as_mv, &tmp_mv->as_mv);
  1.2460 +  } else if (cpi->sf.search_method == BIGDIA) {
  1.2461 +    bestsme = vp9_bigdia_search(x, &mvp_full.as_mv,
  1.2462 +                                step_param,
  1.2463 +                                sadpb, 1,
  1.2464 +                                &cpi->fn_ptr[block_size], 1,
  1.2465 +                                &ref_mv.as_mv, &tmp_mv->as_mv);
  1.2466 +  } else {
  1.2467 +    bestsme = vp9_full_pixel_diamond(cpi, x, &mvp_full, step_param,
  1.2468 +                                     sadpb, further_steps, 1,
  1.2469 +                                     &cpi->fn_ptr[block_size],
  1.2470 +                                     &ref_mv, tmp_mv);
  1.2471 +  }
  1.2472 +
  1.2473 +  x->mv_col_min = tmp_col_min;
  1.2474 +  x->mv_col_max = tmp_col_max;
  1.2475 +  x->mv_row_min = tmp_row_min;
  1.2476 +  x->mv_row_max = tmp_row_max;
  1.2477 +
  1.2478 +  if (bestsme < INT_MAX) {
  1.2479 +    int dis;  /* TODO: use dis in distortion calculation later. */
  1.2480 +    unsigned int sse;
  1.2481 +    cpi->find_fractional_mv_step(x, &tmp_mv->as_mv, &ref_mv.as_mv,
  1.2482 +                                 cm->allow_high_precision_mv,
  1.2483 +                                 x->errorperbit,
  1.2484 +                                 &cpi->fn_ptr[block_size],
  1.2485 +                                 0, cpi->sf.subpel_iters_per_step,
  1.2486 +                                 x->nmvjointcost, x->mvcost,
  1.2487 +                                 &dis, &sse);
  1.2488 +  }
  1.2489 +  *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv.as_mv,
  1.2490 +                             x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
  1.2491 +
  1.2492 +  if (cpi->sf.adaptive_motion_search && cpi->common.show_frame)
  1.2493 +    x->pred_mv[ref].as_int = tmp_mv->as_int;
  1.2494 +
  1.2495 +  if (scaled_ref_frame) {
  1.2496 +    int i;
  1.2497 +    for (i = 0; i < MAX_MB_PLANE; i++)
  1.2498 +      xd->plane[i].pre[0] = backup_yv12[i];
  1.2499 +  }
  1.2500 +}
  1.2501 +
  1.2502 +static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
  1.2503 +                                BLOCK_SIZE bsize,
  1.2504 +                                int_mv *frame_mv,
  1.2505 +                                int mi_row, int mi_col,
  1.2506 +                                int_mv single_newmv[MAX_REF_FRAMES],
  1.2507 +                                int *rate_mv) {
  1.2508 +  int pw = 4 << b_width_log2(bsize), ph = 4 << b_height_log2(bsize);
  1.2509 +  MACROBLOCKD *xd = &x->e_mbd;
  1.2510 +  MB_MODE_INFO *mbmi = &xd->mi_8x8[0]->mbmi;
  1.2511 +  const int refs[2] = { mbmi->ref_frame[0],
  1.2512 +                        mbmi->ref_frame[1] < 0 ? 0 : mbmi->ref_frame[1] };
  1.2513 +  int_mv ref_mv[2];
  1.2514 +  const BLOCK_SIZE block_size = get_plane_block_size(bsize, &xd->plane[0]);
  1.2515 +  int ite, ref;
  1.2516 +  // Prediction buffer from second frame.
  1.2517 +  uint8_t *second_pred = vpx_memalign(16, pw * ph * sizeof(uint8_t));
  1.2518 +
  1.2519 +  // Do joint motion search in compound mode to get more accurate mv.
  1.2520 +  struct buf_2d backup_yv12[2][MAX_MB_PLANE];
  1.2521 +  struct buf_2d scaled_first_yv12 = xd->plane[0].pre[0];
  1.2522 +  int last_besterr[2] = {INT_MAX, INT_MAX};
  1.2523 +  YV12_BUFFER_CONFIG *const scaled_ref_frame[2] = {
  1.2524 +    get_scaled_ref_frame(cpi, mbmi->ref_frame[0]),
  1.2525 +    get_scaled_ref_frame(cpi, mbmi->ref_frame[1])
  1.2526 +  };
  1.2527 +
  1.2528 +  for (ref = 0; ref < 2; ++ref) {
  1.2529 +    ref_mv[ref] = mbmi->ref_mvs[refs[ref]][0];
  1.2530 +
  1.2531 +    if (scaled_ref_frame[ref]) {
  1.2532 +      int i;
  1.2533 +      // Swap out the reference frame for a version that's been scaled to
  1.2534 +      // match the resolution of the current frame, allowing the existing
  1.2535 +      // motion search code to be used without additional modifications.
  1.2536 +      for (i = 0; i < MAX_MB_PLANE; i++)
  1.2537 +        backup_yv12[ref][i] = xd->plane[i].pre[ref];
  1.2538 +      setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col, NULL);
  1.2539 +    }
  1.2540 +
  1.2541 +    xd->scale_factor[ref].sfc->set_scaled_offsets(&xd->scale_factor[ref],
  1.2542 +                                                  mi_row, mi_col);
  1.2543 +    frame_mv[refs[ref]].as_int = single_newmv[refs[ref]].as_int;
  1.2544 +  }
  1.2545 +
  1.2546 +  // Allow joint search multiple times iteratively for each ref frame
  1.2547 +  // and break out the search loop if it couldn't find better mv.
  1.2548 +  for (ite = 0; ite < 4; ite++) {
  1.2549 +    struct buf_2d ref_yv12[2];
  1.2550 +    int bestsme = INT_MAX;
  1.2551 +    int sadpb = x->sadperbit16;
  1.2552 +    int_mv tmp_mv;
  1.2553 +    int search_range = 3;
  1.2554 +
  1.2555 +    int tmp_col_min = x->mv_col_min;
  1.2556 +    int tmp_col_max = x->mv_col_max;
  1.2557 +    int tmp_row_min = x->mv_row_min;
  1.2558 +    int tmp_row_max = x->mv_row_max;
  1.2559 +    int id = ite % 2;
  1.2560 +
  1.2561 +    // Initialized here because of compiler problem in Visual Studio.
  1.2562 +    ref_yv12[0] = xd->plane[0].pre[0];
  1.2563 +    ref_yv12[1] = xd->plane[0].pre[1];
  1.2564 +
  1.2565 +    // Get pred block from second frame.
  1.2566 +    vp9_build_inter_predictor(ref_yv12[!id].buf,
  1.2567 +                              ref_yv12[!id].stride,
  1.2568 +                              second_pred, pw,
  1.2569 +                              &frame_mv[refs[!id]].as_mv,
  1.2570 +                              &xd->scale_factor[!id],
  1.2571 +                              pw, ph, 0,
  1.2572 +                              &xd->subpix, MV_PRECISION_Q3);
  1.2573 +
  1.2574 +    // Compound motion search on first ref frame.
  1.2575 +    if (id)
  1.2576 +      xd->plane[0].pre[0] = ref_yv12[id];
  1.2577 +    vp9_clamp_mv_min_max(x, &ref_mv[id].as_mv);
  1.2578 +
  1.2579 +    // Use mv result from single mode as mvp.
  1.2580 +    tmp_mv.as_int = frame_mv[refs[id]].as_int;
  1.2581 +
  1.2582 +    tmp_mv.as_mv.col >>= 3;
  1.2583 +    tmp_mv.as_mv.row >>= 3;
  1.2584 +
  1.2585 +    // Small-range full-pixel motion search
  1.2586 +    bestsme = vp9_refining_search_8p_c(x, &tmp_mv, sadpb,
  1.2587 +                                       search_range,
  1.2588 +                                       &cpi->fn_ptr[block_size],
  1.2589 +                                       x->nmvjointcost, x->mvcost,
  1.2590 +                                       &ref_mv[id], second_pred,
  1.2591 +                                       pw, ph);
  1.2592 +
  1.2593 +    x->mv_col_min = tmp_col_min;
  1.2594 +    x->mv_col_max = tmp_col_max;
  1.2595 +    x->mv_row_min = tmp_row_min;
  1.2596 +    x->mv_row_max = tmp_row_max;
  1.2597 +
  1.2598 +    if (bestsme < INT_MAX) {
  1.2599 +      int dis; /* TODO: use dis in distortion calculation later. */
  1.2600 +      unsigned int sse;
  1.2601 +
  1.2602 +      bestsme = cpi->find_fractional_mv_step_comp(
  1.2603 +          x, &tmp_mv.as_mv,
  1.2604 +          &ref_mv[id].as_mv,
  1.2605 +          cpi->common.allow_high_precision_mv,
  1.2606 +          x->errorperbit,
  1.2607 +          &cpi->fn_ptr[block_size],
  1.2608 +          0, cpi->sf.subpel_iters_per_step,
  1.2609 +          x->nmvjointcost, x->mvcost,
  1.2610 +          &dis, &sse, second_pred,
  1.2611 +          pw, ph);
  1.2612 +    }
  1.2613 +
  1.2614 +    if (id)
  1.2615 +      xd->plane[0].pre[0] = scaled_first_yv12;
  1.2616 +
  1.2617 +    if (bestsme < last_besterr[id]) {
  1.2618 +      frame_mv[refs[id]].as_int = tmp_mv.as_int;
  1.2619 +      last_besterr[id] = bestsme;
  1.2620 +    } else {
  1.2621 +      break;
  1.2622 +    }
  1.2623 +  }
  1.2624 +
  1.2625 +  *rate_mv = 0;
  1.2626 +
  1.2627 +  for (ref = 0; ref < 2; ++ref) {
  1.2628 +    if (scaled_ref_frame[ref]) {
  1.2629 +      // restore the predictor
  1.2630 +      int i;
  1.2631 +      for (i = 0; i < MAX_MB_PLANE; i++)
  1.2632 +        xd->plane[i].pre[ref] = backup_yv12[ref][i];
  1.2633 +    }
  1.2634 +
  1.2635 +    *rate_mv += vp9_mv_bit_cost(&frame_mv[refs[ref]].as_mv,
  1.2636 +                                &mbmi->ref_mvs[refs[ref]][0].as_mv,
  1.2637 +                                x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
  1.2638 +  }
  1.2639 +
  1.2640 +  vpx_free(second_pred);
  1.2641 +}
  1.2642 +
  1.2643 +static int64_t handle_inter_mode(VP9_COMP *cpi, MACROBLOCK *x,
  1.2644 +                                 const TileInfo *const tile,
  1.2645 +                                 BLOCK_SIZE bsize,
  1.2646 +                                 int64_t txfm_cache[],
  1.2647 +                                 int *rate2, int64_t *distortion,
  1.2648 +                                 int *skippable,
  1.2649 +                                 int *rate_y, int64_t *distortion_y,
  1.2650 +                                 int *rate_uv, int64_t *distortion_uv,
  1.2651 +                                 int *mode_excluded, int *disable_skip,
  1.2652 +                                 INTERPOLATION_TYPE *best_filter,
  1.2653 +                                 int_mv (*mode_mv)[MAX_REF_FRAMES],
  1.2654 +                                 int mi_row, int mi_col,
  1.2655 +                                 int_mv single_newmv[MAX_REF_FRAMES],
  1.2656 +                                 int64_t *psse,
  1.2657 +                                 const int64_t ref_best_rd) {
  1.2658 +  VP9_COMMON *cm = &cpi->common;
  1.2659 +  MACROBLOCKD *xd = &x->e_mbd;
  1.2660 +  MB_MODE_INFO *mbmi = &xd->mi_8x8[0]->mbmi;
  1.2661 +  const int is_comp_pred = has_second_ref(mbmi);
  1.2662 +  const int num_refs = is_comp_pred ? 2 : 1;
  1.2663 +  const int this_mode = mbmi->mode;
  1.2664 +  int_mv *frame_mv = mode_mv[this_mode];
  1.2665 +  int i;
  1.2666 +  int refs[2] = { mbmi->ref_frame[0],
  1.2667 +    (mbmi->ref_frame[1] < 0 ? 0 : mbmi->ref_frame[1]) };
  1.2668 +  int_mv cur_mv[2];
  1.2669 +  int64_t this_rd = 0;
  1.2670 +  DECLARE_ALIGNED_ARRAY(16, uint8_t, tmp_buf, MAX_MB_PLANE * 64 * 64);
  1.2671 +  int pred_exists = 0;
  1.2672 +  int intpel_mv;
  1.2673 +  int64_t rd, best_rd = INT64_MAX;
  1.2674 +  int best_needs_copy = 0;
  1.2675 +  uint8_t *orig_dst[MAX_MB_PLANE];
  1.2676 +  int orig_dst_stride[MAX_MB_PLANE];
  1.2677 +  int rs = 0;
  1.2678 +
  1.2679 +  if (is_comp_pred) {
  1.2680 +    if (frame_mv[refs[0]].as_int == INVALID_MV ||
  1.2681 +        frame_mv[refs[1]].as_int == INVALID_MV)
  1.2682 +      return INT64_MAX;
  1.2683 +  }
  1.2684 +
  1.2685 +  if (this_mode == NEWMV) {
  1.2686 +    int rate_mv;
  1.2687 +    if (is_comp_pred) {
  1.2688 +      // Initialize mv using single prediction mode result.
  1.2689 +      frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
  1.2690 +      frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
  1.2691 +
  1.2692 +      if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
  1.2693 +        joint_motion_search(cpi, x, bsize, frame_mv,
  1.2694 +                            mi_row, mi_col, single_newmv, &rate_mv);
  1.2695 +      } else {
  1.2696 +        rate_mv  = vp9_mv_bit_cost(&frame_mv[refs[0]].as_mv,
  1.2697 +                                   &mbmi->ref_mvs[refs[0]][0].as_mv,
  1.2698 +                                   x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
  1.2699 +        rate_mv += vp9_mv_bit_cost(&frame_mv[refs[1]].as_mv,
  1.2700 +                                   &mbmi->ref_mvs[refs[1]][0].as_mv,
  1.2701 +                                   x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
  1.2702 +      }
  1.2703 +      *rate2 += rate_mv;
  1.2704 +    } else {
  1.2705 +      int_mv tmp_mv;
  1.2706 +      single_motion_search(cpi, x, tile, bsize, mi_row, mi_col,
  1.2707 +                           &tmp_mv, &rate_mv);
  1.2708 +      *rate2 += rate_mv;
  1.2709 +      frame_mv[refs[0]].as_int =
  1.2710 +          xd->mi_8x8[0]->bmi[0].as_mv[0].as_int = tmp_mv.as_int;
  1.2711 +      single_newmv[refs[0]].as_int = tmp_mv.as_int;
  1.2712 +    }
  1.2713 +  }
  1.2714 +
  1.2715 +  // if we're near/nearest and mv == 0,0, compare to zeromv
  1.2716 +  if ((this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
  1.2717 +      frame_mv[refs[0]].as_int == 0 &&
  1.2718 +      !vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP) &&
  1.2719 +      (num_refs == 1 || frame_mv[refs[1]].as_int == 0)) {
  1.2720 +    int rfc = mbmi->mode_context[mbmi->ref_frame[0]];
  1.2721 +    int c1 = cost_mv_ref(cpi, NEARMV, rfc);
  1.2722 +    int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
  1.2723 +    int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
  1.2724 +
  1.2725 +    if (this_mode == NEARMV) {
  1.2726 +      if (c1 > c3)
  1.2727 +        return INT64_MAX;
  1.2728 +    } else if (this_mode == NEARESTMV) {
  1.2729 +      if (c2 > c3)
  1.2730 +        return INT64_MAX;
  1.2731 +    } else {
  1.2732 +      assert(this_mode == ZEROMV);
  1.2733 +      if (num_refs == 1) {
  1.2734 +        if ((c3 >= c2 &&
  1.2735 +             mode_mv[NEARESTMV][mbmi->ref_frame[0]].as_int == 0) ||
  1.2736 +            (c3 >= c1 &&
  1.2737 +             mode_mv[NEARMV][mbmi->ref_frame[0]].as_int == 0))
  1.2738 +          return INT64_MAX;
  1.2739 +      } else {
  1.2740 +        if ((c3 >= c2 &&
  1.2741 +             mode_mv[NEARESTMV][mbmi->ref_frame[0]].as_int == 0 &&
  1.2742 +             mode_mv[NEARESTMV][mbmi->ref_frame[1]].as_int == 0) ||
  1.2743 +            (c3 >= c1 &&
  1.2744 +             mode_mv[NEARMV][mbmi->ref_frame[0]].as_int == 0 &&
  1.2745 +             mode_mv[NEARMV][mbmi->ref_frame[1]].as_int == 0))
  1.2746 +          return INT64_MAX;
  1.2747 +      }
  1.2748 +    }
  1.2749 +  }
  1.2750 +
  1.2751 +  for (i = 0; i < num_refs; ++i) {
  1.2752 +    cur_mv[i] = frame_mv[refs[i]];
  1.2753 +    // Clip "next_nearest" so that it does not extend to far out of image
  1.2754 +    if (this_mode != NEWMV)
  1.2755 +      clamp_mv2(&cur_mv[i].as_mv, xd);
  1.2756 +
  1.2757 +    if (mv_check_bounds(x, &cur_mv[i]))
  1.2758 +      return INT64_MAX;
  1.2759 +    mbmi->mv[i].as_int = cur_mv[i].as_int;
  1.2760 +  }
  1.2761 +
  1.2762 +  // do first prediction into the destination buffer. Do the next
  1.2763 +  // prediction into a temporary buffer. Then keep track of which one
  1.2764 +  // of these currently holds the best predictor, and use the other
  1.2765 +  // one for future predictions. In the end, copy from tmp_buf to
  1.2766 +  // dst if necessary.
  1.2767 +  for (i = 0; i < MAX_MB_PLANE; i++) {
  1.2768 +    orig_dst[i] = xd->plane[i].dst.buf;
  1.2769 +    orig_dst_stride[i] = xd->plane[i].dst.stride;
  1.2770 +  }
  1.2771 +
  1.2772 +  /* We don't include the cost of the second reference here, because there
  1.2773 +   * are only three options: Last/Golden, ARF/Last or Golden/ARF, or in other
  1.2774 +   * words if you present them in that order, the second one is always known
  1.2775 +   * if the first is known */
  1.2776 +  *rate2 += cost_mv_ref(cpi, this_mode,
  1.2777 +                        mbmi->mode_context[mbmi->ref_frame[0]]);
  1.2778 +
  1.2779 +  if (!(*mode_excluded)) {
  1.2780 +    if (is_comp_pred) {
  1.2781 +      *mode_excluded = (cpi->common.comp_pred_mode == SINGLE_PREDICTION_ONLY);
  1.2782 +    } else {
  1.2783 +      *mode_excluded = (cpi->common.comp_pred_mode == COMP_PREDICTION_ONLY);
  1.2784 +    }
  1.2785 +  }
  1.2786 +
  1.2787 +  pred_exists = 0;
  1.2788 +  // Are all MVs integer pel for Y and UV
  1.2789 +  intpel_mv = (mbmi->mv[0].as_mv.row & 15) == 0 &&
  1.2790 +      (mbmi->mv[0].as_mv.col & 15) == 0;
  1.2791 +  if (is_comp_pred)
  1.2792 +    intpel_mv &= (mbmi->mv[1].as_mv.row & 15) == 0 &&
  1.2793 +        (mbmi->mv[1].as_mv.col & 15) == 0;
  1.2794 +  // Search for best switchable filter by checking the variance of
  1.2795 +  // pred error irrespective of whether the filter will be used
  1.2796 +  if (cm->mcomp_filter_type != BILINEAR) {
  1.2797 +    *best_filter = EIGHTTAP;
  1.2798 +    if (x->source_variance <
  1.2799 +        cpi->sf.disable_filter_search_var_thresh) {
  1.2800 +      *best_filter = EIGHTTAP;
  1.2801 +      vp9_zero(cpi->rd_filter_cache);
  1.2802 +    } else {
  1.2803 +      int i, newbest;
  1.2804 +      int tmp_rate_sum = 0;
  1.2805 +      int64_t tmp_dist_sum = 0;
  1.2806 +
  1.2807 +      cpi->rd_filter_cache[SWITCHABLE_FILTERS] = INT64_MAX;
  1.2808 +      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
  1.2809 +        int j;
  1.2810 +        int64_t rs_rd;
  1.2811 +        mbmi->interp_filter = i;
  1.2812 +        vp9_setup_interp_filters(xd, mbmi->interp_filter, cm);
  1.2813 +        rs = get_switchable_rate(x);
  1.2814 +        rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
  1.2815 +
  1.2816 +        if (i > 0 && intpel_mv) {
  1.2817 +          cpi->rd_filter_cache[i] = RDCOST(x->rdmult, x->rddiv,
  1.2818 +                                           tmp_rate_sum, tmp_dist_sum);
  1.2819 +          cpi->rd_filter_cache[SWITCHABLE_FILTERS] =
  1.2820 +              MIN(cpi->rd_filter_cache[SWITCHABLE_FILTERS],
  1.2821 +                  cpi->rd_filter_cache[i] + rs_rd);
  1.2822 +          rd = cpi->rd_filter_cache[i];
  1.2823 +          if (cm->mcomp_filter_type == SWITCHABLE)
  1.2824 +            rd += rs_rd;
  1.2825 +        } else {
  1.2826 +          int rate_sum = 0;
  1.2827 +          int64_t dist_sum = 0;
  1.2828 +          if ((cm->mcomp_filter_type == SWITCHABLE &&
  1.2829 +               (!i || best_needs_copy)) ||
  1.2830 +              (cm->mcomp_filter_type != SWITCHABLE &&
  1.2831 +               (cm->mcomp_filter_type == mbmi->interp_filter ||
  1.2832 +                (i == 0 && intpel_mv)))) {
  1.2833 +            for (j = 0; j < MAX_MB_PLANE; j++) {
  1.2834 +              xd->plane[j].dst.buf = orig_dst[j];
  1.2835 +              xd->plane[j].dst.stride = orig_dst_stride[j];
  1.2836 +            }
  1.2837 +          } else {
  1.2838 +            for (j = 0; j < MAX_MB_PLANE; j++) {
  1.2839 +              xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
  1.2840 +              xd->plane[j].dst.stride = 64;
  1.2841 +            }
  1.2842 +          }
  1.2843 +          vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
  1.2844 +          model_rd_for_sb(cpi, bsize, x, xd, &rate_sum, &dist_sum);
  1.2845 +          cpi->rd_filter_cache[i] = RDCOST(x->rdmult, x->rddiv,
  1.2846 +                                           rate_sum, dist_sum);
  1.2847 +          cpi->rd_filter_cache[SWITCHABLE_FILTERS] =
  1.2848 +              MIN(cpi->rd_filter_cache[SWITCHABLE_FILTERS],
  1.2849 +                  cpi->rd_filter_cache[i] + rs_rd);
  1.2850 +          rd = cpi->rd_filter_cache[i];
  1.2851 +          if (cm->mcomp_filter_type == SWITCHABLE)
  1.2852 +            rd += rs_rd;
  1.2853 +          if (i == 0 && intpel_mv) {
  1.2854 +            tmp_rate_sum = rate_sum;
  1.2855 +            tmp_dist_sum = dist_sum;
  1.2856 +          }
  1.2857 +        }
  1.2858 +        if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
  1.2859 +          if (rd / 2 > ref_best_rd) {
  1.2860 +            for (i = 0; i < MAX_MB_PLANE; i++) {
  1.2861 +              xd->plane[i].dst.buf = orig_dst[i];
  1.2862 +              xd->plane[i].dst.stride = orig_dst_stride[i];
  1.2863 +            }
  1.2864 +            return INT64_MAX;
  1.2865 +          }
  1.2866 +        }
  1.2867 +        newbest = i == 0 || rd < best_rd;
  1.2868 +
  1.2869 +        if (newbest) {
  1.2870 +          best_rd = rd;
  1.2871 +          *best_filter = mbmi->interp_filter;
  1.2872 +          if (cm->mcomp_filter_type == SWITCHABLE && i && !intpel_mv)
  1.2873 +            best_needs_copy = !best_needs_copy;
  1.2874 +        }
  1.2875 +
  1.2876 +        if ((cm->mcomp_filter_type == SWITCHABLE && newbest) ||
  1.2877 +            (cm->mcomp_filter_type != SWITCHABLE &&
  1.2878 +             cm->mcomp_filter_type == mbmi->interp_filter)) {
  1.2879 +          pred_exists = 1;
  1.2880 +        }
  1.2881 +      }
  1.2882 +
  1.2883 +      for (i = 0; i < MAX_MB_PLANE; i++) {
  1.2884 +        xd->plane[i].dst.buf = orig_dst[i];
  1.2885 +        xd->plane[i].dst.stride = orig_dst_stride[i];
  1.2886 +      }
  1.2887 +    }
  1.2888 +  }
  1.2889 +  // Set the appropriate filter
  1.2890 +  mbmi->interp_filter = cm->mcomp_filter_type != SWITCHABLE ?
  1.2891 +      cm->mcomp_filter_type : *best_filter;
  1.2892 +  vp9_setup_interp_filters(xd, mbmi->interp_filter, cm);
  1.2893 +  rs = cm->mcomp_filter_type == SWITCHABLE ? get_switchable_rate(x) : 0;
  1.2894 +
  1.2895 +  if (pred_exists) {
  1.2896 +    if (best_needs_copy) {
  1.2897 +      // again temporarily set the buffers to local memory to prevent a memcpy
  1.2898 +      for (i = 0; i < MAX_MB_PLANE; i++) {
  1.2899 +        xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
  1.2900 +        xd->plane[i].dst.stride = 64;
  1.2901 +      }
  1.2902 +    }
  1.2903 +  } else {
  1.2904 +    // Handles the special case when a filter that is not in the
  1.2905 +    // switchable list (ex. bilinear, 6-tap) is indicated at the frame level
  1.2906 +    vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
  1.2907 +  }
  1.2908 +
  1.2909 +
  1.2910 +  if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
  1.2911 +    int tmp_rate;
  1.2912 +    int64_t tmp_dist;
  1.2913 +    model_rd_for_sb(cpi, bsize, x, xd, &tmp_rate, &tmp_dist);
  1.2914 +    rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
  1.2915 +    // if current pred_error modeled rd is substantially more than the best
  1.2916 +    // so far, do not bother doing full rd
  1.2917 +    if (rd / 2 > ref_best_rd) {
  1.2918 +      for (i = 0; i < MAX_MB_PLANE; i++) {
  1.2919 +        xd->plane[i].dst.buf = orig_dst[i];
  1.2920 +        xd->plane[i].dst.stride = orig_dst_stride[i];
  1.2921 +      }
  1.2922 +      return INT64_MAX;
  1.2923 +    }
  1.2924 +  }
  1.2925 +
  1.2926 +  if (cpi->common.mcomp_filter_type == SWITCHABLE)
  1.2927 +    *rate2 += get_switchable_rate(x);
  1.2928 +
  1.2929 +  if (!is_comp_pred && cpi->enable_encode_breakout) {
  1.2930 +    if (cpi->active_map_enabled && x->active_ptr[0] == 0)
  1.2931 +      x->skip = 1;
  1.2932 +    else if (x->encode_breakout) {
  1.2933 +      const BLOCK_SIZE y_size = get_plane_block_size(bsize, &xd->plane[0]);
  1.2934 +      const BLOCK_SIZE uv_size = get_plane_block_size(bsize, &xd->plane[1]);
  1.2935 +      unsigned int var, sse;
  1.2936 +      // Skipping threshold for ac.
  1.2937 +      unsigned int thresh_ac;
  1.2938 +      // The encode_breakout input
  1.2939 +      unsigned int encode_breakout = x->encode_breakout << 4;
  1.2940 +      unsigned int max_thresh = 36000;
  1.2941 +
  1.2942 +      // Use extreme low threshold for static frames to limit skipping.
  1.2943 +      if (cpi->enable_encode_breakout == 2)
  1.2944 +        max_thresh = 128;
  1.2945 +
  1.2946 +      // Calculate threshold according to dequant value.
  1.2947 +      thresh_ac = (xd->plane[0].dequant[1] * xd->plane[0].dequant[1]) / 9;
  1.2948 +
  1.2949 +      // Use encode_breakout input if it is bigger than internal threshold.
  1.2950 +      if (thresh_ac < encode_breakout)
  1.2951 +        thresh_ac = encode_breakout;
  1.2952 +
  1.2953 +      // Set a maximum for threshold to avoid big PSNR loss in low bitrate case.
  1.2954 +      if (thresh_ac > max_thresh)
  1.2955 +        thresh_ac = max_thresh;
  1.2956 +
  1.2957 +      var = cpi->fn_ptr[y_size].vf(x->plane[0].src.buf, x->plane[0].src.stride,
  1.2958 +                                   xd->plane[0].dst.buf,
  1.2959 +                                   xd->plane[0].dst.stride, &sse);
  1.2960 +
  1.2961 +      // Adjust threshold according to partition size.
  1.2962 +      thresh_ac >>= 8 - (b_width_log2_lookup[bsize] +
  1.2963 +          b_height_log2_lookup[bsize]);
  1.2964 +
  1.2965 +      // Y skipping condition checking
  1.2966 +      if (sse < thresh_ac || sse == 0) {
  1.2967 +        // Skipping threshold for dc
  1.2968 +        unsigned int thresh_dc;
  1.2969 +
  1.2970 +        thresh_dc = (xd->plane[0].dequant[0] * xd->plane[0].dequant[0] >> 6);
  1.2971 +
  1.2972 +        // dc skipping checking
  1.2973 +        if ((sse - var) < thresh_dc || sse == var) {
  1.2974 +          unsigned int sse_u, sse_v;
  1.2975 +          unsigned int var_u, var_v;
  1.2976 +
  1.2977 +          var_u = cpi->fn_ptr[uv_size].vf(x->plane[1].src.buf,
  1.2978 +                                          x->plane[1].src.stride,
  1.2979 +                                          xd->plane[1].dst.buf,
  1.2980 +                                          xd->plane[1].dst.stride, &sse_u);
  1.2981 +
  1.2982 +          // U skipping condition checking
  1.2983 +          if ((sse_u * 4 < thresh_ac || sse_u == 0) &&
  1.2984 +              (sse_u - var_u < thresh_dc || sse_u == var_u)) {
  1.2985 +            var_v = cpi->fn_ptr[uv_size].vf(x->plane[2].src.buf,
  1.2986 +                                            x->plane[2].src.stride,
  1.2987 +                                            xd->plane[2].dst.buf,
  1.2988 +                                            xd->plane[2].dst.stride, &sse_v);
  1.2989 +
  1.2990 +            // V skipping condition checking
  1.2991 +            if ((sse_v * 4 < thresh_ac || sse_v == 0) &&
  1.2992 +                (sse_v - var_v < thresh_dc || sse_v == var_v)) {
  1.2993 +              x->skip = 1;
  1.2994 +
  1.2995 +              // The cost of skip bit needs to be added.
  1.2996 +              *rate2 += vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd), 1);
  1.2997 +
  1.2998 +              // Scaling factor for SSE from spatial domain to frequency domain
  1.2999 +              // is 16. Adjust distortion accordingly.
  1.3000 +              *distortion_uv = (sse_u + sse_v) << 4;
  1.3001 +              *distortion = (sse << 4) + *distortion_uv;
  1.3002 +
  1.3003 +              *disable_skip = 1;
  1.3004 +              this_rd = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
  1.3005 +            }
  1.3006 +          }
  1.3007 +        }
  1.3008 +      }
  1.3009 +    }
  1.3010 +  }
  1.3011 +
  1.3012 +  if (!x->skip) {
  1.3013 +    int skippable_y, skippable_uv;
  1.3014 +    int64_t sseuv = INT64_MAX;
  1.3015 +    int64_t rdcosty = INT64_MAX;
  1.3016 +
  1.3017 +    // Y cost and distortion
  1.3018 +    super_block_yrd(cpi, x, rate_y, distortion_y, &skippable_y, psse,
  1.3019 +                    bsize, txfm_cache, ref_best_rd);
  1.3020 +
  1.3021 +    if (*rate_y == INT_MAX) {
  1.3022 +      *rate2 = INT_MAX;
  1.3023 +      *distortion = INT64_MAX;
  1.3024 +      for (i = 0; i < MAX_MB_PLANE; i++) {
  1.3025 +        xd->plane[i].dst.buf = orig_dst[i];
  1.3026 +        xd->plane[i].dst.stride = orig_dst_stride[i];
  1.3027 +      }
  1.3028 +      return INT64_MAX;
  1.3029 +    }
  1.3030 +
  1.3031 +    *rate2 += *rate_y;
  1.3032 +    *distortion += *distortion_y;
  1.3033 +
  1.3034 +    rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
  1.3035 +    rdcosty = MIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
  1.3036 +
  1.3037 +    super_block_uvrd(cpi, x, rate_uv, distortion_uv, &skippable_uv, &sseuv,
  1.3038 +                     bsize, ref_best_rd - rdcosty);
  1.3039 +    if (*rate_uv == INT_MAX) {
  1.3040 +      *rate2 = INT_MAX;
  1.3041 +      *distortion = INT64_MAX;
  1.3042 +      for (i = 0; i < MAX_MB_PLANE; i++) {
  1.3043 +        xd->plane[i].dst.buf = orig_dst[i];
  1.3044 +        xd->plane[i].dst.stride = orig_dst_stride[i];
  1.3045 +      }
  1.3046 +      return INT64_MAX;
  1.3047 +    }
  1.3048 +
  1.3049 +    *psse += sseuv;
  1.3050 +    *rate2 += *rate_uv;
  1.3051 +    *distortion += *distortion_uv;
  1.3052 +    *skippable = skippable_y && skippable_uv;
  1.3053 +  }
  1.3054 +
  1.3055 +  for (i = 0; i < MAX_MB_PLANE; i++) {
  1.3056 +    xd->plane[i].dst.buf = orig_dst[i];
  1.3057 +    xd->plane[i].dst.stride = orig_dst_stride[i];
  1.3058 +  }
  1.3059 +
  1.3060 +  return this_rd;  // if 0, this will be re-calculated by caller
  1.3061 +}
  1.3062 +
  1.3063 +static void swap_block_ptr(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx,
  1.3064 +                           int max_plane) {
  1.3065 +  struct macroblock_plane *const p = x->plane;
  1.3066 +  struct macroblockd_plane *const pd = x->e_mbd.plane;
  1.3067 +  int i;
  1.3068 +
  1.3069 +  for (i = 0; i < max_plane; ++i) {
  1.3070 +    p[i].coeff    = ctx->coeff_pbuf[i][1];
  1.3071 +    pd[i].qcoeff  = ctx->qcoeff_pbuf[i][1];
  1.3072 +    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
  1.3073 +    pd[i].eobs    = ctx->eobs_pbuf[i][1];
  1.3074 +
  1.3075 +    ctx->coeff_pbuf[i][1]   = ctx->coeff_pbuf[i][0];
  1.3076 +    ctx->qcoeff_pbuf[i][1]  = ctx->qcoeff_pbuf[i][0];
  1.3077 +    ctx->dqcoeff_pbuf[i][1] = ctx->dqcoeff_pbuf[i][0];
  1.3078 +    ctx->eobs_pbuf[i][1]    = ctx->eobs_pbuf[i][0];
  1.3079 +
  1.3080 +    ctx->coeff_pbuf[i][0]   = p[i].coeff;
  1.3081 +    ctx->qcoeff_pbuf[i][0]  = pd[i].qcoeff;
  1.3082 +    ctx->dqcoeff_pbuf[i][0] = pd[i].dqcoeff;
  1.3083 +    ctx->eobs_pbuf[i][0]    = pd[i].eobs;
  1.3084 +  }
  1.3085 +}
  1.3086 +
  1.3087 +void vp9_rd_pick_intra_mode_sb(VP9_COMP *cpi, MACROBLOCK *x,
  1.3088 +                               int *returnrate, int64_t *returndist,
  1.3089 +                               BLOCK_SIZE bsize,
  1.3090 +                               PICK_MODE_CONTEXT *ctx, int64_t best_rd) {
  1.3091 +  VP9_COMMON *const cm = &cpi->common;
  1.3092 +  MACROBLOCKD *const xd = &x->e_mbd;
  1.3093 +  int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
  1.3094 +  int y_skip = 0, uv_skip = 0;
  1.3095 +  int64_t dist_y = 0, dist_uv = 0, tx_cache[TX_MODES] = { 0 };
  1.3096 +  x->skip_encode = 0;
  1.3097 +  ctx->skip = 0;
  1.3098 +  xd->mi_8x8[0]->mbmi.ref_frame[0] = INTRA_FRAME;
  1.3099 +  if (bsize >= BLOCK_8X8) {
  1.3100 +    if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly,
  1.3101 +                               &dist_y, &y_skip, bsize, tx_cache,
  1.3102 +                               best_rd) >= best_rd) {
  1.3103 +      *returnrate = INT_MAX;
  1.3104 +      return;
  1.3105 +    }
  1.3106 +    rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly,
  1.3107 +                            &dist_uv, &uv_skip, bsize);
  1.3108 +  } else {
  1.3109 +    y_skip = 0;
  1.3110 +    if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
  1.3111 +                                     &dist_y, best_rd) >= best_rd) {
  1.3112 +      *returnrate = INT_MAX;
  1.3113 +      return;
  1.3114 +    }
  1.3115 +    rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly,
  1.3116 +                            &dist_uv, &uv_skip, BLOCK_8X8);
  1.3117 +  }
  1.3118 +
  1.3119 +  if (y_skip && uv_skip) {
  1.3120 +    *returnrate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
  1.3121 +                  vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd), 1);
  1.3122 +    *returndist = dist_y + dist_uv;
  1.3123 +    vp9_zero(ctx->tx_rd_diff);
  1.3124 +  } else {
  1.3125 +    int i;
  1.3126 +    *returnrate = rate_y + rate_uv +
  1.3127 +        vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd), 0);
  1.3128 +    *returndist = dist_y + dist_uv;
  1.3129 +    if (cpi->sf.tx_size_search_method == USE_FULL_RD)
  1.3130 +      for (i = 0; i < TX_MODES; i++) {
  1.3131 +        if (tx_cache[i] < INT64_MAX && tx_cache[cm->tx_mode] < INT64_MAX)
  1.3132 +          ctx->tx_rd_diff[i] = tx_cache[i] - tx_cache[cm->tx_mode];
  1.3133 +        else
  1.3134 +          ctx->tx_rd_diff[i] = 0;
  1.3135 +      }
  1.3136 +  }
  1.3137 +
  1.3138 +  ctx->mic = *xd->mi_8x8[0];
  1.3139 +}
  1.3140 +
  1.3141 +int64_t vp9_rd_pick_inter_mode_sb(VP9_COMP *cpi, MACROBLOCK *x,
  1.3142 +                                  const TileInfo *const tile,
  1.3143 +                                  int mi_row, int mi_col,
  1.3144 +                                  int *returnrate,
  1.3145 +                                  int64_t *returndistortion,
  1.3146 +                                  BLOCK_SIZE bsize,
  1.3147 +                                  PICK_MODE_CONTEXT *ctx,
  1.3148 +                                  int64_t best_rd_so_far) {
  1.3149 +  VP9_COMMON *cm = &cpi->common;
  1.3150 +  MACROBLOCKD *xd = &x->e_mbd;
  1.3151 +  MB_MODE_INFO *mbmi = &xd->mi_8x8[0]->mbmi;
  1.3152 +  const struct segmentation *seg = &cm->seg;
  1.3153 +  const BLOCK_SIZE block_size = get_plane_block_size(bsize, &xd->plane[0]);
  1.3154 +  MB_PREDICTION_MODE this_mode;
  1.3155 +  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
  1.3156 +  unsigned char segment_id = mbmi->segment_id;
  1.3157 +  int comp_pred, i;
  1.3158 +  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
  1.3159 +  struct buf_2d yv12_mb[4][MAX_MB_PLANE];
  1.3160 +  int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
  1.3161 +  static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
  1.3162 +                                    VP9_ALT_FLAG };
  1.3163 +  int idx_list[4] = {0,
  1.3164 +                     cpi->lst_fb_idx,
  1.3165 +                     cpi->gld_fb_idx,
  1.3166 +                     cpi->alt_fb_idx};
  1.3167 +  int64_t best_rd = best_rd_so_far;
  1.3168 +  int64_t best_tx_rd[TX_MODES];
  1.3169 +  int64_t best_tx_diff[TX_MODES];
  1.3170 +  int64_t best_pred_diff[NB_PREDICTION_TYPES];
  1.3171 +  int64_t best_pred_rd[NB_PREDICTION_TYPES];
  1.3172 +  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
  1.3173 +  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
  1.3174 +  MB_MODE_INFO best_mbmode = { 0 };
  1.3175 +  int j;
  1.3176 +  int mode_index, best_mode_index = 0;
  1.3177 +  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
  1.3178 +  vp9_prob comp_mode_p;
  1.3179 +  int64_t best_intra_rd = INT64_MAX;
  1.3180 +  int64_t best_inter_rd = INT64_MAX;
  1.3181 +  MB_PREDICTION_MODE best_intra_mode = DC_PRED;
  1.3182 +  MV_REFERENCE_FRAME best_inter_ref_frame = LAST_FRAME;
  1.3183 +  INTERPOLATION_TYPE tmp_best_filter = SWITCHABLE;
  1.3184 +  int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
  1.3185 +  int64_t dist_uv[TX_SIZES];
  1.3186 +  int skip_uv[TX_SIZES];
  1.3187 +  MB_PREDICTION_MODE mode_uv[TX_SIZES];
  1.3188 +  struct scale_factors scale_factor[4];
  1.3189 +  unsigned int ref_frame_mask = 0;
  1.3190 +  unsigned int mode_mask = 0;
  1.3191 +  int64_t mode_distortions[MB_MODE_COUNT] = {-1};
  1.3192 +  int64_t frame_distortions[MAX_REF_FRAMES] = {-1};
  1.3193 +  int intra_cost_penalty = 20 * vp9_dc_quant(cm->base_qindex, cm->y_dc_delta_q);
  1.3194 +  const int bws = num_8x8_blocks_wide_lookup[bsize] / 2;
  1.3195 +  const int bhs = num_8x8_blocks_high_lookup[bsize] / 2;
  1.3196 +  int best_skip2 = 0;
  1.3197 +
  1.3198 +  x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
  1.3199 +
  1.3200 +  // Everywhere the flag is set the error is much higher than its neighbors.
  1.3201 +  ctx->frames_with_high_error = 0;
  1.3202 +  ctx->modes_with_high_error = 0;
  1.3203 +
  1.3204 +  estimate_ref_frame_costs(cpi, segment_id, ref_costs_single, ref_costs_comp,
  1.3205 +                           &comp_mode_p);
  1.3206 +
  1.3207 +  for (i = 0; i < NB_PREDICTION_TYPES; ++i)
  1.3208 +    best_pred_rd[i] = INT64_MAX;
  1.3209 +  for (i = 0; i < TX_MODES; i++)
  1.3210 +    best_tx_rd[i] = INT64_MAX;
  1.3211 +  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
  1.3212 +    best_filter_rd[i] = INT64_MAX;
  1.3213 +  for (i = 0; i < TX_SIZES; i++)
  1.3214 +    rate_uv_intra[i] = INT_MAX;
  1.3215 +
  1.3216 +  *returnrate = INT_MAX;
  1.3217 +
  1.3218 +  // Create a mask set to 1 for each reference frame used by a smaller
  1.3219 +  // resolution.
  1.3220 +  if (cpi->sf.use_avoid_tested_higherror) {
  1.3221 +    switch (block_size) {
  1.3222 +      case BLOCK_64X64:
  1.3223 +        for (i = 0; i < 4; i++) {
  1.3224 +          for (j = 0; j < 4; j++) {
  1.3225 +            ref_frame_mask |= x->mb_context[i][j].frames_with_high_error;
  1.3226 +            mode_mask |= x->mb_context[i][j].modes_with_high_error;
  1.3227 +          }
  1.3228 +        }
  1.3229 +        for (i = 0; i < 4; i++) {
  1.3230 +          ref_frame_mask |= x->sb32_context[i].frames_with_high_error;
  1.3231 +          mode_mask |= x->sb32_context[i].modes_with_high_error;
  1.3232 +        }
  1.3233 +        break;
  1.3234 +      case BLOCK_32X32:
  1.3235 +        for (i = 0; i < 4; i++) {
  1.3236 +          ref_frame_mask |=
  1.3237 +              x->mb_context[x->sb_index][i].frames_with_high_error;
  1.3238 +          mode_mask |= x->mb_context[x->sb_index][i].modes_with_high_error;
  1.3239 +        }
  1.3240 +        break;
  1.3241 +      default:
  1.3242 +        // Until we handle all block sizes set it to present;
  1.3243 +        ref_frame_mask = 0;
  1.3244 +        mode_mask = 0;
  1.3245 +        break;
  1.3246 +    }
  1.3247 +    ref_frame_mask = ~ref_frame_mask;
  1.3248 +    mode_mask = ~mode_mask;
  1.3249 +  }
  1.3250 +
  1.3251 +  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
  1.3252 +    if (cpi->ref_frame_flags & flag_list[ref_frame]) {
  1.3253 +      setup_buffer_inter(cpi, x, tile, idx_list[ref_frame], ref_frame,
  1.3254 +                         block_size, mi_row, mi_col,
  1.3255 +                         frame_mv[NEARESTMV], frame_mv[NEARMV],
  1.3256 +                         yv12_mb, scale_factor);
  1.3257 +    }
  1.3258 +    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
  1.3259 +    frame_mv[ZEROMV][ref_frame].as_int = 0;
  1.3260 +  }
  1.3261 +
  1.3262 +  for (mode_index = 0; mode_index < MAX_MODES; ++mode_index) {
  1.3263 +    int mode_excluded = 0;
  1.3264 +    int64_t this_rd = INT64_MAX;
  1.3265 +    int disable_skip = 0;
  1.3266 +    int compmode_cost = 0;
  1.3267 +    int rate2 = 0, rate_y = 0, rate_uv = 0;
  1.3268 +    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
  1.3269 +    int skippable = 0;
  1.3270 +    int64_t tx_cache[TX_MODES];
  1.3271 +    int i;
  1.3272 +    int this_skip2 = 0;
  1.3273 +    int64_t total_sse = INT_MAX;
  1.3274 +    int early_term = 0;
  1.3275 +
  1.3276 +    for (i = 0; i < TX_MODES; ++i)
  1.3277 +      tx_cache[i] = INT64_MAX;
  1.3278 +
  1.3279 +    x->skip = 0;
  1.3280 +    this_mode = vp9_mode_order[mode_index].mode;
  1.3281 +    ref_frame = vp9_mode_order[mode_index].ref_frame;
  1.3282 +    second_ref_frame = vp9_mode_order[mode_index].second_ref_frame;
  1.3283 +
  1.3284 +    // Look at the reference frame of the best mode so far and set the
  1.3285 +    // skip mask to look at a subset of the remaining modes.
  1.3286 +    if (mode_index > cpi->sf.mode_skip_start) {
  1.3287 +      if (mode_index == (cpi->sf.mode_skip_start + 1)) {
  1.3288 +        switch (vp9_mode_order[best_mode_index].ref_frame) {
  1.3289 +          case INTRA_FRAME:
  1.3290 +            cpi->mode_skip_mask = 0;
  1.3291 +            break;
  1.3292 +          case LAST_FRAME:
  1.3293 +            cpi->mode_skip_mask = LAST_FRAME_MODE_MASK;
  1.3294 +            break;
  1.3295 +          case GOLDEN_FRAME:
  1.3296 +            cpi->mode_skip_mask = GOLDEN_FRAME_MODE_MASK;
  1.3297 +            break;
  1.3298 +          case ALTREF_FRAME:
  1.3299 +            cpi->mode_skip_mask = ALT_REF_MODE_MASK;
  1.3300 +            break;
  1.3301 +          case NONE:
  1.3302 +          case MAX_REF_FRAMES:
  1.3303 +            assert(!"Invalid Reference frame");
  1.3304 +        }
  1.3305 +      }
  1.3306 +      if (cpi->mode_skip_mask & ((int64_t)1 << mode_index))
  1.3307 +        continue;
  1.3308 +    }
  1.3309 +
  1.3310 +    // Skip if the current reference frame has been masked off
  1.3311 +    if (cpi->sf.reference_masking && !cpi->set_ref_frame_mask &&
  1.3312 +        (cpi->ref_frame_mask & (1 << ref_frame)))
  1.3313 +      continue;
  1.3314 +
  1.3315 +    // Test best rd so far against threshold for trying this mode.
  1.3316 +    if ((best_rd < ((int64_t)cpi->rd_threshes[segment_id][bsize][mode_index] *
  1.3317 +                     cpi->rd_thresh_freq_fact[bsize][mode_index] >> 5)) ||
  1.3318 +        cpi->rd_threshes[segment_id][bsize][mode_index] == INT_MAX)
  1.3319 +      continue;
  1.3320 +
  1.3321 +    // Do not allow compound prediction if the segment level reference
  1.3322 +    // frame feature is in use as in this case there can only be one reference.
  1.3323 +    if ((second_ref_frame > INTRA_FRAME) &&
  1.3324 +         vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
  1.3325 +      continue;
  1.3326 +
  1.3327 +    // Skip some checking based on small partitions' result.
  1.3328 +    if (x->fast_ms > 1 && !ref_frame)
  1.3329 +      continue;
  1.3330 +    if (x->fast_ms > 2 && ref_frame != x->subblock_ref)
  1.3331 +      continue;
  1.3332 +
  1.3333 +    if (cpi->sf.use_avoid_tested_higherror && bsize >= BLOCK_8X8) {
  1.3334 +      if (!(ref_frame_mask & (1 << ref_frame))) {
  1.3335 +        continue;
  1.3336 +      }
  1.3337 +      if (!(mode_mask & (1 << this_mode))) {
  1.3338 +        continue;
  1.3339 +      }
  1.3340 +      if (second_ref_frame != NONE
  1.3341 +          && !(ref_frame_mask & (1 << second_ref_frame))) {
  1.3342 +        continue;
  1.3343 +      }
  1.3344 +    }
  1.3345 +
  1.3346 +    mbmi->ref_frame[0] = ref_frame;
  1.3347 +    mbmi->ref_frame[1] = second_ref_frame;
  1.3348 +
  1.3349 +    if (!(ref_frame == INTRA_FRAME
  1.3350 +        || (cpi->ref_frame_flags & flag_list[ref_frame]))) {
  1.3351 +      continue;
  1.3352 +    }
  1.3353 +    if (!(second_ref_frame == NONE
  1.3354 +        || (cpi->ref_frame_flags & flag_list[second_ref_frame]))) {
  1.3355 +      continue;
  1.3356 +    }
  1.3357 +
  1.3358 +    comp_pred = second_ref_frame > INTRA_FRAME;
  1.3359 +    if (comp_pred) {
  1.3360 +      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA)
  1.3361 +        if (vp9_mode_order[best_mode_index].ref_frame == INTRA_FRAME)
  1.3362 +          continue;
  1.3363 +      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_COMP_REFMISMATCH)
  1.3364 +        if (ref_frame != best_inter_ref_frame &&
  1.3365 +            second_ref_frame != best_inter_ref_frame)
  1.3366 +          continue;
  1.3367 +    }
  1.3368 +
  1.3369 +    set_scale_factors(xd, ref_frame, second_ref_frame, scale_factor);
  1.3370 +    mbmi->uv_mode = DC_PRED;
  1.3371 +
  1.3372 +    // Evaluate all sub-pel filters irrespective of whether we can use
  1.3373 +    // them for this frame.
  1.3374 +    mbmi->interp_filter = cm->mcomp_filter_type;
  1.3375 +    vp9_setup_interp_filters(xd, mbmi->interp_filter, cm);
  1.3376 +
  1.3377 +    if (comp_pred) {
  1.3378 +      if (!(cpi->ref_frame_flags & flag_list[second_ref_frame]))
  1.3379 +        continue;
  1.3380 +      set_scale_factors(xd, ref_frame, second_ref_frame, scale_factor);
  1.3381 +
  1.3382 +      mode_excluded = mode_excluded
  1.3383 +                         ? mode_excluded
  1.3384 +                         : cm->comp_pred_mode == SINGLE_PREDICTION_ONLY;
  1.3385 +    } else {
  1.3386 +      if (ref_frame != INTRA_FRAME && second_ref_frame != INTRA_FRAME) {
  1.3387 +        mode_excluded =
  1.3388 +            mode_excluded ?
  1.3389 +                mode_excluded : cm->comp_pred_mode == COMP_PREDICTION_ONLY;
  1.3390 +      }
  1.3391 +    }
  1.3392 +
  1.3393 +    // Select prediction reference frames.
  1.3394 +    for (i = 0; i < MAX_MB_PLANE; i++) {
  1.3395 +      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
  1.3396 +      if (comp_pred)
  1.3397 +        xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
  1.3398 +    }
  1.3399 +
  1.3400 +    // If the segment reference frame feature is enabled....
  1.3401 +    // then do nothing if the current ref frame is not allowed..
  1.3402 +    if (vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
  1.3403 +        vp9_get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) !=
  1.3404 +            (int)ref_frame) {
  1.3405 +      continue;
  1.3406 +    // If the segment skip feature is enabled....
  1.3407 +    // then do nothing if the current mode is not allowed..
  1.3408 +    } else if (vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP) &&
  1.3409 +               (this_mode != ZEROMV && ref_frame != INTRA_FRAME)) {
  1.3410 +      continue;
  1.3411 +    // Disable this drop out case if the ref frame
  1.3412 +    // segment level feature is enabled for this segment. This is to
  1.3413 +    // prevent the possibility that we end up unable to pick any mode.
  1.3414 +    } else if (!vp9_segfeature_active(seg, segment_id,
  1.3415 +                                      SEG_LVL_REF_FRAME)) {
  1.3416 +      // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
  1.3417 +      // unless ARNR filtering is enabled in which case we want
  1.3418 +      // an unfiltered alternative. We allow near/nearest as well
  1.3419 +      // because they may result in zero-zero MVs but be cheaper.
  1.3420 +      if (cpi->is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
  1.3421 +        if ((this_mode != ZEROMV &&
  1.3422 +             !(this_mode == NEARMV &&
  1.3423 +               frame_mv[NEARMV][ALTREF_FRAME].as_int == 0) &&
  1.3424 +             !(this_mode == NEARESTMV &&
  1.3425 +               frame_mv[NEARESTMV][ALTREF_FRAME].as_int == 0)) ||
  1.3426 +            ref_frame != ALTREF_FRAME) {
  1.3427 +          continue;
  1.3428 +        }
  1.3429 +      }
  1.3430 +    }
  1.3431 +    // TODO(JBB): This is to make up for the fact that we don't have sad
  1.3432 +    // functions that work when the block size reads outside the umv.  We
  1.3433 +    // should fix this either by making the motion search just work on
  1.3434 +    // a representative block in the boundary ( first ) and then implement a
  1.3435 +    // function that does sads when inside the border..
  1.3436 +    if (((mi_row + bhs) > cm->mi_rows || (mi_col + bws) > cm->mi_cols) &&
  1.3437 +        this_mode == NEWMV) {
  1.3438 +      continue;
  1.3439 +    }
  1.3440 +
  1.3441 +#ifdef MODE_TEST_HIT_STATS
  1.3442 +    // TEST/DEBUG CODE
  1.3443 +    // Keep a rcord of the number of test hits at each size
  1.3444 +    cpi->mode_test_hits[bsize]++;
  1.3445 +#endif
  1.3446 +
  1.3447 +
  1.3448 +    if (ref_frame == INTRA_FRAME) {
  1.3449 +      TX_SIZE uv_tx;
  1.3450 +      // Disable intra modes other than DC_PRED for blocks with low variance
  1.3451 +      // Threshold for intra skipping based on source variance
  1.3452 +      // TODO(debargha): Specialize the threshold for super block sizes
  1.3453 +      static const unsigned int skip_intra_var_thresh[BLOCK_SIZES] = {
  1.3454 +        64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
  1.3455 +      };
  1.3456 +      if ((cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
  1.3457 +          this_mode != DC_PRED &&
  1.3458 +          x->source_variance < skip_intra_var_thresh[mbmi->sb_type])
  1.3459 +        continue;
  1.3460 +      // Only search the oblique modes if the best so far is
  1.3461 +      // one of the neighboring directional modes
  1.3462 +      if ((cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
  1.3463 +          (this_mode >= D45_PRED && this_mode <= TM_PRED)) {
  1.3464 +        if (vp9_mode_order[best_mode_index].ref_frame > INTRA_FRAME)
  1.3465 +          continue;
  1.3466 +      }
  1.3467 +      mbmi->mode = this_mode;
  1.3468 +      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
  1.3469 +        if (conditional_skipintra(mbmi->mode, best_intra_mode))
  1.3470 +            continue;
  1.3471 +      }
  1.3472 +
  1.3473 +      super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable, NULL,
  1.3474 +                      bsize, tx_cache, best_rd);
  1.3475 +
  1.3476 +      if (rate_y == INT_MAX)
  1.3477 +        continue;
  1.3478 +
  1.3479 +      uv_tx = MIN(mbmi->tx_size, max_uv_txsize_lookup[bsize]);
  1.3480 +      if (rate_uv_intra[uv_tx] == INT_MAX) {
  1.3481 +        choose_intra_uv_mode(cpi, ctx, bsize, &rate_uv_intra[uv_tx],
  1.3482 +                             &rate_uv_tokenonly[uv_tx],
  1.3483 +                             &dist_uv[uv_tx], &skip_uv[uv_tx],
  1.3484 +                             &mode_uv[uv_tx]);
  1.3485 +      }
  1.3486 +
  1.3487 +      rate_uv = rate_uv_tokenonly[uv_tx];
  1.3488 +      distortion_uv = dist_uv[uv_tx];
  1.3489 +      skippable = skippable && skip_uv[uv_tx];
  1.3490 +      mbmi->uv_mode = mode_uv[uv_tx];
  1.3491 +
  1.3492 +      rate2 = rate_y + x->mbmode_cost[mbmi->mode] + rate_uv_intra[uv_tx];
  1.3493 +      if (this_mode != DC_PRED && this_mode != TM_PRED)
  1.3494 +        rate2 += intra_cost_penalty;
  1.3495 +      distortion2 = distortion_y + distortion_uv;
  1.3496 +    } else {
  1.3497 +      mbmi->mode = this_mode;
  1.3498 +      compmode_cost = vp9_cost_bit(comp_mode_p, second_ref_frame > INTRA_FRAME);
  1.3499 +      this_rd = handle_inter_mode(cpi, x, tile, bsize,
  1.3500 +                                  tx_cache,
  1.3501 +                                  &rate2, &distortion2, &skippable,
  1.3502 +                                  &rate_y, &distortion_y,
  1.3503 +                                  &rate_uv, &distortion_uv,
  1.3504 +                                  &mode_excluded, &disable_skip,
  1.3505 +                                  &tmp_best_filter, frame_mv,
  1.3506 +                                  mi_row, mi_col,
  1.3507 +                                  single_newmv, &total_sse, best_rd);
  1.3508 +      if (this_rd == INT64_MAX)
  1.3509 +        continue;
  1.3510 +    }
  1.3511 +
  1.3512 +    if (cm->comp_pred_mode == HYBRID_PREDICTION) {
  1.3513 +      rate2 += compmode_cost;
  1.3514 +    }
  1.3515 +
  1.3516 +    // Estimate the reference frame signaling cost and add it
  1.3517 +    // to the rolling cost variable.
  1.3518 +    if (second_ref_frame > INTRA_FRAME) {
  1.3519 +      rate2 += ref_costs_comp[ref_frame];
  1.3520 +    } else {
  1.3521 +      rate2 += ref_costs_single[ref_frame];
  1.3522 +    }
  1.3523 +
  1.3524 +    if (!disable_skip) {
  1.3525 +      // Test for the condition where skip block will be activated
  1.3526 +      // because there are no non zero coefficients and make any
  1.3527 +      // necessary adjustment for rate. Ignore if skip is coded at
  1.3528 +      // segment level as the cost wont have been added in.
  1.3529 +      // Is Mb level skip allowed (i.e. not coded at segment level).
  1.3530 +      const int mb_skip_allowed = !vp9_segfeature_active(seg, segment_id,
  1.3531 +                                                         SEG_LVL_SKIP);
  1.3532 +
  1.3533 +      if (skippable) {
  1.3534 +        // Back out the coefficient coding costs
  1.3535 +        rate2 -= (rate_y + rate_uv);
  1.3536 +        // for best yrd calculation
  1.3537 +        rate_uv = 0;
  1.3538 +
  1.3539 +        if (mb_skip_allowed) {
  1.3540 +          int prob_skip_cost;
  1.3541 +
  1.3542 +          // Cost the skip mb case
  1.3543 +          vp9_prob skip_prob =
  1.3544 +            vp9_get_pred_prob_mbskip(cm, xd);
  1.3545 +
  1.3546 +          if (skip_prob) {
  1.3547 +            prob_skip_cost = vp9_cost_bit(skip_prob, 1);
  1.3548 +            rate2 += prob_skip_cost;
  1.3549 +          }
  1.3550 +        }
  1.3551 +      } else if (mb_skip_allowed && ref_frame != INTRA_FRAME && !xd->lossless) {
  1.3552 +        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv, distortion2) <
  1.3553 +            RDCOST(x->rdmult, x->rddiv, 0, total_sse)) {
  1.3554 +          // Add in the cost of the no skip flag.
  1.3555 +          int prob_skip_cost = vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd),
  1.3556 +                                            0);
  1.3557 +          rate2 += prob_skip_cost;
  1.3558 +        } else {
  1.3559 +          // FIXME(rbultje) make this work for splitmv also
  1.3560 +          int prob_skip_cost = vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd),
  1.3561 +                                            1);
  1.3562 +          rate2 += prob_skip_cost;
  1.3563 +          distortion2 = total_sse;
  1.3564 +          assert(total_sse >= 0);
  1.3565 +          rate2 -= (rate_y + rate_uv);
  1.3566 +          rate_y = 0;
  1.3567 +          rate_uv = 0;
  1.3568 +          this_skip2 = 1;
  1.3569 +        }
  1.3570 +      } else if (mb_skip_allowed) {
  1.3571 +        // Add in the cost of the no skip flag.
  1.3572 +        int prob_skip_cost = vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd),
  1.3573 +                                          0);
  1.3574 +        rate2 += prob_skip_cost;
  1.3575 +      }
  1.3576 +
  1.3577 +      // Calculate the final RD estimate for this mode.
  1.3578 +      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
  1.3579 +    }
  1.3580 +
  1.3581 +    // Keep record of best intra rd
  1.3582 +    if (!is_inter_block(&xd->mi_8x8[0]->mbmi) &&
  1.3583 +        this_rd < best_intra_rd) {
  1.3584 +      best_intra_rd = this_rd;
  1.3585 +      best_intra_mode = xd->mi_8x8[0]->mbmi.mode;
  1.3586 +    }
  1.3587 +
  1.3588 +    // Keep record of best inter rd with single reference
  1.3589 +    if (is_inter_block(&xd->mi_8x8[0]->mbmi) &&
  1.3590 +        !has_second_ref(&xd->mi_8x8[0]->mbmi) &&
  1.3591 +        !mode_excluded && this_rd < best_inter_rd) {
  1.3592 +      best_inter_rd = this_rd;
  1.3593 +      best_inter_ref_frame = ref_frame;
  1.3594 +    }
  1.3595 +
  1.3596 +    if (!disable_skip && ref_frame == INTRA_FRAME) {
  1.3597 +      for (i = 0; i < NB_PREDICTION_TYPES; ++i)
  1.3598 +        best_pred_rd[i] = MIN(best_pred_rd[i], this_rd);
  1.3599 +      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
  1.3600 +        best_filter_rd[i] = MIN(best_filter_rd[i], this_rd);
  1.3601 +    }
  1.3602 +
  1.3603 +    // Store the respective mode distortions for later use.
  1.3604 +    if (mode_distortions[this_mode] == -1
  1.3605 +        || distortion2 < mode_distortions[this_mode]) {
  1.3606 +      mode_distortions[this_mode] = distortion2;
  1.3607 +    }
  1.3608 +    if (frame_distortions[ref_frame] == -1
  1.3609 +        || distortion2 < frame_distortions[ref_frame]) {
  1.3610 +      frame_distortions[ref_frame] = distortion2;
  1.3611 +    }
  1.3612 +
  1.3613 +    // Did this mode help.. i.e. is it the new best mode
  1.3614 +    if (this_rd < best_rd || x->skip) {
  1.3615 +      int max_plane = MAX_MB_PLANE;
  1.3616 +      if (!mode_excluded) {
  1.3617 +        // Note index of best mode so far
  1.3618 +        best_mode_index = mode_index;
  1.3619 +
  1.3620 +        if (ref_frame == INTRA_FRAME) {
  1.3621 +          /* required for left and above block mv */
  1.3622 +          mbmi->mv[0].as_int = 0;
  1.3623 +          max_plane = 1;
  1.3624 +        }
  1.3625 +
  1.3626 +        *returnrate = rate2;
  1.3627 +        *returndistortion = distortion2;
  1.3628 +        best_rd = this_rd;
  1.3629 +        best_mbmode = *mbmi;
  1.3630 +        best_skip2 = this_skip2;
  1.3631 +        if (!x->select_txfm_size)
  1.3632 +          swap_block_ptr(x, ctx, max_plane);
  1.3633 +        vpx_memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mbmi->tx_size],
  1.3634 +                   sizeof(uint8_t) * ctx->num_4x4_blk);
  1.3635 +
  1.3636 +        // TODO(debargha): enhance this test with a better distortion prediction
  1.3637 +        // based on qp, activity mask and history
  1.3638 +        if ((cpi->sf.mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
  1.3639 +            (mode_index > MIN_EARLY_TERM_INDEX)) {
  1.3640 +          const int qstep = xd->plane[0].dequant[1];
  1.3641 +          // TODO(debargha): Enhance this by specializing for each mode_index
  1.3642 +          int scale = 4;
  1.3643 +          if (x->source_variance < UINT_MAX) {
  1.3644 +            const int var_adjust = (x->source_variance < 16);
  1.3645 +            scale -= var_adjust;
  1.3646 +          }
  1.3647 +          if (ref_frame > INTRA_FRAME &&
  1.3648 +              distortion2 * scale < qstep * qstep) {
  1.3649 +            early_term = 1;
  1.3650 +          }
  1.3651 +        }
  1.3652 +      }
  1.3653 +    }
  1.3654 +
  1.3655 +    /* keep record of best compound/single-only prediction */
  1.3656 +    if (!disable_skip && ref_frame != INTRA_FRAME) {
  1.3657 +      int single_rd, hybrid_rd, single_rate, hybrid_rate;
  1.3658 +
  1.3659 +      if (cm->comp_pred_mode == HYBRID_PREDICTION) {
  1.3660 +        single_rate = rate2 - compmode_cost;
  1.3661 +        hybrid_rate = rate2;
  1.3662 +      } else {
  1.3663 +        single_rate = rate2;
  1.3664 +        hybrid_rate = rate2 + compmode_cost;
  1.3665 +      }
  1.3666 +
  1.3667 +      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
  1.3668 +      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
  1.3669 +
  1.3670 +      if (second_ref_frame <= INTRA_FRAME &&
  1.3671 +          single_rd < best_pred_rd[SINGLE_PREDICTION_ONLY]) {
  1.3672 +        best_pred_rd[SINGLE_PREDICTION_ONLY] = single_rd;
  1.3673 +      } else if (second_ref_frame > INTRA_FRAME &&
  1.3674 +                 single_rd < best_pred_rd[COMP_PREDICTION_ONLY]) {
  1.3675 +        best_pred_rd[COMP_PREDICTION_ONLY] = single_rd;
  1.3676 +      }
  1.3677 +      if (hybrid_rd < best_pred_rd[HYBRID_PREDICTION])
  1.3678 +        best_pred_rd[HYBRID_PREDICTION] = hybrid_rd;
  1.3679 +    }
  1.3680 +
  1.3681 +    /* keep record of best filter type */
  1.3682 +    if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
  1.3683 +        cm->mcomp_filter_type != BILINEAR) {
  1.3684 +      int64_t ref = cpi->rd_filter_cache[cm->mcomp_filter_type == SWITCHABLE ?
  1.3685 +                              SWITCHABLE_FILTERS : cm->mcomp_filter_type];
  1.3686 +      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
  1.3687 +        int64_t adj_rd;
  1.3688 +        // In cases of poor prediction, filter_cache[] can contain really big
  1.3689 +        // values, which actually are bigger than this_rd itself. This can
  1.3690 +        // cause negative best_filter_rd[] values, which is obviously silly.
  1.3691 +        // Therefore, if filter_cache < ref, we do an adjusted calculation.
  1.3692 +        if (cpi->rd_filter_cache[i] >= ref) {
  1.3693 +          adj_rd = this_rd + cpi->rd_filter_cache[i] - ref;
  1.3694 +        } else {
  1.3695 +          // FIXME(rbultje) do this for comppsred also
  1.3696 +          //
  1.3697 +          // To prevent out-of-range computation in
  1.3698 +          //    adj_rd = cpi->rd_filter_cache[i] * this_rd / ref
  1.3699 +          // cpi->rd_filter_cache[i] / ref is converted to a 256 based ratio.
  1.3700 +          int tmp = cpi->rd_filter_cache[i] * 256 / ref;
  1.3701 +          adj_rd = (this_rd * tmp) >> 8;
  1.3702 +        }
  1.3703 +        best_filter_rd[i] = MIN(best_filter_rd[i], adj_rd);
  1.3704 +      }
  1.3705 +    }
  1.3706 +
  1.3707 +    /* keep record of best txfm size */
  1.3708 +    if (bsize < BLOCK_32X32) {
  1.3709 +      if (bsize < BLOCK_16X16)
  1.3710 +        tx_cache[ALLOW_16X16] = tx_cache[ALLOW_8X8];
  1.3711 +
  1.3712 +      tx_cache[ALLOW_32X32] = tx_cache[ALLOW_16X16];
  1.3713 +    }
  1.3714 +    if (!mode_excluded && this_rd != INT64_MAX) {
  1.3715 +      for (i = 0; i < TX_MODES && tx_cache[i] < INT64_MAX; i++) {
  1.3716 +        int64_t adj_rd = INT64_MAX;
  1.3717 +        adj_rd = this_rd + tx_cache[i] - tx_cache[cm->tx_mode];
  1.3718 +
  1.3719 +        if (adj_rd < best_tx_rd[i])
  1.3720 +          best_tx_rd[i] = adj_rd;
  1.3721 +      }
  1.3722 +    }
  1.3723 +
  1.3724 +    if (early_term)
  1.3725 +      break;
  1.3726 +
  1.3727 +    if (x->skip && !comp_pred)
  1.3728 +      break;
  1.3729 +  }
  1.3730 +
  1.3731 +  if (best_rd >= best_rd_so_far)
  1.3732 +    return INT64_MAX;
  1.3733 +
  1.3734 +  // If we used an estimate for the uv intra rd in the loop above...
  1.3735 +  if (cpi->sf.use_uv_intra_rd_estimate) {
  1.3736 +    // Do Intra UV best rd mode selection if best mode choice above was intra.
  1.3737 +    if (vp9_mode_order[best_mode_index].ref_frame == INTRA_FRAME) {
  1.3738 +      TX_SIZE uv_tx_size = get_uv_tx_size(mbmi);
  1.3739 +      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
  1.3740 +                              &rate_uv_tokenonly[uv_tx_size],
  1.3741 +                              &dist_uv[uv_tx_size],
  1.3742 +                              &skip_uv[uv_tx_size],
  1.3743 +                              bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
  1.3744 +    }
  1.3745 +  }
  1.3746 +
  1.3747 +  // If we are using reference masking and the set mask flag is set then
  1.3748 +  // create the reference frame mask.
  1.3749 +  if (cpi->sf.reference_masking && cpi->set_ref_frame_mask)
  1.3750 +    cpi->ref_frame_mask = ~(1 << vp9_mode_order[best_mode_index].ref_frame);
  1.3751 +
  1.3752 +  // Flag all modes that have a distortion thats > 2x the best we found at
  1.3753 +  // this level.
  1.3754 +  for (mode_index = 0; mode_index < MB_MODE_COUNT; ++mode_index) {
  1.3755 +    if (mode_index == NEARESTMV || mode_index == NEARMV || mode_index == NEWMV)
  1.3756 +      continue;
  1.3757 +
  1.3758 +    if (mode_distortions[mode_index] > 2 * *returndistortion) {
  1.3759 +      ctx->modes_with_high_error |= (1 << mode_index);
  1.3760 +    }
  1.3761 +  }
  1.3762 +
  1.3763 +  // Flag all ref frames that have a distortion thats > 2x the best we found at
  1.3764 +  // this level.
  1.3765 +  for (ref_frame = INTRA_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
  1.3766 +    if (frame_distortions[ref_frame] > 2 * *returndistortion) {
  1.3767 +      ctx->frames_with_high_error |= (1 << ref_frame);
  1.3768 +    }
  1.3769 +  }
  1.3770 +
  1.3771 +  assert((cm->mcomp_filter_type == SWITCHABLE) ||
  1.3772 +         (cm->mcomp_filter_type == best_mbmode.interp_filter) ||
  1.3773 +         (best_mbmode.ref_frame[0] == INTRA_FRAME));
  1.3774 +
  1.3775 +  // Updating rd_thresh_freq_fact[] here means that the different
  1.3776 +  // partition/block sizes are handled independently based on the best
  1.3777 +  // choice for the current partition. It may well be better to keep a scaled
  1.3778 +  // best rd so far value and update rd_thresh_freq_fact based on the mode/size
  1.3779 +  // combination that wins out.
  1.3780 +  if (cpi->sf.adaptive_rd_thresh) {
  1.3781 +    for (mode_index = 0; mode_index < MAX_MODES; ++mode_index) {
  1.3782 +      if (mode_index == best_mode_index) {
  1.3783 +        cpi->rd_thresh_freq_fact[bsize][mode_index] -=
  1.3784 +          (cpi->rd_thresh_freq_fact[bsize][mode_index] >> 3);
  1.3785 +      } else {
  1.3786 +        cpi->rd_thresh_freq_fact[bsize][mode_index] += RD_THRESH_INC;
  1.3787 +        if (cpi->rd_thresh_freq_fact[bsize][mode_index] >
  1.3788 +            (cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT)) {
  1.3789 +          cpi->rd_thresh_freq_fact[bsize][mode_index] =
  1.3790 +            cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT;
  1.3791 +        }
  1.3792 +      }
  1.3793 +    }
  1.3794 +  }
  1.3795 +
  1.3796 +  // macroblock modes
  1.3797 +  *mbmi = best_mbmode;
  1.3798 +  x->skip |= best_skip2;
  1.3799 +
  1.3800 +  for (i = 0; i < NB_PREDICTION_TYPES; ++i) {
  1.3801 +    if (best_pred_rd[i] == INT64_MAX)
  1.3802 +      best_pred_diff[i] = INT_MIN;
  1.3803 +    else
  1.3804 +      best_pred_diff[i] = best_rd - best_pred_rd[i];
  1.3805 +  }
  1.3806 +
  1.3807 +  if (!x->skip) {
  1.3808 +    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
  1.3809 +      if (best_filter_rd[i] == INT64_MAX)
  1.3810 +        best_filter_diff[i] = 0;
  1.3811 +      else
  1.3812 +        best_filter_diff[i] = best_rd - best_filter_rd[i];
  1.3813 +    }
  1.3814 +    if (cm->mcomp_filter_type == SWITCHABLE)
  1.3815 +      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
  1.3816 +  } else {
  1.3817 +    vp9_zero(best_filter_diff);
  1.3818 +  }
  1.3819 +
  1.3820 +  if (!x->skip) {
  1.3821 +    for (i = 0; i < TX_MODES; i++) {
  1.3822 +      if (best_tx_rd[i] == INT64_MAX)
  1.3823 +        best_tx_diff[i] = 0;
  1.3824 +      else
  1.3825 +        best_tx_diff[i] = best_rd - best_tx_rd[i];
  1.3826 +    }
  1.3827 +  } else {
  1.3828 +    vp9_zero(best_tx_diff);
  1.3829 +  }
  1.3830 +
  1.3831 +  set_scale_factors(xd, mbmi->ref_frame[0], mbmi->ref_frame[1],
  1.3832 +                    scale_factor);
  1.3833 +  store_coding_context(x, ctx, best_mode_index,
  1.3834 +                       &mbmi->ref_mvs[mbmi->ref_frame[0]][0],
  1.3835 +                       &mbmi->ref_mvs[mbmi->ref_frame[1] < 0 ? 0 :
  1.3836 +                                      mbmi->ref_frame[1]][0],
  1.3837 +                       best_pred_diff, best_tx_diff, best_filter_diff);
  1.3838 +
  1.3839 +  return best_rd;
  1.3840 +}
  1.3841 +
  1.3842 +
  1.3843 +int64_t vp9_rd_pick_inter_mode_sub8x8(VP9_COMP *cpi, MACROBLOCK *x,
  1.3844 +                                      const TileInfo *const tile,
  1.3845 +                                      int mi_row, int mi_col,
  1.3846 +                                      int *returnrate,
  1.3847 +                                      int64_t *returndistortion,
  1.3848 +                                      BLOCK_SIZE bsize,
  1.3849 +                                      PICK_MODE_CONTEXT *ctx,
  1.3850 +                                      int64_t best_rd_so_far) {
  1.3851 +  VP9_COMMON *cm = &cpi->common;
  1.3852 +  MACROBLOCKD *xd = &x->e_mbd;
  1.3853 +  MB_MODE_INFO *mbmi = &xd->mi_8x8[0]->mbmi;
  1.3854 +  const struct segmentation *seg = &cm->seg;
  1.3855 +  const BLOCK_SIZE block_size = get_plane_block_size(bsize, &xd->plane[0]);
  1.3856 +  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
  1.3857 +  unsigned char segment_id = mbmi->segment_id;
  1.3858 +  int comp_pred, i;
  1.3859 +  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
  1.3860 +  struct buf_2d yv12_mb[4][MAX_MB_PLANE];
  1.3861 +  static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
  1.3862 +                                    VP9_ALT_FLAG };
  1.3863 +  int idx_list[4] = {0,
  1.3864 +                     cpi->lst_fb_idx,
  1.3865 +                     cpi->gld_fb_idx,
  1.3866 +                     cpi->alt_fb_idx};
  1.3867 +  int64_t best_rd = best_rd_so_far;
  1.3868 +  int64_t best_yrd = best_rd_so_far;  // FIXME(rbultje) more precise
  1.3869 +  int64_t best_tx_rd[TX_MODES];
  1.3870 +  int64_t best_tx_diff[TX_MODES];
  1.3871 +  int64_t best_pred_diff[NB_PREDICTION_TYPES];
  1.3872 +  int64_t best_pred_rd[NB_PREDICTION_TYPES];
  1.3873 +  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
  1.3874 +  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
  1.3875 +  MB_MODE_INFO best_mbmode = { 0 };
  1.3876 +  int mode_index, best_mode_index = 0;
  1.3877 +  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
  1.3878 +  vp9_prob comp_mode_p;
  1.3879 +  int64_t best_inter_rd = INT64_MAX;
  1.3880 +  MV_REFERENCE_FRAME best_inter_ref_frame = LAST_FRAME;
  1.3881 +  INTERPOLATION_TYPE tmp_best_filter = SWITCHABLE;
  1.3882 +  int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
  1.3883 +  int64_t dist_uv[TX_SIZES];
  1.3884 +  int skip_uv[TX_SIZES];
  1.3885 +  MB_PREDICTION_MODE mode_uv[TX_SIZES] = { 0 };
  1.3886 +  struct scale_factors scale_factor[4];
  1.3887 +  unsigned int ref_frame_mask = 0;
  1.3888 +  unsigned int mode_mask = 0;
  1.3889 +  int intra_cost_penalty = 20 * vp9_dc_quant(cpi->common.base_qindex,
  1.3890 +                                             cpi->common.y_dc_delta_q);
  1.3891 +  int_mv seg_mvs[4][MAX_REF_FRAMES];
  1.3892 +  b_mode_info best_bmodes[4];
  1.3893 +  int best_skip2 = 0;
  1.3894 +
  1.3895 +  x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
  1.3896 +  vpx_memset(x->zcoeff_blk[TX_4X4], 0, 4);
  1.3897 +
  1.3898 +  for (i = 0; i < 4; i++) {
  1.3899 +    int j;
  1.3900 +    for (j = 0; j < MAX_REF_FRAMES; j++)
  1.3901 +      seg_mvs[i][j].as_int = INVALID_MV;
  1.3902 +  }
  1.3903 +
  1.3904 +  estimate_ref_frame_costs(cpi, segment_id, ref_costs_single, ref_costs_comp,
  1.3905 +                           &comp_mode_p);
  1.3906 +
  1.3907 +  for (i = 0; i < NB_PREDICTION_TYPES; ++i)
  1.3908 +    best_pred_rd[i] = INT64_MAX;
  1.3909 +  for (i = 0; i < TX_MODES; i++)
  1.3910 +    best_tx_rd[i] = INT64_MAX;
  1.3911 +  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
  1.3912 +    best_filter_rd[i] = INT64_MAX;
  1.3913 +  for (i = 0; i < TX_SIZES; i++)
  1.3914 +    rate_uv_intra[i] = INT_MAX;
  1.3915 +
  1.3916 +  *returnrate = INT_MAX;
  1.3917 +
  1.3918 +  // Create a mask set to 1 for each reference frame used by a smaller
  1.3919 +  // resolution.
  1.3920 +  if (cpi->sf.use_avoid_tested_higherror) {
  1.3921 +    ref_frame_mask = 0;
  1.3922 +    mode_mask = 0;
  1.3923 +    ref_frame_mask = ~ref_frame_mask;
  1.3924 +    mode_mask = ~mode_mask;
  1.3925 +  }
  1.3926 +
  1.3927 +  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
  1.3928 +    if (cpi->ref_frame_flags & flag_list[ref_frame]) {
  1.3929 +      setup_buffer_inter(cpi, x, tile, idx_list[ref_frame], ref_frame,
  1.3930 +                         block_size, mi_row, mi_col,
  1.3931 +                         frame_mv[NEARESTMV], frame_mv[NEARMV],
  1.3932 +                         yv12_mb, scale_factor);
  1.3933 +    }
  1.3934 +    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
  1.3935 +    frame_mv[ZEROMV][ref_frame].as_int = 0;
  1.3936 +  }
  1.3937 +
  1.3938 +  for (mode_index = 0; mode_index < MAX_REFS; ++mode_index) {
  1.3939 +    int mode_excluded = 0;
  1.3940 +    int64_t this_rd = INT64_MAX;
  1.3941 +    int disable_skip = 0;
  1.3942 +    int compmode_cost = 0;
  1.3943 +    int rate2 = 0, rate_y = 0, rate_uv = 0;
  1.3944 +    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
  1.3945 +    int skippable = 0;
  1.3946 +    int64_t tx_cache[TX_MODES];
  1.3947 +    int i;
  1.3948 +    int this_skip2 = 0;
  1.3949 +    int64_t total_sse = INT_MAX;
  1.3950 +    int early_term = 0;
  1.3951 +
  1.3952 +    for (i = 0; i < TX_MODES; ++i)
  1.3953 +      tx_cache[i] = INT64_MAX;
  1.3954 +
  1.3955 +    x->skip = 0;
  1.3956 +    ref_frame = vp9_ref_order[mode_index].ref_frame;
  1.3957 +    second_ref_frame = vp9_ref_order[mode_index].second_ref_frame;
  1.3958 +
  1.3959 +    // Look at the reference frame of the best mode so far and set the
  1.3960 +    // skip mask to look at a subset of the remaining modes.
  1.3961 +    if (mode_index > 2 && cpi->sf.mode_skip_start < MAX_MODES) {
  1.3962 +      if (mode_index == 3) {
  1.3963 +        switch (vp9_ref_order[best_mode_index].ref_frame) {
  1.3964 +          case INTRA_FRAME:
  1.3965 +            cpi->mode_skip_mask = 0;
  1.3966 +            break;
  1.3967 +          case LAST_FRAME:
  1.3968 +            cpi->mode_skip_mask = 0x0010;
  1.3969 +            break;
  1.3970 +          case GOLDEN_FRAME:
  1.3971 +            cpi->mode_skip_mask = 0x0008;
  1.3972 +            break;
  1.3973 +          case ALTREF_FRAME:
  1.3974 +            cpi->mode_skip_mask = 0x0000;
  1.3975 +            break;
  1.3976 +          case NONE:
  1.3977 +          case MAX_REF_FRAMES:
  1.3978 +            assert(!"Invalid Reference frame");
  1.3979 +        }
  1.3980 +      }
  1.3981 +      if (cpi->mode_skip_mask & ((int64_t)1 << mode_index))
  1.3982 +        continue;
  1.3983 +    }
  1.3984 +
  1.3985 +    // Skip if the current reference frame has been masked off
  1.3986 +    if (cpi->sf.reference_masking && !cpi->set_ref_frame_mask &&
  1.3987 +        (cpi->ref_frame_mask & (1 << ref_frame)))
  1.3988 +      continue;
  1.3989 +
  1.3990 +    // Test best rd so far against threshold for trying this mode.
  1.3991 +    if ((best_rd <
  1.3992 +         ((int64_t)cpi->rd_thresh_sub8x8[segment_id][bsize][mode_index] *
  1.3993 +          cpi->rd_thresh_freq_sub8x8[bsize][mode_index] >> 5)) ||
  1.3994 +        cpi->rd_thresh_sub8x8[segment_id][bsize][mode_index] == INT_MAX)
  1.3995 +      continue;
  1.3996 +
  1.3997 +    // Do not allow compound prediction if the segment level reference
  1.3998 +    // frame feature is in use as in this case there can only be one reference.
  1.3999 +    if ((second_ref_frame > INTRA_FRAME) &&
  1.4000 +         vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
  1.4001 +      continue;
  1.4002 +
  1.4003 +    mbmi->ref_frame[0] = ref_frame;
  1.4004 +    mbmi->ref_frame[1] = second_ref_frame;
  1.4005 +
  1.4006 +    if (!(ref_frame == INTRA_FRAME
  1.4007 +        || (cpi->ref_frame_flags & flag_list[ref_frame]))) {
  1.4008 +      continue;
  1.4009 +    }
  1.4010 +    if (!(second_ref_frame == NONE
  1.4011 +        || (cpi->ref_frame_flags & flag_list[second_ref_frame]))) {
  1.4012 +      continue;
  1.4013 +    }
  1.4014 +
  1.4015 +    comp_pred = second_ref_frame > INTRA_FRAME;
  1.4016 +    if (comp_pred) {
  1.4017 +      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA)
  1.4018 +        if (vp9_ref_order[best_mode_index].ref_frame == INTRA_FRAME)
  1.4019 +          continue;
  1.4020 +      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_COMP_REFMISMATCH)
  1.4021 +        if (ref_frame != best_inter_ref_frame &&
  1.4022 +            second_ref_frame != best_inter_ref_frame)
  1.4023 +          continue;
  1.4024 +    }
  1.4025 +
  1.4026 +    // TODO(jingning, jkoleszar): scaling reference frame not supported for
  1.4027 +    // sub8x8 blocks.
  1.4028 +    if (ref_frame > 0 &&
  1.4029 +        vp9_is_scaled(scale_factor[ref_frame].sfc))
  1.4030 +      continue;
  1.4031 +
  1.4032 +    if (second_ref_frame > 0 &&
  1.4033 +        vp9_is_scaled(scale_factor[second_ref_frame].sfc))
  1.4034 +      continue;
  1.4035 +
  1.4036 +    set_scale_factors(xd, ref_frame, second_ref_frame, scale_factor);
  1.4037 +    mbmi->uv_mode = DC_PRED;
  1.4038 +
  1.4039 +    // Evaluate all sub-pel filters irrespective of whether we can use
  1.4040 +    // them for this frame.
  1.4041 +    mbmi->interp_filter = cm->mcomp_filter_type;
  1.4042 +    vp9_setup_interp_filters(xd, mbmi->interp_filter, &cpi->common);
  1.4043 +
  1.4044 +    if (comp_pred) {
  1.4045 +      if (!(cpi->ref_frame_flags & flag_list[second_ref_frame]))
  1.4046 +        continue;
  1.4047 +      set_scale_factors(xd, ref_frame, second_ref_frame, scale_factor);
  1.4048 +
  1.4049 +      mode_excluded = mode_excluded
  1.4050 +                         ? mode_excluded
  1.4051 +                         : cm->comp_pred_mode == SINGLE_PREDICTION_ONLY;
  1.4052 +    } else {
  1.4053 +      if (ref_frame != INTRA_FRAME && second_ref_frame != INTRA_FRAME) {
  1.4054 +        mode_excluded =
  1.4055 +            mode_excluded ?
  1.4056 +                mode_excluded : cm->comp_pred_mode == COMP_PREDICTION_ONLY;
  1.4057 +      }
  1.4058 +    }
  1.4059 +
  1.4060 +    // Select prediction reference frames.
  1.4061 +    for (i = 0; i < MAX_MB_PLANE; i++) {
  1.4062 +      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
  1.4063 +      if (comp_pred)
  1.4064 +        xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
  1.4065 +    }
  1.4066 +
  1.4067 +    // If the segment reference frame feature is enabled....
  1.4068 +    // then do nothing if the current ref frame is not allowed..
  1.4069 +    if (vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
  1.4070 +        vp9_get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) !=
  1.4071 +            (int)ref_frame) {
  1.4072 +      continue;
  1.4073 +    // If the segment skip feature is enabled....
  1.4074 +    // then do nothing if the current mode is not allowed..
  1.4075 +    } else if (vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP) &&
  1.4076 +               ref_frame != INTRA_FRAME) {
  1.4077 +      continue;
  1.4078 +    // Disable this drop out case if the ref frame
  1.4079 +    // segment level feature is enabled for this segment. This is to
  1.4080 +    // prevent the possibility that we end up unable to pick any mode.
  1.4081 +    } else if (!vp9_segfeature_active(seg, segment_id,
  1.4082 +                                      SEG_LVL_REF_FRAME)) {
  1.4083 +      // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
  1.4084 +      // unless ARNR filtering is enabled in which case we want
  1.4085 +      // an unfiltered alternative. We allow near/nearest as well
  1.4086 +      // because they may result in zero-zero MVs but be cheaper.
  1.4087 +      if (cpi->is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
  1.4088 +        continue;
  1.4089 +    }
  1.4090 +
  1.4091 +#ifdef MODE_TEST_HIT_STATS
  1.4092 +    // TEST/DEBUG CODE
  1.4093 +    // Keep a rcord of the number of test hits at each size
  1.4094 +    cpi->mode_test_hits[bsize]++;
  1.4095 +#endif
  1.4096 +
  1.4097 +    if (ref_frame == INTRA_FRAME) {
  1.4098 +      int rate;
  1.4099 +      mbmi->tx_size = TX_4X4;
  1.4100 +      if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y,
  1.4101 +                                       &distortion_y, best_rd) >= best_rd)
  1.4102 +        continue;
  1.4103 +      rate2 += rate;
  1.4104 +      rate2 += intra_cost_penalty;
  1.4105 +      distortion2 += distortion_y;
  1.4106 +
  1.4107 +      if (rate_uv_intra[TX_4X4] == INT_MAX) {
  1.4108 +        choose_intra_uv_mode(cpi, ctx, bsize, &rate_uv_intra[TX_4X4],
  1.4109 +                             &rate_uv_tokenonly[TX_4X4],
  1.4110 +                             &dist_uv[TX_4X4], &skip_uv[TX_4X4],
  1.4111 +                             &mode_uv[TX_4X4]);
  1.4112 +      }
  1.4113 +      rate2 += rate_uv_intra[TX_4X4];
  1.4114 +      rate_uv = rate_uv_tokenonly[TX_4X4];
  1.4115 +      distortion2 += dist_uv[TX_4X4];
  1.4116 +      distortion_uv = dist_uv[TX_4X4];
  1.4117 +      mbmi->uv_mode = mode_uv[TX_4X4];
  1.4118 +      tx_cache[ONLY_4X4] = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
  1.4119 +      for (i = 0; i < TX_MODES; ++i)
  1.4120 +        tx_cache[i] = tx_cache[ONLY_4X4];
  1.4121 +    } else {
  1.4122 +      int rate;
  1.4123 +      int64_t distortion;
  1.4124 +      int64_t this_rd_thresh;
  1.4125 +      int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
  1.4126 +      int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
  1.4127 +      int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
  1.4128 +      int tmp_best_skippable = 0;
  1.4129 +      int switchable_filter_index;
  1.4130 +      int_mv *second_ref = comp_pred ?
  1.4131 +                             &mbmi->ref_mvs[second_ref_frame][0] : NULL;
  1.4132 +      b_mode_info tmp_best_bmodes[16];
  1.4133 +      MB_MODE_INFO tmp_best_mbmode;
  1.4134 +      BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
  1.4135 +      int pred_exists = 0;
  1.4136 +      int uv_skippable;
  1.4137 +
  1.4138 +      this_rd_thresh = (ref_frame == LAST_FRAME) ?
  1.4139 +          cpi->rd_thresh_sub8x8[segment_id][bsize][THR_LAST] :
  1.4140 +          cpi->rd_thresh_sub8x8[segment_id][bsize][THR_ALTR];
  1.4141 +      this_rd_thresh = (ref_frame == GOLDEN_FRAME) ?
  1.4142 +          cpi->rd_thresh_sub8x8[segment_id][bsize][THR_GOLD] : this_rd_thresh;
  1.4143 +      xd->mi_8x8[0]->mbmi.tx_size = TX_4X4;
  1.4144 +
  1.4145 +      cpi->rd_filter_cache[SWITCHABLE_FILTERS] = INT64_MAX;
  1.4146 +      if (cm->mcomp_filter_type != BILINEAR) {
  1.4147 +        tmp_best_filter = EIGHTTAP;
  1.4148 +        if (x->source_variance <
  1.4149 +            cpi->sf.disable_filter_search_var_thresh) {
  1.4150 +          tmp_best_filter = EIGHTTAP;
  1.4151 +          vp9_zero(cpi->rd_filter_cache);
  1.4152 +        } else {
  1.4153 +          for (switchable_filter_index = 0;
  1.4154 +               switchable_filter_index < SWITCHABLE_FILTERS;
  1.4155 +               ++switchable_filter_index) {
  1.4156 +            int newbest, rs;
  1.4157 +            int64_t rs_rd;
  1.4158 +            mbmi->interp_filter = switchable_filter_index;
  1.4159 +            vp9_setup_interp_filters(xd, mbmi->interp_filter, &cpi->common);
  1.4160 +
  1.4161 +            tmp_rd = rd_pick_best_mbsegmentation(cpi, x, tile,
  1.4162 +                                                 &mbmi->ref_mvs[ref_frame][0],
  1.4163 +                                                 second_ref,
  1.4164 +                                                 best_yrd,
  1.4165 +                                                 &rate, &rate_y, &distortion,
  1.4166 +                                                 &skippable, &total_sse,
  1.4167 +                                                 (int)this_rd_thresh, seg_mvs,
  1.4168 +                                                 bsi, switchable_filter_index,
  1.4169 +                                                 mi_row, mi_col);
  1.4170 +
  1.4171 +            if (tmp_rd == INT64_MAX)
  1.4172 +              continue;
  1.4173 +            cpi->rd_filter_cache[switchable_filter_index] = tmp_rd;
  1.4174 +            rs = get_switchable_rate(x);
  1.4175 +            rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
  1.4176 +            cpi->rd_filter_cache[SWITCHABLE_FILTERS] =
  1.4177 +                MIN(cpi->rd_filter_cache[SWITCHABLE_FILTERS],
  1.4178 +                    tmp_rd + rs_rd);
  1.4179 +            if (cm->mcomp_filter_type == SWITCHABLE)
  1.4180 +              tmp_rd += rs_rd;
  1.4181 +
  1.4182 +            newbest = (tmp_rd < tmp_best_rd);
  1.4183 +            if (newbest) {
  1.4184 +              tmp_best_filter = mbmi->interp_filter;
  1.4185 +              tmp_best_rd = tmp_rd;
  1.4186 +            }
  1.4187 +            if ((newbest && cm->mcomp_filter_type == SWITCHABLE) ||
  1.4188 +                (mbmi->interp_filter == cm->mcomp_filter_type &&
  1.4189 +                 cm->mcomp_filter_type != SWITCHABLE)) {
  1.4190 +              tmp_best_rdu = tmp_rd;
  1.4191 +              tmp_best_rate = rate;
  1.4192 +              tmp_best_ratey = rate_y;
  1.4193 +              tmp_best_distortion = distortion;
  1.4194 +              tmp_best_sse = total_sse;
  1.4195 +              tmp_best_skippable = skippable;
  1.4196 +              tmp_best_mbmode = *mbmi;
  1.4197 +              for (i = 0; i < 4; i++) {
  1.4198 +                tmp_best_bmodes[i] = xd->mi_8x8[0]->bmi[i];
  1.4199 +                x->zcoeff_blk[TX_4X4][i] = !xd->plane[0].eobs[i];
  1.4200 +              }
  1.4201 +              pred_exists = 1;
  1.4202 +              if (switchable_filter_index == 0 &&
  1.4203 +                  cpi->sf.use_rd_breakout &&
  1.4204 +                  best_rd < INT64_MAX) {
  1.4205 +                if (tmp_best_rdu / 2 > best_rd) {
  1.4206 +                  // skip searching the other filters if the first is
  1.4207 +                  // already substantially larger than the best so far
  1.4208 +                  tmp_best_filter = mbmi->interp_filter;
  1.4209 +                  tmp_best_rdu = INT64_MAX;
  1.4210 +                  break;
  1.4211 +                }
  1.4212 +              }
  1.4213 +            }
  1.4214 +          }  // switchable_filter_index loop
  1.4215 +        }
  1.4216 +      }
  1.4217 +
  1.4218 +      if (tmp_best_rdu == INT64_MAX)
  1.4219 +        continue;
  1.4220 +
  1.4221 +      mbmi->interp_filter = (cm->mcomp_filter_type == SWITCHABLE ?
  1.4222 +                             tmp_best_filter : cm->mcomp_filter_type);
  1.4223 +      vp9_setup_interp_filters(xd, mbmi->interp_filter, &cpi->common);
  1.4224 +      if (!pred_exists) {
  1.4225 +        // Handles the special case when a filter that is not in the
  1.4226 +        // switchable list (bilinear, 6-tap) is indicated at the frame level
  1.4227 +        tmp_rd = rd_pick_best_mbsegmentation(cpi, x, tile,
  1.4228 +                     &mbmi->ref_mvs[ref_frame][0],
  1.4229 +                     second_ref,
  1.4230 +                     best_yrd,
  1.4231 +                     &rate, &rate_y, &distortion,
  1.4232 +                     &skippable, &total_sse,
  1.4233 +                     (int)this_rd_thresh, seg_mvs,
  1.4234 +                     bsi, 0,
  1.4235 +                     mi_row, mi_col);
  1.4236 +        if (tmp_rd == INT64_MAX)
  1.4237 +          continue;
  1.4238 +      } else {
  1.4239 +        if (cpi->common.mcomp_filter_type == SWITCHABLE) {
  1.4240 +          int rs = get_switchable_rate(x);
  1.4241 +          tmp_best_rdu -= RDCOST(x->rdmult, x->rddiv, rs, 0);
  1.4242 +        }
  1.4243 +        tmp_rd = tmp_best_rdu;
  1.4244 +        total_sse = tmp_best_sse;
  1.4245 +        rate = tmp_best_rate;
  1.4246 +        rate_y = tmp_best_ratey;
  1.4247 +        distortion = tmp_best_distortion;
  1.4248 +        skippable = tmp_best_skippable;
  1.4249 +        *mbmi = tmp_best_mbmode;
  1.4250 +        for (i = 0; i < 4; i++)
  1.4251 +          xd->mi_8x8[0]->bmi[i] = tmp_best_bmodes[i];
  1.4252 +      }
  1.4253 +
  1.4254 +      rate2 += rate;
  1.4255 +      distortion2 += distortion;
  1.4256 +
  1.4257 +      if (cpi->common.mcomp_filter_type == SWITCHABLE)
  1.4258 +        rate2 += get_switchable_rate(x);
  1.4259 +
  1.4260 +      if (!mode_excluded) {
  1.4261 +        if (comp_pred)
  1.4262 +          mode_excluded = cpi->common.comp_pred_mode == SINGLE_PREDICTION_ONLY;
  1.4263 +        else
  1.4264 +          mode_excluded = cpi->common.comp_pred_mode == COMP_PREDICTION_ONLY;
  1.4265 +      }
  1.4266 +      compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
  1.4267 +
  1.4268 +      tmp_best_rdu = best_rd -
  1.4269 +          MIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
  1.4270 +              RDCOST(x->rdmult, x->rddiv, 0, total_sse));
  1.4271 +
  1.4272 +      if (tmp_best_rdu > 0) {
  1.4273 +        // If even the 'Y' rd value of split is higher than best so far
  1.4274 +        // then dont bother looking at UV
  1.4275 +        vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col,
  1.4276 +                                        BLOCK_8X8);
  1.4277 +        super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
  1.4278 +                         &uv_sse, BLOCK_8X8, tmp_best_rdu);
  1.4279 +        if (rate_uv == INT_MAX)
  1.4280 +          continue;
  1.4281 +        rate2 += rate_uv;
  1.4282 +        distortion2 += distortion_uv;
  1.4283 +        skippable = skippable && uv_skippable;
  1.4284 +        total_sse += uv_sse;
  1.4285 +
  1.4286 +        tx_cache[ONLY_4X4] = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
  1.4287 +        for (i = 0; i < TX_MODES; ++i)
  1.4288 +          tx_cache[i] = tx_cache[ONLY_4X4];
  1.4289 +      }
  1.4290 +    }
  1.4291 +
  1.4292 +    if (cpi->common.comp_pred_mode == HYBRID_PREDICTION) {
  1.4293 +      rate2 += compmode_cost;
  1.4294 +    }
  1.4295 +
  1.4296 +    // Estimate the reference frame signaling cost and add it
  1.4297 +    // to the rolling cost variable.
  1.4298 +    if (second_ref_frame > INTRA_FRAME) {
  1.4299 +      rate2 += ref_costs_comp[ref_frame];
  1.4300 +    } else {
  1.4301 +      rate2 += ref_costs_single[ref_frame];
  1.4302 +    }
  1.4303 +
  1.4304 +    if (!disable_skip) {
  1.4305 +      // Test for the condition where skip block will be activated
  1.4306 +      // because there are no non zero coefficients and make any
  1.4307 +      // necessary adjustment for rate. Ignore if skip is coded at
  1.4308 +      // segment level as the cost wont have been added in.
  1.4309 +      // Is Mb level skip allowed (i.e. not coded at segment level).
  1.4310 +      const int mb_skip_allowed = !vp9_segfeature_active(seg, segment_id,
  1.4311 +                                                         SEG_LVL_SKIP);
  1.4312 +
  1.4313 +      if (mb_skip_allowed && ref_frame != INTRA_FRAME && !xd->lossless) {
  1.4314 +        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv, distortion2) <
  1.4315 +            RDCOST(x->rdmult, x->rddiv, 0, total_sse)) {
  1.4316 +          // Add in the cost of the no skip flag.
  1.4317 +          int prob_skip_cost = vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd),
  1.4318 +                                            0);
  1.4319 +          rate2 += prob_skip_cost;
  1.4320 +        } else {
  1.4321 +          // FIXME(rbultje) make this work for splitmv also
  1.4322 +          int prob_skip_cost = vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd),
  1.4323 +                                            1);
  1.4324 +          rate2 += prob_skip_cost;
  1.4325 +          distortion2 = total_sse;
  1.4326 +          assert(total_sse >= 0);
  1.4327 +          rate2 -= (rate_y + rate_uv);
  1.4328 +          rate_y = 0;
  1.4329 +          rate_uv = 0;
  1.4330 +          this_skip2 = 1;
  1.4331 +        }
  1.4332 +      } else if (mb_skip_allowed) {
  1.4333 +        // Add in the cost of the no skip flag.
  1.4334 +        int prob_skip_cost = vp9_cost_bit(vp9_get_pred_prob_mbskip(cm, xd),
  1.4335 +                                          0);
  1.4336 +        rate2 += prob_skip_cost;
  1.4337 +      }
  1.4338 +
  1.4339 +      // Calculate the final RD estimate for this mode.
  1.4340 +      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
  1.4341 +    }
  1.4342 +
  1.4343 +    // Keep record of best inter rd with single reference
  1.4344 +    if (xd->mi_8x8[0]->mbmi.ref_frame[0] > INTRA_FRAME &&
  1.4345 +        xd->mi_8x8[0]->mbmi.ref_frame[1] == NONE &&
  1.4346 +        !mode_excluded &&
  1.4347 +        this_rd < best_inter_rd) {
  1.4348 +      best_inter_rd = this_rd;
  1.4349 +      best_inter_ref_frame = ref_frame;
  1.4350 +    }
  1.4351 +
  1.4352 +    if (!disable_skip && ref_frame == INTRA_FRAME) {
  1.4353 +      for (i = 0; i < NB_PREDICTION_TYPES; ++i)
  1.4354 +        best_pred_rd[i] = MIN(best_pred_rd[i], this_rd);
  1.4355 +      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
  1.4356 +        best_filter_rd[i] = MIN(best_filter_rd[i], this_rd);
  1.4357 +    }
  1.4358 +
  1.4359 +    // Did this mode help.. i.e. is it the new best mode
  1.4360 +    if (this_rd < best_rd || x->skip) {
  1.4361 +      if (!mode_excluded) {
  1.4362 +        int max_plane = MAX_MB_PLANE;
  1.4363 +        // Note index of best mode so far
  1.4364 +        best_mode_index = mode_index;
  1.4365 +
  1.4366 +        if (ref_frame == INTRA_FRAME) {
  1.4367 +          /* required for left and above block mv */
  1.4368 +          mbmi->mv[0].as_int = 0;
  1.4369 +          max_plane = 1;
  1.4370 +        }
  1.4371 +
  1.4372 +        *returnrate = rate2;
  1.4373 +        *returndistortion = distortion2;
  1.4374 +        best_rd = this_rd;
  1.4375 +        best_yrd = best_rd -
  1.4376 +                   RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
  1.4377 +        best_mbmode = *mbmi;
  1.4378 +        best_skip2 = this_skip2;
  1.4379 +        if (!x->select_txfm_size)
  1.4380 +          swap_block_ptr(x, ctx, max_plane);
  1.4381 +        vpx_memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mbmi->tx_size],
  1.4382 +                   sizeof(uint8_t) * ctx->num_4x4_blk);
  1.4383 +
  1.4384 +        for (i = 0; i < 4; i++)
  1.4385 +          best_bmodes[i] = xd->mi_8x8[0]->bmi[i];
  1.4386 +
  1.4387 +        // TODO(debargha): enhance this test with a better distortion prediction
  1.4388 +        // based on qp, activity mask and history
  1.4389 +        if ((cpi->sf.mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
  1.4390 +            (mode_index > MIN_EARLY_TERM_INDEX)) {
  1.4391 +          const int qstep = xd->plane[0].dequant[1];
  1.4392 +          // TODO(debargha): Enhance this by specializing for each mode_index
  1.4393 +          int scale = 4;
  1.4394 +          if (x->source_variance < UINT_MAX) {
  1.4395 +            const int var_adjust = (x->source_variance < 16);
  1.4396 +            scale -= var_adjust;
  1.4397 +          }
  1.4398 +          if (ref_frame > INTRA_FRAME &&
  1.4399 +              distortion2 * scale < qstep * qstep) {
  1.4400 +            early_term = 1;
  1.4401 +          }
  1.4402 +        }
  1.4403 +      }
  1.4404 +    }
  1.4405 +
  1.4406 +    /* keep record of best compound/single-only prediction */
  1.4407 +    if (!disable_skip && ref_frame != INTRA_FRAME) {
  1.4408 +      int single_rd, hybrid_rd, single_rate, hybrid_rate;
  1.4409 +
  1.4410 +      if (cpi->common.comp_pred_mode == HYBRID_PREDICTION) {
  1.4411 +        single_rate = rate2 - compmode_cost;
  1.4412 +        hybrid_rate = rate2;
  1.4413 +      } else {
  1.4414 +        single_rate = rate2;
  1.4415 +        hybrid_rate = rate2 + compmode_cost;
  1.4416 +      }
  1.4417 +
  1.4418 +      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
  1.4419 +      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
  1.4420 +
  1.4421 +      if (second_ref_frame <= INTRA_FRAME &&
  1.4422 +          single_rd < best_pred_rd[SINGLE_PREDICTION_ONLY]) {
  1.4423 +        best_pred_rd[SINGLE_PREDICTION_ONLY] = single_rd;
  1.4424 +      } else if (second_ref_frame > INTRA_FRAME &&
  1.4425 +                 single_rd < best_pred_rd[COMP_PREDICTION_ONLY]) {
  1.4426 +        best_pred_rd[COMP_PREDICTION_ONLY] = single_rd;
  1.4427 +      }
  1.4428 +      if (hybrid_rd < best_pred_rd[HYBRID_PREDICTION])
  1.4429 +        best_pred_rd[HYBRID_PREDICTION] = hybrid_rd;
  1.4430 +    }
  1.4431 +
  1.4432 +    /* keep record of best filter type */
  1.4433 +    if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
  1.4434 +        cm->mcomp_filter_type != BILINEAR) {
  1.4435 +      int64_t ref = cpi->rd_filter_cache[cm->mcomp_filter_type == SWITCHABLE ?
  1.4436 +                              SWITCHABLE_FILTERS : cm->mcomp_filter_type];
  1.4437 +      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
  1.4438 +        int64_t adj_rd;
  1.4439 +        // In cases of poor prediction, filter_cache[] can contain really big
  1.4440 +        // values, which actually are bigger than this_rd itself. This can
  1.4441 +        // cause negative best_filter_rd[] values, which is obviously silly.
  1.4442 +        // Therefore, if filter_cache < ref, we do an adjusted calculation.
  1.4443 +        if (cpi->rd_filter_cache[i] >= ref)
  1.4444 +          adj_rd = this_rd + cpi->rd_filter_cache[i] - ref;
  1.4445 +        else  // FIXME(rbultje) do this for comppred also
  1.4446 +          adj_rd = this_rd - (ref - cpi->rd_filter_cache[i]) * this_rd / ref;
  1.4447 +        best_filter_rd[i] = MIN(best_filter_rd[i], adj_rd);
  1.4448 +      }
  1.4449 +    }
  1.4450 +
  1.4451 +    /* keep record of best txfm size */
  1.4452 +    if (bsize < BLOCK_32X32) {
  1.4453 +      if (bsize < BLOCK_16X16) {
  1.4454 +        tx_cache[ALLOW_8X8] = tx_cache[ONLY_4X4];
  1.4455 +        tx_cache[ALLOW_16X16] = tx_cache[ALLOW_8X8];
  1.4456 +      }
  1.4457 +      tx_cache[ALLOW_32X32] = tx_cache[ALLOW_16X16];
  1.4458 +    }
  1.4459 +    if (!mode_excluded && this_rd != INT64_MAX) {
  1.4460 +      for (i = 0; i < TX_MODES && tx_cache[i] < INT64_MAX; i++) {
  1.4461 +        int64_t adj_rd = INT64_MAX;
  1.4462 +        if (ref_frame > INTRA_FRAME)
  1.4463 +          adj_rd = this_rd + tx_cache[i] - tx_cache[cm->tx_mode];
  1.4464 +        else
  1.4465 +          adj_rd = this_rd;
  1.4466 +
  1.4467 +        if (adj_rd < best_tx_rd[i])
  1.4468 +          best_tx_rd[i] = adj_rd;
  1.4469 +      }
  1.4470 +    }
  1.4471 +
  1.4472 +    if (early_term)
  1.4473 +      break;
  1.4474 +
  1.4475 +    if (x->skip && !comp_pred)
  1.4476 +      break;
  1.4477 +  }
  1.4478 +
  1.4479 +  if (best_rd >= best_rd_so_far)
  1.4480 +    return INT64_MAX;
  1.4481 +
  1.4482 +  // If we used an estimate for the uv intra rd in the loop above...
  1.4483 +  if (cpi->sf.use_uv_intra_rd_estimate) {
  1.4484 +    // Do Intra UV best rd mode selection if best mode choice above was intra.
  1.4485 +    if (vp9_ref_order[best_mode_index].ref_frame == INTRA_FRAME) {
  1.4486 +      TX_SIZE uv_tx_size = get_uv_tx_size(mbmi);
  1.4487 +      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
  1.4488 +                              &rate_uv_tokenonly[uv_tx_size],
  1.4489 +                              &dist_uv[uv_tx_size],
  1.4490 +                              &skip_uv[uv_tx_size],
  1.4491 +                              BLOCK_8X8);
  1.4492 +    }
  1.4493 +  }
  1.4494 +
  1.4495 +  // If we are using reference masking and the set mask flag is set then
  1.4496 +  // create the reference frame mask.
  1.4497 +  if (cpi->sf.reference_masking && cpi->set_ref_frame_mask)
  1.4498 +    cpi->ref_frame_mask = ~(1 << vp9_ref_order[best_mode_index].ref_frame);
  1.4499 +
  1.4500 +  if (best_rd == INT64_MAX && bsize < BLOCK_8X8) {
  1.4501 +    *returnrate = INT_MAX;
  1.4502 +    *returndistortion = INT_MAX;
  1.4503 +    return best_rd;
  1.4504 +  }
  1.4505 +
  1.4506 +  assert((cm->mcomp_filter_type == SWITCHABLE) ||
  1.4507 +         (cm->mcomp_filter_type == best_mbmode.interp_filter) ||
  1.4508 +         (best_mbmode.ref_frame[0] == INTRA_FRAME));
  1.4509 +
  1.4510 +  // Updating rd_thresh_freq_fact[] here means that the different
  1.4511 +  // partition/block sizes are handled independently based on the best
  1.4512 +  // choice for the current partition. It may well be better to keep a scaled
  1.4513 +  // best rd so far value and update rd_thresh_freq_fact based on the mode/size
  1.4514 +  // combination that wins out.
  1.4515 +  if (cpi->sf.adaptive_rd_thresh) {
  1.4516 +    for (mode_index = 0; mode_index < MAX_REFS; ++mode_index) {
  1.4517 +      if (mode_index == best_mode_index) {
  1.4518 +        cpi->rd_thresh_freq_sub8x8[bsize][mode_index] -=
  1.4519 +          (cpi->rd_thresh_freq_sub8x8[bsize][mode_index] >> 3);
  1.4520 +      } else {
  1.4521 +        cpi->rd_thresh_freq_sub8x8[bsize][mode_index] += RD_THRESH_INC;
  1.4522 +        if (cpi->rd_thresh_freq_sub8x8[bsize][mode_index] >
  1.4523 +            (cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT)) {
  1.4524 +          cpi->rd_thresh_freq_sub8x8[bsize][mode_index] =
  1.4525 +            cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT;
  1.4526 +        }
  1.4527 +      }
  1.4528 +    }
  1.4529 +  }
  1.4530 +
  1.4531 +  // macroblock modes
  1.4532 +  *mbmi = best_mbmode;
  1.4533 +  x->skip |= best_skip2;
  1.4534 +  if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
  1.4535 +    for (i = 0; i < 4; i++)
  1.4536 +      xd->mi_8x8[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
  1.4537 +  } else {
  1.4538 +    for (i = 0; i < 4; ++i)
  1.4539 +      vpx_memcpy(&xd->mi_8x8[0]->bmi[i], &best_bmodes[i], sizeof(b_mode_info));
  1.4540 +
  1.4541 +    mbmi->mv[0].as_int = xd->mi_8x8[0]->bmi[3].as_mv[0].as_int;
  1.4542 +    mbmi->mv[1].as_int = xd->mi_8x8[0]->bmi[3].as_mv[1].as_int;
  1.4543 +  }
  1.4544 +
  1.4545 +  for (i = 0; i < NB_PREDICTION_TYPES; ++i) {
  1.4546 +    if (best_pred_rd[i] == INT64_MAX)
  1.4547 +      best_pred_diff[i] = INT_MIN;
  1.4548 +    else
  1.4549 +      best_pred_diff[i] = best_rd - best_pred_rd[i];
  1.4550 +  }
  1.4551 +
  1.4552 +  if (!x->skip) {
  1.4553 +    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
  1.4554 +      if (best_filter_rd[i] == INT64_MAX)
  1.4555 +        best_filter_diff[i] = 0;
  1.4556 +      else
  1.4557 +        best_filter_diff[i] = best_rd - best_filter_rd[i];
  1.4558 +    }
  1.4559 +    if (cm->mcomp_filter_type == SWITCHABLE)
  1.4560 +      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
  1.4561 +  } else {
  1.4562 +    vp9_zero(best_filter_diff);
  1.4563 +  }
  1.4564 +
  1.4565 +  if (!x->skip) {
  1.4566 +    for (i = 0; i < TX_MODES; i++) {
  1.4567 +      if (best_tx_rd[i] == INT64_MAX)
  1.4568 +        best_tx_diff[i] = 0;
  1.4569 +      else
  1.4570 +        best_tx_diff[i] = best_rd - best_tx_rd[i];
  1.4571 +    }
  1.4572 +  } else {
  1.4573 +    vp9_zero(best_tx_diff);
  1.4574 +  }
  1.4575 +
  1.4576 +  set_scale_factors(xd, mbmi->ref_frame[0], mbmi->ref_frame[1],
  1.4577 +                    scale_factor);
  1.4578 +  store_coding_context(x, ctx, best_mode_index,
  1.4579 +                       &mbmi->ref_mvs[mbmi->ref_frame[0]][0],
  1.4580 +                       &mbmi->ref_mvs[mbmi->ref_frame[1] < 0 ? 0 :
  1.4581 +                                      mbmi->ref_frame[1]][0],
  1.4582 +                       best_pred_diff, best_tx_diff, best_filter_diff);
  1.4583 +
  1.4584 +  return best_rd;
  1.4585 +}

mercurial