1/*
2 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include <assert.h>
12#include <math.h>
13
14#include "./vp9_rtcd.h"
15#include "./vpx_dsp_rtcd.h"
16
17#include "vpx_dsp/vpx_dsp_common.h"
18#include "vpx_mem/vpx_mem.h"
19#include "vpx_ports/mem.h"
20#include "vpx_ports/system_state.h"
21
22#include "vp9/common/vp9_common.h"
23#include "vp9/common/vp9_entropy.h"
24#include "vp9/common/vp9_entropymode.h"
25#include "vp9/common/vp9_idct.h"
26#include "vp9/common/vp9_mvref_common.h"
27#include "vp9/common/vp9_pred_common.h"
28#include "vp9/common/vp9_quant_common.h"
29#include "vp9/common/vp9_reconinter.h"
30#include "vp9/common/vp9_reconintra.h"
31#include "vp9/common/vp9_scan.h"
32#include "vp9/common/vp9_seg_common.h"
33
34#include "vp9/encoder/vp9_cost.h"
35#include "vp9/encoder/vp9_encodemb.h"
36#include "vp9/encoder/vp9_encodemv.h"
37#include "vp9/encoder/vp9_encoder.h"
38#include "vp9/encoder/vp9_mcomp.h"
39#include "vp9/encoder/vp9_quantize.h"
40#include "vp9/encoder/vp9_ratectrl.h"
41#include "vp9/encoder/vp9_rd.h"
42#include "vp9/encoder/vp9_rdopt.h"
43#include "vp9/encoder/vp9_aq_variance.h"
44
45#define LAST_FRAME_MODE_MASK \
46  ((1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
47#define GOLDEN_FRAME_MODE_MASK \
48  ((1 << LAST_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
49#define ALT_REF_MODE_MASK \
50  ((1 << LAST_FRAME) | (1 << GOLDEN_FRAME) | (1 << INTRA_FRAME))
51
52#define SECOND_REF_FRAME_MASK ((1 << ALTREF_FRAME) | 0x01)
53
54#define MIN_EARLY_TERM_INDEX 3
55#define NEW_MV_DISCOUNT_FACTOR 8
56
57typedef struct {
58  PREDICTION_MODE mode;
59  MV_REFERENCE_FRAME ref_frame[2];
60} MODE_DEFINITION;
61
62typedef struct { MV_REFERENCE_FRAME ref_frame[2]; } REF_DEFINITION;
63
64struct rdcost_block_args {
65  const VP9_COMP *cpi;
66  MACROBLOCK *x;
67  ENTROPY_CONTEXT t_above[16];
68  ENTROPY_CONTEXT t_left[16];
69  int this_rate;
70  int64_t this_dist;
71  int64_t this_sse;
72  int64_t this_rd;
73  int64_t best_rd;
74  int exit_early;
75  int use_fast_coef_costing;
76  const scan_order *so;
77  uint8_t skippable;
78};
79
80#define LAST_NEW_MV_INDEX 6
81static const MODE_DEFINITION vp9_mode_order[MAX_MODES] = {
82  { NEARESTMV, { LAST_FRAME, NONE } },
83  { NEARESTMV, { ALTREF_FRAME, NONE } },
84  { NEARESTMV, { GOLDEN_FRAME, NONE } },
85
86  { DC_PRED, { INTRA_FRAME, NONE } },
87
88  { NEWMV, { LAST_FRAME, NONE } },
89  { NEWMV, { ALTREF_FRAME, NONE } },
90  { NEWMV, { GOLDEN_FRAME, NONE } },
91
92  { NEARMV, { LAST_FRAME, NONE } },
93  { NEARMV, { ALTREF_FRAME, NONE } },
94  { NEARMV, { GOLDEN_FRAME, NONE } },
95
96  { ZEROMV, { LAST_FRAME, NONE } },
97  { ZEROMV, { GOLDEN_FRAME, NONE } },
98  { ZEROMV, { ALTREF_FRAME, NONE } },
99
100  { NEARESTMV, { LAST_FRAME, ALTREF_FRAME } },
101  { NEARESTMV, { GOLDEN_FRAME, ALTREF_FRAME } },
102
103  { TM_PRED, { INTRA_FRAME, NONE } },
104
105  { NEARMV, { LAST_FRAME, ALTREF_FRAME } },
106  { NEWMV, { LAST_FRAME, ALTREF_FRAME } },
107  { NEARMV, { GOLDEN_FRAME, ALTREF_FRAME } },
108  { NEWMV, { GOLDEN_FRAME, ALTREF_FRAME } },
109
110  { ZEROMV, { LAST_FRAME, ALTREF_FRAME } },
111  { ZEROMV, { GOLDEN_FRAME, ALTREF_FRAME } },
112
113  { H_PRED, { INTRA_FRAME, NONE } },
114  { V_PRED, { INTRA_FRAME, NONE } },
115  { D135_PRED, { INTRA_FRAME, NONE } },
116  { D207_PRED, { INTRA_FRAME, NONE } },
117  { D153_PRED, { INTRA_FRAME, NONE } },
118  { D63_PRED, { INTRA_FRAME, NONE } },
119  { D117_PRED, { INTRA_FRAME, NONE } },
120  { D45_PRED, { INTRA_FRAME, NONE } },
121};
122
123static const REF_DEFINITION vp9_ref_order[MAX_REFS] = {
124  { { LAST_FRAME, NONE } },           { { GOLDEN_FRAME, NONE } },
125  { { ALTREF_FRAME, NONE } },         { { LAST_FRAME, ALTREF_FRAME } },
126  { { GOLDEN_FRAME, ALTREF_FRAME } }, { { INTRA_FRAME, NONE } },
127};
128
129static void swap_block_ptr(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int m, int n,
130                           int min_plane, int max_plane) {
131  int i;
132
133  for (i = min_plane; i < max_plane; ++i) {
134    struct macroblock_plane *const p = &x->plane[i];
135    struct macroblockd_plane *const pd = &x->e_mbd.plane[i];
136
137    p->coeff = ctx->coeff_pbuf[i][m];
138    p->qcoeff = ctx->qcoeff_pbuf[i][m];
139    pd->dqcoeff = ctx->dqcoeff_pbuf[i][m];
140    p->eobs = ctx->eobs_pbuf[i][m];
141
142    ctx->coeff_pbuf[i][m] = ctx->coeff_pbuf[i][n];
143    ctx->qcoeff_pbuf[i][m] = ctx->qcoeff_pbuf[i][n];
144    ctx->dqcoeff_pbuf[i][m] = ctx->dqcoeff_pbuf[i][n];
145    ctx->eobs_pbuf[i][m] = ctx->eobs_pbuf[i][n];
146
147    ctx->coeff_pbuf[i][n] = p->coeff;
148    ctx->qcoeff_pbuf[i][n] = p->qcoeff;
149    ctx->dqcoeff_pbuf[i][n] = pd->dqcoeff;
150    ctx->eobs_pbuf[i][n] = p->eobs;
151  }
152}
153
154static void model_rd_for_sb(VP9_COMP *cpi, BLOCK_SIZE bsize, MACROBLOCK *x,
155                            MACROBLOCKD *xd, int *out_rate_sum,
156                            int64_t *out_dist_sum, int *skip_txfm_sb,
157                            int64_t *skip_sse_sb) {
158  // Note our transform coeffs are 8 times an orthogonal transform.
159  // Hence quantizer step is also 8 times. To get effective quantizer
160  // we need to divide by 8 before sending to modeling function.
161  int i;
162  int64_t rate_sum = 0;
163  int64_t dist_sum = 0;
164  const int ref = xd->mi[0]->ref_frame[0];
165  unsigned int sse;
166  unsigned int var = 0;
167  int64_t total_sse = 0;
168  int skip_flag = 1;
169  const int shift = 6;
170  int64_t dist;
171  const int dequant_shift =
172#if CONFIG_VP9_HIGHBITDEPTH
173      (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd - 5 :
174#endif  // CONFIG_VP9_HIGHBITDEPTH
175                                                    3;
176  unsigned int qstep_vec[MAX_MB_PLANE];
177  unsigned int nlog2_vec[MAX_MB_PLANE];
178  unsigned int sum_sse_vec[MAX_MB_PLANE];
179  int any_zero_sum_sse = 0;
180
181  x->pred_sse[ref] = 0;
182
183  for (i = 0; i < MAX_MB_PLANE; ++i) {
184    struct macroblock_plane *const p = &x->plane[i];
185    struct macroblockd_plane *const pd = &xd->plane[i];
186    const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
187    const TX_SIZE max_tx_size = max_txsize_lookup[bs];
188    const BLOCK_SIZE unit_size = txsize_to_bsize[max_tx_size];
189    const int64_t dc_thr = p->quant_thred[0] >> shift;
190    const int64_t ac_thr = p->quant_thred[1] >> shift;
191    unsigned int sum_sse = 0;
192    // The low thresholds are used to measure if the prediction errors are
193    // low enough so that we can skip the mode search.
194    const int64_t low_dc_thr = VPXMIN(50, dc_thr >> 2);
195    const int64_t low_ac_thr = VPXMIN(80, ac_thr >> 2);
196    int bw = 1 << (b_width_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
197    int bh = 1 << (b_height_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
198    int idx, idy;
199    int lw = b_width_log2_lookup[unit_size] + 2;
200    int lh = b_height_log2_lookup[unit_size] + 2;
201
202    for (idy = 0; idy < bh; ++idy) {
203      for (idx = 0; idx < bw; ++idx) {
204        uint8_t *src = p->src.buf + (idy * p->src.stride << lh) + (idx << lw);
205        uint8_t *dst = pd->dst.buf + (idy * pd->dst.stride << lh) + (idx << lh);
206        int block_idx = (idy << 1) + idx;
207        int low_err_skip = 0;
208
209        var = cpi->fn_ptr[unit_size].vf(src, p->src.stride, dst, pd->dst.stride,
210                                        &sse);
211        x->bsse[(i << 2) + block_idx] = sse;
212        sum_sse += sse;
213
214        x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_NONE;
215        if (!x->select_tx_size) {
216          // Check if all ac coefficients can be quantized to zero.
217          if (var < ac_thr || var == 0) {
218            x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_ONLY;
219
220            // Check if dc coefficient can be quantized to zero.
221            if (sse - var < dc_thr || sse == var) {
222              x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_DC;
223
224              if (!sse || (var < low_ac_thr && sse - var < low_dc_thr))
225                low_err_skip = 1;
226            }
227          }
228        }
229
230        if (skip_flag && !low_err_skip) skip_flag = 0;
231
232        if (i == 0) x->pred_sse[ref] += sse;
233      }
234    }
235
236    total_sse += sum_sse;
237    sum_sse_vec[i] = sum_sse;
238    any_zero_sum_sse = any_zero_sum_sse || (sum_sse == 0);
239    qstep_vec[i] = pd->dequant[1] >> dequant_shift;
240    nlog2_vec[i] = num_pels_log2_lookup[bs];
241  }
242
243  // Fast approximate the modelling function.
244  if (cpi->sf.simple_model_rd_from_var) {
245    for (i = 0; i < MAX_MB_PLANE; ++i) {
246      int64_t rate;
247      const int64_t square_error = sum_sse_vec[i];
248      int quantizer = qstep_vec[i];
249
250      if (quantizer < 120)
251        rate = (square_error * (280 - quantizer)) >> (16 - VP9_PROB_COST_SHIFT);
252      else
253        rate = 0;
254      dist = (square_error * quantizer) >> 8;
255      rate_sum += rate;
256      dist_sum += dist;
257    }
258  } else {
259    if (any_zero_sum_sse) {
260      for (i = 0; i < MAX_MB_PLANE; ++i) {
261        int rate;
262        vp9_model_rd_from_var_lapndz(sum_sse_vec[i], nlog2_vec[i], qstep_vec[i],
263                                     &rate, &dist);
264        rate_sum += rate;
265        dist_sum += dist;
266      }
267    } else {
268      vp9_model_rd_from_var_lapndz_vec(sum_sse_vec, nlog2_vec, qstep_vec,
269                                       &rate_sum, &dist_sum);
270    }
271  }
272
273  *skip_txfm_sb = skip_flag;
274  *skip_sse_sb = total_sse << 4;
275  *out_rate_sum = (int)rate_sum;
276  *out_dist_sum = dist_sum << 4;
277}
278
279#if CONFIG_VP9_HIGHBITDEPTH
280int64_t vp9_highbd_block_error_c(const tran_low_t *coeff,
281                                 const tran_low_t *dqcoeff, intptr_t block_size,
282                                 int64_t *ssz, int bd) {
283  int i;
284  int64_t error = 0, sqcoeff = 0;
285  int shift = 2 * (bd - 8);
286  int rounding = shift > 0 ? 1 << (shift - 1) : 0;
287
288  for (i = 0; i < block_size; i++) {
289    const int64_t diff = coeff[i] - dqcoeff[i];
290    error += diff * diff;
291    sqcoeff += (int64_t)coeff[i] * (int64_t)coeff[i];
292  }
293  assert(error >= 0 && sqcoeff >= 0);
294  error = (error + rounding) >> shift;
295  sqcoeff = (sqcoeff + rounding) >> shift;
296
297  *ssz = sqcoeff;
298  return error;
299}
300
301static int64_t vp9_highbd_block_error_dispatch(const tran_low_t *coeff,
302                                               const tran_low_t *dqcoeff,
303                                               intptr_t block_size,
304                                               int64_t *ssz, int bd) {
305  if (bd == 8) {
306    return vp9_block_error(coeff, dqcoeff, block_size, ssz);
307  } else {
308    return vp9_highbd_block_error(coeff, dqcoeff, block_size, ssz, bd);
309  }
310}
311#endif  // CONFIG_VP9_HIGHBITDEPTH
312
313int64_t vp9_block_error_c(const tran_low_t *coeff, const tran_low_t *dqcoeff,
314                          intptr_t block_size, int64_t *ssz) {
315  int i;
316  int64_t error = 0, sqcoeff = 0;
317
318  for (i = 0; i < block_size; i++) {
319    const int diff = coeff[i] - dqcoeff[i];
320    error += diff * diff;
321    sqcoeff += coeff[i] * coeff[i];
322  }
323
324  *ssz = sqcoeff;
325  return error;
326}
327
328int64_t vp9_block_error_fp_c(const tran_low_t *coeff, const tran_low_t *dqcoeff,
329                             int block_size) {
330  int i;
331  int64_t error = 0;
332
333  for (i = 0; i < block_size; i++) {
334    const int diff = coeff[i] - dqcoeff[i];
335    error += diff * diff;
336  }
337
338  return error;
339}
340
341/* The trailing '0' is a terminator which is used inside cost_coeffs() to
342 * decide whether to include cost of a trailing EOB node or not (i.e. we
343 * can skip this if the last coefficient in this transform block, e.g. the
344 * 16th coefficient in a 4x4 block or the 64th coefficient in a 8x8 block,
345 * were non-zero). */
346static const int16_t band_counts[TX_SIZES][8] = {
347  { 1, 2, 3, 4, 3, 16 - 13, 0 },
348  { 1, 2, 3, 4, 11, 64 - 21, 0 },
349  { 1, 2, 3, 4, 11, 256 - 21, 0 },
350  { 1, 2, 3, 4, 11, 1024 - 21, 0 },
351};
352static int cost_coeffs(MACROBLOCK *x, int plane, int block, TX_SIZE tx_size,
353                       int pt, const int16_t *scan, const int16_t *nb,
354                       int use_fast_coef_costing) {
355  MACROBLOCKD *const xd = &x->e_mbd;
356  MODE_INFO *mi = xd->mi[0];
357  const struct macroblock_plane *p = &x->plane[plane];
358  const PLANE_TYPE type = get_plane_type(plane);
359  const int16_t *band_count = &band_counts[tx_size][1];
360  const int eob = p->eobs[block];
361  const tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
362  unsigned int(*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
363      x->token_costs[tx_size][type][is_inter_block(mi)];
364  uint8_t token_cache[32 * 32];
365  int cost;
366#if CONFIG_VP9_HIGHBITDEPTH
367  const uint16_t *cat6_high_cost = vp9_get_high_cost_table(xd->bd);
368#else
369  const uint16_t *cat6_high_cost = vp9_get_high_cost_table(8);
370#endif
371
372  // Check for consistency of tx_size with mode info
373  assert(type == PLANE_TYPE_Y
374             ? mi->tx_size == tx_size
375             : get_uv_tx_size(mi, &xd->plane[plane]) == tx_size);
376
377  if (eob == 0) {
378    // single eob token
379    cost = token_costs[0][0][pt][EOB_TOKEN];
380  } else {
381    if (use_fast_coef_costing) {
382      int band_left = *band_count++;
383      int c;
384
385      // dc token
386      int v = qcoeff[0];
387      int16_t prev_t;
388      cost = vp9_get_token_cost(v, &prev_t, cat6_high_cost);
389      cost += (*token_costs)[0][pt][prev_t];
390
391      token_cache[0] = vp9_pt_energy_class[prev_t];
392      ++token_costs;
393
394      // ac tokens
395      for (c = 1; c < eob; c++) {
396        const int rc = scan[c];
397        int16_t t;
398
399        v = qcoeff[rc];
400        cost += vp9_get_token_cost(v, &t, cat6_high_cost);
401        cost += (*token_costs)[!prev_t][!prev_t][t];
402        prev_t = t;
403        if (!--band_left) {
404          band_left = *band_count++;
405          ++token_costs;
406        }
407      }
408
409      // eob token
410      if (band_left) cost += (*token_costs)[0][!prev_t][EOB_TOKEN];
411
412    } else {  // !use_fast_coef_costing
413      int band_left = *band_count++;
414      int c;
415
416      // dc token
417      int v = qcoeff[0];
418      int16_t tok;
419      unsigned int(*tok_cost_ptr)[COEFF_CONTEXTS][ENTROPY_TOKENS];
420      cost = vp9_get_token_cost(v, &tok, cat6_high_cost);
421      cost += (*token_costs)[0][pt][tok];
422
423      token_cache[0] = vp9_pt_energy_class[tok];
424      ++token_costs;
425
426      tok_cost_ptr = &((*token_costs)[!tok]);
427
428      // ac tokens
429      for (c = 1; c < eob; c++) {
430        const int rc = scan[c];
431
432        v = qcoeff[rc];
433        cost += vp9_get_token_cost(v, &tok, cat6_high_cost);
434        pt = get_coef_context(nb, token_cache, c);
435        cost += (*tok_cost_ptr)[pt][tok];
436        token_cache[rc] = vp9_pt_energy_class[tok];
437        if (!--band_left) {
438          band_left = *band_count++;
439          ++token_costs;
440        }
441        tok_cost_ptr = &((*token_costs)[!tok]);
442      }
443
444      // eob token
445      if (band_left) {
446        pt = get_coef_context(nb, token_cache, c);
447        cost += (*token_costs)[0][pt][EOB_TOKEN];
448      }
449    }
450  }
451
452  return cost;
453}
454
455static INLINE int num_4x4_to_edge(int plane_4x4_dim, int mb_to_edge_dim,
456                                  int subsampling_dim, int blk_dim) {
457  return plane_4x4_dim + (mb_to_edge_dim >> (5 + subsampling_dim)) - blk_dim;
458}
459
460// Compute the pixel domain sum square error on all visible 4x4s in the
461// transform block.
462static unsigned pixel_sse(const VP9_COMP *const cpi, const MACROBLOCKD *xd,
463                          const struct macroblockd_plane *const pd,
464                          const uint8_t *src, const int src_stride,
465                          const uint8_t *dst, const int dst_stride, int blk_row,
466                          int blk_col, const BLOCK_SIZE plane_bsize,
467                          const BLOCK_SIZE tx_bsize) {
468  unsigned int sse = 0;
469  const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
470  const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
471  const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
472  const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
473  int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
474                                            pd->subsampling_x, blk_col);
475  int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
476                                             pd->subsampling_y, blk_row);
477  if (tx_bsize == BLOCK_4X4 ||
478      (b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
479    cpi->fn_ptr[tx_bsize].vf(src, src_stride, dst, dst_stride, &sse);
480  } else {
481    const vpx_variance_fn_t vf_4x4 = cpi->fn_ptr[BLOCK_4X4].vf;
482    int r, c;
483    unsigned this_sse = 0;
484    int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
485    int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
486    sse = 0;
487    // if we are in the unrestricted motion border.
488    for (r = 0; r < max_r; ++r) {
489      // Skip visiting the sub blocks that are wholly within the UMV.
490      for (c = 0; c < max_c; ++c) {
491        vf_4x4(src + r * src_stride * 4 + c * 4, src_stride,
492               dst + r * dst_stride * 4 + c * 4, dst_stride, &this_sse);
493        sse += this_sse;
494      }
495    }
496  }
497  return sse;
498}
499
500// Compute the squares sum squares on all visible 4x4s in the transform block.
501static int64_t sum_squares_visible(const MACROBLOCKD *xd,
502                                   const struct macroblockd_plane *const pd,
503                                   const int16_t *diff, const int diff_stride,
504                                   int blk_row, int blk_col,
505                                   const BLOCK_SIZE plane_bsize,
506                                   const BLOCK_SIZE tx_bsize) {
507  int64_t sse;
508  const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
509  const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
510  const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
511  const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
512  int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
513                                            pd->subsampling_x, blk_col);
514  int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
515                                             pd->subsampling_y, blk_row);
516  if (tx_bsize == BLOCK_4X4 ||
517      (b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
518    assert(tx_4x4_w == tx_4x4_h);
519    sse = (int64_t)vpx_sum_squares_2d_i16(diff, diff_stride, tx_4x4_w << 2);
520  } else {
521    int r, c;
522    int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
523    int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
524    sse = 0;
525    // if we are in the unrestricted motion border.
526    for (r = 0; r < max_r; ++r) {
527      // Skip visiting the sub blocks that are wholly within the UMV.
528      for (c = 0; c < max_c; ++c) {
529        sse += (int64_t)vpx_sum_squares_2d_i16(
530            diff + r * diff_stride * 4 + c * 4, diff_stride, 4);
531      }
532    }
533  }
534  return sse;
535}
536
537static void dist_block(const VP9_COMP *cpi, MACROBLOCK *x, int plane,
538                       BLOCK_SIZE plane_bsize, int block, int blk_row,
539                       int blk_col, TX_SIZE tx_size, int64_t *out_dist,
540                       int64_t *out_sse) {
541  MACROBLOCKD *const xd = &x->e_mbd;
542  const struct macroblock_plane *const p = &x->plane[plane];
543  const struct macroblockd_plane *const pd = &xd->plane[plane];
544
545  if (x->block_tx_domain) {
546    const int ss_txfrm_size = tx_size << 1;
547    int64_t this_sse;
548    const int shift = tx_size == TX_32X32 ? 0 : 2;
549    const tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
550    const tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
551#if CONFIG_VP9_HIGHBITDEPTH
552    const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
553    *out_dist = vp9_highbd_block_error_dispatch(
554                    coeff, dqcoeff, 16 << ss_txfrm_size, &this_sse, bd) >>
555                shift;
556#else
557    *out_dist =
558        vp9_block_error(coeff, dqcoeff, 16 << ss_txfrm_size, &this_sse) >>
559        shift;
560#endif  // CONFIG_VP9_HIGHBITDEPTH
561    *out_sse = this_sse >> shift;
562
563    if (x->skip_encode && !is_inter_block(xd->mi[0])) {
564      // TODO(jingning): tune the model to better capture the distortion.
565      const int64_t p =
566          (pd->dequant[1] * pd->dequant[1] * (1 << ss_txfrm_size)) >>
567#if CONFIG_VP9_HIGHBITDEPTH
568          (shift + 2 + (bd - 8) * 2);
569#else
570          (shift + 2);
571#endif  // CONFIG_VP9_HIGHBITDEPTH
572      *out_dist += (p >> 4);
573      *out_sse += p;
574    }
575  } else {
576    const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
577    const int bs = 4 * num_4x4_blocks_wide_lookup[tx_bsize];
578    const int src_stride = p->src.stride;
579    const int dst_stride = pd->dst.stride;
580    const int src_idx = 4 * (blk_row * src_stride + blk_col);
581    const int dst_idx = 4 * (blk_row * dst_stride + blk_col);
582    const uint8_t *src = &p->src.buf[src_idx];
583    const uint8_t *dst = &pd->dst.buf[dst_idx];
584    const tran_low_t *dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
585    const uint16_t *eob = &p->eobs[block];
586    unsigned int tmp;
587
588    tmp = pixel_sse(cpi, xd, pd, src, src_stride, dst, dst_stride, blk_row,
589                    blk_col, plane_bsize, tx_bsize);
590    *out_sse = (int64_t)tmp * 16;
591
592    if (*eob) {
593#if CONFIG_VP9_HIGHBITDEPTH
594      DECLARE_ALIGNED(16, uint16_t, recon16[1024]);
595      uint8_t *recon = (uint8_t *)recon16;
596#else
597      DECLARE_ALIGNED(16, uint8_t, recon[1024]);
598#endif  // CONFIG_VP9_HIGHBITDEPTH
599
600#if CONFIG_VP9_HIGHBITDEPTH
601      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
602        vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(dst), dst_stride, recon16,
603                                 32, NULL, 0, 0, 0, 0, bs, bs, xd->bd);
604        if (xd->lossless) {
605          vp9_highbd_iwht4x4_add(dqcoeff, recon16, 32, *eob, xd->bd);
606        } else {
607          switch (tx_size) {
608            case TX_4X4:
609              vp9_highbd_idct4x4_add(dqcoeff, recon16, 32, *eob, xd->bd);
610              break;
611            case TX_8X8:
612              vp9_highbd_idct8x8_add(dqcoeff, recon16, 32, *eob, xd->bd);
613              break;
614            case TX_16X16:
615              vp9_highbd_idct16x16_add(dqcoeff, recon16, 32, *eob, xd->bd);
616              break;
617            case TX_32X32:
618              vp9_highbd_idct32x32_add(dqcoeff, recon16, 32, *eob, xd->bd);
619              break;
620            default: assert(0 && "Invalid transform size");
621          }
622        }
623        recon = CONVERT_TO_BYTEPTR(recon16);
624      } else {
625#endif  // CONFIG_VP9_HIGHBITDEPTH
626        vpx_convolve_copy(dst, dst_stride, recon, 32, NULL, 0, 0, 0, 0, bs, bs);
627        switch (tx_size) {
628          case TX_32X32: vp9_idct32x32_add(dqcoeff, recon, 32, *eob); break;
629          case TX_16X16: vp9_idct16x16_add(dqcoeff, recon, 32, *eob); break;
630          case TX_8X8: vp9_idct8x8_add(dqcoeff, recon, 32, *eob); break;
631          case TX_4X4:
632            // this is like vp9_short_idct4x4 but has a special case around
633            // eob<=1, which is significant (not just an optimization) for
634            // the lossless case.
635            x->inv_txfm_add(dqcoeff, recon, 32, *eob);
636            break;
637          default: assert(0 && "Invalid transform size"); break;
638        }
639#if CONFIG_VP9_HIGHBITDEPTH
640      }
641#endif  // CONFIG_VP9_HIGHBITDEPTH
642
643      tmp = pixel_sse(cpi, xd, pd, src, src_stride, recon, 32, blk_row, blk_col,
644                      plane_bsize, tx_bsize);
645    }
646
647    *out_dist = (int64_t)tmp * 16;
648  }
649}
650
651static int rate_block(int plane, int block, TX_SIZE tx_size, int coeff_ctx,
652                      struct rdcost_block_args *args) {
653  return cost_coeffs(args->x, plane, block, tx_size, coeff_ctx, args->so->scan,
654                     args->so->neighbors, args->use_fast_coef_costing);
655}
656
657static void block_rd_txfm(int plane, int block, int blk_row, int blk_col,
658                          BLOCK_SIZE plane_bsize, TX_SIZE tx_size, void *arg) {
659  struct rdcost_block_args *args = arg;
660  MACROBLOCK *const x = args->x;
661  MACROBLOCKD *const xd = &x->e_mbd;
662  MODE_INFO *const mi = xd->mi[0];
663  int64_t rd1, rd2, rd;
664  int rate;
665  int64_t dist;
666  int64_t sse;
667  const int coeff_ctx =
668      combine_entropy_contexts(args->t_left[blk_row], args->t_above[blk_col]);
669
670  if (args->exit_early) return;
671
672  if (!is_inter_block(mi)) {
673    struct encode_b_args intra_arg = { x, x->block_qcoeff_opt, args->t_above,
674                                       args->t_left, &mi->skip };
675    vp9_encode_block_intra(plane, block, blk_row, blk_col, plane_bsize, tx_size,
676                           &intra_arg);
677    if (x->block_tx_domain) {
678      dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
679                 tx_size, &dist, &sse);
680    } else {
681      const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
682      const struct macroblock_plane *const p = &x->plane[plane];
683      const struct macroblockd_plane *const pd = &xd->plane[plane];
684      const int src_stride = p->src.stride;
685      const int dst_stride = pd->dst.stride;
686      const int diff_stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
687      const uint8_t *src = &p->src.buf[4 * (blk_row * src_stride + blk_col)];
688      const uint8_t *dst = &pd->dst.buf[4 * (blk_row * dst_stride + blk_col)];
689      const int16_t *diff = &p->src_diff[4 * (blk_row * diff_stride + blk_col)];
690      unsigned int tmp;
691      sse = sum_squares_visible(xd, pd, diff, diff_stride, blk_row, blk_col,
692                                plane_bsize, tx_bsize);
693#if CONFIG_VP9_HIGHBITDEPTH
694      if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && (xd->bd > 8))
695        sse = ROUND64_POWER_OF_TWO(sse, (xd->bd - 8) * 2);
696#endif  // CONFIG_VP9_HIGHBITDEPTH
697      sse = sse * 16;
698      tmp = pixel_sse(args->cpi, xd, pd, src, src_stride, dst, dst_stride,
699                      blk_row, blk_col, plane_bsize, tx_bsize);
700      dist = (int64_t)tmp * 16;
701    }
702  } else if (max_txsize_lookup[plane_bsize] == tx_size) {
703    if (x->skip_txfm[(plane << 2) + (block >> (tx_size << 1))] ==
704        SKIP_TXFM_NONE) {
705      // full forward transform and quantization
706      vp9_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, tx_size);
707      if (x->block_qcoeff_opt)
708        vp9_optimize_b(x, plane, block, tx_size, coeff_ctx);
709      dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
710                 tx_size, &dist, &sse);
711    } else if (x->skip_txfm[(plane << 2) + (block >> (tx_size << 1))] ==
712               SKIP_TXFM_AC_ONLY) {
713      // compute DC coefficient
714      tran_low_t *const coeff = BLOCK_OFFSET(x->plane[plane].coeff, block);
715      tran_low_t *const dqcoeff = BLOCK_OFFSET(xd->plane[plane].dqcoeff, block);
716      vp9_xform_quant_dc(x, plane, block, blk_row, blk_col, plane_bsize,
717                         tx_size);
718      sse = x->bsse[(plane << 2) + (block >> (tx_size << 1))] << 4;
719      dist = sse;
720      if (x->plane[plane].eobs[block]) {
721        const int64_t orig_sse = (int64_t)coeff[0] * coeff[0];
722        const int64_t resd_sse = coeff[0] - dqcoeff[0];
723        int64_t dc_correct = orig_sse - resd_sse * resd_sse;
724#if CONFIG_VP9_HIGHBITDEPTH
725        dc_correct >>= ((xd->bd - 8) * 2);
726#endif
727        if (tx_size != TX_32X32) dc_correct >>= 2;
728
729        dist = VPXMAX(0, sse - dc_correct);
730      }
731    } else {
732      // SKIP_TXFM_AC_DC
733      // skip forward transform. Because this is handled here, the quantization
734      // does not need to do it.
735      x->plane[plane].eobs[block] = 0;
736      sse = x->bsse[(plane << 2) + (block >> (tx_size << 1))] << 4;
737      dist = sse;
738    }
739  } else {
740    // full forward transform and quantization
741    vp9_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, tx_size);
742    if (x->block_qcoeff_opt)
743      vp9_optimize_b(x, plane, block, tx_size, coeff_ctx);
744    dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
745               tx_size, &dist, &sse);
746  }
747
748  rd = RDCOST(x->rdmult, x->rddiv, 0, dist);
749  if (args->this_rd + rd > args->best_rd) {
750    args->exit_early = 1;
751    return;
752  }
753
754  rate = rate_block(plane, block, tx_size, coeff_ctx, args);
755  args->t_above[blk_col] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
756  args->t_left[blk_row] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
757  rd1 = RDCOST(x->rdmult, x->rddiv, rate, dist);
758  rd2 = RDCOST(x->rdmult, x->rddiv, 0, sse);
759
760  // TODO(jingning): temporarily enabled only for luma component
761  rd = VPXMIN(rd1, rd2);
762  if (plane == 0) {
763    x->zcoeff_blk[tx_size][block] =
764        !x->plane[plane].eobs[block] || (rd1 > rd2 && !xd->lossless);
765    x->sum_y_eobs[tx_size] += x->plane[plane].eobs[block];
766  }
767
768  args->this_rate += rate;
769  args->this_dist += dist;
770  args->this_sse += sse;
771  args->this_rd += rd;
772
773  if (args->this_rd > args->best_rd) {
774    args->exit_early = 1;
775    return;
776  }
777
778  args->skippable &= !x->plane[plane].eobs[block];
779}
780
781static void txfm_rd_in_plane(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
782                             int64_t *distortion, int *skippable, int64_t *sse,
783                             int64_t ref_best_rd, int plane, BLOCK_SIZE bsize,
784                             TX_SIZE tx_size, int use_fast_coef_casting) {
785  MACROBLOCKD *const xd = &x->e_mbd;
786  const struct macroblockd_plane *const pd = &xd->plane[plane];
787  struct rdcost_block_args args;
788  vp9_zero(args);
789  args.cpi = cpi;
790  args.x = x;
791  args.best_rd = ref_best_rd;
792  args.use_fast_coef_costing = use_fast_coef_casting;
793  args.skippable = 1;
794
795  if (plane == 0) xd->mi[0]->tx_size = tx_size;
796
797  vp9_get_entropy_contexts(bsize, tx_size, pd, args.t_above, args.t_left);
798
799  args.so = get_scan(xd, tx_size, get_plane_type(plane), 0);
800
801  vp9_foreach_transformed_block_in_plane(xd, bsize, plane, block_rd_txfm,
802                                         &args);
803  if (args.exit_early) {
804    *rate = INT_MAX;
805    *distortion = INT64_MAX;
806    *sse = INT64_MAX;
807    *skippable = 0;
808  } else {
809    *distortion = args.this_dist;
810    *rate = args.this_rate;
811    *sse = args.this_sse;
812    *skippable = args.skippable;
813  }
814}
815
816static void choose_largest_tx_size(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
817                                   int64_t *distortion, int *skip, int64_t *sse,
818                                   int64_t ref_best_rd, BLOCK_SIZE bs) {
819  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
820  VP9_COMMON *const cm = &cpi->common;
821  const TX_SIZE largest_tx_size = tx_mode_to_biggest_tx_size[cm->tx_mode];
822  MACROBLOCKD *const xd = &x->e_mbd;
823  MODE_INFO *const mi = xd->mi[0];
824
825  mi->tx_size = VPXMIN(max_tx_size, largest_tx_size);
826
827  txfm_rd_in_plane(cpi, x, rate, distortion, skip, sse, ref_best_rd, 0, bs,
828                   mi->tx_size, cpi->sf.use_fast_coef_costing);
829}
830
831static void choose_tx_size_from_rd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
832                                   int64_t *distortion, int *skip,
833                                   int64_t *psse, int64_t ref_best_rd,
834                                   BLOCK_SIZE bs) {
835  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
836  VP9_COMMON *const cm = &cpi->common;
837  MACROBLOCKD *const xd = &x->e_mbd;
838  MODE_INFO *const mi = xd->mi[0];
839  vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
840  int r[TX_SIZES][2], s[TX_SIZES];
841  int64_t d[TX_SIZES], sse[TX_SIZES];
842  int64_t rd[TX_SIZES][2] = { { INT64_MAX, INT64_MAX },
843                              { INT64_MAX, INT64_MAX },
844                              { INT64_MAX, INT64_MAX },
845                              { INT64_MAX, INT64_MAX } };
846  int n, m;
847  int s0, s1;
848  int64_t best_rd = INT64_MAX;
849  TX_SIZE best_tx = max_tx_size;
850  int start_tx, end_tx;
851
852  const vpx_prob *tx_probs = get_tx_probs2(max_tx_size, xd, &cm->fc->tx_probs);
853  assert(skip_prob > 0);
854  s0 = vp9_cost_bit(skip_prob, 0);
855  s1 = vp9_cost_bit(skip_prob, 1);
856
857  if (cm->tx_mode == TX_MODE_SELECT) {
858    start_tx = max_tx_size;
859    end_tx = 0;
860  } else {
861    TX_SIZE chosen_tx_size =
862        VPXMIN(max_tx_size, tx_mode_to_biggest_tx_size[cm->tx_mode]);
863    start_tx = chosen_tx_size;
864    end_tx = chosen_tx_size;
865  }
866
867  for (n = start_tx; n >= end_tx; n--) {
868    int r_tx_size = 0;
869    for (m = 0; m <= n - (n == (int)max_tx_size); m++) {
870      if (m == n)
871        r_tx_size += vp9_cost_zero(tx_probs[m]);
872      else
873        r_tx_size += vp9_cost_one(tx_probs[m]);
874    }
875    txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], ref_best_rd, 0,
876                     bs, n, cpi->sf.use_fast_coef_costing);
877    r[n][1] = r[n][0];
878    if (r[n][0] < INT_MAX) {
879      r[n][1] += r_tx_size;
880    }
881    if (d[n] == INT64_MAX || r[n][0] == INT_MAX) {
882      rd[n][0] = rd[n][1] = INT64_MAX;
883    } else if (s[n]) {
884      if (is_inter_block(mi)) {
885        rd[n][0] = rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
886        r[n][1] -= r_tx_size;
887      } else {
888        rd[n][0] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
889        rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1 + r_tx_size, sse[n]);
890      }
891    } else {
892      rd[n][0] = RDCOST(x->rdmult, x->rddiv, r[n][0] + s0, d[n]);
893      rd[n][1] = RDCOST(x->rdmult, x->rddiv, r[n][1] + s0, d[n]);
894    }
895
896    if (is_inter_block(mi) && !xd->lossless && !s[n] && sse[n] != INT64_MAX) {
897      rd[n][0] = VPXMIN(rd[n][0], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
898      rd[n][1] = VPXMIN(rd[n][1], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
899    }
900
901    // Early termination in transform size search.
902    if (cpi->sf.tx_size_search_breakout &&
903        (rd[n][1] == INT64_MAX ||
904         (n < (int)max_tx_size && rd[n][1] > rd[n + 1][1]) || s[n] == 1))
905      break;
906
907    if (rd[n][1] < best_rd) {
908      best_tx = n;
909      best_rd = rd[n][1];
910    }
911  }
912  mi->tx_size = best_tx;
913
914  *distortion = d[mi->tx_size];
915  *rate = r[mi->tx_size][cm->tx_mode == TX_MODE_SELECT];
916  *skip = s[mi->tx_size];
917  *psse = sse[mi->tx_size];
918}
919
920static void super_block_yrd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
921                            int64_t *distortion, int *skip, int64_t *psse,
922                            BLOCK_SIZE bs, int64_t ref_best_rd) {
923  MACROBLOCKD *xd = &x->e_mbd;
924  int64_t sse;
925  int64_t *ret_sse = psse ? psse : &sse;
926
927  assert(bs == xd->mi[0]->sb_type);
928
929  if (cpi->sf.tx_size_search_method == USE_LARGESTALL || xd->lossless) {
930    choose_largest_tx_size(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
931                           bs);
932  } else {
933    choose_tx_size_from_rd(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
934                           bs);
935  }
936}
937
938static int conditional_skipintra(PREDICTION_MODE mode,
939                                 PREDICTION_MODE best_intra_mode) {
940  if (mode == D117_PRED && best_intra_mode != V_PRED &&
941      best_intra_mode != D135_PRED)
942    return 1;
943  if (mode == D63_PRED && best_intra_mode != V_PRED &&
944      best_intra_mode != D45_PRED)
945    return 1;
946  if (mode == D207_PRED && best_intra_mode != H_PRED &&
947      best_intra_mode != D45_PRED)
948    return 1;
949  if (mode == D153_PRED && best_intra_mode != H_PRED &&
950      best_intra_mode != D135_PRED)
951    return 1;
952  return 0;
953}
954
955static int64_t rd_pick_intra4x4block(VP9_COMP *cpi, MACROBLOCK *x, int row,
956                                     int col, PREDICTION_MODE *best_mode,
957                                     const int *bmode_costs, ENTROPY_CONTEXT *a,
958                                     ENTROPY_CONTEXT *l, int *bestrate,
959                                     int *bestratey, int64_t *bestdistortion,
960                                     BLOCK_SIZE bsize, int64_t rd_thresh) {
961  PREDICTION_MODE mode;
962  MACROBLOCKD *const xd = &x->e_mbd;
963  int64_t best_rd = rd_thresh;
964  struct macroblock_plane *p = &x->plane[0];
965  struct macroblockd_plane *pd = &xd->plane[0];
966  const int src_stride = p->src.stride;
967  const int dst_stride = pd->dst.stride;
968  const uint8_t *src_init = &p->src.buf[row * 4 * src_stride + col * 4];
969  uint8_t *dst_init = &pd->dst.buf[row * 4 * src_stride + col * 4];
970  ENTROPY_CONTEXT ta[2], tempa[2];
971  ENTROPY_CONTEXT tl[2], templ[2];
972  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
973  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
974  int idx, idy;
975  uint8_t best_dst[8 * 8];
976#if CONFIG_VP9_HIGHBITDEPTH
977  uint16_t best_dst16[8 * 8];
978#endif
979  memcpy(ta, a, num_4x4_blocks_wide * sizeof(a[0]));
980  memcpy(tl, l, num_4x4_blocks_high * sizeof(l[0]));
981
982  xd->mi[0]->tx_size = TX_4X4;
983
984#if CONFIG_VP9_HIGHBITDEPTH
985  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
986    for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
987      int64_t this_rd;
988      int ratey = 0;
989      int64_t distortion = 0;
990      int rate = bmode_costs[mode];
991
992      if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
993
994      // Only do the oblique modes if the best so far is
995      // one of the neighboring directional modes
996      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
997        if (conditional_skipintra(mode, *best_mode)) continue;
998      }
999
1000      memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1001      memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1002
1003      for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1004        for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1005          const int block = (row + idy) * 2 + (col + idx);
1006          const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1007          uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1008          uint16_t *const dst16 = CONVERT_TO_SHORTPTR(dst);
1009          int16_t *const src_diff =
1010              vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1011          tran_low_t *const coeff = BLOCK_OFFSET(x->plane[0].coeff, block);
1012          xd->mi[0]->bmi[block].as_mode = mode;
1013          vp9_predict_intra_block(xd, 1, TX_4X4, mode,
1014                                  x->skip_encode ? src : dst,
1015                                  x->skip_encode ? src_stride : dst_stride, dst,
1016                                  dst_stride, col + idx, row + idy, 0);
1017          vpx_highbd_subtract_block(4, 4, src_diff, 8, src, src_stride, dst,
1018                                    dst_stride, xd->bd);
1019          if (xd->lossless) {
1020            const scan_order *so = &vp9_default_scan_orders[TX_4X4];
1021            const int coeff_ctx =
1022                combine_entropy_contexts(tempa[idx], templ[idy]);
1023            vp9_highbd_fwht4x4(src_diff, coeff, 8);
1024            vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
1025            ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1026                                 so->neighbors, cpi->sf.use_fast_coef_costing);
1027            tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1028            if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1029              goto next_highbd;
1030            vp9_highbd_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst16,
1031                                   dst_stride, p->eobs[block], xd->bd);
1032          } else {
1033            int64_t unused;
1034            const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1035            const scan_order *so = &vp9_scan_orders[TX_4X4][tx_type];
1036            const int coeff_ctx =
1037                combine_entropy_contexts(tempa[idx], templ[idy]);
1038            if (tx_type == DCT_DCT)
1039              vpx_highbd_fdct4x4(src_diff, coeff, 8);
1040            else
1041              vp9_highbd_fht4x4(src_diff, coeff, 8, tx_type);
1042            vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
1043            ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1044                                 so->neighbors, cpi->sf.use_fast_coef_costing);
1045            distortion += vp9_highbd_block_error_dispatch(
1046                              coeff, BLOCK_OFFSET(pd->dqcoeff, block), 16,
1047                              &unused, xd->bd) >>
1048                          2;
1049            tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1050            if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1051              goto next_highbd;
1052            vp9_highbd_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block),
1053                                  dst16, dst_stride, p->eobs[block], xd->bd);
1054          }
1055        }
1056      }
1057
1058      rate += ratey;
1059      this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1060
1061      if (this_rd < best_rd) {
1062        *bestrate = rate;
1063        *bestratey = ratey;
1064        *bestdistortion = distortion;
1065        best_rd = this_rd;
1066        *best_mode = mode;
1067        memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1068        memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1069        for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1070          memcpy(best_dst16 + idy * 8,
1071                 CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1072                 num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1073        }
1074      }
1075    next_highbd : {}
1076    }
1077    if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1078
1079    for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1080      memcpy(CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1081             best_dst16 + idy * 8, num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1082    }
1083
1084    return best_rd;
1085  }
1086#endif  // CONFIG_VP9_HIGHBITDEPTH
1087
1088  for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1089    int64_t this_rd;
1090    int ratey = 0;
1091    int64_t distortion = 0;
1092    int rate = bmode_costs[mode];
1093
1094    if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
1095
1096    // Only do the oblique modes if the best so far is
1097    // one of the neighboring directional modes
1098    if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
1099      if (conditional_skipintra(mode, *best_mode)) continue;
1100    }
1101
1102    memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1103    memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1104
1105    for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1106      for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1107        const int block = (row + idy) * 2 + (col + idx);
1108        const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1109        uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1110        int16_t *const src_diff =
1111            vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1112        tran_low_t *const coeff = BLOCK_OFFSET(x->plane[0].coeff, block);
1113        xd->mi[0]->bmi[block].as_mode = mode;
1114        vp9_predict_intra_block(xd, 1, TX_4X4, mode, x->skip_encode ? src : dst,
1115                                x->skip_encode ? src_stride : dst_stride, dst,
1116                                dst_stride, col + idx, row + idy, 0);
1117        vpx_subtract_block(4, 4, src_diff, 8, src, src_stride, dst, dst_stride);
1118
1119        if (xd->lossless) {
1120          const scan_order *so = &vp9_default_scan_orders[TX_4X4];
1121          const int coeff_ctx =
1122              combine_entropy_contexts(tempa[idx], templ[idy]);
1123          vp9_fwht4x4(src_diff, coeff, 8);
1124          vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
1125          ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1126                               so->neighbors, cpi->sf.use_fast_coef_costing);
1127          tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1128          if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1129            goto next;
1130          vp9_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst, dst_stride,
1131                          p->eobs[block]);
1132        } else {
1133          int64_t unused;
1134          const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1135          const scan_order *so = &vp9_scan_orders[TX_4X4][tx_type];
1136          const int coeff_ctx =
1137              combine_entropy_contexts(tempa[idx], templ[idy]);
1138          vp9_fht4x4(src_diff, coeff, 8, tx_type);
1139          vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
1140          ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1141                               so->neighbors, cpi->sf.use_fast_coef_costing);
1142          tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1143          distortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, block),
1144                                        16, &unused) >>
1145                        2;
1146          if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1147            goto next;
1148          vp9_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block), dst,
1149                         dst_stride, p->eobs[block]);
1150        }
1151      }
1152    }
1153
1154    rate += ratey;
1155    this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1156
1157    if (this_rd < best_rd) {
1158      *bestrate = rate;
1159      *bestratey = ratey;
1160      *bestdistortion = distortion;
1161      best_rd = this_rd;
1162      *best_mode = mode;
1163      memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1164      memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1165      for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1166        memcpy(best_dst + idy * 8, dst_init + idy * dst_stride,
1167               num_4x4_blocks_wide * 4);
1168    }
1169  next : {}
1170  }
1171
1172  if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1173
1174  for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1175    memcpy(dst_init + idy * dst_stride, best_dst + idy * 8,
1176           num_4x4_blocks_wide * 4);
1177
1178  return best_rd;
1179}
1180
1181static int64_t rd_pick_intra_sub_8x8_y_mode(VP9_COMP *cpi, MACROBLOCK *mb,
1182                                            int *rate, int *rate_y,
1183                                            int64_t *distortion,
1184                                            int64_t best_rd) {
1185  int i, j;
1186  const MACROBLOCKD *const xd = &mb->e_mbd;
1187  MODE_INFO *const mic = xd->mi[0];
1188  const MODE_INFO *above_mi = xd->above_mi;
1189  const MODE_INFO *left_mi = xd->left_mi;
1190  const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
1191  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1192  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1193  int idx, idy;
1194  int cost = 0;
1195  int64_t total_distortion = 0;
1196  int tot_rate_y = 0;
1197  int64_t total_rd = 0;
1198  const int *bmode_costs = cpi->mbmode_cost;
1199
1200  // Pick modes for each sub-block (of size 4x4, 4x8, or 8x4) in an 8x8 block.
1201  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1202    for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1203      PREDICTION_MODE best_mode = DC_PRED;
1204      int r = INT_MAX, ry = INT_MAX;
1205      int64_t d = INT64_MAX, this_rd = INT64_MAX;
1206      i = idy * 2 + idx;
1207      if (cpi->common.frame_type == KEY_FRAME) {
1208        const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, i);
1209        const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, i);
1210
1211        bmode_costs = cpi->y_mode_costs[A][L];
1212      }
1213
1214      this_rd = rd_pick_intra4x4block(
1215          cpi, mb, idy, idx, &best_mode, bmode_costs,
1216          xd->plane[0].above_context + idx, xd->plane[0].left_context + idy, &r,
1217          &ry, &d, bsize, best_rd - total_rd);
1218
1219      if (this_rd >= best_rd - total_rd) return INT64_MAX;
1220
1221      total_rd += this_rd;
1222      cost += r;
1223      total_distortion += d;
1224      tot_rate_y += ry;
1225
1226      mic->bmi[i].as_mode = best_mode;
1227      for (j = 1; j < num_4x4_blocks_high; ++j)
1228        mic->bmi[i + j * 2].as_mode = best_mode;
1229      for (j = 1; j < num_4x4_blocks_wide; ++j)
1230        mic->bmi[i + j].as_mode = best_mode;
1231
1232      if (total_rd >= best_rd) return INT64_MAX;
1233    }
1234  }
1235
1236  *rate = cost;
1237  *rate_y = tot_rate_y;
1238  *distortion = total_distortion;
1239  mic->mode = mic->bmi[3].as_mode;
1240
1241  return RDCOST(mb->rdmult, mb->rddiv, cost, total_distortion);
1242}
1243
1244// This function is used only for intra_only frames
1245static int64_t rd_pick_intra_sby_mode(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1246                                      int *rate_tokenonly, int64_t *distortion,
1247                                      int *skippable, BLOCK_SIZE bsize,
1248                                      int64_t best_rd) {
1249  PREDICTION_MODE mode;
1250  PREDICTION_MODE mode_selected = DC_PRED;
1251  MACROBLOCKD *const xd = &x->e_mbd;
1252  MODE_INFO *const mic = xd->mi[0];
1253  int this_rate, this_rate_tokenonly, s;
1254  int64_t this_distortion, this_rd;
1255  TX_SIZE best_tx = TX_4X4;
1256  int *bmode_costs;
1257  const MODE_INFO *above_mi = xd->above_mi;
1258  const MODE_INFO *left_mi = xd->left_mi;
1259  const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
1260  const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
1261  bmode_costs = cpi->y_mode_costs[A][L];
1262
1263  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1264  /* Y Search for intra prediction mode */
1265  for (mode = DC_PRED; mode <= TM_PRED; mode++) {
1266    if (cpi->sf.use_nonrd_pick_mode) {
1267      // These speed features are turned on in hybrid non-RD and RD mode
1268      // for key frame coding in the context of real-time setting.
1269      if (conditional_skipintra(mode, mode_selected)) continue;
1270      if (*skippable) break;
1271    }
1272
1273    mic->mode = mode;
1274
1275    super_block_yrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s, NULL,
1276                    bsize, best_rd);
1277
1278    if (this_rate_tokenonly == INT_MAX) continue;
1279
1280    this_rate = this_rate_tokenonly + bmode_costs[mode];
1281    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1282
1283    if (this_rd < best_rd) {
1284      mode_selected = mode;
1285      best_rd = this_rd;
1286      best_tx = mic->tx_size;
1287      *rate = this_rate;
1288      *rate_tokenonly = this_rate_tokenonly;
1289      *distortion = this_distortion;
1290      *skippable = s;
1291    }
1292  }
1293
1294  mic->mode = mode_selected;
1295  mic->tx_size = best_tx;
1296
1297  return best_rd;
1298}
1299
1300// Return value 0: early termination triggered, no valid rd cost available;
1301//              1: rd cost values are valid.
1302static int super_block_uvrd(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1303                            int64_t *distortion, int *skippable, int64_t *sse,
1304                            BLOCK_SIZE bsize, int64_t ref_best_rd) {
1305  MACROBLOCKD *const xd = &x->e_mbd;
1306  MODE_INFO *const mi = xd->mi[0];
1307  const TX_SIZE uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
1308  int plane;
1309  int pnrate = 0, pnskip = 1;
1310  int64_t pndist = 0, pnsse = 0;
1311  int is_cost_valid = 1;
1312
1313  if (ref_best_rd < 0) is_cost_valid = 0;
1314
1315  if (is_inter_block(mi) && is_cost_valid) {
1316    int plane;
1317    for (plane = 1; plane < MAX_MB_PLANE; ++plane)
1318      vp9_subtract_plane(x, bsize, plane);
1319  }
1320
1321  *rate = 0;
1322  *distortion = 0;
1323  *sse = 0;
1324  *skippable = 1;
1325
1326  for (plane = 1; plane < MAX_MB_PLANE; ++plane) {
1327    txfm_rd_in_plane(cpi, x, &pnrate, &pndist, &pnskip, &pnsse, ref_best_rd,
1328                     plane, bsize, uv_tx_size, cpi->sf.use_fast_coef_costing);
1329    if (pnrate == INT_MAX) {
1330      is_cost_valid = 0;
1331      break;
1332    }
1333    *rate += pnrate;
1334    *distortion += pndist;
1335    *sse += pnsse;
1336    *skippable &= pnskip;
1337  }
1338
1339  if (!is_cost_valid) {
1340    // reset cost value
1341    *rate = INT_MAX;
1342    *distortion = INT64_MAX;
1343    *sse = INT64_MAX;
1344    *skippable = 0;
1345  }
1346
1347  return is_cost_valid;
1348}
1349
1350static int64_t rd_pick_intra_sbuv_mode(VP9_COMP *cpi, MACROBLOCK *x,
1351                                       PICK_MODE_CONTEXT *ctx, int *rate,
1352                                       int *rate_tokenonly, int64_t *distortion,
1353                                       int *skippable, BLOCK_SIZE bsize,
1354                                       TX_SIZE max_tx_size) {
1355  MACROBLOCKD *xd = &x->e_mbd;
1356  PREDICTION_MODE mode;
1357  PREDICTION_MODE mode_selected = DC_PRED;
1358  int64_t best_rd = INT64_MAX, this_rd;
1359  int this_rate_tokenonly, this_rate, s;
1360  int64_t this_distortion, this_sse;
1361
1362  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1363  for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1364    if (!(cpi->sf.intra_uv_mode_mask[max_tx_size] & (1 << mode))) continue;
1365#if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
1366    if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
1367        (xd->above_mi == NULL || xd->left_mi == NULL) && need_top_left[mode])
1368      continue;
1369#endif  // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
1370
1371    xd->mi[0]->uv_mode = mode;
1372
1373    if (!super_block_uvrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s,
1374                          &this_sse, bsize, best_rd))
1375      continue;
1376    this_rate =
1377        this_rate_tokenonly +
1378        cpi->intra_uv_mode_cost[cpi->common.frame_type][xd->mi[0]->mode][mode];
1379    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1380
1381    if (this_rd < best_rd) {
1382      mode_selected = mode;
1383      best_rd = this_rd;
1384      *rate = this_rate;
1385      *rate_tokenonly = this_rate_tokenonly;
1386      *distortion = this_distortion;
1387      *skippable = s;
1388      if (!x->select_tx_size) swap_block_ptr(x, ctx, 2, 0, 1, MAX_MB_PLANE);
1389    }
1390  }
1391
1392  xd->mi[0]->uv_mode = mode_selected;
1393  return best_rd;
1394}
1395
1396static int64_t rd_sbuv_dcpred(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1397                              int *rate_tokenonly, int64_t *distortion,
1398                              int *skippable, BLOCK_SIZE bsize) {
1399  const VP9_COMMON *cm = &cpi->common;
1400  int64_t unused;
1401
1402  x->e_mbd.mi[0]->uv_mode = DC_PRED;
1403  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1404  super_block_uvrd(cpi, x, rate_tokenonly, distortion, skippable, &unused,
1405                   bsize, INT64_MAX);
1406  *rate =
1407      *rate_tokenonly +
1408      cpi->intra_uv_mode_cost[cm->frame_type][x->e_mbd.mi[0]->mode][DC_PRED];
1409  return RDCOST(x->rdmult, x->rddiv, *rate, *distortion);
1410}
1411
1412static void choose_intra_uv_mode(VP9_COMP *cpi, MACROBLOCK *const x,
1413                                 PICK_MODE_CONTEXT *ctx, BLOCK_SIZE bsize,
1414                                 TX_SIZE max_tx_size, int *rate_uv,
1415                                 int *rate_uv_tokenonly, int64_t *dist_uv,
1416                                 int *skip_uv, PREDICTION_MODE *mode_uv) {
1417  // Use an estimated rd for uv_intra based on DC_PRED if the
1418  // appropriate speed flag is set.
1419  if (cpi->sf.use_uv_intra_rd_estimate) {
1420    rd_sbuv_dcpred(cpi, x, rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
1421                   bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
1422    // Else do a proper rd search for each possible transform size that may
1423    // be considered in the main rd loop.
1424  } else {
1425    rd_pick_intra_sbuv_mode(cpi, x, ctx, rate_uv, rate_uv_tokenonly, dist_uv,
1426                            skip_uv, bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
1427                            max_tx_size);
1428  }
1429  *mode_uv = x->e_mbd.mi[0]->uv_mode;
1430}
1431
1432static int cost_mv_ref(const VP9_COMP *cpi, PREDICTION_MODE mode,
1433                       int mode_context) {
1434  assert(is_inter_mode(mode));
1435  return cpi->inter_mode_cost[mode_context][INTER_OFFSET(mode)];
1436}
1437
1438static int set_and_cost_bmi_mvs(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
1439                                int i, PREDICTION_MODE mode, int_mv this_mv[2],
1440                                int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1441                                int_mv seg_mvs[MAX_REF_FRAMES],
1442                                int_mv *best_ref_mv[2], const int *mvjcost,
1443                                int *mvcost[2]) {
1444  MODE_INFO *const mi = xd->mi[0];
1445  const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1446  int thismvcost = 0;
1447  int idx, idy;
1448  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[mi->sb_type];
1449  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[mi->sb_type];
1450  const int is_compound = has_second_ref(mi);
1451
1452  switch (mode) {
1453    case NEWMV:
1454      this_mv[0].as_int = seg_mvs[mi->ref_frame[0]].as_int;
1455      thismvcost += vp9_mv_bit_cost(&this_mv[0].as_mv, &best_ref_mv[0]->as_mv,
1456                                    mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1457      if (is_compound) {
1458        this_mv[1].as_int = seg_mvs[mi->ref_frame[1]].as_int;
1459        thismvcost += vp9_mv_bit_cost(&this_mv[1].as_mv, &best_ref_mv[1]->as_mv,
1460                                      mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1461      }
1462      break;
1463    case NEARMV:
1464    case NEARESTMV:
1465      this_mv[0].as_int = frame_mv[mode][mi->ref_frame[0]].as_int;
1466      if (is_compound)
1467        this_mv[1].as_int = frame_mv[mode][mi->ref_frame[1]].as_int;
1468      break;
1469    case ZEROMV:
1470      this_mv[0].as_int = 0;
1471      if (is_compound) this_mv[1].as_int = 0;
1472      break;
1473    default: break;
1474  }
1475
1476  mi->bmi[i].as_mv[0].as_int = this_mv[0].as_int;
1477  if (is_compound) mi->bmi[i].as_mv[1].as_int = this_mv[1].as_int;
1478
1479  mi->bmi[i].as_mode = mode;
1480
1481  for (idy = 0; idy < num_4x4_blocks_high; ++idy)
1482    for (idx = 0; idx < num_4x4_blocks_wide; ++idx)
1483      memmove(&mi->bmi[i + idy * 2 + idx], &mi->bmi[i], sizeof(mi->bmi[i]));
1484
1485  return cost_mv_ref(cpi, mode, mbmi_ext->mode_context[mi->ref_frame[0]]) +
1486         thismvcost;
1487}
1488
1489static int64_t encode_inter_mb_segment(VP9_COMP *cpi, MACROBLOCK *x,
1490                                       int64_t best_yrd, int i, int *labelyrate,
1491                                       int64_t *distortion, int64_t *sse,
1492                                       ENTROPY_CONTEXT *ta, ENTROPY_CONTEXT *tl,
1493                                       int mi_row, int mi_col) {
1494  int k;
1495  MACROBLOCKD *xd = &x->e_mbd;
1496  struct macroblockd_plane *const pd = &xd->plane[0];
1497  struct macroblock_plane *const p = &x->plane[0];
1498  MODE_INFO *const mi = xd->mi[0];
1499  const BLOCK_SIZE plane_bsize = get_plane_block_size(mi->sb_type, pd);
1500  const int width = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
1501  const int height = 4 * num_4x4_blocks_high_lookup[plane_bsize];
1502  int idx, idy;
1503
1504  const uint8_t *const src =
1505      &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1506  uint8_t *const dst =
1507      &pd->dst.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->dst.stride)];
1508  int64_t thisdistortion = 0, thissse = 0;
1509  int thisrate = 0, ref;
1510  const scan_order *so = &vp9_default_scan_orders[TX_4X4];
1511  const int is_compound = has_second_ref(mi);
1512  const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
1513
1514  for (ref = 0; ref < 1 + is_compound; ++ref) {
1515    const int bw = b_width_log2_lookup[BLOCK_8X8];
1516    const int h = 4 * (i >> bw);
1517    const int w = 4 * (i & ((1 << bw) - 1));
1518    const struct scale_factors *sf = &xd->block_refs[ref]->sf;
1519    int y_stride = pd->pre[ref].stride;
1520    uint8_t *pre = pd->pre[ref].buf + (h * pd->pre[ref].stride + w);
1521
1522    if (vp9_is_scaled(sf)) {
1523      const int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
1524      const int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
1525
1526      y_stride = xd->block_refs[ref]->buf->y_stride;
1527      pre = xd->block_refs[ref]->buf->y_buffer;
1528      pre += scaled_buffer_offset(x_start + w, y_start + h, y_stride, sf);
1529    }
1530#if CONFIG_VP9_HIGHBITDEPTH
1531    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1532      vp9_highbd_build_inter_predictor(
1533          CONVERT_TO_SHORTPTR(pre), y_stride, CONVERT_TO_SHORTPTR(dst),
1534          pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1535          &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1536          mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2),
1537          xd->bd);
1538    } else {
1539      vp9_build_inter_predictor(
1540          pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1541          &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1542          mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
1543    }
1544#else
1545    vp9_build_inter_predictor(
1546        pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1547        &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1548        mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
1549#endif  // CONFIG_VP9_HIGHBITDEPTH
1550  }
1551
1552#if CONFIG_VP9_HIGHBITDEPTH
1553  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1554    vpx_highbd_subtract_block(
1555        height, width, vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1556        8, src, p->src.stride, dst, pd->dst.stride, xd->bd);
1557  } else {
1558    vpx_subtract_block(height, width,
1559                       vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1560                       8, src, p->src.stride, dst, pd->dst.stride);
1561  }
1562#else
1563  vpx_subtract_block(height, width,
1564                     vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1565                     8, src, p->src.stride, dst, pd->dst.stride);
1566#endif  // CONFIG_VP9_HIGHBITDEPTH
1567
1568  k = i;
1569  for (idy = 0; idy < height / 4; ++idy) {
1570    for (idx = 0; idx < width / 4; ++idx) {
1571#if CONFIG_VP9_HIGHBITDEPTH
1572      const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
1573#endif
1574      int64_t ssz, rd, rd1, rd2;
1575      tran_low_t *coeff;
1576      int coeff_ctx;
1577      k += (idy * 2 + idx);
1578      coeff_ctx = combine_entropy_contexts(ta[k & 1], tl[k >> 1]);
1579      coeff = BLOCK_OFFSET(p->coeff, k);
1580      x->fwd_txfm4x4(vp9_raster_block_offset_int16(BLOCK_8X8, k, p->src_diff),
1581                     coeff, 8);
1582      vp9_regular_quantize_b_4x4(x, 0, k, so->scan, so->iscan);
1583#if CONFIG_VP9_HIGHBITDEPTH
1584      thisdistortion += vp9_highbd_block_error_dispatch(
1585          coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz, bd);
1586#else
1587      thisdistortion +=
1588          vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz);
1589#endif  // CONFIG_VP9_HIGHBITDEPTH
1590      thissse += ssz;
1591      thisrate += cost_coeffs(x, 0, k, TX_4X4, coeff_ctx, so->scan,
1592                              so->neighbors, cpi->sf.use_fast_coef_costing);
1593      ta[k & 1] = tl[k >> 1] = (x->plane[0].eobs[k] > 0) ? 1 : 0;
1594      rd1 = RDCOST(x->rdmult, x->rddiv, thisrate, thisdistortion >> 2);
1595      rd2 = RDCOST(x->rdmult, x->rddiv, 0, thissse >> 2);
1596      rd = VPXMIN(rd1, rd2);
1597      if (rd >= best_yrd) return INT64_MAX;
1598    }
1599  }
1600
1601  *distortion = thisdistortion >> 2;
1602  *labelyrate = thisrate;
1603  *sse = thissse >> 2;
1604
1605  return RDCOST(x->rdmult, x->rddiv, *labelyrate, *distortion);
1606}
1607
1608typedef struct {
1609  int eobs;
1610  int brate;
1611  int byrate;
1612  int64_t bdist;
1613  int64_t bsse;
1614  int64_t brdcost;
1615  int_mv mvs[2];
1616  ENTROPY_CONTEXT ta[2];
1617  ENTROPY_CONTEXT tl[2];
1618} SEG_RDSTAT;
1619
1620typedef struct {
1621  int_mv *ref_mv[2];
1622  int_mv mvp;
1623
1624  int64_t segment_rd;
1625  int r;
1626  int64_t d;
1627  int64_t sse;
1628  int segment_yrate;
1629  PREDICTION_MODE modes[4];
1630  SEG_RDSTAT rdstat[4][INTER_MODES];
1631  int mvthresh;
1632} BEST_SEG_INFO;
1633
1634static INLINE int mv_check_bounds(const MvLimits *mv_limits, const MV *mv) {
1635  return (mv->row >> 3) < mv_limits->row_min ||
1636         (mv->row >> 3) > mv_limits->row_max ||
1637         (mv->col >> 3) < mv_limits->col_min ||
1638         (mv->col >> 3) > mv_limits->col_max;
1639}
1640
1641static INLINE void mi_buf_shift(MACROBLOCK *x, int i) {
1642  MODE_INFO *const mi = x->e_mbd.mi[0];
1643  struct macroblock_plane *const p = &x->plane[0];
1644  struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
1645
1646  p->src.buf =
1647      &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1648  assert(((intptr_t)pd->pre[0].buf & 0x7) == 0);
1649  pd->pre[0].buf =
1650      &pd->pre[0].buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[0].stride)];
1651  if (has_second_ref(mi))
1652    pd->pre[1].buf =
1653        &pd->pre[1]
1654             .buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[1].stride)];
1655}
1656
1657static INLINE void mi_buf_restore(MACROBLOCK *x, struct buf_2d orig_src,
1658                                  struct buf_2d orig_pre[2]) {
1659  MODE_INFO *mi = x->e_mbd.mi[0];
1660  x->plane[0].src = orig_src;
1661  x->e_mbd.plane[0].pre[0] = orig_pre[0];
1662  if (has_second_ref(mi)) x->e_mbd.plane[0].pre[1] = orig_pre[1];
1663}
1664
1665static INLINE int mv_has_subpel(const MV *mv) {
1666  return (mv->row & 0x0F) || (mv->col & 0x0F);
1667}
1668
1669// Check if NEARESTMV/NEARMV/ZEROMV is the cheapest way encode zero motion.
1670// TODO(aconverse): Find out if this is still productive then clean up or remove
1671static int check_best_zero_mv(const VP9_COMP *cpi,
1672                              const uint8_t mode_context[MAX_REF_FRAMES],
1673                              int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1674                              int this_mode,
1675                              const MV_REFERENCE_FRAME ref_frames[2]) {
1676  if ((this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
1677      frame_mv[this_mode][ref_frames[0]].as_int == 0 &&
1678      (ref_frames[1] == NONE ||
1679       frame_mv[this_mode][ref_frames[1]].as_int == 0)) {
1680    int rfc = mode_context[ref_frames[0]];
1681    int c1 = cost_mv_ref(cpi, NEARMV, rfc);
1682    int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
1683    int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
1684
1685    if (this_mode == NEARMV) {
1686      if (c1 > c3) return 0;
1687    } else if (this_mode == NEARESTMV) {
1688      if (c2 > c3) return 0;
1689    } else {
1690      assert(this_mode == ZEROMV);
1691      if (ref_frames[1] == NONE) {
1692        if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0) ||
1693            (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0))
1694          return 0;
1695      } else {
1696        if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0 &&
1697             frame_mv[NEARESTMV][ref_frames[1]].as_int == 0) ||
1698            (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0 &&
1699             frame_mv[NEARMV][ref_frames[1]].as_int == 0))
1700          return 0;
1701      }
1702    }
1703  }
1704  return 1;
1705}
1706
1707static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
1708                                int_mv *frame_mv, int mi_row, int mi_col,
1709                                int_mv single_newmv[MAX_REF_FRAMES],
1710                                int *rate_mv) {
1711  const VP9_COMMON *const cm = &cpi->common;
1712  const int pw = 4 * num_4x4_blocks_wide_lookup[bsize];
1713  const int ph = 4 * num_4x4_blocks_high_lookup[bsize];
1714  MACROBLOCKD *xd = &x->e_mbd;
1715  MODE_INFO *mi = xd->mi[0];
1716  const int refs[2] = { mi->ref_frame[0],
1717                        mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1] };
1718  int_mv ref_mv[2];
1719  int ite, ref;
1720  const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
1721  struct scale_factors sf;
1722
1723  // Do joint motion search in compound mode to get more accurate mv.
1724  struct buf_2d backup_yv12[2][MAX_MB_PLANE];
1725  uint32_t last_besterr[2] = { UINT_MAX, UINT_MAX };
1726  const YV12_BUFFER_CONFIG *const scaled_ref_frame[2] = {
1727    vp9_get_scaled_ref_frame(cpi, mi->ref_frame[0]),
1728    vp9_get_scaled_ref_frame(cpi, mi->ref_frame[1])
1729  };
1730
1731// Prediction buffer from second frame.
1732#if CONFIG_VP9_HIGHBITDEPTH
1733  DECLARE_ALIGNED(16, uint16_t, second_pred_alloc_16[64 * 64]);
1734  uint8_t *second_pred;
1735#else
1736  DECLARE_ALIGNED(16, uint8_t, second_pred[64 * 64]);
1737#endif  // CONFIG_VP9_HIGHBITDEPTH
1738
1739  for (ref = 0; ref < 2; ++ref) {
1740    ref_mv[ref] = x->mbmi_ext->ref_mvs[refs[ref]][0];
1741
1742    if (scaled_ref_frame[ref]) {
1743      int i;
1744      // Swap out the reference frame for a version that's been scaled to
1745      // match the resolution of the current frame, allowing the existing
1746      // motion search code to be used without additional modifications.
1747      for (i = 0; i < MAX_MB_PLANE; i++)
1748        backup_yv12[ref][i] = xd->plane[i].pre[ref];
1749      vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
1750                           NULL);
1751    }
1752
1753    frame_mv[refs[ref]].as_int = single_newmv[refs[ref]].as_int;
1754  }
1755
1756// Since we have scaled the reference frames to match the size of the current
1757// frame we must use a unit scaling factor during mode selection.
1758#if CONFIG_VP9_HIGHBITDEPTH
1759  vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
1760                                    cm->height, cm->use_highbitdepth);
1761#else
1762  vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
1763                                    cm->height);
1764#endif  // CONFIG_VP9_HIGHBITDEPTH
1765
1766  // Allow joint search multiple times iteratively for each reference frame
1767  // and break out of the search loop if it couldn't find a better mv.
1768  for (ite = 0; ite < 4; ite++) {
1769    struct buf_2d ref_yv12[2];
1770    uint32_t bestsme = UINT_MAX;
1771    int sadpb = x->sadperbit16;
1772    MV tmp_mv;
1773    int search_range = 3;
1774
1775    const MvLimits tmp_mv_limits = x->mv_limits;
1776    int id = ite % 2;  // Even iterations search in the first reference frame,
1777                       // odd iterations search in the second. The predictor
1778                       // found for the 'other' reference frame is factored in.
1779
1780    // Initialized here because of compiler problem in Visual Studio.
1781    ref_yv12[0] = xd->plane[0].pre[0];
1782    ref_yv12[1] = xd->plane[0].pre[1];
1783
1784// Get the prediction block from the 'other' reference frame.
1785#if CONFIG_VP9_HIGHBITDEPTH
1786    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1787      second_pred = CONVERT_TO_BYTEPTR(second_pred_alloc_16);
1788      vp9_highbd_build_inter_predictor(
1789          CONVERT_TO_SHORTPTR(ref_yv12[!id].buf), ref_yv12[!id].stride,
1790          second_pred_alloc_16, pw, &frame_mv[refs[!id]].as_mv, &sf, pw, ph, 0,
1791          kernel, MV_PRECISION_Q3, mi_col * MI_SIZE, mi_row * MI_SIZE, xd->bd);
1792    } else {
1793      second_pred = (uint8_t *)second_pred_alloc_16;
1794      vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
1795                                second_pred, pw, &frame_mv[refs[!id]].as_mv,
1796                                &sf, pw, ph, 0, kernel, MV_PRECISION_Q3,
1797                                mi_col * MI_SIZE, mi_row * MI_SIZE);
1798    }
1799#else
1800    vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
1801                              second_pred, pw, &frame_mv[refs[!id]].as_mv, &sf,
1802                              pw, ph, 0, kernel, MV_PRECISION_Q3,
1803                              mi_col * MI_SIZE, mi_row * MI_SIZE);
1804#endif  // CONFIG_VP9_HIGHBITDEPTH
1805
1806    // Do compound motion search on the current reference frame.
1807    if (id) xd->plane[0].pre[0] = ref_yv12[id];
1808    vp9_set_mv_search_range(&x->mv_limits, &ref_mv[id].as_mv);
1809
1810    // Use the mv result from the single mode as mv predictor.
1811    tmp_mv = frame_mv[refs[id]].as_mv;
1812
1813    tmp_mv.col >>= 3;
1814    tmp_mv.row >>= 3;
1815
1816    // Small-range full-pixel motion search.
1817    bestsme = vp9_refining_search_8p_c(x, &tmp_mv, sadpb, search_range,
1818                                       &cpi->fn_ptr[bsize], &ref_mv[id].as_mv,
1819                                       second_pred);
1820    if (bestsme < UINT_MAX)
1821      bestsme = vp9_get_mvpred_av_var(x, &tmp_mv, &ref_mv[id].as_mv,
1822                                      second_pred, &cpi->fn_ptr[bsize], 1);
1823
1824    x->mv_limits = tmp_mv_limits;
1825
1826    if (bestsme < UINT_MAX) {
1827      uint32_t dis; /* TODO: use dis in distortion calculation later. */
1828      uint32_t sse;
1829      bestsme = cpi->find_fractional_mv_step(
1830          x, &tmp_mv, &ref_mv[id].as_mv, cpi->common.allow_high_precision_mv,
1831          x->errorperbit, &cpi->fn_ptr[bsize], 0,
1832          cpi->sf.mv.subpel_iters_per_step, NULL, x->nmvjointcost, x->mvcost,
1833          &dis, &sse, second_pred, pw, ph);
1834    }
1835
1836    // Restore the pointer to the first (possibly scaled) prediction buffer.
1837    if (id) xd->plane[0].pre[0] = ref_yv12[0];
1838
1839    if (bestsme < last_besterr[id]) {
1840      frame_mv[refs[id]].as_mv = tmp_mv;
1841      last_besterr[id] = bestsme;
1842    } else {
1843      break;
1844    }
1845  }
1846
1847  *rate_mv = 0;
1848
1849  for (ref = 0; ref < 2; ++ref) {
1850    if (scaled_ref_frame[ref]) {
1851      // Restore the prediction frame pointers to their unscaled versions.
1852      int i;
1853      for (i = 0; i < MAX_MB_PLANE; i++)
1854        xd->plane[i].pre[ref] = backup_yv12[ref][i];
1855    }
1856
1857    *rate_mv += vp9_mv_bit_cost(&frame_mv[refs[ref]].as_mv,
1858                                &x->mbmi_ext->ref_mvs[refs[ref]][0].as_mv,
1859                                x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
1860  }
1861}
1862
1863static int64_t rd_pick_best_sub8x8_mode(
1864    VP9_COMP *cpi, MACROBLOCK *x, int_mv *best_ref_mv,
1865    int_mv *second_best_ref_mv, int64_t best_rd, int *returntotrate,
1866    int *returnyrate, int64_t *returndistortion, int *skippable, int64_t *psse,
1867    int mvthresh, int_mv seg_mvs[4][MAX_REF_FRAMES], BEST_SEG_INFO *bsi_buf,
1868    int filter_idx, int mi_row, int mi_col) {
1869  int i;
1870  BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
1871  MACROBLOCKD *xd = &x->e_mbd;
1872  MODE_INFO *mi = xd->mi[0];
1873  int mode_idx;
1874  int k, br = 0, idx, idy;
1875  int64_t bd = 0, block_sse = 0;
1876  PREDICTION_MODE this_mode;
1877  VP9_COMMON *cm = &cpi->common;
1878  struct macroblock_plane *const p = &x->plane[0];
1879  struct macroblockd_plane *const pd = &xd->plane[0];
1880  const int label_count = 4;
1881  int64_t this_segment_rd = 0;
1882  int label_mv_thresh;
1883  int segmentyrate = 0;
1884  const BLOCK_SIZE bsize = mi->sb_type;
1885  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1886  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1887  ENTROPY_CONTEXT t_above[2], t_left[2];
1888  int subpelmv = 1, have_ref = 0;
1889  SPEED_FEATURES *const sf = &cpi->sf;
1890  const int has_second_rf = has_second_ref(mi);
1891  const int inter_mode_mask = sf->inter_mode_mask[bsize];
1892  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1893
1894  vp9_zero(*bsi);
1895
1896  bsi->segment_rd = best_rd;
1897  bsi->ref_mv[0] = best_ref_mv;
1898  bsi->ref_mv[1] = second_best_ref_mv;
1899  bsi->mvp.as_int = best_ref_mv->as_int;
1900  bsi->mvthresh = mvthresh;
1901
1902  for (i = 0; i < 4; i++) bsi->modes[i] = ZEROMV;
1903
1904  memcpy(t_above, pd->above_context, sizeof(t_above));
1905  memcpy(t_left, pd->left_context, sizeof(t_left));
1906
1907  // 64 makes this threshold really big effectively
1908  // making it so that we very rarely check mvs on
1909  // segments.   setting this to 1 would make mv thresh
1910  // roughly equal to what it is for macroblocks
1911  label_mv_thresh = 1 * bsi->mvthresh / label_count;
1912
1913  // Segmentation method overheads
1914  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1915    for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1916      // TODO(jingning,rbultje): rewrite the rate-distortion optimization
1917      // loop for 4x4/4x8/8x4 block coding. to be replaced with new rd loop
1918      int_mv mode_mv[MB_MODE_COUNT][2];
1919      int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
1920      PREDICTION_MODE mode_selected = ZEROMV;
1921      int64_t best_rd = INT64_MAX;
1922      const int i = idy * 2 + idx;
1923      int ref;
1924
1925      for (ref = 0; ref < 1 + has_second_rf; ++ref) {
1926        const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
1927        frame_mv[ZEROMV][frame].as_int = 0;
1928        vp9_append_sub8x8_mvs_for_idx(
1929            cm, xd, i, ref, mi_row, mi_col, &frame_mv[NEARESTMV][frame],
1930            &frame_mv[NEARMV][frame], mbmi_ext->mode_context);
1931      }
1932
1933      // search for the best motion vector on this segment
1934      for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
1935        const struct buf_2d orig_src = x->plane[0].src;
1936        struct buf_2d orig_pre[2];
1937
1938        mode_idx = INTER_OFFSET(this_mode);
1939        bsi->rdstat[i][mode_idx].brdcost = INT64_MAX;
1940        if (!(inter_mode_mask & (1 << this_mode))) continue;
1941
1942        if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv,
1943                                this_mode, mi->ref_frame))
1944          continue;
1945
1946        memcpy(orig_pre, pd->pre, sizeof(orig_pre));
1947        memcpy(bsi->rdstat[i][mode_idx].ta, t_above,
1948               sizeof(bsi->rdstat[i][mode_idx].ta));
1949        memcpy(bsi->rdstat[i][mode_idx].tl, t_left,
1950               sizeof(bsi->rdstat[i][mode_idx].tl));
1951
1952        // motion search for newmv (single predictor case only)
1953        if (!has_second_rf && this_mode == NEWMV &&
1954            seg_mvs[i][mi->ref_frame[0]].as_int == INVALID_MV) {
1955          MV *const new_mv = &mode_mv[NEWMV][0].as_mv;
1956          int step_param = 0;
1957          uint32_t bestsme = UINT_MAX;
1958          int sadpb = x->sadperbit4;
1959          MV mvp_full;
1960          int max_mv;
1961          int cost_list[5];
1962          const MvLimits tmp_mv_limits = x->mv_limits;
1963
1964          /* Is the best so far sufficiently good that we cant justify doing
1965           * and new motion search. */
1966          if (best_rd < label_mv_thresh) break;
1967
1968          if (cpi->oxcf.mode != BEST) {
1969            // use previous block's result as next block's MV predictor.
1970            if (i > 0) {
1971              bsi->mvp.as_int = mi->bmi[i - 1].as_mv[0].as_int;
1972              if (i == 2) bsi->mvp.as_int = mi->bmi[i - 2].as_mv[0].as_int;
1973            }
1974          }
1975          if (i == 0)
1976            max_mv = x->max_mv_context[mi->ref_frame[0]];
1977          else
1978            max_mv =
1979                VPXMAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
1980
1981          if (sf->mv.auto_mv_step_size && cm->show_frame) {
1982            // Take wtd average of the step_params based on the last frame's
1983            // max mv magnitude and the best ref mvs of the current block for
1984            // the given reference.
1985            step_param =
1986                (vp9_init_search_range(max_mv) + cpi->mv_step_param) / 2;
1987          } else {
1988            step_param = cpi->mv_step_param;
1989          }
1990
1991          mvp_full.row = bsi->mvp.as_mv.row >> 3;
1992          mvp_full.col = bsi->mvp.as_mv.col >> 3;
1993
1994          if (sf->adaptive_motion_search) {
1995            mvp_full.row = x->pred_mv[mi->ref_frame[0]].row >> 3;
1996            mvp_full.col = x->pred_mv[mi->ref_frame[0]].col >> 3;
1997            step_param = VPXMAX(step_param, 8);
1998          }
1999
2000          // adjust src pointer for this block
2001          mi_buf_shift(x, i);
2002
2003          vp9_set_mv_search_range(&x->mv_limits, &bsi->ref_mv[0]->as_mv);
2004
2005          bestsme = vp9_full_pixel_search(
2006              cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method,
2007              sadpb,
2008              sf->mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL,
2009              &bsi->ref_mv[0]->as_mv, new_mv, INT_MAX, 1);
2010
2011          x->mv_limits = tmp_mv_limits;
2012
2013          if (bestsme < UINT_MAX) {
2014            uint32_t distortion;
2015            cpi->find_fractional_mv_step(
2016                x, new_mv, &bsi->ref_mv[0]->as_mv, cm->allow_high_precision_mv,
2017                x->errorperbit, &cpi->fn_ptr[bsize], sf->mv.subpel_force_stop,
2018                sf->mv.subpel_iters_per_step, cond_cost_list(cpi, cost_list),
2019                x->nmvjointcost, x->mvcost, &distortion,
2020                &x->pred_sse[mi->ref_frame[0]], NULL, 0, 0);
2021
2022            // save motion search result for use in compound prediction
2023            seg_mvs[i][mi->ref_frame[0]].as_mv = *new_mv;
2024          }
2025
2026          if (sf->adaptive_motion_search)
2027            x->pred_mv[mi->ref_frame[0]] = *new_mv;
2028
2029          // restore src pointers
2030          mi_buf_restore(x, orig_src, orig_pre);
2031        }
2032
2033        if (has_second_rf) {
2034          if (seg_mvs[i][mi->ref_frame[1]].as_int == INVALID_MV ||
2035              seg_mvs[i][mi->ref_frame[0]].as_int == INVALID_MV)
2036            continue;
2037        }
2038
2039        if (has_second_rf && this_mode == NEWMV &&
2040            mi->interp_filter == EIGHTTAP) {
2041          // adjust src pointers
2042          mi_buf_shift(x, i);
2043          if (sf->comp_inter_joint_search_thresh <= bsize) {
2044            int rate_mv;
2045            joint_motion_search(cpi, x, bsize, frame_mv[this_mode], mi_row,
2046                                mi_col, seg_mvs[i], &rate_mv);
2047            seg_mvs[i][mi->ref_frame[0]].as_int =
2048                frame_mv[this_mode][mi->ref_frame[0]].as_int;
2049            seg_mvs[i][mi->ref_frame[1]].as_int =
2050                frame_mv[this_mode][mi->ref_frame[1]].as_int;
2051          }
2052          // restore src pointers
2053          mi_buf_restore(x, orig_src, orig_pre);
2054        }
2055
2056        bsi->rdstat[i][mode_idx].brate = set_and_cost_bmi_mvs(
2057            cpi, x, xd, i, this_mode, mode_mv[this_mode], frame_mv, seg_mvs[i],
2058            bsi->ref_mv, x->nmvjointcost, x->mvcost);
2059
2060        for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2061          bsi->rdstat[i][mode_idx].mvs[ref].as_int =
2062              mode_mv[this_mode][ref].as_int;
2063          if (num_4x4_blocks_wide > 1)
2064            bsi->rdstat[i + 1][mode_idx].mvs[ref].as_int =
2065                mode_mv[this_mode][ref].as_int;
2066          if (num_4x4_blocks_high > 1)
2067            bsi->rdstat[i + 2][mode_idx].mvs[ref].as_int =
2068                mode_mv[this_mode][ref].as_int;
2069        }
2070
2071        // Trap vectors that reach beyond the UMV borders
2072        if (mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][0].as_mv) ||
2073            (has_second_rf &&
2074             mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][1].as_mv)))
2075          continue;
2076
2077        if (filter_idx > 0) {
2078          BEST_SEG_INFO *ref_bsi = bsi_buf;
2079          subpelmv = 0;
2080          have_ref = 1;
2081
2082          for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2083            subpelmv |= mv_has_subpel(&mode_mv[this_mode][ref].as_mv);
2084            have_ref &= mode_mv[this_mode][ref].as_int ==
2085                        ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
2086          }
2087
2088          if (filter_idx > 1 && !subpelmv && !have_ref) {
2089            ref_bsi = bsi_buf + 1;
2090            have_ref = 1;
2091            for (ref = 0; ref < 1 + has_second_rf; ++ref)
2092              have_ref &= mode_mv[this_mode][ref].as_int ==
2093                          ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
2094          }
2095
2096          if (!subpelmv && have_ref &&
2097              ref_bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
2098            memcpy(&bsi->rdstat[i][mode_idx], &ref_bsi->rdstat[i][mode_idx],
2099                   sizeof(SEG_RDSTAT));
2100            if (num_4x4_blocks_wide > 1)
2101              bsi->rdstat[i + 1][mode_idx].eobs =
2102                  ref_bsi->rdstat[i + 1][mode_idx].eobs;
2103            if (num_4x4_blocks_high > 1)
2104              bsi->rdstat[i + 2][mode_idx].eobs =
2105                  ref_bsi->rdstat[i + 2][mode_idx].eobs;
2106
2107            if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
2108              mode_selected = this_mode;
2109              best_rd = bsi->rdstat[i][mode_idx].brdcost;
2110            }
2111            continue;
2112          }
2113        }
2114
2115        bsi->rdstat[i][mode_idx].brdcost = encode_inter_mb_segment(
2116            cpi, x, bsi->segment_rd - this_segment_rd, i,
2117            &bsi->rdstat[i][mode_idx].byrate, &bsi->rdstat[i][mode_idx].bdist,
2118            &bsi->rdstat[i][mode_idx].bsse, bsi->rdstat[i][mode_idx].ta,
2119            bsi->rdstat[i][mode_idx].tl, mi_row, mi_col);
2120        if (bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
2121          bsi->rdstat[i][mode_idx].brdcost +=
2122              RDCOST(x->rdmult, x->rddiv, bsi->rdstat[i][mode_idx].brate, 0);
2123          bsi->rdstat[i][mode_idx].brate += bsi->rdstat[i][mode_idx].byrate;
2124          bsi->rdstat[i][mode_idx].eobs = p->eobs[i];
2125          if (num_4x4_blocks_wide > 1)
2126            bsi->rdstat[i + 1][mode_idx].eobs = p->eobs[i + 1];
2127          if (num_4x4_blocks_high > 1)
2128            bsi->rdstat[i + 2][mode_idx].eobs = p->eobs[i + 2];
2129        }
2130
2131        if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
2132          mode_selected = this_mode;
2133          best_rd = bsi->rdstat[i][mode_idx].brdcost;
2134        }
2135      } /*for each 4x4 mode*/
2136
2137      if (best_rd == INT64_MAX) {
2138        int iy, midx;
2139        for (iy = i + 1; iy < 4; ++iy)
2140          for (midx = 0; midx < INTER_MODES; ++midx)
2141            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2142        bsi->segment_rd = INT64_MAX;
2143        return INT64_MAX;
2144      }
2145
2146      mode_idx = INTER_OFFSET(mode_selected);
2147      memcpy(t_above, bsi->rdstat[i][mode_idx].ta, sizeof(t_above));
2148      memcpy(t_left, bsi->rdstat[i][mode_idx].tl, sizeof(t_left));
2149
2150      set_and_cost_bmi_mvs(cpi, x, xd, i, mode_selected, mode_mv[mode_selected],
2151                           frame_mv, seg_mvs[i], bsi->ref_mv, x->nmvjointcost,
2152                           x->mvcost);
2153
2154      br += bsi->rdstat[i][mode_idx].brate;
2155      bd += bsi->rdstat[i][mode_idx].bdist;
2156      block_sse += bsi->rdstat[i][mode_idx].bsse;
2157      segmentyrate += bsi->rdstat[i][mode_idx].byrate;
2158      this_segment_rd += bsi->rdstat[i][mode_idx].brdcost;
2159
2160      if (this_segment_rd > bsi->segment_rd) {
2161        int iy, midx;
2162        for (iy = i + 1; iy < 4; ++iy)
2163          for (midx = 0; midx < INTER_MODES; ++midx)
2164            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2165        bsi->segment_rd = INT64_MAX;
2166        return INT64_MAX;
2167      }
2168    }
2169  } /* for each label */
2170
2171  bsi->r = br;
2172  bsi->d = bd;
2173  bsi->segment_yrate = segmentyrate;
2174  bsi->segment_rd = this_segment_rd;
2175  bsi->sse = block_sse;
2176
2177  // update the coding decisions
2178  for (k = 0; k < 4; ++k) bsi->modes[k] = mi->bmi[k].as_mode;
2179
2180  if (bsi->segment_rd > best_rd) return INT64_MAX;
2181  /* set it to the best */
2182  for (i = 0; i < 4; i++) {
2183    mode_idx = INTER_OFFSET(bsi->modes[i]);
2184    mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
2185    if (has_second_ref(mi))
2186      mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
2187    x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
2188    mi->bmi[i].as_mode = bsi->modes[i];
2189  }
2190
2191  /*
2192   * used to set mbmi->mv.as_int
2193   */
2194  *returntotrate = bsi->r;
2195  *returndistortion = bsi->d;
2196  *returnyrate = bsi->segment_yrate;
2197  *skippable = vp9_is_skippable_in_plane(x, BLOCK_8X8, 0);
2198  *psse = bsi->sse;
2199  mi->mode = bsi->modes[3];
2200
2201  return bsi->segment_rd;
2202}
2203
2204static void estimate_ref_frame_costs(const VP9_COMMON *cm,
2205                                     const MACROBLOCKD *xd, int segment_id,
2206                                     unsigned int *ref_costs_single,
2207                                     unsigned int *ref_costs_comp,
2208                                     vpx_prob *comp_mode_p) {
2209  int seg_ref_active =
2210      segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
2211  if (seg_ref_active) {
2212    memset(ref_costs_single, 0, MAX_REF_FRAMES * sizeof(*ref_costs_single));
2213    memset(ref_costs_comp, 0, MAX_REF_FRAMES * sizeof(*ref_costs_comp));
2214    *comp_mode_p = 128;
2215  } else {
2216    vpx_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
2217    vpx_prob comp_inter_p = 128;
2218
2219    if (cm->reference_mode == REFERENCE_MODE_SELECT) {
2220      comp_inter_p = vp9_get_reference_mode_prob(cm, xd);
2221      *comp_mode_p = comp_inter_p;
2222    } else {
2223      *comp_mode_p = 128;
2224    }
2225
2226    ref_costs_single[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
2227
2228    if (cm->reference_mode != COMPOUND_REFERENCE) {
2229      vpx_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
2230      vpx_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
2231      unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
2232
2233      if (cm->reference_mode == REFERENCE_MODE_SELECT)
2234        base_cost += vp9_cost_bit(comp_inter_p, 0);
2235
2236      ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
2237          ref_costs_single[ALTREF_FRAME] = base_cost;
2238      ref_costs_single[LAST_FRAME] += vp9_cost_bit(ref_single_p1, 0);
2239      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2240      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2241      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
2242      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
2243    } else {
2244      ref_costs_single[LAST_FRAME] = 512;
2245      ref_costs_single[GOLDEN_FRAME] = 512;
2246      ref_costs_single[ALTREF_FRAME] = 512;
2247    }
2248    if (cm->reference_mode != SINGLE_REFERENCE) {
2249      vpx_prob ref_comp_p = vp9_get_pred_prob_comp_ref_p(cm, xd);
2250      unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
2251
2252      if (cm->reference_mode == REFERENCE_MODE_SELECT)
2253        base_cost += vp9_cost_bit(comp_inter_p, 1);
2254
2255      ref_costs_comp[LAST_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 0);
2256      ref_costs_comp[GOLDEN_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 1);
2257    } else {
2258      ref_costs_comp[LAST_FRAME] = 512;
2259      ref_costs_comp[GOLDEN_FRAME] = 512;
2260    }
2261  }
2262}
2263
2264static void store_coding_context(
2265    MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int mode_index,
2266    int64_t comp_pred_diff[REFERENCE_MODES],
2267    int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS], int skippable) {
2268  MACROBLOCKD *const xd = &x->e_mbd;
2269
2270  // Take a snapshot of the coding context so it can be
2271  // restored if we decide to encode this way
2272  ctx->skip = x->skip;
2273  ctx->skippable = skippable;
2274  ctx->best_mode_index = mode_index;
2275  ctx->mic = *xd->mi[0];
2276  ctx->mbmi_ext = *x->mbmi_ext;
2277  ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
2278  ctx->comp_pred_diff = (int)comp_pred_diff[COMPOUND_REFERENCE];
2279  ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
2280
2281  memcpy(ctx->best_filter_diff, best_filter_diff,
2282         sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
2283}
2284
2285static void setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
2286                               MV_REFERENCE_FRAME ref_frame,
2287                               BLOCK_SIZE block_size, int mi_row, int mi_col,
2288                               int_mv frame_nearest_mv[MAX_REF_FRAMES],
2289                               int_mv frame_near_mv[MAX_REF_FRAMES],
2290                               struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
2291  const VP9_COMMON *cm = &cpi->common;
2292  const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
2293  MACROBLOCKD *const xd = &x->e_mbd;
2294  MODE_INFO *const mi = xd->mi[0];
2295  int_mv *const candidates = x->mbmi_ext->ref_mvs[ref_frame];
2296  const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
2297  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2298
2299  assert(yv12 != NULL);
2300
2301  // TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
2302  // use the UV scaling factors.
2303  vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
2304
2305  // Gets an initial list of candidate vectors from neighbours and orders them
2306  vp9_find_mv_refs(cm, xd, mi, ref_frame, candidates, mi_row, mi_col,
2307                   mbmi_ext->mode_context);
2308
2309  // Candidate refinement carried out at encoder and decoder
2310  vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
2311                        &frame_nearest_mv[ref_frame],
2312                        &frame_near_mv[ref_frame]);
2313
2314  // Further refinement that is encode side only to test the top few candidates
2315  // in full and choose the best as the centre point for subsequent searches.
2316  // The current implementation doesn't support scaling.
2317  if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
2318    vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
2319                block_size);
2320}
2321
2322static void single_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
2323                                 int mi_row, int mi_col, int_mv *tmp_mv,
2324                                 int *rate_mv) {
2325  MACROBLOCKD *xd = &x->e_mbd;
2326  const VP9_COMMON *cm = &cpi->common;
2327  MODE_INFO *mi = xd->mi[0];
2328  struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0 } };
2329  int bestsme = INT_MAX;
2330  int step_param;
2331  int sadpb = x->sadperbit16;
2332  MV mvp_full;
2333  int ref = mi->ref_frame[0];
2334  MV ref_mv = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2335  const MvLimits tmp_mv_limits = x->mv_limits;
2336  int cost_list[5];
2337
2338  const YV12_BUFFER_CONFIG *scaled_ref_frame =
2339      vp9_get_scaled_ref_frame(cpi, ref);
2340
2341  MV pred_mv[3];
2342  pred_mv[0] = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2343  pred_mv[1] = x->mbmi_ext->ref_mvs[ref][1].as_mv;
2344  pred_mv[2] = x->pred_mv[ref];
2345
2346  if (scaled_ref_frame) {
2347    int i;
2348    // Swap out the reference frame for a version that's been scaled to
2349    // match the resolution of the current frame, allowing the existing
2350    // motion search code to be used without additional modifications.
2351    for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
2352
2353    vp9_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
2354  }
2355
2356  // Work out the size of the first step in the mv step search.
2357  // 0 here is maximum length first step. 1 is VPXMAX >> 1 etc.
2358  if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) {
2359    // Take wtd average of the step_params based on the last frame's
2360    // max mv magnitude and that based on the best ref mvs of the current
2361    // block for the given reference.
2362    step_param =
2363        (vp9_init_search_range(x->max_mv_context[ref]) + cpi->mv_step_param) /
2364        2;
2365  } else {
2366    step_param = cpi->mv_step_param;
2367  }
2368
2369  if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64) {
2370    int boffset =
2371        2 * (b_width_log2_lookup[BLOCK_64X64] -
2372             VPXMIN(b_height_log2_lookup[bsize], b_width_log2_lookup[bsize]));
2373    step_param = VPXMAX(step_param, boffset);
2374  }
2375
2376  if (cpi->sf.adaptive_motion_search) {
2377    int bwl = b_width_log2_lookup[bsize];
2378    int bhl = b_height_log2_lookup[bsize];
2379    int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
2380
2381    if (tlevel < 5) step_param += 2;
2382
2383    // prev_mv_sad is not setup for dynamically scaled frames.
2384    if (cpi->oxcf.resize_mode != RESIZE_DYNAMIC) {
2385      int i;
2386      for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) {
2387        if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
2388          x->pred_mv[ref].row = 0;
2389          x->pred_mv[ref].col = 0;
2390          tmp_mv->as_int = INVALID_MV;
2391
2392          if (scaled_ref_frame) {
2393            int i;
2394            for (i = 0; i < MAX_MB_PLANE; ++i)
2395              xd->plane[i].pre[0] = backup_yv12[i];
2396          }
2397          return;
2398        }
2399      }
2400    }
2401  }
2402
2403  // Note: MV limits are modified here. Always restore the original values
2404  // after full-pixel motion search.
2405  vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
2406
2407  mvp_full = pred_mv[x->mv_best_ref_index[ref]];
2408
2409  mvp_full.col >>= 3;
2410  mvp_full.row >>= 3;
2411
2412  bestsme = vp9_full_pixel_search(
2413      cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method, sadpb,
2414      cond_cost_list(cpi, cost_list), &ref_mv, &tmp_mv->as_mv, INT_MAX, 1);
2415
2416  x->mv_limits = tmp_mv_limits;
2417
2418  if (bestsme < INT_MAX) {
2419    uint32_t dis; /* TODO: use dis in distortion calculation later. */
2420    cpi->find_fractional_mv_step(
2421        x, &tmp_mv->as_mv, &ref_mv, cm->allow_high_precision_mv, x->errorperbit,
2422        &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop,
2423        cpi->sf.mv.subpel_iters_per_step, cond_cost_list(cpi, cost_list),
2424        x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref], NULL, 0, 0);
2425  }
2426  *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->nmvjointcost,
2427                             x->mvcost, MV_COST_WEIGHT);
2428
2429  if (cpi->sf.adaptive_motion_search) x->pred_mv[ref] = tmp_mv->as_mv;
2430
2431  if (scaled_ref_frame) {
2432    int i;
2433    for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2434  }
2435}
2436
2437static INLINE void restore_dst_buf(MACROBLOCKD *xd,
2438                                   uint8_t *orig_dst[MAX_MB_PLANE],
2439                                   int orig_dst_stride[MAX_MB_PLANE]) {
2440  int i;
2441  for (i = 0; i < MAX_MB_PLANE; i++) {
2442    xd->plane[i].dst.buf = orig_dst[i];
2443    xd->plane[i].dst.stride = orig_dst_stride[i];
2444  }
2445}
2446
2447// In some situations we want to discount tha pparent cost of a new motion
2448// vector. Where there is a subtle motion field and especially where there is
2449// low spatial complexity then it can be hard to cover the cost of a new motion
2450// vector in a single block, even if that motion vector reduces distortion.
2451// However, once established that vector may be usable through the nearest and
2452// near mv modes to reduce distortion in subsequent blocks and also improve
2453// visual quality.
2454static int discount_newmv_test(const VP9_COMP *cpi, int this_mode,
2455                               int_mv this_mv,
2456                               int_mv (*mode_mv)[MAX_REF_FRAMES],
2457                               int ref_frame) {
2458  return (!cpi->rc.is_src_frame_alt_ref && (this_mode == NEWMV) &&
2459          (this_mv.as_int != 0) &&
2460          ((mode_mv[NEARESTMV][ref_frame].as_int == 0) ||
2461           (mode_mv[NEARESTMV][ref_frame].as_int == INVALID_MV)) &&
2462          ((mode_mv[NEARMV][ref_frame].as_int == 0) ||
2463           (mode_mv[NEARMV][ref_frame].as_int == INVALID_MV)));
2464}
2465
2466static int64_t handle_inter_mode(
2467    VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int *rate2,
2468    int64_t *distortion, int *skippable, int *rate_y, int *rate_uv,
2469    int *disable_skip, int_mv (*mode_mv)[MAX_REF_FRAMES], int mi_row,
2470    int mi_col, int_mv single_newmv[MAX_REF_FRAMES],
2471    INTERP_FILTER (*single_filter)[MAX_REF_FRAMES],
2472    int (*single_skippable)[MAX_REF_FRAMES], int64_t *psse,
2473    const int64_t ref_best_rd, int64_t *mask_filter, int64_t filter_cache[]) {
2474  VP9_COMMON *cm = &cpi->common;
2475  MACROBLOCKD *xd = &x->e_mbd;
2476  MODE_INFO *mi = xd->mi[0];
2477  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2478  const int is_comp_pred = has_second_ref(mi);
2479  const int this_mode = mi->mode;
2480  int_mv *frame_mv = mode_mv[this_mode];
2481  int i;
2482  int refs[2] = { mi->ref_frame[0],
2483                  (mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1]) };
2484  int_mv cur_mv[2];
2485#if CONFIG_VP9_HIGHBITDEPTH
2486  DECLARE_ALIGNED(16, uint16_t, tmp_buf16[MAX_MB_PLANE * 64 * 64]);
2487  uint8_t *tmp_buf;
2488#else
2489  DECLARE_ALIGNED(16, uint8_t, tmp_buf[MAX_MB_PLANE * 64 * 64]);
2490#endif  // CONFIG_VP9_HIGHBITDEPTH
2491  int pred_exists = 0;
2492  int intpel_mv;
2493  int64_t rd, tmp_rd, best_rd = INT64_MAX;
2494  int best_needs_copy = 0;
2495  uint8_t *orig_dst[MAX_MB_PLANE];
2496  int orig_dst_stride[MAX_MB_PLANE];
2497  int rs = 0;
2498  INTERP_FILTER best_filter = SWITCHABLE;
2499  uint8_t skip_txfm[MAX_MB_PLANE << 2] = { 0 };
2500  int64_t bsse[MAX_MB_PLANE << 2] = { 0 };
2501
2502  int bsl = mi_width_log2_lookup[bsize];
2503  int pred_filter_search =
2504      cpi->sf.cb_pred_filter_search
2505          ? (((mi_row + mi_col) >> bsl) +
2506             get_chessboard_index(cm->current_video_frame)) &
2507                0x1
2508          : 0;
2509
2510  int skip_txfm_sb = 0;
2511  int64_t skip_sse_sb = INT64_MAX;
2512  int64_t distortion_y = 0, distortion_uv = 0;
2513
2514#if CONFIG_VP9_HIGHBITDEPTH
2515  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2516    tmp_buf = CONVERT_TO_BYTEPTR(tmp_buf16);
2517  } else {
2518    tmp_buf = (uint8_t *)tmp_buf16;
2519  }
2520#endif  // CONFIG_VP9_HIGHBITDEPTH
2521
2522  if (pred_filter_search) {
2523    INTERP_FILTER af = SWITCHABLE, lf = SWITCHABLE;
2524    if (xd->above_mi && is_inter_block(xd->above_mi))
2525      af = xd->above_mi->interp_filter;
2526    if (xd->left_mi && is_inter_block(xd->left_mi))
2527      lf = xd->left_mi->interp_filter;
2528
2529    if ((this_mode != NEWMV) || (af == lf)) best_filter = af;
2530  }
2531
2532  if (is_comp_pred) {
2533    if (frame_mv[refs[0]].as_int == INVALID_MV ||
2534        frame_mv[refs[1]].as_int == INVALID_MV)
2535      return INT64_MAX;
2536
2537    if (cpi->sf.adaptive_mode_search) {
2538      if (single_filter[this_mode][refs[0]] ==
2539          single_filter[this_mode][refs[1]])
2540        best_filter = single_filter[this_mode][refs[0]];
2541    }
2542  }
2543
2544  if (this_mode == NEWMV) {
2545    int rate_mv;
2546    if (is_comp_pred) {
2547      // Initialize mv using single prediction mode result.
2548      frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
2549      frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
2550
2551      if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
2552        joint_motion_search(cpi, x, bsize, frame_mv, mi_row, mi_col,
2553                            single_newmv, &rate_mv);
2554      } else {
2555        rate_mv = vp9_mv_bit_cost(&frame_mv[refs[0]].as_mv,
2556                                  &x->mbmi_ext->ref_mvs[refs[0]][0].as_mv,
2557                                  x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2558        rate_mv += vp9_mv_bit_cost(&frame_mv[refs[1]].as_mv,
2559                                   &x->mbmi_ext->ref_mvs[refs[1]][0].as_mv,
2560                                   x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2561      }
2562      *rate2 += rate_mv;
2563    } else {
2564      int_mv tmp_mv;
2565      single_motion_search(cpi, x, bsize, mi_row, mi_col, &tmp_mv, &rate_mv);
2566      if (tmp_mv.as_int == INVALID_MV) return INT64_MAX;
2567
2568      frame_mv[refs[0]].as_int = xd->mi[0]->bmi[0].as_mv[0].as_int =
2569          tmp_mv.as_int;
2570      single_newmv[refs[0]].as_int = tmp_mv.as_int;
2571
2572      // Estimate the rate implications of a new mv but discount this
2573      // under certain circumstances where we want to help initiate a weak
2574      // motion field, where the distortion gain for a single block may not
2575      // be enough to overcome the cost of a new mv.
2576      if (discount_newmv_test(cpi, this_mode, tmp_mv, mode_mv, refs[0])) {
2577        *rate2 += VPXMAX((rate_mv / NEW_MV_DISCOUNT_FACTOR), 1);
2578      } else {
2579        *rate2 += rate_mv;
2580      }
2581    }
2582  }
2583
2584  for (i = 0; i < is_comp_pred + 1; ++i) {
2585    cur_mv[i] = frame_mv[refs[i]];
2586    // Clip "next_nearest" so that it does not extend to far out of image
2587    if (this_mode != NEWMV) clamp_mv2(&cur_mv[i].as_mv, xd);
2588
2589    if (mv_check_bounds(&x->mv_limits, &cur_mv[i].as_mv)) return INT64_MAX;
2590    mi->mv[i].as_int = cur_mv[i].as_int;
2591  }
2592
2593  // do first prediction into the destination buffer. Do the next
2594  // prediction into a temporary buffer. Then keep track of which one
2595  // of these currently holds the best predictor, and use the other
2596  // one for future predictions. In the end, copy from tmp_buf to
2597  // dst if necessary.
2598  for (i = 0; i < MAX_MB_PLANE; i++) {
2599    orig_dst[i] = xd->plane[i].dst.buf;
2600    orig_dst_stride[i] = xd->plane[i].dst.stride;
2601  }
2602
2603  // We don't include the cost of the second reference here, because there
2604  // are only two options: Last/ARF or Golden/ARF; The second one is always
2605  // known, which is ARF.
2606  //
2607  // Under some circumstances we discount the cost of new mv mode to encourage
2608  // initiation of a motion field.
2609  if (discount_newmv_test(cpi, this_mode, frame_mv[refs[0]], mode_mv,
2610                          refs[0])) {
2611    *rate2 +=
2612        VPXMIN(cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]),
2613               cost_mv_ref(cpi, NEARESTMV, mbmi_ext->mode_context[refs[0]]));
2614  } else {
2615    *rate2 += cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]);
2616  }
2617
2618  if (RDCOST(x->rdmult, x->rddiv, *rate2, 0) > ref_best_rd &&
2619      mi->mode != NEARESTMV)
2620    return INT64_MAX;
2621
2622  pred_exists = 0;
2623  // Are all MVs integer pel for Y and UV
2624  intpel_mv = !mv_has_subpel(&mi->mv[0].as_mv);
2625  if (is_comp_pred) intpel_mv &= !mv_has_subpel(&mi->mv[1].as_mv);
2626
2627  // Search for best switchable filter by checking the variance of
2628  // pred error irrespective of whether the filter will be used
2629  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
2630
2631  if (cm->interp_filter != BILINEAR) {
2632    if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
2633      best_filter = EIGHTTAP;
2634    } else if (best_filter == SWITCHABLE) {
2635      int newbest;
2636      int tmp_rate_sum = 0;
2637      int64_t tmp_dist_sum = 0;
2638
2639      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
2640        int j;
2641        int64_t rs_rd;
2642        int tmp_skip_sb = 0;
2643        int64_t tmp_skip_sse = INT64_MAX;
2644
2645        mi->interp_filter = i;
2646        rs = vp9_get_switchable_rate(cpi, xd);
2647        rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
2648
2649        if (i > 0 && intpel_mv) {
2650          rd = RDCOST(x->rdmult, x->rddiv, tmp_rate_sum, tmp_dist_sum);
2651          filter_cache[i] = rd;
2652          filter_cache[SWITCHABLE_FILTERS] =
2653              VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2654          if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
2655          *mask_filter = VPXMAX(*mask_filter, rd);
2656        } else {
2657          int rate_sum = 0;
2658          int64_t dist_sum = 0;
2659          if (i > 0 && cpi->sf.adaptive_interp_filter_search &&
2660              (cpi->sf.interp_filter_search_mask & (1 << i))) {
2661            rate_sum = INT_MAX;
2662            dist_sum = INT64_MAX;
2663            continue;
2664          }
2665
2666          if ((cm->interp_filter == SWITCHABLE && (!i || best_needs_copy)) ||
2667              (cm->interp_filter != SWITCHABLE &&
2668               (cm->interp_filter == mi->interp_filter ||
2669                (i == 0 && intpel_mv)))) {
2670            restore_dst_buf(xd, orig_dst, orig_dst_stride);
2671          } else {
2672            for (j = 0; j < MAX_MB_PLANE; j++) {
2673              xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
2674              xd->plane[j].dst.stride = 64;
2675            }
2676          }
2677          vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
2678          model_rd_for_sb(cpi, bsize, x, xd, &rate_sum, &dist_sum, &tmp_skip_sb,
2679                          &tmp_skip_sse);
2680
2681          rd = RDCOST(x->rdmult, x->rddiv, rate_sum, dist_sum);
2682          filter_cache[i] = rd;
2683          filter_cache[SWITCHABLE_FILTERS] =
2684              VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2685          if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
2686          *mask_filter = VPXMAX(*mask_filter, rd);
2687
2688          if (i == 0 && intpel_mv) {
2689            tmp_rate_sum = rate_sum;
2690            tmp_dist_sum = dist_sum;
2691          }
2692        }
2693
2694        if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
2695          if (rd / 2 > ref_best_rd) {
2696            restore_dst_buf(xd, orig_dst, orig_dst_stride);
2697            return INT64_MAX;
2698          }
2699        }
2700        newbest = i == 0 || rd < best_rd;
2701
2702        if (newbest) {
2703          best_rd = rd;
2704          best_filter = mi->interp_filter;
2705          if (cm->interp_filter == SWITCHABLE && i && !intpel_mv)
2706            best_needs_copy = !best_needs_copy;
2707        }
2708
2709        if ((cm->interp_filter == SWITCHABLE && newbest) ||
2710            (cm->interp_filter != SWITCHABLE &&
2711             cm->interp_filter == mi->interp_filter)) {
2712          pred_exists = 1;
2713          tmp_rd = best_rd;
2714
2715          skip_txfm_sb = tmp_skip_sb;
2716          skip_sse_sb = tmp_skip_sse;
2717          memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
2718          memcpy(bsse, x->bsse, sizeof(bsse));
2719        }
2720      }
2721      restore_dst_buf(xd, orig_dst, orig_dst_stride);
2722    }
2723  }
2724  // Set the appropriate filter
2725  mi->interp_filter =
2726      cm->interp_filter != SWITCHABLE ? cm->interp_filter : best_filter;
2727  rs = cm->interp_filter == SWITCHABLE ? vp9_get_switchable_rate(cpi, xd) : 0;
2728
2729  if (pred_exists) {
2730    if (best_needs_copy) {
2731      // again temporarily set the buffers to local memory to prevent a memcpy
2732      for (i = 0; i < MAX_MB_PLANE; i++) {
2733        xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
2734        xd->plane[i].dst.stride = 64;
2735      }
2736    }
2737    rd = tmp_rd + RDCOST(x->rdmult, x->rddiv, rs, 0);
2738  } else {
2739    int tmp_rate;
2740    int64_t tmp_dist;
2741    // Handles the special case when a filter that is not in the
2742    // switchable list (ex. bilinear) is indicated at the frame level, or
2743    // skip condition holds.
2744    vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
2745    model_rd_for_sb(cpi, bsize, x, xd, &tmp_rate, &tmp_dist, &skip_txfm_sb,
2746                    &skip_sse_sb);
2747    rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
2748    memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
2749    memcpy(bsse, x->bsse, sizeof(bsse));
2750  }
2751
2752  if (!is_comp_pred) single_filter[this_mode][refs[0]] = mi->interp_filter;
2753
2754  if (cpi->sf.adaptive_mode_search)
2755    if (is_comp_pred)
2756      if (single_skippable[this_mode][refs[0]] &&
2757          single_skippable[this_mode][refs[1]])
2758        memset(skip_txfm, SKIP_TXFM_AC_DC, sizeof(skip_txfm));
2759
2760  if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
2761    // if current pred_error modeled rd is substantially more than the best
2762    // so far, do not bother doing full rd
2763    if (rd / 2 > ref_best_rd) {
2764      restore_dst_buf(xd, orig_dst, orig_dst_stride);
2765      return INT64_MAX;
2766    }
2767  }
2768
2769  if (cm->interp_filter == SWITCHABLE) *rate2 += rs;
2770
2771  memcpy(x->skip_txfm, skip_txfm, sizeof(skip_txfm));
2772  memcpy(x->bsse, bsse, sizeof(bsse));
2773
2774  if (!skip_txfm_sb) {
2775    int skippable_y, skippable_uv;
2776    int64_t sseuv = INT64_MAX;
2777    int64_t rdcosty = INT64_MAX;
2778
2779    // Y cost and distortion
2780    vp9_subtract_plane(x, bsize, 0);
2781    super_block_yrd(cpi, x, rate_y, &distortion_y, &skippable_y, psse, bsize,
2782                    ref_best_rd);
2783
2784    if (*rate_y == INT_MAX) {
2785      *rate2 = INT_MAX;
2786      *distortion = INT64_MAX;
2787      restore_dst_buf(xd, orig_dst, orig_dst_stride);
2788      return INT64_MAX;
2789    }
2790
2791    *rate2 += *rate_y;
2792    *distortion += distortion_y;
2793
2794    rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
2795    rdcosty = VPXMIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
2796
2797    if (!super_block_uvrd(cpi, x, rate_uv, &distortion_uv, &skippable_uv,
2798                          &sseuv, bsize, ref_best_rd - rdcosty)) {
2799      *rate2 = INT_MAX;
2800      *distortion = INT64_MAX;
2801      restore_dst_buf(xd, orig_dst, orig_dst_stride);
2802      return INT64_MAX;
2803    }
2804
2805    *psse += sseuv;
2806    *rate2 += *rate_uv;
2807    *distortion += distortion_uv;
2808    *skippable = skippable_y && skippable_uv;
2809  } else {
2810    x->skip = 1;
2811    *disable_skip = 1;
2812
2813    // The cost of skip bit needs to be added.
2814    *rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2815
2816    *distortion = skip_sse_sb;
2817  }
2818
2819  if (!is_comp_pred) single_skippable[this_mode][refs[0]] = *skippable;
2820
2821  restore_dst_buf(xd, orig_dst, orig_dst_stride);
2822  return 0;  // The rate-distortion cost will be re-calculated by caller.
2823}
2824
2825void vp9_rd_pick_intra_mode_sb(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *rd_cost,
2826                               BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
2827                               int64_t best_rd) {
2828  VP9_COMMON *const cm = &cpi->common;
2829  MACROBLOCKD *const xd = &x->e_mbd;
2830  struct macroblockd_plane *const pd = xd->plane;
2831  int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
2832  int y_skip = 0, uv_skip = 0;
2833  int64_t dist_y = 0, dist_uv = 0;
2834  TX_SIZE max_uv_tx_size;
2835  x->skip_encode = 0;
2836  ctx->skip = 0;
2837  xd->mi[0]->ref_frame[0] = INTRA_FRAME;
2838  xd->mi[0]->ref_frame[1] = NONE;
2839  // Initialize interp_filter here so we do not have to check for inter block
2840  // modes in get_pred_context_switchable_interp()
2841  xd->mi[0]->interp_filter = SWITCHABLE_FILTERS;
2842
2843  if (bsize >= BLOCK_8X8) {
2844    if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly, &dist_y,
2845                               &y_skip, bsize, best_rd) >= best_rd) {
2846      rd_cost->rate = INT_MAX;
2847      return;
2848    }
2849  } else {
2850    y_skip = 0;
2851    if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
2852                                     &dist_y, best_rd) >= best_rd) {
2853      rd_cost->rate = INT_MAX;
2854      return;
2855    }
2856  }
2857  max_uv_tx_size = uv_txsize_lookup[bsize][xd->mi[0]->tx_size]
2858                                   [pd[1].subsampling_x][pd[1].subsampling_y];
2859  rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly, &dist_uv,
2860                          &uv_skip, VPXMAX(BLOCK_8X8, bsize), max_uv_tx_size);
2861
2862  if (y_skip && uv_skip) {
2863    rd_cost->rate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
2864                    vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2865    rd_cost->dist = dist_y + dist_uv;
2866  } else {
2867    rd_cost->rate =
2868        rate_y + rate_uv + vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
2869    rd_cost->dist = dist_y + dist_uv;
2870  }
2871
2872  ctx->mic = *xd->mi[0];
2873  ctx->mbmi_ext = *x->mbmi_ext;
2874  rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2875}
2876
2877// This function is designed to apply a bias or adjustment to an rd value based
2878// on the relative variance of the source and reconstruction.
2879#define VERY_LOW_VAR_THRESH 2
2880#define LOW_VAR_THRESH 5
2881#define VAR_MULT 100
2882static unsigned int max_var_adjust[VP9E_CONTENT_INVALID] = { 16, 16, 100 };
2883
2884static void rd_variance_adjustment(VP9_COMP *cpi, MACROBLOCK *x,
2885                                   BLOCK_SIZE bsize, int64_t *this_rd,
2886                                   MV_REFERENCE_FRAME ref_frame,
2887                                   unsigned int source_variance) {
2888  MACROBLOCKD *const xd = &x->e_mbd;
2889  unsigned int rec_variance;
2890  unsigned int src_variance;
2891  unsigned int src_rec_min;
2892  unsigned int absvar_diff = 0;
2893  unsigned int var_factor = 0;
2894  unsigned int adj_max;
2895  vp9e_tune_content content_type = cpi->oxcf.content;
2896
2897  if (*this_rd == INT64_MAX) return;
2898
2899#if CONFIG_VP9_HIGHBITDEPTH
2900  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2901    if (source_variance > 0) {
2902      rec_variance = vp9_high_get_sby_perpixel_variance(cpi, &xd->plane[0].dst,
2903                                                        bsize, xd->bd);
2904      src_variance = source_variance;
2905    } else {
2906      rec_variance =
2907          vp9_high_get_sby_variance(cpi, &xd->plane[0].dst, bsize, xd->bd);
2908      src_variance =
2909          vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, xd->bd);
2910    }
2911  } else {
2912    if (source_variance > 0) {
2913      rec_variance =
2914          vp9_get_sby_perpixel_variance(cpi, &xd->plane[0].dst, bsize);
2915      src_variance = source_variance;
2916    } else {
2917      rec_variance = vp9_get_sby_variance(cpi, &xd->plane[0].dst, bsize);
2918      src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
2919    }
2920  }
2921#else
2922  if (source_variance > 0) {
2923    rec_variance = vp9_get_sby_perpixel_variance(cpi, &xd->plane[0].dst, bsize);
2924    src_variance = source_variance;
2925  } else {
2926    rec_variance = vp9_get_sby_variance(cpi, &xd->plane[0].dst, bsize);
2927    src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
2928  }
2929#endif  // CONFIG_VP9_HIGHBITDEPTH
2930
2931  // Lower of source (raw per pixel value) and recon variance. Note that
2932  // if the source per pixel is 0 then the recon value here will not be per
2933  // pixel (see above) so will likely be much larger.
2934  src_rec_min = VPXMIN(source_variance, rec_variance);
2935
2936  if (src_rec_min > LOW_VAR_THRESH) return;
2937
2938  absvar_diff = (src_variance > rec_variance) ? (src_variance - rec_variance)
2939                                              : (rec_variance - src_variance);
2940
2941  adj_max = max_var_adjust[content_type];
2942
2943  var_factor =
2944      (unsigned int)((int64_t)VAR_MULT * absvar_diff) / VPXMAX(1, src_variance);
2945  var_factor = VPXMIN(adj_max, var_factor);
2946
2947  *this_rd += (*this_rd * var_factor) / 100;
2948
2949  if (content_type == VP9E_CONTENT_FILM) {
2950    if (src_rec_min <= VERY_LOW_VAR_THRESH) {
2951      if (ref_frame == INTRA_FRAME) *this_rd *= 2;
2952      if (bsize > 6) *this_rd *= 2;
2953    }
2954  }
2955}
2956
2957// Do we have an internal image edge (e.g. formatting bars).
2958int vp9_internal_image_edge(VP9_COMP *cpi) {
2959  return (cpi->oxcf.pass == 2) &&
2960         ((cpi->twopass.this_frame_stats.inactive_zone_rows > 0) ||
2961          (cpi->twopass.this_frame_stats.inactive_zone_cols > 0));
2962}
2963
2964// Checks to see if a super block is on a horizontal image edge.
2965// In most cases this is the "real" edge unless there are formatting
2966// bars embedded in the stream.
2967int vp9_active_h_edge(VP9_COMP *cpi, int mi_row, int mi_step) {
2968  int top_edge = 0;
2969  int bottom_edge = cpi->common.mi_rows;
2970  int is_active_h_edge = 0;
2971
2972  // For two pass account for any formatting bars detected.
2973  if (cpi->oxcf.pass == 2) {
2974    TWO_PASS *twopass = &cpi->twopass;
2975
2976    // The inactive region is specified in MBs not mi units.
2977    // The image edge is in the following MB row.
2978    top_edge += (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
2979
2980    bottom_edge -= (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
2981    bottom_edge = VPXMAX(top_edge, bottom_edge);
2982  }
2983
2984  if (((top_edge >= mi_row) && (top_edge < (mi_row + mi_step))) ||
2985      ((bottom_edge >= mi_row) && (bottom_edge < (mi_row + mi_step)))) {
2986    is_active_h_edge = 1;
2987  }
2988  return is_active_h_edge;
2989}
2990
2991// Checks to see if a super block is on a vertical image edge.
2992// In most cases this is the "real" edge unless there are formatting
2993// bars embedded in the stream.
2994int vp9_active_v_edge(VP9_COMP *cpi, int mi_col, int mi_step) {
2995  int left_edge = 0;
2996  int right_edge = cpi->common.mi_cols;
2997  int is_active_v_edge = 0;
2998
2999  // For two pass account for any formatting bars detected.
3000  if (cpi->oxcf.pass == 2) {
3001    TWO_PASS *twopass = &cpi->twopass;
3002
3003    // The inactive region is specified in MBs not mi units.
3004    // The image edge is in the following MB row.
3005    left_edge += (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
3006
3007    right_edge -= (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
3008    right_edge = VPXMAX(left_edge, right_edge);
3009  }
3010
3011  if (((left_edge >= mi_col) && (left_edge < (mi_col + mi_step))) ||
3012      ((right_edge >= mi_col) && (right_edge < (mi_col + mi_step)))) {
3013    is_active_v_edge = 1;
3014  }
3015  return is_active_v_edge;
3016}
3017
3018// Checks to see if a super block is at the edge of the active image.
3019// In most cases this is the "real" edge unless there are formatting
3020// bars embedded in the stream.
3021int vp9_active_edge_sb(VP9_COMP *cpi, int mi_row, int mi_col) {
3022  return vp9_active_h_edge(cpi, mi_row, MI_BLOCK_SIZE) ||
3023         vp9_active_v_edge(cpi, mi_col, MI_BLOCK_SIZE);
3024}
3025
3026void vp9_rd_pick_inter_mode_sb(VP9_COMP *cpi, TileDataEnc *tile_data,
3027                               MACROBLOCK *x, int mi_row, int mi_col,
3028                               RD_COST *rd_cost, BLOCK_SIZE bsize,
3029                               PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far) {
3030  VP9_COMMON *const cm = &cpi->common;
3031  TileInfo *const tile_info = &tile_data->tile_info;
3032  RD_OPT *const rd_opt = &cpi->rd;
3033  SPEED_FEATURES *const sf = &cpi->sf;
3034  MACROBLOCKD *const xd = &x->e_mbd;
3035  MODE_INFO *const mi = xd->mi[0];
3036  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
3037  const struct segmentation *const seg = &cm->seg;
3038  PREDICTION_MODE this_mode;
3039  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
3040  unsigned char segment_id = mi->segment_id;
3041  int comp_pred, i, k;
3042  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
3043  struct buf_2d yv12_mb[4][MAX_MB_PLANE];
3044  int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
3045  INTERP_FILTER single_inter_filter[MB_MODE_COUNT][MAX_REF_FRAMES];
3046  int single_skippable[MB_MODE_COUNT][MAX_REF_FRAMES];
3047  static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
3048                                    VP9_ALT_FLAG };
3049  int64_t best_rd = best_rd_so_far;
3050  int64_t best_pred_diff[REFERENCE_MODES];
3051  int64_t best_pred_rd[REFERENCE_MODES];
3052  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
3053  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3054  MODE_INFO best_mbmode;
3055  int best_mode_skippable = 0;
3056  int midx, best_mode_index = -1;
3057  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3058  vpx_prob comp_mode_p;
3059  int64_t best_intra_rd = INT64_MAX;
3060  unsigned int best_pred_sse = UINT_MAX;
3061  PREDICTION_MODE best_intra_mode = DC_PRED;
3062  int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
3063  int64_t dist_uv[TX_SIZES];
3064  int skip_uv[TX_SIZES];
3065  PREDICTION_MODE mode_uv[TX_SIZES];
3066  const int intra_cost_penalty =
3067      vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
3068  int best_skip2 = 0;
3069  uint8_t ref_frame_skip_mask[2] = { 0 };
3070  uint16_t mode_skip_mask[MAX_REF_FRAMES] = { 0 };
3071  int mode_skip_start = sf->mode_skip_start + 1;
3072  const int *const rd_threshes = rd_opt->threshes[segment_id][bsize];
3073  const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
3074  int64_t mode_threshold[MAX_MODES];
3075  int *tile_mode_map = tile_data->mode_map[bsize];
3076  int mode_map[MAX_MODES];  // Maintain mode_map information locally to avoid
3077                            // lock mechanism involved with reads from
3078                            // tile_mode_map
3079  const int mode_search_skip_flags = sf->mode_search_skip_flags;
3080  int64_t mask_filter = 0;
3081  int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
3082
3083  vp9_zero(best_mbmode);
3084
3085  x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3086
3087  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
3088
3089  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3090                           &comp_mode_p);
3091
3092  for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
3093  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3094    best_filter_rd[i] = INT64_MAX;
3095  for (i = 0; i < TX_SIZES; i++) rate_uv_intra[i] = INT_MAX;
3096  for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
3097  for (i = 0; i < MB_MODE_COUNT; ++i) {
3098    for (k = 0; k < MAX_REF_FRAMES; ++k) {
3099      single_inter_filter[i][k] = SWITCHABLE;
3100      single_skippable[i][k] = 0;
3101    }
3102  }
3103
3104  rd_cost->rate = INT_MAX;
3105
3106  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3107    x->pred_mv_sad[ref_frame] = INT_MAX;
3108    if (cpi->ref_frame_flags & flag_list[ref_frame]) {
3109      assert(get_ref_frame_buffer(cpi, ref_frame) != NULL);
3110      setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
3111                         frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
3112    }
3113    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
3114    frame_mv[ZEROMV][ref_frame].as_int = 0;
3115  }
3116
3117  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3118    if (!(cpi->ref_frame_flags & flag_list[ref_frame])) {
3119      // Skip checking missing references in both single and compound reference
3120      // modes. Note that a mode will be skipped if both reference frames
3121      // are masked out.
3122      ref_frame_skip_mask[0] |= (1 << ref_frame);
3123      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3124    } else if (sf->reference_masking) {
3125      for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
3126        // Skip fixed mv modes for poor references
3127        if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
3128          mode_skip_mask[ref_frame] |= INTER_NEAREST_NEAR_ZERO;
3129          break;
3130        }
3131      }
3132    }
3133    // If the segment reference frame feature is enabled....
3134    // then do nothing if the current ref frame is not allowed..
3135    if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3136        get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
3137      ref_frame_skip_mask[0] |= (1 << ref_frame);
3138      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3139    }
3140  }
3141
3142  // Disable this drop out case if the ref frame
3143  // segment level feature is enabled for this segment. This is to
3144  // prevent the possibility that we end up unable to pick any mode.
3145  if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
3146    // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
3147    // unless ARNR filtering is enabled in which case we want
3148    // an unfiltered alternative. We allow near/nearest as well
3149    // because they may result in zero-zero MVs but be cheaper.
3150    if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
3151      ref_frame_skip_mask[0] = (1 << LAST_FRAME) | (1 << GOLDEN_FRAME);
3152      ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3153      mode_skip_mask[ALTREF_FRAME] = ~INTER_NEAREST_NEAR_ZERO;
3154      if (frame_mv[NEARMV][ALTREF_FRAME].as_int != 0)
3155        mode_skip_mask[ALTREF_FRAME] |= (1 << NEARMV);
3156      if (frame_mv[NEARESTMV][ALTREF_FRAME].as_int != 0)
3157        mode_skip_mask[ALTREF_FRAME] |= (1 << NEARESTMV);
3158    }
3159  }
3160
3161  if (cpi->rc.is_src_frame_alt_ref) {
3162    if (sf->alt_ref_search_fp) {
3163      mode_skip_mask[ALTREF_FRAME] = 0;
3164      ref_frame_skip_mask[0] = ~(1 << ALTREF_FRAME);
3165      ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3166    }
3167  }
3168
3169  if (sf->alt_ref_search_fp)
3170    if (!cm->show_frame && x->pred_mv_sad[GOLDEN_FRAME] < INT_MAX)
3171      if (x->pred_mv_sad[ALTREF_FRAME] > (x->pred_mv_sad[GOLDEN_FRAME] << 1))
3172        mode_skip_mask[ALTREF_FRAME] |= INTER_ALL;
3173
3174  if (sf->adaptive_mode_search) {
3175    if (cm->show_frame && !cpi->rc.is_src_frame_alt_ref &&
3176        cpi->rc.frames_since_golden >= 3)
3177      if (x->pred_mv_sad[GOLDEN_FRAME] > (x->pred_mv_sad[LAST_FRAME] << 1))
3178        mode_skip_mask[GOLDEN_FRAME] |= INTER_ALL;
3179  }
3180
3181  if (bsize > sf->max_intra_bsize) {
3182    ref_frame_skip_mask[0] |= (1 << INTRA_FRAME);
3183    ref_frame_skip_mask[1] |= (1 << INTRA_FRAME);
3184  }
3185
3186  mode_skip_mask[INTRA_FRAME] |=
3187      ~(sf->intra_y_mode_mask[max_txsize_lookup[bsize]]);
3188
3189  for (i = 0; i <= LAST_NEW_MV_INDEX; ++i) mode_threshold[i] = 0;
3190
3191  for (i = LAST_NEW_MV_INDEX + 1; i < MAX_MODES; ++i)
3192    mode_threshold[i] = ((int64_t)rd_threshes[i] * rd_thresh_freq_fact[i]) >> 5;
3193
3194  midx = sf->schedule_mode_search ? mode_skip_start : 0;
3195
3196  while (midx > 4) {
3197    uint8_t end_pos = 0;
3198    for (i = 5; i < midx; ++i) {
3199      if (mode_threshold[tile_mode_map[i - 1]] >
3200          mode_threshold[tile_mode_map[i]]) {
3201        uint8_t tmp = tile_mode_map[i];
3202        tile_mode_map[i] = tile_mode_map[i - 1];
3203        tile_mode_map[i - 1] = tmp;
3204        end_pos = i;
3205      }
3206    }
3207    midx = end_pos;
3208  }
3209
3210  memcpy(mode_map, tile_mode_map, sizeof(mode_map));
3211
3212  for (midx = 0; midx < MAX_MODES; ++midx) {
3213    int mode_index = mode_map[midx];
3214    int mode_excluded = 0;
3215    int64_t this_rd = INT64_MAX;
3216    int disable_skip = 0;
3217    int compmode_cost = 0;
3218    int rate2 = 0, rate_y = 0, rate_uv = 0;
3219    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3220    int skippable = 0;
3221    int this_skip2 = 0;
3222    int64_t total_sse = INT64_MAX;
3223    int early_term = 0;
3224
3225    this_mode = vp9_mode_order[mode_index].mode;
3226    ref_frame = vp9_mode_order[mode_index].ref_frame[0];
3227    second_ref_frame = vp9_mode_order[mode_index].ref_frame[1];
3228
3229    vp9_zero(x->sum_y_eobs);
3230
3231    // Look at the reference frame of the best mode so far and set the
3232    // skip mask to look at a subset of the remaining modes.
3233    if (midx == mode_skip_start && best_mode_index >= 0) {
3234      switch (best_mbmode.ref_frame[0]) {
3235        case INTRA_FRAME: break;
3236        case LAST_FRAME:
3237          ref_frame_skip_mask[0] |= LAST_FRAME_MODE_MASK;
3238          ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3239          break;
3240        case GOLDEN_FRAME:
3241          ref_frame_skip_mask[0] |= GOLDEN_FRAME_MODE_MASK;
3242          ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3243          break;
3244        case ALTREF_FRAME: ref_frame_skip_mask[0] |= ALT_REF_MODE_MASK; break;
3245        case NONE:
3246        case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
3247      }
3248    }
3249
3250    if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
3251        (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
3252      continue;
3253
3254    if (mode_skip_mask[ref_frame] & (1 << this_mode)) continue;
3255
3256    // Test best rd so far against threshold for trying this mode.
3257    if (best_mode_skippable && sf->schedule_mode_search)
3258      mode_threshold[mode_index] <<= 1;
3259
3260    if (best_rd < mode_threshold[mode_index]) continue;
3261
3262    // This is only used in motion vector unit test.
3263    if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
3264
3265    if (sf->motion_field_mode_search) {
3266      const int mi_width = VPXMIN(num_8x8_blocks_wide_lookup[bsize],
3267                                  tile_info->mi_col_end - mi_col);
3268      const int mi_height = VPXMIN(num_8x8_blocks_high_lookup[bsize],
3269                                   tile_info->mi_row_end - mi_row);
3270      const int bsl = mi_width_log2_lookup[bsize];
3271      int cb_partition_search_ctrl =
3272          (((mi_row + mi_col) >> bsl) +
3273           get_chessboard_index(cm->current_video_frame)) &
3274          0x1;
3275      MODE_INFO *ref_mi;
3276      int const_motion = 1;
3277      int skip_ref_frame = !cb_partition_search_ctrl;
3278      MV_REFERENCE_FRAME rf = NONE;
3279      int_mv ref_mv;
3280      ref_mv.as_int = INVALID_MV;
3281
3282      if ((mi_row - 1) >= tile_info->mi_row_start) {
3283        ref_mv = xd->mi[-xd->mi_stride]->mv[0];
3284        rf = xd->mi[-xd->mi_stride]->ref_frame[0];
3285        for (i = 0; i < mi_width; ++i) {
3286          ref_mi = xd->mi[-xd->mi_stride + i];
3287          const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3288                          (ref_frame == ref_mi->ref_frame[0]);
3289          skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3290        }
3291      }
3292
3293      if ((mi_col - 1) >= tile_info->mi_col_start) {
3294        if (ref_mv.as_int == INVALID_MV) ref_mv = xd->mi[-1]->mv[0];
3295        if (rf == NONE) rf = xd->mi[-1]->ref_frame[0];
3296        for (i = 0; i < mi_height; ++i) {
3297          ref_mi = xd->mi[i * xd->mi_stride - 1];
3298          const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3299                          (ref_frame == ref_mi->ref_frame[0]);
3300          skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3301        }
3302      }
3303
3304      if (skip_ref_frame && this_mode != NEARESTMV && this_mode != NEWMV)
3305        if (rf > INTRA_FRAME)
3306          if (ref_frame != rf) continue;
3307
3308      if (const_motion)
3309        if (this_mode == NEARMV || this_mode == ZEROMV) continue;
3310    }
3311
3312    comp_pred = second_ref_frame > INTRA_FRAME;
3313    if (comp_pred) {
3314      if (!cpi->allow_comp_inter_inter) continue;
3315
3316      // Skip compound inter modes if ARF is not available.
3317      if (!(cpi->ref_frame_flags & flag_list[second_ref_frame])) continue;
3318
3319      // Do not allow compound prediction if the segment level reference frame
3320      // feature is in use as in this case there can only be one reference.
3321      if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
3322
3323      if ((mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3324          best_mode_index >= 0 && best_mbmode.ref_frame[0] == INTRA_FRAME)
3325        continue;
3326
3327      mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3328    } else {
3329      if (ref_frame != INTRA_FRAME)
3330        mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3331    }
3332
3333    if (ref_frame == INTRA_FRAME) {
3334      if (sf->adaptive_mode_search)
3335        if ((x->source_variance << num_pels_log2_lookup[bsize]) > best_pred_sse)
3336          continue;
3337
3338      if (this_mode != DC_PRED) {
3339        // Disable intra modes other than DC_PRED for blocks with low variance
3340        // Threshold for intra skipping based on source variance
3341        // TODO(debargha): Specialize the threshold for super block sizes
3342        const unsigned int skip_intra_var_thresh = 64;
3343        if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
3344            x->source_variance < skip_intra_var_thresh)
3345          continue;
3346        // Only search the oblique modes if the best so far is
3347        // one of the neighboring directional modes
3348        if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
3349            (this_mode >= D45_PRED && this_mode <= TM_PRED)) {
3350          if (best_mode_index >= 0 && best_mbmode.ref_frame[0] > INTRA_FRAME)
3351            continue;
3352        }
3353        if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
3354          if (conditional_skipintra(this_mode, best_intra_mode)) continue;
3355        }
3356      }
3357    } else {
3358      const MV_REFERENCE_FRAME ref_frames[2] = { ref_frame, second_ref_frame };
3359      if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv, this_mode,
3360                              ref_frames))
3361        continue;
3362    }
3363
3364    mi->mode = this_mode;
3365    mi->uv_mode = DC_PRED;
3366    mi->ref_frame[0] = ref_frame;
3367    mi->ref_frame[1] = second_ref_frame;
3368    // Evaluate all sub-pel filters irrespective of whether we can use
3369    // them for this frame.
3370    mi->interp_filter =
3371        cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
3372    mi->mv[0].as_int = mi->mv[1].as_int = 0;
3373
3374    x->skip = 0;
3375    set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3376
3377    // Select prediction reference frames.
3378    for (i = 0; i < MAX_MB_PLANE; i++) {
3379      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3380      if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3381    }
3382
3383    if (ref_frame == INTRA_FRAME) {
3384      TX_SIZE uv_tx;
3385      struct macroblockd_plane *const pd = &xd->plane[1];
3386      memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
3387      super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable, NULL, bsize,
3388                      best_rd);
3389      if (rate_y == INT_MAX) continue;
3390
3391      uv_tx = uv_txsize_lookup[bsize][mi->tx_size][pd->subsampling_x]
3392                              [pd->subsampling_y];
3393      if (rate_uv_intra[uv_tx] == INT_MAX) {
3394        choose_intra_uv_mode(cpi, x, ctx, bsize, uv_tx, &rate_uv_intra[uv_tx],
3395                             &rate_uv_tokenonly[uv_tx], &dist_uv[uv_tx],
3396                             &skip_uv[uv_tx], &mode_uv[uv_tx]);
3397      }
3398
3399      rate_uv = rate_uv_tokenonly[uv_tx];
3400      distortion_uv = dist_uv[uv_tx];
3401      skippable = skippable && skip_uv[uv_tx];
3402      mi->uv_mode = mode_uv[uv_tx];
3403
3404      rate2 = rate_y + cpi->mbmode_cost[mi->mode] + rate_uv_intra[uv_tx];
3405      if (this_mode != DC_PRED && this_mode != TM_PRED)
3406        rate2 += intra_cost_penalty;
3407      distortion2 = distortion_y + distortion_uv;
3408    } else {
3409      this_rd = handle_inter_mode(
3410          cpi, x, bsize, &rate2, &distortion2, &skippable, &rate_y, &rate_uv,
3411          &disable_skip, frame_mv, mi_row, mi_col, single_newmv,
3412          single_inter_filter, single_skippable, &total_sse, best_rd,
3413          &mask_filter, filter_cache);
3414      if (this_rd == INT64_MAX) continue;
3415
3416      compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
3417
3418      if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
3419    }
3420
3421    // Estimate the reference frame signaling cost and add it
3422    // to the rolling cost variable.
3423    if (comp_pred) {
3424      rate2 += ref_costs_comp[ref_frame];
3425    } else {
3426      rate2 += ref_costs_single[ref_frame];
3427    }
3428
3429    if (!disable_skip) {
3430      const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
3431      const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
3432      const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
3433
3434      if (skippable) {
3435        // Back out the coefficient coding costs
3436        rate2 -= (rate_y + rate_uv);
3437
3438        // Cost the skip mb case
3439        rate2 += skip_cost1;
3440      } else if (ref_frame != INTRA_FRAME && !xd->lossless) {
3441        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
3442                   distortion2) <
3443            RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
3444          // Add in the cost of the no skip flag.
3445          rate2 += skip_cost0;
3446        } else {
3447          // FIXME(rbultje) make this work for splitmv also
3448          assert(total_sse >= 0);
3449
3450          rate2 += skip_cost1;
3451          distortion2 = total_sse;
3452          rate2 -= (rate_y + rate_uv);
3453          this_skip2 = 1;
3454        }
3455      } else {
3456        // Add in the cost of the no skip flag.
3457        rate2 += skip_cost0;
3458      }
3459
3460      // Calculate the final RD estimate for this mode.
3461      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3462    }
3463
3464    // Apply an adjustment to the rd value based on the similarity of the
3465    // source variance and reconstructed variance.
3466    rd_variance_adjustment(cpi, x, bsize, &this_rd, ref_frame,
3467                           x->source_variance);
3468
3469    if (ref_frame == INTRA_FRAME) {
3470      // Keep record of best intra rd
3471      if (this_rd < best_intra_rd) {
3472        best_intra_rd = this_rd;
3473        best_intra_mode = mi->mode;
3474      }
3475    }
3476
3477    if (!disable_skip && ref_frame == INTRA_FRAME) {
3478      for (i = 0; i < REFERENCE_MODES; ++i)
3479        best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
3480      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3481        best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
3482    }
3483
3484    // Did this mode help.. i.e. is it the new best mode
3485    if (this_rd < best_rd || x->skip) {
3486      int max_plane = MAX_MB_PLANE;
3487      if (!mode_excluded) {
3488        // Note index of best mode so far
3489        best_mode_index = mode_index;
3490
3491        if (ref_frame == INTRA_FRAME) {
3492          /* required for left and above block mv */
3493          mi->mv[0].as_int = 0;
3494          max_plane = 1;
3495          // Initialize interp_filter here so we do not have to check for
3496          // inter block modes in get_pred_context_switchable_interp()
3497          mi->interp_filter = SWITCHABLE_FILTERS;
3498        } else {
3499          best_pred_sse = x->pred_sse[ref_frame];
3500        }
3501
3502        rd_cost->rate = rate2;
3503        rd_cost->dist = distortion2;
3504        rd_cost->rdcost = this_rd;
3505        best_rd = this_rd;
3506        best_mbmode = *mi;
3507        best_skip2 = this_skip2;
3508        best_mode_skippable = skippable;
3509
3510        if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
3511        memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mi->tx_size],
3512               sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
3513        ctx->sum_y_eobs = x->sum_y_eobs[mi->tx_size];
3514
3515        // TODO(debargha): enhance this test with a better distortion prediction
3516        // based on qp, activity mask and history
3517        if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
3518            (mode_index > MIN_EARLY_TERM_INDEX)) {
3519          int qstep = xd->plane[0].dequant[1];
3520          // TODO(debargha): Enhance this by specializing for each mode_index
3521          int scale = 4;
3522#if CONFIG_VP9_HIGHBITDEPTH
3523          if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3524            qstep >>= (xd->bd - 8);
3525          }
3526#endif  // CONFIG_VP9_HIGHBITDEPTH
3527          if (x->source_variance < UINT_MAX) {
3528            const int var_adjust = (x->source_variance < 16);
3529            scale -= var_adjust;
3530          }
3531          if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
3532            early_term = 1;
3533          }
3534        }
3535      }
3536    }
3537
3538    /* keep record of best compound/single-only prediction */
3539    if (!disable_skip && ref_frame != INTRA_FRAME) {
3540      int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
3541
3542      if (cm->reference_mode == REFERENCE_MODE_SELECT) {
3543        single_rate = rate2 - compmode_cost;
3544        hybrid_rate = rate2;
3545      } else {
3546        single_rate = rate2;
3547        hybrid_rate = rate2 + compmode_cost;
3548      }
3549
3550      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
3551      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
3552
3553      if (!comp_pred) {
3554        if (single_rd < best_pred_rd[SINGLE_REFERENCE])
3555          best_pred_rd[SINGLE_REFERENCE] = single_rd;
3556      } else {
3557        if (single_rd < best_pred_rd[COMPOUND_REFERENCE])
3558          best_pred_rd[COMPOUND_REFERENCE] = single_rd;
3559      }
3560      if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
3561        best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
3562
3563      /* keep record of best filter type */
3564      if (!mode_excluded && cm->interp_filter != BILINEAR) {
3565        int64_t ref =
3566            filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
3567                                                         : cm->interp_filter];
3568
3569        for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3570          int64_t adj_rd;
3571          if (ref == INT64_MAX)
3572            adj_rd = 0;
3573          else if (filter_cache[i] == INT64_MAX)
3574            // when early termination is triggered, the encoder does not have
3575            // access to the rate-distortion cost. it only knows that the cost
3576            // should be above the maximum valid value. hence it takes the known
3577            // maximum plus an arbitrary constant as the rate-distortion cost.
3578            adj_rd = mask_filter - ref + 10;
3579          else
3580            adj_rd = filter_cache[i] - ref;
3581
3582          adj_rd += this_rd;
3583          best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
3584        }
3585      }
3586    }
3587
3588    if (early_term) break;
3589
3590    if (x->skip && !comp_pred) break;
3591  }
3592
3593  // The inter modes' rate costs are not calculated precisely in some cases.
3594  // Therefore, sometimes, NEWMV is chosen instead of NEARESTMV, NEARMV, and
3595  // ZEROMV. Here, checks are added for those cases, and the mode decisions
3596  // are corrected.
3597  if (best_mbmode.mode == NEWMV) {
3598    const MV_REFERENCE_FRAME refs[2] = { best_mbmode.ref_frame[0],
3599                                         best_mbmode.ref_frame[1] };
3600    int comp_pred_mode = refs[1] > INTRA_FRAME;
3601
3602    if (frame_mv[NEARESTMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
3603        ((comp_pred_mode &&
3604          frame_mv[NEARESTMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
3605         !comp_pred_mode))
3606      best_mbmode.mode = NEARESTMV;
3607    else if (frame_mv[NEARMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
3608             ((comp_pred_mode &&
3609               frame_mv[NEARMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
3610              !comp_pred_mode))
3611      best_mbmode.mode = NEARMV;
3612    else if (best_mbmode.mv[0].as_int == 0 &&
3613             ((comp_pred_mode && best_mbmode.mv[1].as_int == 0) ||
3614              !comp_pred_mode))
3615      best_mbmode.mode = ZEROMV;
3616  }
3617
3618  if (best_mode_index < 0 || best_rd >= best_rd_so_far) {
3619    // If adaptive interp filter is enabled, then the current leaf node of 8x8
3620    // data is needed for sub8x8. Hence preserve the context.
3621    if (cpi->row_mt && bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
3622    rd_cost->rate = INT_MAX;
3623    rd_cost->rdcost = INT64_MAX;
3624    return;
3625  }
3626
3627  // If we used an estimate for the uv intra rd in the loop above...
3628  if (sf->use_uv_intra_rd_estimate) {
3629    // Do Intra UV best rd mode selection if best mode choice above was intra.
3630    if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
3631      TX_SIZE uv_tx_size;
3632      *mi = best_mbmode;
3633      uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
3634      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
3635                              &rate_uv_tokenonly[uv_tx_size],
3636                              &dist_uv[uv_tx_size], &skip_uv[uv_tx_size],
3637                              bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
3638                              uv_tx_size);
3639    }
3640  }
3641
3642  assert((cm->interp_filter == SWITCHABLE) ||
3643         (cm->interp_filter == best_mbmode.interp_filter) ||
3644         !is_inter_block(&best_mbmode));
3645
3646  if (!cpi->rc.is_src_frame_alt_ref)
3647    vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
3648                              sf->adaptive_rd_thresh, bsize, best_mode_index);
3649
3650  // macroblock modes
3651  *mi = best_mbmode;
3652  x->skip |= best_skip2;
3653
3654  for (i = 0; i < REFERENCE_MODES; ++i) {
3655    if (best_pred_rd[i] == INT64_MAX)
3656      best_pred_diff[i] = INT_MIN;
3657    else
3658      best_pred_diff[i] = best_rd - best_pred_rd[i];
3659  }
3660
3661  if (!x->skip) {
3662    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3663      if (best_filter_rd[i] == INT64_MAX)
3664        best_filter_diff[i] = 0;
3665      else
3666        best_filter_diff[i] = best_rd - best_filter_rd[i];
3667    }
3668    if (cm->interp_filter == SWITCHABLE)
3669      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
3670  } else {
3671    vp9_zero(best_filter_diff);
3672  }
3673
3674  // TODO(yunqingwang): Moving this line in front of the above best_filter_diff
3675  // updating code causes PSNR loss. Need to figure out the confliction.
3676  x->skip |= best_mode_skippable;
3677
3678  if (!x->skip && !x->select_tx_size) {
3679    int has_high_freq_coeff = 0;
3680    int plane;
3681    int max_plane = is_inter_block(xd->mi[0]) ? MAX_MB_PLANE : 1;
3682    for (plane = 0; plane < max_plane; ++plane) {
3683      x->plane[plane].eobs = ctx->eobs_pbuf[plane][1];
3684      has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
3685    }
3686
3687    for (plane = max_plane; plane < MAX_MB_PLANE; ++plane) {
3688      x->plane[plane].eobs = ctx->eobs_pbuf[plane][2];
3689      has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
3690    }
3691
3692    best_mode_skippable |= !has_high_freq_coeff;
3693  }
3694
3695  assert(best_mode_index >= 0);
3696
3697  store_coding_context(x, ctx, best_mode_index, best_pred_diff,
3698                       best_filter_diff, best_mode_skippable);
3699}
3700
3701void vp9_rd_pick_inter_mode_sb_seg_skip(VP9_COMP *cpi, TileDataEnc *tile_data,
3702                                        MACROBLOCK *x, RD_COST *rd_cost,
3703                                        BLOCK_SIZE bsize,
3704                                        PICK_MODE_CONTEXT *ctx,
3705                                        int64_t best_rd_so_far) {
3706  VP9_COMMON *const cm = &cpi->common;
3707  MACROBLOCKD *const xd = &x->e_mbd;
3708  MODE_INFO *const mi = xd->mi[0];
3709  unsigned char segment_id = mi->segment_id;
3710  const int comp_pred = 0;
3711  int i;
3712  int64_t best_pred_diff[REFERENCE_MODES];
3713  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3714  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3715  vpx_prob comp_mode_p;
3716  INTERP_FILTER best_filter = SWITCHABLE;
3717  int64_t this_rd = INT64_MAX;
3718  int rate2 = 0;
3719  const int64_t distortion2 = 0;
3720
3721  x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3722
3723  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3724                           &comp_mode_p);
3725
3726  for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
3727  for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i) x->pred_mv_sad[i] = INT_MAX;
3728
3729  rd_cost->rate = INT_MAX;
3730
3731  assert(segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP));
3732
3733  mi->mode = ZEROMV;
3734  mi->uv_mode = DC_PRED;
3735  mi->ref_frame[0] = LAST_FRAME;
3736  mi->ref_frame[1] = NONE;
3737  mi->mv[0].as_int = 0;
3738  x->skip = 1;
3739
3740  ctx->sum_y_eobs = 0;
3741
3742  if (cm->interp_filter != BILINEAR) {
3743    best_filter = EIGHTTAP;
3744    if (cm->interp_filter == SWITCHABLE &&
3745        x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
3746      int rs;
3747      int best_rs = INT_MAX;
3748      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
3749        mi->interp_filter = i;
3750        rs = vp9_get_switchable_rate(cpi, xd);
3751        if (rs < best_rs) {
3752          best_rs = rs;
3753          best_filter = mi->interp_filter;
3754        }
3755      }
3756    }
3757  }
3758  // Set the appropriate filter
3759  if (cm->interp_filter == SWITCHABLE) {
3760    mi->interp_filter = best_filter;
3761    rate2 += vp9_get_switchable_rate(cpi, xd);
3762  } else {
3763    mi->interp_filter = cm->interp_filter;
3764  }
3765
3766  if (cm->reference_mode == REFERENCE_MODE_SELECT)
3767    rate2 += vp9_cost_bit(comp_mode_p, comp_pred);
3768
3769  // Estimate the reference frame signaling cost and add it
3770  // to the rolling cost variable.
3771  rate2 += ref_costs_single[LAST_FRAME];
3772  this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3773
3774  rd_cost->rate = rate2;
3775  rd_cost->dist = distortion2;
3776  rd_cost->rdcost = this_rd;
3777
3778  if (this_rd >= best_rd_so_far) {
3779    rd_cost->rate = INT_MAX;
3780    rd_cost->rdcost = INT64_MAX;
3781    return;
3782  }
3783
3784  assert((cm->interp_filter == SWITCHABLE) ||
3785         (cm->interp_filter == mi->interp_filter));
3786
3787  vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
3788                            cpi->sf.adaptive_rd_thresh, bsize, THR_ZEROMV);
3789
3790  vp9_zero(best_pred_diff);
3791  vp9_zero(best_filter_diff);
3792
3793  if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, MAX_MB_PLANE);
3794  store_coding_context(x, ctx, THR_ZEROMV, best_pred_diff, best_filter_diff, 0);
3795}
3796
3797void vp9_rd_pick_inter_mode_sub8x8(VP9_COMP *cpi, TileDataEnc *tile_data,
3798                                   MACROBLOCK *x, int mi_row, int mi_col,
3799                                   RD_COST *rd_cost, BLOCK_SIZE bsize,
3800                                   PICK_MODE_CONTEXT *ctx,
3801                                   int64_t best_rd_so_far) {
3802  VP9_COMMON *const cm = &cpi->common;
3803  RD_OPT *const rd_opt = &cpi->rd;
3804  SPEED_FEATURES *const sf = &cpi->sf;
3805  MACROBLOCKD *const xd = &x->e_mbd;
3806  MODE_INFO *const mi = xd->mi[0];
3807  const struct segmentation *const seg = &cm->seg;
3808  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
3809  unsigned char segment_id = mi->segment_id;
3810  int comp_pred, i;
3811  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
3812  struct buf_2d yv12_mb[4][MAX_MB_PLANE];
3813  static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
3814                                    VP9_ALT_FLAG };
3815  int64_t best_rd = best_rd_so_far;
3816  int64_t best_yrd = best_rd_so_far;  // FIXME(rbultje) more precise
3817  int64_t best_pred_diff[REFERENCE_MODES];
3818  int64_t best_pred_rd[REFERENCE_MODES];
3819  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
3820  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3821  MODE_INFO best_mbmode;
3822  int ref_index, best_ref_index = 0;
3823  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3824  vpx_prob comp_mode_p;
3825  INTERP_FILTER tmp_best_filter = SWITCHABLE;
3826  int rate_uv_intra, rate_uv_tokenonly;
3827  int64_t dist_uv;
3828  int skip_uv;
3829  PREDICTION_MODE mode_uv = DC_PRED;
3830  const int intra_cost_penalty =
3831      vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
3832  int_mv seg_mvs[4][MAX_REF_FRAMES];
3833  b_mode_info best_bmodes[4];
3834  int best_skip2 = 0;
3835  int ref_frame_skip_mask[2] = { 0 };
3836  int64_t mask_filter = 0;
3837  int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
3838  int internal_active_edge =
3839      vp9_active_edge_sb(cpi, mi_row, mi_col) && vp9_internal_image_edge(cpi);
3840  const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
3841
3842  x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3843  memset(x->zcoeff_blk[TX_4X4], 0, 4);
3844  vp9_zero(best_mbmode);
3845
3846  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
3847
3848  for (i = 0; i < 4; i++) {
3849    int j;
3850    for (j = 0; j < MAX_REF_FRAMES; j++) seg_mvs[i][j].as_int = INVALID_MV;
3851  }
3852
3853  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3854                           &comp_mode_p);
3855
3856  for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
3857  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3858    best_filter_rd[i] = INT64_MAX;
3859  rate_uv_intra = INT_MAX;
3860
3861  rd_cost->rate = INT_MAX;
3862
3863  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
3864    if (cpi->ref_frame_flags & flag_list[ref_frame]) {
3865      setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
3866                         frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
3867    } else {
3868      ref_frame_skip_mask[0] |= (1 << ref_frame);
3869      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3870    }
3871    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
3872    frame_mv[ZEROMV][ref_frame].as_int = 0;
3873  }
3874
3875  for (ref_index = 0; ref_index < MAX_REFS; ++ref_index) {
3876    int mode_excluded = 0;
3877    int64_t this_rd = INT64_MAX;
3878    int disable_skip = 0;
3879    int compmode_cost = 0;
3880    int rate2 = 0, rate_y = 0, rate_uv = 0;
3881    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3882    int skippable = 0;
3883    int i;
3884    int this_skip2 = 0;
3885    int64_t total_sse = INT_MAX;
3886    int early_term = 0;
3887    struct buf_2d backup_yv12[2][MAX_MB_PLANE];
3888
3889    ref_frame = vp9_ref_order[ref_index].ref_frame[0];
3890    second_ref_frame = vp9_ref_order[ref_index].ref_frame[1];
3891
3892    vp9_zero(x->sum_y_eobs);
3893
3894#if CONFIG_BETTER_HW_COMPATIBILITY
3895    // forbid 8X4 and 4X8 partitions if any reference frame is scaled.
3896    if (bsize == BLOCK_8X4 || bsize == BLOCK_4X8) {
3897      int ref_scaled = vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf);
3898      if (second_ref_frame > INTRA_FRAME)
3899        ref_scaled += vp9_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf);
3900      if (ref_scaled) continue;
3901    }
3902#endif
3903    // Look at the reference frame of the best mode so far and set the
3904    // skip mask to look at a subset of the remaining modes.
3905    if (ref_index > 2 && sf->mode_skip_start < MAX_MODES) {
3906      if (ref_index == 3) {
3907        switch (best_mbmode.ref_frame[0]) {
3908          case INTRA_FRAME: break;
3909          case LAST_FRAME:
3910            ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME);
3911            ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3912            break;
3913          case GOLDEN_FRAME:
3914            ref_frame_skip_mask[0] |= (1 << LAST_FRAME) | (1 << ALTREF_FRAME);
3915            ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3916            break;
3917          case ALTREF_FRAME:
3918            ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << LAST_FRAME);
3919            break;
3920          case NONE:
3921          case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
3922        }
3923      }
3924    }
3925
3926    if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
3927        (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
3928      continue;
3929
3930    // Test best rd so far against threshold for trying this mode.
3931    if (!internal_active_edge &&
3932        rd_less_than_thresh(best_rd,
3933                            rd_opt->threshes[segment_id][bsize][ref_index],
3934                            &rd_thresh_freq_fact[ref_index]))
3935      continue;
3936
3937    // This is only used in motion vector unit test.
3938    if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
3939
3940    comp_pred = second_ref_frame > INTRA_FRAME;
3941    if (comp_pred) {
3942      if (!cpi->allow_comp_inter_inter) continue;
3943      if (!(cpi->ref_frame_flags & flag_list[second_ref_frame])) continue;
3944      // Do not allow compound prediction if the segment level reference frame
3945      // feature is in use as in this case there can only be one reference.
3946      if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
3947
3948      if ((sf->mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3949          best_mbmode.ref_frame[0] == INTRA_FRAME)
3950        continue;
3951    }
3952
3953    if (comp_pred)
3954      mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3955    else if (ref_frame != INTRA_FRAME)
3956      mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3957
3958    // If the segment reference frame feature is enabled....
3959    // then do nothing if the current ref frame is not allowed..
3960    if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3961        get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
3962      continue;
3963      // Disable this drop out case if the ref frame
3964      // segment level feature is enabled for this segment. This is to
3965      // prevent the possibility that we end up unable to pick any mode.
3966    } else if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
3967      // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
3968      // unless ARNR filtering is enabled in which case we want
3969      // an unfiltered alternative. We allow near/nearest as well
3970      // because they may result in zero-zero MVs but be cheaper.
3971      if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
3972        continue;
3973    }
3974
3975    mi->tx_size = TX_4X4;
3976    mi->uv_mode = DC_PRED;
3977    mi->ref_frame[0] = ref_frame;
3978    mi->ref_frame[1] = second_ref_frame;
3979    // Evaluate all sub-pel filters irrespective of whether we can use
3980    // them for this frame.
3981    mi->interp_filter =
3982        cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
3983    x->skip = 0;
3984    set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3985
3986    // Select prediction reference frames.
3987    for (i = 0; i < MAX_MB_PLANE; i++) {
3988      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3989      if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3990    }
3991
3992    if (ref_frame == INTRA_FRAME) {
3993      int rate;
3994      if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y, &distortion_y,
3995                                       best_rd) >= best_rd)
3996        continue;
3997      rate2 += rate;
3998      rate2 += intra_cost_penalty;
3999      distortion2 += distortion_y;
4000
4001      if (rate_uv_intra == INT_MAX) {
4002        choose_intra_uv_mode(cpi, x, ctx, bsize, TX_4X4, &rate_uv_intra,
4003                             &rate_uv_tokenonly, &dist_uv, &skip_uv, &mode_uv);
4004      }
4005      rate2 += rate_uv_intra;
4006      rate_uv = rate_uv_tokenonly;
4007      distortion2 += dist_uv;
4008      distortion_uv = dist_uv;
4009      mi->uv_mode = mode_uv;
4010    } else {
4011      int rate;
4012      int64_t distortion;
4013      int64_t this_rd_thresh;
4014      int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
4015      int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
4016      int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
4017      int tmp_best_skippable = 0;
4018      int switchable_filter_index;
4019      int_mv *second_ref =
4020          comp_pred ? &x->mbmi_ext->ref_mvs[second_ref_frame][0] : NULL;
4021      b_mode_info tmp_best_bmodes[16];
4022      MODE_INFO tmp_best_mbmode;
4023      BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
4024      int pred_exists = 0;
4025      int uv_skippable;
4026
4027      YV12_BUFFER_CONFIG *scaled_ref_frame[2] = { NULL, NULL };
4028      int ref;
4029
4030      for (ref = 0; ref < 2; ++ref) {
4031        scaled_ref_frame[ref] =
4032            mi->ref_frame[ref] > INTRA_FRAME
4033                ? vp9_get_scaled_ref_frame(cpi, mi->ref_frame[ref])
4034                : NULL;
4035
4036        if (scaled_ref_frame[ref]) {
4037          int i;
4038          // Swap out the reference frame for a version that's been scaled to
4039          // match the resolution of the current frame, allowing the existing
4040          // motion search code to be used without additional modifications.
4041          for (i = 0; i < MAX_MB_PLANE; i++)
4042            backup_yv12[ref][i] = xd->plane[i].pre[ref];
4043          vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
4044                               NULL);
4045        }
4046      }
4047
4048      this_rd_thresh = (ref_frame == LAST_FRAME)
4049                           ? rd_opt->threshes[segment_id][bsize][THR_LAST]
4050                           : rd_opt->threshes[segment_id][bsize][THR_ALTR];
4051      this_rd_thresh = (ref_frame == GOLDEN_FRAME)
4052                           ? rd_opt->threshes[segment_id][bsize][THR_GOLD]
4053                           : this_rd_thresh;
4054      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
4055        filter_cache[i] = INT64_MAX;
4056
4057      if (cm->interp_filter != BILINEAR) {
4058        tmp_best_filter = EIGHTTAP;
4059        if (x->source_variance < sf->disable_filter_search_var_thresh) {
4060          tmp_best_filter = EIGHTTAP;
4061        } else if (sf->adaptive_pred_interp_filter == 1 &&
4062                   ctx->pred_interp_filter < SWITCHABLE) {
4063          tmp_best_filter = ctx->pred_interp_filter;
4064        } else if (sf->adaptive_pred_interp_filter == 2) {
4065          tmp_best_filter = ctx->pred_interp_filter < SWITCHABLE
4066                                ? ctx->pred_interp_filter
4067                                : 0;
4068        } else {
4069          for (switchable_filter_index = 0;
4070               switchable_filter_index < SWITCHABLE_FILTERS;
4071               ++switchable_filter_index) {
4072            int newbest, rs;
4073            int64_t rs_rd;
4074            MB_MODE_INFO_EXT *mbmi_ext = x->mbmi_ext;
4075            mi->interp_filter = switchable_filter_index;
4076            tmp_rd = rd_pick_best_sub8x8_mode(
4077                cpi, x, &mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4078                &rate, &rate_y, &distortion, &skippable, &total_sse,
4079                (int)this_rd_thresh, seg_mvs, bsi, switchable_filter_index,
4080                mi_row, mi_col);
4081
4082            if (tmp_rd == INT64_MAX) continue;
4083            rs = vp9_get_switchable_rate(cpi, xd);
4084            rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
4085            filter_cache[switchable_filter_index] = tmp_rd;
4086            filter_cache[SWITCHABLE_FILTERS] =
4087                VPXMIN(filter_cache[SWITCHABLE_FILTERS], tmp_rd + rs_rd);
4088            if (cm->interp_filter == SWITCHABLE) tmp_rd += rs_rd;
4089
4090            mask_filter = VPXMAX(mask_filter, tmp_rd);
4091
4092            newbest = (tmp_rd < tmp_best_rd);
4093            if (newbest) {
4094              tmp_best_filter = mi->interp_filter;
4095              tmp_best_rd = tmp_rd;
4096            }
4097            if ((newbest && cm->interp_filter == SWITCHABLE) ||
4098                (mi->interp_filter == cm->interp_filter &&
4099                 cm->interp_filter != SWITCHABLE)) {
4100              tmp_best_rdu = tmp_rd;
4101              tmp_best_rate = rate;
4102              tmp_best_ratey = rate_y;
4103              tmp_best_distortion = distortion;
4104              tmp_best_sse = total_sse;
4105              tmp_best_skippable = skippable;
4106              tmp_best_mbmode = *mi;
4107              for (i = 0; i < 4; i++) {
4108                tmp_best_bmodes[i] = xd->mi[0]->bmi[i];
4109                x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
4110                x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
4111              }
4112              pred_exists = 1;
4113              if (switchable_filter_index == 0 && sf->use_rd_breakout &&
4114                  best_rd < INT64_MAX) {
4115                if (tmp_best_rdu / 2 > best_rd) {
4116                  // skip searching the other filters if the first is
4117                  // already substantially larger than the best so far
4118                  tmp_best_filter = mi->interp_filter;
4119                  tmp_best_rdu = INT64_MAX;
4120                  break;
4121                }
4122              }
4123            }
4124          }  // switchable_filter_index loop
4125        }
4126      }
4127
4128      if (tmp_best_rdu == INT64_MAX && pred_exists) continue;
4129
4130      mi->interp_filter = (cm->interp_filter == SWITCHABLE ? tmp_best_filter
4131                                                           : cm->interp_filter);
4132      if (!pred_exists) {
4133        // Handles the special case when a filter that is not in the
4134        // switchable list (bilinear, 6-tap) is indicated at the frame level
4135        tmp_rd = rd_pick_best_sub8x8_mode(
4136            cpi, x, &x->mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4137            &rate, &rate_y, &distortion, &skippable, &total_sse,
4138            (int)this_rd_thresh, seg_mvs, bsi, 0, mi_row, mi_col);
4139        if (tmp_rd == INT64_MAX) continue;
4140      } else {
4141        total_sse = tmp_best_sse;
4142        rate = tmp_best_rate;
4143        rate_y = tmp_best_ratey;
4144        distortion = tmp_best_distortion;
4145        skippable = tmp_best_skippable;
4146        *mi = tmp_best_mbmode;
4147        for (i = 0; i < 4; i++) xd->mi[0]->bmi[i] = tmp_best_bmodes[i];
4148      }
4149
4150      rate2 += rate;
4151      distortion2 += distortion;
4152
4153      if (cm->interp_filter == SWITCHABLE)
4154        rate2 += vp9_get_switchable_rate(cpi, xd);
4155
4156      if (!mode_excluded)
4157        mode_excluded = comp_pred ? cm->reference_mode == SINGLE_REFERENCE
4158                                  : cm->reference_mode == COMPOUND_REFERENCE;
4159
4160      compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
4161
4162      tmp_best_rdu =
4163          best_rd - VPXMIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
4164                           RDCOST(x->rdmult, x->rddiv, 0, total_sse));
4165
4166      if (tmp_best_rdu > 0) {
4167        // If even the 'Y' rd value of split is higher than best so far
4168        // then dont bother looking at UV
4169        vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col, BLOCK_8X8);
4170        memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
4171        if (!super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
4172                              &uv_sse, BLOCK_8X8, tmp_best_rdu)) {
4173          for (ref = 0; ref < 2; ++ref) {
4174            if (scaled_ref_frame[ref]) {
4175              int i;
4176              for (i = 0; i < MAX_MB_PLANE; ++i)
4177                xd->plane[i].pre[ref] = backup_yv12[ref][i];
4178            }
4179          }
4180          continue;
4181        }
4182
4183        rate2 += rate_uv;
4184        distortion2 += distortion_uv;
4185        skippable = skippable && uv_skippable;
4186        total_sse += uv_sse;
4187      }
4188
4189      for (ref = 0; ref < 2; ++ref) {
4190        if (scaled_ref_frame[ref]) {
4191          // Restore the prediction frame pointers to their unscaled versions.
4192          int i;
4193          for (i = 0; i < MAX_MB_PLANE; ++i)
4194            xd->plane[i].pre[ref] = backup_yv12[ref][i];
4195        }
4196      }
4197    }
4198
4199    if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
4200
4201    // Estimate the reference frame signaling cost and add it
4202    // to the rolling cost variable.
4203    if (second_ref_frame > INTRA_FRAME) {
4204      rate2 += ref_costs_comp[ref_frame];
4205    } else {
4206      rate2 += ref_costs_single[ref_frame];
4207    }
4208
4209    if (!disable_skip) {
4210      const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
4211      const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
4212      const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
4213
4214      // Skip is never coded at the segment level for sub8x8 blocks and instead
4215      // always coded in the bitstream at the mode info level.
4216      if (ref_frame != INTRA_FRAME && !xd->lossless) {
4217        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
4218                   distortion2) <
4219            RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
4220          // Add in the cost of the no skip flag.
4221          rate2 += skip_cost0;
4222        } else {
4223          // FIXME(rbultje) make this work for splitmv also
4224          rate2 += skip_cost1;
4225          distortion2 = total_sse;
4226          assert(total_sse >= 0);
4227          rate2 -= (rate_y + rate_uv);
4228          rate_y = 0;
4229          rate_uv = 0;
4230          this_skip2 = 1;
4231        }
4232      } else {
4233        // Add in the cost of the no skip flag.
4234        rate2 += skip_cost0;
4235      }
4236
4237      // Calculate the final RD estimate for this mode.
4238      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4239    }
4240
4241    if (!disable_skip && ref_frame == INTRA_FRAME) {
4242      for (i = 0; i < REFERENCE_MODES; ++i)
4243        best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
4244      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4245        best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
4246    }
4247
4248    // Did this mode help.. i.e. is it the new best mode
4249    if (this_rd < best_rd || x->skip) {
4250      if (!mode_excluded) {
4251        int max_plane = MAX_MB_PLANE;
4252        // Note index of best mode so far
4253        best_ref_index = ref_index;
4254
4255        if (ref_frame == INTRA_FRAME) {
4256          /* required for left and above block mv */
4257          mi->mv[0].as_int = 0;
4258          max_plane = 1;
4259          // Initialize interp_filter here so we do not have to check for
4260          // inter block modes in get_pred_context_switchable_interp()
4261          mi->interp_filter = SWITCHABLE_FILTERS;
4262        }
4263
4264        rd_cost->rate = rate2;
4265        rd_cost->dist = distortion2;
4266        rd_cost->rdcost = this_rd;
4267        best_rd = this_rd;
4268        best_yrd =
4269            best_rd - RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
4270        best_mbmode = *mi;
4271        best_skip2 = this_skip2;
4272        if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
4273        memcpy(ctx->zcoeff_blk, x->zcoeff_blk[TX_4X4],
4274               sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
4275        ctx->sum_y_eobs = x->sum_y_eobs[TX_4X4];
4276
4277        for (i = 0; i < 4; i++) best_bmodes[i] = xd->mi[0]->bmi[i];
4278
4279        // TODO(debargha): enhance this test with a better distortion prediction
4280        // based on qp, activity mask and history
4281        if ((sf->mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
4282            (ref_index > MIN_EARLY_TERM_INDEX)) {
4283          int qstep = xd->plane[0].dequant[1];
4284          // TODO(debargha): Enhance this by specializing for each mode_index
4285          int scale = 4;
4286#if CONFIG_VP9_HIGHBITDEPTH
4287          if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
4288            qstep >>= (xd->bd - 8);
4289          }
4290#endif  // CONFIG_VP9_HIGHBITDEPTH
4291          if (x->source_variance < UINT_MAX) {
4292            const int var_adjust = (x->source_variance < 16);
4293            scale -= var_adjust;
4294          }
4295          if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
4296            early_term = 1;
4297          }
4298        }
4299      }
4300    }
4301
4302    /* keep record of best compound/single-only prediction */
4303    if (!disable_skip && ref_frame != INTRA_FRAME) {
4304      int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
4305
4306      if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4307        single_rate = rate2 - compmode_cost;
4308        hybrid_rate = rate2;
4309      } else {
4310        single_rate = rate2;
4311        hybrid_rate = rate2 + compmode_cost;
4312      }
4313
4314      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
4315      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
4316
4317      if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE])
4318        best_pred_rd[SINGLE_REFERENCE] = single_rd;
4319      else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE])
4320        best_pred_rd[COMPOUND_REFERENCE] = single_rd;
4321
4322      if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
4323        best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
4324    }
4325
4326    /* keep record of best filter type */
4327    if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
4328        cm->interp_filter != BILINEAR) {
4329      int64_t ref =
4330          filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
4331                                                       : cm->interp_filter];
4332      int64_t adj_rd;
4333      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4334        if (ref == INT64_MAX)
4335          adj_rd = 0;
4336        else if (filter_cache[i] == INT64_MAX)
4337          // when early termination is triggered, the encoder does not have
4338          // access to the rate-distortion cost. it only knows that the cost
4339          // should be above the maximum valid value. hence it takes the known
4340          // maximum plus an arbitrary constant as the rate-distortion cost.
4341          adj_rd = mask_filter - ref + 10;
4342        else
4343          adj_rd = filter_cache[i] - ref;
4344
4345        adj_rd += this_rd;
4346        best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
4347      }
4348    }
4349
4350    if (early_term) break;
4351
4352    if (x->skip && !comp_pred) break;
4353  }
4354
4355  if (best_rd >= best_rd_so_far) {
4356    rd_cost->rate = INT_MAX;
4357    rd_cost->rdcost = INT64_MAX;
4358    return;
4359  }
4360
4361  // If we used an estimate for the uv intra rd in the loop above...
4362  if (sf->use_uv_intra_rd_estimate) {
4363    // Do Intra UV best rd mode selection if best mode choice above was intra.
4364    if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
4365      *mi = best_mbmode;
4366      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra, &rate_uv_tokenonly,
4367                              &dist_uv, &skip_uv, BLOCK_8X8, TX_4X4);
4368    }
4369  }
4370
4371  if (best_rd == INT64_MAX) {
4372    rd_cost->rate = INT_MAX;
4373    rd_cost->dist = INT64_MAX;
4374    rd_cost->rdcost = INT64_MAX;
4375    return;
4376  }
4377
4378  assert((cm->interp_filter == SWITCHABLE) ||
4379         (cm->interp_filter == best_mbmode.interp_filter) ||
4380         !is_inter_block(&best_mbmode));
4381
4382  vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact, sf->adaptive_rd_thresh,
4383                            bsize, best_ref_index);
4384
4385  // macroblock modes
4386  *mi = best_mbmode;
4387  x->skip |= best_skip2;
4388  if (!is_inter_block(&best_mbmode)) {
4389    for (i = 0; i < 4; i++) xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
4390  } else {
4391    for (i = 0; i < 4; ++i)
4392      memcpy(&xd->mi[0]->bmi[i], &best_bmodes[i], sizeof(b_mode_info));
4393
4394    mi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
4395    mi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
4396  }
4397
4398  for (i = 0; i < REFERENCE_MODES; ++i) {
4399    if (best_pred_rd[i] == INT64_MAX)
4400      best_pred_diff[i] = INT_MIN;
4401    else
4402      best_pred_diff[i] = best_rd - best_pred_rd[i];
4403  }
4404
4405  if (!x->skip) {
4406    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4407      if (best_filter_rd[i] == INT64_MAX)
4408        best_filter_diff[i] = 0;
4409      else
4410        best_filter_diff[i] = best_rd - best_filter_rd[i];
4411    }
4412    if (cm->interp_filter == SWITCHABLE)
4413      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4414  } else {
4415    vp9_zero(best_filter_diff);
4416  }
4417
4418  store_coding_context(x, ctx, best_ref_index, best_pred_diff, best_filter_diff,
4419                       0);
4420}
4421