Coverage Report

Created: 2025-06-22 08:04

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