Coverage Report

Created: 2026-05-24 07:45

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
  Iterator iterator = av1_hash_get_first_iterator(ref_frame_hash, hash_value1);
1949
0
  for (int i = 0; i < count; i++, aom_iterator_increment(&iterator)) {
1950
0
    block_hash ref_block_hash = *(block_hash *)(aom_iterator_get(&iterator));
1951
0
    if (hash_value2 == ref_block_hash.hash_value2) {
1952
      // Make sure the prediction is from valid area.
1953
0
      const MV dv = { GET_MV_SUBPEL(ref_block_hash.y - y_pos),
1954
0
                      GET_MV_SUBPEL(ref_block_hash.x - x_pos) };
1955
0
      if (!av1_is_dv_valid(dv, &cpi->common, xd, mi_row, mi_col, bsize,
1956
0
                           cpi->common.seq_params->mib_size_log2))
1957
0
        continue;
1958
1959
0
      FULLPEL_MV hash_mv;
1960
0
      hash_mv.col = ref_block_hash.x - x_pos;
1961
0
      hash_mv.row = ref_block_hash.y - y_pos;
1962
0
      if (!av1_is_fullmv_in_range(mv_limits, hash_mv)) continue;
1963
0
      FULLPEL_MV_STATS mv_stats;
1964
0
      const int refCost = get_mvpred_var_cost(ms_params, &hash_mv, &mv_stats);
1965
0
      if (refCost < best_hash_cost) {
1966
0
        best_hash_cost = refCost;
1967
0
        *best_mv = hash_mv;
1968
0
      }
1969
0
    }
1970
0
  }
1971
1972
0
  return best_hash_cost;
1973
0
}
1974
1975
int av1_vector_match(const int16_t *ref, const int16_t *src, int bwl,
1976
                     int search_size_top, int search_size_bottom,
1977
0
                     int full_search, int *sad) {
1978
0
  int best_sad = INT_MAX;
1979
0
  int this_sad;
1980
0
  int d;
1981
0
  int center, offset = 0;
1982
0
  int bw = search_size_top + search_size_bottom;
1983
1984
0
  if (full_search) {
1985
0
    for (d = 0; d <= bw; d++) {
1986
0
      this_sad = aom_vector_var(&ref[d], src, bwl);
1987
0
      if (this_sad < best_sad) {
1988
0
        best_sad = this_sad;
1989
0
        offset = d;
1990
0
      }
1991
0
    }
1992
0
    center = offset;
1993
0
    *sad = best_sad;
1994
0
    return (center - search_size_top);
1995
0
  }
1996
1997
0
  for (d = 0; d <= bw; d += 16) {
1998
0
    this_sad = aom_vector_var(&ref[d], src, bwl);
1999
0
    if (this_sad < best_sad) {
2000
0
      best_sad = this_sad;
2001
0
      offset = d;
2002
0
    }
2003
0
  }
2004
0
  center = offset;
2005
2006
0
  for (d = -8; d <= 8; d += 16) {
2007
0
    int this_pos = offset + d;
2008
    // check limit
2009
0
    if (this_pos < 0 || this_pos > bw) continue;
2010
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2011
0
    if (this_sad < best_sad) {
2012
0
      best_sad = this_sad;
2013
0
      center = this_pos;
2014
0
    }
2015
0
  }
2016
0
  offset = center;
2017
2018
0
  for (d = -4; d <= 4; d += 8) {
2019
0
    int this_pos = offset + d;
2020
    // check limit
2021
0
    if (this_pos < 0 || this_pos > bw) continue;
2022
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2023
0
    if (this_sad < best_sad) {
2024
0
      best_sad = this_sad;
2025
0
      center = this_pos;
2026
0
    }
2027
0
  }
2028
0
  offset = center;
2029
2030
0
  for (d = -2; d <= 2; d += 4) {
2031
0
    int this_pos = offset + d;
2032
    // check limit
2033
0
    if (this_pos < 0 || this_pos > bw) continue;
2034
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2035
0
    if (this_sad < best_sad) {
2036
0
      best_sad = this_sad;
2037
0
      center = this_pos;
2038
0
    }
2039
0
  }
2040
0
  offset = center;
2041
2042
0
  for (d = -1; d <= 1; d += 2) {
2043
0
    int this_pos = offset + d;
2044
    // check limit
2045
0
    if (this_pos < 0 || this_pos > bw) continue;
2046
0
    this_sad = aom_vector_var(&ref[this_pos], src, bwl);
2047
0
    if (this_sad < best_sad) {
2048
0
      best_sad = this_sad;
2049
0
      center = this_pos;
2050
0
    }
2051
0
  }
2052
0
  *sad = best_sad;
2053
0
  return (center - search_size_top);
2054
0
}
2055
2056
// A special fast version of motion search used in rt mode.
2057
// The search window along columns and row is given by:
2058
//  +/- me_search_size_col/row.
2059
unsigned int av1_int_pro_motion_estimation(
2060
    const AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int mi_row,
2061
    int mi_col, const MV *ref_mv, unsigned int *y_sad_zero,
2062
    int me_search_size_col, int me_search_size_row, int is_var_part,
2063
0
    int use_larger_search) {
2064
0
  const AV1_COMMON *const cm = &cpi->common;
2065
0
  MACROBLOCKD *xd = &x->e_mbd;
2066
0
  MB_MODE_INFO *mi = xd->mi[0];
2067
0
  struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0, 0, 0, 0 } };
2068
0
  int idx;
2069
0
  const int bw = block_size_wide[bsize];
2070
0
  const int bh = block_size_high[bsize];
2071
0
  const int is_screen = cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN;
2072
0
  const int full_search = is_screen;
2073
0
  const bool scroll_superblock =
2074
0
      use_larger_search && bsize == cm->seq_params->sb_size;
2075
  // Keep border a multiple of 16.
2076
0
  const int border = (cpi->oxcf.border_in_pixels >> 4) << 4;
2077
0
  int search_size_width_left = me_search_size_col;
2078
0
  int search_size_width_right = me_search_size_col;
2079
0
  int search_size_height_top = me_search_size_row;
2080
0
  int search_size_height_bottom = me_search_size_row;
2081
  // Allow for larger search size for column/horizontal screen motion.
2082
0
  if (scroll_superblock && is_var_part) {
2083
0
    if (((mi_col << 2) - search_size_width_left) < -border)
2084
0
      search_size_width_left = (mi_col << 2) + border;
2085
0
    if (((mi_col << 2) + search_size_width_right + bw) > cm->width + border)
2086
0
      search_size_width_right = cm->width + border - (mi_col << 2) - bw;
2087
0
  } else {
2088
0
    if (((mi_col << 2) - search_size_width_left < -border) ||
2089
0
        ((mi_col << 2) + search_size_width_right + bw > cm->width + border)) {
2090
0
      search_size_width_left = AOMMIN(border, (mi_col << 2) + border);
2091
0
      search_size_width_right =
2092
0
          AOMMIN(border, cm->width + border - (mi_col << 2) - bw);
2093
0
    }
2094
0
  }
2095
  // Allow for larger search size for row/vertical screen motion.
2096
0
  if (scroll_superblock && is_var_part) {
2097
0
    if (((mi_row << 2) - search_size_height_top) < -border)
2098
0
      search_size_height_top = (mi_row << 2) + border;
2099
0
    if (((mi_row << 2) + search_size_height_bottom + bh) > cm->height + border)
2100
0
      search_size_height_bottom = cm->height + border - (mi_row << 2) - bh;
2101
0
  } else {
2102
0
    if (((mi_row << 2) - search_size_height_top < -border) ||
2103
0
        ((mi_row << 2) + search_size_height_bottom + bh >
2104
0
         cm->height + border)) {
2105
0
      search_size_height_top = AOMMIN(border, (mi_row << 2) + border);
2106
0
      search_size_height_bottom =
2107
0
          AOMMIN(border, cm->height + border - (mi_row << 2) - bh);
2108
0
    }
2109
0
  }
2110
  // Make search_size_width/height_left/right/top/bottom multiple of 16.
2111
0
  search_size_width_left &= ~15;
2112
0
  search_size_width_right &= ~15;
2113
0
  search_size_height_top &= ~15;
2114
0
  search_size_height_bottom &= ~15;
2115
0
  const int src_stride = x->plane[0].src.stride;
2116
0
  uint8_t const *ref_buf, *src_buf;
2117
0
  int_mv *best_int_mv = &xd->mi[0]->mv[0];
2118
0
  unsigned int best_sad, tmp_sad, this_sad[4];
2119
0
  int best_sad_col, best_sad_row;
2120
0
  const int row_norm_factor = mi_size_high_log2[bsize] + 1;
2121
0
  const int col_norm_factor = 3 + (bw >> 5);
2122
0
  const YV12_BUFFER_CONFIG *scaled_ref_frame =
2123
0
      av1_get_scaled_ref_frame(cpi, mi->ref_frame[0]);
2124
0
  static const MV search_pos[4] = {
2125
0
    { -1, 0 },
2126
0
    { 0, -1 },
2127
0
    { 0, 1 },
2128
0
    { 1, 0 },
2129
0
  };
2130
2131
0
  if (scaled_ref_frame) {
2132
0
    int i;
2133
    // Swap out the reference frame for a version that's been scaled to
2134
    // match the resolution of the current frame, allowing the existing
2135
    // motion search code to be used without additional modifications.
2136
0
    for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
2137
0
    av1_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL,
2138
0
                         MAX_MB_PLANE);
2139
0
  }
2140
0
  const int ref_stride = xd->plane[0].pre[0].stride;
2141
2142
0
  if (xd->bd != 8) {
2143
0
    best_int_mv->as_fullmv = kZeroFullMv;
2144
0
    best_sad = cpi->ppi->fn_ptr[bsize].sdf(x->plane[0].src.buf, src_stride,
2145
0
                                           xd->plane[0].pre[0].buf, ref_stride);
2146
2147
0
    if (scaled_ref_frame) {
2148
0
      int i;
2149
0
      for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2150
0
    }
2151
0
    return best_sad;
2152
0
  }
2153
0
  const int width_ref_buf =
2154
0
      search_size_width_left + search_size_width_right + bw;
2155
0
  const int height_ref_buf =
2156
0
      search_size_height_top + search_size_height_bottom + bh;
2157
0
  int16_t *hbuf = (int16_t *)aom_malloc(width_ref_buf * sizeof(*hbuf));
2158
0
  int16_t *vbuf = (int16_t *)aom_malloc(height_ref_buf * sizeof(*vbuf));
2159
0
  int16_t *src_hbuf = (int16_t *)aom_malloc(bw * sizeof(*src_hbuf));
2160
0
  int16_t *src_vbuf = (int16_t *)aom_malloc(bh * sizeof(*src_vbuf));
2161
0
  if (!hbuf || !vbuf || !src_hbuf || !src_vbuf) {
2162
0
    aom_free(hbuf);
2163
0
    aom_free(vbuf);
2164
0
    aom_free(src_hbuf);
2165
0
    aom_free(src_vbuf);
2166
0
    aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2167
0
                       "Failed to allocate hbuf, vbuf, src_hbuf, or src_vbuf");
2168
0
  }
2169
2170
  // Set up prediction 1-D reference set for rows.
2171
0
  ref_buf = xd->plane[0].pre[0].buf - search_size_width_left;
2172
0
  aom_int_pro_row(hbuf, ref_buf, ref_stride, width_ref_buf, bh,
2173
0
                  row_norm_factor);
2174
2175
  // Set up prediction 1-D reference set for cols
2176
0
  ref_buf = xd->plane[0].pre[0].buf - search_size_height_top * ref_stride;
2177
0
  aom_int_pro_col(vbuf, ref_buf, ref_stride, bw, height_ref_buf,
2178
0
                  col_norm_factor);
2179
2180
  // Set up src 1-D reference set
2181
0
  src_buf = x->plane[0].src.buf;
2182
0
  aom_int_pro_row(src_hbuf, src_buf, src_stride, bw, bh, row_norm_factor);
2183
0
  aom_int_pro_col(src_vbuf, src_buf, src_stride, bw, bh, col_norm_factor);
2184
2185
  // Find the best match per 1-D search
2186
0
  best_int_mv->as_fullmv.col = av1_vector_match(
2187
0
      hbuf, src_hbuf, mi_size_wide_log2[bsize], search_size_width_left,
2188
0
      search_size_width_right, full_search, &best_sad_col);
2189
0
  best_int_mv->as_fullmv.row = av1_vector_match(
2190
0
      vbuf, src_vbuf, mi_size_high_log2[bsize], search_size_height_top,
2191
0
      search_size_height_bottom, full_search, &best_sad_row);
2192
2193
  // For screen: select between horiz or vert motion.
2194
0
  if (is_screen) {
2195
0
    if (best_sad_col < best_sad_row)
2196
0
      best_int_mv->as_fullmv.row = 0;
2197
0
    else
2198
0
      best_int_mv->as_fullmv.col = 0;
2199
0
  }
2200
2201
0
  FULLPEL_MV this_mv = best_int_mv->as_fullmv;
2202
0
  src_buf = x->plane[0].src.buf;
2203
0
  ref_buf = get_buf_from_fullmv(&xd->plane[0].pre[0], &this_mv);
2204
0
  best_sad =
2205
0
      cpi->ppi->fn_ptr[bsize].sdf(src_buf, src_stride, ref_buf, ref_stride);
2206
2207
0
  if (!is_screen && scroll_superblock) {
2208
0
    if (best_sad_col < best_sad_row && best_sad_col < (int)best_sad) {
2209
0
      best_int_mv->as_fullmv.row = 0;
2210
0
      best_sad = best_sad_col;
2211
0
    } else if (best_sad_row < best_sad_col && best_sad_row < (int)best_sad) {
2212
0
      best_int_mv->as_fullmv.col = 0;
2213
0
      best_sad = best_sad_row;
2214
0
    }
2215
0
  }
2216
2217
  // Evaluate zero MV if found MV is non-zero.
2218
0
  if (best_int_mv->as_int != 0) {
2219
0
    tmp_sad = cpi->ppi->fn_ptr[bsize].sdf(x->plane[0].src.buf, src_stride,
2220
0
                                          xd->plane[0].pre[0].buf, ref_stride);
2221
0
    *y_sad_zero = tmp_sad;
2222
0
    if (tmp_sad < best_sad) {
2223
0
      best_int_mv->as_fullmv = kZeroFullMv;
2224
0
      this_mv = best_int_mv->as_fullmv;
2225
0
      ref_buf = xd->plane[0].pre[0].buf;
2226
0
      best_sad = tmp_sad;
2227
0
    }
2228
0
  } else {
2229
0
    *y_sad_zero = best_sad;
2230
0
  }
2231
2232
0
  if (!scroll_superblock) {
2233
0
    const uint8_t *const pos[4] = {
2234
0
      ref_buf - ref_stride,
2235
0
      ref_buf - 1,
2236
0
      ref_buf + 1,
2237
0
      ref_buf + ref_stride,
2238
0
    };
2239
2240
0
    cpi->ppi->fn_ptr[bsize].sdx4df(src_buf, src_stride, pos, ref_stride,
2241
0
                                   this_sad);
2242
2243
0
    for (idx = 0; idx < 4; ++idx) {
2244
0
      if (this_sad[idx] < best_sad) {
2245
0
        best_sad = this_sad[idx];
2246
0
        best_int_mv->as_fullmv.row = search_pos[idx].row + this_mv.row;
2247
0
        best_int_mv->as_fullmv.col = search_pos[idx].col + this_mv.col;
2248
0
      }
2249
0
    }
2250
2251
0
    if (this_sad[0] < this_sad[3])
2252
0
      this_mv.row -= 1;
2253
0
    else
2254
0
      this_mv.row += 1;
2255
2256
0
    if (this_sad[1] < this_sad[2])
2257
0
      this_mv.col -= 1;
2258
0
    else
2259
0
      this_mv.col += 1;
2260
2261
0
    ref_buf = get_buf_from_fullmv(&xd->plane[0].pre[0], &this_mv);
2262
2263
0
    tmp_sad =
2264
0
        cpi->ppi->fn_ptr[bsize].sdf(src_buf, src_stride, ref_buf, ref_stride);
2265
0
    if (best_sad > tmp_sad) {
2266
0
      best_int_mv->as_fullmv = this_mv;
2267
0
      best_sad = tmp_sad;
2268
0
    }
2269
0
  }
2270
2271
0
  FullMvLimits mv_limits = x->mv_limits;
2272
0
  av1_set_mv_search_range(&mv_limits, ref_mv);
2273
0
  clamp_fullmv(&best_int_mv->as_fullmv, &mv_limits);
2274
2275
0
  convert_fullmv_to_mv(best_int_mv);
2276
2277
0
  if (scaled_ref_frame) {
2278
0
    int i;
2279
0
    for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2280
0
  }
2281
2282
0
  aom_free(hbuf);
2283
0
  aom_free(vbuf);
2284
0
  aom_free(src_hbuf);
2285
0
  aom_free(src_vbuf);
2286
0
  return best_sad;
2287
0
}
2288
2289
// =============================================================================
2290
//  Fullpixel Motion Search: OBMC
2291
// =============================================================================
2292
static inline int get_obmc_mvpred_var(
2293
0
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV *this_mv) {
2294
0
  const aom_variance_fn_ptr_t *vfp = ms_params->vfp;
2295
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2296
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2297
0
  const int32_t *wsrc = ms_buffers->wsrc;
2298
0
  const int32_t *mask = ms_buffers->obmc_mask;
2299
0
  const struct buf_2d *ref_buf = ms_buffers->ref;
2300
2301
0
  const MV mv = get_mv_from_fullmv(this_mv);
2302
0
  unsigned int unused;
2303
2304
0
  return vfp->ovf(get_buf_from_fullmv(ref_buf, this_mv), ref_buf->stride, wsrc,
2305
0
                  mask, &unused) +
2306
0
         mv_err_cost_(&mv, mv_cost_params);
2307
0
}
2308
2309
static int obmc_refining_search_sad(
2310
0
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV *best_mv) {
2311
0
  const aom_variance_fn_ptr_t *fn_ptr = ms_params->vfp;
2312
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2313
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2314
0
  const int32_t *wsrc = ms_buffers->wsrc;
2315
0
  const int32_t *mask = ms_buffers->obmc_mask;
2316
0
  const struct buf_2d *ref_buf = ms_buffers->ref;
2317
0
  const FULLPEL_MV neighbors[4] = { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };
2318
0
  const int kSearchRange = 8;
2319
2320
0
  unsigned int best_sad = fn_ptr->osdf(get_buf_from_fullmv(ref_buf, best_mv),
2321
0
                                       ref_buf->stride, wsrc, mask) +
2322
0
                          mvsad_err_cost_(best_mv, mv_cost_params);
2323
2324
0
  for (int i = 0; i < kSearchRange; i++) {
2325
0
    int best_site = -1;
2326
2327
0
    for (int j = 0; j < 4; j++) {
2328
0
      const FULLPEL_MV mv = { best_mv->row + neighbors[j].row,
2329
0
                              best_mv->col + neighbors[j].col };
2330
0
      if (av1_is_fullmv_in_range(&ms_params->mv_limits, mv)) {
2331
0
        unsigned int sad = fn_ptr->osdf(get_buf_from_fullmv(ref_buf, &mv),
2332
0
                                        ref_buf->stride, wsrc, mask);
2333
0
        if (sad < best_sad) {
2334
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
2335
2336
0
          if (sad < best_sad) {
2337
0
            best_sad = sad;
2338
0
            best_site = j;
2339
0
          }
2340
0
        }
2341
0
      }
2342
0
    }
2343
2344
0
    if (best_site == -1) {
2345
0
      break;
2346
0
    } else {
2347
0
      best_mv->row += neighbors[best_site].row;
2348
0
      best_mv->col += neighbors[best_site].col;
2349
0
    }
2350
0
  }
2351
0
  return best_sad;
2352
0
}
2353
2354
static int obmc_diamond_search_sad(
2355
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, FULLPEL_MV start_mv,
2356
0
    FULLPEL_MV *best_mv, int search_step, int *num00) {
2357
0
  const aom_variance_fn_ptr_t *fn_ptr = ms_params->vfp;
2358
0
  const search_site_config *cfg = ms_params->search_sites;
2359
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
2360
0
  const MSBuffers *ms_buffers = &ms_params->ms_buffers;
2361
0
  const int32_t *wsrc = ms_buffers->wsrc;
2362
0
  const int32_t *mask = ms_buffers->obmc_mask;
2363
0
  const struct buf_2d *const ref_buf = ms_buffers->ref;
2364
2365
  // search_step determines the length of the initial step and hence the number
2366
  // of iterations.
2367
0
  const int tot_steps = cfg->num_search_steps - search_step;
2368
0
  const uint8_t *best_address, *init_ref;
2369
0
  int best_sad = INT_MAX;
2370
0
  int best_site = 0;
2371
2372
0
  clamp_fullmv(&start_mv, &ms_params->mv_limits);
2373
0
  best_address = init_ref = get_buf_from_fullmv(ref_buf, &start_mv);
2374
0
  *num00 = 0;
2375
0
  *best_mv = start_mv;
2376
2377
  // Check the starting position
2378
0
  best_sad = fn_ptr->osdf(best_address, ref_buf->stride, wsrc, mask) +
2379
0
             mvsad_err_cost_(best_mv, mv_cost_params);
2380
2381
0
  for (int step = tot_steps - 1; step >= 0; --step) {
2382
0
    const search_site *const site = cfg->site[step];
2383
0
    best_site = 0;
2384
0
    for (int idx = 1; idx <= cfg->searches_per_step[step]; ++idx) {
2385
0
      const FULLPEL_MV mv = { best_mv->row + site[idx].mv.row,
2386
0
                              best_mv->col + site[idx].mv.col };
2387
0
      if (av1_is_fullmv_in_range(&ms_params->mv_limits, mv)) {
2388
0
        int sad = fn_ptr->osdf(best_address + site[idx].offset, ref_buf->stride,
2389
0
                               wsrc, mask);
2390
0
        if (sad < best_sad) {
2391
0
          sad += mvsad_err_cost_(&mv, mv_cost_params);
2392
2393
0
          if (sad < best_sad) {
2394
0
            best_sad = sad;
2395
0
            best_site = idx;
2396
0
          }
2397
0
        }
2398
0
      }
2399
0
    }
2400
2401
0
    if (best_site != 0) {
2402
0
      best_mv->row += site[best_site].mv.row;
2403
0
      best_mv->col += site[best_site].mv.col;
2404
0
      best_address += site[best_site].offset;
2405
0
    } else if (best_address == init_ref) {
2406
0
      (*num00)++;
2407
0
    }
2408
0
  }
2409
0
  return best_sad;
2410
0
}
2411
2412
static int obmc_full_pixel_diamond(
2413
    const FULLPEL_MOTION_SEARCH_PARAMS *ms_params, const FULLPEL_MV start_mv,
2414
0
    int step_param, FULLPEL_MV *best_mv) {
2415
0
  const search_site_config *cfg = ms_params->search_sites;
2416
0
  FULLPEL_MV tmp_mv;
2417
0
  int thissme, n, num00 = 0;
2418
0
  int bestsme =
2419
0
      obmc_diamond_search_sad(ms_params, start_mv, &tmp_mv, step_param, &n);
2420
0
  if (bestsme < INT_MAX) bestsme = get_obmc_mvpred_var(ms_params, &tmp_mv);
2421
0
  *best_mv = tmp_mv;
2422
2423
  // If there won't be more n-step search, check to see if refining search is
2424
  // needed.
2425
0
  const int further_steps = cfg->num_search_steps - 1 - step_param;
2426
2427
0
  while (n < further_steps) {
2428
0
    ++n;
2429
2430
0
    if (num00) {
2431
0
      num00--;
2432
0
    } else {
2433
0
      thissme = obmc_diamond_search_sad(ms_params, start_mv, &tmp_mv,
2434
0
                                        step_param + n, &num00);
2435
0
      if (thissme < INT_MAX) thissme = get_obmc_mvpred_var(ms_params, &tmp_mv);
2436
2437
0
      if (thissme < bestsme) {
2438
0
        bestsme = thissme;
2439
0
        *best_mv = tmp_mv;
2440
0
      }
2441
0
    }
2442
0
  }
2443
2444
0
  return bestsme;
2445
0
}
2446
2447
int av1_obmc_full_pixel_search(const FULLPEL_MV start_mv,
2448
                               const FULLPEL_MOTION_SEARCH_PARAMS *ms_params,
2449
0
                               const int step_param, FULLPEL_MV *best_mv) {
2450
0
  if (!ms_params->fast_obmc_search) {
2451
0
    const int bestsme =
2452
0
        obmc_full_pixel_diamond(ms_params, start_mv, step_param, best_mv);
2453
0
    return bestsme;
2454
0
  } else {
2455
0
    *best_mv = start_mv;
2456
0
    clamp_fullmv(best_mv, &ms_params->mv_limits);
2457
0
    int thissme = obmc_refining_search_sad(ms_params, best_mv);
2458
0
    if (thissme < INT_MAX) thissme = get_obmc_mvpred_var(ms_params, best_mv);
2459
0
    return thissme;
2460
0
  }
2461
0
}
2462
2463
// =============================================================================
2464
//  Subpixel Motion Search: Translational
2465
// =============================================================================
2466
0
#define INIT_SUBPEL_STEP_SIZE (4)
2467
/*
2468
 * To avoid the penalty for crossing cache-line read, preload the reference
2469
 * area in a small buffer, which is aligned to make sure there won't be crossing
2470
 * cache-line read while reading from this buffer. This reduced the cpu
2471
 * cycles spent on reading ref data in sub-pixel filter functions.
2472
 * TODO: Currently, since sub-pixel search range here is -3 ~ 3, copy 22 rows x
2473
 * 32 cols area that is enough for 16x16 macroblock. Later, for SPLITMV, we
2474
 * could reduce the area.
2475
 */
2476
2477
// Returns the subpel offset used by various subpel variance functions [m]sv[a]f
2478
0
static inline int get_subpel_part(int x) { return x & 7; }
2479
2480
// Gets the address of the ref buffer at subpel location (r, c), rounded to the
2481
// nearest fullpel precision toward - \infty
2482
static inline const uint8_t *get_buf_from_mv(const struct buf_2d *buf,
2483
0
                                             const MV mv) {
2484
0
  const int offset = (mv.row >> 3) * buf->stride + (mv.col >> 3);
2485
0
  return &buf->buf[offset];
2486
0
}
2487
2488
// Estimates the variance of prediction residue using bilinear filter for fast
2489
// search.
2490
static inline int estimated_pref_error(
2491
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2492
0
    unsigned int *sse) {
2493
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2494
2495
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2496
0
  const uint8_t *src = ms_buffers->src->buf;
2497
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
2498
0
  const int src_stride = ms_buffers->src->stride;
2499
0
  const int ref_stride = ms_buffers->ref->stride;
2500
0
  const uint8_t *second_pred = ms_buffers->second_pred;
2501
0
  const uint8_t *mask = ms_buffers->mask;
2502
0
  const int mask_stride = ms_buffers->mask_stride;
2503
0
  const int invert_mask = ms_buffers->inv_mask;
2504
2505
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
2506
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
2507
2508
0
  if (second_pred == NULL) {
2509
0
    return vfp->svf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2510
0
                    sse);
2511
0
  } else if (mask) {
2512
0
    return vfp->msvf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2513
0
                     second_pred, mask, mask_stride, invert_mask, sse);
2514
0
  } else {
2515
0
    return vfp->svaf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, src_stride,
2516
0
                     sse, second_pred);
2517
0
  }
2518
0
}
2519
2520
// Calculates the variance of prediction residue.
2521
static int upsampled_pref_error(MACROBLOCKD *xd, const AV1_COMMON *cm,
2522
                                const MV *this_mv,
2523
                                const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2524
0
                                unsigned int *sse) {
2525
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2526
0
  const SUBPEL_SEARCH_TYPE subpel_search_type = var_params->subpel_search_type;
2527
2528
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2529
0
  const uint8_t *src = ms_buffers->src->buf;
2530
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
2531
0
  const int src_stride = ms_buffers->src->stride;
2532
0
  const int ref_stride = ms_buffers->ref->stride;
2533
0
  const uint8_t *second_pred = ms_buffers->second_pred;
2534
0
  const uint8_t *mask = ms_buffers->mask;
2535
0
  const int mask_stride = ms_buffers->mask_stride;
2536
0
  const int invert_mask = ms_buffers->inv_mask;
2537
0
  const int w = var_params->w;
2538
0
  const int h = var_params->h;
2539
2540
0
  const int mi_row = xd->mi_row;
2541
0
  const int mi_col = xd->mi_col;
2542
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
2543
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
2544
2545
0
  unsigned int besterr;
2546
0
#if CONFIG_AV1_HIGHBITDEPTH
2547
0
  if (is_cur_buf_hbd(xd)) {
2548
0
    uint16_t *pred16 = (uint16_t *)(xd->tmp_upsample_pred);
2549
0
    uint8_t *pred8 = CONVERT_TO_BYTEPTR(pred16);
2550
0
    if (second_pred != NULL) {
2551
0
      if (mask) {
2552
0
        aom_highbd_comp_mask_upsampled_pred(
2553
0
            xd, cm, mi_row, mi_col, this_mv, pred8, second_pred, w, h,
2554
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, mask, mask_stride,
2555
0
            invert_mask, xd->bd, subpel_search_type);
2556
0
      } else {
2557
0
        aom_highbd_comp_avg_upsampled_pred(
2558
0
            xd, cm, mi_row, mi_col, this_mv, pred8, second_pred, w, h,
2559
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, xd->bd,
2560
0
            subpel_search_type);
2561
0
      }
2562
0
    } else {
2563
0
      aom_highbd_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred8, w, h,
2564
0
                                subpel_x_q3, subpel_y_q3, ref, ref_stride,
2565
0
                                xd->bd, subpel_search_type);
2566
0
    }
2567
0
    besterr = vfp->vf(pred8, w, src, src_stride, sse);
2568
0
  } else {
2569
0
    uint8_t *pred = xd->tmp_upsample_pred;
2570
0
    if (second_pred != NULL) {
2571
0
      if (mask) {
2572
0
        aom_comp_mask_upsampled_pred(
2573
0
            xd, cm, mi_row, mi_col, this_mv, pred, second_pred, w, h,
2574
0
            subpel_x_q3, subpel_y_q3, ref, ref_stride, mask, mask_stride,
2575
0
            invert_mask, subpel_search_type);
2576
0
      } else {
2577
0
        aom_comp_avg_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2578
0
                                    second_pred, w, h, subpel_x_q3, subpel_y_q3,
2579
0
                                    ref, ref_stride, subpel_search_type);
2580
0
      }
2581
0
    } else {
2582
0
      aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h,
2583
0
                         subpel_x_q3, subpel_y_q3, ref, ref_stride,
2584
0
                         subpel_search_type);
2585
0
    }
2586
2587
0
    besterr = vfp->vf(pred, w, src, src_stride, sse);
2588
0
  }
2589
#else
2590
  uint8_t *pred = xd->tmp_upsample_pred;
2591
  if (second_pred != NULL) {
2592
    if (mask) {
2593
      aom_comp_mask_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2594
                                   second_pred, w, h, subpel_x_q3, subpel_y_q3,
2595
                                   ref, ref_stride, mask, mask_stride,
2596
                                   invert_mask, subpel_search_type);
2597
    } else {
2598
      aom_comp_avg_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred,
2599
                                  second_pred, w, h, subpel_x_q3, subpel_y_q3,
2600
                                  ref, ref_stride, subpel_search_type);
2601
    }
2602
  } else {
2603
    aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
2604
                       subpel_y_q3, ref, ref_stride, subpel_search_type);
2605
  }
2606
2607
  besterr = vfp->vf(pred, w, src, src_stride, sse);
2608
#endif
2609
0
  return besterr;
2610
0
}
2611
2612
// Estimates whether this_mv is better than best_mv. This function incorporates
2613
// both prediction error and residue into account. It is suffixed "fast" because
2614
// it uses bilinear filter to estimate the prediction.
2615
static inline unsigned int check_better_fast(
2616
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
2617
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2618
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2619
0
    unsigned int *sse1, int *distortion, int *has_better_mv, int is_scaled) {
2620
0
  unsigned int cost;
2621
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
2622
0
    unsigned int sse;
2623
0
    int thismse;
2624
0
    if (is_scaled) {
2625
0
      thismse = upsampled_pref_error(xd, cm, this_mv, var_params, &sse);
2626
0
    } else {
2627
0
      thismse = estimated_pref_error(this_mv, var_params, &sse);
2628
0
    }
2629
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
2630
0
    cost += thismse;
2631
2632
0
    if (cost < *besterr) {
2633
0
      *besterr = cost;
2634
0
      *best_mv = *this_mv;
2635
0
      *distortion = thismse;
2636
0
      *sse1 = sse;
2637
0
      *has_better_mv |= 1;
2638
0
    }
2639
0
  } else {
2640
0
    cost = INT_MAX;
2641
0
  }
2642
0
  return cost;
2643
0
}
2644
2645
// Checks whether this_mv is better than best_mv. This function incorporates
2646
// both prediction error and residue into account.
2647
static AOM_FORCE_INLINE unsigned int check_better(
2648
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
2649
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2650
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2651
0
    unsigned int *sse1, int *distortion, int *is_better) {
2652
0
  unsigned int cost;
2653
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
2654
0
    unsigned int sse;
2655
0
    int thismse;
2656
0
    thismse = upsampled_pref_error(xd, cm, this_mv, var_params, &sse);
2657
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
2658
0
    cost += thismse;
2659
0
    if (cost < *besterr) {
2660
0
      *besterr = cost;
2661
0
      *best_mv = *this_mv;
2662
0
      *distortion = thismse;
2663
0
      *sse1 = sse;
2664
0
      *is_better |= 1;
2665
0
    }
2666
0
  } else {
2667
0
    cost = INT_MAX;
2668
0
  }
2669
0
  return cost;
2670
0
}
2671
2672
static inline MV get_best_diag_step(int step_size, unsigned int left_cost,
2673
                                    unsigned int right_cost,
2674
                                    unsigned int up_cost,
2675
0
                                    unsigned int down_cost) {
2676
0
  const MV diag_step = { up_cost <= down_cost ? -step_size : step_size,
2677
0
                         left_cost <= right_cost ? -step_size : step_size };
2678
2679
0
  return diag_step;
2680
0
}
2681
2682
// Searches the four cardinal direction for a better mv, then follows up with a
2683
// search in the best quadrant. This uses bilinear filter to speed up the
2684
// calculation.
2685
static AOM_FORCE_INLINE MV first_level_check_fast(
2686
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, MV *best_mv,
2687
    int hstep, const SubpelMvLimits *mv_limits,
2688
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2689
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2690
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2691
  // Check the four cardinal directions
2692
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
2693
0
  int dummy = 0;
2694
0
  const unsigned int left = check_better_fast(
2695
0
      xd, cm, &left_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
2696
0
      sse1, distortion, &dummy, is_scaled);
2697
2698
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
2699
0
  const unsigned int right = check_better_fast(
2700
0
      xd, cm, &right_mv, best_mv, mv_limits, var_params, mv_cost_params,
2701
0
      besterr, sse1, distortion, &dummy, is_scaled);
2702
2703
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
2704
0
  const unsigned int up = check_better_fast(
2705
0
      xd, cm, &top_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
2706
0
      sse1, distortion, &dummy, is_scaled);
2707
2708
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
2709
0
  const unsigned int down = check_better_fast(
2710
0
      xd, cm, &bottom_mv, best_mv, mv_limits, var_params, mv_cost_params,
2711
0
      besterr, sse1, distortion, &dummy, is_scaled);
2712
2713
0
  const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
2714
0
  const MV diag_mv = { this_mv.row + diag_step.row,
2715
0
                       this_mv.col + diag_step.col };
2716
2717
  // Check the diagonal direction with the best mv
2718
0
  check_better_fast(xd, cm, &diag_mv, best_mv, mv_limits, var_params,
2719
0
                    mv_cost_params, besterr, sse1, distortion, &dummy,
2720
0
                    is_scaled);
2721
2722
0
  return diag_step;
2723
0
}
2724
2725
// Performs a following up search after first_level_check_fast is called. This
2726
// performs two extra chess pattern searches in the best quadrant.
2727
static AOM_FORCE_INLINE void second_level_check_fast(
2728
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, const MV diag_step,
2729
    MV *best_mv, int hstep, const SubpelMvLimits *mv_limits,
2730
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2731
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2732
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2733
0
  assert(diag_step.row == hstep || diag_step.row == -hstep);
2734
0
  assert(diag_step.col == hstep || diag_step.col == -hstep);
2735
0
  const int tr = this_mv.row;
2736
0
  const int tc = this_mv.col;
2737
0
  const int br = best_mv->row;
2738
0
  const int bc = best_mv->col;
2739
0
  int dummy = 0;
2740
0
  if (tr != br && tc != bc) {
2741
0
    assert(diag_step.col == bc - tc);
2742
0
    assert(diag_step.row == br - tr);
2743
0
    const MV chess_mv_1 = { br, bc + diag_step.col };
2744
0
    const MV chess_mv_2 = { br + diag_step.row, bc };
2745
0
    check_better_fast(xd, cm, &chess_mv_1, best_mv, mv_limits, var_params,
2746
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2747
0
                      is_scaled);
2748
2749
0
    check_better_fast(xd, cm, &chess_mv_2, best_mv, mv_limits, var_params,
2750
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2751
0
                      is_scaled);
2752
0
  } else if (tr == br && tc != bc) {
2753
0
    assert(diag_step.col == bc - tc);
2754
    // Continue searching in the best direction
2755
0
    const MV bottom_long_mv = { br + hstep, bc + diag_step.col };
2756
0
    const MV top_long_mv = { br - hstep, bc + diag_step.col };
2757
0
    check_better_fast(xd, cm, &bottom_long_mv, best_mv, mv_limits, var_params,
2758
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2759
0
                      is_scaled);
2760
0
    check_better_fast(xd, cm, &top_long_mv, best_mv, mv_limits, var_params,
2761
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2762
0
                      is_scaled);
2763
2764
    // Search in the direction opposite of the best quadrant
2765
0
    const MV rev_mv = { br - diag_step.row, bc };
2766
0
    check_better_fast(xd, cm, &rev_mv, best_mv, mv_limits, var_params,
2767
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2768
0
                      is_scaled);
2769
0
  } else if (tr != br && tc == bc) {
2770
0
    assert(diag_step.row == br - tr);
2771
    // Continue searching in the best direction
2772
0
    const MV right_long_mv = { br + diag_step.row, bc + hstep };
2773
0
    const MV left_long_mv = { br + diag_step.row, bc - hstep };
2774
0
    check_better_fast(xd, cm, &right_long_mv, best_mv, mv_limits, var_params,
2775
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2776
0
                      is_scaled);
2777
0
    check_better_fast(xd, cm, &left_long_mv, best_mv, mv_limits, var_params,
2778
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2779
0
                      is_scaled);
2780
2781
    // Search in the direction opposite of the best quadrant
2782
0
    const MV rev_mv = { br, bc - diag_step.col };
2783
0
    check_better_fast(xd, cm, &rev_mv, best_mv, mv_limits, var_params,
2784
0
                      mv_cost_params, besterr, sse1, distortion, &dummy,
2785
0
                      is_scaled);
2786
0
  }
2787
0
}
2788
2789
// Combines first level check and second level check when applicable. This first
2790
// searches the four cardinal directions, and perform several
2791
// diagonal/chess-pattern searches in the best quadrant.
2792
static AOM_FORCE_INLINE void two_level_checks_fast(
2793
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV this_mv, MV *best_mv,
2794
    int hstep, const SubpelMvLimits *mv_limits,
2795
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2796
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2797
0
    unsigned int *sse1, int *distortion, int iters, int is_scaled) {
2798
0
  const MV diag_step = first_level_check_fast(
2799
0
      xd, cm, this_mv, best_mv, hstep, mv_limits, var_params, mv_cost_params,
2800
0
      besterr, sse1, distortion, is_scaled);
2801
0
  if (iters > 1) {
2802
0
    second_level_check_fast(xd, cm, this_mv, diag_step, best_mv, hstep,
2803
0
                            mv_limits, var_params, mv_cost_params, besterr,
2804
0
                            sse1, distortion, is_scaled);
2805
0
  }
2806
0
}
2807
2808
static AOM_FORCE_INLINE MV
2809
first_level_check(MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv,
2810
                  MV *best_mv, const int hstep, const SubpelMvLimits *mv_limits,
2811
                  const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2812
                  const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2813
0
                  unsigned int *sse1, int *distortion) {
2814
0
  int dummy = 0;
2815
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
2816
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
2817
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
2818
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
2819
2820
0
  const unsigned int left =
2821
0
      check_better(xd, cm, &left_mv, best_mv, mv_limits, var_params,
2822
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2823
0
  const unsigned int right =
2824
0
      check_better(xd, cm, &right_mv, best_mv, mv_limits, var_params,
2825
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2826
0
  const unsigned int up =
2827
0
      check_better(xd, cm, &top_mv, best_mv, mv_limits, var_params,
2828
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2829
0
  const unsigned int down =
2830
0
      check_better(xd, cm, &bottom_mv, best_mv, mv_limits, var_params,
2831
0
                   mv_cost_params, besterr, sse1, distortion, &dummy);
2832
2833
0
  const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
2834
0
  const MV diag_mv = { this_mv.row + diag_step.row,
2835
0
                       this_mv.col + diag_step.col };
2836
2837
  // Check the diagonal direction with the best mv
2838
0
  check_better(xd, cm, &diag_mv, best_mv, mv_limits, var_params, mv_cost_params,
2839
0
               besterr, sse1, distortion, &dummy);
2840
2841
0
  return diag_step;
2842
0
}
2843
2844
// A newer version of second level check that gives better quality.
2845
// TODO(chiyotsai@google.com): evaluate this on subpel_search_types different
2846
// from av1_find_best_sub_pixel_tree
2847
static AOM_FORCE_INLINE void second_level_check_v2(
2848
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV diag_step,
2849
    MV *best_mv, const SubpelMvLimits *mv_limits,
2850
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2851
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
2852
0
    unsigned int *sse1, int *distortion, int is_scaled) {
2853
0
  assert(best_mv->row == this_mv.row + diag_step.row ||
2854
0
         best_mv->col == this_mv.col + diag_step.col);
2855
0
  if (CHECK_MV_EQUAL(this_mv, *best_mv)) {
2856
0
    return;
2857
0
  } else if (this_mv.row == best_mv->row) {
2858
    // Search away from diagonal step since diagonal search did not provide any
2859
    // improvement
2860
0
    diag_step.row *= -1;
2861
0
  } else if (this_mv.col == best_mv->col) {
2862
0
    diag_step.col *= -1;
2863
0
  }
2864
2865
0
  const MV row_bias_mv = { best_mv->row + diag_step.row, best_mv->col };
2866
0
  const MV col_bias_mv = { best_mv->row, best_mv->col + diag_step.col };
2867
0
  const MV diag_bias_mv = { best_mv->row + diag_step.row,
2868
0
                            best_mv->col + diag_step.col };
2869
0
  int has_better_mv = 0;
2870
2871
0
  if (var_params->subpel_search_type > USE_2_TAPS) {
2872
0
    check_better(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
2873
0
                 mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2874
0
    check_better(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
2875
0
                 mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2876
2877
    // Do an additional search if the second iteration gives a better mv
2878
0
    if (has_better_mv) {
2879
0
      check_better(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
2880
0
                   mv_cost_params, besterr, sse1, distortion, &has_better_mv);
2881
0
    }
2882
0
  } else {
2883
0
    check_better_fast(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
2884
0
                      mv_cost_params, besterr, sse1, distortion, &has_better_mv,
2885
0
                      is_scaled);
2886
0
    check_better_fast(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
2887
0
                      mv_cost_params, besterr, sse1, distortion, &has_better_mv,
2888
0
                      is_scaled);
2889
2890
    // Do an additional search if the second iteration gives a better mv
2891
0
    if (has_better_mv) {
2892
0
      check_better_fast(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
2893
0
                        mv_cost_params, besterr, sse1, distortion,
2894
0
                        &has_better_mv, is_scaled);
2895
0
    }
2896
0
  }
2897
0
}
2898
2899
// Gets the error at the beginning when the mv has fullpel precision
2900
static unsigned int setup_center_error(
2901
    const MACROBLOCKD *xd, const MV *bestmv,
2902
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2903
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
2904
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
2905
0
  const int w = var_params->w;
2906
0
  const int h = var_params->h;
2907
2908
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
2909
0
  const uint8_t *src = ms_buffers->src->buf;
2910
0
  const uint8_t *y = get_buf_from_mv(ms_buffers->ref, *bestmv);
2911
0
  const int src_stride = ms_buffers->src->stride;
2912
0
  const int y_stride = ms_buffers->ref->stride;
2913
0
  const uint8_t *second_pred = ms_buffers->second_pred;
2914
0
  const uint8_t *mask = ms_buffers->mask;
2915
0
  const int mask_stride = ms_buffers->mask_stride;
2916
0
  const int invert_mask = ms_buffers->inv_mask;
2917
2918
0
  unsigned int besterr;
2919
2920
0
  if (second_pred != NULL) {
2921
0
#if CONFIG_AV1_HIGHBITDEPTH
2922
0
    if (is_cur_buf_hbd(xd)) {
2923
0
      DECLARE_ALIGNED(16, uint16_t, comp_pred16[MAX_SB_SQUARE]);
2924
0
      uint8_t *comp_pred = CONVERT_TO_BYTEPTR(comp_pred16);
2925
0
      if (mask) {
2926
0
        aom_highbd_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride,
2927
0
                                  mask, mask_stride, invert_mask);
2928
0
      } else {
2929
0
        aom_highbd_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2930
0
      }
2931
0
      besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2932
0
    } else {
2933
0
      DECLARE_ALIGNED(16, uint8_t, comp_pred[MAX_SB_SQUARE]);
2934
0
      if (mask) {
2935
0
        aom_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride, mask,
2936
0
                           mask_stride, invert_mask);
2937
0
      } else {
2938
0
        aom_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2939
0
      }
2940
0
      besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2941
0
    }
2942
#else
2943
    (void)xd;
2944
    DECLARE_ALIGNED(16, uint8_t, comp_pred[MAX_SB_SQUARE]);
2945
    if (mask) {
2946
      aom_comp_mask_pred(comp_pred, second_pred, w, h, y, y_stride, mask,
2947
                         mask_stride, invert_mask);
2948
    } else {
2949
      aom_comp_avg_pred(comp_pred, second_pred, w, h, y, y_stride);
2950
    }
2951
    besterr = vfp->vf(comp_pred, w, src, src_stride, sse1);
2952
#endif
2953
0
  } else {
2954
0
    besterr = vfp->vf(y, y_stride, src, src_stride, sse1);
2955
0
  }
2956
0
  *distortion = besterr;
2957
0
  besterr += mv_err_cost_(bestmv, mv_cost_params);
2958
0
  return besterr;
2959
0
}
2960
2961
// Gets the error at the beginning when the mv has fullpel precision
2962
static unsigned int upsampled_setup_center_error(
2963
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV *bestmv,
2964
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
2965
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
2966
0
  unsigned int besterr = upsampled_pref_error(xd, cm, bestmv, var_params, sse1);
2967
0
  *distortion = besterr;
2968
0
  besterr += mv_err_cost_(bestmv, mv_cost_params);
2969
0
  return besterr;
2970
0
}
2971
2972
0
static inline int divide_and_round(int n, int d) {
2973
0
  return ((n < 0) ^ (d < 0)) ? ((n - d / 2) / d) : ((n + d / 2) / d);
2974
0
}
2975
2976
0
static inline int is_cost_list_wellbehaved(const int *cost_list) {
2977
0
  return cost_list[0] < cost_list[1] && cost_list[0] < cost_list[2] &&
2978
0
         cost_list[0] < cost_list[3] && cost_list[0] < cost_list[4];
2979
0
}
2980
2981
// Returns surface minima estimate at given precision in 1/2^n bits.
2982
// Assume a model for the cost surface: S = A(x - x0)^2 + B(y - y0)^2 + C
2983
// For a given set of costs S0, S1, S2, S3, S4 at points
2984
// (y, x) = (0, 0), (0, -1), (1, 0), (0, 1) and (-1, 0) respectively,
2985
// the solution for the location of the minima (x0, y0) is given by:
2986
// x0 = 1/2 (S1 - S3)/(S1 + S3 - 2*S0),
2987
// y0 = 1/2 (S4 - S2)/(S4 + S2 - 2*S0).
2988
// The code below is an integerized version of that.
2989
static inline void get_cost_surf_min(const int *cost_list, int *ir, int *ic,
2990
0
                                     int bits) {
2991
0
  *ic = divide_and_round((cost_list[1] - cost_list[3]) * (1 << (bits - 1)),
2992
0
                         (cost_list[1] - 2 * cost_list[0] + cost_list[3]));
2993
0
  *ir = divide_and_round((cost_list[4] - cost_list[2]) * (1 << (bits - 1)),
2994
0
                         (cost_list[4] - 2 * cost_list[0] + cost_list[2]));
2995
0
}
2996
2997
// Checks the list of mvs searched in the last iteration and see if we are
2998
// repeating it. If so, return 1. Otherwise we update the last_mv_search_list
2999
// with current_mv and return 0.
3000
static inline int check_repeated_mv_and_update(int_mv *last_mv_search_list,
3001
0
                                               const MV current_mv, int iter) {
3002
0
  if (last_mv_search_list) {
3003
0
    if (CHECK_MV_EQUAL(last_mv_search_list[iter].as_mv, current_mv)) {
3004
0
      return 1;
3005
0
    }
3006
3007
0
    last_mv_search_list[iter].as_mv = current_mv;
3008
0
  }
3009
0
  return 0;
3010
0
}
3011
3012
static inline int setup_center_error_facade(
3013
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *bestmv,
3014
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3015
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion,
3016
0
    int is_scaled) {
3017
0
  if (is_scaled) {
3018
0
    return upsampled_setup_center_error(xd, cm, bestmv, var_params,
3019
0
                                        mv_cost_params, sse1, distortion);
3020
0
  } else {
3021
0
    return setup_center_error(xd, bestmv, var_params, mv_cost_params, sse1,
3022
0
                              distortion);
3023
0
  }
3024
0
}
3025
3026
int av1_find_best_sub_pixel_tree_pruned_more(
3027
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3028
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3029
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3030
0
    unsigned int *sse1, int_mv *last_mv_search_list) {
3031
0
  (void)cm;
3032
0
  const int allow_hp = ms_params->allow_hp;
3033
0
  const int forced_stop = ms_params->forced_stop;
3034
0
  const int iters_per_step = ms_params->iters_per_step;
3035
0
  const int *cost_list = ms_params->cost_list;
3036
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3037
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3038
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3039
3040
  // The iteration we are current searching for. Iter 0 corresponds to fullpel
3041
  // mv, iter 1 to half pel, and so on
3042
0
  int iter = 0;
3043
0
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3044
0
  unsigned int besterr = INT_MAX;
3045
0
  *bestmv = start_mv;
3046
3047
0
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3048
0
                                             ? &cm->sf_identity
3049
0
                                             : xd->block_ref_scale_factors[0];
3050
0
  const int is_scaled = av1_is_scaled(sf);
3051
3052
0
  if (start_mv_stats != NULL && !is_scaled) {
3053
0
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3054
0
    *distortion = start_mv_stats->distortion;
3055
0
    *sse1 = start_mv_stats->sse;
3056
0
  } else {
3057
0
    besterr =
3058
0
        setup_center_error_facade(xd, cm, bestmv, var_params, mv_cost_params,
3059
0
                                  sse1, distortion, is_scaled);
3060
0
  }
3061
3062
  // If forced_stop is FULL_PEL, return.
3063
0
  if (forced_stop == FULL_PEL) return besterr;
3064
3065
0
  if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3066
0
    return INT_MAX;
3067
0
  }
3068
0
  iter++;
3069
3070
0
  if (cost_list && cost_list[0] != INT_MAX && cost_list[1] != INT_MAX &&
3071
0
      cost_list[2] != INT_MAX && cost_list[3] != INT_MAX &&
3072
0
      cost_list[4] != INT_MAX && is_cost_list_wellbehaved(cost_list)) {
3073
0
    int ir, ic;
3074
0
    get_cost_surf_min(cost_list, &ir, &ic, 1);
3075
0
    if (ir != 0 || ic != 0) {
3076
0
      const MV this_mv = { start_mv.row + ir * hstep,
3077
0
                           start_mv.col + ic * hstep };
3078
0
      int dummy = 0;
3079
0
      check_better_fast(xd, cm, &this_mv, bestmv, mv_limits, var_params,
3080
0
                        mv_cost_params, &besterr, sse1, distortion, &dummy,
3081
0
                        is_scaled);
3082
0
    }
3083
0
  } else {
3084
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3085
0
                          var_params, mv_cost_params, &besterr, sse1,
3086
0
                          distortion, iters_per_step, is_scaled);
3087
0
  }
3088
3089
  // Each subsequent iteration checks at least one point in common with
3090
  // the last iteration could be 2 ( if diag selected) 1/4 pel
3091
0
  if (forced_stop < HALF_PEL) {
3092
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3093
0
      return INT_MAX;
3094
0
    }
3095
0
    iter++;
3096
3097
0
    hstep >>= 1;
3098
0
    start_mv = *bestmv;
3099
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3100
0
                          var_params, mv_cost_params, &besterr, sse1,
3101
0
                          distortion, iters_per_step, is_scaled);
3102
0
  }
3103
3104
0
  if (allow_hp && forced_stop == EIGHTH_PEL) {
3105
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3106
0
      return INT_MAX;
3107
0
    }
3108
0
    iter++;
3109
3110
0
    hstep >>= 1;
3111
0
    start_mv = *bestmv;
3112
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3113
0
                          var_params, mv_cost_params, &besterr, sse1,
3114
0
                          distortion, iters_per_step, is_scaled);
3115
0
  }
3116
3117
0
  return besterr;
3118
0
}
3119
3120
int av1_find_best_sub_pixel_tree_pruned(
3121
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3122
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3123
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3124
0
    unsigned int *sse1, int_mv *last_mv_search_list) {
3125
0
  (void)cm;
3126
0
  (void)start_mv_stats;
3127
0
  const int allow_hp = ms_params->allow_hp;
3128
0
  const int forced_stop = ms_params->forced_stop;
3129
0
  const int iters_per_step = ms_params->iters_per_step;
3130
0
  const int *cost_list = ms_params->cost_list;
3131
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3132
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3133
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3134
3135
  // The iteration we are current searching for. Iter 0 corresponds to fullpel
3136
  // mv, iter 1 to half pel, and so on
3137
0
  int iter = 0;
3138
0
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3139
0
  unsigned int besterr = INT_MAX;
3140
0
  *bestmv = start_mv;
3141
3142
0
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3143
0
                                             ? &cm->sf_identity
3144
0
                                             : xd->block_ref_scale_factors[0];
3145
0
  const int is_scaled = av1_is_scaled(sf);
3146
3147
0
  if (start_mv_stats != NULL && !is_scaled) {
3148
0
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3149
0
    *distortion = start_mv_stats->distortion;
3150
0
    *sse1 = start_mv_stats->sse;
3151
0
  } else {
3152
0
    besterr =
3153
0
        setup_center_error_facade(xd, cm, bestmv, var_params, mv_cost_params,
3154
0
                                  sse1, distortion, is_scaled);
3155
0
  }
3156
3157
  // If forced_stop is FULL_PEL, return.
3158
0
  if (forced_stop == FULL_PEL) return besterr;
3159
3160
0
  if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3161
0
    return INT_MAX;
3162
0
  }
3163
0
  iter++;
3164
3165
0
  if (cost_list && cost_list[0] != INT_MAX && cost_list[1] != INT_MAX &&
3166
0
      cost_list[2] != INT_MAX && cost_list[3] != INT_MAX &&
3167
0
      cost_list[4] != INT_MAX) {
3168
0
    const unsigned int whichdir = (cost_list[1] < cost_list[3] ? 0 : 1) +
3169
0
                                  (cost_list[2] < cost_list[4] ? 0 : 2);
3170
3171
0
    const MV left_mv = { start_mv.row, start_mv.col - hstep };
3172
0
    const MV right_mv = { start_mv.row, start_mv.col + hstep };
3173
0
    const MV bottom_mv = { start_mv.row + hstep, start_mv.col };
3174
0
    const MV top_mv = { start_mv.row - hstep, start_mv.col };
3175
3176
0
    const MV bottom_left_mv = { start_mv.row + hstep, start_mv.col - hstep };
3177
0
    const MV bottom_right_mv = { start_mv.row + hstep, start_mv.col + hstep };
3178
0
    const MV top_left_mv = { start_mv.row - hstep, start_mv.col - hstep };
3179
0
    const MV top_right_mv = { start_mv.row - hstep, start_mv.col + hstep };
3180
3181
0
    int dummy = 0;
3182
3183
0
    switch (whichdir) {
3184
0
      case 0:  // bottom left quadrant
3185
0
        check_better_fast(xd, cm, &left_mv, bestmv, mv_limits, var_params,
3186
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3187
0
                          is_scaled);
3188
0
        check_better_fast(xd, cm, &bottom_mv, bestmv, mv_limits, var_params,
3189
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3190
0
                          is_scaled);
3191
0
        check_better_fast(xd, cm, &bottom_left_mv, bestmv, mv_limits,
3192
0
                          var_params, mv_cost_params, &besterr, sse1,
3193
0
                          distortion, &dummy, is_scaled);
3194
0
        break;
3195
0
      case 1:  // bottom right quadrant
3196
0
        check_better_fast(xd, cm, &right_mv, bestmv, mv_limits, var_params,
3197
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3198
0
                          is_scaled);
3199
0
        check_better_fast(xd, cm, &bottom_mv, bestmv, mv_limits, var_params,
3200
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3201
0
                          is_scaled);
3202
0
        check_better_fast(xd, cm, &bottom_right_mv, bestmv, mv_limits,
3203
0
                          var_params, mv_cost_params, &besterr, sse1,
3204
0
                          distortion, &dummy, is_scaled);
3205
0
        break;
3206
0
      case 2:  // top left quadrant
3207
0
        check_better_fast(xd, cm, &left_mv, bestmv, mv_limits, var_params,
3208
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3209
0
                          is_scaled);
3210
0
        check_better_fast(xd, cm, &top_mv, bestmv, mv_limits, var_params,
3211
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3212
0
                          is_scaled);
3213
0
        check_better_fast(xd, cm, &top_left_mv, bestmv, mv_limits, var_params,
3214
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3215
0
                          is_scaled);
3216
0
        break;
3217
0
      case 3:  // top right quadrant
3218
0
        check_better_fast(xd, cm, &right_mv, bestmv, mv_limits, var_params,
3219
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3220
0
                          is_scaled);
3221
0
        check_better_fast(xd, cm, &top_mv, bestmv, mv_limits, var_params,
3222
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3223
0
                          is_scaled);
3224
0
        check_better_fast(xd, cm, &top_right_mv, bestmv, mv_limits, var_params,
3225
0
                          mv_cost_params, &besterr, sse1, distortion, &dummy,
3226
0
                          is_scaled);
3227
0
        break;
3228
0
    }
3229
0
  } else {
3230
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3231
0
                          var_params, mv_cost_params, &besterr, sse1,
3232
0
                          distortion, iters_per_step, is_scaled);
3233
0
  }
3234
3235
  // Each subsequent iteration checks at least one point in common with
3236
  // the last iteration could be 2 ( if diag selected) 1/4 pel
3237
0
  if (forced_stop < HALF_PEL) {
3238
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3239
0
      return INT_MAX;
3240
0
    }
3241
0
    iter++;
3242
3243
0
    hstep >>= 1;
3244
0
    start_mv = *bestmv;
3245
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3246
0
                          var_params, mv_cost_params, &besterr, sse1,
3247
0
                          distortion, iters_per_step, is_scaled);
3248
0
  }
3249
3250
0
  if (allow_hp && forced_stop == EIGHTH_PEL) {
3251
0
    if (check_repeated_mv_and_update(last_mv_search_list, *bestmv, iter)) {
3252
0
      return INT_MAX;
3253
0
    }
3254
0
    iter++;
3255
3256
0
    hstep >>= 1;
3257
0
    start_mv = *bestmv;
3258
0
    two_level_checks_fast(xd, cm, start_mv, bestmv, hstep, mv_limits,
3259
0
                          var_params, mv_cost_params, &besterr, sse1,
3260
0
                          distortion, iters_per_step, is_scaled);
3261
0
  }
3262
3263
0
  return besterr;
3264
0
}
3265
3266
int av1_find_best_sub_pixel_tree(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3267
                                 const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3268
                                 MV start_mv,
3269
                                 const FULLPEL_MV_STATS *start_mv_stats,
3270
                                 MV *bestmv, int *distortion,
3271
                                 unsigned int *sse1,
3272
0
                                 int_mv *last_mv_search_list) {
3273
0
  (void)start_mv_stats;
3274
0
  const int allow_hp = ms_params->allow_hp;
3275
0
  const int forced_stop = ms_params->forced_stop;
3276
0
  const int iters_per_step = ms_params->iters_per_step;
3277
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3278
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3279
0
  const SUBPEL_SEARCH_TYPE subpel_search_type =
3280
0
      ms_params->var_params.subpel_search_type;
3281
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3282
3283
  // How many steps to take. A round of 0 means fullpel search only, 1 means
3284
  // half-pel, and so on.
3285
0
  const int round = AOMMIN(FULL_PEL - forced_stop, 3 - !allow_hp);
3286
0
  int hstep = INIT_SUBPEL_STEP_SIZE;  // Step size, initialized to 4/8=1/2 pel
3287
3288
0
  unsigned int besterr = INT_MAX;
3289
3290
0
  *bestmv = start_mv;
3291
3292
0
  const struct scale_factors *const sf = is_intrabc_block(xd->mi[0])
3293
0
                                             ? &cm->sf_identity
3294
0
                                             : xd->block_ref_scale_factors[0];
3295
0
  const int is_scaled = av1_is_scaled(sf);
3296
3297
0
  if (start_mv_stats != NULL && !is_scaled) {
3298
0
    besterr = start_mv_stats->distortion + start_mv_stats->err_cost;
3299
0
    *distortion = start_mv_stats->distortion;
3300
0
    *sse1 = start_mv_stats->sse;
3301
0
  } else {
3302
0
    if (subpel_search_type > USE_2_TAPS) {
3303
0
      besterr = upsampled_setup_center_error(xd, cm, bestmv, var_params,
3304
0
                                             mv_cost_params, sse1, distortion);
3305
0
    } else {
3306
0
      besterr = setup_center_error(xd, bestmv, var_params, mv_cost_params, sse1,
3307
0
                                   distortion);
3308
0
    }
3309
0
  }
3310
3311
  // If forced_stop is FULL_PEL, return.
3312
0
  if (!round) return besterr;
3313
3314
0
  for (int iter = 0; iter < round; ++iter) {
3315
0
    MV iter_center_mv = *bestmv;
3316
0
    if (check_repeated_mv_and_update(last_mv_search_list, iter_center_mv,
3317
0
                                     iter)) {
3318
0
      return INT_MAX;
3319
0
    }
3320
3321
0
    MV diag_step;
3322
0
    if (subpel_search_type > USE_2_TAPS) {
3323
0
      diag_step = first_level_check(xd, cm, iter_center_mv, bestmv, hstep,
3324
0
                                    mv_limits, var_params, mv_cost_params,
3325
0
                                    &besterr, sse1, distortion);
3326
0
    } else {
3327
0
      diag_step = first_level_check_fast(xd, cm, iter_center_mv, bestmv, hstep,
3328
0
                                         mv_limits, var_params, mv_cost_params,
3329
0
                                         &besterr, sse1, distortion, is_scaled);
3330
0
    }
3331
3332
    // Check diagonal sub-pixel position
3333
0
    if (!CHECK_MV_EQUAL(iter_center_mv, *bestmv) && iters_per_step > 1) {
3334
0
      second_level_check_v2(xd, cm, iter_center_mv, diag_step, bestmv,
3335
0
                            mv_limits, var_params, mv_cost_params, &besterr,
3336
0
                            sse1, distortion, is_scaled);
3337
0
    }
3338
3339
0
    hstep >>= 1;
3340
0
  }
3341
3342
0
  return besterr;
3343
0
}
3344
3345
// Note(yunqingwang): The following 2 functions are only used in the motion
3346
// vector unit test, which return extreme motion vectors allowed by the MV
3347
// limits.
3348
// Returns the maximum MV.
3349
int av1_return_max_sub_pixel_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3350
                                const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3351
                                MV start_mv,
3352
                                const FULLPEL_MV_STATS *start_mv_stats,
3353
                                MV *bestmv, int *distortion, unsigned int *sse1,
3354
0
                                int_mv *last_mv_search_list) {
3355
0
  (void)xd;
3356
0
  (void)cm;
3357
0
  (void)start_mv;
3358
0
  (void)start_mv_stats;
3359
0
  (void)last_mv_search_list;
3360
3361
0
  const int allow_hp = ms_params->allow_hp;
3362
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3363
3364
0
  bestmv->row = mv_limits->row_max;
3365
0
  bestmv->col = mv_limits->col_max;
3366
3367
0
  unsigned int besterr = 0;
3368
3369
  // In the sub-pel motion search, if hp is not used, then the last bit of mv
3370
  // has to be 0.
3371
0
  lower_mv_precision(bestmv, allow_hp, 0);
3372
0
  *distortion = besterr;
3373
0
  *sse1 = besterr;
3374
0
  return besterr;
3375
0
}
3376
3377
// Returns the minimum MV.
3378
int av1_return_min_sub_pixel_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3379
                                const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3380
                                MV start_mv,
3381
                                const FULLPEL_MV_STATS *start_mv_stats,
3382
                                MV *bestmv, int *distortion, unsigned int *sse1,
3383
0
                                int_mv *last_mv_search_list) {
3384
0
  (void)xd;
3385
0
  (void)cm;
3386
0
  (void)start_mv;
3387
0
  (void)start_mv_stats;
3388
0
  (void)last_mv_search_list;
3389
3390
0
  const int allow_hp = ms_params->allow_hp;
3391
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3392
3393
0
  bestmv->row = mv_limits->row_min;
3394
0
  bestmv->col = mv_limits->col_min;
3395
3396
0
  unsigned int besterr = 0;
3397
  // In the sub-pel motion search, if hp is not used, then the last bit of mv
3398
  // has to be 0.
3399
0
  lower_mv_precision(bestmv, allow_hp, 0);
3400
0
  *distortion = besterr;
3401
0
  *sse1 = besterr;
3402
0
  return besterr;
3403
0
}
3404
3405
#if !CONFIG_REALTIME_ONLY
3406
// Computes the cost of the current predictor by going through the whole
3407
// av1_enc_build_inter_predictor pipeline. This is mainly used by warped mv
3408
// during motion_mode_rd. We are going through the whole
3409
// av1_enc_build_inter_predictor because we might have changed the interpolation
3410
// filter, etc before motion_mode_rd is called.
3411
static inline unsigned int compute_motion_cost(
3412
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3413
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, BLOCK_SIZE bsize,
3414
0
    const MV *this_mv) {
3415
0
  unsigned int mse;
3416
0
  unsigned int sse;
3417
0
  const int mi_row = xd->mi_row;
3418
0
  const int mi_col = xd->mi_col;
3419
3420
0
  av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
3421
0
                                AOM_PLANE_Y, AOM_PLANE_Y);
3422
3423
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3424
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3425
3426
0
  const uint8_t *const src = ms_buffers->src->buf;
3427
0
  const int src_stride = ms_buffers->src->stride;
3428
0
  const uint8_t *const dst = xd->plane[0].dst.buf;
3429
0
  const int dst_stride = xd->plane[0].dst.stride;
3430
0
  const aom_variance_fn_ptr_t *vfp = ms_params->var_params.vfp;
3431
3432
0
  mse = vfp->vf(dst, dst_stride, src, src_stride, &sse);
3433
0
  mse += mv_err_cost_(this_mv, &ms_params->mv_cost_params);
3434
0
  return mse;
3435
0
}
3436
3437
// Refines MV in a small range
3438
3439
// Macros to build bitmasks which help us avoid redundant computations
3440
//
3441
// To explain the idea here, imagine that on the first iteration of the
3442
// loop below, we step rightwards. Then, on the second iteration, the neighbors
3443
// to consider are:
3444
//     . . .
3445
//     0 1 .
3446
//     . . .
3447
// Where 0 is the initial search point, 1 is the best candidate found in the
3448
// first iteration, and the dots are the other neighbors of point 1.
3449
//
3450
// Naively, we would now need to scan all 8 neighbors of point 1 (point 0 and
3451
// the seven points marked with dots), and compare them to see where to move
3452
// next. However, we already evaluated 5 of those 8 neighbors in the last
3453
// iteration, and decided that they are worse than point 1. So we don't need
3454
// to re-consider these points. We only really need to consider the three
3455
// points which are adjacent to point 1 but *not* to point 0.
3456
//
3457
// As the algorithm goes on, there are other ways that redundant evaluations
3458
// can happen, if the search path curls back around on itself.
3459
//
3460
// To avoid all possible redundancies, we'd have to build a set containing
3461
// every point we have already checked, and this would be quite expensive.
3462
//
3463
// So instead, we apply a 95%-effective solution with a much lower overhead:
3464
// we prune out the points which were considered during the previous
3465
// iteration, but we don't worry about any prior iteration. This can be done
3466
// as follows:
3467
//
3468
// We build a static table, called neighbor_mask, which answers the question
3469
// "if we moved in direction X last time, which neighbors are new, and which
3470
//  were scanned last iteration?"
3471
// Then we can query this table to quickly determine which points we need to
3472
// evaluate, and which we can skip.
3473
//
3474
// To query the table, the logic is simply:
3475
// neighbor_mask[i] & (1 << j) == "if we moved in direction i last iteration,
3476
//                             do we need to scan neighbor j this iteration?"
3477
#define NEIGHBOR_MASK_DIA(left, down, right, up) \
3478
  (left | (down << 1) | (right << 2) | (up << 3))
3479
3480
#define NEIGHBOR_MASK_SQR(left, down, right, up, down_left, down_right, \
3481
                          up_left, up_right)                            \
3482
  (left | (down << 1) | (right << 2) | (up << 3) | (down_left << 4) |   \
3483
   (down_right << 5) | (up_left << 6) | (up_right << 7))
3484
3485
static const warp_search_config warp_search_info[WARP_SEARCH_METHODS] = {
3486
  // WARP_SEARCH_DIAMOND
3487
  {
3488
    .num_neighbors = 4,
3489
    .neighbors = { {  0, -1 }, {  1,  0 }, {  0,  1 }, { -1,  0 } },
3490
    .neighbor_mask = {
3491
      // If we stepped left last time, consider all points except right
3492
      NEIGHBOR_MASK_DIA(1, 1, 0, 1),
3493
      // If we stepped down last time, consider all points except up
3494
      NEIGHBOR_MASK_DIA(1, 1, 1, 0),
3495
      // Stepped right last time
3496
      NEIGHBOR_MASK_DIA(0, 1, 1, 1),
3497
      // Stepped up last time
3498
      NEIGHBOR_MASK_DIA(1, 0, 1, 1),
3499
    },
3500
  },
3501
  // WARP_SEARCH_SQUARE
3502
  {
3503
    .num_neighbors = 8,
3504
    .neighbors = { {  0, -1 }, {  1,  0 }, {  0,  1 }, { -1,  0 },
3505
                   {  1, -1 }, {  1,  1 }, { -1, -1 }, { -1,  1 } },
3506
    .neighbor_mask = {
3507
      // If we stepped left last time, then we only need to consider 3 points:
3508
      // left, down+left, up+left
3509
      NEIGHBOR_MASK_SQR(1, 0, 0, 0, 1, 0, 1, 0),
3510
      // If we stepped down last time, then we only need to consider 3 points:
3511
      // down, down+left, down+right
3512
      NEIGHBOR_MASK_SQR(0, 1, 0, 0, 1, 1, 0, 0),
3513
      // Stepped right last time
3514
      NEIGHBOR_MASK_SQR(0, 0, 1, 0, 0, 1, 0, 1),
3515
      // Stepped up last time
3516
      NEIGHBOR_MASK_SQR(0, 0, 0, 1, 0, 0, 1, 1),
3517
3518
      // If we stepped down+left last time, then we need to consider 5 points:
3519
      // left, down, down+left, down+right, up+left
3520
      NEIGHBOR_MASK_SQR(1, 1, 0, 0, 1, 1, 1, 0),
3521
      // Stepped down+right last time
3522
      NEIGHBOR_MASK_SQR(0, 1, 1, 0, 1, 1, 0, 1),
3523
      // Stepped up+left last time
3524
      NEIGHBOR_MASK_SQR(1, 0, 0, 1, 1, 0, 1, 1),
3525
      // Stepped up+right last time
3526
      NEIGHBOR_MASK_SQR(0, 0, 1, 1, 0, 1, 1, 1),
3527
    },
3528
  },
3529
};
3530
3531
unsigned int av1_refine_warped_mv(MACROBLOCKD *xd, const AV1_COMMON *const cm,
3532
                                  const SUBPEL_MOTION_SEARCH_PARAMS *ms_params,
3533
                                  BLOCK_SIZE bsize, const int *pts0,
3534
                                  const int *pts_inref0, int total_samples,
3535
                                  WARP_SEARCH_METHOD search_method,
3536
0
                                  int num_iterations) {
3537
0
  MB_MODE_INFO *mbmi = xd->mi[0];
3538
3539
0
  const MV *neighbors = warp_search_info[search_method].neighbors;
3540
0
  const int num_neighbors = warp_search_info[search_method].num_neighbors;
3541
0
  const uint8_t *neighbor_mask = warp_search_info[search_method].neighbor_mask;
3542
3543
0
  MV *best_mv = &mbmi->mv[0].as_mv;
3544
3545
0
  WarpedMotionParams best_wm_params = mbmi->wm_params;
3546
0
  int best_num_proj_ref = mbmi->num_proj_ref;
3547
0
  unsigned int bestmse;
3548
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3549
3550
0
  const int mv_shift = ms_params->allow_hp ? 0 : 1;
3551
3552
  // Calculate the center position's error
3553
0
  assert(av1_is_subpelmv_in_range(mv_limits, *best_mv));
3554
0
  bestmse = compute_motion_cost(xd, cm, ms_params, bsize, best_mv);
3555
3556
  // MV search
3557
0
  int pts[SAMPLES_ARRAY_SIZE], pts_inref[SAMPLES_ARRAY_SIZE];
3558
0
  const int mi_row = xd->mi_row;
3559
0
  const int mi_col = xd->mi_col;
3560
3561
  // First step always scans all neighbors
3562
0
  uint8_t valid_neighbors = UINT8_MAX;
3563
3564
0
  for (int ite = 0; ite < num_iterations; ++ite) {
3565
0
    int best_idx = -1;
3566
3567
0
    for (int idx = 0; idx < num_neighbors; ++idx) {
3568
0
      if ((valid_neighbors & (1 << idx)) == 0) {
3569
0
        continue;
3570
0
      }
3571
3572
0
      unsigned int thismse;
3573
3574
0
      MV this_mv = { best_mv->row + neighbors[idx].row * (1 << mv_shift),
3575
0
                     best_mv->col + neighbors[idx].col * (1 << mv_shift) };
3576
0
      if (av1_is_subpelmv_in_range(mv_limits, this_mv)) {
3577
0
        memcpy(pts, pts0, total_samples * 2 * sizeof(*pts0));
3578
0
        memcpy(pts_inref, pts_inref0, total_samples * 2 * sizeof(*pts_inref0));
3579
0
        if (total_samples > 1) {
3580
0
          mbmi->num_proj_ref =
3581
0
              av1_selectSamples(&this_mv, pts, pts_inref, total_samples, bsize);
3582
0
        }
3583
3584
0
        if (!av1_find_projection(mbmi->num_proj_ref, pts, pts_inref, bsize,
3585
0
                                 this_mv.row, this_mv.col, &mbmi->wm_params,
3586
0
                                 mi_row, mi_col)) {
3587
0
          thismse = compute_motion_cost(xd, cm, ms_params, bsize, &this_mv);
3588
3589
0
          if (thismse < bestmse) {
3590
0
            best_idx = idx;
3591
0
            best_wm_params = mbmi->wm_params;
3592
0
            best_num_proj_ref = mbmi->num_proj_ref;
3593
0
            bestmse = thismse;
3594
0
          }
3595
0
        }
3596
0
      }
3597
0
    }
3598
3599
0
    if (best_idx == -1) break;
3600
3601
0
    if (best_idx >= 0) {
3602
0
      best_mv->row += neighbors[best_idx].row * (1 << mv_shift);
3603
0
      best_mv->col += neighbors[best_idx].col * (1 << mv_shift);
3604
0
      valid_neighbors = neighbor_mask[best_idx];
3605
0
    }
3606
0
  }
3607
3608
0
  mbmi->wm_params = best_wm_params;
3609
0
  mbmi->num_proj_ref = best_num_proj_ref;
3610
0
  return bestmse;
3611
0
}
3612
3613
#endif  // !CONFIG_REALTIME_ONLY
3614
// =============================================================================
3615
//  Subpixel Motion Search: OBMC
3616
// =============================================================================
3617
// Estimates the variance of prediction residue
3618
static inline int estimate_obmc_pref_error(
3619
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3620
0
    unsigned int *sse) {
3621
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
3622
3623
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3624
0
  const int32_t *src = ms_buffers->wsrc;
3625
0
  const int32_t *mask = ms_buffers->obmc_mask;
3626
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
3627
0
  const int ref_stride = ms_buffers->ref->stride;
3628
3629
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
3630
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
3631
3632
0
  return vfp->osvf(ref, ref_stride, subpel_x_q3, subpel_y_q3, src, mask, sse);
3633
0
}
3634
3635
// Calculates the variance of prediction residue
3636
static int upsampled_obmc_pref_error(MACROBLOCKD *xd, const AV1_COMMON *cm,
3637
                                     const MV *this_mv,
3638
                                     const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3639
0
                                     unsigned int *sse) {
3640
0
  const aom_variance_fn_ptr_t *vfp = var_params->vfp;
3641
0
  const SUBPEL_SEARCH_TYPE subpel_search_type = var_params->subpel_search_type;
3642
0
  const int w = var_params->w;
3643
0
  const int h = var_params->h;
3644
3645
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3646
0
  const int32_t *wsrc = ms_buffers->wsrc;
3647
0
  const int32_t *mask = ms_buffers->obmc_mask;
3648
0
  const uint8_t *ref = get_buf_from_mv(ms_buffers->ref, *this_mv);
3649
0
  const int ref_stride = ms_buffers->ref->stride;
3650
3651
0
  const int subpel_x_q3 = get_subpel_part(this_mv->col);
3652
0
  const int subpel_y_q3 = get_subpel_part(this_mv->row);
3653
3654
0
  const int mi_row = xd->mi_row;
3655
0
  const int mi_col = xd->mi_col;
3656
3657
0
  unsigned int besterr;
3658
0
#if CONFIG_AV1_HIGHBITDEPTH
3659
0
  if (is_cur_buf_hbd(xd)) {
3660
0
    uint16_t *pred16 = (uint16_t *)(xd->tmp_upsample_pred);
3661
0
    uint8_t *pred8 = CONVERT_TO_BYTEPTR(pred16);
3662
0
    aom_highbd_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred8, w, h,
3663
0
                              subpel_x_q3, subpel_y_q3, ref, ref_stride, xd->bd,
3664
0
                              subpel_search_type);
3665
0
    besterr = vfp->ovf(pred8, w, wsrc, mask, sse);
3666
0
  } else {
3667
0
    uint8_t *pred = xd->tmp_upsample_pred;
3668
0
    aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
3669
0
                       subpel_y_q3, ref, ref_stride, subpel_search_type);
3670
3671
0
    besterr = vfp->ovf(pred, w, wsrc, mask, sse);
3672
0
  }
3673
#else
3674
  uint8_t *pred = xd->tmp_upsample_pred;
3675
  aom_upsampled_pred(xd, cm, mi_row, mi_col, this_mv, pred, w, h, subpel_x_q3,
3676
                     subpel_y_q3, ref, ref_stride, subpel_search_type);
3677
3678
  besterr = vfp->ovf(pred, w, wsrc, mask, sse);
3679
#endif
3680
0
  return besterr;
3681
0
}
3682
3683
static unsigned int setup_obmc_center_error(
3684
    const MV *this_mv, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3685
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
3686
  // TODO(chiyotsai@google.com): There might be a bug here where we didn't use
3687
  // get_buf_from_mv(ref, *this_mv).
3688
0
  const MSBuffers *ms_buffers = &var_params->ms_buffers;
3689
0
  const int32_t *wsrc = ms_buffers->wsrc;
3690
0
  const int32_t *mask = ms_buffers->obmc_mask;
3691
0
  const uint8_t *ref = ms_buffers->ref->buf;
3692
0
  const int ref_stride = ms_buffers->ref->stride;
3693
0
  unsigned int besterr =
3694
0
      var_params->vfp->ovf(ref, ref_stride, wsrc, mask, sse1);
3695
0
  *distortion = besterr;
3696
0
  besterr += mv_err_cost_(this_mv, mv_cost_params);
3697
0
  return besterr;
3698
0
}
3699
3700
static unsigned int upsampled_setup_obmc_center_error(
3701
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV *this_mv,
3702
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3703
0
    const MV_COST_PARAMS *mv_cost_params, unsigned int *sse1, int *distortion) {
3704
0
  unsigned int besterr =
3705
0
      upsampled_obmc_pref_error(xd, cm, this_mv, var_params, sse1);
3706
0
  *distortion = besterr;
3707
0
  besterr += mv_err_cost_(this_mv, mv_cost_params);
3708
0
  return besterr;
3709
0
}
3710
3711
// Estimates the variance of prediction residue
3712
// TODO(chiyotsai@google.com): the cost does does not match the cost in
3713
// mv_cost_. Investigate this later.
3714
static inline int estimate_obmc_mvcost(const MV *this_mv,
3715
0
                                       const MV_COST_PARAMS *mv_cost_params) {
3716
0
  const MV *ref_mv = mv_cost_params->ref_mv;
3717
0
  const int *mvjcost = mv_cost_params->mvjcost;
3718
0
  const int *const *mvcost = mv_cost_params->mvcost;
3719
0
  const int error_per_bit = mv_cost_params->error_per_bit;
3720
0
  const MV_COST_TYPE mv_cost_type = mv_cost_params->mv_cost_type;
3721
0
  const MV diff_mv = { GET_MV_SUBPEL(this_mv->row - ref_mv->row),
3722
0
                       GET_MV_SUBPEL(this_mv->col - ref_mv->col) };
3723
3724
0
  switch (mv_cost_type) {
3725
0
    case MV_COST_ENTROPY:
3726
0
      return (unsigned)((mv_cost(&diff_mv, mvjcost,
3727
0
                                 CONVERT_TO_CONST_MVCOST(mvcost)) *
3728
0
                             error_per_bit +
3729
0
                         4096) >>
3730
0
                        13);
3731
0
    case MV_COST_NONE: return 0;
3732
0
    default:
3733
0
      assert(0 && "L1 norm is not tuned for estimated obmc mvcost");
3734
0
      return 0;
3735
0
  }
3736
0
}
3737
3738
// Estimates whether this_mv is better than best_mv. This function incorporates
3739
// both prediction error and residue into account.
3740
static inline unsigned int obmc_check_better_fast(
3741
    const MV *this_mv, MV *best_mv, const SubpelMvLimits *mv_limits,
3742
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3743
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3744
0
    unsigned int *sse1, int *distortion, int *has_better_mv) {
3745
0
  unsigned int cost;
3746
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
3747
0
    unsigned int sse;
3748
0
    const int thismse = estimate_obmc_pref_error(this_mv, var_params, &sse);
3749
3750
0
    cost = estimate_obmc_mvcost(this_mv, mv_cost_params);
3751
0
    cost += thismse;
3752
3753
0
    if (cost < *besterr) {
3754
0
      *besterr = cost;
3755
0
      *best_mv = *this_mv;
3756
0
      *distortion = thismse;
3757
0
      *sse1 = sse;
3758
0
      *has_better_mv |= 1;
3759
0
    }
3760
0
  } else {
3761
0
    cost = INT_MAX;
3762
0
  }
3763
0
  return cost;
3764
0
}
3765
3766
// Estimates whether this_mv is better than best_mv. This function incorporates
3767
// both prediction error and residue into account.
3768
static inline unsigned int obmc_check_better(
3769
    MACROBLOCKD *xd, const AV1_COMMON *cm, const MV *this_mv, MV *best_mv,
3770
    const SubpelMvLimits *mv_limits, const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3771
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3772
0
    unsigned int *sse1, int *distortion, int *has_better_mv) {
3773
0
  unsigned int cost;
3774
0
  if (av1_is_subpelmv_in_range(mv_limits, *this_mv)) {
3775
0
    unsigned int sse;
3776
0
    const int thismse =
3777
0
        upsampled_obmc_pref_error(xd, cm, this_mv, var_params, &sse);
3778
0
    cost = mv_err_cost_(this_mv, mv_cost_params);
3779
3780
0
    cost += thismse;
3781
3782
0
    if (cost < *besterr) {
3783
0
      *besterr = cost;
3784
0
      *best_mv = *this_mv;
3785
0
      *distortion = thismse;
3786
0
      *sse1 = sse;
3787
0
      *has_better_mv |= 1;
3788
0
    }
3789
0
  } else {
3790
0
    cost = INT_MAX;
3791
0
  }
3792
0
  return cost;
3793
0
}
3794
3795
static AOM_FORCE_INLINE MV obmc_first_level_check(
3796
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV *best_mv,
3797
    const int hstep, const SubpelMvLimits *mv_limits,
3798
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3799
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3800
0
    unsigned int *sse1, int *distortion) {
3801
0
  int dummy = 0;
3802
0
  const MV left_mv = { this_mv.row, this_mv.col - hstep };
3803
0
  const MV right_mv = { this_mv.row, this_mv.col + hstep };
3804
0
  const MV top_mv = { this_mv.row - hstep, this_mv.col };
3805
0
  const MV bottom_mv = { this_mv.row + hstep, this_mv.col };
3806
3807
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
3808
0
    const unsigned int left =
3809
0
        obmc_check_better(xd, cm, &left_mv, best_mv, mv_limits, var_params,
3810
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3811
0
    const unsigned int right =
3812
0
        obmc_check_better(xd, cm, &right_mv, best_mv, mv_limits, var_params,
3813
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3814
0
    const unsigned int up =
3815
0
        obmc_check_better(xd, cm, &top_mv, best_mv, mv_limits, var_params,
3816
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3817
0
    const unsigned int down =
3818
0
        obmc_check_better(xd, cm, &bottom_mv, best_mv, mv_limits, var_params,
3819
0
                          mv_cost_params, besterr, sse1, distortion, &dummy);
3820
3821
0
    const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
3822
0
    const MV diag_mv = { this_mv.row + diag_step.row,
3823
0
                         this_mv.col + diag_step.col };
3824
3825
    // Check the diagonal direction with the best mv
3826
0
    obmc_check_better(xd, cm, &diag_mv, best_mv, mv_limits, var_params,
3827
0
                      mv_cost_params, besterr, sse1, distortion, &dummy);
3828
3829
0
    return diag_step;
3830
0
  } else {
3831
0
    const unsigned int left = obmc_check_better_fast(
3832
0
        &left_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr, sse1,
3833
0
        distortion, &dummy);
3834
0
    const unsigned int right = obmc_check_better_fast(
3835
0
        &right_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
3836
0
        sse1, distortion, &dummy);
3837
3838
0
    const unsigned int up = obmc_check_better_fast(
3839
0
        &top_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr, sse1,
3840
0
        distortion, &dummy);
3841
3842
0
    const unsigned int down = obmc_check_better_fast(
3843
0
        &bottom_mv, best_mv, mv_limits, var_params, mv_cost_params, besterr,
3844
0
        sse1, distortion, &dummy);
3845
3846
0
    const MV diag_step = get_best_diag_step(hstep, left, right, up, down);
3847
0
    const MV diag_mv = { this_mv.row + diag_step.row,
3848
0
                         this_mv.col + diag_step.col };
3849
3850
    // Check the diagonal direction with the best mv
3851
0
    obmc_check_better_fast(&diag_mv, best_mv, mv_limits, var_params,
3852
0
                           mv_cost_params, besterr, sse1, distortion, &dummy);
3853
3854
0
    return diag_step;
3855
0
  }
3856
0
}
3857
3858
// A newer version of second level check for obmc that gives better quality.
3859
static AOM_FORCE_INLINE void obmc_second_level_check_v2(
3860
    MACROBLOCKD *xd, const AV1_COMMON *const cm, const MV this_mv, MV diag_step,
3861
    MV *best_mv, const SubpelMvLimits *mv_limits,
3862
    const SUBPEL_SEARCH_VAR_PARAMS *var_params,
3863
    const MV_COST_PARAMS *mv_cost_params, unsigned int *besterr,
3864
0
    unsigned int *sse1, int *distortion) {
3865
0
  assert(best_mv->row == this_mv.row + diag_step.row ||
3866
0
         best_mv->col == this_mv.col + diag_step.col);
3867
0
  if (CHECK_MV_EQUAL(this_mv, *best_mv)) {
3868
0
    return;
3869
0
  } else if (this_mv.row == best_mv->row) {
3870
    // Search away from diagonal step since diagonal search did not provide any
3871
    // improvement
3872
0
    diag_step.row *= -1;
3873
0
  } else if (this_mv.col == best_mv->col) {
3874
0
    diag_step.col *= -1;
3875
0
  }
3876
3877
0
  const MV row_bias_mv = { best_mv->row + diag_step.row, best_mv->col };
3878
0
  const MV col_bias_mv = { best_mv->row, best_mv->col + diag_step.col };
3879
0
  const MV diag_bias_mv = { best_mv->row + diag_step.row,
3880
0
                            best_mv->col + diag_step.col };
3881
0
  int has_better_mv = 0;
3882
3883
0
  if (var_params->subpel_search_type != USE_2_TAPS_ORIG) {
3884
0
    obmc_check_better(xd, cm, &row_bias_mv, best_mv, mv_limits, var_params,
3885
0
                      mv_cost_params, besterr, sse1, distortion,
3886
0
                      &has_better_mv);
3887
0
    obmc_check_better(xd, cm, &col_bias_mv, best_mv, mv_limits, var_params,
3888
0
                      mv_cost_params, besterr, sse1, distortion,
3889
0
                      &has_better_mv);
3890
3891
    // Do an additional search if the second iteration gives a better mv
3892
0
    if (has_better_mv) {
3893
0
      obmc_check_better(xd, cm, &diag_bias_mv, best_mv, mv_limits, var_params,
3894
0
                        mv_cost_params, besterr, sse1, distortion,
3895
0
                        &has_better_mv);
3896
0
    }
3897
0
  } else {
3898
0
    obmc_check_better_fast(&row_bias_mv, best_mv, mv_limits, var_params,
3899
0
                           mv_cost_params, besterr, sse1, distortion,
3900
0
                           &has_better_mv);
3901
0
    obmc_check_better_fast(&col_bias_mv, best_mv, mv_limits, var_params,
3902
0
                           mv_cost_params, besterr, sse1, distortion,
3903
0
                           &has_better_mv);
3904
3905
    // Do an additional search if the second iteration gives a better mv
3906
0
    if (has_better_mv) {
3907
0
      obmc_check_better_fast(&diag_bias_mv, best_mv, mv_limits, var_params,
3908
0
                             mv_cost_params, besterr, sse1, distortion,
3909
0
                             &has_better_mv);
3910
0
    }
3911
0
  }
3912
0
}
3913
3914
int av1_find_best_obmc_sub_pixel_tree_up(
3915
    MACROBLOCKD *xd, const AV1_COMMON *const cm,
3916
    const SUBPEL_MOTION_SEARCH_PARAMS *ms_params, MV start_mv,
3917
    const FULLPEL_MV_STATS *start_mv_stats, MV *bestmv, int *distortion,
3918
0
    unsigned int *sse1, int_mv *last_mv_search_list) {
3919
0
  (void)last_mv_search_list;
3920
0
  (void)start_mv_stats;
3921
0
  const int allow_hp = ms_params->allow_hp;
3922
0
  const int forced_stop = ms_params->forced_stop;
3923
0
  const int iters_per_step = ms_params->iters_per_step;
3924
0
  const MV_COST_PARAMS *mv_cost_params = &ms_params->mv_cost_params;
3925
0
  const SUBPEL_SEARCH_VAR_PARAMS *var_params = &ms_params->var_params;
3926
0
  const SUBPEL_SEARCH_TYPE subpel_search_type =
3927
0
      ms_params->var_params.subpel_search_type;
3928
0
  const SubpelMvLimits *mv_limits = &ms_params->mv_limits;
3929
3930
0
  int hstep = INIT_SUBPEL_STEP_SIZE;
3931
0
  const int round = AOMMIN(FULL_PEL - forced_stop, 3 - !allow_hp);
3932
3933
0
  unsigned int besterr = INT_MAX;
3934
0
  *bestmv = start_mv;
3935
3936
0
  if (subpel_search_type != USE_2_TAPS_ORIG)
3937
0
    besterr = upsampled_setup_obmc_center_error(
3938
0
        xd, cm, bestmv, var_params, mv_cost_params, sse1, distortion);
3939
0
  else
3940
0
    besterr = setup_obmc_center_error(bestmv, var_params, mv_cost_params, sse1,
3941
0
                                      distortion);
3942
3943
0
  for (int iter = 0; iter < round; ++iter) {
3944
0
    MV iter_center_mv = *bestmv;
3945
0
    MV diag_step = obmc_first_level_check(xd, cm, iter_center_mv, bestmv, hstep,
3946
0
                                          mv_limits, var_params, mv_cost_params,
3947
0
                                          &besterr, sse1, distortion);
3948
3949
0
    if (!CHECK_MV_EQUAL(iter_center_mv, *bestmv) && iters_per_step > 1) {
3950
0
      obmc_second_level_check_v2(xd, cm, iter_center_mv, diag_step, bestmv,
3951
0
                                 mv_limits, var_params, mv_cost_params,
3952
0
                                 &besterr, sse1, distortion);
3953
0
    }
3954
0
    hstep >>= 1;
3955
0
  }
3956
3957
0
  return besterr;
3958
0
}
3959
3960
// =============================================================================
3961
//  Public cost function: mv_cost + pred error
3962
// =============================================================================
3963
int av1_get_mvpred_sse(const MV_COST_PARAMS *mv_cost_params,
3964
                       const FULLPEL_MV best_mv,
3965
                       const aom_variance_fn_ptr_t *vfp,
3966
0
                       const struct buf_2d *src, const struct buf_2d *pre) {
3967
0
  const MV mv = get_mv_from_fullmv(&best_mv);
3968
0
  unsigned int sse, var;
3969
3970
0
  var = vfp->vf(src->buf, src->stride, get_buf_from_fullmv(pre, &best_mv),
3971
0
                pre->stride, &sse);
3972
0
  (void)var;
3973
3974
0
  return sse + mv_err_cost_(&mv, mv_cost_params);
3975
0
}