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