1 /*
2  * Copyright (c) 2020, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include <assert.h>
13 #include <limits.h>
14 #include <math.h>
15 
16 #include "config/aom_dsp_rtcd.h"
17 #include "aom_dsp/aom_dsp_common.h"
18 #include "aom_scale/yv12config.h"
19 #include "aom/aom_integer.h"
20 #include "av1/encoder/context_tree.h"
21 #include "av1/encoder/av1_noise_estimate.h"
22 #include "av1/encoder/encoder.h"
23 
24 #if CONFIG_AV1_TEMPORAL_DENOISING
25 // For SVC: only do noise estimation on top spatial layer.
noise_est_svc(const struct AV1_COMP * const cpi)26 static INLINE int noise_est_svc(const struct AV1_COMP *const cpi) {
27   return (!cpi->use_svc ||
28           (cpi->use_svc &&
29            cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1));
30 }
31 #endif
32 
av1_noise_estimate_init(NOISE_ESTIMATE * const ne,int width,int height)33 void av1_noise_estimate_init(NOISE_ESTIMATE *const ne, int width, int height) {
34   ne->enabled = 0;
35   ne->level = (width * height < 1280 * 720) ? kLowLow : kLow;
36   ne->value = 0;
37   ne->count = 0;
38   ne->thresh = 90;
39   ne->last_w = 0;
40   ne->last_h = 0;
41   if (width * height >= 1920 * 1080) {
42     ne->thresh = 200;
43   } else if (width * height >= 1280 * 720) {
44     ne->thresh = 140;
45   } else if (width * height >= 640 * 360) {
46     ne->thresh = 115;
47   }
48   ne->num_frames_estimate = 15;
49   ne->adapt_thresh = (3 * ne->thresh) >> 1;
50 }
51 
enable_noise_estimation(AV1_COMP * const cpi)52 static int enable_noise_estimation(AV1_COMP *const cpi) {
53   ResizePendingParams *const resize_pending_params =
54       &cpi->resize_pending_params;
55   const int resize_pending =
56       (resize_pending_params->width && resize_pending_params->height &&
57        (cpi->common.width != resize_pending_params->width ||
58         cpi->common.height != resize_pending_params->height));
59 
60 #if CONFIG_AV1_HIGHBITDEPTH
61   if (cpi->common.seq_params.use_highbitdepth) return 0;
62 #endif
63 // Enable noise estimation if denoising is on.
64 #if CONFIG_AV1_TEMPORAL_DENOISING
65   if (cpi->oxcf.noise_sensitivity > 0 && noise_est_svc(cpi) &&
66       cpi->common.width >= 320 && cpi->common.height >= 180)
67     return 1;
68 #endif
69   // Only allow noise estimate under certain encoding mode.
70   // Enabled for 1 pass CBR, speed >=5, and if resolution is same as original.
71   // Not enabled for SVC mode and screen_content_mode.
72   // Not enabled for low resolutions.
73   if (cpi->oxcf.pass == 0 && cpi->oxcf.rc_cfg.mode == AOM_CBR &&
74       cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.speed >= 5 &&
75       resize_pending == 0 && !cpi->use_svc &&
76       cpi->oxcf.tune_cfg.content != AOM_CONTENT_SCREEN &&
77       cpi->common.width * cpi->common.height >= 640 * 360)
78     return 1;
79   else
80     return 0;
81 }
82 
83 #if CONFIG_AV1_TEMPORAL_DENOISING
copy_frame(YV12_BUFFER_CONFIG * const dest,const YV12_BUFFER_CONFIG * const src)84 static void copy_frame(YV12_BUFFER_CONFIG *const dest,
85                        const YV12_BUFFER_CONFIG *const src) {
86   const uint8_t *srcbuf = src->y_buffer;
87   uint8_t *destbuf = dest->y_buffer;
88 
89   assert(dest->y_width == src->y_width);
90   assert(dest->y_height == src->y_height);
91 
92   for (int r = 0; r < dest->y_height; ++r) {
93     memcpy(destbuf, srcbuf, dest->y_width);
94     destbuf += dest->y_stride;
95     srcbuf += src->y_stride;
96   }
97 }
98 #endif  // CONFIG_AV1_TEMPORAL_DENOISING
99 
av1_noise_estimate_extract_level(NOISE_ESTIMATE * const ne)100 NOISE_LEVEL av1_noise_estimate_extract_level(NOISE_ESTIMATE *const ne) {
101   int noise_level = kLowLow;
102   if (ne->value > (ne->thresh << 1)) {
103     noise_level = kHigh;
104   } else {
105     if (ne->value > ne->thresh)
106       noise_level = kMedium;
107     else if (ne->value > (ne->thresh >> 1))
108       noise_level = kLow;
109     else
110       noise_level = kLowLow;
111   }
112   return noise_level;
113 }
114 
av1_update_noise_estimate(AV1_COMP * const cpi)115 void av1_update_noise_estimate(AV1_COMP *const cpi) {
116   const AV1_COMMON *const cm = &cpi->common;
117   const CommonModeInfoParams *const mi_params = &cm->mi_params;
118 
119   NOISE_ESTIMATE *const ne = &cpi->noise_estimate;
120   const int low_res = (cm->width <= 352 && cm->height <= 288);
121   // Estimate of noise level every frame_period frames.
122   int frame_period = 8;
123   int thresh_consec_zeromv = 6;
124   int frame_counter = cm->current_frame.frame_number;
125   // Estimate is between current source and last source.
126   YV12_BUFFER_CONFIG *last_source = cpi->last_source;
127 #if CONFIG_AV1_TEMPORAL_DENOISING
128   if (cpi->oxcf.noise_sensitivity > 0 && noise_est_svc(cpi)) {
129     last_source = &cpi->denoiser.last_source;
130     // Tune these thresholds for different resolutions when denoising is
131     // enabled.
132     if (cm->width > 640 && cm->width <= 1920) {
133       thresh_consec_zeromv = 2;
134     }
135   }
136 #endif
137   ne->enabled = enable_noise_estimation(cpi);
138   if (cpi->svc.number_spatial_layers > 1)
139     frame_counter = cpi->svc.current_superframe;
140   if (!ne->enabled || frame_counter % frame_period != 0 ||
141       last_source == NULL ||
142       (cpi->svc.number_spatial_layers == 1 &&
143        (ne->last_w != cm->width || ne->last_h != cm->height))) {
144 #if CONFIG_AV1_TEMPORAL_DENOISING
145     if (cpi->oxcf.noise_sensitivity > 0 && noise_est_svc(cpi))
146       copy_frame(&cpi->denoiser.last_source, cpi->source);
147 #endif
148     if (last_source != NULL) {
149       ne->last_w = cm->width;
150       ne->last_h = cm->height;
151     }
152     return;
153   } else if (frame_counter > 60 && cpi->svc.num_encoded_top_layer > 1 &&
154              cpi->rc.frames_since_key > cpi->svc.number_spatial_layers &&
155              cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
156              cpi->rc.avg_frame_low_motion < (low_res ? 60 : 40)) {
157     // Force noise estimation to 0 and denoiser off if content has high motion.
158     ne->level = kLowLow;
159     ne->count = 0;
160     ne->num_frames_estimate = 10;
161 #if CONFIG_AV1_TEMPORAL_DENOISING
162     if (cpi->oxcf.noise_sensitivity > 0 && noise_est_svc(cpi) &&
163         cpi->svc.current_superframe > 1) {
164       av1_denoiser_set_noise_level(cpi, ne->level);
165       copy_frame(&cpi->denoiser.last_source, cpi->source);
166     }
167 #endif
168     return;
169   } else {
170     unsigned int bin_size = 100;
171     unsigned int hist[MAX_VAR_HIST_BINS] = { 0 };
172     unsigned int hist_avg[MAX_VAR_HIST_BINS];
173     unsigned int max_bin = 0;
174     unsigned int max_bin_count = 0;
175     unsigned int bin_cnt;
176     int bsize = BLOCK_16X16;
177     // Loop over sub-sample of 16x16 blocks of frame, and for blocks that have
178     // been encoded as zero/small mv at least x consecutive frames, compute
179     // the variance to update estimate of noise in the source.
180     const uint8_t *src_y = cpi->source->y_buffer;
181     const int src_ystride = cpi->source->y_stride;
182     const uint8_t *last_src_y = last_source->y_buffer;
183     const int last_src_ystride = last_source->y_stride;
184     const uint8_t *src_u = cpi->source->u_buffer;
185     const uint8_t *src_v = cpi->source->v_buffer;
186     const int src_uvstride = cpi->source->uv_stride;
187     int mi_row, mi_col;
188     int num_low_motion = 0;
189     int frame_low_motion = 1;
190     for (mi_row = 0; mi_row < mi_params->mi_rows; mi_row += 2) {
191       for (mi_col = 0; mi_col < mi_params->mi_cols; mi_col += 2) {
192         int bl_index =
193             (mi_row >> 1) * (mi_params->mi_cols >> 1) + (mi_col >> 1);
194         if (cpi->consec_zero_mv[bl_index] > thresh_consec_zeromv)
195           num_low_motion++;
196       }
197     }
198     if (num_low_motion <
199         (((3 * (mi_params->mi_rows * mi_params->mi_cols) >> 2)) >> 3))
200       frame_low_motion = 0;
201     for (mi_row = 0; mi_row < mi_params->mi_rows; mi_row++) {
202       for (mi_col = 0; mi_col < mi_params->mi_cols; mi_col++) {
203         // 16x16 blocks, 1/4 sample of frame.
204         if (mi_row % 8 == 0 && mi_col % 8 == 0 &&
205             mi_row < mi_params->mi_rows - 3 &&
206             mi_col < mi_params->mi_cols - 3) {
207           int bl_index =
208               (mi_row >> 1) * (mi_params->mi_cols >> 1) + (mi_col >> 1);
209           int bl_index1 = bl_index + 1;
210           int bl_index2 = bl_index + (mi_params->mi_cols >> 1);
211           int bl_index3 = bl_index2 + 1;
212           int consec_zeromv =
213               AOMMIN(cpi->consec_zero_mv[bl_index],
214                      AOMMIN(cpi->consec_zero_mv[bl_index1],
215                             AOMMIN(cpi->consec_zero_mv[bl_index2],
216                                    cpi->consec_zero_mv[bl_index3])));
217           // Only consider blocks that are likely steady background. i.e, have
218           // been encoded as zero/low motion x (= thresh_consec_zeromv) frames
219           // in a row. consec_zero_mv[] defined for 8x8 blocks, so consider all
220           // 4 sub-blocks for 16x16 block. And exclude this frame if
221           // high_source_sad is true (i.e., scene/content change).
222           if (frame_low_motion && consec_zeromv > thresh_consec_zeromv &&
223               !cpi->rc.high_source_sad) {
224             unsigned int sse;
225             // Compute variance between co-located blocks from current and
226             // last input frames.
227             unsigned int variance = cpi->fn_ptr[bsize].vf(
228                 src_y, src_ystride, last_src_y, last_src_ystride, &sse);
229             unsigned int hist_index = variance / bin_size;
230             if (hist_index < MAX_VAR_HIST_BINS)
231               hist[hist_index]++;
232             else if (hist_index < 3 * (MAX_VAR_HIST_BINS >> 1))
233               hist[MAX_VAR_HIST_BINS - 1]++;  // Account for the tail
234           }
235         }
236         src_y += 4;
237         last_src_y += 4;
238         src_u += 2;
239         src_v += 2;
240       }
241       src_y += (src_ystride << 2) - (mi_params->mi_cols << 2);
242       last_src_y += (last_src_ystride << 2) - (mi_params->mi_cols << 2);
243       src_u += (src_uvstride << 1) - (mi_params->mi_cols << 1);
244       src_v += (src_uvstride << 1) - (mi_params->mi_cols << 1);
245     }
246     ne->last_w = cm->width;
247     ne->last_h = cm->height;
248     // Adjust histogram to account for effect that histogram flattens
249     // and shifts to zero as scene darkens.
250     if (hist[0] > 10 && (hist[MAX_VAR_HIST_BINS - 1] > hist[0] >> 2)) {
251       hist[0] = 0;
252       hist[1] >>= 2;
253       hist[2] >>= 2;
254       hist[3] >>= 2;
255       hist[4] >>= 1;
256       hist[5] >>= 1;
257       hist[6] = 3 * hist[6] >> 1;
258       hist[MAX_VAR_HIST_BINS - 1] >>= 1;
259     }
260 
261     // Average hist[] and find largest bin
262     for (bin_cnt = 0; bin_cnt < MAX_VAR_HIST_BINS; bin_cnt++) {
263       if (bin_cnt == 0)
264         hist_avg[bin_cnt] = (hist[0] + hist[1] + hist[2]) / 3;
265       else if (bin_cnt == MAX_VAR_HIST_BINS - 1)
266         hist_avg[bin_cnt] = hist[MAX_VAR_HIST_BINS - 1] >> 2;
267       else if (bin_cnt == MAX_VAR_HIST_BINS - 2)
268         hist_avg[bin_cnt] = (hist[bin_cnt - 1] + 2 * hist[bin_cnt] +
269                              (hist[bin_cnt + 1] >> 1) + 2) >>
270                             2;
271       else
272         hist_avg[bin_cnt] =
273             (hist[bin_cnt - 1] + 2 * hist[bin_cnt] + hist[bin_cnt + 1] + 2) >>
274             2;
275 
276       if (hist_avg[bin_cnt] > max_bin_count) {
277         max_bin_count = hist_avg[bin_cnt];
278         max_bin = bin_cnt;
279       }
280     }
281 
282     // Scale by 40 to work with existing thresholds
283     ne->value = (int)((3 * ne->value + max_bin * 40) >> 2);
284     // Quickly increase VNR strength when the noise level increases suddenly.
285     if (ne->level < kMedium && ne->value > ne->adapt_thresh) {
286       ne->count = ne->num_frames_estimate;
287     } else {
288       ne->count++;
289     }
290     if (ne->count == ne->num_frames_estimate) {
291       // Reset counter and check noise level condition.
292       ne->num_frames_estimate = 30;
293       ne->count = 0;
294       ne->level = av1_noise_estimate_extract_level(ne);
295 #if CONFIG_AV1_TEMPORAL_DENOISING
296       if (cpi->oxcf.noise_sensitivity > 0 && noise_est_svc(cpi))
297         av1_denoiser_set_noise_level(cpi, ne->level);
298 #endif
299     }
300   }
301 #if CONFIG_AV1_TEMPORAL_DENOISING
302   if (cpi->oxcf.noise_sensitivity > 0 && noise_est_svc(cpi))
303     copy_frame(&cpi->denoiser.last_source, cpi->source);
304 #endif
305 }
306