Coverage Report

Created: 2025-06-22 08:04

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