Coverage Report

Created: 2026-04-01 07:24

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 int diamond_search_sad(FULLPEL_MV start_mv, unsigned int start_mv_sad,
1370
                              const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1371
                              const int search_step, int *num00,
1372
0
                              FULLPEL_MV *best_mv, FULLPEL_MV *second_best_mv) {
1373
0
#define UPDATE_SEARCH_STEP                                      \
1374
0
  do {                                                          \
1375
0
    if (best_site != 0) {                                       \
1376
0
      tmp_second_best_mv = *best_mv;                            \
1377
0
      best_mv->row += site[best_site].mv.row;                   \
1378
0
      best_mv->col += site[best_site].mv.col;                   \
1379
0
      best_address += site[best_site].offset;                   \
1380
0
      is_off_center = 1;                                        \
1381
0
    }                                                           \
1382
0
                                                                \
1383
0
    if (is_off_center == 0) num_center_steps++;                 \
1384
0
                                                                \
1385
0
    if (best_site == 0 && step > 2) {                           \
1386
0
      int next_step_size = cfg->radius[step - 1];               \
1387
0
      while (next_step_size == cfg->radius[step] && step > 2) { \
1388
0
        num_center_steps++;                                     \
1389
0
        --step;                                                 \
1390
0
        next_step_size = cfg->radius[step - 1];                 \
1391
0
      }                                                         \
1392
0
    }                                                           \
1393
0
  } while (0)
1394
1395
0
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1396
0
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1397
1398
0
  const uint8_t *src_buf = src->buf;
1399
0
  const int src_stride = src->stride;
1400
0
  const int ref_stride = ref->stride;
1401
1402
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
1403
1404
0
  const search_site_config *cfg = ms_params->search_sites;
1405
1406
0
  int is_off_center = 0;
1407
  // Number of times that we have stayed in the middle. This is used to skip
1408
  // search steps in the future if diamond_search_sad is called again.
1409
0
  int num_center_steps = 0;
1410
1411
  // search_step determines the length of the initial step and hence the number
1412
  // of iterations.
1413
0
  const int tot_steps = cfg->num_search_steps - search_step;
1414
0
  FULLPEL_MV tmp_second_best_mv;
1415
0
  if (second_best_mv) {
1416
0
    tmp_second_best_mv = *second_best_mv;
1417
0
  }
1418
1419
0
  *best_mv = start_mv;
1420
1421
  // Check the starting position
1422
0
  const uint8_t *best_address = get_buf_from_fullmv(ref, &start_mv);
1423
0
  unsigned int bestsad = start_mv_sad;
1424
1425
  // TODO(chiyotsai@google.com): Implement 4 points search for msdf&sdaf
1426
0
  if (ms_params->ms_buffers.second_pred) {
1427
0
    for (int step = tot_steps - 1; step >= 0; --step) {
1428
0
      const search_site *site = cfg->site[step];
1429
0
      const int num_searches = cfg->searches_per_step[step];
1430
0
      int best_site = 0;
1431
1432
0
      for (int idx = 1; idx <= num_searches; idx++) {
1433
0
        const FULLPEL_MV this_mv = { best_mv->row + site[idx].mv.row,
1434
0
                                     best_mv->col + site[idx].mv.col };
1435
1436
0
        if (av1_is_fullmv_in_range(&ms_params->mv_limits, this_mv)) {
1437
0
          const uint8_t *const check_here = site[idx].offset + best_address;
1438
0
          unsigned int thissad =
1439
0
              get_mvpred_compound_sad(ms_params, src, check_here, ref_stride);
1440
1441
0
          if (thissad < bestsad) {
1442
0
            thissad += mvsad_err_cost_(&this_mv, mv_cost_params);
1443
0
            if (thissad < bestsad) {
1444
0
              bestsad = thissad;
1445
0
              best_site = idx;
1446
0
            }
1447
0
          }
1448
0
        }
1449
0
      }
1450
0
      UPDATE_SEARCH_STEP;
1451
0
    }
1452
0
  } else {
1453
0
    for (int step = tot_steps - 1; step >= 0; --step) {
1454
0
      const search_site *site = cfg->site[step];
1455
0
      const int num_searches = cfg->searches_per_step[step];
1456
0
      int best_site = 0;
1457
1458
0
      int all_in = 1;
1459
      // Trap illegal vectors
1460
0
      all_in &= best_mv->row + site[1].mv.row >= ms_params->mv_limits.row_min;
1461
0
      all_in &= best_mv->row + site[2].mv.row <= ms_params->mv_limits.row_max;
1462
0
      all_in &= best_mv->col + site[3].mv.col >= ms_params->mv_limits.col_min;
1463
0
      all_in &= best_mv->col + site[4].mv.col <= ms_params->mv_limits.col_max;
1464
1465
0
      if (all_in) {
1466
0
        for (int idx = 1; idx <= num_searches; idx += 4) {
1467
0
          unsigned char const *block_offset[4];
1468
0
          unsigned int sads[4];
1469
1470
0
          for (int j = 0; j < 4; j++)
1471
0
            block_offset[j] = site[idx + j].offset + best_address;
1472
1473
0
          ms_params->sdx4df(src_buf, src_stride, block_offset, ref_stride,
1474
0
                            sads);
1475
0
          for (int j = 0; j < 4; j++) {
1476
0
            if (sads[j] < bestsad) {
1477
0
              const FULLPEL_MV this_mv = { best_mv->row + site[idx + j].mv.row,
1478
0
                                           best_mv->col +
1479
0
                                               site[idx + j].mv.col };
1480
0
              unsigned int thissad =
1481
0
                  sads[j] + mvsad_err_cost_(&this_mv, mv_cost_params);
1482
0
              if (thissad < bestsad) {
1483
0
                bestsad = thissad;
1484
0
                best_site = idx + j;
1485
0
              }
1486
0
            }
1487
0
          }
1488
0
        }
1489
0
      } else {
1490
0
        for (int idx = 1; idx <= num_searches; idx++) {
1491
0
          const FULLPEL_MV this_mv = { best_mv->row + site[idx].mv.row,
1492
0
                                       best_mv->col + site[idx].mv.col };
1493
1494
0
          if (av1_is_fullmv_in_range(&ms_params->mv_limits, this_mv)) {
1495
0
            const uint8_t *const check_here = site[idx].offset + best_address;
1496
0
            unsigned int thissad =
1497
0
                get_mvpred_sad(ms_params, src, check_here, ref_stride);
1498
1499
0
            if (thissad < bestsad) {
1500
0
              thissad += mvsad_err_cost_(&this_mv, mv_cost_params);
1501
0
              if (thissad < bestsad) {
1502
0
                bestsad = thissad;
1503
0
                best_site = idx;
1504
0
              }
1505
0
            }
1506
0
          }
1507
0
        }
1508
0
      }
1509
0
      UPDATE_SEARCH_STEP;
1510
0
    }
1511
0
  }
1512
1513
0
  *num00 = num_center_steps;
1514
0
  if (second_best_mv) {
1515
0
    *second_best_mv = tmp_second_best_mv;
1516
0
  }
1517
1518
0
  return bestsad;
1519
1520
0
#undef UPDATE_SEARCH_STEP
1521
0
}
1522
1523
static inline unsigned int get_start_mvpred_sad_cost(
1524
0
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV start_mv) {
1525
0
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1526
0
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1527
0
  const uint8_t *best_address = get_buf_from_fullmv(ref, &start_mv);
1528
1529
0
  unsigned int start_mv_sad =
1530
0
      mvsad_err_cost_(&start_mv, &ms_params->mv_cost_params);
1531
1532
0
  if (ms_params->ms_buffers.second_pred)
1533
0
    start_mv_sad +=
1534
0
        get_mvpred_compound_sad(ms_params, src, best_address, ref->stride);
1535
0
  else
1536
0
    start_mv_sad += get_mvpred_sad(ms_params, src, best_address, ref->stride);
1537
1538
0
  return start_mv_sad;
1539
0
}
1540
1541
static int full_pixel_diamond(FULLPEL_MV start_mv,
1542
                              const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1543
                              const int step_param, int *cost_list,
1544
                              FULLPEL_MV *best_mv,
1545
                              FULLPEL_MV_STATS *best_mv_stats,
1546
0
                              FULLPEL_MV *second_best_mv) {
1547
0
  const search_site_config *cfg = ms_params->search_sites;
1548
0
  int thissme, n, num00 = 0;
1549
1550
  // Clamp start mv and calculate the cost
1551
0
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
1552
0
  unsigned int start_mv_sad = get_start_mvpred_sad_cost(ms_params, start_mv);
1553
1554
0
  diamond_search_sad(start_mv, start_mv_sad, ms_params, step_param, &n, best_mv,
1555
0
                     second_best_mv);
1556
1557
0
  int bestsme = get_mvpred_compound_var_cost(ms_params, best_mv, best_mv_stats);
1558
1559
  // If there won't be more n-step search, check to see if refining search is
1560
  // needed.
1561
0
  const int further_steps = cfg->num_search_steps - 1 - step_param;
1562
0
  while (n < further_steps) {
1563
0
    ++n;
1564
1565
    // TODO(chiyotsai@google.com): There is another bug here where the second
1566
    // best mv gets incorrectly overwritten. Fix it later.
1567
0
    FULLPEL_MV tmp_best_mv;
1568
0
    FULLPEL_MV_STATS tmp_best_mv_stats;
1569
0
    diamond_search_sad(start_mv, start_mv_sad, ms_params, step_param + n,
1570
0
                       &num00, &tmp_best_mv, second_best_mv);
1571
1572
0
    thissme = get_mvpred_compound_var_cost(ms_params, &tmp_best_mv,
1573
0
                                           &tmp_best_mv_stats);
1574
1575
0
    if (thissme < bestsme) {
1576
0
      bestsme = thissme;
1577
0
      *best_mv = tmp_best_mv;
1578
0
      *best_mv_stats = tmp_best_mv_stats;
1579
0
    }
1580
1581
0
    if (num00) {
1582
      // Advance the loop by num00 steps
1583
0
      n += num00;
1584
0
      num00 = 0;
1585
0
    }
1586
0
  }
1587
1588
  // Return cost list.
1589
0
  if (cost_list) {
1590
0
    if (USE_SAD_COSTLIST) {
1591
0
      const int costlist_has_sad = 0;
1592
0
      calc_int_sad_list(*best_mv, ms_params, cost_list, costlist_has_sad);
1593
0
    } else {
1594
0
      calc_int_cost_list(*best_mv, ms_params, cost_list);
1595
0
    }
1596
0
  }
1597
0
  return bestsme;
1598
0
}
1599
1600
// Exhaustive motion search around a given centre position with a given
1601
// step size.
1602
static int exhaustive_mesh_search(FULLPEL_MV start_mv,
1603
                                  const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1604
                                  const int range, const int step,
1605
                                  FULLPEL_MV *best_mv,
1606
0
                                  FULLPEL_MV *second_best_mv) {
1607
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
1608
0
  const struct buf_2d *const src = ms_params->ms_buffers.src;
1609
0
  const struct buf_2d *const ref = ms_params->ms_buffers.ref;
1610
0
  const int ref_stride = ref->stride;
1611
0
  unsigned int best_sad = INT_MAX;
1612
0
  int r, c, i;
1613
0
  int start_col, end_col, start_row, end_row;
1614
0
  const int col_step = (step > 1) ? step : 4;
1615
1616
0
  assert(step >= 1);
1617
1618
0
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
1619
0
  *best_mv = start_mv;
1620
0
  best_sad = get_mvpred_sad(ms_params, src, get_buf_from_fullmv(ref, &start_mv),
1621
0
                            ref_stride);
1622
0
  best_sad += mvsad_err_cost_(&start_mv, mv_cost_params);
1623
0
  start_row = AOMMAX(-range, ms_params->mv_limits.row_min - start_mv.row);
1624
0
  start_col = AOMMAX(-range, ms_params->mv_limits.col_min - start_mv.col);
1625
0
  end_row = AOMMIN(range, ms_params->mv_limits.row_max - start_mv.row);
1626
0
  end_col = AOMMIN(range, ms_params->mv_limits.col_max - start_mv.col);
1627
1628
0
  for (r = start_row; r <= end_row; r += step) {
1629
0
    for (c = start_col; c <= end_col; c += col_step) {
1630
      // Step > 1 means we are not checking every location in this pass.
1631
0
      if (step > 1) {
1632
0
        const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c };
1633
0
        unsigned int sad = get_mvpred_sad(
1634
0
            ms_params, src, get_buf_from_fullmv(ref, &mv), ref_stride);
1635
0
        update_mvs_and_sad(sad, &mv, mv_cost_params, &best_sad,
1636
0
                           /*raw_best_sad=*/NULL, best_mv, second_best_mv);
1637
0
      } else {
1638
        // 4 sads in a single call if we are checking every location
1639
0
        if (c + 3 <= end_col) {
1640
0
          unsigned int sads[4];
1641
0
          const uint8_t *addrs[4];
1642
0
          for (i = 0; i < 4; ++i) {
1643
0
            const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c + i };
1644
0
            addrs[i] = get_buf_from_fullmv(ref, &mv);
1645
0
          }
1646
1647
0
          ms_params->sdx4df(src->buf, src->stride, addrs, ref_stride, sads);
1648
1649
0
          for (i = 0; i < 4; ++i) {
1650
0
            if (sads[i] < best_sad) {
1651
0
              const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c + i };
1652
0
              update_mvs_and_sad(sads[i], &mv, mv_cost_params, &best_sad,
1653
0
                                 /*raw_best_sad=*/NULL, best_mv,
1654
0
                                 second_best_mv);
1655
0
            }
1656
0
          }
1657
0
        } else {
1658
0
          for (i = 0; i < end_col - c; ++i) {
1659
0
            const FULLPEL_MV mv = { start_mv.row + r, start_mv.col + c + i };
1660
0
            unsigned int sad = get_mvpred_sad(
1661
0
                ms_params, src, get_buf_from_fullmv(ref, &mv), ref_stride);
1662
0
            update_mvs_and_sad(sad, &mv, mv_cost_params, &best_sad,
1663
0
                               /*raw_best_sad=*/NULL, best_mv, second_best_mv);
1664
0
          }
1665
0
        }
1666
0
      }
1667
0
    }
1668
0
  }
1669
1670
0
  return best_sad;
1671
0
}
1672
1673
// Runs an limited range exhaustive mesh search using a pattern set
1674
// according to the encode speed profile.
1675
static int full_pixel_exhaustive(const FULLPEL_MV start_mv,
1676
                                 const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1677
                                 const struct MESH_PATTERN *const mesh_patterns,
1678
                                 int *cost_list, FULLPEL_MV *best_mv,
1679
                                 FULLPEL_MV_STATS *mv_stats,
1680
0
                                 FULLPEL_MV *second_best_mv) {
1681
0
  const int kMinRange = 7;
1682
0
  const int kMaxRange = 256;
1683
0
  const int kMinInterval = 1;
1684
1685
0
  int bestsme;
1686
0
  int i;
1687
0
  int interval = mesh_patterns[0].interval;
1688
0
  int range = mesh_patterns[0].range;
1689
0
  int baseline_interval_divisor;
1690
1691
  // TODO(chiyotsai@google.com): Currently exhaustive search calls single ref
1692
  // version of sad and variance function. We still need to check the
1693
  // performance when compound ref exhaustive search is enabled.
1694
0
  assert(!ms_params->ms_buffers.second_pred &&
1695
0
         "Mesh search does not support compound mode!");
1696
1697
0
  *best_mv = start_mv;
1698
1699
  // Trap illegal values for interval and range for this function.
1700
0
  if ((range < kMinRange) || (range > kMaxRange) || (interval < kMinInterval) ||
1701
0
      (interval > range))
1702
0
    return INT_MAX;
1703
1704
0
  baseline_interval_divisor = range / interval;
1705
1706
  // Check size of proposed first range against magnitude of the centre
1707
  // value used as a starting point.
1708
0
  range = AOMMAX(range, (5 * AOMMAX(abs(best_mv->row), abs(best_mv->col))) / 4);
1709
0
  range = AOMMIN(range, kMaxRange);
1710
0
  interval = AOMMAX(interval, range / baseline_interval_divisor);
1711
  // Use a small search step/interval for certain kind of clips.
1712
  // For example, screen content clips with a lot of texts.
1713
  // Large interval could lead to a false matching position, and it can't find
1714
  // the best global candidate in following iterations due to reduced search
1715
  // range. The solution here is to use a small search iterval in the beginning
1716
  // and thus reduces the chance of missing the best candidate.
1717
0
  if (ms_params->fine_search_interval) {
1718
0
    interval = AOMMIN(interval, 4);
1719
0
  }
1720
1721
  // initial search
1722
0
  bestsme = exhaustive_mesh_search(*best_mv, ms_params, range, interval,
1723
0
                                   best_mv, second_best_mv);
1724
1725
0
  if ((interval > kMinInterval) && (range > kMinRange)) {
1726
    // Progressive searches with range and step size decreasing each time
1727
    // till we reach a step size of 1. Then break out.
1728
0
    for (i = 1; i < MAX_MESH_STEP; ++i) {
1729
      // First pass with coarser step and longer range
1730
0
      bestsme = exhaustive_mesh_search(
1731
0
          *best_mv, ms_params, mesh_patterns[i].range,
1732
0
          mesh_patterns[i].interval, best_mv, second_best_mv);
1733
1734
0
      if (mesh_patterns[i].interval == 1) break;
1735
0
    }
1736
0
  }
1737
1738
0
  if (bestsme < INT_MAX) {
1739
0
    bestsme = get_mvpred_var_cost(ms_params, best_mv, mv_stats);
1740
0
  }
1741
1742
  // Return cost list.
1743
0
  if (cost_list) {
1744
0
    if (USE_SAD_COSTLIST) {
1745
0
      const int costlist_has_sad = 0;
1746
0
      calc_int_sad_list(*best_mv, ms_params, cost_list, costlist_has_sad);
1747
0
    } else {
1748
0
      calc_int_cost_list(*best_mv, ms_params, cost_list);
1749
0
    }
1750
0
  }
1751
0
  return bestsme;
1752
0
}
1753
1754
// This function is called when we do joint motion search in comp_inter_inter
1755
// mode, or when searching for one component of an ext-inter compound mode.
1756
int av1_refining_search_8p_c(const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1757
0
                             const FULLPEL_MV start_mv, FULLPEL_MV *best_mv) {
1758
0
  static const search_neighbors neighbors[8] = {
1759
0
    { { -1, 0 }, -1 * SEARCH_GRID_STRIDE_8P + 0 },
1760
0
    { { 0, -1 }, 0 * SEARCH_GRID_STRIDE_8P - 1 },
1761
0
    { { 0, 1 }, 0 * SEARCH_GRID_STRIDE_8P + 1 },
1762
0
    { { 1, 0 }, 1 * SEARCH_GRID_STRIDE_8P + 0 },
1763
0
    { { -1, -1 }, -1 * SEARCH_GRID_STRIDE_8P - 1 },
1764
0
    { { 1, -1 }, 1 * SEARCH_GRID_STRIDE_8P - 1 },
1765
0
    { { -1, 1 }, -1 * SEARCH_GRID_STRIDE_8P + 1 },
1766
0
    { { 1, 1 }, 1 * SEARCH_GRID_STRIDE_8P + 1 }
1767
0
  };
1768
1769
0
  uint8_t do_refine_search_grid[SEARCH_GRID_STRIDE_8P *
1770
0
                                SEARCH_GRID_STRIDE_8P] = { 0 };
1771
0
  int grid_center = SEARCH_GRID_CENTER_8P;
1772
0
  int grid_coord = grid_center;
1773
1774
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
1775
0
  const FullMvLimits *mv_limits = &ms_params->mv_limits;
1776
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
1777
0
  const struct buf_2d *src = ms_buffers->src;
1778
0
  const struct buf_2d *ref = ms_buffers->ref;
1779
0
  const int ref_stride = ref->stride;
1780
1781
0
  *best_mv = start_mv;
1782
0
  clamp_fullmv(best_mv, mv_limits);
1783
1784
0
  unsigned int best_sad = get_mvpred_compound_sad(
1785
0
      ms_params, src, get_buf_from_fullmv(ref, best_mv), ref_stride);
1786
0
  best_sad += mvsad_err_cost_(best_mv, mv_cost_params);
1787
1788
0
  do_refine_search_grid[grid_coord] = 1;
1789
1790
0
  for (int i = 0; i < SEARCH_RANGE_8P; ++i) {
1791
0
    int best_site = -1;
1792
1793
0
    for (int j = 0; j < 8; ++j) {
1794
0
      grid_coord = grid_center + neighbors[j].coord_offset;
1795
0
      if (do_refine_search_grid[grid_coord] == 1) {
1796
0
        continue;
1797
0
      }
1798
0
      const FULLPEL_MV mv = { best_mv->row + neighbors[j].coord.row,
1799
0
                              best_mv->col + neighbors[j].coord.col };
1800
1801
0
      do_refine_search_grid[grid_coord] = 1;
1802
0
      if (av1_is_fullmv_in_range(mv_limits, mv)) {
1803
0
        unsigned int sad;
1804
0
        sad = get_mvpred_compound_sad(
1805
0
            ms_params, src, get_buf_from_fullmv(ref, &mv), ref_stride);
1806
0
        if (sad < best_sad) {
1807
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
1808
1809
0
          if (sad < best_sad) {
1810
0
            best_sad = sad;
1811
0
            best_site = j;
1812
0
          }
1813
0
        }
1814
0
      }
1815
0
    }
1816
1817
0
    if (best_site == -1) {
1818
0
      break;
1819
0
    } else {
1820
0
      best_mv->row += neighbors[best_site].coord.row;
1821
0
      best_mv->col += neighbors[best_site].coord.col;
1822
0
      grid_center += neighbors[best_site].coord_offset;
1823
0
    }
1824
0
  }
1825
0
  return best_sad;
1826
0
}
1827
1828
int av1_full_pixel_search(const FULLPEL_MV start_mv,
1829
                          const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1830
                          const int step_param, int *cost_list,
1831
                          FULLPEL_MV *best_mv, FULLPEL_MV_STATS *best_mv_stats,
1832
0
                          FULLPEL_MV *second_best_mv) {
1833
0
  const BLOCK_SIZE bsize = ms_params->bsize;
1834
0
  const SEARCH_METHODS search_method = ms_params->search_method;
1835
1836
0
  const int is_intra_mode = ms_params->is_intra_mode;
1837
0
  int run_mesh_search = ms_params->run_mesh_search;
1838
1839
0
  int var = 0;
1840
0
  MARK_MV_INVALID(best_mv);
1841
0
  if (second_best_mv) {
1842
0
    MARK_MV_INVALID(second_best_mv);
1843
0
  }
1844
1845
0
  if (cost_list) {
1846
0
    cost_list[0] = INT_MAX;
1847
0
    cost_list[1] = INT_MAX;
1848
0
    cost_list[2] = INT_MAX;
1849
0
    cost_list[3] = INT_MAX;
1850
0
    cost_list[4] = INT_MAX;
1851
0
  }
1852
1853
0
  assert(ms_params->ms_buffers.ref->stride == ms_params->search_sites->stride);
1854
1855
0
  switch (search_method) {
1856
0
    case FAST_BIGDIA:
1857
0
      var = fast_bigdia_search(start_mv, ms_params, step_param, 0, cost_list,
1858
0
                               best_mv, best_mv_stats);
1859
0
      break;
1860
0
    case VFAST_DIAMOND:
1861
0
      var = vfast_dia_search(start_mv, ms_params, step_param, 0, cost_list,
1862
0
                             best_mv, best_mv_stats);
1863
0
      break;
1864
0
    case FAST_DIAMOND:
1865
0
      var = fast_dia_search(start_mv, ms_params, step_param, 0, cost_list,
1866
0
                            best_mv, best_mv_stats);
1867
0
      break;
1868
0
    case FAST_HEX:
1869
0
      var = fast_hex_search(start_mv, ms_params, step_param, 0, cost_list,
1870
0
                            best_mv, best_mv_stats);
1871
0
      break;
1872
0
    case HEX:
1873
0
      var = hex_search(start_mv, ms_params, step_param, 1, cost_list, best_mv,
1874
0
                       best_mv_stats);
1875
0
      break;
1876
0
    case SQUARE:
1877
0
      var = square_search(start_mv, ms_params, step_param, 1, cost_list,
1878
0
                          best_mv, best_mv_stats);
1879
0
      break;
1880
0
    case BIGDIA:
1881
0
      var = bigdia_search(start_mv, ms_params, step_param, 1, cost_list,
1882
0
                          best_mv, best_mv_stats);
1883
0
      break;
1884
0
    case NSTEP:
1885
0
    case NSTEP_8PT:
1886
0
    case DIAMOND:
1887
0
    case CLAMPED_DIAMOND:
1888
0
      var = full_pixel_diamond(start_mv, ms_params, step_param, cost_list,
1889
0
                               best_mv, best_mv_stats, second_best_mv);
1890
0
      break;
1891
0
    default: assert(0 && "Invalid search method.");
1892
0
  }
1893
1894
  // Should we allow a follow on exhaustive search?
1895
0
  if (!run_mesh_search &&
1896
0
      ((search_method == NSTEP) || (search_method == NSTEP_8PT)) &&
1897
0
      !ms_params->ms_buffers.second_pred) {
1898
0
    int exhaustive_thr = ms_params->force_mesh_thresh;
1899
0
    exhaustive_thr >>=
1900
0
        10 - (mi_size_wide_log2[bsize] + mi_size_high_log2[bsize]);
1901
    // Threshold variance for an exhaustive full search.
1902
0
    if (var > exhaustive_thr) run_mesh_search = 1;
1903
0
  }
1904
1905
  // TODO(yunqing): the following is used to reduce mesh search in temporal
1906
  // filtering. Can extend it to intrabc.
1907
0
  if (!is_intra_mode && ms_params->prune_mesh_search) {
1908
0
    const int full_pel_mv_diff = AOMMAX(abs(start_mv.row - best_mv->row),
1909
0
                                        abs(start_mv.col - best_mv->col));
1910
0
    if (full_pel_mv_diff <= ms_params->mesh_search_mv_diff_threshold) {
1911
0
      run_mesh_search = 0;
1912
0
    }
1913
0
  }
1914
1915
0
  if (ms_params->sdf != ms_params->vfp->sdf) {
1916
    // If we are skipping rows when we perform the motion search, we need to
1917
    // check the quality of skipping. If it's bad, then we run mesh search with
1918
    // skip row features off.
1919
    // TODO(chiyotsai@google.com): Handle the case where we have a vertical
1920
    // offset of 1 before we hit this statement to avoid having to redo
1921
    // motion search.
1922
0
    const struct buf_2d *src = ms_params->ms_buffers.src;
1923
0
    const struct buf_2d *ref = ms_params->ms_buffers.ref;
1924
0
    const int src_stride = src->stride;
1925
0
    const int ref_stride = ref->stride;
1926
1927
0
    const uint8_t *src_address = src->buf;
1928
0
    const uint8_t *best_address = get_buf_from_fullmv(ref, best_mv);
1929
0
    const int sad =
1930
0
        ms_params->vfp->sdf(src_address, src_stride, best_address, ref_stride);
1931
0
    const int skip_sad =
1932
0
        ms_params->vfp->sdsf(src_address, src_stride, best_address, ref_stride);
1933
    // We will keep the result of skipping rows if it's good enough. Here, good
1934
    // enough means the error is less than 1 per pixel.
1935
0
    const int kSADThresh =
1936
0
        1 << (mi_size_wide_log2[bsize] + mi_size_high_log2[bsize]);
1937
0
    if (sad > kSADThresh && abs(skip_sad - sad) * 10 >= AOMMAX(sad, 1) * 9) {
1938
      // There is a large discrepancy between skipping and not skipping, so we
1939
      // need to redo the motion search.
1940
0
      FULLPEL_MOTION_SEARCH_PARAMS new_ms_params = *ms_params;
1941
0
      new_ms_params.sdf = new_ms_params.vfp->sdf;
1942
0
      new_ms_params.sdx4df = new_ms_params.vfp->sdx4df;
1943
0
      new_ms_params.sdx3df = new_ms_params.vfp->sdx3df;
1944
1945
0
      return av1_full_pixel_search(start_mv, &new_ms_params, step_param,
1946
0
                                   cost_list, best_mv, best_mv_stats,
1947
0
                                   second_best_mv);
1948
0
    }
1949
0
  }
1950
1951
0
  if (run_mesh_search) {
1952
0
    int var_ex;
1953
0
    FULLPEL_MV tmp_mv_ex;
1954
0
    FULLPEL_MV_STATS tmp_mv_stats;
1955
    // Pick the mesh pattern for exhaustive search based on the toolset (intraBC
1956
    // or non-intraBC)
1957
    // TODO(chiyotsai@google.com):  There is a bug here where the second best mv
1958
    // gets overwritten without actually comparing the rdcost.
1959
0
    const MESH_PATTERN *const mesh_patterns =
1960
0
        ms_params->mesh_patterns[is_intra_mode];
1961
    // TODO(chiyotsai@google.com): the second best mv is not set correctly by
1962
    // full_pixel_exhaustive, which can incorrectly override it.
1963
0
    var_ex =
1964
0
        full_pixel_exhaustive(*best_mv, ms_params, mesh_patterns, cost_list,
1965
0
                              &tmp_mv_ex, &tmp_mv_stats, second_best_mv);
1966
0
    if (var_ex < var) {
1967
0
      var = var_ex;
1968
0
      *best_mv_stats = tmp_mv_stats;
1969
0
      *best_mv = tmp_mv_ex;
1970
0
    }
1971
0
  }
1972
1973
0
  return var;
1974
0
}
1975
1976
int av1_intrabc_hash_search(const AV1_COMP *cpi, const MACROBLOCKD *xd,
1977
                            const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
1978
                            IntraBCHashInfo *intrabc_hash_info,
1979
0
                            FULLPEL_MV *best_mv) {
1980
0
  if (!av1_use_hash_me(cpi)) return INT_MAX;
1981
1982
0
  const BLOCK_SIZE bsize = ms_params->bsize;
1983
0
  const int block_width = block_size_wide[bsize];
1984
0
  const int block_height = block_size_high[bsize];
1985
1986
0
  if (block_width != block_height) return INT_MAX;
1987
1988
0
  const FullMvLimits *mv_limits = &ms_params->mv_limits;
1989
0
  const MSBuffers *ms_buffer = &ms_params->ms_buffers;
1990
1991
0
  const uint8_t *src = ms_buffer->src->buf;
1992
0
  const int src_stride = ms_buffer->src->stride;
1993
1994
0
  const int mi_row = xd->mi_row;
1995
0
  const int mi_col = xd->mi_col;
1996
0
  const int x_pos = mi_col * MI_SIZE;
1997
0
  const int y_pos = mi_row * MI_SIZE;
1998
1999
0
  uint32_t hash_value1, hash_value2;
2000
0
  int best_hash_cost = INT_MAX;
2001
2002
  // for the hashMap
2003
0
  hash_table *ref_frame_hash = &intrabc_hash_info->intrabc_hash_table;
2004
2005
0
  av1_get_block_hash_value(intrabc_hash_info, src, src_stride, block_width,
2006
0
                           &hash_value1, &hash_value2, is_cur_buf_hbd(xd));
2007
2008
0
  int count = av1_hash_table_count(ref_frame_hash, hash_value1);
2009
0
  if (count <= 1) {
2010
0
    return INT_MAX;
2011
0
  }
2012
0
  if (cpi->sf.mv_sf.prune_intrabc_candidate_block_hash_search) {
2013
0
    count = AOMMIN(64, count);
2014
0
  }
2015
2016
0
  Iterator iterator = av1_hash_get_first_iterator(ref_frame_hash, hash_value1);
2017
0
  for (int i = 0; i < count; i++, aom_iterator_increment(&iterator)) {
2018
0
    block_hash ref_block_hash = *(block_hash *)(aom_iterator_get(&iterator));
2019
0
    if (hash_value2 == ref_block_hash.hash_value2) {
2020
      // Make sure the prediction is from valid area.
2021
0
      const MV dv = { GET_MV_SUBPEL(ref_block_hash.y - y_pos),
2022
0
                      GET_MV_SUBPEL(ref_block_hash.x - x_pos) };
2023
0
      if (!av1_is_dv_valid(dv, &cpi->common, xd, mi_row, mi_col, bsize,
2024
0
                           cpi->common.seq_params->mib_size_log2))
2025
0
        continue;
2026
2027
0
      FULLPEL_MV hash_mv;
2028
0
      hash_mv.col = ref_block_hash.x - x_pos;
2029
0
      hash_mv.row = ref_block_hash.y - y_pos;
2030
0
      if (!av1_is_fullmv_in_range(mv_limits, hash_mv)) continue;
2031
0
      FULLPEL_MV_STATS mv_stats;
2032
0
      const int refCost = get_mvpred_var_cost(ms_params, &hash_mv, &mv_stats);
2033
0
      if (refCost < best_hash_cost) {
2034
0
        best_hash_cost = refCost;
2035
0
        *best_mv = hash_mv;
2036
0
      }
2037
0
    }
2038
0
  }
2039
2040
0
  return best_hash_cost;
2041
0
}
2042
2043
int av1_vector_match(const int16_t *ref, const int16_t *src, int bwl,
2044
0
                     int search_size, int full_search, int *sad) {
2045
0
  int best_sad = INT_MAX;
2046
0
  int this_sad;
2047
0
  int d;
2048
0
  int center, offset = 0;
2049
0
  int bw = search_size << 1;
2050
2051
0
  if (full_search) {
2052
0
    for (d = 0; d <= bw; d++) {
2053
0
      this_sad = aom_vector_var(&ref[d], src, bwl);
2054
0
      if (this_sad < best_sad) {
2055
0
        best_sad = this_sad;
2056
0
        offset = d;
2057
0
      }
2058
0
    }
2059
0
    center = offset;
2060
0
    *sad = best_sad;
2061
0
    return (center - (bw >> 1));
2062
0
  }
2063
2064
0
  for (d = 0; d <= bw; d += 16) {
2065
0
    this_sad = aom_vector_var(&ref[d], src, bwl);
2066
0
    if (this_sad < best_sad) {
2067
0
      best_sad = this_sad;
2068
0
      offset = d;
2069
0
    }
2070
0
  }
2071
0
  center = offset;
2072
2073
0
  for (d = -8; d <= 8; d += 16) {
2074
0
    int this_pos = offset + d;
2075
    // check limit
2076
0
    if (this_pos < 0 || this_pos > bw) continue;
2077
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2078
0
    if (this_sad < best_sad) {
2079
0
      best_sad = this_sad;
2080
0
      center = this_pos;
2081
0
    }
2082
0
  }
2083
0
  offset = center;
2084
2085
0
  for (d = -4; d <= 4; d += 8) {
2086
0
    int this_pos = offset + d;
2087
    // check limit
2088
0
    if (this_pos < 0 || this_pos > bw) continue;
2089
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2090
0
    if (this_sad < best_sad) {
2091
0
      best_sad = this_sad;
2092
0
      center = this_pos;
2093
0
    }
2094
0
  }
2095
0
  offset = center;
2096
2097
0
  for (d = -2; d <= 2; d += 4) {
2098
0
    int this_pos = offset + d;
2099
    // check limit
2100
0
    if (this_pos < 0 || this_pos > bw) continue;
2101
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2102
0
    if (this_sad < best_sad) {
2103
0
      best_sad = this_sad;
2104
0
      center = this_pos;
2105
0
    }
2106
0
  }
2107
0
  offset = center;
2108
2109
0
  for (d = -1; d <= 1; d += 2) {
2110
0
    int this_pos = offset + d;
2111
    // check limit
2112
0
    if (this_pos < 0 || this_pos > bw) continue;
2113
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2114
0
    if (this_sad < best_sad) {
2115
0
      best_sad = this_sad;
2116
0
      center = this_pos;
2117
0
    }
2118
0
  }
2119
0
  *sad = best_sad;
2120
0
  return (center - (bw >> 1));
2121
0
}
2122
2123
// A special fast version of motion search used in rt mode.
2124
// The search window along columns and row is given by:
2125
//  +/- me_search_size_col/row.
2126
unsigned int av1_int_pro_motion_estimation(const AV1_COMP *cpi, MACROBLOCK *x,
2127
                                           BLOCK_SIZE bsize, int mi_row,
2128
                                           int mi_col, const MV *ref_mv,
2129
                                           unsigned int *y_sad_zero,
2130
                                           int me_search_size_col,
2131
0
                                           int me_search_size_row) {
2132
0
  const AV1_COMMON *const cm = &cpi->common;
2133
0
  MACROBLOCKD *xd = &x->e_mbd;
2134
0
  MB_MODE_INFO *mi = xd->mi[0];
2135
0
  struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0, 0, 0, 0 } };
2136
0
  int idx;
2137
0
  const int bw = block_size_wide[bsize];
2138
0
  const int bh = block_size_high[bsize];
2139
0
  const int is_screen = cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN;
2140
0
  const int full_search = is_screen;
2141
0
  const bool screen_scroll_superblock =
2142
0
      is_screen && bsize == cm->seq_params->sb_size;
2143
  // Keep border a multiple of 16.
2144
0
  const int border = (cpi->oxcf.border_in_pixels >> 4) << 4;
2145
0
  int search_size_width = me_search_size_col;
2146
0
  int search_size_height = me_search_size_row;
2147
  // Adjust based on boundary.
2148
0
  if (((mi_col << 2) - search_size_width < -border) ||
2149
0
      ((mi_col << 2) + search_size_width > cm->width + border))
2150
0
    search_size_width = border;
2151
0
  if (((mi_row << 2) - search_size_height < -border) ||
2152
0
      ((mi_row << 2) + search_size_height > cm->height + border))
2153
0
    search_size_height = border;
2154
0
  const int src_stride = x->plane[0].src.stride;
2155
0
  const int ref_stride = xd->plane[0].pre[0].stride;
2156
0
  uint8_t const *ref_buf, *src_buf;
2157
0
  int_mv *best_int_mv = &xd->mi[0]->mv[0];
2158
0
  unsigned int best_sad, tmp_sad, this_sad[4];
2159
0
  int best_sad_col, best_sad_row;
2160
0
  const int row_norm_factor = mi_size_high_log2[bsize] + 1;
2161
0
  const int col_norm_factor = 3 + (bw >> 5);
2162
0
  const YV12_BUFFER_CONFIG *scaled_ref_frame =
2163
0
      av1_get_scaled_ref_frame(cpi, mi->ref_frame[0]);
2164
0
  static const MV search_pos[4] = {
2165
0
    { -1, 0 },
2166
0
    { 0, -1 },
2167
0
    { 0, 1 },
2168
0
    { 1, 0 },
2169
0
  };
2170
2171
0
  if (scaled_ref_frame) {
2172
0
    int i;
2173
    // Swap out the reference frame for a version that's been scaled to
2174
    // match the resolution of the current frame, allowing the existing
2175
    // motion search code to be used without additional modifications.
2176
0
    for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
2177
0
    av1_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL,
2178
0
                         MAX_MB_PLANE);
2179
0
  }
2180
2181
0
  if (xd->bd != 8) {
2182
0
    best_int_mv->as_fullmv = kZeroFullMv;
2183
0
    best_sad = cpi->ppi->fn_ptr[bsize].sdf(x->plane[0].src.buf, src_stride,
2184
0
                                           xd->plane[0].pre[0].buf, ref_stride);
2185
2186
0
    if (scaled_ref_frame) {
2187
0
      int i;
2188
0
      for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2189
0
    }
2190
0
    return best_sad;
2191
0
  }
2192
0
  const int width_ref_buf = (search_size_width << 1) + bw;
2193
0
  const int height_ref_buf = (search_size_height << 1) + bh;
2194
0
  int16_t *hbuf = (int16_t *)aom_malloc(width_ref_buf * sizeof(*hbuf));
2195
0
  int16_t *vbuf = (int16_t *)aom_malloc(height_ref_buf * sizeof(*vbuf));
2196
0
  int16_t *src_hbuf = (int16_t *)aom_malloc(bw * sizeof(*src_hbuf));
2197
0
  int16_t *src_vbuf = (int16_t *)aom_malloc(bh * sizeof(*src_vbuf));
2198
0
  if (!hbuf || !vbuf || !src_hbuf || !src_vbuf) {
2199
0
    aom_free(hbuf);
2200
0
    aom_free(vbuf);
2201
0
    aom_free(src_hbuf);
2202
0
    aom_free(src_vbuf);
2203
0
    aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2204
0
                       "Failed to allocate hbuf, vbuf, src_hbuf, or src_vbuf");
2205
0
  }
2206
2207
  // Set up prediction 1-D reference set for rows.
2208
0
  ref_buf = xd->plane[0].pre[0].buf - search_size_width;
2209
0
  aom_int_pro_row(hbuf, ref_buf, ref_stride, width_ref_buf, bh,
2210
0
                  row_norm_factor);
2211
2212
  // Set up prediction 1-D reference set for cols
2213
0
  ref_buf = xd->plane[0].pre[0].buf - search_size_height * ref_stride;
2214
0
  aom_int_pro_col(vbuf, ref_buf, ref_stride, bw, height_ref_buf,
2215
0
                  col_norm_factor);
2216
2217
  // Set up src 1-D reference set
2218
0
  src_buf = x->plane[0].src.buf;
2219
0
  aom_int_pro_row(src_hbuf, src_buf, src_stride, bw, bh, row_norm_factor);
2220
0
  aom_int_pro_col(src_vbuf, src_buf, src_stride, bw, bh, col_norm_factor);
2221
2222
  // Find the best match per 1-D search
2223
0
  best_int_mv->as_fullmv.col =
2224
0
      av1_vector_match(hbuf, src_hbuf, mi_size_wide_log2[bsize],
2225
0
                       search_size_width, full_search, &best_sad_col);
2226
0
  best_int_mv->as_fullmv.row =
2227
0
      av1_vector_match(vbuf, src_vbuf, mi_size_high_log2[bsize],
2228
0
                       search_size_height, full_search, &best_sad_row);
2229
2230
  // For screen: select between horiz or vert motion.
2231
0
  if (is_screen) {
2232
0
    if (best_sad_col < best_sad_row)
2233
0
      best_int_mv->as_fullmv.row = 0;
2234
0
    else
2235
0
      best_int_mv->as_fullmv.col = 0;
2236
0
  }
2237
2238
0
  FULLPEL_MV this_mv = best_int_mv->as_fullmv;
2239
0
  src_buf = x->plane[0].src.buf;
2240
0
  ref_buf = get_buf_from_fullmv(&xd->plane[0].pre[0], &this_mv);
2241
0
  best_sad =
2242
0
      cpi->ppi->fn_ptr[bsize].sdf(src_buf, src_stride, ref_buf, ref_stride);
2243
2244
  // Evaluate zero MV if found MV is non-zero.
2245
0
  if (best_int_mv->as_int != 0) {
2246
0
    tmp_sad = cpi->ppi->fn_ptr[bsize].sdf(x->plane[0].src.buf, src_stride,
2247
0
                                          xd->plane[0].pre[0].buf, ref_stride);
2248
0
    *y_sad_zero = tmp_sad;
2249
0
    if (tmp_sad < best_sad) {
2250
0
      best_int_mv->as_fullmv = kZeroFullMv;
2251
0
      this_mv = best_int_mv->as_fullmv;
2252
0
      ref_buf = xd->plane[0].pre[0].buf;
2253
0
      best_sad = tmp_sad;
2254
0
    }
2255
0
  } else {
2256
0
    *y_sad_zero = best_sad;
2257
0
  }
2258
2259
0
  if (!screen_scroll_superblock) {
2260
0
    const uint8_t *const pos[4] = {
2261
0
      ref_buf - ref_stride,
2262
0
      ref_buf - 1,
2263
0
      ref_buf + 1,
2264
0
      ref_buf + ref_stride,
2265
0
    };
2266
2267
0
    cpi->ppi->fn_ptr[bsize].sdx4df(src_buf, src_stride, pos, ref_stride,
2268
0
                                   this_sad);
2269
2270
0
    for (idx = 0; idx < 4; ++idx) {
2271
0
      if (this_sad[idx] < best_sad) {
2272
0
        best_sad = this_sad[idx];
2273
0
        best_int_mv->as_fullmv.row = search_pos[idx].row + this_mv.row;
2274
0
        best_int_mv->as_fullmv.col = search_pos[idx].col + this_mv.col;
2275
0
      }
2276
0
    }
2277
2278
0
    if (this_sad[0] < this_sad[3])
2279
0
      this_mv.row -= 1;
2280
0
    else
2281
0
      this_mv.row += 1;
2282
2283
0
    if (this_sad[1] < this_sad[2])
2284
0
      this_mv.col -= 1;
2285
0
    else
2286
0
      this_mv.col += 1;
2287
2288
0
    ref_buf = get_buf_from_fullmv(&xd->plane[0].pre[0], &this_mv);
2289
2290
0
    tmp_sad =
2291
0
        cpi->ppi->fn_ptr[bsize].sdf(src_buf, src_stride, ref_buf, ref_stride);
2292
0
    if (best_sad > tmp_sad) {
2293
0
      best_int_mv->as_fullmv = this_mv;
2294
0
      best_sad = tmp_sad;
2295
0
    }
2296
0
  }
2297
2298
0
  FullMvLimits mv_limits = x->mv_limits;
2299
0
  av1_set_mv_search_range(&mv_limits, ref_mv);
2300
0
  clamp_fullmv(&best_int_mv->as_fullmv, &mv_limits);
2301
2302
0
  convert_fullmv_to_mv(best_int_mv);
2303
2304
0
  if (scaled_ref_frame) {
2305
0
    int i;
2306
0
    for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2307
0
  }
2308
2309
0
  aom_free(hbuf);
2310
0
  aom_free(vbuf);
2311
0
  aom_free(src_hbuf);
2312
0
  aom_free(src_vbuf);
2313
0
  return best_sad;
2314
0
}
2315
2316
// =============================================================================
2317
//  Fullpixel Motion Search: OBMC
2318
// =============================================================================
2319
static inline int get_obmc_mvpred_var(
2320
0
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV *this_mv) {
2321
0
  const aom_variance_fn_ptr_t *vfp = ms_params->vfp;
2322
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2323
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2324
0
  const int32_t *wsrc = ms_buffers->wsrc;
2325
0
  const int32_t *mask = ms_buffers->obmc_mask;
2326
0
  const struct buf_2d *ref_buf = ms_buffers->ref;
2327
2328
0
  const MV mv = get_mv_from_fullmv(this_mv);
2329
0
  unsigned int unused;
2330
2331
0
  return vfp->ovf(get_buf_from_fullmv(ref_buf, this_mv), ref_buf->stride, wsrc,
2332
0
                  mask, &unused) +
2333
0
         mv_err_cost_(&mv, mv_cost_params);
2334
0
}
2335
2336
static int obmc_refining_search_sad(
2337
0
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV *best_mv) {
2338
0
  const aom_variance_fn_ptr_t *fn_ptr = ms_params->vfp;
2339
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2340
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2341
0
  const int32_t *wsrc = ms_buffers->wsrc;
2342
0
  const int32_t *mask = ms_buffers->obmc_mask;
2343
0
  const struct buf_2d *ref_buf = ms_buffers->ref;
2344
0
  const FULLPEL_MV neighbors[4] = { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };
2345
0
  const int kSearchRange = 8;
2346
2347
0
  unsigned int best_sad = fn_ptr->osdf(get_buf_from_fullmv(ref_buf, best_mv),
2348
0
                                       ref_buf->stride, wsrc, mask) +
2349
0
                          mvsad_err_cost_(best_mv, mv_cost_params);
2350
2351
0
  for (int i = 0; i < kSearchRange; i++) {
2352
0
    int best_site = -1;
2353
2354
0
    for (int j = 0; j < 4; j++) {
2355
0
      const FULLPEL_MV mv = { best_mv->row + neighbors[j].row,
2356
0
                              best_mv->col + neighbors[j].col };
2357
0
      if (av1_is_fullmv_in_range(&ms_params->mv_limits, mv)) {
2358
0
        unsigned int sad = fn_ptr->osdf(get_buf_from_fullmv(ref_buf, &mv),
2359
0
                                        ref_buf->stride, wsrc, mask);
2360
0
        if (sad < best_sad) {
2361
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
2362
2363
0
          if (sad < best_sad) {
2364
0
            best_sad = sad;
2365
0
            best_site = j;
2366
0
          }
2367
0
        }
2368
0
      }
2369
0
    }
2370
2371
0
    if (best_site == -1) {
2372
0
      break;
2373
0
    } else {
2374
0
      best_mv->row += neighbors[best_site].row;
2375
0
      best_mv->col += neighbors[best_site].col;
2376
0
    }
2377
0
  }
2378
0
  return best_sad;
2379
0
}
2380
2381
static int obmc_diamond_search_sad(
2382
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV start_mv,
2383
0
    FULLPEL_MV *best_mv, int search_step, int *num00) {
2384
0
  const aom_variance_fn_ptr_t *fn_ptr = ms_params->vfp;
2385
0
  const search_site_config *cfg = ms_params->search_sites;
2386
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2387
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2388
0
  const int32_t *wsrc = ms_buffers->wsrc;
2389
0
  const int32_t *mask = ms_buffers->obmc_mask;
2390
0
  const struct buf_2d *const ref_buf = ms_buffers->ref;
2391
2392
  // search_step determines the length of the initial step and hence the number
2393
  // of iterations.
2394
0
  const int tot_steps = cfg->num_search_steps - search_step;
2395
0
  const uint8_t *best_address, *init_ref;
2396
0
  int best_sad = INT_MAX;
2397
0
  int best_site = 0;
2398
2399
0
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
2400
0
  best_address = init_ref = get_buf_from_fullmv(ref_buf, &start_mv);
2401
0
  *num00 = 0;
2402
0
  *best_mv = start_mv;
2403
2404
  // Check the starting position
2405
0
  best_sad = fn_ptr->osdf(best_address, ref_buf->stride, wsrc, mask) +
2406
0
             mvsad_err_cost_(best_mv, mv_cost_params);
2407
2408
0
  for (int step = tot_steps - 1; step >= 0; --step) {
2409
0
    const search_site *const site = cfg->site[step];
2410
0
    best_site = 0;
2411
0
    for (int idx = 1; idx <= cfg->searches_per_step[step]; ++idx) {
2412
0
      const FULLPEL_MV mv = { best_mv->row + site[idx].mv.row,
2413
0
                              best_mv->col + site[idx].mv.col };
2414
0
      if (av1_is_fullmv_in_range(&ms_params->mv_limits, mv)) {
2415
0
        int sad = fn_ptr->osdf(best_address + site[idx].offset, ref_buf->stride,
2416
0
                               wsrc, mask);
2417
0
        if (sad < best_sad) {
2418
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
2419
2420
0
          if (sad < best_sad) {
2421
0
            best_sad = sad;
2422
0
            best_site = idx;
2423
0
          }
2424
0
        }
2425
0
      }
2426
0
    }
2427
2428
0
    if (best_site != 0) {
2429
0
      best_mv->row += site[best_site].mv.row;
2430
0
      best_mv->col += site[best_site].mv.col;
2431
0
      best_address += site[best_site].offset;
2432
0
    } else if (best_address == init_ref) {
2433
0
      (*num00)++;
2434
0
    }
2435
0
  }
2436
0
  return best_sad;
2437
0
}
2438
2439
static int obmc_full_pixel_diamond(
2440
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV start_mv,
2441
0
    int step_param, FULLPEL_MV *best_mv) {
2442
0
  const search_site_config *cfg = ms_params->search_sites;
2443
0
  FULLPEL_MV tmp_mv;
2444
0
  int thissme, n, num00 = 0;
2445
0
  int bestsme =
2446
0
      obmc_diamond_search_sad(ms_params, start_mv, &tmp_mv, step_param, &n);
2447
0
  if (bestsme < INT_MAX) bestsme = get_obmc_mvpred_var(ms_params, &tmp_mv);
2448
0
  *best_mv = tmp_mv;
2449
2450
  // If there won't be more n-step search, check to see if refining search is
2451
  // needed.
2452
0
  const int further_steps = cfg->num_search_steps - 1 - step_param;
2453
2454
0
  while (n < further_steps) {
2455
0
    ++n;
2456
2457
0
    if (num00) {
2458
0
      num00--;
2459
0
    } else {
2460
0
      thissme = obmc_diamond_search_sad(ms_params, start_mv, &tmp_mv,
2461
0
                                        step_param + n, &num00);
2462
0
      if (thissme < INT_MAX) thissme = get_obmc_mvpred_var(ms_params, &tmp_mv);
2463
2464
0
      if (thissme < bestsme) {
2465
0
        bestsme = thissme;
2466
0
        *best_mv = tmp_mv;
2467
0
      }
2468
0
    }
2469
0
  }
2470
2471
0
  return bestsme;
2472
0
}
2473
2474
int av1_obmc_full_pixel_search(const FULLPEL_MV start_mv,
2475
                               const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
2476
0
                               const int step_param, FULLPEL_MV *best_mv) {
2477
0
  if (!ms_params->fast_obmc_search) {
2478
0
    const int bestsme =
2479
0
        obmc_full_pixel_diamond(ms_params, start_mv, step_param, best_mv);
2480
0
    return bestsme;
2481
0
  } else {
2482
0
    *best_mv = start_mv;
2483
0
    clamp_fullmv(best_mv, &ms_params->mv_limits);
2484
0
    int thissme = obmc_refining_search_sad(ms_params, best_mv);
2485
0
    if (thissme < INT_MAX) thissme = get_obmc_mvpred_var(ms_params, best_mv);
2486
0
    return thissme;
2487
0
  }
2488
0
}
2489
2490
// =============================================================================
2491
//  Subpixel Motion Search: Translational
2492
// =============================================================================
2493
0
#define INIT_SUBPEL_STEP_SIZE (4)
2494
/*
2495
 * To avoid the penalty for crossing cache-line read, preload the reference
2496
 * area in a small buffer, which is aligned to make sure there won't be crossing
2497
 * cache-line read while reading from this buffer. This reduced the cpu
2498
 * cycles spent on reading ref data in sub-pixel filter functions.
2499
 * TODO: Currently, since sub-pixel search range here is -3 ~ 3, copy 22 rows x
2500
 * 32 cols area that is enough for 16x16 macroblock. Later, for SPLITMV, we
2501
 * could reduce the area.
2502
 */
2503
2504
// Returns the subpel offset used by various subpel variance functions [m]sv[a]f
2505
0
static inline int get_subpel_part(int x) { return x & 7; }
2506
2507
// Gets the address of the ref buffer at subpel location (r, c), rounded to the
2508
// nearest fullpel precision toward - \infty
2509
static inline const uint8_t *get_buf_from_mv(const struct buf_2d *buf,
2510
0
                                             const MV mv) {
2511
0
  const int offset = (mv.row >> 3) * buf->stride + (mv.col >> 3);
2512
0
  return &buf->buf[offset];
2513
0
}
2514
2515
// Estimates the variance of prediction residue using bilinear filter for fast
2516
// search.
2517
static inline int estimated_pref_error(
2518
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2519
0
    unsigned int *sse) {
2520
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2521
2522
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2523
0
  const uint8_t *src = ms_buffers->src->buf;
2524
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
2525
0
  const int src_stride = ms_buffers->src->stride;
2526
0
  const int ref_stride = ms_buffers->ref->stride;
2527
0
  const uint8_t *second_pred = ms_buffers->second_pred;
2528
0
  const uint8_t *mask = ms_buffers->mask;
2529
0
  const int mask_stride = ms_buffers->mask_stride;
2530
0
  const int invert_mask = ms_buffers->inv_mask;
2531
2532
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
2533
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
2534
2535
0
  if (second_pred == NULL) {
2536
0
    return vfp->svf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2537
0
                    sse);
2538
0
  } else if (mask) {
2539
0
    return vfp->msvf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2540
0
                     second_pred, mask, mask_stride, invert_mask, sse);
2541
0
  } else {
2542
0
    return vfp->svaf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2543
0
                     sse, second_pred);
2544
0
  }
2545
0
}
2546
2547
// Calculates the variance of prediction residue.
2548
static int upsampled_pref_error(MACROBLOCKD *xd, const AV1_COMMON *cm,
2549
                                const MV *this_mv,
2550
                                const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2551
0
                                unsigned int *sse) {
2552
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2553
0
  const SUBPEL_SEARCH_TYPE subpel_search_type = var_params->subpel_search_type;
2554
2555
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2556
0
  const uint8_t *src = ms_buffers->src->buf;
2557
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
2558
0
  const int src_stride = ms_buffers->src->stride;
2559
0
  const int ref_stride = ms_buffers->ref->stride;
2560
0
  const uint8_t *second_pred = ms_buffers->second_pred;
2561
0
  const uint8_t *mask = ms_buffers->mask;
2562
0
  const int mask_stride = ms_buffers->mask_stride;
2563
0
  const int invert_mask = ms_buffers->inv_mask;
2564
0
  const int w = var_params->w;
2565
0
  const int h = var_params->h;
2566
2567
0
  const int mi_row = xd->mi_row;
2568
0
  const int mi_col = xd->mi_col;
2569
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
2570
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
2571
2572
0
  unsigned int besterr;
2573
0
#if CONFIG_AV1_HIGHBITDEPTH
2574
0
  if (is_cur_buf_hbd(xd)) {
2575
0
    DECLARE_ALIGNED(16, uint16_t, pred16[MAX_SB_SQUARE]);
2576
0
    uint8_t *pred8 = CONVERT_TO_BYTEPTR(pred16);
2577
0
    if (second_pred != NULL) {
2578
0
      if (mask) {
2579
0
        aom_highbd_comp_mask_upsampled_pred(
2580
0
            xd, cm, mi_row, mi_col, this_mv, pred8, second_pred, w, h,
2581
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, mask, mask_stride,
2582
0
            invert_mask, xd->bd, subpel_search_type);
2583
0
      } else {
2584
0
        aom_highbd_comp_avg_upsampled_pred(
2585
0
            xd, cm, mi_row, mi_col, this_mv, pred8, second_pred, w, h,
2586
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, xd->bd,
2587
0
            subpel_search_type);
2588
0
      }
2589
0
    } else {
2590
0
      aom_highbd_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred8, w, h,
2591
0
                                subpel_x_q3, subpel_y_q3, ref, ref_stride,
2592
0
                                xd->bd, subpel_search_type);
2593
0
    }
2594
0
    besterr = vfp->vf(pred8, w, src, src_stride, sse);
2595
0
  } else {
2596
0
    DECLARE_ALIGNED(16, uint8_t, pred[MAX_SB_SQUARE]);
2597
0
    if (second_pred != NULL) {
2598
0
      if (mask) {
2599
0
        aom_comp_mask_upsampled_pred(
2600
0
            xd, cm, mi_row, mi_col, this_mv, pred, second_pred, w, h,
2601
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, mask, mask_stride,
2602
0
            invert_mask, subpel_search_type);
2603
0
      } else {
2604
0
        aom_comp_avg_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2605
0
                                    second_pred, w, h, subpel_x_q3, subpel_y_q3,
2606
0
                                    ref, ref_stride, subpel_search_type);
2607
0
      }
2608
0
    } else {
2609
0
      aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h,
2610
0
                         subpel_x_q3, subpel_y_q3, ref, ref_stride,
2611
0
                         subpel_search_type);
2612
0
    }
2613
2614
0
    besterr = vfp->vf(pred, w, src, src_stride, sse);
2615
0
  }
2616
#else
2617
  DECLARE_ALIGNED(16, uint8_t, pred[MAX_SB_SQUARE]);
2618
  if (second_pred != NULL) {
2619
    if (mask) {
2620
      aom_comp_mask_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2621
                                   second_pred, w, h, subpel_x_q3, subpel_y_q3,
2622
                                   ref, ref_stride, mask, mask_stride,
2623
                                   invert_mask, subpel_search_type);
2624
    } else {
2625
      aom_comp_avg_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2626
                                  second_pred, w, h, subpel_x_q3, subpel_y_q3,
2627
                                  ref, ref_stride, subpel_search_type);
2628
    }
2629
  } else {
2630
    aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
2631
                       subpel_y_q3, ref, ref_stride, subpel_search_type);
2632
  }
2633
2634
  besterr = vfp->vf(pred, w, src, src_stride, sse);
2635
#endif
2636
0
  return besterr;
2637
0
}
2638
2639
// Estimates whether this_mv is better than best_mv. This function incorporates
2640
// both prediction error and residue into account. It is suffixed "fast" because
2641
// it uses bilinear filter to estimate the prediction.
2642
static inline unsigned int check_better_fast(
2643
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
2644
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2645
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2646
0
    unsigned int *sse1, int *distortion, int *has_better_mv, int is_scaled) {
2647
0
  unsigned int cost;
2648
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
2649
0
    unsigned int sse;
2650
0
    int thismse;
2651
0
    if (is_scaled) {
2652
0
      thismse = upsampled_pref_error(xd, cm, this_mv, var_params, &sse);
2653
0
    } else {
2654
0
      thismse = estimated_pref_error(this_mv, var_params, &sse);
2655
0
    }
2656
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
2657
0
    cost += thismse;
2658
2659
0
    if (cost < *besterr) {
2660
0
      *besterr = cost;
2661
0
      *best_mv = *this_mv;
2662
0
      *distortion = thismse;
2663
0
      *sse1 = sse;
2664
0
      *has_better_mv |= 1;
2665
0
    }
2666
0
  } else {
2667
0
    cost = INT_MAX;
2668
0
  }
2669
0
  return cost;
2670
0
}
2671
2672
// Checks whether this_mv is better than best_mv. This function incorporates
2673
// both prediction error and residue into account.
2674
static AOM_FORCE_INLINE unsigned int check_better(
2675
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
2676
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2677
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2678
0
    unsigned int *sse1, int *distortion, int *is_better) {
2679
0
  unsigned int cost;
2680
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
2681
0
    unsigned int sse;
2682
0
    int thismse;
2683
0
    thismse = upsampled_pref_error(xd, cm, this_mv, var_params, &sse);
2684
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
2685
0
    cost += thismse;
2686
0
    if (cost < *besterr) {
2687
0
      *besterr = cost;
2688
0
      *best_mv = *this_mv;
2689
0
      *distortion = thismse;
2690
0
      *sse1 = sse;
2691
0
      *is_better |= 1;
2692
0
    }
2693
0
  } else {
2694
0
    cost = INT_MAX;
2695
0
  }
2696
0
  return cost;
2697
0
}
2698
2699
static inline MV get_best_diag_step(int step_size, unsigned int left_cost,
2700
                                    unsigned int right_cost,
2701
                                    unsigned int up_cost,
2702
0
                                    unsigned int down_cost) {
2703
0
  const MV diag_step = { up_cost <= down_cost ? -step_size : step_size,
2704
0
                         left_cost <= right_cost ? -step_size : step_size };
2705
2706
0
  return diag_step;
2707
0
}
2708
2709
// Searches the four cardinal direction for a better mv, then follows up with a
2710
// search in the best quadrant. This uses bilinear filter to speed up the
2711
// calculation.
2712
static AOM_FORCE_INLINE MV first_level_check_fast(
2713
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, MV *best_mv,
2714
    int hstep, const SubpelMvLimits *mv_limits,
2715
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2716
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2717
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2718
  // Check the four cardinal directions
2719
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
2720
0
  int dummy = 0;
2721
0
  const unsigned int left = check_better_fast(
2722
0
      xd, cm, &left_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
2723
0
      sse1, distortion, &dummy, is_scaled);
2724
2725
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
2726
0
  const unsigned int right = check_better_fast(
2727
0
      xd, cm, &right_mv, best_mv, mv_limits, var_params, mv_cost_params,
2728
0
      besterr, sse1, distortion, &dummy, is_scaled);
2729
2730
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
2731
0
  const unsigned int up = check_better_fast(
2732
0
      xd, cm, &top_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
2733
0
      sse1, distortion, &dummy, is_scaled);
2734
2735
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
2736
0
  const unsigned int down = check_better_fast(
2737
0
      xd, cm, &bottom_mv, best_mv, mv_limits, var_params, mv_cost_params,
2738
0
      besterr, sse1, distortion, &dummy, is_scaled);
2739
2740
0
  const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
2741
0
  const MV diag_mv = { this_mv.row + diag_step.row,
2742
0
                       this_mv.col + diag_step.col };
2743
2744
  // Check the diagonal direction with the best mv
2745
0
  check_better_fast(xd, cm, &diag_mv, best_mv, mv_limits, var_params,
2746
0
                    mv_cost_params, besterr, sse1, distortion, &dummy,
2747
0
                    is_scaled);
2748
2749
0
  return diag_step;
2750
0
}
2751
2752
// Performs a following up search after first_level_check_fast is called. This
2753
// performs two extra chess pattern searches in the best quadrant.
2754
static AOM_FORCE_INLINE void second_level_check_fast(
2755
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, const MV diag_step,
2756
    MV *best_mv, int hstep, const SubpelMvLimits *mv_limits,
2757
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2758
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2759
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2760
0
  assert(diag_step.row == hstep || diag_step.row == -hstep);
2761
0
  assert(diag_step.col == hstep || diag_step.col == -hstep);
2762
0
  const int tr = this_mv.row;
2763
0
  const int tc = this_mv.col;
2764
0
  const int br = best_mv->row;
2765
0
  const int bc = best_mv->col;
2766
0
  int dummy = 0;
2767
0
  if (tr != br && tc != bc) {
2768
0
    assert(diag_step.col == bc - tc);
2769
0
    assert(diag_step.row == br - tr);
2770
0
    const MV chess_mv_1 = { br, bc + diag_step.col };
2771
0
    const MV chess_mv_2 = { br + diag_step.row, bc };
2772
0
    check_better_fast(xd, cm, &chess_mv_1, best_mv, mv_limits, var_params,
2773
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2774
0
                      is_scaled);
2775
2776
0
    check_better_fast(xd, cm, &chess_mv_2, best_mv, mv_limits, var_params,
2777
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2778
0
                      is_scaled);
2779
0
  } else if (tr == br && tc != bc) {
2780
0
    assert(diag_step.col == bc - tc);
2781
    // Continue searching in the best direction
2782
0
    const MV bottom_long_mv = { br + hstep, bc + diag_step.col };
2783
0
    const MV top_long_mv = { br - hstep, bc + diag_step.col };
2784
0
    check_better_fast(xd, cm, &bottom_long_mv, best_mv, mv_limits, var_params,
2785
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2786
0
                      is_scaled);
2787
0
    check_better_fast(xd, cm, &top_long_mv, best_mv, mv_limits, var_params,
2788
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2789
0
                      is_scaled);
2790
2791
    // Search in the direction opposite of the best quadrant
2792
0
    const MV rev_mv = { br - diag_step.row, bc };
2793
0
    check_better_fast(xd, cm, &rev_mv, best_mv, mv_limits, var_params,
2794
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2795
0
                      is_scaled);
2796
0
  } else if (tr != br && tc == bc) {
2797
0
    assert(diag_step.row == br - tr);
2798
    // Continue searching in the best direction
2799
0
    const MV right_long_mv = { br + diag_step.row, bc + hstep };
2800
0
    const MV left_long_mv = { br + diag_step.row, bc - hstep };
2801
0
    check_better_fast(xd, cm, &right_long_mv, best_mv, mv_limits, var_params,
2802
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2803
0
                      is_scaled);
2804
0
    check_better_fast(xd, cm, &left_long_mv, best_mv, mv_limits, var_params,
2805
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2806
0
                      is_scaled);
2807
2808
    // Search in the direction opposite of the best quadrant
2809
0
    const MV rev_mv = { br, bc - diag_step.col };
2810
0
    check_better_fast(xd, cm, &rev_mv, best_mv, mv_limits, var_params,
2811
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2812
0
                      is_scaled);
2813
0
  }
2814
0
}
2815
2816
// Combines first level check and second level check when applicable. This first
2817
// searches the four cardinal directions, and perform several
2818
// diagonal/chess-pattern searches in the best quadrant.
2819
static AOM_FORCE_INLINE void two_level_checks_fast(
2820
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, MV *best_mv,
2821
    int hstep, const SubpelMvLimits *mv_limits,
2822
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2823
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2824
0
    unsigned int *sse1, int *distortion, int iters, int is_scaled) {
2825
0
  const MV diag_step = first_level_check_fast(
2826
0
      xd, cm, this_mv, best_mv, hstep, mv_limits, var_params, mv_cost_params,
2827
0
      besterr, sse1, distortion, is_scaled);
2828
0
  if (iters > 1) {
2829
0
    second_level_check_fast(xd, cm, this_mv, diag_step, best_mv, hstep,
2830
0
                            mv_limits, var_params, mv_cost_params, besterr,
2831
0
                            sse1, distortion, is_scaled);
2832
0
  }
2833
0
}
2834
2835
static AOM_FORCE_INLINE MV
2836
first_level_check(MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv,
2837
                  MV *best_mv, const int hstep, const SubpelMvLimits *mv_limits,
2838
                  const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2839
                  const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2840
0
                  unsigned int *sse1, int *distortion) {
2841
0
  int dummy = 0;
2842
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
2843
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
2844
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
2845
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
2846
2847
0
  const unsigned int left =
2848
0
      check_better(xd, cm, &left_mv, best_mv, mv_limits, var_params,
2849
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2850
0
  const unsigned int right =
2851
0
      check_better(xd, cm, &right_mv, best_mv, mv_limits, var_params,
2852
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2853
0
  const unsigned int up =
2854
0
      check_better(xd, cm, &top_mv, best_mv, mv_limits, var_params,
2855
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2856
0
  const unsigned int down =
2857
0
      check_better(xd, cm, &bottom_mv, best_mv, mv_limits, var_params,
2858
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2859
2860
0
  const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
2861
0
  const MV diag_mv = { this_mv.row + diag_step.row,
2862
0
                       this_mv.col + diag_step.col };
2863
2864
  // Check the diagonal direction with the best mv
2865
0
  check_better(xd, cm, &diag_mv, best_mv, mv_limits, var_params, mv_cost_params,
2866
0
               besterr, sse1, distortion, &dummy);
2867
2868
0
  return diag_step;
2869
0
}
2870
2871
// A newer version of second level check that gives better quality.
2872
// TODO(chiyotsai@google.com): evaluate this on subpel_search_types different
2873
// from av1_find_best_sub_pixel_tree
2874
static AOM_FORCE_INLINE void second_level_check_v2(
2875
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV diag_step,
2876
    MV *best_mv, const SubpelMvLimits *mv_limits,
2877
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2878
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2879
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2880
0
  assert(best_mv->row == this_mv.row + diag_step.row ||
2881
0
         best_mv->col == this_mv.col + diag_step.col);
2882
0
  if (CHECK_MV_EQUAL(this_mv, *best_mv)) {
2883
0
    return;
2884
0
  } else if (this_mv.row == best_mv->row) {
2885
    // Search away from diagonal step since diagonal search did not provide any
2886
    // improvement
2887
0
    diag_step.row *= -1;
2888
0
  } else if (this_mv.col == best_mv->col) {
2889
0
    diag_step.col *= -1;
2890
0
  }
2891
2892
0
  const MV row_bias_mv = { best_mv->row + diag_step.row, best_mv->col };
2893
0
  const MV col_bias_mv = { best_mv->row, best_mv->col + diag_step.col };
2894
0
  const MV diag_bias_mv = { best_mv->row + diag_step.row,
2895
0
                            best_mv->col + diag_step.col };
2896
0
  int has_better_mv = 0;
2897
2898
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
2899
0
    check_better(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
2900
0
                 mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2901
0
    check_better(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
2902
0
                 mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2903
2904
    // Do an additional search if the second iteration gives a better mv
2905
0
    if (has_better_mv) {
2906
0
      check_better(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
2907
0
                   mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2908
0
    }
2909
0
  } else {
2910
0
    check_better_fast(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
2911
0
                      mv_cost_params, besterr, sse1, distortion, &has_better_mv,
2912
0
                      is_scaled);
2913
0
    check_better_fast(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
2914
0
                      mv_cost_params, besterr, sse1, distortion, &has_better_mv,
2915
0
                      is_scaled);
2916
2917
    // Do an additional search if the second iteration gives a better mv
2918
0
    if (has_better_mv) {
2919
0
      check_better_fast(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
2920
0
                        mv_cost_params, besterr, sse1, distortion,
2921
0
                        &has_better_mv, is_scaled);
2922
0
    }
2923
0
  }
2924
0
}
2925
2926
// Gets the error at the beginning when the mv has fullpel precision
2927
static unsigned int setup_center_error(
2928
    const MACROBLOCKD *xd, const MV *bestmv,
2929
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2930
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
2931
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2932
0
  const int w = var_params->w;
2933
0
  const int h = var_params->h;
2934
2935
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2936
0
  const uint8_t *src = ms_buffers->src->buf;
2937
0
  const uint8_t *y = get_buf_from_mv(ms_buffers->ref, *bestmv);
2938
0
  const int src_stride = ms_buffers->src->stride;
2939
0
  const int y_stride = ms_buffers->ref->stride;
2940
0
  const uint8_t *second_pred = ms_buffers->second_pred;
2941
0
  const uint8_t *mask = ms_buffers->mask;
2942
0
  const int mask_stride = ms_buffers->mask_stride;
2943
0
  const int invert_mask = ms_buffers->inv_mask;
2944
2945
0
  unsigned int besterr;
2946
2947
0
  if (second_pred != NULL) {
2948
0
#if CONFIG_AV1_HIGHBITDEPTH
2949
0
    if (is_cur_buf_hbd(xd)) {
2950
0
      DECLARE_ALIGNED(16, uint16_t, comp_pred16[MAX_SB_SQUARE]);
2951
0
      uint8_t *comp_pred = CONVERT_TO_BYTEPTR(comp_pred16);
2952
0
      if (mask) {
2953
0
        aom_highbd_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride,
2954
0
                                  mask, mask_stride, invert_mask);
2955
0
      } else {
2956
0
        aom_highbd_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2957
0
      }
2958
0
      besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2959
0
    } else {
2960
0
      DECLARE_ALIGNED(16, uint8_t, comp_pred[MAX_SB_SQUARE]);
2961
0
      if (mask) {
2962
0
        aom_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride, mask,
2963
0
                           mask_stride, invert_mask);
2964
0
      } else {
2965
0
        aom_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2966
0
      }
2967
0
      besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2968
0
    }
2969
#else
2970
    (void)xd;
2971
    DECLARE_ALIGNED(16, uint8_t, comp_pred[MAX_SB_SQUARE]);
2972
    if (mask) {
2973
      aom_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride, mask,
2974
                         mask_stride, invert_mask);
2975
    } else {
2976
      aom_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2977
    }
2978
    besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2979
#endif
2980
0
  } else {
2981
0
    besterr = vfp->vf(y, y_stride, src, src_stride, sse1);
2982
0
  }
2983
0
  *distortion = besterr;
2984
0
  besterr += mv_err_cost_(bestmv, mv_cost_params);
2985
0
  return besterr;
2986
0
}
2987
2988
// Gets the error at the beginning when the mv has fullpel precision
2989
static unsigned int upsampled_setup_center_error(
2990
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV *bestmv,
2991
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2992
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
2993
0
  unsigned int besterr = upsampled_pref_error(xd, cm, bestmv, var_params, sse1);
2994
0
  *distortion = besterr;
2995
0
  besterr += mv_err_cost_(bestmv, mv_cost_params);
2996
0
  return besterr;
2997
0
}
2998
2999
0
static inline int divide_and_round(int n, int d) {
3000
0
  return ((n < 0) ^ (d < 0)) ? ((n - d / 2) / d) : ((n + d / 2) / d);
3001
0
}
3002
3003
0
static inline int is_cost_list_wellbehaved(const int *cost_list) {
3004
0
  return cost_list[0] < cost_list[1] && cost_list[0] < cost_list[2] &&
3005
0
         cost_list[0] < cost_list[3] && cost_list[0] < cost_list[4];
3006
0
}
3007
3008
// Returns surface minima estimate at given precision in 1/2^n bits.
3009
// Assume a model for the cost surface: S = A(x - x0)^2 + B(y - y0)^2 + C
3010
// For a given set of costs S0, S1, S2, S3, S4 at points
3011
// (y, x) = (0, 0), (0, -1), (1, 0), (0, 1) and (-1, 0) respectively,
3012
// the solution for the location of the minima (x0, y0) is given by:
3013
// x0 = 1/2 (S1 - S3)/(S1 + S3 - 2*S0),
3014
// y0 = 1/2 (S4 - S2)/(S4 + S2 - 2*S0).
3015
// The code below is an integerized version of that.
3016
static inline void get_cost_surf_min(const int *cost_list, int *ir, int *ic,
3017
0
                                     int bits) {
3018
0
  *ic = divide_and_round((cost_list[1] - cost_list[3]) * (1 << (bits - 1)),
3019
0
                         (cost_list[1] - 2 * cost_list[0] + cost_list[3]));
3020
0
  *ir = divide_and_round((cost_list[4] - cost_list[2]) * (1 << (bits - 1)),
3021
0
                         (cost_list[4] - 2 * cost_list[0] + cost_list[2]));
3022
0
}
3023
3024
// Checks the list of mvs searched in the last iteration and see if we are
3025
// repeating it. If so, return 1. Otherwise we update the last_mv_search_list
3026
// with current_mv and return 0.
3027
static inline int check_repeated_mv_and_update(int_mv *last_mv_search_list,
3028
0
                                               const MV current_mv, int iter) {
3029
0
  if (last_mv_search_list) {
3030
0
    if (CHECK_MV_EQUAL(last_mv_search_list[iter].as_mv, current_mv)) {
3031
0
      return 1;
3032
0
    }
3033
3034
0
    last_mv_search_list[iter].as_mv = current_mv;
3035
0
  }
3036
0
  return 0;
3037
0
}
3038
3039
static inline int setup_center_error_facade(
3040
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *bestmv,
3041
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3042
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion,
3043
0
    int is_scaled) {
3044
0
  if (is_scaled) {
3045
0
    return upsampled_setup_center_error(xd, cm, bestmv, var_params,
3046
0
                                        mv_cost_params, sse1, distortion);
3047
0
  } else {
3048
0
    return setup_center_error(xd, bestmv, var_params, mv_cost_params, sse1,
3049
0
                              distortion);
3050
0
  }
3051
0
}
3052
3053
int av1_find_best_sub_pixel_tree_pruned_more(
3054
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3055
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3056
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3057
0
    unsigned int *sse1, int_mv *last_mv_search_list) {
3058
0
  (void)cm;
3059
0
  const int allow_hp = ms_params->allow_hp;
3060
0
  const int forced_stop = ms_params->forced_stop;
3061
0
  const int iters_per_step = ms_params->iters_per_step;
3062
0
  const int *cost_list = ms_params->cost_list;
3063
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3064
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3065
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3066
3067
  // The iteration we are current searching for. Iter 0 corresponds to fullpel
3068
  // mv, iter 1 to half pel, and so on
3069
0
  int iter = 0;
3070
0
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3071
0
  unsigned int besterr = INT_MAX;
3072
0
  *bestmv = start_mv;
3073
3074
0
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3075
0
                                             ? &cm->sf_identity
3076
0
                                             : xd->block_ref_scale_factors[0];
3077
0
  const int is_scaled = av1_is_scaled(sf);
3078
3079
0
  if (start_mv_stats != NULL && !is_scaled) {
3080
0
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3081
0
    *distortion = start_mv_stats->distortion;
3082
0
    *sse1 = start_mv_stats->sse;
3083
0
  } else {
3084
0
    besterr =
3085
0
        setup_center_error_facade(xd, cm, bestmv, var_params, mv_cost_params,
3086
0
                                  sse1, distortion, is_scaled);
3087
0
  }
3088
3089
  // If forced_stop is FULL_PEL, return.
3090
0
  if (forced_stop == FULL_PEL) return besterr;
3091
3092
0
  if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3093
0
    return INT_MAX;
3094
0
  }
3095
0
  iter++;
3096
3097
0
  if (cost_list && cost_list[0] != INT_MAX && cost_list[1] != INT_MAX &&
3098
0
      cost_list[2] != INT_MAX && cost_list[3] != INT_MAX &&
3099
0
      cost_list[4] != INT_MAX && is_cost_list_wellbehaved(cost_list)) {
3100
0
    int ir, ic;
3101
0
    get_cost_surf_min(cost_list, &ir, &ic, 1);
3102
0
    if (ir != 0 || ic != 0) {
3103
0
      const MV this_mv = { start_mv.row + ir * hstep,
3104
0
                           start_mv.col + ic * hstep };
3105
0
      int dummy = 0;
3106
0
      check_better_fast(xd, cm, &this_mv, bestmv, mv_limits, var_params,
3107
0
                        mv_cost_params, &besterr, sse1, distortion, &dummy,
3108
0
                        is_scaled);
3109
0
    }
3110
0
  } else {
3111
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3112
0
                          var_params, mv_cost_params, &besterr, sse1,
3113
0
                          distortion, iters_per_step, is_scaled);
3114
0
  }
3115
3116
  // Each subsequent iteration checks at least one point in common with
3117
  // the last iteration could be 2 ( if diag selected) 1/4 pel
3118
0
  if (forced_stop < HALF_PEL) {
3119
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3120
0
      return INT_MAX;
3121
0
    }
3122
0
    iter++;
3123
3124
0
    hstep >>= 1;
3125
0
    start_mv = *bestmv;
3126
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3127
0
                          var_params, mv_cost_params, &besterr, sse1,
3128
0
                          distortion, iters_per_step, is_scaled);
3129
0
  }
3130
3131
0
  if (allow_hp && forced_stop == EIGHTH_PEL) {
3132
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3133
0
      return INT_MAX;
3134
0
    }
3135
0
    iter++;
3136
3137
0
    hstep >>= 1;
3138
0
    start_mv = *bestmv;
3139
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3140
0
                          var_params, mv_cost_params, &besterr, sse1,
3141
0
                          distortion, iters_per_step, is_scaled);
3142
0
  }
3143
3144
0
  return besterr;
3145
0
}
3146
3147
int av1_find_best_sub_pixel_tree_pruned(
3148
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3149
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3150
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3151
0
    unsigned int *sse1, int_mv *last_mv_search_list) {
3152
0
  (void)cm;
3153
0
  (void)start_mv_stats;
3154
0
  const int allow_hp = ms_params->allow_hp;
3155
0
  const int forced_stop = ms_params->forced_stop;
3156
0
  const int iters_per_step = ms_params->iters_per_step;
3157
0
  const int *cost_list = ms_params->cost_list;
3158
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3159
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3160
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3161
3162
  // The iteration we are current searching for. Iter 0 corresponds to fullpel
3163
  // mv, iter 1 to half pel, and so on
3164
0
  int iter = 0;
3165
0
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3166
0
  unsigned int besterr = INT_MAX;
3167
0
  *bestmv = start_mv;
3168
3169
0
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3170
0
                                             ? &cm->sf_identity
3171
0
                                             : xd->block_ref_scale_factors[0];
3172
0
  const int is_scaled = av1_is_scaled(sf);
3173
3174
0
  if (start_mv_stats != NULL && !is_scaled) {
3175
0
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3176
0
    *distortion = start_mv_stats->distortion;
3177
0
    *sse1 = start_mv_stats->sse;
3178
0
  } else {
3179
0
    besterr =
3180
0
        setup_center_error_facade(xd, cm, bestmv, var_params, mv_cost_params,
3181
0
                                  sse1, distortion, is_scaled);
3182
0
  }
3183
3184
  // If forced_stop is FULL_PEL, return.
3185
0
  if (forced_stop == FULL_PEL) return besterr;
3186
3187
0
  if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3188
0
    return INT_MAX;
3189
0
  }
3190
0
  iter++;
3191
3192
0
  if (cost_list && cost_list[0] != INT_MAX && cost_list[1] != INT_MAX &&
3193
0
      cost_list[2] != INT_MAX && cost_list[3] != INT_MAX &&
3194
0
      cost_list[4] != INT_MAX) {
3195
0
    const unsigned int whichdir = (cost_list[1] < cost_list[3] ? 0 : 1) +
3196
0
                                  (cost_list[2] < cost_list[4] ? 0 : 2);
3197
3198
0
    const MV left_mv = { start_mv.row, start_mv.col - hstep };
3199
0
    const MV right_mv = { start_mv.row, start_mv.col + hstep };
3200
0
    const MV bottom_mv = { start_mv.row + hstep, start_mv.col };
3201
0
    const MV top_mv = { start_mv.row - hstep, start_mv.col };
3202
3203
0
    const MV bottom_left_mv = { start_mv.row + hstep, start_mv.col - hstep };
3204
0
    const MV bottom_right_mv = { start_mv.row + hstep, start_mv.col + hstep };
3205
0
    const MV top_left_mv = { start_mv.row - hstep, start_mv.col - hstep };
3206
0
    const MV top_right_mv = { start_mv.row - hstep, start_mv.col + hstep };
3207
3208
0
    int dummy = 0;
3209
3210
0
    switch (whichdir) {
3211
0
      case 0:  // bottom left quadrant
3212
0
        check_better_fast(xd, cm, &left_mv, bestmv, mv_limits, var_params,
3213
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3214
0
                          is_scaled);
3215
0
        check_better_fast(xd, cm, &bottom_mv, bestmv, mv_limits, var_params,
3216
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3217
0
                          is_scaled);
3218
0
        check_better_fast(xd, cm, &bottom_left_mv, bestmv, mv_limits,
3219
0
                          var_params, mv_cost_params, &besterr, sse1,
3220
0
                          distortion, &dummy, is_scaled);
3221
0
        break;
3222
0
      case 1:  // bottom right quadrant
3223
0
        check_better_fast(xd, cm, &right_mv, bestmv, mv_limits, var_params,
3224
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3225
0
                          is_scaled);
3226
0
        check_better_fast(xd, cm, &bottom_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_right_mv, bestmv, mv_limits,
3230
0
                          var_params, mv_cost_params, &besterr, sse1,
3231
0
                          distortion, &dummy, is_scaled);
3232
0
        break;
3233
0
      case 2:  // top left quadrant
3234
0
        check_better_fast(xd, cm, &left_mv, bestmv, mv_limits, var_params,
3235
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3236
0
                          is_scaled);
3237
0
        check_better_fast(xd, cm, &top_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, &top_left_mv, bestmv, mv_limits, var_params,
3241
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3242
0
                          is_scaled);
3243
0
        break;
3244
0
      case 3:  // top right quadrant
3245
0
        check_better_fast(xd, cm, &right_mv, bestmv, mv_limits, var_params,
3246
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3247
0
                          is_scaled);
3248
0
        check_better_fast(xd, cm, &top_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_right_mv, bestmv, mv_limits, var_params,
3252
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3253
0
                          is_scaled);
3254
0
        break;
3255
0
    }
3256
0
  } else {
3257
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3258
0
                          var_params, mv_cost_params, &besterr, sse1,
3259
0
                          distortion, iters_per_step, is_scaled);
3260
0
  }
3261
3262
  // Each subsequent iteration checks at least one point in common with
3263
  // the last iteration could be 2 ( if diag selected) 1/4 pel
3264
0
  if (forced_stop < HALF_PEL) {
3265
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3266
0
      return INT_MAX;
3267
0
    }
3268
0
    iter++;
3269
3270
0
    hstep >>= 1;
3271
0
    start_mv = *bestmv;
3272
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3273
0
                          var_params, mv_cost_params, &besterr, sse1,
3274
0
                          distortion, iters_per_step, is_scaled);
3275
0
  }
3276
3277
0
  if (allow_hp && forced_stop == EIGHTH_PEL) {
3278
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3279
0
      return INT_MAX;
3280
0
    }
3281
0
    iter++;
3282
3283
0
    hstep >>= 1;
3284
0
    start_mv = *bestmv;
3285
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3286
0
                          var_params, mv_cost_params, &besterr, sse1,
3287
0
                          distortion, iters_per_step, is_scaled);
3288
0
  }
3289
3290
0
  return besterr;
3291
0
}
3292
3293
int av1_find_best_sub_pixel_tree(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3294
                                 const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3295
                                 MV start_mv,
3296
                                 const FULLPEL_MV_STATS *start_mv_stats,
3297
                                 MV *bestmv, int *distortion,
3298
                                 unsigned int *sse1,
3299
0
                                 int_mv *last_mv_search_list) {
3300
0
  (void)start_mv_stats;
3301
0
  const int allow_hp = ms_params->allow_hp;
3302
0
  const int forced_stop = ms_params->forced_stop;
3303
0
  const int iters_per_step = ms_params->iters_per_step;
3304
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3305
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3306
0
  const SUBPEL_SEARCH_TYPE subpel_search_type =
3307
0
      ms_params->var_params.subpel_search_type;
3308
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3309
3310
  // How many steps to take. A round of 0 means fullpel search only, 1 means
3311
  // half-pel, and so on.
3312
0
  const int round = AOMMIN(FULL_PEL - forced_stop, 3 - !allow_hp);
3313
0
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3314
3315
0
  unsigned int besterr = INT_MAX;
3316
3317
0
  *bestmv = start_mv;
3318
3319
0
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3320
0
                                             ? &cm->sf_identity
3321
0
                                             : xd->block_ref_scale_factors[0];
3322
0
  const int is_scaled = av1_is_scaled(sf);
3323
3324
0
  if (start_mv_stats != NULL && !is_scaled) {
3325
0
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3326
0
    *distortion = start_mv_stats->distortion;
3327
0
    *sse1 = start_mv_stats->sse;
3328
0
  } else {
3329
0
    if (subpel_search_type != USE_2_TAPS_ORIG) {
3330
0
      besterr = upsampled_setup_center_error(xd, cm, bestmv, var_params,
3331
0
                                             mv_cost_params, sse1, distortion);
3332
0
    } else {
3333
0
      besterr = setup_center_error(xd, bestmv, var_params, mv_cost_params, sse1,
3334
0
                                   distortion);
3335
0
    }
3336
0
  }
3337
3338
  // If forced_stop is FULL_PEL, return.
3339
0
  if (!round) return besterr;
3340
3341
0
  for (int iter = 0; iter < round; ++iter) {
3342
0
    MV iter_center_mv = *bestmv;
3343
0
    if (check_repeated_mv_and_update(last_mv_search_list, iter_center_mv,
3344
0
                                     iter)) {
3345
0
      return INT_MAX;
3346
0
    }
3347
3348
0
    MV diag_step;
3349
0
    if (subpel_search_type != USE_2_TAPS_ORIG) {
3350
0
      diag_step = first_level_check(xd, cm, iter_center_mv, bestmv, hstep,
3351
0
                                    mv_limits, var_params, mv_cost_params,
3352
0
                                    &besterr, sse1, distortion);
3353
0
    } else {
3354
0
      diag_step = first_level_check_fast(xd, cm, iter_center_mv, bestmv, hstep,
3355
0
                                         mv_limits, var_params, mv_cost_params,
3356
0
                                         &besterr, sse1, distortion, is_scaled);
3357
0
    }
3358
3359
    // Check diagonal sub-pixel position
3360
0
    if (!CHECK_MV_EQUAL(iter_center_mv, *bestmv) && iters_per_step > 1) {
3361
0
      second_level_check_v2(xd, cm, iter_center_mv, diag_step, bestmv,
3362
0
                            mv_limits, var_params, mv_cost_params, &besterr,
3363
0
                            sse1, distortion, is_scaled);
3364
0
    }
3365
3366
0
    hstep >>= 1;
3367
0
  }
3368
3369
0
  return besterr;
3370
0
}
3371
3372
// Note(yunqingwang): The following 2 functions are only used in the motion
3373
// vector unit test, which return extreme motion vectors allowed by the MV
3374
// limits.
3375
// Returns the maximum MV.
3376
int av1_return_max_sub_pixel_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3377
                                const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3378
                                MV start_mv,
3379
                                const FULLPEL_MV_STATS *start_mv_stats,
3380
                                MV *bestmv, int *distortion, unsigned int *sse1,
3381
0
                                int_mv *last_mv_search_list) {
3382
0
  (void)xd;
3383
0
  (void)cm;
3384
0
  (void)start_mv;
3385
0
  (void)start_mv_stats;
3386
0
  (void)last_mv_search_list;
3387
3388
0
  const int allow_hp = ms_params->allow_hp;
3389
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3390
3391
0
  bestmv->row = mv_limits->row_max;
3392
0
  bestmv->col = mv_limits->col_max;
3393
3394
0
  unsigned int besterr = 0;
3395
3396
  // In the sub-pel motion search, if hp is not used, then the last bit of mv
3397
  // has to be 0.
3398
0
  lower_mv_precision(bestmv, allow_hp, 0);
3399
0
  *distortion = besterr;
3400
0
  *sse1 = besterr;
3401
0
  return besterr;
3402
0
}
3403
3404
// Returns the minimum MV.
3405
int av1_return_min_sub_pixel_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3406
                                const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3407
                                MV start_mv,
3408
                                const FULLPEL_MV_STATS *start_mv_stats,
3409
                                MV *bestmv, int *distortion, unsigned int *sse1,
3410
0
                                int_mv *last_mv_search_list) {
3411
0
  (void)xd;
3412
0
  (void)cm;
3413
0
  (void)start_mv;
3414
0
  (void)start_mv_stats;
3415
0
  (void)last_mv_search_list;
3416
3417
0
  const int allow_hp = ms_params->allow_hp;
3418
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3419
3420
0
  bestmv->row = mv_limits->row_min;
3421
0
  bestmv->col = mv_limits->col_min;
3422
3423
0
  unsigned int besterr = 0;
3424
  // In the sub-pel motion search, if hp is not used, then the last bit of mv
3425
  // has to be 0.
3426
0
  lower_mv_precision(bestmv, allow_hp, 0);
3427
0
  *distortion = besterr;
3428
0
  *sse1 = besterr;
3429
0
  return besterr;
3430
0
}
3431
3432
#if !CONFIG_REALTIME_ONLY
3433
// Computes the cost of the current predictor by going through the whole
3434
// av1_enc_build_inter_predictor pipeline. This is mainly used by warped mv
3435
// during motion_mode_rd. We are going through the whole
3436
// av1_enc_build_inter_predictor because we might have changed the interpolation
3437
// filter, etc before motion_mode_rd is called.
3438
static inline unsigned int compute_motion_cost(
3439
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3440
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, BLOCK_SIZE bsize,
3441
0
    const MV *this_mv) {
3442
0
  unsigned int mse;
3443
0
  unsigned int sse;
3444
0
  const int mi_row = xd->mi_row;
3445
0
  const int mi_col = xd->mi_col;
3446
3447
0
  av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
3448
0
                                AOM_PLANE_Y, AOM_PLANE_Y);
3449
3450
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3451
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3452
3453
0
  const uint8_t *const src = ms_buffers->src->buf;
3454
0
  const int src_stride = ms_buffers->src->stride;
3455
0
  const uint8_t *const dst = xd->plane[0].dst.buf;
3456
0
  const int dst_stride = xd->plane[0].dst.stride;
3457
0
  const aom_variance_fn_ptr_t *vfp = ms_params->var_params.vfp;
3458
3459
0
  mse = vfp->vf(dst, dst_stride, src, src_stride, &sse);
3460
0
  mse += mv_err_cost_(this_mv, &ms_params->mv_cost_params);
3461
0
  return mse;
3462
0
}
3463
3464
// Refines MV in a small range
3465
3466
// Macros to build bitmasks which help us avoid redundant computations
3467
//
3468
// To explain the idea here, imagine that on the first iteration of the
3469
// loop below, we step rightwards. Then, on the second iteration, the neighbors
3470
// to consider are:
3471
//     . . .
3472
//     0 1 .
3473
//     . . .
3474
// Where 0 is the initial search point, 1 is the best candidate found in the
3475
// first iteration, and the dots are the other neighbors of point 1.
3476
//
3477
// Naively, we would now need to scan all 8 neighbors of point 1 (point 0 and
3478
// the seven points marked with dots), and compare them to see where to move
3479
// next. However, we already evaluated 5 of those 8 neighbors in the last
3480
// iteration, and decided that they are worse than point 1. So we don't need
3481
// to re-consider these points. We only really need to consider the three
3482
// points which are adjacent to point 1 but *not* to point 0.
3483
//
3484
// As the algorithm goes on, there are other ways that redundant evaluations
3485
// can happen, if the search path curls back around on itself.
3486
//
3487
// To avoid all possible redundancies, we'd have to build a set containing
3488
// every point we have already checked, and this would be quite expensive.
3489
//
3490
// So instead, we apply a 95%-effective solution with a much lower overhead:
3491
// we prune out the points which were considered during the previous
3492
// iteration, but we don't worry about any prior iteration. This can be done
3493
// as follows:
3494
//
3495
// We build a static table, called neighbor_mask, which answers the question
3496
// "if we moved in direction X last time, which neighbors are new, and which
3497
//  were scanned last iteration?"
3498
// Then we can query this table to quickly determine which points we need to
3499
// evaluate, and which we can skip.
3500
//
3501
// To query the table, the logic is simply:
3502
// neighbor_mask[i] & (1 << j) == "if we moved in direction i last iteration,
3503
//                             do we need to scan neighbor j this iteration?"
3504
#define NEIGHBOR_MASK_DIA(left, down, right, up) \
3505
  (left | (down << 1) | (right << 2) | (up << 3))
3506
3507
#define NEIGHBOR_MASK_SQR(left, down, right, up, down_left, down_right, \
3508
                          up_left, up_right)                            \
3509
  (left | (down << 1) | (right << 2) | (up << 3) | (down_left << 4) |   \
3510
   (down_right << 5) | (up_left << 6) | (up_right << 7))
3511
3512
static const warp_search_config warp_search_info[WARP_SEARCH_METHODS] = {
3513
  // WARP_SEARCH_DIAMOND
3514
  {
3515
    .num_neighbors = 4,
3516
    .neighbors = { {  0, -1 }, {  1,  0 }, {  0,  1 }, { -1,  0 } },
3517
    .neighbor_mask = {
3518
      // If we stepped left last time, consider all points except right
3519
      NEIGHBOR_MASK_DIA(1, 1, 0, 1),
3520
      // If we stepped down last time, consider all points except up
3521
      NEIGHBOR_MASK_DIA(1, 1, 1, 0),
3522
      // Stepped right last time
3523
      NEIGHBOR_MASK_DIA(0, 1, 1, 1),
3524
      // Stepped up last time
3525
      NEIGHBOR_MASK_DIA(1, 0, 1, 1),
3526
    },
3527
  },
3528
  // WARP_SEARCH_SQUARE
3529
  {
3530
    .num_neighbors = 8,
3531
    .neighbors = { {  0, -1 }, {  1,  0 }, {  0,  1 }, { -1,  0 },
3532
                   {  1, -1 }, {  1,  1 }, { -1, -1 }, { -1,  1 } },
3533
    .neighbor_mask = {
3534
      // If we stepped left last time, then we only need to consider 3 points:
3535
      // left, down+left, up+left
3536
      NEIGHBOR_MASK_SQR(1, 0, 0, 0, 1, 0, 1, 0),
3537
      // If we stepped down last time, then we only need to consider 3 points:
3538
      // down, down+left, down+right
3539
      NEIGHBOR_MASK_SQR(0, 1, 0, 0, 1, 1, 0, 0),
3540
      // Stepped right last time
3541
      NEIGHBOR_MASK_SQR(0, 0, 1, 0, 0, 1, 0, 1),
3542
      // Stepped up last time
3543
      NEIGHBOR_MASK_SQR(0, 0, 0, 1, 0, 0, 1, 1),
3544
3545
      // If we stepped down+left last time, then we need to consider 5 points:
3546
      // left, down, down+left, down+right, up+left
3547
      NEIGHBOR_MASK_SQR(1, 1, 0, 0, 1, 1, 1, 0),
3548
      // Stepped down+right last time
3549
      NEIGHBOR_MASK_SQR(0, 1, 1, 0, 1, 1, 0, 1),
3550
      // Stepped up+left last time
3551
      NEIGHBOR_MASK_SQR(1, 0, 0, 1, 1, 0, 1, 1),
3552
      // Stepped up+right last time
3553
      NEIGHBOR_MASK_SQR(0, 0, 1, 1, 0, 1, 1, 1),
3554
    },
3555
  },
3556
};
3557
3558
unsigned int av1_refine_warped_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3559
                                  const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3560
                                  BLOCK_SIZE bsize, const int *pts0,
3561
                                  const int *pts_inref0, int total_samples,
3562
                                  WARP_SEARCH_METHOD search_method,
3563
0
                                  int num_iterations) {
3564
0
  MB_MODE_INFO *mbmi = xd->mi[0];
3565
3566
0
  const MV *neighbors = warp_search_info[search_method].neighbors;
3567
0
  const int num_neighbors = warp_search_info[search_method].num_neighbors;
3568
0
  const uint8_t *neighbor_mask = warp_search_info[search_method].neighbor_mask;
3569
3570
0
  MV *best_mv = &mbmi->mv[0].as_mv;
3571
3572
0
  WarpedMotionParams best_wm_params = mbmi->wm_params;
3573
0
  int best_num_proj_ref = mbmi->num_proj_ref;
3574
0
  unsigned int bestmse;
3575
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3576
3577
0
  const int mv_shift = ms_params->allow_hp ? 0 : 1;
3578
3579
  // Calculate the center position's error
3580
0
  assert(av1_is_subpelmv_in_range(mv_limits, *best_mv));
3581
0
  bestmse = compute_motion_cost(xd, cm, ms_params, bsize, best_mv);
3582
3583
  // MV search
3584
0
  int pts[SAMPLES_ARRAY_SIZE], pts_inref[SAMPLES_ARRAY_SIZE];
3585
0
  const int mi_row = xd->mi_row;
3586
0
  const int mi_col = xd->mi_col;
3587
3588
  // First step always scans all neighbors
3589
0
  uint8_t valid_neighbors = UINT8_MAX;
3590
3591
0
  for (int ite = 0; ite < num_iterations; ++ite) {
3592
0
    int best_idx = -1;
3593
3594
0
    for (int idx = 0; idx < num_neighbors; ++idx) {
3595
0
      if ((valid_neighbors & (1 << idx)) == 0) {
3596
0
        continue;
3597
0
      }
3598
3599
0
      unsigned int thismse;
3600
3601
0
      MV this_mv = { best_mv->row + neighbors[idx].row * (1 << mv_shift),
3602
0
                     best_mv->col + neighbors[idx].col * (1 << mv_shift) };
3603
0
      if (av1_is_subpelmv_in_range(mv_limits, this_mv)) {
3604
0
        memcpy(pts, pts0, total_samples * 2 * sizeof(*pts0));
3605
0
        memcpy(pts_inref, pts_inref0, total_samples * 2 * sizeof(*pts_inref0));
3606
0
        if (total_samples > 1) {
3607
0
          mbmi->num_proj_ref =
3608
0
              av1_selectSamples(&this_mv, pts, pts_inref, total_samples, bsize);
3609
0
        }
3610
3611
0
        if (!av1_find_projection(mbmi->num_proj_ref, pts, pts_inref, bsize,
3612
0
                                 this_mv.row, this_mv.col, &mbmi->wm_params,
3613
0
                                 mi_row, mi_col)) {
3614
0
          thismse = compute_motion_cost(xd, cm, ms_params, bsize, &this_mv);
3615
3616
0
          if (thismse < bestmse) {
3617
0
            best_idx = idx;
3618
0
            best_wm_params = mbmi->wm_params;
3619
0
            best_num_proj_ref = mbmi->num_proj_ref;
3620
0
            bestmse = thismse;
3621
0
          }
3622
0
        }
3623
0
      }
3624
0
    }
3625
3626
0
    if (best_idx == -1) break;
3627
3628
0
    if (best_idx >= 0) {
3629
0
      best_mv->row += neighbors[best_idx].row * (1 << mv_shift);
3630
0
      best_mv->col += neighbors[best_idx].col * (1 << mv_shift);
3631
0
      valid_neighbors = neighbor_mask[best_idx];
3632
0
    }
3633
0
  }
3634
3635
0
  mbmi->wm_params = best_wm_params;
3636
0
  mbmi->num_proj_ref = best_num_proj_ref;
3637
0
  return bestmse;
3638
0
}
3639
3640
#endif  // !CONFIG_REALTIME_ONLY
3641
// =============================================================================
3642
//  Subpixel Motion Search: OBMC
3643
// =============================================================================
3644
// Estimates the variance of prediction residue
3645
static inline int estimate_obmc_pref_error(
3646
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3647
0
    unsigned int *sse) {
3648
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
3649
3650
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3651
0
  const int32_t *src = ms_buffers->wsrc;
3652
0
  const int32_t *mask = ms_buffers->obmc_mask;
3653
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
3654
0
  const int ref_stride = ms_buffers->ref->stride;
3655
3656
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
3657
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
3658
3659
0
  return vfp->osvf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, mask, sse);
3660
0
}
3661
3662
// Calculates the variance of prediction residue
3663
static int upsampled_obmc_pref_error(MACROBLOCKD *xd, const AV1_COMMON *cm,
3664
                                     const MV *this_mv,
3665
                                     const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3666
0
                                     unsigned int *sse) {
3667
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
3668
0
  const SUBPEL_SEARCH_TYPE subpel_search_type = var_params->subpel_search_type;
3669
0
  const int w = var_params->w;
3670
0
  const int h = var_params->h;
3671
3672
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3673
0
  const int32_t *wsrc = ms_buffers->wsrc;
3674
0
  const int32_t *mask = ms_buffers->obmc_mask;
3675
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
3676
0
  const int ref_stride = ms_buffers->ref->stride;
3677
3678
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
3679
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
3680
3681
0
  const int mi_row = xd->mi_row;
3682
0
  const int mi_col = xd->mi_col;
3683
3684
0
  unsigned int besterr;
3685
0
  DECLARE_ALIGNED(16, uint8_t, pred[2 * MAX_SB_SQUARE]);
3686
0
#if CONFIG_AV1_HIGHBITDEPTH
3687
0
  if (is_cur_buf_hbd(xd)) {
3688
0
    uint8_t *pred8 = CONVERT_TO_BYTEPTR(pred);
3689
0
    aom_highbd_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred8, w, h,
3690
0
                              subpel_x_q3, subpel_y_q3, ref, ref_stride, xd->bd,
3691
0
                              subpel_search_type);
3692
0
    besterr = vfp->ovf(pred8, w, wsrc, mask, sse);
3693
0
  } else {
3694
0
    aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
3695
0
                       subpel_y_q3, ref, ref_stride, subpel_search_type);
3696
3697
0
    besterr = vfp->ovf(pred, w, wsrc, mask, sse);
3698
0
  }
3699
#else
3700
  aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
3701
                     subpel_y_q3, ref, ref_stride, subpel_search_type);
3702
3703
  besterr = vfp->ovf(pred, w, wsrc, mask, sse);
3704
#endif
3705
0
  return besterr;
3706
0
}
3707
3708
static unsigned int setup_obmc_center_error(
3709
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3710
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
3711
  // TODO(chiyotsai@google.com): There might be a bug here where we didn't use
3712
  // get_buf_from_mv(ref, *this_mv).
3713
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3714
0
  const int32_t *wsrc = ms_buffers->wsrc;
3715
0
  const int32_t *mask = ms_buffers->obmc_mask;
3716
0
  const uint8_t *ref = ms_buffers->ref->buf;
3717
0
  const int ref_stride = ms_buffers->ref->stride;
3718
0
  unsigned int besterr =
3719
0
      var_params->vfp->ovf(ref, ref_stride, wsrc, mask, sse1);
3720
0
  *distortion = besterr;
3721
0
  besterr += mv_err_cost_(this_mv, mv_cost_params);
3722
0
  return besterr;
3723
0
}
3724
3725
static unsigned int upsampled_setup_obmc_center_error(
3726
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV *this_mv,
3727
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3728
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
3729
0
  unsigned int besterr =
3730
0
      upsampled_obmc_pref_error(xd, cm, this_mv, var_params, sse1);
3731
0
  *distortion = besterr;
3732
0
  besterr += mv_err_cost_(this_mv, mv_cost_params);
3733
0
  return besterr;
3734
0
}
3735
3736
// Estimates the variance of prediction residue
3737
// TODO(chiyotsai@google.com): the cost does does not match the cost in
3738
// mv_cost_. Investigate this later.
3739
static inline int estimate_obmc_mvcost(const MV *this_mv,
3740
0
                                       const MV_COST_PARAMS *mv_cost_params) {
3741
0
  const MV *ref_mv = mv_cost_params->ref_mv;
3742
0
  const int *mvjcost = mv_cost_params->mvjcost;
3743
0
  const int *const *mvcost = mv_cost_params->mvcost;
3744
0
  const int error_per_bit = mv_cost_params->error_per_bit;
3745
0
  const MV_COST_TYPE mv_cost_type = mv_cost_params->mv_cost_type;
3746
0
  const MV diff_mv = { GET_MV_SUBPEL(this_mv->row - ref_mv->row),
3747
0
                       GET_MV_SUBPEL(this_mv->col - ref_mv->col) };
3748
3749
0
  switch (mv_cost_type) {
3750
0
    case MV_COST_ENTROPY:
3751
0
      return (unsigned)((mv_cost(&diff_mv, mvjcost,
3752
0
                                 CONVERT_TO_CONST_MVCOST(mvcost)) *
3753
0
                             error_per_bit +
3754
0
                         4096) >>
3755
0
                        13);
3756
0
    case MV_COST_NONE: return 0;
3757
0
    default:
3758
0
      assert(0 && "L1 norm is not tuned for estimated obmc mvcost");
3759
0
      return 0;
3760
0
  }
3761
0
}
3762
3763
// Estimates whether this_mv is better than best_mv. This function incorporates
3764
// both prediction error and residue into account.
3765
static inline unsigned int obmc_check_better_fast(
3766
    const MV *this_mv, MV *best_mv, const SubpelMvLimits *mv_limits,
3767
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3768
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3769
0
    unsigned int *sse1, int *distortion, int *has_better_mv) {
3770
0
  unsigned int cost;
3771
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
3772
0
    unsigned int sse;
3773
0
    const int thismse = estimate_obmc_pref_error(this_mv, var_params, &sse);
3774
3775
0
    cost = estimate_obmc_mvcost(this_mv, mv_cost_params);
3776
0
    cost += thismse;
3777
3778
0
    if (cost < *besterr) {
3779
0
      *besterr = cost;
3780
0
      *best_mv = *this_mv;
3781
0
      *distortion = thismse;
3782
0
      *sse1 = sse;
3783
0
      *has_better_mv |= 1;
3784
0
    }
3785
0
  } else {
3786
0
    cost = INT_MAX;
3787
0
  }
3788
0
  return cost;
3789
0
}
3790
3791
// Estimates whether this_mv is better than best_mv. This function incorporates
3792
// both prediction error and residue into account.
3793
static inline unsigned int obmc_check_better(
3794
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
3795
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3796
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3797
0
    unsigned int *sse1, int *distortion, int *has_better_mv) {
3798
0
  unsigned int cost;
3799
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
3800
0
    unsigned int sse;
3801
0
    const int thismse =
3802
0
        upsampled_obmc_pref_error(xd, cm, this_mv, var_params, &sse);
3803
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
3804
3805
0
    cost += thismse;
3806
3807
0
    if (cost < *besterr) {
3808
0
      *besterr = cost;
3809
0
      *best_mv = *this_mv;
3810
0
      *distortion = thismse;
3811
0
      *sse1 = sse;
3812
0
      *has_better_mv |= 1;
3813
0
    }
3814
0
  } else {
3815
0
    cost = INT_MAX;
3816
0
  }
3817
0
  return cost;
3818
0
}
3819
3820
static AOM_FORCE_INLINE MV obmc_first_level_check(
3821
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV *best_mv,
3822
    const int hstep, const SubpelMvLimits *mv_limits,
3823
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3824
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3825
0
    unsigned int *sse1, int *distortion) {
3826
0
  int dummy = 0;
3827
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
3828
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
3829
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
3830
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
3831
3832
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
3833
0
    const unsigned int left =
3834
0
        obmc_check_better(xd, cm, &left_mv, best_mv, mv_limits, var_params,
3835
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3836
0
    const unsigned int right =
3837
0
        obmc_check_better(xd, cm, &right_mv, best_mv, mv_limits, var_params,
3838
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3839
0
    const unsigned int up =
3840
0
        obmc_check_better(xd, cm, &top_mv, best_mv, mv_limits, var_params,
3841
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3842
0
    const unsigned int down =
3843
0
        obmc_check_better(xd, cm, &bottom_mv, best_mv, mv_limits, var_params,
3844
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3845
3846
0
    const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
3847
0
    const MV diag_mv = { this_mv.row + diag_step.row,
3848
0
                         this_mv.col + diag_step.col };
3849
3850
    // Check the diagonal direction with the best mv
3851
0
    obmc_check_better(xd, cm, &diag_mv, best_mv, mv_limits, var_params,
3852
0
                      mv_cost_params, besterr, sse1, distortion, &dummy);
3853
3854
0
    return diag_step;
3855
0
  } else {
3856
0
    const unsigned int left = obmc_check_better_fast(
3857
0
        &left_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr, sse1,
3858
0
        distortion, &dummy);
3859
0
    const unsigned int right = obmc_check_better_fast(
3860
0
        &right_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
3861
0
        sse1, distortion, &dummy);
3862
3863
0
    const unsigned int up = obmc_check_better_fast(
3864
0
        &top_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr, sse1,
3865
0
        distortion, &dummy);
3866
3867
0
    const unsigned int down = obmc_check_better_fast(
3868
0
        &bottom_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
3869
0
        sse1, distortion, &dummy);
3870
3871
0
    const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
3872
0
    const MV diag_mv = { this_mv.row + diag_step.row,
3873
0
                         this_mv.col + diag_step.col };
3874
3875
    // Check the diagonal direction with the best mv
3876
0
    obmc_check_better_fast(&diag_mv, best_mv, mv_limits, var_params,
3877
0
                           mv_cost_params, besterr, sse1, distortion, &dummy);
3878
3879
0
    return diag_step;
3880
0
  }
3881
0
}
3882
3883
// A newer version of second level check for obmc that gives better quality.
3884
static AOM_FORCE_INLINE void obmc_second_level_check_v2(
3885
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV diag_step,
3886
    MV *best_mv, const SubpelMvLimits *mv_limits,
3887
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3888
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3889
0
    unsigned int *sse1, int *distortion) {
3890
0
  assert(best_mv->row == this_mv.row + diag_step.row ||
3891
0
         best_mv->col == this_mv.col + diag_step.col);
3892
0
  if (CHECK_MV_EQUAL(this_mv, *best_mv)) {
3893
0
    return;
3894
0
  } else if (this_mv.row == best_mv->row) {
3895
    // Search away from diagonal step since diagonal search did not provide any
3896
    // improvement
3897
0
    diag_step.row *= -1;
3898
0
  } else if (this_mv.col == best_mv->col) {
3899
0
    diag_step.col *= -1;
3900
0
  }
3901
3902
0
  const MV row_bias_mv = { best_mv->row + diag_step.row, best_mv->col };
3903
0
  const MV col_bias_mv = { best_mv->row, best_mv->col + diag_step.col };
3904
0
  const MV diag_bias_mv = { best_mv->row + diag_step.row,
3905
0
                            best_mv->col + diag_step.col };
3906
0
  int has_better_mv = 0;
3907
3908
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
3909
0
    obmc_check_better(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
3910
0
                      mv_cost_params, besterr, sse1, distortion,
3911
0
                      &has_better_mv);
3912
0
    obmc_check_better(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
3913
0
                      mv_cost_params, besterr, sse1, distortion,
3914
0
                      &has_better_mv);
3915
3916
    // Do an additional search if the second iteration gives a better mv
3917
0
    if (has_better_mv) {
3918
0
      obmc_check_better(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
3919
0
                        mv_cost_params, besterr, sse1, distortion,
3920
0
                        &has_better_mv);
3921
0
    }
3922
0
  } else {
3923
0
    obmc_check_better_fast(&row_bias_mv, best_mv, mv_limits, var_params,
3924
0
                           mv_cost_params, besterr, sse1, distortion,
3925
0
                           &has_better_mv);
3926
0
    obmc_check_better_fast(&col_bias_mv, best_mv, mv_limits, var_params,
3927
0
                           mv_cost_params, besterr, sse1, distortion,
3928
0
                           &has_better_mv);
3929
3930
    // Do an additional search if the second iteration gives a better mv
3931
0
    if (has_better_mv) {
3932
0
      obmc_check_better_fast(&diag_bias_mv, best_mv, mv_limits, var_params,
3933
0
                             mv_cost_params, besterr, sse1, distortion,
3934
0
                             &has_better_mv);
3935
0
    }
3936
0
  }
3937
0
}
3938
3939
int av1_find_best_obmc_sub_pixel_tree_up(
3940
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3941
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3942
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3943
0
    unsigned int *sse1, int_mv *last_mv_search_list) {
3944
0
  (void)last_mv_search_list;
3945
0
  (void)start_mv_stats;
3946
0
  const int allow_hp = ms_params->allow_hp;
3947
0
  const int forced_stop = ms_params->forced_stop;
3948
0
  const int iters_per_step = ms_params->iters_per_step;
3949
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3950
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3951
0
  const SUBPEL_SEARCH_TYPE subpel_search_type =
3952
0
      ms_params->var_params.subpel_search_type;
3953
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3954
3955
0
  int hstep = INIT_SUBPEL_STEP_SIZE;
3956
0
  const int round = AOMMIN(FULL_PEL - forced_stop, 3 - !allow_hp);
3957
3958
0
  unsigned int besterr = INT_MAX;
3959
0
  *bestmv = start_mv;
3960
3961
0
  if (subpel_search_type != USE_2_TAPS_ORIG)
3962
0
    besterr = upsampled_setup_obmc_center_error(
3963
0
        xd, cm, bestmv, var_params, mv_cost_params, sse1, distortion);
3964
0
  else
3965
0
    besterr = setup_obmc_center_error(bestmv, var_params, mv_cost_params, sse1,
3966
0
                                      distortion);
3967
3968
0
  for (int iter = 0; iter < round; ++iter) {
3969
0
    MV iter_center_mv = *bestmv;
3970
0
    MV diag_step = obmc_first_level_check(xd, cm, iter_center_mv, bestmv, hstep,
3971
0
                                          mv_limits, var_params, mv_cost_params,
3972
0
                                          &besterr, sse1, distortion);
3973
3974
0
    if (!CHECK_MV_EQUAL(iter_center_mv, *bestmv) && iters_per_step > 1) {
3975
0
      obmc_second_level_check_v2(xd, cm, iter_center_mv, diag_step, bestmv,
3976
0
                                 mv_limits, var_params, mv_cost_params,
3977
0
                                 &besterr, sse1, distortion);
3978
0
    }
3979
0
    hstep >>= 1;
3980
0
  }
3981
3982
0
  return besterr;
3983
0
}
3984
3985
// =============================================================================
3986
//  Public cost function: mv_cost + pred error
3987
// =============================================================================
3988
int av1_get_mvpred_sse(const MV_COST_PARAMS *mv_cost_params,
3989
                       const FULLPEL_MV best_mv,
3990
                       const aom_variance_fn_ptr_t *vfp,
3991
0
                       const struct buf_2d *src, const struct buf_2d *pre) {
3992
0
  const MV mv = get_mv_from_fullmv(&best_mv);
3993
0
  unsigned int sse, var;
3994
3995
0
  var = vfp->vf(src->buf, src->stride, get_buf_from_fullmv(pre, &best_mv),
3996
0
                pre->stride, &sse);
3997
0
  (void)var;
3998
3999
0
  return sse + mv_err_cost_(&mv, mv_cost_params);
4000
0
}