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