Coverage Report

Created: 2026-04-01 07:24

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