Coverage Report

Created: 2025-12-14 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libavif/ext/aom/av1/encoder/mcomp.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved.
3
 *
4
 * This source code is subject to the terms of the BSD 2 Clause License and
5
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6
 * was not distributed with this source code in the LICENSE file, you can
7
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8
 * Media Patent License 1.0 was not distributed with this source code in the
9
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10
 */
11
12
#include <assert.h>
13
#include <limits.h>
14
#include <math.h>
15
#include <stdio.h>
16
17
#include "config/aom_config.h"
18
#include "config/aom_dsp_rtcd.h"
19
20
#include "aom_dsp/aom_dsp_common.h"
21
#include "aom_mem/aom_mem.h"
22
#include "aom_ports/mem.h"
23
24
#include "av1/common/av1_common_int.h"
25
#include "av1/common/common.h"
26
#include "av1/common/filter.h"
27
#include "av1/common/mvref_common.h"
28
#include "av1/common/reconinter.h"
29
30
#include "av1/encoder/encoder.h"
31
#include "av1/encoder/encodemv.h"
32
#include "av1/encoder/mcomp.h"
33
#include "av1/encoder/rdopt.h"
34
#include "av1/encoder/reconinter_enc.h"
35
36
static inline void init_mv_cost_params(MV_COST_PARAMS *mv_cost_params,
37
                                       const MvCosts *mv_costs,
38
                                       const MV *ref_mv, int errorperbit,
39
7.04M
                                       int sadperbit) {
40
7.04M
  mv_cost_params->ref_mv = ref_mv;
41
7.04M
  mv_cost_params->full_ref_mv = get_fullmv_from_mv(ref_mv);
42
7.04M
  mv_cost_params->mv_cost_type = MV_COST_ENTROPY;
43
7.04M
  mv_cost_params->error_per_bit = errorperbit;
44
7.04M
  mv_cost_params->sad_per_bit = sadperbit;
45
  // For allintra encoding mode, 'mv_costs' is not allocated. Hence, the
46
  // population of mvjcost and mvcost are avoided. In case of IntraBC, these
47
  // values are populated from 'dv_costs' in av1_set_ms_to_intra_mode().
48
7.04M
  if (mv_costs != NULL) {
49
7.04M
    mv_cost_params->mvjcost = mv_costs->nmv_joint_cost;
50
7.04M
    mv_cost_params->mvcost[0] = mv_costs->mv_cost_stack[0];
51
7.04M
    mv_cost_params->mvcost[1] = mv_costs->mv_cost_stack[1];
52
7.04M
  }
53
7.04M
}
54
55
7.04M
static inline void init_ms_buffers(MSBuffers *ms_buffers, const MACROBLOCK *x) {
56
7.04M
  ms_buffers->ref = &x->e_mbd.plane[0].pre[0];
57
7.04M
  ms_buffers->src = &x->plane[0].src;
58
59
7.04M
  av1_set_ms_compound_refs(ms_buffers, NULL, NULL, 0, 0);
60
61
7.04M
  ms_buffers->wsrc = x->obmc_buffer.wsrc;
62
7.04M
  ms_buffers->obmc_mask = x->obmc_buffer.mask;
63
7.04M
}
64
65
20.7k
void av1_init_obmc_buffer(OBMCBuffer *obmc_buffer) {
66
20.7k
  obmc_buffer->wsrc = NULL;
67
20.7k
  obmc_buffer->mask = NULL;
68
20.7k
  obmc_buffer->above_pred = NULL;
69
20.7k
  obmc_buffer->left_pred = NULL;
70
20.7k
}
71
72
void av1_make_default_fullpel_ms_params(
73
    FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const struct AV1_COMP *cpi,
74
    MACROBLOCK *x, BLOCK_SIZE bsize, const MV *ref_mv, FULLPEL_MV start_mv,
75
    const search_site_config search_sites[NUM_DISTINCT_SEARCH_METHODS],
76
4.55M
    SEARCH_METHODS search_method, int fine_search_interval) {
77
4.55M
  const MV_SPEED_FEATURES *mv_sf = &cpi->sf.mv_sf;
78
4.55M
  const int is_key_frame =
79
4.55M
      cpi->ppi->gf_group.update_type[cpi->gf_frame_index] == KF_UPDATE;
80
81
  // High level params
82
4.55M
  ms_params->bsize = bsize;
83
4.55M
  ms_params->vfp = &cpi->ppi->fn_ptr[bsize];
84
85
4.55M
  init_ms_buffers(&ms_params->ms_buffers, x);
86
87
4.55M
  av1_set_mv_search_method(ms_params, search_sites, search_method);
88
89
4.55M
  ms_params->mesh_patterns[0] = mv_sf->mesh_patterns;
90
4.55M
  ms_params->mesh_patterns[1] = mv_sf->intrabc_mesh_patterns;
91
4.55M
  ms_params->force_mesh_thresh = mv_sf->exhaustive_searches_thresh;
92
4.55M
  ms_params->prune_mesh_search =
93
4.55M
      (cpi->sf.mv_sf.prune_mesh_search == PRUNE_MESH_SEARCH_LVL_2) ? 1 : 0;
94
4.55M
  ms_params->mesh_search_mv_diff_threshold = 4;
95
4.55M
  ms_params->run_mesh_search = 0;
96
4.55M
  ms_params->fine_search_interval = fine_search_interval;
97
98
4.55M
  ms_params->is_intra_mode = 0;
99
100
4.55M
  ms_params->fast_obmc_search = mv_sf->obmc_full_pixel_search_level;
101
102
4.55M
  ms_params->mv_limits = x->mv_limits;
103
4.55M
  av1_set_mv_search_range(&ms_params->mv_limits, ref_mv);
104
105
4.55M
  if (cpi->oxcf.algo_cfg.sharpness == 3) {
106
0
    int top_margin = x->e_mbd.mi_row * MI_SIZE + 8;
107
0
    int left_margin = x->e_mbd.mi_col * MI_SIZE + 8;
108
0
    int bottom_margin =
109
0
        cpi->common.height - mi_size_high[bsize] * MI_SIZE - top_margin + 16;
110
0
    int right_margin =
111
0
        cpi->common.width - mi_size_wide[bsize] * MI_SIZE - left_margin + 16;
112
113
0
    bottom_margin = AOMMAX(bottom_margin, -top_margin);
114
0
    right_margin = AOMMAX(right_margin, -left_margin);
115
116
0
    FullMvLimits *mv_limits = &ms_params->mv_limits;
117
0
    mv_limits->row_min = AOMMAX(mv_limits->row_min, -top_margin);
118
0
    mv_limits->row_max = AOMMIN(mv_limits->row_max, bottom_margin);
119
0
    mv_limits->col_min = AOMMAX(mv_limits->col_min, -left_margin);
120
0
    mv_limits->col_max = AOMMIN(mv_limits->col_max, right_margin);
121
0
  }
122
123
  // Mvcost params
124
4.55M
  init_mv_cost_params(&ms_params->mv_cost_params, x->mv_costs, ref_mv,
125
4.55M
                      x->errorperbit, x->sadperbit);
126
127
4.55M
  ms_params->sdf = ms_params->vfp->sdf;
128
4.55M
  ms_params->sdx4df = ms_params->vfp->sdx4df;
129
4.55M
  ms_params->sdx3df = ms_params->vfp->sdx3df;
130
131
4.55M
  if (mv_sf->use_downsampled_sad == 2 && block_size_high[bsize] >= 16) {
132
0
    assert(ms_params->vfp->sdsf != NULL);
133
0
    ms_params->sdf = ms_params->vfp->sdsf;
134
0
    assert(ms_params->vfp->sdsx4df != NULL);
135
0
    ms_params->sdx4df = ms_params->vfp->sdsx4df;
136
    // Skip version of sadx3 is not available yet
137
0
    ms_params->sdx3df = ms_params->vfp->sdsx4df;
138
4.55M
  } else if (mv_sf->use_downsampled_sad == 1 && block_size_high[bsize] >= 16 &&
139
1.13M
             !is_key_frame) {
140
763k
    FULLPEL_MV start_mv_clamped = start_mv;
141
    // adjust start_mv to make sure it is within MV range
142
763k
    clamp_fullmv(&start_mv_clamped, &ms_params->mv_limits);
143
144
763k
    const struct buf_2d *const ref = ms_params->ms_buffers.ref;
145
763k
    const int ref_stride = ref->stride;
146
763k
    const uint8_t *best_address = get_buf_from_fullmv(ref, &start_mv_clamped);
147
763k
    const struct buf_2d *const src = ms_params->ms_buffers.src;
148
763k
    const uint8_t *src_buf = src->buf;
149
763k
    const int src_stride = src->stride;
150
151
763k
    unsigned int start_mv_sad_even_rows, start_mv_sad_odd_rows;
152
763k
    assert(ms_params->vfp->sdsf != NULL);
153
763k
    start_mv_sad_even_rows =
154
763k
        ms_params->vfp->sdsf(src_buf, src_stride, best_address, ref_stride);
155
763k
    start_mv_sad_odd_rows =
156
763k
        ms_params->vfp->sdsf(src_buf + src_stride, src_stride,
157
763k
                             best_address + ref_stride, ref_stride);
158
159
    // If the absolute SAD difference computed between the pred-to-src of even
160
    // and odd rows is small, skip every other row in sad computation.
161
763k
    const int odd_to_even_diff_sad =
162
763k
        abs((int)start_mv_sad_even_rows - (int)start_mv_sad_odd_rows);
163
763k
    const int mult_thresh = 4;
164
763k
    if (odd_to_even_diff_sad * mult_thresh < (int)start_mv_sad_even_rows) {
165
650k
      ms_params->sdf = ms_params->vfp->sdsf;
166
650k
      assert(ms_params->vfp->sdsx4df != NULL);
167
650k
      ms_params->sdx4df = ms_params->vfp->sdsx4df;
168
650k
      ms_params->sdx3df = ms_params->vfp->sdsx4df;
169
650k
    }
170
763k
  }
171
4.55M
}
172
173
void av1_set_ms_to_intra_mode(FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
174
0
                              const IntraBCMVCosts *dv_costs) {
175
0
  ms_params->is_intra_mode = 1;
176
177
0
  MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
178
179
0
  mv_cost_params->mvjcost = dv_costs->joint_mv;
180
0
  mv_cost_params->mvcost[0] = dv_costs->dv_costs[0];
181
0
  mv_cost_params->mvcost[1] = dv_costs->dv_costs[1];
182
0
}
183
184
void av1_make_default_subpel_ms_params(SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
185
                                       const struct AV1_COMP *cpi,
186
                                       const MACROBLOCK *x, BLOCK_SIZE bsize,
187
2.49M
                                       const MV *ref_mv, const int *cost_list) {
188
2.49M
  const AV1_COMMON *cm = &cpi->common;
189
  // High level params
190
2.49M
  ms_params->allow_hp = cm->features.allow_high_precision_mv;
191
2.49M
  ms_params->forced_stop = cpi->sf.mv_sf.subpel_force_stop;
192
2.49M
  ms_params->iters_per_step = cpi->sf.mv_sf.subpel_iters_per_step;
193
2.49M
  ms_params->cost_list = cond_cost_list_const(cpi, cost_list);
194
195
2.49M
  av1_set_subpel_mv_search_range(&ms_params->mv_limits, &x->mv_limits, ref_mv);
196
197
2.49M
  if (cpi->oxcf.algo_cfg.sharpness == 3) {
198
0
    int top_margin = GET_MV_SUBPEL(x->e_mbd.mi_row * MI_SIZE + 8);
199
0
    int left_margin = GET_MV_SUBPEL(x->e_mbd.mi_col * MI_SIZE + 8);
200
0
    int bottom_margin =
201
0
        GET_MV_SUBPEL(cpi->common.height - mi_size_high[bsize] * MI_SIZE -
202
0
                      x->e_mbd.mi_row * MI_SIZE + 8);
203
0
    int right_margin =
204
0
        GET_MV_SUBPEL(cpi->common.width - mi_size_wide[bsize] * MI_SIZE -
205
0
                      x->e_mbd.mi_col * MI_SIZE + 8);
206
207
0
    bottom_margin = AOMMAX(bottom_margin, -top_margin);
208
0
    right_margin = AOMMAX(right_margin, -left_margin);
209
210
0
    SubpelMvLimits *mv_limits = &ms_params->mv_limits;
211
0
    mv_limits->row_min = AOMMAX(mv_limits->row_min, -top_margin);
212
0
    mv_limits->row_max = AOMMIN(mv_limits->row_max, bottom_margin);
213
0
    mv_limits->col_min = AOMMAX(mv_limits->col_min, -left_margin);
214
0
    mv_limits->col_max = AOMMIN(mv_limits->col_max, right_margin);
215
0
  }
216
217
  // Mvcost params
218
2.49M
  init_mv_cost_params(&ms_params->mv_cost_params, x->mv_costs, ref_mv,
219
2.49M
                      x->errorperbit, x->sadperbit);
220
221
  // Subpel variance params
222
2.49M
  ms_params->var_params.vfp = &cpi->ppi->fn_ptr[bsize];
223
2.49M
  ms_params->var_params.subpel_search_type =
224
2.49M
      cpi->sf.mv_sf.use_accurate_subpel_search;
225
2.49M
  ms_params->var_params.w = block_size_wide[bsize];
226
2.49M
  ms_params->var_params.h = block_size_high[bsize];
227
228
  // Ref and src buffers
229
2.49M
  MSBuffers *ms_buffers = &ms_params->var_params.ms_buffers;
230
2.49M
  init_ms_buffers(ms_buffers, x);
231
2.49M
}
232
233
4.61M
void av1_set_mv_search_range(FullMvLimits *mv_limits, const MV *mv) {
234
  // Calculate the outermost full-pixel MVs which are inside the limits set by
235
  // av1_set_subpel_mv_search_range().
236
  //
237
  // The subpel limits are simply mv->col +/- 8*MAX_FULL_PEL_VAL, and similar
238
  // for mv->row. We can then divide by 8 to find the fullpel MV limits. But
239
  // we have to be careful about the rounding. We want these bounds to be
240
  // at least as tight as the subpel limits, which means that we must round
241
  // the minimum values up and the maximum values down when dividing.
242
4.61M
  int col_min = ((mv->col + 7) >> 3) - MAX_FULL_PEL_VAL;
243
4.61M
  int row_min = ((mv->row + 7) >> 3) - MAX_FULL_PEL_VAL;
244
4.61M
  int col_max = (mv->col >> 3) + MAX_FULL_PEL_VAL;
245
4.61M
  int row_max = (mv->row >> 3) + MAX_FULL_PEL_VAL;
246
247
4.61M
  col_min = AOMMAX(col_min, (MV_LOW >> 3) + 1);
248
4.61M
  row_min = AOMMAX(row_min, (MV_LOW >> 3) + 1);
249
4.61M
  col_max = AOMMIN(col_max, (MV_UPP >> 3) - 1);
250
4.61M
  row_max = AOMMIN(row_max, (MV_UPP >> 3) - 1);
251
252
  // Get intersection of UMV window and valid MV window to reduce # of checks
253
  // in diamond search.
254
4.61M
  mv_limits->col_min = AOMMAX(mv_limits->col_min, col_min);
255
4.61M
  mv_limits->col_max = AOMMIN(mv_limits->col_max, col_max);
256
4.61M
  mv_limits->row_min = AOMMAX(mv_limits->row_min, row_min);
257
4.61M
  mv_limits->row_max = AOMMIN(mv_limits->row_max, row_max);
258
259
4.61M
  mv_limits->col_max = AOMMAX(mv_limits->col_min, mv_limits->col_max);
260
4.61M
  mv_limits->row_max = AOMMAX(mv_limits->row_min, mv_limits->row_max);
261
4.61M
}
262
263
2.09M
int av1_init_search_range(int size) {
264
2.09M
  int sr = 0;
265
  // Minimum search size no matter what the passed in value.
266
2.09M
  size = AOMMAX(16, size);
267
268
13.7M
  while ((size << sr) < MAX_FULL_PEL_VAL) sr++;
269
270
2.09M
  sr = AOMMIN(sr, MAX_MVSEARCH_STEPS - 2);
271
2.09M
  return sr;
272
2.09M
}
273
274
// ============================================================================
275
//  Cost of motion vectors
276
// ============================================================================
277
// TODO(any): Adaptively adjust the regularization strength based on image size
278
// and motion activity instead of using hard-coded values. It seems like we
279
// roughly half the lambda for each increase in resolution
280
// These are multiplier used to perform regularization in motion compensation
281
// when x->mv_cost_type is set to MV_COST_L1.
282
// LOWRES
283
1.31M
#define SSE_LAMBDA_LOWRES 2   // Used by mv_cost_err_fn
284
32.7M
#define SAD_LAMBDA_LOWRES 32  // Used by mvsad_err_cost during full pixel search
285
// MIDRES
286
0
#define SSE_LAMBDA_MIDRES 0   // Used by mv_cost_err_fn
287
0
#define SAD_LAMBDA_MIDRES 15  // Used by mvsad_err_cost during full pixel search
288
// HDRES
289
0
#define SSE_LAMBDA_HDRES 1  // Used by mv_cost_err_fn
290
0
#define SAD_LAMBDA_HDRES 8  // Used by mvsad_err_cost during full pixel search
291
292
// Returns the rate of encoding the current motion vector based on the
293
// joint_cost and comp_cost. joint_costs covers the cost of transmitting
294
// JOINT_MV, and comp_cost covers the cost of transmitting the actual motion
295
// vector.
296
static inline int mv_cost(const MV *mv, const int *joint_cost,
297
158M
                          const int *const comp_cost[2]) {
298
158M
  return joint_cost[av1_get_mv_joint(mv)] + comp_cost[0][mv->row] +
299
158M
         comp_cost[1][mv->col];
300
158M
}
301
302
0
#define CONVERT_TO_CONST_MVCOST(ptr) ((const int *const *)(ptr))
303
// Returns the cost of encoding the motion vector diff := *mv - *ref. The cost
304
// is defined as the rate required to encode diff * weight, rounded to the
305
// nearest 2 ** 7.
306
// This is NOT used during motion compensation.
307
int av1_mv_bit_cost(const MV *mv, const MV *ref_mv, const int *mvjcost,
308
4.47M
                    int *const mvcost[2], int weight) {
309
4.47M
  const MV diff = { mv->row - ref_mv->row, mv->col - ref_mv->col };
310
4.47M
  return ROUND_POWER_OF_TWO(
311
4.47M
      mv_cost(&diff, mvjcost, CONVERT_TO_CONST_MVCOST(mvcost)) * weight, 7);
312
4.47M
}
313
314
// Returns the cost of using the current mv during the motion search. This is
315
// used when var is used as the error metric.
316
#define PIXEL_TRANSFORM_ERROR_SCALE 4
317
static inline int mv_err_cost(const MV *mv, const MV *ref_mv,
318
                              const int *mvjcost, const int *const mvcost[2],
319
61.5M
                              int error_per_bit, MV_COST_TYPE mv_cost_type) {
320
61.5M
  const MV diff = { mv->row - ref_mv->row, mv->col - ref_mv->col };
321
61.5M
  const MV abs_diff = { abs(diff.row), abs(diff.col) };
322
323
61.5M
  switch (mv_cost_type) {
324
59.9M
    case MV_COST_ENTROPY:
325
59.9M
      if (mvcost) {
326
59.9M
        return (int)ROUND_POWER_OF_TWO_64(
327
59.9M
            (int64_t)mv_cost(&diff, mvjcost, mvcost) * error_per_bit,
328
59.9M
            RDDIV_BITS + AV1_PROB_COST_SHIFT - RD_EPB_SHIFT +
329
59.9M
                PIXEL_TRANSFORM_ERROR_SCALE);
330
59.9M
      }
331
0
      return 0;
332
1.31M
    case MV_COST_L1_LOWRES:
333
1.31M
      return (SSE_LAMBDA_LOWRES * (abs_diff.row + abs_diff.col)) >> 3;
334
0
    case MV_COST_L1_MIDRES:
335
0
      return (SSE_LAMBDA_MIDRES * (abs_diff.row + abs_diff.col)) >> 3;
336
0
    case MV_COST_L1_HDRES:
337
0
      return (SSE_LAMBDA_HDRES * (abs_diff.row + abs_diff.col)) >> 3;
338
0
    case MV_COST_NONE: return 0;
339
0
    default: assert(0 && "Invalid rd_cost_type"); return 0;
340
61.5M
  }
341
61.5M
}
342
343
static inline int mv_err_cost_(const MV *mv,
344
64.4M
                               const MV_COST_PARAMS *mv_cost_params) {
345
64.4M
  if (mv_cost_params->mv_cost_type == MV_COST_NONE) {
346
2.97M
    return 0;
347
2.97M
  }
348
61.5M
  return mv_err_cost(mv, mv_cost_params->ref_mv, mv_cost_params->mvjcost,
349
61.5M
                     mv_cost_params->mvcost, mv_cost_params->error_per_bit,
350
61.5M
                     mv_cost_params->mv_cost_type);
351
64.4M
}
352
353
// Returns the cost of using the current mv during the motion search. This is
354
// only used during full pixel motion search when sad is used as the error
355
// metric
356
static inline int mvsad_err_cost(const FULLPEL_MV *mv, const FULLPEL_MV *ref_mv,
357
                                 const int *mvjcost, const int *const mvcost[2],
358
127M
                                 int sad_per_bit, MV_COST_TYPE mv_cost_type) {
359
127M
  const MV diff = { GET_MV_SUBPEL(mv->row - ref_mv->row),
360
127M
                    GET_MV_SUBPEL(mv->col - ref_mv->col) };
361
362
127M
  switch (mv_cost_type) {
363
94.4M
    case MV_COST_ENTROPY:
364
94.4M
      return ROUND_POWER_OF_TWO(
365
0
          (unsigned)mv_cost(&diff, mvjcost, CONVERT_TO_CONST_MVCOST(mvcost)) *
366
0
              sad_per_bit,
367
0
          AV1_PROB_COST_SHIFT);
368
32.7M
    case MV_COST_L1_LOWRES:
369
32.7M
      return (SAD_LAMBDA_LOWRES * (abs(diff.row) + abs(diff.col))) >> 3;
370
0
    case MV_COST_L1_MIDRES:
371
0
      return (SAD_LAMBDA_MIDRES * (abs(diff.row) + abs(diff.col))) >> 3;
372
0
    case MV_COST_L1_HDRES:
373
0
      return (SAD_LAMBDA_HDRES * (abs(diff.row) + abs(diff.col))) >> 3;
374
0
    case MV_COST_NONE: return 0;
375
0
    default: assert(0 && "Invalid rd_cost_type"); return 0;
376
127M
  }
377
127M
}
378
379
static inline int mvsad_err_cost_(const FULLPEL_MV *mv,
380
127M
                                  const MV_COST_PARAMS *mv_cost_params) {
381
127M
  return mvsad_err_cost(mv, &mv_cost_params->full_ref_mv,
382
127M
                        mv_cost_params->mvjcost, mv_cost_params->mvcost,
383
127M
                        mv_cost_params->sad_per_bit,
384
127M
                        mv_cost_params->mv_cost_type);
385
127M
}
386
387
// =============================================================================
388
//  Fullpixel Motion Search: Translational
389
// =============================================================================
390
6.29M
#define MAX_PATTERN_SCALES 11
391
31.9M
#define MAX_PATTERN_CANDIDATES 8  // max number of candidates per scale
392
31.3k
#define PATTERN_CANDIDATES_REF 3  // number of refinement candidates
393
394
// Search site initialization for DIAMOND / CLAMPED_DIAMOND search methods.
395
// level = 0: DIAMOND, level = 1: CLAMPED_DIAMOND.
396
static void init_dsmotion_compensation(search_site_config *cfg, int stride,
397
322k
                                       int level) {
398
322k
  int num_search_steps = 0;
399
322k
  int stage_index = MAX_MVSEARCH_STEPS - 1;
400
401
322k
  cfg->site[stage_index][0].mv.col = cfg->site[stage_index][0].mv.row = 0;
402
322k
  cfg->site[stage_index][0].offset = 0;
403
322k
  cfg->stride = stride;
404
405
  // Choose the initial step size depending on level.
406
322k
  const int first_step = (level > 0) ? (MAX_FIRST_STEP / 4) : MAX_FIRST_STEP;
407
408
3.87M
  for (int radius = first_step; radius > 0;) {
409
3.55M
    int num_search_pts = 8;
410
411
3.55M
    const FULLPEL_MV search_site_mvs[13] = {
412
3.55M
      { 0, 0 },           { -radius, 0 },      { radius, 0 },
413
3.55M
      { 0, -radius },     { 0, radius },       { -radius, -radius },
414
3.55M
      { radius, radius }, { -radius, radius }, { radius, -radius },
415
3.55M
    };
416
417
3.55M
    int i;
418
35.5M
    for (i = 0; i <= num_search_pts; ++i) {
419
31.9M
      search_site *const site = &cfg->site[stage_index][i];
420
31.9M
      site->mv = search_site_mvs[i];
421
31.9M
      site->offset = get_offset_from_fullmv(&site->mv, stride);
422
31.9M
    }
423
3.55M
    cfg->searches_per_step[stage_index] = num_search_pts;
424
3.55M
    cfg->radius[stage_index] = radius;
425
    // Update the search radius based on level.
426
3.55M
    if (!level || ((stage_index < 9) && level)) radius /= 2;
427
3.55M
    --stage_index;
428
3.55M
    ++num_search_steps;
429
3.55M
  }
430
322k
  cfg->num_search_steps = num_search_steps;
431
322k
}
432
433
80.7k
void av1_init_motion_fpf(search_site_config *cfg, int stride) {
434
80.7k
  int num_search_steps = 0;
435
80.7k
  int stage_index = MAX_MVSEARCH_STEPS - 1;
436
437
80.7k
  cfg->site[stage_index][0].mv.col = cfg->site[stage_index][0].mv.row = 0;
438
80.7k
  cfg->site[stage_index][0].offset = 0;
439
80.7k
  cfg->stride = stride;
440
441
968k
  for (int radius = MAX_FIRST_STEP; radius > 0; radius /= 2) {
442
    // Generate offsets for 8 search sites per step.
443
887k
    int tan_radius = AOMMAX((int)(0.41 * radius), 1);
444
887k
    int num_search_pts = 12;
445
887k
    if (radius == 1) num_search_pts = 8;
446
447
887k
    const FULLPEL_MV search_site_mvs[13] = {
448
887k
      { 0, 0 },
449
887k
      { -radius, 0 },
450
887k
      { radius, 0 },
451
887k
      { 0, -radius },
452
887k
      { 0, radius },
453
887k
      { -radius, -tan_radius },
454
887k
      { radius, tan_radius },
455
887k
      { -tan_radius, radius },
456
887k
      { tan_radius, -radius },
457
887k
      { -radius, tan_radius },
458
887k
      { radius, -tan_radius },
459
887k
      { tan_radius, radius },
460
887k
      { -tan_radius, -radius },
461
887k
    };
462
463
887k
    int i;
464
12.1M
    for (i = 0; i <= num_search_pts; ++i) {
465
11.2M
      search_site *const site = &cfg->site[stage_index][i];
466
11.2M
      site->mv = search_site_mvs[i];
467
11.2M
      site->offset = get_offset_from_fullmv(&site->mv, stride);
468
11.2M
    }
469
887k
    cfg->searches_per_step[stage_index] = num_search_pts;
470
887k
    cfg->radius[stage_index] = radius;
471
887k
    --stage_index;
472
887k
    ++num_search_steps;
473
887k
  }
474
80.7k
  cfg->num_search_steps = num_search_steps;
475
80.7k
}
476
477
// Search site initialization for NSTEP / NSTEP_8PT search methods.
478
// level = 0: NSTEP, level = 1: NSTEP_8PT.
479
static void init_motion_compensation_nstep(search_site_config *cfg, int stride,
480
322k
                                           int level) {
481
322k
  int num_search_steps = 0;
482
322k
  int stage_index = 0;
483
322k
  cfg->stride = stride;
484
322k
  int radius = 1;
485
322k
  const int num_stages = (level > 0) ? 16 : 15;
486
5.32M
  for (stage_index = 0; stage_index < num_stages; ++stage_index) {
487
5.00M
    int tan_radius = AOMMAX((int)(0.41 * radius), 1);
488
5.00M
    int num_search_pts = 12;
489
5.00M
    if ((radius <= 5) || (level > 0)) {
490
3.22M
      tan_radius = radius;
491
3.22M
      num_search_pts = 8;
492
3.22M
    }
493
5.00M
    const FULLPEL_MV search_site_mvs[13] = {
494
5.00M
      { 0, 0 },
495
5.00M
      { -radius, 0 },
496
5.00M
      { radius, 0 },
497
5.00M
      { 0, -radius },
498
5.00M
      { 0, radius },
499
5.00M
      { -radius, -tan_radius },
500
5.00M
      { radius, tan_radius },
501
5.00M
      { -tan_radius, radius },
502
5.00M
      { tan_radius, -radius },
503
5.00M
      { -radius, tan_radius },
504
5.00M
      { radius, -tan_radius },
505
5.00M
      { tan_radius, radius },
506
5.00M
      { -tan_radius, -radius },
507
5.00M
    };
508
509
57.1M
    for (int i = 0; i <= num_search_pts; ++i) {
510
52.1M
      search_site *const site = &cfg->site[stage_index][i];
511
52.1M
      site->mv = search_site_mvs[i];
512
52.1M
      site->offset = get_offset_from_fullmv(&site->mv, stride);
513
52.1M
    }
514
5.00M
    cfg->searches_per_step[stage_index] = num_search_pts;
515
5.00M
    cfg->radius[stage_index] = radius;
516
5.00M
    ++num_search_steps;
517
5.00M
    if (stage_index < 12)
518
3.87M
      radius = (int)AOMMAX((radius * 1.5 + 0.5), radius + 1);
519
5.00M
  }
520
322k
  cfg->num_search_steps = num_search_steps;
521
322k
}
522
523
// Search site initialization for BIGDIA / FAST_BIGDIA / FAST_DIAMOND
524
// search methods.
525
static void init_motion_compensation_bigdia(search_site_config *cfg, int stride,
526
161k
                                            int level) {
527
161k
  (void)level;
528
161k
  cfg->stride = stride;
529
  // First scale has 4-closest points, the rest have 8 points in diamond
530
  // shape at increasing scales
531
161k
  static const int bigdia_num_candidates[MAX_PATTERN_SCALES] = {
532
161k
    4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
533
161k
  };
534
535
  // BIGDIA search method candidates.
536
  // Note that the largest candidate step at each scale is 2^scale
537
  /* clang-format off */
538
161k
  static const FULLPEL_MV
539
161k
      site_candidates[MAX_PATTERN_SCALES][MAX_PATTERN_CANDIDATES] = {
540
161k
          { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 0 }, { 0, 0 },
541
161k
            { 0, 0 }, { 0, 0 } },
542
161k
          { { -1, -1 }, { 0, -2 }, { 1, -1 }, { 2, 0 }, { 1, 1 }, { 0, 2 },
543
161k
            { -1, 1 }, { -2, 0 } },
544
161k
          { { -2, -2 }, { 0, -4 }, { 2, -2 }, { 4, 0 }, { 2, 2 }, { 0, 4 },
545
161k
            { -2, 2 }, { -4, 0 } },
546
161k
          { { -4, -4 }, { 0, -8 }, { 4, -4 }, { 8, 0 }, { 4, 4 }, { 0, 8 },
547
161k
            { -4, 4 }, { -8, 0 } },
548
161k
          { { -8, -8 }, { 0, -16 }, { 8, -8 }, { 16, 0 }, { 8, 8 }, { 0, 16 },
549
161k
            { -8, 8 }, { -16, 0 } },
550
161k
          { { -16, -16 }, { 0, -32 }, { 16, -16 }, { 32, 0 }, { 16, 16 },
551
161k
            { 0, 32 }, { -16, 16 }, { -32, 0 } },
552
161k
          { { -32, -32 }, { 0, -64 }, { 32, -32 }, { 64, 0 }, { 32, 32 },
553
161k
            { 0, 64 }, { -32, 32 }, { -64, 0 } },
554
161k
          { { -64, -64 }, { 0, -128 }, { 64, -64 }, { 128, 0 }, { 64, 64 },
555
161k
            { 0, 128 }, { -64, 64 }, { -128, 0 } },
556
161k
          { { -128, -128 }, { 0, -256 }, { 128, -128 }, { 256, 0 },
557
161k
            { 128, 128 }, { 0, 256 }, { -128, 128 }, { -256, 0 } },
558
161k
          { { -256, -256 }, { 0, -512 }, { 256, -256 }, { 512, 0 },
559
161k
            { 256, 256 }, { 0, 512 }, { -256, 256 }, { -512, 0 } },
560
161k
          { { -512, -512 }, { 0, -1024 }, { 512, -512 }, { 1024, 0 },
561
161k
            { 512, 512 }, { 0, 1024 }, { -512, 512 }, { -1024, 0 } },
562
161k
        };
563
564
  /* clang-format on */
565
161k
  int radius = 1;
566
1.93M
  for (int i = 0; i < MAX_PATTERN_SCALES; ++i) {
567
1.77M
    cfg->searches_per_step[i] = bigdia_num_candidates[i];
568
1.77M
    cfg->radius[i] = radius;
569
15.9M
    for (int j = 0; j < MAX_PATTERN_CANDIDATES; ++j) {
570
14.2M
      search_site *const site = &cfg->site[i][j];
571
14.2M
      site->mv = site_candidates[i][j];
572
14.2M
      site->offset = get_offset_from_fullmv(&site->mv, stride);
573
14.2M
    }
574
1.77M
    radius *= 2;
575
1.77M
  }
576
161k
  cfg->num_search_steps = MAX_PATTERN_SCALES;
577
161k
}
578
579
// Search site initialization for SQUARE search method.
580
static void init_motion_compensation_square(search_site_config *cfg, int stride,
581
161k
                                            int level) {
582
161k
  (void)level;
583
161k
  cfg->stride = stride;
584
  // All scales have 8 closest points in square shape.
585
161k
  static const int square_num_candidates[MAX_PATTERN_SCALES] = {
586
161k
    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
587
161k
  };
588
589
  // Square search method candidates.
590
  // Note that the largest candidate step at each scale is 2^scale.
591
  /* clang-format off */
592
161k
    static const FULLPEL_MV
593
161k
        square_candidates[MAX_PATTERN_SCALES][MAX_PATTERN_CANDIDATES] = {
594
161k
             { { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
595
161k
               { -1, 1 }, { -1, 0 } },
596
161k
             { { -2, -2 }, { 0, -2 }, { 2, -2 }, { 2, 0 }, { 2, 2 }, { 0, 2 },
597
161k
               { -2, 2 }, { -2, 0 } },
598
161k
             { { -4, -4 }, { 0, -4 }, { 4, -4 }, { 4, 0 }, { 4, 4 }, { 0, 4 },
599
161k
               { -4, 4 }, { -4, 0 } },
600
161k
             { { -8, -8 }, { 0, -8 }, { 8, -8 }, { 8, 0 }, { 8, 8 }, { 0, 8 },
601
161k
               { -8, 8 }, { -8, 0 } },
602
161k
             { { -16, -16 }, { 0, -16 }, { 16, -16 }, { 16, 0 }, { 16, 16 },
603
161k
               { 0, 16 }, { -16, 16 }, { -16, 0 } },
604
161k
             { { -32, -32 }, { 0, -32 }, { 32, -32 }, { 32, 0 }, { 32, 32 },
605
161k
               { 0, 32 }, { -32, 32 }, { -32, 0 } },
606
161k
             { { -64, -64 }, { 0, -64 }, { 64, -64 }, { 64, 0 }, { 64, 64 },
607
161k
               { 0, 64 }, { -64, 64 }, { -64, 0 } },
608
161k
             { { -128, -128 }, { 0, -128 }, { 128, -128 }, { 128, 0 },
609
161k
               { 128, 128 }, { 0, 128 }, { -128, 128 }, { -128, 0 } },
610
161k
             { { -256, -256 }, { 0, -256 }, { 256, -256 }, { 256, 0 },
611
161k
               { 256, 256 }, { 0, 256 }, { -256, 256 }, { -256, 0 } },
612
161k
             { { -512, -512 }, { 0, -512 }, { 512, -512 }, { 512, 0 },
613
161k
               { 512, 512 }, { 0, 512 }, { -512, 512 }, { -512, 0 } },
614
161k
             { { -1024, -1024 }, { 0, -1024 }, { 1024, -1024 }, { 1024, 0 },
615
161k
               { 1024, 1024 }, { 0, 1024 }, { -1024, 1024 }, { -1024, 0 } },
616
161k
    };
617
618
  /* clang-format on */
619
161k
  int radius = 1;
620
1.93M
  for (int i = 0; i < MAX_PATTERN_SCALES; ++i) {
621
1.77M
    cfg->searches_per_step[i] = square_num_candidates[i];
622
1.77M
    cfg->radius[i] = radius;
623
15.9M
    for (int j = 0; j < MAX_PATTERN_CANDIDATES; ++j) {
624
14.2M
      search_site *const site = &cfg->site[i][j];
625
14.2M
      site->mv = square_candidates[i][j];
626
14.2M
      site->offset = get_offset_from_fullmv(&site->mv, stride);
627
14.2M
    }
628
1.77M
    radius *= 2;
629
1.77M
  }
630
161k
  cfg->num_search_steps = MAX_PATTERN_SCALES;
631
161k
}
632
633
// Search site initialization for HEX / FAST_HEX search methods.
634
static void init_motion_compensation_hex(search_site_config *cfg, int stride,
635
161k
                                         int level) {
636
161k
  (void)level;
637
161k
  cfg->stride = stride;
638
  // First scale has 8-closest points, the rest have 6 points in hex shape
639
  // at increasing scales.
640
161k
  static const int hex_num_candidates[MAX_PATTERN_SCALES] = { 8, 6, 6, 6, 6, 6,
641
161k
                                                              6, 6, 6, 6, 6 };
642
  // Note that the largest candidate step at each scale is 2^scale.
643
  /* clang-format off */
644
161k
    static const FULLPEL_MV
645
161k
        hex_candidates[MAX_PATTERN_SCALES][MAX_PATTERN_CANDIDATES] = {
646
161k
        { { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
647
161k
          { -1, 1 }, { -1, 0 } },
648
161k
        { { -1, -2 }, { 1, -2 }, { 2, 0 }, { 1, 2 }, { -1, 2 }, { -2, 0 } },
649
161k
        { { -2, -4 }, { 2, -4 }, { 4, 0 }, { 2, 4 }, { -2, 4 }, { -4, 0 } },
650
161k
        { { -4, -8 }, { 4, -8 }, { 8, 0 }, { 4, 8 }, { -4, 8 }, { -8, 0 } },
651
161k
        { { -8, -16 }, { 8, -16 }, { 16, 0 }, { 8, 16 },
652
161k
          { -8, 16 }, { -16, 0 } },
653
161k
        { { -16, -32 }, { 16, -32 }, { 32, 0 }, { 16, 32 }, { -16, 32 },
654
161k
          { -32, 0 } },
655
161k
        { { -32, -64 }, { 32, -64 }, { 64, 0 }, { 32, 64 }, { -32, 64 },
656
161k
          { -64, 0 } },
657
161k
        { { -64, -128 }, { 64, -128 }, { 128, 0 }, { 64, 128 },
658
161k
          { -64, 128 }, { -128, 0 } },
659
161k
        { { -128, -256 }, { 128, -256 }, { 256, 0 }, { 128, 256 },
660
161k
          { -128, 256 }, { -256, 0 } },
661
161k
        { { -256, -512 }, { 256, -512 }, { 512, 0 }, { 256, 512 },
662
161k
          { -256, 512 }, { -512, 0 } },
663
161k
        { { -512, -1024 }, { 512, -1024 }, { 1024, 0 }, { 512, 1024 },
664
161k
          { -512, 1024 }, { -1024, 0 } },
665
161k
    };
666
667
  /* clang-format on */
668
161k
  int radius = 1;
669
1.93M
  for (int i = 0; i < MAX_PATTERN_SCALES; ++i) {
670
1.77M
    cfg->searches_per_step[i] = hex_num_candidates[i];
671
1.77M
    cfg->radius[i] = radius;
672
12.7M
    for (int j = 0; j < hex_num_candidates[i]; ++j) {
673
10.9M
      search_site *const site = &cfg->site[i][j];
674
10.9M
      site->mv = hex_candidates[i][j];
675
10.9M
      site->offset = get_offset_from_fullmv(&site->mv, stride);
676
10.9M
    }
677
1.77M
    radius *= 2;
678
1.77M
  }
679
161k
  cfg->num_search_steps = MAX_PATTERN_SCALES;
680
161k
}
681
682
const av1_init_search_site_config
683
    av1_init_motion_compensation[NUM_DISTINCT_SEARCH_METHODS] = {
684
      init_dsmotion_compensation,     init_motion_compensation_nstep,
685
      init_motion_compensation_nstep, init_dsmotion_compensation,
686
      init_motion_compensation_hex,   init_motion_compensation_bigdia,
687
      init_motion_compensation_square
688
    };
689
690
// Checks whether the mv is within range of the mv_limits
691
static inline int check_bounds(const FullMvLimits *mv_limits, int row, int col,
692
4.15M
                               int range) {
693
4.15M
  return ((row - range) >= mv_limits->row_min) &
694
4.15M
         ((row + range) <= mv_limits->row_max) &
695
4.15M
         ((col - range) >= mv_limits->col_min) &
696
4.15M
         ((col + range) <= mv_limits->col_max);
697
4.15M
}
698
699
static inline int get_mvpred_var_cost(
700
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV *this_mv,
701
1.04M
    FULLPEL_MV_STATS *mv_stats) {
702
1.04M
  const aom_variance_fn_ptr_t *vfp = ms_params->vfp;
703
1.04M
  const MV sub_this_mv = get_mv_from_fullmv(this_mv);
704
1.04M
  const struct buf_2d *const src = ms_params->ms_buffers.src;
705
1.04M
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
706
1.04M
  const uint8_t *src_buf = src->buf;
707
1.04M
  const int src_stride = src->stride;
708
1.04M
  const int ref_stride = ref->stride;
709
710
1.04M
  int bestsme;
711
712
1.04M
  bestsme = vfp->vf(src_buf, src_stride, get_buf_from_fullmv(ref, this_mv),
713
1.04M
                    ref_stride, &mv_stats->sse);
714
1.04M
  mv_stats->distortion = bestsme;
715
716
1.04M
  mv_stats->err_cost = mv_err_cost_(&sub_this_mv, &ms_params->mv_cost_params);
717
1.04M
  bestsme += mv_stats->err_cost;
718
719
1.04M
  return bestsme;
720
1.04M
}
721
722
static inline int get_mvpred_sad(const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
723
                                 const struct buf_2d *const src,
724
                                 const uint8_t *const ref_address,
725
58.1M
                                 const int ref_stride) {
726
58.1M
  const uint8_t *src_buf = src->buf;
727
58.1M
  const int src_stride = src->stride;
728
729
58.1M
  return ms_params->sdf(src_buf, src_stride, ref_address, ref_stride);
730
58.1M
}
731
732
static inline int get_mvpred_compound_var_cost(
733
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV *this_mv,
734
14.6M
    FULLPEL_MV_STATS *mv_stats) {
735
14.6M
  const aom_variance_fn_ptr_t *vfp = ms_params->vfp;
736
14.6M
  const struct buf_2d *const src = ms_params->ms_buffers.src;
737
14.6M
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
738
14.6M
  const uint8_t *src_buf = src->buf;
739
14.6M
  const int src_stride = src->stride;
740
14.6M
  const int ref_stride = ref->stride;
741
742
14.6M
  const uint8_t *mask = ms_params->ms_buffers.mask;
743
14.6M
  const uint8_t *second_pred = ms_params->ms_buffers.second_pred;
744
14.6M
  const int mask_stride = ms_params->ms_buffers.mask_stride;
745
14.6M
  const int invert_mask = ms_params->ms_buffers.inv_mask;
746
14.6M
  int bestsme;
747
748
14.6M
  if (mask) {
749
0
    bestsme = vfp->msvf(get_buf_from_fullmv(ref, this_mv), ref_stride, 0, 0,
750
0
                        src_buf, src_stride, second_pred, mask, mask_stride,
751
0
                        invert_mask, &mv_stats->sse);
752
14.6M
  } else if (second_pred) {
753
0
    bestsme = vfp->svaf(get_buf_from_fullmv(ref, this_mv), ref_stride, 0, 0,
754
0
                        src_buf, src_stride, &mv_stats->sse, second_pred);
755
14.6M
  } else {
756
14.6M
    bestsme = vfp->vf(src_buf, src_stride, get_buf_from_fullmv(ref, this_mv),
757
14.6M
                      ref_stride, &mv_stats->sse);
758
14.6M
  }
759
14.6M
  mv_stats->distortion = bestsme;
760
761
14.6M
  const MV sub_this_mv = get_mv_from_fullmv(this_mv);
762
14.6M
  mv_stats->err_cost = mv_err_cost_(&sub_this_mv, &ms_params->mv_cost_params);
763
14.6M
  bestsme += mv_stats->err_cost;
764
765
14.6M
  return bestsme;
766
14.6M
}
767
768
static inline int get_mvpred_compound_sad(
769
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
770
    const struct buf_2d *const src, const uint8_t *const ref_address,
771
0
    const int ref_stride) {
772
0
  const aom_variance_fn_ptr_t *vfp = ms_params->vfp;
773
0
  const uint8_t *src_buf = src->buf;
774
0
  const int src_stride = src->stride;
775
776
0
  const uint8_t *mask = ms_params->ms_buffers.mask;
777
0
  const uint8_t *second_pred = ms_params->ms_buffers.second_pred;
778
0
  const int mask_stride = ms_params->ms_buffers.mask_stride;
779
0
  const int invert_mask = ms_params->ms_buffers.inv_mask;
780
781
0
  if (mask) {
782
0
    return vfp->msdf(src_buf, src_stride, ref_address, ref_stride, second_pred,
783
0
                     mask, mask_stride, invert_mask);
784
0
  } else if (second_pred) {
785
0
    assert(vfp->sdaf != NULL);
786
0
    return vfp->sdaf(src_buf, src_stride, ref_address, ref_stride, second_pred);
787
0
  } else {
788
0
    return ms_params->sdf(src_buf, src_stride, ref_address, ref_stride);
789
0
  }
790
0
}
791
792
// Calculates and returns a sad+mvcost list around an integer best pel during
793
// fullpixel motion search. The resulting list can be used to speed up subpel
794
// motion search later.
795
467k
#define USE_SAD_COSTLIST 1
796
797
// calc_int_cost_list uses var to populate the costlist, which is more accurate
798
// than sad but slightly slower.
799
static AOM_FORCE_INLINE void calc_int_cost_list(
800
    const FULLPEL_MV best_mv, const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
801
0
    int *cost_list) {
802
0
  static const FULLPEL_MV neighbors[4] = {
803
0
    { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 }
804
0
  };
805
0
  const int br = best_mv.row;
806
0
  const int bc = best_mv.col;
807
0
808
0
  FULLPEL_MV_STATS mv_stats;
809
0
  cost_list[0] = get_mvpred_var_cost(ms_params, &best_mv, &mv_stats);
810
0
811
0
  if (check_bounds(&ms_params->mv_limits, br, bc, 1)) {
812
0
    for (int i = 0; i < 4; i++) {
813
0
      const FULLPEL_MV neighbor_mv = { br + neighbors[i].row,
814
0
                                       bc + neighbors[i].col };
815
0
      cost_list[i + 1] =
816
0
          get_mvpred_var_cost(ms_params, &neighbor_mv, &mv_stats);
817
0
    }
818
0
  } else {
819
0
    for (int i = 0; i < 4; i++) {
820
0
      const FULLPEL_MV neighbor_mv = { br + neighbors[i].row,
821
0
                                       bc + neighbors[i].col };
822
0
      if (!av1_is_fullmv_in_range(&ms_params->mv_limits, neighbor_mv)) {
823
0
        cost_list[i + 1] = INT_MAX;
824
0
      } else {
825
0
        cost_list[i + 1] =
826
0
            get_mvpred_var_cost(ms_params, &neighbor_mv, &mv_stats);
827
0
      }
828
0
    }
829
0
  }
830
0
}
831
832
// calc_int_sad_list uses sad to populate the costlist, which is less accurate
833
// than var but faster.
834
static AOM_FORCE_INLINE void calc_int_sad_list(
835
    const FULLPEL_MV best_mv, const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
836
468k
    int *cost_list, int costlist_has_sad) {
837
468k
  static const FULLPEL_MV neighbors[4] = {
838
468k
    { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 }
839
468k
  };
840
468k
  const struct buf_2d *const src = ms_params->ms_buffers.src;
841
468k
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
842
468k
  const int ref_stride = ref->stride;
843
468k
  const int br = best_mv.row;
844
468k
  const int bc = best_mv.col;
845
846
468k
  assert(av1_is_fullmv_in_range(&ms_params->mv_limits, best_mv));
847
848
  // Refresh the costlist it does not contain valid sad
849
468k
  if (!costlist_has_sad) {
850
0
    cost_list[0] = get_mvpred_sad(
851
0
        ms_params, src, get_buf_from_fullmv(ref, &best_mv), ref_stride);
852
853
0
    if (check_bounds(&ms_params->mv_limits, br, bc, 1)) {
854
0
      for (int i = 0; i < 4; i++) {
855
0
        const FULLPEL_MV this_mv = { br + neighbors[i].row,
856
0
                                     bc + neighbors[i].col };
857
0
        cost_list[i + 1] = get_mvpred_sad(
858
0
            ms_params, src, get_buf_from_fullmv(ref, &this_mv), ref_stride);
859
0
      }
860
0
    } else {
861
0
      for (int i = 0; i < 4; i++) {
862
0
        const FULLPEL_MV this_mv = { br + neighbors[i].row,
863
0
                                     bc + neighbors[i].col };
864
0
        if (!av1_is_fullmv_in_range(&ms_params->mv_limits, this_mv)) {
865
0
          cost_list[i + 1] = INT_MAX;
866
0
        } else {
867
0
          cost_list[i + 1] = get_mvpred_sad(
868
0
              ms_params, src, get_buf_from_fullmv(ref, &this_mv), ref_stride);
869
0
        }
870
0
      }
871
0
    }
872
0
  }
873
874
468k
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
875
468k
  cost_list[0] += mvsad_err_cost_(&best_mv, mv_cost_params);
876
877
2.33M
  for (int idx = 0; idx < 4; idx++) {
878
1.86M
    if (cost_list[idx + 1] != INT_MAX) {
879
1.86M
      const FULLPEL_MV this_mv = { br + neighbors[idx].row,
880
1.86M
                                   bc + neighbors[idx].col };
881
1.86M
      cost_list[idx + 1] += mvsad_err_cost_(&this_mv, mv_cost_params);
882
1.86M
    }
883
1.86M
  }
884
468k
}
885
886
// Computes motion vector cost and adds to the sad cost.
887
// Then updates the best sad and motion vectors.
888
// Inputs:
889
//   this_sad: the sad to be evaluated.
890
//   mv: the current motion vector.
891
//   mv_cost_params: a structure containing information to compute mv cost.
892
//   best_sad: the current best sad.
893
//   raw_best_sad (optional): the current best sad without calculating mv cost.
894
//   best_mv: the current best motion vector.
895
//   second_best_mv (optional): the second best motion vector up to now.
896
// Modifies:
897
//   best_sad, raw_best_sad, best_mv, second_best_mv
898
//   If the current sad is lower than the current best sad.
899
// Returns:
900
//   Whether the input sad (mv) is better than the current best.
901
static inline int update_mvs_and_sad(const unsigned int this_sad,
902
                                     const FULLPEL_MV *mv,
903
                                     const MV_COST_PARAMS *mv_cost_params,
904
                                     unsigned int *best_sad,
905
                                     unsigned int *raw_best_sad,
906
                                     FULLPEL_MV *best_mv,
907
51.8M
                                     FULLPEL_MV *second_best_mv) {
908
51.8M
  if (this_sad >= *best_sad) return 0;
909
910
  // Add the motion vector cost.
911
13.5M
  const unsigned int sad = this_sad + mvsad_err_cost_(mv, mv_cost_params);
912
13.5M
  if (sad < *best_sad) {
913
2.75M
    if (raw_best_sad) *raw_best_sad = this_sad;
914
2.75M
    *best_sad = sad;
915
2.75M
    if (second_best_mv) *second_best_mv = *best_mv;
916
2.75M
    *best_mv = *mv;
917
2.75M
    return 1;
918
2.75M
  }
919
10.8M
  return 0;
920
13.5M
}
921
922
// Calculate sad4 and update the bestmv information
923
// in FAST_DIAMOND search method.
924
static inline void calc_sad4_update_bestmv(
925
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
926
    const MV_COST_PARAMS *mv_cost_params, FULLPEL_MV *best_mv,
927
    const FULLPEL_MV center_mv, const uint8_t *center_address,
928
    unsigned int *bestsad, unsigned int *raw_bestsad, int search_step,
929
4.32M
    int *best_site, int cand_start, int *cost_list) {
930
4.32M
  const struct buf_2d *const src = ms_params->ms_buffers.src;
931
4.32M
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
932
4.32M
  const search_site *site = ms_params->search_sites->site[search_step];
933
934
4.32M
  unsigned char const *block_offset[4];
935
4.32M
  unsigned int sads_buf[4];
936
4.32M
  unsigned int *sads;
937
4.32M
  const uint8_t *src_buf = src->buf;
938
4.32M
  const int src_stride = src->stride;
939
4.32M
  if (cost_list) {
940
468k
    sads = (unsigned int *)(cost_list + 1);
941
3.85M
  } else {
942
3.85M
    sads = sads_buf;
943
3.85M
  }
944
  // Loop over number of candidates.
945
21.6M
  for (int j = 0; j < 4; j++)
946
17.3M
    block_offset[j] = site[cand_start + j].offset + center_address;
947
948
  // 4-point sad calculation.
949
4.32M
  ms_params->sdx4df(src_buf, src_stride, block_offset, ref->stride, sads);
950
951
21.5M
  for (int j = 0; j < 4; j++) {
952
17.2M
    const FULLPEL_MV this_mv = { center_mv.row + site[cand_start + j].mv.row,
953
17.2M
                                 center_mv.col + site[cand_start + j].mv.col };
954
17.2M
    const int found_better_mv = update_mvs_and_sad(
955
17.2M
        sads[j], &this_mv, mv_cost_params, bestsad, raw_bestsad, best_mv,
956
17.2M
        /*second_best_mv=*/NULL);
957
17.2M
    if (found_better_mv) *best_site = cand_start + j;
958
17.2M
  }
959
4.32M
}
960
961
static inline void calc_sad3_update_bestmv(
962
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
963
    const MV_COST_PARAMS *mv_cost_params, FULLPEL_MV *best_mv,
964
    FULLPEL_MV center_mv, const uint8_t *center_address, unsigned int *bestsad,
965
    unsigned int *raw_bestsad, int search_step, int *best_site,
966
1.38M
    const int *chkpts_indices, int *cost_list) {
967
1.38M
  const struct buf_2d *const src = ms_params->ms_buffers.src;
968
1.38M
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
969
1.38M
  const search_site *site = ms_params->search_sites->site[search_step];
970
1.38M
  unsigned char const *block_offset[4] = {
971
1.38M
    center_address + site[chkpts_indices[0]].offset,
972
1.38M
    center_address + site[chkpts_indices[1]].offset,
973
1.38M
    center_address + site[chkpts_indices[2]].offset,
974
1.38M
    center_address,
975
1.38M
  };
976
1.38M
  unsigned int sads[4];
977
1.38M
  ms_params->sdx3df(src->buf, src->stride, block_offset, ref->stride, sads);
978
5.54M
  for (int j = 0; j < 3; j++) {
979
4.15M
    const int index = chkpts_indices[j];
980
4.15M
    const FULLPEL_MV this_mv = { center_mv.row + site[index].mv.row,
981
4.15M
                                 center_mv.col + site[index].mv.col };
982
4.15M
    const int found_better_mv = update_mvs_and_sad(
983
4.15M
        sads[j], &this_mv, mv_cost_params, bestsad, raw_bestsad, best_mv,
984
4.15M
        /*second_best_mv=*/NULL);
985
4.15M
    if (found_better_mv) *best_site = j;
986
4.15M
  }
987
1.38M
  if (cost_list) {
988
577k
    for (int j = 0; j < 3; j++) {
989
433k
      int index = chkpts_indices[j];
990
433k
      cost_list[index + 1] = sads[j];
991
433k
    }
992
144k
  }
993
1.38M
}
994
995
// Calculate sad and update the bestmv information
996
// in FAST_DIAMOND search method.
997
static inline void calc_sad_update_bestmv(
998
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
999
    const MV_COST_PARAMS *mv_cost_params, FULLPEL_MV *best_mv,
1000
    const FULLPEL_MV center_mv, const uint8_t *center_address,
1001
    unsigned int *bestsad, unsigned int *raw_bestsad, int search_step,
1002
2.27M
    int *best_site, const int num_candidates, int cand_start, int *cost_list) {
1003
2.27M
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1004
2.27M
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1005
2.27M
  const search_site *site = ms_params->search_sites->site[search_step];
1006
  // Loop over number of candidates.
1007
2.79M
  for (int i = cand_start; i < num_candidates; i++) {
1008
517k
    const FULLPEL_MV this_mv = { center_mv.row + site[i].mv.row,
1009
517k
                                 center_mv.col + site[i].mv.col };
1010
517k
    if (!av1_is_fullmv_in_range(&ms_params->mv_limits, this_mv)) continue;
1011
361k
    int thissad = get_mvpred_sad(ms_params, src,
1012
361k
                                 center_address + site[i].offset, ref->stride);
1013
361k
    if (cost_list) {
1014
408
      cost_list[i + 1] = thissad;
1015
408
    }
1016
361k
    const int found_better_mv = update_mvs_and_sad(
1017
361k
        thissad, &this_mv, mv_cost_params, bestsad, raw_bestsad, best_mv,
1018
361k
        /*second_best_mv=*/NULL);
1019
361k
    if (found_better_mv) *best_site = i;
1020
361k
  }
1021
2.27M
}
1022
1023
static inline void calc_sad_update_bestmv_with_indices(
1024
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1025
    const MV_COST_PARAMS *mv_cost_params, FULLPEL_MV *best_mv,
1026
    const FULLPEL_MV center_mv, const uint8_t *center_address,
1027
    unsigned int *bestsad, unsigned int *raw_bestsad, int search_step,
1028
    int *best_site, const int num_candidates, const int *chkpts_indices,
1029
32.3k
    int *cost_list) {
1030
32.3k
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1031
32.3k
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1032
32.3k
  const search_site *site = ms_params->search_sites->site[search_step];
1033
  // Loop over number of candidates.
1034
129k
  for (int i = 0; i < num_candidates; i++) {
1035
96.9k
    int index = chkpts_indices[i];
1036
96.9k
    const FULLPEL_MV this_mv = { center_mv.row + site[index].mv.row,
1037
96.9k
                                 center_mv.col + site[index].mv.col };
1038
96.9k
    if (!av1_is_fullmv_in_range(&ms_params->mv_limits, this_mv)) {
1039
51.5k
      if (cost_list) {
1040
73
        cost_list[index + 1] = INT_MAX;
1041
73
      }
1042
51.5k
      continue;
1043
51.5k
    }
1044
45.3k
    const int thissad = get_mvpred_sad(
1045
45.3k
        ms_params, src, center_address + site[index].offset, ref->stride);
1046
45.3k
    if (cost_list) {
1047
146
      cost_list[index + 1] = thissad;
1048
146
    }
1049
45.3k
    const int found_better_mv = update_mvs_and_sad(
1050
45.3k
        thissad, &this_mv, mv_cost_params, bestsad, raw_bestsad, best_mv,
1051
45.3k
        /*second_best_mv=*/NULL);
1052
45.3k
    if (found_better_mv) *best_site = i;
1053
45.3k
  }
1054
32.3k
}
1055
1056
// Generic pattern search function that searches over multiple scales.
1057
// Each scale can have a different number of candidates and shape of
1058
// candidates as indicated in the num_candidates and candidates arrays
1059
// passed into this function
1060
static int pattern_search(FULLPEL_MV start_mv,
1061
                          const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1062
                          int search_step, const int do_init_search,
1063
                          int *cost_list, FULLPEL_MV *best_mv,
1064
867k
                          FULLPEL_MV_STATS *best_mv_stats) {
1065
867k
  static const int search_steps[MAX_MVSEARCH_STEPS] = {
1066
867k
    10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
1067
867k
  };
1068
867k
  int i, s, t;
1069
1070
867k
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1071
867k
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1072
867k
  const search_site_config *search_sites = ms_params->search_sites;
1073
867k
  const int *num_candidates = search_sites->searches_per_step;
1074
867k
  const int ref_stride = ref->stride;
1075
867k
  const int last_is_4 = num_candidates[0] == 4;
1076
867k
  int br, bc;
1077
867k
  unsigned int bestsad = UINT_MAX, raw_bestsad = UINT_MAX;
1078
867k
  int k = -1;
1079
867k
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
1080
867k
  search_step = AOMMIN(search_step, MAX_MVSEARCH_STEPS - 1);
1081
867k
  assert(search_step >= 0);
1082
867k
  int best_init_s = search_steps[search_step];
1083
  // adjust ref_mv to make sure it is within MV range
1084
867k
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
1085
867k
  br = start_mv.row;
1086
867k
  bc = start_mv.col;
1087
867k
  if (cost_list != NULL) {
1088
466k
    cost_list[0] = cost_list[1] = cost_list[2] = cost_list[3] = cost_list[4] =
1089
466k
        INT_MAX;
1090
466k
  }
1091
867k
  int costlist_has_sad = 0;
1092
1093
  // Work out the start point for the search
1094
867k
  raw_bestsad = get_mvpred_sad(ms_params, src,
1095
867k
                               get_buf_from_fullmv(ref, &start_mv), ref_stride);
1096
867k
  bestsad = raw_bestsad + mvsad_err_cost_(&start_mv, mv_cost_params);
1097
1098
  // Search all possible scales up to the search param around the center point
1099
  // pick the scale of the point that is best as the starting scale of
1100
  // further steps around it.
1101
867k
  const uint8_t *center_address = get_buf_from_fullmv(ref, &start_mv);
1102
867k
  if (do_init_search) {
1103
224k
    s = best_init_s;
1104
224k
    best_init_s = -1;
1105
1.14M
    for (t = 0; t <= s; ++t) {
1106
924k
      int best_site = -1;
1107
924k
      FULLPEL_MV center_mv = { br, bc };
1108
924k
      if (check_bounds(&ms_params->mv_limits, br, bc, 1 << t)) {
1109
        // Call 4-point sad for multiples of 4 candidates.
1110
879k
        const int no_of_4_cand_loops = num_candidates[t] >> 2;
1111
2.41M
        for (i = 0; i < no_of_4_cand_loops; i++) {
1112
1.53M
          calc_sad4_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1113
1.53M
                                  center_address, &bestsad, &raw_bestsad, t,
1114
1.53M
                                  &best_site, i * 4, /*cost_list=*/NULL);
1115
1.53M
        }
1116
        // Rest of the candidates
1117
879k
        const int remaining_cand = num_candidates[t] % 4;
1118
879k
        calc_sad_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1119
879k
                               center_address, &bestsad, &raw_bestsad, t,
1120
879k
                               &best_site, remaining_cand,
1121
879k
                               no_of_4_cand_loops * 4, NULL);
1122
879k
      } else {
1123
44.8k
        calc_sad_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1124
44.8k
                               center_address, &bestsad, &raw_bestsad, t,
1125
44.8k
                               &best_site, num_candidates[t], 0, NULL);
1126
44.8k
      }
1127
924k
      if (best_site == -1) {
1128
556k
        continue;
1129
556k
      } else {
1130
367k
        best_init_s = t;
1131
367k
        k = best_site;
1132
367k
      }
1133
924k
    }
1134
224k
    if (best_init_s != -1) {
1135
177k
      br += search_sites->site[best_init_s][k].mv.row;
1136
177k
      bc += search_sites->site[best_init_s][k].mv.col;
1137
177k
      center_address += search_sites->site[best_init_s][k].offset;
1138
177k
    }
1139
224k
  }
1140
1141
  // If the center point is still the best, just skip this and move to
1142
  // the refinement step.
1143
867k
  if (best_init_s != -1) {
1144
821k
    const int last_s = (last_is_4 && cost_list != NULL);
1145
821k
    int best_site = -1;
1146
821k
    s = best_init_s;
1147
1148
2.34M
    for (; s >= last_s; s--) {
1149
      // No need to search all points the 1st time if initial search was used
1150
1.52M
      if (!do_init_search || s != best_init_s) {
1151
1.34M
        FULLPEL_MV center_mv = { br, bc };
1152
1.34M
        if (check_bounds(&ms_params->mv_limits, br, bc, 1 << s)) {
1153
          // Call 4-point sad for multiples of 4 candidates.
1154
1.32M
          const int no_of_4_cand_loops = num_candidates[s] >> 2;
1155
3.65M
          for (i = 0; i < no_of_4_cand_loops; i++) {
1156
2.32M
            calc_sad4_update_bestmv(ms_params, mv_cost_params, best_mv,
1157
2.32M
                                    center_mv, center_address, &bestsad,
1158
2.32M
                                    &raw_bestsad, s, &best_site, i * 4,
1159
2.32M
                                    /*cost_list=*/NULL);
1160
2.32M
          }
1161
          // Rest of the candidates
1162
1.32M
          const int remaining_cand = num_candidates[s] % 4;
1163
1.32M
          calc_sad_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1164
1.32M
                                 center_address, &bestsad, &raw_bestsad, s,
1165
1.32M
                                 &best_site, remaining_cand,
1166
1.32M
                                 no_of_4_cand_loops * 4, NULL);
1167
1.32M
        } else {
1168
22.3k
          calc_sad_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1169
22.3k
                                 center_address, &bestsad, &raw_bestsad, s,
1170
22.3k
                                 &best_site, num_candidates[s], 0, NULL);
1171
22.3k
        }
1172
1173
1.34M
        if (best_site == -1) {
1174
559k
          continue;
1175
789k
        } else {
1176
789k
          br += search_sites->site[s][best_site].mv.row;
1177
789k
          bc += search_sites->site[s][best_site].mv.col;
1178
789k
          center_address += search_sites->site[s][best_site].offset;
1179
789k
          k = best_site;
1180
789k
        }
1181
1.34M
      }
1182
1183
1.27M
      do {
1184
1.27M
        int next_chkpts_indices[PATTERN_CANDIDATES_REF];
1185
1.27M
        best_site = -1;
1186
1.27M
        next_chkpts_indices[0] = (k == 0) ? num_candidates[s] - 1 : k - 1;
1187
1.27M
        next_chkpts_indices[1] = k;
1188
1.27M
        next_chkpts_indices[2] = (k == num_candidates[s] - 1) ? 0 : k + 1;
1189
1190
1.27M
        FULLPEL_MV center_mv = { br, bc };
1191
1.27M
        if (check_bounds(&ms_params->mv_limits, br, bc, 1 << s)) {
1192
1.24M
          calc_sad3_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1193
1.24M
                                  center_address, &bestsad, &raw_bestsad, s,
1194
1.24M
                                  &best_site, next_chkpts_indices, NULL);
1195
1.24M
        } else {
1196
31.2k
          calc_sad_update_bestmv_with_indices(
1197
31.2k
              ms_params, mv_cost_params, best_mv, center_mv, center_address,
1198
31.2k
              &bestsad, &raw_bestsad, s, &best_site, PATTERN_CANDIDATES_REF,
1199
31.2k
              next_chkpts_indices, NULL);
1200
31.2k
        }
1201
1202
1.27M
        if (best_site != -1) {
1203
306k
          k = next_chkpts_indices[best_site];
1204
306k
          br += search_sites->site[s][k].mv.row;
1205
306k
          bc += search_sites->site[s][k].mv.col;
1206
306k
          center_address += search_sites->site[s][k].offset;
1207
306k
        }
1208
1.27M
      } while (best_site != -1);
1209
966k
    }
1210
    // Note: If we enter the if below, then cost_list must be non-NULL.
1211
821k
    if (s == 0) {
1212
468k
      cost_list[0] = raw_bestsad;
1213
468k
      costlist_has_sad = 1;
1214
468k
      assert(num_candidates[s] == 4);
1215
468k
      if (!do_init_search || s != best_init_s) {
1216
468k
        FULLPEL_MV center_mv = { br, bc };
1217
468k
        if (check_bounds(&ms_params->mv_limits, br, bc, 1 << s)) {
1218
468k
          calc_sad4_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1219
468k
                                  center_address, &bestsad, &raw_bestsad, s,
1220
468k
                                  &best_site, 0, cost_list);
1221
468k
        } else {
1222
166
          calc_sad_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1223
166
                                 center_address, &bestsad, &raw_bestsad, s,
1224
166
                                 &best_site, /*num_candidates=*/4,
1225
166
                                 /*cand_start=*/0, cost_list);
1226
166
        }
1227
1228
468k
        if (best_site != -1) {
1229
139k
          br += search_sites->site[s][best_site].mv.row;
1230
139k
          bc += search_sites->site[s][best_site].mv.col;
1231
139k
          center_address += search_sites->site[s][best_site].offset;
1232
139k
          k = best_site;
1233
139k
        }
1234
468k
      }
1235
613k
      while (best_site != -1) {
1236
144k
        int next_chkpts_indices[PATTERN_CANDIDATES_REF];
1237
144k
        best_site = -1;
1238
144k
        next_chkpts_indices[0] = (k == 0) ? num_candidates[s] - 1 : k - 1;
1239
144k
        next_chkpts_indices[1] = k;
1240
144k
        next_chkpts_indices[2] = (k == num_candidates[s] - 1) ? 0 : k + 1;
1241
144k
        cost_list[1] = cost_list[2] = cost_list[3] = cost_list[4] = INT_MAX;
1242
144k
        cost_list[((k + 2) % 4) + 1] = cost_list[0];
1243
144k
        cost_list[0] = raw_bestsad;
1244
1245
144k
        FULLPEL_MV center_mv = { br, bc };
1246
144k
        if (check_bounds(&ms_params->mv_limits, br, bc, 1 << s)) {
1247
144k
          assert(PATTERN_CANDIDATES_REF == 3);
1248
144k
          calc_sad3_update_bestmv(ms_params, mv_cost_params, best_mv, center_mv,
1249
144k
                                  center_address, &bestsad, &raw_bestsad, s,
1250
144k
                                  &best_site, next_chkpts_indices, cost_list);
1251
144k
        } else {
1252
93
          calc_sad_update_bestmv_with_indices(
1253
93
              ms_params, mv_cost_params, best_mv, center_mv, center_address,
1254
93
              &bestsad, &raw_bestsad, s, &best_site, PATTERN_CANDIDATES_REF,
1255
93
              next_chkpts_indices, cost_list);
1256
93
        }
1257
1258
144k
        if (best_site != -1) {
1259
5.57k
          k = next_chkpts_indices[best_site];
1260
5.57k
          br += search_sites->site[s][k].mv.row;
1261
5.57k
          bc += search_sites->site[s][k].mv.col;
1262
5.57k
          center_address += search_sites->site[s][k].offset;
1263
5.57k
        }
1264
144k
      }
1265
468k
    }
1266
821k
  }
1267
867k
  best_mv->row = br;
1268
867k
  best_mv->col = bc;
1269
1270
867k
  assert(center_address == get_buf_from_fullmv(ref, best_mv) &&
1271
867k
         "center address is out of sync with best_mv!\n");
1272
1273
  // Returns the one-away integer pel cost/sad around the best as follows:
1274
  // cost_list[0]: cost/sad at the best integer pel
1275
  // cost_list[1]: cost/sad at delta {0, -1} (left)   from the best integer pel
1276
  // cost_list[2]: cost/sad at delta { 1, 0} (bottom) from the best integer pel
1277
  // cost_list[3]: cost/sad at delta { 0, 1} (right)  from the best integer pel
1278
  // cost_list[4]: cost/sad at delta {-1, 0} (top)    from the best integer pel
1279
867k
  if (cost_list) {
1280
467k
    if (USE_SAD_COSTLIST) {
1281
467k
      calc_int_sad_list(*best_mv, ms_params, cost_list, costlist_has_sad);
1282
467k
    } else {
1283
0
      calc_int_cost_list(*best_mv, ms_params, cost_list);
1284
0
    }
1285
467k
  }
1286
1287
867k
  const int var_cost = get_mvpred_var_cost(ms_params, best_mv, best_mv_stats);
1288
867k
  return var_cost;
1289
867k
}
1290
1291
// For the following foo_search, the input arguments are:
1292
// start_mv: where we are starting our motion search
1293
// ms_params: a collection of motion search parameters
1294
// search_step: how many steps to skip in our motion search. For example,
1295
//   a value 3 suggests that 3 search steps have already taken place prior to
1296
//   this function call, so we jump directly to step 4 of the search process
1297
// do_init_search: if on, do an initial search of all possible scales around the
1298
//   start_mv, and then pick the best scale.
1299
// cond_list: used to hold the cost around the best full mv so we can use it to
1300
//   speed up subpel search later.
1301
// best_mv: the best mv found in the motion search
1302
static int hex_search(const FULLPEL_MV start_mv,
1303
                      const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1304
                      const int search_step, const int do_init_search,
1305
                      int *cost_list, FULLPEL_MV *best_mv,
1306
0
                      FULLPEL_MV_STATS *best_mv_stats) {
1307
0
  return pattern_search(start_mv, ms_params, search_step, do_init_search,
1308
0
                        cost_list, best_mv, best_mv_stats);
1309
0
}
1310
1311
static int bigdia_search(const FULLPEL_MV start_mv,
1312
                         const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1313
                         const int search_step, const int do_init_search,
1314
                         int *cost_list, FULLPEL_MV *best_mv,
1315
867k
                         FULLPEL_MV_STATS *best_mv_stats) {
1316
867k
  return pattern_search(start_mv, ms_params, search_step, do_init_search,
1317
867k
                        cost_list, best_mv, best_mv_stats);
1318
867k
}
1319
1320
static int square_search(const FULLPEL_MV start_mv,
1321
                         const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1322
                         const int search_step, const int do_init_search,
1323
                         int *cost_list, FULLPEL_MV *best_mv,
1324
0
                         FULLPEL_MV_STATS *best_mv_stats) {
1325
0
  return pattern_search(start_mv, ms_params, search_step, do_init_search,
1326
0
                        cost_list, best_mv, best_mv_stats);
1327
0
}
1328
1329
static int fast_hex_search(const FULLPEL_MV start_mv,
1330
                           const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1331
                           const int search_step, const int do_init_search,
1332
                           int *cost_list, FULLPEL_MV *best_mv,
1333
0
                           FULLPEL_MV_STATS *best_mv_stats) {
1334
0
  return hex_search(start_mv, ms_params,
1335
0
                    AOMMAX(MAX_MVSEARCH_STEPS - 2, search_step), do_init_search,
1336
0
                    cost_list, best_mv, best_mv_stats);
1337
0
}
1338
1339
static int vfast_dia_search(const FULLPEL_MV start_mv,
1340
                            const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1341
                            const int search_step, const int do_init_search,
1342
                            int *cost_list, FULLPEL_MV *best_mv,
1343
7
                            FULLPEL_MV_STATS *best_mv_stats) {
1344
7
  return bigdia_search(start_mv, ms_params,
1345
7
                       AOMMAX(MAX_MVSEARCH_STEPS - 1, search_step),
1346
7
                       do_init_search, cost_list, best_mv, best_mv_stats);
1347
7
}
1348
1349
static int fast_dia_search(const FULLPEL_MV start_mv,
1350
                           const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1351
                           const int search_step, const int do_init_search,
1352
                           int *cost_list, FULLPEL_MV *best_mv,
1353
467k
                           FULLPEL_MV_STATS *best_mv_stats) {
1354
467k
  return bigdia_search(start_mv, ms_params,
1355
467k
                       AOMMAX(MAX_MVSEARCH_STEPS - 2, search_step),
1356
467k
                       do_init_search, cost_list, best_mv, best_mv_stats);
1357
467k
}
1358
1359
static int fast_bigdia_search(const FULLPEL_MV start_mv,
1360
                              const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1361
                              const int search_step, const int do_init_search,
1362
                              int *cost_list, FULLPEL_MV *best_mv,
1363
176k
                              FULLPEL_MV_STATS *best_mv_stats) {
1364
176k
  return bigdia_search(start_mv, ms_params,
1365
176k
                       AOMMAX(MAX_MVSEARCH_STEPS - 3, search_step),
1366
176k
                       do_init_search, cost_list, best_mv, best_mv_stats);
1367
176k
}
1368
1369
static int diamond_search_sad(FULLPEL_MV start_mv, unsigned int start_mv_sad,
1370
                              const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1371
                              const int search_step, int *num00,
1372
14.6M
                              FULLPEL_MV *best_mv, FULLPEL_MV *second_best_mv) {
1373
14.6M
#define UPDATE_SEARCH_STEP                                      \
1374
54.5M
  do {                                                          \
1375
54.5M
    if (best_site != 0) {                                       \
1376
27.3M
      tmp_second_best_mv = *best_mv;                            \
1377
27.3M
      best_mv->row += site[best_site].mv.row;                   \
1378
27.3M
      best_mv->col += site[best_site].mv.col;                   \
1379
27.3M
      best_address += site[best_site].offset;                   \
1380
27.3M
      is_off_center = 1;                                        \
1381
27.3M
    }                                                           \
1382
54.5M
                                                                \
1383
54.5M
    if (is_off_center == 0) num_center_steps++;                 \
1384
54.5M
                                                                \
1385
54.5M
    if (best_site == 0 && step > 2) {                           \
1386
8.27M
      int next_step_size = cfg->radius[step - 1];               \
1387
8.27M
      while (next_step_size == cfg->radius[step] && step > 2) { \
1388
0
        num_center_steps++;                                     \
1389
0
        --step;                                                 \
1390
0
        next_step_size = cfg->radius[step - 1];                 \
1391
0
      }                                                         \
1392
8.27M
    }                                                           \
1393
54.5M
  } while (0)
1394
1395
14.6M
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1396
14.6M
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1397
1398
14.6M
  const uint8_t *src_buf = src->buf;
1399
14.6M
  const int src_stride = src->stride;
1400
14.6M
  const int ref_stride = ref->stride;
1401
1402
14.6M
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
1403
1404
14.6M
  const search_site_config *cfg = ms_params->search_sites;
1405
1406
14.6M
  int is_off_center = 0;
1407
  // Number of times that we have stayed in the middle. This is used to skip
1408
  // search steps in the future if diamond_search_sad is called again.
1409
14.6M
  int num_center_steps = 0;
1410
1411
  // search_step determines the length of the initial step and hence the number
1412
  // of iterations.
1413
14.6M
  const int tot_steps = cfg->num_search_steps - search_step;
1414
14.6M
  FULLPEL_MV tmp_second_best_mv;
1415
14.6M
  if (second_best_mv) {
1416
9.09M
    tmp_second_best_mv = *second_best_mv;
1417
9.09M
  }
1418
1419
14.6M
  *best_mv = start_mv;
1420
1421
  // Check the starting position
1422
14.6M
  const uint8_t *best_address = get_buf_from_fullmv(ref, &start_mv);
1423
14.6M
  unsigned int bestsad = start_mv_sad;
1424
1425
  // TODO(chiyotsai@google.com): Implement 4 points search for msdf&sdaf
1426
14.6M
  if (ms_params->ms_buffers.second_pred) {
1427
0
    for (int step = tot_steps - 1; step >= 0; --step) {
1428
0
      const search_site *site = cfg->site[step];
1429
0
      const int num_searches = cfg->searches_per_step[step];
1430
0
      int best_site = 0;
1431
1432
0
      for (int idx = 1; idx <= num_searches; idx++) {
1433
0
        const FULLPEL_MV this_mv = { best_mv->row + site[idx].mv.row,
1434
0
                                     best_mv->col + site[idx].mv.col };
1435
1436
0
        if (av1_is_fullmv_in_range(&ms_params->mv_limits, this_mv)) {
1437
0
          const uint8_t *const check_here = site[idx].offset + best_address;
1438
0
          unsigned int thissad =
1439
0
              get_mvpred_compound_sad(ms_params, src, check_here, ref_stride);
1440
1441
0
          if (thissad < bestsad) {
1442
0
            thissad += mvsad_err_cost_(&this_mv, mv_cost_params);
1443
0
            if (thissad < bestsad) {
1444
0
              bestsad = thissad;
1445
0
              best_site = idx;
1446
0
            }
1447
0
          }
1448
0
        }
1449
0
      }
1450
0
      UPDATE_SEARCH_STEP;
1451
0
    }
1452
14.6M
  } else {
1453
69.2M
    for (int step = tot_steps - 1; step >= 0; --step) {
1454
54.5M
      const search_site *site = cfg->site[step];
1455
54.5M
      const int num_searches = cfg->searches_per_step[step];
1456
54.5M
      int best_site = 0;
1457
1458
54.5M
      int all_in = 1;
1459
      // Trap illegal vectors
1460
54.5M
      all_in &= best_mv->row + site[1].mv.row >= ms_params->mv_limits.row_min;
1461
54.5M
      all_in &= best_mv->row + site[2].mv.row <= ms_params->mv_limits.row_max;
1462
54.5M
      all_in &= best_mv->col + site[3].mv.col >= ms_params->mv_limits.col_min;
1463
54.5M
      all_in &= best_mv->col + site[4].mv.col <= ms_params->mv_limits.col_max;
1464
1465
54.5M
      if (all_in) {
1466
145M
        for (int idx = 1; idx <= num_searches; idx += 4) {
1467
97.6M
          unsigned char const *block_offset[4];
1468
97.6M
          unsigned int sads[4];
1469
1470
487M
          for (int j = 0; j < 4; j++)
1471
390M
            block_offset[j] = site[idx + j].offset + best_address;
1472
1473
97.6M
          ms_params->sdx4df(src_buf, src_stride, block_offset, ref_stride,
1474
97.6M
                            sads);
1475
481M
          for (int j = 0; j < 4; j++) {
1476
383M
            if (sads[j] < bestsad) {
1477
96.5M
              const FULLPEL_MV this_mv = { best_mv->row + site[idx + j].mv.row,
1478
96.5M
                                           best_mv->col +
1479
96.5M
                                               site[idx + j].mv.col };
1480
96.5M
              unsigned int thissad =
1481
96.5M
                  sads[j] + mvsad_err_cost_(&this_mv, mv_cost_params);
1482
96.5M
              if (thissad < bestsad) {
1483
36.0M
                bestsad = thissad;
1484
36.0M
                best_site = idx + j;
1485
36.0M
              }
1486
96.5M
            }
1487
383M
          }
1488
97.6M
        }
1489
48.0M
      } else {
1490
64.8M
        for (int idx = 1; idx <= num_searches; idx++) {
1491
58.3M
          const FULLPEL_MV this_mv = { best_mv->row + site[idx].mv.row,
1492
58.3M
                                       best_mv->col + site[idx].mv.col };
1493
1494
58.3M
          if (av1_is_fullmv_in_range(&ms_params->mv_limits, this_mv)) {
1495
29.4M
            const uint8_t *const check_here = site[idx].offset + best_address;
1496
29.4M
            unsigned int thissad =
1497
29.4M
                get_mvpred_sad(ms_params, src, check_here, ref_stride);
1498
1499
29.4M
            if (thissad < bestsad) {
1500
9.90M
              thissad += mvsad_err_cost_(&this_mv, mv_cost_params);
1501
9.90M
              if (thissad < bestsad) {
1502
4.79M
                bestsad = thissad;
1503
4.79M
                best_site = idx;
1504
4.79M
              }
1505
9.90M
            }
1506
29.4M
          }
1507
58.3M
        }
1508
6.47M
      }
1509
54.5M
      UPDATE_SEARCH_STEP;
1510
54.5M
    }
1511
14.6M
  }
1512
1513
14.6M
  *num00 = num_center_steps;
1514
14.6M
  if (second_best_mv) {
1515
9.10M
    *second_best_mv = tmp_second_best_mv;
1516
9.10M
  }
1517
1518
14.6M
  return bestsad;
1519
1520
14.6M
#undef UPDATE_SEARCH_STEP
1521
14.6M
}
1522
1523
static inline unsigned int get_start_mvpred_sad_cost(
1524
3.68M
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV start_mv) {
1525
3.68M
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1526
3.68M
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1527
3.68M
  const uint8_t *best_address = get_buf_from_fullmv(ref, &start_mv);
1528
1529
3.68M
  unsigned int start_mv_sad =
1530
3.68M
      mvsad_err_cost_(&start_mv, &ms_params->mv_cost_params);
1531
1532
3.68M
  if (ms_params->ms_buffers.second_pred)
1533
0
    start_mv_sad +=
1534
0
        get_mvpred_compound_sad(ms_params, src, best_address, ref->stride);
1535
3.68M
  else
1536
3.68M
    start_mv_sad += get_mvpred_sad(ms_params, src, best_address, ref->stride);
1537
1538
3.68M
  return start_mv_sad;
1539
3.68M
}
1540
1541
static int full_pixel_diamond(FULLPEL_MV start_mv,
1542
                              const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1543
                              const int step_param, int *cost_list,
1544
                              FULLPEL_MV *best_mv,
1545
                              FULLPEL_MV_STATS *best_mv_stats,
1546
3.68M
                              FULLPEL_MV *second_best_mv) {
1547
3.68M
  const search_site_config *cfg = ms_params->search_sites;
1548
3.68M
  int thissme, n, num00 = 0;
1549
1550
  // Clamp start mv and calculate the cost
1551
3.68M
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
1552
3.68M
  unsigned int start_mv_sad = get_start_mvpred_sad_cost(ms_params, start_mv);
1553
1554
3.68M
  diamond_search_sad(start_mv, start_mv_sad, ms_params, step_param, &n, best_mv,
1555
3.68M
                     second_best_mv);
1556
1557
3.68M
  int bestsme = get_mvpred_compound_var_cost(ms_params, best_mv, best_mv_stats);
1558
1559
  // If there won't be more n-step search, check to see if refining search is
1560
  // needed.
1561
3.68M
  const int further_steps = cfg->num_search_steps - 1 - step_param;
1562
14.6M
  while (n < further_steps) {
1563
10.9M
    ++n;
1564
1565
    // TODO(chiyotsai@google.com): There is another bug here where the second
1566
    // best mv gets incorrectly overwritten. Fix it later.
1567
10.9M
    FULLPEL_MV tmp_best_mv;
1568
10.9M
    FULLPEL_MV_STATS tmp_best_mv_stats;
1569
10.9M
    diamond_search_sad(start_mv, start_mv_sad, ms_params, step_param + n,
1570
10.9M
                       &num00, &tmp_best_mv, second_best_mv);
1571
1572
10.9M
    thissme = get_mvpred_compound_var_cost(ms_params, &tmp_best_mv,
1573
10.9M
                                           &tmp_best_mv_stats);
1574
1575
10.9M
    if (thissme < bestsme) {
1576
2.04M
      bestsme = thissme;
1577
2.04M
      *best_mv = tmp_best_mv;
1578
2.04M
      *best_mv_stats = tmp_best_mv_stats;
1579
2.04M
    }
1580
1581
10.9M
    if (num00) {
1582
      // Advance the loop by num00 steps
1583
1.30M
      n += num00;
1584
1.30M
      num00 = 0;
1585
1.30M
    }
1586
10.9M
  }
1587
1588
  // Return cost list.
1589
3.68M
  if (cost_list) {
1590
0
    if (USE_SAD_COSTLIST) {
1591
0
      const int costlist_has_sad = 0;
1592
0
      calc_int_sad_list(*best_mv, ms_params, cost_list, costlist_has_sad);
1593
0
    } else {
1594
0
      calc_int_cost_list(*best_mv, ms_params, cost_list);
1595
0
    }
1596
0
  }
1597
3.68M
  return bestsme;
1598
3.68M
}
1599
1600
// Exhaustive motion search around a given centre position with a given
1601
// step size.
1602
static int exhaustive_mesh_search(FULLPEL_MV start_mv,
1603
                                  const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1604
                                  const int range, const int step,
1605
                                  FULLPEL_MV *best_mv,
1606
715k
                                  FULLPEL_MV *second_best_mv) {
1607
715k
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
1608
715k
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1609
715k
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1610
715k
  const int ref_stride = ref->stride;
1611
715k
  unsigned int best_sad = INT_MAX;
1612
715k
  int r, c, i;
1613
715k
  int start_col, end_col, start_row, end_row;
1614
715k
  const int col_step = (step > 1) ? step : 4;
1615
1616
715k
  assert(step >= 1);
1617
1618
715k
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
1619
715k
  *best_mv = start_mv;
1620
715k
  best_sad = get_mvpred_sad(ms_params, src, get_buf_from_fullmv(ref, &start_mv),
1621
715k
                            ref_stride);
1622
715k
  best_sad += mvsad_err_cost_(&start_mv, mv_cost_params);
1623
715k
  start_row = AOMMAX(-range, ms_params->mv_limits.row_min - start_mv.row);
1624
715k
  start_col = AOMMAX(-range, ms_params->mv_limits.col_min - start_mv.col);
1625
715k
  end_row = AOMMIN(range, ms_params->mv_limits.row_max - start_mv.row);
1626
715k
  end_col = AOMMIN(range, ms_params->mv_limits.col_max - start_mv.col);
1627
1628
6.58M
  for (r = start_row; r <= end_row; r += step) {
1629
33.5M
    for (c = start_col; c <= end_col; c += col_step) {
1630
      // Step > 1 means we are not checking every location in this pass.
1631
27.6M
      if (step > 1) {
1632
19.8M
        const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c };
1633
19.8M
        unsigned int sad = get_mvpred_sad(
1634
19.8M
            ms_params, src, get_buf_from_fullmv(ref, &mv), ref_stride);
1635
19.8M
        update_mvs_and_sad(sad, &mv, mv_cost_params, &best_sad,
1636
19.8M
                           /*raw_best_sad=*/NULL, best_mv, second_best_mv);
1637
19.8M
      } else {
1638
        // 4 sads in a single call if we are checking every location
1639
7.76M
        if (c + 3 <= end_col) {
1640
7.45M
          unsigned int sads[4];
1641
7.45M
          const uint8_t *addrs[4];
1642
35.4M
          for (i = 0; i < 4; ++i) {
1643
27.9M
            const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c + i };
1644
27.9M
            addrs[i] = get_buf_from_fullmv(ref, &mv);
1645
27.9M
          }
1646
1647
7.45M
          ms_params->sdx4df(src->buf, src->stride, addrs, ref_stride, sads);
1648
1649
35.6M
          for (i = 0; i < 4; ++i) {
1650
28.2M
            if (sads[i] < best_sad) {
1651
6.94M
              const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c + i };
1652
6.94M
              update_mvs_and_sad(sads[i], &mv, mv_cost_params, &best_sad,
1653
6.94M
                                 /*raw_best_sad=*/NULL, best_mv,
1654
6.94M
                                 second_best_mv);
1655
6.94M
            }
1656
28.2M
          }
1657
7.45M
        } else {
1658
5.30M
          for (i = 0; i < end_col - c; ++i) {
1659
5.00M
            const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c + i };
1660
5.00M
            unsigned int sad = get_mvpred_sad(
1661
5.00M
                ms_params, src, get_buf_from_fullmv(ref, &mv), ref_stride);
1662
5.00M
            update_mvs_and_sad(sad, &mv, mv_cost_params, &best_sad,
1663
5.00M
                               /*raw_best_sad=*/NULL, best_mv, second_best_mv);
1664
5.00M
          }
1665
302k
        }
1666
7.76M
      }
1667
27.6M
    }
1668
5.86M
  }
1669
1670
715k
  return best_sad;
1671
715k
}
1672
1673
// Runs an limited range exhaustive mesh search using a pattern set
1674
// according to the encode speed profile.
1675
static int full_pixel_exhaustive(const FULLPEL_MV start_mv,
1676
                                 const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1677
                                 const struct MESH_PATTERN *const mesh_patterns,
1678
                                 int *cost_list, FULLPEL_MV *best_mv,
1679
                                 FULLPEL_MV_STATS *mv_stats,
1680
179k
                                 FULLPEL_MV *second_best_mv) {
1681
179k
  const int kMinRange = 7;
1682
179k
  const int kMaxRange = 256;
1683
179k
  const int kMinInterval = 1;
1684
1685
179k
  int bestsme;
1686
179k
  int i;
1687
179k
  int interval = mesh_patterns[0].interval;
1688
179k
  int range = mesh_patterns[0].range;
1689
179k
  int baseline_interval_divisor;
1690
1691
  // TODO(chiyotsai@google.com): Currently exhaustive search calls single ref
1692
  // version of sad and variance function. We still need to check the
1693
  // performance when compound ref exhaustive search is enabled.
1694
179k
  assert(!ms_params->ms_buffers.second_pred &&
1695
179k
         "Mesh search does not support compound mode!");
1696
1697
179k
  *best_mv = start_mv;
1698
1699
  // Trap illegal values for interval and range for this function.
1700
179k
  if ((range < kMinRange) || (range > kMaxRange) || (interval < kMinInterval) ||
1701
179k
      (interval > range))
1702
0
    return INT_MAX;
1703
1704
179k
  baseline_interval_divisor = range / interval;
1705
1706
  // Check size of proposed first range against magnitude of the centre
1707
  // value used as a starting point.
1708
179k
  range = AOMMAX(range, (5 * AOMMAX(abs(best_mv->row), abs(best_mv->col))) / 4);
1709
179k
  range = AOMMIN(range, kMaxRange);
1710
179k
  interval = AOMMAX(interval, range / baseline_interval_divisor);
1711
  // Use a small search step/interval for certain kind of clips.
1712
  // For example, screen content clips with a lot of texts.
1713
  // Large interval could lead to a false matching position, and it can't find
1714
  // the best global candidate in following iterations due to reduced search
1715
  // range. The solution here is to use a small search iterval in the beginning
1716
  // and thus reduces the chance of missing the best candidate.
1717
179k
  if (ms_params->fine_search_interval) {
1718
0
    interval = AOMMIN(interval, 4);
1719
0
  }
1720
1721
  // initial search
1722
179k
  bestsme = exhaustive_mesh_search(*best_mv, ms_params, range, interval,
1723
179k
                                   best_mv, second_best_mv);
1724
1725
179k
  if ((interval > kMinInterval) && (range > kMinRange)) {
1726
    // Progressive searches with range and step size decreasing each time
1727
    // till we reach a step size of 1. Then break out.
1728
536k
    for (i = 1; i < MAX_MESH_STEP; ++i) {
1729
      // First pass with coarser step and longer range
1730
536k
      bestsme = exhaustive_mesh_search(
1731
536k
          *best_mv, ms_params, mesh_patterns[i].range,
1732
536k
          mesh_patterns[i].interval, best_mv, second_best_mv);
1733
1734
536k
      if (mesh_patterns[i].interval == 1) break;
1735
536k
    }
1736
179k
  }
1737
1738
179k
  if (bestsme < INT_MAX) {
1739
179k
    bestsme = get_mvpred_var_cost(ms_params, best_mv, mv_stats);
1740
179k
  }
1741
1742
  // Return cost list.
1743
179k
  if (cost_list) {
1744
0
    if (USE_SAD_COSTLIST) {
1745
0
      const int costlist_has_sad = 0;
1746
0
      calc_int_sad_list(*best_mv, ms_params, cost_list, costlist_has_sad);
1747
0
    } else {
1748
0
      calc_int_cost_list(*best_mv, ms_params, cost_list);
1749
0
    }
1750
0
  }
1751
179k
  return bestsme;
1752
179k
}
1753
1754
// This function is called when we do joint motion search in comp_inter_inter
1755
// mode, or when searching for one component of an ext-inter compound mode.
1756
int av1_refining_search_8p_c(const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1757
0
                             const FULLPEL_MV start_mv, FULLPEL_MV *best_mv) {
1758
0
  static const search_neighbors neighbors[8] = {
1759
0
    { { -1, 0 }, -1 * SEARCH_GRID_STRIDE_8P + 0 },
1760
0
    { { 0, -1 }, 0 * SEARCH_GRID_STRIDE_8P - 1 },
1761
0
    { { 0, 1 }, 0 * SEARCH_GRID_STRIDE_8P + 1 },
1762
0
    { { 1, 0 }, 1 * SEARCH_GRID_STRIDE_8P + 0 },
1763
0
    { { -1, -1 }, -1 * SEARCH_GRID_STRIDE_8P - 1 },
1764
0
    { { 1, -1 }, 1 * SEARCH_GRID_STRIDE_8P - 1 },
1765
0
    { { -1, 1 }, -1 * SEARCH_GRID_STRIDE_8P + 1 },
1766
0
    { { 1, 1 }, 1 * SEARCH_GRID_STRIDE_8P + 1 }
1767
0
  };
1768
1769
0
  uint8_t do_refine_search_grid[SEARCH_GRID_STRIDE_8P *
1770
0
                                SEARCH_GRID_STRIDE_8P] = { 0 };
1771
0
  int grid_center = SEARCH_GRID_CENTER_8P;
1772
0
  int grid_coord = grid_center;
1773
1774
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
1775
0
  const FullMvLimits *mv_limits = &ms_params->mv_limits;
1776
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
1777
0
  const struct buf_2d *src = ms_buffers->src;
1778
0
  const struct buf_2d *ref = ms_buffers->ref;
1779
0
  const int ref_stride = ref->stride;
1780
1781
0
  *best_mv = start_mv;
1782
0
  clamp_fullmv(best_mv, mv_limits);
1783
1784
0
  unsigned int best_sad = get_mvpred_compound_sad(
1785
0
      ms_params, src, get_buf_from_fullmv(ref, best_mv), ref_stride);
1786
0
  best_sad += mvsad_err_cost_(best_mv, mv_cost_params);
1787
1788
0
  do_refine_search_grid[grid_coord] = 1;
1789
1790
0
  for (int i = 0; i < SEARCH_RANGE_8P; ++i) {
1791
0
    int best_site = -1;
1792
1793
0
    for (int j = 0; j < 8; ++j) {
1794
0
      grid_coord = grid_center + neighbors[j].coord_offset;
1795
0
      if (do_refine_search_grid[grid_coord] == 1) {
1796
0
        continue;
1797
0
      }
1798
0
      const FULLPEL_MV mv = { best_mv->row + neighbors[j].coord.row,
1799
0
                              best_mv->col + neighbors[j].coord.col };
1800
1801
0
      do_refine_search_grid[grid_coord] = 1;
1802
0
      if (av1_is_fullmv_in_range(mv_limits, mv)) {
1803
0
        unsigned int sad;
1804
0
        sad = get_mvpred_compound_sad(
1805
0
            ms_params, src, get_buf_from_fullmv(ref, &mv), ref_stride);
1806
0
        if (sad < best_sad) {
1807
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
1808
1809
0
          if (sad < best_sad) {
1810
0
            best_sad = sad;
1811
0
            best_site = j;
1812
0
          }
1813
0
        }
1814
0
      }
1815
0
    }
1816
1817
0
    if (best_site == -1) {
1818
0
      break;
1819
0
    } else {
1820
0
      best_mv->row += neighbors[best_site].coord.row;
1821
0
      best_mv->col += neighbors[best_site].coord.col;
1822
0
      grid_center += neighbors[best_site].coord_offset;
1823
0
    }
1824
0
  }
1825
0
  return best_sad;
1826
0
}
1827
1828
int av1_full_pixel_search(const FULLPEL_MV start_mv,
1829
                          const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1830
                          const int step_param, int *cost_list,
1831
                          FULLPEL_MV *best_mv, FULLPEL_MV_STATS *best_mv_stats,
1832
4.55M
                          FULLPEL_MV *second_best_mv) {
1833
4.55M
  const BLOCK_SIZE bsize = ms_params->bsize;
1834
4.55M
  const SEARCH_METHODS search_method = ms_params->search_method;
1835
1836
4.55M
  const int is_intra_mode = ms_params->is_intra_mode;
1837
4.55M
  int run_mesh_search = ms_params->run_mesh_search;
1838
1839
4.55M
  int var = 0;
1840
4.55M
  MARK_MV_INVALID(best_mv);
1841
4.55M
  if (second_best_mv) {
1842
1.80M
    MARK_MV_INVALID(second_best_mv);
1843
1.80M
  }
1844
1845
4.55M
  if (cost_list) {
1846
467k
    cost_list[0] = INT_MAX;
1847
467k
    cost_list[1] = INT_MAX;
1848
467k
    cost_list[2] = INT_MAX;
1849
467k
    cost_list[3] = INT_MAX;
1850
467k
    cost_list[4] = INT_MAX;
1851
467k
  }
1852
1853
4.55M
  assert(ms_params->ms_buffers.ref->stride == ms_params->search_sites->stride);
1854
1855
4.55M
  switch (search_method) {
1856
176k
    case FAST_BIGDIA:
1857
176k
      var = fast_bigdia_search(start_mv, ms_params, step_param, 0, cost_list,
1858
176k
                               best_mv, best_mv_stats);
1859
176k
      break;
1860
7
    case VFAST_DIAMOND:
1861
7
      var = vfast_dia_search(start_mv, ms_params, step_param, 0, cost_list,
1862
7
                             best_mv, best_mv_stats);
1863
7
      break;
1864
467k
    case FAST_DIAMOND:
1865
467k
      var = fast_dia_search(start_mv, ms_params, step_param, 0, cost_list,
1866
467k
                            best_mv, best_mv_stats);
1867
467k
      break;
1868
0
    case FAST_HEX:
1869
0
      var = fast_hex_search(start_mv, ms_params, step_param, 0, cost_list,
1870
0
                            best_mv, best_mv_stats);
1871
0
      break;
1872
0
    case HEX:
1873
0
      var = hex_search(start_mv, ms_params, step_param, 1, cost_list, best_mv,
1874
0
                       best_mv_stats);
1875
0
      break;
1876
0
    case SQUARE:
1877
0
      var = square_search(start_mv, ms_params, step_param, 1, cost_list,
1878
0
                          best_mv, best_mv_stats);
1879
0
      break;
1880
224k
    case BIGDIA:
1881
224k
      var = bigdia_search(start_mv, ms_params, step_param, 1, cost_list,
1882
224k
                          best_mv, best_mv_stats);
1883
224k
      break;
1884
399k
    case NSTEP:
1885
399k
    case NSTEP_8PT:
1886
3.68M
    case DIAMOND:
1887
3.68M
    case CLAMPED_DIAMOND:
1888
3.68M
      var = full_pixel_diamond(start_mv, ms_params, step_param, cost_list,
1889
3.68M
                               best_mv, best_mv_stats, second_best_mv);
1890
3.68M
      break;
1891
0
    default: assert(0 && "Invalid search method.");
1892
4.55M
  }
1893
1894
  // Should we allow a follow on exhaustive search?
1895
4.54M
  if (!run_mesh_search &&
1896
4.35M
      ((search_method == NSTEP) || (search_method == NSTEP_8PT)) &&
1897
200k
      !ms_params->ms_buffers.second_pred) {
1898
200k
    int exhaustive_thr = ms_params->force_mesh_thresh;
1899
200k
    exhaustive_thr >>=
1900
200k
        10 - (mi_size_wide_log2[bsize] + mi_size_high_log2[bsize]);
1901
    // Threshold variance for an exhaustive full search.
1902
200k
    if (var > exhaustive_thr) run_mesh_search = 1;
1903
200k
  }
1904
1905
  // TODO(yunqing): the following is used to reduce mesh search in temporal
1906
  // filtering. Can extend it to intrabc.
1907
4.54M
  if (!is_intra_mode && ms_params->prune_mesh_search) {
1908
4.08M
    const int full_pel_mv_diff = AOMMAX(abs(start_mv.row - best_mv->row),
1909
4.08M
                                        abs(start_mv.col - best_mv->col));
1910
4.08M
    if (full_pel_mv_diff <= ms_params->mesh_search_mv_diff_threshold) {
1911
2.18M
      run_mesh_search = 0;
1912
2.18M
    }
1913
4.08M
  }
1914
1915
4.54M
  if (ms_params->sdf != ms_params->vfp->sdf) {
1916
    // If we are skipping rows when we perform the motion search, we need to
1917
    // check the quality of skipping. If it's bad, then we run mesh search with
1918
    // skip row features off.
1919
    // TODO(chiyotsai@google.com): Handle the case where we have a vertical
1920
    // offset of 1 before we hit this statement to avoid having to redo
1921
    // motion search.
1922
650k
    const struct buf_2d *src = ms_params->ms_buffers.src;
1923
650k
    const struct buf_2d *ref = ms_params->ms_buffers.ref;
1924
650k
    const int src_stride = src->stride;
1925
650k
    const int ref_stride = ref->stride;
1926
1927
650k
    const uint8_t *src_address = src->buf;
1928
650k
    const uint8_t *best_address = get_buf_from_fullmv(ref, best_mv);
1929
650k
    const int sad =
1930
650k
        ms_params->vfp->sdf(src_address, src_stride, best_address, ref_stride);
1931
650k
    const int skip_sad =
1932
650k
        ms_params->vfp->sdsf(src_address, src_stride, best_address, ref_stride);
1933
    // We will keep the result of skipping rows if it's good enough. Here, good
1934
    // enough means the error is less than 1 per pixel.
1935
650k
    const int kSADThresh =
1936
650k
        1 << (mi_size_wide_log2[bsize] + mi_size_high_log2[bsize]);
1937
650k
    if (sad > kSADThresh && abs(skip_sad - sad) * 10 >= AOMMAX(sad, 1) * 9) {
1938
      // There is a large discrepancy between skipping and not skipping, so we
1939
      // need to redo the motion search.
1940
15
      FULLPEL_MOTION_SEARCH_PARAMS new_ms_params = *ms_params;
1941
15
      new_ms_params.sdf = new_ms_params.vfp->sdf;
1942
15
      new_ms_params.sdx4df = new_ms_params.vfp->sdx4df;
1943
15
      new_ms_params.sdx3df = new_ms_params.vfp->sdx3df;
1944
1945
15
      return av1_full_pixel_search(start_mv, &new_ms_params, step_param,
1946
15
                                   cost_list, best_mv, best_mv_stats,
1947
15
                                   second_best_mv);
1948
15
    }
1949
650k
  }
1950
1951
4.54M
  if (run_mesh_search) {
1952
179k
    int var_ex;
1953
179k
    FULLPEL_MV tmp_mv_ex;
1954
179k
    FULLPEL_MV_STATS tmp_mv_stats;
1955
    // Pick the mesh pattern for exhaustive search based on the toolset (intraBC
1956
    // or non-intraBC)
1957
    // TODO(chiyotsai@google.com):  There is a bug here where the second best mv
1958
    // gets overwritten without actually comparing the rdcost.
1959
179k
    const MESH_PATTERN *const mesh_patterns =
1960
179k
        ms_params->mesh_patterns[is_intra_mode];
1961
    // TODO(chiyotsai@google.com): the second best mv is not set correctly by
1962
    // full_pixel_exhaustive, which can incorrectly override it.
1963
179k
    var_ex =
1964
179k
        full_pixel_exhaustive(*best_mv, ms_params, mesh_patterns, cost_list,
1965
179k
                              &tmp_mv_ex, &tmp_mv_stats, second_best_mv);
1966
179k
    if (var_ex < var) {
1967
50.0k
      var = var_ex;
1968
50.0k
      *best_mv_stats = tmp_mv_stats;
1969
50.0k
      *best_mv = tmp_mv_ex;
1970
50.0k
    }
1971
179k
  }
1972
1973
4.54M
  return var;
1974
4.54M
}
1975
1976
int av1_intrabc_hash_search(const AV1_COMP *cpi, const MACROBLOCKD *xd,
1977
                            const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1978
                            IntraBCHashInfo *intrabc_hash_info,
1979
0
                            FULLPEL_MV *best_mv) {
1980
0
  if (!av1_use_hash_me(cpi)) return INT_MAX;
1981
1982
0
  const BLOCK_SIZE bsize = ms_params->bsize;
1983
0
  const int block_width = block_size_wide[bsize];
1984
0
  const int block_height = block_size_high[bsize];
1985
1986
0
  if (block_width != block_height) return INT_MAX;
1987
1988
0
  const FullMvLimits *mv_limits = &ms_params->mv_limits;
1989
0
  const MSBuffers *ms_buffer = &ms_params->ms_buffers;
1990
1991
0
  const uint8_t *src = ms_buffer->src->buf;
1992
0
  const int src_stride = ms_buffer->src->stride;
1993
1994
0
  const int mi_row = xd->mi_row;
1995
0
  const int mi_col = xd->mi_col;
1996
0
  const int x_pos = mi_col * MI_SIZE;
1997
0
  const int y_pos = mi_row * MI_SIZE;
1998
1999
0
  uint32_t hash_value1, hash_value2;
2000
0
  int best_hash_cost = INT_MAX;
2001
2002
  // for the hashMap
2003
0
  hash_table *ref_frame_hash = &intrabc_hash_info->intrabc_hash_table;
2004
2005
0
  av1_get_block_hash_value(intrabc_hash_info, src, src_stride, block_width,
2006
0
                           &hash_value1, &hash_value2, is_cur_buf_hbd(xd));
2007
2008
0
  int count = av1_hash_table_count(ref_frame_hash, hash_value1);
2009
0
  if (count <= 1) {
2010
0
    return INT_MAX;
2011
0
  }
2012
0
  if (cpi->sf.mv_sf.prune_intrabc_candidate_block_hash_search) {
2013
0
    count = AOMMIN(64, count);
2014
0
  }
2015
2016
0
  Iterator iterator = av1_hash_get_first_iterator(ref_frame_hash, hash_value1);
2017
0
  for (int i = 0; i < count; i++, aom_iterator_increment(&iterator)) {
2018
0
    block_hash ref_block_hash = *(block_hash *)(aom_iterator_get(&iterator));
2019
0
    if (hash_value2 == ref_block_hash.hash_value2) {
2020
      // Make sure the prediction is from valid area.
2021
0
      const MV dv = { GET_MV_SUBPEL(ref_block_hash.y - y_pos),
2022
0
                      GET_MV_SUBPEL(ref_block_hash.x - x_pos) };
2023
0
      if (!av1_is_dv_valid(dv, &cpi->common, xd, mi_row, mi_col, bsize,
2024
0
                           cpi->common.seq_params->mib_size_log2))
2025
0
        continue;
2026
2027
0
      FULLPEL_MV hash_mv;
2028
0
      hash_mv.col = ref_block_hash.x - x_pos;
2029
0
      hash_mv.row = ref_block_hash.y - y_pos;
2030
0
      if (!av1_is_fullmv_in_range(mv_limits, hash_mv)) continue;
2031
0
      FULLPEL_MV_STATS mv_stats;
2032
0
      const int refCost = get_mvpred_var_cost(ms_params, &hash_mv, &mv_stats);
2033
0
      if (refCost < best_hash_cost) {
2034
0
        best_hash_cost = refCost;
2035
0
        *best_mv = hash_mv;
2036
0
      }
2037
0
    }
2038
0
  }
2039
2040
0
  return best_hash_cost;
2041
0
}
2042
2043
int av1_vector_match(const int16_t *ref, const int16_t *src, int bwl,
2044
123k
                     int search_size, int full_search, int *sad) {
2045
123k
  int best_sad = INT_MAX;
2046
123k
  int this_sad;
2047
123k
  int d;
2048
123k
  int center, offset = 0;
2049
123k
  int bw = search_size << 1;
2050
2051
123k
  if (full_search) {
2052
0
    for (d = 0; d <= bw; d++) {
2053
0
      this_sad = aom_vector_var(&ref[d], src, bwl);
2054
0
      if (this_sad < best_sad) {
2055
0
        best_sad = this_sad;
2056
0
        offset = d;
2057
0
      }
2058
0
    }
2059
0
    center = offset;
2060
0
    *sad = best_sad;
2061
0
    return (center - (bw >> 1));
2062
0
  }
2063
2064
412k
  for (d = 0; d <= bw; d += 16) {
2065
289k
    this_sad = aom_vector_var(&ref[d], src, bwl);
2066
289k
    if (this_sad < best_sad) {
2067
196k
      best_sad = this_sad;
2068
196k
      offset = d;
2069
196k
    }
2070
289k
  }
2071
123k
  center = offset;
2072
2073
370k
  for (d = -8; d <= 8; d += 16) {
2074
246k
    int this_pos = offset + d;
2075
    // check limit
2076
246k
    if (this_pos < 0 || this_pos > bw) continue;
2077
130k
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2078
130k
    if (this_sad < best_sad) {
2079
36.1k
      best_sad = this_sad;
2080
36.1k
      center = this_pos;
2081
36.1k
    }
2082
130k
  }
2083
123k
  offset = center;
2084
2085
370k
  for (d = -4; d <= 4; d += 8) {
2086
246k
    int this_pos = offset + d;
2087
    // check limit
2088
246k
    if (this_pos < 0 || this_pos > bw) continue;
2089
164k
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2090
164k
    if (this_sad < best_sad) {
2091
35.5k
      best_sad = this_sad;
2092
35.5k
      center = this_pos;
2093
35.5k
    }
2094
164k
  }
2095
123k
  offset = center;
2096
2097
370k
  for (d = -2; d <= 2; d += 4) {
2098
246k
    int this_pos = offset + d;
2099
    // check limit
2100
246k
    if (this_pos < 0 || this_pos > bw) continue;
2101
183k
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2102
183k
    if (this_sad < best_sad) {
2103
32.4k
      best_sad = this_sad;
2104
32.4k
      center = this_pos;
2105
32.4k
    }
2106
183k
  }
2107
123k
  offset = center;
2108
2109
370k
  for (d = -1; d <= 1; d += 2) {
2110
246k
    int this_pos = offset + d;
2111
    // check limit
2112
246k
    if (this_pos < 0 || this_pos > bw) continue;
2113
196k
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2114
196k
    if (this_sad < best_sad) {
2115
28.8k
      best_sad = this_sad;
2116
28.8k
      center = this_pos;
2117
28.8k
    }
2118
196k
  }
2119
123k
  *sad = best_sad;
2120
123k
  return (center - (bw >> 1));
2121
123k
}
2122
2123
// A special fast version of motion search used in rt mode.
2124
// The search window along columns and row is given by:
2125
//  +/- me_search_size_col/row.
2126
unsigned int av1_int_pro_motion_estimation(const AV1_COMP *cpi, MACROBLOCK *x,
2127
                                           BLOCK_SIZE bsize, int mi_row,
2128
                                           int mi_col, const MV *ref_mv,
2129
                                           unsigned int *y_sad_zero,
2130
                                           int me_search_size_col,
2131
63.3k
                                           int me_search_size_row) {
2132
63.3k
  const AV1_COMMON *const cm = &cpi->common;
2133
63.3k
  MACROBLOCKD *xd = &x->e_mbd;
2134
63.3k
  MB_MODE_INFO *mi = xd->mi[0];
2135
63.3k
  struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0, 0, 0, 0 } };
2136
63.3k
  int idx;
2137
63.3k
  const int bw = block_size_wide[bsize];
2138
63.3k
  const int bh = block_size_high[bsize];
2139
63.3k
  const int is_screen = cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN;
2140
63.3k
  const int full_search = is_screen;
2141
63.3k
  const bool screen_scroll_superblock =
2142
63.3k
      is_screen && bsize == cm->seq_params->sb_size;
2143
  // Keep border a multiple of 16.
2144
63.3k
  const int border = (cpi->oxcf.border_in_pixels >> 4) << 4;
2145
63.3k
  int search_size_width = me_search_size_col;
2146
63.3k
  int search_size_height = me_search_size_row;
2147
  // Adjust based on boundary.
2148
63.3k
  if (((mi_col << 2) - search_size_width < -border) ||
2149
63.2k
      ((mi_col << 2) + search_size_width > cm->width + border))
2150
0
    search_size_width = border;
2151
63.3k
  if (((mi_row << 2) - search_size_height < -border) ||
2152
63.3k
      ((mi_row << 2) + search_size_height > cm->height + border))
2153
0
    search_size_height = border;
2154
63.3k
  const int src_stride = x->plane[0].src.stride;
2155
63.3k
  const int ref_stride = xd->plane[0].pre[0].stride;
2156
63.3k
  uint8_t const *ref_buf, *src_buf;
2157
63.3k
  int_mv *best_int_mv = &xd->mi[0]->mv[0];
2158
63.3k
  unsigned int best_sad, tmp_sad, this_sad[4];
2159
63.3k
  int best_sad_col, best_sad_row;
2160
63.3k
  const int row_norm_factor = mi_size_high_log2[bsize] + 1;
2161
63.3k
  const int col_norm_factor = 3 + (bw >> 5);
2162
63.3k
  const YV12_BUFFER_CONFIG *scaled_ref_frame =
2163
63.3k
      av1_get_scaled_ref_frame(cpi, mi->ref_frame[0]);
2164
63.3k
  static const MV search_pos[4] = {
2165
63.3k
    { -1, 0 },
2166
63.3k
    { 0, -1 },
2167
63.3k
    { 0, 1 },
2168
63.3k
    { 1, 0 },
2169
63.3k
  };
2170
2171
63.3k
  if (scaled_ref_frame) {
2172
0
    int i;
2173
    // Swap out the reference frame for a version that's been scaled to
2174
    // match the resolution of the current frame, allowing the existing
2175
    // motion search code to be used without additional modifications.
2176
0
    for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
2177
0
    av1_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL,
2178
0
                         MAX_MB_PLANE);
2179
0
  }
2180
2181
63.3k
  if (xd->bd != 8) {
2182
1.60k
    best_int_mv->as_fullmv = kZeroFullMv;
2183
1.60k
    best_sad = cpi->ppi->fn_ptr[bsize].sdf(x->plane[0].src.buf, src_stride,
2184
1.60k
                                           xd->plane[0].pre[0].buf, ref_stride);
2185
2186
1.60k
    if (scaled_ref_frame) {
2187
0
      int i;
2188
0
      for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2189
0
    }
2190
1.60k
    return best_sad;
2191
1.60k
  }
2192
61.7k
  const int width_ref_buf = (search_size_width << 1) + bw;
2193
61.7k
  const int height_ref_buf = (search_size_height << 1) + bh;
2194
61.7k
  int16_t *hbuf = (int16_t *)aom_malloc(width_ref_buf * sizeof(*hbuf));
2195
61.7k
  int16_t *vbuf = (int16_t *)aom_malloc(height_ref_buf * sizeof(*vbuf));
2196
61.7k
  int16_t *src_hbuf = (int16_t *)aom_malloc(bw * sizeof(*src_hbuf));
2197
61.7k
  int16_t *src_vbuf = (int16_t *)aom_malloc(bh * sizeof(*src_vbuf));
2198
61.8k
  if (!hbuf || !vbuf || !src_hbuf || !src_vbuf) {
2199
0
    aom_free(hbuf);
2200
0
    aom_free(vbuf);
2201
0
    aom_free(src_hbuf);
2202
0
    aom_free(src_vbuf);
2203
0
    aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2204
0
                       "Failed to allocate hbuf, vbuf, src_hbuf, or src_vbuf");
2205
0
  }
2206
2207
  // Set up prediction 1-D reference set for rows.
2208
61.7k
  ref_buf = xd->plane[0].pre[0].buf - search_size_width;
2209
61.7k
  aom_int_pro_row(hbuf, ref_buf, ref_stride, width_ref_buf, bh,
2210
61.7k
                  row_norm_factor);
2211
2212
  // Set up prediction 1-D reference set for cols
2213
61.7k
  ref_buf = xd->plane[0].pre[0].buf - search_size_height * ref_stride;
2214
61.7k
  aom_int_pro_col(vbuf, ref_buf, ref_stride, bw, height_ref_buf,
2215
61.7k
                  col_norm_factor);
2216
2217
  // Set up src 1-D reference set
2218
61.7k
  src_buf = x->plane[0].src.buf;
2219
61.7k
  aom_int_pro_row(src_hbuf, src_buf, src_stride, bw, bh, row_norm_factor);
2220
61.7k
  aom_int_pro_col(src_vbuf, src_buf, src_stride, bw, bh, col_norm_factor);
2221
2222
  // Find the best match per 1-D search
2223
61.7k
  best_int_mv->as_fullmv.col =
2224
61.7k
      av1_vector_match(hbuf, src_hbuf, mi_size_wide_log2[bsize],
2225
61.7k
                       search_size_width, full_search, &best_sad_col);
2226
61.7k
  best_int_mv->as_fullmv.row =
2227
61.7k
      av1_vector_match(vbuf, src_vbuf, mi_size_high_log2[bsize],
2228
61.7k
                       search_size_height, full_search, &best_sad_row);
2229
2230
  // For screen: select between horiz or vert motion.
2231
61.7k
  if (is_screen) {
2232
0
    if (best_sad_col < best_sad_row)
2233
0
      best_int_mv->as_fullmv.row = 0;
2234
0
    else
2235
0
      best_int_mv->as_fullmv.col = 0;
2236
0
  }
2237
2238
61.7k
  FULLPEL_MV this_mv = best_int_mv->as_fullmv;
2239
61.7k
  src_buf = x->plane[0].src.buf;
2240
61.7k
  ref_buf = get_buf_from_fullmv(&xd->plane[0].pre[0], &this_mv);
2241
61.7k
  best_sad =
2242
61.7k
      cpi->ppi->fn_ptr[bsize].sdf(src_buf, src_stride, ref_buf, ref_stride);
2243
2244
  // Evaluate zero MV if found MV is non-zero.
2245
61.7k
  if (best_int_mv->as_int != 0) {
2246
61.2k
    tmp_sad = cpi->ppi->fn_ptr[bsize].sdf(x->plane[0].src.buf, src_stride,
2247
61.2k
                                          xd->plane[0].pre[0].buf, ref_stride);
2248
61.2k
    *y_sad_zero = tmp_sad;
2249
61.2k
    if (tmp_sad < best_sad) {
2250
22.9k
      best_int_mv->as_fullmv = kZeroFullMv;
2251
22.9k
      this_mv = best_int_mv->as_fullmv;
2252
22.9k
      ref_buf = xd->plane[0].pre[0].buf;
2253
22.9k
      best_sad = tmp_sad;
2254
22.9k
    }
2255
61.2k
  } else {
2256
511
    *y_sad_zero = best_sad;
2257
511
  }
2258
2259
61.7k
  if (!screen_scroll_superblock) {
2260
61.7k
    const uint8_t *const pos[4] = {
2261
61.7k
      ref_buf - ref_stride,
2262
61.7k
      ref_buf - 1,
2263
61.7k
      ref_buf + 1,
2264
61.7k
      ref_buf + ref_stride,
2265
61.7k
    };
2266
2267
61.7k
    cpi->ppi->fn_ptr[bsize].sdx4df(src_buf, src_stride, pos, ref_stride,
2268
61.7k
                                   this_sad);
2269
2270
308k
    for (idx = 0; idx < 4; ++idx) {
2271
246k
      if (this_sad[idx] < best_sad) {
2272
56.3k
        best_sad = this_sad[idx];
2273
56.3k
        best_int_mv->as_fullmv.row = search_pos[idx].row + this_mv.row;
2274
56.3k
        best_int_mv->as_fullmv.col = search_pos[idx].col + this_mv.col;
2275
56.3k
      }
2276
246k
    }
2277
2278
61.7k
    if (this_sad[0] < this_sad[3])
2279
31.0k
      this_mv.row -= 1;
2280
30.7k
    else
2281
30.7k
      this_mv.row += 1;
2282
2283
61.7k
    if (this_sad[1] < this_sad[2])
2284
30.8k
      this_mv.col -= 1;
2285
30.9k
    else
2286
30.9k
      this_mv.col += 1;
2287
2288
61.7k
    ref_buf = get_buf_from_fullmv(&xd->plane[0].pre[0], &this_mv);
2289
2290
61.7k
    tmp_sad =
2291
61.7k
        cpi->ppi->fn_ptr[bsize].sdf(src_buf, src_stride, ref_buf, ref_stride);
2292
61.7k
    if (best_sad > tmp_sad) {
2293
7.74k
      best_int_mv->as_fullmv = this_mv;
2294
7.74k
      best_sad = tmp_sad;
2295
7.74k
    }
2296
61.7k
  }
2297
2298
61.7k
  FullMvLimits mv_limits = x->mv_limits;
2299
61.7k
  av1_set_mv_search_range(&mv_limits, ref_mv);
2300
61.7k
  clamp_fullmv(&best_int_mv->as_fullmv, &mv_limits);
2301
2302
61.7k
  convert_fullmv_to_mv(best_int_mv);
2303
2304
61.7k
  if (scaled_ref_frame) {
2305
0
    int i;
2306
0
    for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2307
0
  }
2308
2309
61.7k
  aom_free(hbuf);
2310
61.7k
  aom_free(vbuf);
2311
61.7k
  aom_free(src_hbuf);
2312
61.7k
  aom_free(src_vbuf);
2313
61.7k
  return best_sad;
2314
63.3k
}
2315
2316
// =============================================================================
2317
//  Fullpixel Motion Search: OBMC
2318
// =============================================================================
2319
static inline int get_obmc_mvpred_var(
2320
0
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV *this_mv) {
2321
0
  const aom_variance_fn_ptr_t *vfp = ms_params->vfp;
2322
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2323
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2324
0
  const int32_t *wsrc = ms_buffers->wsrc;
2325
0
  const int32_t *mask = ms_buffers->obmc_mask;
2326
0
  const struct buf_2d *ref_buf = ms_buffers->ref;
2327
2328
0
  const MV mv = get_mv_from_fullmv(this_mv);
2329
0
  unsigned int unused;
2330
2331
0
  return vfp->ovf(get_buf_from_fullmv(ref_buf, this_mv), ref_buf->stride, wsrc,
2332
0
                  mask, &unused) +
2333
0
         mv_err_cost_(&mv, mv_cost_params);
2334
0
}
2335
2336
static int obmc_refining_search_sad(
2337
0
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV *best_mv) {
2338
0
  const aom_variance_fn_ptr_t *fn_ptr = ms_params->vfp;
2339
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2340
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2341
0
  const int32_t *wsrc = ms_buffers->wsrc;
2342
0
  const int32_t *mask = ms_buffers->obmc_mask;
2343
0
  const struct buf_2d *ref_buf = ms_buffers->ref;
2344
0
  const FULLPEL_MV neighbors[4] = { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };
2345
0
  const int kSearchRange = 8;
2346
2347
0
  unsigned int best_sad = fn_ptr->osdf(get_buf_from_fullmv(ref_buf, best_mv),
2348
0
                                       ref_buf->stride, wsrc, mask) +
2349
0
                          mvsad_err_cost_(best_mv, mv_cost_params);
2350
2351
0
  for (int i = 0; i < kSearchRange; i++) {
2352
0
    int best_site = -1;
2353
2354
0
    for (int j = 0; j < 4; j++) {
2355
0
      const FULLPEL_MV mv = { best_mv->row + neighbors[j].row,
2356
0
                              best_mv->col + neighbors[j].col };
2357
0
      if (av1_is_fullmv_in_range(&ms_params->mv_limits, mv)) {
2358
0
        unsigned int sad = fn_ptr->osdf(get_buf_from_fullmv(ref_buf, &mv),
2359
0
                                        ref_buf->stride, wsrc, mask);
2360
0
        if (sad < best_sad) {
2361
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
2362
2363
0
          if (sad < best_sad) {
2364
0
            best_sad = sad;
2365
0
            best_site = j;
2366
0
          }
2367
0
        }
2368
0
      }
2369
0
    }
2370
2371
0
    if (best_site == -1) {
2372
0
      break;
2373
0
    } else {
2374
0
      best_mv->row += neighbors[best_site].row;
2375
0
      best_mv->col += neighbors[best_site].col;
2376
0
    }
2377
0
  }
2378
0
  return best_sad;
2379
0
}
2380
2381
static int obmc_diamond_search_sad(
2382
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV start_mv,
2383
0
    FULLPEL_MV *best_mv, int search_step, int *num00) {
2384
0
  const aom_variance_fn_ptr_t *fn_ptr = ms_params->vfp;
2385
0
  const search_site_config *cfg = ms_params->search_sites;
2386
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2387
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2388
0
  const int32_t *wsrc = ms_buffers->wsrc;
2389
0
  const int32_t *mask = ms_buffers->obmc_mask;
2390
0
  const struct buf_2d *const ref_buf = ms_buffers->ref;
2391
2392
  // search_step determines the length of the initial step and hence the number
2393
  // of iterations.
2394
0
  const int tot_steps = cfg->num_search_steps - search_step;
2395
0
  const uint8_t *best_address, *init_ref;
2396
0
  int best_sad = INT_MAX;
2397
0
  int best_site = 0;
2398
2399
0
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
2400
0
  best_address = init_ref = get_buf_from_fullmv(ref_buf, &start_mv);
2401
0
  *num00 = 0;
2402
0
  *best_mv = start_mv;
2403
2404
  // Check the starting position
2405
0
  best_sad = fn_ptr->osdf(best_address, ref_buf->stride, wsrc, mask) +
2406
0
             mvsad_err_cost_(best_mv, mv_cost_params);
2407
2408
0
  for (int step = tot_steps - 1; step >= 0; --step) {
2409
0
    const search_site *const site = cfg->site[step];
2410
0
    best_site = 0;
2411
0
    for (int idx = 1; idx <= cfg->searches_per_step[step]; ++idx) {
2412
0
      const FULLPEL_MV mv = { best_mv->row + site[idx].mv.row,
2413
0
                              best_mv->col + site[idx].mv.col };
2414
0
      if (av1_is_fullmv_in_range(&ms_params->mv_limits, mv)) {
2415
0
        int sad = fn_ptr->osdf(best_address + site[idx].offset, ref_buf->stride,
2416
0
                               wsrc, mask);
2417
0
        if (sad < best_sad) {
2418
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
2419
2420
0
          if (sad < best_sad) {
2421
0
            best_sad = sad;
2422
0
            best_site = idx;
2423
0
          }
2424
0
        }
2425
0
      }
2426
0
    }
2427
2428
0
    if (best_site != 0) {
2429
0
      best_mv->row += site[best_site].mv.row;
2430
0
      best_mv->col += site[best_site].mv.col;
2431
0
      best_address += site[best_site].offset;
2432
0
    } else if (best_address == init_ref) {
2433
0
      (*num00)++;
2434
0
    }
2435
0
  }
2436
0
  return best_sad;
2437
0
}
2438
2439
static int obmc_full_pixel_diamond(
2440
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV start_mv,
2441
0
    int step_param, FULLPEL_MV *best_mv) {
2442
0
  const search_site_config *cfg = ms_params->search_sites;
2443
0
  FULLPEL_MV tmp_mv;
2444
0
  int thissme, n, num00 = 0;
2445
0
  int bestsme =
2446
0
      obmc_diamond_search_sad(ms_params, start_mv, &tmp_mv, step_param, &n);
2447
0
  if (bestsme < INT_MAX) bestsme = get_obmc_mvpred_var(ms_params, &tmp_mv);
2448
0
  *best_mv = tmp_mv;
2449
2450
  // If there won't be more n-step search, check to see if refining search is
2451
  // needed.
2452
0
  const int further_steps = cfg->num_search_steps - 1 - step_param;
2453
2454
0
  while (n < further_steps) {
2455
0
    ++n;
2456
2457
0
    if (num00) {
2458
0
      num00--;
2459
0
    } else {
2460
0
      thissme = obmc_diamond_search_sad(ms_params, start_mv, &tmp_mv,
2461
0
                                        step_param + n, &num00);
2462
0
      if (thissme < INT_MAX) thissme = get_obmc_mvpred_var(ms_params, &tmp_mv);
2463
2464
0
      if (thissme < bestsme) {
2465
0
        bestsme = thissme;
2466
0
        *best_mv = tmp_mv;
2467
0
      }
2468
0
    }
2469
0
  }
2470
2471
0
  return bestsme;
2472
0
}
2473
2474
int av1_obmc_full_pixel_search(const FULLPEL_MV start_mv,
2475
                               const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
2476
0
                               const int step_param, FULLPEL_MV *best_mv) {
2477
0
  if (!ms_params->fast_obmc_search) {
2478
0
    const int bestsme =
2479
0
        obmc_full_pixel_diamond(ms_params, start_mv, step_param, best_mv);
2480
0
    return bestsme;
2481
0
  } else {
2482
0
    *best_mv = start_mv;
2483
0
    clamp_fullmv(best_mv, &ms_params->mv_limits);
2484
0
    int thissme = obmc_refining_search_sad(ms_params, best_mv);
2485
0
    if (thissme < INT_MAX) thissme = get_obmc_mvpred_var(ms_params, best_mv);
2486
0
    return thissme;
2487
0
  }
2488
0
}
2489
2490
// =============================================================================
2491
//  Subpixel Motion Search: Translational
2492
// =============================================================================
2493
3.71M
#define INIT_SUBPEL_STEP_SIZE (4)
2494
/*
2495
 * To avoid the penalty for crossing cache-line read, preload the reference
2496
 * area in a small buffer, which is aligned to make sure there won't be crossing
2497
 * cache-line read while reading from this buffer. This reduced the cpu
2498
 * cycles spent on reading ref data in sub-pixel filter functions.
2499
 * TODO: Currently, since sub-pixel search range here is -3 ~ 3, copy 22 rows x
2500
 * 32 cols area that is enough for 16x16 macroblock. Later, for SPLITMV, we
2501
 * could reduce the area.
2502
 */
2503
2504
// Returns the subpel offset used by various subpel variance functions [m]sv[a]f
2505
90.7M
static inline int get_subpel_part(int x) { return x & 7; }
2506
2507
// Gets the address of the ref buffer at subpel location (r, c), rounded to the
2508
// nearest fullpel precision toward - \infty
2509
static inline const uint8_t *get_buf_from_mv(const struct buf_2d *buf,
2510
46.8M
                                             const MV mv) {
2511
46.8M
  const int offset = (mv.row >> 3) * buf->stride + (mv.col >> 3);
2512
46.8M
  return &buf->buf[offset];
2513
46.8M
}
2514
2515
// Estimates the variance of prediction residue using bilinear filter for fast
2516
// search.
2517
static inline int estimated_pref_error(
2518
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2519
45.3M
    unsigned int *sse) {
2520
45.3M
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2521
2522
45.3M
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2523
45.3M
  const uint8_t *src = ms_buffers->src->buf;
2524
45.3M
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
2525
45.3M
  const int src_stride = ms_buffers->src->stride;
2526
45.3M
  const int ref_stride = ms_buffers->ref->stride;
2527
45.3M
  const uint8_t *second_pred = ms_buffers->second_pred;
2528
45.3M
  const uint8_t *mask = ms_buffers->mask;
2529
45.3M
  const int mask_stride = ms_buffers->mask_stride;
2530
45.3M
  const int invert_mask = ms_buffers->inv_mask;
2531
2532
45.3M
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
2533
45.3M
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
2534
2535
45.3M
  if (second_pred == NULL) {
2536
45.3M
    return vfp->svf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2537
45.3M
                    sse);
2538
45.3M
  } else if (mask) {
2539
0
    return vfp->msvf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2540
0
                     second_pred, mask, mask_stride, invert_mask, sse);
2541
5.35k
  } else {
2542
5.35k
    return vfp->svaf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2543
5.35k
                     sse, second_pred);
2544
5.35k
  }
2545
45.3M
}
2546
2547
// Calculates the variance of prediction residue.
2548
static int upsampled_pref_error(MACROBLOCKD *xd, const AV1_COMMON *cm,
2549
                                const MV *this_mv,
2550
                                const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2551
0
                                unsigned int *sse) {
2552
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2553
0
  const SUBPEL_SEARCH_TYPE subpel_search_type = var_params->subpel_search_type;
2554
2555
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2556
0
  const uint8_t *src = ms_buffers->src->buf;
2557
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
2558
0
  const int src_stride = ms_buffers->src->stride;
2559
0
  const int ref_stride = ms_buffers->ref->stride;
2560
0
  const uint8_t *second_pred = ms_buffers->second_pred;
2561
0
  const uint8_t *mask = ms_buffers->mask;
2562
0
  const int mask_stride = ms_buffers->mask_stride;
2563
0
  const int invert_mask = ms_buffers->inv_mask;
2564
0
  const int w = var_params->w;
2565
0
  const int h = var_params->h;
2566
2567
0
  const int mi_row = xd->mi_row;
2568
0
  const int mi_col = xd->mi_col;
2569
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
2570
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
2571
2572
0
  unsigned int besterr;
2573
0
#if CONFIG_AV1_HIGHBITDEPTH
2574
0
  if (is_cur_buf_hbd(xd)) {
2575
0
    DECLARE_ALIGNED(16, uint16_t, pred16[MAX_SB_SQUARE]);
2576
0
    uint8_t *pred8 = CONVERT_TO_BYTEPTR(pred16);
2577
0
    if (second_pred != NULL) {
2578
0
      if (mask) {
2579
0
        aom_highbd_comp_mask_upsampled_pred(
2580
0
            xd, cm, mi_row, mi_col, this_mv, pred8, second_pred, w, h,
2581
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, mask, mask_stride,
2582
0
            invert_mask, xd->bd, subpel_search_type);
2583
0
      } else {
2584
0
        aom_highbd_comp_avg_upsampled_pred(
2585
0
            xd, cm, mi_row, mi_col, this_mv, pred8, second_pred, w, h,
2586
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, xd->bd,
2587
0
            subpel_search_type);
2588
0
      }
2589
0
    } else {
2590
0
      aom_highbd_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred8, w, h,
2591
0
                                subpel_x_q3, subpel_y_q3, ref, ref_stride,
2592
0
                                xd->bd, subpel_search_type);
2593
0
    }
2594
0
    besterr = vfp->vf(pred8, w, src, src_stride, sse);
2595
0
  } else {
2596
0
    DECLARE_ALIGNED(16, uint8_t, pred[MAX_SB_SQUARE]);
2597
0
    if (second_pred != NULL) {
2598
0
      if (mask) {
2599
0
        aom_comp_mask_upsampled_pred(
2600
0
            xd, cm, mi_row, mi_col, this_mv, pred, second_pred, w, h,
2601
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, mask, mask_stride,
2602
0
            invert_mask, subpel_search_type);
2603
0
      } else {
2604
0
        aom_comp_avg_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2605
0
                                    second_pred, w, h, subpel_x_q3, subpel_y_q3,
2606
0
                                    ref, ref_stride, subpel_search_type);
2607
0
      }
2608
0
    } else {
2609
0
      aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h,
2610
0
                         subpel_x_q3, subpel_y_q3, ref, ref_stride,
2611
0
                         subpel_search_type);
2612
0
    }
2613
2614
0
    besterr = vfp->vf(pred, w, src, src_stride, sse);
2615
0
  }
2616
#else
2617
  DECLARE_ALIGNED(16, uint8_t, pred[MAX_SB_SQUARE]);
2618
  if (second_pred != NULL) {
2619
    if (mask) {
2620
      aom_comp_mask_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2621
                                   second_pred, w, h, subpel_x_q3, subpel_y_q3,
2622
                                   ref, ref_stride, mask, mask_stride,
2623
                                   invert_mask, subpel_search_type);
2624
    } else {
2625
      aom_comp_avg_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2626
                                  second_pred, w, h, subpel_x_q3, subpel_y_q3,
2627
                                  ref, ref_stride, subpel_search_type);
2628
    }
2629
  } else {
2630
    aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
2631
                       subpel_y_q3, ref, ref_stride, subpel_search_type);
2632
  }
2633
2634
  besterr = vfp->vf(pred, w, src, src_stride, sse);
2635
#endif
2636
0
  return besterr;
2637
0
}
2638
2639
// Estimates whether this_mv is better than best_mv. This function incorporates
2640
// both prediction error and residue into account. It is suffixed "fast" because
2641
// it uses bilinear filter to estimate the prediction.
2642
static inline unsigned int check_better_fast(
2643
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
2644
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2645
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2646
45.4M
    unsigned int *sse1, int *distortion, int *has_better_mv, int is_scaled) {
2647
45.4M
  unsigned int cost;
2648
45.4M
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
2649
45.3M
    unsigned int sse;
2650
45.3M
    int thismse;
2651
45.3M
    if (is_scaled) {
2652
0
      thismse = upsampled_pref_error(xd, cm, this_mv, var_params, &sse);
2653
45.3M
    } else {
2654
45.3M
      thismse = estimated_pref_error(this_mv, var_params, &sse);
2655
45.3M
    }
2656
45.3M
    cost = mv_err_cost_(this_mv, mv_cost_params);
2657
45.3M
    cost += thismse;
2658
2659
45.3M
    if (cost < *besterr) {
2660
12.7M
      *besterr = cost;
2661
12.7M
      *best_mv = *this_mv;
2662
12.7M
      *distortion = thismse;
2663
12.7M
      *sse1 = sse;
2664
12.7M
      *has_better_mv |= 1;
2665
12.7M
    }
2666
45.3M
  } else {
2667
49.8k
    cost = INT_MAX;
2668
49.8k
  }
2669
45.4M
  return cost;
2670
45.4M
}
2671
2672
// Checks whether this_mv is better than best_mv. This function incorporates
2673
// both prediction error and residue into account.
2674
static AOM_FORCE_INLINE unsigned int check_better(
2675
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
2676
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2677
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2678
0
    unsigned int *sse1, int *distortion, int *is_better) {
2679
0
  unsigned int cost;
2680
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
2681
0
    unsigned int sse;
2682
0
    int thismse;
2683
0
    thismse = upsampled_pref_error(xd, cm, this_mv, var_params, &sse);
2684
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
2685
0
    cost += thismse;
2686
0
    if (cost < *besterr) {
2687
0
      *besterr = cost;
2688
0
      *best_mv = *this_mv;
2689
0
      *distortion = thismse;
2690
0
      *sse1 = sse;
2691
0
      *is_better |= 1;
2692
0
    }
2693
0
  } else {
2694
0
    cost = INT_MAX;
2695
0
  }
2696
0
  return cost;
2697
0
}
2698
2699
static inline MV get_best_diag_step(int step_size, unsigned int left_cost,
2700
                                    unsigned int right_cost,
2701
                                    unsigned int up_cost,
2702
8.82M
                                    unsigned int down_cost) {
2703
8.82M
  const MV diag_step = { up_cost <= down_cost ? -step_size : step_size,
2704
8.82M
                         left_cost <= right_cost ? -step_size : step_size };
2705
2706
8.82M
  return diag_step;
2707
8.82M
}
2708
2709
// Searches the four cardinal direction for a better mv, then follows up with a
2710
// search in the best quadrant. This uses bilinear filter to speed up the
2711
// calculation.
2712
static AOM_FORCE_INLINE MV first_level_check_fast(
2713
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, MV *best_mv,
2714
    int hstep, const SubpelMvLimits *mv_limits,
2715
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2716
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2717
8.82M
    unsigned int *sse1, int *distortion, int is_scaled) {
2718
  // Check the four cardinal directions
2719
8.82M
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
2720
8.82M
  int dummy = 0;
2721
8.82M
  const unsigned int left = check_better_fast(
2722
8.82M
      xd, cm, &left_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
2723
8.82M
      sse1, distortion, &dummy, is_scaled);
2724
2725
8.82M
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
2726
8.82M
  const unsigned int right = check_better_fast(
2727
8.82M
      xd, cm, &right_mv, best_mv, mv_limits, var_params, mv_cost_params,
2728
8.82M
      besterr, sse1, distortion, &dummy, is_scaled);
2729
2730
8.82M
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
2731
8.82M
  const unsigned int up = check_better_fast(
2732
8.82M
      xd, cm, &top_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
2733
8.82M
      sse1, distortion, &dummy, is_scaled);
2734
2735
8.82M
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
2736
8.82M
  const unsigned int down = check_better_fast(
2737
8.82M
      xd, cm, &bottom_mv, best_mv, mv_limits, var_params, mv_cost_params,
2738
8.82M
      besterr, sse1, distortion, &dummy, is_scaled);
2739
2740
8.82M
  const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
2741
8.82M
  const MV diag_mv = { this_mv.row + diag_step.row,
2742
8.82M
                       this_mv.col + diag_step.col };
2743
2744
  // Check the diagonal direction with the best mv
2745
8.82M
  check_better_fast(xd, cm, &diag_mv, best_mv, mv_limits, var_params,
2746
8.82M
                    mv_cost_params, besterr, sse1, distortion, &dummy,
2747
8.82M
                    is_scaled);
2748
2749
8.82M
  return diag_step;
2750
8.82M
}
2751
2752
// Performs a following up search after first_level_check_fast is called. This
2753
// performs two extra chess pattern searches in the best quadrant.
2754
static AOM_FORCE_INLINE void second_level_check_fast(
2755
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, const MV diag_step,
2756
    MV *best_mv, int hstep, const SubpelMvLimits *mv_limits,
2757
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2758
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2759
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2760
0
  assert(diag_step.row == hstep || diag_step.row == -hstep);
2761
0
  assert(diag_step.col == hstep || diag_step.col == -hstep);
2762
0
  const int tr = this_mv.row;
2763
0
  const int tc = this_mv.col;
2764
0
  const int br = best_mv->row;
2765
0
  const int bc = best_mv->col;
2766
0
  int dummy = 0;
2767
0
  if (tr != br && tc != bc) {
2768
0
    assert(diag_step.col == bc - tc);
2769
0
    assert(diag_step.row == br - tr);
2770
0
    const MV chess_mv_1 = { br, bc + diag_step.col };
2771
0
    const MV chess_mv_2 = { br + diag_step.row, bc };
2772
0
    check_better_fast(xd, cm, &chess_mv_1, best_mv, mv_limits, var_params,
2773
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2774
0
                      is_scaled);
2775
2776
0
    check_better_fast(xd, cm, &chess_mv_2, best_mv, mv_limits, var_params,
2777
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2778
0
                      is_scaled);
2779
0
  } else if (tr == br && tc != bc) {
2780
0
    assert(diag_step.col == bc - tc);
2781
    // Continue searching in the best direction
2782
0
    const MV bottom_long_mv = { br + hstep, bc + diag_step.col };
2783
0
    const MV top_long_mv = { br - hstep, bc + diag_step.col };
2784
0
    check_better_fast(xd, cm, &bottom_long_mv, best_mv, mv_limits, var_params,
2785
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2786
0
                      is_scaled);
2787
0
    check_better_fast(xd, cm, &top_long_mv, best_mv, mv_limits, var_params,
2788
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2789
0
                      is_scaled);
2790
2791
    // Search in the direction opposite of the best quadrant
2792
0
    const MV rev_mv = { br - diag_step.row, bc };
2793
0
    check_better_fast(xd, cm, &rev_mv, best_mv, mv_limits, var_params,
2794
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2795
0
                      is_scaled);
2796
0
  } else if (tr != br && tc == bc) {
2797
0
    assert(diag_step.row == br - tr);
2798
    // Continue searching in the best direction
2799
0
    const MV right_long_mv = { br + diag_step.row, bc + hstep };
2800
0
    const MV left_long_mv = { br + diag_step.row, bc - hstep };
2801
0
    check_better_fast(xd, cm, &right_long_mv, best_mv, mv_limits, var_params,
2802
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2803
0
                      is_scaled);
2804
0
    check_better_fast(xd, cm, &left_long_mv, best_mv, mv_limits, var_params,
2805
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2806
0
                      is_scaled);
2807
2808
    // Search in the direction opposite of the best quadrant
2809
0
    const MV rev_mv = { br, bc - diag_step.col };
2810
0
    check_better_fast(xd, cm, &rev_mv, best_mv, mv_limits, var_params,
2811
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2812
0
                      is_scaled);
2813
0
  }
2814
0
}
2815
2816
// Combines first level check and second level check when applicable. This first
2817
// searches the four cardinal directions, and perform several
2818
// diagonal/chess-pattern searches in the best quadrant.
2819
static AOM_FORCE_INLINE void two_level_checks_fast(
2820
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, MV *best_mv,
2821
    int hstep, const SubpelMvLimits *mv_limits,
2822
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2823
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2824
8.82M
    unsigned int *sse1, int *distortion, int iters, int is_scaled) {
2825
8.82M
  const MV diag_step = first_level_check_fast(
2826
8.82M
      xd, cm, this_mv, best_mv, hstep, mv_limits, var_params, mv_cost_params,
2827
8.82M
      besterr, sse1, distortion, is_scaled);
2828
8.82M
  if (iters > 1) {
2829
0
    second_level_check_fast(xd, cm, this_mv, diag_step, best_mv, hstep,
2830
0
                            mv_limits, var_params, mv_cost_params, besterr,
2831
0
                            sse1, distortion, is_scaled);
2832
0
  }
2833
8.82M
}
2834
2835
static AOM_FORCE_INLINE MV
2836
first_level_check(MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv,
2837
                  MV *best_mv, const int hstep, const SubpelMvLimits *mv_limits,
2838
                  const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2839
                  const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2840
0
                  unsigned int *sse1, int *distortion) {
2841
0
  int dummy = 0;
2842
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
2843
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
2844
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
2845
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
2846
2847
0
  const unsigned int left =
2848
0
      check_better(xd, cm, &left_mv, best_mv, mv_limits, var_params,
2849
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2850
0
  const unsigned int right =
2851
0
      check_better(xd, cm, &right_mv, best_mv, mv_limits, var_params,
2852
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2853
0
  const unsigned int up =
2854
0
      check_better(xd, cm, &top_mv, best_mv, mv_limits, var_params,
2855
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2856
0
  const unsigned int down =
2857
0
      check_better(xd, cm, &bottom_mv, best_mv, mv_limits, var_params,
2858
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2859
2860
0
  const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
2861
0
  const MV diag_mv = { this_mv.row + diag_step.row,
2862
0
                       this_mv.col + diag_step.col };
2863
2864
  // Check the diagonal direction with the best mv
2865
0
  check_better(xd, cm, &diag_mv, best_mv, mv_limits, var_params, mv_cost_params,
2866
0
               besterr, sse1, distortion, &dummy);
2867
2868
0
  return diag_step;
2869
0
}
2870
2871
// A newer version of second level check that gives better quality.
2872
// TODO(chiyotsai@google.com): evaluate this on subpel_search_types different
2873
// from av1_find_best_sub_pixel_tree
2874
static AOM_FORCE_INLINE void second_level_check_v2(
2875
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV diag_step,
2876
    MV *best_mv, const SubpelMvLimits *mv_limits,
2877
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2878
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2879
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2880
0
  assert(best_mv->row == this_mv.row + diag_step.row ||
2881
0
         best_mv->col == this_mv.col + diag_step.col);
2882
0
  if (CHECK_MV_EQUAL(this_mv, *best_mv)) {
2883
0
    return;
2884
0
  } else if (this_mv.row == best_mv->row) {
2885
    // Search away from diagonal step since diagonal search did not provide any
2886
    // improvement
2887
0
    diag_step.row *= -1;
2888
0
  } else if (this_mv.col == best_mv->col) {
2889
0
    diag_step.col *= -1;
2890
0
  }
2891
2892
0
  const MV row_bias_mv = { best_mv->row + diag_step.row, best_mv->col };
2893
0
  const MV col_bias_mv = { best_mv->row, best_mv->col + diag_step.col };
2894
0
  const MV diag_bias_mv = { best_mv->row + diag_step.row,
2895
0
                            best_mv->col + diag_step.col };
2896
0
  int has_better_mv = 0;
2897
2898
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
2899
0
    check_better(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
2900
0
                 mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2901
0
    check_better(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
2902
0
                 mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2903
2904
    // Do an additional search if the second iteration gives a better mv
2905
0
    if (has_better_mv) {
2906
0
      check_better(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
2907
0
                   mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2908
0
    }
2909
0
  } else {
2910
0
    check_better_fast(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
2911
0
                      mv_cost_params, besterr, sse1, distortion, &has_better_mv,
2912
0
                      is_scaled);
2913
0
    check_better_fast(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
2914
0
                      mv_cost_params, besterr, sse1, distortion, &has_better_mv,
2915
0
                      is_scaled);
2916
2917
    // Do an additional search if the second iteration gives a better mv
2918
0
    if (has_better_mv) {
2919
0
      check_better_fast(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
2920
0
                        mv_cost_params, besterr, sse1, distortion,
2921
0
                        &has_better_mv, is_scaled);
2922
0
    }
2923
0
  }
2924
0
}
2925
2926
// Gets the error at the beginning when the mv has fullpel precision
2927
static unsigned int setup_center_error(
2928
    const MACROBLOCKD *xd, const MV *bestmv,
2929
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2930
1.45M
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
2931
1.45M
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2932
1.45M
  const int w = var_params->w;
2933
1.45M
  const int h = var_params->h;
2934
2935
1.45M
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2936
1.45M
  const uint8_t *src = ms_buffers->src->buf;
2937
1.45M
  const uint8_t *y = get_buf_from_mv(ms_buffers->ref, *bestmv);
2938
1.45M
  const int src_stride = ms_buffers->src->stride;
2939
1.45M
  const int y_stride = ms_buffers->ref->stride;
2940
1.45M
  const uint8_t *second_pred = ms_buffers->second_pred;
2941
1.45M
  const uint8_t *mask = ms_buffers->mask;
2942
1.45M
  const int mask_stride = ms_buffers->mask_stride;
2943
1.45M
  const int invert_mask = ms_buffers->inv_mask;
2944
2945
1.45M
  unsigned int besterr;
2946
2947
1.45M
  if (second_pred != NULL) {
2948
0
#if CONFIG_AV1_HIGHBITDEPTH
2949
0
    if (is_cur_buf_hbd(xd)) {
2950
0
      DECLARE_ALIGNED(16, uint16_t, comp_pred16[MAX_SB_SQUARE]);
2951
0
      uint8_t *comp_pred = CONVERT_TO_BYTEPTR(comp_pred16);
2952
0
      if (mask) {
2953
0
        aom_highbd_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride,
2954
0
                                  mask, mask_stride, invert_mask);
2955
0
      } else {
2956
0
        aom_highbd_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2957
0
      }
2958
0
      besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2959
0
    } else {
2960
0
      DECLARE_ALIGNED(16, uint8_t, comp_pred[MAX_SB_SQUARE]);
2961
0
      if (mask) {
2962
0
        aom_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride, mask,
2963
0
                           mask_stride, invert_mask);
2964
0
      } else {
2965
0
        aom_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2966
0
      }
2967
0
      besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2968
0
    }
2969
#else
2970
    (void)xd;
2971
    DECLARE_ALIGNED(16, uint8_t, comp_pred[MAX_SB_SQUARE]);
2972
    if (mask) {
2973
      aom_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride, mask,
2974
                         mask_stride, invert_mask);
2975
    } else {
2976
      aom_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2977
    }
2978
    besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2979
#endif
2980
1.45M
  } else {
2981
1.45M
    besterr = vfp->vf(y, y_stride, src, src_stride, sse1);
2982
1.45M
  }
2983
1.45M
  *distortion = besterr;
2984
1.45M
  besterr += mv_err_cost_(bestmv, mv_cost_params);
2985
1.45M
  return besterr;
2986
1.45M
}
2987
2988
// Gets the error at the beginning when the mv has fullpel precision
2989
static unsigned int upsampled_setup_center_error(
2990
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV *bestmv,
2991
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2992
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
2993
0
  unsigned int besterr = upsampled_pref_error(xd, cm, bestmv, var_params, sse1);
2994
0
  *distortion = besterr;
2995
0
  besterr += mv_err_cost_(bestmv, mv_cost_params);
2996
0
  return besterr;
2997
0
}
2998
2999
2.47k
static inline int divide_and_round(int n, int d) {
3000
2.47k
  return ((n < 0) ^ (d < 0)) ? ((n - d / 2) / d) : ((n + d / 2) / d);
3001
2.47k
}
3002
3003
1.26k
static inline int is_cost_list_wellbehaved(const int *cost_list) {
3004
1.26k
  return cost_list[0] < cost_list[1] && cost_list[0] < cost_list[2] &&
3005
1.25k
         cost_list[0] < cost_list[3] && cost_list[0] < cost_list[4];
3006
1.26k
}
3007
3008
// Returns surface minima estimate at given precision in 1/2^n bits.
3009
// Assume a model for the cost surface: S = A(x - x0)^2 + B(y - y0)^2 + C
3010
// For a given set of costs S0, S1, S2, S3, S4 at points
3011
// (y, x) = (0, 0), (0, -1), (1, 0), (0, 1) and (-1, 0) respectively,
3012
// the solution for the location of the minima (x0, y0) is given by:
3013
// x0 = 1/2 (S1 - S3)/(S1 + S3 - 2*S0),
3014
// y0 = 1/2 (S4 - S2)/(S4 + S2 - 2*S0).
3015
// The code below is an integerized version of that.
3016
static inline void get_cost_surf_min(const int *cost_list, int *ir, int *ic,
3017
1.23k
                                     int bits) {
3018
1.23k
  *ic = divide_and_round((cost_list[1] - cost_list[3]) * (1 << (bits - 1)),
3019
1.23k
                         (cost_list[1] - 2 * cost_list[0] + cost_list[3]));
3020
1.23k
  *ir = divide_and_round((cost_list[4] - cost_list[2]) * (1 << (bits - 1)),
3021
1.23k
                         (cost_list[4] - 2 * cost_list[0] + cost_list[2]));
3022
1.23k
}
3023
3024
// Checks the list of mvs searched in the last iteration and see if we are
3025
// repeating it. If so, return 1. Otherwise we update the last_mv_search_list
3026
// with current_mv and return 0.
3027
static inline int check_repeated_mv_and_update(int_mv *last_mv_search_list,
3028
9.32M
                                               const MV current_mv, int iter) {
3029
9.32M
  if (last_mv_search_list) {
3030
7.70M
    if (CHECK_MV_EQUAL(last_mv_search_list[iter].as_mv, current_mv)) {
3031
35.9k
      return 1;
3032
35.9k
    }
3033
3034
7.67M
    last_mv_search_list[iter].as_mv = current_mv;
3035
7.67M
  }
3036
9.28M
  return 0;
3037
9.32M
}
3038
3039
static inline int setup_center_error_facade(
3040
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *bestmv,
3041
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3042
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion,
3043
1.45M
    int is_scaled) {
3044
1.45M
  if (is_scaled) {
3045
0
    return upsampled_setup_center_error(xd, cm, bestmv, var_params,
3046
0
                                        mv_cost_params, sse1, distortion);
3047
1.45M
  } else {
3048
1.45M
    return setup_center_error(xd, bestmv, var_params, mv_cost_params, sse1,
3049
1.45M
                              distortion);
3050
1.45M
  }
3051
1.45M
}
3052
3053
int av1_find_best_sub_pixel_tree_pruned_more(
3054
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3055
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3056
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3057
3.20M
    unsigned int *sse1, int_mv *last_mv_search_list) {
3058
3.20M
  (void)cm;
3059
3.20M
  const int allow_hp = ms_params->allow_hp;
3060
3.20M
  const int forced_stop = ms_params->forced_stop;
3061
3.20M
  const int iters_per_step = ms_params->iters_per_step;
3062
3.20M
  const int *cost_list = ms_params->cost_list;
3063
3.20M
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3064
3.20M
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3065
3.20M
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3066
3067
  // The iteration we are current searching for. Iter 0 corresponds to fullpel
3068
  // mv, iter 1 to half pel, and so on
3069
3.20M
  int iter = 0;
3070
3.20M
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3071
3.20M
  unsigned int besterr = INT_MAX;
3072
3.20M
  *bestmv = start_mv;
3073
3074
3.20M
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3075
3.20M
                                             ? &cm->sf_identity
3076
3.20M
                                             : xd->block_ref_scale_factors[0];
3077
3.20M
  const int is_scaled = av1_is_scaled(sf);
3078
3079
3.20M
  if (start_mv_stats != NULL && !is_scaled) {
3080
1.79M
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3081
1.79M
    *distortion = start_mv_stats->distortion;
3082
1.79M
    *sse1 = start_mv_stats->sse;
3083
1.79M
  } else {
3084
1.40M
    besterr =
3085
1.40M
        setup_center_error_facade(xd, cm, bestmv, var_params, mv_cost_params,
3086
1.40M
                                  sse1, distortion, is_scaled);
3087
1.40M
  }
3088
3089
  // If forced_stop is FULL_PEL, return.
3090
3.20M
  if (forced_stop == FULL_PEL) return besterr;
3091
3092
3.20M
  if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3093
0
    return INT_MAX;
3094
0
  }
3095
3.20M
  iter++;
3096
3097
3.20M
  if (cost_list && cost_list[0] != INT_MAX && cost_list[1] != INT_MAX &&
3098
1.26k
      cost_list[2] != INT_MAX && cost_list[3] != INT_MAX &&
3099
1.26k
      cost_list[4] != INT_MAX && is_cost_list_wellbehaved(cost_list)) {
3100
1.23k
    int ir, ic;
3101
1.23k
    get_cost_surf_min(cost_list, &ir, &ic, 1);
3102
1.23k
    if (ir != 0 || ic != 0) {
3103
334
      const MV this_mv = { start_mv.row + ir * hstep,
3104
334
                           start_mv.col + ic * hstep };
3105
334
      int dummy = 0;
3106
334
      check_better_fast(xd, cm, &this_mv, bestmv, mv_limits, var_params,
3107
334
                        mv_cost_params, &besterr, sse1, distortion, &dummy,
3108
334
                        is_scaled);
3109
334
    }
3110
3.20M
  } else {
3111
3.20M
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3112
3.20M
                          var_params, mv_cost_params, &besterr, sse1,
3113
3.20M
                          distortion, iters_per_step, is_scaled);
3114
3.20M
  }
3115
3116
  // Each subsequent iteration checks at least one point in common with
3117
  // the last iteration could be 2 ( if diag selected) 1/4 pel
3118
3.20M
  if (forced_stop < HALF_PEL) {
3119
3.20M
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3120
31.5k
      return INT_MAX;
3121
31.5k
    }
3122
3.17M
    iter++;
3123
3124
3.17M
    hstep >>= 1;
3125
3.17M
    start_mv = *bestmv;
3126
3.17M
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3127
3.17M
                          var_params, mv_cost_params, &besterr, sse1,
3128
3.17M
                          distortion, iters_per_step, is_scaled);
3129
3.17M
  }
3130
3131
3.17M
  if (allow_hp && forced_stop == EIGHTH_PEL) {
3132
1.90M
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3133
4.33k
      return INT_MAX;
3134
4.33k
    }
3135
1.89M
    iter++;
3136
3137
1.89M
    hstep >>= 1;
3138
1.89M
    start_mv = *bestmv;
3139
1.89M
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3140
1.89M
                          var_params, mv_cost_params, &besterr, sse1,
3141
1.89M
                          distortion, iters_per_step, is_scaled);
3142
1.89M
  }
3143
3144
3.16M
  return besterr;
3145
3.17M
}
3146
3147
int av1_find_best_sub_pixel_tree_pruned(
3148
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3149
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3150
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3151
508k
    unsigned int *sse1, int_mv *last_mv_search_list) {
3152
508k
  (void)cm;
3153
508k
  (void)start_mv_stats;
3154
508k
  const int allow_hp = ms_params->allow_hp;
3155
508k
  const int forced_stop = ms_params->forced_stop;
3156
508k
  const int iters_per_step = ms_params->iters_per_step;
3157
508k
  const int *cost_list = ms_params->cost_list;
3158
508k
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3159
508k
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3160
508k
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3161
3162
  // The iteration we are current searching for. Iter 0 corresponds to fullpel
3163
  // mv, iter 1 to half pel, and so on
3164
508k
  int iter = 0;
3165
508k
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3166
508k
  unsigned int besterr = INT_MAX;
3167
508k
  *bestmv = start_mv;
3168
3169
508k
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3170
508k
                                             ? &cm->sf_identity
3171
508k
                                             : xd->block_ref_scale_factors[0];
3172
508k
  const int is_scaled = av1_is_scaled(sf);
3173
3174
508k
  if (start_mv_stats != NULL && !is_scaled) {
3175
464k
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3176
464k
    *distortion = start_mv_stats->distortion;
3177
464k
    *sse1 = start_mv_stats->sse;
3178
464k
  } else {
3179
43.6k
    besterr =
3180
43.6k
        setup_center_error_facade(xd, cm, bestmv, var_params, mv_cost_params,
3181
43.6k
                                  sse1, distortion, is_scaled);
3182
43.6k
  }
3183
3184
  // If forced_stop is FULL_PEL, return.
3185
508k
  if (forced_stop == FULL_PEL) return besterr;
3186
3187
508k
  if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3188
0
    return INT_MAX;
3189
0
  }
3190
508k
  iter++;
3191
3192
508k
  if (cost_list && cost_list[0] != INT_MAX && cost_list[1] != INT_MAX &&
3193
464k
      cost_list[2] != INT_MAX && cost_list[3] != INT_MAX &&
3194
464k
      cost_list[4] != INT_MAX) {
3195
464k
    const unsigned int whichdir = (cost_list[1] < cost_list[3] ? 0 : 1) +
3196
464k
                                  (cost_list[2] < cost_list[4] ? 0 : 2);
3197
3198
464k
    const MV left_mv = { start_mv.row, start_mv.col - hstep };
3199
464k
    const MV right_mv = { start_mv.row, start_mv.col + hstep };
3200
464k
    const MV bottom_mv = { start_mv.row + hstep, start_mv.col };
3201
464k
    const MV top_mv = { start_mv.row - hstep, start_mv.col };
3202
3203
464k
    const MV bottom_left_mv = { start_mv.row + hstep, start_mv.col - hstep };
3204
464k
    const MV bottom_right_mv = { start_mv.row + hstep, start_mv.col + hstep };
3205
464k
    const MV top_left_mv = { start_mv.row - hstep, start_mv.col - hstep };
3206
464k
    const MV top_right_mv = { start_mv.row - hstep, start_mv.col + hstep };
3207
3208
464k
    int dummy = 0;
3209
3210
464k
    switch (whichdir) {
3211
103k
      case 0:  // bottom left quadrant
3212
103k
        check_better_fast(xd, cm, &left_mv, bestmv, mv_limits, var_params,
3213
103k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3214
103k
                          is_scaled);
3215
103k
        check_better_fast(xd, cm, &bottom_mv, bestmv, mv_limits, var_params,
3216
103k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3217
103k
                          is_scaled);
3218
103k
        check_better_fast(xd, cm, &bottom_left_mv, bestmv, mv_limits,
3219
103k
                          var_params, mv_cost_params, &besterr, sse1,
3220
103k
                          distortion, &dummy, is_scaled);
3221
103k
        break;
3222
121k
      case 1:  // bottom right quadrant
3223
121k
        check_better_fast(xd, cm, &right_mv, bestmv, mv_limits, var_params,
3224
121k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3225
121k
                          is_scaled);
3226
121k
        check_better_fast(xd, cm, &bottom_mv, bestmv, mv_limits, var_params,
3227
121k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3228
121k
                          is_scaled);
3229
121k
        check_better_fast(xd, cm, &bottom_right_mv, bestmv, mv_limits,
3230
121k
                          var_params, mv_cost_params, &besterr, sse1,
3231
121k
                          distortion, &dummy, is_scaled);
3232
121k
        break;
3233
111k
      case 2:  // top left quadrant
3234
111k
        check_better_fast(xd, cm, &left_mv, bestmv, mv_limits, var_params,
3235
111k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3236
111k
                          is_scaled);
3237
111k
        check_better_fast(xd, cm, &top_mv, bestmv, mv_limits, var_params,
3238
111k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3239
111k
                          is_scaled);
3240
111k
        check_better_fast(xd, cm, &top_left_mv, bestmv, mv_limits, var_params,
3241
111k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3242
111k
                          is_scaled);
3243
111k
        break;
3244
130k
      case 3:  // top right quadrant
3245
130k
        check_better_fast(xd, cm, &right_mv, bestmv, mv_limits, var_params,
3246
130k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3247
130k
                          is_scaled);
3248
130k
        check_better_fast(xd, cm, &top_mv, bestmv, mv_limits, var_params,
3249
130k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3250
130k
                          is_scaled);
3251
130k
        check_better_fast(xd, cm, &top_right_mv, bestmv, mv_limits, var_params,
3252
130k
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3253
130k
                          is_scaled);
3254
130k
        break;
3255
464k
    }
3256
464k
  } else {
3257
43.3k
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3258
43.3k
                          var_params, mv_cost_params, &besterr, sse1,
3259
43.3k
                          distortion, iters_per_step, is_scaled);
3260
43.3k
  }
3261
3262
  // Each subsequent iteration checks at least one point in common with
3263
  // the last iteration could be 2 ( if diag selected) 1/4 pel
3264
510k
  if (forced_stop < HALF_PEL) {
3265
510k
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3266
0
      return INT_MAX;
3267
0
    }
3268
510k
    iter++;
3269
3270
510k
    hstep >>= 1;
3271
510k
    start_mv = *bestmv;
3272
510k
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3273
510k
                          var_params, mv_cost_params, &besterr, sse1,
3274
510k
                          distortion, iters_per_step, is_scaled);
3275
510k
  }
3276
3277
509k
  if (allow_hp && forced_stop == EIGHTH_PEL) {
3278
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3279
0
      return INT_MAX;
3280
0
    }
3281
0
    iter++;
3282
3283
0
    hstep >>= 1;
3284
0
    start_mv = *bestmv;
3285
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3286
0
                          var_params, mv_cost_params, &besterr, sse1,
3287
0
                          distortion, iters_per_step, is_scaled);
3288
0
  }
3289
3290
509k
  return besterr;
3291
509k
}
3292
3293
int av1_find_best_sub_pixel_tree(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3294
                                 const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3295
                                 MV start_mv,
3296
                                 const FULLPEL_MV_STATS *start_mv_stats,
3297
                                 MV *bestmv, int *distortion,
3298
                                 unsigned int *sse1,
3299
0
                                 int_mv *last_mv_search_list) {
3300
0
  (void)start_mv_stats;
3301
0
  const int allow_hp = ms_params->allow_hp;
3302
0
  const int forced_stop = ms_params->forced_stop;
3303
0
  const int iters_per_step = ms_params->iters_per_step;
3304
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3305
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3306
0
  const SUBPEL_SEARCH_TYPE subpel_search_type =
3307
0
      ms_params->var_params.subpel_search_type;
3308
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3309
3310
  // How many steps to take. A round of 0 means fullpel search only, 1 means
3311
  // half-pel, and so on.
3312
0
  const int round = AOMMIN(FULL_PEL - forced_stop, 3 - !allow_hp);
3313
0
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3314
3315
0
  unsigned int besterr = INT_MAX;
3316
3317
0
  *bestmv = start_mv;
3318
3319
0
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3320
0
                                             ? &cm->sf_identity
3321
0
                                             : xd->block_ref_scale_factors[0];
3322
0
  const int is_scaled = av1_is_scaled(sf);
3323
3324
0
  if (start_mv_stats != NULL && !is_scaled) {
3325
0
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3326
0
    *distortion = start_mv_stats->distortion;
3327
0
    *sse1 = start_mv_stats->sse;
3328
0
  } else {
3329
0
    if (subpel_search_type != USE_2_TAPS_ORIG) {
3330
0
      besterr = upsampled_setup_center_error(xd, cm, bestmv, var_params,
3331
0
                                             mv_cost_params, sse1, distortion);
3332
0
    } else {
3333
0
      besterr = setup_center_error(xd, bestmv, var_params, mv_cost_params, sse1,
3334
0
                                   distortion);
3335
0
    }
3336
0
  }
3337
3338
  // If forced_stop is FULL_PEL, return.
3339
0
  if (!round) return besterr;
3340
3341
0
  for (int iter = 0; iter < round; ++iter) {
3342
0
    MV iter_center_mv = *bestmv;
3343
0
    if (check_repeated_mv_and_update(last_mv_search_list, iter_center_mv,
3344
0
                                     iter)) {
3345
0
      return INT_MAX;
3346
0
    }
3347
3348
0
    MV diag_step;
3349
0
    if (subpel_search_type != USE_2_TAPS_ORIG) {
3350
0
      diag_step = first_level_check(xd, cm, iter_center_mv, bestmv, hstep,
3351
0
                                    mv_limits, var_params, mv_cost_params,
3352
0
                                    &besterr, sse1, distortion);
3353
0
    } else {
3354
0
      diag_step = first_level_check_fast(xd, cm, iter_center_mv, bestmv, hstep,
3355
0
                                         mv_limits, var_params, mv_cost_params,
3356
0
                                         &besterr, sse1, distortion, is_scaled);
3357
0
    }
3358
3359
    // Check diagonal sub-pixel position
3360
0
    if (!CHECK_MV_EQUAL(iter_center_mv, *bestmv) && iters_per_step > 1) {
3361
0
      second_level_check_v2(xd, cm, iter_center_mv, diag_step, bestmv,
3362
0
                            mv_limits, var_params, mv_cost_params, &besterr,
3363
0
                            sse1, distortion, is_scaled);
3364
0
    }
3365
3366
0
    hstep >>= 1;
3367
0
  }
3368
3369
0
  return besterr;
3370
0
}
3371
3372
// Note(yunqingwang): The following 2 functions are only used in the motion
3373
// vector unit test, which return extreme motion vectors allowed by the MV
3374
// limits.
3375
// Returns the maximum MV.
3376
int av1_return_max_sub_pixel_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3377
                                const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3378
                                MV start_mv,
3379
                                const FULLPEL_MV_STATS *start_mv_stats,
3380
                                MV *bestmv, int *distortion, unsigned int *sse1,
3381
0
                                int_mv *last_mv_search_list) {
3382
0
  (void)xd;
3383
0
  (void)cm;
3384
0
  (void)start_mv;
3385
0
  (void)start_mv_stats;
3386
0
  (void)last_mv_search_list;
3387
3388
0
  const int allow_hp = ms_params->allow_hp;
3389
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3390
3391
0
  bestmv->row = mv_limits->row_max;
3392
0
  bestmv->col = mv_limits->col_max;
3393
3394
0
  unsigned int besterr = 0;
3395
3396
  // In the sub-pel motion search, if hp is not used, then the last bit of mv
3397
  // has to be 0.
3398
0
  lower_mv_precision(bestmv, allow_hp, 0);
3399
0
  *distortion = besterr;
3400
0
  *sse1 = besterr;
3401
0
  return besterr;
3402
0
}
3403
3404
// Returns the minimum MV.
3405
int av1_return_min_sub_pixel_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3406
                                const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3407
                                MV start_mv,
3408
                                const FULLPEL_MV_STATS *start_mv_stats,
3409
                                MV *bestmv, int *distortion, unsigned int *sse1,
3410
0
                                int_mv *last_mv_search_list) {
3411
0
  (void)xd;
3412
0
  (void)cm;
3413
0
  (void)start_mv;
3414
0
  (void)start_mv_stats;
3415
0
  (void)last_mv_search_list;
3416
3417
0
  const int allow_hp = ms_params->allow_hp;
3418
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3419
3420
0
  bestmv->row = mv_limits->row_min;
3421
0
  bestmv->col = mv_limits->col_min;
3422
3423
0
  unsigned int besterr = 0;
3424
  // In the sub-pel motion search, if hp is not used, then the last bit of mv
3425
  // has to be 0.
3426
0
  lower_mv_precision(bestmv, allow_hp, 0);
3427
0
  *distortion = besterr;
3428
0
  *sse1 = besterr;
3429
0
  return besterr;
3430
0
}
3431
3432
#if !CONFIG_REALTIME_ONLY
3433
// Computes the cost of the current predictor by going through the whole
3434
// av1_enc_build_inter_predictor pipeline. This is mainly used by warped mv
3435
// during motion_mode_rd. We are going through the whole
3436
// av1_enc_build_inter_predictor because we might have changed the interpolation
3437
// filter, etc before motion_mode_rd is called.
3438
static inline unsigned int compute_motion_cost(
3439
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3440
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, BLOCK_SIZE bsize,
3441
1.76M
    const MV *this_mv) {
3442
1.76M
  unsigned int mse;
3443
1.76M
  unsigned int sse;
3444
1.76M
  const int mi_row = xd->mi_row;
3445
1.76M
  const int mi_col = xd->mi_col;
3446
3447
1.76M
  av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
3448
1.76M
                                AOM_PLANE_Y, AOM_PLANE_Y);
3449
3450
1.76M
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3451
1.76M
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3452
3453
1.76M
  const uint8_t *const src = ms_buffers->src->buf;
3454
1.76M
  const int src_stride = ms_buffers->src->stride;
3455
1.76M
  const uint8_t *const dst = xd->plane[0].dst.buf;
3456
1.76M
  const int dst_stride = xd->plane[0].dst.stride;
3457
1.76M
  const aom_variance_fn_ptr_t *vfp = ms_params->var_params.vfp;
3458
3459
1.76M
  mse = vfp->vf(dst, dst_stride, src, src_stride, &sse);
3460
1.76M
  mse += mv_err_cost_(this_mv, &ms_params->mv_cost_params);
3461
1.76M
  return mse;
3462
1.76M
}
3463
3464
// Refines MV in a small range
3465
3466
// Macros to build bitmasks which help us avoid redundant computations
3467
//
3468
// To explain the idea here, imagine that on the first iteration of the
3469
// loop below, we step rightwards. Then, on the second iteration, the neighbors
3470
// to consider are:
3471
//     . . .
3472
//     0 1 .
3473
//     . . .
3474
// Where 0 is the initial search point, 1 is the best candidate found in the
3475
// first iteration, and the dots are the other neighbors of point 1.
3476
//
3477
// Naively, we would now need to scan all 8 neighbors of point 1 (point 0 and
3478
// the seven points marked with dots), and compare them to see where to move
3479
// next. However, we already evaluated 5 of those 8 neighbors in the last
3480
// iteration, and decided that they are worse than point 1. So we don't need
3481
// to re-consider these points. We only really need to consider the three
3482
// points which are adjacent to point 1 but *not* to point 0.
3483
//
3484
// As the algorithm goes on, there are other ways that redundant evaluations
3485
// can happen, if the search path curls back around on itself.
3486
//
3487
// To avoid all possible redundancies, we'd have to build a set containing
3488
// every point we have already checked, and this would be quite expensive.
3489
//
3490
// So instead, we apply a 95%-effective solution with a much lower overhead:
3491
// we prune out the points which were considered during the previous
3492
// iteration, but we don't worry about any prior iteration. This can be done
3493
// as follows:
3494
//
3495
// We build a static table, called neighbor_mask, which answers the question
3496
// "if we moved in direction X last time, which neighbors are new, and which
3497
//  were scanned last iteration?"
3498
// Then we can query this table to quickly determine which points we need to
3499
// evaluate, and which we can skip.
3500
//
3501
// To query the table, the logic is simply:
3502
// neighbor_mask[i] & (1 << j) == "if we moved in direction i last iteration,
3503
//                             do we need to scan neighbor j this iteration?"
3504
#define NEIGHBOR_MASK_DIA(left, down, right, up) \
3505
  (left | (down << 1) | (right << 2) | (up << 3))
3506
3507
#define NEIGHBOR_MASK_SQR(left, down, right, up, down_left, down_right, \
3508
                          up_left, up_right)                            \
3509
  (left | (down << 1) | (right << 2) | (up << 3) | (down_left << 4) |   \
3510
   (down_right << 5) | (up_left << 6) | (up_right << 7))
3511
3512
static const warp_search_config warp_search_info[WARP_SEARCH_METHODS] = {
3513
  // WARP_SEARCH_DIAMOND
3514
  {
3515
    .num_neighbors = 4,
3516
    .neighbors = { {  0, -1 }, {  1,  0 }, {  0,  1 }, { -1,  0 } },
3517
    .neighbor_mask = {
3518
      // If we stepped left last time, consider all points except right
3519
      NEIGHBOR_MASK_DIA(1, 1, 0, 1),
3520
      // If we stepped down last time, consider all points except up
3521
      NEIGHBOR_MASK_DIA(1, 1, 1, 0),
3522
      // Stepped right last time
3523
      NEIGHBOR_MASK_DIA(0, 1, 1, 1),
3524
      // Stepped up last time
3525
      NEIGHBOR_MASK_DIA(1, 0, 1, 1),
3526
    },
3527
  },
3528
  // WARP_SEARCH_SQUARE
3529
  {
3530
    .num_neighbors = 8,
3531
    .neighbors = { {  0, -1 }, {  1,  0 }, {  0,  1 }, { -1,  0 },
3532
                   {  1, -1 }, {  1,  1 }, { -1, -1 }, { -1,  1 } },
3533
    .neighbor_mask = {
3534
      // If we stepped left last time, then we only need to consider 3 points:
3535
      // left, down+left, up+left
3536
      NEIGHBOR_MASK_SQR(1, 0, 0, 0, 1, 0, 1, 0),
3537
      // If we stepped down last time, then we only need to consider 3 points:
3538
      // down, down+left, down+right
3539
      NEIGHBOR_MASK_SQR(0, 1, 0, 0, 1, 1, 0, 0),
3540
      // Stepped right last time
3541
      NEIGHBOR_MASK_SQR(0, 0, 1, 0, 0, 1, 0, 1),
3542
      // Stepped up last time
3543
      NEIGHBOR_MASK_SQR(0, 0, 0, 1, 0, 0, 1, 1),
3544
3545
      // If we stepped down+left last time, then we need to consider 5 points:
3546
      // left, down, down+left, down+right, up+left
3547
      NEIGHBOR_MASK_SQR(1, 1, 0, 0, 1, 1, 1, 0),
3548
      // Stepped down+right last time
3549
      NEIGHBOR_MASK_SQR(0, 1, 1, 0, 1, 1, 0, 1),
3550
      // Stepped up+left last time
3551
      NEIGHBOR_MASK_SQR(1, 0, 0, 1, 1, 0, 1, 1),
3552
      // Stepped up+right last time
3553
      NEIGHBOR_MASK_SQR(0, 0, 1, 1, 0, 1, 1, 1),
3554
    },
3555
  },
3556
};
3557
3558
unsigned int av1_refine_warped_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3559
                                  const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3560
                                  BLOCK_SIZE bsize, const int *pts0,
3561
                                  const int *pts_inref0, int total_samples,
3562
                                  WARP_SEARCH_METHOD search_method,
3563
191k
                                  int num_iterations) {
3564
191k
  MB_MODE_INFO *mbmi = xd->mi[0];
3565
3566
191k
  const MV *neighbors = warp_search_info[search_method].neighbors;
3567
191k
  const int num_neighbors = warp_search_info[search_method].num_neighbors;
3568
191k
  const uint8_t *neighbor_mask = warp_search_info[search_method].neighbor_mask;
3569
3570
191k
  MV *best_mv = &mbmi->mv[0].as_mv;
3571
3572
191k
  WarpedMotionParams best_wm_params = mbmi->wm_params;
3573
191k
  int best_num_proj_ref = mbmi->num_proj_ref;
3574
191k
  unsigned int bestmse;
3575
191k
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3576
3577
191k
  const int mv_shift = ms_params->allow_hp ? 0 : 1;
3578
3579
  // Calculate the center position's error
3580
191k
  assert(av1_is_subpelmv_in_range(mv_limits, *best_mv));
3581
191k
  bestmse = compute_motion_cost(xd, cm, ms_params, bsize, best_mv);
3582
3583
  // MV search
3584
191k
  int pts[SAMPLES_ARRAY_SIZE], pts_inref[SAMPLES_ARRAY_SIZE];
3585
191k
  const int mi_row = xd->mi_row;
3586
191k
  const int mi_col = xd->mi_col;
3587
3588
  // First step always scans all neighbors
3589
191k
  uint8_t valid_neighbors = UINT8_MAX;
3590
3591
474k
  for (int ite = 0; ite < num_iterations; ++ite) {
3592
469k
    int best_idx = -1;
3593
3594
2.34M
    for (int idx = 0; idx < num_neighbors; ++idx) {
3595
1.87M
      if ((valid_neighbors & (1 << idx)) == 0) {
3596
278k
        continue;
3597
278k
      }
3598
3599
1.59M
      unsigned int thismse;
3600
3601
1.59M
      MV this_mv = { best_mv->row + neighbors[idx].row * (1 << mv_shift),
3602
1.59M
                     best_mv->col + neighbors[idx].col * (1 << mv_shift) };
3603
1.59M
      if (av1_is_subpelmv_in_range(mv_limits, this_mv)) {
3604
1.59M
        memcpy(pts, pts0, total_samples * 2 * sizeof(*pts0));
3605
1.59M
        memcpy(pts_inref, pts_inref0, total_samples * 2 * sizeof(*pts_inref0));
3606
1.59M
        if (total_samples > 1) {
3607
653k
          mbmi->num_proj_ref =
3608
653k
              av1_selectSamples(&this_mv, pts, pts_inref, total_samples, bsize);
3609
653k
        }
3610
3611
1.59M
        if (!av1_find_projection(mbmi->num_proj_ref, pts, pts_inref, bsize,
3612
1.59M
                                 this_mv.row, this_mv.col, &mbmi->wm_params,
3613
1.59M
                                 mi_row, mi_col)) {
3614
1.57M
          thismse = compute_motion_cost(xd, cm, ms_params, bsize, &this_mv);
3615
3616
1.57M
          if (thismse < bestmse) {
3617
347k
            best_idx = idx;
3618
347k
            best_wm_params = mbmi->wm_params;
3619
347k
            best_num_proj_ref = mbmi->num_proj_ref;
3620
347k
            bestmse = thismse;
3621
347k
          }
3622
1.57M
        }
3623
1.59M
      }
3624
1.59M
    }
3625
3626
469k
    if (best_idx == -1) break;
3627
3628
283k
    if (best_idx >= 0) {
3629
283k
      best_mv->row += neighbors[best_idx].row * (1 << mv_shift);
3630
283k
      best_mv->col += neighbors[best_idx].col * (1 << mv_shift);
3631
283k
      valid_neighbors = neighbor_mask[best_idx];
3632
283k
    }
3633
283k
  }
3634
3635
191k
  mbmi->wm_params = best_wm_params;
3636
191k
  mbmi->num_proj_ref = best_num_proj_ref;
3637
191k
  return bestmse;
3638
191k
}
3639
3640
#endif  // !CONFIG_REALTIME_ONLY
3641
// =============================================================================
3642
//  Subpixel Motion Search: OBMC
3643
// =============================================================================
3644
// Estimates the variance of prediction residue
3645
static inline int estimate_obmc_pref_error(
3646
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3647
0
    unsigned int *sse) {
3648
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
3649
3650
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3651
0
  const int32_t *src = ms_buffers->wsrc;
3652
0
  const int32_t *mask = ms_buffers->obmc_mask;
3653
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
3654
0
  const int ref_stride = ms_buffers->ref->stride;
3655
3656
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
3657
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
3658
3659
0
  return vfp->osvf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, mask, sse);
3660
0
}
3661
3662
// Calculates the variance of prediction residue
3663
static int upsampled_obmc_pref_error(MACROBLOCKD *xd, const AV1_COMMON *cm,
3664
                                     const MV *this_mv,
3665
                                     const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3666
0
                                     unsigned int *sse) {
3667
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
3668
0
  const SUBPEL_SEARCH_TYPE subpel_search_type = var_params->subpel_search_type;
3669
0
  const int w = var_params->w;
3670
0
  const int h = var_params->h;
3671
3672
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3673
0
  const int32_t *wsrc = ms_buffers->wsrc;
3674
0
  const int32_t *mask = ms_buffers->obmc_mask;
3675
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
3676
0
  const int ref_stride = ms_buffers->ref->stride;
3677
3678
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
3679
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
3680
3681
0
  const int mi_row = xd->mi_row;
3682
0
  const int mi_col = xd->mi_col;
3683
3684
0
  unsigned int besterr;
3685
0
  DECLARE_ALIGNED(16, uint8_t, pred[2 * MAX_SB_SQUARE]);
3686
0
#if CONFIG_AV1_HIGHBITDEPTH
3687
0
  if (is_cur_buf_hbd(xd)) {
3688
0
    uint8_t *pred8 = CONVERT_TO_BYTEPTR(pred);
3689
0
    aom_highbd_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred8, w, h,
3690
0
                              subpel_x_q3, subpel_y_q3, ref, ref_stride, xd->bd,
3691
0
                              subpel_search_type);
3692
0
    besterr = vfp->ovf(pred8, w, wsrc, mask, sse);
3693
0
  } else {
3694
0
    aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
3695
0
                       subpel_y_q3, ref, ref_stride, subpel_search_type);
3696
3697
0
    besterr = vfp->ovf(pred, w, wsrc, mask, sse);
3698
0
  }
3699
#else
3700
  aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
3701
                     subpel_y_q3, ref, ref_stride, subpel_search_type);
3702
3703
  besterr = vfp->ovf(pred, w, wsrc, mask, sse);
3704
#endif
3705
0
  return besterr;
3706
0
}
3707
3708
static unsigned int setup_obmc_center_error(
3709
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3710
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
3711
  // TODO(chiyotsai@google.com): There might be a bug here where we didn't use
3712
  // get_buf_from_mv(ref, *this_mv).
3713
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3714
0
  const int32_t *wsrc = ms_buffers->wsrc;
3715
0
  const int32_t *mask = ms_buffers->obmc_mask;
3716
0
  const uint8_t *ref = ms_buffers->ref->buf;
3717
0
  const int ref_stride = ms_buffers->ref->stride;
3718
0
  unsigned int besterr =
3719
0
      var_params->vfp->ovf(ref, ref_stride, wsrc, mask, sse1);
3720
0
  *distortion = besterr;
3721
0
  besterr += mv_err_cost_(this_mv, mv_cost_params);
3722
0
  return besterr;
3723
0
}
3724
3725
static unsigned int upsampled_setup_obmc_center_error(
3726
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV *this_mv,
3727
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3728
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
3729
0
  unsigned int besterr =
3730
0
      upsampled_obmc_pref_error(xd, cm, this_mv, var_params, sse1);
3731
0
  *distortion = besterr;
3732
0
  besterr += mv_err_cost_(this_mv, mv_cost_params);
3733
0
  return besterr;
3734
0
}
3735
3736
// Estimates the variance of prediction residue
3737
// TODO(chiyotsai@google.com): the cost does does not match the cost in
3738
// mv_cost_. Investigate this later.
3739
static inline int estimate_obmc_mvcost(const MV *this_mv,
3740
0
                                       const MV_COST_PARAMS *mv_cost_params) {
3741
0
  const MV *ref_mv = mv_cost_params->ref_mv;
3742
0
  const int *mvjcost = mv_cost_params->mvjcost;
3743
0
  const int *const *mvcost = mv_cost_params->mvcost;
3744
0
  const int error_per_bit = mv_cost_params->error_per_bit;
3745
0
  const MV_COST_TYPE mv_cost_type = mv_cost_params->mv_cost_type;
3746
0
  const MV diff_mv = { GET_MV_SUBPEL(this_mv->row - ref_mv->row),
3747
0
                       GET_MV_SUBPEL(this_mv->col - ref_mv->col) };
3748
3749
0
  switch (mv_cost_type) {
3750
0
    case MV_COST_ENTROPY:
3751
0
      return (unsigned)((mv_cost(&diff_mv, mvjcost,
3752
0
                                 CONVERT_TO_CONST_MVCOST(mvcost)) *
3753
0
                             error_per_bit +
3754
0
                         4096) >>
3755
0
                        13);
3756
0
    case MV_COST_NONE: return 0;
3757
0
    default:
3758
0
      assert(0 && "L1 norm is not tuned for estimated obmc mvcost");
3759
0
      return 0;
3760
0
  }
3761
0
}
3762
3763
// Estimates whether this_mv is better than best_mv. This function incorporates
3764
// both prediction error and residue into account.
3765
static inline unsigned int obmc_check_better_fast(
3766
    const MV *this_mv, MV *best_mv, const SubpelMvLimits *mv_limits,
3767
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3768
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3769
0
    unsigned int *sse1, int *distortion, int *has_better_mv) {
3770
0
  unsigned int cost;
3771
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
3772
0
    unsigned int sse;
3773
0
    const int thismse = estimate_obmc_pref_error(this_mv, var_params, &sse);
3774
3775
0
    cost = estimate_obmc_mvcost(this_mv, mv_cost_params);
3776
0
    cost += thismse;
3777
3778
0
    if (cost < *besterr) {
3779
0
      *besterr = cost;
3780
0
      *best_mv = *this_mv;
3781
0
      *distortion = thismse;
3782
0
      *sse1 = sse;
3783
0
      *has_better_mv |= 1;
3784
0
    }
3785
0
  } else {
3786
0
    cost = INT_MAX;
3787
0
  }
3788
0
  return cost;
3789
0
}
3790
3791
// Estimates whether this_mv is better than best_mv. This function incorporates
3792
// both prediction error and residue into account.
3793
static inline unsigned int obmc_check_better(
3794
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
3795
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3796
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3797
0
    unsigned int *sse1, int *distortion, int *has_better_mv) {
3798
0
  unsigned int cost;
3799
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
3800
0
    unsigned int sse;
3801
0
    const int thismse =
3802
0
        upsampled_obmc_pref_error(xd, cm, this_mv, var_params, &sse);
3803
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
3804
3805
0
    cost += thismse;
3806
3807
0
    if (cost < *besterr) {
3808
0
      *besterr = cost;
3809
0
      *best_mv = *this_mv;
3810
0
      *distortion = thismse;
3811
0
      *sse1 = sse;
3812
0
      *has_better_mv |= 1;
3813
0
    }
3814
0
  } else {
3815
0
    cost = INT_MAX;
3816
0
  }
3817
0
  return cost;
3818
0
}
3819
3820
static AOM_FORCE_INLINE MV obmc_first_level_check(
3821
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV *best_mv,
3822
    const int hstep, const SubpelMvLimits *mv_limits,
3823
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3824
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3825
0
    unsigned int *sse1, int *distortion) {
3826
0
  int dummy = 0;
3827
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
3828
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
3829
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
3830
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
3831
3832
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
3833
0
    const unsigned int left =
3834
0
        obmc_check_better(xd, cm, &left_mv, best_mv, mv_limits, var_params,
3835
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3836
0
    const unsigned int right =
3837
0
        obmc_check_better(xd, cm, &right_mv, best_mv, mv_limits, var_params,
3838
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3839
0
    const unsigned int up =
3840
0
        obmc_check_better(xd, cm, &top_mv, best_mv, mv_limits, var_params,
3841
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3842
0
    const unsigned int down =
3843
0
        obmc_check_better(xd, cm, &bottom_mv, best_mv, mv_limits, var_params,
3844
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3845
3846
0
    const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
3847
0
    const MV diag_mv = { this_mv.row + diag_step.row,
3848
0
                         this_mv.col + diag_step.col };
3849
3850
    // Check the diagonal direction with the best mv
3851
0
    obmc_check_better(xd, cm, &diag_mv, best_mv, mv_limits, var_params,
3852
0
                      mv_cost_params, besterr, sse1, distortion, &dummy);
3853
3854
0
    return diag_step;
3855
0
  } else {
3856
0
    const unsigned int left = obmc_check_better_fast(
3857
0
        &left_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr, sse1,
3858
0
        distortion, &dummy);
3859
0
    const unsigned int right = obmc_check_better_fast(
3860
0
        &right_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
3861
0
        sse1, distortion, &dummy);
3862
3863
0
    const unsigned int up = obmc_check_better_fast(
3864
0
        &top_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr, sse1,
3865
0
        distortion, &dummy);
3866
3867
0
    const unsigned int down = obmc_check_better_fast(
3868
0
        &bottom_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
3869
0
        sse1, distortion, &dummy);
3870
3871
0
    const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
3872
0
    const MV diag_mv = { this_mv.row + diag_step.row,
3873
0
                         this_mv.col + diag_step.col };
3874
3875
    // Check the diagonal direction with the best mv
3876
0
    obmc_check_better_fast(&diag_mv, best_mv, mv_limits, var_params,
3877
0
                           mv_cost_params, besterr, sse1, distortion, &dummy);
3878
3879
0
    return diag_step;
3880
0
  }
3881
0
}
3882
3883
// A newer version of second level check for obmc that gives better quality.
3884
static AOM_FORCE_INLINE void obmc_second_level_check_v2(
3885
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV diag_step,
3886
    MV *best_mv, const SubpelMvLimits *mv_limits,
3887
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3888
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3889
0
    unsigned int *sse1, int *distortion) {
3890
0
  assert(best_mv->row == this_mv.row + diag_step.row ||
3891
0
         best_mv->col == this_mv.col + diag_step.col);
3892
0
  if (CHECK_MV_EQUAL(this_mv, *best_mv)) {
3893
0
    return;
3894
0
  } else if (this_mv.row == best_mv->row) {
3895
    // Search away from diagonal step since diagonal search did not provide any
3896
    // improvement
3897
0
    diag_step.row *= -1;
3898
0
  } else if (this_mv.col == best_mv->col) {
3899
0
    diag_step.col *= -1;
3900
0
  }
3901
3902
0
  const MV row_bias_mv = { best_mv->row + diag_step.row, best_mv->col };
3903
0
  const MV col_bias_mv = { best_mv->row, best_mv->col + diag_step.col };
3904
0
  const MV diag_bias_mv = { best_mv->row + diag_step.row,
3905
0
                            best_mv->col + diag_step.col };
3906
0
  int has_better_mv = 0;
3907
3908
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
3909
0
    obmc_check_better(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
3910
0
                      mv_cost_params, besterr, sse1, distortion,
3911
0
                      &has_better_mv);
3912
0
    obmc_check_better(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
3913
0
                      mv_cost_params, besterr, sse1, distortion,
3914
0
                      &has_better_mv);
3915
3916
    // Do an additional search if the second iteration gives a better mv
3917
0
    if (has_better_mv) {
3918
0
      obmc_check_better(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
3919
0
                        mv_cost_params, besterr, sse1, distortion,
3920
0
                        &has_better_mv);
3921
0
    }
3922
0
  } else {
3923
0
    obmc_check_better_fast(&row_bias_mv, best_mv, mv_limits, var_params,
3924
0
                           mv_cost_params, besterr, sse1, distortion,
3925
0
                           &has_better_mv);
3926
0
    obmc_check_better_fast(&col_bias_mv, best_mv, mv_limits, var_params,
3927
0
                           mv_cost_params, besterr, sse1, distortion,
3928
0
                           &has_better_mv);
3929
3930
    // Do an additional search if the second iteration gives a better mv
3931
0
    if (has_better_mv) {
3932
0
      obmc_check_better_fast(&diag_bias_mv, best_mv, mv_limits, var_params,
3933
0
                             mv_cost_params, besterr, sse1, distortion,
3934
0
                             &has_better_mv);
3935
0
    }
3936
0
  }
3937
0
}
3938
3939
int av1_find_best_obmc_sub_pixel_tree_up(
3940
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3941
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3942
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3943
0
    unsigned int *sse1, int_mv *last_mv_search_list) {
3944
0
  (void)last_mv_search_list;
3945
0
  (void)start_mv_stats;
3946
0
  const int allow_hp = ms_params->allow_hp;
3947
0
  const int forced_stop = ms_params->forced_stop;
3948
0
  const int iters_per_step = ms_params->iters_per_step;
3949
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3950
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3951
0
  const SUBPEL_SEARCH_TYPE subpel_search_type =
3952
0
      ms_params->var_params.subpel_search_type;
3953
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3954
3955
0
  int hstep = INIT_SUBPEL_STEP_SIZE;
3956
0
  const int round = AOMMIN(FULL_PEL - forced_stop, 3 - !allow_hp);
3957
3958
0
  unsigned int besterr = INT_MAX;
3959
0
  *bestmv = start_mv;
3960
3961
0
  if (subpel_search_type != USE_2_TAPS_ORIG)
3962
0
    besterr = upsampled_setup_obmc_center_error(
3963
0
        xd, cm, bestmv, var_params, mv_cost_params, sse1, distortion);
3964
0
  else
3965
0
    besterr = setup_obmc_center_error(bestmv, var_params, mv_cost_params, sse1,
3966
0
                                      distortion);
3967
3968
0
  for (int iter = 0; iter < round; ++iter) {
3969
0
    MV iter_center_mv = *bestmv;
3970
0
    MV diag_step = obmc_first_level_check(xd, cm, iter_center_mv, bestmv, hstep,
3971
0
                                          mv_limits, var_params, mv_cost_params,
3972
0
                                          &besterr, sse1, distortion);
3973
3974
0
    if (!CHECK_MV_EQUAL(iter_center_mv, *bestmv) && iters_per_step > 1) {
3975
0
      obmc_second_level_check_v2(xd, cm, iter_center_mv, diag_step, bestmv,
3976
0
                                 mv_limits, var_params, mv_cost_params,
3977
0
                                 &besterr, sse1, distortion);
3978
0
    }
3979
0
    hstep >>= 1;
3980
0
  }
3981
3982
0
  return besterr;
3983
0
}
3984
3985
// =============================================================================
3986
//  Public cost function: mv_cost + pred error
3987
// =============================================================================
3988
int av1_get_mvpred_sse(const MV_COST_PARAMS *mv_cost_params,
3989
                       const FULLPEL_MV best_mv,
3990
                       const aom_variance_fn_ptr_t *vfp,
3991
200k
                       const struct buf_2d *src, const struct buf_2d *pre) {
3992
200k
  const MV mv = get_mv_from_fullmv(&best_mv);
3993
200k
  unsigned int sse, var;
3994
3995
200k
  var = vfp->vf(src->buf, src->stride, get_buf_from_fullmv(pre, &best_mv),
3996
200k
                pre->stride, &sse);
3997
200k
  (void)var;
3998
3999
200k
  return sse + mv_err_cost_(&mv, mv_cost_params);
4000
200k
}