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