• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10 
11  */
12 
13 #include <assert.h>
14 #include <limits.h>
15 #include <math.h>
16 #include <stdio.h>
17 
18 #include "av1/common/reconinter.h"
19 #include "av1/common/reconintra.h"
20 
21 #include "av1/encoder/encodemv.h"
22 #include "av1/encoder/intra_mode_search.h"
23 #include "av1/encoder/model_rd.h"
24 #include "av1/encoder/motion_search_facade.h"
25 #include "av1/encoder/nonrd_opt.h"
26 #include "av1/encoder/reconinter_enc.h"
27 #include "av1/encoder/var_based_part.h"
28 
early_term_inter_search_with_sse(int early_term_idx,BLOCK_SIZE bsize,int64_t this_sse,int64_t best_sse,PREDICTION_MODE this_mode)29 static INLINE int early_term_inter_search_with_sse(int early_term_idx,
30                                                    BLOCK_SIZE bsize,
31                                                    int64_t this_sse,
32                                                    int64_t best_sse,
33                                                    PREDICTION_MODE this_mode) {
34   // Aggressiveness to terminate inter mode search early is adjusted based on
35   // speed and block size.
36   static const double early_term_thresh[4][4] = { { 0.65, 0.65, 0.65, 0.7 },
37                                                   { 0.6, 0.65, 0.85, 0.9 },
38                                                   { 0.5, 0.5, 0.55, 0.6 },
39                                                   { 0.6, 0.75, 0.85, 0.85 } };
40   static const double early_term_thresh_newmv_nearestmv[4] = { 0.3, 0.3, 0.3,
41                                                                0.3 };
42 
43   const int size_group = size_group_lookup[bsize];
44   assert(size_group < 4);
45   assert((early_term_idx > 0) && (early_term_idx < EARLY_TERM_INDICES));
46   const double threshold =
47       ((early_term_idx == EARLY_TERM_IDX_4) &&
48        (this_mode == NEWMV || this_mode == NEARESTMV))
49           ? early_term_thresh_newmv_nearestmv[size_group]
50           : early_term_thresh[early_term_idx - 1][size_group];
51 
52   // Terminate inter mode search early based on best sse so far.
53   if ((early_term_idx > 0) && (threshold * this_sse > best_sse)) {
54     return 1;
55   }
56   return 0;
57 }
58 
init_best_pickmode(BEST_PICKMODE * bp)59 static INLINE void init_best_pickmode(BEST_PICKMODE *bp) {
60   bp->best_sse = INT64_MAX;
61   bp->best_mode = NEARESTMV;
62   bp->best_ref_frame = LAST_FRAME;
63   bp->best_second_ref_frame = NONE_FRAME;
64   bp->best_tx_size = TX_8X8;
65   bp->tx_type = DCT_DCT;
66   bp->best_pred_filter = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
67   bp->best_mode_skip_txfm = 0;
68   bp->best_mode_initial_skip_flag = 0;
69   bp->best_pred = NULL;
70   bp->best_motion_mode = SIMPLE_TRANSLATION;
71   bp->num_proj_ref = 0;
72   av1_zero(bp->wm_params);
73   av1_zero(bp->pmi);
74 }
75 
76 // Copy best inter mode parameters to best_pickmode
update_search_state_nonrd(InterModeSearchStateNonrd * search_state,MB_MODE_INFO * const mi,TxfmSearchInfo * txfm_info,RD_STATS * nonskip_rdc,PICK_MODE_CONTEXT * ctx,PREDICTION_MODE this_best_mode,const int64_t sse_y)77 static INLINE void update_search_state_nonrd(
78     InterModeSearchStateNonrd *search_state, MB_MODE_INFO *const mi,
79     TxfmSearchInfo *txfm_info, RD_STATS *nonskip_rdc, PICK_MODE_CONTEXT *ctx,
80     PREDICTION_MODE this_best_mode, const int64_t sse_y) {
81   BEST_PICKMODE *const best_pickmode = &search_state->best_pickmode;
82 
83   best_pickmode->best_sse = sse_y;
84   best_pickmode->best_mode = this_best_mode;
85   best_pickmode->best_motion_mode = mi->motion_mode;
86   best_pickmode->wm_params = mi->wm_params;
87   best_pickmode->num_proj_ref = mi->num_proj_ref;
88   best_pickmode->best_pred_filter = mi->interp_filters;
89   best_pickmode->best_tx_size = mi->tx_size;
90   best_pickmode->best_ref_frame = mi->ref_frame[0];
91   best_pickmode->best_second_ref_frame = mi->ref_frame[1];
92   best_pickmode->best_mode_skip_txfm = search_state->this_rdc.skip_txfm;
93   best_pickmode->best_mode_initial_skip_flag =
94       (nonskip_rdc->rate == INT_MAX && search_state->this_rdc.skip_txfm);
95   if (!best_pickmode->best_mode_skip_txfm) {
96     memcpy(ctx->blk_skip, txfm_info->blk_skip,
97            sizeof(txfm_info->blk_skip[0]) * ctx->num_4x4_blk);
98   }
99 }
100 
subpel_select(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int_mv * mv,MV ref_mv,FULLPEL_MV start_mv,bool fullpel_performed_well)101 static INLINE int subpel_select(AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
102                                 int_mv *mv, MV ref_mv, FULLPEL_MV start_mv,
103                                 bool fullpel_performed_well) {
104   const int frame_lowmotion = cpi->rc.avg_frame_low_motion;
105   const int reduce_mv_pel_precision_highmotion =
106       cpi->sf.rt_sf.reduce_mv_pel_precision_highmotion;
107 
108   // Reduce MV precision for higher int MV value & frame-level motion
109   if (reduce_mv_pel_precision_highmotion >= 3) {
110     int mv_thresh = 4;
111     const int is_low_resoln =
112         (cpi->common.width * cpi->common.height <= 320 * 240);
113     mv_thresh = (bsize > BLOCK_32X32) ? 2 : (bsize > BLOCK_16X16) ? 4 : 6;
114     if (frame_lowmotion > 0 && frame_lowmotion < 40) mv_thresh = 12;
115     mv_thresh = (is_low_resoln) ? mv_thresh >> 1 : mv_thresh;
116     if (abs(mv->as_fullmv.row) >= mv_thresh ||
117         abs(mv->as_fullmv.col) >= mv_thresh)
118       return HALF_PEL;
119   } else if (reduce_mv_pel_precision_highmotion >= 1) {
120     int mv_thresh;
121     const int th_vals[2][3] = { { 4, 8, 10 }, { 4, 6, 8 } };
122     const int th_idx = reduce_mv_pel_precision_highmotion - 1;
123     assert(th_idx >= 0 && th_idx < 2);
124     if (frame_lowmotion > 0 && frame_lowmotion < 40)
125       mv_thresh = 12;
126     else
127       mv_thresh = (bsize >= BLOCK_32X32)   ? th_vals[th_idx][0]
128                   : (bsize >= BLOCK_16X16) ? th_vals[th_idx][1]
129                                            : th_vals[th_idx][2];
130     if (abs(mv->as_fullmv.row) >= (mv_thresh << 1) ||
131         abs(mv->as_fullmv.col) >= (mv_thresh << 1))
132       return FULL_PEL;
133     else if (abs(mv->as_fullmv.row) >= mv_thresh ||
134              abs(mv->as_fullmv.col) >= mv_thresh)
135       return HALF_PEL;
136   }
137   // Reduce MV precision for relatively static (e.g. background), low-complex
138   // large areas
139   if (cpi->sf.rt_sf.reduce_mv_pel_precision_lowcomplex >= 2) {
140     const int qband = x->qindex >> (QINDEX_BITS - 2);
141     assert(qband < 4);
142     if (x->content_state_sb.source_sad_nonrd <= kVeryLowSad &&
143         bsize > BLOCK_16X16 && qband != 0) {
144       if (x->source_variance < 500)
145         return FULL_PEL;
146       else if (x->source_variance < 5000)
147         return HALF_PEL;
148     }
149   } else if (cpi->sf.rt_sf.reduce_mv_pel_precision_lowcomplex >= 1) {
150     if (fullpel_performed_well && ref_mv.row == 0 && ref_mv.col == 0 &&
151         start_mv.row == 0 && start_mv.col == 0)
152       return HALF_PEL;
153   }
154   return cpi->sf.mv_sf.subpel_force_stop;
155 }
156 
use_aggressive_subpel_search_method(MACROBLOCK * x,bool use_adaptive_subpel_search,bool fullpel_performed_well)157 static bool use_aggressive_subpel_search_method(MACROBLOCK *x,
158                                                 bool use_adaptive_subpel_search,
159                                                 bool fullpel_performed_well) {
160   if (!use_adaptive_subpel_search) return false;
161   const int qband = x->qindex >> (QINDEX_BITS - 2);
162   assert(qband < 4);
163   if ((qband > 0) && (fullpel_performed_well ||
164                       (x->content_state_sb.source_sad_nonrd <= kLowSad) ||
165                       (x->source_variance < 100)))
166     return true;
167   return false;
168 }
169 
170 /*!\brief Runs Motion Estimation for a specific block and specific ref frame.
171  *
172  * \ingroup nonrd_mode_search
173  * \callgraph
174  * \callergraph
175  * Finds the best Motion Vector by running Motion Estimation for a specific
176  * block and a specific reference frame. Exits early if RDCost of Full Pel part
177  * exceeds best RD Cost fund so far
178  * \param[in]    cpi                      Top-level encoder structure
179  * \param[in]    x                        Pointer to structure holding all the
180  *                                        data for the current macroblock
181  * \param[in]    bsize                    Current block size
182  * \param[in]    tmp_mv                   Pointer to best found New MV
183  * \param[in]    rate_mv                  Pointer to Rate of the best new MV
184  * \param[in]    best_rd_sofar            RD Cost of the best mode found so far
185  * \param[in]    use_base_mv              Flag, indicating that tmp_mv holds
186  *                                        specific MV to start the search with
187  *
188  * \return Returns 0 if ME was terminated after Full Pel Search because too
189  * high RD Cost. Otherwise returns 1. Best New MV is placed into \c tmp_mv.
190  * Rate estimation for this vector is placed to \c rate_mv
191  */
combined_motion_search(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int_mv * tmp_mv,int * rate_mv,int64_t best_rd_sofar,int use_base_mv)192 static int combined_motion_search(AV1_COMP *cpi, MACROBLOCK *x,
193                                   BLOCK_SIZE bsize, int_mv *tmp_mv,
194                                   int *rate_mv, int64_t best_rd_sofar,
195                                   int use_base_mv) {
196   MACROBLOCKD *xd = &x->e_mbd;
197   const AV1_COMMON *cm = &cpi->common;
198   const SPEED_FEATURES *sf = &cpi->sf;
199   MB_MODE_INFO *mi = xd->mi[0];
200   int step_param = (sf->rt_sf.fullpel_search_step_param)
201                        ? sf->rt_sf.fullpel_search_step_param
202                        : cpi->mv_search_params.mv_step_param;
203   FULLPEL_MV start_mv;
204   const int ref = mi->ref_frame[0];
205   const MV ref_mv = av1_get_ref_mv(x, mi->ref_mv_idx).as_mv;
206   MV center_mv;
207   int dis;
208   int rv = 0;
209   int cost_list[5];
210   int search_subpel = 1;
211 
212   start_mv = get_fullmv_from_mv(&ref_mv);
213 
214   if (!use_base_mv)
215     center_mv = ref_mv;
216   else
217     center_mv = tmp_mv->as_mv;
218 
219   const SEARCH_METHODS search_method =
220       av1_get_default_mv_search_method(x, &cpi->sf.mv_sf, bsize);
221   const search_site_config *src_search_sites =
222       av1_get_search_site_config(cpi, x, search_method);
223   FULLPEL_MOTION_SEARCH_PARAMS full_ms_params;
224   FULLPEL_MV_STATS best_mv_stats;
225   av1_make_default_fullpel_ms_params(&full_ms_params, cpi, x, bsize, &center_mv,
226                                      start_mv, src_search_sites, search_method,
227                                      /*fine_search_interval=*/0);
228 
229   const unsigned int full_var_rd = av1_full_pixel_search(
230       start_mv, &full_ms_params, step_param, cond_cost_list(cpi, cost_list),
231       &tmp_mv->as_fullmv, &best_mv_stats, NULL);
232 
233   // calculate the bit cost on motion vector
234   MV mvp_full = get_mv_from_fullmv(&tmp_mv->as_fullmv);
235 
236   *rate_mv = av1_mv_bit_cost(&mvp_full, &ref_mv, x->mv_costs->nmv_joint_cost,
237                              x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
238 
239   // TODO(kyslov) Account for Rate Mode!
240   rv = !(RDCOST(x->rdmult, (*rate_mv), 0) > best_rd_sofar);
241 
242   if (rv && search_subpel) {
243     SUBPEL_MOTION_SEARCH_PARAMS ms_params;
244     av1_make_default_subpel_ms_params(&ms_params, cpi, x, bsize, &ref_mv,
245                                       cost_list);
246     const bool fullpel_performed_well =
247         (bsize == BLOCK_64X64 && full_var_rd * 40 < 62267 * 7) ||
248         (bsize == BLOCK_32X32 && full_var_rd * 8 < 42380) ||
249         (bsize == BLOCK_16X16 && full_var_rd * 8 < 10127);
250     if (sf->rt_sf.reduce_mv_pel_precision_highmotion ||
251         sf->rt_sf.reduce_mv_pel_precision_lowcomplex)
252       ms_params.forced_stop = subpel_select(cpi, x, bsize, tmp_mv, ref_mv,
253                                             start_mv, fullpel_performed_well);
254 
255     MV subpel_start_mv = get_mv_from_fullmv(&tmp_mv->as_fullmv);
256     assert(av1_is_subpelmv_in_range(&ms_params.mv_limits, subpel_start_mv));
257     // adaptively downgrade subpel search method based on block properties
258     if (use_aggressive_subpel_search_method(
259             x, sf->rt_sf.use_adaptive_subpel_search, fullpel_performed_well))
260       av1_find_best_sub_pixel_tree_pruned_more(
261           xd, cm, &ms_params, subpel_start_mv, &best_mv_stats, &tmp_mv->as_mv,
262           &dis, &x->pred_sse[ref], NULL);
263     else
264       cpi->mv_search_params.find_fractional_mv_step(
265           xd, cm, &ms_params, subpel_start_mv, &best_mv_stats, &tmp_mv->as_mv,
266           &dis, &x->pred_sse[ref], NULL);
267     *rate_mv =
268         av1_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->mv_costs->nmv_joint_cost,
269                         x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
270   }
271   // The final MV can not be equal to the reference MV as this will trigger an
272   // assert later. This can happen if both NEAREST and NEAR modes were skipped.
273   rv = (tmp_mv->as_mv.col != ref_mv.col || tmp_mv->as_mv.row != ref_mv.row);
274   return rv;
275 }
276 
277 /*!\brief Searches for the best New Motion Vector.
278  *
279  * \ingroup nonrd_mode_search
280  * \callgraph
281  * \callergraph
282  * Finds the best Motion Vector by doing Motion Estimation. Uses reduced
283  * complexity ME for non-LAST frames or calls \c combined_motion_search
284  * for LAST reference frame
285  * \param[in]    cpi                      Top-level encoder structure
286  * \param[in]    x                        Pointer to structure holding all the
287  *                                        data for the current macroblock
288  * \param[in]    frame_mv                 Array that holds MVs for all modes
289  *                                        and ref frames
290  * \param[in]    ref_frame                Reference frame for which to find
291  *                                        the best New MVs
292  * \param[in]    gf_temporal_ref          Flag, indicating temporal reference
293  *                                        for GOLDEN frame
294  * \param[in]    bsize                    Current block size
295  * \param[in]    mi_row                   Row index in 4x4 units
296  * \param[in]    mi_col                   Column index in 4x4 units
297  * \param[in]    rate_mv                  Pointer to Rate of the best new MV
298  * \param[in]    best_rdc                 Pointer to the RD Cost for the best
299  *                                        mode found so far
300  *
301  * \return Returns -1 if the search was not done, otherwise returns 0.
302  * Best New MV is placed into \c frame_mv array, Rate estimation for this
303  * vector is placed to \c rate_mv
304  */
search_new_mv(AV1_COMP * cpi,MACROBLOCK * x,int_mv frame_mv[][REF_FRAMES],MV_REFERENCE_FRAME ref_frame,int gf_temporal_ref,BLOCK_SIZE bsize,int mi_row,int mi_col,int * rate_mv,RD_STATS * best_rdc)305 static int search_new_mv(AV1_COMP *cpi, MACROBLOCK *x,
306                          int_mv frame_mv[][REF_FRAMES],
307                          MV_REFERENCE_FRAME ref_frame, int gf_temporal_ref,
308                          BLOCK_SIZE bsize, int mi_row, int mi_col, int *rate_mv,
309                          RD_STATS *best_rdc) {
310   MACROBLOCKD *const xd = &x->e_mbd;
311   MB_MODE_INFO *const mi = xd->mi[0];
312   AV1_COMMON *cm = &cpi->common;
313   int_mv *this_ref_frm_newmv = &frame_mv[NEWMV][ref_frame];
314   unsigned int y_sad_zero;
315   if (ref_frame > LAST_FRAME && cpi->oxcf.rc_cfg.mode == AOM_CBR &&
316       gf_temporal_ref) {
317     int tmp_sad;
318     int dis;
319 
320     if (bsize < BLOCK_16X16) return -1;
321 
322     int me_search_size_col = block_size_wide[bsize] >> 1;
323     int me_search_size_row = block_size_high[bsize] >> 1;
324     tmp_sad = av1_int_pro_motion_estimation(
325         cpi, x, bsize, mi_row, mi_col,
326         &x->mbmi_ext.ref_mv_stack[ref_frame][0].this_mv.as_mv, &y_sad_zero,
327         me_search_size_col, me_search_size_row);
328 
329     if (tmp_sad > x->pred_mv_sad[LAST_FRAME]) return -1;
330 
331     this_ref_frm_newmv->as_int = mi->mv[0].as_int;
332     int_mv best_mv = mi->mv[0];
333     best_mv.as_mv.row >>= 3;
334     best_mv.as_mv.col >>= 3;
335     MV ref_mv = av1_get_ref_mv(x, 0).as_mv;
336     this_ref_frm_newmv->as_mv.row >>= 3;
337     this_ref_frm_newmv->as_mv.col >>= 3;
338 
339     SUBPEL_MOTION_SEARCH_PARAMS ms_params;
340     av1_make_default_subpel_ms_params(&ms_params, cpi, x, bsize, &ref_mv, NULL);
341     if (cpi->sf.rt_sf.reduce_mv_pel_precision_highmotion ||
342         cpi->sf.rt_sf.reduce_mv_pel_precision_lowcomplex) {
343       FULLPEL_MV start_mv = { .row = 0, .col = 0 };
344       ms_params.forced_stop =
345           subpel_select(cpi, x, bsize, &best_mv, ref_mv, start_mv, false);
346     }
347     MV start_mv = get_mv_from_fullmv(&best_mv.as_fullmv);
348     assert(av1_is_subpelmv_in_range(&ms_params.mv_limits, start_mv));
349     cpi->mv_search_params.find_fractional_mv_step(
350         xd, cm, &ms_params, start_mv, NULL, &best_mv.as_mv, &dis,
351         &x->pred_sse[ref_frame], NULL);
352     this_ref_frm_newmv->as_int = best_mv.as_int;
353 
354     // When NEWMV is same as ref_mv from the drl, it is preferred to code the
355     // MV as NEARESTMV or NEARMV. In this case, NEWMV needs to be skipped to
356     // avoid an assert failure at a later stage. The scenario can occur if
357     // NEARESTMV was not evaluated for ALTREF.
358     if (this_ref_frm_newmv->as_mv.col == ref_mv.col &&
359         this_ref_frm_newmv->as_mv.row == ref_mv.row)
360       return -1;
361 
362     *rate_mv = av1_mv_bit_cost(&this_ref_frm_newmv->as_mv, &ref_mv,
363                                x->mv_costs->nmv_joint_cost,
364                                x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
365   } else if (!combined_motion_search(cpi, x, bsize, &frame_mv[NEWMV][ref_frame],
366                                      rate_mv, best_rdc->rdcost, 0)) {
367     return -1;
368   }
369 
370   return 0;
371 }
372 
estimate_single_ref_frame_costs(const AV1_COMMON * cm,const MACROBLOCKD * xd,const ModeCosts * mode_costs,int segment_id,BLOCK_SIZE bsize,unsigned int * ref_costs_single)373 static void estimate_single_ref_frame_costs(const AV1_COMMON *cm,
374                                             const MACROBLOCKD *xd,
375                                             const ModeCosts *mode_costs,
376                                             int segment_id, BLOCK_SIZE bsize,
377                                             unsigned int *ref_costs_single) {
378   int seg_ref_active =
379       segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
380   if (seg_ref_active) {
381     memset(ref_costs_single, 0, REF_FRAMES * sizeof(*ref_costs_single));
382   } else {
383     int intra_inter_ctx = av1_get_intra_inter_context(xd);
384     ref_costs_single[INTRA_FRAME] =
385         mode_costs->intra_inter_cost[intra_inter_ctx][0];
386     unsigned int base_cost = mode_costs->intra_inter_cost[intra_inter_ctx][1];
387     if (cm->current_frame.reference_mode == REFERENCE_MODE_SELECT &&
388         is_comp_ref_allowed(bsize)) {
389       const int comp_ref_type_ctx = av1_get_comp_reference_type_context(xd);
390       base_cost += mode_costs->comp_ref_type_cost[comp_ref_type_ctx][1];
391     }
392     ref_costs_single[LAST_FRAME] = base_cost;
393     ref_costs_single[GOLDEN_FRAME] = base_cost;
394     ref_costs_single[ALTREF_FRAME] = base_cost;
395     // add cost for last, golden, altref
396     ref_costs_single[LAST_FRAME] += mode_costs->single_ref_cost[0][0][0];
397     ref_costs_single[GOLDEN_FRAME] += mode_costs->single_ref_cost[0][0][1];
398     ref_costs_single[GOLDEN_FRAME] += mode_costs->single_ref_cost[0][1][0];
399     ref_costs_single[ALTREF_FRAME] += mode_costs->single_ref_cost[0][0][1];
400     ref_costs_single[ALTREF_FRAME] += mode_costs->single_ref_cost[0][2][0];
401   }
402 }
403 
set_force_skip_flag(const AV1_COMP * const cpi,MACROBLOCK * const x,unsigned int sse,int * force_skip)404 static INLINE void set_force_skip_flag(const AV1_COMP *const cpi,
405                                        MACROBLOCK *const x, unsigned int sse,
406                                        int *force_skip) {
407   if (x->txfm_search_params.tx_mode_search_type == TX_MODE_SELECT &&
408       cpi->sf.rt_sf.tx_size_level_based_on_qstep &&
409       cpi->sf.rt_sf.tx_size_level_based_on_qstep >= 2) {
410     const int qstep = x->plane[AOM_PLANE_Y].dequant_QTX[1] >> (x->e_mbd.bd - 5);
411     const unsigned int qstep_sq = qstep * qstep;
412     // If the sse is low for low source variance blocks, mark those as
413     // transform skip.
414     // Note: Though qstep_sq is based on ac qstep, the threshold is kept
415     // low so that reliable early estimate of tx skip can be obtained
416     // through its comparison with sse.
417     if (sse < qstep_sq && x->source_variance < qstep_sq &&
418         x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] == 0 &&
419         x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] == 0)
420       *force_skip = 1;
421   }
422 }
423 
424 #define CAP_TX_SIZE_FOR_BSIZE_GT32(tx_mode_search_type, bsize) \
425   (((tx_mode_search_type) != ONLY_4X4 && (bsize) > BLOCK_32X32) ? true : false)
426 #define TX_SIZE_FOR_BSIZE_GT32 (TX_16X16)
427 
calculate_tx_size(const AV1_COMP * const cpi,BLOCK_SIZE bsize,MACROBLOCK * const x,unsigned int var,unsigned int sse,int * force_skip)428 static TX_SIZE calculate_tx_size(const AV1_COMP *const cpi, BLOCK_SIZE bsize,
429                                  MACROBLOCK *const x, unsigned int var,
430                                  unsigned int sse, int *force_skip) {
431   MACROBLOCKD *const xd = &x->e_mbd;
432   TX_SIZE tx_size;
433   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
434   if (txfm_params->tx_mode_search_type == TX_MODE_SELECT) {
435     int multiplier = 8;
436     unsigned int var_thresh = 0;
437     unsigned int is_high_var = 1;
438     // Use quantizer based thresholds to determine transform size.
439     if (cpi->sf.rt_sf.tx_size_level_based_on_qstep) {
440       const int qband = x->qindex >> (QINDEX_BITS - 2);
441       const int mult[4] = { 8, 7, 6, 5 };
442       assert(qband < 4);
443       multiplier = mult[qband];
444       const int qstep = x->plane[AOM_PLANE_Y].dequant_QTX[1] >> (xd->bd - 5);
445       const unsigned int qstep_sq = qstep * qstep;
446       var_thresh = qstep_sq * 2;
447       if (cpi->sf.rt_sf.tx_size_level_based_on_qstep >= 2) {
448         // If the sse is low for low source variance blocks, mark those as
449         // transform skip.
450         // Note: Though qstep_sq is based on ac qstep, the threshold is kept
451         // low so that reliable early estimate of tx skip can be obtained
452         // through its comparison with sse.
453         if (sse < qstep_sq && x->source_variance < qstep_sq &&
454             x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] == 0 &&
455             x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] == 0)
456           *force_skip = 1;
457         // Further lower transform size based on aq mode only if residual
458         // variance is high.
459         is_high_var = (var >= var_thresh);
460       }
461     }
462     // Choose larger transform size for blocks where dc component is dominant or
463     // the ac component is low.
464     if (sse > ((var * multiplier) >> 2) || (var < var_thresh))
465       tx_size =
466           AOMMIN(max_txsize_lookup[bsize],
467                  tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]);
468     else
469       tx_size = TX_8X8;
470 
471     if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
472         cyclic_refresh_segment_id_boosted(xd->mi[0]->segment_id) && is_high_var)
473       tx_size = TX_8X8;
474     else if (tx_size > TX_16X16)
475       tx_size = TX_16X16;
476   } else {
477     tx_size =
478         AOMMIN(max_txsize_lookup[bsize],
479                tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]);
480   }
481 
482   if (CAP_TX_SIZE_FOR_BSIZE_GT32(txfm_params->tx_mode_search_type, bsize))
483     tx_size = TX_SIZE_FOR_BSIZE_GT32;
484 
485   return AOMMIN(tx_size, TX_16X16);
486 }
487 
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,uint32_t * sse8x8,int * sum8x8,uint32_t * var8x8)488 static void block_variance(const uint8_t *src, int src_stride,
489                            const uint8_t *ref, int ref_stride, int w, int h,
490                            unsigned int *sse, int *sum, int block_size,
491                            uint32_t *sse8x8, int *sum8x8, uint32_t *var8x8) {
492   int k = 0;
493   *sse = 0;
494   *sum = 0;
495 
496   // This function is called for block sizes >= BLOCK_32x32. As per the design
497   // the aom_get_var_sse_sum_8x8_quad() processes four 8x8 blocks (in a 8x32)
498   // per call. Hence the width and height of the block need to be at least 8 and
499   // 32 samples respectively.
500   assert(w >= 32);
501   assert(h >= 8);
502   for (int row = 0; row < h; row += block_size) {
503     for (int col = 0; col < w; col += 32) {
504       aom_get_var_sse_sum_8x8_quad(src + src_stride * row + col, src_stride,
505                                    ref + ref_stride * row + col, ref_stride,
506                                    &sse8x8[k], &sum8x8[k], sse, sum,
507                                    &var8x8[k]);
508       k += 4;
509     }
510   }
511 }
512 
block_variance_16x16_dual(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,uint32_t * sse16x16,uint32_t * var16x16)513 static void block_variance_16x16_dual(const uint8_t *src, int src_stride,
514                                       const uint8_t *ref, int ref_stride, int w,
515                                       int h, unsigned int *sse, int *sum,
516                                       int block_size, uint32_t *sse16x16,
517                                       uint32_t *var16x16) {
518   int k = 0;
519   *sse = 0;
520   *sum = 0;
521   // This function is called for block sizes >= BLOCK_32x32. As per the design
522   // the aom_get_var_sse_sum_16x16_dual() processes four 16x16 blocks (in a
523   // 16x32) per call. Hence the width and height of the block need to be at
524   // least 16 and 32 samples respectively.
525   assert(w >= 32);
526   assert(h >= 16);
527   for (int row = 0; row < h; row += block_size) {
528     for (int col = 0; col < w; col += 32) {
529       aom_get_var_sse_sum_16x16_dual(src + src_stride * row + col, src_stride,
530                                      ref + ref_stride * row + col, ref_stride,
531                                      &sse16x16[k], sse, sum, &var16x16[k]);
532       k += 2;
533     }
534   }
535 }
536 
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)537 static void calculate_variance(int bw, int bh, TX_SIZE tx_size,
538                                unsigned int *sse_i, int *sum_i,
539                                unsigned int *var_o, unsigned int *sse_o,
540                                int *sum_o) {
541   const BLOCK_SIZE unit_size = txsize_to_bsize[tx_size];
542   const int nw = 1 << (bw - b_width_log2_lookup[unit_size]);
543   const int nh = 1 << (bh - b_height_log2_lookup[unit_size]);
544   int row, col, k = 0;
545 
546   for (row = 0; row < nh; row += 2) {
547     for (col = 0; col < nw; col += 2) {
548       sse_o[k] = sse_i[row * nw + col] + sse_i[row * nw + col + 1] +
549                  sse_i[(row + 1) * nw + col] + sse_i[(row + 1) * nw + col + 1];
550       sum_o[k] = sum_i[row * nw + col] + sum_i[row * nw + col + 1] +
551                  sum_i[(row + 1) * nw + col] + sum_i[(row + 1) * nw + col + 1];
552       var_o[k] = sse_o[k] - (uint32_t)(((int64_t)sum_o[k] * sum_o[k]) >>
553                                        (b_width_log2_lookup[unit_size] +
554                                         b_height_log2_lookup[unit_size] + 6));
555       k++;
556     }
557   }
558 }
559 
560 // Adjust the ac_thr according to speed, width, height and normalized sum
ac_thr_factor(int speed,int width,int height,int norm_sum)561 static int ac_thr_factor(int speed, int width, int height, int norm_sum) {
562   if (speed >= 8 && norm_sum < 5) {
563     if (width <= 640 && height <= 480)
564       return 4;
565     else
566       return 2;
567   }
568   return 1;
569 }
570 
571 // Sets early_term flag based on chroma planes prediction
set_early_term_based_on_uv_plane(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,MACROBLOCKD * xd,int mi_row,int mi_col,int * early_term,int num_blk,const unsigned int * sse_tx,const unsigned int * var_tx,int sum,unsigned int var,unsigned int sse)572 static INLINE void set_early_term_based_on_uv_plane(
573     AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, MACROBLOCKD *xd, int mi_row,
574     int mi_col, int *early_term, int num_blk, const unsigned int *sse_tx,
575     const unsigned int *var_tx, int sum, unsigned int var, unsigned int sse) {
576   AV1_COMMON *const cm = &cpi->common;
577   struct macroblock_plane *const p = &x->plane[AOM_PLANE_Y];
578   const uint32_t dc_quant = p->dequant_QTX[0];
579   const uint32_t ac_quant = p->dequant_QTX[1];
580   int64_t dc_thr = dc_quant * dc_quant >> 6;
581   int64_t ac_thr = ac_quant * ac_quant >> 6;
582   const int bw = b_width_log2_lookup[bsize];
583   const int bh = b_height_log2_lookup[bsize];
584   int ac_test = 1;
585   int dc_test = 1;
586   const int norm_sum = abs(sum) >> (bw + bh);
587 
588 #if CONFIG_AV1_TEMPORAL_DENOISING
589   if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
590       cpi->oxcf.speed > 5)
591     ac_thr = av1_scale_acskip_thresh(ac_thr, cpi->denoiser.denoising_level,
592                                      norm_sum, cpi->svc.temporal_layer_id);
593   else
594     ac_thr *= ac_thr_factor(cpi->oxcf.speed, cm->width, cm->height, norm_sum);
595 #else
596   ac_thr *= ac_thr_factor(cpi->oxcf.speed, cm->width, cm->height, norm_sum);
597 
598 #endif
599 
600   if (cpi->sf.rt_sf.increase_source_sad_thresh) {
601     dc_thr = dc_thr << 1;
602     ac_thr = ac_thr << 2;
603   }
604 
605   for (int k = 0; k < num_blk; k++) {
606     // Check if all ac coefficients can be quantized to zero.
607     if (!(var_tx[k] < ac_thr || var == 0)) {
608       ac_test = 0;
609       break;
610     }
611     // Check if dc coefficient can be quantized to zero.
612     if (!(sse_tx[k] - var_tx[k] < dc_thr || sse == var)) {
613       dc_test = 0;
614       break;
615     }
616   }
617 
618   // Check if chroma can be skipped based on ac and dc test flags.
619   if (ac_test && dc_test) {
620     int skip_uv[2] = { 0 };
621     unsigned int var_uv[2];
622     unsigned int sse_uv[2];
623     // Transform skipping test in UV planes.
624     for (int plane = AOM_PLANE_U; plane <= AOM_PLANE_V; plane++) {
625       int j = plane - 1;
626       skip_uv[j] = 1;
627       if (x->color_sensitivity[COLOR_SENS_IDX(plane)]) {
628         skip_uv[j] = 0;
629         struct macroblock_plane *const puv = &x->plane[plane];
630         struct macroblockd_plane *const puvd = &xd->plane[plane];
631         const BLOCK_SIZE uv_bsize = get_plane_block_size(
632             bsize, puvd->subsampling_x, puvd->subsampling_y);
633         // Adjust these thresholds for UV.
634         const int shift_ac = cpi->sf.rt_sf.increase_source_sad_thresh ? 5 : 3;
635         const int shift_dc = cpi->sf.rt_sf.increase_source_sad_thresh ? 4 : 3;
636         const int64_t uv_dc_thr =
637             (puv->dequant_QTX[0] * puv->dequant_QTX[0]) >> shift_dc;
638         const int64_t uv_ac_thr =
639             (puv->dequant_QTX[1] * puv->dequant_QTX[1]) >> shift_ac;
640         av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
641                                       plane, plane);
642         var_uv[j] = cpi->ppi->fn_ptr[uv_bsize].vf(puv->src.buf, puv->src.stride,
643                                                   puvd->dst.buf,
644                                                   puvd->dst.stride, &sse_uv[j]);
645         if ((var_uv[j] < uv_ac_thr || var_uv[j] == 0) &&
646             (sse_uv[j] - var_uv[j] < uv_dc_thr || sse_uv[j] == var_uv[j]))
647           skip_uv[j] = 1;
648         else
649           break;
650       }
651     }
652     if (skip_uv[0] & skip_uv[1]) {
653       *early_term = 1;
654     }
655   }
656 }
657 
calc_rate_dist_block_param(AV1_COMP * cpi,MACROBLOCK * x,RD_STATS * rd_stats,int calculate_rd,int * early_term,BLOCK_SIZE bsize,unsigned int sse)658 static INLINE void calc_rate_dist_block_param(AV1_COMP *cpi, MACROBLOCK *x,
659                                               RD_STATS *rd_stats,
660                                               int calculate_rd, int *early_term,
661                                               BLOCK_SIZE bsize,
662                                               unsigned int sse) {
663   if (calculate_rd) {
664     if (!*early_term) {
665       const int bw = block_size_wide[bsize];
666       const int bh = block_size_high[bsize];
667 
668       model_rd_with_curvfit(cpi, x, bsize, AOM_PLANE_Y, rd_stats->sse, bw * bh,
669                             &rd_stats->rate, &rd_stats->dist);
670     }
671 
672     if (*early_term) {
673       rd_stats->rate = 0;
674       rd_stats->dist = sse << 4;
675     }
676   }
677 }
678 
model_skip_for_sb_y_large_64(AV1_COMP * cpi,BLOCK_SIZE bsize,int mi_row,int mi_col,MACROBLOCK * x,MACROBLOCKD * xd,RD_STATS * rd_stats,int * early_term,int calculate_rd,int64_t best_sse,unsigned int * var_output,unsigned int var_prune_threshold)679 static void model_skip_for_sb_y_large_64(AV1_COMP *cpi, BLOCK_SIZE bsize,
680                                          int mi_row, int mi_col, MACROBLOCK *x,
681                                          MACROBLOCKD *xd, RD_STATS *rd_stats,
682                                          int *early_term, int calculate_rd,
683                                          int64_t best_sse,
684                                          unsigned int *var_output,
685                                          unsigned int var_prune_threshold) {
686   // Note our transform coeffs are 8 times an orthogonal transform.
687   // Hence quantizer step is also 8 times. To get effective quantizer
688   // we need to divide by 8 before sending to modeling function.
689   unsigned int sse;
690   struct macroblock_plane *const p = &x->plane[AOM_PLANE_Y];
691   struct macroblockd_plane *const pd = &xd->plane[AOM_PLANE_Y];
692   int test_skip = 1;
693   unsigned int var;
694   int sum;
695   const int bw = b_width_log2_lookup[bsize];
696   const int bh = b_height_log2_lookup[bsize];
697   unsigned int sse16x16[64] = { 0 };
698   unsigned int var16x16[64] = { 0 };
699   assert(xd->mi[0]->tx_size == TX_16X16);
700   assert(bsize > BLOCK_32X32);
701 
702   // Calculate variance for whole partition, and also save 16x16 blocks'
703   // variance to be used in following transform skipping test.
704   block_variance_16x16_dual(p->src.buf, p->src.stride, pd->dst.buf,
705                             pd->dst.stride, 4 << bw, 4 << bh, &sse, &sum, 16,
706                             sse16x16, var16x16);
707 
708   var = sse - (unsigned int)(((int64_t)sum * sum) >> (bw + bh + 4));
709   if (var_output) {
710     *var_output = var;
711     if (*var_output > var_prune_threshold) {
712       return;
713     }
714   }
715 
716   rd_stats->sse = sse;
717   // Skipping test
718   *early_term = 0;
719   set_force_skip_flag(cpi, x, sse, early_term);
720   // The code below for setting skip flag assumes transform size of at least
721   // 8x8, so force this lower limit on transform.
722   MB_MODE_INFO *const mi = xd->mi[0];
723   if (!calculate_rd && cpi->sf.rt_sf.sse_early_term_inter_search &&
724       early_term_inter_search_with_sse(
725           cpi->sf.rt_sf.sse_early_term_inter_search, bsize, sse, best_sse,
726           mi->mode))
727     test_skip = 0;
728 
729   if (*early_term) test_skip = 0;
730 
731   // Evaluate if the partition block is a skippable block in Y plane.
732   if (test_skip) {
733     const unsigned int *sse_tx = sse16x16;
734     const unsigned int *var_tx = var16x16;
735     const unsigned int num_block = (1 << (bw + bh - 2)) >> 2;
736     set_early_term_based_on_uv_plane(cpi, x, bsize, xd, mi_row, mi_col,
737                                      early_term, num_block, sse_tx, var_tx, sum,
738                                      var, sse);
739   }
740   calc_rate_dist_block_param(cpi, x, rd_stats, calculate_rd, early_term, bsize,
741                              sse);
742 }
743 
model_skip_for_sb_y_large(AV1_COMP * cpi,BLOCK_SIZE bsize,int mi_row,int mi_col,MACROBLOCK * x,MACROBLOCKD * xd,RD_STATS * rd_stats,int * early_term,int calculate_rd,int64_t best_sse,unsigned int * var_output,unsigned int var_prune_threshold)744 static void model_skip_for_sb_y_large(AV1_COMP *cpi, BLOCK_SIZE bsize,
745                                       int mi_row, int mi_col, MACROBLOCK *x,
746                                       MACROBLOCKD *xd, RD_STATS *rd_stats,
747                                       int *early_term, int calculate_rd,
748                                       int64_t best_sse,
749                                       unsigned int *var_output,
750                                       unsigned int var_prune_threshold) {
751   if (x->force_zeromv_skip_for_blk) {
752     *early_term = 1;
753     rd_stats->rate = 0;
754     rd_stats->dist = 0;
755     rd_stats->sse = 0;
756     return;
757   }
758 
759   // For block sizes greater than 32x32, the transform size is always 16x16.
760   // This function avoids calling calculate_variance() for tx_size 16x16 cases
761   // by directly populating variance at tx_size level from
762   // block_variance_16x16_dual() function.
763   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
764   if (CAP_TX_SIZE_FOR_BSIZE_GT32(txfm_params->tx_mode_search_type, bsize)) {
765     xd->mi[0]->tx_size = TX_SIZE_FOR_BSIZE_GT32;
766     model_skip_for_sb_y_large_64(cpi, bsize, mi_row, mi_col, x, xd, rd_stats,
767                                  early_term, calculate_rd, best_sse, var_output,
768                                  var_prune_threshold);
769     return;
770   }
771 
772   // Note our transform coeffs are 8 times an orthogonal transform.
773   // Hence quantizer step is also 8 times. To get effective quantizer
774   // we need to divide by 8 before sending to modeling function.
775   unsigned int sse;
776   struct macroblock_plane *const p = &x->plane[AOM_PLANE_Y];
777   struct macroblockd_plane *const pd = &xd->plane[AOM_PLANE_Y];
778   int test_skip = 1;
779   unsigned int var;
780   int sum;
781 
782   const int bw = b_width_log2_lookup[bsize];
783   const int bh = b_height_log2_lookup[bsize];
784   unsigned int sse8x8[256] = { 0 };
785   int sum8x8[256] = { 0 };
786   unsigned int var8x8[256] = { 0 };
787   TX_SIZE tx_size;
788 
789   // Calculate variance for whole partition, and also save 8x8 blocks' variance
790   // to be used in following transform skipping test.
791   block_variance(p->src.buf, p->src.stride, pd->dst.buf, pd->dst.stride,
792                  4 << bw, 4 << bh, &sse, &sum, 8, sse8x8, sum8x8, var8x8);
793   var = sse - (unsigned int)(((int64_t)sum * sum) >> (bw + bh + 4));
794   if (var_output) {
795     *var_output = var;
796     if (*var_output > var_prune_threshold) {
797       return;
798     }
799   }
800 
801   rd_stats->sse = sse;
802   // Skipping test
803   *early_term = 0;
804   tx_size = calculate_tx_size(cpi, bsize, x, var, sse, early_term);
805   assert(tx_size <= TX_16X16);
806   // The code below for setting skip flag assumes transform size of at least
807   // 8x8, so force this lower limit on transform.
808   if (tx_size < TX_8X8) tx_size = TX_8X8;
809   xd->mi[0]->tx_size = tx_size;
810 
811   MB_MODE_INFO *const mi = xd->mi[0];
812   if (!calculate_rd && cpi->sf.rt_sf.sse_early_term_inter_search &&
813       early_term_inter_search_with_sse(
814           cpi->sf.rt_sf.sse_early_term_inter_search, bsize, sse, best_sse,
815           mi->mode))
816     test_skip = 0;
817 
818   if (*early_term) test_skip = 0;
819 
820   // Evaluate if the partition block is a skippable block in Y plane.
821   if (test_skip) {
822     unsigned int sse16x16[64] = { 0 };
823     int sum16x16[64] = { 0 };
824     unsigned int var16x16[64] = { 0 };
825     const unsigned int *sse_tx = sse8x8;
826     const unsigned int *var_tx = var8x8;
827     unsigned int num_blks = 1 << (bw + bh - 2);
828 
829     if (tx_size >= TX_16X16) {
830       calculate_variance(bw, bh, TX_8X8, sse8x8, sum8x8, var16x16, sse16x16,
831                          sum16x16);
832       sse_tx = sse16x16;
833       var_tx = var16x16;
834       num_blks = num_blks >> 2;
835     }
836     set_early_term_based_on_uv_plane(cpi, x, bsize, xd, mi_row, mi_col,
837                                      early_term, num_blks, sse_tx, var_tx, sum,
838                                      var, sse);
839   }
840   calc_rate_dist_block_param(cpi, x, rd_stats, calculate_rd, early_term, bsize,
841                              sse);
842 }
843 
model_rd_for_sb_y(const AV1_COMP * const cpi,BLOCK_SIZE bsize,MACROBLOCK * x,MACROBLOCKD * xd,RD_STATS * rd_stats,unsigned int * var_out,int calculate_rd,int * early_term)844 static void model_rd_for_sb_y(const AV1_COMP *const cpi, BLOCK_SIZE bsize,
845                               MACROBLOCK *x, MACROBLOCKD *xd,
846                               RD_STATS *rd_stats, unsigned int *var_out,
847                               int calculate_rd, int *early_term) {
848   if (x->force_zeromv_skip_for_blk && early_term != NULL) {
849     *early_term = 1;
850     rd_stats->rate = 0;
851     rd_stats->dist = 0;
852     rd_stats->sse = 0;
853   }
854 
855   // Note our transform coeffs are 8 times an orthogonal transform.
856   // Hence quantizer step is also 8 times. To get effective quantizer
857   // we need to divide by 8 before sending to modeling function.
858   const int ref = xd->mi[0]->ref_frame[0];
859 
860   assert(bsize < BLOCK_SIZES_ALL);
861 
862   struct macroblock_plane *const p = &x->plane[AOM_PLANE_Y];
863   struct macroblockd_plane *const pd = &xd->plane[AOM_PLANE_Y];
864   unsigned int sse;
865   int rate;
866   int64_t dist;
867 
868   unsigned int var = cpi->ppi->fn_ptr[bsize].vf(
869       p->src.buf, p->src.stride, pd->dst.buf, pd->dst.stride, &sse);
870   int force_skip = 0;
871   xd->mi[0]->tx_size = calculate_tx_size(cpi, bsize, x, var, sse, &force_skip);
872   if (var_out) {
873     *var_out = var;
874   }
875 
876   if (calculate_rd && (!force_skip || ref == INTRA_FRAME)) {
877     const int bwide = block_size_wide[bsize];
878     const int bhigh = block_size_high[bsize];
879     model_rd_with_curvfit(cpi, x, bsize, AOM_PLANE_Y, sse, bwide * bhigh, &rate,
880                           &dist);
881   } else {
882     rate = INT_MAX;  // this will be overwritten later with av1_block_yrd
883     dist = INT_MAX;
884   }
885   rd_stats->sse = sse;
886   x->pred_sse[ref] = (unsigned int)AOMMIN(sse, UINT_MAX);
887 
888   if (force_skip && ref > INTRA_FRAME) {
889     rate = 0;
890     dist = (int64_t)sse << 4;
891   }
892 
893   assert(rate >= 0);
894 
895   rd_stats->skip_txfm = (rate == 0);
896   rate = AOMMIN(rate, INT_MAX);
897   rd_stats->rate = rate;
898   rd_stats->dist = dist;
899 }
900 
get_drl_cost(PREDICTION_MODE this_mode,int ref_mv_idx,const MB_MODE_INFO_EXT * mbmi_ext,const int (* const drl_mode_cost0)[2],int8_t ref_frame_type)901 static INLINE int get_drl_cost(PREDICTION_MODE this_mode, int ref_mv_idx,
902                                const MB_MODE_INFO_EXT *mbmi_ext,
903                                const int (*const drl_mode_cost0)[2],
904                                int8_t ref_frame_type) {
905   int cost = 0;
906   if (this_mode == NEWMV || this_mode == NEW_NEWMV) {
907     for (int idx = 0; idx < 2; ++idx) {
908       if (mbmi_ext->ref_mv_count[ref_frame_type] > idx + 1) {
909         uint8_t drl_ctx = av1_drl_ctx(mbmi_ext->weight[ref_frame_type], idx);
910         cost += drl_mode_cost0[drl_ctx][ref_mv_idx != idx];
911         if (ref_mv_idx == idx) return cost;
912       }
913     }
914     return cost;
915   }
916 
917   if (have_nearmv_in_inter_mode(this_mode)) {
918     for (int idx = 1; idx < 3; ++idx) {
919       if (mbmi_ext->ref_mv_count[ref_frame_type] > idx + 1) {
920         uint8_t drl_ctx = av1_drl_ctx(mbmi_ext->weight[ref_frame_type], idx);
921         cost += drl_mode_cost0[drl_ctx][ref_mv_idx != (idx - 1)];
922         if (ref_mv_idx == (idx - 1)) return cost;
923       }
924     }
925     return cost;
926   }
927   return cost;
928 }
929 
cost_mv_ref(const ModeCosts * const mode_costs,PREDICTION_MODE mode,int16_t mode_context)930 static int cost_mv_ref(const ModeCosts *const mode_costs, PREDICTION_MODE mode,
931                        int16_t mode_context) {
932   if (is_inter_compound_mode(mode)) {
933     return mode_costs
934         ->inter_compound_mode_cost[mode_context][INTER_COMPOUND_OFFSET(mode)];
935   }
936 
937   int mode_cost = 0;
938   int16_t mode_ctx = mode_context & NEWMV_CTX_MASK;
939 
940   assert(is_inter_mode(mode));
941 
942   if (mode == NEWMV) {
943     mode_cost = mode_costs->newmv_mode_cost[mode_ctx][0];
944     return mode_cost;
945   } else {
946     mode_cost = mode_costs->newmv_mode_cost[mode_ctx][1];
947     mode_ctx = (mode_context >> GLOBALMV_OFFSET) & GLOBALMV_CTX_MASK;
948 
949     if (mode == GLOBALMV) {
950       mode_cost += mode_costs->zeromv_mode_cost[mode_ctx][0];
951       return mode_cost;
952     } else {
953       mode_cost += mode_costs->zeromv_mode_cost[mode_ctx][1];
954       mode_ctx = (mode_context >> REFMV_OFFSET) & REFMV_CTX_MASK;
955       mode_cost += mode_costs->refmv_mode_cost[mode_ctx][mode != NEARESTMV];
956       return mode_cost;
957     }
958   }
959 }
960 
newmv_diff_bias(MACROBLOCKD * xd,PREDICTION_MODE this_mode,RD_STATS * this_rdc,BLOCK_SIZE bsize,int mv_row,int mv_col,int speed,uint32_t spatial_variance,CONTENT_STATE_SB content_state_sb)961 static void newmv_diff_bias(MACROBLOCKD *xd, PREDICTION_MODE this_mode,
962                             RD_STATS *this_rdc, BLOCK_SIZE bsize, int mv_row,
963                             int mv_col, int speed, uint32_t spatial_variance,
964                             CONTENT_STATE_SB content_state_sb) {
965   // Bias against MVs associated with NEWMV mode that are very different from
966   // top/left neighbors.
967   if (this_mode == NEWMV) {
968     int al_mv_average_row;
969     int al_mv_average_col;
970     int row_diff, col_diff;
971     int above_mv_valid = 0;
972     int left_mv_valid = 0;
973     int above_row = INVALID_MV_ROW_COL, above_col = INVALID_MV_ROW_COL;
974     int left_row = INVALID_MV_ROW_COL, left_col = INVALID_MV_ROW_COL;
975     if (bsize >= BLOCK_64X64 && content_state_sb.source_sad_nonrd != kHighSad &&
976         spatial_variance < 300 &&
977         (mv_row > 16 || mv_row < -16 || mv_col > 16 || mv_col < -16)) {
978       this_rdc->rdcost = this_rdc->rdcost << 2;
979       return;
980     }
981     if (xd->above_mbmi) {
982       above_mv_valid = xd->above_mbmi->mv[0].as_int != INVALID_MV;
983       above_row = xd->above_mbmi->mv[0].as_mv.row;
984       above_col = xd->above_mbmi->mv[0].as_mv.col;
985     }
986     if (xd->left_mbmi) {
987       left_mv_valid = xd->left_mbmi->mv[0].as_int != INVALID_MV;
988       left_row = xd->left_mbmi->mv[0].as_mv.row;
989       left_col = xd->left_mbmi->mv[0].as_mv.col;
990     }
991     if (above_mv_valid && left_mv_valid) {
992       al_mv_average_row = (above_row + left_row + 1) >> 1;
993       al_mv_average_col = (above_col + left_col + 1) >> 1;
994     } else if (above_mv_valid) {
995       al_mv_average_row = above_row;
996       al_mv_average_col = above_col;
997     } else if (left_mv_valid) {
998       al_mv_average_row = left_row;
999       al_mv_average_col = left_col;
1000     } else {
1001       al_mv_average_row = al_mv_average_col = 0;
1002     }
1003     row_diff = al_mv_average_row - mv_row;
1004     col_diff = al_mv_average_col - mv_col;
1005     if (row_diff > 80 || row_diff < -80 || col_diff > 80 || col_diff < -80) {
1006       if (bsize >= BLOCK_32X32)
1007         this_rdc->rdcost = this_rdc->rdcost << 1;
1008       else
1009         this_rdc->rdcost = 5 * this_rdc->rdcost >> 2;
1010     }
1011   } else {
1012     // Bias for speed >= 8 for low spatial variance.
1013     if (speed >= 8 && spatial_variance < 150 &&
1014         (mv_row > 64 || mv_row < -64 || mv_col > 64 || mv_col < -64))
1015       this_rdc->rdcost = 5 * this_rdc->rdcost >> 2;
1016   }
1017 }
1018 
update_thresh_freq_fact(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,MV_REFERENCE_FRAME ref_frame,THR_MODES best_mode_idx,PREDICTION_MODE mode)1019 static INLINE void update_thresh_freq_fact(AV1_COMP *cpi, MACROBLOCK *x,
1020                                            BLOCK_SIZE bsize,
1021                                            MV_REFERENCE_FRAME ref_frame,
1022                                            THR_MODES best_mode_idx,
1023                                            PREDICTION_MODE mode) {
1024   const THR_MODES thr_mode_idx = mode_idx[ref_frame][mode_offset(mode)];
1025   const BLOCK_SIZE min_size = AOMMAX(bsize - 3, BLOCK_4X4);
1026   const BLOCK_SIZE max_size = AOMMIN(bsize + 6, BLOCK_128X128);
1027   for (BLOCK_SIZE bs = min_size; bs <= max_size; bs += 3) {
1028     int *freq_fact = &x->thresh_freq_fact[bs][thr_mode_idx];
1029     if (thr_mode_idx == best_mode_idx) {
1030       *freq_fact -= (*freq_fact >> 4);
1031     } else {
1032       *freq_fact =
1033           AOMMIN(*freq_fact + RD_THRESH_INC,
1034                  cpi->sf.inter_sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT);
1035     }
1036   }
1037 }
1038 
1039 #if CONFIG_AV1_TEMPORAL_DENOISING
av1_pickmode_ctx_den_update(AV1_PICKMODE_CTX_DEN * ctx_den,int64_t zero_last_cost_orig,unsigned int ref_frame_cost[REF_FRAMES],int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],int reuse_inter_pred,BEST_PICKMODE * bp)1040 static void av1_pickmode_ctx_den_update(
1041     AV1_PICKMODE_CTX_DEN *ctx_den, int64_t zero_last_cost_orig,
1042     unsigned int ref_frame_cost[REF_FRAMES],
1043     int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES], int reuse_inter_pred,
1044     BEST_PICKMODE *bp) {
1045   ctx_den->zero_last_cost_orig = zero_last_cost_orig;
1046   ctx_den->ref_frame_cost = ref_frame_cost;
1047   ctx_den->frame_mv = frame_mv;
1048   ctx_den->reuse_inter_pred = reuse_inter_pred;
1049   ctx_den->best_tx_size = bp->best_tx_size;
1050   ctx_den->best_mode = bp->best_mode;
1051   ctx_den->best_ref_frame = bp->best_ref_frame;
1052   ctx_den->best_pred_filter = bp->best_pred_filter;
1053   ctx_den->best_mode_skip_txfm = bp->best_mode_skip_txfm;
1054 }
1055 
recheck_zeromv_after_denoising(AV1_COMP * cpi,MB_MODE_INFO * const mi,MACROBLOCK * x,MACROBLOCKD * const xd,AV1_DENOISER_DECISION decision,AV1_PICKMODE_CTX_DEN * ctx_den,struct buf_2d yv12_mb[4][MAX_MB_PLANE],RD_STATS * best_rdc,BEST_PICKMODE * best_pickmode,BLOCK_SIZE bsize,int mi_row,int mi_col)1056 static void recheck_zeromv_after_denoising(
1057     AV1_COMP *cpi, MB_MODE_INFO *const mi, MACROBLOCK *x, MACROBLOCKD *const xd,
1058     AV1_DENOISER_DECISION decision, AV1_PICKMODE_CTX_DEN *ctx_den,
1059     struct buf_2d yv12_mb[4][MAX_MB_PLANE], RD_STATS *best_rdc,
1060     BEST_PICKMODE *best_pickmode, BLOCK_SIZE bsize, int mi_row, int mi_col) {
1061   // If INTRA or GOLDEN reference was selected, re-evaluate ZEROMV on
1062   // denoised result. Only do this under noise conditions, and if rdcost of
1063   // ZEROMV on original source is not significantly higher than rdcost of best
1064   // mode.
1065   if (cpi->noise_estimate.enabled && cpi->noise_estimate.level > kLow &&
1066       ctx_den->zero_last_cost_orig < (best_rdc->rdcost << 3) &&
1067       ((ctx_den->best_ref_frame == INTRA_FRAME && decision >= FILTER_BLOCK) ||
1068        (ctx_den->best_ref_frame == GOLDEN_FRAME &&
1069         cpi->svc.number_spatial_layers == 1 &&
1070         decision == FILTER_ZEROMV_BLOCK))) {
1071     // Check if we should pick ZEROMV on denoised signal.
1072     AV1_COMMON *const cm = &cpi->common;
1073     RD_STATS this_rdc;
1074     const ModeCosts *mode_costs = &x->mode_costs;
1075     TxfmSearchInfo *txfm_info = &x->txfm_search_info;
1076     MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
1077 
1078     mi->mode = GLOBALMV;
1079     mi->ref_frame[0] = LAST_FRAME;
1080     mi->ref_frame[1] = NONE_FRAME;
1081     set_ref_ptrs(cm, xd, mi->ref_frame[0], NONE_FRAME);
1082     mi->mv[0].as_int = 0;
1083     mi->interp_filters = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
1084     xd->plane[AOM_PLANE_Y].pre[0] = yv12_mb[LAST_FRAME][AOM_PLANE_Y];
1085     av1_enc_build_inter_predictor_y(xd, mi_row, mi_col);
1086     unsigned int var;
1087     model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc, &var, 1, NULL);
1088 
1089     const int16_t mode_ctx =
1090         av1_mode_context_analyzer(mbmi_ext->mode_context, mi->ref_frame);
1091     this_rdc.rate += cost_mv_ref(mode_costs, GLOBALMV, mode_ctx);
1092 
1093     this_rdc.rate += ctx_den->ref_frame_cost[LAST_FRAME];
1094     this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
1095     txfm_info->skip_txfm = this_rdc.skip_txfm;
1096     // Don't switch to ZEROMV if the rdcost for ZEROMV on denoised source
1097     // is higher than best_ref mode (on original source).
1098     if (this_rdc.rdcost > best_rdc->rdcost) {
1099       this_rdc = *best_rdc;
1100       mi->mode = best_pickmode->best_mode;
1101       mi->ref_frame[0] = best_pickmode->best_ref_frame;
1102       set_ref_ptrs(cm, xd, mi->ref_frame[0], NONE_FRAME);
1103       mi->interp_filters = best_pickmode->best_pred_filter;
1104       if (best_pickmode->best_ref_frame == INTRA_FRAME) {
1105         mi->mv[0].as_int = INVALID_MV;
1106       } else {
1107         mi->mv[0].as_int = ctx_den
1108                                ->frame_mv[best_pickmode->best_mode]
1109                                          [best_pickmode->best_ref_frame]
1110                                .as_int;
1111         if (ctx_den->reuse_inter_pred) {
1112           xd->plane[AOM_PLANE_Y].pre[0] = yv12_mb[GOLDEN_FRAME][AOM_PLANE_Y];
1113           av1_enc_build_inter_predictor_y(xd, mi_row, mi_col);
1114         }
1115       }
1116       mi->tx_size = best_pickmode->best_tx_size;
1117       txfm_info->skip_txfm = best_pickmode->best_mode_skip_txfm;
1118     } else {
1119       ctx_den->best_ref_frame = LAST_FRAME;
1120       *best_rdc = this_rdc;
1121     }
1122   }
1123 }
1124 #endif  // CONFIG_AV1_TEMPORAL_DENOISING
1125 
1126 /*!\brief Searches for the best interpolation filter
1127  *
1128  * \ingroup nonrd_mode_search
1129  * \callgraph
1130  * \callergraph
1131  * Iterates through subset of possible interpolation filters (EIGHTTAP_REGULAR,
1132  * EIGTHTAP_SMOOTH, MULTITAP_SHARP, depending on FILTER_SEARCH_SIZE) and selects
1133  * the one that gives lowest RD cost. RD cost is calculated using curvfit model.
1134  * Support for dual filters (different filters in the x & y directions) is
1135  * allowed if sf.interp_sf.disable_dual_filter = 0.
1136  *
1137  * \param[in]    cpi                  Top-level encoder structure
1138  * \param[in]    x                    Pointer to structure holding all the
1139  *                                    data for the current macroblock
1140  * \param[in]    this_rdc             Pointer to calculated RD Cost
1141  * \param[in]    inter_pred_params_sr Pointer to structure holding parameters of
1142                                       inter prediction for single reference
1143  * \param[in]    mi_row               Row index in 4x4 units
1144  * \param[in]    mi_col               Column index in 4x4 units
1145  * \param[in]    tmp_buffer           Pointer to a temporary buffer for
1146  *                                    prediction re-use
1147  * \param[in]    bsize                Current block size
1148  * \param[in]    reuse_inter_pred     Flag, indicating prediction re-use
1149  * \param[out]   this_mode_pred       Pointer to store prediction buffer
1150  *                                    for prediction re-use
1151  * \param[out]   this_early_term      Flag, indicating that transform can be
1152  *                                    skipped
1153  * \param[out]   var                  The residue variance of the current
1154  *                                    predictor.
1155  * \param[in]    use_model_yrd_large  Flag, indicating special logic to handle
1156  *                                    large blocks
1157  * \param[in]    best_sse             Best sse so far.
1158  * \param[in]    is_single_pred       Flag, indicating single mode.
1159  *
1160  * \remark Nothing is returned. Instead, calculated RD cost is placed to
1161  * \c this_rdc and best filter is placed to \c mi->interp_filters. In case
1162  * \c reuse_inter_pred flag is set, this function also outputs
1163  * \c this_mode_pred. Also \c this_early_temp is set if transform can be
1164  * skipped
1165  */
search_filter_ref(AV1_COMP * cpi,MACROBLOCK * x,RD_STATS * this_rdc,InterPredParams * inter_pred_params_sr,int mi_row,int mi_col,PRED_BUFFER * tmp_buffer,BLOCK_SIZE bsize,int reuse_inter_pred,PRED_BUFFER ** this_mode_pred,int * this_early_term,unsigned int * var,int use_model_yrd_large,int64_t best_sse,int is_single_pred)1166 static void search_filter_ref(AV1_COMP *cpi, MACROBLOCK *x, RD_STATS *this_rdc,
1167                               InterPredParams *inter_pred_params_sr, int mi_row,
1168                               int mi_col, PRED_BUFFER *tmp_buffer,
1169                               BLOCK_SIZE bsize, int reuse_inter_pred,
1170                               PRED_BUFFER **this_mode_pred,
1171                               int *this_early_term, unsigned int *var,
1172                               int use_model_yrd_large, int64_t best_sse,
1173                               int is_single_pred) {
1174   AV1_COMMON *const cm = &cpi->common;
1175   MACROBLOCKD *const xd = &x->e_mbd;
1176   struct macroblockd_plane *const pd = &xd->plane[AOM_PLANE_Y];
1177   MB_MODE_INFO *const mi = xd->mi[0];
1178   const int bw = block_size_wide[bsize];
1179   int dim_factor =
1180       (cpi->sf.interp_sf.disable_dual_filter == 0) ? FILTER_SEARCH_SIZE : 1;
1181   RD_STATS pf_rd_stats[FILTER_SEARCH_SIZE * FILTER_SEARCH_SIZE] = { 0 };
1182   TX_SIZE pf_tx_size[FILTER_SEARCH_SIZE * FILTER_SEARCH_SIZE] = { 0 };
1183   PRED_BUFFER *current_pred = *this_mode_pred;
1184   int best_skip = 0;
1185   int best_early_term = 0;
1186   int64_t best_cost = INT64_MAX;
1187   int best_filter_index = -1;
1188 
1189   SubpelParams subpel_params;
1190   // Initialize inter prediction params at mode level for single reference
1191   // mode.
1192   if (is_single_pred)
1193     init_inter_mode_params(&mi->mv[0].as_mv, inter_pred_params_sr,
1194                            &subpel_params, xd->block_ref_scale_factors[0],
1195                            pd->pre->width, pd->pre->height);
1196   for (int filter_idx = 0; filter_idx < FILTER_SEARCH_SIZE * FILTER_SEARCH_SIZE;
1197        ++filter_idx) {
1198     int64_t cost;
1199     if (cpi->sf.interp_sf.disable_dual_filter &&
1200         filters_ref_set[filter_idx].as_filters.x_filter !=
1201             filters_ref_set[filter_idx].as_filters.y_filter)
1202       continue;
1203 
1204     mi->interp_filters.as_int = filters_ref_set[filter_idx].as_int;
1205     if (is_single_pred)
1206       av1_enc_build_inter_predictor_y_nonrd(xd, inter_pred_params_sr,
1207                                             &subpel_params);
1208     else
1209       av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
1210                                     AOM_PLANE_Y, AOM_PLANE_Y);
1211     unsigned int curr_var = UINT_MAX;
1212     if (use_model_yrd_large)
1213       model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd,
1214                                 &pf_rd_stats[filter_idx], this_early_term, 1,
1215                                 best_sse, &curr_var, UINT_MAX);
1216     else
1217       model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rd_stats[filter_idx], &curr_var,
1218                         1, NULL);
1219     pf_rd_stats[filter_idx].rate += av1_get_switchable_rate(
1220         x, xd, cm->features.interp_filter, cm->seq_params->enable_dual_filter);
1221     cost = RDCOST(x->rdmult, pf_rd_stats[filter_idx].rate,
1222                   pf_rd_stats[filter_idx].dist);
1223     pf_tx_size[filter_idx] = mi->tx_size;
1224     if (cost < best_cost) {
1225       *var = curr_var;
1226       best_filter_index = filter_idx;
1227       best_cost = cost;
1228       best_skip = pf_rd_stats[filter_idx].skip_txfm;
1229       best_early_term = *this_early_term;
1230       if (reuse_inter_pred) {
1231         if (*this_mode_pred != current_pred) {
1232           free_pred_buffer(*this_mode_pred);
1233           *this_mode_pred = current_pred;
1234         }
1235         current_pred = &tmp_buffer[get_pred_buffer(tmp_buffer, 3)];
1236         pd->dst.buf = current_pred->data;
1237         pd->dst.stride = bw;
1238       }
1239     }
1240   }
1241   assert(best_filter_index >= 0 &&
1242          best_filter_index < dim_factor * FILTER_SEARCH_SIZE);
1243   if (reuse_inter_pred && *this_mode_pred != current_pred)
1244     free_pred_buffer(current_pred);
1245 
1246   mi->interp_filters.as_int = filters_ref_set[best_filter_index].as_int;
1247   mi->tx_size = pf_tx_size[best_filter_index];
1248   this_rdc->rate = pf_rd_stats[best_filter_index].rate;
1249   this_rdc->dist = pf_rd_stats[best_filter_index].dist;
1250   this_rdc->sse = pf_rd_stats[best_filter_index].sse;
1251   this_rdc->skip_txfm = (best_skip || best_early_term);
1252   *this_early_term = best_early_term;
1253   if (reuse_inter_pred) {
1254     pd->dst.buf = (*this_mode_pred)->data;
1255     pd->dst.stride = (*this_mode_pred)->stride;
1256   } else if (best_filter_index < dim_factor * FILTER_SEARCH_SIZE - 1) {
1257     if (is_single_pred)
1258       av1_enc_build_inter_predictor_y_nonrd(xd, inter_pred_params_sr,
1259                                             &subpel_params);
1260     else
1261       av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
1262                                     AOM_PLANE_Y, AOM_PLANE_Y);
1263   }
1264 }
1265 #if !CONFIG_REALTIME_ONLY
1266 
is_warped_mode_allowed(const AV1_COMP * cpi,MACROBLOCK * const x,const MB_MODE_INFO * mbmi)1267 static AOM_INLINE int is_warped_mode_allowed(const AV1_COMP *cpi,
1268                                              MACROBLOCK *const x,
1269                                              const MB_MODE_INFO *mbmi) {
1270   const FeatureFlags *const features = &cpi->common.features;
1271   const MACROBLOCKD *xd = &x->e_mbd;
1272 
1273   if (cpi->sf.inter_sf.extra_prune_warped) return 0;
1274   if (has_second_ref(mbmi)) return 0;
1275   MOTION_MODE last_motion_mode_allowed = SIMPLE_TRANSLATION;
1276 
1277   if (features->switchable_motion_mode) {
1278     // Determine which motion modes to search if more than SIMPLE_TRANSLATION
1279     // is allowed.
1280     last_motion_mode_allowed = motion_mode_allowed(
1281         xd->global_motion, xd, mbmi, features->allow_warped_motion);
1282   }
1283 
1284   if (last_motion_mode_allowed == WARPED_CAUSAL) {
1285     return 1;
1286   }
1287 
1288   return 0;
1289 }
1290 
calc_num_proj_ref(AV1_COMP * cpi,MACROBLOCK * x,MB_MODE_INFO * mi)1291 static void calc_num_proj_ref(AV1_COMP *cpi, MACROBLOCK *x, MB_MODE_INFO *mi) {
1292   AV1_COMMON *const cm = &cpi->common;
1293   MACROBLOCKD *const xd = &x->e_mbd;
1294   const FeatureFlags *const features = &cm->features;
1295 
1296   mi->num_proj_ref = 1;
1297   WARP_SAMPLE_INFO *const warp_sample_info =
1298       &x->warp_sample_info[mi->ref_frame[0]];
1299   int *pts0 = warp_sample_info->pts;
1300   int *pts_inref0 = warp_sample_info->pts_inref;
1301   MOTION_MODE last_motion_mode_allowed = SIMPLE_TRANSLATION;
1302 
1303   if (features->switchable_motion_mode) {
1304     // Determine which motion modes to search if more than SIMPLE_TRANSLATION
1305     // is allowed.
1306     last_motion_mode_allowed = motion_mode_allowed(
1307         xd->global_motion, xd, mi, features->allow_warped_motion);
1308   }
1309 
1310   if (last_motion_mode_allowed == WARPED_CAUSAL) {
1311     if (warp_sample_info->num < 0) {
1312       warp_sample_info->num = av1_findSamples(cm, xd, pts0, pts_inref0);
1313     }
1314     mi->num_proj_ref = warp_sample_info->num;
1315   }
1316 }
1317 
search_motion_mode(AV1_COMP * cpi,MACROBLOCK * x,RD_STATS * this_rdc,int mi_row,int mi_col,BLOCK_SIZE bsize,int * this_early_term,int use_model_yrd_large,int * rate_mv,int64_t best_sse)1318 static void search_motion_mode(AV1_COMP *cpi, MACROBLOCK *x, RD_STATS *this_rdc,
1319                                int mi_row, int mi_col, BLOCK_SIZE bsize,
1320                                int *this_early_term, int use_model_yrd_large,
1321                                int *rate_mv, int64_t best_sse) {
1322   AV1_COMMON *const cm = &cpi->common;
1323   MACROBLOCKD *const xd = &x->e_mbd;
1324   const FeatureFlags *const features = &cm->features;
1325   MB_MODE_INFO *const mi = xd->mi[0];
1326   RD_STATS pf_rd_stats[MOTION_MODE_SEARCH_SIZE] = { 0 };
1327   int best_skip = 0;
1328   int best_early_term = 0;
1329   int64_t best_cost = INT64_MAX;
1330   int best_mode_index = -1;
1331   const int interp_filter = features->interp_filter;
1332 
1333   const MOTION_MODE motion_modes[MOTION_MODE_SEARCH_SIZE] = {
1334     SIMPLE_TRANSLATION, WARPED_CAUSAL
1335   };
1336   int mode_search_size = is_warped_mode_allowed(cpi, x, mi) ? 2 : 1;
1337 
1338   WARP_SAMPLE_INFO *const warp_sample_info =
1339       &x->warp_sample_info[mi->ref_frame[0]];
1340   int *pts0 = warp_sample_info->pts;
1341   int *pts_inref0 = warp_sample_info->pts_inref;
1342 
1343   const int total_samples = mi->num_proj_ref;
1344   if (total_samples == 0) {
1345     // Do not search WARPED_CAUSAL if there are no samples to use to determine
1346     // warped parameters.
1347     mode_search_size = 1;
1348   }
1349 
1350   const MB_MODE_INFO base_mbmi = *mi;
1351   MB_MODE_INFO best_mbmi;
1352 
1353   for (int mode_index = 0; mode_index < mode_search_size; ++mode_index) {
1354     int64_t cost = INT64_MAX;
1355     MOTION_MODE motion_mode = motion_modes[mode_index];
1356     *mi = base_mbmi;
1357     mi->motion_mode = motion_mode;
1358     if (motion_mode == SIMPLE_TRANSLATION) {
1359       mi->interp_filters = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
1360 
1361       av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
1362                                     AOM_PLANE_Y, AOM_PLANE_Y);
1363       if (use_model_yrd_large)
1364         model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd,
1365                                   &pf_rd_stats[mode_index], this_early_term, 1,
1366                                   best_sse, NULL, UINT_MAX);
1367       else
1368         model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rd_stats[mode_index], NULL, 1,
1369                           NULL);
1370       pf_rd_stats[mode_index].rate +=
1371           av1_get_switchable_rate(x, xd, cm->features.interp_filter,
1372                                   cm->seq_params->enable_dual_filter);
1373       cost = RDCOST(x->rdmult, pf_rd_stats[mode_index].rate,
1374                     pf_rd_stats[mode_index].dist);
1375     } else if (motion_mode == WARPED_CAUSAL) {
1376       int pts[SAMPLES_ARRAY_SIZE], pts_inref[SAMPLES_ARRAY_SIZE];
1377       const ModeCosts *mode_costs = &x->mode_costs;
1378       mi->wm_params.wmtype = DEFAULT_WMTYPE;
1379       mi->interp_filters =
1380           av1_broadcast_interp_filter(av1_unswitchable_filter(interp_filter));
1381 
1382       memcpy(pts, pts0, total_samples * 2 * sizeof(*pts0));
1383       memcpy(pts_inref, pts_inref0, total_samples * 2 * sizeof(*pts_inref0));
1384       // Select the samples according to motion vector difference
1385       if (mi->num_proj_ref > 1) {
1386         mi->num_proj_ref = av1_selectSamples(&mi->mv[0].as_mv, pts, pts_inref,
1387                                              mi->num_proj_ref, bsize);
1388       }
1389 
1390       // Compute the warped motion parameters with a least squares fit
1391       //  using the collected samples
1392       if (!av1_find_projection(mi->num_proj_ref, pts, pts_inref, bsize,
1393                                mi->mv[0].as_mv.row, mi->mv[0].as_mv.col,
1394                                &mi->wm_params, mi_row, mi_col)) {
1395         if (mi->mode == NEWMV) {
1396           const int_mv mv0 = mi->mv[0];
1397           const WarpedMotionParams wm_params0 = mi->wm_params;
1398           const int num_proj_ref0 = mi->num_proj_ref;
1399 
1400           const int_mv ref_mv = av1_get_ref_mv(x, 0);
1401           SUBPEL_MOTION_SEARCH_PARAMS ms_params;
1402           av1_make_default_subpel_ms_params(&ms_params, cpi, x, bsize,
1403                                             &ref_mv.as_mv, NULL);
1404 
1405           // Refine MV in a small range.
1406           av1_refine_warped_mv(xd, cm, &ms_params, bsize, pts0, pts_inref0,
1407                                total_samples, cpi->sf.mv_sf.warp_search_method,
1408                                cpi->sf.mv_sf.warp_search_iters);
1409           if (mi->mv[0].as_int == ref_mv.as_int) {
1410             continue;
1411           }
1412 
1413           if (mv0.as_int != mi->mv[0].as_int) {
1414             // Keep the refined MV and WM parameters.
1415             int tmp_rate_mv = av1_mv_bit_cost(
1416                 &mi->mv[0].as_mv, &ref_mv.as_mv, x->mv_costs->nmv_joint_cost,
1417                 x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
1418             *rate_mv = tmp_rate_mv;
1419           } else {
1420             // Restore the old MV and WM parameters.
1421             mi->mv[0] = mv0;
1422             mi->wm_params = wm_params0;
1423             mi->num_proj_ref = num_proj_ref0;
1424           }
1425         }
1426         // Build the warped predictor
1427         av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
1428                                       AOM_PLANE_Y, av1_num_planes(cm) - 1);
1429         if (use_model_yrd_large)
1430           model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd,
1431                                     &pf_rd_stats[mode_index], this_early_term,
1432                                     1, best_sse, NULL, UINT_MAX);
1433         else
1434           model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rd_stats[mode_index], NULL,
1435                             1, NULL);
1436 
1437         pf_rd_stats[mode_index].rate +=
1438             mode_costs->motion_mode_cost[bsize][mi->motion_mode];
1439         cost = RDCOST(x->rdmult, pf_rd_stats[mode_index].rate,
1440                       pf_rd_stats[mode_index].dist);
1441       } else {
1442         cost = INT64_MAX;
1443       }
1444     }
1445     if (cost < best_cost) {
1446       best_mode_index = mode_index;
1447       best_cost = cost;
1448       best_skip = pf_rd_stats[mode_index].skip_txfm;
1449       best_early_term = *this_early_term;
1450       best_mbmi = *mi;
1451     }
1452   }
1453   assert(best_mode_index >= 0 && best_mode_index < FILTER_SEARCH_SIZE);
1454 
1455   *mi = best_mbmi;
1456   this_rdc->rate = pf_rd_stats[best_mode_index].rate;
1457   this_rdc->dist = pf_rd_stats[best_mode_index].dist;
1458   this_rdc->sse = pf_rd_stats[best_mode_index].sse;
1459   this_rdc->skip_txfm = (best_skip || best_early_term);
1460   *this_early_term = best_early_term;
1461   if (best_mode_index < FILTER_SEARCH_SIZE - 1) {
1462     av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
1463                                   AOM_PLANE_Y, AOM_PLANE_Y);
1464   }
1465 }
1466 #endif  // !CONFIG_REALTIME_ONLY
1467 
1468 #define COLLECT_NON_SQR_STAT 0
1469 
1470 #if COLLECT_NONRD_PICK_MODE_STAT
1471 
print_stage_time(const char * stage_name,int64_t stage_time,int64_t total_time)1472 static AOM_INLINE void print_stage_time(const char *stage_name,
1473                                         int64_t stage_time,
1474                                         int64_t total_time) {
1475   printf("    %s: %ld (%f%%)\n", stage_name, stage_time,
1476          100 * stage_time / (float)total_time);
1477 }
1478 
print_time(const mode_search_stat_nonrd * const ms_stat,BLOCK_SIZE bsize,int mi_rows,int mi_cols,int mi_row,int mi_col)1479 static void print_time(const mode_search_stat_nonrd *const ms_stat,
1480                        BLOCK_SIZE bsize, int mi_rows, int mi_cols, int mi_row,
1481                        int mi_col) {
1482   if ((mi_row + mi_size_high[bsize] >= mi_rows) &&
1483       (mi_col + mi_size_wide[bsize] >= mi_cols)) {
1484     int64_t total_time = 0l;
1485     int32_t total_blocks = 0;
1486     for (BLOCK_SIZE bs = 0; bs < BLOCK_SIZES; bs++) {
1487       total_time += ms_stat->total_block_times[bs];
1488       total_blocks += ms_stat->num_blocks[bs];
1489     }
1490 
1491     printf("\n");
1492     for (BLOCK_SIZE bs = 0; bs < BLOCK_SIZES; bs++) {
1493       if (ms_stat->num_blocks[bs] == 0) {
1494         continue;
1495       }
1496       if (!COLLECT_NON_SQR_STAT && block_size_wide[bs] != block_size_high[bs]) {
1497         continue;
1498       }
1499 
1500       printf("BLOCK_%dX%d Num %d, Time: %ld (%f%%), Avg_time %f:\n",
1501              block_size_wide[bs], block_size_high[bs], ms_stat->num_blocks[bs],
1502              ms_stat->total_block_times[bs],
1503              100 * ms_stat->total_block_times[bs] / (float)total_time,
1504              (float)ms_stat->total_block_times[bs] / ms_stat->num_blocks[bs]);
1505       for (int j = 0; j < MB_MODE_COUNT; j++) {
1506         if (ms_stat->nonskipped_search_times[bs][j] == 0) {
1507           continue;
1508         }
1509 
1510         int64_t total_mode_time = ms_stat->nonskipped_search_times[bs][j];
1511         printf("  Mode %d, %d/%d tps %f\n", j,
1512                ms_stat->num_nonskipped_searches[bs][j],
1513                ms_stat->num_searches[bs][j],
1514                ms_stat->num_nonskipped_searches[bs][j] > 0
1515                    ? (float)ms_stat->nonskipped_search_times[bs][j] /
1516                          ms_stat->num_nonskipped_searches[bs][j]
1517                    : 0l);
1518         if (j >= INTER_MODE_START) {
1519           total_mode_time = ms_stat->ms_time[bs][j] + ms_stat->ifs_time[bs][j] +
1520                             ms_stat->model_rd_time[bs][j] +
1521                             ms_stat->txfm_time[bs][j];
1522           print_stage_time("Motion Search Time", ms_stat->ms_time[bs][j],
1523                            total_time);
1524           print_stage_time("Filter Search Time", ms_stat->ifs_time[bs][j],
1525                            total_time);
1526           print_stage_time("Model    RD   Time", ms_stat->model_rd_time[bs][j],
1527                            total_time);
1528           print_stage_time("Tranfm Search Time", ms_stat->txfm_time[bs][j],
1529                            total_time);
1530         }
1531         print_stage_time("Total  Mode   Time", total_mode_time, total_time);
1532       }
1533       printf("\n");
1534     }
1535     printf("Total time = %ld. Total blocks = %d\n", total_time, total_blocks);
1536   }
1537 }
1538 #endif  // COLLECT_NONRD_PICK_MODE_STAT
1539 
should_prune_intra_modes_using_neighbors(const MACROBLOCKD * xd,bool enable_intra_mode_pruning_using_neighbors,PREDICTION_MODE this_mode,PREDICTION_MODE above_mode,PREDICTION_MODE left_mode)1540 static bool should_prune_intra_modes_using_neighbors(
1541     const MACROBLOCKD *xd, bool enable_intra_mode_pruning_using_neighbors,
1542     PREDICTION_MODE this_mode, PREDICTION_MODE above_mode,
1543     PREDICTION_MODE left_mode) {
1544   if (!enable_intra_mode_pruning_using_neighbors) return false;
1545 
1546   // Avoid pruning of DC_PRED as it is the most probable mode to win as per the
1547   // statistics generated for nonrd intra mode evaluations.
1548   if (this_mode == DC_PRED) return false;
1549 
1550   // Enable the pruning for current mode only if it is not the winner mode of
1551   // both the neighboring blocks (left/top).
1552   return xd->up_available && this_mode != above_mode && xd->left_available &&
1553          this_mode != left_mode;
1554 }
1555 
av1_nonrd_pick_intra_mode(AV1_COMP * cpi,MACROBLOCK * x,RD_STATS * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)1556 void av1_nonrd_pick_intra_mode(AV1_COMP *cpi, MACROBLOCK *x, RD_STATS *rd_cost,
1557                                BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
1558   AV1_COMMON *const cm = &cpi->common;
1559   MACROBLOCKD *const xd = &x->e_mbd;
1560   MB_MODE_INFO *const mi = xd->mi[0];
1561   RD_STATS this_rdc, best_rdc;
1562   struct estimate_block_intra_args args;
1563   init_estimate_block_intra_args(&args, cpi, x);
1564   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
1565   mi->tx_size =
1566       AOMMIN(max_txsize_lookup[bsize],
1567              tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]);
1568   assert(IMPLIES(xd->lossless[mi->segment_id], mi->tx_size == TX_4X4));
1569   const BLOCK_SIZE tx_bsize = txsize_to_bsize[mi->tx_size];
1570 
1571   // If the current block size is the same as the transform block size, enable
1572   // mode pruning based on the best SAD so far.
1573   if (cpi->sf.rt_sf.prune_intra_mode_using_best_sad_so_far && bsize == tx_bsize)
1574     args.prune_mode_based_on_sad = true;
1575 
1576   int *bmode_costs;
1577   PREDICTION_MODE best_mode = DC_PRED;
1578   const MB_MODE_INFO *above_mi = xd->above_mbmi;
1579   const MB_MODE_INFO *left_mi = xd->left_mbmi;
1580   const PREDICTION_MODE A = av1_above_block_mode(above_mi);
1581   const PREDICTION_MODE L = av1_left_block_mode(left_mi);
1582   const int above_ctx = intra_mode_context[A];
1583   const int left_ctx = intra_mode_context[L];
1584   const unsigned int source_variance = x->source_variance;
1585   bmode_costs = x->mode_costs.y_mode_costs[above_ctx][left_ctx];
1586 
1587   av1_invalid_rd_stats(&best_rdc);
1588   av1_invalid_rd_stats(&this_rdc);
1589 
1590   init_mbmi_nonrd(mi, DC_PRED, INTRA_FRAME, NONE_FRAME, cm);
1591   mi->mv[0].as_int = mi->mv[1].as_int = INVALID_MV;
1592 
1593   // Change the limit of this loop to add other intra prediction
1594   // mode tests.
1595   for (int mode_index = 0; mode_index < RTC_INTRA_MODES; ++mode_index) {
1596     PREDICTION_MODE this_mode = intra_mode_list[mode_index];
1597 
1598     // As per the statistics generated for intra mode evaluation in the nonrd
1599     // path, it is found that the probability of H_PRED mode being the winner is
1600     // very low when the best mode so far is V_PRED (out of DC_PRED and V_PRED).
1601     // If V_PRED is the winner mode out of DC_PRED and V_PRED, it could imply
1602     // the presence of a vertically dominant pattern. Hence, H_PRED mode is not
1603     // evaluated.
1604     if (cpi->sf.rt_sf.prune_h_pred_using_best_mode_so_far &&
1605         this_mode == H_PRED && best_mode == V_PRED)
1606       continue;
1607 
1608     if (should_prune_intra_modes_using_neighbors(
1609             xd, cpi->sf.rt_sf.enable_intra_mode_pruning_using_neighbors,
1610             this_mode, A, L)) {
1611       // Prune V_PRED and H_PRED if source variance of the block is less than
1612       // or equal to 50. The source variance threshold is obtained empirically.
1613       if ((this_mode == V_PRED || this_mode == H_PRED) && source_variance <= 50)
1614         continue;
1615 
1616       // As per the statistics, probability of SMOOTH_PRED being the winner is
1617       // low when best mode so far is DC_PRED (out of DC_PRED, V_PRED and
1618       // H_PRED). Hence, SMOOTH_PRED mode is not evaluated.
1619       if (best_mode == DC_PRED && this_mode == SMOOTH_PRED) continue;
1620     }
1621 
1622     this_rdc.dist = this_rdc.rate = 0;
1623     args.mode = this_mode;
1624     args.skippable = 1;
1625     args.rdc = &this_rdc;
1626     mi->mode = this_mode;
1627     av1_foreach_transformed_block_in_plane(xd, bsize, AOM_PLANE_Y,
1628                                            av1_estimate_block_intra, &args);
1629 
1630     if (this_rdc.rate == INT_MAX) continue;
1631 
1632     const int skip_ctx = av1_get_skip_txfm_context(xd);
1633     if (args.skippable) {
1634       this_rdc.rate = x->mode_costs.skip_txfm_cost[skip_ctx][1];
1635     } else {
1636       this_rdc.rate += x->mode_costs.skip_txfm_cost[skip_ctx][0];
1637     }
1638     this_rdc.rate += bmode_costs[this_mode];
1639     this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
1640 
1641     if (this_rdc.rdcost < best_rdc.rdcost) {
1642       best_rdc = this_rdc;
1643       best_mode = this_mode;
1644       if (!this_rdc.skip_txfm) {
1645         memset(ctx->blk_skip, 0,
1646                sizeof(x->txfm_search_info.blk_skip[0]) * ctx->num_4x4_blk);
1647       }
1648     }
1649   }
1650 
1651   mi->mode = best_mode;
1652   // Keep DC for UV since mode test is based on Y channel only.
1653   mi->uv_mode = UV_DC_PRED;
1654   *rd_cost = best_rdc;
1655 
1656   // For lossless: always force the skip flags off.
1657   // Even though the blk_skip is set to 0 above in the rdcost comparison,
1658   // do it here again in case the above logic changes.
1659   if (is_lossless_requested(&cpi->oxcf.rc_cfg)) {
1660     x->txfm_search_info.skip_txfm = 0;
1661     memset(ctx->blk_skip, 0,
1662            sizeof(x->txfm_search_info.blk_skip[0]) * ctx->num_4x4_blk);
1663   }
1664 
1665 #if CONFIG_INTERNAL_STATS
1666   store_coding_context_nonrd(x, ctx, mi->mode);
1667 #else
1668   store_coding_context_nonrd(x, ctx);
1669 #endif  // CONFIG_INTERNAL_STATS
1670 }
1671 
is_same_gf_and_last_scale(AV1_COMMON * cm)1672 static AOM_INLINE int is_same_gf_and_last_scale(AV1_COMMON *cm) {
1673   struct scale_factors *const sf_last = get_ref_scale_factors(cm, LAST_FRAME);
1674   struct scale_factors *const sf_golden =
1675       get_ref_scale_factors(cm, GOLDEN_FRAME);
1676   return ((sf_last->x_scale_fp == sf_golden->x_scale_fp) &&
1677           (sf_last->y_scale_fp == sf_golden->y_scale_fp));
1678 }
1679 
get_ref_frame_use_mask(AV1_COMP * cpi,MACROBLOCK * x,MB_MODE_INFO * mi,int mi_row,int mi_col,BLOCK_SIZE bsize,int gf_temporal_ref,int use_ref_frame[],int * force_skip_low_temp_var)1680 static AOM_INLINE void get_ref_frame_use_mask(AV1_COMP *cpi, MACROBLOCK *x,
1681                                               MB_MODE_INFO *mi, int mi_row,
1682                                               int mi_col, BLOCK_SIZE bsize,
1683                                               int gf_temporal_ref,
1684                                               int use_ref_frame[],
1685                                               int *force_skip_low_temp_var) {
1686   AV1_COMMON *const cm = &cpi->common;
1687   const struct segmentation *const seg = &cm->seg;
1688   const int is_small_sb = (cm->seq_params->sb_size == BLOCK_64X64);
1689 
1690   // When the ref_frame_config is used to set the reference frame structure
1691   // then the usage of alt_ref is determined by the ref_frame_flags
1692   // (and not the speed feature use_nonrd_altref_frame).
1693   int use_alt_ref_frame = cpi->ppi->rtc_ref.set_ref_frame_config ||
1694                           cpi->sf.rt_sf.use_nonrd_altref_frame;
1695 
1696   int use_golden_ref_frame = 1;
1697   int use_last_ref_frame = 1;
1698 
1699   // When the ref_frame_config is used to set the reference frame structure:
1700   // check if LAST is used as a reference. And only remove golden and altref
1701   // references below if last is used as a reference.
1702   if (cpi->ppi->rtc_ref.set_ref_frame_config)
1703     use_last_ref_frame =
1704         cpi->ref_frame_flags & AOM_LAST_FLAG ? use_last_ref_frame : 0;
1705 
1706   // frame_since_golden is not used when user sets the referene structure.
1707   if (!cpi->ppi->rtc_ref.set_ref_frame_config && use_last_ref_frame &&
1708       cpi->rc.frames_since_golden == 0 && gf_temporal_ref) {
1709     use_golden_ref_frame = 0;
1710   }
1711 
1712   if (use_last_ref_frame && cpi->sf.rt_sf.short_circuit_low_temp_var &&
1713       x->nonrd_prune_ref_frame_search) {
1714     if (is_small_sb)
1715       *force_skip_low_temp_var = av1_get_force_skip_low_temp_var_small_sb(
1716           &x->part_search_info.variance_low[0], mi_row, mi_col, bsize);
1717     else
1718       *force_skip_low_temp_var = av1_get_force_skip_low_temp_var(
1719           &x->part_search_info.variance_low[0], mi_row, mi_col, bsize);
1720     // If force_skip_low_temp_var is set, skip golden reference.
1721     if (*force_skip_low_temp_var) {
1722       use_golden_ref_frame = 0;
1723       use_alt_ref_frame = 0;
1724     }
1725   }
1726 
1727   if (use_last_ref_frame &&
1728       (x->nonrd_prune_ref_frame_search > 2 || x->force_zeromv_skip_for_blk ||
1729        (x->nonrd_prune_ref_frame_search > 1 && bsize > BLOCK_64X64))) {
1730     use_golden_ref_frame = 0;
1731     use_alt_ref_frame = 0;
1732   }
1733 
1734   if (segfeature_active(seg, mi->segment_id, SEG_LVL_REF_FRAME) &&
1735       get_segdata(seg, mi->segment_id, SEG_LVL_REF_FRAME) == GOLDEN_FRAME) {
1736     use_golden_ref_frame = 1;
1737     use_alt_ref_frame = 0;
1738   }
1739 
1740   // Skip golden/altref reference if color is set, on flat blocks with motion.
1741   // For screen: always skip golden/alt (if color_sensitivity_sb_g/alt is set)
1742   // except when x->nonrd_prune_ref_frame_search = 0. This latter flag
1743   // may be set in the variance partition when golden is a much better
1744   // reference than last, in which case it may not be worth skipping
1745   // golden/altref completely.
1746   // Condition on use_last_ref to make sure there remains at least one
1747   // reference.
1748   if (use_last_ref_frame &&
1749       ((cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN &&
1750         x->nonrd_prune_ref_frame_search != 0) ||
1751        (x->source_variance < 200 &&
1752         x->content_state_sb.source_sad_nonrd >= kLowSad))) {
1753     if (x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_U)] == 1 ||
1754         x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_V)] == 1)
1755       use_golden_ref_frame = 0;
1756     if (x->color_sensitivity_sb_alt[COLOR_SENS_IDX(AOM_PLANE_U)] == 1 ||
1757         x->color_sensitivity_sb_alt[COLOR_SENS_IDX(AOM_PLANE_V)] == 1)
1758       use_alt_ref_frame = 0;
1759   }
1760 
1761   // For non-screen: if golden and altref are not being selected as references
1762   // (use_golden_ref_frame/use_alt_ref_frame = 0) check to allow golden back
1763   // based on the sad of nearest/nearmv of LAST ref. If this block sad is large,
1764   // keep golden as reference. Only do this for the agrressive pruning mode and
1765   // avoid it when color is set for golden reference.
1766   if (cpi->oxcf.tune_cfg.content != AOM_CONTENT_SCREEN &&
1767       (cpi->ref_frame_flags & AOM_LAST_FLAG) && !use_golden_ref_frame &&
1768       !use_alt_ref_frame && x->pred_mv_sad[LAST_FRAME] != INT_MAX &&
1769       x->nonrd_prune_ref_frame_search > 2 &&
1770       x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_U)] == 0 &&
1771       x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_V)] == 0) {
1772     int thr = (cm->width * cm->height > RESOLUTION_288P) ? 100 : 150;
1773     int pred = x->pred_mv_sad[LAST_FRAME] >>
1774                (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
1775     if (pred > thr) use_golden_ref_frame = 1;
1776   }
1777 
1778   use_alt_ref_frame =
1779       cpi->ref_frame_flags & AOM_ALT_FLAG ? use_alt_ref_frame : 0;
1780   use_golden_ref_frame =
1781       cpi->ref_frame_flags & AOM_GOLD_FLAG ? use_golden_ref_frame : 0;
1782 
1783   // For spatial layers: enable golden ref if it is set by user and
1784   // corresponds to the lower spatial layer.
1785   if (cpi->svc.spatial_layer_id > 0 && (cpi->ref_frame_flags & AOM_GOLD_FLAG) &&
1786       x->content_state_sb.source_sad_nonrd < kHighSad) {
1787     const int buffslot_golden =
1788         cpi->ppi->rtc_ref.ref_idx[GOLDEN_FRAME - LAST_FRAME];
1789     if (cpi->ppi->rtc_ref.buffer_time_index[buffslot_golden] ==
1790         cpi->svc.current_superframe)
1791       use_golden_ref_frame = 1;
1792   }
1793 
1794   use_ref_frame[ALTREF_FRAME] = use_alt_ref_frame;
1795   use_ref_frame[GOLDEN_FRAME] = use_golden_ref_frame;
1796   use_ref_frame[LAST_FRAME] = use_last_ref_frame;
1797   // Keep this assert on, as only 3 references are used in nonrd_pickmode
1798   // (LAST, GOLDEN, ALTREF), and if all 3 are not set by user then this
1799   // frame must be an intra-only frame and hence should never enter the
1800   // pickmode here for inter frames.
1801   assert(use_last_ref_frame || use_golden_ref_frame || use_alt_ref_frame);
1802 }
1803 
is_filter_search_enabled_blk(AV1_COMP * cpi,MACROBLOCK * x,int mi_row,int mi_col,BLOCK_SIZE bsize,int segment_id,int cb_pred_filter_search,InterpFilter * filt_select)1804 static AOM_INLINE int is_filter_search_enabled_blk(
1805     AV1_COMP *cpi, MACROBLOCK *x, int mi_row, int mi_col, BLOCK_SIZE bsize,
1806     int segment_id, int cb_pred_filter_search, InterpFilter *filt_select) {
1807   const AV1_COMMON *const cm = &cpi->common;
1808   // filt search disabled
1809   if (!cpi->sf.rt_sf.use_nonrd_filter_search) return 0;
1810   // filt search purely based on mode properties
1811   if (!cb_pred_filter_search) return 1;
1812   MACROBLOCKD *const xd = &x->e_mbd;
1813   int enable_interp_search = 0;
1814   if (!(xd->left_mbmi && xd->above_mbmi)) {
1815     // neighbors info unavailable
1816     enable_interp_search = 2;
1817   } else if (!(is_inter_block(xd->left_mbmi) &&
1818                is_inter_block(xd->above_mbmi))) {
1819     // neighbor is INTRA
1820     enable_interp_search = 2;
1821   } else if (xd->left_mbmi->interp_filters.as_int !=
1822              xd->above_mbmi->interp_filters.as_int) {
1823     // filters are different
1824     enable_interp_search = 2;
1825   } else if ((cb_pred_filter_search == 1) &&
1826              (xd->left_mbmi->interp_filters.as_filters.x_filter !=
1827               EIGHTTAP_REGULAR)) {
1828     // not regular
1829     enable_interp_search = 2;
1830   } else {
1831     // enable prediction based on chessboard pattern
1832     if (xd->left_mbmi->interp_filters.as_filters.x_filter == EIGHTTAP_SMOOTH)
1833       *filt_select = EIGHTTAP_SMOOTH;
1834     const int bsl = mi_size_wide_log2[bsize];
1835     enable_interp_search =
1836         (bool)((((mi_row + mi_col) >> bsl) +
1837                 get_chessboard_index(cm->current_frame.frame_number)) &
1838                0x1);
1839     if (cyclic_refresh_segment_id_boosted(segment_id)) enable_interp_search = 1;
1840   }
1841   return enable_interp_search;
1842 }
1843 
skip_mode_by_threshold(PREDICTION_MODE mode,MV_REFERENCE_FRAME ref_frame,int_mv mv,int frames_since_golden,const int * const rd_threshes,const int * const rd_thresh_freq_fact,int64_t best_cost,int best_skip,int extra_shift)1844 static AOM_INLINE int skip_mode_by_threshold(
1845     PREDICTION_MODE mode, MV_REFERENCE_FRAME ref_frame, int_mv mv,
1846     int frames_since_golden, const int *const rd_threshes,
1847     const int *const rd_thresh_freq_fact, int64_t best_cost, int best_skip,
1848     int extra_shift) {
1849   int skip_this_mode = 0;
1850   const THR_MODES mode_index = mode_idx[ref_frame][INTER_OFFSET(mode)];
1851   int64_t mode_rd_thresh =
1852       best_skip ? ((int64_t)rd_threshes[mode_index]) << (extra_shift + 1)
1853                 : ((int64_t)rd_threshes[mode_index]) << extra_shift;
1854 
1855   // Increase mode_rd_thresh value for non-LAST for improved encoding
1856   // speed
1857   if (ref_frame != LAST_FRAME) {
1858     mode_rd_thresh = mode_rd_thresh << 1;
1859     if (ref_frame == GOLDEN_FRAME && frames_since_golden > 4)
1860       mode_rd_thresh = mode_rd_thresh << (extra_shift + 1);
1861   }
1862 
1863   if (rd_less_than_thresh(best_cost, mode_rd_thresh,
1864                           rd_thresh_freq_fact[mode_index]))
1865     if (mv.as_int != 0) skip_this_mode = 1;
1866 
1867   return skip_this_mode;
1868 }
1869 
skip_mode_by_low_temp(PREDICTION_MODE mode,MV_REFERENCE_FRAME ref_frame,BLOCK_SIZE bsize,CONTENT_STATE_SB content_state_sb,int_mv mv,int force_skip_low_temp_var)1870 static AOM_INLINE int skip_mode_by_low_temp(
1871     PREDICTION_MODE mode, MV_REFERENCE_FRAME ref_frame, BLOCK_SIZE bsize,
1872     CONTENT_STATE_SB content_state_sb, int_mv mv, int force_skip_low_temp_var) {
1873   // Skip non-zeromv mode search for non-LAST frame if force_skip_low_temp_var
1874   // is set. If nearestmv for golden frame is 0, zeromv mode will be skipped
1875   // later.
1876   if (force_skip_low_temp_var && ref_frame != LAST_FRAME && mv.as_int != 0) {
1877     return 1;
1878   }
1879 
1880   if (content_state_sb.source_sad_nonrd != kHighSad && bsize >= BLOCK_64X64 &&
1881       force_skip_low_temp_var && mode == NEWMV) {
1882     return 1;
1883   }
1884   return 0;
1885 }
1886 
skip_mode_by_bsize_and_ref_frame(PREDICTION_MODE mode,MV_REFERENCE_FRAME ref_frame,BLOCK_SIZE bsize,int extra_prune,unsigned int sse_zeromv_norm,int more_prune)1887 static AOM_INLINE int skip_mode_by_bsize_and_ref_frame(
1888     PREDICTION_MODE mode, MV_REFERENCE_FRAME ref_frame, BLOCK_SIZE bsize,
1889     int extra_prune, unsigned int sse_zeromv_norm, int more_prune) {
1890   const unsigned int thresh_skip_golden = 500;
1891 
1892   if (ref_frame != LAST_FRAME && sse_zeromv_norm < thresh_skip_golden &&
1893       mode == NEWMV)
1894     return 1;
1895 
1896   if (bsize == BLOCK_128X128 && mode == NEWMV) return 1;
1897 
1898   // Skip testing non-LAST if this flag is set.
1899   if (extra_prune) {
1900     if (extra_prune > 1 && ref_frame != LAST_FRAME &&
1901         (bsize > BLOCK_16X16 && mode == NEWMV))
1902       return 1;
1903 
1904     if (ref_frame != LAST_FRAME && mode == NEARMV) return 1;
1905 
1906     if (more_prune && bsize >= BLOCK_32X32 && mode == NEARMV) return 1;
1907   }
1908   return 0;
1909 }
1910 
set_block_source_sad(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,struct buf_2d * yv12_mb)1911 static void set_block_source_sad(AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
1912                                  struct buf_2d *yv12_mb) {
1913   struct macroblock_plane *const p = &x->plane[0];
1914   const int y_sad = cpi->ppi->fn_ptr[bsize].sdf(p->src.buf, p->src.stride,
1915                                                 yv12_mb->buf, yv12_mb->stride);
1916   if (y_sad == 0) x->block_is_zero_sad = 1;
1917 }
1918 
set_color_sensitivity(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int y_sad,unsigned int source_variance,struct buf_2d yv12_mb[MAX_MB_PLANE])1919 static void set_color_sensitivity(AV1_COMP *cpi, MACROBLOCK *x,
1920                                   BLOCK_SIZE bsize, int y_sad,
1921                                   unsigned int source_variance,
1922                                   struct buf_2d yv12_mb[MAX_MB_PLANE]) {
1923   const int subsampling_x = cpi->common.seq_params->subsampling_x;
1924   const int subsampling_y = cpi->common.seq_params->subsampling_y;
1925   const int source_sad_nonrd = x->content_state_sb.source_sad_nonrd;
1926   const int high_res = cpi->common.width * cpi->common.height >= 640 * 360;
1927   if (bsize == cpi->common.seq_params->sb_size) {
1928     // At superblock level color_sensitivity is already set to 0, 1, or 2.
1929     // 2 is middle/uncertain level. To avoid additional sad
1930     // computations when bsize = sb_size force level 2 to 1 (certain color)
1931     // for motion areas.
1932     if (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] == 2) {
1933       x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] =
1934           source_sad_nonrd >= kMedSad ? 1 : 0;
1935     }
1936     if (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] == 2) {
1937       x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] =
1938           source_sad_nonrd >= kMedSad ? 1 : 0;
1939     }
1940     return;
1941   }
1942   int shift = 3;
1943   unsigned int source_var_thr = 50;
1944   int uv_sad_thr = 100;
1945   if (source_sad_nonrd >= kMedSad && x->source_variance > 0 && high_res)
1946     shift = 4;
1947   if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN) {
1948     if (cpi->rc.high_source_sad) shift = 6;
1949     if (source_sad_nonrd > kMedSad) {
1950       source_var_thr = 1200;
1951       uv_sad_thr = 10;
1952     }
1953   }
1954   NOISE_LEVEL noise_level = kLow;
1955   int norm_sad =
1956       y_sad >> (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
1957   unsigned int thresh_spatial = (cpi->common.width > 1920) ? 5000 : 1000;
1958   // If the spatial source variance is high and the normalized y_sad
1959   // is low, then y-channel is likely good for mode estimation, so keep
1960   // color_sensitivity off. For low noise content for now, since there is
1961   // some bdrate regression for noisy color clip.
1962   if (cpi->noise_estimate.enabled)
1963     noise_level = av1_noise_estimate_extract_level(&cpi->noise_estimate);
1964   if (noise_level == kLow && source_variance > thresh_spatial &&
1965       cpi->oxcf.tune_cfg.content != AOM_CONTENT_SCREEN && norm_sad < 50) {
1966     x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] = 0;
1967     x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] = 0;
1968     return;
1969   }
1970   const int num_planes = av1_num_planes(&cpi->common);
1971 
1972   for (int plane = AOM_PLANE_U; plane < num_planes; ++plane) {
1973     // Always check if level = 2. If level = 0 check again for
1974     // motion areas for higher resolns, where color artifacts
1975     // are more noticeable.
1976     if (x->color_sensitivity[COLOR_SENS_IDX(plane)] == 2 ||
1977         (x->color_sensitivity[COLOR_SENS_IDX(plane)] == 0 &&
1978          source_sad_nonrd >= kMedSad && high_res)) {
1979       struct macroblock_plane *const p = &x->plane[plane];
1980       const BLOCK_SIZE bs =
1981           get_plane_block_size(bsize, subsampling_x, subsampling_y);
1982 
1983       const int uv_sad = cpi->ppi->fn_ptr[bs].sdf(
1984           p->src.buf, p->src.stride, yv12_mb[plane].buf, yv12_mb[plane].stride);
1985 
1986       const int norm_uv_sad =
1987           uv_sad >> (b_width_log2_lookup[bs] + b_height_log2_lookup[bs]);
1988       x->color_sensitivity[COLOR_SENS_IDX(plane)] =
1989           uv_sad > (y_sad >> shift) && norm_uv_sad > 40;
1990       if (source_variance < source_var_thr && norm_uv_sad > uv_sad_thr)
1991         x->color_sensitivity[COLOR_SENS_IDX(plane)] = 1;
1992     }
1993   }
1994 }
1995 
setup_compound_prediction(const AV1_COMMON * cm,MACROBLOCK * x,struct buf_2d yv12_mb[8][MAX_MB_PLANE],const int * use_ref_frame_mask,const MV_REFERENCE_FRAME * rf,int * ref_mv_idx)1996 static void setup_compound_prediction(const AV1_COMMON *cm, MACROBLOCK *x,
1997                                       struct buf_2d yv12_mb[8][MAX_MB_PLANE],
1998                                       const int *use_ref_frame_mask,
1999                                       const MV_REFERENCE_FRAME *rf,
2000                                       int *ref_mv_idx) {
2001   MACROBLOCKD *const xd = &x->e_mbd;
2002   MB_MODE_INFO *const mbmi = xd->mi[0];
2003   MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
2004   MV_REFERENCE_FRAME ref_frame_comp;
2005   if (!use_ref_frame_mask[rf[1]]) {
2006     // Need to setup pred_block, if it hasn't been done in find_predictors.
2007     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_yv12_buf(cm, rf[1]);
2008     const int num_planes = av1_num_planes(cm);
2009     if (yv12 != NULL) {
2010       const struct scale_factors *const sf =
2011           get_ref_scale_factors_const(cm, rf[1]);
2012       av1_setup_pred_block(xd, yv12_mb[rf[1]], yv12, sf, sf, num_planes);
2013     }
2014   }
2015   ref_frame_comp = av1_ref_frame_type(rf);
2016   mbmi_ext->mode_context[ref_frame_comp] = 0;
2017   mbmi_ext->ref_mv_count[ref_frame_comp] = UINT8_MAX;
2018   av1_find_mv_refs(cm, xd, mbmi, ref_frame_comp, mbmi_ext->ref_mv_count,
2019                    xd->ref_mv_stack, xd->weight, NULL, mbmi_ext->global_mvs,
2020                    mbmi_ext->mode_context);
2021   av1_copy_usable_ref_mv_stack_and_weight(xd, mbmi_ext, ref_frame_comp);
2022   *ref_mv_idx = mbmi->ref_mv_idx + 1;
2023 }
2024 
set_compound_mode(MACROBLOCK * x,MV_REFERENCE_FRAME ref_frame,MV_REFERENCE_FRAME ref_frame2,int ref_mv_idx,int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],PREDICTION_MODE this_mode)2025 static void set_compound_mode(MACROBLOCK *x, MV_REFERENCE_FRAME ref_frame,
2026                               MV_REFERENCE_FRAME ref_frame2, int ref_mv_idx,
2027                               int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],
2028                               PREDICTION_MODE this_mode) {
2029   MACROBLOCKD *const xd = &x->e_mbd;
2030   MB_MODE_INFO *const mi = xd->mi[0];
2031   mi->ref_frame[0] = ref_frame;
2032   mi->ref_frame[1] = ref_frame2;
2033   mi->compound_idx = 1;
2034   mi->comp_group_idx = 0;
2035   mi->interinter_comp.type = COMPOUND_AVERAGE;
2036   MV_REFERENCE_FRAME ref_frame_comp = av1_ref_frame_type(mi->ref_frame);
2037   if (this_mode == GLOBAL_GLOBALMV) {
2038     frame_mv[this_mode][ref_frame].as_int = 0;
2039     frame_mv[this_mode][ref_frame2].as_int = 0;
2040   } else if (this_mode == NEAREST_NEARESTMV) {
2041     frame_mv[this_mode][ref_frame].as_int =
2042         xd->ref_mv_stack[ref_frame_comp][0].this_mv.as_int;
2043     frame_mv[this_mode][ref_frame2].as_int =
2044         xd->ref_mv_stack[ref_frame_comp][0].comp_mv.as_int;
2045   } else if (this_mode == NEAR_NEARMV) {
2046     frame_mv[this_mode][ref_frame].as_int =
2047         xd->ref_mv_stack[ref_frame_comp][ref_mv_idx].this_mv.as_int;
2048     frame_mv[this_mode][ref_frame2].as_int =
2049         xd->ref_mv_stack[ref_frame_comp][ref_mv_idx].comp_mv.as_int;
2050   }
2051 }
2052 
2053 // Prune compound mode if the single mode variance is lower than a fixed
2054 // percentage of the median value.
skip_comp_based_on_var(const unsigned int (* single_vars)[REF_FRAMES],BLOCK_SIZE bsize)2055 static bool skip_comp_based_on_var(
2056     const unsigned int (*single_vars)[REF_FRAMES], BLOCK_SIZE bsize) {
2057   unsigned int best_var = UINT_MAX;
2058   for (int cur_mode_idx = 0; cur_mode_idx < RTC_INTER_MODES; cur_mode_idx++) {
2059     for (int ref_idx = 0; ref_idx < REF_FRAMES; ref_idx++) {
2060       best_var = AOMMIN(best_var, single_vars[cur_mode_idx][ref_idx]);
2061     }
2062   }
2063   const unsigned int thresh_64 = (unsigned int)(0.57356805f * 8659);
2064   const unsigned int thresh_32 = (unsigned int)(0.23964763f * 4281);
2065 
2066   // Currently, the thresh for 128 and 16 are not well-tuned. We are using the
2067   // results from 64 and 32 as an heuristic.
2068   switch (bsize) {
2069     case BLOCK_128X128: return best_var < 4 * thresh_64;
2070     case BLOCK_64X64: return best_var < thresh_64;
2071     case BLOCK_32X32: return best_var < thresh_32;
2072     case BLOCK_16X16: return best_var < thresh_32 / 4;
2073     default: return false;
2074   }
2075 }
2076 
fill_single_inter_mode_costs(int (* single_inter_mode_costs)[REF_FRAMES],int num_inter_modes,const REF_MODE * reference_mode_set,const ModeCosts * mode_costs,const int16_t * mode_context)2077 static AOM_FORCE_INLINE void fill_single_inter_mode_costs(
2078     int (*single_inter_mode_costs)[REF_FRAMES], int num_inter_modes,
2079     const REF_MODE *reference_mode_set, const ModeCosts *mode_costs,
2080     const int16_t *mode_context) {
2081   bool ref_frame_used[REF_FRAMES] = { false };
2082   for (int idx = 0; idx < num_inter_modes; idx++) {
2083     ref_frame_used[reference_mode_set[idx].ref_frame] = true;
2084   }
2085 
2086   for (int this_ref_frame = LAST_FRAME; this_ref_frame < REF_FRAMES;
2087        this_ref_frame++) {
2088     if (!ref_frame_used[this_ref_frame]) {
2089       continue;
2090     }
2091 
2092     const MV_REFERENCE_FRAME rf[2] = { this_ref_frame, NONE_FRAME };
2093     const int16_t mode_ctx = av1_mode_context_analyzer(mode_context, rf);
2094     for (PREDICTION_MODE this_mode = NEARESTMV; this_mode <= NEWMV;
2095          this_mode++) {
2096       single_inter_mode_costs[INTER_OFFSET(this_mode)][this_ref_frame] =
2097           cost_mv_ref(mode_costs, this_mode, mode_ctx);
2098     }
2099   }
2100 }
2101 
is_globalmv_better(PREDICTION_MODE this_mode,MV_REFERENCE_FRAME ref_frame,int rate_mv,const ModeCosts * mode_costs,const int (* single_inter_mode_costs)[REF_FRAMES],const MB_MODE_INFO_EXT * mbmi_ext)2102 static AOM_INLINE bool is_globalmv_better(
2103     PREDICTION_MODE this_mode, MV_REFERENCE_FRAME ref_frame, int rate_mv,
2104     const ModeCosts *mode_costs,
2105     const int (*single_inter_mode_costs)[REF_FRAMES],
2106     const MB_MODE_INFO_EXT *mbmi_ext) {
2107   const int globalmv_mode_cost =
2108       single_inter_mode_costs[INTER_OFFSET(GLOBALMV)][ref_frame];
2109   int this_mode_cost =
2110       rate_mv + single_inter_mode_costs[INTER_OFFSET(this_mode)][ref_frame];
2111   if (this_mode == NEWMV || this_mode == NEARMV) {
2112     const MV_REFERENCE_FRAME rf[2] = { ref_frame, NONE_FRAME };
2113     this_mode_cost += get_drl_cost(
2114         NEWMV, 0, mbmi_ext, mode_costs->drl_mode_cost0, av1_ref_frame_type(rf));
2115   }
2116   return this_mode_cost > globalmv_mode_cost;
2117 }
2118 
2119 // Set up the mv/ref_frames etc based on the comp_index. Returns 1 if it
2120 // succeeds, 0 if it fails.
setup_compound_params_from_comp_idx(const AV1_COMP * cpi,MACROBLOCK * x,struct buf_2d yv12_mb[8][MAX_MB_PLANE],PREDICTION_MODE * this_mode,MV_REFERENCE_FRAME * ref_frame,MV_REFERENCE_FRAME * ref_frame2,int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],const int * use_ref_frame_mask,int comp_index,bool comp_use_zero_zeromv_only,MV_REFERENCE_FRAME * last_comp_ref_frame,BLOCK_SIZE bsize)2121 static AOM_INLINE int setup_compound_params_from_comp_idx(
2122     const AV1_COMP *cpi, MACROBLOCK *x, struct buf_2d yv12_mb[8][MAX_MB_PLANE],
2123     PREDICTION_MODE *this_mode, MV_REFERENCE_FRAME *ref_frame,
2124     MV_REFERENCE_FRAME *ref_frame2, int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],
2125     const int *use_ref_frame_mask, int comp_index,
2126     bool comp_use_zero_zeromv_only, MV_REFERENCE_FRAME *last_comp_ref_frame,
2127     BLOCK_SIZE bsize) {
2128   const MV_REFERENCE_FRAME *rf = comp_ref_mode_set[comp_index].ref_frame;
2129   int skip_gf = 0;
2130   int skip_alt = 0;
2131   *this_mode = comp_ref_mode_set[comp_index].pred_mode;
2132   *ref_frame = rf[0];
2133   *ref_frame2 = rf[1];
2134   assert(*ref_frame == LAST_FRAME);
2135   assert(*this_mode == GLOBAL_GLOBALMV || *this_mode == NEAREST_NEARESTMV);
2136   if (x->source_variance < 50 && bsize > BLOCK_16X16) {
2137     if (x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_U)] == 1 ||
2138         x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_V)] == 1)
2139       skip_gf = 1;
2140     if (x->color_sensitivity_sb_alt[COLOR_SENS_IDX(AOM_PLANE_U)] == 1 ||
2141         x->color_sensitivity_sb_alt[COLOR_SENS_IDX(AOM_PLANE_V)] == 1)
2142       skip_alt = 1;
2143   }
2144   if (comp_use_zero_zeromv_only && *this_mode != GLOBAL_GLOBALMV) {
2145     return 0;
2146   }
2147   if (*ref_frame2 == GOLDEN_FRAME &&
2148       (cpi->sf.rt_sf.ref_frame_comp_nonrd[0] == 0 || skip_gf ||
2149        !(cpi->ref_frame_flags & AOM_GOLD_FLAG))) {
2150     return 0;
2151   } else if (*ref_frame2 == LAST2_FRAME &&
2152              (cpi->sf.rt_sf.ref_frame_comp_nonrd[1] == 0 ||
2153               !(cpi->ref_frame_flags & AOM_LAST2_FLAG))) {
2154     return 0;
2155   } else if (*ref_frame2 == ALTREF_FRAME &&
2156              (cpi->sf.rt_sf.ref_frame_comp_nonrd[2] == 0 || skip_alt ||
2157               !(cpi->ref_frame_flags & AOM_ALT_FLAG))) {
2158     return 0;
2159   }
2160   int ref_mv_idx = 0;
2161   if (*last_comp_ref_frame != rf[1]) {
2162     // Only needs to be done once per reference pair.
2163     setup_compound_prediction(&cpi->common, x, yv12_mb, use_ref_frame_mask, rf,
2164                               &ref_mv_idx);
2165     *last_comp_ref_frame = rf[1];
2166   }
2167   set_compound_mode(x, *ref_frame, *ref_frame2, ref_mv_idx, frame_mv,
2168                     *this_mode);
2169   if (*this_mode != GLOBAL_GLOBALMV &&
2170       frame_mv[*this_mode][*ref_frame].as_int == 0 &&
2171       frame_mv[*this_mode][*ref_frame2].as_int == 0) {
2172     return 0;
2173   }
2174 
2175   return 1;
2176 }
2177 
previous_mode_performed_poorly(PREDICTION_MODE mode,MV_REFERENCE_FRAME ref_frame,const unsigned int (* vars)[REF_FRAMES],const int64_t (* uv_dist)[REF_FRAMES])2178 static AOM_INLINE bool previous_mode_performed_poorly(
2179     PREDICTION_MODE mode, MV_REFERENCE_FRAME ref_frame,
2180     const unsigned int (*vars)[REF_FRAMES],
2181     const int64_t (*uv_dist)[REF_FRAMES]) {
2182   unsigned int best_var = UINT_MAX;
2183   int64_t best_uv_dist = INT64_MAX;
2184   for (int midx = 0; midx < RTC_INTER_MODES; midx++) {
2185     best_var = AOMMIN(best_var, vars[midx][ref_frame]);
2186     best_uv_dist = AOMMIN(best_uv_dist, uv_dist[midx][ref_frame]);
2187   }
2188   assert(best_var != UINT_MAX && "Invalid variance data.");
2189   const float mult = 1.125f;
2190   bool var_bad = mult * best_var < vars[INTER_OFFSET(mode)][ref_frame];
2191   if (uv_dist[INTER_OFFSET(mode)][ref_frame] < INT64_MAX &&
2192       best_uv_dist != uv_dist[INTER_OFFSET(mode)][ref_frame]) {
2193     // If we have chroma info, then take it into account
2194     var_bad &= mult * best_uv_dist < uv_dist[INTER_OFFSET(mode)][ref_frame];
2195   }
2196   return var_bad;
2197 }
2198 
prune_compoundmode_with_singlemode_var(PREDICTION_MODE compound_mode,MV_REFERENCE_FRAME ref_frame,MV_REFERENCE_FRAME ref_frame2,const int_mv (* frame_mv)[REF_FRAMES],const uint8_t (* mode_checked)[REF_FRAMES],const unsigned int (* vars)[REF_FRAMES],const int64_t (* uv_dist)[REF_FRAMES])2199 static AOM_INLINE bool prune_compoundmode_with_singlemode_var(
2200     PREDICTION_MODE compound_mode, MV_REFERENCE_FRAME ref_frame,
2201     MV_REFERENCE_FRAME ref_frame2, const int_mv (*frame_mv)[REF_FRAMES],
2202     const uint8_t (*mode_checked)[REF_FRAMES],
2203     const unsigned int (*vars)[REF_FRAMES],
2204     const int64_t (*uv_dist)[REF_FRAMES]) {
2205   const PREDICTION_MODE single_mode0 = compound_ref0_mode(compound_mode);
2206   const PREDICTION_MODE single_mode1 = compound_ref1_mode(compound_mode);
2207 
2208   bool first_ref_valid = false, second_ref_valid = false;
2209   bool first_ref_bad = false, second_ref_bad = false;
2210   if (mode_checked[single_mode0][ref_frame] &&
2211       frame_mv[single_mode0][ref_frame].as_int ==
2212           frame_mv[compound_mode][ref_frame].as_int &&
2213       vars[INTER_OFFSET(single_mode0)][ref_frame] < UINT_MAX) {
2214     first_ref_valid = true;
2215     first_ref_bad =
2216         previous_mode_performed_poorly(single_mode0, ref_frame, vars, uv_dist);
2217   }
2218   if (mode_checked[single_mode1][ref_frame2] &&
2219       frame_mv[single_mode1][ref_frame2].as_int ==
2220           frame_mv[compound_mode][ref_frame2].as_int &&
2221       vars[INTER_OFFSET(single_mode1)][ref_frame2] < UINT_MAX) {
2222     second_ref_valid = true;
2223     second_ref_bad =
2224         previous_mode_performed_poorly(single_mode1, ref_frame2, vars, uv_dist);
2225   }
2226   if (first_ref_valid && second_ref_valid) {
2227     return first_ref_bad && second_ref_bad;
2228   } else if (first_ref_valid || second_ref_valid) {
2229     return first_ref_bad || second_ref_bad;
2230   }
2231   return false;
2232 }
2233 
2234 // Function to setup parameters used for inter mode evaluation in non-rd.
set_params_nonrd_pick_inter_mode(AV1_COMP * cpi,MACROBLOCK * x,InterModeSearchStateNonrd * search_state,RD_STATS * rd_cost,int * force_skip_low_temp_var,int mi_row,int mi_col,int gf_temporal_ref,unsigned char segment_id,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,int denoise_svc_pickmode)2235 static AOM_FORCE_INLINE void set_params_nonrd_pick_inter_mode(
2236     AV1_COMP *cpi, MACROBLOCK *x, InterModeSearchStateNonrd *search_state,
2237     RD_STATS *rd_cost, int *force_skip_low_temp_var, int mi_row, int mi_col,
2238     int gf_temporal_ref, unsigned char segment_id, BLOCK_SIZE bsize
2239 #if CONFIG_AV1_TEMPORAL_DENOISING
2240     ,
2241     PICK_MODE_CONTEXT *ctx, int denoise_svc_pickmode
2242 #endif
2243 ) {
2244   AV1_COMMON *const cm = &cpi->common;
2245   MACROBLOCKD *const xd = &x->e_mbd;
2246   TxfmSearchInfo *txfm_info = &x->txfm_search_info;
2247   MB_MODE_INFO *const mi = xd->mi[0];
2248   const ModeCosts *mode_costs = &x->mode_costs;
2249   int skip_pred_mv = 0;
2250 
2251   // Initialize variance and distortion (chroma) for all modes and reference
2252   // frames
2253   for (int idx = 0; idx < RTC_INTER_MODES; idx++) {
2254     for (int ref = 0; ref < REF_FRAMES; ref++) {
2255       search_state->vars[idx][ref] = UINT_MAX;
2256       search_state->uv_dist[idx][ref] = INT64_MAX;
2257     }
2258   }
2259 
2260   // Initialize values of color sensitivity with sb level color sensitivity
2261   av1_copy(x->color_sensitivity, x->color_sensitivity_sb);
2262 
2263   init_best_pickmode(&search_state->best_pickmode);
2264 
2265   // Estimate cost for single reference frames
2266   estimate_single_ref_frame_costs(cm, xd, mode_costs, segment_id, bsize,
2267                                   search_state->ref_costs_single);
2268 
2269   // Reset flag to indicate modes evaluated
2270   av1_zero(search_state->mode_checked);
2271 
2272   txfm_info->skip_txfm = 0;
2273 
2274   // Initialize mode decisions
2275   av1_invalid_rd_stats(&search_state->best_rdc);
2276   av1_invalid_rd_stats(&search_state->this_rdc);
2277   av1_invalid_rd_stats(rd_cost);
2278   for (int ref_idx = 0; ref_idx < REF_FRAMES; ++ref_idx) {
2279     x->warp_sample_info[ref_idx].num = -1;
2280   }
2281 
2282   mi->bsize = bsize;
2283   mi->ref_frame[0] = NONE_FRAME;
2284   mi->ref_frame[1] = NONE_FRAME;
2285 
2286 #if CONFIG_AV1_TEMPORAL_DENOISING
2287   if (cpi->oxcf.noise_sensitivity > 0) {
2288     // if (cpi->ppi->use_svc) denoise_svc_pickmode =
2289     // av1_denoise_svc_non_key(cpi);
2290     if (cpi->denoiser.denoising_level > kDenLowLow && denoise_svc_pickmode)
2291       av1_denoiser_reset_frame_stats(ctx);
2292   }
2293 #endif
2294 
2295   // Populate predicated motion vectors for LAST_FRAME
2296   if (cpi->ref_frame_flags & AOM_LAST_FLAG) {
2297     find_predictors(cpi, x, LAST_FRAME, search_state->frame_mv,
2298                     search_state->yv12_mb, bsize, *force_skip_low_temp_var,
2299                     x->force_zeromv_skip_for_blk,
2300                     &search_state->use_scaled_ref_frame[LAST_FRAME]);
2301   }
2302   // Update mask to use all reference frame
2303   get_ref_frame_use_mask(cpi, x, mi, mi_row, mi_col, bsize, gf_temporal_ref,
2304                          search_state->use_ref_frame_mask,
2305                          force_skip_low_temp_var);
2306 
2307   skip_pred_mv = x->force_zeromv_skip_for_blk ||
2308                  (x->nonrd_prune_ref_frame_search > 2 &&
2309                   x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] != 2 &&
2310                   x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] != 2);
2311 
2312   // Populate predicated motion vectors for other single reference frame
2313   // Start at LAST_FRAME + 1.
2314   for (MV_REFERENCE_FRAME ref_frame_iter = LAST_FRAME + 1;
2315        ref_frame_iter <= ALTREF_FRAME; ++ref_frame_iter) {
2316     if (search_state->use_ref_frame_mask[ref_frame_iter]) {
2317       find_predictors(cpi, x, ref_frame_iter, search_state->frame_mv,
2318                       search_state->yv12_mb, bsize, *force_skip_low_temp_var,
2319                       skip_pred_mv,
2320                       &search_state->use_scaled_ref_frame[ref_frame_iter]);
2321     }
2322   }
2323 }
2324 
2325 // Function to check the inter mode can be skipped based on mode statistics and
2326 // speed features settings.
skip_inter_mode_nonrd(AV1_COMP * cpi,MACROBLOCK * x,InterModeSearchStateNonrd * search_state,int64_t * thresh_sad_pred,int * force_mv_inter_layer,int * is_single_pred,PREDICTION_MODE * this_mode,MV_REFERENCE_FRAME * last_comp_ref_frame,MV_REFERENCE_FRAME * ref_frame,MV_REFERENCE_FRAME * ref_frame2,int idx,int_mv svc_mv,int force_skip_low_temp_var,unsigned int sse_zeromv_norm,int num_inter_modes,unsigned char segment_id,BLOCK_SIZE bsize,bool comp_use_zero_zeromv_only,bool check_globalmv)2327 static AOM_FORCE_INLINE bool skip_inter_mode_nonrd(
2328     AV1_COMP *cpi, MACROBLOCK *x, InterModeSearchStateNonrd *search_state,
2329     int64_t *thresh_sad_pred, int *force_mv_inter_layer, int *is_single_pred,
2330     PREDICTION_MODE *this_mode, MV_REFERENCE_FRAME *last_comp_ref_frame,
2331     MV_REFERENCE_FRAME *ref_frame, MV_REFERENCE_FRAME *ref_frame2, int idx,
2332     int_mv svc_mv, int force_skip_low_temp_var, unsigned int sse_zeromv_norm,
2333     int num_inter_modes, unsigned char segment_id, BLOCK_SIZE bsize,
2334     bool comp_use_zero_zeromv_only, bool check_globalmv) {
2335   AV1_COMMON *const cm = &cpi->common;
2336   const struct segmentation *const seg = &cm->seg;
2337   const SVC *const svc = &cpi->svc;
2338   MACROBLOCKD *const xd = &x->e_mbd;
2339   MB_MODE_INFO *const mi = xd->mi[0];
2340   const REAL_TIME_SPEED_FEATURES *const rt_sf = &cpi->sf.rt_sf;
2341 
2342   // Skip compound mode based on reference frame mask and type of the mode and
2343   // for allowed compound modes, setup ref mv stack and reference frame.
2344   if (idx >= num_inter_modes) {
2345     const int comp_index = idx - num_inter_modes;
2346     if (!setup_compound_params_from_comp_idx(
2347             cpi, x, search_state->yv12_mb, this_mode, ref_frame, ref_frame2,
2348             search_state->frame_mv, search_state->use_ref_frame_mask,
2349             comp_index, comp_use_zero_zeromv_only, last_comp_ref_frame,
2350             bsize)) {
2351       return true;
2352     }
2353     *is_single_pred = 0;
2354   } else {
2355     *this_mode = ref_mode_set[idx].pred_mode;
2356     *ref_frame = ref_mode_set[idx].ref_frame;
2357     *ref_frame2 = NONE_FRAME;
2358   }
2359 
2360   if (segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP) &&
2361       (*this_mode != GLOBALMV || *ref_frame != LAST_FRAME))
2362     return true;
2363 
2364   if (x->sb_me_block && *ref_frame == LAST_FRAME) {
2365     // We want to make sure to test the superblock MV:
2366     // so don't skip (return false) for NEAREST_LAST or NEAR_LAST if they
2367     // have this sb MV. And don't skip NEWMV_LAST: this will be set to
2368     // sb MV in handle_inter_mode_nonrd(), in case NEAREST or NEAR don't
2369     // have it.
2370     if (*this_mode == NEARESTMV &&
2371         search_state->frame_mv[NEARESTMV][LAST_FRAME].as_int ==
2372             x->sb_me_mv.as_int) {
2373       return false;
2374     }
2375     if (*this_mode == NEARMV &&
2376         search_state->frame_mv[NEARMV][LAST_FRAME].as_int ==
2377             x->sb_me_mv.as_int) {
2378       return false;
2379     }
2380     if (*this_mode == NEWMV) {
2381       return false;
2382     }
2383   }
2384 
2385   // Skip the single reference mode for which mode check flag is set.
2386   if (*is_single_pred && search_state->mode_checked[*this_mode][*ref_frame]) {
2387     return true;
2388   }
2389 
2390   // Skip GLOBALMV mode if check_globalmv flag is not enabled.
2391   if (!check_globalmv && *this_mode == GLOBALMV) {
2392     return true;
2393   }
2394 
2395 #if COLLECT_NONRD_PICK_MODE_STAT
2396   aom_usec_timer_start(&x->ms_stat_nonrd.timer1);
2397   x->ms_stat_nonrd.num_searches[bsize][*this_mode]++;
2398 #endif
2399   mi->mode = *this_mode;
2400   mi->ref_frame[0] = *ref_frame;
2401   mi->ref_frame[1] = *ref_frame2;
2402 
2403   // Skip the mode if use reference frame mask flag is not set.
2404   if (!search_state->use_ref_frame_mask[*ref_frame]) return true;
2405 
2406   // Skip mode for some modes and reference frames when
2407   // force_zeromv_skip_for_blk flag is true.
2408   if (x->force_zeromv_skip_for_blk &&
2409       ((!(*this_mode == NEARESTMV &&
2410           search_state->frame_mv[*this_mode][*ref_frame].as_int == 0) &&
2411         *this_mode != GLOBALMV) ||
2412        *ref_frame != LAST_FRAME))
2413     return true;
2414 
2415   // Skip compound mode based on variance of previously evaluated single
2416   // reference modes.
2417   if (rt_sf->prune_compoundmode_with_singlemode_var && !*is_single_pred &&
2418       prune_compoundmode_with_singlemode_var(
2419           *this_mode, *ref_frame, *ref_frame2, search_state->frame_mv,
2420           search_state->mode_checked, search_state->vars,
2421           search_state->uv_dist)) {
2422     return true;
2423   }
2424 
2425   *force_mv_inter_layer = 0;
2426   if (cpi->ppi->use_svc && svc->spatial_layer_id > 0 &&
2427       ((*ref_frame == LAST_FRAME && svc->skip_mvsearch_last) ||
2428        (*ref_frame == GOLDEN_FRAME && svc->skip_mvsearch_gf) ||
2429        (*ref_frame == ALTREF_FRAME && svc->skip_mvsearch_altref))) {
2430     // Only test mode if NEARESTMV/NEARMV is (svc_mv.mv.col, svc_mv.mv.row),
2431     // otherwise set NEWMV to (svc_mv.mv.col, svc_mv.mv.row).
2432     // Skip newmv and filter search.
2433     *force_mv_inter_layer = 1;
2434     if (*this_mode == NEWMV) {
2435       search_state->frame_mv[*this_mode][*ref_frame] = svc_mv;
2436     } else if (search_state->frame_mv[*this_mode][*ref_frame].as_int !=
2437                svc_mv.as_int) {
2438       return true;
2439     }
2440   }
2441 
2442   // If the segment reference frame feature is enabled then do nothing if the
2443   // current ref frame is not allowed.
2444   if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
2445       get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)(*ref_frame))
2446     return true;
2447 
2448   // For screen content: skip mode testing based on source_sad.
2449   if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN) {
2450     // If source_sad is computed: skip non-zero motion
2451     // check for stationary (super)blocks. Otherwise if superblock
2452     // has motion skip the modes with zero motion on last reference
2453     // for flat blocks, and color is not set.
2454     // For the latter condition: the same condition should apply
2455     // to newmv if (0, 0), so this latter condition is repeated
2456     // below after search_new_mv.
2457     if (rt_sf->source_metrics_sb_nonrd) {
2458       if ((search_state->frame_mv[*this_mode][*ref_frame].as_int != 0 &&
2459            x->content_state_sb.source_sad_nonrd == kZeroSad) ||
2460           (search_state->frame_mv[*this_mode][*ref_frame].as_int == 0 &&
2461            x->block_is_zero_sad == 0 && *ref_frame == LAST_FRAME &&
2462            ((x->color_sensitivity_sb[COLOR_SENS_IDX(AOM_PLANE_U)] == 0 &&
2463              x->color_sensitivity_sb[COLOR_SENS_IDX(AOM_PLANE_V)] == 0) ||
2464             cpi->rc.high_source_sad) &&
2465            x->source_variance == 0))
2466         return true;
2467     }
2468     // Skip NEWMV search for flat blocks.
2469     if (*this_mode == NEWMV && x->source_variance < 100) return true;
2470     // Skip non-LAST for color on flat blocks.
2471     if (*ref_frame > LAST_FRAME && x->source_variance == 0 &&
2472         (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] == 1 ||
2473          x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] == 1))
2474       return true;
2475   }
2476 
2477   // Skip mode based on block size, reference frame mode and other block
2478   // properties.
2479   if (skip_mode_by_bsize_and_ref_frame(
2480           *this_mode, *ref_frame, bsize, x->nonrd_prune_ref_frame_search,
2481           sse_zeromv_norm, rt_sf->nonrd_aggressive_skip))
2482     return true;
2483 
2484   // Skip mode based on low temporal variance and souce sad.
2485   if (skip_mode_by_low_temp(*this_mode, *ref_frame, bsize, x->content_state_sb,
2486                             search_state->frame_mv[*this_mode][*ref_frame],
2487                             force_skip_low_temp_var))
2488     return true;
2489 
2490   // Disable this drop out case if the ref frame segment level feature is
2491   // enabled for this segment. This is to prevent the possibility that we
2492   // end up unable to pick any mode.
2493   if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
2494     // Check for skipping GOLDEN and ALTREF based pred_mv_sad.
2495     if (rt_sf->nonrd_prune_ref_frame_search > 0 &&
2496         x->pred_mv_sad[*ref_frame] != INT_MAX && *ref_frame != LAST_FRAME) {
2497       if ((int64_t)(x->pred_mv_sad[*ref_frame]) > *thresh_sad_pred) return true;
2498     }
2499   }
2500 
2501   // Check for skipping NEARMV based on pred_mv_sad.
2502   if (*this_mode == NEARMV && x->pred_mv1_sad[*ref_frame] != INT_MAX &&
2503       x->pred_mv1_sad[*ref_frame] > (x->pred_mv0_sad[*ref_frame] << 1))
2504     return true;
2505 
2506   // Skip single reference mode based on rd threshold.
2507   if (*is_single_pred) {
2508     if (skip_mode_by_threshold(
2509             *this_mode, *ref_frame,
2510             search_state->frame_mv[*this_mode][*ref_frame],
2511             cpi->rc.frames_since_golden, cpi->rd.threshes[segment_id][bsize],
2512             x->thresh_freq_fact[bsize], search_state->best_rdc.rdcost,
2513             search_state->best_pickmode.best_mode_skip_txfm,
2514             (rt_sf->nonrd_aggressive_skip ? 1 : 0)))
2515       return true;
2516   }
2517   return false;
2518 }
2519 
2520 // Function to perform inter mode evaluation for non-rd
handle_inter_mode_nonrd(AV1_COMP * cpi,MACROBLOCK * x,InterModeSearchStateNonrd * search_state,PICK_MODE_CONTEXT * ctx,PRED_BUFFER ** this_mode_pred,PRED_BUFFER * tmp_buffer,InterPredParams inter_pred_params_sr,int * best_early_term,unsigned int * sse_zeromv_norm,bool * check_globalmv,int64_t * zero_last_cost_orig,int denoise_svc_pickmode,int idx,int force_mv_inter_layer,int is_single_pred,int gf_temporal_ref,int use_model_yrd_large,int filter_search_enabled_blk,BLOCK_SIZE bsize,PREDICTION_MODE this_mode,InterpFilter filt_select,int cb_pred_filter_search,int reuse_inter_pred,int * sb_me_has_been_tested)2521 static AOM_FORCE_INLINE bool handle_inter_mode_nonrd(
2522     AV1_COMP *cpi, MACROBLOCK *x, InterModeSearchStateNonrd *search_state,
2523     PICK_MODE_CONTEXT *ctx, PRED_BUFFER **this_mode_pred,
2524     PRED_BUFFER *tmp_buffer, InterPredParams inter_pred_params_sr,
2525     int *best_early_term, unsigned int *sse_zeromv_norm, bool *check_globalmv,
2526 #if CONFIG_AV1_TEMPORAL_DENOISING
2527     int64_t *zero_last_cost_orig, int denoise_svc_pickmode,
2528 #endif
2529     int idx, int force_mv_inter_layer, int is_single_pred, int gf_temporal_ref,
2530     int use_model_yrd_large, int filter_search_enabled_blk, BLOCK_SIZE bsize,
2531     PREDICTION_MODE this_mode, InterpFilter filt_select,
2532     int cb_pred_filter_search, int reuse_inter_pred,
2533     int *sb_me_has_been_tested) {
2534   AV1_COMMON *const cm = &cpi->common;
2535   MACROBLOCKD *const xd = &x->e_mbd;
2536   MB_MODE_INFO *const mi = xd->mi[0];
2537   const MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
2538   const int mi_row = xd->mi_row;
2539   const int mi_col = xd->mi_col;
2540   struct macroblockd_plane *const pd = &xd->plane[AOM_PLANE_Y];
2541   const int bw = block_size_wide[bsize];
2542   const InterpFilter filter_ref = cm->features.interp_filter;
2543   const InterpFilter default_interp_filter = EIGHTTAP_REGULAR;
2544   TxfmSearchInfo *txfm_info = &x->txfm_search_info;
2545   const ModeCosts *mode_costs = &x->mode_costs;
2546   const REAL_TIME_SPEED_FEATURES *const rt_sf = &cpi->sf.rt_sf;
2547   BEST_PICKMODE *const best_pickmode = &search_state->best_pickmode;
2548 
2549   MV_REFERENCE_FRAME ref_frame = mi->ref_frame[0];
2550   MV_REFERENCE_FRAME ref_frame2 = mi->ref_frame[1];
2551   int_mv *const this_mv = &search_state->frame_mv[this_mode][ref_frame];
2552   unsigned int var = UINT_MAX;
2553   int this_early_term = 0;
2554   int rate_mv = 0;
2555   int is_skippable;
2556   int skip_this_mv = 0;
2557   unsigned int var_threshold = UINT_MAX;
2558   PREDICTION_MODE this_best_mode;
2559   RD_STATS nonskip_rdc;
2560   av1_invalid_rd_stats(&nonskip_rdc);
2561 
2562   if (x->sb_me_block && this_mode == NEWMV && ref_frame == LAST_FRAME) {
2563     // Set the NEWMV_LAST to the sb MV.
2564     search_state->frame_mv[NEWMV][LAST_FRAME].as_int = x->sb_me_mv.as_int;
2565   } else if (this_mode == NEWMV && !force_mv_inter_layer) {
2566 #if COLLECT_NONRD_PICK_MODE_STAT
2567     aom_usec_timer_start(&x->ms_stat_nonrd.timer2);
2568 #endif
2569     // Find the best motion vector for single/compound mode.
2570     const bool skip_newmv = search_new_mv(
2571         cpi, x, search_state->frame_mv, ref_frame, gf_temporal_ref, bsize,
2572         mi_row, mi_col, &rate_mv, &search_state->best_rdc);
2573 #if COLLECT_NONRD_PICK_MODE_STAT
2574     aom_usec_timer_mark(&x->ms_stat_nonrd.timer2);
2575     x->ms_stat_nonrd.ms_time[bsize][this_mode] +=
2576         aom_usec_timer_elapsed(&x->ms_stat_nonrd.timer2);
2577 #endif
2578     // Skip NEWMV mode,
2579     //   (i). For bsize smaller than 16X16
2580     //  (ii). Based on sad of the predicted mv w.r.t LAST_FRAME
2581     // (iii). When motion vector is same as that of reference mv
2582     if (skip_newmv) {
2583       return true;
2584     }
2585   }
2586 
2587   // Check the current motion vector is same as that of previously evaluated
2588   // motion vectors.
2589   for (PREDICTION_MODE inter_mv_mode = NEARESTMV; inter_mv_mode <= NEWMV;
2590        inter_mv_mode++) {
2591     if (inter_mv_mode == this_mode) continue;
2592     if (is_single_pred &&
2593         search_state->mode_checked[inter_mv_mode][ref_frame] &&
2594         this_mv->as_int ==
2595             search_state->frame_mv[inter_mv_mode][ref_frame].as_int) {
2596       skip_this_mv = 1;
2597       break;
2598     }
2599   }
2600 
2601   // Skip single mode if current motion vector is same that of previously
2602   // evaluated motion vectors.
2603   if (skip_this_mv && is_single_pred) return true;
2604 
2605   // For screen: for spatially flat blocks with non-zero motion,
2606   // skip newmv if the motion vector is (0, 0)-LAST, and color is not set.
2607   if (this_mode == NEWMV && cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN &&
2608       cpi->svc.spatial_layer_id == 0 && rt_sf->source_metrics_sb_nonrd) {
2609     if (this_mv->as_int == 0 && ref_frame == LAST_FRAME &&
2610         x->block_is_zero_sad == 0 &&
2611         ((x->color_sensitivity_sb[COLOR_SENS_IDX(AOM_PLANE_U)] == 0 &&
2612           x->color_sensitivity_sb[COLOR_SENS_IDX(AOM_PLANE_V)] == 0) ||
2613          cpi->rc.high_source_sad) &&
2614         x->source_variance == 0)
2615       return true;
2616   }
2617 
2618   mi->mode = this_mode;
2619   mi->mv[0].as_int = this_mv->as_int;
2620   mi->mv[1].as_int = 0;
2621   if (!is_single_pred)
2622     mi->mv[1].as_int = search_state->frame_mv[this_mode][ref_frame2].as_int;
2623 
2624   // Set buffers to store predicted samples for reuse
2625   if (reuse_inter_pred) {
2626     if (!*this_mode_pred) {
2627       *this_mode_pred = &tmp_buffer[3];
2628     } else {
2629       *this_mode_pred = &tmp_buffer[get_pred_buffer(tmp_buffer, 3)];
2630       pd->dst.buf = (*this_mode_pred)->data;
2631       pd->dst.stride = bw;
2632     }
2633   }
2634 
2635   mi->motion_mode = SIMPLE_TRANSLATION;
2636 #if !CONFIG_REALTIME_ONLY
2637   if (cpi->oxcf.motion_mode_cfg.allow_warped_motion) {
2638     calc_num_proj_ref(cpi, x, mi);
2639   }
2640 #endif
2641   // set variance threshold for compound mode pruning
2642   if (rt_sf->prune_compoundmode_with_singlecompound_var && !is_single_pred &&
2643       use_model_yrd_large) {
2644     const PREDICTION_MODE single_mode0 = compound_ref0_mode(this_mode);
2645     const PREDICTION_MODE single_mode1 = compound_ref1_mode(this_mode);
2646     var_threshold =
2647         AOMMIN(var_threshold,
2648                search_state->vars[INTER_OFFSET(single_mode0)][ref_frame]);
2649     var_threshold =
2650         AOMMIN(var_threshold,
2651                search_state->vars[INTER_OFFSET(single_mode1)][ref_frame2]);
2652   }
2653 
2654   // decide interpolation filter, build prediction signal, get sse
2655   const bool is_mv_subpel =
2656       (mi->mv[0].as_mv.row & 0x07) || (mi->mv[0].as_mv.col & 0x07);
2657   const bool enable_filt_search_this_mode =
2658       (filter_search_enabled_blk == 2)
2659           ? true
2660           : (filter_search_enabled_blk && !force_mv_inter_layer &&
2661              is_single_pred &&
2662              (ref_frame == LAST_FRAME || !x->nonrd_prune_ref_frame_search));
2663   if (is_mv_subpel && enable_filt_search_this_mode) {
2664 #if COLLECT_NONRD_PICK_MODE_STAT
2665     aom_usec_timer_start(&x->ms_stat_nonrd.timer2);
2666 #endif
2667     search_filter_ref(
2668         cpi, x, &search_state->this_rdc, &inter_pred_params_sr, mi_row, mi_col,
2669         tmp_buffer, bsize, reuse_inter_pred, this_mode_pred, &this_early_term,
2670         &var, use_model_yrd_large, best_pickmode->best_sse, is_single_pred);
2671 #if COLLECT_NONRD_PICK_MODE_STAT
2672     aom_usec_timer_mark(&x->ms_stat_nonrd.timer2);
2673     x->ms_stat_nonrd.ifs_time[bsize][this_mode] +=
2674         aom_usec_timer_elapsed(&x->ms_stat_nonrd.timer2);
2675 #endif
2676 #if !CONFIG_REALTIME_ONLY
2677   } else if (cpi->oxcf.motion_mode_cfg.allow_warped_motion &&
2678              this_mode == NEWMV) {
2679     // Find the best motion mode when current mode is NEWMV
2680     search_motion_mode(cpi, x, &search_state->this_rdc, mi_row, mi_col, bsize,
2681                        &this_early_term, use_model_yrd_large, &rate_mv,
2682                        best_pickmode->best_sse);
2683     if (this_mode == NEWMV) {
2684       this_mv[0] = mi->mv[0];
2685     }
2686 #endif
2687   } else {
2688     mi->interp_filters =
2689         (filter_ref == SWITCHABLE)
2690             ? av1_broadcast_interp_filter(default_interp_filter)
2691             : av1_broadcast_interp_filter(filter_ref);
2692     if (force_mv_inter_layer)
2693       mi->interp_filters = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
2694 
2695     // If it is sub-pel motion and cb_pred_filter_search is enabled, select
2696     // the pre-decided filter
2697     if (is_mv_subpel && cb_pred_filter_search)
2698       mi->interp_filters = av1_broadcast_interp_filter(filt_select);
2699 
2700 #if COLLECT_NONRD_PICK_MODE_STAT
2701     aom_usec_timer_start(&x->ms_stat_nonrd.timer2);
2702 #endif
2703     if (is_single_pred) {
2704       SubpelParams subpel_params;
2705       // Initialize inter mode level params for single reference mode.
2706       init_inter_mode_params(&mi->mv[0].as_mv, &inter_pred_params_sr,
2707                              &subpel_params, xd->block_ref_scale_factors[0],
2708                              pd->pre->width, pd->pre->height);
2709       av1_enc_build_inter_predictor_y_nonrd(xd, &inter_pred_params_sr,
2710                                             &subpel_params);
2711     } else {
2712       av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
2713                                     AOM_PLANE_Y, AOM_PLANE_Y);
2714     }
2715 
2716     if (use_model_yrd_large) {
2717       model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd,
2718                                 &search_state->this_rdc, &this_early_term, 0,
2719                                 best_pickmode->best_sse, &var, var_threshold);
2720     } else {
2721       model_rd_for_sb_y(cpi, bsize, x, xd, &search_state->this_rdc, &var, 0,
2722                         &this_early_term);
2723     }
2724 #if COLLECT_NONRD_PICK_MODE_STAT
2725     aom_usec_timer_mark(&x->ms_stat_nonrd.timer2);
2726     x->ms_stat_nonrd.model_rd_time[bsize][this_mode] +=
2727         aom_usec_timer_elapsed(&x->ms_stat_nonrd.timer2);
2728 #endif
2729   }
2730 
2731   // update variance for single mode
2732   if (is_single_pred) {
2733     search_state->vars[INTER_OFFSET(this_mode)][ref_frame] = var;
2734     if (this_mv->as_int == 0) {
2735       search_state->vars[INTER_OFFSET(GLOBALMV)][ref_frame] = var;
2736     }
2737   }
2738   // prune compound mode based on single mode var threshold
2739   if (!is_single_pred && var > var_threshold) {
2740     if (reuse_inter_pred) free_pred_buffer(*this_mode_pred);
2741     return true;
2742   }
2743 
2744   if (ref_frame == LAST_FRAME && this_mv->as_int == 0) {
2745     *sse_zeromv_norm = (unsigned int)(search_state->this_rdc.sse >>
2746                                       (b_width_log2_lookup[bsize] +
2747                                        b_height_log2_lookup[bsize]));
2748   }
2749 
2750   // Perform early termination based on sse.
2751   if (rt_sf->sse_early_term_inter_search &&
2752       early_term_inter_search_with_sse(rt_sf->sse_early_term_inter_search,
2753                                        bsize, search_state->this_rdc.sse,
2754                                        best_pickmode->best_sse, this_mode)) {
2755     if (reuse_inter_pred) free_pred_buffer(*this_mode_pred);
2756     return true;
2757   }
2758 
2759 #if COLLECT_NONRD_PICK_MODE_STAT
2760   x->ms_stat_nonrd.num_nonskipped_searches[bsize][this_mode]++;
2761 #endif
2762 
2763   const int skip_ctx = av1_get_skip_txfm_context(xd);
2764   const int skip_txfm_cost = mode_costs->skip_txfm_cost[skip_ctx][1];
2765   const int no_skip_txfm_cost = mode_costs->skip_txfm_cost[skip_ctx][0];
2766   const int64_t sse_y = search_state->this_rdc.sse;
2767 
2768   if (this_early_term) {
2769     search_state->this_rdc.skip_txfm = 1;
2770     search_state->this_rdc.rate = skip_txfm_cost;
2771     search_state->this_rdc.dist = search_state->this_rdc.sse << 4;
2772   } else {
2773 #if COLLECT_NONRD_PICK_MODE_STAT
2774     aom_usec_timer_start(&x->ms_stat_nonrd.timer2);
2775 #endif
2776     // Calculates RD Cost using Hadamard transform.
2777     av1_block_yrd(x, &search_state->this_rdc, &is_skippable, bsize,
2778                   mi->tx_size);
2779     if (search_state->this_rdc.skip_txfm ||
2780         RDCOST(x->rdmult, search_state->this_rdc.rate,
2781                search_state->this_rdc.dist) >=
2782             RDCOST(x->rdmult, 0, search_state->this_rdc.sse)) {
2783       if (!search_state->this_rdc.skip_txfm) {
2784         // Need to store "real" rdc for possible future use if UV rdc
2785         // disallows tx skip
2786         nonskip_rdc = search_state->this_rdc;
2787         nonskip_rdc.rate += no_skip_txfm_cost;
2788       }
2789       search_state->this_rdc.rate = skip_txfm_cost;
2790       search_state->this_rdc.skip_txfm = 1;
2791       search_state->this_rdc.dist = search_state->this_rdc.sse;
2792     } else {
2793       search_state->this_rdc.rate += no_skip_txfm_cost;
2794     }
2795 
2796     // Populate predicted sample for chroma planes based on color sensitivity.
2797     if ((x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] ||
2798          x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)])) {
2799       RD_STATS rdc_uv;
2800       const BLOCK_SIZE uv_bsize =
2801           get_plane_block_size(bsize, xd->plane[AOM_PLANE_U].subsampling_x,
2802                                xd->plane[AOM_PLANE_U].subsampling_y);
2803       if (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)]) {
2804         av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
2805                                       AOM_PLANE_U, AOM_PLANE_U);
2806       }
2807       if (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)]) {
2808         av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
2809                                       AOM_PLANE_V, AOM_PLANE_V);
2810       }
2811       // Compute sse for chroma planes.
2812       const int64_t sse_uv = av1_model_rd_for_sb_uv(
2813           cpi, uv_bsize, x, xd, &rdc_uv, AOM_PLANE_U, AOM_PLANE_V);
2814       if (rdc_uv.dist < x->min_dist_inter_uv)
2815         x->min_dist_inter_uv = rdc_uv.dist;
2816       search_state->this_rdc.sse += sse_uv;
2817       // Restore Y rdc if UV rdc disallows txfm skip
2818       if (search_state->this_rdc.skip_txfm && !rdc_uv.skip_txfm &&
2819           nonskip_rdc.rate != INT_MAX)
2820         search_state->this_rdc = nonskip_rdc;
2821       if (is_single_pred) {
2822         search_state->uv_dist[INTER_OFFSET(this_mode)][ref_frame] = rdc_uv.dist;
2823       }
2824       search_state->this_rdc.rate += rdc_uv.rate;
2825       search_state->this_rdc.dist += rdc_uv.dist;
2826       search_state->this_rdc.skip_txfm =
2827           search_state->this_rdc.skip_txfm && rdc_uv.skip_txfm;
2828     }
2829 #if COLLECT_NONRD_PICK_MODE_STAT
2830     aom_usec_timer_mark(&x->ms_stat_nonrd.timer2);
2831     x->ms_stat_nonrd.txfm_time[bsize][this_mode] +=
2832         aom_usec_timer_elapsed(&x->ms_stat_nonrd.timer2);
2833 #endif
2834   }
2835 
2836   this_best_mode = this_mode;
2837   // TODO(kyslov) account for UV prediction cost
2838   search_state->this_rdc.rate += rate_mv;
2839   if (!is_single_pred) {
2840     const int16_t mode_ctx =
2841         av1_mode_context_analyzer(mbmi_ext->mode_context, mi->ref_frame);
2842     search_state->this_rdc.rate += cost_mv_ref(mode_costs, this_mode, mode_ctx);
2843   } else {
2844     // If the current mode has zeromv but is not GLOBALMV, compare the rate
2845     // cost. If GLOBALMV is cheaper, use GLOBALMV instead.
2846     if (this_mode != GLOBALMV &&
2847         this_mv->as_int == search_state->frame_mv[GLOBALMV][ref_frame].as_int) {
2848       if (is_globalmv_better(this_mode, ref_frame, rate_mv, mode_costs,
2849                              search_state->single_inter_mode_costs, mbmi_ext)) {
2850         this_best_mode = GLOBALMV;
2851       }
2852     }
2853 
2854     search_state->this_rdc.rate +=
2855         search_state
2856             ->single_inter_mode_costs[INTER_OFFSET(this_best_mode)][ref_frame];
2857   }
2858 
2859   if (is_single_pred && this_mv->as_int == 0 && var < UINT_MAX) {
2860     search_state->vars[INTER_OFFSET(GLOBALMV)][ref_frame] = var;
2861   }
2862 
2863   search_state->this_rdc.rate += search_state->ref_costs_single[ref_frame];
2864 
2865   search_state->this_rdc.rdcost = RDCOST(x->rdmult, search_state->this_rdc.rate,
2866                                          search_state->this_rdc.dist);
2867   if (cpi->oxcf.rc_cfg.mode == AOM_CBR && is_single_pred) {
2868     newmv_diff_bias(xd, this_best_mode, &search_state->this_rdc, bsize,
2869                     search_state->frame_mv[this_best_mode][ref_frame].as_mv.row,
2870                     search_state->frame_mv[this_best_mode][ref_frame].as_mv.col,
2871                     cpi->speed, x->source_variance, x->content_state_sb);
2872   }
2873 
2874 #if CONFIG_AV1_TEMPORAL_DENOISING
2875   if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc_pickmode &&
2876       cpi->denoiser.denoising_level > kDenLowLow) {
2877     av1_denoiser_update_frame_stats(mi, sse_y, this_mode, ctx);
2878     // Keep track of zero_last cost.
2879     if (ref_frame == LAST_FRAME && this_mv->as_int == 0)
2880       *zero_last_cost_orig = search_state->this_rdc.rdcost;
2881   }
2882 #else
2883   (void)(sse_y);
2884 #endif
2885 
2886   search_state->mode_checked[this_mode][ref_frame] = 1;
2887   search_state->mode_checked[this_best_mode][ref_frame] = 1;
2888 
2889   if (*check_globalmv) {
2890     int32_t abs_mv =
2891         abs(search_state->frame_mv[this_best_mode][ref_frame].as_mv.row) +
2892         abs(search_state->frame_mv[this_best_mode][ref_frame].as_mv.col);
2893     // Early exit check: if the magnitude of this_best_mode's mv is small
2894     // enough, we skip GLOBALMV check in the next loop iteration.
2895     if (abs_mv < 2) {
2896       *check_globalmv = false;
2897     }
2898   }
2899 #if COLLECT_NONRD_PICK_MODE_STAT
2900   aom_usec_timer_mark(&x->ms_stat_nonrd.timer1);
2901   x->ms_stat_nonrd.nonskipped_search_times[bsize][this_mode] +=
2902       aom_usec_timer_elapsed(&x->ms_stat_nonrd.timer1);
2903 #endif
2904 
2905   if (x->sb_me_block && ref_frame == LAST_FRAME &&
2906       search_state->frame_mv[this_best_mode][ref_frame].as_int ==
2907           x->sb_me_mv.as_int)
2908     *sb_me_has_been_tested = 1;
2909 
2910   // Copy best mode params to search state
2911   if (search_state->this_rdc.rdcost < search_state->best_rdc.rdcost) {
2912     search_state->best_rdc = search_state->this_rdc;
2913     *best_early_term = this_early_term;
2914     update_search_state_nonrd(search_state, mi, txfm_info, &nonskip_rdc, ctx,
2915                               this_best_mode, sse_y);
2916 
2917     // This is needed for the compound modes.
2918     search_state->frame_mv_best[this_best_mode][ref_frame].as_int =
2919         search_state->frame_mv[this_best_mode][ref_frame].as_int;
2920     if (ref_frame2 > NONE_FRAME) {
2921       search_state->frame_mv_best[this_best_mode][ref_frame2].as_int =
2922           search_state->frame_mv[this_best_mode][ref_frame2].as_int;
2923     }
2924 
2925     if (reuse_inter_pred) {
2926       free_pred_buffer(best_pickmode->best_pred);
2927       best_pickmode->best_pred = *this_mode_pred;
2928     }
2929   } else {
2930     if (reuse_inter_pred) free_pred_buffer(*this_mode_pred);
2931   }
2932 
2933   if (*best_early_term && (idx > 0 || rt_sf->nonrd_aggressive_skip)) {
2934     txfm_info->skip_txfm = 1;
2935     if (!x->sb_me_block || *sb_me_has_been_tested) return false;
2936   }
2937   return true;
2938 }
2939 
2940 // Function to perform screen content mode evaluation for non-rd
handle_screen_content_mode_nonrd(AV1_COMP * cpi,MACROBLOCK * x,InterModeSearchStateNonrd * search_state,PRED_BUFFER * this_mode_pred,PICK_MODE_CONTEXT * ctx,PRED_BUFFER * tmp_buffer,struct buf_2d * orig_dst,int skip_idtx_palette,int try_palette,BLOCK_SIZE bsize,int reuse_inter_pred,int mi_col,int mi_row)2941 static AOM_FORCE_INLINE void handle_screen_content_mode_nonrd(
2942     AV1_COMP *cpi, MACROBLOCK *x, InterModeSearchStateNonrd *search_state,
2943     PRED_BUFFER *this_mode_pred, PICK_MODE_CONTEXT *ctx,
2944     PRED_BUFFER *tmp_buffer, struct buf_2d *orig_dst, int skip_idtx_palette,
2945     int try_palette, BLOCK_SIZE bsize, int reuse_inter_pred, int mi_col,
2946     int mi_row) {
2947   AV1_COMMON *const cm = &cpi->common;
2948   const REAL_TIME_SPEED_FEATURES *const rt_sf = &cpi->sf.rt_sf;
2949   MACROBLOCKD *const xd = &x->e_mbd;
2950   MB_MODE_INFO *const mi = xd->mi[0];
2951   struct macroblockd_plane *const pd = &xd->plane[0];
2952   const int bw = block_size_wide[bsize];
2953   const int bh = block_size_high[bsize];
2954   TxfmSearchInfo *txfm_info = &x->txfm_search_info;
2955   BEST_PICKMODE *const best_pickmode = &search_state->best_pickmode;
2956 
2957   // TODO(marpan): Only allow for 8 bit-depth for now, re-enable for 10/12 bit
2958   // when issue 3359 is fixed.
2959   if (cm->seq_params->bit_depth == 8 &&
2960       cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN && !skip_idtx_palette &&
2961       !cpi->oxcf.txfm_cfg.use_inter_dct_only && !x->force_zeromv_skip_for_blk &&
2962       is_inter_mode(best_pickmode->best_mode) &&
2963       best_pickmode->best_pred != NULL &&
2964       (!rt_sf->prune_idtx_nonrd ||
2965        (rt_sf->prune_idtx_nonrd && bsize <= BLOCK_32X32 &&
2966         best_pickmode->best_mode_skip_txfm != 1 && x->source_variance > 200))) {
2967     RD_STATS idtx_rdc;
2968     av1_init_rd_stats(&idtx_rdc);
2969     int is_skippable;
2970     this_mode_pred = &tmp_buffer[get_pred_buffer(tmp_buffer, 3)];
2971     pd->dst.buf = this_mode_pred->data;
2972     pd->dst.stride = bw;
2973     const PRED_BUFFER *const best_pred = best_pickmode->best_pred;
2974     av1_block_yrd_idtx(x, best_pred->data, best_pred->stride, &idtx_rdc,
2975                        &is_skippable, bsize, mi->tx_size);
2976     int64_t idx_rdcost_y = RDCOST(x->rdmult, idtx_rdc.rate, idtx_rdc.dist);
2977     int allow_idtx = 1;
2978     // Incorporate color into rd cost.
2979     if ((x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] ||
2980          x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)])) {
2981       RD_STATS rdc_uv;
2982       const BLOCK_SIZE uv_bsize =
2983           get_plane_block_size(bsize, xd->plane[AOM_PLANE_U].subsampling_x,
2984                                xd->plane[AOM_PLANE_U].subsampling_y);
2985       if (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)]) {
2986         av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
2987                                       AOM_PLANE_U, AOM_PLANE_U);
2988       }
2989       if (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)]) {
2990         av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
2991                                       AOM_PLANE_V, AOM_PLANE_V);
2992       }
2993       av1_model_rd_for_sb_uv(cpi, uv_bsize, x, xd, &rdc_uv, AOM_PLANE_U,
2994                              AOM_PLANE_V);
2995       if (rdc_uv.dist < x->min_dist_inter_uv)
2996         x->min_dist_inter_uv = rdc_uv.dist;
2997       idtx_rdc.rate += rdc_uv.rate;
2998       idtx_rdc.dist += rdc_uv.dist;
2999       idtx_rdc.skip_txfm = idtx_rdc.skip_txfm && rdc_uv.skip_txfm;
3000       if (idx_rdcost_y == 0 && rdc_uv.dist > 0 && x->source_variance < 3000 &&
3001           x->content_state_sb.source_sad_nonrd > kMedSad)
3002         allow_idtx = 0;
3003     }
3004     int64_t idx_rdcost = RDCOST(x->rdmult, idtx_rdc.rate, idtx_rdc.dist);
3005     if (allow_idtx && idx_rdcost < search_state->best_rdc.rdcost) {
3006       best_pickmode->tx_type = IDTX;
3007       search_state->best_rdc.rdcost = idx_rdcost;
3008       best_pickmode->best_mode_skip_txfm = idtx_rdc.skip_txfm;
3009       if (!idtx_rdc.skip_txfm) {
3010         memcpy(ctx->blk_skip, txfm_info->blk_skip,
3011                sizeof(txfm_info->blk_skip[0]) * ctx->num_4x4_blk);
3012       }
3013       xd->tx_type_map[0] = best_pickmode->tx_type;
3014       memset(ctx->tx_type_map, best_pickmode->tx_type, ctx->num_4x4_blk);
3015       memset(xd->tx_type_map, best_pickmode->tx_type, ctx->num_4x4_blk);
3016     }
3017     pd->dst = *orig_dst;
3018   }
3019 
3020   if (!try_palette) return;
3021   const unsigned int intra_ref_frame_cost =
3022       search_state->ref_costs_single[INTRA_FRAME];
3023 
3024   if (!is_mode_intra(best_pickmode->best_mode)) {
3025     PRED_BUFFER *const best_pred = best_pickmode->best_pred;
3026     if (reuse_inter_pred && best_pred != NULL) {
3027       if (best_pred->data == orig_dst->buf) {
3028         this_mode_pred = &tmp_buffer[get_pred_buffer(tmp_buffer, 3)];
3029         aom_convolve_copy(best_pred->data, best_pred->stride,
3030                           this_mode_pred->data, this_mode_pred->stride, bw, bh);
3031         best_pickmode->best_pred = this_mode_pred;
3032       }
3033     }
3034     pd->dst = *orig_dst;
3035   }
3036   // Search palette mode for Luma plane in inter frame.
3037   av1_search_palette_mode_luma(cpi, x, bsize, intra_ref_frame_cost, ctx,
3038                                &search_state->this_rdc,
3039                                search_state->best_rdc.rdcost);
3040   // Update best mode data in search_state
3041   if (search_state->this_rdc.rdcost < search_state->best_rdc.rdcost) {
3042     best_pickmode->pmi = mi->palette_mode_info;
3043     best_pickmode->best_mode = DC_PRED;
3044     mi->mv[0].as_int = INVALID_MV;
3045     mi->mv[1].as_int = INVALID_MV;
3046     best_pickmode->best_ref_frame = INTRA_FRAME;
3047     best_pickmode->best_second_ref_frame = NONE;
3048     search_state->best_rdc.rate = search_state->this_rdc.rate;
3049     search_state->best_rdc.dist = search_state->this_rdc.dist;
3050     search_state->best_rdc.rdcost = search_state->this_rdc.rdcost;
3051     best_pickmode->best_mode_skip_txfm = search_state->this_rdc.skip_txfm;
3052     // Keep the skip_txfm off if the color_sensitivity is set.
3053     if (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] ||
3054         x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)])
3055       search_state->this_rdc.skip_txfm = 0;
3056     if (!search_state->this_rdc.skip_txfm) {
3057       memcpy(ctx->blk_skip, txfm_info->blk_skip,
3058              sizeof(txfm_info->blk_skip[0]) * ctx->num_4x4_blk);
3059     }
3060     if (xd->tx_type_map[0] != DCT_DCT)
3061       av1_copy_array(ctx->tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
3062   }
3063 }
3064 
3065 /*!\brief AV1 inter mode selection based on Non-RD optimized model.
3066  *
3067  * \ingroup nonrd_mode_search
3068  * \callgraph
3069  * Top level function for Non-RD optimized inter mode selection.
3070  * This finction will loop over subset of inter modes and select the best one
3071  * based on calculated modelled RD cost. While making decisions which modes to
3072  * check, this function applies heuristics based on previously checked modes,
3073  * block residual variance, block size, and other factors to prune certain
3074  * modes and reference frames. Currently only single reference frame modes
3075  * are checked. Additional heuristics are applied to decide if intra modes
3076  *  need to be checked.
3077  *  *
3078  * \param[in]    cpi            Top-level encoder structure
3079  * \param[in]    tile_data      Pointer to struct holding adaptive
3080                                 data/contexts/models for the tile during
3081                                 encoding
3082  * \param[in]    x              Pointer to structure holding all the data for
3083                                 the current macroblock
3084  * \param[in]    rd_cost        Struct to keep track of the RD information
3085  * \param[in]    bsize          Current block size
3086  * \param[in]    ctx            Structure to hold snapshot of coding context
3087                                 during the mode picking process
3088  *
3089  * \remark Nothing is returned. Instead, the MB_MODE_INFO struct inside x
3090  * is modified to store information about the best mode computed
3091  * in this function. The rd_cost struct is also updated with the RD stats
3092  * corresponding to the best mode found.
3093  */
av1_nonrd_pick_inter_mode_sb(AV1_COMP * cpi,TileDataEnc * tile_data,MACROBLOCK * x,RD_STATS * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)3094 void av1_nonrd_pick_inter_mode_sb(AV1_COMP *cpi, TileDataEnc *tile_data,
3095                                   MACROBLOCK *x, RD_STATS *rd_cost,
3096                                   BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
3097   AV1_COMMON *const cm = &cpi->common;
3098   SVC *const svc = &cpi->svc;
3099   MACROBLOCKD *const xd = &x->e_mbd;
3100   MB_MODE_INFO *const mi = xd->mi[0];
3101   struct macroblockd_plane *const pd = &xd->plane[AOM_PLANE_Y];
3102   const MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
3103   MV_REFERENCE_FRAME ref_frame, ref_frame2;
3104   const unsigned char segment_id = mi->segment_id;
3105   int best_early_term = 0;
3106   int force_skip_low_temp_var = 0;
3107   unsigned int sse_zeromv_norm = UINT_MAX;
3108   const int num_inter_modes = NUM_INTER_MODES;
3109   const REAL_TIME_SPEED_FEATURES *const rt_sf = &cpi->sf.rt_sf;
3110   bool check_globalmv = rt_sf->check_globalmv_on_single_ref;
3111   PRED_BUFFER tmp_buffer[4];
3112   DECLARE_ALIGNED(16, uint8_t, pred_buf[MAX_MB_PLANE * MAX_SB_SQUARE]);
3113   PRED_BUFFER *this_mode_pred = NULL;
3114   const int reuse_inter_pred =
3115       rt_sf->reuse_inter_pred_nonrd && cm->seq_params->bit_depth == AOM_BITS_8;
3116   InterModeSearchStateNonrd search_state;
3117   av1_zero(search_state.use_ref_frame_mask);
3118   av1_zero(search_state.use_scaled_ref_frame);
3119   BEST_PICKMODE *const best_pickmode = &search_state.best_pickmode;
3120   (void)tile_data;
3121 
3122   const int bh = block_size_high[bsize];
3123   const int bw = block_size_wide[bsize];
3124   const int pixels_in_block = bh * bw;
3125   struct buf_2d orig_dst = pd->dst;
3126   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
3127   TxfmSearchInfo *txfm_info = &x->txfm_search_info;
3128 #if COLLECT_NONRD_PICK_MODE_STAT
3129   // Mode statistics can be collected only when num_workers is 1
3130   assert(cpi->mt_info.num_workers <= 1);
3131   aom_usec_timer_start(&x->ms_stat_nonrd.bsize_timer);
3132 #endif
3133   int64_t thresh_sad_pred = INT64_MAX;
3134   const int mi_row = xd->mi_row;
3135   const int mi_col = xd->mi_col;
3136   int_mv svc_mv = { .as_int = 0 };
3137   int force_mv_inter_layer = 0;
3138   bool comp_use_zero_zeromv_only = 0;
3139   int tot_num_comp_modes = NUM_COMP_INTER_MODES_RT;
3140 #if CONFIG_AV1_TEMPORAL_DENOISING
3141   const int denoise_recheck_zeromv = 1;
3142   AV1_PICKMODE_CTX_DEN ctx_den;
3143   int64_t zero_last_cost_orig = INT64_MAX;
3144   int denoise_svc_pickmode = 1;
3145   const int resize_pending = is_frame_resize_pending(cpi);
3146 #endif
3147   const ModeCosts *mode_costs = &x->mode_costs;
3148   struct scale_factors sf_no_scale;
3149   av1_setup_scale_factors_for_frame(&sf_no_scale, cm->width, cm->height,
3150                                     cm->width, cm->height);
3151   if (reuse_inter_pred) {
3152     for (int buf_idx = 0; buf_idx < 3; buf_idx++) {
3153       tmp_buffer[buf_idx].data = &pred_buf[pixels_in_block * buf_idx];
3154       tmp_buffer[buf_idx].stride = bw;
3155       tmp_buffer[buf_idx].in_use = 0;
3156     }
3157     tmp_buffer[3].data = pd->dst.buf;
3158     tmp_buffer[3].stride = pd->dst.stride;
3159     tmp_buffer[3].in_use = 0;
3160   }
3161 
3162   const int gf_temporal_ref = is_same_gf_and_last_scale(cm);
3163 
3164   // If the lower spatial layer uses an averaging filter for downsampling
3165   // (phase = 8), the target decimated pixel is shifted by (1/2, 1/2) relative
3166   // to source, so use subpel motion vector to compensate. The nonzero motion
3167   // is half pixel shifted to left and top, so (-4, -4). This has more effect
3168   // on higher resolutions, so condition it on that for now.
3169   // Exclude quality layers, which have the same resolution and hence no shift.
3170   if (cpi->ppi->use_svc && svc->spatial_layer_id > 0 &&
3171       !svc->has_lower_quality_layer &&
3172       svc->downsample_filter_phase[svc->spatial_layer_id - 1] == 8 &&
3173       cm->width * cm->height > 640 * 480) {
3174     svc_mv.as_mv.row = -4;
3175     svc_mv.as_mv.col = -4;
3176   }
3177 
3178   // Setup parameters used for inter mode evaluation.
3179   set_params_nonrd_pick_inter_mode(cpi, x, &search_state, rd_cost,
3180                                    &force_skip_low_temp_var, mi_row, mi_col,
3181                                    gf_temporal_ref, segment_id, bsize
3182 #if CONFIG_AV1_TEMPORAL_DENOISING
3183                                    ,
3184                                    ctx, denoise_svc_pickmode
3185 #endif
3186   );
3187 
3188   if (rt_sf->use_comp_ref_nonrd && is_comp_ref_allowed(bsize)) {
3189     // Only search compound if bsize \gt BLOCK_16X16.
3190     if (bsize > BLOCK_16X16) {
3191       comp_use_zero_zeromv_only = rt_sf->check_only_zero_zeromv_on_large_blocks;
3192     } else {
3193       tot_num_comp_modes = 0;
3194     }
3195   } else {
3196     tot_num_comp_modes = 0;
3197   }
3198 
3199   if (x->pred_mv_sad[LAST_FRAME] != INT_MAX) {
3200     thresh_sad_pred = ((int64_t)x->pred_mv_sad[LAST_FRAME]) << 1;
3201     // Increase threshold for less aggressive pruning.
3202     if (rt_sf->nonrd_prune_ref_frame_search == 1)
3203       thresh_sad_pred += (x->pred_mv_sad[LAST_FRAME] >> 2);
3204   }
3205 
3206   const int use_model_yrd_large = get_model_rd_flag(cpi, xd, bsize);
3207 
3208   // decide block-level interp filter search flags:
3209   // filter_search_enabled_blk:
3210   // 0: disabled
3211   // 1: filter search depends on mode properties
3212   // 2: filter search forced since prediction is unreliable
3213   // cb_pred_filter_search 0: disabled cb prediction
3214   InterpFilter filt_select = EIGHTTAP_REGULAR;
3215   const int cb_pred_filter_search =
3216       x->content_state_sb.source_sad_nonrd > kVeryLowSad
3217           ? cpi->sf.interp_sf.cb_pred_filter_search
3218           : 0;
3219   const int filter_search_enabled_blk =
3220       is_filter_search_enabled_blk(cpi, x, mi_row, mi_col, bsize, segment_id,
3221                                    cb_pred_filter_search, &filt_select);
3222 
3223 #if COLLECT_NONRD_PICK_MODE_STAT
3224   x->ms_stat_nonrd.num_blocks[bsize]++;
3225 #endif
3226   init_mbmi_nonrd(mi, DC_PRED, NONE_FRAME, NONE_FRAME, cm);
3227   mi->tx_size = AOMMIN(
3228       AOMMIN(max_txsize_lookup[bsize],
3229              tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]),
3230       TX_16X16);
3231 
3232   fill_single_inter_mode_costs(search_state.single_inter_mode_costs,
3233                                num_inter_modes, ref_mode_set, mode_costs,
3234                                mbmi_ext->mode_context);
3235 
3236   MV_REFERENCE_FRAME last_comp_ref_frame = NONE_FRAME;
3237 
3238   // Initialize inter prediction params at block level for single reference
3239   // mode.
3240   InterPredParams inter_pred_params_sr;
3241   init_inter_block_params(&inter_pred_params_sr, pd->width, pd->height,
3242                           mi_row * MI_SIZE, mi_col * MI_SIZE, pd->subsampling_x,
3243                           pd->subsampling_y, xd->bd, is_cur_buf_hbd(xd),
3244                           /*is_intrabc=*/0);
3245   inter_pred_params_sr.conv_params =
3246       get_conv_params(/*do_average=*/0, AOM_PLANE_Y, xd->bd);
3247 
3248   x->block_is_zero_sad = x->content_state_sb.source_sad_nonrd == kZeroSad ||
3249                          segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP);
3250   if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN &&
3251       !x->force_zeromv_skip_for_blk &&
3252       x->content_state_sb.source_sad_nonrd != kZeroSad &&
3253       x->source_variance == 0 && bsize < cm->seq_params->sb_size &&
3254       search_state.yv12_mb[LAST_FRAME][0].width == cm->width &&
3255       search_state.yv12_mb[LAST_FRAME][0].height == cm->height) {
3256     set_block_source_sad(cpi, x, bsize, &search_state.yv12_mb[LAST_FRAME][0]);
3257   }
3258 
3259   int sb_me_has_been_tested = 0;
3260   x->sb_me_block = x->sb_me_partition;
3261   // Only use this feature (force testing of superblock motion) if coding
3262   // block size is large.
3263   if (x->sb_me_block) {
3264     if (cm->seq_params->sb_size == BLOCK_128X128 && bsize < BLOCK_64X64)
3265       x->sb_me_block = 0;
3266     else if (cm->seq_params->sb_size == BLOCK_64X64 && bsize < BLOCK_32X32)
3267       x->sb_me_block = 0;
3268   }
3269 
3270   x->min_dist_inter_uv = INT64_MAX;
3271   for (int idx = 0; idx < num_inter_modes + tot_num_comp_modes; ++idx) {
3272     // If we are at the first compound mode, and the single modes already
3273     // perform well, then end the search.
3274     if (rt_sf->skip_compound_based_on_var && idx == num_inter_modes &&
3275         skip_comp_based_on_var(search_state.vars, bsize)) {
3276       break;
3277     }
3278 
3279     int is_single_pred = 1;
3280     PREDICTION_MODE this_mode;
3281 
3282     if (idx == 0 && !x->force_zeromv_skip_for_blk) {
3283       // Set color sensitivity on first tested mode only.
3284       // Use y-sad already computed in find_predictors: take the sad with motion
3285       // vector closest to 0; the uv-sad computed below in set_color_sensitivity
3286       // is for zeromv.
3287       // For screen: first check if golden reference is being used, if so,
3288       // force color_sensitivity on (=1) if the color sensitivity for sb_g is 1.
3289       // The check in set_color_sensitivity() will then follow and check for
3290       // setting the flag if the level is still 2 or 0.
3291       if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN &&
3292           search_state.use_ref_frame_mask[GOLDEN_FRAME]) {
3293         if (x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_U)] == 1)
3294           x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] = 1;
3295         if (x->color_sensitivity_sb_g[COLOR_SENS_IDX(AOM_PLANE_V)] == 1)
3296           x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] = 1;
3297       }
3298       if (search_state.use_ref_frame_mask[LAST_FRAME] &&
3299           x->pred_mv0_sad[LAST_FRAME] != INT_MAX) {
3300         int y_sad = x->pred_mv0_sad[LAST_FRAME];
3301         if (x->pred_mv1_sad[LAST_FRAME] != INT_MAX &&
3302             (abs(search_state.frame_mv[NEARMV][LAST_FRAME].as_mv.col) +
3303              abs(search_state.frame_mv[NEARMV][LAST_FRAME].as_mv.row)) <
3304                 (abs(search_state.frame_mv[NEARESTMV][LAST_FRAME].as_mv.col) +
3305                  abs(search_state.frame_mv[NEARESTMV][LAST_FRAME].as_mv.row)))
3306           y_sad = x->pred_mv1_sad[LAST_FRAME];
3307         set_color_sensitivity(cpi, x, bsize, y_sad, x->source_variance,
3308                               search_state.yv12_mb[LAST_FRAME]);
3309       }
3310     }
3311 
3312     // Check the inter mode can be skipped based on mode statistics and speed
3313     // features settings.
3314     if (skip_inter_mode_nonrd(cpi, x, &search_state, &thresh_sad_pred,
3315                               &force_mv_inter_layer, &is_single_pred,
3316                               &this_mode, &last_comp_ref_frame, &ref_frame,
3317                               &ref_frame2, idx, svc_mv, force_skip_low_temp_var,
3318                               sse_zeromv_norm, num_inter_modes, segment_id,
3319                               bsize, comp_use_zero_zeromv_only, check_globalmv))
3320       continue;
3321 
3322     // Select prediction reference frames.
3323     for (int plane = 0; plane < MAX_MB_PLANE; plane++) {
3324       xd->plane[plane].pre[0] = search_state.yv12_mb[ref_frame][plane];
3325       if (!is_single_pred)
3326         xd->plane[plane].pre[1] = search_state.yv12_mb[ref_frame2][plane];
3327     }
3328 
3329     mi->ref_frame[0] = ref_frame;
3330     mi->ref_frame[1] = ref_frame2;
3331     set_ref_ptrs(cm, xd, ref_frame, ref_frame2);
3332 
3333     // Check if the scaled reference frame should be used. This is set in the
3334     // find_predictors() for each usable reference. If so, set the
3335     // block_ref_scale_factors[] to no reference scaling.
3336     if (search_state.use_scaled_ref_frame[ref_frame]) {
3337       xd->block_ref_scale_factors[0] = &sf_no_scale;
3338     }
3339     if (!is_single_pred && search_state.use_scaled_ref_frame[ref_frame2]) {
3340       xd->block_ref_scale_factors[1] = &sf_no_scale;
3341     }
3342 
3343     // Perform inter mode evaluation for non-rd
3344     if (!handle_inter_mode_nonrd(
3345             cpi, x, &search_state, ctx, &this_mode_pred, tmp_buffer,
3346             inter_pred_params_sr, &best_early_term, &sse_zeromv_norm,
3347             &check_globalmv,
3348 #if CONFIG_AV1_TEMPORAL_DENOISING
3349             &zero_last_cost_orig, denoise_svc_pickmode,
3350 #endif
3351             idx, force_mv_inter_layer, is_single_pred, gf_temporal_ref,
3352             use_model_yrd_large, filter_search_enabled_blk, bsize, this_mode,
3353             filt_select, cb_pred_filter_search, reuse_inter_pred,
3354             &sb_me_has_been_tested)) {
3355       break;
3356     }
3357   }
3358 
3359   // Restore mode data of best inter mode
3360   mi->mode = best_pickmode->best_mode;
3361   mi->motion_mode = best_pickmode->best_motion_mode;
3362   mi->wm_params = best_pickmode->wm_params;
3363   mi->num_proj_ref = best_pickmode->num_proj_ref;
3364   mi->interp_filters = best_pickmode->best_pred_filter;
3365   mi->tx_size = best_pickmode->best_tx_size;
3366   memset(mi->inter_tx_size, mi->tx_size, sizeof(mi->inter_tx_size));
3367   mi->ref_frame[0] = best_pickmode->best_ref_frame;
3368   mi->mv[0].as_int = search_state
3369                          .frame_mv_best[best_pickmode->best_mode]
3370                                        [best_pickmode->best_ref_frame]
3371                          .as_int;
3372   mi->mv[1].as_int = 0;
3373   if (best_pickmode->best_second_ref_frame > INTRA_FRAME) {
3374     mi->ref_frame[1] = best_pickmode->best_second_ref_frame;
3375     mi->mv[1].as_int = search_state
3376                            .frame_mv_best[best_pickmode->best_mode]
3377                                          [best_pickmode->best_second_ref_frame]
3378                            .as_int;
3379   }
3380   // Perform intra prediction search, if the best SAD is above a certain
3381   // threshold.
3382   mi->angle_delta[PLANE_TYPE_Y] = 0;
3383   mi->angle_delta[PLANE_TYPE_UV] = 0;
3384   mi->filter_intra_mode_info.use_filter_intra = 0;
3385 
3386 #if COLLECT_NONRD_PICK_MODE_STAT
3387   aom_usec_timer_start(&x->ms_stat_nonrd.timer1);
3388   x->ms_stat_nonrd.num_searches[bsize][DC_PRED]++;
3389   x->ms_stat_nonrd.num_nonskipped_searches[bsize][DC_PRED]++;
3390 #endif
3391 
3392   int force_palette_test = 0;
3393   if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN &&
3394       x->content_state_sb.source_sad_nonrd != kZeroSad &&
3395       bsize <= BLOCK_16X16) {
3396     unsigned int thresh_sse = cpi->rc.high_source_sad ? 15000 : 200000;
3397     unsigned int thresh_source_var = cpi->rc.high_source_sad ? 50 : 200;
3398     unsigned int best_sse_inter_motion =
3399         (unsigned int)(search_state.best_rdc.sse >>
3400                        (b_width_log2_lookup[bsize] +
3401                         b_height_log2_lookup[bsize]));
3402     if (best_sse_inter_motion > thresh_sse &&
3403         x->source_variance > thresh_source_var)
3404       force_palette_test = 1;
3405   }
3406 
3407   // Evaluate Intra modes in inter frame
3408   if (!x->force_zeromv_skip_for_blk)
3409     av1_estimate_intra_mode(cpi, x, bsize, best_early_term,
3410                             search_state.ref_costs_single[INTRA_FRAME],
3411                             reuse_inter_pred, &orig_dst, tmp_buffer,
3412                             &this_mode_pred, &search_state.best_rdc,
3413                             best_pickmode, ctx);
3414 
3415   int skip_idtx_palette = (x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] ||
3416                            x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)]) &&
3417                           x->content_state_sb.source_sad_nonrd != kZeroSad &&
3418                           !cpi->rc.high_source_sad;
3419 
3420   int try_palette =
3421       !skip_idtx_palette && cpi->oxcf.tool_cfg.enable_palette &&
3422       av1_allow_palette(cpi->common.features.allow_screen_content_tools,
3423                         mi->bsize);
3424   try_palette =
3425       try_palette &&
3426       (is_mode_intra(best_pickmode->best_mode) || force_palette_test) &&
3427       x->source_variance > 0 && !x->force_zeromv_skip_for_blk &&
3428       (cpi->rc.high_source_sad || x->source_variance > 300);
3429 
3430   if (rt_sf->prune_palette_nonrd && bsize > BLOCK_16X16) try_palette = 0;
3431 
3432   // Perform screen content mode evaluation for non-rd
3433   handle_screen_content_mode_nonrd(
3434       cpi, x, &search_state, this_mode_pred, ctx, tmp_buffer, &orig_dst,
3435       skip_idtx_palette, try_palette, bsize, reuse_inter_pred, mi_col, mi_row);
3436 
3437 #if COLLECT_NONRD_PICK_MODE_STAT
3438   aom_usec_timer_mark(&x->ms_stat_nonrd.timer1);
3439   x->ms_stat_nonrd.nonskipped_search_times[bsize][DC_PRED] +=
3440       aom_usec_timer_elapsed(&x->ms_stat_nonrd.timer1);
3441 #endif
3442 
3443   pd->dst = orig_dst;
3444   // Best mode is finalized. Restore the mode data to mbmi
3445   if (try_palette) mi->palette_mode_info = best_pickmode->pmi;
3446   mi->mode = best_pickmode->best_mode;
3447   mi->ref_frame[0] = best_pickmode->best_ref_frame;
3448   mi->ref_frame[1] = best_pickmode->best_second_ref_frame;
3449   // For lossless: always force the skip flags off.
3450   if (is_lossless_requested(&cpi->oxcf.rc_cfg)) {
3451     txfm_info->skip_txfm = 0;
3452     memset(ctx->blk_skip, 0, sizeof(ctx->blk_skip[0]) * ctx->num_4x4_blk);
3453   } else {
3454     txfm_info->skip_txfm = best_pickmode->best_mode_skip_txfm;
3455   }
3456   if (has_second_ref(mi)) {
3457     mi->comp_group_idx = 0;
3458     mi->compound_idx = 1;
3459     mi->interinter_comp.type = COMPOUND_AVERAGE;
3460   }
3461 
3462   if (!is_inter_block(mi)) {
3463     mi->interp_filters = av1_broadcast_interp_filter(SWITCHABLE_FILTERS);
3464   } else {
3465     // If inter mode is selected and ref_frame was one that uses the
3466     // scaled reference frame, then we can't use reuse_inter_pred.
3467     if (search_state.use_scaled_ref_frame[best_pickmode->best_ref_frame] ||
3468         (has_second_ref(mi) &&
3469          search_state
3470              .use_scaled_ref_frame[best_pickmode->best_second_ref_frame]))
3471       x->reuse_inter_pred = 0;
3472   }
3473 
3474   // Restore the predicted samples of best mode to final buffer
3475   if (reuse_inter_pred && best_pickmode->best_pred != NULL) {
3476     PRED_BUFFER *const best_pred = best_pickmode->best_pred;
3477     if (best_pred->data != orig_dst.buf && is_inter_mode(mi->mode)) {
3478       aom_convolve_copy(best_pred->data, best_pred->stride, pd->dst.buf,
3479                         pd->dst.stride, bw, bh);
3480     }
3481   }
3482 
3483 #if CONFIG_AV1_TEMPORAL_DENOISING
3484   if (cpi->oxcf.noise_sensitivity > 0 && resize_pending == 0 &&
3485       denoise_svc_pickmode && cpi->denoiser.denoising_level > kDenLowLow &&
3486       cpi->denoiser.reset == 0) {
3487     AV1_DENOISER_DECISION decision = COPY_BLOCK;
3488     ctx->sb_skip_denoising = 0;
3489     av1_pickmode_ctx_den_update(
3490         &ctx_den, zero_last_cost_orig, search_state.ref_costs_single,
3491         search_state.frame_mv, reuse_inter_pred, best_pickmode);
3492     av1_denoiser_denoise(cpi, x, mi_row, mi_col, bsize, ctx, &decision,
3493                          gf_temporal_ref);
3494     if (denoise_recheck_zeromv)
3495       recheck_zeromv_after_denoising(
3496           cpi, mi, x, xd, decision, &ctx_den, search_state.yv12_mb,
3497           &search_state.best_rdc, best_pickmode, bsize, mi_row, mi_col);
3498     best_pickmode->best_ref_frame = ctx_den.best_ref_frame;
3499   }
3500 #endif
3501 
3502   // Update the factors used for RD thresholding for all modes.
3503   if (cpi->sf.inter_sf.adaptive_rd_thresh && !has_second_ref(mi)) {
3504     THR_MODES best_mode_idx =
3505         mode_idx[best_pickmode->best_ref_frame][mode_offset(mi->mode)];
3506     if (best_pickmode->best_ref_frame == INTRA_FRAME) {
3507       // Only consider the modes that are included in the intra_mode_list.
3508       int intra_modes = sizeof(intra_mode_list) / sizeof(PREDICTION_MODE);
3509       for (int mode_index = 0; mode_index < intra_modes; mode_index++) {
3510         update_thresh_freq_fact(cpi, x, bsize, INTRA_FRAME, best_mode_idx,
3511                                 intra_mode_list[mode_index]);
3512       }
3513     } else {
3514       PREDICTION_MODE this_mode;
3515       for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
3516         update_thresh_freq_fact(cpi, x, bsize, best_pickmode->best_ref_frame,
3517                                 best_mode_idx, this_mode);
3518       }
3519     }
3520   }
3521 
3522 #if CONFIG_INTERNAL_STATS
3523   store_coding_context_nonrd(x, ctx, mi->mode);
3524 #else
3525   store_coding_context_nonrd(x, ctx);
3526 #endif  // CONFIG_INTERNAL_STATS
3527 
3528 #if COLLECT_NONRD_PICK_MODE_STAT
3529   aom_usec_timer_mark(&x->ms_stat_nonrd.bsize_timer);
3530   x->ms_stat_nonrd.total_block_times[bsize] +=
3531       aom_usec_timer_elapsed(&x->ms_stat_nonrd.bsize_timer);
3532   print_time(&x->ms_stat_nonrd, bsize, cm->mi_params.mi_rows,
3533              cm->mi_params.mi_cols, mi_row, mi_col);
3534 #endif  // COLLECT_NONRD_PICK_MODE_STAT
3535 
3536   *rd_cost = search_state.best_rdc;
3537 
3538   // Reset the xd->block_ref_scale_factors[i], as they may have
3539   // been set to pointer &sf_no_scale, which becomes invalid afer
3540   // this function.
3541   set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3542 }
3543