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