]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_pickmode.c
For non-rd pickmode: remove VAR_PARTITION condition.
[libvpx] / vp9 / encoder / vp9_pickmode.c
1 /*
2  *  Copyright (c) 2014 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 <limits.h>
13 #include <math.h>
14 #include <stdio.h>
15
16 #include "./vp9_rtcd.h"
17 #include "./vpx_dsp_rtcd.h"
18
19 #include "vpx_mem/vpx_mem.h"
20 #include "vpx_ports/mem.h"
21
22 #include "vp9/common/vp9_blockd.h"
23 #include "vp9/common/vp9_common.h"
24 #include "vp9/common/vp9_mvref_common.h"
25 #include "vp9/common/vp9_pred_common.h"
26 #include "vp9/common/vp9_reconinter.h"
27 #include "vp9/common/vp9_reconintra.h"
28 #include "vp9/common/vp9_scan.h"
29
30 #include "vp9/encoder/vp9_cost.h"
31 #include "vp9/encoder/vp9_encoder.h"
32 #include "vp9/encoder/vp9_pickmode.h"
33 #include "vp9/encoder/vp9_ratectrl.h"
34 #include "vp9/encoder/vp9_rd.h"
35
36 typedef struct {
37   uint8_t *data;
38   int stride;
39   int in_use;
40 } PRED_BUFFER;
41
42 static int mv_refs_rt(const VP9_COMMON *cm, const MACROBLOCKD *xd,
43                       const TileInfo *const tile,
44                       MODE_INFO *mi, MV_REFERENCE_FRAME ref_frame,
45                       int_mv *mv_ref_list,
46                       int mi_row, int mi_col) {
47   const int *ref_sign_bias = cm->ref_frame_sign_bias;
48   int i, refmv_count = 0;
49
50   const POSITION *const mv_ref_search = mv_ref_blocks[mi->mbmi.sb_type];
51
52   int different_ref_found = 0;
53   int context_counter = 0;
54   int const_motion = 0;
55
56   // Blank the reference vector list
57   memset(mv_ref_list, 0, sizeof(*mv_ref_list) * MAX_MV_REF_CANDIDATES);
58
59   // The nearest 2 blocks are treated differently
60   // if the size < 8x8 we get the mv from the bmi substructure,
61   // and we also need to keep a mode count.
62   for (i = 0; i < 2; ++i) {
63     const POSITION *const mv_ref = &mv_ref_search[i];
64     if (is_inside(tile, mi_col, mi_row, cm->mi_rows, mv_ref)) {
65       const MODE_INFO *const candidate_mi = xd->mi[mv_ref->col + mv_ref->row *
66                                                    xd->mi_stride];
67       const MB_MODE_INFO *const candidate = &candidate_mi->mbmi;
68       // Keep counts for entropy encoding.
69       context_counter += mode_2_counter[candidate->mode];
70       different_ref_found = 1;
71
72       if (candidate->ref_frame[0] == ref_frame)
73         ADD_MV_REF_LIST(get_sub_block_mv(candidate_mi, 0, mv_ref->col, -1),
74                         refmv_count, mv_ref_list, Done);
75     }
76   }
77
78   const_motion = 1;
79
80   // Check the rest of the neighbors in much the same way
81   // as before except we don't need to keep track of sub blocks or
82   // mode counts.
83   for (; i < MVREF_NEIGHBOURS && !refmv_count; ++i) {
84     const POSITION *const mv_ref = &mv_ref_search[i];
85     if (is_inside(tile, mi_col, mi_row, cm->mi_rows, mv_ref)) {
86       const MB_MODE_INFO *const candidate = &xd->mi[mv_ref->col + mv_ref->row *
87                                                     xd->mi_stride]->mbmi;
88       different_ref_found = 1;
89
90       if (candidate->ref_frame[0] == ref_frame)
91         ADD_MV_REF_LIST(candidate->mv[0], refmv_count, mv_ref_list, Done);
92     }
93   }
94
95   // Since we couldn't find 2 mvs from the same reference frame
96   // go back through the neighbors and find motion vectors from
97   // different reference frames.
98   if (different_ref_found && !refmv_count) {
99     for (i = 0; i < MVREF_NEIGHBOURS; ++i) {
100       const POSITION *mv_ref = &mv_ref_search[i];
101       if (is_inside(tile, mi_col, mi_row, cm->mi_rows, mv_ref)) {
102         const MB_MODE_INFO *const candidate = &xd->mi[mv_ref->col + mv_ref->row
103                                               * xd->mi_stride]->mbmi;
104
105         // If the candidate is INTRA we don't want to consider its mv.
106         IF_DIFF_REF_FRAME_ADD_MV(candidate, ref_frame, ref_sign_bias,
107                                  refmv_count, mv_ref_list, Done);
108       }
109     }
110   }
111
112  Done:
113
114   mi->mbmi.mode_context[ref_frame] = counter_to_context[context_counter];
115
116   // Clamp vectors
117   for (i = 0; i < MAX_MV_REF_CANDIDATES; ++i)
118     clamp_mv_ref(&mv_ref_list[i].as_mv, xd);
119
120   return const_motion;
121 }
122
123 static int combined_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
124                                   BLOCK_SIZE bsize, int mi_row, int mi_col,
125                                   int_mv *tmp_mv, int *rate_mv,
126                                   int64_t best_rd_sofar) {
127   MACROBLOCKD *xd = &x->e_mbd;
128   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
129   struct buf_2d backup_yv12[MAX_MB_PLANE] = {{0, 0}};
130   const int step_param = cpi->sf.mv.fullpel_search_step_param;
131   const int sadpb = x->sadperbit16;
132   MV mvp_full;
133   const int ref = mbmi->ref_frame[0];
134   const MV ref_mv = mbmi->ref_mvs[ref][0].as_mv;
135   int dis;
136   int rate_mode;
137   const int tmp_col_min = x->mv_col_min;
138   const int tmp_col_max = x->mv_col_max;
139   const int tmp_row_min = x->mv_row_min;
140   const int tmp_row_max = x->mv_row_max;
141   int rv = 0;
142   int cost_list[5];
143   const YV12_BUFFER_CONFIG *scaled_ref_frame = vp9_get_scaled_ref_frame(cpi,
144                                                                         ref);
145   if (scaled_ref_frame) {
146     int i;
147     // Swap out the reference frame for a version that's been scaled to
148     // match the resolution of the current frame, allowing the existing
149     // motion search code to be used without additional modifications.
150     for (i = 0; i < MAX_MB_PLANE; i++)
151       backup_yv12[i] = xd->plane[i].pre[0];
152     vp9_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
153   }
154   vp9_set_mv_search_range(x, &ref_mv);
155
156   assert(x->mv_best_ref_index[ref] <= 2);
157   if (x->mv_best_ref_index[ref] < 2)
158     mvp_full = mbmi->ref_mvs[ref][x->mv_best_ref_index[ref]].as_mv;
159   else
160     mvp_full = x->pred_mv[ref];
161
162   mvp_full.col >>= 3;
163   mvp_full.row >>= 3;
164
165   vp9_full_pixel_search(cpi, x, bsize, &mvp_full, step_param, sadpb,
166                         cond_cost_list(cpi, cost_list),
167                         &ref_mv, &tmp_mv->as_mv, INT_MAX, 0);
168
169   x->mv_col_min = tmp_col_min;
170   x->mv_col_max = tmp_col_max;
171   x->mv_row_min = tmp_row_min;
172   x->mv_row_max = tmp_row_max;
173
174   // calculate the bit cost on motion vector
175   mvp_full.row = tmp_mv->as_mv.row * 8;
176   mvp_full.col = tmp_mv->as_mv.col * 8;
177
178   *rate_mv = vp9_mv_bit_cost(&mvp_full, &ref_mv,
179                              x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
180
181   rate_mode = cpi->inter_mode_cost[mbmi->mode_context[ref]]
182                                   [INTER_OFFSET(NEWMV)];
183   rv = !(RDCOST(x->rdmult, x->rddiv, (*rate_mv + rate_mode), 0) >
184          best_rd_sofar);
185
186   if (rv) {
187     cpi->find_fractional_mv_step(x, &tmp_mv->as_mv, &ref_mv,
188                                  cpi->common.allow_high_precision_mv,
189                                  x->errorperbit,
190                                  &cpi->fn_ptr[bsize],
191                                  cpi->sf.mv.subpel_force_stop,
192                                  cpi->sf.mv.subpel_iters_per_step,
193                                  cond_cost_list(cpi, cost_list),
194                                  x->nmvjointcost, x->mvcost,
195                                  &dis, &x->pred_sse[ref], NULL, 0, 0);
196     *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv,
197                                x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
198   }
199
200   if (scaled_ref_frame) {
201     int i;
202     for (i = 0; i < MAX_MB_PLANE; i++)
203       xd->plane[i].pre[0] = backup_yv12[i];
204   }
205   return rv;
206 }
207
208 static void block_variance(const uint8_t *src, int src_stride,
209                            const uint8_t *ref, int ref_stride,
210                            int w, int h, unsigned int *sse, int *sum,
211                            int block_size, unsigned int *sse8x8,
212                            int *sum8x8, unsigned int *var8x8) {
213   int i, j, k = 0;
214
215   *sse = 0;
216   *sum = 0;
217
218   for (i = 0; i < h; i += block_size) {
219     for (j = 0; j < w; j += block_size) {
220       vpx_get8x8var(src + src_stride * i + j, src_stride,
221                     ref + ref_stride * i + j, ref_stride,
222                     &sse8x8[k], &sum8x8[k]);
223       *sse += sse8x8[k];
224       *sum += sum8x8[k];
225       var8x8[k] = sse8x8[k] - (((unsigned int)sum8x8[k] * sum8x8[k]) >> 6);
226       k++;
227     }
228   }
229 }
230
231 static void calculate_variance(int bw, int bh, TX_SIZE tx_size,
232                                unsigned int *sse_i, int *sum_i,
233                                unsigned int *var_o, unsigned int *sse_o,
234                                int *sum_o) {
235   const BLOCK_SIZE unit_size = txsize_to_bsize[tx_size];
236   const int nw = 1 << (bw - b_width_log2_lookup[unit_size]);
237   const int nh = 1 << (bh - b_height_log2_lookup[unit_size]);
238   int i, j, k = 0;
239
240   for (i = 0; i < nh; i += 2) {
241     for (j = 0; j < nw; j += 2) {
242       sse_o[k] = sse_i[i * nw + j] + sse_i[i * nw + j + 1] +
243           sse_i[(i + 1) * nw + j] + sse_i[(i + 1) * nw + j + 1];
244       sum_o[k] = sum_i[i * nw + j] + sum_i[i * nw + j + 1] +
245           sum_i[(i + 1) * nw + j] + sum_i[(i + 1) * nw + j + 1];
246       var_o[k] = sse_o[k] - (((unsigned int)sum_o[k] * sum_o[k]) >>
247           (b_width_log2_lookup[unit_size] +
248               b_height_log2_lookup[unit_size] + 6));
249       k++;
250     }
251   }
252 }
253
254 static void model_rd_for_sb_y_large(VP9_COMP *cpi, BLOCK_SIZE bsize,
255                                     MACROBLOCK *x, MACROBLOCKD *xd,
256                                     int *out_rate_sum, int64_t *out_dist_sum,
257                                     unsigned int *var_y, unsigned int *sse_y,
258                                     int mi_row, int mi_col, int *early_term) {
259   // Note our transform coeffs are 8 times an orthogonal transform.
260   // Hence quantizer step is also 8 times. To get effective quantizer
261   // we need to divide by 8 before sending to modeling function.
262   unsigned int sse;
263   int rate;
264   int64_t dist;
265   struct macroblock_plane *const p = &x->plane[0];
266   struct macroblockd_plane *const pd = &xd->plane[0];
267   const uint32_t dc_quant = pd->dequant[0];
268   const uint32_t ac_quant = pd->dequant[1];
269   const int64_t dc_thr = dc_quant * dc_quant >> 6;
270   const int64_t ac_thr = ac_quant * ac_quant >> 6;
271   unsigned int var;
272   int sum;
273   int skip_dc = 0;
274
275   const int bw = b_width_log2_lookup[bsize];
276   const int bh = b_height_log2_lookup[bsize];
277   const int num8x8 = 1 << (bw + bh - 2);
278   unsigned int sse8x8[64] = {0};
279   int sum8x8[64] = {0};
280   unsigned int var8x8[64] = {0};
281   TX_SIZE tx_size;
282   int i, k;
283
284   // Calculate variance for whole partition, and also save 8x8 blocks' variance
285   // to be used in following transform skipping test.
286   block_variance(p->src.buf, p->src.stride, pd->dst.buf, pd->dst.stride,
287                  4 << bw, 4 << bh, &sse, &sum, 8, sse8x8, sum8x8, var8x8);
288   var = sse - (((int64_t)sum * sum) >> (bw + bh + 4));
289
290   *var_y = var;
291   *sse_y = sse;
292
293   if (cpi->common.tx_mode == TX_MODE_SELECT) {
294     if (sse > (var << 2))
295       tx_size = MIN(max_txsize_lookup[bsize],
296                     tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
297     else
298       tx_size = TX_8X8;
299
300     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
301         cyclic_refresh_segment_id_boosted(xd->mi[0]->mbmi.segment_id))
302       tx_size = TX_8X8;
303     else if (tx_size > TX_16X16)
304       tx_size = TX_16X16;
305   } else {
306     tx_size = MIN(max_txsize_lookup[bsize],
307                   tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
308   }
309
310   assert(tx_size >= TX_8X8);
311   xd->mi[0]->mbmi.tx_size = tx_size;
312
313   // Evaluate if the partition block is a skippable block in Y plane.
314   {
315     unsigned int sse16x16[16] = {0};
316     int sum16x16[16] = {0};
317     unsigned int var16x16[16] = {0};
318     const int num16x16 = num8x8 >> 2;
319
320     unsigned int sse32x32[4] = {0};
321     int sum32x32[4] = {0};
322     unsigned int var32x32[4] = {0};
323     const int num32x32 = num8x8 >> 4;
324
325     int ac_test = 1;
326     int dc_test = 1;
327     const int num = (tx_size == TX_8X8) ? num8x8 :
328         ((tx_size == TX_16X16) ? num16x16 : num32x32);
329     const unsigned int *sse_tx = (tx_size == TX_8X8) ? sse8x8 :
330         ((tx_size == TX_16X16) ? sse16x16 : sse32x32);
331     const unsigned int *var_tx = (tx_size == TX_8X8) ? var8x8 :
332         ((tx_size == TX_16X16) ? var16x16 : var32x32);
333
334     // Calculate variance if tx_size > TX_8X8
335     if (tx_size >= TX_16X16)
336       calculate_variance(bw, bh, TX_8X8, sse8x8, sum8x8, var16x16, sse16x16,
337                          sum16x16);
338     if (tx_size == TX_32X32)
339       calculate_variance(bw, bh, TX_16X16, sse16x16, sum16x16, var32x32,
340                          sse32x32, sum32x32);
341
342     // Skipping test
343     x->skip_txfm[0] = 0;
344     for (k = 0; k < num; k++)
345       // Check if all ac coefficients can be quantized to zero.
346       if (!(var_tx[k] < ac_thr || var == 0)) {
347         ac_test = 0;
348         break;
349       }
350
351     for (k = 0; k < num; k++)
352       // Check if dc coefficient can be quantized to zero.
353       if (!(sse_tx[k] - var_tx[k] < dc_thr || sse == var)) {
354         dc_test = 0;
355         break;
356       }
357
358     if (ac_test) {
359       x->skip_txfm[0] = 2;
360
361       if (dc_test)
362         x->skip_txfm[0] = 1;
363     } else if (dc_test) {
364       skip_dc = 1;
365     }
366   }
367
368   if (x->skip_txfm[0] == 1) {
369     int skip_uv[2] = {0};
370     unsigned int var_uv[2];
371     unsigned int sse_uv[2];
372
373     *out_rate_sum = 0;
374     *out_dist_sum = sse << 4;
375
376     // Transform skipping test in UV planes.
377     for (i = 1; i <= 2; i++) {
378       struct macroblock_plane *const p = &x->plane[i];
379       struct macroblockd_plane *const pd = &xd->plane[i];
380       const TX_SIZE uv_tx_size = get_uv_tx_size(&xd->mi[0]->mbmi, pd);
381       const BLOCK_SIZE unit_size = txsize_to_bsize[uv_tx_size];
382       const BLOCK_SIZE uv_bsize = get_plane_block_size(bsize, pd);
383       const int uv_bw = b_width_log2_lookup[uv_bsize];
384       const int uv_bh = b_height_log2_lookup[uv_bsize];
385       const int sf = (uv_bw - b_width_log2_lookup[unit_size]) +
386           (uv_bh - b_height_log2_lookup[unit_size]);
387       const uint32_t uv_dc_thr = pd->dequant[0] * pd->dequant[0] >> (6 - sf);
388       const uint32_t uv_ac_thr = pd->dequant[1] * pd->dequant[1] >> (6 - sf);
389       int j = i - 1;
390
391       vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, i);
392       var_uv[j] = cpi->fn_ptr[uv_bsize].vf(p->src.buf, p->src.stride,
393           pd->dst.buf, pd->dst.stride, &sse_uv[j]);
394
395       if ((var_uv[j] < uv_ac_thr || var_uv[j] == 0) &&
396           (sse_uv[j] - var_uv[j] < uv_dc_thr || sse_uv[j] == var_uv[j]))
397         skip_uv[j] = 1;
398       else
399         break;
400     }
401
402     // If the transform in YUV planes are skippable, the mode search checks
403     // fewer inter modes and doesn't check intra modes.
404     if (skip_uv[0] & skip_uv[1]) {
405       *early_term = 1;
406     }
407
408     return;
409   }
410
411   if (!skip_dc) {
412 #if CONFIG_VP9_HIGHBITDEPTH
413     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
414       vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
415                                    dc_quant >> (xd->bd - 5), &rate, &dist);
416     } else {
417       vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
418                                    dc_quant >> 3, &rate, &dist);
419     }
420 #else
421     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
422                                  dc_quant >> 3, &rate, &dist);
423 #endif  // CONFIG_VP9_HIGHBITDEPTH
424   }
425
426   if (!skip_dc) {
427     *out_rate_sum = rate >> 1;
428     *out_dist_sum = dist << 3;
429   } else {
430     *out_rate_sum = 0;
431     *out_dist_sum = (sse - var) << 4;
432   }
433
434 #if CONFIG_VP9_HIGHBITDEPTH
435   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
436     vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
437                                  ac_quant >> (xd->bd - 5), &rate, &dist);
438   } else {
439     vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
440                                  ac_quant >> 3, &rate, &dist);
441   }
442 #else
443   vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
444                                ac_quant >> 3, &rate, &dist);
445 #endif  // CONFIG_VP9_HIGHBITDEPTH
446
447   *out_rate_sum += rate;
448   *out_dist_sum += dist << 4;
449 }
450
451 static void model_rd_for_sb_y(VP9_COMP *cpi, BLOCK_SIZE bsize,
452                               MACROBLOCK *x, MACROBLOCKD *xd,
453                               int *out_rate_sum, int64_t *out_dist_sum,
454                               unsigned int *var_y, unsigned int *sse_y) {
455   // Note our transform coeffs are 8 times an orthogonal transform.
456   // Hence quantizer step is also 8 times. To get effective quantizer
457   // we need to divide by 8 before sending to modeling function.
458   unsigned int sse;
459   int rate;
460   int64_t dist;
461   struct macroblock_plane *const p = &x->plane[0];
462   struct macroblockd_plane *const pd = &xd->plane[0];
463   const int64_t dc_thr = p->quant_thred[0] >> 6;
464   const int64_t ac_thr = p->quant_thred[1] >> 6;
465   const uint32_t dc_quant = pd->dequant[0];
466   const uint32_t ac_quant = pd->dequant[1];
467   unsigned int var = cpi->fn_ptr[bsize].vf(p->src.buf, p->src.stride,
468                                            pd->dst.buf, pd->dst.stride, &sse);
469   int skip_dc = 0;
470
471   *var_y = var;
472   *sse_y = sse;
473
474   if (cpi->common.tx_mode == TX_MODE_SELECT) {
475     if (sse > (var << 2))
476       xd->mi[0]->mbmi.tx_size =
477           MIN(max_txsize_lookup[bsize],
478               tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
479     else
480       xd->mi[0]->mbmi.tx_size = TX_8X8;
481
482     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
483         cyclic_refresh_segment_id_boosted(xd->mi[0]->mbmi.segment_id))
484       xd->mi[0]->mbmi.tx_size = TX_8X8;
485     else if (xd->mi[0]->mbmi.tx_size > TX_16X16)
486       xd->mi[0]->mbmi.tx_size = TX_16X16;
487   } else {
488     xd->mi[0]->mbmi.tx_size =
489         MIN(max_txsize_lookup[bsize],
490             tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
491   }
492
493   // Evaluate if the partition block is a skippable block in Y plane.
494   {
495     const BLOCK_SIZE unit_size =
496         txsize_to_bsize[xd->mi[0]->mbmi.tx_size];
497     const unsigned int num_blk_log2 =
498         (b_width_log2_lookup[bsize] - b_width_log2_lookup[unit_size]) +
499         (b_height_log2_lookup[bsize] - b_height_log2_lookup[unit_size]);
500     const unsigned int sse_tx = sse >> num_blk_log2;
501     const unsigned int var_tx = var >> num_blk_log2;
502
503     x->skip_txfm[0] = 0;
504     // Check if all ac coefficients can be quantized to zero.
505     if (var_tx < ac_thr || var == 0) {
506       x->skip_txfm[0] = 2;
507       // Check if dc coefficient can be quantized to zero.
508       if (sse_tx - var_tx < dc_thr || sse == var)
509         x->skip_txfm[0] = 1;
510     } else {
511       if (sse_tx - var_tx < dc_thr || sse == var)
512         skip_dc = 1;
513     }
514   }
515
516   if (x->skip_txfm[0] == 1) {
517     *out_rate_sum = 0;
518     *out_dist_sum = sse << 4;
519     return;
520   }
521
522   if (!skip_dc) {
523 #if CONFIG_VP9_HIGHBITDEPTH
524     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
525       vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
526                                    dc_quant >> (xd->bd - 5), &rate, &dist);
527     } else {
528       vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
529                                    dc_quant >> 3, &rate, &dist);
530     }
531 #else
532     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
533                                  dc_quant >> 3, &rate, &dist);
534 #endif  // CONFIG_VP9_HIGHBITDEPTH
535   }
536
537   if (!skip_dc) {
538     *out_rate_sum = rate >> 1;
539     *out_dist_sum = dist << 3;
540   } else {
541     *out_rate_sum = 0;
542     *out_dist_sum = (sse - var) << 4;
543   }
544
545 #if CONFIG_VP9_HIGHBITDEPTH
546   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
547     vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
548                                  ac_quant >> (xd->bd - 5), &rate, &dist);
549   } else {
550     vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
551                                  ac_quant >> 3, &rate, &dist);
552   }
553 #else
554   vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
555                                ac_quant >> 3, &rate, &dist);
556 #endif  // CONFIG_VP9_HIGHBITDEPTH
557
558   *out_rate_sum += rate;
559   *out_dist_sum += dist << 4;
560 }
561
562 #if CONFIG_VP9_HIGHBITDEPTH
563 static void block_yrd(VP9_COMP *cpi, MACROBLOCK *x, int *rate, int64_t *dist,
564                       int *skippable, int64_t *sse, int plane,
565                       BLOCK_SIZE bsize, TX_SIZE tx_size) {
566   MACROBLOCKD *xd = &x->e_mbd;
567   unsigned int var_y, sse_y;
568   (void)plane;
569   (void)tx_size;
570   model_rd_for_sb_y(cpi, bsize, x, xd, rate, dist, &var_y, &sse_y);
571   *sse = INT_MAX;
572   *skippable = 0;
573   return;
574 }
575 #else
576 static void block_yrd(VP9_COMP *cpi, MACROBLOCK *x, int *rate, int64_t *dist,
577                       int *skippable, int64_t *sse, int plane,
578                       BLOCK_SIZE bsize, TX_SIZE tx_size) {
579   MACROBLOCKD *xd = &x->e_mbd;
580   const struct macroblockd_plane *pd = &xd->plane[plane];
581   const struct macroblock_plane *const p = &x->plane[plane];
582   const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
583   const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
584   const int step = 1 << (tx_size << 1);
585   const int block_step = (1 << tx_size);
586   int block = 0, r, c;
587   int shift = tx_size == TX_32X32 ? 0 : 2;
588   const int max_blocks_wide = num_4x4_w + (xd->mb_to_right_edge >= 0 ? 0 :
589       xd->mb_to_right_edge >> (5 + pd->subsampling_x));
590   const int max_blocks_high = num_4x4_h + (xd->mb_to_bottom_edge >= 0 ? 0 :
591       xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
592   int eob_cost = 0;
593
594   (void)cpi;
595   vp9_subtract_plane(x, bsize, plane);
596   *skippable = 1;
597   // Keep track of the row and column of the blocks we use so that we know
598   // if we are in the unrestricted motion border.
599   for (r = 0; r < max_blocks_high; r += block_step) {
600     for (c = 0; c < num_4x4_w; c += block_step) {
601       if (c < max_blocks_wide) {
602         const scan_order *const scan_order = &vp9_default_scan_orders[tx_size];
603         tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
604         tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
605         tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
606         uint16_t *const eob = &p->eobs[block];
607         const int diff_stride = 4 * num_4x4_blocks_wide_lookup[bsize];
608         const int16_t *src_diff;
609         src_diff = &p->src_diff[(r * diff_stride + c) << 2];
610
611         switch (tx_size) {
612           case TX_32X32:
613             vp9_fdct32x32_rd(src_diff, coeff, diff_stride);
614             vp9_quantize_fp_32x32(coeff, 1024, x->skip_block, p->zbin,
615                                   p->round_fp, p->quant_fp, p->quant_shift,
616                                   qcoeff, dqcoeff, pd->dequant, eob,
617                                   scan_order->scan, scan_order->iscan);
618             break;
619           case TX_16X16:
620             vp9_hadamard_16x16(src_diff, diff_stride, (int16_t *)coeff);
621             vp9_quantize_fp(coeff, 256, x->skip_block, p->zbin, p->round_fp,
622                             p->quant_fp, p->quant_shift, qcoeff, dqcoeff,
623                             pd->dequant, eob,
624                             scan_order->scan, scan_order->iscan);
625             break;
626           case TX_8X8:
627             vp9_hadamard_8x8(src_diff, diff_stride, (int16_t *)coeff);
628             vp9_quantize_fp(coeff, 64, x->skip_block, p->zbin, p->round_fp,
629                             p->quant_fp, p->quant_shift, qcoeff, dqcoeff,
630                             pd->dequant, eob,
631                             scan_order->scan, scan_order->iscan);
632             break;
633           case TX_4X4:
634             x->fwd_txm4x4(src_diff, coeff, diff_stride);
635             vp9_quantize_fp(coeff, 16, x->skip_block, p->zbin, p->round_fp,
636                             p->quant_fp, p->quant_shift, qcoeff, dqcoeff,
637                             pd->dequant, eob,
638                             scan_order->scan, scan_order->iscan);
639             break;
640           default:
641             assert(0);
642             break;
643         }
644         *skippable &= (*eob == 0);
645         eob_cost += 1;
646       }
647       block += step;
648     }
649   }
650
651   if (*skippable && *sse < INT64_MAX) {
652     *rate = 0;
653     *dist = (*sse << 6) >> shift;
654     *sse = *dist;
655     return;
656   }
657
658   block = 0;
659   *rate = 0;
660   *dist = 0;
661   *sse = (*sse << 6) >> shift;
662   for (r = 0; r < max_blocks_high; r += block_step) {
663     for (c = 0; c < num_4x4_w; c += block_step) {
664       if (c < max_blocks_wide) {
665         tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
666         tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
667         tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
668         uint16_t *const eob = &p->eobs[block];
669
670         if (*eob == 1)
671           *rate += (int)abs(qcoeff[0]);
672         else if (*eob > 1)
673           *rate += (int)vp9_satd((const int16_t *)qcoeff, step << 4);
674
675         *dist += vp9_block_error_fp(coeff, dqcoeff, step << 4) >> shift;
676       }
677       block += step;
678     }
679   }
680
681   if (*skippable == 0) {
682     *rate <<= 10;
683     *rate += (eob_cost << 8);
684   }
685 }
686 #endif
687
688 static void model_rd_for_sb_uv(VP9_COMP *cpi, BLOCK_SIZE bsize,
689                                MACROBLOCK *x, MACROBLOCKD *xd,
690                                int *out_rate_sum, int64_t *out_dist_sum,
691                                unsigned int *var_y, unsigned int *sse_y) {
692   // Note our transform coeffs are 8 times an orthogonal transform.
693   // Hence quantizer step is also 8 times. To get effective quantizer
694   // we need to divide by 8 before sending to modeling function.
695   unsigned int sse;
696   int rate;
697   int64_t dist;
698   int i;
699
700   *out_rate_sum = 0;
701   *out_dist_sum = 0;
702
703   for (i = 1; i <= 2; ++i) {
704     struct macroblock_plane *const p = &x->plane[i];
705     struct macroblockd_plane *const pd = &xd->plane[i];
706     const uint32_t dc_quant = pd->dequant[0];
707     const uint32_t ac_quant = pd->dequant[1];
708     const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
709     unsigned int var;
710
711     if (!x->color_sensitivity[i - 1])
712       continue;
713
714     var = cpi->fn_ptr[bs].vf(p->src.buf, p->src.stride,
715                              pd->dst.buf, pd->dst.stride, &sse);
716     *var_y += var;
717     *sse_y += sse;
718
719   #if CONFIG_VP9_HIGHBITDEPTH
720     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
721       vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bs],
722                                    dc_quant >> (xd->bd - 5), &rate, &dist);
723     } else {
724       vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bs],
725                                    dc_quant >> 3, &rate, &dist);
726     }
727   #else
728     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bs],
729                                  dc_quant >> 3, &rate, &dist);
730   #endif  // CONFIG_VP9_HIGHBITDEPTH
731
732     *out_rate_sum += rate >> 1;
733     *out_dist_sum += dist << 3;
734
735   #if CONFIG_VP9_HIGHBITDEPTH
736     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
737       vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bs],
738                                    ac_quant >> (xd->bd - 5), &rate, &dist);
739     } else {
740       vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bs],
741                                    ac_quant >> 3, &rate, &dist);
742     }
743   #else
744     vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bs],
745                                  ac_quant >> 3, &rate, &dist);
746   #endif  // CONFIG_VP9_HIGHBITDEPTH
747
748     *out_rate_sum += rate;
749     *out_dist_sum += dist << 4;
750   }
751 }
752
753 static int get_pred_buffer(PRED_BUFFER *p, int len) {
754   int i;
755
756   for (i = 0; i < len; i++) {
757     if (!p[i].in_use) {
758       p[i].in_use = 1;
759       return i;
760     }
761   }
762   return -1;
763 }
764
765 static void free_pred_buffer(PRED_BUFFER *p) {
766   if (p != NULL)
767     p->in_use = 0;
768 }
769
770 static void encode_breakout_test(VP9_COMP *cpi, MACROBLOCK *x,
771                                  BLOCK_SIZE bsize, int mi_row, int mi_col,
772                                  MV_REFERENCE_FRAME ref_frame,
773                                  PREDICTION_MODE this_mode,
774                                  unsigned int var_y, unsigned int sse_y,
775                                  struct buf_2d yv12_mb[][MAX_MB_PLANE],
776                                  int *rate, int64_t *dist) {
777   MACROBLOCKD *xd = &x->e_mbd;
778   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
779
780   const BLOCK_SIZE uv_size = get_plane_block_size(bsize, &xd->plane[1]);
781   unsigned int var = var_y, sse = sse_y;
782   // Skipping threshold for ac.
783   unsigned int thresh_ac;
784   // Skipping threshold for dc.
785   unsigned int thresh_dc;
786   if (x->encode_breakout > 0) {
787     // Set a maximum for threshold to avoid big PSNR loss in low bit rate
788     // case. Use extreme low threshold for static frames to limit
789     // skipping.
790     const unsigned int max_thresh = 36000;
791     // The encode_breakout input
792     const unsigned int min_thresh =
793         MIN(((unsigned int)x->encode_breakout << 4), max_thresh);
794 #if CONFIG_VP9_HIGHBITDEPTH
795     const int shift = (xd->bd << 1) - 16;
796 #endif
797
798     // Calculate threshold according to dequant value.
799     thresh_ac = (xd->plane[0].dequant[1] * xd->plane[0].dequant[1]) >> 3;
800 #if CONFIG_VP9_HIGHBITDEPTH
801     if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && shift > 0) {
802       thresh_ac = ROUND_POWER_OF_TWO(thresh_ac, shift);
803     }
804 #endif  // CONFIG_VP9_HIGHBITDEPTH
805     thresh_ac = clamp(thresh_ac, min_thresh, max_thresh);
806
807     // Adjust ac threshold according to partition size.
808     thresh_ac >>=
809         8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
810
811     thresh_dc = (xd->plane[0].dequant[0] * xd->plane[0].dequant[0] >> 6);
812 #if CONFIG_VP9_HIGHBITDEPTH
813     if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && shift > 0) {
814       thresh_dc = ROUND_POWER_OF_TWO(thresh_dc, shift);
815     }
816 #endif  // CONFIG_VP9_HIGHBITDEPTH
817   } else {
818     thresh_ac = 0;
819     thresh_dc = 0;
820   }
821
822   // Y skipping condition checking for ac and dc.
823   if (var <= thresh_ac && (sse - var) <= thresh_dc) {
824     unsigned int sse_u, sse_v;
825     unsigned int var_u, var_v;
826
827     // Skip UV prediction unless breakout is zero (lossless) to save
828     // computation with low impact on the result
829     if (x->encode_breakout == 0) {
830       xd->plane[1].pre[0] = yv12_mb[ref_frame][1];
831       xd->plane[2].pre[0] = yv12_mb[ref_frame][2];
832       vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col, bsize);
833     }
834
835     var_u = cpi->fn_ptr[uv_size].vf(x->plane[1].src.buf,
836                                     x->plane[1].src.stride,
837                                     xd->plane[1].dst.buf,
838                                     xd->plane[1].dst.stride, &sse_u);
839
840     // U skipping condition checking
841     if (((var_u << 2) <= thresh_ac) && (sse_u - var_u <= thresh_dc)) {
842       var_v = cpi->fn_ptr[uv_size].vf(x->plane[2].src.buf,
843                                       x->plane[2].src.stride,
844                                       xd->plane[2].dst.buf,
845                                       xd->plane[2].dst.stride, &sse_v);
846
847       // V skipping condition checking
848       if (((var_v << 2) <= thresh_ac) && (sse_v - var_v <= thresh_dc)) {
849         x->skip = 1;
850
851         // The cost of skip bit needs to be added.
852         *rate = cpi->inter_mode_cost[mbmi->mode_context[ref_frame]]
853                                     [INTER_OFFSET(this_mode)];
854
855         // More on this part of rate
856         // rate += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
857
858         // Scaling factor for SSE from spatial domain to frequency
859         // domain is 16. Adjust distortion accordingly.
860         // TODO(yunqingwang): In this function, only y-plane dist is
861         // calculated.
862         *dist = (sse << 4);  // + ((sse_u + sse_v) << 4);
863
864         // *disable_skip = 1;
865       }
866     }
867   }
868 }
869
870 struct estimate_block_intra_args {
871   VP9_COMP *cpi;
872   MACROBLOCK *x;
873   PREDICTION_MODE mode;
874   int rate;
875   int64_t dist;
876 };
877
878 static void estimate_block_intra(int plane, int block, BLOCK_SIZE plane_bsize,
879                                  TX_SIZE tx_size, void *arg) {
880   struct estimate_block_intra_args* const args = arg;
881   VP9_COMP *const cpi = args->cpi;
882   MACROBLOCK *const x = args->x;
883   MACROBLOCKD *const xd = &x->e_mbd;
884   struct macroblock_plane *const p = &x->plane[0];
885   struct macroblockd_plane *const pd = &xd->plane[0];
886   const BLOCK_SIZE bsize_tx = txsize_to_bsize[tx_size];
887   uint8_t *const src_buf_base = p->src.buf;
888   uint8_t *const dst_buf_base = pd->dst.buf;
889   const int src_stride = p->src.stride;
890   const int dst_stride = pd->dst.stride;
891   int i, j;
892   int rate;
893   int64_t dist;
894   int64_t this_sse = INT64_MAX;
895   int is_skippable;
896
897   txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &i, &j);
898   assert(plane == 0);
899   (void) plane;
900
901   p->src.buf = &src_buf_base[4 * (j * src_stride + i)];
902   pd->dst.buf = &dst_buf_base[4 * (j * dst_stride + i)];
903   // Use source buffer as an approximation for the fully reconstructed buffer.
904   vp9_predict_intra_block(xd, block >> (2 * tx_size),
905                           b_width_log2_lookup[plane_bsize],
906                           tx_size, args->mode,
907                           x->skip_encode ? p->src.buf : pd->dst.buf,
908                           x->skip_encode ? src_stride : dst_stride,
909                           pd->dst.buf, dst_stride,
910                           i, j, 0);
911
912   // TODO(jingning): This needs further refactoring.
913   block_yrd(cpi, x, &rate, &dist, &is_skippable, &this_sse, 0,
914             bsize_tx, MIN(tx_size, TX_16X16));
915   x->skip_txfm[0] = is_skippable;
916   rate += vp9_cost_bit(vp9_get_skip_prob(&cpi->common, xd), is_skippable);
917
918   p->src.buf = src_buf_base;
919   pd->dst.buf = dst_buf_base;
920   args->rate += rate;
921   args->dist += dist;
922 }
923
924 static const THR_MODES mode_idx[MAX_REF_FRAMES - 1][4] = {
925   {THR_DC, THR_V_PRED, THR_H_PRED, THR_TM},
926   {THR_NEARESTMV, THR_NEARMV, THR_ZEROMV, THR_NEWMV},
927   {THR_NEARESTG, THR_NEARG, THR_ZEROG, THR_NEWG},
928 };
929
930 static const PREDICTION_MODE intra_mode_list[] = {
931   DC_PRED, V_PRED, H_PRED, TM_PRED
932 };
933
934 static int mode_offset(const PREDICTION_MODE mode) {
935   if (mode >= NEARESTMV) {
936     return INTER_OFFSET(mode);
937   } else {
938     switch (mode) {
939       case DC_PRED:
940         return 0;
941       case V_PRED:
942         return 1;
943       case H_PRED:
944         return 2;
945       case TM_PRED:
946         return 3;
947       default:
948         return -1;
949     }
950   }
951 }
952
953 static INLINE void update_thresh_freq_fact(VP9_COMP *cpi,
954                                            TileDataEnc *tile_data,
955                                            BLOCK_SIZE bsize,
956                                            MV_REFERENCE_FRAME ref_frame,
957                                            THR_MODES best_mode_idx,
958                                            PREDICTION_MODE mode) {
959   THR_MODES thr_mode_idx = mode_idx[ref_frame][mode_offset(mode)];
960   int *freq_fact = &tile_data->thresh_freq_fact[bsize][thr_mode_idx];
961   if (thr_mode_idx == best_mode_idx)
962     *freq_fact -= (*freq_fact >> 4);
963   else
964     *freq_fact = MIN(*freq_fact + RD_THRESH_INC,
965         cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT);
966 }
967
968 void vp9_pick_intra_mode(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *rd_cost,
969                          BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
970   MACROBLOCKD *const xd = &x->e_mbd;
971   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
972   RD_COST this_rdc, best_rdc;
973   PREDICTION_MODE this_mode;
974   struct estimate_block_intra_args args = { cpi, x, DC_PRED, 0, 0 };
975   const TX_SIZE intra_tx_size =
976       MIN(max_txsize_lookup[bsize],
977           tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
978   MODE_INFO *const mic = xd->mi[0];
979   int *bmode_costs;
980   const MODE_INFO *above_mi = xd->mi[-xd->mi_stride];
981   const MODE_INFO *left_mi = xd->left_available ? xd->mi[-1] : NULL;
982   const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
983   const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
984   bmode_costs = cpi->y_mode_costs[A][L];
985
986   (void) ctx;
987   vp9_rd_cost_reset(&best_rdc);
988   vp9_rd_cost_reset(&this_rdc);
989
990   mbmi->ref_frame[0] = INTRA_FRAME;
991   mbmi->mv[0].as_int = INVALID_MV;
992   mbmi->uv_mode = DC_PRED;
993   memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
994
995   // Change the limit of this loop to add other intra prediction
996   // mode tests.
997   for (this_mode = DC_PRED; this_mode <= H_PRED; ++this_mode) {
998     args.mode = this_mode;
999     args.rate = 0;
1000     args.dist = 0;
1001     mbmi->tx_size = intra_tx_size;
1002     vp9_foreach_transformed_block_in_plane(xd, bsize, 0,
1003                                            estimate_block_intra, &args);
1004     this_rdc.rate = args.rate;
1005     this_rdc.dist = args.dist;
1006     this_rdc.rate += bmode_costs[this_mode];
1007     this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
1008                              this_rdc.rate, this_rdc.dist);
1009
1010     if (this_rdc.rdcost < best_rdc.rdcost) {
1011       best_rdc = this_rdc;
1012       mbmi->mode = this_mode;
1013     }
1014   }
1015
1016   *rd_cost = best_rdc;
1017 }
1018
1019 static void init_ref_frame_cost(VP9_COMMON *const cm,
1020                                 MACROBLOCKD *const xd,
1021                                 int ref_frame_cost[MAX_REF_FRAMES]) {
1022   vp9_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
1023   vp9_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
1024   vp9_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
1025
1026   ref_frame_cost[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
1027   ref_frame_cost[LAST_FRAME] = ref_frame_cost[GOLDEN_FRAME] =
1028     ref_frame_cost[ALTREF_FRAME] = vp9_cost_bit(intra_inter_p, 1);
1029
1030   ref_frame_cost[LAST_FRAME] += vp9_cost_bit(ref_single_p1, 0);
1031   ref_frame_cost[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
1032   ref_frame_cost[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
1033   ref_frame_cost[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
1034   ref_frame_cost[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
1035 }
1036
1037 typedef struct {
1038   MV_REFERENCE_FRAME ref_frame;
1039   PREDICTION_MODE pred_mode;
1040 } REF_MODE;
1041
1042 #define RT_INTER_MODES 8
1043 static const REF_MODE ref_mode_set[RT_INTER_MODES] = {
1044     {LAST_FRAME, ZEROMV},
1045     {LAST_FRAME, NEARESTMV},
1046     {GOLDEN_FRAME, ZEROMV},
1047     {LAST_FRAME, NEARMV},
1048     {LAST_FRAME, NEWMV},
1049     {GOLDEN_FRAME, NEARESTMV},
1050     {GOLDEN_FRAME, NEARMV},
1051     {GOLDEN_FRAME, NEWMV}
1052 };
1053
1054 // TODO(jingning) placeholder for inter-frame non-RD mode decision.
1055 // this needs various further optimizations. to be continued..
1056 void vp9_pick_inter_mode(VP9_COMP *cpi, MACROBLOCK *x,
1057                          TileDataEnc *tile_data,
1058                          int mi_row, int mi_col, RD_COST *rd_cost,
1059                          BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
1060   VP9_COMMON *const cm = &cpi->common;
1061   TileInfo *const tile_info = &tile_data->tile_info;
1062   MACROBLOCKD *const xd = &x->e_mbd;
1063   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1064   struct macroblockd_plane *const pd = &xd->plane[0];
1065   PREDICTION_MODE best_mode = ZEROMV;
1066   MV_REFERENCE_FRAME ref_frame, best_ref_frame = LAST_FRAME;
1067   MV_REFERENCE_FRAME usable_ref_frame;
1068   TX_SIZE best_tx_size = TX_SIZES;
1069   INTERP_FILTER best_pred_filter = EIGHTTAP;
1070   int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
1071   struct buf_2d yv12_mb[4][MAX_MB_PLANE];
1072   static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
1073                                     VP9_ALT_FLAG };
1074   RD_COST this_rdc, best_rdc;
1075   uint8_t skip_txfm = 0, best_mode_skip_txfm = 0;
1076   // var_y and sse_y are saved to be used in skipping checking
1077   unsigned int var_y = UINT_MAX;
1078   unsigned int sse_y = UINT_MAX;
1079   // Reduce the intra cost penalty for small blocks (<=16x16).
1080   const int reduction_fac = (bsize <= BLOCK_16X16) ?
1081       ((bsize <= BLOCK_8X8) ? 4 : 2) : 0;
1082   const int intra_cost_penalty = vp9_get_intra_cost_penalty(
1083       cm->base_qindex, cm->y_dc_delta_q, cm->bit_depth) >> reduction_fac;
1084   const int64_t inter_mode_thresh = RDCOST(x->rdmult, x->rddiv,
1085                                            intra_cost_penalty, 0);
1086   const int *const rd_threshes = cpi->rd.threshes[mbmi->segment_id][bsize];
1087   const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
1088   INTERP_FILTER filter_ref;
1089   const int bsl = mi_width_log2_lookup[bsize];
1090   const int pred_filter_search = cm->interp_filter == SWITCHABLE ?
1091       (((mi_row + mi_col) >> bsl) +
1092        get_chessboard_index(cm->current_video_frame)) & 0x1 : 0;
1093   int const_motion[MAX_REF_FRAMES] = { 0 };
1094   const int bh = num_4x4_blocks_high_lookup[bsize] << 2;
1095   const int bw = num_4x4_blocks_wide_lookup[bsize] << 2;
1096   // For speed 6, the result of interp filter is reused later in actual encoding
1097   // process.
1098   // tmp[3] points to dst buffer, and the other 3 point to allocated buffers.
1099   PRED_BUFFER tmp[4];
1100   DECLARE_ALIGNED(16, uint8_t, pred_buf[3 * 64 * 64]);
1101 #if CONFIG_VP9_HIGHBITDEPTH
1102   DECLARE_ALIGNED(16, uint16_t, pred_buf_16[3 * 64 * 64]);
1103 #endif
1104   struct buf_2d orig_dst = pd->dst;
1105   PRED_BUFFER *best_pred = NULL;
1106   PRED_BUFFER *this_mode_pred = NULL;
1107   const int pixels_in_block = bh * bw;
1108   int reuse_inter_pred = cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready;
1109   int ref_frame_skip_mask = 0;
1110   int idx;
1111   int best_pred_sad = INT_MAX;
1112   int best_early_term = 0;
1113   int ref_frame_cost[MAX_REF_FRAMES];
1114
1115   init_ref_frame_cost(cm, xd, ref_frame_cost);
1116
1117   if (reuse_inter_pred) {
1118     int i;
1119     for (i = 0; i < 3; i++) {
1120 #if CONFIG_VP9_HIGHBITDEPTH
1121       if (cm->use_highbitdepth)
1122         tmp[i].data = CONVERT_TO_BYTEPTR(&pred_buf_16[pixels_in_block * i]);
1123       else
1124         tmp[i].data = &pred_buf[pixels_in_block * i];
1125 #else
1126       tmp[i].data = &pred_buf[pixels_in_block * i];
1127 #endif  // CONFIG_VP9_HIGHBITDEPTH
1128       tmp[i].stride = bw;
1129       tmp[i].in_use = 0;
1130     }
1131     tmp[3].data = pd->dst.buf;
1132     tmp[3].stride = pd->dst.stride;
1133     tmp[3].in_use = 0;
1134   }
1135
1136   x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
1137   x->skip = 0;
1138
1139   if (xd->up_available)
1140     filter_ref = xd->mi[-xd->mi_stride]->mbmi.interp_filter;
1141   else if (xd->left_available)
1142     filter_ref = xd->mi[-1]->mbmi.interp_filter;
1143   else
1144     filter_ref = cm->interp_filter;
1145
1146   // initialize mode decisions
1147   vp9_rd_cost_reset(&best_rdc);
1148   vp9_rd_cost_reset(rd_cost);
1149   mbmi->sb_type = bsize;
1150   mbmi->ref_frame[0] = NONE;
1151   mbmi->ref_frame[1] = NONE;
1152   mbmi->tx_size = MIN(max_txsize_lookup[bsize],
1153                       tx_mode_to_biggest_tx_size[cm->tx_mode]);
1154
1155 #if CONFIG_VP9_TEMPORAL_DENOISING
1156   vp9_denoiser_reset_frame_stats(ctx);
1157 #endif
1158
1159   if (cpi->rc.frames_since_golden == 0) {
1160     usable_ref_frame = LAST_FRAME;
1161   } else {
1162     usable_ref_frame = GOLDEN_FRAME;
1163   }
1164
1165   for (ref_frame = LAST_FRAME; ref_frame <= usable_ref_frame; ++ref_frame) {
1166     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
1167
1168     x->pred_mv_sad[ref_frame] = INT_MAX;
1169     frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
1170     frame_mv[ZEROMV][ref_frame].as_int = 0;
1171
1172     if ((cpi->ref_frame_flags & flag_list[ref_frame]) && (yv12 != NULL)) {
1173       int_mv *const candidates = mbmi->ref_mvs[ref_frame];
1174       const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
1175
1176       vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col,
1177                            sf, sf);
1178
1179       if (cm->use_prev_frame_mvs)
1180         vp9_find_mv_refs(cm, xd, tile_info, xd->mi[0], ref_frame,
1181                          candidates, mi_row, mi_col, NULL, NULL);
1182       else
1183         const_motion[ref_frame] = mv_refs_rt(cm, xd, tile_info,
1184                                              xd->mi[0],
1185                                              ref_frame, candidates,
1186                                              mi_row, mi_col);
1187
1188       vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
1189                             &frame_mv[NEARESTMV][ref_frame],
1190                             &frame_mv[NEARMV][ref_frame]);
1191
1192       if (!vp9_is_scaled(sf) && bsize >= BLOCK_8X8)
1193         vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride,
1194                     ref_frame, bsize);
1195     } else {
1196       ref_frame_skip_mask |= (1 << ref_frame);
1197     }
1198   }
1199
1200   for (idx = 0; idx < RT_INTER_MODES; ++idx) {
1201     int rate_mv = 0;
1202     int mode_rd_thresh;
1203     int mode_index;
1204     int i;
1205     PREDICTION_MODE this_mode = ref_mode_set[idx].pred_mode;
1206     int64_t this_sse;
1207     int is_skippable;
1208     int this_early_term = 0;
1209
1210     if (!(cpi->sf.inter_mode_mask[bsize] & (1 << this_mode)))
1211       continue;
1212
1213     ref_frame = ref_mode_set[idx].ref_frame;
1214     if (!(cpi->ref_frame_flags & flag_list[ref_frame]))
1215       continue;
1216     if (const_motion[ref_frame] && this_mode == NEARMV)
1217       continue;
1218
1219     i = (ref_frame == LAST_FRAME) ? GOLDEN_FRAME : LAST_FRAME;
1220     if (cpi->ref_frame_flags & flag_list[i])
1221       if (x->pred_mv_sad[ref_frame] > (x->pred_mv_sad[i] << 1))
1222         ref_frame_skip_mask |= (1 << ref_frame);
1223     if (ref_frame_skip_mask & (1 << ref_frame))
1224       continue;
1225
1226     // Select prediction reference frames.
1227     for (i = 0; i < MAX_MB_PLANE; i++)
1228       xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
1229
1230     mbmi->ref_frame[0] = ref_frame;
1231     set_ref_ptrs(cm, xd, ref_frame, NONE);
1232
1233     mode_index = mode_idx[ref_frame][INTER_OFFSET(this_mode)];
1234     mode_rd_thresh = best_mode_skip_txfm ?
1235             rd_threshes[mode_index] << 1 : rd_threshes[mode_index];
1236     if (rd_less_than_thresh(best_rdc.rdcost, mode_rd_thresh,
1237                             rd_thresh_freq_fact[mode_index]))
1238       continue;
1239
1240     if (this_mode == NEWMV) {
1241       if (ref_frame > LAST_FRAME) {
1242         int tmp_sad;
1243         int dis, cost_list[5];
1244
1245         if (bsize < BLOCK_16X16)
1246           continue;
1247
1248         tmp_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col);
1249
1250         if (tmp_sad > x->pred_mv_sad[LAST_FRAME])
1251           continue;
1252         if (tmp_sad + (num_pels_log2_lookup[bsize] << 4) > best_pred_sad)
1253           continue;
1254
1255         frame_mv[NEWMV][ref_frame].as_int = mbmi->mv[0].as_int;
1256         rate_mv = vp9_mv_bit_cost(&frame_mv[NEWMV][ref_frame].as_mv,
1257           &mbmi->ref_mvs[ref_frame][0].as_mv,
1258           x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
1259         frame_mv[NEWMV][ref_frame].as_mv.row >>= 3;
1260         frame_mv[NEWMV][ref_frame].as_mv.col >>= 3;
1261
1262         cpi->find_fractional_mv_step(x, &frame_mv[NEWMV][ref_frame].as_mv,
1263           &mbmi->ref_mvs[ref_frame][0].as_mv,
1264           cpi->common.allow_high_precision_mv,
1265           x->errorperbit,
1266           &cpi->fn_ptr[bsize],
1267           cpi->sf.mv.subpel_force_stop,
1268           cpi->sf.mv.subpel_iters_per_step,
1269           cond_cost_list(cpi, cost_list),
1270           x->nmvjointcost, x->mvcost, &dis,
1271           &x->pred_sse[ref_frame], NULL, 0, 0);
1272       } else if (!combined_motion_search(cpi, x, bsize, mi_row, mi_col,
1273         &frame_mv[NEWMV][ref_frame], &rate_mv, best_rdc.rdcost)) {
1274         continue;
1275       }
1276     }
1277
1278     if (this_mode == NEWMV && ref_frame == LAST_FRAME &&
1279         frame_mv[NEWMV][LAST_FRAME].as_int != INVALID_MV) {
1280       const int pre_stride = xd->plane[0].pre[0].stride;
1281       const uint8_t * const pre_buf = xd->plane[0].pre[0].buf +
1282           (frame_mv[NEWMV][LAST_FRAME].as_mv.row >> 3) * pre_stride +
1283           (frame_mv[NEWMV][LAST_FRAME].as_mv.col >> 3);
1284       best_pred_sad = cpi->fn_ptr[bsize].sdf(x->plane[0].src.buf,
1285                                    x->plane[0].src.stride,
1286                                    pre_buf, pre_stride);
1287       x->pred_mv_sad[LAST_FRAME] = best_pred_sad;
1288     }
1289
1290     if (this_mode != NEARESTMV &&
1291         frame_mv[this_mode][ref_frame].as_int ==
1292             frame_mv[NEARESTMV][ref_frame].as_int)
1293       continue;
1294
1295     mbmi->mode = this_mode;
1296     mbmi->mv[0].as_int = frame_mv[this_mode][ref_frame].as_int;
1297
1298     // Search for the best prediction filter type, when the resulting
1299     // motion vector is at sub-pixel accuracy level for luma component, i.e.,
1300     // the last three bits are all zeros.
1301     if (reuse_inter_pred) {
1302       if (!this_mode_pred) {
1303         this_mode_pred = &tmp[3];
1304       } else {
1305         this_mode_pred = &tmp[get_pred_buffer(tmp, 3)];
1306         pd->dst.buf = this_mode_pred->data;
1307         pd->dst.stride = bw;
1308       }
1309     }
1310
1311     if ((this_mode == NEWMV || filter_ref == SWITCHABLE) && pred_filter_search
1312         && (ref_frame == LAST_FRAME)
1313         && (((mbmi->mv[0].as_mv.row | mbmi->mv[0].as_mv.col) & 0x07) != 0)) {
1314       int pf_rate[3];
1315       int64_t pf_dist[3];
1316       unsigned int pf_var[3];
1317       unsigned int pf_sse[3];
1318       TX_SIZE pf_tx_size[3];
1319       int64_t best_cost = INT64_MAX;
1320       INTERP_FILTER best_filter = SWITCHABLE, filter;
1321       PRED_BUFFER *current_pred = this_mode_pred;
1322
1323       for (filter = EIGHTTAP; filter <= EIGHTTAP_SMOOTH; ++filter) {
1324         int64_t cost;
1325         mbmi->interp_filter = filter;
1326         vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
1327         model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rate[filter], &pf_dist[filter],
1328                           &pf_var[filter], &pf_sse[filter]);
1329         pf_rate[filter] += vp9_get_switchable_rate(cpi, xd);
1330         cost = RDCOST(x->rdmult, x->rddiv, pf_rate[filter], pf_dist[filter]);
1331         pf_tx_size[filter] = mbmi->tx_size;
1332         if (cost < best_cost) {
1333           best_filter = filter;
1334           best_cost = cost;
1335           skip_txfm = x->skip_txfm[0];
1336
1337           if (reuse_inter_pred) {
1338             if (this_mode_pred != current_pred) {
1339               free_pred_buffer(this_mode_pred);
1340               this_mode_pred = current_pred;
1341             }
1342
1343             if (filter < EIGHTTAP_SHARP) {
1344               current_pred = &tmp[get_pred_buffer(tmp, 3)];
1345               pd->dst.buf = current_pred->data;
1346               pd->dst.stride = bw;
1347             }
1348           }
1349         }
1350       }
1351
1352       if (reuse_inter_pred && this_mode_pred != current_pred)
1353         free_pred_buffer(current_pred);
1354
1355       mbmi->interp_filter = best_filter;
1356       mbmi->tx_size = pf_tx_size[best_filter];
1357       this_rdc.rate = pf_rate[best_filter];
1358       this_rdc.dist = pf_dist[best_filter];
1359       var_y = pf_var[best_filter];
1360       sse_y = pf_sse[best_filter];
1361       x->skip_txfm[0] = skip_txfm;
1362       if (reuse_inter_pred) {
1363         pd->dst.buf = this_mode_pred->data;
1364         pd->dst.stride = this_mode_pred->stride;
1365       }
1366     } else {
1367       mbmi->interp_filter = (filter_ref == SWITCHABLE) ? EIGHTTAP : filter_ref;
1368       vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
1369
1370       // For large partition blocks, extra testing is done.
1371       if (bsize > BLOCK_32X32 &&
1372         !cyclic_refresh_segment_id_boosted(xd->mi[0]->mbmi.segment_id) &&
1373         cm->base_qindex) {
1374         model_rd_for_sb_y_large(cpi, bsize, x, xd, &this_rdc.rate,
1375                                 &this_rdc.dist, &var_y, &sse_y, mi_row, mi_col,
1376                                 &this_early_term);
1377       } else {
1378         model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc.rate, &this_rdc.dist,
1379                           &var_y, &sse_y);
1380       }
1381     }
1382
1383     if (!this_early_term) {
1384       this_sse = (int64_t)sse_y;
1385       block_yrd(cpi, x, &this_rdc.rate, &this_rdc.dist, &is_skippable,
1386                 &this_sse, 0, bsize, MIN(mbmi->tx_size, TX_16X16));
1387       x->skip_txfm[0] = is_skippable;
1388       if (is_skippable) {
1389         this_rdc.rate = vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
1390       } else {
1391         if (RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist) <
1392             RDCOST(x->rdmult, x->rddiv, 0, this_sse)) {
1393           this_rdc.rate += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
1394         } else {
1395           this_rdc.rate = vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
1396           this_rdc.dist = this_sse;
1397           x->skip_txfm[0] = 1;
1398         }
1399       }
1400
1401       if (cm->interp_filter == SWITCHABLE) {
1402         if ((mbmi->mv[0].as_mv.row | mbmi->mv[0].as_mv.col) & 0x07)
1403           this_rdc.rate += vp9_get_switchable_rate(cpi, xd);
1404       }
1405     } else {
1406       this_rdc.rate += cm->interp_filter == SWITCHABLE ?
1407           vp9_get_switchable_rate(cpi, xd) : 0;
1408       this_rdc.rate += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
1409     }
1410
1411     if (x->color_sensitivity[0] || x->color_sensitivity[1]) {
1412       int uv_rate = 0;
1413       int64_t uv_dist = 0;
1414       if (x->color_sensitivity[0])
1415         vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, 1);
1416       if (x->color_sensitivity[1])
1417         vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, 2);
1418       model_rd_for_sb_uv(cpi, bsize, x, xd, &uv_rate, &uv_dist,
1419                          &var_y, &sse_y);
1420       this_rdc.rate += uv_rate;
1421       this_rdc.dist += uv_dist;
1422     }
1423
1424     this_rdc.rate += rate_mv;
1425     this_rdc.rate +=
1426         cpi->inter_mode_cost[mbmi->mode_context[ref_frame]][INTER_OFFSET(
1427             this_mode)];
1428     this_rdc.rate += ref_frame_cost[ref_frame];
1429     this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
1430
1431     // Skipping checking: test to see if this block can be reconstructed by
1432     // prediction only.
1433     if (cpi->allow_encode_breakout) {
1434       encode_breakout_test(cpi, x, bsize, mi_row, mi_col, ref_frame, this_mode,
1435                            var_y, sse_y, yv12_mb, &this_rdc.rate,
1436                            &this_rdc.dist);
1437       if (x->skip) {
1438         this_rdc.rate += rate_mv;
1439         this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, this_rdc.rate,
1440                                  this_rdc.dist);
1441       }
1442     }
1443
1444 #if CONFIG_VP9_TEMPORAL_DENOISING
1445     if (cpi->oxcf.noise_sensitivity > 0)
1446       vp9_denoiser_update_frame_stats(mbmi, sse_y, this_mode, ctx);
1447 #else
1448     (void)ctx;
1449 #endif
1450
1451     if (this_rdc.rdcost < best_rdc.rdcost || x->skip) {
1452       best_rdc = this_rdc;
1453       best_mode = this_mode;
1454       best_pred_filter = mbmi->interp_filter;
1455       best_tx_size = mbmi->tx_size;
1456       best_ref_frame = ref_frame;
1457       best_mode_skip_txfm = x->skip_txfm[0];
1458       best_early_term = this_early_term;
1459
1460       if (reuse_inter_pred) {
1461         free_pred_buffer(best_pred);
1462         best_pred = this_mode_pred;
1463       }
1464     } else {
1465       if (reuse_inter_pred)
1466         free_pred_buffer(this_mode_pred);
1467     }
1468
1469     if (x->skip)
1470       break;
1471
1472     // If early termination flag is 1 and at least 2 modes are checked,
1473     // the mode search is terminated.
1474     if (best_early_term && idx > 0) {
1475       x->skip = 1;
1476       break;
1477     }
1478   }
1479
1480   mbmi->mode          = best_mode;
1481   mbmi->interp_filter = best_pred_filter;
1482   mbmi->tx_size       = best_tx_size;
1483   mbmi->ref_frame[0]  = best_ref_frame;
1484   mbmi->mv[0].as_int  = frame_mv[best_mode][best_ref_frame].as_int;
1485   xd->mi[0]->bmi[0].as_mv[0].as_int = mbmi->mv[0].as_int;
1486   x->skip_txfm[0] = best_mode_skip_txfm;
1487
1488   // Perform intra prediction search, if the best SAD is above a certain
1489   // threshold.
1490   if (best_rdc.rdcost == INT64_MAX ||
1491       (!x->skip && best_rdc.rdcost > inter_mode_thresh &&
1492        bsize <= cpi->sf.max_intra_bsize)) {
1493     struct estimate_block_intra_args args = { cpi, x, DC_PRED, 0, 0 };
1494     const TX_SIZE intra_tx_size =
1495         MIN(max_txsize_lookup[bsize],
1496             tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
1497     int i;
1498     TX_SIZE best_intra_tx_size = TX_SIZES;
1499
1500     if (reuse_inter_pred && best_pred != NULL) {
1501       if (best_pred->data == orig_dst.buf) {
1502         this_mode_pred = &tmp[get_pred_buffer(tmp, 3)];
1503 #if CONFIG_VP9_HIGHBITDEPTH
1504         if (cm->use_highbitdepth)
1505           vp9_highbd_convolve_copy(best_pred->data, best_pred->stride,
1506                                    this_mode_pred->data, this_mode_pred->stride,
1507                                    NULL, 0, NULL, 0, bw, bh, xd->bd);
1508         else
1509           vp9_convolve_copy(best_pred->data, best_pred->stride,
1510                           this_mode_pred->data, this_mode_pred->stride,
1511                           NULL, 0, NULL, 0, bw, bh);
1512 #else
1513         vp9_convolve_copy(best_pred->data, best_pred->stride,
1514                           this_mode_pred->data, this_mode_pred->stride,
1515                           NULL, 0, NULL, 0, bw, bh);
1516 #endif  // CONFIG_VP9_HIGHBITDEPTH
1517         best_pred = this_mode_pred;
1518       }
1519     }
1520     pd->dst = orig_dst;
1521
1522     for (i = 0; i < 4; ++i) {
1523       const PREDICTION_MODE this_mode = intra_mode_list[i];
1524       THR_MODES mode_index = mode_idx[INTRA_FRAME][mode_offset(this_mode)];
1525       int mode_rd_thresh = rd_threshes[mode_index];
1526
1527       if (!((1 << this_mode) & cpi->sf.intra_y_mode_bsize_mask[bsize]))
1528         continue;
1529
1530       if (rd_less_than_thresh(best_rdc.rdcost, mode_rd_thresh,
1531                               rd_thresh_freq_fact[mode_index]))
1532         continue;
1533
1534       mbmi->mode = this_mode;
1535       mbmi->ref_frame[0] = INTRA_FRAME;
1536       args.mode = this_mode;
1537       args.rate = 0;
1538       args.dist = 0;
1539       mbmi->tx_size = intra_tx_size;
1540       vp9_foreach_transformed_block_in_plane(xd, bsize, 0,
1541                                              estimate_block_intra, &args);
1542       this_rdc.rate = args.rate;
1543       this_rdc.dist = args.dist;
1544       this_rdc.rate += cpi->mbmode_cost[this_mode];
1545       this_rdc.rate += ref_frame_cost[INTRA_FRAME];
1546       this_rdc.rate += intra_cost_penalty;
1547       this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
1548                                this_rdc.rate, this_rdc.dist);
1549
1550       if (this_rdc.rdcost < best_rdc.rdcost) {
1551         best_rdc = this_rdc;
1552         best_mode = this_mode;
1553         best_intra_tx_size = mbmi->tx_size;
1554         best_ref_frame = INTRA_FRAME;
1555         mbmi->uv_mode = this_mode;
1556         mbmi->mv[0].as_int = INVALID_MV;
1557         best_mode_skip_txfm = x->skip_txfm[0];
1558       }
1559     }
1560
1561     // Reset mb_mode_info to the best inter mode.
1562     if (best_ref_frame != INTRA_FRAME) {
1563       mbmi->tx_size = best_tx_size;
1564     } else {
1565       mbmi->tx_size = best_intra_tx_size;
1566     }
1567   }
1568
1569   pd->dst = orig_dst;
1570   mbmi->mode = best_mode;
1571   mbmi->ref_frame[0] = best_ref_frame;
1572   x->skip_txfm[0] = best_mode_skip_txfm;
1573
1574   if (reuse_inter_pred && best_pred != NULL) {
1575     if (best_pred->data != orig_dst.buf && is_inter_mode(mbmi->mode)) {
1576 #if CONFIG_VP9_HIGHBITDEPTH
1577       if (cm->use_highbitdepth)
1578         vp9_highbd_convolve_copy(best_pred->data, best_pred->stride,
1579                                  pd->dst.buf, pd->dst.stride, NULL, 0,
1580                                  NULL, 0, bw, bh, xd->bd);
1581       else
1582         vp9_convolve_copy(best_pred->data, best_pred->stride,
1583                           pd->dst.buf, pd->dst.stride, NULL, 0,
1584                           NULL, 0, bw, bh);
1585 #else
1586       vp9_convolve_copy(best_pred->data, best_pred->stride,
1587                         pd->dst.buf, pd->dst.stride, NULL, 0,
1588                         NULL, 0, bw, bh);
1589 #endif  // CONFIG_VP9_HIGHBITDEPTH
1590     }
1591   }
1592
1593   if (cpi->sf.adaptive_rd_thresh) {
1594     THR_MODES best_mode_idx = mode_idx[best_ref_frame][mode_offset(mbmi->mode)];
1595
1596     if (best_ref_frame == INTRA_FRAME) {
1597       // Only consider the modes that are included in the intra_mode_list.
1598       int intra_modes = sizeof(intra_mode_list)/sizeof(PREDICTION_MODE);
1599       int i;
1600
1601       // TODO(yunqingwang): Check intra mode mask and only update freq_fact
1602       // for those valid modes.
1603       for (i = 0; i < intra_modes; i++) {
1604         update_thresh_freq_fact(cpi, tile_data, bsize, INTRA_FRAME,
1605                                 best_mode_idx, intra_mode_list[i]);
1606       }
1607     } else {
1608       for (ref_frame = LAST_FRAME; ref_frame <= GOLDEN_FRAME; ++ref_frame) {
1609         PREDICTION_MODE this_mode;
1610         if (best_ref_frame != ref_frame) continue;
1611         for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
1612           update_thresh_freq_fact(cpi, tile_data, bsize, ref_frame,
1613                                   best_mode_idx, this_mode);
1614         }
1615       }
1616     }
1617   }
1618
1619   *rd_cost = best_rdc;
1620 }
1621
1622 void vp9_pick_inter_mode_sub8x8(VP9_COMP *cpi, MACROBLOCK *x,
1623                                 TileDataEnc *tile_data,
1624                                 int mi_row, int mi_col, RD_COST *rd_cost,
1625                                 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
1626   VP9_COMMON *const cm = &cpi->common;
1627   TileInfo *const tile_info = &tile_data->tile_info;
1628   SPEED_FEATURES *const sf = &cpi->sf;
1629   MACROBLOCKD *const xd = &x->e_mbd;
1630   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1631   const struct segmentation *const seg = &cm->seg;
1632   MV_REFERENCE_FRAME ref_frame, second_ref_frame = NONE;
1633   MV_REFERENCE_FRAME best_ref_frame = NONE;
1634   unsigned char segment_id = mbmi->segment_id;
1635   struct buf_2d yv12_mb[4][MAX_MB_PLANE];
1636   static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
1637                                     VP9_ALT_FLAG };
1638   int64_t best_rd = INT64_MAX;
1639   b_mode_info bsi[MAX_REF_FRAMES][4];
1640   int ref_frame_skip_mask = 0;
1641   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1642   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1643   int idx, idy;
1644
1645   x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
1646   ctx->pred_pixel_ready = 0;
1647
1648   for (ref_frame = LAST_FRAME; ref_frame <= GOLDEN_FRAME; ++ref_frame) {
1649     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
1650     int_mv dummy_mv[2];
1651     x->pred_mv_sad[ref_frame] = INT_MAX;
1652
1653     if ((cpi->ref_frame_flags & flag_list[ref_frame]) && (yv12 != NULL)) {
1654       int_mv *const candidates = mbmi->ref_mvs[ref_frame];
1655       const struct scale_factors *const sf =
1656                              &cm->frame_refs[ref_frame - 1].sf;
1657       vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col,
1658                            sf, sf);
1659       vp9_find_mv_refs(cm, xd, tile_info, xd->mi[0], ref_frame,
1660                        candidates, mi_row, mi_col, NULL, NULL);
1661
1662       vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
1663                             &dummy_mv[0], &dummy_mv[1]);
1664     } else {
1665       ref_frame_skip_mask |= (1 << ref_frame);
1666     }
1667   }
1668
1669   mbmi->sb_type = bsize;
1670   mbmi->tx_size = TX_4X4;
1671   mbmi->uv_mode = DC_PRED;
1672   mbmi->ref_frame[0] = LAST_FRAME;
1673   mbmi->ref_frame[1] = NONE;
1674   mbmi->interp_filter = cm->interp_filter == SWITCHABLE ? EIGHTTAP
1675                                                         : cm->interp_filter;
1676
1677   for (ref_frame = LAST_FRAME; ref_frame <= GOLDEN_FRAME; ++ref_frame) {
1678     int64_t this_rd = 0;
1679     int plane;
1680
1681     if (ref_frame_skip_mask & (1 << ref_frame))
1682       continue;
1683
1684     // TODO(jingning, agrange): Scaling reference frame not supported for
1685     // sub8x8 blocks. Is this supported now?
1686     if (ref_frame > INTRA_FRAME &&
1687         vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf))
1688       continue;
1689
1690     // If the segment reference frame feature is enabled....
1691     // then do nothing if the current ref frame is not allowed..
1692     if (vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
1693         vp9_get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame)
1694       continue;
1695
1696     mbmi->ref_frame[0] = ref_frame;
1697     x->skip = 0;
1698     set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
1699
1700     // Select prediction reference frames.
1701     for (plane = 0; plane < MAX_MB_PLANE; plane++)
1702       xd->plane[plane].pre[0] = yv12_mb[ref_frame][plane];
1703
1704     for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1705       for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1706         int_mv b_mv[MB_MODE_COUNT];
1707         int64_t b_best_rd = INT64_MAX;
1708         const int i = idy * 2 + idx;
1709         PREDICTION_MODE this_mode;
1710         RD_COST this_rdc;
1711         unsigned int var_y, sse_y;
1712
1713         struct macroblock_plane *p = &x->plane[0];
1714         struct macroblockd_plane *pd = &xd->plane[0];
1715
1716         const struct buf_2d orig_src = p->src;
1717         const struct buf_2d orig_dst = pd->dst;
1718         struct buf_2d orig_pre[2];
1719         memcpy(orig_pre, xd->plane[0].pre, sizeof(orig_pre));
1720
1721         // set buffer pointers for sub8x8 motion search.
1722         p->src.buf =
1723             &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1724         pd->dst.buf =
1725             &pd->dst.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->dst.stride)];
1726         pd->pre[0].buf =
1727             &pd->pre[0].buf[vp9_raster_block_offset(BLOCK_8X8,
1728                                                     i, pd->pre[0].stride)];
1729
1730         b_mv[ZEROMV].as_int = 0;
1731         b_mv[NEWMV].as_int = INVALID_MV;
1732         vp9_append_sub8x8_mvs_for_idx(cm, xd, tile_info, i, 0, mi_row, mi_col,
1733                                       &b_mv[NEARESTMV],
1734                                       &b_mv[NEARMV]);
1735
1736         for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
1737           int b_rate = 0;
1738           xd->mi[0]->bmi[i].as_mv[0].as_int = b_mv[this_mode].as_int;
1739
1740           if (this_mode == NEWMV) {
1741             const int step_param = cpi->sf.mv.fullpel_search_step_param;
1742             MV mvp_full;
1743             MV tmp_mv;
1744             int cost_list[5];
1745             const int tmp_col_min = x->mv_col_min;
1746             const int tmp_col_max = x->mv_col_max;
1747             const int tmp_row_min = x->mv_row_min;
1748             const int tmp_row_max = x->mv_row_max;
1749             int dummy_dist;
1750
1751             if (i == 0) {
1752               mvp_full.row = b_mv[NEARESTMV].as_mv.row >> 3;
1753               mvp_full.col = b_mv[NEARESTMV].as_mv.col >> 3;
1754             } else {
1755               mvp_full.row = xd->mi[0]->bmi[0].as_mv[0].as_mv.row >> 3;
1756               mvp_full.col = xd->mi[0]->bmi[0].as_mv[0].as_mv.col >> 3;
1757             }
1758
1759             vp9_set_mv_search_range(x, &mbmi->ref_mvs[0]->as_mv);
1760
1761             vp9_full_pixel_search(
1762                 cpi, x, bsize, &mvp_full, step_param, x->sadperbit4,
1763                 cond_cost_list(cpi, cost_list),
1764                 &mbmi->ref_mvs[ref_frame][0].as_mv, &tmp_mv,
1765                 INT_MAX, 0);
1766
1767             x->mv_col_min = tmp_col_min;
1768             x->mv_col_max = tmp_col_max;
1769             x->mv_row_min = tmp_row_min;
1770             x->mv_row_max = tmp_row_max;
1771
1772             // calculate the bit cost on motion vector
1773             mvp_full.row = tmp_mv.row * 8;
1774             mvp_full.col = tmp_mv.col * 8;
1775
1776             b_rate += vp9_mv_bit_cost(&mvp_full,
1777                                       &mbmi->ref_mvs[ref_frame][0].as_mv,
1778                                       x->nmvjointcost, x->mvcost,
1779                                       MV_COST_WEIGHT);
1780
1781             b_rate += cpi->inter_mode_cost[mbmi->mode_context[ref_frame]]
1782                                           [INTER_OFFSET(NEWMV)];
1783             if (RDCOST(x->rdmult, x->rddiv, b_rate, 0) > b_best_rd)
1784               continue;
1785
1786             cpi->find_fractional_mv_step(x, &tmp_mv,
1787                                          &mbmi->ref_mvs[ref_frame][0].as_mv,
1788                                          cpi->common.allow_high_precision_mv,
1789                                          x->errorperbit,
1790                                          &cpi->fn_ptr[bsize],
1791                                          cpi->sf.mv.subpel_force_stop,
1792                                          cpi->sf.mv.subpel_iters_per_step,
1793                                          cond_cost_list(cpi, cost_list),
1794                                          x->nmvjointcost, x->mvcost,
1795                                          &dummy_dist,
1796                                          &x->pred_sse[ref_frame], NULL, 0, 0);
1797
1798             xd->mi[0]->bmi[i].as_mv[0].as_mv = tmp_mv;
1799           } else {
1800             b_rate += cpi->inter_mode_cost[mbmi->mode_context[ref_frame]]
1801                                           [INTER_OFFSET(this_mode)];
1802           }
1803
1804 #if CONFIG_VP9_HIGHBITDEPTH
1805           if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1806             vp9_highbd_build_inter_predictor(pd->pre[0].buf, pd->pre[0].stride,
1807                                     pd->dst.buf, pd->dst.stride,
1808                                     &xd->mi[0]->bmi[i].as_mv[0].as_mv,
1809                                     &xd->block_refs[0]->sf,
1810                                     4 * num_4x4_blocks_wide,
1811                                     4 * num_4x4_blocks_high, 0,
1812                                     vp9_get_interp_kernel(mbmi->interp_filter),
1813                                     MV_PRECISION_Q3,
1814                                     mi_col * MI_SIZE + 4 * (i & 0x01),
1815                                     mi_row * MI_SIZE + 4 * (i >> 1), xd->bd);
1816           } else {
1817 #endif
1818             vp9_build_inter_predictor(pd->pre[0].buf, pd->pre[0].stride,
1819                                      pd->dst.buf, pd->dst.stride,
1820                                      &xd->mi[0]->bmi[i].as_mv[0].as_mv,
1821                                      &xd->block_refs[0]->sf,
1822                                      4 * num_4x4_blocks_wide,
1823                                      4 * num_4x4_blocks_high, 0,
1824                                      vp9_get_interp_kernel(mbmi->interp_filter),
1825                                      MV_PRECISION_Q3,
1826                                      mi_col * MI_SIZE + 4 * (i & 0x01),
1827                                      mi_row * MI_SIZE + 4 * (i >> 1));
1828
1829 #if CONFIG_VP9_HIGHBITDEPTH
1830           }
1831 #endif
1832
1833           model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc.rate, &this_rdc.dist,
1834                             &var_y, &sse_y);
1835
1836           this_rdc.rate += b_rate;
1837           this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
1838                                    this_rdc.rate, this_rdc.dist);
1839           if (this_rdc.rdcost < b_best_rd) {
1840             b_best_rd = this_rdc.rdcost;
1841             bsi[ref_frame][i].as_mode = this_mode;
1842             bsi[ref_frame][i].as_mv[0].as_mv = xd->mi[0]->bmi[i].as_mv[0].as_mv;
1843           }
1844         }  // mode search
1845
1846         // restore source and prediction buffer pointers.
1847         p->src = orig_src;
1848         pd->pre[0] = orig_pre[0];
1849         pd->dst = orig_dst;
1850         this_rd += b_best_rd;
1851
1852         xd->mi[0]->bmi[i] = bsi[ref_frame][i];
1853         if (num_4x4_blocks_wide > 1)
1854           xd->mi[0]->bmi[i + 1] = xd->mi[0]->bmi[i];
1855         if (num_4x4_blocks_high > 1)
1856           xd->mi[0]->bmi[i + 2] = xd->mi[0]->bmi[i];
1857       }
1858     }  // loop through sub8x8 blocks
1859
1860     if (this_rd < best_rd) {
1861       best_rd = this_rd;
1862       best_ref_frame = ref_frame;
1863     }
1864   }  // reference frames
1865
1866   mbmi->tx_size = TX_4X4;
1867   mbmi->ref_frame[0] = best_ref_frame;
1868   for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1869     for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1870       const int block = idy * 2 + idx;
1871       xd->mi[0]->bmi[block] = bsi[best_ref_frame][block];
1872       if (num_4x4_blocks_wide > 1)
1873         xd->mi[0]->bmi[block + 1] = bsi[best_ref_frame][block];
1874       if (num_4x4_blocks_high > 1)
1875         xd->mi[0]->bmi[block + 2] = bsi[best_ref_frame][block];
1876     }
1877   }
1878   mbmi->mode = xd->mi[0]->bmi[3].as_mode;
1879   ctx->mic = *(xd->mi[0]);
1880   ctx->skip_txfm[0] = 0;
1881   ctx->skip = 0;
1882   // Dummy assignment for speed -5. No effect in speed -6.
1883   rd_cost->rdcost = best_rd;
1884 }