• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include <assert.h>
12 #include <limits.h>
13 #include <math.h>
14 
15 #include "./vpx_dsp_rtcd.h"
16 #include "vpx_dsp/vpx_dsp_common.h"
17 #include "vpx_scale/yv12config.h"
18 #include "vpx/vpx_integer.h"
19 #include "vp9/common/vp9_reconinter.h"
20 #include "vp9/encoder/vp9_context_tree.h"
21 #include "vp9/encoder/vp9_denoiser.h"
22 #include "vp9/encoder/vp9_encoder.h"
23 
24 #ifdef OUTPUT_YUV_DENOISED
25 static void make_grayscale(YV12_BUFFER_CONFIG *yuv);
26 #endif
27 
absdiff_thresh(BLOCK_SIZE bs,int increase_denoising)28 static int absdiff_thresh(BLOCK_SIZE bs, int increase_denoising) {
29   (void)bs;
30   return 3 + (increase_denoising ? 1 : 0);
31 }
32 
delta_thresh(BLOCK_SIZE bs,int increase_denoising)33 static int delta_thresh(BLOCK_SIZE bs, int increase_denoising) {
34   (void)bs;
35   (void)increase_denoising;
36   return 4;
37 }
38 
noise_motion_thresh(BLOCK_SIZE bs,int increase_denoising)39 static int noise_motion_thresh(BLOCK_SIZE bs, int increase_denoising) {
40   (void)bs;
41   (void)increase_denoising;
42   return 625;
43 }
44 
sse_thresh(BLOCK_SIZE bs,int increase_denoising)45 static unsigned int sse_thresh(BLOCK_SIZE bs, int increase_denoising) {
46   return (1 << num_pels_log2_lookup[bs]) * (increase_denoising ? 80 : 40);
47 }
48 
sse_diff_thresh(BLOCK_SIZE bs,int increase_denoising,int motion_magnitude)49 static int sse_diff_thresh(BLOCK_SIZE bs, int increase_denoising,
50                            int motion_magnitude) {
51   if (motion_magnitude > noise_motion_thresh(bs, increase_denoising)) {
52     if (increase_denoising)
53       return (1 << num_pels_log2_lookup[bs]) << 2;
54     else
55       return 0;
56   } else {
57     return (1 << num_pels_log2_lookup[bs]) << 4;
58   }
59 }
60 
total_adj_weak_thresh(BLOCK_SIZE bs,int increase_denoising)61 static int total_adj_weak_thresh(BLOCK_SIZE bs, int increase_denoising) {
62   return (1 << num_pels_log2_lookup[bs]) * (increase_denoising ? 3 : 2);
63 }
64 
65 // TODO(jackychen): If increase_denoising is enabled in the future,
66 // we might need to update the code for calculating 'total_adj' in
67 // case the C code is not bit-exact with corresponding sse2 code.
vp9_denoiser_filter_c(const uint8_t * sig,int sig_stride,const uint8_t * mc_avg,int mc_avg_stride,uint8_t * avg,int avg_stride,int increase_denoising,BLOCK_SIZE bs,int motion_magnitude)68 int vp9_denoiser_filter_c(const uint8_t *sig, int sig_stride,
69                           const uint8_t *mc_avg, int mc_avg_stride,
70                           uint8_t *avg, int avg_stride, int increase_denoising,
71                           BLOCK_SIZE bs, int motion_magnitude) {
72   int r, c;
73   const uint8_t *sig_start = sig;
74   const uint8_t *mc_avg_start = mc_avg;
75   uint8_t *avg_start = avg;
76   int diff, adj, absdiff, delta;
77   int adj_val[] = { 3, 4, 6 };
78   int total_adj = 0;
79   int shift_inc = 1;
80 
81   // If motion_magnitude is small, making the denoiser more aggressive by
82   // increasing the adjustment for each level. Add another increment for
83   // blocks that are labeled for increase denoising.
84   if (motion_magnitude <= MOTION_MAGNITUDE_THRESHOLD) {
85     if (increase_denoising) {
86       shift_inc = 2;
87     }
88     adj_val[0] += shift_inc;
89     adj_val[1] += shift_inc;
90     adj_val[2] += shift_inc;
91   }
92 
93   // First attempt to apply a strong temporal denoising filter.
94   for (r = 0; r < (4 << b_height_log2_lookup[bs]); ++r) {
95     for (c = 0; c < (4 << b_width_log2_lookup[bs]); ++c) {
96       diff = mc_avg[c] - sig[c];
97       absdiff = abs(diff);
98 
99       if (absdiff <= absdiff_thresh(bs, increase_denoising)) {
100         avg[c] = mc_avg[c];
101         total_adj += diff;
102       } else {
103         switch (absdiff) {
104           case 4:
105           case 5:
106           case 6:
107           case 7: adj = adj_val[0]; break;
108           case 8:
109           case 9:
110           case 10:
111           case 11:
112           case 12:
113           case 13:
114           case 14:
115           case 15: adj = adj_val[1]; break;
116           default: adj = adj_val[2];
117         }
118         if (diff > 0) {
119           avg[c] = VPXMIN(UINT8_MAX, sig[c] + adj);
120           total_adj += adj;
121         } else {
122           avg[c] = VPXMAX(0, sig[c] - adj);
123           total_adj -= adj;
124         }
125       }
126     }
127     sig += sig_stride;
128     avg += avg_stride;
129     mc_avg += mc_avg_stride;
130   }
131 
132   // If the strong filter did not modify the signal too much, we're all set.
133   if (abs(total_adj) <= total_adj_strong_thresh(bs, increase_denoising)) {
134     return FILTER_BLOCK;
135   }
136 
137   // Otherwise, we try to dampen the filter if the delta is not too high.
138   delta = ((abs(total_adj) - total_adj_strong_thresh(bs, increase_denoising)) >>
139            num_pels_log2_lookup[bs]) +
140           1;
141 
142   if (delta >= delta_thresh(bs, increase_denoising)) {
143     return COPY_BLOCK;
144   }
145 
146   mc_avg = mc_avg_start;
147   avg = avg_start;
148   sig = sig_start;
149   for (r = 0; r < (4 << b_height_log2_lookup[bs]); ++r) {
150     for (c = 0; c < (4 << b_width_log2_lookup[bs]); ++c) {
151       diff = mc_avg[c] - sig[c];
152       adj = abs(diff);
153       if (adj > delta) {
154         adj = delta;
155       }
156       if (diff > 0) {
157         // Diff positive means we made positive adjustment above
158         // (in first try/attempt), so now make negative adjustment to bring
159         // denoised signal down.
160         avg[c] = VPXMAX(0, avg[c] - adj);
161         total_adj -= adj;
162       } else {
163         // Diff negative means we made negative adjustment above
164         // (in first try/attempt), so now make positive adjustment to bring
165         // denoised signal up.
166         avg[c] = VPXMIN(UINT8_MAX, avg[c] + adj);
167         total_adj += adj;
168       }
169     }
170     sig += sig_stride;
171     avg += avg_stride;
172     mc_avg += mc_avg_stride;
173   }
174 
175   // We can use the filter if it has been sufficiently dampened
176   if (abs(total_adj) <= total_adj_weak_thresh(bs, increase_denoising)) {
177     return FILTER_BLOCK;
178   }
179   return COPY_BLOCK;
180 }
181 
block_start(uint8_t * framebuf,int stride,int mi_row,int mi_col)182 static uint8_t *block_start(uint8_t *framebuf, int stride, int mi_row,
183                             int mi_col) {
184   return framebuf + (stride * mi_row << 3) + (mi_col << 3);
185 }
186 
perform_motion_compensation(VP9_COMMON * const cm,VP9_DENOISER * denoiser,MACROBLOCK * mb,BLOCK_SIZE bs,int increase_denoising,int mi_row,int mi_col,PICK_MODE_CONTEXT * ctx,int motion_magnitude,int is_skin,int * zeromv_filter,int consec_zeromv,int num_spatial_layers,int width,int lst_fb_idx,int gld_fb_idx,int use_svc,int spatial_layer,int use_gf_temporal_ref)187 static VP9_DENOISER_DECISION perform_motion_compensation(
188     VP9_COMMON *const cm, VP9_DENOISER *denoiser, MACROBLOCK *mb, BLOCK_SIZE bs,
189     int increase_denoising, int mi_row, int mi_col, PICK_MODE_CONTEXT *ctx,
190     int motion_magnitude, int is_skin, int *zeromv_filter, int consec_zeromv,
191     int num_spatial_layers, int width, int lst_fb_idx, int gld_fb_idx,
192     int use_svc, int spatial_layer, int use_gf_temporal_ref) {
193   const int sse_diff = (ctx->newmv_sse == UINT_MAX)
194                            ? 0
195                            : ((int)ctx->zeromv_sse - (int)ctx->newmv_sse);
196   int frame;
197   int denoise_layer_idx = 0;
198   MACROBLOCKD *filter_mbd = &mb->e_mbd;
199   MODE_INFO *mi = filter_mbd->mi[0];
200   MODE_INFO saved_mi;
201   int i;
202   struct buf_2d saved_dst[MAX_MB_PLANE];
203   struct buf_2d saved_pre[MAX_MB_PLANE];
204   RefBuffer *saved_block_refs[2];
205   MV_REFERENCE_FRAME saved_frame;
206 
207   frame = ctx->best_reference_frame;
208 
209   saved_mi = *mi;
210 
211   if (is_skin && (motion_magnitude > 0 || consec_zeromv < 4)) return COPY_BLOCK;
212 
213   // Avoid denoising small blocks. When noise > kDenLow or frame width > 480,
214   // denoise 16x16 blocks.
215   if (bs == BLOCK_8X8 || bs == BLOCK_8X16 || bs == BLOCK_16X8 ||
216       (bs == BLOCK_16X16 && width > 480 &&
217        denoiser->denoising_level <= kDenLow))
218     return COPY_BLOCK;
219 
220   // If the best reference frame uses inter-prediction and there is enough of a
221   // difference in sum-squared-error, use it.
222   if (frame != INTRA_FRAME && frame != ALTREF_FRAME &&
223       (frame != GOLDEN_FRAME || num_spatial_layers == 1 ||
224        use_gf_temporal_ref) &&
225       sse_diff > sse_diff_thresh(bs, increase_denoising, motion_magnitude)) {
226     mi->ref_frame[0] = ctx->best_reference_frame;
227     mi->mode = ctx->best_sse_inter_mode;
228     mi->mv[0] = ctx->best_sse_mv;
229   } else {
230     // Otherwise, use the zero reference frame.
231     frame = ctx->best_zeromv_reference_frame;
232     ctx->newmv_sse = ctx->zeromv_sse;
233     // Bias to last reference.
234     if ((num_spatial_layers > 1 && !use_gf_temporal_ref) ||
235         frame == ALTREF_FRAME ||
236         (frame != LAST_FRAME &&
237          ((ctx->zeromv_lastref_sse<(5 * ctx->zeromv_sse)>> 2) ||
238           denoiser->denoising_level >= kDenHigh))) {
239       frame = LAST_FRAME;
240       ctx->newmv_sse = ctx->zeromv_lastref_sse;
241     }
242     mi->ref_frame[0] = frame;
243     mi->mode = ZEROMV;
244     mi->mv[0].as_int = 0;
245     ctx->best_sse_inter_mode = ZEROMV;
246     ctx->best_sse_mv.as_int = 0;
247     *zeromv_filter = 1;
248     if (denoiser->denoising_level > kDenMedium) {
249       motion_magnitude = 0;
250     }
251   }
252 
253   saved_frame = frame;
254   // When using SVC, we need to map REF_FRAME to the frame buffer index.
255   if (use_svc) {
256     if (frame == LAST_FRAME)
257       frame = lst_fb_idx + 1;
258     else if (frame == GOLDEN_FRAME)
259       frame = gld_fb_idx + 1;
260     // Shift for the second spatial layer.
261     if (num_spatial_layers - spatial_layer == 2)
262       frame = frame + denoiser->num_ref_frames;
263     denoise_layer_idx = num_spatial_layers - spatial_layer - 1;
264   }
265 
266   // Force copy (no denoise, copy source in denoised buffer) if
267   // running_avg_y[frame] is NULL.
268   if (denoiser->running_avg_y[frame].buffer_alloc == NULL) {
269     // Restore everything to its original state
270     *mi = saved_mi;
271     return COPY_BLOCK;
272   }
273 
274   if (ctx->newmv_sse > sse_thresh(bs, increase_denoising)) {
275     // Restore everything to its original state
276     *mi = saved_mi;
277     return COPY_BLOCK;
278   }
279   if (motion_magnitude > (noise_motion_thresh(bs, increase_denoising) << 3)) {
280     // Restore everything to its original state
281     *mi = saved_mi;
282     return COPY_BLOCK;
283   }
284 
285   // We will restore these after motion compensation.
286   for (i = 0; i < MAX_MB_PLANE; ++i) {
287     saved_pre[i] = filter_mbd->plane[i].pre[0];
288     saved_dst[i] = filter_mbd->plane[i].dst;
289   }
290   saved_block_refs[0] = filter_mbd->block_refs[0];
291 
292   // Set the pointers in the MACROBLOCKD to point to the buffers in the denoiser
293   // struct.
294   filter_mbd->plane[0].pre[0].buf =
295       block_start(denoiser->running_avg_y[frame].y_buffer,
296                   denoiser->running_avg_y[frame].y_stride, mi_row, mi_col);
297   filter_mbd->plane[0].pre[0].stride = denoiser->running_avg_y[frame].y_stride;
298   filter_mbd->plane[1].pre[0].buf =
299       block_start(denoiser->running_avg_y[frame].u_buffer,
300                   denoiser->running_avg_y[frame].uv_stride, mi_row, mi_col);
301   filter_mbd->plane[1].pre[0].stride = denoiser->running_avg_y[frame].uv_stride;
302   filter_mbd->plane[2].pre[0].buf =
303       block_start(denoiser->running_avg_y[frame].v_buffer,
304                   denoiser->running_avg_y[frame].uv_stride, mi_row, mi_col);
305   filter_mbd->plane[2].pre[0].stride = denoiser->running_avg_y[frame].uv_stride;
306 
307   filter_mbd->plane[0].dst.buf = block_start(
308       denoiser->mc_running_avg_y[denoise_layer_idx].y_buffer,
309       denoiser->mc_running_avg_y[denoise_layer_idx].y_stride, mi_row, mi_col);
310   filter_mbd->plane[0].dst.stride =
311       denoiser->mc_running_avg_y[denoise_layer_idx].y_stride;
312   filter_mbd->plane[1].dst.buf = block_start(
313       denoiser->mc_running_avg_y[denoise_layer_idx].u_buffer,
314       denoiser->mc_running_avg_y[denoise_layer_idx].uv_stride, mi_row, mi_col);
315   filter_mbd->plane[1].dst.stride =
316       denoiser->mc_running_avg_y[denoise_layer_idx].uv_stride;
317   filter_mbd->plane[2].dst.buf = block_start(
318       denoiser->mc_running_avg_y[denoise_layer_idx].v_buffer,
319       denoiser->mc_running_avg_y[denoise_layer_idx].uv_stride, mi_row, mi_col);
320   filter_mbd->plane[2].dst.stride =
321       denoiser->mc_running_avg_y[denoise_layer_idx].uv_stride;
322 
323   set_ref_ptrs(cm, filter_mbd, saved_frame, NONE);
324   vp9_build_inter_predictors_sby(filter_mbd, mi_row, mi_col, bs);
325 
326   // Restore everything to its original state
327   *mi = saved_mi;
328   filter_mbd->block_refs[0] = saved_block_refs[0];
329   for (i = 0; i < MAX_MB_PLANE; ++i) {
330     filter_mbd->plane[i].pre[0] = saved_pre[i];
331     filter_mbd->plane[i].dst = saved_dst[i];
332   }
333 
334   return FILTER_BLOCK;
335 }
336 
vp9_denoiser_denoise(VP9_COMP * cpi,MACROBLOCK * mb,int mi_row,int mi_col,BLOCK_SIZE bs,PICK_MODE_CONTEXT * ctx,VP9_DENOISER_DECISION * denoiser_decision,int use_gf_temporal_ref)337 void vp9_denoiser_denoise(VP9_COMP *cpi, MACROBLOCK *mb, int mi_row, int mi_col,
338                           BLOCK_SIZE bs, PICK_MODE_CONTEXT *ctx,
339                           VP9_DENOISER_DECISION *denoiser_decision,
340                           int use_gf_temporal_ref) {
341   int mv_col, mv_row;
342   int motion_magnitude = 0;
343   int zeromv_filter = 0;
344   VP9_DENOISER *denoiser = &cpi->denoiser;
345   VP9_DENOISER_DECISION decision = COPY_BLOCK;
346 
347   const int shift =
348       cpi->svc.number_spatial_layers - cpi->svc.spatial_layer_id == 2
349           ? denoiser->num_ref_frames
350           : 0;
351   YV12_BUFFER_CONFIG avg = denoiser->running_avg_y[INTRA_FRAME + shift];
352   const int denoise_layer_index =
353       cpi->svc.number_spatial_layers - cpi->svc.spatial_layer_id - 1;
354   YV12_BUFFER_CONFIG mc_avg = denoiser->mc_running_avg_y[denoise_layer_index];
355   uint8_t *avg_start = block_start(avg.y_buffer, avg.y_stride, mi_row, mi_col);
356 
357   uint8_t *mc_avg_start =
358       block_start(mc_avg.y_buffer, mc_avg.y_stride, mi_row, mi_col);
359   struct buf_2d src = mb->plane[0].src;
360   int is_skin = 0;
361   int increase_denoising = 0;
362   int consec_zeromv = 0;
363   int last_is_reference = cpi->ref_frame_flags & VP9_LAST_FLAG;
364   mv_col = ctx->best_sse_mv.as_mv.col;
365   mv_row = ctx->best_sse_mv.as_mv.row;
366   motion_magnitude = mv_row * mv_row + mv_col * mv_col;
367 
368   if (cpi->use_skin_detection && bs <= BLOCK_32X32 &&
369       denoiser->denoising_level < kDenHigh) {
370     int motion_level = (motion_magnitude < 16) ? 0 : 1;
371     // If motion for current block is small/zero, compute consec_zeromv for
372     // skin detection (early exit in skin detection is done for large
373     // consec_zeromv when current block has small/zero motion).
374     consec_zeromv = 0;
375     if (motion_level == 0) {
376       VP9_COMMON *const cm = &cpi->common;
377       int j, i;
378       // Loop through the 8x8 sub-blocks.
379       const int bw = num_8x8_blocks_wide_lookup[bs];
380       const int bh = num_8x8_blocks_high_lookup[bs];
381       const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
382       const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
383       const int block_index = mi_row * cm->mi_cols + mi_col;
384       consec_zeromv = 100;
385       for (i = 0; i < ymis; i++) {
386         for (j = 0; j < xmis; j++) {
387           int bl_index = block_index + i * cm->mi_cols + j;
388           consec_zeromv = VPXMIN(cpi->consec_zero_mv[bl_index], consec_zeromv);
389           // No need to keep checking 8x8 blocks if any of the sub-blocks
390           // has small consec_zeromv (since threshold for no_skin based on
391           // zero/small motion in skin detection is high, i.e, > 4).
392           if (consec_zeromv < 4) {
393             i = ymis;
394             break;
395           }
396         }
397       }
398     }
399     // TODO(marpan): Compute skin detection over sub-blocks.
400     is_skin = vp9_compute_skin_block(
401         mb->plane[0].src.buf, mb->plane[1].src.buf, mb->plane[2].src.buf,
402         mb->plane[0].src.stride, mb->plane[1].src.stride, bs, consec_zeromv,
403         motion_level);
404   }
405   if (!is_skin && denoiser->denoising_level == kDenHigh) increase_denoising = 1;
406 
407   // Copy block if LAST_FRAME is not a reference.
408   // Last doesn't always exist when SVC layers are dynamically changed, e.g. top
409   // spatial layer doesn't have last reference when it's brought up for the
410   // first time on the fly.
411   if (last_is_reference && denoiser->denoising_level >= kDenLow &&
412       !ctx->sb_skip_denoising)
413     decision = perform_motion_compensation(
414         &cpi->common, denoiser, mb, bs, increase_denoising, mi_row, mi_col, ctx,
415         motion_magnitude, is_skin, &zeromv_filter, consec_zeromv,
416         cpi->svc.number_spatial_layers, cpi->Source->y_width, cpi->lst_fb_idx,
417         cpi->gld_fb_idx, cpi->use_svc, cpi->svc.spatial_layer_id,
418         use_gf_temporal_ref);
419 
420   if (decision == FILTER_BLOCK) {
421     decision = vp9_denoiser_filter(src.buf, src.stride, mc_avg_start,
422                                    mc_avg.y_stride, avg_start, avg.y_stride,
423                                    increase_denoising, bs, motion_magnitude);
424   }
425 
426   if (decision == FILTER_BLOCK) {
427     vpx_convolve_copy(avg_start, avg.y_stride, src.buf, src.stride, NULL, 0, 0,
428                       0, 0, num_4x4_blocks_wide_lookup[bs] << 2,
429                       num_4x4_blocks_high_lookup[bs] << 2);
430   } else {  // COPY_BLOCK
431     vpx_convolve_copy(src.buf, src.stride, avg_start, avg.y_stride, NULL, 0, 0,
432                       0, 0, num_4x4_blocks_wide_lookup[bs] << 2,
433                       num_4x4_blocks_high_lookup[bs] << 2);
434   }
435   *denoiser_decision = decision;
436   if (decision == FILTER_BLOCK && zeromv_filter == 1)
437     *denoiser_decision = FILTER_ZEROMV_BLOCK;
438 }
439 
copy_frame(YV12_BUFFER_CONFIG * const dest,const YV12_BUFFER_CONFIG * const src)440 static void copy_frame(YV12_BUFFER_CONFIG *const dest,
441                        const YV12_BUFFER_CONFIG *const src) {
442   int r;
443   const uint8_t *srcbuf = src->y_buffer;
444   uint8_t *destbuf = dest->y_buffer;
445 
446   assert(dest->y_width == src->y_width);
447   assert(dest->y_height == src->y_height);
448 
449   for (r = 0; r < dest->y_height; ++r) {
450     memcpy(destbuf, srcbuf, dest->y_width);
451     destbuf += dest->y_stride;
452     srcbuf += src->y_stride;
453   }
454 }
455 
swap_frame_buffer(YV12_BUFFER_CONFIG * const dest,YV12_BUFFER_CONFIG * const src)456 static void swap_frame_buffer(YV12_BUFFER_CONFIG *const dest,
457                               YV12_BUFFER_CONFIG *const src) {
458   uint8_t *tmp_buf = dest->y_buffer;
459   assert(dest->y_width == src->y_width);
460   assert(dest->y_height == src->y_height);
461   dest->y_buffer = src->y_buffer;
462   src->y_buffer = tmp_buf;
463 }
464 
vp9_denoiser_update_frame_info(VP9_DENOISER * denoiser,YV12_BUFFER_CONFIG src,struct SVC * svc,FRAME_TYPE frame_type,int refresh_alt_ref_frame,int refresh_golden_frame,int refresh_last_frame,int alt_fb_idx,int gld_fb_idx,int lst_fb_idx,int resized,int svc_refresh_denoiser_buffers,int second_spatial_layer)465 void vp9_denoiser_update_frame_info(
466     VP9_DENOISER *denoiser, YV12_BUFFER_CONFIG src, struct SVC *svc,
467     FRAME_TYPE frame_type, int refresh_alt_ref_frame, int refresh_golden_frame,
468     int refresh_last_frame, int alt_fb_idx, int gld_fb_idx, int lst_fb_idx,
469     int resized, int svc_refresh_denoiser_buffers, int second_spatial_layer) {
470   const int shift = second_spatial_layer ? denoiser->num_ref_frames : 0;
471   // Copy source into denoised reference buffers on KEY_FRAME or
472   // if the just encoded frame was resized. For SVC, copy source if the base
473   // spatial layer was key frame.
474   if (frame_type == KEY_FRAME || resized != 0 || denoiser->reset ||
475       svc_refresh_denoiser_buffers) {
476     int i;
477     // Start at 1 so as not to overwrite the INTRA_FRAME
478     for (i = 1; i < denoiser->num_ref_frames; ++i) {
479       if (denoiser->running_avg_y[i + shift].buffer_alloc != NULL)
480         copy_frame(&denoiser->running_avg_y[i + shift], &src);
481     }
482     denoiser->reset = 0;
483     return;
484   }
485 
486   if (svc->temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS &&
487       svc->use_set_ref_frame_config) {
488     int i;
489     for (i = 0; i < REF_FRAMES; i++) {
490       if (svc->update_buffer_slot[svc->spatial_layer_id] & (1 << i))
491         copy_frame(&denoiser->running_avg_y[i + 1 + shift],
492                    &denoiser->running_avg_y[INTRA_FRAME + shift]);
493     }
494   } else {
495     // If more than one refresh occurs, must copy frame buffer.
496     if ((refresh_alt_ref_frame + refresh_golden_frame + refresh_last_frame) >
497         1) {
498       if (refresh_alt_ref_frame) {
499         copy_frame(&denoiser->running_avg_y[alt_fb_idx + 1 + shift],
500                    &denoiser->running_avg_y[INTRA_FRAME + shift]);
501       }
502       if (refresh_golden_frame) {
503         copy_frame(&denoiser->running_avg_y[gld_fb_idx + 1 + shift],
504                    &denoiser->running_avg_y[INTRA_FRAME + shift]);
505       }
506       if (refresh_last_frame) {
507         copy_frame(&denoiser->running_avg_y[lst_fb_idx + 1 + shift],
508                    &denoiser->running_avg_y[INTRA_FRAME + shift]);
509       }
510     } else {
511       if (refresh_alt_ref_frame) {
512         swap_frame_buffer(&denoiser->running_avg_y[alt_fb_idx + 1 + shift],
513                           &denoiser->running_avg_y[INTRA_FRAME + shift]);
514       }
515       if (refresh_golden_frame) {
516         swap_frame_buffer(&denoiser->running_avg_y[gld_fb_idx + 1 + shift],
517                           &denoiser->running_avg_y[INTRA_FRAME + shift]);
518       }
519       if (refresh_last_frame) {
520         swap_frame_buffer(&denoiser->running_avg_y[lst_fb_idx + 1 + shift],
521                           &denoiser->running_avg_y[INTRA_FRAME + shift]);
522       }
523     }
524   }
525 }
526 
vp9_denoiser_reset_frame_stats(PICK_MODE_CONTEXT * ctx)527 void vp9_denoiser_reset_frame_stats(PICK_MODE_CONTEXT *ctx) {
528   ctx->zeromv_sse = UINT_MAX;
529   ctx->newmv_sse = UINT_MAX;
530   ctx->zeromv_lastref_sse = UINT_MAX;
531   ctx->best_sse_mv.as_int = 0;
532 }
533 
vp9_denoiser_update_frame_stats(MODE_INFO * mi,unsigned int sse,PREDICTION_MODE mode,PICK_MODE_CONTEXT * ctx)534 void vp9_denoiser_update_frame_stats(MODE_INFO *mi, unsigned int sse,
535                                      PREDICTION_MODE mode,
536                                      PICK_MODE_CONTEXT *ctx) {
537   if (mi->mv[0].as_int == 0 && sse < ctx->zeromv_sse) {
538     ctx->zeromv_sse = sse;
539     ctx->best_zeromv_reference_frame = mi->ref_frame[0];
540     if (mi->ref_frame[0] == LAST_FRAME) ctx->zeromv_lastref_sse = sse;
541   }
542 
543   if (mi->mv[0].as_int != 0 && sse < ctx->newmv_sse) {
544     ctx->newmv_sse = sse;
545     ctx->best_sse_inter_mode = mode;
546     ctx->best_sse_mv = mi->mv[0];
547     ctx->best_reference_frame = mi->ref_frame[0];
548   }
549 }
550 
vp9_denoiser_realloc_svc_helper(VP9_COMMON * cm,VP9_DENOISER * denoiser,int fb_idx)551 static int vp9_denoiser_realloc_svc_helper(VP9_COMMON *cm,
552                                            VP9_DENOISER *denoiser, int fb_idx) {
553   int fail = 0;
554   if (denoiser->running_avg_y[fb_idx].buffer_alloc == NULL) {
555     fail =
556         vpx_alloc_frame_buffer(&denoiser->running_avg_y[fb_idx], cm->width,
557                                cm->height, cm->subsampling_x, cm->subsampling_y,
558 #if CONFIG_VP9_HIGHBITDEPTH
559                                cm->use_highbitdepth,
560 #endif
561                                VP9_ENC_BORDER_IN_PIXELS, 0);
562     if (fail) {
563       vp9_denoiser_free(denoiser);
564       return 1;
565     }
566   }
567   return 0;
568 }
569 
vp9_denoiser_realloc_svc(VP9_COMMON * cm,VP9_DENOISER * denoiser,struct SVC * svc,int svc_buf_shift,int refresh_alt,int refresh_gld,int refresh_lst,int alt_fb_idx,int gld_fb_idx,int lst_fb_idx)570 int vp9_denoiser_realloc_svc(VP9_COMMON *cm, VP9_DENOISER *denoiser,
571                              struct SVC *svc, int svc_buf_shift,
572                              int refresh_alt, int refresh_gld, int refresh_lst,
573                              int alt_fb_idx, int gld_fb_idx, int lst_fb_idx) {
574   int fail = 0;
575   if (svc->temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS &&
576       svc->use_set_ref_frame_config) {
577     int i;
578     for (i = 0; i < REF_FRAMES; i++) {
579       if (cm->frame_type == KEY_FRAME ||
580           svc->update_buffer_slot[svc->spatial_layer_id] & (1 << i)) {
581         fail = vp9_denoiser_realloc_svc_helper(cm, denoiser,
582                                                i + 1 + svc_buf_shift);
583       }
584     }
585   } else {
586     if (refresh_alt) {
587       // Increase the frame buffer index by 1 to map it to the buffer index in
588       // the denoiser.
589       fail = vp9_denoiser_realloc_svc_helper(cm, denoiser,
590                                              alt_fb_idx + 1 + svc_buf_shift);
591       if (fail) return 1;
592     }
593     if (refresh_gld) {
594       fail = vp9_denoiser_realloc_svc_helper(cm, denoiser,
595                                              gld_fb_idx + 1 + svc_buf_shift);
596       if (fail) return 1;
597     }
598     if (refresh_lst) {
599       fail = vp9_denoiser_realloc_svc_helper(cm, denoiser,
600                                              lst_fb_idx + 1 + svc_buf_shift);
601       if (fail) return 1;
602     }
603   }
604   return 0;
605 }
606 
vp9_denoiser_alloc(VP9_COMMON * cm,struct SVC * svc,VP9_DENOISER * denoiser,int use_svc,int noise_sen,int width,int height,int ssx,int ssy,int use_highbitdepth,int border)607 int vp9_denoiser_alloc(VP9_COMMON *cm, struct SVC *svc, VP9_DENOISER *denoiser,
608                        int use_svc, int noise_sen, int width, int height,
609                        int ssx, int ssy,
610 #if CONFIG_VP9_HIGHBITDEPTH
611                        int use_highbitdepth,
612 #endif
613                        int border) {
614   int i, layer, fail, init_num_ref_frames;
615   const int legacy_byte_alignment = 0;
616   int num_layers = 1;
617   int scaled_width = width;
618   int scaled_height = height;
619   if (use_svc) {
620     LAYER_CONTEXT *lc = &svc->layer_context[svc->spatial_layer_id *
621                                                 svc->number_temporal_layers +
622                                             svc->temporal_layer_id];
623     get_layer_resolution(width, height, lc->scaling_factor_num,
624                          lc->scaling_factor_den, &scaled_width, &scaled_height);
625     // For SVC: only denoise at most 2 spatial (highest) layers.
626     if (noise_sen >= 2)
627       // Denoise from one spatial layer below the top.
628       svc->first_layer_denoise = VPXMAX(svc->number_spatial_layers - 2, 0);
629     else
630       // Only denoise the top spatial layer.
631       svc->first_layer_denoise = VPXMAX(svc->number_spatial_layers - 1, 0);
632     num_layers = svc->number_spatial_layers - svc->first_layer_denoise;
633   }
634   assert(denoiser != NULL);
635   denoiser->num_ref_frames = use_svc ? SVC_REF_FRAMES : NONSVC_REF_FRAMES;
636   init_num_ref_frames = use_svc ? MAX_REF_FRAMES : NONSVC_REF_FRAMES;
637   denoiser->num_layers = num_layers;
638   CHECK_MEM_ERROR(cm, denoiser->running_avg_y,
639                   vpx_calloc(denoiser->num_ref_frames * num_layers,
640                              sizeof(denoiser->running_avg_y[0])));
641   CHECK_MEM_ERROR(
642       cm, denoiser->mc_running_avg_y,
643       vpx_calloc(num_layers, sizeof(denoiser->mc_running_avg_y[0])));
644 
645   for (layer = 0; layer < num_layers; ++layer) {
646     const int denoise_width = (layer == 0) ? width : scaled_width;
647     const int denoise_height = (layer == 0) ? height : scaled_height;
648     for (i = 0; i < init_num_ref_frames; ++i) {
649       fail = vpx_alloc_frame_buffer(
650           &denoiser->running_avg_y[i + denoiser->num_ref_frames * layer],
651           denoise_width, denoise_height, ssx, ssy,
652 #if CONFIG_VP9_HIGHBITDEPTH
653           use_highbitdepth,
654 #endif
655           border, legacy_byte_alignment);
656       if (fail) {
657         vp9_denoiser_free(denoiser);
658         return 1;
659       }
660 #ifdef OUTPUT_YUV_DENOISED
661       make_grayscale(&denoiser->running_avg_y[i]);
662 #endif
663     }
664 
665     fail = vpx_alloc_frame_buffer(&denoiser->mc_running_avg_y[layer],
666                                   denoise_width, denoise_height, ssx, ssy,
667 #if CONFIG_VP9_HIGHBITDEPTH
668                                   use_highbitdepth,
669 #endif
670                                   border, legacy_byte_alignment);
671     if (fail) {
672       vp9_denoiser_free(denoiser);
673       return 1;
674     }
675   }
676 
677   // denoiser->last_source only used for noise_estimation, so only for top
678   // layer.
679   fail = vpx_alloc_frame_buffer(&denoiser->last_source, width, height, ssx, ssy,
680 #if CONFIG_VP9_HIGHBITDEPTH
681                                 use_highbitdepth,
682 #endif
683                                 border, legacy_byte_alignment);
684   if (fail) {
685     vp9_denoiser_free(denoiser);
686     return 1;
687   }
688 #ifdef OUTPUT_YUV_DENOISED
689   make_grayscale(&denoiser->running_avg_y[i]);
690 #endif
691   denoiser->frame_buffer_initialized = 1;
692   denoiser->denoising_level = kDenLow;
693   denoiser->prev_denoising_level = kDenLow;
694   denoiser->reset = 0;
695   denoiser->current_denoiser_frame = 0;
696   return 0;
697 }
698 
vp9_denoiser_free(VP9_DENOISER * denoiser)699 void vp9_denoiser_free(VP9_DENOISER *denoiser) {
700   int i;
701   if (denoiser == NULL) {
702     return;
703   }
704   denoiser->frame_buffer_initialized = 0;
705   for (i = 0; i < denoiser->num_ref_frames * denoiser->num_layers; ++i) {
706     vpx_free_frame_buffer(&denoiser->running_avg_y[i]);
707   }
708   vpx_free(denoiser->running_avg_y);
709   denoiser->running_avg_y = NULL;
710 
711   for (i = 0; i < denoiser->num_layers; ++i) {
712     vpx_free_frame_buffer(&denoiser->mc_running_avg_y[i]);
713   }
714 
715   vpx_free(denoiser->mc_running_avg_y);
716   denoiser->mc_running_avg_y = NULL;
717   vpx_free_frame_buffer(&denoiser->last_source);
718 }
719 
force_refresh_longterm_ref(VP9_COMP * const cpi)720 static void force_refresh_longterm_ref(VP9_COMP *const cpi) {
721   SVC *const svc = &cpi->svc;
722   // If long term reference is used, force refresh of that slot, so
723   // denoiser buffer for long term reference stays in sync.
724   if (svc->use_gf_temporal_ref_current_layer) {
725     int index = svc->spatial_layer_id;
726     if (svc->number_spatial_layers == 3) index = svc->spatial_layer_id - 1;
727     assert(index >= 0);
728     cpi->alt_fb_idx = svc->buffer_gf_temporal_ref[index].idx;
729     cpi->refresh_alt_ref_frame = 1;
730   }
731 }
732 
vp9_denoiser_set_noise_level(VP9_COMP * const cpi,int noise_level)733 void vp9_denoiser_set_noise_level(VP9_COMP *const cpi, int noise_level) {
734   VP9_DENOISER *const denoiser = &cpi->denoiser;
735   denoiser->denoising_level = noise_level;
736   if (denoiser->denoising_level > kDenLowLow &&
737       denoiser->prev_denoising_level == kDenLowLow) {
738     denoiser->reset = 1;
739     force_refresh_longterm_ref(cpi);
740   } else {
741     denoiser->reset = 0;
742   }
743   denoiser->prev_denoising_level = denoiser->denoising_level;
744 }
745 
746 // Scale/increase the partition threshold
747 // for denoiser speed-up.
vp9_scale_part_thresh(int64_t threshold,VP9_DENOISER_LEVEL noise_level,int content_state,int temporal_layer_id)748 int64_t vp9_scale_part_thresh(int64_t threshold, VP9_DENOISER_LEVEL noise_level,
749                               int content_state, int temporal_layer_id) {
750   if ((content_state == kLowSadLowSumdiff) ||
751       (content_state == kHighSadLowSumdiff) ||
752       (content_state == kLowVarHighSumdiff) || (noise_level == kDenHigh) ||
753       (temporal_layer_id != 0)) {
754     int64_t scaled_thr =
755         (temporal_layer_id < 2) ? (3 * threshold) >> 1 : (7 * threshold) >> 2;
756     return scaled_thr;
757   } else {
758     return (5 * threshold) >> 2;
759   }
760 }
761 
762 //  Scale/increase the ac skip threshold for
763 //  denoiser speed-up.
vp9_scale_acskip_thresh(int64_t threshold,VP9_DENOISER_LEVEL noise_level,int abs_sumdiff,int temporal_layer_id)764 int64_t vp9_scale_acskip_thresh(int64_t threshold,
765                                 VP9_DENOISER_LEVEL noise_level, int abs_sumdiff,
766                                 int temporal_layer_id) {
767   if (noise_level >= kDenLow && abs_sumdiff < 5)
768     return threshold *=
769            (noise_level == kDenLow) ? 2 : (temporal_layer_id == 2) ? 10 : 6;
770   else
771     return threshold;
772 }
773 
vp9_denoiser_reset_on_first_frame(VP9_COMP * const cpi)774 void vp9_denoiser_reset_on_first_frame(VP9_COMP *const cpi) {
775   if (vp9_denoise_svc_non_key(cpi) &&
776       cpi->denoiser.current_denoiser_frame == 0) {
777     cpi->denoiser.reset = 1;
778     force_refresh_longterm_ref(cpi);
779   }
780 }
781 
vp9_denoiser_update_ref_frame(VP9_COMP * const cpi)782 void vp9_denoiser_update_ref_frame(VP9_COMP *const cpi) {
783   VP9_COMMON *const cm = &cpi->common;
784   SVC *const svc = &cpi->svc;
785 
786   if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
787       cpi->denoiser.denoising_level > kDenLowLow) {
788     int svc_refresh_denoiser_buffers = 0;
789     int denoise_svc_second_layer = 0;
790     FRAME_TYPE frame_type = cm->intra_only ? KEY_FRAME : cm->frame_type;
791     cpi->denoiser.current_denoiser_frame++;
792     if (cpi->use_svc) {
793       const int svc_buf_shift =
794           svc->number_spatial_layers - svc->spatial_layer_id == 2
795               ? cpi->denoiser.num_ref_frames
796               : 0;
797       int layer =
798           LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
799                            svc->number_temporal_layers);
800       LAYER_CONTEXT *const lc = &svc->layer_context[layer];
801       svc_refresh_denoiser_buffers =
802           lc->is_key_frame || svc->spatial_layer_sync[svc->spatial_layer_id];
803       denoise_svc_second_layer =
804           svc->number_spatial_layers - svc->spatial_layer_id == 2 ? 1 : 0;
805       // Check if we need to allocate extra buffers in the denoiser
806       // for refreshed frames.
807       if (vp9_denoiser_realloc_svc(cm, &cpi->denoiser, svc, svc_buf_shift,
808                                    cpi->refresh_alt_ref_frame,
809                                    cpi->refresh_golden_frame,
810                                    cpi->refresh_last_frame, cpi->alt_fb_idx,
811                                    cpi->gld_fb_idx, cpi->lst_fb_idx))
812         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
813                            "Failed to re-allocate denoiser for SVC");
814     }
815     vp9_denoiser_update_frame_info(
816         &cpi->denoiser, *cpi->Source, svc, frame_type,
817         cpi->refresh_alt_ref_frame, cpi->refresh_golden_frame,
818         cpi->refresh_last_frame, cpi->alt_fb_idx, cpi->gld_fb_idx,
819         cpi->lst_fb_idx, cpi->resize_pending, svc_refresh_denoiser_buffers,
820         denoise_svc_second_layer);
821   }
822 }
823 
824 #ifdef OUTPUT_YUV_DENOISED
make_grayscale(YV12_BUFFER_CONFIG * yuv)825 static void make_grayscale(YV12_BUFFER_CONFIG *yuv) {
826   int r, c;
827   uint8_t *u = yuv->u_buffer;
828   uint8_t *v = yuv->v_buffer;
829 
830   for (r = 0; r < yuv->uv_height; ++r) {
831     for (c = 0; c < yuv->uv_width; ++c) {
832       u[c] = UINT8_MAX / 2;
833       v[c] = UINT8_MAX / 2;
834     }
835     u += yuv->uv_stride;
836     v += yuv->uv_stride;
837   }
838 }
839 #endif
840