Coverage Report

Created: 2025-06-22 08:04

/src/aom/av1/encoder/pickrst.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 <float.h>
14
#include <limits.h>
15
#include <math.h>
16
17
#include "config/aom_scale_rtcd.h"
18
#include "config/av1_rtcd.h"
19
20
#include "aom_dsp/aom_dsp_common.h"
21
#include "aom_dsp/binary_codes_writer.h"
22
#include "aom_dsp/mathutils.h"
23
#include "aom_dsp/psnr.h"
24
#include "aom_mem/aom_mem.h"
25
#include "aom_ports/mem.h"
26
#include "av1/common/av1_common_int.h"
27
#include "av1/common/quant_common.h"
28
#include "av1/common/restoration.h"
29
30
#include "av1/encoder/av1_quantize.h"
31
#include "av1/encoder/encoder.h"
32
#include "av1/encoder/picklpf.h"
33
#include "av1/encoder/pickrst.h"
34
35
// Number of Wiener iterations
36
0
#define NUM_WIENER_ITERS 5
37
38
// Penalty factor for use of dual sgr
39
0
#define DUAL_SGR_PENALTY_MULT 0.01
40
41
// Working precision for Wiener filter coefficients
42
0
#define WIENER_TAP_SCALE_FACTOR ((int64_t)1 << 16)
43
44
0
#define SGRPROJ_EP_GRP1_START_IDX 0
45
0
#define SGRPROJ_EP_GRP1_END_IDX 9
46
0
#define SGRPROJ_EP_GRP1_SEARCH_COUNT 4
47
0
#define SGRPROJ_EP_GRP2_3_SEARCH_COUNT 2
48
static const int sgproj_ep_grp1_seed[SGRPROJ_EP_GRP1_SEARCH_COUNT] = { 0, 3, 6,
49
                                                                       9 };
50
static const int sgproj_ep_grp2_3[SGRPROJ_EP_GRP2_3_SEARCH_COUNT][14] = {
51
  { 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, -1, -1, -1, -1 },
52
  { 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15 }
53
};
54
55
#if DEBUG_LR_COSTING
56
RestorationUnitInfo lr_ref_params[RESTORE_TYPES][MAX_MB_PLANE]
57
                                 [MAX_LR_UNITS_W * MAX_LR_UNITS_H];
58
#endif  // DEBUG_LR_COSTING
59
60
typedef int64_t (*sse_extractor_type)(const YV12_BUFFER_CONFIG *a,
61
                                      const YV12_BUFFER_CONFIG *b);
62
typedef int64_t (*sse_part_extractor_type)(const YV12_BUFFER_CONFIG *a,
63
                                           const YV12_BUFFER_CONFIG *b,
64
                                           int hstart, int width, int vstart,
65
                                           int height);
66
typedef uint64_t (*var_part_extractor_type)(const YV12_BUFFER_CONFIG *a,
67
                                            int hstart, int width, int vstart,
68
                                            int height);
69
70
#if CONFIG_AV1_HIGHBITDEPTH
71
#define NUM_EXTRACTORS (3 * (1 + 1))
72
#else
73
#define NUM_EXTRACTORS 3
74
#endif
75
static const sse_part_extractor_type sse_part_extractors[NUM_EXTRACTORS] = {
76
  aom_get_y_sse_part,        aom_get_u_sse_part,
77
  aom_get_v_sse_part,
78
#if CONFIG_AV1_HIGHBITDEPTH
79
  aom_highbd_get_y_sse_part, aom_highbd_get_u_sse_part,
80
  aom_highbd_get_v_sse_part,
81
#endif
82
};
83
static const var_part_extractor_type var_part_extractors[NUM_EXTRACTORS] = {
84
  aom_get_y_var,        aom_get_u_var,        aom_get_v_var,
85
#if CONFIG_AV1_HIGHBITDEPTH
86
  aom_highbd_get_y_var, aom_highbd_get_u_var, aom_highbd_get_v_var,
87
#endif
88
};
89
90
static int64_t sse_restoration_unit(const RestorationTileLimits *limits,
91
                                    const YV12_BUFFER_CONFIG *src,
92
                                    const YV12_BUFFER_CONFIG *dst, int plane,
93
0
                                    int highbd) {
94
0
  return sse_part_extractors[3 * highbd + plane](
95
0
      src, dst, limits->h_start, limits->h_end - limits->h_start,
96
0
      limits->v_start, limits->v_end - limits->v_start);
97
0
}
98
99
static uint64_t var_restoration_unit(const RestorationTileLimits *limits,
100
                                     const YV12_BUFFER_CONFIG *src, int plane,
101
0
                                     int highbd) {
102
0
  return var_part_extractors[3 * highbd + plane](
103
0
      src, limits->h_start, limits->h_end - limits->h_start, limits->v_start,
104
0
      limits->v_end - limits->v_start);
105
0
}
106
107
typedef struct {
108
  const YV12_BUFFER_CONFIG *src;
109
  YV12_BUFFER_CONFIG *dst;
110
111
  const AV1_COMMON *cm;
112
  const MACROBLOCK *x;
113
  int plane;
114
  int plane_w;
115
  int plane_h;
116
  RestUnitSearchInfo *rusi;
117
118
  // Speed features
119
  const LOOP_FILTER_SPEED_FEATURES *lpf_sf;
120
121
  uint8_t *dgd_buffer;
122
  int dgd_stride;
123
  const uint8_t *src_buffer;
124
  int src_stride;
125
126
  // SSE values for each restoration mode for the current RU
127
  // These are saved by each search function for use in search_switchable()
128
  int64_t sse[RESTORE_SWITCHABLE_TYPES];
129
130
  // This flag will be set based on the speed feature
131
  // 'prune_sgr_based_on_wiener'. 0 implies no pruning and 1 implies pruning.
132
  uint8_t skip_sgr_eval;
133
134
  // Total rate and distortion so far for each restoration type
135
  // These are initialised by reset_rsc in search_rest_type
136
  int64_t total_sse[RESTORE_TYPES];
137
  int64_t total_bits[RESTORE_TYPES];
138
139
  // Reference parameters for delta-coding
140
  //
141
  // For each restoration type, we need to store the latest parameter set which
142
  // has been used, so that we can properly cost up the next parameter set.
143
  // Note that we have two sets of these - one for the single-restoration-mode
144
  // search (ie, frame_restoration_type = RESTORE_WIENER or RESTORE_SGRPROJ)
145
  // and one for the switchable mode. This is because these two cases can lead
146
  // to different sets of parameters being signaled, but we don't know which
147
  // we will pick for sure until the end of the search process.
148
  WienerInfo ref_wiener;
149
  SgrprojInfo ref_sgrproj;
150
  WienerInfo switchable_ref_wiener;
151
  SgrprojInfo switchable_ref_sgrproj;
152
153
  // Buffers used to hold dgd-avg and src-avg data respectively during SIMD
154
  // call of Wiener filter.
155
  int16_t *dgd_avg;
156
  int16_t *src_avg;
157
} RestSearchCtxt;
158
159
0
static inline void rsc_on_tile(void *priv) {
160
0
  RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
161
0
  set_default_wiener(&rsc->ref_wiener);
162
0
  set_default_sgrproj(&rsc->ref_sgrproj);
163
0
  set_default_wiener(&rsc->switchable_ref_wiener);
164
0
  set_default_sgrproj(&rsc->switchable_ref_sgrproj);
165
0
}
166
167
0
static inline void reset_rsc(RestSearchCtxt *rsc) {
168
0
  memset(rsc->total_sse, 0, sizeof(rsc->total_sse));
169
0
  memset(rsc->total_bits, 0, sizeof(rsc->total_bits));
170
0
}
171
172
static inline void init_rsc(const YV12_BUFFER_CONFIG *src, const AV1_COMMON *cm,
173
                            const MACROBLOCK *x,
174
                            const LOOP_FILTER_SPEED_FEATURES *lpf_sf, int plane,
175
                            RestUnitSearchInfo *rusi, YV12_BUFFER_CONFIG *dst,
176
0
                            RestSearchCtxt *rsc) {
177
0
  rsc->src = src;
178
0
  rsc->dst = dst;
179
0
  rsc->cm = cm;
180
0
  rsc->x = x;
181
0
  rsc->plane = plane;
182
0
  rsc->rusi = rusi;
183
0
  rsc->lpf_sf = lpf_sf;
184
185
0
  const YV12_BUFFER_CONFIG *dgd = &cm->cur_frame->buf;
186
0
  const int is_uv = plane != AOM_PLANE_Y;
187
0
  int plane_w, plane_h;
188
0
  av1_get_upsampled_plane_size(cm, is_uv, &plane_w, &plane_h);
189
0
  assert(plane_w == src->crop_widths[is_uv]);
190
0
  assert(plane_h == src->crop_heights[is_uv]);
191
0
  assert(src->crop_widths[is_uv] == dgd->crop_widths[is_uv]);
192
0
  assert(src->crop_heights[is_uv] == dgd->crop_heights[is_uv]);
193
194
0
  rsc->plane_w = plane_w;
195
0
  rsc->plane_h = plane_h;
196
0
  rsc->src_buffer = src->buffers[plane];
197
0
  rsc->src_stride = src->strides[is_uv];
198
0
  rsc->dgd_buffer = dgd->buffers[plane];
199
0
  rsc->dgd_stride = dgd->strides[is_uv];
200
0
}
201
202
static int64_t try_restoration_unit(const RestSearchCtxt *rsc,
203
                                    const RestorationTileLimits *limits,
204
0
                                    const RestorationUnitInfo *rui) {
205
0
  const AV1_COMMON *const cm = rsc->cm;
206
0
  const int plane = rsc->plane;
207
0
  const int is_uv = plane > 0;
208
0
  const RestorationInfo *rsi = &cm->rst_info[plane];
209
0
  RestorationLineBuffers rlbs;
210
0
  const int bit_depth = cm->seq_params->bit_depth;
211
0
  const int highbd = cm->seq_params->use_highbitdepth;
212
213
0
  const YV12_BUFFER_CONFIG *fts = &cm->cur_frame->buf;
214
  // TODO(yunqing): For now, only use optimized LR filter in decoder. Can be
215
  // also used in encoder.
216
0
  const int optimized_lr = 0;
217
218
0
  av1_loop_restoration_filter_unit(
219
0
      limits, rui, &rsi->boundaries, &rlbs, rsc->plane_w, rsc->plane_h,
220
0
      is_uv && cm->seq_params->subsampling_x,
221
0
      is_uv && cm->seq_params->subsampling_y, highbd, bit_depth,
222
0
      fts->buffers[plane], fts->strides[is_uv], rsc->dst->buffers[plane],
223
0
      rsc->dst->strides[is_uv], cm->rst_tmpbuf, optimized_lr, cm->error);
224
225
0
  return sse_restoration_unit(limits, rsc->src, rsc->dst, plane, highbd);
226
0
}
227
228
int64_t av1_lowbd_pixel_proj_error_c(const uint8_t *src8, int width, int height,
229
                                     int src_stride, const uint8_t *dat8,
230
                                     int dat_stride, int32_t *flt0,
231
                                     int flt0_stride, int32_t *flt1,
232
                                     int flt1_stride, int xq[2],
233
0
                                     const sgr_params_type *params) {
234
0
  int i, j;
235
0
  const uint8_t *src = src8;
236
0
  const uint8_t *dat = dat8;
237
0
  int64_t err = 0;
238
0
  if (params->r[0] > 0 && params->r[1] > 0) {
239
0
    for (i = 0; i < height; ++i) {
240
0
      for (j = 0; j < width; ++j) {
241
0
        assert(flt1[j] < (1 << 15) && flt1[j] > -(1 << 15));
242
0
        assert(flt0[j] < (1 << 15) && flt0[j] > -(1 << 15));
243
0
        const int32_t u = (int32_t)(dat[j] << SGRPROJ_RST_BITS);
244
0
        int32_t v = u << SGRPROJ_PRJ_BITS;
245
0
        v += xq[0] * (flt0[j] - u) + xq[1] * (flt1[j] - u);
246
0
        const int32_t e =
247
0
            ROUND_POWER_OF_TWO(v, SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS) - src[j];
248
0
        err += ((int64_t)e * e);
249
0
      }
250
0
      dat += dat_stride;
251
0
      src += src_stride;
252
0
      flt0 += flt0_stride;
253
0
      flt1 += flt1_stride;
254
0
    }
255
0
  } else if (params->r[0] > 0) {
256
0
    for (i = 0; i < height; ++i) {
257
0
      for (j = 0; j < width; ++j) {
258
0
        assert(flt0[j] < (1 << 15) && flt0[j] > -(1 << 15));
259
0
        const int32_t u = (int32_t)(dat[j] << SGRPROJ_RST_BITS);
260
0
        int32_t v = u << SGRPROJ_PRJ_BITS;
261
0
        v += xq[0] * (flt0[j] - u);
262
0
        const int32_t e =
263
0
            ROUND_POWER_OF_TWO(v, SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS) - src[j];
264
0
        err += ((int64_t)e * e);
265
0
      }
266
0
      dat += dat_stride;
267
0
      src += src_stride;
268
0
      flt0 += flt0_stride;
269
0
    }
270
0
  } else if (params->r[1] > 0) {
271
0
    for (i = 0; i < height; ++i) {
272
0
      for (j = 0; j < width; ++j) {
273
0
        assert(flt1[j] < (1 << 15) && flt1[j] > -(1 << 15));
274
0
        const int32_t u = (int32_t)(dat[j] << SGRPROJ_RST_BITS);
275
0
        int32_t v = u << SGRPROJ_PRJ_BITS;
276
0
        v += xq[1] * (flt1[j] - u);
277
0
        const int32_t e =
278
0
            ROUND_POWER_OF_TWO(v, SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS) - src[j];
279
0
        err += ((int64_t)e * e);
280
0
      }
281
0
      dat += dat_stride;
282
0
      src += src_stride;
283
0
      flt1 += flt1_stride;
284
0
    }
285
0
  } else {
286
0
    for (i = 0; i < height; ++i) {
287
0
      for (j = 0; j < width; ++j) {
288
0
        const int32_t e = (int32_t)(dat[j]) - src[j];
289
0
        err += ((int64_t)e * e);
290
0
      }
291
0
      dat += dat_stride;
292
0
      src += src_stride;
293
0
    }
294
0
  }
295
296
0
  return err;
297
0
}
298
299
#if CONFIG_AV1_HIGHBITDEPTH
300
int64_t av1_highbd_pixel_proj_error_c(const uint8_t *src8, int width,
301
                                      int height, int src_stride,
302
                                      const uint8_t *dat8, int dat_stride,
303
                                      int32_t *flt0, int flt0_stride,
304
                                      int32_t *flt1, int flt1_stride, int xq[2],
305
0
                                      const sgr_params_type *params) {
306
0
  const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
307
0
  const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
308
0
  int i, j;
309
0
  int64_t err = 0;
310
0
  const int32_t half = 1 << (SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS - 1);
311
0
  if (params->r[0] > 0 && params->r[1] > 0) {
312
0
    int xq0 = xq[0];
313
0
    int xq1 = xq[1];
314
0
    for (i = 0; i < height; ++i) {
315
0
      for (j = 0; j < width; ++j) {
316
0
        const int32_t d = dat[j];
317
0
        const int32_t s = src[j];
318
0
        const int32_t u = (int32_t)(d << SGRPROJ_RST_BITS);
319
0
        int32_t v0 = flt0[j] - u;
320
0
        int32_t v1 = flt1[j] - u;
321
0
        int32_t v = half;
322
0
        v += xq0 * v0;
323
0
        v += xq1 * v1;
324
0
        const int32_t e = (v >> (SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS)) + d - s;
325
0
        err += ((int64_t)e * e);
326
0
      }
327
0
      dat += dat_stride;
328
0
      flt0 += flt0_stride;
329
0
      flt1 += flt1_stride;
330
0
      src += src_stride;
331
0
    }
332
0
  } else if (params->r[0] > 0 || params->r[1] > 0) {
333
0
    int exq;
334
0
    int32_t *flt;
335
0
    int flt_stride;
336
0
    if (params->r[0] > 0) {
337
0
      exq = xq[0];
338
0
      flt = flt0;
339
0
      flt_stride = flt0_stride;
340
0
    } else {
341
0
      exq = xq[1];
342
0
      flt = flt1;
343
0
      flt_stride = flt1_stride;
344
0
    }
345
0
    for (i = 0; i < height; ++i) {
346
0
      for (j = 0; j < width; ++j) {
347
0
        const int32_t d = dat[j];
348
0
        const int32_t s = src[j];
349
0
        const int32_t u = (int32_t)(d << SGRPROJ_RST_BITS);
350
0
        int32_t v = half;
351
0
        v += exq * (flt[j] - u);
352
0
        const int32_t e = (v >> (SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS)) + d - s;
353
0
        err += ((int64_t)e * e);
354
0
      }
355
0
      dat += dat_stride;
356
0
      flt += flt_stride;
357
0
      src += src_stride;
358
0
    }
359
0
  } else {
360
0
    for (i = 0; i < height; ++i) {
361
0
      for (j = 0; j < width; ++j) {
362
0
        const int32_t d = dat[j];
363
0
        const int32_t s = src[j];
364
0
        const int32_t e = d - s;
365
0
        err += ((int64_t)e * e);
366
0
      }
367
0
      dat += dat_stride;
368
0
      src += src_stride;
369
0
    }
370
0
  }
371
0
  return err;
372
0
}
373
#endif  // CONFIG_AV1_HIGHBITDEPTH
374
375
static int64_t get_pixel_proj_error(const uint8_t *src8, int width, int height,
376
                                    int src_stride, const uint8_t *dat8,
377
                                    int dat_stride, int use_highbitdepth,
378
                                    int32_t *flt0, int flt0_stride,
379
                                    int32_t *flt1, int flt1_stride, int *xqd,
380
0
                                    const sgr_params_type *params) {
381
0
  int xq[2];
382
0
  av1_decode_xq(xqd, xq, params);
383
384
0
#if CONFIG_AV1_HIGHBITDEPTH
385
0
  if (use_highbitdepth) {
386
0
    return av1_highbd_pixel_proj_error(src8, width, height, src_stride, dat8,
387
0
                                       dat_stride, flt0, flt0_stride, flt1,
388
0
                                       flt1_stride, xq, params);
389
390
0
  } else {
391
0
    return av1_lowbd_pixel_proj_error(src8, width, height, src_stride, dat8,
392
0
                                      dat_stride, flt0, flt0_stride, flt1,
393
0
                                      flt1_stride, xq, params);
394
0
  }
395
#else
396
  (void)use_highbitdepth;
397
  return av1_lowbd_pixel_proj_error(src8, width, height, src_stride, dat8,
398
                                    dat_stride, flt0, flt0_stride, flt1,
399
                                    flt1_stride, xq, params);
400
#endif
401
0
}
402
403
#define USE_SGRPROJ_REFINEMENT_SEARCH 1
404
static int64_t finer_search_pixel_proj_error(
405
    const uint8_t *src8, int width, int height, int src_stride,
406
    const uint8_t *dat8, int dat_stride, int use_highbitdepth, int32_t *flt0,
407
    int flt0_stride, int32_t *flt1, int flt1_stride, int start_step, int *xqd,
408
0
    const sgr_params_type *params) {
409
0
  int64_t err = get_pixel_proj_error(
410
0
      src8, width, height, src_stride, dat8, dat_stride, use_highbitdepth, flt0,
411
0
      flt0_stride, flt1, flt1_stride, xqd, params);
412
0
  (void)start_step;
413
0
#if USE_SGRPROJ_REFINEMENT_SEARCH
414
0
  int64_t err2;
415
0
  int tap_min[] = { SGRPROJ_PRJ_MIN0, SGRPROJ_PRJ_MIN1 };
416
0
  int tap_max[] = { SGRPROJ_PRJ_MAX0, SGRPROJ_PRJ_MAX1 };
417
0
  for (int s = start_step; s >= 1; s >>= 1) {
418
0
    for (int p = 0; p < 2; ++p) {
419
0
      if ((params->r[0] == 0 && p == 0) || (params->r[1] == 0 && p == 1)) {
420
0
        continue;
421
0
      }
422
0
      int skip = 0;
423
0
      do {
424
0
        if (xqd[p] - s >= tap_min[p]) {
425
0
          xqd[p] -= s;
426
0
          err2 =
427
0
              get_pixel_proj_error(src8, width, height, src_stride, dat8,
428
0
                                   dat_stride, use_highbitdepth, flt0,
429
0
                                   flt0_stride, flt1, flt1_stride, xqd, params);
430
0
          if (err2 > err) {
431
0
            xqd[p] += s;
432
0
          } else {
433
0
            err = err2;
434
0
            skip = 1;
435
            // At the highest step size continue moving in the same direction
436
0
            if (s == start_step) continue;
437
0
          }
438
0
        }
439
0
        break;
440
0
      } while (1);
441
0
      if (skip) break;
442
0
      do {
443
0
        if (xqd[p] + s <= tap_max[p]) {
444
0
          xqd[p] += s;
445
0
          err2 =
446
0
              get_pixel_proj_error(src8, width, height, src_stride, dat8,
447
0
                                   dat_stride, use_highbitdepth, flt0,
448
0
                                   flt0_stride, flt1, flt1_stride, xqd, params);
449
0
          if (err2 > err) {
450
0
            xqd[p] -= s;
451
0
          } else {
452
0
            err = err2;
453
            // At the highest step size continue moving in the same direction
454
0
            if (s == start_step) continue;
455
0
          }
456
0
        }
457
0
        break;
458
0
      } while (1);
459
0
    }
460
0
  }
461
0
#endif  // USE_SGRPROJ_REFINEMENT_SEARCH
462
0
  return err;
463
0
}
464
465
0
static int64_t signed_rounded_divide(int64_t dividend, int64_t divisor) {
466
0
  if (dividend < 0)
467
0
    return (dividend - divisor / 2) / divisor;
468
0
  else
469
0
    return (dividend + divisor / 2) / divisor;
470
0
}
471
472
static inline void calc_proj_params_r0_r1_c(const uint8_t *src8, int width,
473
                                            int height, int src_stride,
474
                                            const uint8_t *dat8, int dat_stride,
475
                                            int32_t *flt0, int flt0_stride,
476
                                            int32_t *flt1, int flt1_stride,
477
0
                                            int64_t H[2][2], int64_t C[2]) {
478
0
  const int size = width * height;
479
0
  const uint8_t *src = src8;
480
0
  const uint8_t *dat = dat8;
481
0
  for (int i = 0; i < height; ++i) {
482
0
    for (int j = 0; j < width; ++j) {
483
0
      const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
484
0
      const int32_t s =
485
0
          (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
486
0
      const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
487
0
      const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
488
0
      H[0][0] += (int64_t)f1 * f1;
489
0
      H[1][1] += (int64_t)f2 * f2;
490
0
      H[0][1] += (int64_t)f1 * f2;
491
0
      C[0] += (int64_t)f1 * s;
492
0
      C[1] += (int64_t)f2 * s;
493
0
    }
494
0
  }
495
0
  H[0][0] /= size;
496
0
  H[0][1] /= size;
497
0
  H[1][1] /= size;
498
0
  H[1][0] = H[0][1];
499
0
  C[0] /= size;
500
0
  C[1] /= size;
501
0
}
502
503
#if CONFIG_AV1_HIGHBITDEPTH
504
static inline void calc_proj_params_r0_r1_high_bd_c(
505
    const uint8_t *src8, int width, int height, int src_stride,
506
    const uint8_t *dat8, int dat_stride, int32_t *flt0, int flt0_stride,
507
0
    int32_t *flt1, int flt1_stride, int64_t H[2][2], int64_t C[2]) {
508
0
  const int size = width * height;
509
0
  const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
510
0
  const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
511
0
  for (int i = 0; i < height; ++i) {
512
0
    for (int j = 0; j < width; ++j) {
513
0
      const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
514
0
      const int32_t s =
515
0
          (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
516
0
      const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
517
0
      const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
518
0
      H[0][0] += (int64_t)f1 * f1;
519
0
      H[1][1] += (int64_t)f2 * f2;
520
0
      H[0][1] += (int64_t)f1 * f2;
521
0
      C[0] += (int64_t)f1 * s;
522
0
      C[1] += (int64_t)f2 * s;
523
0
    }
524
0
  }
525
0
  H[0][0] /= size;
526
0
  H[0][1] /= size;
527
0
  H[1][1] /= size;
528
0
  H[1][0] = H[0][1];
529
0
  C[0] /= size;
530
0
  C[1] /= size;
531
0
}
532
#endif  // CONFIG_AV1_HIGHBITDEPTH
533
534
static inline void calc_proj_params_r0_c(const uint8_t *src8, int width,
535
                                         int height, int src_stride,
536
                                         const uint8_t *dat8, int dat_stride,
537
                                         int32_t *flt0, int flt0_stride,
538
0
                                         int64_t H[2][2], int64_t C[2]) {
539
0
  const int size = width * height;
540
0
  const uint8_t *src = src8;
541
0
  const uint8_t *dat = dat8;
542
0
  for (int i = 0; i < height; ++i) {
543
0
    for (int j = 0; j < width; ++j) {
544
0
      const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
545
0
      const int32_t s =
546
0
          (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
547
0
      const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
548
0
      H[0][0] += (int64_t)f1 * f1;
549
0
      C[0] += (int64_t)f1 * s;
550
0
    }
551
0
  }
552
0
  H[0][0] /= size;
553
0
  C[0] /= size;
554
0
}
555
556
#if CONFIG_AV1_HIGHBITDEPTH
557
static inline void calc_proj_params_r0_high_bd_c(
558
    const uint8_t *src8, int width, int height, int src_stride,
559
    const uint8_t *dat8, int dat_stride, int32_t *flt0, int flt0_stride,
560
0
    int64_t H[2][2], int64_t C[2]) {
561
0
  const int size = width * height;
562
0
  const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
563
0
  const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
564
0
  for (int i = 0; i < height; ++i) {
565
0
    for (int j = 0; j < width; ++j) {
566
0
      const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
567
0
      const int32_t s =
568
0
          (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
569
0
      const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
570
0
      H[0][0] += (int64_t)f1 * f1;
571
0
      C[0] += (int64_t)f1 * s;
572
0
    }
573
0
  }
574
0
  H[0][0] /= size;
575
0
  C[0] /= size;
576
0
}
577
#endif  // CONFIG_AV1_HIGHBITDEPTH
578
579
static inline void calc_proj_params_r1_c(const uint8_t *src8, int width,
580
                                         int height, int src_stride,
581
                                         const uint8_t *dat8, int dat_stride,
582
                                         int32_t *flt1, int flt1_stride,
583
0
                                         int64_t H[2][2], int64_t C[2]) {
584
0
  const int size = width * height;
585
0
  const uint8_t *src = src8;
586
0
  const uint8_t *dat = dat8;
587
0
  for (int i = 0; i < height; ++i) {
588
0
    for (int j = 0; j < width; ++j) {
589
0
      const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
590
0
      const int32_t s =
591
0
          (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
592
0
      const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
593
0
      H[1][1] += (int64_t)f2 * f2;
594
0
      C[1] += (int64_t)f2 * s;
595
0
    }
596
0
  }
597
0
  H[1][1] /= size;
598
0
  C[1] /= size;
599
0
}
600
601
#if CONFIG_AV1_HIGHBITDEPTH
602
static inline void calc_proj_params_r1_high_bd_c(
603
    const uint8_t *src8, int width, int height, int src_stride,
604
    const uint8_t *dat8, int dat_stride, int32_t *flt1, int flt1_stride,
605
0
    int64_t H[2][2], int64_t C[2]) {
606
0
  const int size = width * height;
607
0
  const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
608
0
  const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
609
0
  for (int i = 0; i < height; ++i) {
610
0
    for (int j = 0; j < width; ++j) {
611
0
      const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
612
0
      const int32_t s =
613
0
          (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
614
0
      const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
615
0
      H[1][1] += (int64_t)f2 * f2;
616
0
      C[1] += (int64_t)f2 * s;
617
0
    }
618
0
  }
619
0
  H[1][1] /= size;
620
0
  C[1] /= size;
621
0
}
622
#endif  // CONFIG_AV1_HIGHBITDEPTH
623
624
// The function calls 3 subfunctions for the following cases :
625
// 1) When params->r[0] > 0 and params->r[1] > 0. In this case all elements
626
// of C and H need to be computed.
627
// 2) When only params->r[0] > 0. In this case only H[0][0] and C[0] are
628
// non-zero and need to be computed.
629
// 3) When only params->r[1] > 0. In this case only H[1][1] and C[1] are
630
// non-zero and need to be computed.
631
void av1_calc_proj_params_c(const uint8_t *src8, int width, int height,
632
                            int src_stride, const uint8_t *dat8, int dat_stride,
633
                            int32_t *flt0, int flt0_stride, int32_t *flt1,
634
                            int flt1_stride, int64_t H[2][2], int64_t C[2],
635
0
                            const sgr_params_type *params) {
636
0
  if ((params->r[0] > 0) && (params->r[1] > 0)) {
637
0
    calc_proj_params_r0_r1_c(src8, width, height, src_stride, dat8, dat_stride,
638
0
                             flt0, flt0_stride, flt1, flt1_stride, H, C);
639
0
  } else if (params->r[0] > 0) {
640
0
    calc_proj_params_r0_c(src8, width, height, src_stride, dat8, dat_stride,
641
0
                          flt0, flt0_stride, H, C);
642
0
  } else if (params->r[1] > 0) {
643
0
    calc_proj_params_r1_c(src8, width, height, src_stride, dat8, dat_stride,
644
0
                          flt1, flt1_stride, H, C);
645
0
  }
646
0
}
647
648
#if CONFIG_AV1_HIGHBITDEPTH
649
void av1_calc_proj_params_high_bd_c(const uint8_t *src8, int width, int height,
650
                                    int src_stride, const uint8_t *dat8,
651
                                    int dat_stride, int32_t *flt0,
652
                                    int flt0_stride, int32_t *flt1,
653
                                    int flt1_stride, int64_t H[2][2],
654
                                    int64_t C[2],
655
0
                                    const sgr_params_type *params) {
656
0
  if ((params->r[0] > 0) && (params->r[1] > 0)) {
657
0
    calc_proj_params_r0_r1_high_bd_c(src8, width, height, src_stride, dat8,
658
0
                                     dat_stride, flt0, flt0_stride, flt1,
659
0
                                     flt1_stride, H, C);
660
0
  } else if (params->r[0] > 0) {
661
0
    calc_proj_params_r0_high_bd_c(src8, width, height, src_stride, dat8,
662
0
                                  dat_stride, flt0, flt0_stride, H, C);
663
0
  } else if (params->r[1] > 0) {
664
0
    calc_proj_params_r1_high_bd_c(src8, width, height, src_stride, dat8,
665
0
                                  dat_stride, flt1, flt1_stride, H, C);
666
0
  }
667
0
}
668
#endif  // CONFIG_AV1_HIGHBITDEPTH
669
670
static inline void get_proj_subspace(const uint8_t *src8, int width, int height,
671
                                     int src_stride, const uint8_t *dat8,
672
                                     int dat_stride, int use_highbitdepth,
673
                                     int32_t *flt0, int flt0_stride,
674
                                     int32_t *flt1, int flt1_stride, int *xq,
675
0
                                     const sgr_params_type *params) {
676
0
  int64_t H[2][2] = { { 0, 0 }, { 0, 0 } };
677
0
  int64_t C[2] = { 0, 0 };
678
679
  // Default values to be returned if the problem becomes ill-posed
680
0
  xq[0] = 0;
681
0
  xq[1] = 0;
682
683
0
  if (!use_highbitdepth) {
684
0
    if ((width & 0x7) == 0) {
685
0
      av1_calc_proj_params(src8, width, height, src_stride, dat8, dat_stride,
686
0
                           flt0, flt0_stride, flt1, flt1_stride, H, C, params);
687
0
    } else {
688
0
      av1_calc_proj_params_c(src8, width, height, src_stride, dat8, dat_stride,
689
0
                             flt0, flt0_stride, flt1, flt1_stride, H, C,
690
0
                             params);
691
0
    }
692
0
  }
693
0
#if CONFIG_AV1_HIGHBITDEPTH
694
0
  else {  // NOLINT
695
0
    if ((width & 0x7) == 0) {
696
0
      av1_calc_proj_params_high_bd(src8, width, height, src_stride, dat8,
697
0
                                   dat_stride, flt0, flt0_stride, flt1,
698
0
                                   flt1_stride, H, C, params);
699
0
    } else {
700
0
      av1_calc_proj_params_high_bd_c(src8, width, height, src_stride, dat8,
701
0
                                     dat_stride, flt0, flt0_stride, flt1,
702
0
                                     flt1_stride, H, C, params);
703
0
    }
704
0
  }
705
0
#endif
706
707
0
  if (params->r[0] == 0) {
708
    // H matrix is now only the scalar H[1][1]
709
    // C vector is now only the scalar C[1]
710
0
    const int64_t Det = H[1][1];
711
0
    if (Det == 0) return;  // ill-posed, return default values
712
0
    xq[0] = 0;
713
0
    xq[1] = (int)signed_rounded_divide(C[1] * (1 << SGRPROJ_PRJ_BITS), Det);
714
0
  } else if (params->r[1] == 0) {
715
    // H matrix is now only the scalar H[0][0]
716
    // C vector is now only the scalar C[0]
717
0
    const int64_t Det = H[0][0];
718
0
    if (Det == 0) return;  // ill-posed, return default values
719
0
    xq[0] = (int)signed_rounded_divide(C[0] * (1 << SGRPROJ_PRJ_BITS), Det);
720
0
    xq[1] = 0;
721
0
  } else {
722
0
    const int64_t Det = H[0][0] * H[1][1] - H[0][1] * H[1][0];
723
0
    if (Det == 0) return;  // ill-posed, return default values
724
725
    // If scaling up dividend would overflow, instead scale down the divisor
726
0
    const int64_t div1 = H[1][1] * C[0] - H[0][1] * C[1];
727
0
    if ((div1 > 0 && INT64_MAX / (1 << SGRPROJ_PRJ_BITS) < div1) ||
728
0
        (div1 < 0 && INT64_MIN / (1 << SGRPROJ_PRJ_BITS) > div1))
729
0
      xq[0] = (int)signed_rounded_divide(div1, Det / (1 << SGRPROJ_PRJ_BITS));
730
0
    else
731
0
      xq[0] = (int)signed_rounded_divide(div1 * (1 << SGRPROJ_PRJ_BITS), Det);
732
733
0
    const int64_t div2 = H[0][0] * C[1] - H[1][0] * C[0];
734
0
    if ((div2 > 0 && INT64_MAX / (1 << SGRPROJ_PRJ_BITS) < div2) ||
735
0
        (div2 < 0 && INT64_MIN / (1 << SGRPROJ_PRJ_BITS) > div2))
736
0
      xq[1] = (int)signed_rounded_divide(div2, Det / (1 << SGRPROJ_PRJ_BITS));
737
0
    else
738
0
      xq[1] = (int)signed_rounded_divide(div2 * (1 << SGRPROJ_PRJ_BITS), Det);
739
0
  }
740
0
}
741
742
0
static inline void encode_xq(int *xq, int *xqd, const sgr_params_type *params) {
743
0
  if (params->r[0] == 0) {
744
0
    xqd[0] = 0;
745
0
    xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - xq[1], SGRPROJ_PRJ_MIN1,
746
0
                   SGRPROJ_PRJ_MAX1);
747
0
  } else if (params->r[1] == 0) {
748
0
    xqd[0] = clamp(xq[0], SGRPROJ_PRJ_MIN0, SGRPROJ_PRJ_MAX0);
749
0
    xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - xqd[0], SGRPROJ_PRJ_MIN1,
750
0
                   SGRPROJ_PRJ_MAX1);
751
0
  } else {
752
0
    xqd[0] = clamp(xq[0], SGRPROJ_PRJ_MIN0, SGRPROJ_PRJ_MAX0);
753
0
    xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - xqd[0] - xq[1], SGRPROJ_PRJ_MIN1,
754
0
                   SGRPROJ_PRJ_MAX1);
755
0
  }
756
0
}
757
758
// Apply the self-guided filter across an entire restoration unit.
759
static inline void apply_sgr(int sgr_params_idx, const uint8_t *dat8, int width,
760
                             int height, int dat_stride, int use_highbd,
761
                             int bit_depth, int pu_width, int pu_height,
762
                             int32_t *flt0, int32_t *flt1, int flt_stride,
763
0
                             struct aom_internal_error_info *error_info) {
764
0
  for (int i = 0; i < height; i += pu_height) {
765
0
    const int h = AOMMIN(pu_height, height - i);
766
0
    int32_t *flt0_row = flt0 + i * flt_stride;
767
0
    int32_t *flt1_row = flt1 + i * flt_stride;
768
0
    const uint8_t *dat8_row = dat8 + i * dat_stride;
769
770
    // Iterate over the stripe in blocks of width pu_width
771
0
    for (int j = 0; j < width; j += pu_width) {
772
0
      const int w = AOMMIN(pu_width, width - j);
773
0
      if (av1_selfguided_restoration(
774
0
              dat8_row + j, w, h, dat_stride, flt0_row + j, flt1_row + j,
775
0
              flt_stride, sgr_params_idx, bit_depth, use_highbd) != 0) {
776
0
        aom_internal_error(
777
0
            error_info, AOM_CODEC_MEM_ERROR,
778
0
            "Error allocating buffer in av1_selfguided_restoration");
779
0
      }
780
0
    }
781
0
  }
782
0
}
783
784
static inline void compute_sgrproj_err(
785
    const uint8_t *dat8, const int width, const int height,
786
    const int dat_stride, const uint8_t *src8, const int src_stride,
787
    const int use_highbitdepth, const int bit_depth, const int pu_width,
788
    const int pu_height, const int ep, int32_t *flt0, int32_t *flt1,
789
    const int flt_stride, int *exqd, int64_t *err,
790
0
    struct aom_internal_error_info *error_info) {
791
0
  int exq[2];
792
0
  apply_sgr(ep, dat8, width, height, dat_stride, use_highbitdepth, bit_depth,
793
0
            pu_width, pu_height, flt0, flt1, flt_stride, error_info);
794
0
  const sgr_params_type *const params = &av1_sgr_params[ep];
795
0
  get_proj_subspace(src8, width, height, src_stride, dat8, dat_stride,
796
0
                    use_highbitdepth, flt0, flt_stride, flt1, flt_stride, exq,
797
0
                    params);
798
0
  encode_xq(exq, exqd, params);
799
0
  *err = finer_search_pixel_proj_error(
800
0
      src8, width, height, src_stride, dat8, dat_stride, use_highbitdepth, flt0,
801
0
      flt_stride, flt1, flt_stride, 2, exqd, params);
802
0
}
803
804
static inline void get_best_error(int64_t *besterr, const int64_t err,
805
                                  const int *exqd, int *bestxqd, int *bestep,
806
0
                                  const int ep) {
807
0
  if (*besterr == -1 || err < *besterr) {
808
0
    *bestep = ep;
809
0
    *besterr = err;
810
0
    bestxqd[0] = exqd[0];
811
0
    bestxqd[1] = exqd[1];
812
0
  }
813
0
}
814
815
static SgrprojInfo search_selfguided_restoration(
816
    const uint8_t *dat8, int width, int height, int dat_stride,
817
    const uint8_t *src8, int src_stride, int use_highbitdepth, int bit_depth,
818
    int pu_width, int pu_height, int32_t *rstbuf, int enable_sgr_ep_pruning,
819
0
    struct aom_internal_error_info *error_info) {
820
0
  int32_t *flt0 = rstbuf;
821
0
  int32_t *flt1 = flt0 + RESTORATION_UNITPELS_MAX;
822
0
  int ep, idx, bestep = 0;
823
0
  int64_t besterr = -1;
824
0
  int exqd[2], bestxqd[2] = { 0, 0 };
825
0
  int flt_stride = ((width + 7) & ~7) + 8;
826
0
  assert(pu_width == (RESTORATION_PROC_UNIT_SIZE >> 1) ||
827
0
         pu_width == RESTORATION_PROC_UNIT_SIZE);
828
0
  assert(pu_height == (RESTORATION_PROC_UNIT_SIZE >> 1) ||
829
0
         pu_height == RESTORATION_PROC_UNIT_SIZE);
830
0
  if (!enable_sgr_ep_pruning) {
831
0
    for (ep = 0; ep < SGRPROJ_PARAMS; ep++) {
832
0
      int64_t err;
833
0
      compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
834
0
                          use_highbitdepth, bit_depth, pu_width, pu_height, ep,
835
0
                          flt0, flt1, flt_stride, exqd, &err, error_info);
836
0
      get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
837
0
    }
838
0
  } else {
839
    // evaluate first four seed ep in first group
840
0
    for (idx = 0; idx < SGRPROJ_EP_GRP1_SEARCH_COUNT; idx++) {
841
0
      ep = sgproj_ep_grp1_seed[idx];
842
0
      int64_t err;
843
0
      compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
844
0
                          use_highbitdepth, bit_depth, pu_width, pu_height, ep,
845
0
                          flt0, flt1, flt_stride, exqd, &err, error_info);
846
0
      get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
847
0
    }
848
    // evaluate left and right ep of winner in seed ep
849
0
    int bestep_ref = bestep;
850
0
    for (ep = bestep_ref - 1; ep < bestep_ref + 2; ep += 2) {
851
0
      if (ep < SGRPROJ_EP_GRP1_START_IDX || ep > SGRPROJ_EP_GRP1_END_IDX)
852
0
        continue;
853
0
      int64_t err;
854
0
      compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
855
0
                          use_highbitdepth, bit_depth, pu_width, pu_height, ep,
856
0
                          flt0, flt1, flt_stride, exqd, &err, error_info);
857
0
      get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
858
0
    }
859
    // evaluate last two group
860
0
    for (idx = 0; idx < SGRPROJ_EP_GRP2_3_SEARCH_COUNT; idx++) {
861
0
      ep = sgproj_ep_grp2_3[idx][bestep];
862
0
      int64_t err;
863
0
      compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
864
0
                          use_highbitdepth, bit_depth, pu_width, pu_height, ep,
865
0
                          flt0, flt1, flt_stride, exqd, &err, error_info);
866
0
      get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
867
0
    }
868
0
  }
869
870
0
  SgrprojInfo ret;
871
0
  ret.ep = bestep;
872
0
  ret.xqd[0] = bestxqd[0];
873
0
  ret.xqd[1] = bestxqd[1];
874
0
  return ret;
875
0
}
876
877
static int count_sgrproj_bits(SgrprojInfo *sgrproj_info,
878
0
                              SgrprojInfo *ref_sgrproj_info) {
879
0
  int bits = SGRPROJ_PARAMS_BITS;
880
0
  const sgr_params_type *params = &av1_sgr_params[sgrproj_info->ep];
881
0
  if (params->r[0] > 0)
882
0
    bits += aom_count_primitive_refsubexpfin(
883
0
        SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1, SGRPROJ_PRJ_SUBEXP_K,
884
0
        ref_sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0,
885
0
        sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0);
886
0
  if (params->r[1] > 0)
887
0
    bits += aom_count_primitive_refsubexpfin(
888
0
        SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1, SGRPROJ_PRJ_SUBEXP_K,
889
0
        ref_sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1,
890
0
        sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1);
891
0
  return bits;
892
0
}
893
894
static inline void search_sgrproj(const RestorationTileLimits *limits,
895
                                  int rest_unit_idx, void *priv,
896
                                  int32_t *tmpbuf, RestorationLineBuffers *rlbs,
897
0
                                  struct aom_internal_error_info *error_info) {
898
0
  (void)rlbs;
899
0
  RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
900
0
  RestUnitSearchInfo *rusi = &rsc->rusi[rest_unit_idx];
901
902
0
  const MACROBLOCK *const x = rsc->x;
903
0
  const AV1_COMMON *const cm = rsc->cm;
904
0
  const int highbd = cm->seq_params->use_highbitdepth;
905
0
  const int bit_depth = cm->seq_params->bit_depth;
906
907
0
  const int64_t bits_none = x->mode_costs.sgrproj_restore_cost[0];
908
  // Prune evaluation of RESTORE_SGRPROJ if 'skip_sgr_eval' is set
909
0
  if (rsc->skip_sgr_eval) {
910
0
    rsc->total_bits[RESTORE_SGRPROJ] += bits_none;
911
0
    rsc->total_sse[RESTORE_SGRPROJ] += rsc->sse[RESTORE_NONE];
912
0
    rusi->best_rtype[RESTORE_SGRPROJ - 1] = RESTORE_NONE;
913
0
    rsc->sse[RESTORE_SGRPROJ] = INT64_MAX;
914
0
    return;
915
0
  }
916
917
0
  uint8_t *dgd_start =
918
0
      rsc->dgd_buffer + limits->v_start * rsc->dgd_stride + limits->h_start;
919
0
  const uint8_t *src_start =
920
0
      rsc->src_buffer + limits->v_start * rsc->src_stride + limits->h_start;
921
922
0
  const int is_uv = rsc->plane > 0;
923
0
  const int ss_x = is_uv && cm->seq_params->subsampling_x;
924
0
  const int ss_y = is_uv && cm->seq_params->subsampling_y;
925
0
  const int procunit_width = RESTORATION_PROC_UNIT_SIZE >> ss_x;
926
0
  const int procunit_height = RESTORATION_PROC_UNIT_SIZE >> ss_y;
927
928
0
  rusi->sgrproj = search_selfguided_restoration(
929
0
      dgd_start, limits->h_end - limits->h_start,
930
0
      limits->v_end - limits->v_start, rsc->dgd_stride, src_start,
931
0
      rsc->src_stride, highbd, bit_depth, procunit_width, procunit_height,
932
0
      tmpbuf, rsc->lpf_sf->enable_sgr_ep_pruning, error_info);
933
934
0
  RestorationUnitInfo rui;
935
0
  rui.restoration_type = RESTORE_SGRPROJ;
936
0
  rui.sgrproj_info = rusi->sgrproj;
937
938
0
  rsc->sse[RESTORE_SGRPROJ] = try_restoration_unit(rsc, limits, &rui);
939
940
0
  const int64_t bits_sgr =
941
0
      x->mode_costs.sgrproj_restore_cost[1] +
942
0
      (count_sgrproj_bits(&rusi->sgrproj, &rsc->ref_sgrproj)
943
0
       << AV1_PROB_COST_SHIFT);
944
0
  double cost_none = RDCOST_DBL_WITH_NATIVE_BD_DIST(
945
0
      x->rdmult, bits_none >> 4, rsc->sse[RESTORE_NONE], bit_depth);
946
0
  double cost_sgr = RDCOST_DBL_WITH_NATIVE_BD_DIST(
947
0
      x->rdmult, bits_sgr >> 4, rsc->sse[RESTORE_SGRPROJ], bit_depth);
948
0
  if (rusi->sgrproj.ep < 10)
949
0
    cost_sgr *=
950
0
        (1 + DUAL_SGR_PENALTY_MULT * rsc->lpf_sf->dual_sgr_penalty_level);
951
952
0
  RestorationType rtype =
953
0
      (cost_sgr < cost_none) ? RESTORE_SGRPROJ : RESTORE_NONE;
954
0
  rusi->best_rtype[RESTORE_SGRPROJ - 1] = rtype;
955
956
#if DEBUG_LR_COSTING
957
  // Store ref params for later checking
958
  lr_ref_params[RESTORE_SGRPROJ][rsc->plane][rest_unit_idx].sgrproj_info =
959
      rsc->ref_sgrproj;
960
#endif  // DEBUG_LR_COSTING
961
962
0
  rsc->total_sse[RESTORE_SGRPROJ] += rsc->sse[rtype];
963
0
  rsc->total_bits[RESTORE_SGRPROJ] +=
964
0
      (cost_sgr < cost_none) ? bits_sgr : bits_none;
965
0
  if (cost_sgr < cost_none) rsc->ref_sgrproj = rusi->sgrproj;
966
0
}
967
968
static void acc_stat_one_line(const uint8_t *dgd, const uint8_t *src,
969
                              int dgd_stride, int h_start, int h_end,
970
                              uint8_t avg, const int wiener_halfwin,
971
                              const int wiener_win2, int32_t *M_int32,
972
0
                              int32_t *H_int32, int count) {
973
0
  int j, k, l;
974
0
  int16_t Y[WIENER_WIN2];
975
976
0
  for (j = h_start; j < h_end; j++) {
977
0
    const int16_t X = (int16_t)src[j] - (int16_t)avg;
978
0
    int idx = 0;
979
0
    for (k = -wiener_halfwin; k <= wiener_halfwin; k++) {
980
0
      for (l = -wiener_halfwin; l <= wiener_halfwin; l++) {
981
0
        Y[idx] =
982
0
            (int16_t)dgd[(count + l) * dgd_stride + (j + k)] - (int16_t)avg;
983
0
        idx++;
984
0
      }
985
0
    }
986
0
    assert(idx == wiener_win2);
987
0
    for (k = 0; k < wiener_win2; ++k) {
988
0
      M_int32[k] += (int32_t)Y[k] * X;
989
0
      for (l = k; l < wiener_win2; ++l) {
990
        // H is a symmetric matrix, so we only need to fill out the upper
991
        // triangle here. We can copy it down to the lower triangle outside
992
        // the (i, j) loops.
993
0
        H_int32[k * wiener_win2 + l] += (int32_t)Y[k] * Y[l];
994
0
      }
995
0
    }
996
0
  }
997
0
}
998
999
void av1_compute_stats_c(int wiener_win, const uint8_t *dgd, const uint8_t *src,
1000
                         int16_t *dgd_avg, int16_t *src_avg, int h_start,
1001
                         int h_end, int v_start, int v_end, int dgd_stride,
1002
                         int src_stride, int64_t *M, int64_t *H,
1003
0
                         int use_downsampled_wiener_stats) {
1004
0
  (void)dgd_avg;
1005
0
  (void)src_avg;
1006
0
  int i, k, l;
1007
0
  const int wiener_win2 = wiener_win * wiener_win;
1008
0
  const int wiener_halfwin = (wiener_win >> 1);
1009
0
  uint8_t avg = find_average(dgd, h_start, h_end, v_start, v_end, dgd_stride);
1010
0
  int32_t M_row[WIENER_WIN2] = { 0 };
1011
0
  int32_t H_row[WIENER_WIN2 * WIENER_WIN2] = { 0 };
1012
0
  int downsample_factor =
1013
0
      use_downsampled_wiener_stats ? WIENER_STATS_DOWNSAMPLE_FACTOR : 1;
1014
1015
0
  memset(M, 0, sizeof(*M) * wiener_win2);
1016
0
  memset(H, 0, sizeof(*H) * wiener_win2 * wiener_win2);
1017
1018
0
  for (i = v_start; i < v_end; i = i + downsample_factor) {
1019
0
    if (use_downsampled_wiener_stats &&
1020
0
        (v_end - i < WIENER_STATS_DOWNSAMPLE_FACTOR)) {
1021
0
      downsample_factor = v_end - i;
1022
0
    }
1023
1024
0
    memset(M_row, 0, sizeof(int32_t) * WIENER_WIN2);
1025
0
    memset(H_row, 0, sizeof(int32_t) * WIENER_WIN2 * WIENER_WIN2);
1026
0
    acc_stat_one_line(dgd, src + i * src_stride, dgd_stride, h_start, h_end,
1027
0
                      avg, wiener_halfwin, wiener_win2, M_row, H_row, i);
1028
1029
0
    for (k = 0; k < wiener_win2; ++k) {
1030
      // Scale M matrix based on the downsampling factor
1031
0
      M[k] += ((int64_t)M_row[k] * downsample_factor);
1032
0
      for (l = k; l < wiener_win2; ++l) {
1033
        // H is a symmetric matrix, so we only need to fill out the upper
1034
        // triangle here. We can copy it down to the lower triangle outside
1035
        // the (i, j) loops.
1036
        // Scale H Matrix based on the downsampling factor
1037
0
        H[k * wiener_win2 + l] +=
1038
0
            ((int64_t)H_row[k * wiener_win2 + l] * downsample_factor);
1039
0
      }
1040
0
    }
1041
0
  }
1042
1043
0
  for (k = 0; k < wiener_win2; ++k) {
1044
0
    for (l = k + 1; l < wiener_win2; ++l) {
1045
0
      H[l * wiener_win2 + k] = H[k * wiener_win2 + l];
1046
0
    }
1047
0
  }
1048
0
}
1049
1050
#if CONFIG_AV1_HIGHBITDEPTH
1051
void av1_compute_stats_highbd_c(int wiener_win, const uint8_t *dgd8,
1052
                                const uint8_t *src8, int16_t *dgd_avg,
1053
                                int16_t *src_avg, int h_start, int h_end,
1054
                                int v_start, int v_end, int dgd_stride,
1055
                                int src_stride, int64_t *M, int64_t *H,
1056
0
                                aom_bit_depth_t bit_depth) {
1057
0
  (void)dgd_avg;
1058
0
  (void)src_avg;
1059
0
  int i, j, k, l;
1060
0
  int32_t Y[WIENER_WIN2];
1061
0
  const int wiener_win2 = wiener_win * wiener_win;
1062
0
  const int wiener_halfwin = (wiener_win >> 1);
1063
0
  const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
1064
0
  const uint16_t *dgd = CONVERT_TO_SHORTPTR(dgd8);
1065
0
  uint16_t avg =
1066
0
      find_average_highbd(dgd, h_start, h_end, v_start, v_end, dgd_stride);
1067
1068
0
  uint8_t bit_depth_divider = 1;
1069
0
  if (bit_depth == AOM_BITS_12)
1070
0
    bit_depth_divider = 16;
1071
0
  else if (bit_depth == AOM_BITS_10)
1072
0
    bit_depth_divider = 4;
1073
1074
0
  memset(M, 0, sizeof(*M) * wiener_win2);
1075
0
  memset(H, 0, sizeof(*H) * wiener_win2 * wiener_win2);
1076
0
  for (i = v_start; i < v_end; i++) {
1077
0
    for (j = h_start; j < h_end; j++) {
1078
0
      const int32_t X = (int32_t)src[i * src_stride + j] - (int32_t)avg;
1079
0
      int idx = 0;
1080
0
      for (k = -wiener_halfwin; k <= wiener_halfwin; k++) {
1081
0
        for (l = -wiener_halfwin; l <= wiener_halfwin; l++) {
1082
0
          Y[idx] = (int32_t)dgd[(i + l) * dgd_stride + (j + k)] - (int32_t)avg;
1083
0
          idx++;
1084
0
        }
1085
0
      }
1086
0
      assert(idx == wiener_win2);
1087
0
      for (k = 0; k < wiener_win2; ++k) {
1088
0
        M[k] += (int64_t)Y[k] * X;
1089
0
        for (l = k; l < wiener_win2; ++l) {
1090
          // H is a symmetric matrix, so we only need to fill out the upper
1091
          // triangle here. We can copy it down to the lower triangle outside
1092
          // the (i, j) loops.
1093
0
          H[k * wiener_win2 + l] += (int64_t)Y[k] * Y[l];
1094
0
        }
1095
0
      }
1096
0
    }
1097
0
  }
1098
0
  for (k = 0; k < wiener_win2; ++k) {
1099
0
    M[k] /= bit_depth_divider;
1100
0
    H[k * wiener_win2 + k] /= bit_depth_divider;
1101
0
    for (l = k + 1; l < wiener_win2; ++l) {
1102
0
      H[k * wiener_win2 + l] /= bit_depth_divider;
1103
0
      H[l * wiener_win2 + k] = H[k * wiener_win2 + l];
1104
0
    }
1105
0
  }
1106
0
}
1107
#endif  // CONFIG_AV1_HIGHBITDEPTH
1108
1109
0
static inline int wrap_index(int i, int wiener_win) {
1110
0
  const int wiener_halfwin1 = (wiener_win >> 1) + 1;
1111
0
  return (i >= wiener_halfwin1 ? wiener_win - 1 - i : i);
1112
0
}
1113
1114
// Splits each w[i] into smaller components w1[i] and w2[i] such that
1115
// w[i] = w1[i] * WIENER_TAP_SCALE_FACTOR + w2[i].
1116
static inline void split_wiener_filter_coefficients(int wiener_win,
1117
                                                    const int32_t *w,
1118
0
                                                    int32_t *w1, int32_t *w2) {
1119
0
  for (int i = 0; i < wiener_win; i++) {
1120
0
    w1[i] = w[i] / WIENER_TAP_SCALE_FACTOR;
1121
0
    w2[i] = w[i] - w1[i] * WIENER_TAP_SCALE_FACTOR;
1122
0
    assert(w[i] == w1[i] * WIENER_TAP_SCALE_FACTOR + w2[i]);
1123
0
  }
1124
0
}
1125
1126
// Calculates x * w / WIENER_TAP_SCALE_FACTOR, where
1127
// w = w1 * WIENER_TAP_SCALE_FACTOR + w2.
1128
//
1129
// The multiplication x * w may overflow, so we multiply x by the components of
1130
// w (w1 and w2) and combine the multiplication with the division.
1131
0
static inline int64_t multiply_and_scale(int64_t x, int32_t w1, int32_t w2) {
1132
  // Let y = x * w / WIENER_TAP_SCALE_FACTOR
1133
  //       = x * (w1 * WIENER_TAP_SCALE_FACTOR + w2) / WIENER_TAP_SCALE_FACTOR
1134
0
  const int64_t y = x * w1 + x * w2 / WIENER_TAP_SCALE_FACTOR;
1135
0
  return y;
1136
0
}
1137
1138
// Solve linear equations to find Wiener filter tap values
1139
// Taps are output scaled by WIENER_FILT_STEP
1140
static int linsolve_wiener(int n, int64_t *A, int stride, int64_t *b,
1141
0
                           int64_t *x) {
1142
0
  for (int k = 0; k < n - 1; k++) {
1143
    // Partial pivoting: bring the row with the largest pivot to the top
1144
0
    for (int i = n - 1; i > k; i--) {
1145
      // If row i has a better (bigger) pivot than row (i-1), swap them
1146
0
      if (llabs(A[(i - 1) * stride + k]) < llabs(A[i * stride + k])) {
1147
0
        for (int j = 0; j < n; j++) {
1148
0
          const int64_t c = A[i * stride + j];
1149
0
          A[i * stride + j] = A[(i - 1) * stride + j];
1150
0
          A[(i - 1) * stride + j] = c;
1151
0
        }
1152
0
        const int64_t c = b[i];
1153
0
        b[i] = b[i - 1];
1154
0
        b[i - 1] = c;
1155
0
      }
1156
0
    }
1157
1158
    // b/278065963: The multiplies
1159
    //   c / 256 * A[k * stride + j] / cd * 256
1160
    // and
1161
    //   c / 256 * b[k] / cd * 256
1162
    // within Gaussian elimination can cause a signed integer overflow. Rework
1163
    // the multiplies so that larger scaling is used without significantly
1164
    // impacting the overall precision.
1165
    //
1166
    // Precision guidance:
1167
    //   scale_threshold: Pick as high as possible.
1168
    // For max_abs_akj >= scale_threshold scenario:
1169
    //   scaler_A: Pick as low as possible. Needed for A[(i + 1) * stride + j].
1170
    //   scaler_c: Pick as low as possible while maintaining scaler_c >=
1171
    //     (1 << 7). Needed for A[(i + 1) * stride + j] and b[i + 1].
1172
0
    int64_t max_abs_akj = 0;
1173
0
    for (int j = 0; j < n; j++) {
1174
0
      const int64_t abs_akj = llabs(A[k * stride + j]);
1175
0
      if (abs_akj > max_abs_akj) max_abs_akj = abs_akj;
1176
0
    }
1177
0
    const int scale_threshold = 1 << 22;
1178
0
    const int scaler_A = max_abs_akj < scale_threshold ? 1 : (1 << 6);
1179
0
    const int scaler_c = max_abs_akj < scale_threshold ? 1 : (1 << 7);
1180
0
    const int scaler = scaler_c * scaler_A;
1181
1182
    // Forward elimination (convert A to row-echelon form)
1183
0
    for (int i = k; i < n - 1; i++) {
1184
0
      if (A[k * stride + k] == 0) return 0;
1185
0
      const int64_t c = A[(i + 1) * stride + k] / scaler_c;
1186
0
      const int64_t cd = A[k * stride + k];
1187
0
      for (int j = 0; j < n; j++) {
1188
0
        A[(i + 1) * stride + j] -=
1189
0
            A[k * stride + j] / scaler_A * c / cd * scaler;
1190
0
      }
1191
0
      b[i + 1] -= c * b[k] / cd * scaler_c;
1192
0
    }
1193
0
  }
1194
  // Back-substitution
1195
0
  for (int i = n - 1; i >= 0; i--) {
1196
0
    if (A[i * stride + i] == 0) return 0;
1197
0
    int64_t c = 0;
1198
0
    for (int j = i + 1; j <= n - 1; j++) {
1199
0
      c += A[i * stride + j] * x[j] / WIENER_TAP_SCALE_FACTOR;
1200
0
    }
1201
    // Store filter taps x in scaled form.
1202
0
    x[i] = WIENER_TAP_SCALE_FACTOR * (b[i] - c) / A[i * stride + i];
1203
0
  }
1204
1205
0
  return 1;
1206
0
}
1207
1208
// Fix vector b, update vector a
1209
static inline void update_a_sep_sym(int wiener_win, int64_t **Mc, int64_t **Hc,
1210
0
                                    int32_t *a, const int32_t *b) {
1211
0
  int i, j;
1212
0
  int64_t S[WIENER_WIN];
1213
0
  int64_t A[WIENER_HALFWIN1], B[WIENER_HALFWIN1 * WIENER_HALFWIN1];
1214
0
  int32_t b1[WIENER_WIN], b2[WIENER_WIN];
1215
0
  const int wiener_win2 = wiener_win * wiener_win;
1216
0
  const int wiener_halfwin1 = (wiener_win >> 1) + 1;
1217
0
  memset(A, 0, sizeof(A));
1218
0
  memset(B, 0, sizeof(B));
1219
0
  for (i = 0; i < wiener_win; i++) {
1220
0
    for (j = 0; j < wiener_win; ++j) {
1221
0
      const int jj = wrap_index(j, wiener_win);
1222
0
      A[jj] += Mc[i][j] * b[i] / WIENER_TAP_SCALE_FACTOR;
1223
0
    }
1224
0
  }
1225
0
  split_wiener_filter_coefficients(wiener_win, b, b1, b2);
1226
1227
0
  for (i = 0; i < wiener_win; i++) {
1228
0
    for (j = 0; j < wiener_win; j++) {
1229
0
      int k, l;
1230
0
      for (k = 0; k < wiener_win; ++k) {
1231
0
        const int kk = wrap_index(k, wiener_win);
1232
0
        for (l = 0; l < wiener_win; ++l) {
1233
0
          const int ll = wrap_index(l, wiener_win);
1234
          // Calculate
1235
          // B[ll * wiener_halfwin1 + kk] +=
1236
          //    Hc[j * wiener_win + i][k * wiener_win2 + l] * b[i] /
1237
          //    WIENER_TAP_SCALE_FACTOR * b[j] / WIENER_TAP_SCALE_FACTOR;
1238
          //
1239
          // The last multiplication may overflow, so we combine the last
1240
          // multiplication with the last division.
1241
0
          const int64_t x = Hc[j * wiener_win + i][k * wiener_win2 + l] * b[i] /
1242
0
                            WIENER_TAP_SCALE_FACTOR;
1243
          // b[j] = b1[j] * WIENER_TAP_SCALE_FACTOR + b2[j]
1244
0
          B[ll * wiener_halfwin1 + kk] += multiply_and_scale(x, b1[j], b2[j]);
1245
0
        }
1246
0
      }
1247
0
    }
1248
0
  }
1249
  // Normalization enforcement in the system of equations itself
1250
0
  for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1251
0
    A[i] -=
1252
0
        A[wiener_halfwin1 - 1] * 2 +
1253
0
        B[i * wiener_halfwin1 + wiener_halfwin1 - 1] -
1254
0
        2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 + (wiener_halfwin1 - 1)];
1255
0
  }
1256
0
  for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1257
0
    for (j = 0; j < wiener_halfwin1 - 1; ++j) {
1258
0
      B[i * wiener_halfwin1 + j] -=
1259
0
          2 * (B[i * wiener_halfwin1 + (wiener_halfwin1 - 1)] +
1260
0
               B[(wiener_halfwin1 - 1) * wiener_halfwin1 + j] -
1261
0
               2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 +
1262
0
                     (wiener_halfwin1 - 1)]);
1263
0
    }
1264
0
  }
1265
0
  if (linsolve_wiener(wiener_halfwin1 - 1, B, wiener_halfwin1, A, S)) {
1266
0
    S[wiener_halfwin1 - 1] = WIENER_TAP_SCALE_FACTOR;
1267
0
    for (i = wiener_halfwin1; i < wiener_win; ++i) {
1268
0
      S[i] = S[wiener_win - 1 - i];
1269
0
      S[wiener_halfwin1 - 1] -= 2 * S[i];
1270
0
    }
1271
0
    for (i = 0; i < wiener_win; ++i) {
1272
0
      a[i] = (int32_t)CLIP(S[i], -(1 << (WIENER_FILT_BITS - 1)),
1273
0
                           (1 << (WIENER_FILT_BITS - 1)) - 1);
1274
0
    }
1275
0
  }
1276
0
}
1277
1278
// Fix vector a, update vector b
1279
static inline void update_b_sep_sym(int wiener_win, int64_t **Mc, int64_t **Hc,
1280
0
                                    const int32_t *a, int32_t *b) {
1281
0
  int i, j;
1282
0
  int64_t S[WIENER_WIN];
1283
0
  int64_t A[WIENER_HALFWIN1], B[WIENER_HALFWIN1 * WIENER_HALFWIN1];
1284
0
  int32_t a1[WIENER_WIN], a2[WIENER_WIN];
1285
0
  const int wiener_win2 = wiener_win * wiener_win;
1286
0
  const int wiener_halfwin1 = (wiener_win >> 1) + 1;
1287
0
  memset(A, 0, sizeof(A));
1288
0
  memset(B, 0, sizeof(B));
1289
0
  for (i = 0; i < wiener_win; i++) {
1290
0
    const int ii = wrap_index(i, wiener_win);
1291
0
    for (j = 0; j < wiener_win; j++) {
1292
0
      A[ii] += Mc[i][j] * a[j] / WIENER_TAP_SCALE_FACTOR;
1293
0
    }
1294
0
  }
1295
0
  split_wiener_filter_coefficients(wiener_win, a, a1, a2);
1296
1297
0
  for (i = 0; i < wiener_win; i++) {
1298
0
    const int ii = wrap_index(i, wiener_win);
1299
0
    for (j = 0; j < wiener_win; j++) {
1300
0
      const int jj = wrap_index(j, wiener_win);
1301
0
      int k, l;
1302
0
      for (k = 0; k < wiener_win; ++k) {
1303
0
        for (l = 0; l < wiener_win; ++l) {
1304
          // Calculate
1305
          // B[jj * wiener_halfwin1 + ii] +=
1306
          //     Hc[i * wiener_win + j][k * wiener_win2 + l] * a[k] /
1307
          //     WIENER_TAP_SCALE_FACTOR * a[l] / WIENER_TAP_SCALE_FACTOR;
1308
          //
1309
          // The last multiplication may overflow, so we combine the last
1310
          // multiplication with the last division.
1311
0
          const int64_t x = Hc[i * wiener_win + j][k * wiener_win2 + l] * a[k] /
1312
0
                            WIENER_TAP_SCALE_FACTOR;
1313
          // a[l] = a1[l] * WIENER_TAP_SCALE_FACTOR + a2[l]
1314
0
          B[jj * wiener_halfwin1 + ii] += multiply_and_scale(x, a1[l], a2[l]);
1315
0
        }
1316
0
      }
1317
0
    }
1318
0
  }
1319
  // Normalization enforcement in the system of equations itself
1320
0
  for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1321
0
    A[i] -=
1322
0
        A[wiener_halfwin1 - 1] * 2 +
1323
0
        B[i * wiener_halfwin1 + wiener_halfwin1 - 1] -
1324
0
        2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 + (wiener_halfwin1 - 1)];
1325
0
  }
1326
0
  for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1327
0
    for (j = 0; j < wiener_halfwin1 - 1; ++j) {
1328
0
      B[i * wiener_halfwin1 + j] -=
1329
0
          2 * (B[i * wiener_halfwin1 + (wiener_halfwin1 - 1)] +
1330
0
               B[(wiener_halfwin1 - 1) * wiener_halfwin1 + j] -
1331
0
               2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 +
1332
0
                     (wiener_halfwin1 - 1)]);
1333
0
    }
1334
0
  }
1335
0
  if (linsolve_wiener(wiener_halfwin1 - 1, B, wiener_halfwin1, A, S)) {
1336
0
    S[wiener_halfwin1 - 1] = WIENER_TAP_SCALE_FACTOR;
1337
0
    for (i = wiener_halfwin1; i < wiener_win; ++i) {
1338
0
      S[i] = S[wiener_win - 1 - i];
1339
0
      S[wiener_halfwin1 - 1] -= 2 * S[i];
1340
0
    }
1341
0
    for (i = 0; i < wiener_win; ++i) {
1342
0
      b[i] = (int32_t)CLIP(S[i], -(1 << (WIENER_FILT_BITS - 1)),
1343
0
                           (1 << (WIENER_FILT_BITS - 1)) - 1);
1344
0
    }
1345
0
  }
1346
0
}
1347
1348
static void wiener_decompose_sep_sym(int wiener_win, int64_t *M, int64_t *H,
1349
0
                                     int32_t *a, int32_t *b) {
1350
0
  static const int32_t init_filt[WIENER_WIN] = {
1351
0
    WIENER_FILT_TAP0_MIDV, WIENER_FILT_TAP1_MIDV, WIENER_FILT_TAP2_MIDV,
1352
0
    WIENER_FILT_TAP3_MIDV, WIENER_FILT_TAP2_MIDV, WIENER_FILT_TAP1_MIDV,
1353
0
    WIENER_FILT_TAP0_MIDV,
1354
0
  };
1355
0
  int64_t *Hc[WIENER_WIN2];
1356
0
  int64_t *Mc[WIENER_WIN];
1357
0
  int i, j, iter;
1358
0
  const int plane_off = (WIENER_WIN - wiener_win) >> 1;
1359
0
  const int wiener_win2 = wiener_win * wiener_win;
1360
0
  for (i = 0; i < wiener_win; i++) {
1361
0
    a[i] = b[i] =
1362
0
        WIENER_TAP_SCALE_FACTOR / WIENER_FILT_STEP * init_filt[i + plane_off];
1363
0
  }
1364
0
  for (i = 0; i < wiener_win; i++) {
1365
0
    Mc[i] = M + i * wiener_win;
1366
0
    for (j = 0; j < wiener_win; j++) {
1367
0
      Hc[i * wiener_win + j] =
1368
0
          H + i * wiener_win * wiener_win2 + j * wiener_win;
1369
0
    }
1370
0
  }
1371
1372
0
  iter = 1;
1373
0
  while (iter < NUM_WIENER_ITERS) {
1374
0
    update_a_sep_sym(wiener_win, Mc, Hc, a, b);
1375
0
    update_b_sep_sym(wiener_win, Mc, Hc, a, b);
1376
0
    iter++;
1377
0
  }
1378
0
}
1379
1380
// Computes the function x'*H*x - x'*M for the learned 2D filter x, and compares
1381
// against identity filters; Final score is defined as the difference between
1382
// the function values
1383
static int64_t compute_score(int wiener_win, int64_t *M, int64_t *H,
1384
0
                             InterpKernel vfilt, InterpKernel hfilt) {
1385
0
  int32_t ab[WIENER_WIN * WIENER_WIN];
1386
0
  int16_t a[WIENER_WIN], b[WIENER_WIN];
1387
0
  int64_t P = 0, Q = 0;
1388
0
  int64_t iP = 0, iQ = 0;
1389
0
  int64_t Score, iScore;
1390
0
  int i, k, l;
1391
0
  const int plane_off = (WIENER_WIN - wiener_win) >> 1;
1392
0
  const int wiener_win2 = wiener_win * wiener_win;
1393
1394
0
  a[WIENER_HALFWIN] = b[WIENER_HALFWIN] = WIENER_FILT_STEP;
1395
0
  for (i = 0; i < WIENER_HALFWIN; ++i) {
1396
0
    a[i] = a[WIENER_WIN - i - 1] = vfilt[i];
1397
0
    b[i] = b[WIENER_WIN - i - 1] = hfilt[i];
1398
0
    a[WIENER_HALFWIN] -= 2 * a[i];
1399
0
    b[WIENER_HALFWIN] -= 2 * b[i];
1400
0
  }
1401
0
  memset(ab, 0, sizeof(ab));
1402
0
  for (k = 0; k < wiener_win; ++k) {
1403
0
    for (l = 0; l < wiener_win; ++l)
1404
0
      ab[k * wiener_win + l] = a[l + plane_off] * b[k + plane_off];
1405
0
  }
1406
0
  for (k = 0; k < wiener_win2; ++k) {
1407
0
    P += ab[k] * M[k] / WIENER_FILT_STEP / WIENER_FILT_STEP;
1408
0
    for (l = 0; l < wiener_win2; ++l) {
1409
0
      Q += ab[k] * H[k * wiener_win2 + l] * ab[l] / WIENER_FILT_STEP /
1410
0
           WIENER_FILT_STEP / WIENER_FILT_STEP / WIENER_FILT_STEP;
1411
0
    }
1412
0
  }
1413
0
  Score = Q - 2 * P;
1414
1415
0
  iP = M[wiener_win2 >> 1];
1416
0
  iQ = H[(wiener_win2 >> 1) * wiener_win2 + (wiener_win2 >> 1)];
1417
0
  iScore = iQ - 2 * iP;
1418
1419
0
  return Score - iScore;
1420
0
}
1421
1422
static inline void finalize_sym_filter(int wiener_win, int32_t *f,
1423
0
                                       InterpKernel fi) {
1424
0
  int i;
1425
0
  const int wiener_halfwin = (wiener_win >> 1);
1426
1427
0
  for (i = 0; i < wiener_halfwin; ++i) {
1428
0
    const int64_t dividend = (int64_t)f[i] * WIENER_FILT_STEP;
1429
0
    const int64_t divisor = WIENER_TAP_SCALE_FACTOR;
1430
    // Perform this division with proper rounding rather than truncation
1431
0
    if (dividend < 0) {
1432
0
      fi[i] = (int16_t)((dividend - (divisor / 2)) / divisor);
1433
0
    } else {
1434
0
      fi[i] = (int16_t)((dividend + (divisor / 2)) / divisor);
1435
0
    }
1436
0
  }
1437
  // Specialize for 7-tap filter
1438
0
  if (wiener_win == WIENER_WIN) {
1439
0
    fi[0] = CLIP(fi[0], WIENER_FILT_TAP0_MINV, WIENER_FILT_TAP0_MAXV);
1440
0
    fi[1] = CLIP(fi[1], WIENER_FILT_TAP1_MINV, WIENER_FILT_TAP1_MAXV);
1441
0
    fi[2] = CLIP(fi[2], WIENER_FILT_TAP2_MINV, WIENER_FILT_TAP2_MAXV);
1442
0
  } else {
1443
0
    fi[2] = CLIP(fi[1], WIENER_FILT_TAP2_MINV, WIENER_FILT_TAP2_MAXV);
1444
0
    fi[1] = CLIP(fi[0], WIENER_FILT_TAP1_MINV, WIENER_FILT_TAP1_MAXV);
1445
0
    fi[0] = 0;
1446
0
  }
1447
  // Satisfy filter constraints
1448
0
  fi[WIENER_WIN - 1] = fi[0];
1449
0
  fi[WIENER_WIN - 2] = fi[1];
1450
0
  fi[WIENER_WIN - 3] = fi[2];
1451
  // The central element has an implicit +WIENER_FILT_STEP
1452
0
  fi[3] = -2 * (fi[0] + fi[1] + fi[2]);
1453
0
}
1454
1455
static int count_wiener_bits(int wiener_win, WienerInfo *wiener_info,
1456
0
                             WienerInfo *ref_wiener_info) {
1457
0
  int bits = 0;
1458
0
  if (wiener_win == WIENER_WIN)
1459
0
    bits += aom_count_primitive_refsubexpfin(
1460
0
        WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
1461
0
        WIENER_FILT_TAP0_SUBEXP_K,
1462
0
        ref_wiener_info->vfilter[0] - WIENER_FILT_TAP0_MINV,
1463
0
        wiener_info->vfilter[0] - WIENER_FILT_TAP0_MINV);
1464
0
  bits += aom_count_primitive_refsubexpfin(
1465
0
      WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
1466
0
      WIENER_FILT_TAP1_SUBEXP_K,
1467
0
      ref_wiener_info->vfilter[1] - WIENER_FILT_TAP1_MINV,
1468
0
      wiener_info->vfilter[1] - WIENER_FILT_TAP1_MINV);
1469
0
  bits += aom_count_primitive_refsubexpfin(
1470
0
      WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
1471
0
      WIENER_FILT_TAP2_SUBEXP_K,
1472
0
      ref_wiener_info->vfilter[2] - WIENER_FILT_TAP2_MINV,
1473
0
      wiener_info->vfilter[2] - WIENER_FILT_TAP2_MINV);
1474
0
  if (wiener_win == WIENER_WIN)
1475
0
    bits += aom_count_primitive_refsubexpfin(
1476
0
        WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
1477
0
        WIENER_FILT_TAP0_SUBEXP_K,
1478
0
        ref_wiener_info->hfilter[0] - WIENER_FILT_TAP0_MINV,
1479
0
        wiener_info->hfilter[0] - WIENER_FILT_TAP0_MINV);
1480
0
  bits += aom_count_primitive_refsubexpfin(
1481
0
      WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
1482
0
      WIENER_FILT_TAP1_SUBEXP_K,
1483
0
      ref_wiener_info->hfilter[1] - WIENER_FILT_TAP1_MINV,
1484
0
      wiener_info->hfilter[1] - WIENER_FILT_TAP1_MINV);
1485
0
  bits += aom_count_primitive_refsubexpfin(
1486
0
      WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
1487
0
      WIENER_FILT_TAP2_SUBEXP_K,
1488
0
      ref_wiener_info->hfilter[2] - WIENER_FILT_TAP2_MINV,
1489
0
      wiener_info->hfilter[2] - WIENER_FILT_TAP2_MINV);
1490
0
  return bits;
1491
0
}
1492
1493
static int64_t finer_search_wiener(const RestSearchCtxt *rsc,
1494
                                   const RestorationTileLimits *limits,
1495
0
                                   RestorationUnitInfo *rui, int wiener_win) {
1496
0
  const int plane_off = (WIENER_WIN - wiener_win) >> 1;
1497
0
  int64_t err = try_restoration_unit(rsc, limits, rui);
1498
1499
0
  if (rsc->lpf_sf->disable_wiener_coeff_refine_search) return err;
1500
1501
  // Refinement search around the wiener filter coefficients.
1502
0
  int64_t err2;
1503
0
  int tap_min[] = { WIENER_FILT_TAP0_MINV, WIENER_FILT_TAP1_MINV,
1504
0
                    WIENER_FILT_TAP2_MINV };
1505
0
  int tap_max[] = { WIENER_FILT_TAP0_MAXV, WIENER_FILT_TAP1_MAXV,
1506
0
                    WIENER_FILT_TAP2_MAXV };
1507
1508
0
  WienerInfo *plane_wiener = &rui->wiener_info;
1509
1510
  // printf("err  pre = %"PRId64"\n", err);
1511
0
  const int start_step = 4;
1512
0
  for (int s = start_step; s >= 1; s >>= 1) {
1513
0
    for (int p = plane_off; p < WIENER_HALFWIN; ++p) {
1514
0
      int skip = 0;
1515
0
      do {
1516
0
        if (plane_wiener->hfilter[p] - s >= tap_min[p]) {
1517
0
          plane_wiener->hfilter[p] -= s;
1518
0
          plane_wiener->hfilter[WIENER_WIN - p - 1] -= s;
1519
0
          plane_wiener->hfilter[WIENER_HALFWIN] += 2 * s;
1520
0
          err2 = try_restoration_unit(rsc, limits, rui);
1521
0
          if (err2 > err) {
1522
0
            plane_wiener->hfilter[p] += s;
1523
0
            plane_wiener->hfilter[WIENER_WIN - p - 1] += s;
1524
0
            plane_wiener->hfilter[WIENER_HALFWIN] -= 2 * s;
1525
0
          } else {
1526
0
            err = err2;
1527
0
            skip = 1;
1528
            // At the highest step size continue moving in the same direction
1529
0
            if (s == start_step) continue;
1530
0
          }
1531
0
        }
1532
0
        break;
1533
0
      } while (1);
1534
0
      if (skip) break;
1535
0
      do {
1536
0
        if (plane_wiener->hfilter[p] + s <= tap_max[p]) {
1537
0
          plane_wiener->hfilter[p] += s;
1538
0
          plane_wiener->hfilter[WIENER_WIN - p - 1] += s;
1539
0
          plane_wiener->hfilter[WIENER_HALFWIN] -= 2 * s;
1540
0
          err2 = try_restoration_unit(rsc, limits, rui);
1541
0
          if (err2 > err) {
1542
0
            plane_wiener->hfilter[p] -= s;
1543
0
            plane_wiener->hfilter[WIENER_WIN - p - 1] -= s;
1544
0
            plane_wiener->hfilter[WIENER_HALFWIN] += 2 * s;
1545
0
          } else {
1546
0
            err = err2;
1547
            // At the highest step size continue moving in the same direction
1548
0
            if (s == start_step) continue;
1549
0
          }
1550
0
        }
1551
0
        break;
1552
0
      } while (1);
1553
0
    }
1554
0
    for (int p = plane_off; p < WIENER_HALFWIN; ++p) {
1555
0
      int skip = 0;
1556
0
      do {
1557
0
        if (plane_wiener->vfilter[p] - s >= tap_min[p]) {
1558
0
          plane_wiener->vfilter[p] -= s;
1559
0
          plane_wiener->vfilter[WIENER_WIN - p - 1] -= s;
1560
0
          plane_wiener->vfilter[WIENER_HALFWIN] += 2 * s;
1561
0
          err2 = try_restoration_unit(rsc, limits, rui);
1562
0
          if (err2 > err) {
1563
0
            plane_wiener->vfilter[p] += s;
1564
0
            plane_wiener->vfilter[WIENER_WIN - p - 1] += s;
1565
0
            plane_wiener->vfilter[WIENER_HALFWIN] -= 2 * s;
1566
0
          } else {
1567
0
            err = err2;
1568
0
            skip = 1;
1569
            // At the highest step size continue moving in the same direction
1570
0
            if (s == start_step) continue;
1571
0
          }
1572
0
        }
1573
0
        break;
1574
0
      } while (1);
1575
0
      if (skip) break;
1576
0
      do {
1577
0
        if (plane_wiener->vfilter[p] + s <= tap_max[p]) {
1578
0
          plane_wiener->vfilter[p] += s;
1579
0
          plane_wiener->vfilter[WIENER_WIN - p - 1] += s;
1580
0
          plane_wiener->vfilter[WIENER_HALFWIN] -= 2 * s;
1581
0
          err2 = try_restoration_unit(rsc, limits, rui);
1582
0
          if (err2 > err) {
1583
0
            plane_wiener->vfilter[p] -= s;
1584
0
            plane_wiener->vfilter[WIENER_WIN - p - 1] -= s;
1585
0
            plane_wiener->vfilter[WIENER_HALFWIN] += 2 * s;
1586
0
          } else {
1587
0
            err = err2;
1588
            // At the highest step size continue moving in the same direction
1589
0
            if (s == start_step) continue;
1590
0
          }
1591
0
        }
1592
0
        break;
1593
0
      } while (1);
1594
0
    }
1595
0
  }
1596
  // printf("err post = %"PRId64"\n", err);
1597
0
  return err;
1598
0
}
1599
1600
static inline void search_wiener(const RestorationTileLimits *limits,
1601
                                 int rest_unit_idx, void *priv, int32_t *tmpbuf,
1602
                                 RestorationLineBuffers *rlbs,
1603
0
                                 struct aom_internal_error_info *error_info) {
1604
0
  (void)tmpbuf;
1605
0
  (void)rlbs;
1606
0
  (void)error_info;
1607
0
  RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
1608
0
  RestUnitSearchInfo *rusi = &rsc->rusi[rest_unit_idx];
1609
1610
0
  const MACROBLOCK *const x = rsc->x;
1611
0
  const int64_t bits_none = x->mode_costs.wiener_restore_cost[0];
1612
1613
  // Skip Wiener search for low variance contents
1614
0
  if (rsc->lpf_sf->prune_wiener_based_on_src_var) {
1615
0
    const int scale[3] = { 0, 1, 2 };
1616
    // Obtain the normalized Qscale
1617
0
    const int qs = av1_dc_quant_QTX(rsc->cm->quant_params.base_qindex, 0,
1618
0
                                    rsc->cm->seq_params->bit_depth) >>
1619
0
                   3;
1620
    // Derive threshold as sqr(normalized Qscale) * scale / 16,
1621
0
    const uint64_t thresh =
1622
0
        (qs * qs * scale[rsc->lpf_sf->prune_wiener_based_on_src_var]) >> 4;
1623
0
    const int highbd = rsc->cm->seq_params->use_highbitdepth;
1624
0
    const uint64_t src_var =
1625
0
        var_restoration_unit(limits, rsc->src, rsc->plane, highbd);
1626
    // Do not perform Wiener search if source variance is lower than threshold
1627
    // or if the reconstruction error is zero
1628
0
    int prune_wiener = (src_var < thresh) || (rsc->sse[RESTORE_NONE] == 0);
1629
0
    if (prune_wiener) {
1630
0
      rsc->total_bits[RESTORE_WIENER] += bits_none;
1631
0
      rsc->total_sse[RESTORE_WIENER] += rsc->sse[RESTORE_NONE];
1632
0
      rusi->best_rtype[RESTORE_WIENER - 1] = RESTORE_NONE;
1633
0
      rsc->sse[RESTORE_WIENER] = INT64_MAX;
1634
0
      if (rsc->lpf_sf->prune_sgr_based_on_wiener == 2) rsc->skip_sgr_eval = 1;
1635
0
      return;
1636
0
    }
1637
0
  }
1638
1639
0
  const int wiener_win =
1640
0
      (rsc->plane == AOM_PLANE_Y) ? WIENER_WIN : WIENER_WIN_CHROMA;
1641
1642
0
  int reduced_wiener_win = wiener_win;
1643
0
  if (rsc->lpf_sf->reduce_wiener_window_size) {
1644
0
    reduced_wiener_win =
1645
0
        (rsc->plane == AOM_PLANE_Y) ? WIENER_WIN_REDUCED : WIENER_WIN_CHROMA;
1646
0
  }
1647
1648
0
  int64_t M[WIENER_WIN2];
1649
0
  int64_t H[WIENER_WIN2 * WIENER_WIN2];
1650
0
  int32_t vfilter[WIENER_WIN], hfilter[WIENER_WIN];
1651
1652
0
#if CONFIG_AV1_HIGHBITDEPTH
1653
0
  const AV1_COMMON *const cm = rsc->cm;
1654
0
  if (cm->seq_params->use_highbitdepth) {
1655
    // TODO(any) : Add support for use_downsampled_wiener_stats SF in HBD
1656
    // functions. Optimize intrinsics of HBD design similar to LBD (i.e.,
1657
    // pre-calculate d and s buffers and avoid most of the C operations).
1658
0
    av1_compute_stats_highbd(reduced_wiener_win, rsc->dgd_buffer,
1659
0
                             rsc->src_buffer, rsc->dgd_avg, rsc->src_avg,
1660
0
                             limits->h_start, limits->h_end, limits->v_start,
1661
0
                             limits->v_end, rsc->dgd_stride, rsc->src_stride, M,
1662
0
                             H, cm->seq_params->bit_depth);
1663
0
  } else {
1664
0
    av1_compute_stats(reduced_wiener_win, rsc->dgd_buffer, rsc->src_buffer,
1665
0
                      rsc->dgd_avg, rsc->src_avg, limits->h_start,
1666
0
                      limits->h_end, limits->v_start, limits->v_end,
1667
0
                      rsc->dgd_stride, rsc->src_stride, M, H,
1668
0
                      rsc->lpf_sf->use_downsampled_wiener_stats);
1669
0
  }
1670
#else
1671
  av1_compute_stats(reduced_wiener_win, rsc->dgd_buffer, rsc->src_buffer,
1672
                    rsc->dgd_avg, rsc->src_avg, limits->h_start, limits->h_end,
1673
                    limits->v_start, limits->v_end, rsc->dgd_stride,
1674
                    rsc->src_stride, M, H,
1675
                    rsc->lpf_sf->use_downsampled_wiener_stats);
1676
#endif
1677
1678
0
  wiener_decompose_sep_sym(reduced_wiener_win, M, H, vfilter, hfilter);
1679
1680
0
  RestorationUnitInfo rui;
1681
0
  memset(&rui, 0, sizeof(rui));
1682
0
  rui.restoration_type = RESTORE_WIENER;
1683
0
  finalize_sym_filter(reduced_wiener_win, vfilter, rui.wiener_info.vfilter);
1684
0
  finalize_sym_filter(reduced_wiener_win, hfilter, rui.wiener_info.hfilter);
1685
1686
  // Filter score computes the value of the function x'*A*x - x'*b for the
1687
  // learned filter and compares it against identity filer. If there is no
1688
  // reduction in the function, the filter is reverted back to identity
1689
0
  if (compute_score(reduced_wiener_win, M, H, rui.wiener_info.vfilter,
1690
0
                    rui.wiener_info.hfilter) > 0) {
1691
0
    rsc->total_bits[RESTORE_WIENER] += bits_none;
1692
0
    rsc->total_sse[RESTORE_WIENER] += rsc->sse[RESTORE_NONE];
1693
0
    rusi->best_rtype[RESTORE_WIENER - 1] = RESTORE_NONE;
1694
0
    rsc->sse[RESTORE_WIENER] = INT64_MAX;
1695
0
    if (rsc->lpf_sf->prune_sgr_based_on_wiener == 2) rsc->skip_sgr_eval = 1;
1696
0
    return;
1697
0
  }
1698
1699
0
  rsc->sse[RESTORE_WIENER] =
1700
0
      finer_search_wiener(rsc, limits, &rui, reduced_wiener_win);
1701
0
  rusi->wiener = rui.wiener_info;
1702
1703
0
  if (reduced_wiener_win != WIENER_WIN) {
1704
0
    assert(rui.wiener_info.vfilter[0] == 0 &&
1705
0
           rui.wiener_info.vfilter[WIENER_WIN - 1] == 0);
1706
0
    assert(rui.wiener_info.hfilter[0] == 0 &&
1707
0
           rui.wiener_info.hfilter[WIENER_WIN - 1] == 0);
1708
0
  }
1709
1710
0
  const int64_t bits_wiener =
1711
0
      x->mode_costs.wiener_restore_cost[1] +
1712
0
      (count_wiener_bits(wiener_win, &rusi->wiener, &rsc->ref_wiener)
1713
0
       << AV1_PROB_COST_SHIFT);
1714
1715
0
  double cost_none = RDCOST_DBL_WITH_NATIVE_BD_DIST(
1716
0
      x->rdmult, bits_none >> 4, rsc->sse[RESTORE_NONE],
1717
0
      rsc->cm->seq_params->bit_depth);
1718
0
  double cost_wiener = RDCOST_DBL_WITH_NATIVE_BD_DIST(
1719
0
      x->rdmult, bits_wiener >> 4, rsc->sse[RESTORE_WIENER],
1720
0
      rsc->cm->seq_params->bit_depth);
1721
1722
0
  RestorationType rtype =
1723
0
      (cost_wiener < cost_none) ? RESTORE_WIENER : RESTORE_NONE;
1724
0
  rusi->best_rtype[RESTORE_WIENER - 1] = rtype;
1725
1726
  // Set 'skip_sgr_eval' based on rdcost ratio of RESTORE_WIENER and
1727
  // RESTORE_NONE or based on best_rtype
1728
0
  if (rsc->lpf_sf->prune_sgr_based_on_wiener == 1) {
1729
0
    rsc->skip_sgr_eval = cost_wiener > (1.01 * cost_none);
1730
0
  } else if (rsc->lpf_sf->prune_sgr_based_on_wiener == 2) {
1731
0
    rsc->skip_sgr_eval = rusi->best_rtype[RESTORE_WIENER - 1] == RESTORE_NONE;
1732
0
  }
1733
1734
#if DEBUG_LR_COSTING
1735
  // Store ref params for later checking
1736
  lr_ref_params[RESTORE_WIENER][rsc->plane][rest_unit_idx].wiener_info =
1737
      rsc->ref_wiener;
1738
#endif  // DEBUG_LR_COSTING
1739
1740
0
  rsc->total_sse[RESTORE_WIENER] += rsc->sse[rtype];
1741
0
  rsc->total_bits[RESTORE_WIENER] +=
1742
0
      (cost_wiener < cost_none) ? bits_wiener : bits_none;
1743
0
  if (cost_wiener < cost_none) rsc->ref_wiener = rusi->wiener;
1744
0
}
1745
1746
static inline void search_norestore(
1747
    const RestorationTileLimits *limits, int rest_unit_idx, void *priv,
1748
    int32_t *tmpbuf, RestorationLineBuffers *rlbs,
1749
0
    struct aom_internal_error_info *error_info) {
1750
0
  (void)rest_unit_idx;
1751
0
  (void)tmpbuf;
1752
0
  (void)rlbs;
1753
0
  (void)error_info;
1754
1755
0
  RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
1756
1757
0
  const int highbd = rsc->cm->seq_params->use_highbitdepth;
1758
0
  rsc->sse[RESTORE_NONE] = sse_restoration_unit(
1759
0
      limits, rsc->src, &rsc->cm->cur_frame->buf, rsc->plane, highbd);
1760
1761
0
  rsc->total_sse[RESTORE_NONE] += rsc->sse[RESTORE_NONE];
1762
0
}
1763
1764
static inline void search_switchable(
1765
    const RestorationTileLimits *limits, int rest_unit_idx, void *priv,
1766
    int32_t *tmpbuf, RestorationLineBuffers *rlbs,
1767
0
    struct aom_internal_error_info *error_info) {
1768
0
  (void)limits;
1769
0
  (void)tmpbuf;
1770
0
  (void)rlbs;
1771
0
  (void)error_info;
1772
0
  RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
1773
0
  RestUnitSearchInfo *rusi = &rsc->rusi[rest_unit_idx];
1774
1775
0
  const MACROBLOCK *const x = rsc->x;
1776
1777
0
  const int wiener_win =
1778
0
      (rsc->plane == AOM_PLANE_Y) ? WIENER_WIN : WIENER_WIN_CHROMA;
1779
1780
0
  double best_cost = 0;
1781
0
  int64_t best_bits = 0;
1782
0
  RestorationType best_rtype = RESTORE_NONE;
1783
1784
0
  for (RestorationType r = 0; r < RESTORE_SWITCHABLE_TYPES; ++r) {
1785
    // If this restoration mode was skipped, or could not find a solution
1786
    // that was better than RESTORE_NONE, then we can't select it here either.
1787
    //
1788
    // Note: It is possible for the restoration search functions to find a
1789
    // filter which is better than RESTORE_NONE when looking purely at SSE, but
1790
    // for it to be rejected overall due to its rate cost. In this case, there
1791
    // is a chance that it may be have a lower rate cost when looking at
1792
    // RESTORE_SWITCHABLE, and so it might be acceptable here.
1793
    //
1794
    // Therefore we prune based on SSE, rather than on whether or not the
1795
    // previous search function selected this mode.
1796
0
    if (r > RESTORE_NONE) {
1797
0
      if (rsc->sse[r] > rsc->sse[RESTORE_NONE]) continue;
1798
0
    }
1799
1800
0
    const int64_t sse = rsc->sse[r];
1801
0
    int64_t coeff_pcost = 0;
1802
0
    switch (r) {
1803
0
      case RESTORE_NONE: coeff_pcost = 0; break;
1804
0
      case RESTORE_WIENER:
1805
0
        coeff_pcost = count_wiener_bits(wiener_win, &rusi->wiener,
1806
0
                                        &rsc->switchable_ref_wiener);
1807
0
        break;
1808
0
      case RESTORE_SGRPROJ:
1809
0
        coeff_pcost =
1810
0
            count_sgrproj_bits(&rusi->sgrproj, &rsc->switchable_ref_sgrproj);
1811
0
        break;
1812
0
      default: assert(0); break;
1813
0
    }
1814
0
    const int64_t coeff_bits = coeff_pcost << AV1_PROB_COST_SHIFT;
1815
0
    const int64_t bits = x->mode_costs.switchable_restore_cost[r] + coeff_bits;
1816
0
    double cost = RDCOST_DBL_WITH_NATIVE_BD_DIST(
1817
0
        x->rdmult, bits >> 4, sse, rsc->cm->seq_params->bit_depth);
1818
0
    if (r == RESTORE_SGRPROJ && rusi->sgrproj.ep < 10)
1819
0
      cost *= (1 + DUAL_SGR_PENALTY_MULT * rsc->lpf_sf->dual_sgr_penalty_level);
1820
0
    if (r == 0 || cost < best_cost) {
1821
0
      best_cost = cost;
1822
0
      best_bits = bits;
1823
0
      best_rtype = r;
1824
0
    }
1825
0
  }
1826
1827
0
  rusi->best_rtype[RESTORE_SWITCHABLE - 1] = best_rtype;
1828
1829
#if DEBUG_LR_COSTING
1830
  // Store ref params for later checking
1831
  lr_ref_params[RESTORE_SWITCHABLE][rsc->plane][rest_unit_idx].wiener_info =
1832
      rsc->switchable_ref_wiener;
1833
  lr_ref_params[RESTORE_SWITCHABLE][rsc->plane][rest_unit_idx].sgrproj_info =
1834
      rsc->switchable_ref_sgrproj;
1835
#endif  // DEBUG_LR_COSTING
1836
1837
0
  rsc->total_sse[RESTORE_SWITCHABLE] += rsc->sse[best_rtype];
1838
0
  rsc->total_bits[RESTORE_SWITCHABLE] += best_bits;
1839
0
  if (best_rtype == RESTORE_WIENER) rsc->switchable_ref_wiener = rusi->wiener;
1840
0
  if (best_rtype == RESTORE_SGRPROJ)
1841
0
    rsc->switchable_ref_sgrproj = rusi->sgrproj;
1842
0
}
1843
1844
static inline void copy_unit_info(RestorationType frame_rtype,
1845
                                  const RestUnitSearchInfo *rusi,
1846
0
                                  RestorationUnitInfo *rui) {
1847
0
  assert(frame_rtype > 0);
1848
0
  rui->restoration_type = rusi->best_rtype[frame_rtype - 1];
1849
0
  if (rui->restoration_type == RESTORE_WIENER)
1850
0
    rui->wiener_info = rusi->wiener;
1851
0
  else
1852
0
    rui->sgrproj_info = rusi->sgrproj;
1853
0
}
1854
1855
static void restoration_search(AV1_COMMON *cm, int plane, RestSearchCtxt *rsc,
1856
0
                               bool *disable_lr_filter) {
1857
0
  const BLOCK_SIZE sb_size = cm->seq_params->sb_size;
1858
0
  const int mib_size_log2 = cm->seq_params->mib_size_log2;
1859
0
  const CommonTileParams *tiles = &cm->tiles;
1860
0
  const int is_uv = plane > 0;
1861
0
  const int ss_y = is_uv && cm->seq_params->subsampling_y;
1862
0
  RestorationInfo *rsi = &cm->rst_info[plane];
1863
0
  const int ru_size = rsi->restoration_unit_size;
1864
0
  const int ext_size = ru_size * 3 / 2;
1865
1866
0
  int plane_w, plane_h;
1867
0
  av1_get_upsampled_plane_size(cm, is_uv, &plane_w, &plane_h);
1868
1869
0
  static const rest_unit_visitor_t funs[RESTORE_TYPES] = {
1870
0
    search_norestore, search_wiener, search_sgrproj, search_switchable
1871
0
  };
1872
1873
0
  const int plane_num_units = rsi->num_rest_units;
1874
0
  const RestorationType num_rtypes =
1875
0
      (plane_num_units > 1) ? RESTORE_TYPES : RESTORE_SWITCHABLE_TYPES;
1876
1877
0
  reset_rsc(rsc);
1878
1879
  // Iterate over restoration units in encoding order, so that each RU gets
1880
  // the correct reference parameters when we cost it up. This is effectively
1881
  // a nested iteration over:
1882
  // * Each tile, order does not matter
1883
  //   * Each superblock within that tile, in raster order
1884
  //     * Each LR unit which is coded within that superblock, in raster order
1885
0
  for (int tile_row = 0; tile_row < tiles->rows; tile_row++) {
1886
0
    int sb_row_start = tiles->row_start_sb[tile_row];
1887
0
    int sb_row_end = tiles->row_start_sb[tile_row + 1];
1888
0
    for (int tile_col = 0; tile_col < tiles->cols; tile_col++) {
1889
0
      int sb_col_start = tiles->col_start_sb[tile_col];
1890
0
      int sb_col_end = tiles->col_start_sb[tile_col + 1];
1891
1892
      // Reset reference parameters for delta-coding at the start of each tile
1893
0
      rsc_on_tile(rsc);
1894
1895
0
      for (int sb_row = sb_row_start; sb_row < sb_row_end; sb_row++) {
1896
0
        int mi_row = sb_row << mib_size_log2;
1897
0
        for (int sb_col = sb_col_start; sb_col < sb_col_end; sb_col++) {
1898
0
          int mi_col = sb_col << mib_size_log2;
1899
1900
0
          int rcol0, rcol1, rrow0, rrow1;
1901
0
          int has_lr_info = av1_loop_restoration_corners_in_sb(
1902
0
              cm, plane, mi_row, mi_col, sb_size, &rcol0, &rcol1, &rrow0,
1903
0
              &rrow1);
1904
1905
0
          if (!has_lr_info) continue;
1906
1907
0
          RestorationTileLimits limits;
1908
0
          for (int rrow = rrow0; rrow < rrow1; rrow++) {
1909
0
            int y0 = rrow * ru_size;
1910
0
            int remaining_h = plane_h - y0;
1911
0
            int h = (remaining_h < ext_size) ? remaining_h : ru_size;
1912
1913
0
            limits.v_start = y0;
1914
0
            limits.v_end = y0 + h;
1915
0
            assert(limits.v_end <= plane_h);
1916
            // Offset upwards to align with the restoration processing stripe
1917
0
            const int voffset = RESTORATION_UNIT_OFFSET >> ss_y;
1918
0
            limits.v_start = AOMMAX(0, limits.v_start - voffset);
1919
0
            if (limits.v_end < plane_h) limits.v_end -= voffset;
1920
1921
0
            for (int rcol = rcol0; rcol < rcol1; rcol++) {
1922
0
              int x0 = rcol * ru_size;
1923
0
              int remaining_w = plane_w - x0;
1924
0
              int w = (remaining_w < ext_size) ? remaining_w : ru_size;
1925
1926
0
              limits.h_start = x0;
1927
0
              limits.h_end = x0 + w;
1928
0
              assert(limits.h_end <= plane_w);
1929
1930
0
              const int unit_idx = rrow * rsi->horz_units + rcol;
1931
1932
0
              rsc->skip_sgr_eval = 0;
1933
0
              for (RestorationType r = RESTORE_NONE; r < num_rtypes; r++) {
1934
0
                if (disable_lr_filter[r]) continue;
1935
1936
0
                funs[r](&limits, unit_idx, rsc, rsc->cm->rst_tmpbuf, NULL,
1937
0
                        cm->error);
1938
0
              }
1939
0
            }
1940
0
          }
1941
0
        }
1942
0
      }
1943
0
    }
1944
0
  }
1945
0
}
1946
1947
static inline void av1_derive_flags_for_lr_processing(
1948
0
    const LOOP_FILTER_SPEED_FEATURES *lpf_sf, bool *disable_lr_filter) {
1949
0
  const bool is_wiener_disabled = lpf_sf->disable_wiener_filter;
1950
0
  const bool is_sgr_disabled = lpf_sf->disable_sgr_filter;
1951
1952
  // Enable None Loop restoration filter if either of Wiener or Self-guided is
1953
  // enabled.
1954
0
  disable_lr_filter[RESTORE_NONE] = (is_wiener_disabled && is_sgr_disabled);
1955
1956
0
  disable_lr_filter[RESTORE_WIENER] = is_wiener_disabled;
1957
0
  disable_lr_filter[RESTORE_SGRPROJ] = is_sgr_disabled;
1958
1959
  // Enable Swicthable Loop restoration filter if both of the Wiener and
1960
  // Self-guided are enabled.
1961
0
  disable_lr_filter[RESTORE_SWITCHABLE] =
1962
0
      (is_wiener_disabled || is_sgr_disabled);
1963
0
}
1964
1965
#define COUPLED_CHROMA_FROM_LUMA_RESTORATION 0
1966
// Allocate both decoder-side and encoder-side info structs for a single plane.
1967
// The unit size passed in should be the minimum size which we are going to
1968
// search; before each search, set_restoration_unit_size() must be called to
1969
// configure the actual size.
1970
static RestUnitSearchInfo *allocate_search_structs(AV1_COMMON *cm,
1971
                                                   RestorationInfo *rsi,
1972
                                                   int is_uv,
1973
0
                                                   int min_luma_unit_size) {
1974
#if COUPLED_CHROMA_FROM_LUMA_RESTORATION
1975
  int sx = cm->seq_params.subsampling_x;
1976
  int sy = cm->seq_params.subsampling_y;
1977
  int s = (p > 0) ? AOMMIN(sx, sy) : 0;
1978
#else
1979
0
  int s = 0;
1980
0
#endif  // !COUPLED_CHROMA_FROM_LUMA_RESTORATION
1981
0
  int min_unit_size = min_luma_unit_size >> s;
1982
1983
0
  int plane_w, plane_h;
1984
0
  av1_get_upsampled_plane_size(cm, is_uv, &plane_w, &plane_h);
1985
1986
0
  const int max_horz_units = av1_lr_count_units(min_unit_size, plane_w);
1987
0
  const int max_vert_units = av1_lr_count_units(min_unit_size, plane_h);
1988
0
  const int max_num_units = max_horz_units * max_vert_units;
1989
1990
0
  aom_free(rsi->unit_info);
1991
0
  CHECK_MEM_ERROR(cm, rsi->unit_info,
1992
0
                  (RestorationUnitInfo *)aom_memalign(
1993
0
                      16, sizeof(*rsi->unit_info) * max_num_units));
1994
1995
0
  RestUnitSearchInfo *rusi;
1996
0
  CHECK_MEM_ERROR(
1997
0
      cm, rusi,
1998
0
      (RestUnitSearchInfo *)aom_memalign(16, sizeof(*rusi) * max_num_units));
1999
2000
  // If the restoration unit dimensions are not multiples of
2001
  // rsi->restoration_unit_size then some elements of the rusi array may be
2002
  // left uninitialised when we reach copy_unit_info(...). This is not a
2003
  // problem, as these elements are ignored later, but in order to quiet
2004
  // Valgrind's warnings we initialise the array below.
2005
0
  memset(rusi, 0, sizeof(*rusi) * max_num_units);
2006
2007
0
  return rusi;
2008
0
}
2009
2010
static void set_restoration_unit_size(AV1_COMMON *cm, RestorationInfo *rsi,
2011
0
                                      int is_uv, int luma_unit_size) {
2012
#if COUPLED_CHROMA_FROM_LUMA_RESTORATION
2013
  int sx = cm->seq_params.subsampling_x;
2014
  int sy = cm->seq_params.subsampling_y;
2015
  int s = (p > 0) ? AOMMIN(sx, sy) : 0;
2016
#else
2017
0
  int s = 0;
2018
0
#endif  // !COUPLED_CHROMA_FROM_LUMA_RESTORATION
2019
0
  int unit_size = luma_unit_size >> s;
2020
2021
0
  int plane_w, plane_h;
2022
0
  av1_get_upsampled_plane_size(cm, is_uv, &plane_w, &plane_h);
2023
2024
0
  const int horz_units = av1_lr_count_units(unit_size, plane_w);
2025
0
  const int vert_units = av1_lr_count_units(unit_size, plane_h);
2026
2027
0
  rsi->restoration_unit_size = unit_size;
2028
0
  rsi->num_rest_units = horz_units * vert_units;
2029
0
  rsi->horz_units = horz_units;
2030
0
  rsi->vert_units = vert_units;
2031
0
}
2032
2033
0
void av1_pick_filter_restoration(const YV12_BUFFER_CONFIG *src, AV1_COMP *cpi) {
2034
0
  AV1_COMMON *const cm = &cpi->common;
2035
0
  MACROBLOCK *const x = &cpi->td.mb;
2036
0
  const SequenceHeader *const seq_params = cm->seq_params;
2037
0
  const LOOP_FILTER_SPEED_FEATURES *lpf_sf = &cpi->sf.lpf_sf;
2038
0
  const int num_planes = av1_num_planes(cm);
2039
0
  const int highbd = cm->seq_params->use_highbitdepth;
2040
0
  assert(!cm->features.all_lossless);
2041
2042
0
  av1_fill_lr_rates(&x->mode_costs, x->e_mbd.tile_ctx);
2043
2044
  // Select unit size based on speed feature settings, and allocate
2045
  // rui structs based on this size
2046
0
  int min_lr_unit_size = cpi->sf.lpf_sf.min_lr_unit_size;
2047
0
  int max_lr_unit_size = cpi->sf.lpf_sf.max_lr_unit_size;
2048
2049
  // The minimum allowed unit size at a syntax level is 1 superblock.
2050
  // Apply this constraint here so that the speed features code which sets
2051
  // cpi->sf.lpf_sf.min_lr_unit_size does not need to know the superblock size
2052
0
  min_lr_unit_size =
2053
0
      AOMMAX(min_lr_unit_size, block_size_wide[cm->seq_params->sb_size]);
2054
2055
0
  for (int plane = 0; plane < num_planes; ++plane) {
2056
0
    cpi->pick_lr_ctxt.rusi[plane] = allocate_search_structs(
2057
0
        cm, &cm->rst_info[plane], plane > 0, min_lr_unit_size);
2058
0
  }
2059
2060
0
  x->rdmult = cpi->rd.RDMULT;
2061
2062
  // Allocate the frame buffer trial_frame_rst, which is used to temporarily
2063
  // store the loop restored frame.
2064
0
  if (aom_realloc_frame_buffer(
2065
0
          &cpi->trial_frame_rst, cm->superres_upscaled_width,
2066
0
          cm->superres_upscaled_height, seq_params->subsampling_x,
2067
0
          seq_params->subsampling_y, highbd, AOM_RESTORATION_FRAME_BORDER,
2068
0
          cm->features.byte_alignment, NULL, NULL, NULL, false, 0))
2069
0
    aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
2070
0
                       "Failed to allocate trial restored frame buffer");
2071
2072
0
  RestSearchCtxt rsc;
2073
2074
  // The buffers 'src_avg' and 'dgd_avg' are used to compute H and M buffers.
2075
  // These buffers are only required for the AVX2 and NEON implementations of
2076
  // av1_compute_stats. The buffer size required is calculated based on maximum
2077
  // width and height of the LRU (i.e., from foreach_rest_unit_in_plane() 1.5
2078
  // times the RESTORATION_UNITSIZE_MAX) allowed for Wiener filtering. The width
2079
  // and height aligned to multiple of 16 is considered for intrinsic purpose.
2080
0
  rsc.dgd_avg = NULL;
2081
0
  rsc.src_avg = NULL;
2082
#if HAVE_AVX2 || HAVE_NEON || HAVE_SVE
2083
  // The buffers allocated below are used during Wiener filter processing.
2084
  // Hence, allocate the same when Wiener filter is enabled. Make sure to
2085
  // allocate these buffers only for the SIMD extensions that make use of them
2086
  // (i.e. AVX2 for low bitdepth and NEON and SVE for low and high bitdepth).
2087
#if HAVE_AVX2
2088
  bool allocate_buffers = !cpi->sf.lpf_sf.disable_wiener_filter && !highbd;
2089
#elif HAVE_NEON || HAVE_SVE
2090
  bool allocate_buffers = !cpi->sf.lpf_sf.disable_wiener_filter;
2091
#endif
2092
  if (allocate_buffers) {
2093
    const int buf_size = sizeof(*cpi->pick_lr_ctxt.dgd_avg) * 6 *
2094
                         RESTORATION_UNITSIZE_MAX * RESTORATION_UNITSIZE_MAX;
2095
    CHECK_MEM_ERROR(cm, cpi->pick_lr_ctxt.dgd_avg,
2096
                    (int16_t *)aom_memalign(32, buf_size));
2097
2098
    rsc.dgd_avg = cpi->pick_lr_ctxt.dgd_avg;
2099
    // When LRU width isn't multiple of 16, the 256 bits load instruction used
2100
    // in AVX2 intrinsic can read data beyond valid LRU. Hence, in order to
2101
    // silence Valgrind warning this buffer is initialized with zero. Overhead
2102
    // due to this initialization is negligible since it is done at frame level.
2103
    memset(rsc.dgd_avg, 0, buf_size);
2104
    rsc.src_avg =
2105
        rsc.dgd_avg + 3 * RESTORATION_UNITSIZE_MAX * RESTORATION_UNITSIZE_MAX;
2106
    // Asserts the starting address of src_avg is always 32-bytes aligned.
2107
    assert(!((intptr_t)rsc.src_avg % 32));
2108
  }
2109
#endif
2110
2111
  // Initialize all planes, so that any planes we skip searching will still have
2112
  // valid data
2113
0
  for (int plane = 0; plane < num_planes; plane++) {
2114
0
    cm->rst_info[plane].frame_restoration_type = RESTORE_NONE;
2115
0
  }
2116
2117
  // Decide which planes to search
2118
0
  int plane_start, plane_end;
2119
2120
0
  if (lpf_sf->disable_loop_restoration_luma) {
2121
0
    plane_start = AOM_PLANE_U;
2122
0
  } else {
2123
0
    plane_start = AOM_PLANE_Y;
2124
0
  }
2125
2126
0
  if (num_planes == 1 || lpf_sf->disable_loop_restoration_chroma) {
2127
0
    plane_end = AOM_PLANE_Y;
2128
0
  } else {
2129
0
    plane_end = AOM_PLANE_V;
2130
0
  }
2131
2132
  // Derive the flags to enable/disable Loop restoration filters based on the
2133
  // speed features 'disable_wiener_filter' and 'disable_sgr_filter'.
2134
0
  bool disable_lr_filter[RESTORE_TYPES] = { false };
2135
0
  av1_derive_flags_for_lr_processing(lpf_sf, disable_lr_filter);
2136
2137
0
  for (int plane = plane_start; plane <= plane_end; plane++) {
2138
0
    const YV12_BUFFER_CONFIG *dgd = &cm->cur_frame->buf;
2139
0
    const int is_uv = plane != AOM_PLANE_Y;
2140
0
    int plane_w, plane_h;
2141
0
    av1_get_upsampled_plane_size(cm, is_uv, &plane_w, &plane_h);
2142
0
    av1_extend_frame(dgd->buffers[plane], plane_w, plane_h, dgd->strides[is_uv],
2143
0
                     RESTORATION_BORDER, RESTORATION_BORDER, highbd);
2144
0
  }
2145
2146
0
  double best_cost = DBL_MAX;
2147
0
  int best_luma_unit_size = max_lr_unit_size;
2148
0
  for (int luma_unit_size = max_lr_unit_size;
2149
0
       luma_unit_size >= min_lr_unit_size; luma_unit_size >>= 1) {
2150
0
    int64_t bits_this_size = 0;
2151
0
    int64_t sse_this_size = 0;
2152
0
    RestorationType best_rtype[MAX_MB_PLANE] = { RESTORE_NONE, RESTORE_NONE,
2153
0
                                                 RESTORE_NONE };
2154
0
    for (int plane = plane_start; plane <= plane_end; ++plane) {
2155
0
      set_restoration_unit_size(cm, &cm->rst_info[plane], plane > 0,
2156
0
                                luma_unit_size);
2157
0
      init_rsc(src, &cpi->common, x, lpf_sf, plane,
2158
0
               cpi->pick_lr_ctxt.rusi[plane], &cpi->trial_frame_rst, &rsc);
2159
2160
0
      restoration_search(cm, plane, &rsc, disable_lr_filter);
2161
2162
0
      const int plane_num_units = cm->rst_info[plane].num_rest_units;
2163
0
      const RestorationType num_rtypes =
2164
0
          (plane_num_units > 1) ? RESTORE_TYPES : RESTORE_SWITCHABLE_TYPES;
2165
0
      double best_cost_this_plane = DBL_MAX;
2166
0
      for (RestorationType r = 0; r < num_rtypes; ++r) {
2167
        // Disable Loop restoration filter based on the flags set using speed
2168
        // feature 'disable_wiener_filter' and 'disable_sgr_filter'.
2169
0
        if (disable_lr_filter[r]) continue;
2170
2171
0
        double cost_this_plane = RDCOST_DBL_WITH_NATIVE_BD_DIST(
2172
0
            x->rdmult, rsc.total_bits[r] >> 4, rsc.total_sse[r],
2173
0
            cm->seq_params->bit_depth);
2174
2175
0
        if (cost_this_plane < best_cost_this_plane) {
2176
0
          best_cost_this_plane = cost_this_plane;
2177
0
          best_rtype[plane] = r;
2178
0
        }
2179
0
      }
2180
2181
0
      bits_this_size += rsc.total_bits[best_rtype[plane]];
2182
0
      sse_this_size += rsc.total_sse[best_rtype[plane]];
2183
0
    }
2184
2185
0
    double cost_this_size = RDCOST_DBL_WITH_NATIVE_BD_DIST(
2186
0
        x->rdmult, bits_this_size >> 4, sse_this_size,
2187
0
        cm->seq_params->bit_depth);
2188
2189
0
    if (cost_this_size < best_cost) {
2190
0
      best_cost = cost_this_size;
2191
0
      best_luma_unit_size = luma_unit_size;
2192
      // Copy parameters out of rusi struct, before we overwrite it at
2193
      // the start of the next iteration
2194
0
      bool all_none = true;
2195
0
      for (int plane = plane_start; plane <= plane_end; ++plane) {
2196
0
        cm->rst_info[plane].frame_restoration_type = best_rtype[plane];
2197
0
        if (best_rtype[plane] != RESTORE_NONE) {
2198
0
          all_none = false;
2199
0
          const int plane_num_units = cm->rst_info[plane].num_rest_units;
2200
0
          for (int u = 0; u < plane_num_units; ++u) {
2201
0
            copy_unit_info(best_rtype[plane], &cpi->pick_lr_ctxt.rusi[plane][u],
2202
0
                           &cm->rst_info[plane].unit_info[u]);
2203
0
          }
2204
0
        }
2205
0
      }
2206
      // Heuristic: If all best_rtype entries are RESTORE_NONE, this means we
2207
      // couldn't find any good filters at this size. So we likely won't find
2208
      // any good filters at a smaller size either, so skip
2209
0
      if (all_none) {
2210
0
        break;
2211
0
      }
2212
0
    } else {
2213
      // Heuristic: If this size is worse than the previous (larger) size, then
2214
      // the next size down will likely be even worse, so skip
2215
0
      break;
2216
0
    }
2217
0
  }
2218
2219
  // Final fixup to set the correct unit size
2220
  // We set this for all planes, even ones we have skipped searching,
2221
  // so that other code does not need to care which planes were and weren't
2222
  // searched
2223
0
  for (int plane = 0; plane < num_planes; ++plane) {
2224
0
    set_restoration_unit_size(cm, &cm->rst_info[plane], plane > 0,
2225
0
                              best_luma_unit_size);
2226
0
  }
2227
2228
#if HAVE_AVX2 || HAVE_NEON || HAVE_SVE
2229
#if HAVE_AVX2
2230
  bool free_buffers = !cpi->sf.lpf_sf.disable_wiener_filter && !highbd;
2231
#elif HAVE_NEON || HAVE_SVE
2232
  bool free_buffers = !cpi->sf.lpf_sf.disable_wiener_filter;
2233
#endif
2234
  if (free_buffers) {
2235
    aom_free(cpi->pick_lr_ctxt.dgd_avg);
2236
    cpi->pick_lr_ctxt.dgd_avg = NULL;
2237
  }
2238
#endif
2239
0
  for (int plane = 0; plane < num_planes; plane++) {
2240
0
    aom_free(cpi->pick_lr_ctxt.rusi[plane]);
2241
0
    cpi->pick_lr_ctxt.rusi[plane] = NULL;
2242
0
  }
2243
0
}