]> granicus.if.org Git - libvpx/blob - vp10/encoder/rdopt.c
Changes to exhaustive motion search.
[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 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           if (bestsme < INT_MAX) {
1842             int distortion;
1843             cpi->find_fractional_mv_step(
1844                 x,
1845                 new_mv,
1846                 &bsi->ref_mv[0]->as_mv,
1847                 cm->allow_high_precision_mv,
1848                 x->errorperbit, &cpi->fn_ptr[bsize],
1849                 cpi->sf.mv.subpel_force_stop,
1850                 cpi->sf.mv.subpel_iters_per_step,
1851                 cond_cost_list(cpi, cost_list),
1852                 x->nmvjointcost, x->mvcost,
1853                 &distortion,
1854                 &x->pred_sse[mbmi->ref_frame[0]],
1855                 NULL, 0, 0);
1856
1857             // save motion search result for use in compound prediction
1858             seg_mvs[i][mbmi->ref_frame[0]].as_mv = *new_mv;
1859           }
1860
1861           if (cpi->sf.adaptive_motion_search)
1862             x->pred_mv[mbmi->ref_frame[0]] = *new_mv;
1863
1864           // restore src pointers
1865           mi_buf_restore(x, orig_src, orig_pre);
1866         }
1867
1868         if (has_second_rf) {
1869           if (seg_mvs[i][mbmi->ref_frame[1]].as_int == INVALID_MV ||
1870               seg_mvs[i][mbmi->ref_frame[0]].as_int == INVALID_MV)
1871             continue;
1872         }
1873
1874         if (has_second_rf && this_mode == NEWMV &&
1875             mbmi->interp_filter == EIGHTTAP) {
1876           // adjust src pointers
1877           mi_buf_shift(x, i);
1878           if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
1879             int rate_mv;
1880             joint_motion_search(cpi, x, bsize, frame_mv[this_mode],
1881                                 mi_row, mi_col, seg_mvs[i],
1882                                 &rate_mv);
1883             seg_mvs[i][mbmi->ref_frame[0]].as_int =
1884                 frame_mv[this_mode][mbmi->ref_frame[0]].as_int;
1885             seg_mvs[i][mbmi->ref_frame[1]].as_int =
1886                 frame_mv[this_mode][mbmi->ref_frame[1]].as_int;
1887           }
1888           // restore src pointers
1889           mi_buf_restore(x, orig_src, orig_pre);
1890         }
1891
1892         bsi->rdstat[i][mode_idx].brate =
1893             set_and_cost_bmi_mvs(cpi, x, xd, i, this_mode, mode_mv[this_mode],
1894                                  frame_mv, seg_mvs[i], bsi->ref_mv,
1895                                  x->nmvjointcost, x->mvcost);
1896
1897         for (ref = 0; ref < 1 + has_second_rf; ++ref) {
1898           bsi->rdstat[i][mode_idx].mvs[ref].as_int =
1899               mode_mv[this_mode][ref].as_int;
1900           if (num_4x4_blocks_wide > 1)
1901             bsi->rdstat[i + 1][mode_idx].mvs[ref].as_int =
1902                 mode_mv[this_mode][ref].as_int;
1903           if (num_4x4_blocks_high > 1)
1904             bsi->rdstat[i + 2][mode_idx].mvs[ref].as_int =
1905                 mode_mv[this_mode][ref].as_int;
1906         }
1907
1908         // Trap vectors that reach beyond the UMV borders
1909         if (mv_check_bounds(x, &mode_mv[this_mode][0].as_mv) ||
1910             (has_second_rf &&
1911              mv_check_bounds(x, &mode_mv[this_mode][1].as_mv)))
1912           continue;
1913
1914         if (filter_idx > 0) {
1915           BEST_SEG_INFO *ref_bsi = bsi_buf;
1916           subpelmv = 0;
1917           have_ref = 1;
1918
1919           for (ref = 0; ref < 1 + has_second_rf; ++ref) {
1920             subpelmv |= mv_has_subpel(&mode_mv[this_mode][ref].as_mv);
1921             have_ref &= mode_mv[this_mode][ref].as_int ==
1922                 ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
1923           }
1924
1925           if (filter_idx > 1 && !subpelmv && !have_ref) {
1926             ref_bsi = bsi_buf + 1;
1927             have_ref = 1;
1928             for (ref = 0; ref < 1 + has_second_rf; ++ref)
1929               have_ref &= mode_mv[this_mode][ref].as_int ==
1930                   ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
1931           }
1932
1933           if (!subpelmv && have_ref &&
1934               ref_bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
1935             memcpy(&bsi->rdstat[i][mode_idx], &ref_bsi->rdstat[i][mode_idx],
1936                    sizeof(SEG_RDSTAT));
1937             if (num_4x4_blocks_wide > 1)
1938               bsi->rdstat[i + 1][mode_idx].eobs =
1939                   ref_bsi->rdstat[i + 1][mode_idx].eobs;
1940             if (num_4x4_blocks_high > 1)
1941               bsi->rdstat[i + 2][mode_idx].eobs =
1942                   ref_bsi->rdstat[i + 2][mode_idx].eobs;
1943
1944             if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
1945               mode_selected = this_mode;
1946               best_rd = bsi->rdstat[i][mode_idx].brdcost;
1947             }
1948             continue;
1949           }
1950         }
1951
1952         bsi->rdstat[i][mode_idx].brdcost =
1953             encode_inter_mb_segment(cpi, x,
1954                                     bsi->segment_rd - this_segment_rd, i,
1955                                     &bsi->rdstat[i][mode_idx].byrate,
1956                                     &bsi->rdstat[i][mode_idx].bdist,
1957                                     &bsi->rdstat[i][mode_idx].bsse,
1958                                     bsi->rdstat[i][mode_idx].ta,
1959                                     bsi->rdstat[i][mode_idx].tl,
1960                                     idy, idx,
1961                                     mi_row, mi_col);
1962         if (bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
1963           bsi->rdstat[i][mode_idx].brdcost += RDCOST(x->rdmult, x->rddiv,
1964                                             bsi->rdstat[i][mode_idx].brate, 0);
1965           bsi->rdstat[i][mode_idx].brate += bsi->rdstat[i][mode_idx].byrate;
1966           bsi->rdstat[i][mode_idx].eobs = p->eobs[i];
1967           if (num_4x4_blocks_wide > 1)
1968             bsi->rdstat[i + 1][mode_idx].eobs = p->eobs[i + 1];
1969           if (num_4x4_blocks_high > 1)
1970             bsi->rdstat[i + 2][mode_idx].eobs = p->eobs[i + 2];
1971         }
1972
1973         if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
1974           mode_selected = this_mode;
1975           best_rd = bsi->rdstat[i][mode_idx].brdcost;
1976         }
1977       } /*for each 4x4 mode*/
1978
1979       if (best_rd == INT64_MAX) {
1980         int iy, midx;
1981         for (iy = i + 1; iy < 4; ++iy)
1982           for (midx = 0; midx < INTER_MODES; ++midx)
1983             bsi->rdstat[iy][midx].brdcost = INT64_MAX;
1984         bsi->segment_rd = INT64_MAX;
1985         return INT64_MAX;
1986       }
1987
1988       mode_idx = INTER_OFFSET(mode_selected);
1989       memcpy(t_above, bsi->rdstat[i][mode_idx].ta, sizeof(t_above));
1990       memcpy(t_left, bsi->rdstat[i][mode_idx].tl, sizeof(t_left));
1991
1992       set_and_cost_bmi_mvs(cpi, x, xd, i, mode_selected, mode_mv[mode_selected],
1993                            frame_mv, seg_mvs[i], bsi->ref_mv, x->nmvjointcost,
1994                            x->mvcost);
1995
1996       br += bsi->rdstat[i][mode_idx].brate;
1997       bd += bsi->rdstat[i][mode_idx].bdist;
1998       block_sse += bsi->rdstat[i][mode_idx].bsse;
1999       segmentyrate += bsi->rdstat[i][mode_idx].byrate;
2000       this_segment_rd += bsi->rdstat[i][mode_idx].brdcost;
2001
2002       if (this_segment_rd > bsi->segment_rd) {
2003         int iy, midx;
2004         for (iy = i + 1; iy < 4; ++iy)
2005           for (midx = 0; midx < INTER_MODES; ++midx)
2006             bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2007         bsi->segment_rd = INT64_MAX;
2008         return INT64_MAX;
2009       }
2010     }
2011   } /* for each label */
2012
2013   bsi->r = br;
2014   bsi->d = bd;
2015   bsi->segment_yrate = segmentyrate;
2016   bsi->segment_rd = this_segment_rd;
2017   bsi->sse = block_sse;
2018
2019   // update the coding decisions
2020   for (k = 0; k < 4; ++k)
2021     bsi->modes[k] = mi->bmi[k].as_mode;
2022
2023   if (bsi->segment_rd > best_rd)
2024     return INT64_MAX;
2025   /* set it to the best */
2026   for (i = 0; i < 4; i++) {
2027     mode_idx = INTER_OFFSET(bsi->modes[i]);
2028     mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
2029     if (has_second_ref(mbmi))
2030       mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
2031     x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
2032     mi->bmi[i].as_mode = bsi->modes[i];
2033   }
2034
2035   /*
2036    * used to set mbmi->mv.as_int
2037    */
2038   *returntotrate = bsi->r;
2039   *returndistortion = bsi->d;
2040   *returnyrate = bsi->segment_yrate;
2041   *skippable = vp10_is_skippable_in_plane(x, BLOCK_8X8, 0);
2042   *psse = bsi->sse;
2043   mbmi->mode = bsi->modes[3];
2044
2045   return bsi->segment_rd;
2046 }
2047
2048 static void estimate_ref_frame_costs(const VP10_COMMON *cm,
2049                                      const MACROBLOCKD *xd,
2050                                      int segment_id,
2051                                      unsigned int *ref_costs_single,
2052                                      unsigned int *ref_costs_comp,
2053                                      vpx_prob *comp_mode_p) {
2054   int seg_ref_active = segfeature_active(&cm->seg, segment_id,
2055                                          SEG_LVL_REF_FRAME);
2056   if (seg_ref_active) {
2057     memset(ref_costs_single, 0, MAX_REF_FRAMES * sizeof(*ref_costs_single));
2058     memset(ref_costs_comp,   0, MAX_REF_FRAMES * sizeof(*ref_costs_comp));
2059     *comp_mode_p = 128;
2060   } else {
2061     vpx_prob intra_inter_p = vp10_get_intra_inter_prob(cm, xd);
2062     vpx_prob comp_inter_p = 128;
2063
2064     if (cm->reference_mode == REFERENCE_MODE_SELECT) {
2065       comp_inter_p = vp10_get_reference_mode_prob(cm, xd);
2066       *comp_mode_p = comp_inter_p;
2067     } else {
2068       *comp_mode_p = 128;
2069     }
2070
2071     ref_costs_single[INTRA_FRAME] = vp10_cost_bit(intra_inter_p, 0);
2072
2073     if (cm->reference_mode != COMPOUND_REFERENCE) {
2074       vpx_prob ref_single_p1 = vp10_get_pred_prob_single_ref_p1(cm, xd);
2075       vpx_prob ref_single_p2 = vp10_get_pred_prob_single_ref_p2(cm, xd);
2076       unsigned int base_cost = vp10_cost_bit(intra_inter_p, 1);
2077
2078       if (cm->reference_mode == REFERENCE_MODE_SELECT)
2079         base_cost += vp10_cost_bit(comp_inter_p, 0);
2080
2081       ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
2082           ref_costs_single[ALTREF_FRAME] = base_cost;
2083       ref_costs_single[LAST_FRAME]   += vp10_cost_bit(ref_single_p1, 0);
2084       ref_costs_single[GOLDEN_FRAME] += vp10_cost_bit(ref_single_p1, 1);
2085       ref_costs_single[ALTREF_FRAME] += vp10_cost_bit(ref_single_p1, 1);
2086       ref_costs_single[GOLDEN_FRAME] += vp10_cost_bit(ref_single_p2, 0);
2087       ref_costs_single[ALTREF_FRAME] += vp10_cost_bit(ref_single_p2, 1);
2088     } else {
2089       ref_costs_single[LAST_FRAME]   = 512;
2090       ref_costs_single[GOLDEN_FRAME] = 512;
2091       ref_costs_single[ALTREF_FRAME] = 512;
2092     }
2093     if (cm->reference_mode != SINGLE_REFERENCE) {
2094       vpx_prob ref_comp_p = vp10_get_pred_prob_comp_ref_p(cm, xd);
2095       unsigned int base_cost = vp10_cost_bit(intra_inter_p, 1);
2096
2097       if (cm->reference_mode == REFERENCE_MODE_SELECT)
2098         base_cost += vp10_cost_bit(comp_inter_p, 1);
2099
2100       ref_costs_comp[LAST_FRAME]   = base_cost + vp10_cost_bit(ref_comp_p, 0);
2101       ref_costs_comp[GOLDEN_FRAME] = base_cost + vp10_cost_bit(ref_comp_p, 1);
2102     } else {
2103       ref_costs_comp[LAST_FRAME]   = 512;
2104       ref_costs_comp[GOLDEN_FRAME] = 512;
2105     }
2106   }
2107 }
2108
2109 static void store_coding_context(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx,
2110                          int mode_index,
2111                          int64_t comp_pred_diff[REFERENCE_MODES],
2112                          int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS],
2113                          int skippable) {
2114   MACROBLOCKD *const xd = &x->e_mbd;
2115
2116   // Take a snapshot of the coding context so it can be
2117   // restored if we decide to encode this way
2118   ctx->skip = x->skip;
2119   ctx->skippable = skippable;
2120   ctx->best_mode_index = mode_index;
2121   ctx->mic = *xd->mi[0];
2122   ctx->mbmi_ext = *x->mbmi_ext;
2123   ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
2124   ctx->comp_pred_diff   = (int)comp_pred_diff[COMPOUND_REFERENCE];
2125   ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
2126
2127   memcpy(ctx->best_filter_diff, best_filter_diff,
2128          sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
2129 }
2130
2131 static void setup_buffer_inter(VP10_COMP *cpi, MACROBLOCK *x,
2132                                MV_REFERENCE_FRAME ref_frame,
2133                                BLOCK_SIZE block_size,
2134                                int mi_row, int mi_col,
2135                                int_mv frame_nearest_mv[MAX_REF_FRAMES],
2136                                int_mv frame_near_mv[MAX_REF_FRAMES],
2137                                struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
2138   const VP10_COMMON *cm = &cpi->common;
2139   const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
2140   MACROBLOCKD *const xd = &x->e_mbd;
2141   MODE_INFO *const mi = xd->mi[0];
2142   int_mv *const candidates = x->mbmi_ext->ref_mvs[ref_frame];
2143   const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
2144   MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2145
2146   assert(yv12 != NULL);
2147
2148   // TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
2149   // use the UV scaling factors.
2150   vp10_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
2151
2152   // Gets an initial list of candidate vectors from neighbours and orders them
2153   vp10_find_mv_refs(cm, xd, mi, ref_frame, candidates, mi_row, mi_col,
2154                    NULL, NULL, mbmi_ext->mode_context);
2155
2156   // Candidate refinement carried out at encoder and decoder
2157   vp10_find_best_ref_mvs(cm->allow_high_precision_mv, candidates,
2158                          &frame_nearest_mv[ref_frame],
2159                          &frame_near_mv[ref_frame]);
2160
2161   // Further refinement that is encode side only to test the top few candidates
2162   // in full and choose the best as the centre point for subsequent searches.
2163   // The current implementation doesn't support scaling.
2164   if (!vp10_is_scaled(sf) && block_size >= BLOCK_8X8)
2165     vp10_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride,
2166                 ref_frame, block_size);
2167 }
2168
2169 static void single_motion_search(VP10_COMP *cpi, MACROBLOCK *x,
2170                                  BLOCK_SIZE bsize,
2171                                  int mi_row, int mi_col,
2172                                  int_mv *tmp_mv, int *rate_mv) {
2173   MACROBLOCKD *xd = &x->e_mbd;
2174   const VP10_COMMON *cm = &cpi->common;
2175   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
2176   struct buf_2d backup_yv12[MAX_MB_PLANE] = {{0, 0}};
2177   int bestsme = INT_MAX;
2178   int step_param;
2179   int sadpb = x->sadperbit16;
2180   MV mvp_full;
2181   int ref = mbmi->ref_frame[0];
2182   MV ref_mv = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2183
2184   int tmp_col_min = x->mv_col_min;
2185   int tmp_col_max = x->mv_col_max;
2186   int tmp_row_min = x->mv_row_min;
2187   int tmp_row_max = x->mv_row_max;
2188   int cost_list[5];
2189
2190   const YV12_BUFFER_CONFIG *scaled_ref_frame = vp10_get_scaled_ref_frame(cpi,
2191                                                                         ref);
2192
2193   MV pred_mv[3];
2194   pred_mv[0] = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2195   pred_mv[1] = x->mbmi_ext->ref_mvs[ref][1].as_mv;
2196   pred_mv[2] = x->pred_mv[ref];
2197
2198   if (scaled_ref_frame) {
2199     int i;
2200     // Swap out the reference frame for a version that's been scaled to
2201     // match the resolution of the current frame, allowing the existing
2202     // motion search code to be used without additional modifications.
2203     for (i = 0; i < MAX_MB_PLANE; i++)
2204       backup_yv12[i] = xd->plane[i].pre[0];
2205
2206     vp10_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
2207   }
2208
2209   vp10_set_mv_search_range(x, &ref_mv);
2210
2211   // Work out the size of the first step in the mv step search.
2212   // 0 here is maximum length first step. 1 is VPXMAX >> 1 etc.
2213   if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) {
2214     // Take wtd average of the step_params based on the last frame's
2215     // max mv magnitude and that based on the best ref mvs of the current
2216     // block for the given reference.
2217     step_param = (vp10_init_search_range(x->max_mv_context[ref]) +
2218                     cpi->mv_step_param) / 2;
2219   } else {
2220     step_param = cpi->mv_step_param;
2221   }
2222
2223   if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64) {
2224     int boffset =
2225         2 * (b_width_log2_lookup[BLOCK_64X64] -
2226              VPXMIN(b_height_log2_lookup[bsize], b_width_log2_lookup[bsize]));
2227     step_param = VPXMAX(step_param, boffset);
2228   }
2229
2230   if (cpi->sf.adaptive_motion_search) {
2231     int bwl = b_width_log2_lookup[bsize];
2232     int bhl = b_height_log2_lookup[bsize];
2233     int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
2234
2235     if (tlevel < 5)
2236       step_param += 2;
2237
2238     // prev_mv_sad is not setup for dynamically scaled frames.
2239     if (cpi->oxcf.resize_mode != RESIZE_DYNAMIC) {
2240       int i;
2241       for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) {
2242         if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
2243           x->pred_mv[ref].row = 0;
2244           x->pred_mv[ref].col = 0;
2245           tmp_mv->as_int = INVALID_MV;
2246
2247           if (scaled_ref_frame) {
2248             int i;
2249             for (i = 0; i < MAX_MB_PLANE; ++i)
2250               xd->plane[i].pre[0] = backup_yv12[i];
2251           }
2252           return;
2253         }
2254       }
2255     }
2256   }
2257
2258   mvp_full = pred_mv[x->mv_best_ref_index[ref]];
2259
2260   mvp_full.col >>= 3;
2261   mvp_full.row >>= 3;
2262
2263   bestsme = vp10_full_pixel_search(cpi, x, bsize, &mvp_full, step_param, sadpb,
2264                                   cond_cost_list(cpi, cost_list),
2265                                   &ref_mv, &tmp_mv->as_mv, INT_MAX, 1);
2266
2267   x->mv_col_min = tmp_col_min;
2268   x->mv_col_max = tmp_col_max;
2269   x->mv_row_min = tmp_row_min;
2270   x->mv_row_max = tmp_row_max;
2271
2272   if (bestsme < INT_MAX) {
2273     int dis;  /* TODO: use dis in distortion calculation later. */
2274     cpi->find_fractional_mv_step(x, &tmp_mv->as_mv, &ref_mv,
2275                                  cm->allow_high_precision_mv,
2276                                  x->errorperbit,
2277                                  &cpi->fn_ptr[bsize],
2278                                  cpi->sf.mv.subpel_force_stop,
2279                                  cpi->sf.mv.subpel_iters_per_step,
2280                                  cond_cost_list(cpi, cost_list),
2281                                  x->nmvjointcost, x->mvcost,
2282                                  &dis, &x->pred_sse[ref], NULL, 0, 0);
2283   }
2284   *rate_mv = vp10_mv_bit_cost(&tmp_mv->as_mv, &ref_mv,
2285                              x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2286
2287   if (cpi->sf.adaptive_motion_search)
2288     x->pred_mv[ref] = tmp_mv->as_mv;
2289
2290   if (scaled_ref_frame) {
2291     int i;
2292     for (i = 0; i < MAX_MB_PLANE; i++)
2293       xd->plane[i].pre[0] = backup_yv12[i];
2294   }
2295 }
2296
2297
2298
2299 static INLINE void restore_dst_buf(MACROBLOCKD *xd,
2300                                    uint8_t *orig_dst[MAX_MB_PLANE],
2301                                    int orig_dst_stride[MAX_MB_PLANE]) {
2302   int i;
2303   for (i = 0; i < MAX_MB_PLANE; i++) {
2304     xd->plane[i].dst.buf = orig_dst[i];
2305     xd->plane[i].dst.stride = orig_dst_stride[i];
2306   }
2307 }
2308
2309 // In some situations we want to discount tha pparent cost of a new motion
2310 // vector. Where there is a subtle motion field and especially where there is
2311 // low spatial complexity then it can be hard to cover the cost of a new motion
2312 // vector in a single block, even if that motion vector reduces distortion.
2313 // However, once established that vector may be usable through the nearest and
2314 // near mv modes to reduce distortion in subsequent blocks and also improve
2315 // visual quality.
2316 static int discount_newmv_test(const VP10_COMP *cpi,
2317                                int this_mode,
2318                                int_mv this_mv,
2319                                int_mv (*mode_mv)[MAX_REF_FRAMES],
2320                                int ref_frame) {
2321   return (!cpi->rc.is_src_frame_alt_ref &&
2322           (this_mode == NEWMV) &&
2323           (this_mv.as_int != 0) &&
2324           ((mode_mv[NEARESTMV][ref_frame].as_int == 0) ||
2325            (mode_mv[NEARESTMV][ref_frame].as_int == INVALID_MV)) &&
2326           ((mode_mv[NEARMV][ref_frame].as_int == 0) ||
2327            (mode_mv[NEARMV][ref_frame].as_int == INVALID_MV)));
2328 }
2329
2330 #define LEFT_TOP_MARGIN ((VP9_ENC_BORDER_IN_PIXELS - VP9_INTERP_EXTEND) << 3)
2331 #define RIGHT_BOTTOM_MARGIN ((VP9_ENC_BORDER_IN_PIXELS -\
2332                                 VP9_INTERP_EXTEND) << 3)
2333
2334 // TODO(jingning): this mv clamping function should be block size dependent.
2335 static INLINE void clamp_mv2(MV *mv, const MACROBLOCKD *xd) {
2336   clamp_mv(mv, xd->mb_to_left_edge - LEFT_TOP_MARGIN,
2337                xd->mb_to_right_edge + RIGHT_BOTTOM_MARGIN,
2338                xd->mb_to_top_edge - LEFT_TOP_MARGIN,
2339                xd->mb_to_bottom_edge + RIGHT_BOTTOM_MARGIN);
2340 }
2341
2342 static int64_t handle_inter_mode(VP10_COMP *cpi, MACROBLOCK *x,
2343                                  BLOCK_SIZE bsize,
2344                                  int *rate2, int64_t *distortion,
2345                                  int *skippable,
2346                                  int *rate_y, int *rate_uv,
2347                                  int *disable_skip,
2348                                  int_mv (*mode_mv)[MAX_REF_FRAMES],
2349                                  int mi_row, int mi_col,
2350                                  int_mv single_newmv[MAX_REF_FRAMES],
2351                                  INTERP_FILTER (*single_filter)[MAX_REF_FRAMES],
2352                                  int (*single_skippable)[MAX_REF_FRAMES],
2353                                  int64_t *psse,
2354                                  const int64_t ref_best_rd,
2355                                  int64_t *mask_filter,
2356                                  int64_t filter_cache[]) {
2357   VP10_COMMON *cm = &cpi->common;
2358   MACROBLOCKD *xd = &x->e_mbd;
2359   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
2360   MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2361   const int is_comp_pred = has_second_ref(mbmi);
2362   const int this_mode = mbmi->mode;
2363   int_mv *frame_mv = mode_mv[this_mode];
2364   int i;
2365   int refs[2] = { mbmi->ref_frame[0],
2366     (mbmi->ref_frame[1] < 0 ? 0 : mbmi->ref_frame[1]) };
2367   int_mv cur_mv[2];
2368 #if CONFIG_VP9_HIGHBITDEPTH
2369   DECLARE_ALIGNED(16, uint16_t, tmp_buf16[MAX_MB_PLANE * 64 * 64]);
2370   uint8_t *tmp_buf;
2371 #else
2372   DECLARE_ALIGNED(16, uint8_t, tmp_buf[MAX_MB_PLANE * 64 * 64]);
2373 #endif  // CONFIG_VP9_HIGHBITDEPTH
2374   int pred_exists = 0;
2375   int intpel_mv;
2376   int64_t rd, tmp_rd, best_rd = INT64_MAX;
2377   int best_needs_copy = 0;
2378   uint8_t *orig_dst[MAX_MB_PLANE];
2379   int orig_dst_stride[MAX_MB_PLANE];
2380   int rs = 0;
2381   INTERP_FILTER best_filter = SWITCHABLE;
2382   uint8_t skip_txfm[MAX_MB_PLANE << 2] = {0};
2383   int64_t bsse[MAX_MB_PLANE << 2] = {0};
2384
2385   int bsl = mi_width_log2_lookup[bsize];
2386   int pred_filter_search = cpi->sf.cb_pred_filter_search ?
2387       (((mi_row + mi_col) >> bsl) +
2388        get_chessboard_index(cm->current_video_frame)) & 0x1 : 0;
2389
2390   int skip_txfm_sb = 0;
2391   int64_t skip_sse_sb = INT64_MAX;
2392   int64_t distortion_y = 0, distortion_uv = 0;
2393
2394 #if CONFIG_VP9_HIGHBITDEPTH
2395   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2396     tmp_buf = CONVERT_TO_BYTEPTR(tmp_buf16);
2397   } else {
2398     tmp_buf = (uint8_t *)tmp_buf16;
2399   }
2400 #endif  // CONFIG_VP9_HIGHBITDEPTH
2401
2402   if (pred_filter_search) {
2403     INTERP_FILTER af = SWITCHABLE, lf = SWITCHABLE;
2404     if (xd->up_available)
2405       af = xd->mi[-xd->mi_stride]->mbmi.interp_filter;
2406     if (xd->left_available)
2407       lf = xd->mi[-1]->mbmi.interp_filter;
2408
2409     if ((this_mode != NEWMV) || (af == lf))
2410       best_filter = af;
2411   }
2412
2413   if (is_comp_pred) {
2414     if (frame_mv[refs[0]].as_int == INVALID_MV ||
2415         frame_mv[refs[1]].as_int == INVALID_MV)
2416       return INT64_MAX;
2417
2418     if (cpi->sf.adaptive_mode_search) {
2419       if (single_filter[this_mode][refs[0]] ==
2420           single_filter[this_mode][refs[1]])
2421         best_filter = single_filter[this_mode][refs[0]];
2422     }
2423   }
2424
2425   if (this_mode == NEWMV) {
2426     int rate_mv;
2427     if (is_comp_pred) {
2428       // Initialize mv using single prediction mode result.
2429       frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
2430       frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
2431
2432       if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
2433         joint_motion_search(cpi, x, bsize, frame_mv,
2434                             mi_row, mi_col, single_newmv, &rate_mv);
2435       } else {
2436         rate_mv  = vp10_mv_bit_cost(&frame_mv[refs[0]].as_mv,
2437                                    &x->mbmi_ext->ref_mvs[refs[0]][0].as_mv,
2438                                    x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2439         rate_mv += vp10_mv_bit_cost(&frame_mv[refs[1]].as_mv,
2440                                    &x->mbmi_ext->ref_mvs[refs[1]][0].as_mv,
2441                                    x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2442       }
2443       *rate2 += rate_mv;
2444     } else {
2445       int_mv tmp_mv;
2446       single_motion_search(cpi, x, bsize, mi_row, mi_col,
2447                            &tmp_mv, &rate_mv);
2448       if (tmp_mv.as_int == INVALID_MV)
2449         return INT64_MAX;
2450
2451       frame_mv[refs[0]].as_int =
2452           xd->mi[0]->bmi[0].as_mv[0].as_int = tmp_mv.as_int;
2453       single_newmv[refs[0]].as_int = tmp_mv.as_int;
2454
2455       // Estimate the rate implications of a new mv but discount this
2456       // under certain circumstances where we want to help initiate a weak
2457       // motion field, where the distortion gain for a single block may not
2458       // be enough to overcome the cost of a new mv.
2459       if (discount_newmv_test(cpi, this_mode, tmp_mv, mode_mv, refs[0])) {
2460         *rate2 += VPXMAX((rate_mv / NEW_MV_DISCOUNT_FACTOR), 1);
2461       } else {
2462         *rate2 += rate_mv;
2463       }
2464     }
2465   }
2466
2467   for (i = 0; i < is_comp_pred + 1; ++i) {
2468     cur_mv[i] = frame_mv[refs[i]];
2469     // Clip "next_nearest" so that it does not extend to far out of image
2470     if (this_mode != NEWMV)
2471       clamp_mv2(&cur_mv[i].as_mv, xd);
2472
2473     if (mv_check_bounds(x, &cur_mv[i].as_mv))
2474       return INT64_MAX;
2475     mbmi->mv[i].as_int = cur_mv[i].as_int;
2476   }
2477
2478   // do first prediction into the destination buffer. Do the next
2479   // prediction into a temporary buffer. Then keep track of which one
2480   // of these currently holds the best predictor, and use the other
2481   // one for future predictions. In the end, copy from tmp_buf to
2482   // dst if necessary.
2483   for (i = 0; i < MAX_MB_PLANE; i++) {
2484     orig_dst[i] = xd->plane[i].dst.buf;
2485     orig_dst_stride[i] = xd->plane[i].dst.stride;
2486   }
2487
2488   // We don't include the cost of the second reference here, because there
2489   // are only three options: Last/Golden, ARF/Last or Golden/ARF, or in other
2490   // words if you present them in that order, the second one is always known
2491   // if the first is known.
2492   //
2493   // Under some circumstances we discount the cost of new mv mode to encourage
2494   // initiation of a motion field.
2495   if (discount_newmv_test(cpi, this_mode, frame_mv[refs[0]],
2496                           mode_mv, refs[0])) {
2497     *rate2 += VPXMIN(cost_mv_ref(cpi, this_mode,
2498                                  mbmi_ext->mode_context[refs[0]]),
2499                      cost_mv_ref(cpi, NEARESTMV,
2500                                  mbmi_ext->mode_context[refs[0]]));
2501   } else {
2502     *rate2 += cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]);
2503   }
2504
2505   if (RDCOST(x->rdmult, x->rddiv, *rate2, 0) > ref_best_rd &&
2506       mbmi->mode != NEARESTMV)
2507     return INT64_MAX;
2508
2509   pred_exists = 0;
2510   // Are all MVs integer pel for Y and UV
2511   intpel_mv = !mv_has_subpel(&mbmi->mv[0].as_mv);
2512   if (is_comp_pred)
2513     intpel_mv &= !mv_has_subpel(&mbmi->mv[1].as_mv);
2514
2515   // Search for best switchable filter by checking the variance of
2516   // pred error irrespective of whether the filter will be used
2517   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
2518     filter_cache[i] = INT64_MAX;
2519
2520   if (cm->interp_filter != BILINEAR) {
2521     if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
2522       best_filter = EIGHTTAP;
2523     } else if (best_filter == SWITCHABLE) {
2524       int newbest;
2525       int tmp_rate_sum = 0;
2526       int64_t tmp_dist_sum = 0;
2527
2528       for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
2529         int j;
2530         int64_t rs_rd;
2531         int tmp_skip_sb = 0;
2532         int64_t tmp_skip_sse = INT64_MAX;
2533
2534         mbmi->interp_filter = i;
2535         rs = vp10_get_switchable_rate(cpi, xd);
2536         rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
2537
2538         if (i > 0 && intpel_mv) {
2539           rd = RDCOST(x->rdmult, x->rddiv, tmp_rate_sum, tmp_dist_sum);
2540           filter_cache[i] = rd;
2541           filter_cache[SWITCHABLE_FILTERS] =
2542               VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2543           if (cm->interp_filter == SWITCHABLE)
2544             rd += rs_rd;
2545           *mask_filter = VPXMAX(*mask_filter, rd);
2546         } else {
2547           int rate_sum = 0;
2548           int64_t dist_sum = 0;
2549           if (i > 0 && cpi->sf.adaptive_interp_filter_search &&
2550               (cpi->sf.interp_filter_search_mask & (1 << i))) {
2551             rate_sum = INT_MAX;
2552             dist_sum = INT64_MAX;
2553             continue;
2554           }
2555
2556           if ((cm->interp_filter == SWITCHABLE &&
2557                (!i || best_needs_copy)) ||
2558               (cm->interp_filter != SWITCHABLE &&
2559                (cm->interp_filter == mbmi->interp_filter ||
2560                 (i == 0 && intpel_mv)))) {
2561             restore_dst_buf(xd, orig_dst, orig_dst_stride);
2562           } else {
2563             for (j = 0; j < MAX_MB_PLANE; j++) {
2564               xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
2565               xd->plane[j].dst.stride = 64;
2566             }
2567           }
2568           vp10_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
2569           model_rd_for_sb(cpi, bsize, x, xd, &rate_sum, &dist_sum,
2570                           &tmp_skip_sb, &tmp_skip_sse);
2571
2572           rd = RDCOST(x->rdmult, x->rddiv, rate_sum, dist_sum);
2573           filter_cache[i] = rd;
2574           filter_cache[SWITCHABLE_FILTERS] =
2575               VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2576           if (cm->interp_filter == SWITCHABLE)
2577             rd += rs_rd;
2578           *mask_filter = VPXMAX(*mask_filter, rd);
2579
2580           if (i == 0 && intpel_mv) {
2581             tmp_rate_sum = rate_sum;
2582             tmp_dist_sum = dist_sum;
2583           }
2584         }
2585
2586         if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
2587           if (rd / 2 > ref_best_rd) {
2588             restore_dst_buf(xd, orig_dst, orig_dst_stride);
2589             return INT64_MAX;
2590           }
2591         }
2592         newbest = i == 0 || rd < best_rd;
2593
2594         if (newbest) {
2595           best_rd = rd;
2596           best_filter = mbmi->interp_filter;
2597           if (cm->interp_filter == SWITCHABLE && i && !intpel_mv)
2598             best_needs_copy = !best_needs_copy;
2599         }
2600
2601         if ((cm->interp_filter == SWITCHABLE && newbest) ||
2602             (cm->interp_filter != SWITCHABLE &&
2603              cm->interp_filter == mbmi->interp_filter)) {
2604           pred_exists = 1;
2605           tmp_rd = best_rd;
2606
2607           skip_txfm_sb = tmp_skip_sb;
2608           skip_sse_sb = tmp_skip_sse;
2609           memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
2610           memcpy(bsse, x->bsse, sizeof(bsse));
2611         }
2612       }
2613       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2614     }
2615   }
2616   // Set the appropriate filter
2617   mbmi->interp_filter = cm->interp_filter != SWITCHABLE ?
2618       cm->interp_filter : best_filter;
2619   rs = cm->interp_filter == SWITCHABLE ? vp10_get_switchable_rate(cpi, xd) : 0;
2620
2621   if (pred_exists) {
2622     if (best_needs_copy) {
2623       // again temporarily set the buffers to local memory to prevent a memcpy
2624       for (i = 0; i < MAX_MB_PLANE; i++) {
2625         xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
2626         xd->plane[i].dst.stride = 64;
2627       }
2628     }
2629     rd = tmp_rd + RDCOST(x->rdmult, x->rddiv, rs, 0);
2630   } else {
2631     int tmp_rate;
2632     int64_t tmp_dist;
2633     // Handles the special case when a filter that is not in the
2634     // switchable list (ex. bilinear) is indicated at the frame level, or
2635     // skip condition holds.
2636     vp10_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
2637     model_rd_for_sb(cpi, bsize, x, xd, &tmp_rate, &tmp_dist,
2638                     &skip_txfm_sb, &skip_sse_sb);
2639     rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
2640     memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
2641     memcpy(bsse, x->bsse, sizeof(bsse));
2642   }
2643
2644   if (!is_comp_pred)
2645     single_filter[this_mode][refs[0]] = mbmi->interp_filter;
2646
2647   if (cpi->sf.adaptive_mode_search)
2648     if (is_comp_pred)
2649       if (single_skippable[this_mode][refs[0]] &&
2650           single_skippable[this_mode][refs[1]])
2651         memset(skip_txfm, SKIP_TXFM_AC_DC, sizeof(skip_txfm));
2652
2653   if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
2654     // if current pred_error modeled rd is substantially more than the best
2655     // so far, do not bother doing full rd
2656     if (rd / 2 > ref_best_rd) {
2657       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2658       return INT64_MAX;
2659     }
2660   }
2661
2662   if (cm->interp_filter == SWITCHABLE)
2663     *rate2 += rs;
2664
2665   memcpy(x->skip_txfm, skip_txfm, sizeof(skip_txfm));
2666   memcpy(x->bsse, bsse, sizeof(bsse));
2667
2668   if (!skip_txfm_sb) {
2669     int skippable_y, skippable_uv;
2670     int64_t sseuv = INT64_MAX;
2671     int64_t rdcosty = INT64_MAX;
2672
2673     // Y cost and distortion
2674     vp10_subtract_plane(x, bsize, 0);
2675     super_block_yrd(cpi, x, rate_y, &distortion_y, &skippable_y, psse,
2676                     bsize, ref_best_rd);
2677
2678     if (*rate_y == INT_MAX) {
2679       *rate2 = INT_MAX;
2680       *distortion = INT64_MAX;
2681       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2682       return INT64_MAX;
2683     }
2684
2685     *rate2 += *rate_y;
2686     *distortion += distortion_y;
2687
2688     rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
2689     rdcosty = VPXMIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
2690
2691     if (!super_block_uvrd(cpi, x, rate_uv, &distortion_uv, &skippable_uv,
2692                           &sseuv, bsize, ref_best_rd - rdcosty)) {
2693       *rate2 = INT_MAX;
2694       *distortion = INT64_MAX;
2695       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2696       return INT64_MAX;
2697     }
2698
2699     *psse += sseuv;
2700     *rate2 += *rate_uv;
2701     *distortion += distortion_uv;
2702     *skippable = skippable_y && skippable_uv;
2703   } else {
2704     x->skip = 1;
2705     *disable_skip = 1;
2706
2707     // The cost of skip bit needs to be added.
2708     *rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 1);
2709
2710     *distortion = skip_sse_sb;
2711   }
2712
2713   if (!is_comp_pred)
2714     single_skippable[this_mode][refs[0]] = *skippable;
2715
2716   restore_dst_buf(xd, orig_dst, orig_dst_stride);
2717   return 0;  // The rate-distortion cost will be re-calculated by caller.
2718 }
2719
2720 void vp10_rd_pick_intra_mode_sb(VP10_COMP *cpi, MACROBLOCK *x,
2721                                RD_COST *rd_cost, BLOCK_SIZE bsize,
2722                                PICK_MODE_CONTEXT *ctx, int64_t best_rd) {
2723   VP10_COMMON *const cm = &cpi->common;
2724   MACROBLOCKD *const xd = &x->e_mbd;
2725   struct macroblockd_plane *const pd = xd->plane;
2726   int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
2727   int y_skip = 0, uv_skip = 0;
2728   int64_t dist_y = 0, dist_uv = 0;
2729   TX_SIZE max_uv_tx_size;
2730   ctx->skip = 0;
2731   xd->mi[0]->mbmi.ref_frame[0] = INTRA_FRAME;
2732   xd->mi[0]->mbmi.ref_frame[1] = NONE;
2733
2734   if (bsize >= BLOCK_8X8) {
2735     if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly,
2736                                &dist_y, &y_skip, bsize,
2737                                best_rd) >= best_rd) {
2738       rd_cost->rate = INT_MAX;
2739       return;
2740     }
2741   } else {
2742     y_skip = 0;
2743     if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
2744                                      &dist_y, best_rd) >= best_rd) {
2745       rd_cost->rate = INT_MAX;
2746       return;
2747     }
2748   }
2749   max_uv_tx_size = get_uv_tx_size_impl(xd->mi[0]->mbmi.tx_size, bsize,
2750                                        pd[1].subsampling_x,
2751                                        pd[1].subsampling_y);
2752   rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly,
2753                           &dist_uv, &uv_skip, VPXMAX(BLOCK_8X8, bsize),
2754                           max_uv_tx_size);
2755
2756   if (y_skip && uv_skip) {
2757     rd_cost->rate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
2758                     vp10_cost_bit(vp10_get_skip_prob(cm, xd), 1);
2759     rd_cost->dist = dist_y + dist_uv;
2760   } else {
2761     rd_cost->rate = rate_y + rate_uv +
2762                       vp10_cost_bit(vp10_get_skip_prob(cm, xd), 0);
2763     rd_cost->dist = dist_y + dist_uv;
2764   }
2765
2766   ctx->mic = *xd->mi[0];
2767   ctx->mbmi_ext = *x->mbmi_ext;
2768   rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2769 }
2770
2771 // This function is designed to apply a bias or adjustment to an rd value based
2772 // on the relative variance of the source and reconstruction.
2773 #define LOW_VAR_THRESH 16
2774 #define VLOW_ADJ_MAX 25
2775 #define VHIGH_ADJ_MAX 8
2776 static void rd_variance_adjustment(VP10_COMP *cpi,
2777                                    MACROBLOCK *x,
2778                                    BLOCK_SIZE bsize,
2779                                    int64_t *this_rd,
2780                                    MV_REFERENCE_FRAME ref_frame,
2781                                    unsigned int source_variance) {
2782   MACROBLOCKD *const xd = &x->e_mbd;
2783   unsigned int recon_variance;
2784   unsigned int absvar_diff = 0;
2785   int64_t var_error = 0;
2786   int64_t var_factor = 0;
2787
2788   if (*this_rd == INT64_MAX)
2789     return;
2790
2791 #if CONFIG_VP9_HIGHBITDEPTH
2792   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2793     recon_variance =
2794       vp10_high_get_sby_perpixel_variance(cpi, &xd->plane[0].dst, bsize, xd->bd);
2795   } else {
2796     recon_variance =
2797       vp10_get_sby_perpixel_variance(cpi, &xd->plane[0].dst, bsize);
2798   }
2799 #else
2800   recon_variance =
2801     vp10_get_sby_perpixel_variance(cpi, &xd->plane[0].dst, bsize);
2802 #endif  // CONFIG_VP9_HIGHBITDEPTH
2803
2804   if ((source_variance + recon_variance) > LOW_VAR_THRESH) {
2805     absvar_diff = (source_variance > recon_variance)
2806       ? (source_variance - recon_variance)
2807       : (recon_variance - source_variance);
2808
2809     var_error = ((int64_t)200 * source_variance * recon_variance) /
2810       (((int64_t)source_variance * source_variance) +
2811        ((int64_t)recon_variance * recon_variance));
2812     var_error = 100 - var_error;
2813   }
2814
2815   // Source variance above a threshold and ref frame is intra.
2816   // This case is targeted mainly at discouraging intra modes that give rise
2817   // to a predictor with a low spatial complexity compared to the source.
2818   if ((source_variance > LOW_VAR_THRESH) && (ref_frame == INTRA_FRAME) &&
2819       (source_variance > recon_variance)) {
2820     var_factor = VPXMIN(absvar_diff, VPXMIN(VLOW_ADJ_MAX, var_error));
2821   // A second possible case of interest is where the source variance
2822   // is very low and we wish to discourage false texture or motion trails.
2823   } else if ((source_variance < (LOW_VAR_THRESH >> 1)) &&
2824              (recon_variance > source_variance)) {
2825     var_factor = VPXMIN(absvar_diff, VPXMIN(VHIGH_ADJ_MAX, var_error));
2826   }
2827   *this_rd += (*this_rd * var_factor) / 100;
2828 }
2829
2830
2831 // Do we have an internal image edge (e.g. formatting bars).
2832 int vp10_internal_image_edge(VP10_COMP *cpi) {
2833   return (cpi->oxcf.pass == 2) &&
2834     ((cpi->twopass.this_frame_stats.inactive_zone_rows > 0) ||
2835     (cpi->twopass.this_frame_stats.inactive_zone_cols > 0));
2836 }
2837
2838 // Checks to see if a super block is on a horizontal image edge.
2839 // In most cases this is the "real" edge unless there are formatting
2840 // bars embedded in the stream.
2841 int vp10_active_h_edge(VP10_COMP *cpi, int mi_row, int mi_step) {
2842   int top_edge = 0;
2843   int bottom_edge = cpi->common.mi_rows;
2844   int is_active_h_edge = 0;
2845
2846   // For two pass account for any formatting bars detected.
2847   if (cpi->oxcf.pass == 2) {
2848     TWO_PASS *twopass = &cpi->twopass;
2849
2850     // The inactive region is specified in MBs not mi units.
2851     // The image edge is in the following MB row.
2852     top_edge += (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
2853
2854     bottom_edge -= (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
2855     bottom_edge = VPXMAX(top_edge, bottom_edge);
2856   }
2857
2858   if (((top_edge >= mi_row) && (top_edge < (mi_row + mi_step))) ||
2859       ((bottom_edge >= mi_row) && (bottom_edge < (mi_row + mi_step)))) {
2860     is_active_h_edge = 1;
2861   }
2862   return is_active_h_edge;
2863 }
2864
2865 // Checks to see if a super block is on a vertical image edge.
2866 // In most cases this is the "real" edge unless there are formatting
2867 // bars embedded in the stream.
2868 int vp10_active_v_edge(VP10_COMP *cpi, int mi_col, int mi_step) {
2869   int left_edge = 0;
2870   int right_edge = cpi->common.mi_cols;
2871   int is_active_v_edge = 0;
2872
2873   // For two pass account for any formatting bars detected.
2874   if (cpi->oxcf.pass == 2) {
2875     TWO_PASS *twopass = &cpi->twopass;
2876
2877     // The inactive region is specified in MBs not mi units.
2878     // The image edge is in the following MB row.
2879     left_edge += (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
2880
2881     right_edge -= (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
2882     right_edge = VPXMAX(left_edge, right_edge);
2883   }
2884
2885   if (((left_edge >= mi_col) && (left_edge < (mi_col + mi_step))) ||
2886       ((right_edge >= mi_col) && (right_edge < (mi_col + mi_step)))) {
2887     is_active_v_edge = 1;
2888   }
2889   return is_active_v_edge;
2890 }
2891
2892 // Checks to see if a super block is at the edge of the active image.
2893 // In most cases this is the "real" edge unless there are formatting
2894 // bars embedded in the stream.
2895 int vp10_active_edge_sb(VP10_COMP *cpi,
2896                        int mi_row, int mi_col) {
2897   return vp10_active_h_edge(cpi, mi_row, MI_BLOCK_SIZE) ||
2898          vp10_active_v_edge(cpi, mi_col, MI_BLOCK_SIZE);
2899 }
2900
2901 void vp10_rd_pick_inter_mode_sb(VP10_COMP *cpi,
2902                                 TileDataEnc *tile_data,
2903                                 MACROBLOCK *x,
2904                                 int mi_row, int mi_col,
2905                                 RD_COST *rd_cost, BLOCK_SIZE bsize,
2906                                 PICK_MODE_CONTEXT *ctx,
2907                                 int64_t best_rd_so_far) {
2908   VP10_COMMON *const cm = &cpi->common;
2909   RD_OPT *const rd_opt = &cpi->rd;
2910   SPEED_FEATURES *const sf = &cpi->sf;
2911   MACROBLOCKD *const xd = &x->e_mbd;
2912   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
2913   MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2914   const struct segmentation *const seg = &cm->seg;
2915   PREDICTION_MODE this_mode;
2916   MV_REFERENCE_FRAME ref_frame, second_ref_frame;
2917   unsigned char segment_id = mbmi->segment_id;
2918   int comp_pred, i, k;
2919   int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
2920   struct buf_2d yv12_mb[4][MAX_MB_PLANE];
2921   int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
2922   INTERP_FILTER single_inter_filter[MB_MODE_COUNT][MAX_REF_FRAMES];
2923   int single_skippable[MB_MODE_COUNT][MAX_REF_FRAMES];
2924   static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
2925                                     VP9_ALT_FLAG };
2926   int64_t best_rd = best_rd_so_far;
2927   int64_t best_pred_diff[REFERENCE_MODES];
2928   int64_t best_pred_rd[REFERENCE_MODES];
2929   int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
2930   int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
2931   MB_MODE_INFO best_mbmode;
2932   int best_mode_skippable = 0;
2933   int midx, best_mode_index = -1;
2934   unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
2935   vpx_prob comp_mode_p;
2936   int64_t best_intra_rd = INT64_MAX;
2937   unsigned int best_pred_sse = UINT_MAX;
2938   PREDICTION_MODE best_intra_mode = DC_PRED;
2939   int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
2940   int64_t dist_uv[TX_SIZES];
2941   int skip_uv[TX_SIZES];
2942   PREDICTION_MODE mode_uv[TX_SIZES];
2943   const int intra_cost_penalty = vp10_get_intra_cost_penalty(
2944       cm->base_qindex, cm->y_dc_delta_q, cm->bit_depth);
2945   int best_skip2 = 0;
2946   uint8_t ref_frame_skip_mask[2] = { 0 };
2947   uint16_t mode_skip_mask[MAX_REF_FRAMES] = { 0 };
2948   int mode_skip_start = sf->mode_skip_start + 1;
2949   const int *const rd_threshes = rd_opt->threshes[segment_id][bsize];
2950   const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
2951   int64_t mode_threshold[MAX_MODES];
2952   int *mode_map = tile_data->mode_map[bsize];
2953   const int mode_search_skip_flags = sf->mode_search_skip_flags;
2954   int64_t mask_filter = 0;
2955   int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
2956
2957   vp10_zero(best_mbmode);
2958
2959   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
2960     filter_cache[i] = INT64_MAX;
2961
2962   estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
2963                            &comp_mode_p);
2964
2965   for (i = 0; i < REFERENCE_MODES; ++i)
2966     best_pred_rd[i] = INT64_MAX;
2967   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
2968     best_filter_rd[i] = INT64_MAX;
2969   for (i = 0; i < TX_SIZES; i++)
2970     rate_uv_intra[i] = INT_MAX;
2971   for (i = 0; i < MAX_REF_FRAMES; ++i)
2972     x->pred_sse[i] = INT_MAX;
2973   for (i = 0; i < MB_MODE_COUNT; ++i) {
2974     for (k = 0; k < MAX_REF_FRAMES; ++k) {
2975       single_inter_filter[i][k] = SWITCHABLE;
2976       single_skippable[i][k] = 0;
2977     }
2978   }
2979
2980   rd_cost->rate = INT_MAX;
2981
2982   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2983     x->pred_mv_sad[ref_frame] = INT_MAX;
2984     if (cpi->ref_frame_flags & flag_list[ref_frame]) {
2985       assert(get_ref_frame_buffer(cpi, ref_frame) != NULL);
2986       setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
2987                          frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
2988     }
2989     frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
2990     frame_mv[ZEROMV][ref_frame].as_int = 0;
2991   }
2992
2993   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2994     if (!(cpi->ref_frame_flags & flag_list[ref_frame])) {
2995       // Skip checking missing references in both single and compound reference
2996       // modes. Note that a mode will be skipped iff both reference frames
2997       // are masked out.
2998       ref_frame_skip_mask[0] |= (1 << ref_frame);
2999       ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3000     } else {
3001       for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
3002         // Skip fixed mv modes for poor references
3003         if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
3004           mode_skip_mask[ref_frame] |= INTER_NEAREST_NEAR_ZERO;
3005           break;
3006         }
3007       }
3008     }
3009     // If the segment reference frame feature is enabled....
3010     // then do nothing if the current ref frame is not allowed..
3011     if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3012         get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
3013       ref_frame_skip_mask[0] |= (1 << ref_frame);
3014       ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3015     }
3016   }
3017
3018   // Disable this drop out case if the ref frame
3019   // segment level feature is enabled for this segment. This is to
3020   // prevent the possibility that we end up unable to pick any mode.
3021   if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
3022     // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
3023     // unless ARNR filtering is enabled in which case we want
3024     // an unfiltered alternative. We allow near/nearest as well
3025     // because they may result in zero-zero MVs but be cheaper.
3026     if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
3027       ref_frame_skip_mask[0] = (1 << LAST_FRAME) | (1 << GOLDEN_FRAME);
3028       ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3029       mode_skip_mask[ALTREF_FRAME] = ~INTER_NEAREST_NEAR_ZERO;
3030       if (frame_mv[NEARMV][ALTREF_FRAME].as_int != 0)
3031         mode_skip_mask[ALTREF_FRAME] |= (1 << NEARMV);
3032       if (frame_mv[NEARESTMV][ALTREF_FRAME].as_int != 0)
3033         mode_skip_mask[ALTREF_FRAME] |= (1 << NEARESTMV);
3034     }
3035   }
3036
3037   if (cpi->rc.is_src_frame_alt_ref) {
3038     if (sf->alt_ref_search_fp) {
3039       mode_skip_mask[ALTREF_FRAME] = 0;
3040       ref_frame_skip_mask[0] = ~(1 << ALTREF_FRAME);
3041       ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3042     }
3043   }
3044
3045   if (sf->alt_ref_search_fp)
3046     if (!cm->show_frame && x->pred_mv_sad[GOLDEN_FRAME] < INT_MAX)
3047       if (x->pred_mv_sad[ALTREF_FRAME] > (x->pred_mv_sad[GOLDEN_FRAME] << 1))
3048         mode_skip_mask[ALTREF_FRAME] |= INTER_ALL;
3049
3050   if (sf->adaptive_mode_search) {
3051     if (cm->show_frame && !cpi->rc.is_src_frame_alt_ref &&
3052         cpi->rc.frames_since_golden >= 3)
3053       if (x->pred_mv_sad[GOLDEN_FRAME] > (x->pred_mv_sad[LAST_FRAME] << 1))
3054         mode_skip_mask[GOLDEN_FRAME] |= INTER_ALL;
3055   }
3056
3057   if (bsize > sf->max_intra_bsize) {
3058     ref_frame_skip_mask[0] |= (1 << INTRA_FRAME);
3059     ref_frame_skip_mask[1] |= (1 << INTRA_FRAME);
3060   }
3061
3062   mode_skip_mask[INTRA_FRAME] |=
3063       ~(sf->intra_y_mode_mask[max_txsize_lookup[bsize]]);
3064
3065   for (i = 0; i <= LAST_NEW_MV_INDEX; ++i)
3066     mode_threshold[i] = 0;
3067   for (i = LAST_NEW_MV_INDEX + 1; i < MAX_MODES; ++i)
3068     mode_threshold[i] = ((int64_t)rd_threshes[i] * rd_thresh_freq_fact[i]) >> 5;
3069
3070   midx =  sf->schedule_mode_search ? mode_skip_start : 0;
3071   while (midx > 4) {
3072     uint8_t end_pos = 0;
3073     for (i = 5; i < midx; ++i) {
3074       if (mode_threshold[mode_map[i - 1]] > mode_threshold[mode_map[i]]) {
3075         uint8_t tmp = mode_map[i];
3076         mode_map[i] = mode_map[i - 1];
3077         mode_map[i - 1] = tmp;
3078         end_pos = i;
3079       }
3080     }
3081     midx = end_pos;
3082   }
3083
3084   for (midx = 0; midx < MAX_MODES; ++midx) {
3085     int mode_index = mode_map[midx];
3086     int mode_excluded = 0;
3087     int64_t this_rd = INT64_MAX;
3088     int disable_skip = 0;
3089     int compmode_cost = 0;
3090     int rate2 = 0, rate_y = 0, rate_uv = 0;
3091     int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3092     int skippable = 0;
3093     int this_skip2 = 0;
3094     int64_t total_sse = INT64_MAX;
3095     int early_term = 0;
3096
3097     this_mode = vp10_mode_order[mode_index].mode;
3098     ref_frame = vp10_mode_order[mode_index].ref_frame[0];
3099     second_ref_frame = vp10_mode_order[mode_index].ref_frame[1];
3100
3101     // Look at the reference frame of the best mode so far and set the
3102     // skip mask to look at a subset of the remaining modes.
3103     if (midx == mode_skip_start && best_mode_index >= 0) {
3104       switch (best_mbmode.ref_frame[0]) {
3105         case INTRA_FRAME:
3106           break;
3107         case LAST_FRAME:
3108           ref_frame_skip_mask[0] |= LAST_FRAME_MODE_MASK;
3109           ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3110           break;
3111         case GOLDEN_FRAME:
3112           ref_frame_skip_mask[0] |= GOLDEN_FRAME_MODE_MASK;
3113           ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3114           break;
3115         case ALTREF_FRAME:
3116           ref_frame_skip_mask[0] |= ALT_REF_MODE_MASK;
3117           break;
3118         case NONE:
3119         case MAX_REF_FRAMES:
3120           assert(0 && "Invalid Reference frame");
3121           break;
3122       }
3123     }
3124
3125     if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
3126         (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
3127       continue;
3128
3129     if (mode_skip_mask[ref_frame] & (1 << this_mode))
3130       continue;
3131
3132     // Test best rd so far against threshold for trying this mode.
3133     if (best_mode_skippable && sf->schedule_mode_search)
3134       mode_threshold[mode_index] <<= 1;
3135
3136     if (best_rd < mode_threshold[mode_index])
3137       continue;
3138
3139     comp_pred = second_ref_frame > INTRA_FRAME;
3140     if (comp_pred) {
3141       if (!cpi->allow_comp_inter_inter)
3142         continue;
3143
3144       // Skip compound inter modes if ARF is not available.
3145       if (!(cpi->ref_frame_flags & flag_list[second_ref_frame]))
3146         continue;
3147
3148       // Do not allow compound prediction if the segment level reference frame
3149       // feature is in use as in this case there can only be one reference.
3150       if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
3151         continue;
3152
3153       if ((mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3154           best_mode_index >= 0 && best_mbmode.ref_frame[0] == INTRA_FRAME)
3155         continue;
3156
3157       mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3158     } else {
3159       if (ref_frame != INTRA_FRAME)
3160         mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3161     }
3162
3163     if (ref_frame == INTRA_FRAME) {
3164       if (sf->adaptive_mode_search)
3165         if ((x->source_variance << num_pels_log2_lookup[bsize]) > best_pred_sse)
3166           continue;
3167
3168       if (this_mode != DC_PRED) {
3169         // Disable intra modes other than DC_PRED for blocks with low variance
3170         // Threshold for intra skipping based on source variance
3171         // TODO(debargha): Specialize the threshold for super block sizes
3172         const unsigned int skip_intra_var_thresh = 64;
3173         if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
3174             x->source_variance < skip_intra_var_thresh)
3175           continue;
3176         // Only search the oblique modes if the best so far is
3177         // one of the neighboring directional modes
3178         if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
3179             (this_mode >= D45_PRED && this_mode <= TM_PRED)) {
3180           if (best_mode_index >= 0 &&
3181               best_mbmode.ref_frame[0] > INTRA_FRAME)
3182             continue;
3183         }
3184         if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
3185           if (conditional_skipintra(this_mode, best_intra_mode))
3186               continue;
3187         }
3188       }
3189     } else {
3190       const MV_REFERENCE_FRAME ref_frames[2] = {ref_frame, second_ref_frame};
3191       if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv,
3192                               this_mode, ref_frames))
3193         continue;
3194     }
3195
3196     mbmi->mode = this_mode;
3197     mbmi->uv_mode = DC_PRED;
3198     mbmi->ref_frame[0] = ref_frame;
3199     mbmi->ref_frame[1] = second_ref_frame;
3200     // Evaluate all sub-pel filters irrespective of whether we can use
3201     // them for this frame.
3202     mbmi->interp_filter = cm->interp_filter == SWITCHABLE ? EIGHTTAP
3203                                                           : cm->interp_filter;
3204     mbmi->mv[0].as_int = mbmi->mv[1].as_int = 0;
3205
3206     x->skip = 0;
3207     set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3208
3209     // Select prediction reference frames.
3210     for (i = 0; i < MAX_MB_PLANE; i++) {
3211       xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3212       if (comp_pred)
3213         xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3214     }
3215
3216     if (ref_frame == INTRA_FRAME) {
3217       TX_SIZE uv_tx;
3218       struct macroblockd_plane *const pd = &xd->plane[1];
3219       memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
3220       super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable,
3221                       NULL, bsize, best_rd);
3222       if (rate_y == INT_MAX)
3223         continue;
3224
3225       uv_tx = get_uv_tx_size_impl(mbmi->tx_size, bsize, pd->subsampling_x,
3226                                   pd->subsampling_y);
3227       if (rate_uv_intra[uv_tx] == INT_MAX) {
3228         choose_intra_uv_mode(cpi, x, ctx, bsize, uv_tx,
3229                              &rate_uv_intra[uv_tx], &rate_uv_tokenonly[uv_tx],
3230                              &dist_uv[uv_tx], &skip_uv[uv_tx], &mode_uv[uv_tx]);
3231       }
3232
3233       rate_uv = rate_uv_tokenonly[uv_tx];
3234       distortion_uv = dist_uv[uv_tx];
3235       skippable = skippable && skip_uv[uv_tx];
3236       mbmi->uv_mode = mode_uv[uv_tx];
3237
3238       rate2 = rate_y + cpi->mbmode_cost[mbmi->mode] + rate_uv_intra[uv_tx];
3239       if (this_mode != DC_PRED && this_mode != TM_PRED)
3240         rate2 += intra_cost_penalty;
3241       distortion2 = distortion_y + distortion_uv;
3242     } else {
3243       this_rd = handle_inter_mode(cpi, x, bsize,
3244                                   &rate2, &distortion2, &skippable,
3245                                   &rate_y, &rate_uv,
3246                                   &disable_skip, frame_mv,
3247                                   mi_row, mi_col,
3248                                   single_newmv, single_inter_filter,
3249                                   single_skippable, &total_sse, best_rd,
3250                                   &mask_filter, filter_cache);
3251       if (this_rd == INT64_MAX)
3252         continue;
3253
3254       compmode_cost = vp10_cost_bit(comp_mode_p, comp_pred);
3255
3256       if (cm->reference_mode == REFERENCE_MODE_SELECT)
3257         rate2 += compmode_cost;
3258     }
3259
3260     // Estimate the reference frame signaling cost and add it
3261     // to the rolling cost variable.
3262     if (comp_pred) {
3263       rate2 += ref_costs_comp[ref_frame];
3264     } else {
3265       rate2 += ref_costs_single[ref_frame];
3266     }
3267
3268     if (!disable_skip) {
3269       if (skippable) {
3270         // Back out the coefficient coding costs
3271         rate2 -= (rate_y + rate_uv);
3272
3273         // Cost the skip mb case
3274         rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 1);
3275       } else if (ref_frame != INTRA_FRAME && !xd->lossless[mbmi->segment_id]) {
3276         if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv, distortion2) <
3277             RDCOST(x->rdmult, x->rddiv, 0, total_sse)) {
3278           // Add in the cost of the no skip flag.
3279           rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 0);
3280         } else {
3281           // FIXME(rbultje) make this work for splitmv also
3282           rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 1);
3283           distortion2 = total_sse;
3284           assert(total_sse >= 0);
3285           rate2 -= (rate_y + rate_uv);
3286           this_skip2 = 1;
3287         }
3288       } else {
3289         // Add in the cost of the no skip flag.
3290         rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 0);
3291       }
3292
3293       // Calculate the final RD estimate for this mode.
3294       this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3295     }
3296
3297     // Apply an adjustment to the rd value based on the similarity of the
3298     // source variance and reconstructed variance.
3299     rd_variance_adjustment(cpi, x, bsize, &this_rd,
3300                            ref_frame, x->source_variance);
3301
3302     if (ref_frame == INTRA_FRAME) {
3303     // Keep record of best intra rd
3304       if (this_rd < best_intra_rd) {
3305         best_intra_rd = this_rd;
3306         best_intra_mode = mbmi->mode;
3307       }
3308     }
3309
3310     if (!disable_skip && ref_frame == INTRA_FRAME) {
3311       for (i = 0; i < REFERENCE_MODES; ++i)
3312         best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
3313       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3314         best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
3315     }
3316
3317     // Did this mode help.. i.e. is it the new best mode
3318     if (this_rd < best_rd || x->skip) {
3319       int max_plane = MAX_MB_PLANE;
3320       if (!mode_excluded) {
3321         // Note index of best mode so far
3322         best_mode_index = mode_index;
3323
3324         if (ref_frame == INTRA_FRAME) {
3325           /* required for left and above block mv */
3326           mbmi->mv[0].as_int = 0;
3327           max_plane = 1;
3328         } else {
3329           best_pred_sse = x->pred_sse[ref_frame];
3330         }
3331
3332         rd_cost->rate = rate2;
3333         rd_cost->dist = distortion2;
3334         rd_cost->rdcost = this_rd;
3335         best_rd = this_rd;
3336         best_mbmode = *mbmi;
3337         best_skip2 = this_skip2;
3338         best_mode_skippable = skippable;
3339
3340         if (!x->select_tx_size)
3341           swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
3342         memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mbmi->tx_size],
3343                sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
3344
3345         // TODO(debargha): enhance this test with a better distortion prediction
3346         // based on qp, activity mask and history
3347         if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
3348             (mode_index > MIN_EARLY_TERM_INDEX)) {
3349           int qstep = xd->plane[0].dequant[1];
3350           // TODO(debargha): Enhance this by specializing for each mode_index
3351           int scale = 4;
3352 #if CONFIG_VP9_HIGHBITDEPTH
3353           if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3354             qstep >>= (xd->bd - 8);
3355           }
3356 #endif  // CONFIG_VP9_HIGHBITDEPTH
3357           if (x->source_variance < UINT_MAX) {
3358             const int var_adjust = (x->source_variance < 16);
3359             scale -= var_adjust;
3360           }
3361           if (ref_frame > INTRA_FRAME &&
3362               distortion2 * scale < qstep * qstep) {
3363             early_term = 1;
3364           }
3365         }
3366       }
3367     }
3368
3369     /* keep record of best compound/single-only prediction */
3370     if (!disable_skip && ref_frame != INTRA_FRAME) {
3371       int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
3372
3373       if (cm->reference_mode == REFERENCE_MODE_SELECT) {
3374         single_rate = rate2 - compmode_cost;
3375         hybrid_rate = rate2;
3376       } else {
3377         single_rate = rate2;
3378         hybrid_rate = rate2 + compmode_cost;
3379       }
3380
3381       single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
3382       hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
3383
3384       if (!comp_pred) {
3385         if (single_rd < best_pred_rd[SINGLE_REFERENCE])
3386           best_pred_rd[SINGLE_REFERENCE] = single_rd;
3387       } else {
3388         if (single_rd < best_pred_rd[COMPOUND_REFERENCE])
3389           best_pred_rd[COMPOUND_REFERENCE] = single_rd;
3390       }
3391       if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
3392         best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
3393
3394       /* keep record of best filter type */
3395       if (!mode_excluded && cm->interp_filter != BILINEAR) {
3396         int64_t ref = filter_cache[cm->interp_filter == SWITCHABLE ?
3397                               SWITCHABLE_FILTERS : cm->interp_filter];
3398
3399         for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3400           int64_t adj_rd;
3401           if (ref == INT64_MAX)
3402             adj_rd = 0;
3403           else if (filter_cache[i] == INT64_MAX)
3404             // when early termination is triggered, the encoder does not have
3405             // access to the rate-distortion cost. it only knows that the cost
3406             // should be above the maximum valid value. hence it takes the known
3407             // maximum plus an arbitrary constant as the rate-distortion cost.
3408             adj_rd = mask_filter - ref + 10;
3409           else
3410             adj_rd = filter_cache[i] - ref;
3411
3412           adj_rd += this_rd;
3413           best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
3414         }
3415       }
3416     }
3417
3418     if (early_term)
3419       break;
3420
3421     if (x->skip && !comp_pred)
3422       break;
3423   }
3424
3425   // The inter modes' rate costs are not calculated precisely in some cases.
3426   // Therefore, sometimes, NEWMV is chosen instead of NEARESTMV, NEARMV, and
3427   // ZEROMV. Here, checks are added for those cases, and the mode decisions
3428   // are corrected.
3429   if (best_mbmode.mode == NEWMV) {
3430     const MV_REFERENCE_FRAME refs[2] = {best_mbmode.ref_frame[0],
3431         best_mbmode.ref_frame[1]};
3432     int comp_pred_mode = refs[1] > INTRA_FRAME;
3433
3434     if (frame_mv[NEARESTMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
3435         ((comp_pred_mode && frame_mv[NEARESTMV][refs[1]].as_int ==
3436             best_mbmode.mv[1].as_int) || !comp_pred_mode))
3437       best_mbmode.mode = NEARESTMV;
3438     else if (frame_mv[NEARMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
3439         ((comp_pred_mode && frame_mv[NEARMV][refs[1]].as_int ==
3440             best_mbmode.mv[1].as_int) || !comp_pred_mode))
3441       best_mbmode.mode = NEARMV;
3442     else if (best_mbmode.mv[0].as_int == 0 &&
3443         ((comp_pred_mode && best_mbmode.mv[1].as_int == 0) || !comp_pred_mode))
3444       best_mbmode.mode = ZEROMV;
3445   }
3446
3447   if (best_mode_index < 0 || best_rd >= best_rd_so_far) {
3448     rd_cost->rate = INT_MAX;
3449     rd_cost->rdcost = INT64_MAX;
3450     return;
3451   }
3452
3453   // If we used an estimate for the uv intra rd in the loop above...
3454   if (sf->use_uv_intra_rd_estimate) {
3455     // Do Intra UV best rd mode selection if best mode choice above was intra.
3456     if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
3457       TX_SIZE uv_tx_size;
3458       *mbmi = best_mbmode;
3459       uv_tx_size = get_uv_tx_size(mbmi, &xd->plane[1]);
3460       rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
3461                               &rate_uv_tokenonly[uv_tx_size],
3462                               &dist_uv[uv_tx_size],
3463                               &skip_uv[uv_tx_size],
3464                               bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
3465                               uv_tx_size);
3466     }
3467   }
3468
3469   assert((cm->interp_filter == SWITCHABLE) ||
3470          (cm->interp_filter == best_mbmode.interp_filter) ||
3471          !is_inter_block(&best_mbmode));
3472
3473   if (!cpi->rc.is_src_frame_alt_ref)
3474     vp10_update_rd_thresh_fact(tile_data->thresh_freq_fact,
3475                               sf->adaptive_rd_thresh, bsize, best_mode_index);
3476
3477   // macroblock modes
3478   *mbmi = best_mbmode;
3479   x->skip |= best_skip2;
3480
3481   for (i = 0; i < REFERENCE_MODES; ++i) {
3482     if (best_pred_rd[i] == INT64_MAX)
3483       best_pred_diff[i] = INT_MIN;
3484     else
3485       best_pred_diff[i] = best_rd - best_pred_rd[i];
3486   }
3487
3488   if (!x->skip) {
3489     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3490       if (best_filter_rd[i] == INT64_MAX)
3491         best_filter_diff[i] = 0;
3492       else
3493         best_filter_diff[i] = best_rd - best_filter_rd[i];
3494     }
3495     if (cm->interp_filter == SWITCHABLE)
3496       assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
3497   } else {
3498     vp10_zero(best_filter_diff);
3499   }
3500
3501   // TODO(yunqingwang): Moving this line in front of the above best_filter_diff
3502   // updating code causes PSNR loss. Need to figure out the confliction.
3503   x->skip |= best_mode_skippable;
3504
3505   if (!x->skip && !x->select_tx_size) {
3506     int has_high_freq_coeff = 0;
3507     int plane;
3508     int max_plane = is_inter_block(&xd->mi[0]->mbmi)
3509                         ? MAX_MB_PLANE : 1;
3510     for (plane = 0; plane < max_plane; ++plane) {
3511       x->plane[plane].eobs = ctx->eobs_pbuf[plane][1];
3512       has_high_freq_coeff |= vp10_has_high_freq_in_plane(x, bsize, plane);
3513     }
3514
3515     for (plane = max_plane; plane < MAX_MB_PLANE; ++plane) {
3516       x->plane[plane].eobs = ctx->eobs_pbuf[plane][2];
3517       has_high_freq_coeff |= vp10_has_high_freq_in_plane(x, bsize, plane);
3518     }
3519
3520     best_mode_skippable |= !has_high_freq_coeff;
3521   }
3522
3523   assert(best_mode_index >= 0);
3524
3525   store_coding_context(x, ctx, best_mode_index, best_pred_diff,
3526                        best_filter_diff, best_mode_skippable);
3527 }
3528
3529 void vp10_rd_pick_inter_mode_sb_seg_skip(VP10_COMP *cpi,
3530                                         TileDataEnc *tile_data,
3531                                         MACROBLOCK *x,
3532                                         RD_COST *rd_cost,
3533                                         BLOCK_SIZE bsize,
3534                                         PICK_MODE_CONTEXT *ctx,
3535                                         int64_t best_rd_so_far) {
3536   VP10_COMMON *const cm = &cpi->common;
3537   MACROBLOCKD *const xd = &x->e_mbd;
3538   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
3539   unsigned char segment_id = mbmi->segment_id;
3540   const int comp_pred = 0;
3541   int i;
3542   int64_t best_pred_diff[REFERENCE_MODES];
3543   int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3544   unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3545   vpx_prob comp_mode_p;
3546   INTERP_FILTER best_filter = SWITCHABLE;
3547   int64_t this_rd = INT64_MAX;
3548   int rate2 = 0;
3549   const int64_t distortion2 = 0;
3550
3551   estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3552                            &comp_mode_p);
3553
3554   for (i = 0; i < MAX_REF_FRAMES; ++i)
3555     x->pred_sse[i] = INT_MAX;
3556   for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i)
3557     x->pred_mv_sad[i] = INT_MAX;
3558
3559   rd_cost->rate = INT_MAX;
3560
3561   assert(segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP));
3562
3563   mbmi->mode = ZEROMV;
3564   mbmi->uv_mode = DC_PRED;
3565   mbmi->ref_frame[0] = LAST_FRAME;
3566   mbmi->ref_frame[1] = NONE;
3567   mbmi->mv[0].as_int = 0;
3568   x->skip = 1;
3569
3570   if (cm->interp_filter != BILINEAR) {
3571     best_filter = EIGHTTAP;
3572     if (cm->interp_filter == SWITCHABLE &&
3573         x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
3574       int rs;
3575       int best_rs = INT_MAX;
3576       for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
3577         mbmi->interp_filter = i;
3578         rs = vp10_get_switchable_rate(cpi, xd);
3579         if (rs < best_rs) {
3580           best_rs = rs;
3581           best_filter = mbmi->interp_filter;
3582         }
3583       }
3584     }
3585   }
3586   // Set the appropriate filter
3587   if (cm->interp_filter == SWITCHABLE) {
3588     mbmi->interp_filter = best_filter;
3589     rate2 += vp10_get_switchable_rate(cpi, xd);
3590   } else {
3591     mbmi->interp_filter = cm->interp_filter;
3592   }
3593
3594   if (cm->reference_mode == REFERENCE_MODE_SELECT)
3595     rate2 += vp10_cost_bit(comp_mode_p, comp_pred);
3596
3597   // Estimate the reference frame signaling cost and add it
3598   // to the rolling cost variable.
3599   rate2 += ref_costs_single[LAST_FRAME];
3600   this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3601
3602   rd_cost->rate = rate2;
3603   rd_cost->dist = distortion2;
3604   rd_cost->rdcost = this_rd;
3605
3606   if (this_rd >= best_rd_so_far) {
3607     rd_cost->rate = INT_MAX;
3608     rd_cost->rdcost = INT64_MAX;
3609     return;
3610   }
3611
3612   assert((cm->interp_filter == SWITCHABLE) ||
3613          (cm->interp_filter == mbmi->interp_filter));
3614
3615   vp10_update_rd_thresh_fact(tile_data->thresh_freq_fact,
3616                             cpi->sf.adaptive_rd_thresh, bsize, THR_ZEROMV);
3617
3618   vp10_zero(best_pred_diff);
3619   vp10_zero(best_filter_diff);
3620
3621   if (!x->select_tx_size)
3622     swap_block_ptr(x, ctx, 1, 0, 0, MAX_MB_PLANE);
3623   store_coding_context(x, ctx, THR_ZEROMV,
3624                        best_pred_diff, best_filter_diff, 0);
3625 }
3626
3627 void vp10_rd_pick_inter_mode_sub8x8(VP10_COMP *cpi,
3628                                    TileDataEnc *tile_data,
3629                                    MACROBLOCK *x,
3630                                    int mi_row, int mi_col,
3631                                    RD_COST *rd_cost,
3632                                    BLOCK_SIZE bsize,
3633                                    PICK_MODE_CONTEXT *ctx,
3634                                    int64_t best_rd_so_far) {
3635   VP10_COMMON *const cm = &cpi->common;
3636   RD_OPT *const rd_opt = &cpi->rd;
3637   SPEED_FEATURES *const sf = &cpi->sf;
3638   MACROBLOCKD *const xd = &x->e_mbd;
3639   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
3640   const struct segmentation *const seg = &cm->seg;
3641   MV_REFERENCE_FRAME ref_frame, second_ref_frame;
3642   unsigned char segment_id = mbmi->segment_id;
3643   int comp_pred, i;
3644   int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
3645   struct buf_2d yv12_mb[4][MAX_MB_PLANE];
3646   static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
3647                                     VP9_ALT_FLAG };
3648   int64_t best_rd = best_rd_so_far;
3649   int64_t best_yrd = best_rd_so_far;  // FIXME(rbultje) more precise
3650   int64_t best_pred_diff[REFERENCE_MODES];
3651   int64_t best_pred_rd[REFERENCE_MODES];
3652   int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
3653   int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3654   MB_MODE_INFO best_mbmode;
3655   int ref_index, best_ref_index = 0;
3656   unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3657   vpx_prob comp_mode_p;
3658   INTERP_FILTER tmp_best_filter = SWITCHABLE;
3659   int rate_uv_intra, rate_uv_tokenonly;
3660   int64_t dist_uv;
3661   int skip_uv;
3662   PREDICTION_MODE mode_uv = DC_PRED;
3663   const int intra_cost_penalty = vp10_get_intra_cost_penalty(
3664     cm->base_qindex, cm->y_dc_delta_q, cm->bit_depth);
3665   int_mv seg_mvs[4][MAX_REF_FRAMES];
3666   b_mode_info best_bmodes[4];
3667   int best_skip2 = 0;
3668   int ref_frame_skip_mask[2] = { 0 };
3669   int64_t mask_filter = 0;
3670   int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
3671   int internal_active_edge =
3672     vp10_active_edge_sb(cpi, mi_row, mi_col) && vp10_internal_image_edge(cpi);
3673
3674   memset(x->zcoeff_blk[TX_4X4], 0, 4);
3675   vp10_zero(best_mbmode);
3676
3677   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
3678     filter_cache[i] = INT64_MAX;
3679
3680   for (i = 0; i < 4; i++) {
3681     int j;
3682     for (j = 0; j < MAX_REF_FRAMES; j++)
3683       seg_mvs[i][j].as_int = INVALID_MV;
3684   }
3685
3686   estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3687                            &comp_mode_p);
3688
3689   for (i = 0; i < REFERENCE_MODES; ++i)
3690     best_pred_rd[i] = INT64_MAX;
3691   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3692     best_filter_rd[i] = INT64_MAX;
3693   rate_uv_intra = INT_MAX;
3694
3695   rd_cost->rate = INT_MAX;
3696
3697   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
3698     if (cpi->ref_frame_flags & flag_list[ref_frame]) {
3699       setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
3700                          frame_mv[NEARESTMV], frame_mv[NEARMV],
3701                          yv12_mb);
3702     } else {
3703       ref_frame_skip_mask[0] |= (1 << ref_frame);
3704       ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3705     }
3706     frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
3707     frame_mv[ZEROMV][ref_frame].as_int = 0;
3708   }
3709
3710   for (ref_index = 0; ref_index < MAX_REFS; ++ref_index) {
3711     int mode_excluded = 0;
3712     int64_t this_rd = INT64_MAX;
3713     int disable_skip = 0;
3714     int compmode_cost = 0;
3715     int rate2 = 0, rate_y = 0, rate_uv = 0;
3716     int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3717     int skippable = 0;
3718     int i;
3719     int this_skip2 = 0;
3720     int64_t total_sse = INT_MAX;
3721     int early_term = 0;
3722
3723     ref_frame = vp10_ref_order[ref_index].ref_frame[0];
3724     second_ref_frame = vp10_ref_order[ref_index].ref_frame[1];
3725
3726     // Look at the reference frame of the best mode so far and set the
3727     // skip mask to look at a subset of the remaining modes.
3728     if (ref_index > 2 && sf->mode_skip_start < MAX_MODES) {
3729       if (ref_index == 3) {
3730         switch (best_mbmode.ref_frame[0]) {
3731           case INTRA_FRAME:
3732             break;
3733           case LAST_FRAME:
3734             ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME);
3735             ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3736             break;
3737           case GOLDEN_FRAME:
3738             ref_frame_skip_mask[0] |= (1 << LAST_FRAME) | (1 << ALTREF_FRAME);
3739             ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3740             break;
3741           case ALTREF_FRAME:
3742             ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << LAST_FRAME);
3743             break;
3744           case NONE:
3745           case MAX_REF_FRAMES:
3746             assert(0 && "Invalid Reference frame");
3747             break;
3748         }
3749       }
3750     }
3751
3752     if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
3753         (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
3754       continue;
3755
3756     // Test best rd so far against threshold for trying this mode.
3757     if (!internal_active_edge &&
3758         rd_less_than_thresh(best_rd,
3759                             rd_opt->threshes[segment_id][bsize][ref_index],
3760                             tile_data->thresh_freq_fact[bsize][ref_index]))
3761       continue;
3762
3763     comp_pred = second_ref_frame > INTRA_FRAME;
3764     if (comp_pred) {
3765       if (!cpi->allow_comp_inter_inter)
3766         continue;
3767       if (!(cpi->ref_frame_flags & flag_list[second_ref_frame]))
3768         continue;
3769       // Do not allow compound prediction if the segment level reference frame
3770       // feature is in use as in this case there can only be one reference.
3771       if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
3772         continue;
3773
3774       if ((sf->mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3775           best_mbmode.ref_frame[0] == INTRA_FRAME)
3776         continue;
3777     }
3778
3779     // TODO(jingning, jkoleszar): scaling reference frame not supported for
3780     // sub8x8 blocks.
3781     if (ref_frame > INTRA_FRAME &&
3782         vp10_is_scaled(&cm->frame_refs[ref_frame - 1].sf))
3783       continue;
3784
3785     if (second_ref_frame > INTRA_FRAME &&
3786         vp10_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf))
3787       continue;
3788
3789     if (comp_pred)
3790       mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3791     else if (ref_frame != INTRA_FRAME)
3792       mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3793
3794     // If the segment reference frame feature is enabled....
3795     // then do nothing if the current ref frame is not allowed..
3796     if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3797         get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
3798       continue;
3799     // Disable this drop out case if the ref frame
3800     // segment level feature is enabled for this segment. This is to
3801     // prevent the possibility that we end up unable to pick any mode.
3802     } else if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
3803       // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
3804       // unless ARNR filtering is enabled in which case we want
3805       // an unfiltered alternative. We allow near/nearest as well
3806       // because they may result in zero-zero MVs but be cheaper.
3807       if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
3808         continue;
3809     }
3810
3811     mbmi->tx_size = TX_4X4;
3812     mbmi->uv_mode = DC_PRED;
3813     mbmi->ref_frame[0] = ref_frame;
3814     mbmi->ref_frame[1] = second_ref_frame;
3815     // Evaluate all sub-pel filters irrespective of whether we can use
3816     // them for this frame.
3817     mbmi->interp_filter = cm->interp_filter == SWITCHABLE ? EIGHTTAP
3818                                                           : cm->interp_filter;
3819     x->skip = 0;
3820     set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3821
3822     // Select prediction reference frames.
3823     for (i = 0; i < MAX_MB_PLANE; i++) {
3824       xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3825       if (comp_pred)
3826         xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3827     }
3828
3829     if (ref_frame == INTRA_FRAME) {
3830       int rate;
3831       if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y,
3832                                        &distortion_y, best_rd) >= best_rd)
3833         continue;
3834       rate2 += rate;
3835       rate2 += intra_cost_penalty;
3836       distortion2 += distortion_y;
3837
3838       if (rate_uv_intra == INT_MAX) {
3839         choose_intra_uv_mode(cpi, x, ctx, bsize, TX_4X4,
3840                              &rate_uv_intra,
3841                              &rate_uv_tokenonly,
3842                              &dist_uv, &skip_uv,
3843                              &mode_uv);
3844       }
3845       rate2 += rate_uv_intra;
3846       rate_uv = rate_uv_tokenonly;
3847       distortion2 += dist_uv;
3848       distortion_uv = dist_uv;
3849       mbmi->uv_mode = mode_uv;
3850     } else {
3851       int rate;
3852       int64_t distortion;
3853       int64_t this_rd_thresh;
3854       int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
3855       int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
3856       int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
3857       int tmp_best_skippable = 0;
3858       int switchable_filter_index;
3859       int_mv *second_ref = comp_pred ?
3860                              &x->mbmi_ext->ref_mvs[second_ref_frame][0] : NULL;
3861       b_mode_info tmp_best_bmodes[16];
3862       MB_MODE_INFO tmp_best_mbmode;
3863       BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
3864       int pred_exists = 0;
3865       int uv_skippable;
3866
3867       this_rd_thresh = (ref_frame == LAST_FRAME) ?
3868           rd_opt->threshes[segment_id][bsize][THR_LAST] :
3869           rd_opt->threshes[segment_id][bsize][THR_ALTR];
3870       this_rd_thresh = (ref_frame == GOLDEN_FRAME) ?
3871       rd_opt->threshes[segment_id][bsize][THR_GOLD] : this_rd_thresh;
3872       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
3873         filter_cache[i] = INT64_MAX;
3874
3875       if (cm->interp_filter != BILINEAR) {
3876         tmp_best_filter = EIGHTTAP;
3877         if (x->source_variance < sf->disable_filter_search_var_thresh) {
3878           tmp_best_filter = EIGHTTAP;
3879         } else if (sf->adaptive_pred_interp_filter == 1 &&
3880                    ctx->pred_interp_filter < SWITCHABLE) {
3881           tmp_best_filter = ctx->pred_interp_filter;
3882         } else if (sf->adaptive_pred_interp_filter == 2) {
3883           tmp_best_filter = ctx->pred_interp_filter < SWITCHABLE ?
3884                               ctx->pred_interp_filter : 0;
3885         } else {
3886           for (switchable_filter_index = 0;
3887                switchable_filter_index < SWITCHABLE_FILTERS;
3888                ++switchable_filter_index) {
3889             int newbest, rs;
3890             int64_t rs_rd;
3891             MB_MODE_INFO_EXT *mbmi_ext = x->mbmi_ext;
3892             mbmi->interp_filter = switchable_filter_index;
3893             tmp_rd = rd_pick_best_sub8x8_mode(cpi, x,
3894                                               &mbmi_ext->ref_mvs[ref_frame][0],
3895                                               second_ref, best_yrd, &rate,
3896                                               &rate_y, &distortion,
3897                                               &skippable, &total_sse,
3898                                               (int) this_rd_thresh, seg_mvs,
3899                                               bsi, switchable_filter_index,
3900                                               mi_row, mi_col);
3901
3902             if (tmp_rd == INT64_MAX)
3903               continue;
3904             rs = vp10_get_switchable_rate(cpi, xd);
3905             rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
3906             filter_cache[switchable_filter_index] = tmp_rd;
3907             filter_cache[SWITCHABLE_FILTERS] =
3908                 VPXMIN(filter_cache[SWITCHABLE_FILTERS], tmp_rd + rs_rd);
3909             if (cm->interp_filter == SWITCHABLE)
3910               tmp_rd += rs_rd;
3911
3912             mask_filter = VPXMAX(mask_filter, tmp_rd);
3913
3914             newbest = (tmp_rd < tmp_best_rd);
3915             if (newbest) {
3916               tmp_best_filter = mbmi->interp_filter;
3917               tmp_best_rd = tmp_rd;
3918             }
3919             if ((newbest && cm->interp_filter == SWITCHABLE) ||
3920                 (mbmi->interp_filter == cm->interp_filter &&
3921                  cm->interp_filter != SWITCHABLE)) {
3922               tmp_best_rdu = tmp_rd;
3923               tmp_best_rate = rate;
3924               tmp_best_ratey = rate_y;
3925               tmp_best_distortion = distortion;
3926               tmp_best_sse = total_sse;
3927               tmp_best_skippable = skippable;
3928               tmp_best_mbmode = *mbmi;
3929               for (i = 0; i < 4; i++) {
3930                 tmp_best_bmodes[i] = xd->mi[0]->bmi[i];
3931                 x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
3932               }
3933               pred_exists = 1;
3934               if (switchable_filter_index == 0 &&
3935                   sf->use_rd_breakout &&
3936                   best_rd < INT64_MAX) {
3937                 if (tmp_best_rdu / 2 > best_rd) {
3938                   // skip searching the other filters if the first is
3939                   // already substantially larger than the best so far
3940                   tmp_best_filter = mbmi->interp_filter;
3941                   tmp_best_rdu = INT64_MAX;
3942                   break;
3943                 }
3944               }
3945             }
3946           }  // switchable_filter_index loop
3947         }
3948       }
3949
3950       if (tmp_best_rdu == INT64_MAX && pred_exists)
3951         continue;
3952
3953       mbmi->interp_filter = (cm->interp_filter == SWITCHABLE ?
3954                              tmp_best_filter : cm->interp_filter);
3955       if (!pred_exists) {
3956         // Handles the special case when a filter that is not in the
3957         // switchable list (bilinear, 6-tap) is indicated at the frame level
3958         tmp_rd = rd_pick_best_sub8x8_mode(cpi, x,
3959                                           &x->mbmi_ext->ref_mvs[ref_frame][0],
3960                                           second_ref, best_yrd, &rate, &rate_y,
3961                                           &distortion, &skippable, &total_sse,
3962                                           (int) this_rd_thresh, seg_mvs, bsi, 0,
3963                                           mi_row, mi_col);
3964         if (tmp_rd == INT64_MAX)
3965           continue;
3966       } else {
3967         total_sse = tmp_best_sse;
3968         rate = tmp_best_rate;
3969         rate_y = tmp_best_ratey;
3970         distortion = tmp_best_distortion;
3971         skippable = tmp_best_skippable;
3972         *mbmi = tmp_best_mbmode;
3973         for (i = 0; i < 4; i++)
3974           xd->mi[0]->bmi[i] = tmp_best_bmodes[i];
3975       }
3976
3977       rate2 += rate;
3978       distortion2 += distortion;
3979
3980       if (cm->interp_filter == SWITCHABLE)
3981         rate2 += vp10_get_switchable_rate(cpi, xd);
3982
3983       if (!mode_excluded)
3984         mode_excluded = comp_pred ? cm->reference_mode == SINGLE_REFERENCE
3985                                   : cm->reference_mode == COMPOUND_REFERENCE;
3986
3987       compmode_cost = vp10_cost_bit(comp_mode_p, comp_pred);
3988
3989       tmp_best_rdu = best_rd -
3990           VPXMIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
3991                  RDCOST(x->rdmult, x->rddiv, 0, total_sse));
3992
3993       if (tmp_best_rdu > 0) {
3994         // If even the 'Y' rd value of split is higher than best so far
3995         // then dont bother looking at UV
3996         vp10_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col,
3997                                         BLOCK_8X8);
3998         memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
3999         if (!super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
4000                               &uv_sse, BLOCK_8X8, tmp_best_rdu))
4001           continue;
4002
4003         rate2 += rate_uv;
4004         distortion2 += distortion_uv;
4005         skippable = skippable && uv_skippable;
4006         total_sse += uv_sse;
4007       }
4008     }
4009
4010     if (cm->reference_mode == REFERENCE_MODE_SELECT)
4011       rate2 += compmode_cost;
4012
4013     // Estimate the reference frame signaling cost and add it
4014     // to the rolling cost variable.
4015     if (second_ref_frame > INTRA_FRAME) {
4016       rate2 += ref_costs_comp[ref_frame];
4017     } else {
4018       rate2 += ref_costs_single[ref_frame];
4019     }
4020
4021     if (!disable_skip) {
4022       // Skip is never coded at the segment level for sub8x8 blocks and instead
4023       // always coded in the bitstream at the mode info level.
4024
4025       if (ref_frame != INTRA_FRAME && !xd->lossless[mbmi->segment_id]) {
4026         if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv, distortion2) <
4027             RDCOST(x->rdmult, x->rddiv, 0, total_sse)) {
4028           // Add in the cost of the no skip flag.
4029           rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 0);
4030         } else {
4031           // FIXME(rbultje) make this work for splitmv also
4032           rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 1);
4033           distortion2 = total_sse;
4034           assert(total_sse >= 0);
4035           rate2 -= (rate_y + rate_uv);
4036           rate_y = 0;
4037           rate_uv = 0;
4038           this_skip2 = 1;
4039         }
4040       } else {
4041         // Add in the cost of the no skip flag.
4042         rate2 += vp10_cost_bit(vp10_get_skip_prob(cm, xd), 0);
4043       }
4044
4045       // Calculate the final RD estimate for this mode.
4046       this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4047     }
4048
4049     if (!disable_skip && ref_frame == INTRA_FRAME) {
4050       for (i = 0; i < REFERENCE_MODES; ++i)
4051         best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
4052       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4053         best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
4054     }
4055
4056     // Did this mode help.. i.e. is it the new best mode
4057     if (this_rd < best_rd || x->skip) {
4058       if (!mode_excluded) {
4059         int max_plane = MAX_MB_PLANE;
4060         // Note index of best mode so far
4061         best_ref_index = ref_index;
4062
4063         if (ref_frame == INTRA_FRAME) {
4064           /* required for left and above block mv */
4065           mbmi->mv[0].as_int = 0;
4066           max_plane = 1;
4067         }
4068
4069         rd_cost->rate = rate2;
4070         rd_cost->dist = distortion2;
4071         rd_cost->rdcost = this_rd;
4072         best_rd = this_rd;
4073         best_yrd = best_rd -
4074                    RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
4075         best_mbmode = *mbmi;
4076         best_skip2 = this_skip2;
4077         if (!x->select_tx_size)
4078           swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
4079         memcpy(ctx->zcoeff_blk, x->zcoeff_blk[TX_4X4],
4080                sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
4081
4082         for (i = 0; i < 4; i++)
4083           best_bmodes[i] = xd->mi[0]->bmi[i];
4084
4085         // TODO(debargha): enhance this test with a better distortion prediction
4086         // based on qp, activity mask and history
4087         if ((sf->mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
4088             (ref_index > MIN_EARLY_TERM_INDEX)) {
4089           int qstep = xd->plane[0].dequant[1];
4090           // TODO(debargha): Enhance this by specializing for each mode_index
4091           int scale = 4;
4092 #if CONFIG_VP9_HIGHBITDEPTH
4093           if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
4094             qstep >>= (xd->bd - 8);
4095           }
4096 #endif  // CONFIG_VP9_HIGHBITDEPTH
4097           if (x->source_variance < UINT_MAX) {
4098             const int var_adjust = (x->source_variance < 16);
4099             scale -= var_adjust;
4100           }
4101           if (ref_frame > INTRA_FRAME &&
4102               distortion2 * scale < qstep * qstep) {
4103             early_term = 1;
4104           }
4105         }
4106       }
4107     }
4108
4109     /* keep record of best compound/single-only prediction */
4110     if (!disable_skip && ref_frame != INTRA_FRAME) {
4111       int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
4112
4113       if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4114         single_rate = rate2 - compmode_cost;
4115         hybrid_rate = rate2;
4116       } else {
4117         single_rate = rate2;
4118         hybrid_rate = rate2 + compmode_cost;
4119       }
4120
4121       single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
4122       hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
4123
4124       if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE])
4125         best_pred_rd[SINGLE_REFERENCE] = single_rd;
4126       else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE])
4127         best_pred_rd[COMPOUND_REFERENCE] = single_rd;
4128
4129       if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
4130         best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
4131     }
4132
4133     /* keep record of best filter type */
4134     if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
4135         cm->interp_filter != BILINEAR) {
4136       int64_t ref = filter_cache[cm->interp_filter == SWITCHABLE ?
4137                               SWITCHABLE_FILTERS : cm->interp_filter];
4138       int64_t adj_rd;
4139       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4140         if (ref == INT64_MAX)
4141           adj_rd = 0;
4142         else if (filter_cache[i] == INT64_MAX)
4143           // when early termination is triggered, the encoder does not have
4144           // access to the rate-distortion cost. it only knows that the cost
4145           // should be above the maximum valid value. hence it takes the known
4146           // maximum plus an arbitrary constant as the rate-distortion cost.
4147           adj_rd = mask_filter - ref + 10;
4148         else
4149           adj_rd = filter_cache[i] - ref;
4150
4151         adj_rd += this_rd;
4152         best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
4153       }
4154     }
4155
4156     if (early_term)
4157       break;
4158
4159     if (x->skip && !comp_pred)
4160       break;
4161   }
4162
4163   if (best_rd >= best_rd_so_far) {
4164     rd_cost->rate = INT_MAX;
4165     rd_cost->rdcost = INT64_MAX;
4166     return;
4167   }
4168
4169   // If we used an estimate for the uv intra rd in the loop above...
4170   if (sf->use_uv_intra_rd_estimate) {
4171     // Do Intra UV best rd mode selection if best mode choice above was intra.
4172     if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
4173       *mbmi = best_mbmode;
4174       rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra,
4175                               &rate_uv_tokenonly,
4176                               &dist_uv,
4177                               &skip_uv,
4178                               BLOCK_8X8, TX_4X4);
4179     }
4180   }
4181
4182   if (best_rd == INT64_MAX) {
4183     rd_cost->rate = INT_MAX;
4184     rd_cost->dist = INT64_MAX;
4185     rd_cost->rdcost = INT64_MAX;
4186     return;
4187   }
4188
4189   assert((cm->interp_filter == SWITCHABLE) ||
4190          (cm->interp_filter == best_mbmode.interp_filter) ||
4191          !is_inter_block(&best_mbmode));
4192
4193   vp10_update_rd_thresh_fact(tile_data->thresh_freq_fact,
4194                             sf->adaptive_rd_thresh, bsize, best_ref_index);
4195
4196   // macroblock modes
4197   *mbmi = best_mbmode;
4198   x->skip |= best_skip2;
4199   if (!is_inter_block(&best_mbmode)) {
4200     for (i = 0; i < 4; i++)
4201       xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
4202   } else {
4203     for (i = 0; i < 4; ++i)
4204       memcpy(&xd->mi[0]->bmi[i], &best_bmodes[i], sizeof(b_mode_info));
4205
4206     mbmi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
4207     mbmi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
4208   }
4209
4210   for (i = 0; i < REFERENCE_MODES; ++i) {
4211     if (best_pred_rd[i] == INT64_MAX)
4212       best_pred_diff[i] = INT_MIN;
4213     else
4214       best_pred_diff[i] = best_rd - best_pred_rd[i];
4215   }
4216
4217   if (!x->skip) {
4218     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4219       if (best_filter_rd[i] == INT64_MAX)
4220         best_filter_diff[i] = 0;
4221       else
4222         best_filter_diff[i] = best_rd - best_filter_rd[i];
4223     }
4224     if (cm->interp_filter == SWITCHABLE)
4225       assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4226   } else {
4227     vp10_zero(best_filter_diff);
4228   }
4229
4230   store_coding_context(x, ctx, best_ref_index,
4231                        best_pred_diff, best_filter_diff, 0);
4232 }