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