Coverage Report

Created: 2026-10-28 07:26

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