vp9_denoiser.c 22.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 *  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

Tim Kopp's avatar
Tim Kopp committed
11
#include <assert.h>
12
#include <limits.h>
13 14
#include <math.h>

Zoe Liu's avatar
Zoe Liu committed
15
#include "./vpx_dsp_rtcd.h"
16
#include "vpx_dsp/vpx_dsp_common.h"
17
#include "vpx_scale/yv12config.h"
Tim Kopp's avatar
Tim Kopp committed
18
#include "vpx/vpx_integer.h"
19
#include "vp9/common/vp9_reconinter.h"
20
#include "vp9/encoder/vp9_context_tree.h"
Tim Kopp's avatar
Tim Kopp committed
21
#include "vp9/encoder/vp9_denoiser.h"
22
#include "vp9/encoder/vp9_encoder.h"
23

24 25
// OUTPUT_YUV_DENOISED

26 27 28 29
#ifdef OUTPUT_YUV_DENOISED
static void make_grayscale(YV12_BUFFER_CONFIG *yuv);
#endif

30 31 32 33 34 35 36 37 38 39 40 41 42 43
static int absdiff_thresh(BLOCK_SIZE bs, int increase_denoising) {
  (void)bs;
  return 3 + (increase_denoising ? 1 : 0);
}

static int delta_thresh(BLOCK_SIZE bs, int increase_denoising) {
  (void)bs;
  (void)increase_denoising;
  return 4;
}

static int noise_motion_thresh(BLOCK_SIZE bs, int increase_denoising) {
  (void)bs;
  (void)increase_denoising;
44
  return 625;
45 46 47
}

static unsigned int sse_thresh(BLOCK_SIZE bs, int increase_denoising) {
48
  return (1 << num_pels_log2_lookup[bs]) * (increase_denoising ? 80 : 40);
49 50 51
}

static int sse_diff_thresh(BLOCK_SIZE bs, int increase_denoising,
52
                           int motion_magnitude) {
53
  if (motion_magnitude > noise_motion_thresh(bs, increase_denoising)) {
54 55 56 57
    if (increase_denoising)
      return (1 << num_pels_log2_lookup[bs]) << 2;
    else
      return 0;
58
  } else {
59
    return (1 << num_pels_log2_lookup[bs]) << 4;
60 61 62 63
  }
}

static int total_adj_weak_thresh(BLOCK_SIZE bs, int increase_denoising) {
64
  return (1 << num_pels_log2_lookup[bs]) * (increase_denoising ? 3 : 2);
65 66
}

67 68 69 70
// TODO(jackychen): If increase_denoising is enabled in the future,
// we might need to update the code for calculating 'total_adj' in
// case the C code is not bit-exact with corresponding sse2 code.
int vp9_denoiser_filter_c(const uint8_t *sig, int sig_stride,
71 72 73
                          const uint8_t *mc_avg, int mc_avg_stride,
                          uint8_t *avg, int avg_stride, int increase_denoising,
                          BLOCK_SIZE bs, int motion_magnitude) {
74
  int r, c;
75 76 77 78
  const uint8_t *sig_start = sig;
  const uint8_t *mc_avg_start = mc_avg;
  uint8_t *avg_start = avg;
  int diff, adj, absdiff, delta;
79
  int adj_val[] = { 3, 4, 6 };
80
  int total_adj = 0;
81 82
  int shift_inc = 1;

83 84 85
  // If motion_magnitude is small, making the denoiser more aggressive by
  // increasing the adjustment for each level. Add another increment for
  // blocks that are labeled for increase denoising.
86 87 88 89 90 91 92 93
  if (motion_magnitude <= MOTION_MAGNITUDE_THRESHOLD) {
    if (increase_denoising) {
      shift_inc = 2;
    }
    adj_val[0] += shift_inc;
    adj_val[1] += shift_inc;
    adj_val[2] += shift_inc;
  }
94

95
  // First attempt to apply a strong temporal denoising filter.
96 97
  for (r = 0; r < (4 << b_height_log2_lookup[bs]); ++r) {
    for (c = 0; c < (4 << b_width_log2_lookup[bs]); ++c) {
98
      diff = mc_avg[c] - sig[c];
99
      absdiff = abs(diff);
100

101
      if (absdiff <= absdiff_thresh(bs, increase_denoising)) {
102 103
        avg[c] = mc_avg[c];
        total_adj += diff;
104
      } else {
105
        switch (absdiff) {
106 107 108 109 110 111 112 113 114 115 116 117 118
          case 4:
          case 5:
          case 6:
          case 7: adj = adj_val[0]; break;
          case 8:
          case 9:
          case 10:
          case 11:
          case 12:
          case 13:
          case 14:
          case 15: adj = adj_val[1]; break;
          default: adj = adj_val[2];
119 120
        }
        if (diff > 0) {
121
          avg[c] = VPXMIN(UINT8_MAX, sig[c] + adj);
122 123
          total_adj += adj;
        } else {
124
          avg[c] = VPXMAX(0, sig[c] - adj);
125 126
          total_adj -= adj;
        }
127 128 129 130 131 132
      }
    }
    sig += sig_stride;
    avg += avg_stride;
    mc_avg += mc_avg_stride;
  }
133 134 135 136 137 138 139

  // If the strong filter did not modify the signal too much, we're all set.
  if (abs(total_adj) <= total_adj_strong_thresh(bs, increase_denoising)) {
    return FILTER_BLOCK;
  }

  // Otherwise, we try to dampen the filter if the delta is not too high.
140 141 142
  delta = ((abs(total_adj) - total_adj_strong_thresh(bs, increase_denoising)) >>
           num_pels_log2_lookup[bs]) +
          1;
143 144

  if (delta >= delta_thresh(bs, increase_denoising)) {
145 146 147
    return COPY_BLOCK;
  }

148
  mc_avg = mc_avg_start;
149 150
  avg = avg_start;
  sig = sig_start;
151 152
  for (r = 0; r < (4 << b_height_log2_lookup[bs]); ++r) {
    for (c = 0; c < (4 << b_width_log2_lookup[bs]); ++c) {
153 154 155 156 157 158
      diff = mc_avg[c] - sig[c];
      adj = abs(diff);
      if (adj > delta) {
        adj = delta;
      }
      if (diff > 0) {
JackyChen's avatar
JackyChen committed
159 160 161
        // Diff positive means we made positive adjustment above
        // (in first try/attempt), so now make negative adjustment to bring
        // denoised signal down.
162
        avg[c] = VPXMAX(0, avg[c] - adj);
JackyChen's avatar
JackyChen committed
163
        total_adj -= adj;
164
      } else {
JackyChen's avatar
JackyChen committed
165 166 167
        // Diff negative means we made negative adjustment above
        // (in first try/attempt), so now make positive adjustment to bring
        // denoised signal up.
168
        avg[c] = VPXMIN(UINT8_MAX, avg[c] + adj);
JackyChen's avatar
JackyChen committed
169
        total_adj += adj;
170 171 172 173 174 175 176 177 178 179 180 181
      }
    }
    sig += sig_stride;
    avg += avg_stride;
    mc_avg += mc_avg_stride;
  }

  // We can use the filter if it has been sufficiently dampened
  if (abs(total_adj) <= total_adj_weak_thresh(bs, increase_denoising)) {
    return FILTER_BLOCK;
  }
  return COPY_BLOCK;
182 183
}

184 185 186
static uint8_t *block_start(uint8_t *framebuf, int stride, int mi_row,
                            int mi_col) {
  return framebuf + (stride * mi_row << 3) + (mi_col << 3);
187 188
}

189
static VP9_DENOISER_DECISION perform_motion_compensation(
190
    VP9_COMMON *const cm, VP9_DENOISER *denoiser, MACROBLOCK *mb, BLOCK_SIZE bs,
191
    int increase_denoising, int mi_row, int mi_col, PICK_MODE_CONTEXT *ctx,
192
    int motion_magnitude, int is_skin, int *zeromv_filter, int consec_zeromv,
193
    int num_spatial_layers, int width) {
194 195 196
  const int sse_diff = (ctx->newmv_sse == UINT_MAX)
                           ? 0
                           : ((int)ctx->zeromv_sse - (int)ctx->newmv_sse);
197 198
  MV_REFERENCE_FRAME frame;
  MACROBLOCKD *filter_mbd = &mb->e_mbd;
199 200
  MODE_INFO *mi = filter_mbd->mi[0];
  MODE_INFO saved_mi;
201
  int i;
Tim Kopp's avatar
Tim Kopp committed
202
  struct buf_2d saved_dst[MAX_MB_PLANE];
203
  struct buf_2d saved_pre[MAX_MB_PLANE];
204
  RefBuffer *saved_block_refs[2];
Tim Kopp's avatar
Tim Kopp committed
205

206
  frame = ctx->best_reference_frame;
207
  saved_mi = *mi;
208

209
  if (is_skin && (motion_magnitude > 0 || consec_zeromv < 4)) return COPY_BLOCK;
210

211 212 213 214 215
  // Avoid denoising small blocks. When noise > kDenLow or frame width > 480,
  // denoise 16x16 blocks.
  if (bs == BLOCK_8X8 || bs == BLOCK_8X16 || bs == BLOCK_16X8 ||
      (bs == BLOCK_16X16 && width > 480 &&
       denoiser->denoising_level <= kDenLow))
216 217
    return COPY_BLOCK;

218 219
  // If the best reference frame uses inter-prediction and there is enough of a
  // difference in sum-squared-error, use it.
220
  if (frame != INTRA_FRAME && frame != ALTREF_FRAME &&
221
      (frame != GOLDEN_FRAME || num_spatial_layers == 1) &&
Marco's avatar
Marco committed
222
      sse_diff > sse_diff_thresh(bs, increase_denoising, motion_magnitude)) {
223 224 225
    mi->ref_frame[0] = ctx->best_reference_frame;
    mi->mode = ctx->best_sse_inter_mode;
    mi->mv[0] = ctx->best_sse_mv;
226 227
  } else {
    // Otherwise, use the zero reference frame.
228
    frame = ctx->best_zeromv_reference_frame;
229 230
    ctx->newmv_sse = ctx->zeromv_sse;
    // Bias to last reference.
231
    if (num_spatial_layers > 1 || frame == ALTREF_FRAME ||
232 233 234
        (frame != LAST_FRAME &&
         ((ctx->zeromv_lastref_sse<(5 * ctx->zeromv_sse)>> 2) ||
          denoiser->denoising_level >= kDenHigh))) {
235 236 237
      frame = LAST_FRAME;
      ctx->newmv_sse = ctx->zeromv_lastref_sse;
    }
238 239 240
    mi->ref_frame[0] = frame;
    mi->mode = ZEROMV;
    mi->mv[0].as_int = 0;
241 242
    ctx->best_sse_inter_mode = ZEROMV;
    ctx->best_sse_mv.as_int = 0;
243
    *zeromv_filter = 1;
244 245 246
    if (denoiser->denoising_level > kDenMedium) {
      motion_magnitude = 0;
    }
247 248
  }

249 250
  if (ctx->newmv_sse > sse_thresh(bs, increase_denoising)) {
    // Restore everything to its original state
251
    *mi = saved_mi;
252 253
    return COPY_BLOCK;
  }
254
  if (motion_magnitude > (noise_motion_thresh(bs, increase_denoising) << 3)) {
255
    // Restore everything to its original state
256
    *mi = saved_mi;
257 258 259 260 261
    return COPY_BLOCK;
  }

  // We will restore these after motion compensation.
  for (i = 0; i < MAX_MB_PLANE; ++i) {
262
    saved_pre[i] = filter_mbd->plane[i].pre[0];
263 264
    saved_dst[i] = filter_mbd->plane[i].dst;
  }
265
  saved_block_refs[0] = filter_mbd->block_refs[0];
266

267 268
  // Set the pointers in the MACROBLOCKD to point to the buffers in the denoiser
  // struct.
269 270
  filter_mbd->plane[0].pre[0].buf =
      block_start(denoiser->running_avg_y[frame].y_buffer,
271 272
                  denoiser->running_avg_y[frame].y_stride, mi_row, mi_col);
  filter_mbd->plane[0].pre[0].stride = denoiser->running_avg_y[frame].y_stride;
273
  filter_mbd->plane[1].pre[0].buf =
274 275 276
      block_start(denoiser->running_avg_y[frame].u_buffer,
                  denoiser->running_avg_y[frame].uv_stride, mi_row, mi_col);
  filter_mbd->plane[1].pre[0].stride = denoiser->running_avg_y[frame].uv_stride;
277 278
  filter_mbd->plane[2].pre[0].buf =
      block_start(denoiser->running_avg_y[frame].v_buffer,
279 280
                  denoiser->running_avg_y[frame].uv_stride, mi_row, mi_col);
  filter_mbd->plane[2].pre[0].stride = denoiser->running_avg_y[frame].uv_stride;
281

282 283
  filter_mbd->plane[0].dst.buf =
      block_start(denoiser->mc_running_avg_y.y_buffer,
284
                  denoiser->mc_running_avg_y.y_stride, mi_row, mi_col);
285 286 287
  filter_mbd->plane[0].dst.stride = denoiser->mc_running_avg_y.y_stride;
  filter_mbd->plane[1].dst.buf =
      block_start(denoiser->mc_running_avg_y.u_buffer,
288
                  denoiser->mc_running_avg_y.uv_stride, mi_row, mi_col);
Tim Kopp's avatar
Tim Kopp committed
289
  filter_mbd->plane[1].dst.stride = denoiser->mc_running_avg_y.uv_stride;
290 291
  filter_mbd->plane[2].dst.buf =
      block_start(denoiser->mc_running_avg_y.v_buffer,
292
                  denoiser->mc_running_avg_y.uv_stride, mi_row, mi_col);
Tim Kopp's avatar
Tim Kopp committed
293
  filter_mbd->plane[2].dst.stride = denoiser->mc_running_avg_y.uv_stride;
294

295
  set_ref_ptrs(cm, filter_mbd, frame, NONE);
296
  vp9_build_inter_predictors_sby(filter_mbd, mi_row, mi_col, bs);
297 298

  // Restore everything to its original state
299
  *mi = saved_mi;
300
  filter_mbd->block_refs[0] = saved_block_refs[0];
Tim Kopp's avatar
Tim Kopp committed
301
  for (i = 0; i < MAX_MB_PLANE; ++i) {
302
    filter_mbd->plane[i].pre[0] = saved_pre[i];
Tim Kopp's avatar
Tim Kopp committed
303 304
    filter_mbd->plane[i].dst = saved_dst[i];
  }
305 306 307 308

  return FILTER_BLOCK;
}

309 310
void vp9_denoiser_denoise(VP9_COMP *cpi, MACROBLOCK *mb, int mi_row, int mi_col,
                          BLOCK_SIZE bs, PICK_MODE_CONTEXT *ctx,
311
                          VP9_DENOISER_DECISION *denoiser_decision) {
Marco's avatar
Marco committed
312
  int mv_col, mv_row;
313
  int motion_magnitude = 0;
314
  int zeromv_filter = 0;
315
  VP9_DENOISER *denoiser = &cpi->denoiser;
316
  VP9_DENOISER_DECISION decision = COPY_BLOCK;
317
  YV12_BUFFER_CONFIG avg = denoiser->running_avg_y[INTRA_FRAME];
318 319
  YV12_BUFFER_CONFIG mc_avg = denoiser->mc_running_avg_y;
  uint8_t *avg_start = block_start(avg.y_buffer, avg.y_stride, mi_row, mi_col);
320 321
  uint8_t *mc_avg_start =
      block_start(mc_avg.y_buffer, mc_avg.y_stride, mi_row, mi_col);
322
  struct buf_2d src = mb->plane[0].src;
323
  int is_skin = 0;
324
  int increase_denoising = 0;
325
  int consec_zeromv = 0;
326 327 328
  mv_col = ctx->best_sse_mv.as_mv.col;
  mv_row = ctx->best_sse_mv.as_mv.row;
  motion_magnitude = mv_row * mv_row + mv_col * mv_col;
329

330
  if (cpi->use_skin_detection && bs <= BLOCK_32X32 &&
331
      denoiser->denoising_level < kDenHigh) {
332 333 334 335
    int motion_level = (motion_magnitude < 16) ? 0 : 1;
    // If motion for current block is small/zero, compute consec_zeromv for
    // skin detection (early exit in skin detection is done for large
    // consec_zeromv when current block has small/zero motion).
336
    consec_zeromv = 0;
337
    if (motion_level == 0) {
338
      VP9_COMMON *const cm = &cpi->common;
339 340 341 342 343 344 345 346 347 348 349
      int j, i;
      // Loop through the 8x8 sub-blocks.
      const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
      const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
      const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
      const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
      const int block_index = mi_row * cm->mi_cols + mi_col;
      consec_zeromv = 100;
      for (i = 0; i < ymis; i++) {
        for (j = 0; j < xmis; j++) {
          int bl_index = block_index + i * cm->mi_cols + j;
350
          consec_zeromv = VPXMIN(cpi->consec_zero_mv[bl_index], consec_zeromv);
351 352
          // No need to keep checking 8x8 blocks if any of the sub-blocks
          // has small consec_zeromv (since threshold for no_skin based on
353 354
          // zero/small motion in skin detection is high, i.e, > 4).
          if (consec_zeromv < 4) {
355 356 357 358 359 360 361
            i = ymis;
            j = xmis;
          }
        }
      }
    }
    // TODO(marpan): Compute skin detection over sub-blocks.
362 363 364 365
    is_skin = vp9_compute_skin_block(
        mb->plane[0].src.buf, mb->plane[1].src.buf, mb->plane[2].src.buf,
        mb->plane[0].src.stride, mb->plane[1].src.stride, bs, consec_zeromv,
        motion_level);
366
  }
367
  if (!is_skin && denoiser->denoising_level == kDenHigh) increase_denoising = 1;
Marco's avatar
Marco committed
368

369
  if (denoiser->denoising_level >= kDenLow && !ctx->sb_skip_denoising)
370
    decision = perform_motion_compensation(
371
        &cpi->common, denoiser, mb, bs, increase_denoising, mi_row, mi_col, ctx,
372
        motion_magnitude, is_skin, &zeromv_filter, consec_zeromv,
373
        cpi->svc.number_spatial_layers, cpi->Source->y_width);
374 375

  if (decision == FILTER_BLOCK) {
376 377 378
    decision = vp9_denoiser_filter(src.buf, src.stride, mc_avg_start,
                                   mc_avg.y_stride, avg_start, avg.y_stride,
                                   increase_denoising, bs, motion_magnitude);
379
  }
380 381

  if (decision == FILTER_BLOCK) {
382 383
    vpx_convolve_copy(avg_start, avg.y_stride, src.buf, src.stride, NULL, 0,
                      NULL, 0, num_4x4_blocks_wide_lookup[bs] << 2,
384
                      num_4x4_blocks_high_lookup[bs] << 2);
385
  } else {  // COPY_BLOCK
386 387
    vpx_convolve_copy(src.buf, src.stride, avg_start, avg.y_stride, NULL, 0,
                      NULL, 0, num_4x4_blocks_wide_lookup[bs] << 2,
388
                      num_4x4_blocks_high_lookup[bs] << 2);
389
  }
390
  *denoiser_decision = decision;
391 392
  if (decision == FILTER_BLOCK && zeromv_filter == 1)
    *denoiser_decision = FILTER_ZEROMV_BLOCK;
393 394
}

395 396
static void copy_frame(YV12_BUFFER_CONFIG *const dest,
                       const YV12_BUFFER_CONFIG *const src) {
397
  int r;
398 399
  const uint8_t *srcbuf = src->y_buffer;
  uint8_t *destbuf = dest->y_buffer;
400

401 402
  assert(dest->y_width == src->y_width);
  assert(dest->y_height == src->y_height);
403

404 405 406 407
  for (r = 0; r < dest->y_height; ++r) {
    memcpy(destbuf, srcbuf, dest->y_width);
    destbuf += dest->y_stride;
    srcbuf += src->y_stride;
408
  }
409 410
}

411 412
static void swap_frame_buffer(YV12_BUFFER_CONFIG *const dest,
                              YV12_BUFFER_CONFIG *const src) {
413 414 415 416 417
  uint8_t *tmp_buf = dest->y_buffer;
  assert(dest->y_width == src->y_width);
  assert(dest->y_height == src->y_height);
  dest->y_buffer = src->y_buffer;
  src->y_buffer = tmp_buf;
418 419
}

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
void vp9_denoise_init_svc(VP9_COMP *cpi) {
  // For fixed pattern SVC, on base temporal layer. Note we only denoise
  // higher spatial layer for SVC.
  if (cpi->svc.temporal_layering_mode != VP9E_TEMPORAL_LAYERING_MODE_BYPASS &&
      cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
      cpi->svc.temporal_layer_id == 0) {
    VP9_DENOISER *denoiser = &cpi->denoiser;
    copy_frame(&denoiser->running_avg_y[LAST_FRAME],
               &denoiser->running_avg_y[GOLDEN_FRAME]);
  }
}

void vp9_denoiser_update_frame_info(
    VP9_DENOISER *denoiser, YV12_BUFFER_CONFIG src, FRAME_TYPE frame_type,
    int refresh_alt_ref_frame, int refresh_golden_frame, int refresh_last_frame,
    int resized, int svc_base_is_key, int svc_fixed_pattern,
    int temporal_layer_id) {
437
  // Copy source into denoised reference buffers on KEY_FRAME or
438 439 440 441
  // if the just encoded frame was resized. For SVC, copy source if the base
  // spatial layer was key frame.
  if (frame_type == KEY_FRAME || resized != 0 || denoiser->reset ||
      svc_base_is_key) {
Tim Kopp's avatar
Tim Kopp committed
442
    int i;
443
    // Start at 1 so as not to overwrite the INTRA_FRAME
444
    for (i = 1; i < denoiser->num_ref_frames; ++i)
445
      copy_frame(&denoiser->running_avg_y[i], &src);
446
    denoiser->reset = 0;
447 448 449
    return;
  }

450
  // If more than one refresh occurs, must copy frame buffer.
451
  if (refresh_golden_frame + refresh_last_frame + refresh_alt_ref_frame > 1) {
452
    if (refresh_golden_frame) {
453 454
      copy_frame(&denoiser->running_avg_y[GOLDEN_FRAME],
                 &denoiser->running_avg_y[INTRA_FRAME]);
455
    }
456 457 458 459
    // For fixed pattern SVC: update denoised last_frame if alt_ref is
    // refreshed, only for non-zero temporal layer.
    if (refresh_last_frame ||
        (refresh_alt_ref_frame && svc_fixed_pattern && temporal_layer_id > 0)) {
460 461
      copy_frame(&denoiser->running_avg_y[LAST_FRAME],
                 &denoiser->running_avg_y[INTRA_FRAME]);
462 463 464 465 466 467
    }
  } else {
    if (refresh_golden_frame) {
      swap_frame_buffer(&denoiser->running_avg_y[GOLDEN_FRAME],
                        &denoiser->running_avg_y[INTRA_FRAME]);
    }
468 469 470 471
    // For fixed pattern SVC: update denoised last_frame if alt_ref is
    // refreshed, only for non-zero temporal layer.
    if (refresh_last_frame ||
        (refresh_alt_ref_frame && svc_fixed_pattern && temporal_layer_id > 0)) {
472 473 474
      swap_frame_buffer(&denoiser->running_avg_y[LAST_FRAME],
                        &denoiser->running_avg_y[INTRA_FRAME]);
    }
475
  }
476 477 478 479 480 481 482 483 484 485
  // For fixed pattern SVC we need to keep track of denoised last_frame for base
  // temporal layer (since alt_ref refresh may update denoised last_frame on
  // the upper/middle temporal layers).We do this by copying the current
  // denoised last into the denoised golden_frame, for temporal_layer_id = 0.
  // For the fixed pattern SVC golden is always spatial reference and is never
  // used for denoising, so we can use it to keep track of denoised last_frame.
  if (svc_fixed_pattern && temporal_layer_id == 0) {
    copy_frame(&denoiser->running_avg_y[GOLDEN_FRAME],
               &denoiser->running_avg_y[LAST_FRAME]);
  }
486 487
}

488 489
void vp9_denoiser_reset_frame_stats(PICK_MODE_CONTEXT *ctx) {
  ctx->zeromv_sse = UINT_MAX;
Marco's avatar
Marco committed
490
  ctx->newmv_sse = UINT_MAX;
491
  ctx->zeromv_lastref_sse = UINT_MAX;
492
  ctx->best_sse_mv.as_int = 0;
493 494
}

495
void vp9_denoiser_update_frame_stats(MODE_INFO *mi, unsigned int sse,
496
                                     PREDICTION_MODE mode,
497
                                     PICK_MODE_CONTEXT *ctx) {
498
  if (mi->mv[0].as_int == 0 && sse < ctx->zeromv_sse) {
499
    ctx->zeromv_sse = sse;
500
    ctx->best_zeromv_reference_frame = mi->ref_frame[0];
501
    if (mi->ref_frame[0] == LAST_FRAME) ctx->zeromv_lastref_sse = sse;
502 503
  }

504
  if (mi->mv[0].as_int != 0 && sse < ctx->newmv_sse) {
505 506
    ctx->newmv_sse = sse;
    ctx->best_sse_inter_mode = mode;
507 508
    ctx->best_sse_mv = mi->mv[0];
    ctx->best_reference_frame = mi->ref_frame[0];
509
  }
510 511
}

512 513
int vp9_denoiser_alloc(VP9_COMMON *cm, int use_svc, VP9_DENOISER *denoiser,
                       int width, int height, int ssx, int ssy,
514 515 516 517
#if CONFIG_VP9_HIGHBITDEPTH
                       int use_highbitdepth,
#endif
                       int border) {
518
  int i, fail;
519
  const int legacy_byte_alignment = 0;
Tim Kopp's avatar
Tim Kopp committed
520
  assert(denoiser != NULL);
521

522 523 524 525 526
  denoiser->num_ref_frames = use_svc ? MAX_REF_FRAMES : NONSVC_REF_FRAMES;
  CHECK_MEM_ERROR(
      cm, denoiser->running_avg_y,
      vpx_calloc(denoiser->num_ref_frames, sizeof(denoiser->running_avg_y[0])));
  for (i = 0; i < denoiser->num_ref_frames; ++i) {
527
    fail = vpx_alloc_frame_buffer(&denoiser->running_avg_y[i], width, height,
528 529 530 531
                                  ssx, ssy,
#if CONFIG_VP9_HIGHBITDEPTH
                                  use_highbitdepth,
#endif
532
                                  border, legacy_byte_alignment);
533 534 535 536
    if (fail) {
      vp9_denoiser_free(denoiser);
      return 1;
    }
537 538 539
#ifdef OUTPUT_YUV_DENOISED
    make_grayscale(&denoiser->running_avg_y[i]);
#endif
540 541
  }

542 543
  fail = vpx_alloc_frame_buffer(&denoiser->mc_running_avg_y, width, height, ssx,
                                ssy,
544 545
#if CONFIG_VP9_HIGHBITDEPTH
                                use_highbitdepth,
546 547 548 549 550 551 552
#endif
                                border, legacy_byte_alignment);
  if (fail) {
    vp9_denoiser_free(denoiser);
    return 1;
  }

553
  fail = vpx_alloc_frame_buffer(&denoiser->last_source, width, height, ssx, ssy,
554 555
#if CONFIG_VP9_HIGHBITDEPTH
                                use_highbitdepth,
556
#endif
557
                                border, legacy_byte_alignment);
558
  if (fail) {
559 560 561
    vp9_denoiser_free(denoiser);
    return 1;
  }
562 563 564
#ifdef OUTPUT_YUV_DENOISED
  make_grayscale(&denoiser->running_avg_y[i]);
#endif
565
  denoiser->frame_buffer_initialized = 1;
566
  denoiser->denoising_level = kDenLow;
567 568
  denoiser->prev_denoising_level = kDenLow;
  denoiser->reset = 0;
569 570 571 572
  return 0;
}

void vp9_denoiser_free(VP9_DENOISER *denoiser) {
573
  int i;
Tim Kopp's avatar
Tim Kopp committed
574 575 576
  if (denoiser == NULL) {
    return;
  }
577
  denoiser->frame_buffer_initialized = 0;
578
  for (i = 0; i < denoiser->num_ref_frames; ++i) {
579
    vpx_free_frame_buffer(&denoiser->running_avg_y[i]);
580
  }
581 582
  vpx_free(denoiser->running_avg_y);
  denoiser->running_avg_y = NULL;
583
  vpx_free_frame_buffer(&denoiser->mc_running_avg_y);
584 585 586
  vpx_free_frame_buffer(&denoiser->last_source);
}

587
void vp9_denoiser_set_noise_level(VP9_DENOISER *denoiser, int noise_level) {
588
  denoiser->denoising_level = noise_level;
589 590 591 592 593 594
  if (denoiser->denoising_level > kDenLowLow &&
      denoiser->prev_denoising_level == kDenLowLow)
    denoiser->reset = 1;
  else
    denoiser->reset = 0;
  denoiser->prev_denoising_level = denoiser->denoising_level;
595
}
596

597
// Scale/increase the partition threshold for denoiser speed-up.
598
int64_t vp9_scale_part_thresh(int64_t threshold, VP9_DENOISER_LEVEL noise_level,
599
                              int content_state, int temporal_layer_id) {
600
  if ((content_state == kLowSadLowSumdiff) ||
601
      (content_state == kHighSadLowSumdiff) ||
602 603 604 605 606 607
      (content_state == kLowVarHighSumdiff) || (noise_level == kDenHigh) ||
      (temporal_layer_id != 0)) {
    int64_t scaled_thr =
        (temporal_layer_id < 2) ? (3 * threshold) >> 1 : (7 * threshold) >> 2;
    return scaled_thr;
  } else {
608
    return (5 * threshold) >> 2;
609
  }
610 611 612 613
}

//  Scale/increase the ac skip threshold for denoiser speed-up.
int64_t vp9_scale_acskip_thresh(int64_t threshold,
614 615
                                VP9_DENOISER_LEVEL noise_level, int abs_sumdiff,
                                int temporal_layer_id) {
616
  if (noise_level >= kDenLow && abs_sumdiff < 5)
617 618
    return threshold *=
           (noise_level == kDenLow) ? 2 : (temporal_layer_id == 2) ? 10 : 6;
619 620 621 622
  else
    return threshold;
}

623 624 625 626 627 628
#ifdef OUTPUT_YUV_DENOISED
static void make_grayscale(YV12_BUFFER_CONFIG *yuv) {
  int r, c;
  uint8_t *u = yuv->u_buffer;
  uint8_t *v = yuv->v_buffer;

629 630
  for (r = 0; r < yuv->uv_height; ++r) {
    for (c = 0; c < yuv->uv_width; ++c) {
631 632 633
      u[c] = UINT8_MAX / 2;
      v[c] = UINT8_MAX / 2;
    }
634 635
    u += yuv->uv_stride;
    v += yuv->uv_stride;
636 637 638
  }
}
#endif