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