Coverage Report

Created: 2026-04-01 07:49

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