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/psnr.h"
23 #include "aom_mem/aom_mem.h"
24 #include "aom_ports/mem.h"
25 #include "aom_ports/system_state.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/mathutils.h"
33 #include "av1/encoder/picklpf.h"
34 #include "av1/encoder/pickrst.h"
35 
36 // When set to RESTORE_WIENER or RESTORE_SGRPROJ only those are allowed.
37 // When set to RESTORE_TYPES we allow switchable.
38 static const RestorationType force_restore_type = RESTORE_TYPES;
39 
40 // Number of Wiener iterations
41 #define NUM_WIENER_ITERS 5
42 
43 // Penalty factor for use of dual sgr
44 #define DUAL_SGR_PENALTY_MULT 0.01
45 
46 // Working precision for Wiener filter coefficients
47 #define WIENER_TAP_SCALE_FACTOR ((int64_t)1 << 16)
48 
49 #define SGRPROJ_EP_GRP1_START_IDX 0
50 #define SGRPROJ_EP_GRP1_END_IDX 9
51 #define SGRPROJ_EP_GRP1_SEARCH_COUNT 4
52 #define SGRPROJ_EP_GRP2_3_SEARCH_COUNT 2
53 static const int sgproj_ep_grp1_seed[SGRPROJ_EP_GRP1_SEARCH_COUNT] = { 0, 3, 6,
54                                                                        9 };
55 static const int sgproj_ep_grp2_3[SGRPROJ_EP_GRP2_3_SEARCH_COUNT][14] = {
56   { 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, -1, -1, -1, -1 },
57   { 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15 }
58 };
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   // The best coefficients for Wiener or Sgrproj restoration
109   WienerInfo wiener;
110   SgrprojInfo sgrproj;
111 
112   // The sum of squared errors for this rtype.
113   int64_t sse[RESTORE_SWITCHABLE_TYPES];
114 
115   // The rtype to use for this unit given a frame rtype as
116   // index. Indices: WIENER, SGRPROJ, SWITCHABLE.
117   RestorationType best_rtype[RESTORE_TYPES - 1];
118 
119   // This flag will be set based on the speed feature
120   // 'prune_sgr_based_on_wiener'. 0 implies no pruning and 1 implies pruning.
121   uint8_t skip_sgr_eval;
122 } RestUnitSearchInfo;
123 
124 typedef struct {
125   const YV12_BUFFER_CONFIG *src;
126   YV12_BUFFER_CONFIG *dst;
127 
128   const AV1_COMMON *cm;
129   const MACROBLOCK *x;
130   int plane;
131   int plane_width;
132   int plane_height;
133   RestUnitSearchInfo *rusi;
134 
135   // Speed features
136   const SPEED_FEATURES *sf;
137 
138   uint8_t *dgd_buffer;
139   int dgd_stride;
140   const uint8_t *src_buffer;
141   int src_stride;
142 
143   // sse and bits are initialised by reset_rsc in search_rest_type
144   int64_t sse;
145   int64_t bits;
146   int tile_y0, tile_stripe0;
147 
148   // sgrproj and wiener are initialised by rsc_on_tile when starting the first
149   // tile in the frame.
150   SgrprojInfo sgrproj;
151   WienerInfo wiener;
152   AV1PixelRect tile_rect;
153 } RestSearchCtxt;
154 
rsc_on_tile(void * priv)155 static AOM_INLINE void rsc_on_tile(void *priv) {
156   RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
157   set_default_sgrproj(&rsc->sgrproj);
158   set_default_wiener(&rsc->wiener);
159   rsc->tile_stripe0 = 0;
160 }
161 
reset_rsc(RestSearchCtxt * rsc)162 static AOM_INLINE void reset_rsc(RestSearchCtxt *rsc) {
163   rsc->sse = 0;
164   rsc->bits = 0;
165 }
166 
init_rsc(const YV12_BUFFER_CONFIG * src,const AV1_COMMON * cm,const MACROBLOCK * x,const SPEED_FEATURES * sf,int plane,RestUnitSearchInfo * rusi,YV12_BUFFER_CONFIG * dst,RestSearchCtxt * rsc)167 static AOM_INLINE void init_rsc(const YV12_BUFFER_CONFIG *src,
168                                 const AV1_COMMON *cm, const MACROBLOCK *x,
169                                 const SPEED_FEATURES *sf, int plane,
170                                 RestUnitSearchInfo *rusi,
171                                 YV12_BUFFER_CONFIG *dst, RestSearchCtxt *rsc) {
172   rsc->src = src;
173   rsc->dst = dst;
174   rsc->cm = cm;
175   rsc->x = x;
176   rsc->plane = plane;
177   rsc->rusi = rusi;
178   rsc->sf = sf;
179 
180   const YV12_BUFFER_CONFIG *dgd = &cm->cur_frame->buf;
181   const int is_uv = plane != AOM_PLANE_Y;
182   rsc->plane_width = src->crop_widths[is_uv];
183   rsc->plane_height = src->crop_heights[is_uv];
184   rsc->src_buffer = src->buffers[plane];
185   rsc->src_stride = src->strides[is_uv];
186   rsc->dgd_buffer = dgd->buffers[plane];
187   rsc->dgd_stride = dgd->strides[is_uv];
188   rsc->tile_rect = av1_whole_frame_rect(cm, is_uv);
189   assert(src->crop_widths[is_uv] == dgd->crop_widths[is_uv]);
190   assert(src->crop_heights[is_uv] == dgd->crop_heights[is_uv]);
191 }
192 
try_restoration_unit(const RestSearchCtxt * rsc,const RestorationTileLimits * limits,const AV1PixelRect * tile_rect,const RestorationUnitInfo * rui)193 static int64_t try_restoration_unit(const RestSearchCtxt *rsc,
194                                     const RestorationTileLimits *limits,
195                                     const AV1PixelRect *tile_rect,
196                                     const RestorationUnitInfo *rui) {
197   const AV1_COMMON *const cm = rsc->cm;
198   const int plane = rsc->plane;
199   const int is_uv = plane > 0;
200   const RestorationInfo *rsi = &cm->rst_info[plane];
201   RestorationLineBuffers rlbs;
202   const int bit_depth = cm->seq_params.bit_depth;
203   const int highbd = cm->seq_params.use_highbitdepth;
204 
205   const YV12_BUFFER_CONFIG *fts = &cm->cur_frame->buf;
206   // TODO(yunqing): For now, only use optimized LR filter in decoder. Can be
207   // also used in encoder.
208   const int optimized_lr = 0;
209 
210   av1_loop_restoration_filter_unit(
211       limits, rui, &rsi->boundaries, &rlbs, tile_rect, rsc->tile_stripe0,
212       is_uv && cm->seq_params.subsampling_x,
213       is_uv && cm->seq_params.subsampling_y, highbd, bit_depth,
214       fts->buffers[plane], fts->strides[is_uv], rsc->dst->buffers[plane],
215       rsc->dst->strides[is_uv], cm->rst_tmpbuf, optimized_lr);
216 
217   return sse_restoration_unit(limits, rsc->src, rsc->dst, plane, highbd);
218 }
219 
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)220 int64_t av1_lowbd_pixel_proj_error_c(const uint8_t *src8, int width, int height,
221                                      int src_stride, const uint8_t *dat8,
222                                      int dat_stride, int32_t *flt0,
223                                      int flt0_stride, int32_t *flt1,
224                                      int flt1_stride, int xq[2],
225                                      const sgr_params_type *params) {
226   int i, j;
227   const uint8_t *src = src8;
228   const uint8_t *dat = dat8;
229   int64_t err = 0;
230   if (params->r[0] > 0 && params->r[1] > 0) {
231     for (i = 0; i < height; ++i) {
232       for (j = 0; j < width; ++j) {
233         assert(flt1[j] < (1 << 15) && flt1[j] > -(1 << 15));
234         assert(flt0[j] < (1 << 15) && flt0[j] > -(1 << 15));
235         const int32_t u = (int32_t)(dat[j] << SGRPROJ_RST_BITS);
236         int32_t v = u << SGRPROJ_PRJ_BITS;
237         v += xq[0] * (flt0[j] - u) + xq[1] * (flt1[j] - u);
238         const int32_t e =
239             ROUND_POWER_OF_TWO(v, SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS) - src[j];
240         err += ((int64_t)e * e);
241       }
242       dat += dat_stride;
243       src += src_stride;
244       flt0 += flt0_stride;
245       flt1 += flt1_stride;
246     }
247   } else if (params->r[0] > 0) {
248     for (i = 0; i < height; ++i) {
249       for (j = 0; j < width; ++j) {
250         assert(flt0[j] < (1 << 15) && flt0[j] > -(1 << 15));
251         const int32_t u = (int32_t)(dat[j] << SGRPROJ_RST_BITS);
252         int32_t v = u << SGRPROJ_PRJ_BITS;
253         v += xq[0] * (flt0[j] - u);
254         const int32_t e =
255             ROUND_POWER_OF_TWO(v, SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS) - src[j];
256         err += ((int64_t)e * e);
257       }
258       dat += dat_stride;
259       src += src_stride;
260       flt0 += flt0_stride;
261     }
262   } else if (params->r[1] > 0) {
263     for (i = 0; i < height; ++i) {
264       for (j = 0; j < width; ++j) {
265         assert(flt1[j] < (1 << 15) && flt1[j] > -(1 << 15));
266         const int32_t u = (int32_t)(dat[j] << SGRPROJ_RST_BITS);
267         int32_t v = u << SGRPROJ_PRJ_BITS;
268         v += xq[1] * (flt1[j] - u);
269         const int32_t e =
270             ROUND_POWER_OF_TWO(v, SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS) - src[j];
271         err += ((int64_t)e * e);
272       }
273       dat += dat_stride;
274       src += src_stride;
275       flt1 += flt1_stride;
276     }
277   } else {
278     for (i = 0; i < height; ++i) {
279       for (j = 0; j < width; ++j) {
280         const int32_t e = (int32_t)(dat[j]) - src[j];
281         err += ((int64_t)e * e);
282       }
283       dat += dat_stride;
284       src += src_stride;
285     }
286   }
287 
288   return err;
289 }
290 
291 #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)292 int64_t av1_highbd_pixel_proj_error_c(const uint8_t *src8, int width,
293                                       int height, int src_stride,
294                                       const uint8_t *dat8, int dat_stride,
295                                       int32_t *flt0, int flt0_stride,
296                                       int32_t *flt1, int flt1_stride, int xq[2],
297                                       const sgr_params_type *params) {
298   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
299   const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
300   int i, j;
301   int64_t err = 0;
302   const int32_t half = 1 << (SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS - 1);
303   if (params->r[0] > 0 && params->r[1] > 0) {
304     int xq0 = xq[0];
305     int xq1 = xq[1];
306     for (i = 0; i < height; ++i) {
307       for (j = 0; j < width; ++j) {
308         const int32_t d = dat[j];
309         const int32_t s = src[j];
310         const int32_t u = (int32_t)(d << SGRPROJ_RST_BITS);
311         int32_t v0 = flt0[j] - u;
312         int32_t v1 = flt1[j] - u;
313         int32_t v = half;
314         v += xq0 * v0;
315         v += xq1 * v1;
316         const int32_t e = (v >> (SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS)) + d - s;
317         err += ((int64_t)e * e);
318       }
319       dat += dat_stride;
320       flt0 += flt0_stride;
321       flt1 += flt1_stride;
322       src += src_stride;
323     }
324   } else if (params->r[0] > 0 || params->r[1] > 0) {
325     int exq;
326     int32_t *flt;
327     int flt_stride;
328     if (params->r[0] > 0) {
329       exq = xq[0];
330       flt = flt0;
331       flt_stride = flt0_stride;
332     } else {
333       exq = xq[1];
334       flt = flt1;
335       flt_stride = flt1_stride;
336     }
337     for (i = 0; i < height; ++i) {
338       for (j = 0; j < width; ++j) {
339         const int32_t d = dat[j];
340         const int32_t s = src[j];
341         const int32_t u = (int32_t)(d << SGRPROJ_RST_BITS);
342         int32_t v = half;
343         v += exq * (flt[j] - u);
344         const int32_t e = (v >> (SGRPROJ_RST_BITS + SGRPROJ_PRJ_BITS)) + d - s;
345         err += ((int64_t)e * e);
346       }
347       dat += dat_stride;
348       flt += flt_stride;
349       src += src_stride;
350     }
351   } else {
352     for (i = 0; i < height; ++i) {
353       for (j = 0; j < width; ++j) {
354         const int32_t d = dat[j];
355         const int32_t s = src[j];
356         const int32_t e = d - s;
357         err += ((int64_t)e * e);
358       }
359       dat += dat_stride;
360       src += src_stride;
361     }
362   }
363   return err;
364 }
365 #endif  // CONFIG_AV1_HIGHBITDEPTH
366 
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)367 static int64_t get_pixel_proj_error(const uint8_t *src8, int width, int height,
368                                     int src_stride, const uint8_t *dat8,
369                                     int dat_stride, int use_highbitdepth,
370                                     int32_t *flt0, int flt0_stride,
371                                     int32_t *flt1, int flt1_stride, int *xqd,
372                                     const sgr_params_type *params) {
373   int xq[2];
374   av1_decode_xq(xqd, xq, params);
375 
376 #if CONFIG_AV1_HIGHBITDEPTH
377   if (use_highbitdepth) {
378     return av1_highbd_pixel_proj_error(src8, width, height, src_stride, dat8,
379                                        dat_stride, flt0, flt0_stride, flt1,
380                                        flt1_stride, xq, params);
381 
382   } else {
383     return av1_lowbd_pixel_proj_error(src8, width, height, src_stride, dat8,
384                                       dat_stride, flt0, flt0_stride, flt1,
385                                       flt1_stride, xq, params);
386   }
387 #else
388   (void)use_highbitdepth;
389   return av1_lowbd_pixel_proj_error(src8, width, height, src_stride, dat8,
390                                     dat_stride, flt0, flt0_stride, flt1,
391                                     flt1_stride, xq, params);
392 #endif
393 }
394 
395 #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)396 static int64_t finer_search_pixel_proj_error(
397     const uint8_t *src8, int width, int height, int src_stride,
398     const uint8_t *dat8, int dat_stride, int use_highbitdepth, int32_t *flt0,
399     int flt0_stride, int32_t *flt1, int flt1_stride, int start_step, int *xqd,
400     const sgr_params_type *params) {
401   int64_t err = get_pixel_proj_error(
402       src8, width, height, src_stride, dat8, dat_stride, use_highbitdepth, flt0,
403       flt0_stride, flt1, flt1_stride, xqd, params);
404   (void)start_step;
405 #if USE_SGRPROJ_REFINEMENT_SEARCH
406   int64_t err2;
407   int tap_min[] = { SGRPROJ_PRJ_MIN0, SGRPROJ_PRJ_MIN1 };
408   int tap_max[] = { SGRPROJ_PRJ_MAX0, SGRPROJ_PRJ_MAX1 };
409   for (int s = start_step; s >= 1; s >>= 1) {
410     for (int p = 0; p < 2; ++p) {
411       if ((params->r[0] == 0 && p == 0) || (params->r[1] == 0 && p == 1)) {
412         continue;
413       }
414       int skip = 0;
415       do {
416         if (xqd[p] - s >= tap_min[p]) {
417           xqd[p] -= s;
418           err2 =
419               get_pixel_proj_error(src8, width, height, src_stride, dat8,
420                                    dat_stride, use_highbitdepth, flt0,
421                                    flt0_stride, flt1, flt1_stride, xqd, params);
422           if (err2 > err) {
423             xqd[p] += s;
424           } else {
425             err = err2;
426             skip = 1;
427             // At the highest step size continue moving in the same direction
428             if (s == start_step) continue;
429           }
430         }
431         break;
432       } while (1);
433       if (skip) break;
434       do {
435         if (xqd[p] + s <= tap_max[p]) {
436           xqd[p] += s;
437           err2 =
438               get_pixel_proj_error(src8, width, height, src_stride, dat8,
439                                    dat_stride, use_highbitdepth, flt0,
440                                    flt0_stride, flt1, flt1_stride, xqd, params);
441           if (err2 > err) {
442             xqd[p] -= s;
443           } else {
444             err = err2;
445             // At the highest step size continue moving in the same direction
446             if (s == start_step) continue;
447           }
448         }
449         break;
450       } while (1);
451     }
452   }
453 #endif  // USE_SGRPROJ_REFINEMENT_SEARCH
454   return err;
455 }
456 
signed_rounded_divide(int64_t dividend,int64_t divisor)457 static int64_t signed_rounded_divide(int64_t dividend, int64_t divisor) {
458   if (dividend < 0)
459     return (dividend - divisor / 2) / divisor;
460   else
461     return (dividend + divisor / 2) / divisor;
462 }
463 
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])464 static AOM_INLINE void calc_proj_params_r0_r1_c(
465     const uint8_t *src8, int width, int height, int src_stride,
466     const uint8_t *dat8, int dat_stride, int32_t *flt0, int flt0_stride,
467     int32_t *flt1, int flt1_stride, int64_t H[2][2], int64_t C[2]) {
468   const int size = width * height;
469   const uint8_t *src = src8;
470   const uint8_t *dat = dat8;
471   for (int i = 0; i < height; ++i) {
472     for (int j = 0; j < width; ++j) {
473       const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
474       const int32_t s =
475           (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
476       const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
477       const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
478       H[0][0] += (int64_t)f1 * f1;
479       H[1][1] += (int64_t)f2 * f2;
480       H[0][1] += (int64_t)f1 * f2;
481       C[0] += (int64_t)f1 * s;
482       C[1] += (int64_t)f2 * s;
483     }
484   }
485   H[0][0] /= size;
486   H[0][1] /= size;
487   H[1][1] /= size;
488   H[1][0] = H[0][1];
489   C[0] /= size;
490   C[1] /= size;
491 }
492 
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])493 static AOM_INLINE void calc_proj_params_r0_r1_high_bd_c(
494     const uint8_t *src8, int width, int height, int src_stride,
495     const uint8_t *dat8, int dat_stride, int32_t *flt0, int flt0_stride,
496     int32_t *flt1, int flt1_stride, int64_t H[2][2], int64_t C[2]) {
497   const int size = width * height;
498   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
499   const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
500   for (int i = 0; i < height; ++i) {
501     for (int j = 0; j < width; ++j) {
502       const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
503       const int32_t s =
504           (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
505       const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
506       const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
507       H[0][0] += (int64_t)f1 * f1;
508       H[1][1] += (int64_t)f2 * f2;
509       H[0][1] += (int64_t)f1 * f2;
510       C[0] += (int64_t)f1 * s;
511       C[1] += (int64_t)f2 * s;
512     }
513   }
514   H[0][0] /= size;
515   H[0][1] /= size;
516   H[1][1] /= size;
517   H[1][0] = H[0][1];
518   C[0] /= size;
519   C[1] /= size;
520 }
521 
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])522 static AOM_INLINE void calc_proj_params_r0_c(const uint8_t *src8, int width,
523                                              int height, int src_stride,
524                                              const uint8_t *dat8,
525                                              int dat_stride, int32_t *flt0,
526                                              int flt0_stride, int64_t H[2][2],
527                                              int64_t C[2]) {
528   const int size = width * height;
529   const uint8_t *src = src8;
530   const uint8_t *dat = dat8;
531   for (int i = 0; i < height; ++i) {
532     for (int j = 0; j < width; ++j) {
533       const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
534       const int32_t s =
535           (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
536       const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
537       H[0][0] += (int64_t)f1 * f1;
538       C[0] += (int64_t)f1 * s;
539     }
540   }
541   H[0][0] /= size;
542   C[0] /= size;
543 }
544 
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])545 static AOM_INLINE void calc_proj_params_r0_high_bd_c(
546     const uint8_t *src8, int width, int height, int src_stride,
547     const uint8_t *dat8, int dat_stride, int32_t *flt0, int flt0_stride,
548     int64_t H[2][2], int64_t C[2]) {
549   const int size = width * height;
550   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
551   const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
552   for (int i = 0; i < height; ++i) {
553     for (int j = 0; j < width; ++j) {
554       const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
555       const int32_t s =
556           (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
557       const int32_t f1 = (int32_t)flt0[i * flt0_stride + j] - u;
558       H[0][0] += (int64_t)f1 * f1;
559       C[0] += (int64_t)f1 * s;
560     }
561   }
562   H[0][0] /= size;
563   C[0] /= size;
564 }
565 
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])566 static AOM_INLINE void calc_proj_params_r1_c(const uint8_t *src8, int width,
567                                              int height, int src_stride,
568                                              const uint8_t *dat8,
569                                              int dat_stride, int32_t *flt1,
570                                              int flt1_stride, int64_t H[2][2],
571                                              int64_t C[2]) {
572   const int size = width * height;
573   const uint8_t *src = src8;
574   const uint8_t *dat = dat8;
575   for (int i = 0; i < height; ++i) {
576     for (int j = 0; j < width; ++j) {
577       const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
578       const int32_t s =
579           (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
580       const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
581       H[1][1] += (int64_t)f2 * f2;
582       C[1] += (int64_t)f2 * s;
583     }
584   }
585   H[1][1] /= size;
586   C[1] /= size;
587 }
588 
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])589 static AOM_INLINE void calc_proj_params_r1_high_bd_c(
590     const uint8_t *src8, int width, int height, int src_stride,
591     const uint8_t *dat8, int dat_stride, int32_t *flt1, int flt1_stride,
592     int64_t H[2][2], int64_t C[2]) {
593   const int size = width * height;
594   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
595   const uint16_t *dat = CONVERT_TO_SHORTPTR(dat8);
596   for (int i = 0; i < height; ++i) {
597     for (int j = 0; j < width; ++j) {
598       const int32_t u = (int32_t)(dat[i * dat_stride + j] << SGRPROJ_RST_BITS);
599       const int32_t s =
600           (int32_t)(src[i * src_stride + j] << SGRPROJ_RST_BITS) - u;
601       const int32_t f2 = (int32_t)flt1[i * flt1_stride + j] - u;
602       H[1][1] += (int64_t)f2 * f2;
603       C[1] += (int64_t)f2 * s;
604     }
605   }
606   H[1][1] /= size;
607   C[1] /= size;
608 }
609 
610 // The function calls 3 subfunctions for the following cases :
611 // 1) When params->r[0] > 0 and params->r[1] > 0. In this case all elements
612 // of C and H need to be computed.
613 // 2) When only params->r[0] > 0. In this case only H[0][0] and C[0] are
614 // non-zero and need to be computed.
615 // 3) When only params->r[1] > 0. In this case only H[1][1] and C[1] are
616 // 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)617 void av1_calc_proj_params_c(const uint8_t *src8, int width, int height,
618                             int src_stride, const uint8_t *dat8, int dat_stride,
619                             int32_t *flt0, int flt0_stride, int32_t *flt1,
620                             int flt1_stride, int64_t H[2][2], int64_t C[2],
621                             const sgr_params_type *params) {
622   if ((params->r[0] > 0) && (params->r[1] > 0)) {
623     calc_proj_params_r0_r1_c(src8, width, height, src_stride, dat8, dat_stride,
624                              flt0, flt0_stride, flt1, flt1_stride, H, C);
625   } else if (params->r[0] > 0) {
626     calc_proj_params_r0_c(src8, width, height, src_stride, dat8, dat_stride,
627                           flt0, flt0_stride, H, C);
628   } else if (params->r[1] > 0) {
629     calc_proj_params_r1_c(src8, width, height, src_stride, dat8, dat_stride,
630                           flt1, flt1_stride, H, C);
631   }
632 }
633 
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)634 static AOM_INLINE void av1_calc_proj_params_high_bd_c(
635     const uint8_t *src8, int width, int height, int src_stride,
636     const uint8_t *dat8, int dat_stride, int32_t *flt0, int flt0_stride,
637     int32_t *flt1, int flt1_stride, int64_t H[2][2], int64_t C[2],
638     const sgr_params_type *params) {
639   if ((params->r[0] > 0) && (params->r[1] > 0)) {
640     calc_proj_params_r0_r1_high_bd_c(src8, width, height, src_stride, dat8,
641                                      dat_stride, flt0, flt0_stride, flt1,
642                                      flt1_stride, H, C);
643   } else if (params->r[0] > 0) {
644     calc_proj_params_r0_high_bd_c(src8, width, height, src_stride, dat8,
645                                   dat_stride, flt0, flt0_stride, H, C);
646   } else if (params->r[1] > 0) {
647     calc_proj_params_r1_high_bd_c(src8, width, height, src_stride, dat8,
648                                   dat_stride, flt1, flt1_stride, H, C);
649   }
650 }
651 
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)652 static AOM_INLINE void get_proj_subspace(const uint8_t *src8, int width,
653                                          int height, int src_stride,
654                                          const uint8_t *dat8, int dat_stride,
655                                          int use_highbitdepth, int32_t *flt0,
656                                          int flt0_stride, int32_t *flt1,
657                                          int flt1_stride, int *xq,
658                                          const sgr_params_type *params) {
659   int64_t H[2][2] = { { 0, 0 }, { 0, 0 } };
660   int64_t C[2] = { 0, 0 };
661 
662   // Default values to be returned if the problem becomes ill-posed
663   xq[0] = 0;
664   xq[1] = 0;
665 
666   if (!use_highbitdepth) {
667     if ((width & 0x7) == 0) {
668       av1_calc_proj_params(src8, width, height, src_stride, dat8, dat_stride,
669                            flt0, flt0_stride, flt1, flt1_stride, H, C, params);
670     } else {
671       av1_calc_proj_params_c(src8, width, height, src_stride, dat8, dat_stride,
672                              flt0, flt0_stride, flt1, flt1_stride, H, C,
673                              params);
674     }
675   } else {
676     av1_calc_proj_params_high_bd_c(src8, width, height, src_stride, dat8,
677                                    dat_stride, flt0, flt0_stride, flt1,
678                                    flt1_stride, H, C, params);
679   }
680 
681   if (params->r[0] == 0) {
682     // H matrix is now only the scalar H[1][1]
683     // C vector is now only the scalar C[1]
684     const int64_t Det = H[1][1];
685     if (Det == 0) return;  // ill-posed, return default values
686     xq[0] = 0;
687     xq[1] = (int)signed_rounded_divide(C[1] * (1 << SGRPROJ_PRJ_BITS), Det);
688   } else if (params->r[1] == 0) {
689     // H matrix is now only the scalar H[0][0]
690     // C vector is now only the scalar C[0]
691     const int64_t Det = H[0][0];
692     if (Det == 0) return;  // ill-posed, return default values
693     xq[0] = (int)signed_rounded_divide(C[0] * (1 << SGRPROJ_PRJ_BITS), Det);
694     xq[1] = 0;
695   } else {
696     const int64_t Det = H[0][0] * H[1][1] - H[0][1] * H[1][0];
697     if (Det == 0) return;  // ill-posed, return default values
698 
699     // If scaling up dividend would overflow, instead scale down the divisor
700     const int64_t div1 = H[1][1] * C[0] - H[0][1] * C[1];
701     if ((div1 > 0 && INT64_MAX / (1 << SGRPROJ_PRJ_BITS) < div1) ||
702         (div1 < 0 && INT64_MIN / (1 << SGRPROJ_PRJ_BITS) > div1))
703       xq[0] = (int)signed_rounded_divide(div1, Det / (1 << SGRPROJ_PRJ_BITS));
704     else
705       xq[0] = (int)signed_rounded_divide(div1 * (1 << SGRPROJ_PRJ_BITS), Det);
706 
707     const int64_t div2 = H[0][0] * C[1] - H[1][0] * C[0];
708     if ((div2 > 0 && INT64_MAX / (1 << SGRPROJ_PRJ_BITS) < div2) ||
709         (div2 < 0 && INT64_MIN / (1 << SGRPROJ_PRJ_BITS) > div2))
710       xq[1] = (int)signed_rounded_divide(div2, Det / (1 << SGRPROJ_PRJ_BITS));
711     else
712       xq[1] = (int)signed_rounded_divide(div2 * (1 << SGRPROJ_PRJ_BITS), Det);
713   }
714 }
715 
encode_xq(int * xq,int * xqd,const sgr_params_type * params)716 static AOM_INLINE void encode_xq(int *xq, int *xqd,
717                                  const sgr_params_type *params) {
718   if (params->r[0] == 0) {
719     xqd[0] = 0;
720     xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - xq[1], SGRPROJ_PRJ_MIN1,
721                    SGRPROJ_PRJ_MAX1);
722   } else if (params->r[1] == 0) {
723     xqd[0] = clamp(xq[0], SGRPROJ_PRJ_MIN0, SGRPROJ_PRJ_MAX0);
724     xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - xqd[0], SGRPROJ_PRJ_MIN1,
725                    SGRPROJ_PRJ_MAX1);
726   } else {
727     xqd[0] = clamp(xq[0], SGRPROJ_PRJ_MIN0, SGRPROJ_PRJ_MAX0);
728     xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - xqd[0] - xq[1], SGRPROJ_PRJ_MIN1,
729                    SGRPROJ_PRJ_MAX1);
730   }
731 }
732 
733 // 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)734 static AOM_INLINE void apply_sgr(int sgr_params_idx, const uint8_t *dat8,
735                                  int width, int height, int dat_stride,
736                                  int use_highbd, int bit_depth, int pu_width,
737                                  int pu_height, int32_t *flt0, int32_t *flt1,
738                                  int flt_stride) {
739   for (int i = 0; i < height; i += pu_height) {
740     const int h = AOMMIN(pu_height, height - i);
741     int32_t *flt0_row = flt0 + i * flt_stride;
742     int32_t *flt1_row = flt1 + i * flt_stride;
743     const uint8_t *dat8_row = dat8 + i * dat_stride;
744 
745     // Iterate over the stripe in blocks of width pu_width
746     for (int j = 0; j < width; j += pu_width) {
747       const int w = AOMMIN(pu_width, width - j);
748       const int ret = av1_selfguided_restoration(
749           dat8_row + j, w, h, dat_stride, flt0_row + j, flt1_row + j,
750           flt_stride, sgr_params_idx, bit_depth, use_highbd);
751       (void)ret;
752       assert(!ret);
753     }
754   }
755 }
756 
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)757 static AOM_INLINE void compute_sgrproj_err(
758     const uint8_t *dat8, const int width, const int height,
759     const int dat_stride, const uint8_t *src8, const int src_stride,
760     const int use_highbitdepth, const int bit_depth, const int pu_width,
761     const int pu_height, const int ep, int32_t *flt0, int32_t *flt1,
762     const int flt_stride, int *exqd, int64_t *err) {
763   int exq[2];
764   apply_sgr(ep, dat8, width, height, dat_stride, use_highbitdepth, bit_depth,
765             pu_width, pu_height, flt0, flt1, flt_stride);
766   aom_clear_system_state();
767   const sgr_params_type *const params = &av1_sgr_params[ep];
768   get_proj_subspace(src8, width, height, src_stride, dat8, dat_stride,
769                     use_highbitdepth, flt0, flt_stride, flt1, flt_stride, exq,
770                     params);
771   aom_clear_system_state();
772   encode_xq(exq, exqd, params);
773   *err = finer_search_pixel_proj_error(
774       src8, width, height, src_stride, dat8, dat_stride, use_highbitdepth, flt0,
775       flt_stride, flt1, flt_stride, 2, exqd, params);
776 }
777 
get_best_error(int64_t * besterr,const int64_t err,const int * exqd,int * bestxqd,int * bestep,const int ep)778 static AOM_INLINE void get_best_error(int64_t *besterr, const int64_t err,
779                                       const int *exqd, int *bestxqd,
780                                       int *bestep, const int ep) {
781   if (*besterr == -1 || err < *besterr) {
782     *bestep = ep;
783     *besterr = err;
784     bestxqd[0] = exqd[0];
785     bestxqd[1] = exqd[1];
786   }
787 }
788 
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)789 static SgrprojInfo search_selfguided_restoration(
790     const uint8_t *dat8, int width, int height, int dat_stride,
791     const uint8_t *src8, int src_stride, int use_highbitdepth, int bit_depth,
792     int pu_width, int pu_height, int32_t *rstbuf, int enable_sgr_ep_pruning) {
793   int32_t *flt0 = rstbuf;
794   int32_t *flt1 = flt0 + RESTORATION_UNITPELS_MAX;
795   int ep, idx, bestep = 0;
796   int64_t besterr = -1;
797   int exqd[2], bestxqd[2] = { 0, 0 };
798   int flt_stride = ((width + 7) & ~7) + 8;
799   assert(pu_width == (RESTORATION_PROC_UNIT_SIZE >> 1) ||
800          pu_width == RESTORATION_PROC_UNIT_SIZE);
801   assert(pu_height == (RESTORATION_PROC_UNIT_SIZE >> 1) ||
802          pu_height == RESTORATION_PROC_UNIT_SIZE);
803   if (!enable_sgr_ep_pruning) {
804     for (ep = 0; ep < SGRPROJ_PARAMS; ep++) {
805       int64_t err;
806       compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
807                           use_highbitdepth, bit_depth, pu_width, pu_height, ep,
808                           flt0, flt1, flt_stride, exqd, &err);
809       get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
810     }
811   } else {
812     // evaluate first four seed ep in first group
813     for (idx = 0; idx < SGRPROJ_EP_GRP1_SEARCH_COUNT; idx++) {
814       ep = sgproj_ep_grp1_seed[idx];
815       int64_t err;
816       compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
817                           use_highbitdepth, bit_depth, pu_width, pu_height, ep,
818                           flt0, flt1, flt_stride, exqd, &err);
819       get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
820     }
821     // evaluate left and right ep of winner in seed ep
822     int bestep_ref = bestep;
823     for (ep = bestep_ref - 1; ep < bestep_ref + 2; ep += 2) {
824       if (ep < SGRPROJ_EP_GRP1_START_IDX || ep > SGRPROJ_EP_GRP1_END_IDX)
825         continue;
826       int64_t err;
827       compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
828                           use_highbitdepth, bit_depth, pu_width, pu_height, ep,
829                           flt0, flt1, flt_stride, exqd, &err);
830       get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
831     }
832     // evaluate last two group
833     for (idx = 0; idx < SGRPROJ_EP_GRP2_3_SEARCH_COUNT; idx++) {
834       ep = sgproj_ep_grp2_3[idx][bestep];
835       int64_t err;
836       compute_sgrproj_err(dat8, width, height, dat_stride, src8, src_stride,
837                           use_highbitdepth, bit_depth, pu_width, pu_height, ep,
838                           flt0, flt1, flt_stride, exqd, &err);
839       get_best_error(&besterr, err, exqd, bestxqd, &bestep, ep);
840     }
841   }
842 
843   SgrprojInfo ret;
844   ret.ep = bestep;
845   ret.xqd[0] = bestxqd[0];
846   ret.xqd[1] = bestxqd[1];
847   return ret;
848 }
849 
count_sgrproj_bits(SgrprojInfo * sgrproj_info,SgrprojInfo * ref_sgrproj_info)850 static int count_sgrproj_bits(SgrprojInfo *sgrproj_info,
851                               SgrprojInfo *ref_sgrproj_info) {
852   int bits = SGRPROJ_PARAMS_BITS;
853   const sgr_params_type *params = &av1_sgr_params[sgrproj_info->ep];
854   if (params->r[0] > 0)
855     bits += aom_count_primitive_refsubexpfin(
856         SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1, SGRPROJ_PRJ_SUBEXP_K,
857         ref_sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0,
858         sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0);
859   if (params->r[1] > 0)
860     bits += aom_count_primitive_refsubexpfin(
861         SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1, SGRPROJ_PRJ_SUBEXP_K,
862         ref_sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1,
863         sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1);
864   return bits;
865 }
866 
search_sgrproj(const RestorationTileLimits * limits,const AV1PixelRect * tile,int rest_unit_idx,void * priv,int32_t * tmpbuf,RestorationLineBuffers * rlbs)867 static AOM_INLINE void search_sgrproj(const RestorationTileLimits *limits,
868                                       const AV1PixelRect *tile,
869                                       int rest_unit_idx, void *priv,
870                                       int32_t *tmpbuf,
871                                       RestorationLineBuffers *rlbs) {
872   (void)rlbs;
873   RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
874   RestUnitSearchInfo *rusi = &rsc->rusi[rest_unit_idx];
875 
876   const MACROBLOCK *const x = rsc->x;
877   const AV1_COMMON *const cm = rsc->cm;
878   const int highbd = cm->seq_params.use_highbitdepth;
879   const int bit_depth = cm->seq_params.bit_depth;
880 
881   const int64_t bits_none = x->sgrproj_restore_cost[0];
882   // Prune evaluation of RESTORE_SGRPROJ if 'skip_sgr_eval' is set
883   if (rusi->skip_sgr_eval) {
884     rsc->bits += bits_none;
885     rsc->sse += rusi->sse[RESTORE_NONE];
886     rusi->best_rtype[RESTORE_SGRPROJ - 1] = RESTORE_NONE;
887     rusi->sse[RESTORE_SGRPROJ] = INT64_MAX;
888     return;
889   }
890 
891   uint8_t *dgd_start =
892       rsc->dgd_buffer + limits->v_start * rsc->dgd_stride + limits->h_start;
893   const uint8_t *src_start =
894       rsc->src_buffer + limits->v_start * rsc->src_stride + limits->h_start;
895 
896   const int is_uv = rsc->plane > 0;
897   const int ss_x = is_uv && cm->seq_params.subsampling_x;
898   const int ss_y = is_uv && cm->seq_params.subsampling_y;
899   const int procunit_width = RESTORATION_PROC_UNIT_SIZE >> ss_x;
900   const int procunit_height = RESTORATION_PROC_UNIT_SIZE >> ss_y;
901 
902   rusi->sgrproj = search_selfguided_restoration(
903       dgd_start, limits->h_end - limits->h_start,
904       limits->v_end - limits->v_start, rsc->dgd_stride, src_start,
905       rsc->src_stride, highbd, bit_depth, procunit_width, procunit_height,
906       tmpbuf, rsc->sf->lpf_sf.enable_sgr_ep_pruning);
907 
908   RestorationUnitInfo rui;
909   rui.restoration_type = RESTORE_SGRPROJ;
910   rui.sgrproj_info = rusi->sgrproj;
911 
912   rusi->sse[RESTORE_SGRPROJ] = try_restoration_unit(rsc, limits, tile, &rui);
913 
914   const int64_t bits_sgr = x->sgrproj_restore_cost[1] +
915                            (count_sgrproj_bits(&rusi->sgrproj, &rsc->sgrproj)
916                             << AV1_PROB_COST_SHIFT);
917 
918   double cost_none =
919       RDCOST_DBL(x->rdmult, bits_none >> 4, rusi->sse[RESTORE_NONE]);
920   double cost_sgr =
921       RDCOST_DBL(x->rdmult, bits_sgr >> 4, rusi->sse[RESTORE_SGRPROJ]);
922   if (rusi->sgrproj.ep < 10)
923     cost_sgr *=
924         (1 + DUAL_SGR_PENALTY_MULT * rsc->sf->lpf_sf.dual_sgr_penalty_level);
925 
926   RestorationType rtype =
927       (cost_sgr < cost_none) ? RESTORE_SGRPROJ : RESTORE_NONE;
928   rusi->best_rtype[RESTORE_SGRPROJ - 1] = rtype;
929 
930   rsc->sse += rusi->sse[rtype];
931   rsc->bits += (cost_sgr < cost_none) ? bits_sgr : bits_none;
932   if (cost_sgr < cost_none) rsc->sgrproj = rusi->sgrproj;
933 }
934 
av1_compute_stats_c(int wiener_win,const uint8_t * dgd,const uint8_t * src,int h_start,int h_end,int v_start,int v_end,int dgd_stride,int src_stride,int64_t * M,int64_t * H)935 void av1_compute_stats_c(int wiener_win, const uint8_t *dgd, const uint8_t *src,
936                          int h_start, int h_end, int v_start, int v_end,
937                          int dgd_stride, int src_stride, int64_t *M,
938                          int64_t *H) {
939   int i, j, k, l;
940   int16_t Y[WIENER_WIN2];
941   const int wiener_win2 = wiener_win * wiener_win;
942   const int wiener_halfwin = (wiener_win >> 1);
943   uint8_t avg = find_average(dgd, h_start, h_end, v_start, v_end, dgd_stride);
944 
945   memset(M, 0, sizeof(*M) * wiener_win2);
946   memset(H, 0, sizeof(*H) * wiener_win2 * wiener_win2);
947   for (i = v_start; i < v_end; i++) {
948     for (j = h_start; j < h_end; j++) {
949       const int16_t X = (int16_t)src[i * src_stride + j] - (int16_t)avg;
950       int idx = 0;
951       for (k = -wiener_halfwin; k <= wiener_halfwin; k++) {
952         for (l = -wiener_halfwin; l <= wiener_halfwin; l++) {
953           Y[idx] = (int16_t)dgd[(i + l) * dgd_stride + (j + k)] - (int16_t)avg;
954           idx++;
955         }
956       }
957       assert(idx == wiener_win2);
958       for (k = 0; k < wiener_win2; ++k) {
959         M[k] += (int32_t)Y[k] * X;
960         for (l = k; l < wiener_win2; ++l) {
961           // H is a symmetric matrix, so we only need to fill out the upper
962           // triangle here. We can copy it down to the lower triangle outside
963           // the (i, j) loops.
964           H[k * wiener_win2 + l] += (int32_t)Y[k] * Y[l];
965         }
966       }
967     }
968   }
969   for (k = 0; k < wiener_win2; ++k) {
970     for (l = k + 1; l < wiener_win2; ++l) {
971       H[l * wiener_win2 + k] = H[k * wiener_win2 + l];
972     }
973   }
974 }
975 
976 #if CONFIG_AV1_HIGHBITDEPTH
av1_compute_stats_highbd_c(int wiener_win,const uint8_t * dgd8,const uint8_t * src8,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)977 void av1_compute_stats_highbd_c(int wiener_win, const uint8_t *dgd8,
978                                 const uint8_t *src8, int h_start, int h_end,
979                                 int v_start, int v_end, int dgd_stride,
980                                 int src_stride, int64_t *M, int64_t *H,
981                                 aom_bit_depth_t bit_depth) {
982   int i, j, k, l;
983   int32_t Y[WIENER_WIN2];
984   const int wiener_win2 = wiener_win * wiener_win;
985   const int wiener_halfwin = (wiener_win >> 1);
986   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
987   const uint16_t *dgd = CONVERT_TO_SHORTPTR(dgd8);
988   uint16_t avg =
989       find_average_highbd(dgd, h_start, h_end, v_start, v_end, dgd_stride);
990 
991   uint8_t bit_depth_divider = 1;
992   if (bit_depth == AOM_BITS_12)
993     bit_depth_divider = 16;
994   else if (bit_depth == AOM_BITS_10)
995     bit_depth_divider = 4;
996 
997   memset(M, 0, sizeof(*M) * wiener_win2);
998   memset(H, 0, sizeof(*H) * wiener_win2 * wiener_win2);
999   for (i = v_start; i < v_end; i++) {
1000     for (j = h_start; j < h_end; j++) {
1001       const int32_t X = (int32_t)src[i * src_stride + j] - (int32_t)avg;
1002       int idx = 0;
1003       for (k = -wiener_halfwin; k <= wiener_halfwin; k++) {
1004         for (l = -wiener_halfwin; l <= wiener_halfwin; l++) {
1005           Y[idx] = (int32_t)dgd[(i + l) * dgd_stride + (j + k)] - (int32_t)avg;
1006           idx++;
1007         }
1008       }
1009       assert(idx == wiener_win2);
1010       for (k = 0; k < wiener_win2; ++k) {
1011         M[k] += (int64_t)Y[k] * X;
1012         for (l = k; l < wiener_win2; ++l) {
1013           // H is a symmetric matrix, so we only need to fill out the upper
1014           // triangle here. We can copy it down to the lower triangle outside
1015           // the (i, j) loops.
1016           H[k * wiener_win2 + l] += (int64_t)Y[k] * Y[l];
1017         }
1018       }
1019     }
1020   }
1021   for (k = 0; k < wiener_win2; ++k) {
1022     M[k] /= bit_depth_divider;
1023     H[k * wiener_win2 + k] /= bit_depth_divider;
1024     for (l = k + 1; l < wiener_win2; ++l) {
1025       H[k * wiener_win2 + l] /= bit_depth_divider;
1026       H[l * wiener_win2 + k] = H[k * wiener_win2 + l];
1027     }
1028   }
1029 }
1030 #endif  // CONFIG_AV1_HIGHBITDEPTH
1031 
wrap_index(int i,int wiener_win)1032 static INLINE int wrap_index(int i, int wiener_win) {
1033   const int wiener_halfwin1 = (wiener_win >> 1) + 1;
1034   return (i >= wiener_halfwin1 ? wiener_win - 1 - i : i);
1035 }
1036 
1037 // Solve linear equations to find Wiener filter tap values
1038 // Taps are output scaled by WIENER_FILT_STEP
linsolve_wiener(int n,int64_t * A,int stride,int64_t * b,int32_t * x)1039 static int linsolve_wiener(int n, int64_t *A, int stride, int64_t *b,
1040                            int32_t *x) {
1041   for (int k = 0; k < n - 1; k++) {
1042     // Partial pivoting: bring the row with the largest pivot to the top
1043     for (int i = n - 1; i > k; i--) {
1044       // If row i has a better (bigger) pivot than row (i-1), swap them
1045       if (llabs(A[(i - 1) * stride + k]) < llabs(A[i * stride + k])) {
1046         for (int j = 0; j < n; j++) {
1047           const int64_t c = A[i * stride + j];
1048           A[i * stride + j] = A[(i - 1) * stride + j];
1049           A[(i - 1) * stride + j] = c;
1050         }
1051         const int64_t c = b[i];
1052         b[i] = b[i - 1];
1053         b[i - 1] = c;
1054       }
1055     }
1056     // Forward elimination (convert A to row-echelon form)
1057     for (int i = k; i < n - 1; i++) {
1058       if (A[k * stride + k] == 0) return 0;
1059       const int64_t c = A[(i + 1) * stride + k];
1060       const int64_t cd = A[k * stride + k];
1061       for (int j = 0; j < n; j++) {
1062         A[(i + 1) * stride + j] -= c / 256 * A[k * stride + j] / cd * 256;
1063       }
1064       b[i + 1] -= c * b[k] / cd;
1065     }
1066   }
1067   // Back-substitution
1068   for (int i = n - 1; i >= 0; i--) {
1069     if (A[i * stride + i] == 0) return 0;
1070     int64_t c = 0;
1071     for (int j = i + 1; j <= n - 1; j++) {
1072       c += A[i * stride + j] * x[j] / WIENER_TAP_SCALE_FACTOR;
1073     }
1074     // Store filter taps x in scaled form.
1075     x[i] = (int32_t)(WIENER_TAP_SCALE_FACTOR * (b[i] - c) / A[i * stride + i]);
1076   }
1077 
1078   return 1;
1079 }
1080 
1081 // Fix vector b, update vector a
update_a_sep_sym(int wiener_win,int64_t ** Mc,int64_t ** Hc,int32_t * a,int32_t * b)1082 static AOM_INLINE void update_a_sep_sym(int wiener_win, int64_t **Mc,
1083                                         int64_t **Hc, int32_t *a, int32_t *b) {
1084   int i, j;
1085   int32_t S[WIENER_WIN];
1086   int64_t A[WIENER_HALFWIN1], B[WIENER_HALFWIN1 * WIENER_HALFWIN1];
1087   const int wiener_win2 = wiener_win * wiener_win;
1088   const int wiener_halfwin1 = (wiener_win >> 1) + 1;
1089   memset(A, 0, sizeof(A));
1090   memset(B, 0, sizeof(B));
1091   for (i = 0; i < wiener_win; i++) {
1092     for (j = 0; j < wiener_win; ++j) {
1093       const int jj = wrap_index(j, wiener_win);
1094       A[jj] += Mc[i][j] * b[i] / WIENER_TAP_SCALE_FACTOR;
1095     }
1096   }
1097   for (i = 0; i < wiener_win; i++) {
1098     for (j = 0; j < wiener_win; j++) {
1099       int k, l;
1100       for (k = 0; k < wiener_win; ++k) {
1101         for (l = 0; l < wiener_win; ++l) {
1102           const int kk = wrap_index(k, wiener_win);
1103           const int ll = wrap_index(l, wiener_win);
1104           B[ll * wiener_halfwin1 + kk] +=
1105               Hc[j * wiener_win + i][k * wiener_win2 + l] * b[i] /
1106               WIENER_TAP_SCALE_FACTOR * b[j] / WIENER_TAP_SCALE_FACTOR;
1107         }
1108       }
1109     }
1110   }
1111   // Normalization enforcement in the system of equations itself
1112   for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1113     A[i] -=
1114         A[wiener_halfwin1 - 1] * 2 +
1115         B[i * wiener_halfwin1 + wiener_halfwin1 - 1] -
1116         2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 + (wiener_halfwin1 - 1)];
1117   }
1118   for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1119     for (j = 0; j < wiener_halfwin1 - 1; ++j) {
1120       B[i * wiener_halfwin1 + j] -=
1121           2 * (B[i * wiener_halfwin1 + (wiener_halfwin1 - 1)] +
1122                B[(wiener_halfwin1 - 1) * wiener_halfwin1 + j] -
1123                2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 +
1124                      (wiener_halfwin1 - 1)]);
1125     }
1126   }
1127   if (linsolve_wiener(wiener_halfwin1 - 1, B, wiener_halfwin1, A, S)) {
1128     S[wiener_halfwin1 - 1] = WIENER_TAP_SCALE_FACTOR;
1129     for (i = wiener_halfwin1; i < wiener_win; ++i) {
1130       S[i] = S[wiener_win - 1 - i];
1131       S[wiener_halfwin1 - 1] -= 2 * S[i];
1132     }
1133     memcpy(a, S, wiener_win * sizeof(*a));
1134   }
1135 }
1136 
1137 // Fix vector a, update vector b
update_b_sep_sym(int wiener_win,int64_t ** Mc,int64_t ** Hc,int32_t * a,int32_t * b)1138 static AOM_INLINE void update_b_sep_sym(int wiener_win, int64_t **Mc,
1139                                         int64_t **Hc, int32_t *a, int32_t *b) {
1140   int i, j;
1141   int32_t S[WIENER_WIN];
1142   int64_t A[WIENER_HALFWIN1], B[WIENER_HALFWIN1 * WIENER_HALFWIN1];
1143   const int wiener_win2 = wiener_win * wiener_win;
1144   const int wiener_halfwin1 = (wiener_win >> 1) + 1;
1145   memset(A, 0, sizeof(A));
1146   memset(B, 0, sizeof(B));
1147   for (i = 0; i < wiener_win; i++) {
1148     const int ii = wrap_index(i, wiener_win);
1149     for (j = 0; j < wiener_win; j++) {
1150       A[ii] += Mc[i][j] * a[j] / WIENER_TAP_SCALE_FACTOR;
1151     }
1152   }
1153 
1154   for (i = 0; i < wiener_win; i++) {
1155     for (j = 0; j < wiener_win; j++) {
1156       const int ii = wrap_index(i, wiener_win);
1157       const int jj = wrap_index(j, wiener_win);
1158       int k, l;
1159       for (k = 0; k < wiener_win; ++k) {
1160         for (l = 0; l < wiener_win; ++l) {
1161           B[jj * wiener_halfwin1 + ii] +=
1162               Hc[i * wiener_win + j][k * wiener_win2 + l] * a[k] /
1163               WIENER_TAP_SCALE_FACTOR * a[l] / WIENER_TAP_SCALE_FACTOR;
1164         }
1165       }
1166     }
1167   }
1168   // Normalization enforcement in the system of equations itself
1169   for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1170     A[i] -=
1171         A[wiener_halfwin1 - 1] * 2 +
1172         B[i * wiener_halfwin1 + wiener_halfwin1 - 1] -
1173         2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 + (wiener_halfwin1 - 1)];
1174   }
1175   for (i = 0; i < wiener_halfwin1 - 1; ++i) {
1176     for (j = 0; j < wiener_halfwin1 - 1; ++j) {
1177       B[i * wiener_halfwin1 + j] -=
1178           2 * (B[i * wiener_halfwin1 + (wiener_halfwin1 - 1)] +
1179                B[(wiener_halfwin1 - 1) * wiener_halfwin1 + j] -
1180                2 * B[(wiener_halfwin1 - 1) * wiener_halfwin1 +
1181                      (wiener_halfwin1 - 1)]);
1182     }
1183   }
1184   if (linsolve_wiener(wiener_halfwin1 - 1, B, wiener_halfwin1, A, S)) {
1185     S[wiener_halfwin1 - 1] = WIENER_TAP_SCALE_FACTOR;
1186     for (i = wiener_halfwin1; i < wiener_win; ++i) {
1187       S[i] = S[wiener_win - 1 - i];
1188       S[wiener_halfwin1 - 1] -= 2 * S[i];
1189     }
1190     memcpy(b, S, wiener_win * sizeof(*b));
1191   }
1192 }
1193 
wiener_decompose_sep_sym(int wiener_win,int64_t * M,int64_t * H,int32_t * a,int32_t * b)1194 static int wiener_decompose_sep_sym(int wiener_win, int64_t *M, int64_t *H,
1195                                     int32_t *a, int32_t *b) {
1196   static const int32_t init_filt[WIENER_WIN] = {
1197     WIENER_FILT_TAP0_MIDV, WIENER_FILT_TAP1_MIDV, WIENER_FILT_TAP2_MIDV,
1198     WIENER_FILT_TAP3_MIDV, WIENER_FILT_TAP2_MIDV, WIENER_FILT_TAP1_MIDV,
1199     WIENER_FILT_TAP0_MIDV,
1200   };
1201   int64_t *Hc[WIENER_WIN2];
1202   int64_t *Mc[WIENER_WIN];
1203   int i, j, iter;
1204   const int plane_off = (WIENER_WIN - wiener_win) >> 1;
1205   const int wiener_win2 = wiener_win * wiener_win;
1206   for (i = 0; i < wiener_win; i++) {
1207     a[i] = b[i] =
1208         WIENER_TAP_SCALE_FACTOR / WIENER_FILT_STEP * init_filt[i + plane_off];
1209   }
1210   for (i = 0; i < wiener_win; i++) {
1211     Mc[i] = M + i * wiener_win;
1212     for (j = 0; j < wiener_win; j++) {
1213       Hc[i * wiener_win + j] =
1214           H + i * wiener_win * wiener_win2 + j * wiener_win;
1215     }
1216   }
1217 
1218   iter = 1;
1219   while (iter < NUM_WIENER_ITERS) {
1220     update_a_sep_sym(wiener_win, Mc, Hc, a, b);
1221     update_b_sep_sym(wiener_win, Mc, Hc, a, b);
1222     iter++;
1223   }
1224   return 1;
1225 }
1226 
1227 // Computes the function x'*H*x - x'*M for the learned 2D filter x, and compares
1228 // against identity filters; Final score is defined as the difference between
1229 // the function values
compute_score(int wiener_win,int64_t * M,int64_t * H,InterpKernel vfilt,InterpKernel hfilt)1230 static int64_t compute_score(int wiener_win, int64_t *M, int64_t *H,
1231                              InterpKernel vfilt, InterpKernel hfilt) {
1232   int32_t ab[WIENER_WIN * WIENER_WIN];
1233   int16_t a[WIENER_WIN], b[WIENER_WIN];
1234   int64_t P = 0, Q = 0;
1235   int64_t iP = 0, iQ = 0;
1236   int64_t Score, iScore;
1237   int i, k, l;
1238   const int plane_off = (WIENER_WIN - wiener_win) >> 1;
1239   const int wiener_win2 = wiener_win * wiener_win;
1240 
1241   aom_clear_system_state();
1242 
1243   a[WIENER_HALFWIN] = b[WIENER_HALFWIN] = WIENER_FILT_STEP;
1244   for (i = 0; i < WIENER_HALFWIN; ++i) {
1245     a[i] = a[WIENER_WIN - i - 1] = vfilt[i];
1246     b[i] = b[WIENER_WIN - i - 1] = hfilt[i];
1247     a[WIENER_HALFWIN] -= 2 * a[i];
1248     b[WIENER_HALFWIN] -= 2 * b[i];
1249   }
1250   memset(ab, 0, sizeof(ab));
1251   for (k = 0; k < wiener_win; ++k) {
1252     for (l = 0; l < wiener_win; ++l)
1253       ab[k * wiener_win + l] = a[l + plane_off] * b[k + plane_off];
1254   }
1255   for (k = 0; k < wiener_win2; ++k) {
1256     P += ab[k] * M[k] / WIENER_FILT_STEP / WIENER_FILT_STEP;
1257     for (l = 0; l < wiener_win2; ++l) {
1258       Q += ab[k] * H[k * wiener_win2 + l] * ab[l] / WIENER_FILT_STEP /
1259            WIENER_FILT_STEP / WIENER_FILT_STEP / WIENER_FILT_STEP;
1260     }
1261   }
1262   Score = Q - 2 * P;
1263 
1264   iP = M[wiener_win2 >> 1];
1265   iQ = H[(wiener_win2 >> 1) * wiener_win2 + (wiener_win2 >> 1)];
1266   iScore = iQ - 2 * iP;
1267 
1268   return Score - iScore;
1269 }
1270 
finalize_sym_filter(int wiener_win,int32_t * f,InterpKernel fi)1271 static AOM_INLINE void finalize_sym_filter(int wiener_win, int32_t *f,
1272                                            InterpKernel fi) {
1273   int i;
1274   const int wiener_halfwin = (wiener_win >> 1);
1275 
1276   for (i = 0; i < wiener_halfwin; ++i) {
1277     const int64_t dividend = f[i] * WIENER_FILT_STEP;
1278     const int64_t divisor = WIENER_TAP_SCALE_FACTOR;
1279     // Perform this division with proper rounding rather than truncation
1280     if (dividend < 0) {
1281       fi[i] = (int16_t)((dividend - (divisor / 2)) / divisor);
1282     } else {
1283       fi[i] = (int16_t)((dividend + (divisor / 2)) / divisor);
1284     }
1285   }
1286   // Specialize for 7-tap filter
1287   if (wiener_win == WIENER_WIN) {
1288     fi[0] = CLIP(fi[0], WIENER_FILT_TAP0_MINV, WIENER_FILT_TAP0_MAXV);
1289     fi[1] = CLIP(fi[1], WIENER_FILT_TAP1_MINV, WIENER_FILT_TAP1_MAXV);
1290     fi[2] = CLIP(fi[2], WIENER_FILT_TAP2_MINV, WIENER_FILT_TAP2_MAXV);
1291   } else {
1292     fi[2] = CLIP(fi[1], WIENER_FILT_TAP2_MINV, WIENER_FILT_TAP2_MAXV);
1293     fi[1] = CLIP(fi[0], WIENER_FILT_TAP1_MINV, WIENER_FILT_TAP1_MAXV);
1294     fi[0] = 0;
1295   }
1296   // Satisfy filter constraints
1297   fi[WIENER_WIN - 1] = fi[0];
1298   fi[WIENER_WIN - 2] = fi[1];
1299   fi[WIENER_WIN - 3] = fi[2];
1300   // The central element has an implicit +WIENER_FILT_STEP
1301   fi[3] = -2 * (fi[0] + fi[1] + fi[2]);
1302 }
1303 
count_wiener_bits(int wiener_win,WienerInfo * wiener_info,WienerInfo * ref_wiener_info)1304 static int count_wiener_bits(int wiener_win, WienerInfo *wiener_info,
1305                              WienerInfo *ref_wiener_info) {
1306   int bits = 0;
1307   if (wiener_win == WIENER_WIN)
1308     bits += aom_count_primitive_refsubexpfin(
1309         WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
1310         WIENER_FILT_TAP0_SUBEXP_K,
1311         ref_wiener_info->vfilter[0] - WIENER_FILT_TAP0_MINV,
1312         wiener_info->vfilter[0] - WIENER_FILT_TAP0_MINV);
1313   bits += aom_count_primitive_refsubexpfin(
1314       WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
1315       WIENER_FILT_TAP1_SUBEXP_K,
1316       ref_wiener_info->vfilter[1] - WIENER_FILT_TAP1_MINV,
1317       wiener_info->vfilter[1] - WIENER_FILT_TAP1_MINV);
1318   bits += aom_count_primitive_refsubexpfin(
1319       WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
1320       WIENER_FILT_TAP2_SUBEXP_K,
1321       ref_wiener_info->vfilter[2] - WIENER_FILT_TAP2_MINV,
1322       wiener_info->vfilter[2] - WIENER_FILT_TAP2_MINV);
1323   if (wiener_win == WIENER_WIN)
1324     bits += aom_count_primitive_refsubexpfin(
1325         WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
1326         WIENER_FILT_TAP0_SUBEXP_K,
1327         ref_wiener_info->hfilter[0] - WIENER_FILT_TAP0_MINV,
1328         wiener_info->hfilter[0] - WIENER_FILT_TAP0_MINV);
1329   bits += aom_count_primitive_refsubexpfin(
1330       WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
1331       WIENER_FILT_TAP1_SUBEXP_K,
1332       ref_wiener_info->hfilter[1] - WIENER_FILT_TAP1_MINV,
1333       wiener_info->hfilter[1] - WIENER_FILT_TAP1_MINV);
1334   bits += aom_count_primitive_refsubexpfin(
1335       WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
1336       WIENER_FILT_TAP2_SUBEXP_K,
1337       ref_wiener_info->hfilter[2] - WIENER_FILT_TAP2_MINV,
1338       wiener_info->hfilter[2] - WIENER_FILT_TAP2_MINV);
1339   return bits;
1340 }
1341 
1342 #define USE_WIENER_REFINEMENT_SEARCH 1
finer_tile_search_wiener(const RestSearchCtxt * rsc,const RestorationTileLimits * limits,const AV1PixelRect * tile,RestorationUnitInfo * rui,int wiener_win)1343 static int64_t finer_tile_search_wiener(const RestSearchCtxt *rsc,
1344                                         const RestorationTileLimits *limits,
1345                                         const AV1PixelRect *tile,
1346                                         RestorationUnitInfo *rui,
1347                                         int wiener_win) {
1348   const int plane_off = (WIENER_WIN - wiener_win) >> 1;
1349   int64_t err = try_restoration_unit(rsc, limits, tile, rui);
1350 #if USE_WIENER_REFINEMENT_SEARCH
1351   int64_t err2;
1352   int tap_min[] = { WIENER_FILT_TAP0_MINV, WIENER_FILT_TAP1_MINV,
1353                     WIENER_FILT_TAP2_MINV };
1354   int tap_max[] = { WIENER_FILT_TAP0_MAXV, WIENER_FILT_TAP1_MAXV,
1355                     WIENER_FILT_TAP2_MAXV };
1356 
1357   WienerInfo *plane_wiener = &rui->wiener_info;
1358 
1359   // printf("err  pre = %"PRId64"\n", err);
1360   const int start_step = 4;
1361   for (int s = start_step; s >= 1; s >>= 1) {
1362     for (int p = plane_off; p < WIENER_HALFWIN; ++p) {
1363       int skip = 0;
1364       do {
1365         if (plane_wiener->hfilter[p] - s >= tap_min[p]) {
1366           plane_wiener->hfilter[p] -= s;
1367           plane_wiener->hfilter[WIENER_WIN - p - 1] -= s;
1368           plane_wiener->hfilter[WIENER_HALFWIN] += 2 * s;
1369           err2 = try_restoration_unit(rsc, limits, tile, rui);
1370           if (err2 > err) {
1371             plane_wiener->hfilter[p] += s;
1372             plane_wiener->hfilter[WIENER_WIN - p - 1] += s;
1373             plane_wiener->hfilter[WIENER_HALFWIN] -= 2 * s;
1374           } else {
1375             err = err2;
1376             skip = 1;
1377             // At the highest step size continue moving in the same direction
1378             if (s == start_step) continue;
1379           }
1380         }
1381         break;
1382       } while (1);
1383       if (skip) break;
1384       do {
1385         if (plane_wiener->hfilter[p] + s <= tap_max[p]) {
1386           plane_wiener->hfilter[p] += s;
1387           plane_wiener->hfilter[WIENER_WIN - p - 1] += s;
1388           plane_wiener->hfilter[WIENER_HALFWIN] -= 2 * s;
1389           err2 = try_restoration_unit(rsc, limits, tile, rui);
1390           if (err2 > err) {
1391             plane_wiener->hfilter[p] -= s;
1392             plane_wiener->hfilter[WIENER_WIN - p - 1] -= s;
1393             plane_wiener->hfilter[WIENER_HALFWIN] += 2 * s;
1394           } else {
1395             err = err2;
1396             // At the highest step size continue moving in the same direction
1397             if (s == start_step) continue;
1398           }
1399         }
1400         break;
1401       } while (1);
1402     }
1403     for (int p = plane_off; p < WIENER_HALFWIN; ++p) {
1404       int skip = 0;
1405       do {
1406         if (plane_wiener->vfilter[p] - s >= tap_min[p]) {
1407           plane_wiener->vfilter[p] -= s;
1408           plane_wiener->vfilter[WIENER_WIN - p - 1] -= s;
1409           plane_wiener->vfilter[WIENER_HALFWIN] += 2 * s;
1410           err2 = try_restoration_unit(rsc, limits, tile, rui);
1411           if (err2 > err) {
1412             plane_wiener->vfilter[p] += s;
1413             plane_wiener->vfilter[WIENER_WIN - p - 1] += s;
1414             plane_wiener->vfilter[WIENER_HALFWIN] -= 2 * s;
1415           } else {
1416             err = err2;
1417             skip = 1;
1418             // At the highest step size continue moving in the same direction
1419             if (s == start_step) continue;
1420           }
1421         }
1422         break;
1423       } while (1);
1424       if (skip) break;
1425       do {
1426         if (plane_wiener->vfilter[p] + s <= tap_max[p]) {
1427           plane_wiener->vfilter[p] += s;
1428           plane_wiener->vfilter[WIENER_WIN - p - 1] += s;
1429           plane_wiener->vfilter[WIENER_HALFWIN] -= 2 * s;
1430           err2 = try_restoration_unit(rsc, limits, tile, rui);
1431           if (err2 > err) {
1432             plane_wiener->vfilter[p] -= s;
1433             plane_wiener->vfilter[WIENER_WIN - p - 1] -= s;
1434             plane_wiener->vfilter[WIENER_HALFWIN] += 2 * s;
1435           } else {
1436             err = err2;
1437             // At the highest step size continue moving in the same direction
1438             if (s == start_step) continue;
1439           }
1440         }
1441         break;
1442       } while (1);
1443     }
1444   }
1445   // printf("err post = %"PRId64"\n", err);
1446 #endif  // USE_WIENER_REFINEMENT_SEARCH
1447   return err;
1448 }
1449 
search_wiener(const RestorationTileLimits * limits,const AV1PixelRect * tile_rect,int rest_unit_idx,void * priv,int32_t * tmpbuf,RestorationLineBuffers * rlbs)1450 static AOM_INLINE void search_wiener(const RestorationTileLimits *limits,
1451                                      const AV1PixelRect *tile_rect,
1452                                      int rest_unit_idx, void *priv,
1453                                      int32_t *tmpbuf,
1454                                      RestorationLineBuffers *rlbs) {
1455   (void)tmpbuf;
1456   (void)rlbs;
1457   RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
1458   RestUnitSearchInfo *rusi = &rsc->rusi[rest_unit_idx];
1459 
1460   const MACROBLOCK *const x = rsc->x;
1461   const int64_t bits_none = x->wiener_restore_cost[0];
1462 
1463   // Skip Wiener search for low variance contents
1464   if (rsc->sf->lpf_sf.prune_wiener_based_on_src_var) {
1465     const int scale[3] = { 0, 1, 2 };
1466     // Obtain the normalized Qscale
1467     const int qs = av1_dc_quant_QTX(rsc->cm->quant_params.base_qindex, 0,
1468                                     rsc->cm->seq_params.bit_depth) >>
1469                    3;
1470     // Derive threshold as sqr(normalized Qscale) * scale / 16,
1471     const uint64_t thresh =
1472         (qs * qs * scale[rsc->sf->lpf_sf.prune_wiener_based_on_src_var]) >> 4;
1473     const int highbd = rsc->cm->seq_params.use_highbitdepth;
1474     const uint64_t src_var =
1475         var_restoration_unit(limits, rsc->src, rsc->plane, highbd);
1476     // Do not perform Wiener search if source variance is lower than threshold
1477     // or if the reconstruction error is zero
1478     int prune_wiener = (src_var < thresh) || (rusi->sse[RESTORE_NONE] == 0);
1479     if (prune_wiener) {
1480       rsc->bits += bits_none;
1481       rsc->sse += rusi->sse[RESTORE_NONE];
1482       rusi->best_rtype[RESTORE_WIENER - 1] = RESTORE_NONE;
1483       rusi->sse[RESTORE_WIENER] = INT64_MAX;
1484       if (rsc->sf->lpf_sf.prune_sgr_based_on_wiener == 2)
1485         rusi->skip_sgr_eval = 1;
1486       return;
1487     }
1488   }
1489 
1490   const int wiener_win =
1491       (rsc->plane == AOM_PLANE_Y) ? WIENER_WIN : WIENER_WIN_CHROMA;
1492 
1493   int reduced_wiener_win = wiener_win;
1494   if (rsc->sf->lpf_sf.reduce_wiener_window_size) {
1495     reduced_wiener_win =
1496         (rsc->plane == AOM_PLANE_Y) ? WIENER_WIN_REDUCED : WIENER_WIN_CHROMA;
1497   }
1498 
1499   int64_t M[WIENER_WIN2];
1500   int64_t H[WIENER_WIN2 * WIENER_WIN2];
1501   int32_t vfilter[WIENER_WIN], hfilter[WIENER_WIN];
1502 
1503 #if CONFIG_AV1_HIGHBITDEPTH
1504   const AV1_COMMON *const cm = rsc->cm;
1505   if (cm->seq_params.use_highbitdepth) {
1506     av1_compute_stats_highbd(reduced_wiener_win, rsc->dgd_buffer,
1507                              rsc->src_buffer, limits->h_start, limits->h_end,
1508                              limits->v_start, limits->v_end, rsc->dgd_stride,
1509                              rsc->src_stride, M, H, cm->seq_params.bit_depth);
1510   } else {
1511     av1_compute_stats(reduced_wiener_win, rsc->dgd_buffer, rsc->src_buffer,
1512                       limits->h_start, limits->h_end, limits->v_start,
1513                       limits->v_end, rsc->dgd_stride, rsc->src_stride, M, H);
1514   }
1515 #else
1516   av1_compute_stats(reduced_wiener_win, rsc->dgd_buffer, rsc->src_buffer,
1517                     limits->h_start, limits->h_end, limits->v_start,
1518                     limits->v_end, rsc->dgd_stride, rsc->src_stride, M, H);
1519 #endif
1520 
1521   if (!wiener_decompose_sep_sym(reduced_wiener_win, M, H, vfilter, hfilter)) {
1522     rsc->bits += bits_none;
1523     rsc->sse += rusi->sse[RESTORE_NONE];
1524     rusi->best_rtype[RESTORE_WIENER - 1] = RESTORE_NONE;
1525     rusi->sse[RESTORE_WIENER] = INT64_MAX;
1526     if (rsc->sf->lpf_sf.prune_sgr_based_on_wiener == 2) rusi->skip_sgr_eval = 1;
1527     return;
1528   }
1529 
1530   RestorationUnitInfo rui;
1531   memset(&rui, 0, sizeof(rui));
1532   rui.restoration_type = RESTORE_WIENER;
1533   finalize_sym_filter(reduced_wiener_win, vfilter, rui.wiener_info.vfilter);
1534   finalize_sym_filter(reduced_wiener_win, hfilter, rui.wiener_info.hfilter);
1535 
1536   // Filter score computes the value of the function x'*A*x - x'*b for the
1537   // learned filter and compares it against identity filer. If there is no
1538   // reduction in the function, the filter is reverted back to identity
1539   if (compute_score(reduced_wiener_win, M, H, rui.wiener_info.vfilter,
1540                     rui.wiener_info.hfilter) > 0) {
1541     rsc->bits += bits_none;
1542     rsc->sse += rusi->sse[RESTORE_NONE];
1543     rusi->best_rtype[RESTORE_WIENER - 1] = RESTORE_NONE;
1544     rusi->sse[RESTORE_WIENER] = INT64_MAX;
1545     if (rsc->sf->lpf_sf.prune_sgr_based_on_wiener == 2) rusi->skip_sgr_eval = 1;
1546     return;
1547   }
1548 
1549   aom_clear_system_state();
1550 
1551   rusi->sse[RESTORE_WIENER] = finer_tile_search_wiener(
1552       rsc, limits, tile_rect, &rui, reduced_wiener_win);
1553   rusi->wiener = rui.wiener_info;
1554 
1555   if (reduced_wiener_win != WIENER_WIN) {
1556     assert(rui.wiener_info.vfilter[0] == 0 &&
1557            rui.wiener_info.vfilter[WIENER_WIN - 1] == 0);
1558     assert(rui.wiener_info.hfilter[0] == 0 &&
1559            rui.wiener_info.hfilter[WIENER_WIN - 1] == 0);
1560   }
1561 
1562   const int64_t bits_wiener =
1563       x->wiener_restore_cost[1] +
1564       (count_wiener_bits(wiener_win, &rusi->wiener, &rsc->wiener)
1565        << AV1_PROB_COST_SHIFT);
1566 
1567   double cost_none =
1568       RDCOST_DBL(x->rdmult, bits_none >> 4, rusi->sse[RESTORE_NONE]);
1569   double cost_wiener =
1570       RDCOST_DBL(x->rdmult, bits_wiener >> 4, rusi->sse[RESTORE_WIENER]);
1571 
1572   RestorationType rtype =
1573       (cost_wiener < cost_none) ? RESTORE_WIENER : RESTORE_NONE;
1574   rusi->best_rtype[RESTORE_WIENER - 1] = rtype;
1575 
1576   // Set 'skip_sgr_eval' based on rdcost ratio of RESTORE_WIENER and
1577   // RESTORE_NONE or based on best_rtype
1578   if (rsc->sf->lpf_sf.prune_sgr_based_on_wiener == 1) {
1579     rusi->skip_sgr_eval = cost_wiener > (1.01 * cost_none);
1580   } else if (rsc->sf->lpf_sf.prune_sgr_based_on_wiener == 2) {
1581     rusi->skip_sgr_eval = rusi->best_rtype[RESTORE_WIENER - 1] == RESTORE_NONE;
1582   }
1583 
1584   rsc->sse += rusi->sse[rtype];
1585   rsc->bits += (cost_wiener < cost_none) ? bits_wiener : bits_none;
1586   if (cost_wiener < cost_none) rsc->wiener = rusi->wiener;
1587 }
1588 
search_norestore(const RestorationTileLimits * limits,const AV1PixelRect * tile_rect,int rest_unit_idx,void * priv,int32_t * tmpbuf,RestorationLineBuffers * rlbs)1589 static AOM_INLINE void search_norestore(const RestorationTileLimits *limits,
1590                                         const AV1PixelRect *tile_rect,
1591                                         int rest_unit_idx, void *priv,
1592                                         int32_t *tmpbuf,
1593                                         RestorationLineBuffers *rlbs) {
1594   (void)tile_rect;
1595   (void)tmpbuf;
1596   (void)rlbs;
1597 
1598   RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
1599   RestUnitSearchInfo *rusi = &rsc->rusi[rest_unit_idx];
1600 
1601   const int highbd = rsc->cm->seq_params.use_highbitdepth;
1602   rusi->sse[RESTORE_NONE] = sse_restoration_unit(
1603       limits, rsc->src, &rsc->cm->cur_frame->buf, rsc->plane, highbd);
1604 
1605   rsc->sse += rusi->sse[RESTORE_NONE];
1606 }
1607 
search_switchable(const RestorationTileLimits * limits,const AV1PixelRect * tile_rect,int rest_unit_idx,void * priv,int32_t * tmpbuf,RestorationLineBuffers * rlbs)1608 static AOM_INLINE void search_switchable(const RestorationTileLimits *limits,
1609                                          const AV1PixelRect *tile_rect,
1610                                          int rest_unit_idx, void *priv,
1611                                          int32_t *tmpbuf,
1612                                          RestorationLineBuffers *rlbs) {
1613   (void)limits;
1614   (void)tile_rect;
1615   (void)tmpbuf;
1616   (void)rlbs;
1617   RestSearchCtxt *rsc = (RestSearchCtxt *)priv;
1618   RestUnitSearchInfo *rusi = &rsc->rusi[rest_unit_idx];
1619 
1620   const MACROBLOCK *const x = rsc->x;
1621 
1622   const int wiener_win =
1623       (rsc->plane == AOM_PLANE_Y) ? WIENER_WIN : WIENER_WIN_CHROMA;
1624 
1625   double best_cost = 0;
1626   int64_t best_bits = 0;
1627   RestorationType best_rtype = RESTORE_NONE;
1628 
1629   for (RestorationType r = 0; r < RESTORE_SWITCHABLE_TYPES; ++r) {
1630     // Check for the condition that wiener or sgrproj search could not
1631     // find a solution or the solution was worse than RESTORE_NONE.
1632     // In either case the best_rtype will be set as RESTORE_NONE. These
1633     // should be skipped from the test below.
1634     if (r > RESTORE_NONE) {
1635       if (rusi->best_rtype[r - 1] == RESTORE_NONE) continue;
1636     }
1637 
1638     const int64_t sse = rusi->sse[r];
1639     int64_t coeff_pcost = 0;
1640     switch (r) {
1641       case RESTORE_NONE: coeff_pcost = 0; break;
1642       case RESTORE_WIENER:
1643         coeff_pcost =
1644             count_wiener_bits(wiener_win, &rusi->wiener, &rsc->wiener);
1645         break;
1646       case RESTORE_SGRPROJ:
1647         coeff_pcost = count_sgrproj_bits(&rusi->sgrproj, &rsc->sgrproj);
1648         break;
1649       default: assert(0); break;
1650     }
1651     const int64_t coeff_bits = coeff_pcost << AV1_PROB_COST_SHIFT;
1652     const int64_t bits = x->switchable_restore_cost[r] + coeff_bits;
1653     double cost = RDCOST_DBL(x->rdmult, bits >> 4, sse);
1654     if (r == RESTORE_SGRPROJ && rusi->sgrproj.ep < 10)
1655       cost *=
1656           (1 + DUAL_SGR_PENALTY_MULT * rsc->sf->lpf_sf.dual_sgr_penalty_level);
1657     if (r == 0 || cost < best_cost) {
1658       best_cost = cost;
1659       best_bits = bits;
1660       best_rtype = r;
1661     }
1662   }
1663 
1664   rusi->best_rtype[RESTORE_SWITCHABLE - 1] = best_rtype;
1665 
1666   rsc->sse += rusi->sse[best_rtype];
1667   rsc->bits += best_bits;
1668   if (best_rtype == RESTORE_WIENER) rsc->wiener = rusi->wiener;
1669   if (best_rtype == RESTORE_SGRPROJ) rsc->sgrproj = rusi->sgrproj;
1670 }
1671 
copy_unit_info(RestorationType frame_rtype,const RestUnitSearchInfo * rusi,RestorationUnitInfo * rui)1672 static AOM_INLINE void copy_unit_info(RestorationType frame_rtype,
1673                                       const RestUnitSearchInfo *rusi,
1674                                       RestorationUnitInfo *rui) {
1675   assert(frame_rtype > 0);
1676   rui->restoration_type = rusi->best_rtype[frame_rtype - 1];
1677   if (rui->restoration_type == RESTORE_WIENER)
1678     rui->wiener_info = rusi->wiener;
1679   else
1680     rui->sgrproj_info = rusi->sgrproj;
1681 }
1682 
search_rest_type(RestSearchCtxt * rsc,RestorationType rtype)1683 static double search_rest_type(RestSearchCtxt *rsc, RestorationType rtype) {
1684   static const rest_unit_visitor_t funs[RESTORE_TYPES] = {
1685     search_norestore, search_wiener, search_sgrproj, search_switchable
1686   };
1687 
1688   reset_rsc(rsc);
1689   rsc_on_tile(rsc);
1690 
1691   av1_foreach_rest_unit_in_plane(rsc->cm, rsc->plane, funs[rtype], rsc,
1692                                  &rsc->tile_rect, rsc->cm->rst_tmpbuf, NULL);
1693   return RDCOST_DBL(rsc->x->rdmult, rsc->bits >> 4, rsc->sse);
1694 }
1695 
rest_tiles_in_plane(const AV1_COMMON * cm,int plane)1696 static int rest_tiles_in_plane(const AV1_COMMON *cm, int plane) {
1697   const RestorationInfo *rsi = &cm->rst_info[plane];
1698   return rsi->units_per_tile;
1699 }
1700 
av1_pick_filter_restoration(const YV12_BUFFER_CONFIG * src,AV1_COMP * cpi)1701 void av1_pick_filter_restoration(const YV12_BUFFER_CONFIG *src, AV1_COMP *cpi) {
1702   AV1_COMMON *const cm = &cpi->common;
1703   const int num_planes = av1_num_planes(cm);
1704   assert(!cm->features.all_lossless);
1705 
1706   int ntiles[2];
1707   for (int is_uv = 0; is_uv < 2; ++is_uv)
1708     ntiles[is_uv] = rest_tiles_in_plane(cm, is_uv);
1709 
1710   assert(ntiles[1] <= ntiles[0]);
1711   RestUnitSearchInfo *rusi =
1712       (RestUnitSearchInfo *)aom_memalign(16, sizeof(*rusi) * ntiles[0]);
1713 
1714   // If the restoration unit dimensions are not multiples of
1715   // rsi->restoration_unit_size then some elements of the rusi array may be
1716   // left uninitialised when we reach copy_unit_info(...). This is not a
1717   // problem, as these elements are ignored later, but in order to quiet
1718   // Valgrind's warnings we initialise the array below.
1719   memset(rusi, 0, sizeof(*rusi) * ntiles[0]);
1720   cpi->td.mb.rdmult = cpi->rd.RDMULT;
1721 
1722   RestSearchCtxt rsc;
1723   const int plane_start = AOM_PLANE_Y;
1724   const int plane_end = num_planes > 1 ? AOM_PLANE_V : AOM_PLANE_Y;
1725   for (int plane = plane_start; plane <= plane_end; ++plane) {
1726     init_rsc(src, &cpi->common, &cpi->td.mb, &cpi->sf, plane, rusi,
1727              &cpi->trial_frame_rst, &rsc);
1728 
1729     const int plane_ntiles = ntiles[plane > 0];
1730     const RestorationType num_rtypes =
1731         (plane_ntiles > 1) ? RESTORE_TYPES : RESTORE_SWITCHABLE_TYPES;
1732 
1733     double best_cost = 0;
1734     RestorationType best_rtype = RESTORE_NONE;
1735 
1736     const int highbd = rsc.cm->seq_params.use_highbitdepth;
1737     if (!cpi->sf.lpf_sf.disable_loop_restoration_chroma || !plane) {
1738       av1_extend_frame(rsc.dgd_buffer, rsc.plane_width, rsc.plane_height,
1739                        rsc.dgd_stride, RESTORATION_BORDER, RESTORATION_BORDER,
1740                        highbd);
1741 
1742       for (RestorationType r = 0; r < num_rtypes; ++r) {
1743         if ((force_restore_type != RESTORE_TYPES) && (r != RESTORE_NONE) &&
1744             (r != force_restore_type))
1745           continue;
1746 
1747         double cost = search_rest_type(&rsc, r);
1748 
1749         if (r == 0 || cost < best_cost) {
1750           best_cost = cost;
1751           best_rtype = r;
1752         }
1753       }
1754     }
1755 
1756     cm->rst_info[plane].frame_restoration_type = best_rtype;
1757     if (force_restore_type != RESTORE_TYPES)
1758       assert(best_rtype == force_restore_type || best_rtype == RESTORE_NONE);
1759 
1760     if (best_rtype != RESTORE_NONE) {
1761       for (int u = 0; u < plane_ntiles; ++u) {
1762         copy_unit_info(best_rtype, &rusi[u], &cm->rst_info[plane].unit_info[u]);
1763       }
1764     }
1765   }
1766 
1767   aom_free(rusi);
1768 }
1769