xref: /aosp_15_r20/external/libvpx/vp9/encoder/vp9_pickmode.c (revision fb1b10ab9aebc7c7068eedab379b749d7e3900be)
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/vpx_codec.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_mem/vpx_mem.h"
22 #include "vpx_ports/compiler_attributes.h"
23 
24 #include "vp9/common/vp9_blockd.h"
25 #include "vp9/common/vp9_common.h"
26 #include "vp9/common/vp9_mvref_common.h"
27 #include "vp9/common/vp9_pred_common.h"
28 #include "vp9/common/vp9_reconinter.h"
29 #include "vp9/common/vp9_reconintra.h"
30 #include "vp9/common/vp9_scan.h"
31 
32 #include "vp9/encoder/vp9_cost.h"
33 #include "vp9/encoder/vp9_encoder.h"
34 #include "vp9/encoder/vp9_pickmode.h"
35 #include "vp9/encoder/vp9_ratectrl.h"
36 #include "vp9/encoder/vp9_rd.h"
37 
38 typedef struct {
39   uint8_t *data;
40   int stride;
41   int in_use;
42 } PRED_BUFFER;
43 
44 typedef struct {
45   PRED_BUFFER *best_pred;
46   PREDICTION_MODE best_mode;
47   TX_SIZE best_tx_size;
48   TX_SIZE best_intra_tx_size;
49   MV_REFERENCE_FRAME best_ref_frame;
50   MV_REFERENCE_FRAME best_second_ref_frame;
51   uint8_t best_mode_skip_txfm;
52   INTERP_FILTER best_pred_filter;
53 } BEST_PICKMODE;
54 
55 static const int pos_shift_16x16[4][4] = {
56   { 9, 10, 13, 14 }, { 11, 12, 15, 16 }, { 17, 18, 21, 22 }, { 19, 20, 23, 24 }
57 };
58 
mv_refs_rt(VP9_COMP * cpi,const VP9_COMMON * cm,const MACROBLOCK * x,const MACROBLOCKD * xd,const TileInfo * const tile,MODE_INFO * mi,MV_REFERENCE_FRAME ref_frame,int_mv * mv_ref_list,int_mv * base_mv,int mi_row,int mi_col,int use_base_mv)59 static int mv_refs_rt(VP9_COMP *cpi, const VP9_COMMON *cm, const MACROBLOCK *x,
60                       const MACROBLOCKD *xd, const TileInfo *const tile,
61                       MODE_INFO *mi, MV_REFERENCE_FRAME ref_frame,
62                       int_mv *mv_ref_list, int_mv *base_mv, int mi_row,
63                       int mi_col, int use_base_mv) {
64   const int *ref_sign_bias = cm->ref_frame_sign_bias;
65   int i, refmv_count = 0;
66 
67   const POSITION *const mv_ref_search = mv_ref_blocks[mi->sb_type];
68 
69   int different_ref_found = 0;
70   int context_counter = 0;
71   int const_motion = 0;
72 
73   // Blank the reference vector list
74   memset(mv_ref_list, 0, sizeof(*mv_ref_list) * MAX_MV_REF_CANDIDATES);
75 
76   // The nearest 2 blocks are treated differently
77   // if the size < 8x8 we get the mv from the bmi substructure,
78   // and we also need to keep a mode count.
79   for (i = 0; i < 2; ++i) {
80     const POSITION *const mv_ref = &mv_ref_search[i];
81     if (is_inside(tile, mi_col, mi_row, cm->mi_rows, mv_ref)) {
82       const MODE_INFO *const candidate_mi =
83           xd->mi[mv_ref->col + mv_ref->row * xd->mi_stride];
84       // Keep counts for entropy encoding.
85       context_counter += mode_2_counter[candidate_mi->mode];
86       different_ref_found = 1;
87 
88       if (candidate_mi->ref_frame[0] == ref_frame)
89         ADD_MV_REF_LIST(get_sub_block_mv(candidate_mi, 0, mv_ref->col, -1),
90                         refmv_count, mv_ref_list, Done);
91     }
92   }
93 
94   const_motion = 1;
95 
96   // Check the rest of the neighbors in much the same way
97   // as before except we don't need to keep track of sub blocks or
98   // mode counts.
99   for (; i < MVREF_NEIGHBOURS && !refmv_count; ++i) {
100     const POSITION *const mv_ref = &mv_ref_search[i];
101     if (is_inside(tile, mi_col, mi_row, cm->mi_rows, mv_ref)) {
102       const MODE_INFO *const candidate_mi =
103           xd->mi[mv_ref->col + mv_ref->row * xd->mi_stride];
104       different_ref_found = 1;
105 
106       if (candidate_mi->ref_frame[0] == ref_frame)
107         ADD_MV_REF_LIST(candidate_mi->mv[0], refmv_count, mv_ref_list, Done);
108     }
109   }
110 
111   // Since we couldn't find 2 mvs from the same reference frame
112   // go back through the neighbors and find motion vectors from
113   // different reference frames.
114   if (different_ref_found && !refmv_count) {
115     for (i = 0; i < MVREF_NEIGHBOURS; ++i) {
116       const POSITION *mv_ref = &mv_ref_search[i];
117       if (is_inside(tile, mi_col, mi_row, cm->mi_rows, mv_ref)) {
118         const MODE_INFO *const candidate_mi =
119             xd->mi[mv_ref->col + mv_ref->row * xd->mi_stride];
120 
121         // If the candidate is INTRA we don't want to consider its mv.
122         IF_DIFF_REF_FRAME_ADD_MV(candidate_mi, ref_frame, ref_sign_bias,
123                                  refmv_count, mv_ref_list, Done);
124       }
125     }
126   }
127   if (use_base_mv &&
128       !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
129       ref_frame == LAST_FRAME) {
130     // Get base layer mv.
131     MV_REF *candidate =
132         &cm->prev_frame
133              ->mvs[(mi_col >> 1) + (mi_row >> 1) * (cm->mi_cols >> 1)];
134     if (candidate->mv[0].as_int != INVALID_MV) {
135       base_mv->as_mv.row = (candidate->mv[0].as_mv.row * 2);
136       base_mv->as_mv.col = (candidate->mv[0].as_mv.col * 2);
137       clamp_mv_ref(&base_mv->as_mv, xd);
138     } else {
139       base_mv->as_int = INVALID_MV;
140     }
141   }
142 
143 Done:
144 
145   x->mbmi_ext->mode_context[ref_frame] = counter_to_context[context_counter];
146 
147   // Clamp vectors
148   for (i = 0; i < MAX_MV_REF_CANDIDATES; ++i)
149     clamp_mv_ref(&mv_ref_list[i].as_mv, xd);
150 
151   return const_motion;
152 }
153 
combined_motion_search(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int mi_row,int mi_col,int_mv * tmp_mv,int * rate_mv,int64_t best_rd_sofar,int use_base_mv)154 static int combined_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
155                                   BLOCK_SIZE bsize, int mi_row, int mi_col,
156                                   int_mv *tmp_mv, int *rate_mv,
157                                   int64_t best_rd_sofar, int use_base_mv) {
158   MACROBLOCKD *xd = &x->e_mbd;
159   MODE_INFO *mi = xd->mi[0];
160   struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0 } };
161   const int step_param = cpi->sf.mv.fullpel_search_step_param;
162   const int sadpb = x->sadperbit16;
163   MV mvp_full;
164   const int ref = mi->ref_frame[0];
165   const MV ref_mv = x->mbmi_ext->ref_mvs[ref][0].as_mv;
166   MV center_mv;
167   uint32_t dis;
168   int rate_mode;
169   const MvLimits tmp_mv_limits = x->mv_limits;
170   int rv = 0;
171   int cost_list[5];
172   int search_subpel = 1;
173   const YV12_BUFFER_CONFIG *scaled_ref_frame =
174       vp9_get_scaled_ref_frame(cpi, ref);
175   if (scaled_ref_frame) {
176     int i;
177     // Swap out the reference frame for a version that's been scaled to
178     // match the resolution of the current frame, allowing the existing
179     // motion search code to be used without additional modifications.
180     for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
181     vp9_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
182   }
183   vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
184 
185   // Limit motion vector for large lightning change.
186   if (cpi->oxcf.speed > 5 && x->lowvar_highsumdiff) {
187     x->mv_limits.col_min = VPXMAX(x->mv_limits.col_min, -10);
188     x->mv_limits.row_min = VPXMAX(x->mv_limits.row_min, -10);
189     x->mv_limits.col_max = VPXMIN(x->mv_limits.col_max, 10);
190     x->mv_limits.row_max = VPXMIN(x->mv_limits.row_max, 10);
191   }
192 
193   assert(x->mv_best_ref_index[ref] <= 2);
194   if (x->mv_best_ref_index[ref] < 2)
195     mvp_full = x->mbmi_ext->ref_mvs[ref][x->mv_best_ref_index[ref]].as_mv;
196   else
197     mvp_full = x->pred_mv[ref];
198 
199   mvp_full.col >>= 3;
200   mvp_full.row >>= 3;
201 
202   if (!use_base_mv)
203     center_mv = ref_mv;
204   else
205     center_mv = tmp_mv->as_mv;
206 
207   if (x->sb_use_mv_part) {
208     tmp_mv->as_mv.row = x->sb_mvrow_part >> 3;
209     tmp_mv->as_mv.col = x->sb_mvcol_part >> 3;
210   } else {
211     vp9_full_pixel_search(
212         cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method, sadpb,
213         cond_cost_list(cpi, cost_list), &center_mv, &tmp_mv->as_mv, INT_MAX, 0);
214   }
215 
216   x->mv_limits = tmp_mv_limits;
217 
218   // calculate the bit cost on motion vector
219   mvp_full.row = tmp_mv->as_mv.row * 8;
220   mvp_full.col = tmp_mv->as_mv.col * 8;
221 
222   *rate_mv = vp9_mv_bit_cost(&mvp_full, &ref_mv, x->nmvjointcost, x->mvcost,
223                              MV_COST_WEIGHT);
224 
225   rate_mode =
226       cpi->inter_mode_cost[x->mbmi_ext->mode_context[ref]][INTER_OFFSET(NEWMV)];
227   rv =
228       !(RDCOST(x->rdmult, x->rddiv, (*rate_mv + rate_mode), 0) > best_rd_sofar);
229 
230   // For SVC on non-reference frame, avoid subpel for (0, 0) motion.
231   if (cpi->use_svc && cpi->svc.non_reference_frame) {
232     if (mvp_full.row == 0 && mvp_full.col == 0) search_subpel = 0;
233   }
234 
235   if (rv && search_subpel) {
236     SUBPEL_FORCE_STOP subpel_force_stop = cpi->sf.mv.subpel_force_stop;
237     if (use_base_mv && cpi->sf.base_mv_aggressive) subpel_force_stop = HALF_PEL;
238     if (cpi->sf.mv.enable_adaptive_subpel_force_stop) {
239       const int mv_thresh = cpi->sf.mv.adapt_subpel_force_stop.mv_thresh;
240       if (abs(tmp_mv->as_mv.row) >= mv_thresh ||
241           abs(tmp_mv->as_mv.col) >= mv_thresh)
242         subpel_force_stop = cpi->sf.mv.adapt_subpel_force_stop.force_stop_above;
243       else
244         subpel_force_stop = cpi->sf.mv.adapt_subpel_force_stop.force_stop_below;
245     }
246     cpi->find_fractional_mv_step(
247         x, &tmp_mv->as_mv, &ref_mv, cpi->common.allow_high_precision_mv,
248         x->errorperbit, &cpi->fn_ptr[bsize], subpel_force_stop,
249         cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list),
250         x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref], NULL, 0, 0,
251         cpi->sf.use_accurate_subpel_search);
252     *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->nmvjointcost,
253                                x->mvcost, MV_COST_WEIGHT);
254   }
255 
256   if (scaled_ref_frame) {
257     int i;
258     for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
259   }
260   return rv;
261 }
262 
block_variance(const uint8_t * src,int src_stride,const uint8_t * ref,int ref_stride,int w,int h,unsigned int * sse,int * sum,int block_size,int use_highbitdepth,vpx_bit_depth_t bd,uint32_t * sse8x8,int * sum8x8,uint32_t * var8x8)263 static void block_variance(const uint8_t *src, int src_stride,
264                            const uint8_t *ref, int ref_stride, int w, int h,
265                            unsigned int *sse, int *sum, int block_size,
266 #if CONFIG_VP9_HIGHBITDEPTH
267                            int use_highbitdepth, vpx_bit_depth_t bd,
268 #endif
269                            uint32_t *sse8x8, int *sum8x8, uint32_t *var8x8) {
270   int i, j, k = 0;
271   uint32_t k_sqr = 0;
272 
273   *sse = 0;
274   *sum = 0;
275 
276   for (i = 0; i < h; i += block_size) {
277     for (j = 0; j < w; j += block_size) {
278 #if CONFIG_VP9_HIGHBITDEPTH
279       if (use_highbitdepth) {
280         switch (bd) {
281           case VPX_BITS_8:
282             vpx_highbd_8_get8x8var(src + src_stride * i + j, src_stride,
283                                    ref + ref_stride * i + j, ref_stride,
284                                    &sse8x8[k], &sum8x8[k]);
285             break;
286           case VPX_BITS_10:
287             vpx_highbd_10_get8x8var(src + src_stride * i + j, src_stride,
288                                     ref + ref_stride * i + j, ref_stride,
289                                     &sse8x8[k], &sum8x8[k]);
290             break;
291           case VPX_BITS_12:
292             vpx_highbd_12_get8x8var(src + src_stride * i + j, src_stride,
293                                     ref + ref_stride * i + j, ref_stride,
294                                     &sse8x8[k], &sum8x8[k]);
295             break;
296         }
297       } else {
298         vpx_get8x8var(src + src_stride * i + j, src_stride,
299                       ref + ref_stride * i + j, ref_stride, &sse8x8[k],
300                       &sum8x8[k]);
301       }
302 #else
303       vpx_get8x8var(src + src_stride * i + j, src_stride,
304                     ref + ref_stride * i + j, ref_stride, &sse8x8[k],
305                     &sum8x8[k]);
306 #endif
307       *sse += sse8x8[k];
308       *sum += sum8x8[k];
309       k_sqr = (uint32_t)(((int64_t)sum8x8[k] * sum8x8[k]) >> 6);
310       var8x8[k] = sse8x8[k] > k_sqr ? sse8x8[k] - k_sqr : k_sqr - sse8x8[k];
311       k++;
312     }
313   }
314 }
315 
calculate_variance(int bw,int bh,TX_SIZE tx_size,unsigned int * sse_i,int * sum_i,unsigned int * var_o,unsigned int * sse_o,int * sum_o)316 static void calculate_variance(int bw, int bh, TX_SIZE tx_size,
317                                unsigned int *sse_i, int *sum_i,
318                                unsigned int *var_o, unsigned int *sse_o,
319                                int *sum_o) {
320   const BLOCK_SIZE unit_size = txsize_to_bsize[tx_size];
321   const int nw = 1 << (bw - b_width_log2_lookup[unit_size]);
322   const int nh = 1 << (bh - b_height_log2_lookup[unit_size]);
323   int i, j, k = 0;
324   uint32_t k_sqr = 0;
325 
326   for (i = 0; i < nh; i += 2) {
327     for (j = 0; j < nw; j += 2) {
328       sse_o[k] = sse_i[i * nw + j] + sse_i[i * nw + j + 1] +
329                  sse_i[(i + 1) * nw + j] + sse_i[(i + 1) * nw + j + 1];
330       sum_o[k] = sum_i[i * nw + j] + sum_i[i * nw + j + 1] +
331                  sum_i[(i + 1) * nw + j] + sum_i[(i + 1) * nw + j + 1];
332       k_sqr = (uint32_t)(((int64_t)sum_o[k] * sum_o[k]) >>
333                          (b_width_log2_lookup[unit_size] +
334                           b_height_log2_lookup[unit_size] + 6));
335       var_o[k] = sse_o[k] > k_sqr ? sse_o[k] - k_sqr : k_sqr - sse_o[k];
336       k++;
337     }
338   }
339 }
340 
341 // Adjust the ac_thr according to speed, width, height and normalized sum
ac_thr_factor(const int speed,const int width,const int height,const int norm_sum)342 static int ac_thr_factor(const int speed, const int width, const int height,
343                          const int norm_sum) {
344   if (speed >= 8 && norm_sum < 5) {
345     if (width <= 640 && height <= 480)
346       return 4;
347     else
348       return 2;
349   }
350   return 1;
351 }
352 
calculate_tx_size(VP9_COMP * const cpi,BLOCK_SIZE bsize,MACROBLOCKD * const xd,unsigned int var,unsigned int sse,int64_t ac_thr,unsigned int source_variance,int is_intra)353 static TX_SIZE calculate_tx_size(VP9_COMP *const cpi, BLOCK_SIZE bsize,
354                                  MACROBLOCKD *const xd, unsigned int var,
355                                  unsigned int sse, int64_t ac_thr,
356                                  unsigned int source_variance, int is_intra) {
357   // TODO(marpan): Tune selection for intra-modes, screen content, etc.
358   TX_SIZE tx_size;
359   unsigned int var_thresh = is_intra ? (unsigned int)ac_thr : 1;
360   int limit_tx = 1;
361   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
362       (source_variance == 0 || var < var_thresh))
363     limit_tx = 0;
364   if (cpi->common.tx_mode == TX_MODE_SELECT) {
365     if (sse > (var << 2))
366       tx_size = VPXMIN(max_txsize_lookup[bsize],
367                        tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
368     else
369       tx_size = TX_8X8;
370     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && limit_tx &&
371         cyclic_refresh_segment_id_boosted(xd->mi[0]->segment_id))
372       tx_size = TX_8X8;
373     else if (tx_size > TX_16X16 && limit_tx)
374       tx_size = TX_16X16;
375     // For screen-content force 4X4 tx_size over 8X8, for large variance.
376     if (cpi->oxcf.content == VP9E_CONTENT_SCREEN && tx_size == TX_8X8 &&
377         bsize <= BLOCK_16X16 && ((var >> 5) > (unsigned int)ac_thr))
378       tx_size = TX_4X4;
379   } else {
380     tx_size = VPXMIN(max_txsize_lookup[bsize],
381                      tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
382   }
383   return tx_size;
384 }
385 
compute_intra_yprediction(PREDICTION_MODE mode,BLOCK_SIZE bsize,MACROBLOCK * x,MACROBLOCKD * xd)386 static void compute_intra_yprediction(PREDICTION_MODE mode, BLOCK_SIZE bsize,
387                                       MACROBLOCK *x, MACROBLOCKD *xd) {
388   struct macroblockd_plane *const pd = &xd->plane[0];
389   struct macroblock_plane *const p = &x->plane[0];
390   uint8_t *const src_buf_base = p->src.buf;
391   uint8_t *const dst_buf_base = pd->dst.buf;
392   const int src_stride = p->src.stride;
393   const int dst_stride = pd->dst.stride;
394   // block and transform sizes, in number of 4x4 blocks log 2 ("*_b")
395   // 4x4=0, 8x8=2, 16x16=4, 32x32=6, 64x64=8
396   const TX_SIZE tx_size = max_txsize_lookup[bsize];
397   const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
398   const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
399   int row, col;
400   // If mb_to_right_edge is < 0 we are in a situation in which
401   // the current block size extends into the UMV and we won't
402   // visit the sub blocks that are wholly within the UMV.
403   const int max_blocks_wide =
404       num_4x4_w + (xd->mb_to_right_edge >= 0
405                        ? 0
406                        : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
407   const int max_blocks_high =
408       num_4x4_h + (xd->mb_to_bottom_edge >= 0
409                        ? 0
410                        : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
411 
412   // Keep track of the row and column of the blocks we use so that we know
413   // if we are in the unrestricted motion border.
414   for (row = 0; row < max_blocks_high; row += (1 << tx_size)) {
415     // Skip visiting the sub blocks that are wholly within the UMV.
416     for (col = 0; col < max_blocks_wide; col += (1 << tx_size)) {
417       p->src.buf = &src_buf_base[4 * (row * (int64_t)src_stride + col)];
418       pd->dst.buf = &dst_buf_base[4 * (row * (int64_t)dst_stride + col)];
419       vp9_predict_intra_block(xd, b_width_log2_lookup[bsize], tx_size, mode,
420                               x->skip_encode ? p->src.buf : pd->dst.buf,
421                               x->skip_encode ? src_stride : dst_stride,
422                               pd->dst.buf, dst_stride, col, row, 0);
423     }
424   }
425   p->src.buf = src_buf_base;
426   pd->dst.buf = dst_buf_base;
427 }
428 
model_rd_for_sb_y_large(VP9_COMP * cpi,BLOCK_SIZE bsize,MACROBLOCK * x,MACROBLOCKD * xd,int * out_rate_sum,int64_t * out_dist_sum,unsigned int * var_y,unsigned int * sse_y,int mi_row,int mi_col,int * early_term,int * flag_preduv_computed)429 static void model_rd_for_sb_y_large(VP9_COMP *cpi, BLOCK_SIZE bsize,
430                                     MACROBLOCK *x, MACROBLOCKD *xd,
431                                     int *out_rate_sum, int64_t *out_dist_sum,
432                                     unsigned int *var_y, unsigned int *sse_y,
433                                     int mi_row, int mi_col, int *early_term,
434                                     int *flag_preduv_computed) {
435   // Note our transform coeffs are 8 times an orthogonal transform.
436   // Hence quantizer step is also 8 times. To get effective quantizer
437   // we need to divide by 8 before sending to modeling function.
438   unsigned int sse;
439   int rate;
440   int64_t dist;
441   struct macroblock_plane *const p = &x->plane[0];
442   struct macroblockd_plane *const pd = &xd->plane[0];
443   const uint32_t dc_quant = pd->dequant[0];
444   const uint32_t ac_quant = pd->dequant[1];
445   int64_t dc_thr = dc_quant * dc_quant >> 6;
446   int64_t ac_thr = ac_quant * ac_quant >> 6;
447   unsigned int var;
448   int sum;
449   int skip_dc = 0;
450 
451   const int bw = b_width_log2_lookup[bsize];
452   const int bh = b_height_log2_lookup[bsize];
453   const int num8x8 = 1 << (bw + bh - 2);
454   unsigned int sse8x8[64] = { 0 };
455   int sum8x8[64] = { 0 };
456   unsigned int var8x8[64] = { 0 };
457   TX_SIZE tx_size;
458   int i, k;
459   uint32_t sum_sqr;
460 #if CONFIG_VP9_HIGHBITDEPTH
461   const vpx_bit_depth_t bd = cpi->common.bit_depth;
462 #endif
463   // Calculate variance for whole partition, and also save 8x8 blocks' variance
464   // to be used in following transform skipping test.
465   block_variance(p->src.buf, p->src.stride, pd->dst.buf, pd->dst.stride,
466                  4 << bw, 4 << bh, &sse, &sum, 8,
467 #if CONFIG_VP9_HIGHBITDEPTH
468                  cpi->common.use_highbitdepth, bd,
469 #endif
470                  sse8x8, sum8x8, var8x8);
471   sum_sqr = (uint32_t)((int64_t)sum * sum) >> (bw + bh + 4);
472   var = sse > sum_sqr ? sse - sum_sqr : sum_sqr - sse;
473 
474   *var_y = var;
475   *sse_y = sse;
476 
477 #if CONFIG_VP9_TEMPORAL_DENOISING
478   if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
479       cpi->oxcf.speed > 5)
480     ac_thr = vp9_scale_acskip_thresh(ac_thr, cpi->denoiser.denoising_level,
481                                      (abs(sum) >> (bw + bh)),
482                                      cpi->svc.temporal_layer_id);
483   else
484     ac_thr *= ac_thr_factor(cpi->oxcf.speed, cpi->common.width,
485                             cpi->common.height, abs(sum) >> (bw + bh));
486 #else
487   ac_thr *= ac_thr_factor(cpi->oxcf.speed, cpi->common.width,
488                           cpi->common.height, abs(sum) >> (bw + bh));
489 #endif
490 
491   tx_size = calculate_tx_size(cpi, bsize, xd, var, sse, ac_thr,
492                               x->source_variance, 0);
493   // The code below for setting skip flag assumes tranform size of at least 8x8,
494   // so force this lower limit on transform.
495   if (tx_size < TX_8X8) tx_size = TX_8X8;
496   xd->mi[0]->tx_size = tx_size;
497 
498   if (cpi->oxcf.content == VP9E_CONTENT_SCREEN && x->zero_temp_sad_source &&
499       x->source_variance == 0)
500     dc_thr = dc_thr << 1;
501 
502   // Evaluate if the partition block is a skippable block in Y plane.
503   {
504     unsigned int sse16x16[16] = { 0 };
505     int sum16x16[16] = { 0 };
506     unsigned int var16x16[16] = { 0 };
507     const int num16x16 = num8x8 >> 2;
508 
509     unsigned int sse32x32[4] = { 0 };
510     int sum32x32[4] = { 0 };
511     unsigned int var32x32[4] = { 0 };
512     const int num32x32 = num8x8 >> 4;
513 
514     int ac_test = 1;
515     int dc_test = 1;
516     const int num = (tx_size == TX_8X8)
517                         ? num8x8
518                         : ((tx_size == TX_16X16) ? num16x16 : num32x32);
519     const unsigned int *sse_tx =
520         (tx_size == TX_8X8) ? sse8x8
521                             : ((tx_size == TX_16X16) ? sse16x16 : sse32x32);
522     const unsigned int *var_tx =
523         (tx_size == TX_8X8) ? var8x8
524                             : ((tx_size == TX_16X16) ? var16x16 : var32x32);
525 
526     // Calculate variance if tx_size > TX_8X8
527     if (tx_size >= TX_16X16)
528       calculate_variance(bw, bh, TX_8X8, sse8x8, sum8x8, var16x16, sse16x16,
529                          sum16x16);
530     if (tx_size == TX_32X32)
531       calculate_variance(bw, bh, TX_16X16, sse16x16, sum16x16, var32x32,
532                          sse32x32, sum32x32);
533 
534     // Skipping test
535     x->skip_txfm[0] = SKIP_TXFM_NONE;
536     for (k = 0; k < num; k++)
537       // Check if all ac coefficients can be quantized to zero.
538       if (!(var_tx[k] < ac_thr || var == 0)) {
539         ac_test = 0;
540         break;
541       }
542 
543     for (k = 0; k < num; k++)
544       // Check if dc coefficient can be quantized to zero.
545       if (!(sse_tx[k] - var_tx[k] < dc_thr || sse == var)) {
546         dc_test = 0;
547         break;
548       }
549 
550     if (ac_test) {
551       x->skip_txfm[0] = SKIP_TXFM_AC_ONLY;
552 
553       if (dc_test) x->skip_txfm[0] = SKIP_TXFM_AC_DC;
554     } else if (dc_test) {
555       skip_dc = 1;
556     }
557   }
558 
559   if (x->skip_txfm[0] == SKIP_TXFM_AC_DC) {
560     int skip_uv[2] = { 0 };
561     unsigned int var_uv[2];
562     unsigned int sse_uv[2];
563 
564     *out_rate_sum = 0;
565     *out_dist_sum = sse << 4;
566 
567     // Transform skipping test in UV planes.
568     for (i = 1; i <= 2; i++) {
569       struct macroblock_plane *const p_uv = &x->plane[i];
570       struct macroblockd_plane *const pd_uv = &xd->plane[i];
571       const TX_SIZE uv_tx_size = get_uv_tx_size(xd->mi[0], pd_uv);
572       const BLOCK_SIZE unit_size = txsize_to_bsize[uv_tx_size];
573       const BLOCK_SIZE uv_bsize = get_plane_block_size(bsize, pd_uv);
574       const int uv_bw = b_width_log2_lookup[uv_bsize];
575       const int uv_bh = b_height_log2_lookup[uv_bsize];
576       const int sf = (uv_bw - b_width_log2_lookup[unit_size]) +
577                      (uv_bh - b_height_log2_lookup[unit_size]);
578       const uint32_t uv_dc_thr =
579           pd_uv->dequant[0] * pd_uv->dequant[0] >> (6 - sf);
580       const uint32_t uv_ac_thr =
581           pd_uv->dequant[1] * pd_uv->dequant[1] >> (6 - sf);
582       int j = i - 1;
583 
584       vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, i);
585       flag_preduv_computed[i - 1] = 1;
586       var_uv[j] = cpi->fn_ptr[uv_bsize].vf(p_uv->src.buf, p_uv->src.stride,
587                                            pd_uv->dst.buf, pd_uv->dst.stride,
588                                            &sse_uv[j]);
589 
590       if ((var_uv[j] < uv_ac_thr || var_uv[j] == 0) &&
591           (sse_uv[j] - var_uv[j] < uv_dc_thr || sse_uv[j] == var_uv[j]))
592         skip_uv[j] = 1;
593       else
594         break;
595     }
596 
597     // If the transform in YUV planes are skippable, the mode search checks
598     // fewer inter modes and doesn't check intra modes.
599     if (skip_uv[0] & skip_uv[1]) {
600       *early_term = 1;
601     }
602     return;
603   }
604 
605   if (!skip_dc) {
606 #if CONFIG_VP9_HIGHBITDEPTH
607     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
608                                  dc_quant >> (xd->bd - 5), &rate, &dist);
609 #else
610     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
611                                  dc_quant >> 3, &rate, &dist);
612 #endif  // CONFIG_VP9_HIGHBITDEPTH
613   }
614 
615   if (!skip_dc) {
616     *out_rate_sum = rate >> 1;
617     *out_dist_sum = dist << 3;
618   } else {
619     *out_rate_sum = 0;
620     *out_dist_sum = (sse - var) << 4;
621   }
622 
623 #if CONFIG_VP9_HIGHBITDEPTH
624   vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
625                                ac_quant >> (xd->bd - 5), &rate, &dist);
626 #else
627   vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize], ac_quant >> 3,
628                                &rate, &dist);
629 #endif  // CONFIG_VP9_HIGHBITDEPTH
630 
631   *out_rate_sum += rate;
632   *out_dist_sum += dist << 4;
633 }
634 
model_rd_for_sb_y(VP9_COMP * cpi,BLOCK_SIZE bsize,MACROBLOCK * x,MACROBLOCKD * xd,int * out_rate_sum,int64_t * out_dist_sum,unsigned int * var_y,unsigned int * sse_y,int is_intra)635 static void model_rd_for_sb_y(VP9_COMP *cpi, BLOCK_SIZE bsize, MACROBLOCK *x,
636                               MACROBLOCKD *xd, int *out_rate_sum,
637                               int64_t *out_dist_sum, unsigned int *var_y,
638                               unsigned int *sse_y, int is_intra) {
639   // Note our transform coeffs are 8 times an orthogonal transform.
640   // Hence quantizer step is also 8 times. To get effective quantizer
641   // we need to divide by 8 before sending to modeling function.
642   unsigned int sse;
643   int rate;
644   int64_t dist;
645   struct macroblock_plane *const p = &x->plane[0];
646   struct macroblockd_plane *const pd = &xd->plane[0];
647   const int64_t dc_thr = p->quant_thred[0] >> 6;
648   const int64_t ac_thr = p->quant_thred[1] >> 6;
649   const uint32_t dc_quant = pd->dequant[0];
650   const uint32_t ac_quant = pd->dequant[1];
651   unsigned int var = cpi->fn_ptr[bsize].vf(p->src.buf, p->src.stride,
652                                            pd->dst.buf, pd->dst.stride, &sse);
653   int skip_dc = 0;
654 
655   *var_y = var;
656   *sse_y = sse;
657 
658   xd->mi[0]->tx_size = calculate_tx_size(cpi, bsize, xd, var, sse, ac_thr,
659                                          x->source_variance, is_intra);
660 
661   // Evaluate if the partition block is a skippable block in Y plane.
662   {
663     const BLOCK_SIZE unit_size = txsize_to_bsize[xd->mi[0]->tx_size];
664     const unsigned int num_blk_log2 =
665         (b_width_log2_lookup[bsize] - b_width_log2_lookup[unit_size]) +
666         (b_height_log2_lookup[bsize] - b_height_log2_lookup[unit_size]);
667     const unsigned int sse_tx = sse >> num_blk_log2;
668     const unsigned int var_tx = var >> num_blk_log2;
669 
670     x->skip_txfm[0] = SKIP_TXFM_NONE;
671     // Check if all ac coefficients can be quantized to zero.
672     if (var_tx < ac_thr || var == 0) {
673       x->skip_txfm[0] = SKIP_TXFM_AC_ONLY;
674       // Check if dc coefficient can be quantized to zero.
675       if (sse_tx - var_tx < dc_thr || sse == var)
676         x->skip_txfm[0] = SKIP_TXFM_AC_DC;
677     } else {
678       if (sse_tx - var_tx < dc_thr || sse == var) skip_dc = 1;
679     }
680   }
681 
682   if (x->skip_txfm[0] == SKIP_TXFM_AC_DC) {
683     *out_rate_sum = 0;
684     *out_dist_sum = sse << 4;
685     return;
686   }
687 
688   if (!skip_dc) {
689 #if CONFIG_VP9_HIGHBITDEPTH
690     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
691                                  dc_quant >> (xd->bd - 5), &rate, &dist);
692 #else
693     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bsize],
694                                  dc_quant >> 3, &rate, &dist);
695 #endif  // CONFIG_VP9_HIGHBITDEPTH
696   }
697 
698   if (!skip_dc) {
699     *out_rate_sum = rate >> 1;
700     *out_dist_sum = dist << 3;
701   } else {
702     *out_rate_sum = 0;
703     *out_dist_sum = (sse - var) << 4;
704   }
705 
706 #if CONFIG_VP9_HIGHBITDEPTH
707   vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize],
708                                ac_quant >> (xd->bd - 5), &rate, &dist);
709 #else
710   vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bsize], ac_quant >> 3,
711                                &rate, &dist);
712 #endif  // CONFIG_VP9_HIGHBITDEPTH
713 
714   *out_rate_sum += rate;
715   *out_dist_sum += dist << 4;
716 }
717 
block_yrd(VP9_COMP * cpi,MACROBLOCK * x,RD_COST * this_rdc,int * skippable,int64_t * sse,BLOCK_SIZE bsize,TX_SIZE tx_size,int rd_computed,int is_intra)718 static void block_yrd(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *this_rdc,
719                       int *skippable, int64_t *sse, BLOCK_SIZE bsize,
720                       TX_SIZE tx_size, int rd_computed, int is_intra) {
721   MACROBLOCKD *xd = &x->e_mbd;
722   const struct macroblockd_plane *pd = &xd->plane[0];
723   struct macroblock_plane *const p = &x->plane[0];
724   const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
725   const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
726   const int step = 1 << (tx_size << 1);
727   const int block_step = (1 << tx_size);
728   int block = 0, r, c;
729   const int max_blocks_wide =
730       num_4x4_w + (xd->mb_to_right_edge >= 0 ? 0 : xd->mb_to_right_edge >> 5);
731   const int max_blocks_high =
732       num_4x4_h + (xd->mb_to_bottom_edge >= 0 ? 0 : xd->mb_to_bottom_edge >> 5);
733   int eob_cost = 0;
734   const int bw = 4 * num_4x4_w;
735   const int bh = 4 * num_4x4_h;
736 
737   if (cpi->sf.use_simple_block_yrd && cpi->common.frame_type != KEY_FRAME &&
738       (bsize < BLOCK_32X32 ||
739        (cpi->use_svc &&
740         (bsize < BLOCK_32X32 || cpi->svc.temporal_layer_id > 0)))) {
741     unsigned int var_y, sse_y;
742     (void)tx_size;
743     if (!rd_computed)
744       model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc->rate, &this_rdc->dist,
745                         &var_y, &sse_y, is_intra);
746     *sse = INT_MAX;
747     *skippable = 0;
748     return;
749   }
750 
751   (void)cpi;
752 
753   // The max tx_size passed in is TX_16X16.
754   assert(tx_size != TX_32X32);
755 #if CONFIG_VP9_HIGHBITDEPTH
756   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
757     vpx_highbd_subtract_block(bh, bw, p->src_diff, bw, p->src.buf,
758                               p->src.stride, pd->dst.buf, pd->dst.stride,
759                               x->e_mbd.bd);
760   } else {
761     vpx_subtract_block(bh, bw, p->src_diff, bw, p->src.buf, p->src.stride,
762                        pd->dst.buf, pd->dst.stride);
763   }
764 #else
765   vpx_subtract_block(bh, bw, p->src_diff, bw, p->src.buf, p->src.stride,
766                      pd->dst.buf, pd->dst.stride);
767 #endif
768   *skippable = 1;
769   // Keep track of the row and column of the blocks we use so that we know
770   // if we are in the unrestricted motion border.
771   for (r = 0; r < max_blocks_high; r += block_step) {
772     for (c = 0; c < num_4x4_w; c += block_step) {
773       if (c < max_blocks_wide) {
774         const ScanOrder *const scan_order = &vp9_default_scan_orders[tx_size];
775         tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
776         tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
777         tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
778         uint16_t *const eob = &p->eobs[block];
779         const int diff_stride = bw;
780         const int16_t *src_diff;
781         src_diff = &p->src_diff[(r * diff_stride + c) << 2];
782 
783         // skip block condition should be handled before this is called.
784         assert(!x->skip_block);
785 
786         switch (tx_size) {
787           case TX_16X16:
788             vpx_hadamard_16x16(src_diff, diff_stride, coeff);
789             vp9_quantize_fp(coeff, 256, p, qcoeff, dqcoeff, pd->dequant, eob,
790                             scan_order);
791             break;
792           case TX_8X8:
793             vpx_hadamard_8x8(src_diff, diff_stride, coeff);
794             vp9_quantize_fp(coeff, 64, p, qcoeff, dqcoeff, pd->dequant, eob,
795                             scan_order);
796             break;
797           default:
798             assert(tx_size == TX_4X4);
799             x->fwd_txfm4x4(src_diff, coeff, diff_stride);
800             vp9_quantize_fp(coeff, 16, p, qcoeff, dqcoeff, pd->dequant, eob,
801                             scan_order);
802             break;
803         }
804         *skippable &= (*eob == 0);
805         eob_cost += 1;
806       }
807       block += step;
808     }
809   }
810 
811   this_rdc->rate = 0;
812   if (*sse < INT64_MAX) {
813     *sse = (*sse << 6) >> 2;
814     if (*skippable) {
815       this_rdc->dist = *sse;
816       return;
817     }
818   }
819 
820   block = 0;
821   this_rdc->dist = 0;
822   for (r = 0; r < max_blocks_high; r += block_step) {
823     for (c = 0; c < num_4x4_w; c += block_step) {
824       if (c < max_blocks_wide) {
825         tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
826         tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
827         tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
828         uint16_t *const eob = &p->eobs[block];
829 
830         if (*eob == 1)
831           this_rdc->rate += (int)abs(qcoeff[0]);
832         else if (*eob > 1)
833           this_rdc->rate += vpx_satd(qcoeff, step << 4);
834 
835         this_rdc->dist += vp9_block_error_fp(coeff, dqcoeff, step << 4) >> 2;
836       }
837       block += step;
838     }
839   }
840 
841   // If skippable is set, rate gets clobbered later.
842   this_rdc->rate <<= (2 + VP9_PROB_COST_SHIFT);
843   this_rdc->rate += (eob_cost << VP9_PROB_COST_SHIFT);
844 }
845 
model_rd_for_sb_uv(VP9_COMP * cpi,BLOCK_SIZE plane_bsize,MACROBLOCK * x,MACROBLOCKD * xd,RD_COST * this_rdc,unsigned int * var_y,unsigned int * sse_y,int start_plane,int stop_plane)846 static void model_rd_for_sb_uv(VP9_COMP *cpi, BLOCK_SIZE plane_bsize,
847                                MACROBLOCK *x, MACROBLOCKD *xd,
848                                RD_COST *this_rdc, unsigned int *var_y,
849                                unsigned int *sse_y, int start_plane,
850                                int stop_plane) {
851   // Note our transform coeffs are 8 times an orthogonal transform.
852   // Hence quantizer step is also 8 times. To get effective quantizer
853   // we need to divide by 8 before sending to modeling function.
854   unsigned int sse;
855   int rate;
856   int64_t dist;
857   int i;
858 #if CONFIG_VP9_HIGHBITDEPTH
859   uint64_t tot_var = *var_y;
860   uint64_t tot_sse = *sse_y;
861 #else
862   uint32_t tot_var = *var_y;
863   uint32_t tot_sse = *sse_y;
864 #endif
865 
866   this_rdc->rate = 0;
867   this_rdc->dist = 0;
868 
869   for (i = start_plane; i <= stop_plane; ++i) {
870     struct macroblock_plane *const p = &x->plane[i];
871     struct macroblockd_plane *const pd = &xd->plane[i];
872     const uint32_t dc_quant = pd->dequant[0];
873     const uint32_t ac_quant = pd->dequant[1];
874     const BLOCK_SIZE bs = plane_bsize;
875     unsigned int var;
876     if (!x->color_sensitivity[i - 1]) continue;
877 
878     var = cpi->fn_ptr[bs].vf(p->src.buf, p->src.stride, pd->dst.buf,
879                              pd->dst.stride, &sse);
880     assert(sse >= var);
881     tot_var += var;
882     tot_sse += sse;
883 
884 #if CONFIG_VP9_HIGHBITDEPTH
885     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bs],
886                                  dc_quant >> (xd->bd - 5), &rate, &dist);
887 #else
888     vp9_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bs],
889                                  dc_quant >> 3, &rate, &dist);
890 #endif  // CONFIG_VP9_HIGHBITDEPTH
891 
892     this_rdc->rate += rate >> 1;
893     this_rdc->dist += dist << 3;
894 
895 #if CONFIG_VP9_HIGHBITDEPTH
896     vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bs],
897                                  ac_quant >> (xd->bd - 5), &rate, &dist);
898 #else
899     vp9_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bs], ac_quant >> 3,
900                                  &rate, &dist);
901 #endif  // CONFIG_VP9_HIGHBITDEPTH
902 
903     this_rdc->rate += rate;
904     this_rdc->dist += dist << 4;
905   }
906 
907 #if CONFIG_VP9_HIGHBITDEPTH
908   *var_y = tot_var > UINT32_MAX ? UINT32_MAX : (uint32_t)tot_var;
909   *sse_y = tot_sse > UINT32_MAX ? UINT32_MAX : (uint32_t)tot_sse;
910 #else
911   *var_y = tot_var;
912   *sse_y = tot_sse;
913 #endif
914 }
915 
get_pred_buffer(PRED_BUFFER * p,int len)916 static int get_pred_buffer(PRED_BUFFER *p, int len) {
917   int i;
918 
919   for (i = 0; i < len; i++) {
920     if (!p[i].in_use) {
921       p[i].in_use = 1;
922       return i;
923     }
924   }
925   return -1;
926 }
927 
free_pred_buffer(PRED_BUFFER * p)928 static void free_pred_buffer(PRED_BUFFER *p) {
929   if (p != NULL) p->in_use = 0;
930 }
931 
encode_breakout_test(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int mi_row,int mi_col,MV_REFERENCE_FRAME ref_frame,PREDICTION_MODE this_mode,unsigned int var_y,unsigned int sse_y,struct buf_2d yv12_mb[][MAX_MB_PLANE],int * rate,int64_t * dist,int * flag_preduv_computed)932 static void encode_breakout_test(
933     VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int mi_row, int mi_col,
934     MV_REFERENCE_FRAME ref_frame, PREDICTION_MODE this_mode, unsigned int var_y,
935     unsigned int sse_y, struct buf_2d yv12_mb[][MAX_MB_PLANE], int *rate,
936     int64_t *dist, int *flag_preduv_computed) {
937   MACROBLOCKD *xd = &x->e_mbd;
938   MODE_INFO *const mi = xd->mi[0];
939   const BLOCK_SIZE uv_size = get_plane_block_size(bsize, &xd->plane[1]);
940   unsigned int var = var_y, sse = sse_y;
941   // Skipping threshold for ac.
942   unsigned int thresh_ac;
943   // Skipping threshold for dc.
944   unsigned int thresh_dc;
945   int motion_low = 1;
946 
947   if (cpi->use_svc && ref_frame == GOLDEN_FRAME) return;
948   if (mi->mv[0].as_mv.row > 64 || mi->mv[0].as_mv.row < -64 ||
949       mi->mv[0].as_mv.col > 64 || mi->mv[0].as_mv.col < -64)
950     motion_low = 0;
951   if (x->encode_breakout > 0 && motion_low == 1) {
952     // Set a maximum for threshold to avoid big PSNR loss in low bit rate
953     // case. Use extreme low threshold for static frames to limit
954     // skipping.
955     const unsigned int max_thresh = 36000;
956     // The encode_breakout input
957     const unsigned int min_thresh =
958         VPXMIN(((unsigned int)x->encode_breakout << 4), max_thresh);
959 #if CONFIG_VP9_HIGHBITDEPTH
960     const int shift = (xd->bd << 1) - 16;
961 #endif
962 
963     // Calculate threshold according to dequant value.
964     thresh_ac = (xd->plane[0].dequant[1] * xd->plane[0].dequant[1]) >> 3;
965 #if CONFIG_VP9_HIGHBITDEPTH
966     if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && shift > 0) {
967       thresh_ac = ROUND_POWER_OF_TWO(thresh_ac, shift);
968     }
969 #endif  // CONFIG_VP9_HIGHBITDEPTH
970     thresh_ac = clamp(thresh_ac, min_thresh, max_thresh);
971 
972     // Adjust ac threshold according to partition size.
973     thresh_ac >>=
974         8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
975 
976     thresh_dc = (xd->plane[0].dequant[0] * xd->plane[0].dequant[0] >> 6);
977 #if CONFIG_VP9_HIGHBITDEPTH
978     if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && shift > 0) {
979       thresh_dc = ROUND_POWER_OF_TWO(thresh_dc, shift);
980     }
981 #endif  // CONFIG_VP9_HIGHBITDEPTH
982   } else {
983     thresh_ac = 0;
984     thresh_dc = 0;
985   }
986 
987   // Y skipping condition checking for ac and dc.
988   if (var <= thresh_ac && (sse - var) <= thresh_dc) {
989     unsigned int sse_u, sse_v;
990     unsigned int var_u, var_v;
991     unsigned int thresh_ac_uv = thresh_ac;
992     unsigned int thresh_dc_uv = thresh_dc;
993     if (x->sb_is_skin) {
994       thresh_ac_uv = 0;
995       thresh_dc_uv = 0;
996     }
997 
998     if (!flag_preduv_computed[0] || !flag_preduv_computed[1]) {
999       xd->plane[1].pre[0] = yv12_mb[ref_frame][1];
1000       xd->plane[2].pre[0] = yv12_mb[ref_frame][2];
1001       vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col, bsize);
1002     }
1003 
1004     var_u = cpi->fn_ptr[uv_size].vf(x->plane[1].src.buf, x->plane[1].src.stride,
1005                                     xd->plane[1].dst.buf,
1006                                     xd->plane[1].dst.stride, &sse_u);
1007 
1008     // U skipping condition checking
1009     if (((var_u << 2) <= thresh_ac_uv) && (sse_u - var_u <= thresh_dc_uv)) {
1010       var_v = cpi->fn_ptr[uv_size].vf(
1011           x->plane[2].src.buf, x->plane[2].src.stride, xd->plane[2].dst.buf,
1012           xd->plane[2].dst.stride, &sse_v);
1013 
1014       // V skipping condition checking
1015       if (((var_v << 2) <= thresh_ac_uv) && (sse_v - var_v <= thresh_dc_uv)) {
1016         x->skip = 1;
1017 
1018         // The cost of skip bit needs to be added.
1019         *rate = cpi->inter_mode_cost[x->mbmi_ext->mode_context[ref_frame]]
1020                                     [INTER_OFFSET(this_mode)];
1021 
1022         // More on this part of rate
1023         // rate += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
1024 
1025         // Scaling factor for SSE from spatial domain to frequency
1026         // domain is 16. Adjust distortion accordingly.
1027         // TODO(yunqingwang): In this function, only y-plane dist is
1028         // calculated.
1029         *dist = (sse << 4);  // + ((sse_u + sse_v) << 4);
1030 
1031         // *disable_skip = 1;
1032       }
1033     }
1034   }
1035 }
1036 
1037 struct estimate_block_intra_args {
1038   VP9_COMP *cpi;
1039   MACROBLOCK *x;
1040   PREDICTION_MODE mode;
1041   int skippable;
1042   RD_COST *rdc;
1043 };
1044 
estimate_block_intra(int plane,int block,int row,int col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg)1045 static void estimate_block_intra(int plane, int block, int row, int col,
1046                                  BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
1047                                  void *arg) {
1048   struct estimate_block_intra_args *const args = arg;
1049   VP9_COMP *const cpi = args->cpi;
1050   MACROBLOCK *const x = args->x;
1051   MACROBLOCKD *const xd = &x->e_mbd;
1052   struct macroblock_plane *const p = &x->plane[plane];
1053   struct macroblockd_plane *const pd = &xd->plane[plane];
1054   const BLOCK_SIZE bsize_tx = txsize_to_bsize[tx_size];
1055   uint8_t *const src_buf_base = p->src.buf;
1056   uint8_t *const dst_buf_base = pd->dst.buf;
1057   const int src_stride = p->src.stride;
1058   const int dst_stride = pd->dst.stride;
1059   RD_COST this_rdc;
1060 
1061   (void)block;
1062 
1063   p->src.buf = &src_buf_base[4 * (row * (int64_t)src_stride + col)];
1064   pd->dst.buf = &dst_buf_base[4 * (row * (int64_t)dst_stride + col)];
1065   // Use source buffer as an approximation for the fully reconstructed buffer.
1066   vp9_predict_intra_block(xd, b_width_log2_lookup[plane_bsize], tx_size,
1067                           args->mode, x->skip_encode ? p->src.buf : pd->dst.buf,
1068                           x->skip_encode ? src_stride : dst_stride, pd->dst.buf,
1069                           dst_stride, col, row, plane);
1070 
1071   if (plane == 0) {
1072     int64_t this_sse = INT64_MAX;
1073     block_yrd(cpi, x, &this_rdc, &args->skippable, &this_sse, bsize_tx,
1074               VPXMIN(tx_size, TX_16X16), 0, 1);
1075   } else {
1076     unsigned int var = 0;
1077     unsigned int sse = 0;
1078     model_rd_for_sb_uv(cpi, bsize_tx, x, xd, &this_rdc, &var, &sse, plane,
1079                        plane);
1080   }
1081 
1082   p->src.buf = src_buf_base;
1083   pd->dst.buf = dst_buf_base;
1084   args->rdc->rate += this_rdc.rate;
1085   args->rdc->dist += this_rdc.dist;
1086 }
1087 
1088 static const THR_MODES mode_idx[MAX_REF_FRAMES][4] = {
1089   { THR_DC, THR_V_PRED, THR_H_PRED, THR_TM },
1090   { THR_NEARESTMV, THR_NEARMV, THR_ZEROMV, THR_NEWMV },
1091   { THR_NEARESTG, THR_NEARG, THR_ZEROG, THR_NEWG },
1092   { THR_NEARESTA, THR_NEARA, THR_ZEROA, THR_NEWA },
1093 };
1094 
1095 static const PREDICTION_MODE intra_mode_list[] = { DC_PRED, V_PRED, H_PRED,
1096                                                    TM_PRED };
1097 
mode_offset(const PREDICTION_MODE mode)1098 static int mode_offset(const PREDICTION_MODE mode) {
1099   if (mode >= NEARESTMV) {
1100     return INTER_OFFSET(mode);
1101   } else {
1102     switch (mode) {
1103       case DC_PRED: return 0;
1104       case V_PRED: return 1;
1105       case H_PRED: return 2;
1106       case TM_PRED: return 3;
1107       default: return -1;
1108     }
1109   }
1110 }
1111 
rd_less_than_thresh_row_mt(int64_t best_rd,int thresh,const int * const thresh_fact)1112 static INLINE int rd_less_than_thresh_row_mt(int64_t best_rd, int thresh,
1113                                              const int *const thresh_fact) {
1114   int is_rd_less_than_thresh;
1115   is_rd_less_than_thresh =
1116       best_rd < ((int64_t)thresh * (*thresh_fact) >> 5) || thresh == INT_MAX;
1117   return is_rd_less_than_thresh;
1118 }
1119 
update_thresh_freq_fact_row_mt(VP9_COMP * cpi,TileDataEnc * tile_data,unsigned int source_variance,int thresh_freq_fact_idx,MV_REFERENCE_FRAME ref_frame,THR_MODES best_mode_idx,PREDICTION_MODE mode)1120 static INLINE void update_thresh_freq_fact_row_mt(
1121     VP9_COMP *cpi, TileDataEnc *tile_data, unsigned int source_variance,
1122     int thresh_freq_fact_idx, MV_REFERENCE_FRAME ref_frame,
1123     THR_MODES best_mode_idx, PREDICTION_MODE mode) {
1124   THR_MODES thr_mode_idx = mode_idx[ref_frame][mode_offset(mode)];
1125   int freq_fact_idx = thresh_freq_fact_idx + thr_mode_idx;
1126   int *freq_fact = &tile_data->row_base_thresh_freq_fact[freq_fact_idx];
1127   if (thr_mode_idx == best_mode_idx)
1128     *freq_fact -= (*freq_fact >> 4);
1129   else if (cpi->sf.limit_newmv_early_exit && mode == NEWMV &&
1130            ref_frame == LAST_FRAME && source_variance < 5) {
1131     *freq_fact = VPXMIN(*freq_fact + RD_THRESH_INC, 32);
1132   } else {
1133     *freq_fact = VPXMIN(*freq_fact + RD_THRESH_INC,
1134                         cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT);
1135   }
1136 }
1137 
update_thresh_freq_fact(VP9_COMP * cpi,TileDataEnc * tile_data,unsigned int source_variance,BLOCK_SIZE bsize,MV_REFERENCE_FRAME ref_frame,THR_MODES best_mode_idx,PREDICTION_MODE mode)1138 static INLINE void update_thresh_freq_fact(
1139     VP9_COMP *cpi, TileDataEnc *tile_data, unsigned int source_variance,
1140     BLOCK_SIZE bsize, MV_REFERENCE_FRAME ref_frame, THR_MODES best_mode_idx,
1141     PREDICTION_MODE mode) {
1142   THR_MODES thr_mode_idx = mode_idx[ref_frame][mode_offset(mode)];
1143   int *freq_fact = &tile_data->thresh_freq_fact[bsize][thr_mode_idx];
1144   if (thr_mode_idx == best_mode_idx)
1145     *freq_fact -= (*freq_fact >> 4);
1146   else if (cpi->sf.limit_newmv_early_exit && mode == NEWMV &&
1147            ref_frame == LAST_FRAME && source_variance < 5) {
1148     *freq_fact = VPXMIN(*freq_fact + RD_THRESH_INC, 32);
1149   } else {
1150     *freq_fact = VPXMIN(*freq_fact + RD_THRESH_INC,
1151                         cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT);
1152   }
1153 }
1154 
vp9_pick_intra_mode(VP9_COMP * cpi,MACROBLOCK * x,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)1155 void vp9_pick_intra_mode(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *rd_cost,
1156                          BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
1157   MACROBLOCKD *const xd = &x->e_mbd;
1158   MODE_INFO *const mi = xd->mi[0];
1159   RD_COST this_rdc, best_rdc;
1160   PREDICTION_MODE this_mode;
1161   struct estimate_block_intra_args args = { cpi, x, DC_PRED, 1, 0 };
1162   const TX_SIZE intra_tx_size =
1163       VPXMIN(max_txsize_lookup[bsize],
1164              tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
1165   MODE_INFO *const mic = xd->mi[0];
1166   int *bmode_costs;
1167   const MODE_INFO *above_mi = xd->above_mi;
1168   const MODE_INFO *left_mi = xd->left_mi;
1169   const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
1170   const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
1171   bmode_costs = cpi->y_mode_costs[A][L];
1172 
1173   (void)ctx;
1174   vp9_rd_cost_reset(&best_rdc);
1175   vp9_rd_cost_reset(&this_rdc);
1176 
1177   mi->ref_frame[0] = INTRA_FRAME;
1178   // Initialize interp_filter here so we do not have to check for inter block
1179   // modes in get_pred_context_switchable_interp()
1180   mi->interp_filter = SWITCHABLE_FILTERS;
1181 
1182   mi->mv[0].as_int = INVALID_MV;
1183   mi->uv_mode = DC_PRED;
1184   memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
1185 
1186   // Change the limit of this loop to add other intra prediction
1187   // mode tests.
1188   for (this_mode = DC_PRED; this_mode <= H_PRED; ++this_mode) {
1189     this_rdc.dist = this_rdc.rate = 0;
1190     args.mode = this_mode;
1191     args.skippable = 1;
1192     args.rdc = &this_rdc;
1193     mi->tx_size = intra_tx_size;
1194     vp9_foreach_transformed_block_in_plane(xd, bsize, 0, estimate_block_intra,
1195                                            &args);
1196     if (args.skippable) {
1197       x->skip_txfm[0] = SKIP_TXFM_AC_DC;
1198       this_rdc.rate = vp9_cost_bit(vp9_get_skip_prob(&cpi->common, xd), 1);
1199     } else {
1200       x->skip_txfm[0] = SKIP_TXFM_NONE;
1201       this_rdc.rate += vp9_cost_bit(vp9_get_skip_prob(&cpi->common, xd), 0);
1202     }
1203     this_rdc.rate += bmode_costs[this_mode];
1204     this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
1205 
1206     if (this_rdc.rdcost < best_rdc.rdcost) {
1207       best_rdc = this_rdc;
1208       mi->mode = this_mode;
1209     }
1210   }
1211 
1212   *rd_cost = best_rdc;
1213 }
1214 
init_ref_frame_cost(VP9_COMMON * const cm,MACROBLOCKD * const xd,int ref_frame_cost[MAX_REF_FRAMES])1215 static void init_ref_frame_cost(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1216                                 int ref_frame_cost[MAX_REF_FRAMES]) {
1217   vpx_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
1218   vpx_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
1219   vpx_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
1220 
1221   ref_frame_cost[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
1222   ref_frame_cost[LAST_FRAME] = ref_frame_cost[GOLDEN_FRAME] =
1223       ref_frame_cost[ALTREF_FRAME] = vp9_cost_bit(intra_inter_p, 1);
1224 
1225   ref_frame_cost[LAST_FRAME] += vp9_cost_bit(ref_single_p1, 0);
1226   ref_frame_cost[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
1227   ref_frame_cost[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
1228   ref_frame_cost[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
1229   ref_frame_cost[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
1230 }
1231 
1232 typedef struct {
1233   MV_REFERENCE_FRAME ref_frame;
1234   PREDICTION_MODE pred_mode;
1235 } REF_MODE;
1236 
1237 #define RT_INTER_MODES 12
1238 static const REF_MODE ref_mode_set[RT_INTER_MODES] = {
1239   { LAST_FRAME, ZEROMV },   { LAST_FRAME, NEARESTMV },
1240   { GOLDEN_FRAME, ZEROMV }, { LAST_FRAME, NEARMV },
1241   { LAST_FRAME, NEWMV },    { GOLDEN_FRAME, NEARESTMV },
1242   { GOLDEN_FRAME, NEARMV }, { GOLDEN_FRAME, NEWMV },
1243   { ALTREF_FRAME, ZEROMV }, { ALTREF_FRAME, NEARESTMV },
1244   { ALTREF_FRAME, NEARMV }, { ALTREF_FRAME, NEWMV }
1245 };
1246 
1247 #define RT_INTER_MODES_SVC 8
1248 static const REF_MODE ref_mode_set_svc[RT_INTER_MODES_SVC] = {
1249   { LAST_FRAME, ZEROMV },      { LAST_FRAME, NEARESTMV },
1250   { LAST_FRAME, NEARMV },      { GOLDEN_FRAME, ZEROMV },
1251   { GOLDEN_FRAME, NEARESTMV }, { GOLDEN_FRAME, NEARMV },
1252   { LAST_FRAME, NEWMV },       { GOLDEN_FRAME, NEWMV }
1253 };
1254 
find_predictors(VP9_COMP * cpi,MACROBLOCK * x,MV_REFERENCE_FRAME ref_frame,int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],int const_motion[MAX_REF_FRAMES],int * ref_frame_skip_mask,TileDataEnc * tile_data,int mi_row,int mi_col,struct buf_2d yv12_mb[4][MAX_MB_PLANE],BLOCK_SIZE bsize,int force_skip_low_temp_var,int comp_pred_allowed)1255 static INLINE void find_predictors(
1256     VP9_COMP *cpi, MACROBLOCK *x, MV_REFERENCE_FRAME ref_frame,
1257     int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1258     int const_motion[MAX_REF_FRAMES], int *ref_frame_skip_mask,
1259     TileDataEnc *tile_data, int mi_row, int mi_col,
1260     struct buf_2d yv12_mb[4][MAX_MB_PLANE], BLOCK_SIZE bsize,
1261     int force_skip_low_temp_var, int comp_pred_allowed) {
1262   VP9_COMMON *const cm = &cpi->common;
1263   MACROBLOCKD *const xd = &x->e_mbd;
1264   const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
1265   TileInfo *const tile_info = &tile_data->tile_info;
1266   // TODO(jingning) placeholder for inter-frame non-RD mode decision.
1267   x->pred_mv_sad[ref_frame] = INT_MAX;
1268   frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
1269   frame_mv[ZEROMV][ref_frame].as_int = 0;
1270   // this needs various further optimizations. to be continued..
1271   if ((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) && (yv12 != NULL)) {
1272     int_mv *const candidates = x->mbmi_ext->ref_mvs[ref_frame];
1273     const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
1274     vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
1275     if (cm->use_prev_frame_mvs || comp_pred_allowed) {
1276       vp9_find_mv_refs(cm, xd, xd->mi[0], ref_frame, candidates, mi_row, mi_col,
1277                        x->mbmi_ext->mode_context);
1278     } else {
1279       const_motion[ref_frame] =
1280           mv_refs_rt(cpi, cm, x, xd, tile_info, xd->mi[0], ref_frame,
1281                      candidates, &frame_mv[NEWMV][ref_frame], mi_row, mi_col,
1282                      (int)(cpi->svc.use_base_mv && cpi->svc.spatial_layer_id));
1283     }
1284     vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
1285                           &frame_mv[NEARESTMV][ref_frame],
1286                           &frame_mv[NEARMV][ref_frame]);
1287     // Early exit for golden frame if force_skip_low_temp_var is set.
1288     if (!vp9_is_scaled(sf) && bsize >= BLOCK_8X8 &&
1289         !(force_skip_low_temp_var && ref_frame == GOLDEN_FRAME)) {
1290       vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
1291                   bsize);
1292     }
1293   } else {
1294     *ref_frame_skip_mask |= (1 << ref_frame);
1295   }
1296 }
1297 
vp9_NEWMV_diff_bias(const NOISE_ESTIMATE * ne,MACROBLOCKD * xd,PREDICTION_MODE this_mode,RD_COST * this_rdc,BLOCK_SIZE bsize,int mv_row,int mv_col,int is_last_frame,int lowvar_highsumdiff,int is_skin)1298 static void vp9_NEWMV_diff_bias(const NOISE_ESTIMATE *ne, MACROBLOCKD *xd,
1299                                 PREDICTION_MODE this_mode, RD_COST *this_rdc,
1300                                 BLOCK_SIZE bsize, int mv_row, int mv_col,
1301                                 int is_last_frame, int lowvar_highsumdiff,
1302                                 int is_skin) {
1303   // Bias against MVs associated with NEWMV mode that are very different from
1304   // top/left neighbors.
1305   if (this_mode == NEWMV) {
1306     int al_mv_average_row;
1307     int al_mv_average_col;
1308     int left_row, left_col;
1309     int row_diff, col_diff;
1310     int above_mv_valid = 0;
1311     int left_mv_valid = 0;
1312     int above_row = 0;
1313     int above_col = 0;
1314 
1315     if (xd->above_mi) {
1316       above_mv_valid = xd->above_mi->mv[0].as_int != INVALID_MV;
1317       above_row = xd->above_mi->mv[0].as_mv.row;
1318       above_col = xd->above_mi->mv[0].as_mv.col;
1319     }
1320     if (xd->left_mi) {
1321       left_mv_valid = xd->left_mi->mv[0].as_int != INVALID_MV;
1322       left_row = xd->left_mi->mv[0].as_mv.row;
1323       left_col = xd->left_mi->mv[0].as_mv.col;
1324     }
1325     if (above_mv_valid && left_mv_valid) {
1326       al_mv_average_row = (above_row + left_row + 1) >> 1;
1327       al_mv_average_col = (above_col + left_col + 1) >> 1;
1328     } else if (above_mv_valid) {
1329       al_mv_average_row = above_row;
1330       al_mv_average_col = above_col;
1331     } else if (left_mv_valid) {
1332       al_mv_average_row = left_row;
1333       al_mv_average_col = left_col;
1334     } else {
1335       al_mv_average_row = al_mv_average_col = 0;
1336     }
1337     row_diff = (al_mv_average_row - mv_row);
1338     col_diff = (al_mv_average_col - mv_col);
1339     if (row_diff > 48 || row_diff < -48 || col_diff > 48 || col_diff < -48) {
1340       if (bsize > BLOCK_32X32)
1341         this_rdc->rdcost = this_rdc->rdcost << 1;
1342       else
1343         this_rdc->rdcost = 3 * this_rdc->rdcost >> 1;
1344     }
1345   }
1346   // If noise estimation is enabled, and estimated level is above threshold,
1347   // add a bias to LAST reference with small motion, for large blocks.
1348   if (ne->enabled && ne->level >= kMedium && bsize >= BLOCK_32X32 &&
1349       is_last_frame && mv_row < 8 && mv_row > -8 && mv_col < 8 && mv_col > -8)
1350     this_rdc->rdcost = 7 * (this_rdc->rdcost >> 3);
1351   else if (lowvar_highsumdiff && !is_skin && bsize >= BLOCK_16X16 &&
1352            is_last_frame && mv_row < 16 && mv_row > -16 && mv_col < 16 &&
1353            mv_col > -16)
1354     this_rdc->rdcost = 7 * (this_rdc->rdcost >> 3);
1355 }
1356 
1357 #if CONFIG_VP9_TEMPORAL_DENOISING
vp9_pickmode_ctx_den_update(VP9_PICKMODE_CTX_DEN * ctx_den,int64_t zero_last_cost_orig,int ref_frame_cost[MAX_REF_FRAMES],int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],int reuse_inter_pred,BEST_PICKMODE * bp)1358 static void vp9_pickmode_ctx_den_update(
1359     VP9_PICKMODE_CTX_DEN *ctx_den, int64_t zero_last_cost_orig,
1360     int ref_frame_cost[MAX_REF_FRAMES],
1361     int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES], int reuse_inter_pred,
1362     BEST_PICKMODE *bp) {
1363   ctx_den->zero_last_cost_orig = zero_last_cost_orig;
1364   ctx_den->ref_frame_cost = ref_frame_cost;
1365   ctx_den->frame_mv = frame_mv;
1366   ctx_den->reuse_inter_pred = reuse_inter_pred;
1367   ctx_den->best_tx_size = bp->best_tx_size;
1368   ctx_den->best_mode = bp->best_mode;
1369   ctx_den->best_ref_frame = bp->best_ref_frame;
1370   ctx_den->best_pred_filter = bp->best_pred_filter;
1371   ctx_den->best_mode_skip_txfm = bp->best_mode_skip_txfm;
1372 }
1373 
recheck_zeromv_after_denoising(VP9_COMP * cpi,MODE_INFO * const mi,MACROBLOCK * x,MACROBLOCKD * const xd,VP9_DENOISER_DECISION decision,VP9_PICKMODE_CTX_DEN * ctx_den,struct buf_2d yv12_mb[4][MAX_MB_PLANE],RD_COST * best_rdc,BLOCK_SIZE bsize,int mi_row,int mi_col)1374 static void recheck_zeromv_after_denoising(
1375     VP9_COMP *cpi, MODE_INFO *const mi, MACROBLOCK *x, MACROBLOCKD *const xd,
1376     VP9_DENOISER_DECISION decision, VP9_PICKMODE_CTX_DEN *ctx_den,
1377     struct buf_2d yv12_mb[4][MAX_MB_PLANE], RD_COST *best_rdc, BLOCK_SIZE bsize,
1378     int mi_row, int mi_col) {
1379   // If INTRA or GOLDEN reference was selected, re-evaluate ZEROMV on
1380   // denoised result. Only do this under noise conditions, and if rdcost of
1381   // ZEROMV onoriginal source is not significantly higher than rdcost of best
1382   // mode.
1383   if (cpi->noise_estimate.enabled && cpi->noise_estimate.level > kLow &&
1384       ctx_den->zero_last_cost_orig < (best_rdc->rdcost << 3) &&
1385       ((ctx_den->best_ref_frame == INTRA_FRAME && decision >= FILTER_BLOCK) ||
1386        (ctx_den->best_ref_frame == GOLDEN_FRAME &&
1387         cpi->svc.number_spatial_layers == 1 &&
1388         decision == FILTER_ZEROMV_BLOCK))) {
1389     // Check if we should pick ZEROMV on denoised signal.
1390     VP9_COMMON *const cm = &cpi->common;
1391     int rate = 0;
1392     int64_t dist = 0;
1393     uint32_t var_y = UINT_MAX;
1394     uint32_t sse_y = UINT_MAX;
1395     RD_COST this_rdc;
1396     mi->mode = ZEROMV;
1397     mi->ref_frame[0] = LAST_FRAME;
1398     mi->ref_frame[1] = NO_REF_FRAME;
1399     set_ref_ptrs(cm, xd, mi->ref_frame[0], NO_REF_FRAME);
1400     mi->mv[0].as_int = 0;
1401     mi->interp_filter = EIGHTTAP;
1402     if (cpi->sf.default_interp_filter == BILINEAR) mi->interp_filter = BILINEAR;
1403     xd->plane[0].pre[0] = yv12_mb[LAST_FRAME][0];
1404     vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
1405     model_rd_for_sb_y(cpi, bsize, x, xd, &rate, &dist, &var_y, &sse_y, 0);
1406     this_rdc.rate = rate + ctx_den->ref_frame_cost[LAST_FRAME] +
1407                     cpi->inter_mode_cost[x->mbmi_ext->mode_context[LAST_FRAME]]
1408                                         [INTER_OFFSET(ZEROMV)];
1409     this_rdc.dist = dist;
1410     this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, rate, dist);
1411     // Don't switch to ZEROMV if the rdcost for ZEROMV on denoised source
1412     // is higher than best_ref mode (on original source).
1413     if (this_rdc.rdcost > best_rdc->rdcost) {
1414       this_rdc = *best_rdc;
1415       mi->mode = ctx_den->best_mode;
1416       mi->ref_frame[0] = ctx_den->best_ref_frame;
1417       set_ref_ptrs(cm, xd, mi->ref_frame[0], NO_REF_FRAME);
1418       mi->interp_filter = ctx_den->best_pred_filter;
1419       if (ctx_den->best_ref_frame == INTRA_FRAME) {
1420         mi->mv[0].as_int = INVALID_MV;
1421         mi->interp_filter = SWITCHABLE_FILTERS;
1422       } else if (ctx_den->best_ref_frame == GOLDEN_FRAME) {
1423         mi->mv[0].as_int =
1424             ctx_den->frame_mv[ctx_den->best_mode][ctx_den->best_ref_frame]
1425                 .as_int;
1426         if (ctx_den->reuse_inter_pred) {
1427           xd->plane[0].pre[0] = yv12_mb[GOLDEN_FRAME][0];
1428           vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
1429         }
1430       }
1431       mi->tx_size = ctx_den->best_tx_size;
1432       x->skip_txfm[0] = ctx_den->best_mode_skip_txfm;
1433     } else {
1434       ctx_den->best_ref_frame = LAST_FRAME;
1435       *best_rdc = this_rdc;
1436     }
1437   }
1438 }
1439 #endif  // CONFIG_VP9_TEMPORAL_DENOISING
1440 
get_force_skip_low_temp_var(uint8_t * variance_low,int mi_row,int mi_col,BLOCK_SIZE bsize)1441 static INLINE int get_force_skip_low_temp_var(uint8_t *variance_low, int mi_row,
1442                                               int mi_col, BLOCK_SIZE bsize) {
1443   const int i = (mi_row & 0x7) >> 1;
1444   const int j = (mi_col & 0x7) >> 1;
1445   int force_skip_low_temp_var = 0;
1446   // Set force_skip_low_temp_var based on the block size and block offset.
1447   if (bsize == BLOCK_64X64) {
1448     force_skip_low_temp_var = variance_low[0];
1449   } else if (bsize == BLOCK_64X32) {
1450     if (!(mi_col & 0x7) && !(mi_row & 0x7)) {
1451       force_skip_low_temp_var = variance_low[1];
1452     } else if (!(mi_col & 0x7) && (mi_row & 0x7)) {
1453       force_skip_low_temp_var = variance_low[2];
1454     }
1455   } else if (bsize == BLOCK_32X64) {
1456     if (!(mi_col & 0x7) && !(mi_row & 0x7)) {
1457       force_skip_low_temp_var = variance_low[3];
1458     } else if ((mi_col & 0x7) && !(mi_row & 0x7)) {
1459       force_skip_low_temp_var = variance_low[4];
1460     }
1461   } else if (bsize == BLOCK_32X32) {
1462     if (!(mi_col & 0x7) && !(mi_row & 0x7)) {
1463       force_skip_low_temp_var = variance_low[5];
1464     } else if ((mi_col & 0x7) && !(mi_row & 0x7)) {
1465       force_skip_low_temp_var = variance_low[6];
1466     } else if (!(mi_col & 0x7) && (mi_row & 0x7)) {
1467       force_skip_low_temp_var = variance_low[7];
1468     } else if ((mi_col & 0x7) && (mi_row & 0x7)) {
1469       force_skip_low_temp_var = variance_low[8];
1470     }
1471   } else if (bsize == BLOCK_16X16) {
1472     force_skip_low_temp_var = variance_low[pos_shift_16x16[i][j]];
1473   } else if (bsize == BLOCK_32X16) {
1474     // The col shift index for the second 16x16 block.
1475     const int j2 = ((mi_col + 2) & 0x7) >> 1;
1476     // Only if each 16x16 block inside has low temporal variance.
1477     force_skip_low_temp_var = variance_low[pos_shift_16x16[i][j]] &&
1478                               variance_low[pos_shift_16x16[i][j2]];
1479   } else if (bsize == BLOCK_16X32) {
1480     // The row shift index for the second 16x16 block.
1481     const int i2 = ((mi_row + 2) & 0x7) >> 1;
1482     force_skip_low_temp_var = variance_low[pos_shift_16x16[i][j]] &&
1483                               variance_low[pos_shift_16x16[i2][j]];
1484   }
1485   return force_skip_low_temp_var;
1486 }
1487 
search_filter_ref(VP9_COMP * cpi,MACROBLOCK * x,RD_COST * this_rdc,int mi_row,int mi_col,PRED_BUFFER * tmp,BLOCK_SIZE bsize,int reuse_inter_pred,PRED_BUFFER ** this_mode_pred,unsigned int * var_y,unsigned int * sse_y,int force_smooth_filter,int * this_early_term,int * flag_preduv_computed,int use_model_yrd_large)1488 static void search_filter_ref(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *this_rdc,
1489                               int mi_row, int mi_col, PRED_BUFFER *tmp,
1490                               BLOCK_SIZE bsize, int reuse_inter_pred,
1491                               PRED_BUFFER **this_mode_pred, unsigned int *var_y,
1492                               unsigned int *sse_y, int force_smooth_filter,
1493                               int *this_early_term, int *flag_preduv_computed,
1494                               int use_model_yrd_large) {
1495   MACROBLOCKD *const xd = &x->e_mbd;
1496   MODE_INFO *const mi = xd->mi[0];
1497   struct macroblockd_plane *const pd = &xd->plane[0];
1498   const int bw = num_4x4_blocks_wide_lookup[bsize] << 2;
1499 
1500   int pf_rate[3] = { 0 };
1501   int64_t pf_dist[3] = { 0 };
1502   int curr_rate[3] = { 0 };
1503   unsigned int pf_var[3] = { 0 };
1504   unsigned int pf_sse[3] = { 0 };
1505   TX_SIZE pf_tx_size[3] = { 0 };
1506   int64_t best_cost = INT64_MAX;
1507   INTERP_FILTER best_filter = SWITCHABLE, filter;
1508   PRED_BUFFER *current_pred = *this_mode_pred;
1509   uint8_t skip_txfm = SKIP_TXFM_NONE;
1510   int best_early_term = 0;
1511   int best_flag_preduv_computed[2] = { 0 };
1512   INTERP_FILTER filter_start = force_smooth_filter ? EIGHTTAP_SMOOTH : EIGHTTAP;
1513   INTERP_FILTER filter_end = EIGHTTAP_SMOOTH;
1514   for (filter = filter_start; filter <= filter_end; ++filter) {
1515     int64_t cost;
1516     mi->interp_filter = filter;
1517     vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
1518     // For large partition blocks, extra testing is done.
1519     if (use_model_yrd_large)
1520       model_rd_for_sb_y_large(cpi, bsize, x, xd, &pf_rate[filter],
1521                               &pf_dist[filter], &pf_var[filter],
1522                               &pf_sse[filter], mi_row, mi_col, this_early_term,
1523                               flag_preduv_computed);
1524     else
1525       model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rate[filter], &pf_dist[filter],
1526                         &pf_var[filter], &pf_sse[filter], 0);
1527     curr_rate[filter] = pf_rate[filter];
1528     pf_rate[filter] += vp9_get_switchable_rate(cpi, xd);
1529     cost = RDCOST(x->rdmult, x->rddiv, pf_rate[filter], pf_dist[filter]);
1530     pf_tx_size[filter] = mi->tx_size;
1531     if (cost < best_cost) {
1532       best_filter = filter;
1533       best_cost = cost;
1534       skip_txfm = x->skip_txfm[0];
1535       best_early_term = *this_early_term;
1536       best_flag_preduv_computed[0] = flag_preduv_computed[0];
1537       best_flag_preduv_computed[1] = flag_preduv_computed[1];
1538 
1539       if (reuse_inter_pred) {
1540         if (*this_mode_pred != current_pred) {
1541           free_pred_buffer(*this_mode_pred);
1542           *this_mode_pred = current_pred;
1543         }
1544         if (filter != filter_end) {
1545           current_pred = &tmp[get_pred_buffer(tmp, 3)];
1546           pd->dst.buf = current_pred->data;
1547           pd->dst.stride = bw;
1548         }
1549       }
1550     }
1551   }
1552 
1553   if (reuse_inter_pred && *this_mode_pred != current_pred)
1554     free_pred_buffer(current_pred);
1555 
1556   mi->interp_filter = best_filter;
1557   mi->tx_size = pf_tx_size[best_filter];
1558   this_rdc->rate = curr_rate[best_filter];
1559   this_rdc->dist = pf_dist[best_filter];
1560   *var_y = pf_var[best_filter];
1561   *sse_y = pf_sse[best_filter];
1562   x->skip_txfm[0] = skip_txfm;
1563   *this_early_term = best_early_term;
1564   flag_preduv_computed[0] = best_flag_preduv_computed[0];
1565   flag_preduv_computed[1] = best_flag_preduv_computed[1];
1566   if (reuse_inter_pred) {
1567     pd->dst.buf = (*this_mode_pred)->data;
1568     pd->dst.stride = (*this_mode_pred)->stride;
1569   } else if (best_filter < filter_end) {
1570     mi->interp_filter = best_filter;
1571     vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
1572   }
1573 }
1574 
search_new_mv(VP9_COMP * cpi,MACROBLOCK * x,int_mv frame_mv[][MAX_REF_FRAMES],MV_REFERENCE_FRAME ref_frame,int gf_temporal_ref,BLOCK_SIZE bsize,int mi_row,int mi_col,int best_pred_sad,int * rate_mv,unsigned int best_sse_sofar,RD_COST * best_rdc)1575 static int search_new_mv(VP9_COMP *cpi, MACROBLOCK *x,
1576                          int_mv frame_mv[][MAX_REF_FRAMES],
1577                          MV_REFERENCE_FRAME ref_frame, int gf_temporal_ref,
1578                          BLOCK_SIZE bsize, int mi_row, int mi_col,
1579                          int best_pred_sad, int *rate_mv,
1580                          unsigned int best_sse_sofar, RD_COST *best_rdc) {
1581   SVC *const svc = &cpi->svc;
1582   MACROBLOCKD *const xd = &x->e_mbd;
1583   MODE_INFO *const mi = xd->mi[0];
1584   SPEED_FEATURES *const sf = &cpi->sf;
1585 
1586   if (ref_frame > LAST_FRAME && gf_temporal_ref &&
1587       cpi->oxcf.rc_mode == VPX_CBR) {
1588     int tmp_sad;
1589     uint32_t dis;
1590     int cost_list[5] = { INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX };
1591 
1592     if (bsize < BLOCK_16X16) return -1;
1593 
1594     tmp_sad = vp9_int_pro_motion_estimation(
1595         cpi, x, bsize, mi_row, mi_col,
1596         &x->mbmi_ext->ref_mvs[ref_frame][0].as_mv);
1597 
1598     if (tmp_sad > x->pred_mv_sad[LAST_FRAME]) return -1;
1599     if (tmp_sad + (num_pels_log2_lookup[bsize] << 4) > best_pred_sad) return -1;
1600 
1601     frame_mv[NEWMV][ref_frame].as_int = mi->mv[0].as_int;
1602     *rate_mv = vp9_mv_bit_cost(&frame_mv[NEWMV][ref_frame].as_mv,
1603                                &x->mbmi_ext->ref_mvs[ref_frame][0].as_mv,
1604                                x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
1605     frame_mv[NEWMV][ref_frame].as_mv.row >>= 3;
1606     frame_mv[NEWMV][ref_frame].as_mv.col >>= 3;
1607 
1608     cpi->find_fractional_mv_step(
1609         x, &frame_mv[NEWMV][ref_frame].as_mv,
1610         &x->mbmi_ext->ref_mvs[ref_frame][0].as_mv,
1611         cpi->common.allow_high_precision_mv, x->errorperbit,
1612         &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop,
1613         cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list),
1614         x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref_frame], NULL, 0, 0,
1615         cpi->sf.use_accurate_subpel_search);
1616   } else if (svc->use_base_mv && svc->spatial_layer_id) {
1617     if (frame_mv[NEWMV][ref_frame].as_int != INVALID_MV) {
1618       const int pre_stride = xd->plane[0].pre[0].stride;
1619       unsigned int base_mv_sse = UINT_MAX;
1620       int scale = (cpi->rc.avg_frame_low_motion > 60) ? 2 : 4;
1621       const uint8_t *const pre_buf =
1622           xd->plane[0].pre[0].buf +
1623           (frame_mv[NEWMV][ref_frame].as_mv.row >> 3) * pre_stride +
1624           (frame_mv[NEWMV][ref_frame].as_mv.col >> 3);
1625       cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
1626                             pre_buf, pre_stride, &base_mv_sse);
1627 
1628       // Exit NEWMV search if base_mv is (0,0) && bsize < BLOCK_16x16,
1629       // for SVC encoding.
1630       if (cpi->use_svc && svc->use_base_mv && bsize < BLOCK_16X16 &&
1631           frame_mv[NEWMV][ref_frame].as_mv.row == 0 &&
1632           frame_mv[NEWMV][ref_frame].as_mv.col == 0)
1633         return -1;
1634 
1635       // Exit NEWMV search if base_mv_sse is large.
1636       if (sf->base_mv_aggressive && (base_mv_sse >> scale) > best_sse_sofar)
1637         return -1;
1638       if ((base_mv_sse >> 1) < best_sse_sofar) {
1639         // Base layer mv is good.
1640         // Exit NEWMV search if the base_mv is (0, 0) and sse is low, since
1641         // (0, 0) mode is already tested.
1642         unsigned int base_mv_sse_normalized =
1643             base_mv_sse >>
1644             (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
1645         if (sf->base_mv_aggressive && base_mv_sse <= best_sse_sofar &&
1646             base_mv_sse_normalized < 400 &&
1647             frame_mv[NEWMV][ref_frame].as_mv.row == 0 &&
1648             frame_mv[NEWMV][ref_frame].as_mv.col == 0)
1649           return -1;
1650         if (!combined_motion_search(cpi, x, bsize, mi_row, mi_col,
1651                                     &frame_mv[NEWMV][ref_frame], rate_mv,
1652                                     best_rdc->rdcost, 1)) {
1653           return -1;
1654         }
1655       } else if (!combined_motion_search(cpi, x, bsize, mi_row, mi_col,
1656                                          &frame_mv[NEWMV][ref_frame], rate_mv,
1657                                          best_rdc->rdcost, 0)) {
1658         return -1;
1659       }
1660     } else if (!combined_motion_search(cpi, x, bsize, mi_row, mi_col,
1661                                        &frame_mv[NEWMV][ref_frame], rate_mv,
1662                                        best_rdc->rdcost, 0)) {
1663       return -1;
1664     }
1665   } else if (!combined_motion_search(cpi, x, bsize, mi_row, mi_col,
1666                                      &frame_mv[NEWMV][ref_frame], rate_mv,
1667                                      best_rdc->rdcost, 0)) {
1668     return -1;
1669   }
1670 
1671   return 0;
1672 }
1673 
init_best_pickmode(BEST_PICKMODE * bp)1674 static INLINE void init_best_pickmode(BEST_PICKMODE *bp) {
1675   bp->best_mode = ZEROMV;
1676   bp->best_ref_frame = LAST_FRAME;
1677   bp->best_tx_size = TX_SIZES;
1678   bp->best_intra_tx_size = TX_SIZES;
1679   bp->best_pred_filter = EIGHTTAP;
1680   bp->best_mode_skip_txfm = SKIP_TXFM_NONE;
1681   bp->best_second_ref_frame = NO_REF_FRAME;
1682   bp->best_pred = NULL;
1683 }
1684 
vp9_pick_inter_mode(VP9_COMP * cpi,MACROBLOCK * x,TileDataEnc * tile_data,int mi_row,int mi_col,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)1685 void vp9_pick_inter_mode(VP9_COMP *cpi, MACROBLOCK *x, TileDataEnc *tile_data,
1686                          int mi_row, int mi_col, RD_COST *rd_cost,
1687                          BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
1688   VP9_COMMON *const cm = &cpi->common;
1689   SPEED_FEATURES *const sf = &cpi->sf;
1690   SVC *const svc = &cpi->svc;
1691   MACROBLOCKD *const xd = &x->e_mbd;
1692   MODE_INFO *const mi = xd->mi[0];
1693   struct macroblockd_plane *const pd = &xd->plane[0];
1694 
1695   BEST_PICKMODE best_pickmode;
1696 
1697   MV_REFERENCE_FRAME ref_frame;
1698   MV_REFERENCE_FRAME usable_ref_frame, second_ref_frame;
1699   int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
1700   uint8_t mode_checked[MB_MODE_COUNT][MAX_REF_FRAMES];
1701   struct buf_2d yv12_mb[4][MAX_MB_PLANE] = { 0 };
1702   RD_COST this_rdc, best_rdc;
1703   // var_y and sse_y are saved to be used in skipping checking
1704   unsigned int var_y = UINT_MAX;
1705   unsigned int sse_y = UINT_MAX;
1706   const int intra_cost_penalty =
1707       vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
1708   int64_t inter_mode_thresh =
1709       RDCOST(x->rdmult, x->rddiv, intra_cost_penalty, 0);
1710   const int *const rd_threshes = cpi->rd.threshes[mi->segment_id][bsize];
1711   const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
1712   int thresh_freq_fact_idx = (sb_row * BLOCK_SIZES + bsize) * MAX_MODES;
1713   const int *const rd_thresh_freq_fact =
1714       (cpi->sf.adaptive_rd_thresh_row_mt)
1715           ? &(tile_data->row_base_thresh_freq_fact[thresh_freq_fact_idx])
1716           : tile_data->thresh_freq_fact[bsize];
1717 #if CONFIG_VP9_TEMPORAL_DENOISING
1718   const int denoise_recheck_zeromv = 1;
1719 #endif
1720   INTERP_FILTER filter_ref;
1721   int pred_filter_search = cm->interp_filter == SWITCHABLE;
1722   int const_motion[MAX_REF_FRAMES] = { 0 };
1723   const int bh = num_4x4_blocks_high_lookup[bsize] << 2;
1724   const int bw = num_4x4_blocks_wide_lookup[bsize] << 2;
1725   // For speed 6, the result of interp filter is reused later in actual encoding
1726   // process.
1727   // tmp[3] points to dst buffer, and the other 3 point to allocated buffers.
1728   PRED_BUFFER tmp[4];
1729   DECLARE_ALIGNED(16, uint8_t, pred_buf[3 * 64 * 64] VPX_UNINITIALIZED);
1730 #if CONFIG_VP9_HIGHBITDEPTH
1731   DECLARE_ALIGNED(16, uint16_t, pred_buf_16[3 * 64 * 64] VPX_UNINITIALIZED);
1732 #endif
1733   struct buf_2d orig_dst = pd->dst;
1734   PRED_BUFFER *this_mode_pred = NULL;
1735   const int pixels_in_block = bh * bw;
1736   int reuse_inter_pred = cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready;
1737   int ref_frame_skip_mask = 0;
1738   int idx;
1739   int best_pred_sad = INT_MAX;
1740   int best_early_term = 0;
1741   int ref_frame_cost[MAX_REF_FRAMES];
1742   int svc_force_zero_mode[3] = { 0 };
1743   int perform_intra_pred = 1;
1744   int use_golden_nonzeromv = 1;
1745   int force_skip_low_temp_var = 0;
1746   int skip_ref_find_pred[4] = { 0 };
1747   unsigned int sse_zeromv_normalized = UINT_MAX;
1748   unsigned int best_sse_sofar = UINT_MAX;
1749   int gf_temporal_ref = 0;
1750   int force_test_gf_zeromv = 0;
1751 #if CONFIG_VP9_TEMPORAL_DENOISING
1752   VP9_PICKMODE_CTX_DEN ctx_den;
1753   int64_t zero_last_cost_orig = INT64_MAX;
1754   int denoise_svc_pickmode = 1;
1755 #endif
1756   INTERP_FILTER filter_gf_svc = EIGHTTAP;
1757   MV_REFERENCE_FRAME inter_layer_ref = GOLDEN_FRAME;
1758   const struct segmentation *const seg = &cm->seg;
1759   int comp_modes = 0;
1760   int num_inter_modes = (cpi->use_svc) ? RT_INTER_MODES_SVC : RT_INTER_MODES;
1761   int flag_svc_subpel = 0;
1762   int svc_mv_col = 0;
1763   int svc_mv_row = 0;
1764   int no_scaling = 0;
1765   int large_block = 0;
1766   int use_model_yrd_large = 0;
1767   unsigned int thresh_svc_skip_golden = 500;
1768   unsigned int thresh_skip_golden = 500;
1769   int force_smooth_filter = cpi->sf.force_smooth_interpol;
1770   int scene_change_detected =
1771       cpi->rc.high_source_sad ||
1772       (cpi->use_svc && cpi->svc.high_source_sad_superframe);
1773 
1774   init_best_pickmode(&best_pickmode);
1775 
1776   x->encode_breakout = seg->enabled
1777                            ? cpi->segment_encode_breakout[mi->segment_id]
1778                            : cpi->encode_breakout;
1779 
1780   x->source_variance = UINT_MAX;
1781   if (cpi->sf.default_interp_filter == BILINEAR) {
1782     best_pickmode.best_pred_filter = BILINEAR;
1783     filter_gf_svc = BILINEAR;
1784   }
1785   if (cpi->use_svc && svc->spatial_layer_id > 0) {
1786     int layer =
1787         LAYER_IDS_TO_IDX(svc->spatial_layer_id - 1, svc->temporal_layer_id,
1788                          svc->number_temporal_layers);
1789     LAYER_CONTEXT *const lc = &svc->layer_context[layer];
1790     if (lc->scaling_factor_num == lc->scaling_factor_den) no_scaling = 1;
1791   }
1792   if (svc->spatial_layer_id > 0 &&
1793       (svc->high_source_sad_superframe || no_scaling))
1794     thresh_svc_skip_golden = 0;
1795   // Lower the skip threshold if lower spatial layer is better quality relative
1796   // to current layer.
1797   else if (svc->spatial_layer_id > 0 && cm->base_qindex > 150 &&
1798            cm->base_qindex > svc->lower_layer_qindex + 15)
1799     thresh_svc_skip_golden = 100;
1800   // Increase skip threshold if lower spatial layer is lower quality relative
1801   // to current layer.
1802   else if (svc->spatial_layer_id > 0 && cm->base_qindex < 140 &&
1803            cm->base_qindex < svc->lower_layer_qindex - 20)
1804     thresh_svc_skip_golden = 1000;
1805 
1806   if (!cpi->use_svc ||
1807       (svc->use_gf_temporal_ref_current_layer &&
1808        !svc->layer_context[svc->temporal_layer_id].is_key_frame)) {
1809     struct scale_factors *const sf_last = &cm->frame_refs[LAST_FRAME - 1].sf;
1810     struct scale_factors *const sf_golden =
1811         &cm->frame_refs[GOLDEN_FRAME - 1].sf;
1812     gf_temporal_ref = 1;
1813     // For temporal long term prediction, check that the golden reference
1814     // is same scale as last reference, otherwise disable.
1815     if ((sf_last->x_scale_fp != sf_golden->x_scale_fp) ||
1816         (sf_last->y_scale_fp != sf_golden->y_scale_fp)) {
1817       gf_temporal_ref = 0;
1818     } else {
1819       if (cpi->rc.avg_frame_low_motion > 70)
1820         thresh_svc_skip_golden = 500;
1821       else
1822         thresh_svc_skip_golden = 0;
1823     }
1824   }
1825 
1826   init_ref_frame_cost(cm, xd, ref_frame_cost);
1827   memset(&mode_checked[0][0], 0, MB_MODE_COUNT * MAX_REF_FRAMES);
1828 
1829   if (reuse_inter_pred) {
1830     int i;
1831     for (i = 0; i < 3; i++) {
1832 #if CONFIG_VP9_HIGHBITDEPTH
1833       if (cm->use_highbitdepth)
1834         tmp[i].data = CONVERT_TO_BYTEPTR(&pred_buf_16[pixels_in_block * i]);
1835       else
1836         tmp[i].data = &pred_buf[pixels_in_block * i];
1837 #else
1838       tmp[i].data = &pred_buf[pixels_in_block * i];
1839 #endif  // CONFIG_VP9_HIGHBITDEPTH
1840       tmp[i].stride = bw;
1841       tmp[i].in_use = 0;
1842     }
1843     tmp[3].data = pd->dst.buf;
1844     tmp[3].stride = pd->dst.stride;
1845     tmp[3].in_use = 0;
1846   }
1847 
1848   x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
1849   x->skip = 0;
1850 
1851   if (cpi->sf.cb_pred_filter_search) {
1852     const int bsl = mi_width_log2_lookup[bsize];
1853     pred_filter_search = cm->interp_filter == SWITCHABLE
1854                              ? (((mi_row + mi_col) >> bsl) +
1855                                 get_chessboard_index(cm->current_video_frame)) &
1856                                    0x1
1857                              : 0;
1858   }
1859   // Instead of using vp9_get_pred_context_switchable_interp(xd) to assign
1860   // filter_ref, we use a less strict condition on assigning filter_ref.
1861   // This is to reduce the probabily of entering the flow of not assigning
1862   // filter_ref and then skip filter search.
1863   filter_ref = cm->interp_filter;
1864   if (cpi->sf.default_interp_filter != BILINEAR) {
1865     if (xd->above_mi && is_inter_block(xd->above_mi))
1866       filter_ref = xd->above_mi->interp_filter;
1867     else if (xd->left_mi && is_inter_block(xd->left_mi))
1868       filter_ref = xd->left_mi->interp_filter;
1869   }
1870 
1871   // initialize mode decisions
1872   vp9_rd_cost_reset(&best_rdc);
1873   vp9_rd_cost_reset(rd_cost);
1874   mi->sb_type = bsize;
1875   mi->ref_frame[0] = NO_REF_FRAME;
1876   mi->ref_frame[1] = NO_REF_FRAME;
1877 
1878   mi->tx_size =
1879       VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[cm->tx_mode]);
1880 
1881   if (sf->short_circuit_flat_blocks || sf->limit_newmv_early_exit) {
1882 #if CONFIG_VP9_HIGHBITDEPTH
1883     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
1884       x->source_variance = vp9_high_get_sby_perpixel_variance(
1885           cpi, &x->plane[0].src, bsize, xd->bd);
1886     else
1887 #endif  // CONFIG_VP9_HIGHBITDEPTH
1888       x->source_variance =
1889           vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1890 
1891     if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1892         cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && mi->segment_id > 0 &&
1893         x->zero_temp_sad_source && x->source_variance == 0) {
1894       mi->segment_id = 0;
1895       vp9_init_plane_quantizers(cpi, x);
1896     }
1897   }
1898 
1899 #if CONFIG_VP9_TEMPORAL_DENOISING
1900   if (cpi->oxcf.noise_sensitivity > 0) {
1901     if (cpi->use_svc) denoise_svc_pickmode = vp9_denoise_svc_non_key(cpi);
1902     if (cpi->denoiser.denoising_level > kDenLowLow && denoise_svc_pickmode)
1903       vp9_denoiser_reset_frame_stats(ctx);
1904   }
1905 #endif
1906 
1907   if (cpi->rc.frames_since_golden == 0 && gf_temporal_ref &&
1908       !cpi->rc.alt_ref_gf_group && !cpi->rc.last_frame_is_src_altref) {
1909     usable_ref_frame = LAST_FRAME;
1910   } else {
1911     usable_ref_frame = GOLDEN_FRAME;
1912   }
1913 
1914   if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) {
1915     if (cpi->rc.alt_ref_gf_group || cpi->rc.is_src_frame_alt_ref)
1916       usable_ref_frame = ALTREF_FRAME;
1917 
1918     if (cpi->rc.is_src_frame_alt_ref) {
1919       skip_ref_find_pred[LAST_FRAME] = 1;
1920       skip_ref_find_pred[GOLDEN_FRAME] = 1;
1921     }
1922     if (!cm->show_frame) {
1923       if (cpi->rc.frames_since_key == 1) {
1924         usable_ref_frame = LAST_FRAME;
1925         skip_ref_find_pred[GOLDEN_FRAME] = 1;
1926         skip_ref_find_pred[ALTREF_FRAME] = 1;
1927       }
1928     }
1929   }
1930 
1931   // For svc mode, on spatial_layer_id > 0: if the reference has different scale
1932   // constrain the inter mode to only test zero motion.
1933   if (cpi->use_svc && svc->force_zero_mode_spatial_ref &&
1934       svc->spatial_layer_id > 0 && !gf_temporal_ref) {
1935     if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
1936       struct scale_factors *const ref_sf = &cm->frame_refs[LAST_FRAME - 1].sf;
1937       if (vp9_is_scaled(ref_sf)) {
1938         svc_force_zero_mode[LAST_FRAME - 1] = 1;
1939         inter_layer_ref = LAST_FRAME;
1940       }
1941     }
1942     if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
1943       struct scale_factors *const ref_sf = &cm->frame_refs[GOLDEN_FRAME - 1].sf;
1944       if (vp9_is_scaled(ref_sf)) {
1945         svc_force_zero_mode[GOLDEN_FRAME - 1] = 1;
1946         inter_layer_ref = GOLDEN_FRAME;
1947       }
1948     }
1949   }
1950 
1951   if (cpi->sf.short_circuit_low_temp_var) {
1952     force_skip_low_temp_var =
1953         get_force_skip_low_temp_var(&x->variance_low[0], mi_row, mi_col, bsize);
1954     // If force_skip_low_temp_var is set, and for short circuit mode = 1 and 3,
1955     // skip golden reference.
1956     if ((cpi->sf.short_circuit_low_temp_var == 1 ||
1957          cpi->sf.short_circuit_low_temp_var == 3) &&
1958         force_skip_low_temp_var) {
1959       usable_ref_frame = LAST_FRAME;
1960     }
1961   }
1962 
1963   if (sf->disable_golden_ref && (x->content_state_sb != kVeryHighSad ||
1964                                  cpi->rc.avg_frame_low_motion < 60))
1965     usable_ref_frame = LAST_FRAME;
1966 
1967   if (!((cpi->ref_frame_flags & VP9_GOLD_FLAG) &&
1968         !svc_force_zero_mode[GOLDEN_FRAME - 1] && !force_skip_low_temp_var))
1969     use_golden_nonzeromv = 0;
1970 
1971   if (cpi->oxcf.speed >= 8 && !cpi->use_svc &&
1972       ((cpi->rc.frames_since_golden + 1) < x->last_sb_high_content ||
1973        x->last_sb_high_content > 40 || cpi->rc.frames_since_golden > 120))
1974     usable_ref_frame = LAST_FRAME;
1975 
1976   // Compound prediction modes: (0,0) on LAST/GOLDEN and ARF.
1977   if (cm->reference_mode == REFERENCE_MODE_SELECT &&
1978       cpi->sf.use_compound_nonrd_pickmode && usable_ref_frame == ALTREF_FRAME)
1979     comp_modes = 2;
1980 
1981   // If the segment reference frame feature is enabled and it's set to GOLDEN
1982   // reference, then make sure we don't skip checking GOLDEN, this is to
1983   // prevent possibility of not picking any mode.
1984   if (segfeature_active(seg, mi->segment_id, SEG_LVL_REF_FRAME) &&
1985       get_segdata(seg, mi->segment_id, SEG_LVL_REF_FRAME) == GOLDEN_FRAME) {
1986     usable_ref_frame = GOLDEN_FRAME;
1987     skip_ref_find_pred[GOLDEN_FRAME] = 0;
1988     thresh_svc_skip_golden = 0;
1989   }
1990 
1991   for (ref_frame = LAST_FRAME; ref_frame <= usable_ref_frame; ++ref_frame) {
1992     // Skip find_predictor if the reference frame is not in the
1993     // ref_frame_flags (i.e., not used as a reference for this frame).
1994     skip_ref_find_pred[ref_frame] =
1995         !(cpi->ref_frame_flags & ref_frame_to_flag(ref_frame));
1996     if (!skip_ref_find_pred[ref_frame]) {
1997       find_predictors(cpi, x, ref_frame, frame_mv, const_motion,
1998                       &ref_frame_skip_mask, tile_data, mi_row, mi_col, yv12_mb,
1999                       bsize, force_skip_low_temp_var, comp_modes > 0);
2000     }
2001   }
2002 
2003   if (cpi->use_svc || cpi->oxcf.speed <= 7 || bsize < BLOCK_32X32)
2004     x->sb_use_mv_part = 0;
2005 
2006   // Set the flag_svc_subpel to 1 for SVC if the lower spatial layer used
2007   // an averaging filter for downsampling (phase = 8). If so, we will test
2008   // a nonzero motion mode on the spatial reference.
2009   // The nonzero motion is half pixel shifted to left and top (-4, -4).
2010   if (cpi->use_svc && svc->spatial_layer_id > 0 &&
2011       svc_force_zero_mode[inter_layer_ref - 1] &&
2012       svc->downsample_filter_phase[svc->spatial_layer_id - 1] == 8 &&
2013       !gf_temporal_ref) {
2014     svc_mv_col = -4;
2015     svc_mv_row = -4;
2016     flag_svc_subpel = 1;
2017   }
2018 
2019   // For SVC with quality layers, when QP of lower layer is lower
2020   // than current layer: force check of GF-ZEROMV before early exit
2021   // due to skip flag.
2022   if (svc->spatial_layer_id > 0 && no_scaling &&
2023       (cpi->ref_frame_flags & VP9_GOLD_FLAG) &&
2024       cm->base_qindex > svc->lower_layer_qindex + 10)
2025     force_test_gf_zeromv = 1;
2026 
2027   // For low motion content use x->sb_is_skin in addition to VeryHighSad
2028   // for setting large_block.
2029   large_block = (x->content_state_sb == kVeryHighSad ||
2030                  (x->sb_is_skin && cpi->rc.avg_frame_low_motion > 70) ||
2031                  cpi->oxcf.speed < 7)
2032                     ? bsize > BLOCK_32X32
2033                     : bsize >= BLOCK_32X32;
2034   use_model_yrd_large =
2035       cpi->oxcf.rc_mode == VPX_CBR && large_block &&
2036       !cyclic_refresh_segment_id_boosted(xd->mi[0]->segment_id) &&
2037       cm->base_qindex;
2038 
2039   for (idx = 0; idx < num_inter_modes + comp_modes; ++idx) {
2040     int rate_mv = 0;
2041     int mode_rd_thresh;
2042     int mode_index;
2043     int i;
2044     int64_t this_sse;
2045     int is_skippable;
2046     int this_early_term = 0;
2047     int rd_computed = 0;
2048     int flag_preduv_computed[2] = { 0 };
2049     int inter_mv_mode = 0;
2050     int skip_this_mv = 0;
2051     int comp_pred = 0;
2052     int force_mv_inter_layer = 0;
2053     PREDICTION_MODE this_mode;
2054     second_ref_frame = NO_REF_FRAME;
2055 
2056     if (idx < num_inter_modes) {
2057       this_mode = ref_mode_set[idx].pred_mode;
2058       ref_frame = ref_mode_set[idx].ref_frame;
2059 
2060       if (cpi->use_svc) {
2061         this_mode = ref_mode_set_svc[idx].pred_mode;
2062         ref_frame = ref_mode_set_svc[idx].ref_frame;
2063       }
2064     } else {
2065       // Add (0,0) compound modes.
2066       this_mode = ZEROMV;
2067       ref_frame = LAST_FRAME;
2068       if (idx == num_inter_modes + comp_modes - 1) ref_frame = GOLDEN_FRAME;
2069       second_ref_frame = ALTREF_FRAME;
2070       comp_pred = 1;
2071     }
2072 
2073     if (ref_frame > usable_ref_frame) continue;
2074     if (skip_ref_find_pred[ref_frame]) continue;
2075 
2076     if (svc->previous_frame_is_intra_only) {
2077       if (ref_frame != LAST_FRAME || frame_mv[this_mode][ref_frame].as_int != 0)
2078         continue;
2079     }
2080 
2081     // If the segment reference frame feature is enabled then do nothing if the
2082     // current ref frame is not allowed.
2083     if (segfeature_active(seg, mi->segment_id, SEG_LVL_REF_FRAME) &&
2084         get_segdata(seg, mi->segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame)
2085       continue;
2086 
2087     if (flag_svc_subpel && ref_frame == inter_layer_ref) {
2088       force_mv_inter_layer = 1;
2089       // Only test mode if NEARESTMV/NEARMV is (svc_mv_col, svc_mv_row),
2090       // otherwise set NEWMV to (svc_mv_col, svc_mv_row).
2091       if (this_mode == NEWMV) {
2092         frame_mv[this_mode][ref_frame].as_mv.col = svc_mv_col;
2093         frame_mv[this_mode][ref_frame].as_mv.row = svc_mv_row;
2094       } else if (frame_mv[this_mode][ref_frame].as_mv.col != svc_mv_col ||
2095                  frame_mv[this_mode][ref_frame].as_mv.row != svc_mv_row) {
2096         continue;
2097       }
2098     }
2099 
2100     if (comp_pred) {
2101       if (!cpi->allow_comp_inter_inter) continue;
2102       // Skip compound inter modes if ARF is not available.
2103       if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
2104         continue;
2105       // Do not allow compound prediction if the segment level reference frame
2106       // feature is in use as in this case there can only be one reference.
2107       if (segfeature_active(seg, mi->segment_id, SEG_LVL_REF_FRAME)) continue;
2108     }
2109 
2110     // For CBR mode: skip the golden reference search if sse of zeromv_last is
2111     // below threshold.
2112     if (ref_frame == GOLDEN_FRAME && cpi->oxcf.rc_mode == VPX_CBR &&
2113         ((cpi->use_svc && sse_zeromv_normalized < thresh_svc_skip_golden) ||
2114          (!cpi->use_svc && sse_zeromv_normalized < thresh_skip_golden)))
2115       continue;
2116 
2117     if (!(cpi->ref_frame_flags & ref_frame_to_flag(ref_frame))) continue;
2118 
2119     // For screen content. If zero_temp_sad source is computed: skip
2120     // non-zero motion check for stationary blocks. If the superblock is
2121     // non-stationary then for flat blocks skip the zero last check (keep golden
2122     // as it may be inter-layer reference). Otherwise (if zero_temp_sad_source
2123     // is not computed) skip non-zero motion check for flat blocks.
2124     // TODO(marpan): Compute zero_temp_sad_source per coding block.
2125     if (cpi->oxcf.content == VP9E_CONTENT_SCREEN) {
2126       if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
2127         if ((frame_mv[this_mode][ref_frame].as_int != 0 &&
2128              x->zero_temp_sad_source) ||
2129             (frame_mv[this_mode][ref_frame].as_int == 0 &&
2130              x->source_variance == 0 && ref_frame == LAST_FRAME &&
2131              !x->zero_temp_sad_source))
2132           continue;
2133       } else if (frame_mv[this_mode][ref_frame].as_int != 0 &&
2134                  x->source_variance == 0) {
2135         continue;
2136       }
2137     }
2138 
2139     if (!(cpi->sf.inter_mode_mask[bsize] & (1 << this_mode))) continue;
2140 
2141     if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) {
2142       if (cpi->rc.is_src_frame_alt_ref &&
2143           (ref_frame != ALTREF_FRAME ||
2144            frame_mv[this_mode][ref_frame].as_int != 0))
2145         continue;
2146 
2147       if (!cm->show_frame && ref_frame == ALTREF_FRAME &&
2148           frame_mv[this_mode][ref_frame].as_int != 0)
2149         continue;
2150 
2151       if (cpi->rc.alt_ref_gf_group && cm->show_frame &&
2152           cpi->rc.frames_since_golden > (cpi->rc.baseline_gf_interval >> 1) &&
2153           ref_frame == GOLDEN_FRAME &&
2154           frame_mv[this_mode][ref_frame].as_int != 0)
2155         continue;
2156 
2157       if (cpi->rc.alt_ref_gf_group && cm->show_frame &&
2158           cpi->rc.frames_since_golden > 0 &&
2159           cpi->rc.frames_since_golden < (cpi->rc.baseline_gf_interval >> 1) &&
2160           ref_frame == ALTREF_FRAME &&
2161           frame_mv[this_mode][ref_frame].as_int != 0)
2162         continue;
2163     }
2164 
2165     if (const_motion[ref_frame] && this_mode == NEARMV) continue;
2166 
2167     // Skip non-zeromv mode search for golden frame if force_skip_low_temp_var
2168     // is set. If nearestmv for golden frame is 0, zeromv mode will be skipped
2169     // later.
2170     if (!force_mv_inter_layer && force_skip_low_temp_var &&
2171         ref_frame == GOLDEN_FRAME &&
2172         frame_mv[this_mode][ref_frame].as_int != 0) {
2173       continue;
2174     }
2175 
2176     if (x->content_state_sb != kVeryHighSad &&
2177         (cpi->sf.short_circuit_low_temp_var >= 2 ||
2178          (cpi->sf.short_circuit_low_temp_var == 1 && bsize == BLOCK_64X64)) &&
2179         force_skip_low_temp_var && ref_frame == LAST_FRAME &&
2180         this_mode == NEWMV) {
2181       continue;
2182     }
2183 
2184     if (cpi->use_svc) {
2185       if (!force_mv_inter_layer && svc_force_zero_mode[ref_frame - 1] &&
2186           frame_mv[this_mode][ref_frame].as_int != 0)
2187         continue;
2188     }
2189 
2190     // Disable this drop out case if the ref frame segment level feature is
2191     // enabled for this segment. This is to prevent the possibility that we end
2192     // up unable to pick any mode.
2193     if (!segfeature_active(seg, mi->segment_id, SEG_LVL_REF_FRAME)) {
2194       if (sf->reference_masking &&
2195           !(frame_mv[this_mode][ref_frame].as_int == 0 &&
2196             ref_frame == LAST_FRAME)) {
2197         if (usable_ref_frame < ALTREF_FRAME) {
2198           if (!force_skip_low_temp_var && usable_ref_frame > LAST_FRAME) {
2199             i = (ref_frame == LAST_FRAME) ? GOLDEN_FRAME : LAST_FRAME;
2200             if ((cpi->ref_frame_flags & ref_frame_to_flag(i)))
2201               if (x->pred_mv_sad[ref_frame] > (x->pred_mv_sad[i] << 1))
2202                 ref_frame_skip_mask |= (1 << ref_frame);
2203           }
2204         } else if (!cpi->rc.is_src_frame_alt_ref &&
2205                    !(frame_mv[this_mode][ref_frame].as_int == 0 &&
2206                      ref_frame == ALTREF_FRAME)) {
2207           int ref1 = (ref_frame == GOLDEN_FRAME) ? LAST_FRAME : GOLDEN_FRAME;
2208           int ref2 = (ref_frame == ALTREF_FRAME) ? LAST_FRAME : ALTREF_FRAME;
2209           if (((cpi->ref_frame_flags & ref_frame_to_flag(ref1)) &&
2210                (x->pred_mv_sad[ref_frame] > (x->pred_mv_sad[ref1] << 1))) ||
2211               ((cpi->ref_frame_flags & ref_frame_to_flag(ref2)) &&
2212                (x->pred_mv_sad[ref_frame] > (x->pred_mv_sad[ref2] << 1))))
2213             ref_frame_skip_mask |= (1 << ref_frame);
2214         }
2215       }
2216       if (ref_frame_skip_mask & (1 << ref_frame)) continue;
2217     }
2218 
2219     // Select prediction reference frames.
2220     for (i = 0; i < MAX_MB_PLANE; i++) {
2221       xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
2222       if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
2223     }
2224 
2225     mi->ref_frame[0] = ref_frame;
2226     mi->ref_frame[1] = second_ref_frame;
2227     set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
2228 
2229     mode_index = mode_idx[ref_frame][INTER_OFFSET(this_mode)];
2230     mode_rd_thresh = best_pickmode.best_mode_skip_txfm
2231                          ? rd_threshes[mode_index] << 1
2232                          : rd_threshes[mode_index];
2233 
2234     // Increase mode_rd_thresh value for GOLDEN_FRAME for improved encoding
2235     // speed with little/no subjective quality loss.
2236     if (cpi->sf.bias_golden && ref_frame == GOLDEN_FRAME &&
2237         cpi->rc.frames_since_golden > 4)
2238       mode_rd_thresh = mode_rd_thresh << 3;
2239 
2240     if ((cpi->sf.adaptive_rd_thresh_row_mt &&
2241          rd_less_than_thresh_row_mt(best_rdc.rdcost, mode_rd_thresh,
2242                                     &rd_thresh_freq_fact[mode_index])) ||
2243         (!cpi->sf.adaptive_rd_thresh_row_mt &&
2244          rd_less_than_thresh(best_rdc.rdcost, mode_rd_thresh,
2245                              &rd_thresh_freq_fact[mode_index])))
2246       if (frame_mv[this_mode][ref_frame].as_int != 0) continue;
2247 
2248     if (this_mode == NEWMV && !force_mv_inter_layer) {
2249       if (search_new_mv(cpi, x, frame_mv, ref_frame, gf_temporal_ref, bsize,
2250                         mi_row, mi_col, best_pred_sad, &rate_mv, best_sse_sofar,
2251                         &best_rdc))
2252         continue;
2253     }
2254 
2255     // TODO(jianj): Skipping the testing of (duplicate) non-zero motion vector
2256     // causes some regression, leave it for duplicate zero-mv for now, until
2257     // regression issue is resolved.
2258     for (inter_mv_mode = NEARESTMV; inter_mv_mode <= NEWMV; inter_mv_mode++) {
2259       if (inter_mv_mode == this_mode || comp_pred) continue;
2260       if (mode_checked[inter_mv_mode][ref_frame] &&
2261           frame_mv[this_mode][ref_frame].as_int ==
2262               frame_mv[inter_mv_mode][ref_frame].as_int &&
2263           frame_mv[inter_mv_mode][ref_frame].as_int == 0) {
2264         skip_this_mv = 1;
2265         break;
2266       }
2267     }
2268 
2269     if (skip_this_mv) continue;
2270 
2271     // If use_golden_nonzeromv is false, NEWMV mode is skipped for golden, no
2272     // need to compute best_pred_sad which is only used to skip golden NEWMV.
2273     if (use_golden_nonzeromv && this_mode == NEWMV && ref_frame == LAST_FRAME &&
2274         frame_mv[NEWMV][LAST_FRAME].as_int != INVALID_MV) {
2275       const int pre_stride = xd->plane[0].pre[0].stride;
2276       const uint8_t *const pre_buf =
2277           xd->plane[0].pre[0].buf +
2278           (frame_mv[NEWMV][LAST_FRAME].as_mv.row >> 3) * pre_stride +
2279           (frame_mv[NEWMV][LAST_FRAME].as_mv.col >> 3);
2280       best_pred_sad = cpi->fn_ptr[bsize].sdf(
2281           x->plane[0].src.buf, x->plane[0].src.stride, pre_buf, pre_stride);
2282       x->pred_mv_sad[LAST_FRAME] = best_pred_sad;
2283     }
2284 
2285     if (this_mode != NEARESTMV && !comp_pred &&
2286         frame_mv[this_mode][ref_frame].as_int ==
2287             frame_mv[NEARESTMV][ref_frame].as_int)
2288       continue;
2289 
2290     mi->mode = this_mode;
2291     mi->mv[0].as_int = frame_mv[this_mode][ref_frame].as_int;
2292     mi->mv[1].as_int = 0;
2293 
2294     // Search for the best prediction filter type, when the resulting
2295     // motion vector is at sub-pixel accuracy level for luma component, i.e.,
2296     // the last three bits are all zeros.
2297     if (reuse_inter_pred) {
2298       if (!this_mode_pred) {
2299         this_mode_pred = &tmp[3];
2300       } else {
2301         this_mode_pred = &tmp[get_pred_buffer(tmp, 3)];
2302         pd->dst.buf = this_mode_pred->data;
2303         pd->dst.stride = bw;
2304       }
2305     }
2306 
2307     if ((this_mode == NEWMV || filter_ref == SWITCHABLE) &&
2308         pred_filter_search &&
2309         (ref_frame == LAST_FRAME ||
2310          (ref_frame == GOLDEN_FRAME && !force_mv_inter_layer &&
2311           (cpi->use_svc || cpi->oxcf.rc_mode == VPX_VBR))) &&
2312         (((mi->mv[0].as_mv.row | mi->mv[0].as_mv.col) & 0x07) != 0)) {
2313       rd_computed = 1;
2314       search_filter_ref(cpi, x, &this_rdc, mi_row, mi_col, tmp, bsize,
2315                         reuse_inter_pred, &this_mode_pred, &var_y, &sse_y,
2316                         force_smooth_filter, &this_early_term,
2317                         flag_preduv_computed, use_model_yrd_large);
2318     } else {
2319       mi->interp_filter = (filter_ref == SWITCHABLE) ? EIGHTTAP : filter_ref;
2320 
2321       if (cpi->use_svc && ref_frame == GOLDEN_FRAME &&
2322           svc_force_zero_mode[ref_frame - 1])
2323         mi->interp_filter = filter_gf_svc;
2324 
2325       vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
2326 
2327       // For large partition blocks, extra testing is done.
2328       if (use_model_yrd_large) {
2329         rd_computed = 1;
2330         model_rd_for_sb_y_large(cpi, bsize, x, xd, &this_rdc.rate,
2331                                 &this_rdc.dist, &var_y, &sse_y, mi_row, mi_col,
2332                                 &this_early_term, flag_preduv_computed);
2333       } else {
2334         rd_computed = 1;
2335         model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc.rate, &this_rdc.dist,
2336                           &var_y, &sse_y, 0);
2337       }
2338       // Save normalized sse (between current and last frame) for (0, 0) motion.
2339       if (ref_frame == LAST_FRAME &&
2340           frame_mv[this_mode][ref_frame].as_int == 0) {
2341         sse_zeromv_normalized =
2342             sse_y >> (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
2343       }
2344       if (sse_y < best_sse_sofar) best_sse_sofar = sse_y;
2345     }
2346 
2347     if (!this_early_term) {
2348       this_sse = (int64_t)sse_y;
2349       block_yrd(cpi, x, &this_rdc, &is_skippable, &this_sse, bsize,
2350                 VPXMIN(mi->tx_size, TX_16X16), rd_computed, 0);
2351       x->skip_txfm[0] = is_skippable;
2352       if (is_skippable) {
2353         this_rdc.rate = vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2354       } else {
2355         if (RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist) <
2356             RDCOST(x->rdmult, x->rddiv, 0, this_sse)) {
2357           this_rdc.rate += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
2358         } else {
2359           this_rdc.rate = vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2360           this_rdc.dist = this_sse;
2361           x->skip_txfm[0] = SKIP_TXFM_AC_DC;
2362         }
2363       }
2364 
2365       if (cm->interp_filter == SWITCHABLE) {
2366         if ((mi->mv[0].as_mv.row | mi->mv[0].as_mv.col) & 0x07)
2367           this_rdc.rate += vp9_get_switchable_rate(cpi, xd);
2368       }
2369     } else {
2370       if (cm->interp_filter == SWITCHABLE) {
2371         if ((mi->mv[0].as_mv.row | mi->mv[0].as_mv.col) & 0x07)
2372           this_rdc.rate += vp9_get_switchable_rate(cpi, xd);
2373       }
2374       this_rdc.rate += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2375     }
2376 
2377     if (!this_early_term &&
2378         (x->color_sensitivity[0] || x->color_sensitivity[1])) {
2379       RD_COST rdc_uv;
2380       const BLOCK_SIZE uv_bsize = get_plane_block_size(bsize, &xd->plane[1]);
2381       if (x->color_sensitivity[0] && !flag_preduv_computed[0]) {
2382         vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, 1);
2383         flag_preduv_computed[0] = 1;
2384       }
2385       if (x->color_sensitivity[1] && !flag_preduv_computed[1]) {
2386         vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, 2);
2387         flag_preduv_computed[1] = 1;
2388       }
2389       model_rd_for_sb_uv(cpi, uv_bsize, x, xd, &rdc_uv, &var_y, &sse_y, 1, 2);
2390       this_rdc.rate += rdc_uv.rate;
2391       this_rdc.dist += rdc_uv.dist;
2392     }
2393 
2394     this_rdc.rate += rate_mv;
2395     this_rdc.rate += cpi->inter_mode_cost[x->mbmi_ext->mode_context[ref_frame]]
2396                                          [INTER_OFFSET(this_mode)];
2397     // TODO(marpan): Add costing for compound mode.
2398     this_rdc.rate += ref_frame_cost[ref_frame];
2399     this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
2400 
2401     // Bias against NEWMV that is very different from its neighbors, and bias
2402     // to small motion-lastref for noisy input.
2403     if (cpi->oxcf.rc_mode == VPX_CBR && cpi->oxcf.speed >= 5 &&
2404         cpi->oxcf.content != VP9E_CONTENT_SCREEN) {
2405       vp9_NEWMV_diff_bias(&cpi->noise_estimate, xd, this_mode, &this_rdc, bsize,
2406                           frame_mv[this_mode][ref_frame].as_mv.row,
2407                           frame_mv[this_mode][ref_frame].as_mv.col,
2408                           ref_frame == LAST_FRAME, x->lowvar_highsumdiff,
2409                           x->sb_is_skin);
2410     }
2411 
2412     // Skipping checking: test to see if this block can be reconstructed by
2413     // prediction only.
2414     if (cpi->allow_encode_breakout && !xd->lossless && !scene_change_detected &&
2415         !svc->high_num_blocks_with_motion) {
2416       encode_breakout_test(cpi, x, bsize, mi_row, mi_col, ref_frame, this_mode,
2417                            var_y, sse_y, yv12_mb, &this_rdc.rate,
2418                            &this_rdc.dist, flag_preduv_computed);
2419       if (x->skip) {
2420         this_rdc.rate += rate_mv;
2421         this_rdc.rdcost =
2422             RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
2423       }
2424     }
2425 
2426     // On spatially flat blocks for screne content: bias against zero-last
2427     // if the sse_y is non-zero. Only on scene change or high motion frames.
2428     if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
2429         (scene_change_detected || svc->high_num_blocks_with_motion) &&
2430         ref_frame == LAST_FRAME && frame_mv[this_mode][ref_frame].as_int == 0 &&
2431         svc->spatial_layer_id == 0 && x->source_variance == 0 && sse_y > 0) {
2432       this_rdc.rdcost = this_rdc.rdcost << 2;
2433     }
2434 
2435 #if CONFIG_VP9_TEMPORAL_DENOISING
2436     if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc_pickmode &&
2437         cpi->denoiser.denoising_level > kDenLowLow) {
2438       vp9_denoiser_update_frame_stats(mi, sse_y, this_mode, ctx);
2439       // Keep track of zero_last cost.
2440       if (ref_frame == LAST_FRAME && frame_mv[this_mode][ref_frame].as_int == 0)
2441         zero_last_cost_orig = this_rdc.rdcost;
2442     }
2443 #else
2444     (void)ctx;
2445 #endif
2446 
2447     mode_checked[this_mode][ref_frame] = 1;
2448 
2449     if (this_rdc.rdcost < best_rdc.rdcost || x->skip) {
2450       best_rdc = this_rdc;
2451       best_early_term = this_early_term;
2452       best_pickmode.best_mode = this_mode;
2453       best_pickmode.best_pred_filter = mi->interp_filter;
2454       best_pickmode.best_tx_size = mi->tx_size;
2455       best_pickmode.best_ref_frame = ref_frame;
2456       best_pickmode.best_mode_skip_txfm = x->skip_txfm[0];
2457       best_pickmode.best_second_ref_frame = second_ref_frame;
2458 
2459       if (reuse_inter_pred) {
2460         free_pred_buffer(best_pickmode.best_pred);
2461         best_pickmode.best_pred = this_mode_pred;
2462       }
2463     } else {
2464       if (reuse_inter_pred) free_pred_buffer(this_mode_pred);
2465     }
2466 
2467     if (x->skip &&
2468         (!force_test_gf_zeromv || mode_checked[ZEROMV][GOLDEN_FRAME]))
2469       break;
2470 
2471     // If early termination flag is 1 and at least 2 modes are checked,
2472     // the mode search is terminated.
2473     if (best_early_term && idx > 0 && !scene_change_detected &&
2474         (!force_test_gf_zeromv || mode_checked[ZEROMV][GOLDEN_FRAME])) {
2475       x->skip = 1;
2476       break;
2477     }
2478   }
2479 
2480   mi->mode = best_pickmode.best_mode;
2481   mi->interp_filter = best_pickmode.best_pred_filter;
2482   mi->tx_size = best_pickmode.best_tx_size;
2483   mi->ref_frame[0] = best_pickmode.best_ref_frame;
2484   mi->mv[0].as_int =
2485       frame_mv[best_pickmode.best_mode][best_pickmode.best_ref_frame].as_int;
2486   xd->mi[0]->bmi[0].as_mv[0].as_int = mi->mv[0].as_int;
2487   x->skip_txfm[0] = best_pickmode.best_mode_skip_txfm;
2488   mi->ref_frame[1] = best_pickmode.best_second_ref_frame;
2489 
2490   // For spatial enhancemanent layer: perform intra prediction only if base
2491   // layer is chosen as the reference. Always perform intra prediction if
2492   // LAST is the only reference, or is_key_frame is set, or on base
2493   // temporal layer.
2494   if (svc->spatial_layer_id && !gf_temporal_ref) {
2495     perform_intra_pred =
2496         svc->temporal_layer_id == 0 ||
2497         svc->layer_context[svc->temporal_layer_id].is_key_frame ||
2498         !(cpi->ref_frame_flags & VP9_GOLD_FLAG) ||
2499         (!svc->layer_context[svc->temporal_layer_id].is_key_frame &&
2500          svc_force_zero_mode[best_pickmode.best_ref_frame - 1]);
2501     inter_mode_thresh = (inter_mode_thresh << 1) + inter_mode_thresh;
2502   }
2503   if ((cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
2504        cpi->rc.is_src_frame_alt_ref) ||
2505       svc->previous_frame_is_intra_only)
2506     perform_intra_pred = 0;
2507 
2508   // If the segment reference frame feature is enabled and set then
2509   // skip the intra prediction.
2510   if (segfeature_active(seg, mi->segment_id, SEG_LVL_REF_FRAME) &&
2511       get_segdata(seg, mi->segment_id, SEG_LVL_REF_FRAME) > 0)
2512     perform_intra_pred = 0;
2513 
2514   // Perform intra prediction search, if the best SAD is above a certain
2515   // threshold.
2516   if (best_rdc.rdcost == INT64_MAX ||
2517       (cpi->oxcf.content == VP9E_CONTENT_SCREEN && x->source_variance == 0) ||
2518       (scene_change_detected && perform_intra_pred) ||
2519       ((!force_skip_low_temp_var || bsize < BLOCK_32X32 ||
2520         x->content_state_sb == kVeryHighSad) &&
2521        perform_intra_pred && !x->skip && best_rdc.rdcost > inter_mode_thresh &&
2522        bsize <= cpi->sf.max_intra_bsize && !x->skip_low_source_sad &&
2523        !x->lowvar_highsumdiff)) {
2524     struct estimate_block_intra_args args = { cpi, x, DC_PRED, 1, 0 };
2525     int64_t this_sse = INT64_MAX;
2526     int i;
2527     PRED_BUFFER *const best_pred = best_pickmode.best_pred;
2528     TX_SIZE intra_tx_size =
2529         VPXMIN(max_txsize_lookup[bsize],
2530                tx_mode_to_biggest_tx_size[cpi->common.tx_mode]);
2531 
2532     if (reuse_inter_pred && best_pred != NULL) {
2533       if (best_pred->data == orig_dst.buf) {
2534         this_mode_pred = &tmp[get_pred_buffer(tmp, 3)];
2535 #if CONFIG_VP9_HIGHBITDEPTH
2536         if (cm->use_highbitdepth)
2537           vpx_highbd_convolve_copy(
2538               CONVERT_TO_SHORTPTR(best_pred->data), best_pred->stride,
2539               CONVERT_TO_SHORTPTR(this_mode_pred->data), this_mode_pred->stride,
2540               NULL, 0, 0, 0, 0, bw, bh, xd->bd);
2541         else
2542           vpx_convolve_copy(best_pred->data, best_pred->stride,
2543                             this_mode_pred->data, this_mode_pred->stride, NULL,
2544                             0, 0, 0, 0, bw, bh);
2545 #else
2546         vpx_convolve_copy(best_pred->data, best_pred->stride,
2547                           this_mode_pred->data, this_mode_pred->stride, NULL, 0,
2548                           0, 0, 0, bw, bh);
2549 #endif  // CONFIG_VP9_HIGHBITDEPTH
2550         best_pickmode.best_pred = this_mode_pred;
2551       }
2552     }
2553     pd->dst = orig_dst;
2554 
2555     for (i = 0; i < 4; ++i) {
2556       const PREDICTION_MODE this_mode = intra_mode_list[i];
2557       THR_MODES mode_index = mode_idx[INTRA_FRAME][mode_offset(this_mode)];
2558       int mode_rd_thresh = rd_threshes[mode_index];
2559       // For spatially flat blocks, under short_circuit_flat_blocks flag:
2560       // only check DC mode for stationary blocks, otherwise also check
2561       // H and V mode.
2562       if (sf->short_circuit_flat_blocks && x->source_variance == 0 &&
2563           ((x->zero_temp_sad_source && this_mode != DC_PRED) || i > 2)) {
2564         continue;
2565       }
2566 
2567       if (!((1 << this_mode) & cpi->sf.intra_y_mode_bsize_mask[bsize]))
2568         continue;
2569 
2570       if (cpi->sf.rt_intra_dc_only_low_content && this_mode != DC_PRED &&
2571           x->content_state_sb != kVeryHighSad)
2572         continue;
2573 
2574       if ((cpi->sf.adaptive_rd_thresh_row_mt &&
2575            rd_less_than_thresh_row_mt(best_rdc.rdcost, mode_rd_thresh,
2576                                       &rd_thresh_freq_fact[mode_index])) ||
2577           (!cpi->sf.adaptive_rd_thresh_row_mt &&
2578            rd_less_than_thresh(best_rdc.rdcost, mode_rd_thresh,
2579                                &rd_thresh_freq_fact[mode_index]))) {
2580         // Avoid this early exit for screen on base layer, for scene
2581         // changes or high motion frames.
2582         if (cpi->oxcf.content != VP9E_CONTENT_SCREEN ||
2583             svc->spatial_layer_id > 0 ||
2584             (!scene_change_detected && !svc->high_num_blocks_with_motion))
2585           continue;
2586       }
2587 
2588       mi->mode = this_mode;
2589       mi->ref_frame[0] = INTRA_FRAME;
2590       this_rdc.dist = this_rdc.rate = 0;
2591       args.mode = this_mode;
2592       args.skippable = 1;
2593       args.rdc = &this_rdc;
2594       mi->tx_size = intra_tx_size;
2595 
2596       compute_intra_yprediction(this_mode, bsize, x, xd);
2597       model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc.rate, &this_rdc.dist,
2598                         &var_y, &sse_y, 1);
2599       block_yrd(cpi, x, &this_rdc, &args.skippable, &this_sse, bsize,
2600                 VPXMIN(mi->tx_size, TX_16X16), 1, 1);
2601 
2602       // Check skip cost here since skippable is not set for for uv, this
2603       // mirrors the behavior used by inter
2604       if (args.skippable) {
2605         x->skip_txfm[0] = SKIP_TXFM_AC_DC;
2606         this_rdc.rate = vp9_cost_bit(vp9_get_skip_prob(&cpi->common, xd), 1);
2607       } else {
2608         x->skip_txfm[0] = SKIP_TXFM_NONE;
2609         this_rdc.rate += vp9_cost_bit(vp9_get_skip_prob(&cpi->common, xd), 0);
2610       }
2611       // Inter and intra RD will mismatch in scale for non-screen content.
2612       if (cpi->oxcf.content == VP9E_CONTENT_SCREEN) {
2613         if (x->color_sensitivity[0])
2614           vp9_foreach_transformed_block_in_plane(xd, bsize, 1,
2615                                                  estimate_block_intra, &args);
2616         if (x->color_sensitivity[1])
2617           vp9_foreach_transformed_block_in_plane(xd, bsize, 2,
2618                                                  estimate_block_intra, &args);
2619       }
2620       this_rdc.rate += cpi->mbmode_cost[this_mode];
2621       this_rdc.rate += ref_frame_cost[INTRA_FRAME];
2622       this_rdc.rate += intra_cost_penalty;
2623       this_rdc.rdcost =
2624           RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
2625 
2626       if (this_rdc.rdcost < best_rdc.rdcost) {
2627         best_rdc = this_rdc;
2628         best_pickmode.best_mode = this_mode;
2629         best_pickmode.best_intra_tx_size = mi->tx_size;
2630         best_pickmode.best_ref_frame = INTRA_FRAME;
2631         best_pickmode.best_second_ref_frame = NO_REF_FRAME;
2632         mi->uv_mode = this_mode;
2633         mi->mv[0].as_int = INVALID_MV;
2634         mi->mv[1].as_int = INVALID_MV;
2635         best_pickmode.best_mode_skip_txfm = x->skip_txfm[0];
2636       }
2637     }
2638 
2639     // Reset mb_mode_info to the best inter mode.
2640     if (best_pickmode.best_ref_frame != INTRA_FRAME) {
2641       mi->tx_size = best_pickmode.best_tx_size;
2642     } else {
2643       mi->tx_size = best_pickmode.best_intra_tx_size;
2644     }
2645   }
2646 
2647   pd->dst = orig_dst;
2648   mi->mode = best_pickmode.best_mode;
2649   mi->ref_frame[0] = best_pickmode.best_ref_frame;
2650   mi->ref_frame[1] = best_pickmode.best_second_ref_frame;
2651   x->skip_txfm[0] = best_pickmode.best_mode_skip_txfm;
2652 
2653   if (!is_inter_block(mi)) {
2654     mi->interp_filter = SWITCHABLE_FILTERS;
2655   }
2656 
2657   if (reuse_inter_pred && best_pickmode.best_pred != NULL) {
2658     PRED_BUFFER *const best_pred = best_pickmode.best_pred;
2659     if (best_pred->data != orig_dst.buf && is_inter_mode(mi->mode)) {
2660 #if CONFIG_VP9_HIGHBITDEPTH
2661       if (cm->use_highbitdepth)
2662         vpx_highbd_convolve_copy(
2663             CONVERT_TO_SHORTPTR(best_pred->data), best_pred->stride,
2664             CONVERT_TO_SHORTPTR(pd->dst.buf), pd->dst.stride, NULL, 0, 0, 0, 0,
2665             bw, bh, xd->bd);
2666       else
2667         vpx_convolve_copy(best_pred->data, best_pred->stride, pd->dst.buf,
2668                           pd->dst.stride, NULL, 0, 0, 0, 0, bw, bh);
2669 #else
2670       vpx_convolve_copy(best_pred->data, best_pred->stride, pd->dst.buf,
2671                         pd->dst.stride, NULL, 0, 0, 0, 0, bw, bh);
2672 #endif  // CONFIG_VP9_HIGHBITDEPTH
2673     }
2674   }
2675 
2676 #if CONFIG_VP9_TEMPORAL_DENOISING
2677   if (cpi->oxcf.noise_sensitivity > 0 && cpi->resize_pending == 0 &&
2678       denoise_svc_pickmode && cpi->denoiser.denoising_level > kDenLowLow &&
2679       cpi->denoiser.reset == 0) {
2680     VP9_DENOISER_DECISION decision = COPY_BLOCK;
2681     ctx->sb_skip_denoising = 0;
2682     // TODO(marpan): There is an issue with denoising when the
2683     // superblock partitioning scheme is based on the pickmode.
2684     // Remove this condition when the issue is resolved.
2685     if (x->sb_pickmode_part) ctx->sb_skip_denoising = 1;
2686     vp9_pickmode_ctx_den_update(&ctx_den, zero_last_cost_orig, ref_frame_cost,
2687                                 frame_mv, reuse_inter_pred, &best_pickmode);
2688     vp9_denoiser_denoise(cpi, x, mi_row, mi_col, bsize, ctx, &decision,
2689                          gf_temporal_ref);
2690     if (denoise_recheck_zeromv)
2691       recheck_zeromv_after_denoising(cpi, mi, x, xd, decision, &ctx_den,
2692                                      yv12_mb, &best_rdc, bsize, mi_row, mi_col);
2693     best_pickmode.best_ref_frame = ctx_den.best_ref_frame;
2694   }
2695 #endif
2696 
2697   if (best_pickmode.best_ref_frame == ALTREF_FRAME ||
2698       best_pickmode.best_second_ref_frame == ALTREF_FRAME)
2699     x->arf_frame_usage++;
2700   else if (best_pickmode.best_ref_frame != INTRA_FRAME)
2701     x->lastgolden_frame_usage++;
2702 
2703   if (cpi->sf.adaptive_rd_thresh) {
2704     THR_MODES best_mode_idx =
2705         mode_idx[best_pickmode.best_ref_frame][mode_offset(mi->mode)];
2706 
2707     if (best_pickmode.best_ref_frame == INTRA_FRAME) {
2708       // Only consider the modes that are included in the intra_mode_list.
2709       int intra_modes = sizeof(intra_mode_list) / sizeof(PREDICTION_MODE);
2710       int i;
2711 
2712       // TODO(yunqingwang): Check intra mode mask and only update freq_fact
2713       // for those valid modes.
2714       for (i = 0; i < intra_modes; i++) {
2715         if (cpi->sf.adaptive_rd_thresh_row_mt)
2716           update_thresh_freq_fact_row_mt(cpi, tile_data, x->source_variance,
2717                                          thresh_freq_fact_idx, INTRA_FRAME,
2718                                          best_mode_idx, intra_mode_list[i]);
2719         else
2720           update_thresh_freq_fact(cpi, tile_data, x->source_variance, bsize,
2721                                   INTRA_FRAME, best_mode_idx,
2722                                   intra_mode_list[i]);
2723       }
2724     } else {
2725       for (ref_frame = LAST_FRAME; ref_frame <= GOLDEN_FRAME; ++ref_frame) {
2726         PREDICTION_MODE this_mode;
2727         if (best_pickmode.best_ref_frame != ref_frame) continue;
2728         for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
2729           if (cpi->sf.adaptive_rd_thresh_row_mt)
2730             update_thresh_freq_fact_row_mt(cpi, tile_data, x->source_variance,
2731                                            thresh_freq_fact_idx, ref_frame,
2732                                            best_mode_idx, this_mode);
2733           else
2734             update_thresh_freq_fact(cpi, tile_data, x->source_variance, bsize,
2735                                     ref_frame, best_mode_idx, this_mode);
2736         }
2737       }
2738     }
2739   }
2740 
2741   *rd_cost = best_rdc;
2742 }
2743 
vp9_pick_inter_mode_sub8x8(VP9_COMP * cpi,MACROBLOCK * x,int mi_row,int mi_col,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)2744 void vp9_pick_inter_mode_sub8x8(VP9_COMP *cpi, MACROBLOCK *x, int mi_row,
2745                                 int mi_col, RD_COST *rd_cost, BLOCK_SIZE bsize,
2746                                 PICK_MODE_CONTEXT *ctx) {
2747   VP9_COMMON *const cm = &cpi->common;
2748   SPEED_FEATURES *const sf = &cpi->sf;
2749   MACROBLOCKD *const xd = &x->e_mbd;
2750   MODE_INFO *const mi = xd->mi[0];
2751   MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2752   const struct segmentation *const seg = &cm->seg;
2753   MV_REFERENCE_FRAME ref_frame, second_ref_frame = NO_REF_FRAME;
2754   MV_REFERENCE_FRAME best_ref_frame = NO_REF_FRAME;
2755   unsigned char segment_id = mi->segment_id;
2756   struct buf_2d yv12_mb[4][MAX_MB_PLANE];
2757   int64_t best_rd = INT64_MAX;
2758   b_mode_info bsi[MAX_REF_FRAMES][4];
2759   int ref_frame_skip_mask = 0;
2760   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2761   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2762   int idx, idy;
2763 
2764   x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
2765   ctx->pred_pixel_ready = 0;
2766 
2767   for (ref_frame = LAST_FRAME; ref_frame <= GOLDEN_FRAME; ++ref_frame) {
2768     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
2769     int_mv dummy_mv[2];
2770     x->pred_mv_sad[ref_frame] = INT_MAX;
2771 
2772     if ((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) &&
2773         (yv12 != NULL)) {
2774       int_mv *const candidates = mbmi_ext->ref_mvs[ref_frame];
2775       const struct scale_factors *const ref_sf =
2776           &cm->frame_refs[ref_frame - 1].sf;
2777       vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, ref_sf,
2778                            ref_sf);
2779       vp9_find_mv_refs(cm, xd, xd->mi[0], ref_frame, candidates, mi_row, mi_col,
2780                        mbmi_ext->mode_context);
2781 
2782       vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
2783                             &dummy_mv[0], &dummy_mv[1]);
2784     } else {
2785       ref_frame_skip_mask |= (1 << ref_frame);
2786     }
2787   }
2788 
2789   mi->sb_type = bsize;
2790   mi->tx_size = TX_4X4;
2791   mi->uv_mode = DC_PRED;
2792   mi->ref_frame[0] = LAST_FRAME;
2793   mi->ref_frame[1] = NO_REF_FRAME;
2794   mi->interp_filter =
2795       cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
2796 
2797   for (ref_frame = LAST_FRAME; ref_frame <= GOLDEN_FRAME; ++ref_frame) {
2798     int64_t this_rd = 0;
2799     int plane;
2800 
2801     if (ref_frame_skip_mask & (1 << ref_frame)) continue;
2802 
2803 #if CONFIG_BETTER_HW_COMPATIBILITY
2804     if ((bsize == BLOCK_8X4 || bsize == BLOCK_4X8) && ref_frame > INTRA_FRAME &&
2805         vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf))
2806       continue;
2807 #endif
2808 
2809     // TODO(jingning, agrange): Scaling reference frame not supported for
2810     // sub8x8 blocks. Is this supported now?
2811     if (ref_frame > INTRA_FRAME &&
2812         vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf))
2813       continue;
2814 
2815     // If the segment reference frame feature is enabled....
2816     // then do nothing if the current ref frame is not allowed..
2817     if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
2818         get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame)
2819       continue;
2820 
2821     mi->ref_frame[0] = ref_frame;
2822     x->skip = 0;
2823     set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
2824 
2825     // Select prediction reference frames.
2826     for (plane = 0; plane < MAX_MB_PLANE; plane++)
2827       xd->plane[plane].pre[0] = yv12_mb[ref_frame][plane];
2828 
2829     for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
2830       for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
2831         int_mv b_mv[MB_MODE_COUNT];
2832         int64_t b_best_rd = INT64_MAX;
2833         const int i = idy * 2 + idx;
2834         PREDICTION_MODE this_mode;
2835         RD_COST this_rdc;
2836         unsigned int var_y, sse_y;
2837 
2838         struct macroblock_plane *p = &x->plane[0];
2839         struct macroblockd_plane *pd = &xd->plane[0];
2840 
2841         const struct buf_2d orig_src = p->src;
2842         const struct buf_2d orig_dst = pd->dst;
2843         struct buf_2d orig_pre[2];
2844         memcpy(orig_pre, xd->plane[0].pre, sizeof(orig_pre));
2845 
2846         // set buffer pointers for sub8x8 motion search.
2847         p->src.buf =
2848             &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
2849         pd->dst.buf =
2850             &pd->dst.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->dst.stride)];
2851         pd->pre[0].buf =
2852             &pd->pre[0]
2853                  .buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[0].stride)];
2854 
2855         b_mv[ZEROMV].as_int = 0;
2856         b_mv[NEWMV].as_int = INVALID_MV;
2857         vp9_append_sub8x8_mvs_for_idx(cm, xd, i, 0, mi_row, mi_col,
2858                                       &b_mv[NEARESTMV], &b_mv[NEARMV],
2859                                       mbmi_ext->mode_context);
2860 
2861         for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
2862           int b_rate = 0;
2863           xd->mi[0]->bmi[i].as_mv[0].as_int = b_mv[this_mode].as_int;
2864 
2865           if (this_mode == NEWMV) {
2866             const int step_param = cpi->sf.mv.fullpel_search_step_param;
2867             MV mvp_full;
2868             MV tmp_mv;
2869             int cost_list[5];
2870             const MvLimits tmp_mv_limits = x->mv_limits;
2871             uint32_t dummy_dist;
2872 
2873             if (i == 0) {
2874               mvp_full.row = b_mv[NEARESTMV].as_mv.row >> 3;
2875               mvp_full.col = b_mv[NEARESTMV].as_mv.col >> 3;
2876             } else {
2877               mvp_full.row = xd->mi[0]->bmi[0].as_mv[0].as_mv.row >> 3;
2878               mvp_full.col = xd->mi[0]->bmi[0].as_mv[0].as_mv.col >> 3;
2879             }
2880 
2881             vp9_set_mv_search_range(&x->mv_limits,
2882                                     &mbmi_ext->ref_mvs[ref_frame][0].as_mv);
2883 
2884             vp9_full_pixel_search(
2885                 cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method,
2886                 x->sadperbit4, cond_cost_list(cpi, cost_list),
2887                 &mbmi_ext->ref_mvs[ref_frame][0].as_mv, &tmp_mv, INT_MAX, 0);
2888 
2889             x->mv_limits = tmp_mv_limits;
2890 
2891             // calculate the bit cost on motion vector
2892             mvp_full.row = tmp_mv.row * 8;
2893             mvp_full.col = tmp_mv.col * 8;
2894 
2895             b_rate += vp9_mv_bit_cost(
2896                 &mvp_full, &mbmi_ext->ref_mvs[ref_frame][0].as_mv,
2897                 x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2898 
2899             b_rate += cpi->inter_mode_cost[x->mbmi_ext->mode_context[ref_frame]]
2900                                           [INTER_OFFSET(NEWMV)];
2901             if (RDCOST(x->rdmult, x->rddiv, b_rate, 0) > b_best_rd) continue;
2902 
2903             cpi->find_fractional_mv_step(
2904                 x, &tmp_mv, &mbmi_ext->ref_mvs[ref_frame][0].as_mv,
2905                 cpi->common.allow_high_precision_mv, x->errorperbit,
2906                 &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop,
2907                 cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list),
2908                 x->nmvjointcost, x->mvcost, &dummy_dist,
2909                 &x->pred_sse[ref_frame], NULL, 0, 0,
2910                 cpi->sf.use_accurate_subpel_search);
2911 
2912             xd->mi[0]->bmi[i].as_mv[0].as_mv = tmp_mv;
2913           } else {
2914             b_rate += cpi->inter_mode_cost[x->mbmi_ext->mode_context[ref_frame]]
2915                                           [INTER_OFFSET(this_mode)];
2916           }
2917 
2918 #if CONFIG_VP9_HIGHBITDEPTH
2919           if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2920             vp9_highbd_build_inter_predictor(
2921                 CONVERT_TO_SHORTPTR(pd->pre[0].buf), pd->pre[0].stride,
2922                 CONVERT_TO_SHORTPTR(pd->dst.buf), pd->dst.stride,
2923                 &xd->mi[0]->bmi[i].as_mv[0].as_mv, &xd->block_refs[0]->sf,
2924                 4 * num_4x4_blocks_wide, 4 * num_4x4_blocks_high, 0,
2925                 vp9_filter_kernels[mi->interp_filter], MV_PRECISION_Q3,
2926                 mi_col * MI_SIZE + 4 * (i & 0x01),
2927                 mi_row * MI_SIZE + 4 * (i >> 1), xd->bd);
2928           } else {
2929 #endif
2930             vp9_build_inter_predictor(
2931                 pd->pre[0].buf, pd->pre[0].stride, pd->dst.buf, pd->dst.stride,
2932                 &xd->mi[0]->bmi[i].as_mv[0].as_mv, &xd->block_refs[0]->sf,
2933                 4 * num_4x4_blocks_wide, 4 * num_4x4_blocks_high, 0,
2934                 vp9_filter_kernels[mi->interp_filter], MV_PRECISION_Q3,
2935                 mi_col * MI_SIZE + 4 * (i & 0x01),
2936                 mi_row * MI_SIZE + 4 * (i >> 1));
2937 
2938 #if CONFIG_VP9_HIGHBITDEPTH
2939           }
2940 #endif
2941 
2942           model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc.rate, &this_rdc.dist,
2943                             &var_y, &sse_y, 0);
2944 
2945           this_rdc.rate += b_rate;
2946           this_rdc.rdcost =
2947               RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
2948           if (this_rdc.rdcost < b_best_rd) {
2949             b_best_rd = this_rdc.rdcost;
2950             bsi[ref_frame][i].as_mode = this_mode;
2951             bsi[ref_frame][i].as_mv[0].as_mv = xd->mi[0]->bmi[i].as_mv[0].as_mv;
2952           }
2953         }  // mode search
2954 
2955         // restore source and prediction buffer pointers.
2956         p->src = orig_src;
2957         pd->pre[0] = orig_pre[0];
2958         pd->dst = orig_dst;
2959         this_rd += b_best_rd;
2960 
2961         xd->mi[0]->bmi[i] = bsi[ref_frame][i];
2962         if (num_4x4_blocks_wide > 1) xd->mi[0]->bmi[i + 1] = xd->mi[0]->bmi[i];
2963         if (num_4x4_blocks_high > 1) xd->mi[0]->bmi[i + 2] = xd->mi[0]->bmi[i];
2964       }
2965     }  // loop through sub8x8 blocks
2966 
2967     if (this_rd < best_rd) {
2968       best_rd = this_rd;
2969       best_ref_frame = ref_frame;
2970     }
2971   }  // reference frames
2972 
2973   mi->tx_size = TX_4X4;
2974   mi->ref_frame[0] = best_ref_frame;
2975   for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
2976     for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
2977       const int block = idy * 2 + idx;
2978       xd->mi[0]->bmi[block] = bsi[best_ref_frame][block];
2979       if (num_4x4_blocks_wide > 1)
2980         xd->mi[0]->bmi[block + 1] = bsi[best_ref_frame][block];
2981       if (num_4x4_blocks_high > 1)
2982         xd->mi[0]->bmi[block + 2] = bsi[best_ref_frame][block];
2983     }
2984   }
2985   mi->mode = xd->mi[0]->bmi[3].as_mode;
2986   ctx->mic = *(xd->mi[0]);
2987   ctx->mbmi_ext = *x->mbmi_ext;
2988   ctx->skip_txfm[0] = SKIP_TXFM_NONE;
2989   ctx->skip = 0;
2990   // Dummy assignment for speed -5. No effect in speed -6.
2991   rd_cost->rdcost = best_rd;
2992 }
2993