Coverage Report

Created: 2026-04-01 07:49

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