• 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 <limits.h>
12 
13 #include "denoising.h"
14 
15 #include "vp8/common/reconinter.h"
16 #include "vpx/vpx_integer.h"
17 #include "vpx_mem/vpx_mem.h"
18 #include "vp8_rtcd.h"
19 
20 static const unsigned int NOISE_MOTION_THRESHOLD = 25 * 25;
21 /* SSE_DIFF_THRESHOLD is selected as ~95% confidence assuming
22  * var(noise) ~= 100.
23  */
24 static const unsigned int SSE_DIFF_THRESHOLD = 16 * 16 * 20;
25 static const unsigned int SSE_THRESHOLD = 16 * 16 * 40;
26 static const unsigned int SSE_THRESHOLD_HIGH = 16 * 16 * 80;
27 
28 /*
29  * The filter function was modified to reduce the computational complexity.
30  * Step 1:
31  * Instead of applying tap coefficients for each pixel, we calculated the
32  * pixel adjustments vs. pixel diff value ahead of time.
33  *     adjustment = filtered_value - current_raw
34  *                = (filter_coefficient * diff + 128) >> 8
35  * where
36  *     filter_coefficient = (255 << 8) / (256 + ((absdiff * 330) >> 3));
37  *     filter_coefficient += filter_coefficient /
38  *                           (3 + motion_magnitude_adjustment);
39  *     filter_coefficient is clamped to 0 ~ 255.
40  *
41  * Step 2:
42  * The adjustment vs. diff curve becomes flat very quick when diff increases.
43  * This allowed us to use only several levels to approximate the curve without
44  * changing the filtering algorithm too much.
45  * The adjustments were further corrected by checking the motion magnitude.
46  * The levels used are:
47  * diff       adjustment w/o motion correction   adjustment w/ motion correction
48  * [-255, -16]           -6                                   -7
49  * [-15, -8]             -4                                   -5
50  * [-7, -4]              -3                                   -4
51  * [-3, 3]               diff                                 diff
52  * [4, 7]                 3                                    4
53  * [8, 15]                4                                    5
54  * [16, 255]              6                                    7
55  */
56 
vp8_denoiser_filter_c(unsigned char * mc_running_avg_y,int mc_avg_y_stride,unsigned char * running_avg_y,int avg_y_stride,unsigned char * sig,int sig_stride,unsigned int motion_magnitude,int increase_denoising)57 int vp8_denoiser_filter_c(unsigned char *mc_running_avg_y, int mc_avg_y_stride,
58                           unsigned char *running_avg_y, int avg_y_stride,
59                           unsigned char *sig, int sig_stride,
60                           unsigned int motion_magnitude,
61                           int increase_denoising) {
62   unsigned char *running_avg_y_start = running_avg_y;
63   unsigned char *sig_start = sig;
64   int sum_diff_thresh;
65   int r, c;
66   int sum_diff = 0;
67   int adj_val[3] = { 3, 4, 6 };
68   int shift_inc1 = 0;
69   int shift_inc2 = 1;
70   int col_sum[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
71   /* If motion_magnitude is small, making the denoiser more aggressive by
72    * increasing the adjustment for each level. Add another increment for
73    * blocks that are labeled for increase denoising. */
74   if (motion_magnitude <= MOTION_MAGNITUDE_THRESHOLD) {
75     if (increase_denoising) {
76       shift_inc1 = 1;
77       shift_inc2 = 2;
78     }
79     adj_val[0] += shift_inc2;
80     adj_val[1] += shift_inc2;
81     adj_val[2] += shift_inc2;
82   }
83 
84   for (r = 0; r < 16; ++r) {
85     for (c = 0; c < 16; ++c) {
86       int diff = 0;
87       int adjustment = 0;
88       int absdiff = 0;
89 
90       diff = mc_running_avg_y[c] - sig[c];
91       absdiff = abs(diff);
92 
93       // When |diff| <= |3 + shift_inc1|, use pixel value from
94       // last denoised raw.
95       if (absdiff <= 3 + shift_inc1) {
96         running_avg_y[c] = mc_running_avg_y[c];
97         col_sum[c] += diff;
98       } else {
99         if (absdiff >= 4 + shift_inc1 && absdiff <= 7) {
100           adjustment = adj_val[0];
101         } else if (absdiff >= 8 && absdiff <= 15) {
102           adjustment = adj_val[1];
103         } else {
104           adjustment = adj_val[2];
105         }
106 
107         if (diff > 0) {
108           if ((sig[c] + adjustment) > 255) {
109             running_avg_y[c] = 255;
110           } else {
111             running_avg_y[c] = sig[c] + adjustment;
112           }
113 
114           col_sum[c] += adjustment;
115         } else {
116           if ((sig[c] - adjustment) < 0) {
117             running_avg_y[c] = 0;
118           } else {
119             running_avg_y[c] = sig[c] - adjustment;
120           }
121 
122           col_sum[c] -= adjustment;
123         }
124       }
125     }
126 
127     /* Update pointers for next iteration. */
128     sig += sig_stride;
129     mc_running_avg_y += mc_avg_y_stride;
130     running_avg_y += avg_y_stride;
131   }
132 
133   for (c = 0; c < 16; ++c) {
134     // Below we clip the value in the same way which SSE code use.
135     // When adopting aggressive denoiser, the adj_val for each pixel
136     // could be at most 8 (this is current max adjustment of the map).
137     // In SSE code, we calculate the sum of adj_val for
138     // the columns, so the sum could be upto 128(16 rows). However,
139     // the range of the value is -128 ~ 127 in SSE code, that's why
140     // we do this change in C code.
141     // We don't do this for UV denoiser, since there are only 8 rows,
142     // and max adjustments <= 8, so the sum of the columns will not
143     // exceed 64.
144     if (col_sum[c] >= 128) {
145       col_sum[c] = 127;
146     }
147     sum_diff += col_sum[c];
148   }
149 
150   sum_diff_thresh = SUM_DIFF_THRESHOLD;
151   if (increase_denoising) sum_diff_thresh = SUM_DIFF_THRESHOLD_HIGH;
152   if (abs(sum_diff) > sum_diff_thresh) {
153     // Before returning to copy the block (i.e., apply no denoising), check
154     // if we can still apply some (weaker) temporal filtering to this block,
155     // that would otherwise not be denoised at all. Simplest is to apply
156     // an additional adjustment to running_avg_y to bring it closer to sig.
157     // The adjustment is capped by a maximum delta, and chosen such that
158     // in most cases the resulting sum_diff will be within the
159     // accceptable range given by sum_diff_thresh.
160 
161     // The delta is set by the excess of absolute pixel diff over threshold.
162     int delta = ((abs(sum_diff) - sum_diff_thresh) >> 8) + 1;
163     // Only apply the adjustment for max delta up to 3.
164     if (delta < 4) {
165       sig -= sig_stride * 16;
166       mc_running_avg_y -= mc_avg_y_stride * 16;
167       running_avg_y -= avg_y_stride * 16;
168       for (r = 0; r < 16; ++r) {
169         for (c = 0; c < 16; ++c) {
170           int diff = mc_running_avg_y[c] - sig[c];
171           int adjustment = abs(diff);
172           if (adjustment > delta) adjustment = delta;
173           if (diff > 0) {
174             // Bring denoised signal down.
175             if (running_avg_y[c] - adjustment < 0) {
176               running_avg_y[c] = 0;
177             } else {
178               running_avg_y[c] = running_avg_y[c] - adjustment;
179             }
180             col_sum[c] -= adjustment;
181           } else if (diff < 0) {
182             // Bring denoised signal up.
183             if (running_avg_y[c] + adjustment > 255) {
184               running_avg_y[c] = 255;
185             } else {
186               running_avg_y[c] = running_avg_y[c] + adjustment;
187             }
188             col_sum[c] += adjustment;
189           }
190         }
191         // TODO(marpan): Check here if abs(sum_diff) has gone below the
192         // threshold sum_diff_thresh, and if so, we can exit the row loop.
193         sig += sig_stride;
194         mc_running_avg_y += mc_avg_y_stride;
195         running_avg_y += avg_y_stride;
196       }
197 
198       sum_diff = 0;
199       for (c = 0; c < 16; ++c) {
200         if (col_sum[c] >= 128) {
201           col_sum[c] = 127;
202         }
203         sum_diff += col_sum[c];
204       }
205 
206       if (abs(sum_diff) > sum_diff_thresh) return COPY_BLOCK;
207     } else {
208       return COPY_BLOCK;
209     }
210   }
211 
212   vp8_copy_mem16x16(running_avg_y_start, avg_y_stride, sig_start, sig_stride);
213   return FILTER_BLOCK;
214 }
215 
vp8_denoiser_filter_uv_c(unsigned char * mc_running_avg_uv,int mc_avg_uv_stride,unsigned char * running_avg_uv,int avg_uv_stride,unsigned char * sig,int sig_stride,unsigned int motion_magnitude,int increase_denoising)216 int vp8_denoiser_filter_uv_c(unsigned char *mc_running_avg_uv,
217                              int mc_avg_uv_stride,
218                              unsigned char *running_avg_uv, int avg_uv_stride,
219                              unsigned char *sig, int sig_stride,
220                              unsigned int motion_magnitude,
221                              int increase_denoising) {
222   unsigned char *running_avg_uv_start = running_avg_uv;
223   unsigned char *sig_start = sig;
224   int sum_diff_thresh;
225   int r, c;
226   int sum_diff = 0;
227   int sum_block = 0;
228   int adj_val[3] = { 3, 4, 6 };
229   int shift_inc1 = 0;
230   int shift_inc2 = 1;
231   /* If motion_magnitude is small, making the denoiser more aggressive by
232    * increasing the adjustment for each level. Add another increment for
233    * blocks that are labeled for increase denoising. */
234   if (motion_magnitude <= MOTION_MAGNITUDE_THRESHOLD_UV) {
235     if (increase_denoising) {
236       shift_inc1 = 1;
237       shift_inc2 = 2;
238     }
239     adj_val[0] += shift_inc2;
240     adj_val[1] += shift_inc2;
241     adj_val[2] += shift_inc2;
242   }
243 
244   // Avoid denoising color signal if its close to average level.
245   for (r = 0; r < 8; ++r) {
246     for (c = 0; c < 8; ++c) {
247       sum_block += sig[c];
248     }
249     sig += sig_stride;
250   }
251   if (abs(sum_block - (128 * 8 * 8)) < SUM_DIFF_FROM_AVG_THRESH_UV) {
252     return COPY_BLOCK;
253   }
254 
255   sig -= sig_stride * 8;
256   for (r = 0; r < 8; ++r) {
257     for (c = 0; c < 8; ++c) {
258       int diff = 0;
259       int adjustment = 0;
260       int absdiff = 0;
261 
262       diff = mc_running_avg_uv[c] - sig[c];
263       absdiff = abs(diff);
264 
265       // When |diff| <= |3 + shift_inc1|, use pixel value from
266       // last denoised raw.
267       if (absdiff <= 3 + shift_inc1) {
268         running_avg_uv[c] = mc_running_avg_uv[c];
269         sum_diff += diff;
270       } else {
271         if (absdiff >= 4 && absdiff <= 7) {
272           adjustment = adj_val[0];
273         } else if (absdiff >= 8 && absdiff <= 15) {
274           adjustment = adj_val[1];
275         } else {
276           adjustment = adj_val[2];
277         }
278         if (diff > 0) {
279           if ((sig[c] + adjustment) > 255) {
280             running_avg_uv[c] = 255;
281           } else {
282             running_avg_uv[c] = sig[c] + adjustment;
283           }
284           sum_diff += adjustment;
285         } else {
286           if ((sig[c] - adjustment) < 0) {
287             running_avg_uv[c] = 0;
288           } else {
289             running_avg_uv[c] = sig[c] - adjustment;
290           }
291           sum_diff -= adjustment;
292         }
293       }
294     }
295     /* Update pointers for next iteration. */
296     sig += sig_stride;
297     mc_running_avg_uv += mc_avg_uv_stride;
298     running_avg_uv += avg_uv_stride;
299   }
300 
301   sum_diff_thresh = SUM_DIFF_THRESHOLD_UV;
302   if (increase_denoising) sum_diff_thresh = SUM_DIFF_THRESHOLD_HIGH_UV;
303   if (abs(sum_diff) > sum_diff_thresh) {
304     // Before returning to copy the block (i.e., apply no denoising), check
305     // if we can still apply some (weaker) temporal filtering to this block,
306     // that would otherwise not be denoised at all. Simplest is to apply
307     // an additional adjustment to running_avg_y to bring it closer to sig.
308     // The adjustment is capped by a maximum delta, and chosen such that
309     // in most cases the resulting sum_diff will be within the
310     // accceptable range given by sum_diff_thresh.
311 
312     // The delta is set by the excess of absolute pixel diff over threshold.
313     int delta = ((abs(sum_diff) - sum_diff_thresh) >> 8) + 1;
314     // Only apply the adjustment for max delta up to 3.
315     if (delta < 4) {
316       sig -= sig_stride * 8;
317       mc_running_avg_uv -= mc_avg_uv_stride * 8;
318       running_avg_uv -= avg_uv_stride * 8;
319       for (r = 0; r < 8; ++r) {
320         for (c = 0; c < 8; ++c) {
321           int diff = mc_running_avg_uv[c] - sig[c];
322           int adjustment = abs(diff);
323           if (adjustment > delta) adjustment = delta;
324           if (diff > 0) {
325             // Bring denoised signal down.
326             if (running_avg_uv[c] - adjustment < 0) {
327               running_avg_uv[c] = 0;
328             } else {
329               running_avg_uv[c] = running_avg_uv[c] - adjustment;
330             }
331             sum_diff -= adjustment;
332           } else if (diff < 0) {
333             // Bring denoised signal up.
334             if (running_avg_uv[c] + adjustment > 255) {
335               running_avg_uv[c] = 255;
336             } else {
337               running_avg_uv[c] = running_avg_uv[c] + adjustment;
338             }
339             sum_diff += adjustment;
340           }
341         }
342         // TODO(marpan): Check here if abs(sum_diff) has gone below the
343         // threshold sum_diff_thresh, and if so, we can exit the row loop.
344         sig += sig_stride;
345         mc_running_avg_uv += mc_avg_uv_stride;
346         running_avg_uv += avg_uv_stride;
347       }
348       if (abs(sum_diff) > sum_diff_thresh) return COPY_BLOCK;
349     } else {
350       return COPY_BLOCK;
351     }
352   }
353 
354   vp8_copy_mem8x8(running_avg_uv_start, avg_uv_stride, sig_start, sig_stride);
355   return FILTER_BLOCK;
356 }
357 
vp8_denoiser_set_parameters(VP8_DENOISER * denoiser,int mode)358 void vp8_denoiser_set_parameters(VP8_DENOISER *denoiser, int mode) {
359   assert(mode > 0);  // Denoiser is allocated only if mode > 0.
360   if (mode == 1) {
361     denoiser->denoiser_mode = kDenoiserOnYOnly;
362   } else if (mode == 2) {
363     denoiser->denoiser_mode = kDenoiserOnYUV;
364   } else if (mode == 3) {
365     denoiser->denoiser_mode = kDenoiserOnYUVAggressive;
366   } else {
367     denoiser->denoiser_mode = kDenoiserOnYUV;
368   }
369   if (denoiser->denoiser_mode != kDenoiserOnYUVAggressive) {
370     denoiser->denoise_pars.scale_sse_thresh = 1;
371     denoiser->denoise_pars.scale_motion_thresh = 8;
372     denoiser->denoise_pars.scale_increase_filter = 0;
373     denoiser->denoise_pars.denoise_mv_bias = 95;
374     denoiser->denoise_pars.pickmode_mv_bias = 100;
375     denoiser->denoise_pars.qp_thresh = 0;
376     denoiser->denoise_pars.consec_zerolast = UINT_MAX;
377     denoiser->denoise_pars.spatial_blur = 0;
378   } else {
379     denoiser->denoise_pars.scale_sse_thresh = 2;
380     denoiser->denoise_pars.scale_motion_thresh = 16;
381     denoiser->denoise_pars.scale_increase_filter = 1;
382     denoiser->denoise_pars.denoise_mv_bias = 60;
383     denoiser->denoise_pars.pickmode_mv_bias = 75;
384     denoiser->denoise_pars.qp_thresh = 80;
385     denoiser->denoise_pars.consec_zerolast = 15;
386     denoiser->denoise_pars.spatial_blur = 0;
387   }
388 }
389 
vp8_denoiser_allocate(VP8_DENOISER * denoiser,int width,int height,int num_mb_rows,int num_mb_cols,int mode)390 int vp8_denoiser_allocate(VP8_DENOISER *denoiser, int width, int height,
391                           int num_mb_rows, int num_mb_cols, int mode) {
392   int i;
393   assert(denoiser);
394   denoiser->num_mb_cols = num_mb_cols;
395 
396   for (i = 0; i < MAX_REF_FRAMES; ++i) {
397     denoiser->yv12_running_avg[i].flags = 0;
398 
399     if (vp8_yv12_alloc_frame_buffer(&(denoiser->yv12_running_avg[i]), width,
400                                     height, VP8BORDERINPIXELS) < 0) {
401       vp8_denoiser_free(denoiser);
402       return 1;
403     }
404     memset(denoiser->yv12_running_avg[i].buffer_alloc, 0,
405            denoiser->yv12_running_avg[i].frame_size);
406   }
407   denoiser->yv12_mc_running_avg.flags = 0;
408 
409   if (vp8_yv12_alloc_frame_buffer(&(denoiser->yv12_mc_running_avg), width,
410                                   height, VP8BORDERINPIXELS) < 0) {
411     vp8_denoiser_free(denoiser);
412     return 1;
413   }
414 
415   memset(denoiser->yv12_mc_running_avg.buffer_alloc, 0,
416          denoiser->yv12_mc_running_avg.frame_size);
417 
418   if (vp8_yv12_alloc_frame_buffer(&denoiser->yv12_last_source, width, height,
419                                   VP8BORDERINPIXELS) < 0) {
420     vp8_denoiser_free(denoiser);
421     return 1;
422   }
423   memset(denoiser->yv12_last_source.buffer_alloc, 0,
424          denoiser->yv12_last_source.frame_size);
425 
426   denoiser->denoise_state = vpx_calloc((num_mb_rows * num_mb_cols), 1);
427   if (!denoiser->denoise_state) {
428     vp8_denoiser_free(denoiser);
429     return 1;
430   }
431   memset(denoiser->denoise_state, 0, (num_mb_rows * num_mb_cols));
432   vp8_denoiser_set_parameters(denoiser, mode);
433   denoiser->nmse_source_diff = 0;
434   denoiser->nmse_source_diff_count = 0;
435   denoiser->qp_avg = 0;
436   // QP threshold below which we can go up to aggressive mode.
437   denoiser->qp_threshold_up = 80;
438   // QP threshold above which we can go back down to normal mode.
439   // For now keep this second threshold high, so not used currently.
440   denoiser->qp_threshold_down = 128;
441   // Bitrate thresholds and noise metric (nmse) thresholds for switching to
442   // aggressive mode.
443   // TODO(marpan): Adjust thresholds, including effect on resolution.
444   denoiser->bitrate_threshold = 400000;  // (bits/sec).
445   denoiser->threshold_aggressive_mode = 80;
446   if (width * height > 1280 * 720) {
447     denoiser->bitrate_threshold = 3000000;
448     denoiser->threshold_aggressive_mode = 200;
449   } else if (width * height > 960 * 540) {
450     denoiser->bitrate_threshold = 1200000;
451     denoiser->threshold_aggressive_mode = 120;
452   } else if (width * height > 640 * 480) {
453     denoiser->bitrate_threshold = 600000;
454     denoiser->threshold_aggressive_mode = 100;
455   }
456   return 0;
457 }
458 
vp8_denoiser_free(VP8_DENOISER * denoiser)459 void vp8_denoiser_free(VP8_DENOISER *denoiser) {
460   int i;
461   assert(denoiser);
462 
463   for (i = 0; i < MAX_REF_FRAMES; ++i) {
464     vp8_yv12_de_alloc_frame_buffer(&denoiser->yv12_running_avg[i]);
465   }
466   vp8_yv12_de_alloc_frame_buffer(&denoiser->yv12_mc_running_avg);
467   vp8_yv12_de_alloc_frame_buffer(&denoiser->yv12_last_source);
468   vpx_free(denoiser->denoise_state);
469 }
470 
vp8_denoiser_denoise_mb(VP8_DENOISER * denoiser,MACROBLOCK * x,unsigned int best_sse,unsigned int zero_mv_sse,int recon_yoffset,int recon_uvoffset,loop_filter_info_n * lfi_n,int mb_row,int mb_col,int block_index,int consec_zero_last)471 void vp8_denoiser_denoise_mb(VP8_DENOISER *denoiser, MACROBLOCK *x,
472                              unsigned int best_sse, unsigned int zero_mv_sse,
473                              int recon_yoffset, int recon_uvoffset,
474                              loop_filter_info_n *lfi_n, int mb_row, int mb_col,
475                              int block_index, int consec_zero_last)
476 
477 {
478   int mv_row;
479   int mv_col;
480   unsigned int motion_threshold;
481   unsigned int motion_magnitude2;
482   unsigned int sse_thresh;
483   int sse_diff_thresh = 0;
484   // Spatial loop filter: only applied selectively based on
485   // temporal filter state of block relative to top/left neighbors.
486   int apply_spatial_loop_filter = 1;
487   MV_REFERENCE_FRAME frame = x->best_reference_frame;
488   MV_REFERENCE_FRAME zero_frame = x->best_zeromv_reference_frame;
489 
490   enum vp8_denoiser_decision decision = FILTER_BLOCK;
491   enum vp8_denoiser_decision decision_u = COPY_BLOCK;
492   enum vp8_denoiser_decision decision_v = COPY_BLOCK;
493 
494   if (zero_frame) {
495     YV12_BUFFER_CONFIG *src = &denoiser->yv12_running_avg[frame];
496     YV12_BUFFER_CONFIG *dst = &denoiser->yv12_mc_running_avg;
497     YV12_BUFFER_CONFIG saved_pre, saved_dst;
498     MB_MODE_INFO saved_mbmi;
499     MACROBLOCKD *filter_xd = &x->e_mbd;
500     MB_MODE_INFO *mbmi = &filter_xd->mode_info_context->mbmi;
501     int sse_diff = 0;
502     // Bias on zero motion vector sse.
503     const int zero_bias = denoiser->denoise_pars.denoise_mv_bias;
504     zero_mv_sse = (unsigned int)((int64_t)zero_mv_sse * zero_bias / 100);
505     sse_diff = (int)zero_mv_sse - (int)best_sse;
506 
507     saved_mbmi = *mbmi;
508 
509     /* Use the best MV for the compensation. */
510     mbmi->ref_frame = x->best_reference_frame;
511     mbmi->mode = x->best_sse_inter_mode;
512     mbmi->mv = x->best_sse_mv;
513     mbmi->need_to_clamp_mvs = x->need_to_clamp_best_mvs;
514     mv_col = x->best_sse_mv.as_mv.col;
515     mv_row = x->best_sse_mv.as_mv.row;
516     // Bias to zero_mv if small amount of motion.
517     // Note sse_diff_thresh is intialized to zero, so this ensures
518     // we will always choose zero_mv for denoising if
519     // zero_mv_see <= best_sse (i.e., sse_diff <= 0).
520     if ((unsigned int)(mv_row * mv_row + mv_col * mv_col) <=
521         NOISE_MOTION_THRESHOLD) {
522       sse_diff_thresh = (int)SSE_DIFF_THRESHOLD;
523     }
524 
525     if (frame == INTRA_FRAME || sse_diff <= sse_diff_thresh) {
526       /*
527        * Handle intra blocks as referring to last frame with zero motion
528        * and let the absolute pixel difference affect the filter factor.
529        * Also consider small amount of motion as being random walk due
530        * to noise, if it doesn't mean that we get a much bigger error.
531        * Note that any changes to the mode info only affects the
532        * denoising.
533        */
534       x->denoise_zeromv = 1;
535       mbmi->ref_frame = x->best_zeromv_reference_frame;
536 
537       src = &denoiser->yv12_running_avg[zero_frame];
538 
539       mbmi->mode = ZEROMV;
540       mbmi->mv.as_int = 0;
541       x->best_sse_inter_mode = ZEROMV;
542       x->best_sse_mv.as_int = 0;
543       best_sse = zero_mv_sse;
544     }
545 
546     mv_row = x->best_sse_mv.as_mv.row;
547     mv_col = x->best_sse_mv.as_mv.col;
548     motion_magnitude2 = mv_row * mv_row + mv_col * mv_col;
549     motion_threshold =
550         denoiser->denoise_pars.scale_motion_thresh * NOISE_MOTION_THRESHOLD;
551 
552     if (motion_magnitude2 <
553         denoiser->denoise_pars.scale_increase_filter * NOISE_MOTION_THRESHOLD) {
554       x->increase_denoising = 1;
555     }
556 
557     sse_thresh = denoiser->denoise_pars.scale_sse_thresh * SSE_THRESHOLD;
558     if (x->increase_denoising) {
559       sse_thresh = denoiser->denoise_pars.scale_sse_thresh * SSE_THRESHOLD_HIGH;
560     }
561 
562     if (best_sse > sse_thresh || motion_magnitude2 > motion_threshold) {
563       decision = COPY_BLOCK;
564     }
565 
566     // If block is considered skin, don't denoise if the block
567     // (1) is selected as non-zero motion for current frame, or
568     // (2) has not been selected as ZERO_LAST mode at least x past frames
569     // in a row.
570     // TODO(marpan): Parameter "x" should be varied with framerate.
571     // In particualar, should be reduced for layers (base layer/LAST).
572     if (x->is_skin && (consec_zero_last < 2 || motion_magnitude2 > 0)) {
573       decision = COPY_BLOCK;
574     }
575 
576     if (decision == FILTER_BLOCK) {
577       saved_pre = filter_xd->pre;
578       saved_dst = filter_xd->dst;
579 
580       /* Compensate the running average. */
581       filter_xd->pre.y_buffer = src->y_buffer + recon_yoffset;
582       filter_xd->pre.u_buffer = src->u_buffer + recon_uvoffset;
583       filter_xd->pre.v_buffer = src->v_buffer + recon_uvoffset;
584       /* Write the compensated running average to the destination buffer. */
585       filter_xd->dst.y_buffer = dst->y_buffer + recon_yoffset;
586       filter_xd->dst.u_buffer = dst->u_buffer + recon_uvoffset;
587       filter_xd->dst.v_buffer = dst->v_buffer + recon_uvoffset;
588 
589       if (!x->skip) {
590         vp8_build_inter_predictors_mb(filter_xd);
591       } else {
592         vp8_build_inter16x16_predictors_mb(
593             filter_xd, filter_xd->dst.y_buffer, filter_xd->dst.u_buffer,
594             filter_xd->dst.v_buffer, filter_xd->dst.y_stride,
595             filter_xd->dst.uv_stride);
596       }
597       filter_xd->pre = saved_pre;
598       filter_xd->dst = saved_dst;
599       *mbmi = saved_mbmi;
600     }
601   } else {
602     // zero_frame should always be 1 for real-time mode, as the
603     // ZEROMV mode is always checked, so we should never go into this branch.
604     // If case ZEROMV is not checked, then we will force no denoise (COPY).
605     decision = COPY_BLOCK;
606   }
607 
608   if (decision == FILTER_BLOCK) {
609     unsigned char *mc_running_avg_y =
610         denoiser->yv12_mc_running_avg.y_buffer + recon_yoffset;
611     int mc_avg_y_stride = denoiser->yv12_mc_running_avg.y_stride;
612     unsigned char *running_avg_y =
613         denoiser->yv12_running_avg[INTRA_FRAME].y_buffer + recon_yoffset;
614     int avg_y_stride = denoiser->yv12_running_avg[INTRA_FRAME].y_stride;
615 
616     /* Filter. */
617     decision = vp8_denoiser_filter(mc_running_avg_y, mc_avg_y_stride,
618                                    running_avg_y, avg_y_stride, x->thismb, 16,
619                                    motion_magnitude2, x->increase_denoising);
620     denoiser->denoise_state[block_index] =
621         motion_magnitude2 > 0 ? kFilterNonZeroMV : kFilterZeroMV;
622     // Only denoise UV for zero motion, and if y channel was denoised.
623     if (denoiser->denoiser_mode != kDenoiserOnYOnly && motion_magnitude2 == 0 &&
624         decision == FILTER_BLOCK) {
625       unsigned char *mc_running_avg_u =
626           denoiser->yv12_mc_running_avg.u_buffer + recon_uvoffset;
627       unsigned char *running_avg_u =
628           denoiser->yv12_running_avg[INTRA_FRAME].u_buffer + recon_uvoffset;
629       unsigned char *mc_running_avg_v =
630           denoiser->yv12_mc_running_avg.v_buffer + recon_uvoffset;
631       unsigned char *running_avg_v =
632           denoiser->yv12_running_avg[INTRA_FRAME].v_buffer + recon_uvoffset;
633       int mc_avg_uv_stride = denoiser->yv12_mc_running_avg.uv_stride;
634       int avg_uv_stride = denoiser->yv12_running_avg[INTRA_FRAME].uv_stride;
635       int signal_stride = x->block[16].src_stride;
636       decision_u = vp8_denoiser_filter_uv(
637           mc_running_avg_u, mc_avg_uv_stride, running_avg_u, avg_uv_stride,
638           x->block[16].src + *x->block[16].base_src, signal_stride,
639           motion_magnitude2, 0);
640       decision_v = vp8_denoiser_filter_uv(
641           mc_running_avg_v, mc_avg_uv_stride, running_avg_v, avg_uv_stride,
642           x->block[20].src + *x->block[20].base_src, signal_stride,
643           motion_magnitude2, 0);
644     }
645   }
646   if (decision == COPY_BLOCK) {
647     /* No filtering of this block; it differs too much from the predictor,
648      * or the motion vector magnitude is considered too big.
649      */
650     x->denoise_zeromv = 0;
651     vp8_copy_mem16x16(
652         x->thismb, 16,
653         denoiser->yv12_running_avg[INTRA_FRAME].y_buffer + recon_yoffset,
654         denoiser->yv12_running_avg[INTRA_FRAME].y_stride);
655     denoiser->denoise_state[block_index] = kNoFilter;
656   }
657   if (denoiser->denoiser_mode != kDenoiserOnYOnly) {
658     if (decision_u == COPY_BLOCK) {
659       vp8_copy_mem8x8(
660           x->block[16].src + *x->block[16].base_src, x->block[16].src_stride,
661           denoiser->yv12_running_avg[INTRA_FRAME].u_buffer + recon_uvoffset,
662           denoiser->yv12_running_avg[INTRA_FRAME].uv_stride);
663     }
664     if (decision_v == COPY_BLOCK) {
665       vp8_copy_mem8x8(
666           x->block[20].src + *x->block[20].base_src, x->block[16].src_stride,
667           denoiser->yv12_running_avg[INTRA_FRAME].v_buffer + recon_uvoffset,
668           denoiser->yv12_running_avg[INTRA_FRAME].uv_stride);
669     }
670   }
671   // Option to selectively deblock the denoised signal, for y channel only.
672   if (apply_spatial_loop_filter) {
673     loop_filter_info lfi;
674     int apply_filter_col = 0;
675     int apply_filter_row = 0;
676     int apply_filter = 0;
677     int y_stride = denoiser->yv12_running_avg[INTRA_FRAME].y_stride;
678     int uv_stride = denoiser->yv12_running_avg[INTRA_FRAME].uv_stride;
679 
680     // Fix filter level to some nominal value for now.
681     int filter_level = 48;
682 
683     int hev_index = lfi_n->hev_thr_lut[INTER_FRAME][filter_level];
684     lfi.mblim = lfi_n->mblim[filter_level];
685     lfi.blim = lfi_n->blim[filter_level];
686     lfi.lim = lfi_n->lim[filter_level];
687     lfi.hev_thr = lfi_n->hev_thr[hev_index];
688 
689     // Apply filter if there is a difference in the denoiser filter state
690     // between the current and left/top block, or if non-zero motion vector
691     // is used for the motion-compensated filtering.
692     if (mb_col > 0) {
693       apply_filter_col =
694           !((denoiser->denoise_state[block_index] ==
695              denoiser->denoise_state[block_index - 1]) &&
696             denoiser->denoise_state[block_index] != kFilterNonZeroMV);
697       if (apply_filter_col) {
698         // Filter left vertical edge.
699         apply_filter = 1;
700         vp8_loop_filter_mbv(
701             denoiser->yv12_running_avg[INTRA_FRAME].y_buffer + recon_yoffset,
702             NULL, NULL, y_stride, uv_stride, &lfi);
703       }
704     }
705     if (mb_row > 0) {
706       apply_filter_row =
707           !((denoiser->denoise_state[block_index] ==
708              denoiser->denoise_state[block_index - denoiser->num_mb_cols]) &&
709             denoiser->denoise_state[block_index] != kFilterNonZeroMV);
710       if (apply_filter_row) {
711         // Filter top horizontal edge.
712         apply_filter = 1;
713         vp8_loop_filter_mbh(
714             denoiser->yv12_running_avg[INTRA_FRAME].y_buffer + recon_yoffset,
715             NULL, NULL, y_stride, uv_stride, &lfi);
716       }
717     }
718     if (apply_filter) {
719       // Update the signal block |x|. Pixel changes are only to top and/or
720       // left boundary pixels: can we avoid full block copy here.
721       vp8_copy_mem16x16(
722           denoiser->yv12_running_avg[INTRA_FRAME].y_buffer + recon_yoffset,
723           y_stride, x->thismb, 16);
724     }
725   }
726 }
727