tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

pickrst.c (89535B)


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