Coverage Report

Created: 2025-10-10 07:09

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