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