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