xref: /aosp_15_r20/external/libaom/av1/encoder/temporal_filter.c (revision 77c1e3ccc04c968bd2bc212e87364f250e820521)
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved.
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include <float.h>
13 #include <math.h>
14 #include <limits.h>
15 
16 #include "config/aom_config.h"
17 #include "config/aom_scale_rtcd.h"
18 
19 #include "aom_dsp/aom_dsp_common.h"
20 #include "aom_dsp/mathutils.h"
21 #include "aom_dsp/odintrin.h"
22 #include "aom_mem/aom_mem.h"
23 #include "aom_ports/aom_timer.h"
24 #include "aom_ports/mem.h"
25 #include "av1/common/alloccommon.h"
26 #include "av1/common/av1_common_int.h"
27 #include "av1/common/quant_common.h"
28 #include "av1/common/reconinter.h"
29 #include "av1/encoder/av1_quantize.h"
30 #include "av1/encoder/encodeframe.h"
31 #include "av1/encoder/encoder.h"
32 #include "av1/encoder/ethread.h"
33 #include "av1/encoder/extend.h"
34 #include "av1/encoder/firstpass.h"
35 #include "av1/encoder/gop_structure.h"
36 #include "av1/encoder/intra_mode_search_utils.h"
37 #include "av1/encoder/mcomp.h"
38 #include "av1/encoder/motion_search_facade.h"
39 #include "av1/encoder/pass2_strategy.h"
40 #include "av1/encoder/ratectrl.h"
41 #include "av1/encoder/reconinter_enc.h"
42 #include "av1/encoder/segmentation.h"
43 #include "av1/encoder/temporal_filter.h"
44 
45 /*!\cond */
46 
47 // NOTE: All `tf` in this file means `temporal filtering`.
48 
49 // Forward Declaration.
50 static void tf_determine_block_partition(const MV block_mv, const int block_mse,
51                                          MV *subblock_mvs, int *subblock_mses);
52 
53 // This function returns the minimum and maximum log variances for 4x4 sub
54 // blocks in the current block.
get_log_var_4x4sub_blk(AV1_COMP * cpi,const YV12_BUFFER_CONFIG * const frame_to_filter,int mb_row,int mb_col,BLOCK_SIZE block_size,double * blk_4x4_var_min,double * blk_4x4_var_max,int is_hbd)55 static inline void get_log_var_4x4sub_blk(
56     AV1_COMP *cpi, const YV12_BUFFER_CONFIG *const frame_to_filter, int mb_row,
57     int mb_col, BLOCK_SIZE block_size, double *blk_4x4_var_min,
58     double *blk_4x4_var_max, int is_hbd) {
59   const int mb_height = block_size_high[block_size];
60   const int mb_width = block_size_wide[block_size];
61   int var_min = INT_MAX;
62   int var_max = 0;
63 
64   // Derive the source buffer.
65   const int src_stride = frame_to_filter->y_stride;
66   const int y_offset = mb_row * mb_height * src_stride + mb_col * mb_width;
67   const uint8_t *src_buf = frame_to_filter->y_buffer + y_offset;
68 
69   for (int i = 0; i < mb_height; i += MI_SIZE) {
70     for (int j = 0; j < mb_width; j += MI_SIZE) {
71       // Calculate the 4x4 sub-block variance.
72       const int var = av1_calc_normalized_variance(
73           cpi->ppi->fn_ptr[BLOCK_4X4].vf, src_buf + (i * src_stride) + j,
74           src_stride, is_hbd);
75 
76       // Record min and max for over-arching block
77       var_min = AOMMIN(var_min, var);
78       var_max = AOMMAX(var_max, var);
79     }
80   }
81 
82   *blk_4x4_var_min = log1p(var_min / 16.0);
83   *blk_4x4_var_max = log1p(var_max / 16.0);
84 }
85 
86 // Helper function to get `q` used for encoding.
get_q(const AV1_COMP * cpi)87 static int get_q(const AV1_COMP *cpi) {
88   const GF_GROUP *gf_group = &cpi->ppi->gf_group;
89   const FRAME_TYPE frame_type = gf_group->frame_type[cpi->gf_frame_index];
90   const int q =
91       (int)av1_convert_qindex_to_q(cpi->ppi->p_rc.avg_frame_qindex[frame_type],
92                                    cpi->common.seq_params->bit_depth);
93   return q;
94 }
95 
96 /*!\endcond */
97 /*!\brief Does motion search for blocks in temporal filtering. This is
98  *  the first step for temporal filtering. More specifically, given a frame to
99  * be filtered and another frame as reference, this function searches the
100  * reference frame to find out the most similar block as that from the frame
101  * to be filtered. This found block will be further used for weighted
102  * averaging.
103  *
104  * NOTE: Besides doing motion search for the entire block, this function will
105  *       also do motion search for each 1/4 sub-block to get more precise
106  *       predictions. Then, this function will determines whether to use 4
107  *       sub-blocks to replace the entire block. If we do need to split the
108  *       entire block, 4 elements in `subblock_mvs` and `subblock_mses` refer to
109  *       the searched motion vector and search error (MSE) w.r.t. each sub-block
110  *       respectively. Otherwise, the 4 elements will be the same, all of which
111  *       are assigned as the searched motion vector and search error (MSE) for
112  *       the entire block.
113  *
114  * \ingroup src_frame_proc
115  * \param[in]   cpi                   Top level encoder instance structure
116  * \param[in]   mb                    Pointer to macroblock
117  * \param[in]   frame_to_filter       Pointer to the frame to be filtered
118  * \param[in]   ref_frame             Pointer to the reference frame
119  * \param[in]   block_size            Block size used for motion search
120  * \param[in]   mb_row                Row index of the block in the frame
121  * \param[in]   mb_col                Column index of the block in the frame
122  * \param[in]   ref_mv                Reference motion vector, which is commonly
123  *                                    inherited from the motion search result of
124  *                                    previous frame.
125  * \param[in]   allow_me_for_sub_blks Flag to indicate whether motion search at
126  *                                    16x16 sub-block level is needed or not.
127  * \param[out]  subblock_mvs          Pointer to the motion vectors for
128  *                                    4 sub-blocks
129  * \param[out]  subblock_mses         Pointer to the search errors (MSE) for
130  *                                    4 sub-blocks
131  *
132  * \remark Nothing will be returned. Results are saved in subblock_mvs and
133  *         subblock_mses
134  */
tf_motion_search(AV1_COMP * cpi,MACROBLOCK * mb,const YV12_BUFFER_CONFIG * frame_to_filter,const YV12_BUFFER_CONFIG * ref_frame,const BLOCK_SIZE block_size,const int mb_row,const int mb_col,MV * ref_mv,bool allow_me_for_sub_blks,MV * subblock_mvs,int * subblock_mses)135 static void tf_motion_search(AV1_COMP *cpi, MACROBLOCK *mb,
136                              const YV12_BUFFER_CONFIG *frame_to_filter,
137                              const YV12_BUFFER_CONFIG *ref_frame,
138                              const BLOCK_SIZE block_size, const int mb_row,
139                              const int mb_col, MV *ref_mv,
140                              bool allow_me_for_sub_blks, MV *subblock_mvs,
141                              int *subblock_mses) {
142   // Frame information
143   const int min_frame_size = AOMMIN(cpi->common.width, cpi->common.height);
144 
145   // Block information (ONLY Y-plane is used for motion search).
146   const int mb_height = block_size_high[block_size];
147   const int mb_width = block_size_wide[block_size];
148   const int mb_pels = mb_height * mb_width;
149   const int y_stride = frame_to_filter->y_stride;
150   const int src_width = frame_to_filter->y_width;
151   const int ref_width = ref_frame->y_width;
152   assert(y_stride == ref_frame->y_stride);
153   assert(src_width == ref_width);
154   const int y_offset = mb_row * mb_height * y_stride + mb_col * mb_width;
155 
156   // Save input state.
157   MACROBLOCKD *const mbd = &mb->e_mbd;
158   const struct buf_2d ori_src_buf = mb->plane[0].src;
159   const struct buf_2d ori_pre_buf = mbd->plane[0].pre[0];
160 
161   // Parameters used for motion search.
162   FULLPEL_MOTION_SEARCH_PARAMS full_ms_params;
163   SUBPEL_MOTION_SEARCH_PARAMS ms_params;
164   const int step_param = av1_init_search_range(
165       AOMMAX(frame_to_filter->y_crop_width, frame_to_filter->y_crop_height));
166   const SUBPEL_SEARCH_TYPE subpel_search_type = USE_8_TAPS;
167   const int force_integer_mv = cpi->common.features.cur_frame_force_integer_mv;
168   const MV_COST_TYPE mv_cost_type =
169       min_frame_size >= 720
170           ? MV_COST_L1_HDRES
171           : (min_frame_size >= 480 ? MV_COST_L1_MIDRES : MV_COST_L1_LOWRES);
172 
173   // Starting position for motion search.
174   FULLPEL_MV start_mv = get_fullmv_from_mv(ref_mv);
175   // Baseline position for motion search (used for rate distortion comparison).
176   const MV baseline_mv = kZeroMv;
177 
178   // Setup.
179   mb->plane[0].src.buf = frame_to_filter->y_buffer + y_offset;
180   mb->plane[0].src.stride = y_stride;
181   mb->plane[0].src.width = src_width;
182   mbd->plane[0].pre[0].buf = ref_frame->y_buffer + y_offset;
183   mbd->plane[0].pre[0].stride = y_stride;
184   mbd->plane[0].pre[0].width = ref_width;
185 
186   const SEARCH_METHODS search_method = NSTEP;
187   const search_site_config *search_site_cfg =
188       av1_get_search_site_config(cpi, mb, search_method);
189 
190   // Unused intermediate results for motion search.
191   unsigned int sse, error;
192   int distortion;
193   int cost_list[5];
194 
195   // Do motion search.
196   int_mv best_mv;  // Searched motion vector.
197   FULLPEL_MV_STATS best_mv_stats;
198   int block_mse = INT_MAX;
199   MV block_mv = kZeroMv;
200   const int q = get_q(cpi);
201 
202   av1_make_default_fullpel_ms_params(&full_ms_params, cpi, mb, block_size,
203                                      &baseline_mv, start_mv, search_site_cfg,
204                                      search_method,
205                                      /*fine_search_interval=*/0);
206   full_ms_params.run_mesh_search = 1;
207   full_ms_params.mv_cost_params.mv_cost_type = mv_cost_type;
208 
209   if (cpi->sf.mv_sf.prune_mesh_search == PRUNE_MESH_SEARCH_LVL_1) {
210     // Enable prune_mesh_search based on q for PRUNE_MESH_SEARCH_LVL_1.
211     full_ms_params.prune_mesh_search = (q <= 20) ? 0 : 1;
212     full_ms_params.mesh_search_mv_diff_threshold = 2;
213   }
214 
215   av1_full_pixel_search(start_mv, &full_ms_params, step_param,
216                         cond_cost_list(cpi, cost_list), &best_mv.as_fullmv,
217                         &best_mv_stats, NULL);
218 
219   if (force_integer_mv == 1) {  // Only do full search on the entire block.
220     const int mv_row = best_mv.as_mv.row;
221     const int mv_col = best_mv.as_mv.col;
222     best_mv.as_mv.row = GET_MV_SUBPEL(mv_row);
223     best_mv.as_mv.col = GET_MV_SUBPEL(mv_col);
224     const int mv_offset = mv_row * y_stride + mv_col;
225     error = cpi->ppi->fn_ptr[block_size].vf(
226         ref_frame->y_buffer + y_offset + mv_offset, y_stride,
227         frame_to_filter->y_buffer + y_offset, y_stride, &sse);
228     block_mse = DIVIDE_AND_ROUND(error, mb_pels);
229     block_mv = best_mv.as_mv;
230   } else {  // Do fractional search on the entire block and all sub-blocks.
231     av1_make_default_subpel_ms_params(&ms_params, cpi, mb, block_size,
232                                       &baseline_mv, cost_list);
233     ms_params.forced_stop = EIGHTH_PEL;
234     ms_params.var_params.subpel_search_type = subpel_search_type;
235     // Since we are merely refining the result from full pixel search, we don't
236     // need regularization for subpel search
237     ms_params.mv_cost_params.mv_cost_type = MV_COST_NONE;
238     best_mv_stats.err_cost = 0;
239 
240     MV subpel_start_mv = get_mv_from_fullmv(&best_mv.as_fullmv);
241     assert(av1_is_subpelmv_in_range(&ms_params.mv_limits, subpel_start_mv));
242     error = cpi->mv_search_params.find_fractional_mv_step(
243         &mb->e_mbd, &cpi->common, &ms_params, subpel_start_mv, &best_mv_stats,
244         &best_mv.as_mv, &distortion, &sse, NULL);
245     block_mse = DIVIDE_AND_ROUND(error, mb_pels);
246     block_mv = best_mv.as_mv;
247     *ref_mv = best_mv.as_mv;
248 
249     if (allow_me_for_sub_blks) {
250       // On 4 sub-blocks.
251       const BLOCK_SIZE subblock_size = av1_ss_size_lookup[block_size][1][1];
252       const int subblock_height = block_size_high[subblock_size];
253       const int subblock_width = block_size_wide[subblock_size];
254       const int subblock_pels = subblock_height * subblock_width;
255       start_mv = get_fullmv_from_mv(ref_mv);
256 
257       int subblock_idx = 0;
258       for (int i = 0; i < mb_height; i += subblock_height) {
259         for (int j = 0; j < mb_width; j += subblock_width) {
260           const int offset = i * y_stride + j;
261           mb->plane[0].src.buf = frame_to_filter->y_buffer + y_offset + offset;
262           mbd->plane[0].pre[0].buf = ref_frame->y_buffer + y_offset + offset;
263           av1_make_default_fullpel_ms_params(
264               &full_ms_params, cpi, mb, subblock_size, &baseline_mv, start_mv,
265               search_site_cfg, search_method,
266               /*fine_search_interval=*/0);
267           full_ms_params.run_mesh_search = 1;
268           full_ms_params.mv_cost_params.mv_cost_type = mv_cost_type;
269 
270           if (cpi->sf.mv_sf.prune_mesh_search == PRUNE_MESH_SEARCH_LVL_1) {
271             // Enable prune_mesh_search based on q for PRUNE_MESH_SEARCH_LVL_1.
272             full_ms_params.prune_mesh_search = (q <= 20) ? 0 : 1;
273             full_ms_params.mesh_search_mv_diff_threshold = 2;
274           }
275           av1_full_pixel_search(start_mv, &full_ms_params, step_param,
276                                 cond_cost_list(cpi, cost_list),
277                                 &best_mv.as_fullmv, &best_mv_stats, NULL);
278 
279           av1_make_default_subpel_ms_params(&ms_params, cpi, mb, subblock_size,
280                                             &baseline_mv, cost_list);
281           ms_params.forced_stop = EIGHTH_PEL;
282           ms_params.var_params.subpel_search_type = subpel_search_type;
283           // Since we are merely refining the result from full pixel search, we
284           // don't need regularization for subpel search
285           ms_params.mv_cost_params.mv_cost_type = MV_COST_NONE;
286           best_mv_stats.err_cost = 0;
287 
288           subpel_start_mv = get_mv_from_fullmv(&best_mv.as_fullmv);
289           assert(
290               av1_is_subpelmv_in_range(&ms_params.mv_limits, subpel_start_mv));
291           error = cpi->mv_search_params.find_fractional_mv_step(
292               &mb->e_mbd, &cpi->common, &ms_params, subpel_start_mv,
293               &best_mv_stats, &best_mv.as_mv, &distortion, &sse, NULL);
294           subblock_mses[subblock_idx] = DIVIDE_AND_ROUND(error, subblock_pels);
295           subblock_mvs[subblock_idx] = best_mv.as_mv;
296           ++subblock_idx;
297         }
298       }
299     }
300   }
301 
302   // Restore input state.
303   mb->plane[0].src = ori_src_buf;
304   mbd->plane[0].pre[0] = ori_pre_buf;
305 
306   // Make partition decision.
307   if (allow_me_for_sub_blks) {
308     tf_determine_block_partition(block_mv, block_mse, subblock_mvs,
309                                  subblock_mses);
310   } else {
311     // Copy 32X32 block mv and mse values to sub blocks
312     for (int i = 0; i < 4; ++i) {
313       subblock_mvs[i] = block_mv;
314       subblock_mses[i] = block_mse;
315     }
316   }
317   // Do not pass down the reference motion vector if error is too large.
318   const int thresh = (min_frame_size >= 720) ? 12 : 3;
319   if (block_mse > (thresh << (mbd->bd - 8))) {
320     *ref_mv = kZeroMv;
321   }
322 }
323 /*!\cond */
324 
325 // Determines whether to split the entire block to 4 sub-blocks for filtering.
326 // In particular, this decision is made based on the comparison between the
327 // motion search error of the entire block and the errors of all sub-blocks.
328 // Inputs:
329 //   block_mv: Motion vector for the entire block (ONLY as reference).
330 //   block_mse: Motion search error (MSE) for the entire block (ONLY as
331 //              reference).
332 //   subblock_mvs: Pointer to the motion vectors for 4 sub-blocks (will be
333 //                 modified based on the partition decision).
334 //   subblock_mses: Pointer to the search errors (MSE) for 4 sub-blocks (will
335 //                  be modified based on the partition decision).
336 // Returns:
337 //   Nothing will be returned. Results are saved in `subblock_mvs` and
338 //   `subblock_mses`.
tf_determine_block_partition(const MV block_mv,const int block_mse,MV * subblock_mvs,int * subblock_mses)339 static void tf_determine_block_partition(const MV block_mv, const int block_mse,
340                                          MV *subblock_mvs, int *subblock_mses) {
341   int min_subblock_mse = INT_MAX;
342   int max_subblock_mse = INT_MIN;
343   int64_t sum_subblock_mse = 0;
344   for (int i = 0; i < 4; ++i) {
345     sum_subblock_mse += subblock_mses[i];
346     min_subblock_mse = AOMMIN(min_subblock_mse, subblock_mses[i]);
347     max_subblock_mse = AOMMAX(max_subblock_mse, subblock_mses[i]);
348   }
349 
350   // TODO(any): The following magic numbers may be tuned to improve the
351   // performance OR find a way to get rid of these magic numbers.
352   if (((block_mse * 15 < sum_subblock_mse * 4) &&
353        max_subblock_mse - min_subblock_mse < 48) ||
354       ((block_mse * 14 < sum_subblock_mse * 4) &&
355        max_subblock_mse - min_subblock_mse < 24)) {  // No split.
356     for (int i = 0; i < 4; ++i) {
357       subblock_mvs[i] = block_mv;
358       subblock_mses[i] = block_mse;
359     }
360   }
361 }
362 
363 // Helper function to determine whether a frame is encoded with high bit-depth.
is_frame_high_bitdepth(const YV12_BUFFER_CONFIG * frame)364 static inline int is_frame_high_bitdepth(const YV12_BUFFER_CONFIG *frame) {
365   return (frame->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0;
366 }
367 
368 /*!\endcond */
369 /*!\brief Builds predictor for blocks in temporal filtering. This is the
370  * second step for temporal filtering, which is to construct predictions from
371  * all reference frames INCLUDING the frame to be filtered itself. These
372  * predictors are built based on the motion search results (motion vector is
373  * set as 0 for the frame to be filtered), and will be futher used for
374  * weighted averaging.
375  *
376  * \ingroup src_frame_proc
377  * \param[in]   ref_frame      Pointer to the reference frame (or the frame
378  *                             to be filtered)
379  * \param[in]   mbd            Pointer to the block for filtering. Besides
380  *                             containing the subsampling information of all
381  *                             planes, this field also gives the searched
382  *                             motion vector for the entire block, i.e.,
383  *                             `mbd->mi[0]->mv[0]`. This vector  should be 0
384  *                             if the `ref_frame` itself is the frame to be
385  *                             filtered.
386  * \param[in]   block_size     Size of the block
387  * \param[in]   mb_row         Row index of the block in the frame
388  * \param[in]   mb_col         Column index of the block in the frame
389  * \param[in]   num_planes     Number of planes in the frame
390  * \param[in]   scale          Scaling factor
391  * \param[in]   subblock_mvs   The motion vectors for each sub-block (row-major
392  *                             order)
393  * \param[out]  pred           Pointer to the predictor to be built
394  *
395  * \remark Nothing returned, But the contents of `pred` will be modified
396  */
tf_build_predictor(const YV12_BUFFER_CONFIG * ref_frame,const MACROBLOCKD * mbd,const BLOCK_SIZE block_size,const int mb_row,const int mb_col,const int num_planes,const struct scale_factors * scale,const MV * subblock_mvs,uint8_t * pred)397 static void tf_build_predictor(const YV12_BUFFER_CONFIG *ref_frame,
398                                const MACROBLOCKD *mbd,
399                                const BLOCK_SIZE block_size, const int mb_row,
400                                const int mb_col, const int num_planes,
401                                const struct scale_factors *scale,
402                                const MV *subblock_mvs, uint8_t *pred) {
403   // Information of the entire block.
404   const int mb_height = block_size_high[block_size];  // Height.
405   const int mb_width = block_size_wide[block_size];   // Width.
406   const int mb_y = mb_height * mb_row;                // Y-coord (Top-left).
407   const int mb_x = mb_width * mb_col;                 // X-coord (Top-left).
408   const int bit_depth = mbd->bd;                      // Bit depth.
409   const int is_intrabc = 0;                           // Is intra-copied?
410   const int is_high_bitdepth = is_frame_high_bitdepth(ref_frame);
411 
412   // Default interpolation filters.
413   const int_interpfilters interp_filters =
414       av1_broadcast_interp_filter(MULTITAP_SHARP2);
415 
416   // Handle Y-plane, U-plane and V-plane (if needed) in sequence.
417   int plane_offset = 0;
418   for (int plane = 0; plane < num_planes; ++plane) {
419     const int subsampling_y = mbd->plane[plane].subsampling_y;
420     const int subsampling_x = mbd->plane[plane].subsampling_x;
421     // Information of each sub-block in current plane.
422     const int plane_h = mb_height >> subsampling_y;  // Plane height.
423     const int plane_w = mb_width >> subsampling_x;   // Plane width.
424     const int plane_y = mb_y >> subsampling_y;       // Y-coord (Top-left).
425     const int plane_x = mb_x >> subsampling_x;       // X-coord (Top-left).
426     const int h = plane_h >> 1;                      // Sub-block height.
427     const int w = plane_w >> 1;                      // Sub-block width.
428     const int is_y_plane = (plane == 0);             // Is Y-plane?
429 
430     const struct buf_2d ref_buf = { NULL, ref_frame->buffers[plane],
431                                     ref_frame->widths[is_y_plane ? 0 : 1],
432                                     ref_frame->heights[is_y_plane ? 0 : 1],
433                                     ref_frame->strides[is_y_plane ? 0 : 1] };
434 
435     // Handle each subblock.
436     int subblock_idx = 0;
437     for (int i = 0; i < plane_h; i += h) {
438       for (int j = 0; j < plane_w; j += w) {
439         // Choose proper motion vector.
440         const MV mv = subblock_mvs[subblock_idx++];
441         assert(mv.row >= INT16_MIN && mv.row <= INT16_MAX &&
442                mv.col >= INT16_MIN && mv.col <= INT16_MAX);
443 
444         const int y = plane_y + i;
445         const int x = plane_x + j;
446 
447         // Build predictior for each sub-block on current plane.
448         InterPredParams inter_pred_params;
449         av1_init_inter_params(&inter_pred_params, w, h, y, x, subsampling_x,
450                               subsampling_y, bit_depth, is_high_bitdepth,
451                               is_intrabc, scale, &ref_buf, interp_filters);
452         inter_pred_params.conv_params = get_conv_params(0, plane, bit_depth);
453         av1_enc_build_one_inter_predictor(&pred[plane_offset + i * plane_w + j],
454                                           plane_w, &mv, &inter_pred_params);
455       }
456     }
457     plane_offset += plane_h * plane_w;
458   }
459 }
460 /*!\cond */
461 
462 // Computes temporal filter weights and accumulators for the frame to be
463 // filtered. More concretely, the filter weights for all pixels are the same.
464 // Inputs:
465 //   mbd: Pointer to the block for filtering, which is ONLY used to get
466 //        subsampling information of all planes as well as the bit-depth.
467 //   block_size: Size of the block.
468 //   num_planes: Number of planes in the frame.
469 //   pred: Pointer to the well-built predictors.
470 //   accum: Pointer to the pixel-wise accumulator for filtering.
471 //   count: Pointer to the pixel-wise counter fot filtering.
472 // Returns:
473 //   Nothing will be returned. But the content to which `accum` and `pred`
474 //   point will be modified.
tf_apply_temporal_filter_self(const YV12_BUFFER_CONFIG * ref_frame,const MACROBLOCKD * mbd,const BLOCK_SIZE block_size,const int mb_row,const int mb_col,const int num_planes,uint32_t * accum,uint16_t * count)475 static void tf_apply_temporal_filter_self(const YV12_BUFFER_CONFIG *ref_frame,
476                                           const MACROBLOCKD *mbd,
477                                           const BLOCK_SIZE block_size,
478                                           const int mb_row, const int mb_col,
479                                           const int num_planes, uint32_t *accum,
480                                           uint16_t *count) {
481   // Block information.
482   const int mb_height = block_size_high[block_size];
483   const int mb_width = block_size_wide[block_size];
484   const int is_high_bitdepth = is_cur_buf_hbd(mbd);
485 
486   int plane_offset = 0;
487   for (int plane = 0; plane < num_planes; ++plane) {
488     const int subsampling_y = mbd->plane[plane].subsampling_y;
489     const int subsampling_x = mbd->plane[plane].subsampling_x;
490     const int h = mb_height >> subsampling_y;  // Plane height.
491     const int w = mb_width >> subsampling_x;   // Plane width.
492 
493     const int frame_stride = ref_frame->strides[plane == AOM_PLANE_Y ? 0 : 1];
494     const uint8_t *buf8 = ref_frame->buffers[plane];
495     const uint16_t *buf16 = CONVERT_TO_SHORTPTR(buf8);
496     const int frame_offset = mb_row * h * frame_stride + mb_col * w;
497 
498     int pred_idx = 0;
499     int pixel_idx = 0;
500     for (int i = 0; i < h; ++i) {
501       for (int j = 0; j < w; ++j) {
502         const int idx = plane_offset + pred_idx;  // Index with plane shift.
503         const int pred_value = is_high_bitdepth
504                                    ? buf16[frame_offset + pixel_idx]
505                                    : buf8[frame_offset + pixel_idx];
506         accum[idx] += TF_WEIGHT_SCALE * pred_value;
507         count[idx] += TF_WEIGHT_SCALE;
508         ++pred_idx;
509         ++pixel_idx;
510       }
511       pixel_idx += (frame_stride - w);
512     }
513     plane_offset += h * w;
514   }
515 }
516 
517 // Function to compute pixel-wise squared difference between two buffers.
518 // Inputs:
519 //   ref: Pointer to reference buffer.
520 //   ref_offset: Start position of reference buffer for computation.
521 //   ref_stride: Stride for reference buffer.
522 //   tgt: Pointer to target buffer.
523 //   tgt_offset: Start position of target buffer for computation.
524 //   tgt_stride: Stride for target buffer.
525 //   height: Height of block for computation.
526 //   width: Width of block for computation.
527 //   is_high_bitdepth: Whether the two buffers point to high bit-depth frames.
528 //   square_diff: Pointer to save the squared differces.
529 // Returns:
530 //   Nothing will be returned. But the content to which `square_diff` points
531 //   will be modified.
compute_square_diff(const uint8_t * ref,const int ref_offset,const int ref_stride,const uint8_t * tgt,const int tgt_offset,const int tgt_stride,const int height,const int width,const int is_high_bitdepth,uint32_t * square_diff)532 static inline void compute_square_diff(const uint8_t *ref, const int ref_offset,
533                                        const int ref_stride, const uint8_t *tgt,
534                                        const int tgt_offset,
535                                        const int tgt_stride, const int height,
536                                        const int width,
537                                        const int is_high_bitdepth,
538                                        uint32_t *square_diff) {
539   const uint16_t *ref16 = CONVERT_TO_SHORTPTR(ref);
540   const uint16_t *tgt16 = CONVERT_TO_SHORTPTR(tgt);
541 
542   int ref_idx = 0;
543   int tgt_idx = 0;
544   int idx = 0;
545   for (int i = 0; i < height; ++i) {
546     for (int j = 0; j < width; ++j) {
547       const uint16_t ref_value = is_high_bitdepth ? ref16[ref_offset + ref_idx]
548                                                   : ref[ref_offset + ref_idx];
549       const uint16_t tgt_value = is_high_bitdepth ? tgt16[tgt_offset + tgt_idx]
550                                                   : tgt[tgt_offset + tgt_idx];
551       const uint32_t diff = (ref_value > tgt_value) ? (ref_value - tgt_value)
552                                                     : (tgt_value - ref_value);
553       square_diff[idx] = diff * diff;
554 
555       ++ref_idx;
556       ++tgt_idx;
557       ++idx;
558     }
559     ref_idx += (ref_stride - width);
560     tgt_idx += (tgt_stride - width);
561   }
562 }
563 
564 // Function to accumulate pixel-wise squared difference between two luma buffers
565 // to be consumed while filtering the chroma planes.
566 // Inputs:
567 //   square_diff: Pointer to squared differences from luma plane.
568 //   luma_sse_sum: Pointer to save the sum of luma squared differences.
569 //   block_height: Height of block for computation.
570 //   block_width: Width of block for computation.
571 //   ss_x_shift: Chroma subsampling shift in 'X' direction
572 //   ss_y_shift: Chroma subsampling shift in 'Y' direction
573 // Returns:
574 //   Nothing will be returned. But the content to which `luma_sse_sum` points
575 //   will be modified.
compute_luma_sq_error_sum(uint32_t * square_diff,uint32_t * luma_sse_sum,int block_height,int block_width,int ss_x_shift,int ss_y_shift)576 static void compute_luma_sq_error_sum(uint32_t *square_diff,
577                                       uint32_t *luma_sse_sum, int block_height,
578                                       int block_width, int ss_x_shift,
579                                       int ss_y_shift) {
580   for (int i = 0; i < block_height; ++i) {
581     for (int j = 0; j < block_width; ++j) {
582       for (int ii = 0; ii < (1 << ss_y_shift); ++ii) {
583         for (int jj = 0; jj < (1 << ss_x_shift); ++jj) {
584           const int yy = (i << ss_y_shift) + ii;     // Y-coord on Y-plane.
585           const int xx = (j << ss_x_shift) + jj;     // X-coord on Y-plane.
586           const int ww = block_width << ss_x_shift;  // Width of Y-plane.
587           luma_sse_sum[i * block_width + j] += square_diff[yy * ww + xx];
588         }
589       }
590     }
591   }
592 }
593 
594 /*!\endcond */
595 /*!\brief Applies temporal filtering. NOTE that there are various optimised
596  * versions of this function called where the appropriate instruction set is
597  * supported.
598  *
599  * \ingroup src_frame_proc
600  * \param[in]   frame_to_filter Pointer to the frame to be filtered, which is
601  *                              used as reference to compute squared
602  *                              difference from the predictor.
603  * \param[in]   mbd             Pointer to the block for filtering, ONLY used
604  *                              to get subsampling information for the  planes
605  * \param[in]   block_size      Size of the block
606  * \param[in]   mb_row          Row index of the block in the frame
607  * \param[in]   mb_col          Column index of the block in the frame
608  * \param[in]   num_planes      Number of planes in the frame
609  * \param[in]   noise_levels    Estimated noise levels for each plane
610  *                              in the frame (Y,U,V)
611  * \param[in]   subblock_mvs    Pointer to the motion vectors for 4 sub-blocks
612  * \param[in]   subblock_mses   Pointer to the search errors (MSE) for 4
613  *                              sub-blocks
614  * \param[in]   q_factor        Quantization factor. This is actually the `q`
615  *                              defined in libaom, converted from `qindex`
616  * \param[in]   filter_strength Filtering strength. This value lies in range
617  *                              [0, 6] where 6 is the maximum strength.
618  * \param[in]   tf_wgt_calc_lvl Controls the weight calculation method during
619  *                              temporal filtering
620  * \param[out]  pred            Pointer to the well-built predictors
621  * \param[out]  accum           Pointer to the pixel-wise accumulator for
622  *                              filtering
623  * \param[out]  count           Pointer to the pixel-wise counter for
624  *                              filtering
625  *
626  * \remark Nothing returned, But the contents of `accum`, `pred` and 'count'
627  *         will be modified
628  */
av1_apply_temporal_filter_c(const YV12_BUFFER_CONFIG * frame_to_filter,const MACROBLOCKD * mbd,const BLOCK_SIZE block_size,const int mb_row,const int mb_col,const int num_planes,const double * noise_levels,const MV * subblock_mvs,const int * subblock_mses,const int q_factor,const int filter_strength,int tf_wgt_calc_lvl,const uint8_t * pred,uint32_t * accum,uint16_t * count)629 void av1_apply_temporal_filter_c(
630     const YV12_BUFFER_CONFIG *frame_to_filter, const MACROBLOCKD *mbd,
631     const BLOCK_SIZE block_size, const int mb_row, const int mb_col,
632     const int num_planes, const double *noise_levels, const MV *subblock_mvs,
633     const int *subblock_mses, const int q_factor, const int filter_strength,
634     int tf_wgt_calc_lvl, const uint8_t *pred, uint32_t *accum,
635     uint16_t *count) {
636   // Block information.
637   const int mb_height = block_size_high[block_size];
638   const int mb_width = block_size_wide[block_size];
639   const int mb_pels = mb_height * mb_width;
640   const int is_high_bitdepth = is_frame_high_bitdepth(frame_to_filter);
641   const uint16_t *pred16 = CONVERT_TO_SHORTPTR(pred);
642   // Frame information.
643   const int frame_height = frame_to_filter->y_crop_height;
644   const int frame_width = frame_to_filter->y_crop_width;
645   const int min_frame_size = AOMMIN(frame_height, frame_width);
646   // Variables to simplify combined error calculation.
647   const double inv_factor = 1.0 / ((TF_WINDOW_BLOCK_BALANCE_WEIGHT + 1) *
648                                    TF_SEARCH_ERROR_NORM_WEIGHT);
649   const double weight_factor =
650       (double)TF_WINDOW_BLOCK_BALANCE_WEIGHT * inv_factor;
651   // Decay factors for non-local mean approach.
652   double decay_factor[MAX_MB_PLANE] = { 0 };
653   // Adjust filtering based on q.
654   // Larger q -> stronger filtering -> larger weight.
655   // Smaller q -> weaker filtering -> smaller weight.
656   double q_decay = pow((double)q_factor / TF_Q_DECAY_THRESHOLD, 2);
657   q_decay = CLIP(q_decay, 1e-5, 1);
658   if (q_factor >= TF_QINDEX_CUTOFF) {
659     // Max q_factor is 255, therefore the upper bound of q_decay is 8.
660     // We do not need a clip here.
661     q_decay = 0.5 * pow((double)q_factor / 64, 2);
662   }
663   // Smaller strength -> smaller filtering weight.
664   double s_decay = pow((double)filter_strength / TF_STRENGTH_THRESHOLD, 2);
665   s_decay = CLIP(s_decay, 1e-5, 1);
666   for (int plane = 0; plane < num_planes; plane++) {
667     // Larger noise -> larger filtering weight.
668     const double n_decay = 0.5 + log(2 * noise_levels[plane] + 5.0);
669     decay_factor[plane] = 1 / (n_decay * q_decay * s_decay);
670   }
671   double d_factor[4] = { 0 };
672   for (int subblock_idx = 0; subblock_idx < 4; subblock_idx++) {
673     // Larger motion vector -> smaller filtering weight.
674     const MV mv = subblock_mvs[subblock_idx];
675     const double distance = sqrt(pow(mv.row, 2) + pow(mv.col, 2));
676     double distance_threshold = min_frame_size * TF_SEARCH_DISTANCE_THRESHOLD;
677     distance_threshold = AOMMAX(distance_threshold, 1);
678     d_factor[subblock_idx] = distance / distance_threshold;
679     d_factor[subblock_idx] = AOMMAX(d_factor[subblock_idx], 1);
680   }
681 
682   // Allocate memory for pixel-wise squared differences. They,
683   // regardless of the subsampling, are assigned with memory of size `mb_pels`.
684   uint32_t *square_diff = aom_memalign(16, mb_pels * sizeof(uint32_t));
685   if (!square_diff) {
686     aom_internal_error(mbd->error_info, AOM_CODEC_MEM_ERROR,
687                        "Error allocating temporal filter data");
688   }
689   memset(square_diff, 0, mb_pels * sizeof(square_diff[0]));
690 
691   // Allocate memory for accumulated luma squared error. This value will be
692   // consumed while filtering the chroma planes.
693   uint32_t *luma_sse_sum = aom_memalign(32, mb_pels * sizeof(uint32_t));
694   if (!luma_sse_sum) {
695     aom_free(square_diff);
696     aom_internal_error(mbd->error_info, AOM_CODEC_MEM_ERROR,
697                        "Error allocating temporal filter data");
698   }
699   memset(luma_sse_sum, 0, mb_pels * sizeof(luma_sse_sum[0]));
700 
701   // Get window size for pixel-wise filtering.
702   assert(TF_WINDOW_LENGTH % 2 == 1);
703   const int half_window = TF_WINDOW_LENGTH >> 1;
704 
705   // Handle planes in sequence.
706   int plane_offset = 0;
707   for (int plane = 0; plane < num_planes; ++plane) {
708     // Locate pixel on reference frame.
709     const int subsampling_y = mbd->plane[plane].subsampling_y;
710     const int subsampling_x = mbd->plane[plane].subsampling_x;
711     const int h = mb_height >> subsampling_y;  // Plane height.
712     const int w = mb_width >> subsampling_x;   // Plane width.
713     const int frame_stride =
714         frame_to_filter->strides[plane == AOM_PLANE_Y ? 0 : 1];
715     const int frame_offset = mb_row * h * frame_stride + mb_col * w;
716     const uint8_t *ref = frame_to_filter->buffers[plane];
717     const int ss_y_shift =
718         subsampling_y - mbd->plane[AOM_PLANE_Y].subsampling_y;
719     const int ss_x_shift =
720         subsampling_x - mbd->plane[AOM_PLANE_Y].subsampling_x;
721     const int num_ref_pixels = TF_WINDOW_LENGTH * TF_WINDOW_LENGTH +
722                                ((plane) ? (1 << (ss_x_shift + ss_y_shift)) : 0);
723     const double inv_num_ref_pixels = 1.0 / num_ref_pixels;
724 
725     // Filter U-plane and V-plane using Y-plane. This is because motion
726     // search is only done on Y-plane, so the information from Y-plane will
727     // be more accurate. The luma sse sum is reused in both chroma planes.
728     if (plane == AOM_PLANE_U)
729       compute_luma_sq_error_sum(square_diff, luma_sse_sum, h, w, ss_x_shift,
730                                 ss_y_shift);
731     compute_square_diff(ref, frame_offset, frame_stride, pred, plane_offset, w,
732                         h, w, is_high_bitdepth, square_diff);
733 
734     // Perform filtering.
735     int pred_idx = 0;
736     for (int i = 0; i < h; ++i) {
737       for (int j = 0; j < w; ++j) {
738         // non-local mean approach
739         uint64_t sum_square_diff = 0;
740 
741         for (int wi = -half_window; wi <= half_window; ++wi) {
742           for (int wj = -half_window; wj <= half_window; ++wj) {
743             const int y = CLIP(i + wi, 0, h - 1);  // Y-coord on current plane.
744             const int x = CLIP(j + wj, 0, w - 1);  // X-coord on current plane.
745             sum_square_diff += square_diff[y * w + x];
746           }
747         }
748 
749         sum_square_diff += luma_sse_sum[i * w + j];
750 
751         // Scale down the difference for high bit depth input.
752         if (mbd->bd > 8) sum_square_diff >>= ((mbd->bd - 8) * 2);
753 
754         // Combine window error and block error, and normalize it.
755         const double window_error = sum_square_diff * inv_num_ref_pixels;
756         const int subblock_idx = (i >= h / 2) * 2 + (j >= w / 2);
757         const double block_error = (double)subblock_mses[subblock_idx];
758         const double combined_error =
759             weight_factor * window_error + block_error * inv_factor;
760 
761         // Compute filter weight.
762         double scaled_error =
763             combined_error * d_factor[subblock_idx] * decay_factor[plane];
764         scaled_error = AOMMIN(scaled_error, 7);
765         int weight;
766         if (tf_wgt_calc_lvl == 0) {
767           weight = (int)(exp(-scaled_error) * TF_WEIGHT_SCALE);
768         } else {
769           const float fweight =
770               approx_exp((float)-scaled_error) * TF_WEIGHT_SCALE;
771           weight = iroundpf(fweight);
772         }
773 
774         const int idx = plane_offset + pred_idx;  // Index with plane shift.
775         const int pred_value = is_high_bitdepth ? pred16[idx] : pred[idx];
776         accum[idx] += weight * pred_value;
777         count[idx] += weight;
778 
779         ++pred_idx;
780       }
781     }
782     plane_offset += h * w;
783   }
784 
785   aom_free(square_diff);
786   aom_free(luma_sse_sum);
787 }
788 #if CONFIG_AV1_HIGHBITDEPTH
789 // Calls High bit-depth temporal filter
av1_highbd_apply_temporal_filter_c(const YV12_BUFFER_CONFIG * frame_to_filter,const MACROBLOCKD * mbd,const BLOCK_SIZE block_size,const int mb_row,const int mb_col,const int num_planes,const double * noise_levels,const MV * subblock_mvs,const int * subblock_mses,const int q_factor,const int filter_strength,int tf_wgt_calc_lvl,const uint8_t * pred,uint32_t * accum,uint16_t * count)790 void av1_highbd_apply_temporal_filter_c(
791     const YV12_BUFFER_CONFIG *frame_to_filter, const MACROBLOCKD *mbd,
792     const BLOCK_SIZE block_size, const int mb_row, const int mb_col,
793     const int num_planes, const double *noise_levels, const MV *subblock_mvs,
794     const int *subblock_mses, const int q_factor, const int filter_strength,
795     int tf_wgt_calc_lvl, const uint8_t *pred, uint32_t *accum,
796     uint16_t *count) {
797   av1_apply_temporal_filter_c(frame_to_filter, mbd, block_size, mb_row, mb_col,
798                               num_planes, noise_levels, subblock_mvs,
799                               subblock_mses, q_factor, filter_strength,
800                               tf_wgt_calc_lvl, pred, accum, count);
801 }
802 #endif  // CONFIG_AV1_HIGHBITDEPTH
803 /*!\brief Normalizes the accumulated filtering result to produce the filtered
804  *        frame
805  *
806  * \ingroup src_frame_proc
807  * \param[in]   mbd            Pointer to the block for filtering, which is
808  *                             ONLY used to get subsampling information for
809  *                             all the planes
810  * \param[in]   block_size     Size of the block
811  * \param[in]   mb_row         Row index of the block in the frame
812  * \param[in]   mb_col         Column index of the block in the frame
813  * \param[in]   num_planes     Number of planes in the frame
814  * \param[in]   accum          Pointer to the pre-computed accumulator
815  * \param[in]   count          Pointer to the pre-computed count
816  * \param[out]  result_buffer  Pointer to result buffer
817  *
818  * \remark Nothing returned, but the content to which `result_buffer` pointer
819  *         will be modified
820  */
tf_normalize_filtered_frame(const MACROBLOCKD * mbd,const BLOCK_SIZE block_size,const int mb_row,const int mb_col,const int num_planes,const uint32_t * accum,const uint16_t * count,YV12_BUFFER_CONFIG * result_buffer)821 static void tf_normalize_filtered_frame(
822     const MACROBLOCKD *mbd, const BLOCK_SIZE block_size, const int mb_row,
823     const int mb_col, const int num_planes, const uint32_t *accum,
824     const uint16_t *count, YV12_BUFFER_CONFIG *result_buffer) {
825   // Block information.
826   const int mb_height = block_size_high[block_size];
827   const int mb_width = block_size_wide[block_size];
828   const int is_high_bitdepth = is_frame_high_bitdepth(result_buffer);
829 
830   int plane_offset = 0;
831   for (int plane = 0; plane < num_planes; ++plane) {
832     const int plane_h = mb_height >> mbd->plane[plane].subsampling_y;
833     const int plane_w = mb_width >> mbd->plane[plane].subsampling_x;
834     const int frame_stride = result_buffer->strides[plane == 0 ? 0 : 1];
835     const int frame_offset = mb_row * plane_h * frame_stride + mb_col * plane_w;
836     uint8_t *const buf = result_buffer->buffers[plane];
837     uint16_t *const buf16 = CONVERT_TO_SHORTPTR(buf);
838 
839     int plane_idx = 0;             // Pixel index on current plane (block-base).
840     int frame_idx = frame_offset;  // Pixel index on the entire frame.
841     for (int i = 0; i < plane_h; ++i) {
842       for (int j = 0; j < plane_w; ++j) {
843         const int idx = plane_idx + plane_offset;
844         const uint16_t rounding = count[idx] >> 1;
845         if (is_high_bitdepth) {
846           buf16[frame_idx] =
847               (uint16_t)OD_DIVU(accum[idx] + rounding, count[idx]);
848         } else {
849           buf[frame_idx] = (uint8_t)OD_DIVU(accum[idx] + rounding, count[idx]);
850         }
851         ++plane_idx;
852         ++frame_idx;
853       }
854       frame_idx += (frame_stride - plane_w);
855     }
856     plane_offset += plane_h * plane_w;
857   }
858 }
859 
av1_tf_do_filtering_row(AV1_COMP * cpi,ThreadData * td,int mb_row)860 void av1_tf_do_filtering_row(AV1_COMP *cpi, ThreadData *td, int mb_row) {
861   TemporalFilterCtx *tf_ctx = &cpi->tf_ctx;
862   YV12_BUFFER_CONFIG **frames = tf_ctx->frames;
863   const int num_frames = tf_ctx->num_frames;
864   const int filter_frame_idx = tf_ctx->filter_frame_idx;
865   const int compute_frame_diff = tf_ctx->compute_frame_diff;
866   const struct scale_factors *scale = &tf_ctx->sf;
867   const double *noise_levels = tf_ctx->noise_levels;
868   const int num_pels = tf_ctx->num_pels;
869   const int q_factor = tf_ctx->q_factor;
870   const BLOCK_SIZE block_size = TF_BLOCK_SIZE;
871   const YV12_BUFFER_CONFIG *const frame_to_filter = frames[filter_frame_idx];
872   MACROBLOCK *const mb = &td->mb;
873   MACROBLOCKD *const mbd = &mb->e_mbd;
874   TemporalFilterData *const tf_data = &td->tf_data;
875   const int mb_height = block_size_high[block_size];
876   const int mb_width = block_size_wide[block_size];
877   const int mi_h = mi_size_high_log2[block_size];
878   const int mi_w = mi_size_wide_log2[block_size];
879   const int num_planes = av1_num_planes(&cpi->common);
880   const int weight_calc_level_in_tf = cpi->sf.hl_sf.weight_calc_level_in_tf;
881   uint32_t *accum = tf_data->accum;
882   uint16_t *count = tf_data->count;
883   uint8_t *pred = tf_data->pred;
884 
885   // Factor to control the filering strength.
886   const int filter_strength = cpi->oxcf.algo_cfg.arnr_strength;
887 
888   // Do filtering.
889   FRAME_DIFF *diff = &td->tf_data.diff;
890   av1_set_mv_row_limits(&cpi->common.mi_params, &mb->mv_limits,
891                         (mb_row << mi_h), (mb_height >> MI_SIZE_LOG2),
892                         cpi->oxcf.border_in_pixels);
893   for (int mb_col = 0; mb_col < tf_ctx->mb_cols; mb_col++) {
894     av1_set_mv_col_limits(&cpi->common.mi_params, &mb->mv_limits,
895                           (mb_col << mi_w), (mb_width >> MI_SIZE_LOG2),
896                           cpi->oxcf.border_in_pixels);
897     memset(accum, 0, num_pels * sizeof(accum[0]));
898     memset(count, 0, num_pels * sizeof(count[0]));
899     MV ref_mv = kZeroMv;  // Reference motion vector passed down along frames.
900                           // Perform temporal filtering frame by frame.
901 
902     // Decide whether to perform motion search at 16x16 sub-block level or not
903     // based on 4x4 sub-blocks source variance. Allow motion search for split
904     // partition only if the difference between max and min source variance of
905     // 4x4 blocks is greater than a threshold (which is derived empirically).
906     bool allow_me_for_sub_blks = true;
907     if (cpi->sf.hl_sf.allow_sub_blk_me_in_tf) {
908       const int is_hbd = is_frame_high_bitdepth(frame_to_filter);
909       // Initialize minimum variance to a large value and maximum variance to 0.
910       double blk_4x4_var_min = DBL_MAX;
911       double blk_4x4_var_max = 0;
912       get_log_var_4x4sub_blk(cpi, frame_to_filter, mb_row, mb_col,
913                              TF_BLOCK_SIZE, &blk_4x4_var_min, &blk_4x4_var_max,
914                              is_hbd);
915       // TODO([email protected]): Experiment and adjust the
916       // threshold for high bit depth.
917       if ((blk_4x4_var_max - blk_4x4_var_min) <= 4.0)
918         allow_me_for_sub_blks = false;
919     }
920 
921     for (int frame = 0; frame < num_frames; frame++) {
922       if (frames[frame] == NULL) continue;
923 
924       // Motion search.
925       MV subblock_mvs[4] = { kZeroMv, kZeroMv, kZeroMv, kZeroMv };
926       int subblock_mses[4] = { INT_MAX, INT_MAX, INT_MAX, INT_MAX };
927       if (frame ==
928           filter_frame_idx) {  // Frame to be filtered.
929                                // Change ref_mv sign for following frames.
930         ref_mv.row *= -1;
931         ref_mv.col *= -1;
932       } else {  // Other reference frames.
933         tf_motion_search(cpi, mb, frame_to_filter, frames[frame], block_size,
934                          mb_row, mb_col, &ref_mv, allow_me_for_sub_blks,
935                          subblock_mvs, subblock_mses);
936       }
937 
938       // Perform weighted averaging.
939       if (frame == filter_frame_idx) {  // Frame to be filtered.
940         tf_apply_temporal_filter_self(frames[frame], mbd, block_size, mb_row,
941                                       mb_col, num_planes, accum, count);
942       } else {  // Other reference frames.
943         tf_build_predictor(frames[frame], mbd, block_size, mb_row, mb_col,
944                            num_planes, scale, subblock_mvs, pred);
945 
946         // All variants of av1_apply_temporal_filter() contain floating point
947         // operations. Hence, clear the system state.
948 
949         // TODO(any): avx2/sse2 version should be changed to align with C
950         // function before using. In particular, current avx2/sse2 function
951         // only supports 32x32 block size and 5x5 filtering window.
952         if (is_frame_high_bitdepth(frame_to_filter)) {  // for high bit-depth
953 #if CONFIG_AV1_HIGHBITDEPTH
954           if (TF_BLOCK_SIZE == BLOCK_32X32 && TF_WINDOW_LENGTH == 5) {
955             av1_highbd_apply_temporal_filter(
956                 frame_to_filter, mbd, block_size, mb_row, mb_col, num_planes,
957                 noise_levels, subblock_mvs, subblock_mses, q_factor,
958                 filter_strength, weight_calc_level_in_tf, pred, accum, count);
959           } else {
960 #endif  // CONFIG_AV1_HIGHBITDEPTH
961             av1_apply_temporal_filter_c(
962                 frame_to_filter, mbd, block_size, mb_row, mb_col, num_planes,
963                 noise_levels, subblock_mvs, subblock_mses, q_factor,
964                 filter_strength, weight_calc_level_in_tf, pred, accum, count);
965 #if CONFIG_AV1_HIGHBITDEPTH
966           }
967 #endif  // CONFIG_AV1_HIGHBITDEPTH
968         } else {
969           // for 8-bit
970           if (TF_BLOCK_SIZE == BLOCK_32X32 && TF_WINDOW_LENGTH == 5) {
971             av1_apply_temporal_filter(
972                 frame_to_filter, mbd, block_size, mb_row, mb_col, num_planes,
973                 noise_levels, subblock_mvs, subblock_mses, q_factor,
974                 filter_strength, weight_calc_level_in_tf, pred, accum, count);
975           } else {
976             av1_apply_temporal_filter_c(
977                 frame_to_filter, mbd, block_size, mb_row, mb_col, num_planes,
978                 noise_levels, subblock_mvs, subblock_mses, q_factor,
979                 filter_strength, weight_calc_level_in_tf, pred, accum, count);
980           }
981         }
982       }
983     }
984     tf_normalize_filtered_frame(mbd, block_size, mb_row, mb_col, num_planes,
985                                 accum, count, tf_ctx->output_frame);
986 
987     if (compute_frame_diff) {
988       const int y_height = mb_height >> mbd->plane[0].subsampling_y;
989       const int y_width = mb_width >> mbd->plane[0].subsampling_x;
990       const int source_y_stride = frame_to_filter->y_stride;
991       const int filter_y_stride = tf_ctx->output_frame->y_stride;
992       const int source_offset =
993           mb_row * y_height * source_y_stride + mb_col * y_width;
994       const int filter_offset =
995           mb_row * y_height * filter_y_stride + mb_col * y_width;
996       unsigned int sse = 0;
997       cpi->ppi->fn_ptr[block_size].vf(
998           frame_to_filter->y_buffer + source_offset, source_y_stride,
999           tf_ctx->output_frame->y_buffer + filter_offset, filter_y_stride,
1000           &sse);
1001       diff->sum += sse;
1002       diff->sse += sse * (int64_t)sse;
1003     }
1004   }
1005 }
1006 
1007 /*!\brief Does temporal filter for a given frame.
1008  *
1009  * \ingroup src_frame_proc
1010  * \param[in]   cpi                   Top level encoder instance structure
1011  *
1012  * \remark Nothing will be returned, but the contents of td->diff will be
1013  modified.
1014  */
tf_do_filtering(AV1_COMP * cpi)1015 static void tf_do_filtering(AV1_COMP *cpi) {
1016   // Basic information.
1017   ThreadData *td = &cpi->td;
1018   TemporalFilterCtx *tf_ctx = &cpi->tf_ctx;
1019   const struct scale_factors *scale = &tf_ctx->sf;
1020   const int num_planes = av1_num_planes(&cpi->common);
1021   assert(num_planes >= 1 && num_planes <= MAX_MB_PLANE);
1022 
1023   MACROBLOCKD *mbd = &td->mb.e_mbd;
1024   uint8_t *input_buffer[MAX_MB_PLANE];
1025   MB_MODE_INFO **input_mb_mode_info;
1026   tf_save_state(mbd, &input_mb_mode_info, input_buffer, num_planes);
1027   tf_setup_macroblockd(mbd, &td->tf_data, scale);
1028 
1029   // Perform temporal filtering for each row.
1030   for (int mb_row = 0; mb_row < tf_ctx->mb_rows; mb_row++)
1031     av1_tf_do_filtering_row(cpi, td, mb_row);
1032 
1033   tf_restore_state(mbd, input_mb_mode_info, input_buffer, num_planes);
1034 }
1035 
1036 /*!\brief Setups the frame buffer for temporal filtering. This fuction
1037  * determines how many frames will be used for temporal filtering and then
1038  * groups them into a buffer. This function will also estimate the noise level
1039  * of the to-filter frame.
1040  *
1041  * \ingroup src_frame_proc
1042  * \param[in]   cpi             Top level encoder instance structure
1043  * \param[in]   filter_frame_lookahead_idx  The index of the to-filter frame
1044  *                              in the lookahead buffer cpi->lookahead
1045  * \param[in]   gf_frame_index  GOP index
1046  *
1047  * \remark Nothing will be returned. But the fields `frames`, `num_frames`,
1048  *         `filter_frame_idx` and `noise_levels` will be updated in cpi->tf_ctx.
1049  */
tf_setup_filtering_buffer(AV1_COMP * cpi,int filter_frame_lookahead_idx,int gf_frame_index)1050 static void tf_setup_filtering_buffer(AV1_COMP *cpi,
1051                                       int filter_frame_lookahead_idx,
1052                                       int gf_frame_index) {
1053   const GF_GROUP *gf_group = &cpi->ppi->gf_group;
1054   const FRAME_UPDATE_TYPE update_type = gf_group->update_type[gf_frame_index];
1055   const FRAME_TYPE frame_type = gf_group->frame_type[gf_frame_index];
1056   const int is_forward_keyframe =
1057       av1_gop_check_forward_keyframe(gf_group, gf_frame_index);
1058 
1059   TemporalFilterCtx *tf_ctx = &cpi->tf_ctx;
1060   YV12_BUFFER_CONFIG **frames = tf_ctx->frames;
1061   // Number of frames used for filtering. Set `arnr_max_frames` as 1 to disable
1062   // temporal filtering.
1063   int num_frames = AOMMAX(cpi->oxcf.algo_cfg.arnr_max_frames, 1);
1064   int num_before = 0;  // Number of filtering frames before the to-filter frame.
1065   int num_after = 0;   // Number of filtering frames after the to-filer frame.
1066   const int lookahead_depth =
1067       av1_lookahead_depth(cpi->ppi->lookahead, cpi->compressor_stage);
1068 
1069   // Temporal filtering should not go beyond key frames
1070   const int key_to_curframe =
1071       AOMMAX(cpi->rc.frames_since_key + filter_frame_lookahead_idx, 0);
1072   const int curframe_to_key =
1073       AOMMAX(cpi->rc.frames_to_key - filter_frame_lookahead_idx - 1, 0);
1074 
1075   // Number of buffered frames before the to-filter frame.
1076   int max_before = AOMMIN(filter_frame_lookahead_idx, key_to_curframe);
1077 
1078   // Number of buffered frames after the to-filter frame.
1079   int max_after =
1080       AOMMIN(lookahead_depth - filter_frame_lookahead_idx - 1, curframe_to_key);
1081 
1082   // Estimate noises for each plane.
1083   const struct lookahead_entry *to_filter_buf = av1_lookahead_peek(
1084       cpi->ppi->lookahead, filter_frame_lookahead_idx, cpi->compressor_stage);
1085   assert(to_filter_buf != NULL);
1086   const YV12_BUFFER_CONFIG *to_filter_frame = &to_filter_buf->img;
1087   const int num_planes = av1_num_planes(&cpi->common);
1088   double *noise_levels = tf_ctx->noise_levels;
1089   av1_estimate_noise_level(to_filter_frame, noise_levels, AOM_PLANE_Y,
1090                            num_planes - 1, cpi->common.seq_params->bit_depth,
1091                            NOISE_ESTIMATION_EDGE_THRESHOLD);
1092   // Get quantization factor.
1093   const int q = get_q(cpi);
1094   // Get correlation estimates from first-pass;
1095   const FIRSTPASS_STATS *stats =
1096       cpi->twopass_frame.stats_in - (cpi->rc.frames_since_key == 0);
1097   double accu_coeff0 = 1.0, accu_coeff1 = 1.0;
1098   for (int i = 1; i <= max_after; i++) {
1099     if (stats + filter_frame_lookahead_idx + i >=
1100         cpi->ppi->twopass.stats_buf_ctx->stats_in_end) {
1101       max_after = i - 1;
1102       break;
1103     }
1104     accu_coeff1 *=
1105         AOMMAX(stats[filter_frame_lookahead_idx + i].cor_coeff, 0.001);
1106   }
1107   if (max_after >= 1) {
1108     accu_coeff1 = pow(accu_coeff1, 1.0 / (double)max_after);
1109   }
1110   for (int i = 1; i <= max_before; i++) {
1111     if (stats + filter_frame_lookahead_idx - i + 1 <=
1112         cpi->ppi->twopass.stats_buf_ctx->stats_in_start) {
1113       max_before = i - 1;
1114       break;
1115     }
1116     accu_coeff0 *=
1117         AOMMAX(stats[filter_frame_lookahead_idx - i + 1].cor_coeff, 0.001);
1118   }
1119   if (max_before >= 1) {
1120     accu_coeff0 = pow(accu_coeff0, 1.0 / (double)max_before);
1121   }
1122 
1123   // Adjust number of filtering frames based on quantization factor. When the
1124   // quantization factor is small enough (lossless compression), we will not
1125   // change the number of frames for key frame filtering, which is to avoid
1126   // visual quality drop.
1127   int adjust_num = 6;
1128   const int adjust_num_frames_for_arf_filtering =
1129       cpi->sf.hl_sf.adjust_num_frames_for_arf_filtering;
1130   if (num_frames == 1) {  // `arnr_max_frames = 1` is used to disable filtering.
1131     adjust_num = 0;
1132   } else if ((update_type == KF_UPDATE) && q <= 10) {
1133     adjust_num = 0;
1134   } else if (adjust_num_frames_for_arf_filtering > 0 &&
1135              update_type != KF_UPDATE && (cpi->rc.frames_since_key > 0)) {
1136     // Since screen content detection happens after temporal filtering,
1137     // 'frames_since_key' check is added to ensure the sf is disabled for the
1138     // first alt-ref frame.
1139     // Adjust number of frames to be considered for filtering based on noise
1140     // level of the current frame. For low-noise frame, use more frames to
1141     // filter such that the filtered frame can provide better predictions for
1142     // subsequent frames and vice versa.
1143     const uint8_t av1_adjust_num_using_noise_lvl[2][3] = { { 6, 4, 2 },
1144                                                            { 4, 2, 0 } };
1145     const uint8_t *adjust_num_frames =
1146         av1_adjust_num_using_noise_lvl[adjust_num_frames_for_arf_filtering - 1];
1147 
1148     if (noise_levels[AOM_PLANE_Y] < 0.5)
1149       adjust_num = adjust_num_frames[0];
1150     else if (noise_levels[AOM_PLANE_Y] < 1.0)
1151       adjust_num = adjust_num_frames[1];
1152     else
1153       adjust_num = adjust_num_frames[2];
1154   }
1155   num_frames = AOMMIN(num_frames + adjust_num, lookahead_depth);
1156 
1157   if (frame_type == KEY_FRAME) {
1158     num_before = AOMMIN(is_forward_keyframe ? num_frames / 2 : 0, max_before);
1159     num_after = AOMMIN(num_frames - 1, max_after);
1160   } else {
1161     int gfu_boost = av1_calc_arf_boost(&cpi->ppi->twopass, &cpi->twopass_frame,
1162                                        &cpi->ppi->p_rc, &cpi->frame_info,
1163                                        filter_frame_lookahead_idx, max_before,
1164                                        max_after, NULL, NULL, 0);
1165 
1166     num_frames = AOMMIN(num_frames, gfu_boost / 150);
1167     num_frames += !(num_frames & 1);  // Make the number odd.
1168 
1169     // Only use 2 neighbours for the second ARF.
1170     if (update_type == INTNL_ARF_UPDATE) num_frames = AOMMIN(num_frames, 3);
1171     if (AOMMIN(max_after, max_before) >= num_frames / 2) {
1172       // just use half half
1173       num_before = num_frames / 2;
1174       num_after = num_frames / 2;
1175     } else {
1176       if (max_after < num_frames / 2) {
1177         num_after = max_after;
1178         num_before = AOMMIN(num_frames - 1 - num_after, max_before);
1179       } else {
1180         num_before = max_before;
1181         num_after = AOMMIN(num_frames - 1 - num_before, max_after);
1182       }
1183       // Adjust insymmetry based on frame-level correlation
1184       if (max_after > 0 && max_before > 0) {
1185         if (num_after < num_before) {
1186           const int insym = (int)(0.4 / AOMMAX(1 - accu_coeff1, 0.01));
1187           num_before = AOMMIN(num_before, num_after + insym);
1188         } else {
1189           const int insym = (int)(0.4 / AOMMAX(1 - accu_coeff0, 0.01));
1190           num_after = AOMMIN(num_after, num_before + insym);
1191         }
1192       }
1193     }
1194   }
1195   num_frames = num_before + 1 + num_after;
1196 
1197   // Setup the frame buffer.
1198   for (int frame = 0; frame < num_frames; ++frame) {
1199     const int lookahead_idx = frame - num_before + filter_frame_lookahead_idx;
1200     struct lookahead_entry *buf = av1_lookahead_peek(
1201         cpi->ppi->lookahead, lookahead_idx, cpi->compressor_stage);
1202     assert(buf != NULL);
1203     frames[frame] = &buf->img;
1204   }
1205   tf_ctx->num_frames = num_frames;
1206   tf_ctx->filter_frame_idx = num_before;
1207   assert(frames[tf_ctx->filter_frame_idx] == to_filter_frame);
1208 
1209   av1_setup_src_planes(&cpi->td.mb, &to_filter_buf->img, 0, 0, num_planes,
1210                        cpi->common.seq_params->sb_size);
1211   av1_setup_block_planes(&cpi->td.mb.e_mbd,
1212                          cpi->common.seq_params->subsampling_x,
1213                          cpi->common.seq_params->subsampling_y, num_planes);
1214 }
1215 
1216 /*!\cond */
1217 
av1_estimate_noise_from_single_plane_c(const uint8_t * src,int height,int width,int stride,int edge_thresh)1218 double av1_estimate_noise_from_single_plane_c(const uint8_t *src, int height,
1219                                               int width, int stride,
1220                                               int edge_thresh) {
1221   int64_t accum = 0;
1222   int count = 0;
1223 
1224   for (int i = 1; i < height - 1; ++i) {
1225     for (int j = 1; j < width - 1; ++j) {
1226       // Setup a small 3x3 matrix.
1227       const int center_idx = i * stride + j;
1228       int mat[3][3];
1229       for (int ii = -1; ii <= 1; ++ii) {
1230         for (int jj = -1; jj <= 1; ++jj) {
1231           const int idx = center_idx + ii * stride + jj;
1232           mat[ii + 1][jj + 1] = src[idx];
1233         }
1234       }
1235       // Compute sobel gradients.
1236       const int Gx = (mat[0][0] - mat[0][2]) + (mat[2][0] - mat[2][2]) +
1237                      2 * (mat[1][0] - mat[1][2]);
1238       const int Gy = (mat[0][0] - mat[2][0]) + (mat[0][2] - mat[2][2]) +
1239                      2 * (mat[0][1] - mat[2][1]);
1240       const int Ga = ROUND_POWER_OF_TWO(abs(Gx) + abs(Gy), 0);
1241       // Accumulate Laplacian.
1242       if (Ga < edge_thresh) {  // Only count smooth pixels.
1243         const int v = 4 * mat[1][1] -
1244                       2 * (mat[0][1] + mat[2][1] + mat[1][0] + mat[1][2]) +
1245                       (mat[0][0] + mat[0][2] + mat[2][0] + mat[2][2]);
1246         accum += ROUND_POWER_OF_TWO(abs(v), 0);
1247         ++count;
1248       }
1249     }
1250   }
1251 
1252   // Return -1.0 (unreliable estimation) if there are too few smooth pixels.
1253   return (count < 16) ? -1.0 : (double)accum / (6 * count) * SQRT_PI_BY_2;
1254 }
1255 
1256 #if CONFIG_AV1_HIGHBITDEPTH
av1_highbd_estimate_noise_from_single_plane_c(const uint16_t * src16,int height,int width,const int stride,int bit_depth,int edge_thresh)1257 double av1_highbd_estimate_noise_from_single_plane_c(const uint16_t *src16,
1258                                                      int height, int width,
1259                                                      const int stride,
1260                                                      int bit_depth,
1261                                                      int edge_thresh) {
1262   int64_t accum = 0;
1263   int count = 0;
1264   for (int i = 1; i < height - 1; ++i) {
1265     for (int j = 1; j < width - 1; ++j) {
1266       // Setup a small 3x3 matrix.
1267       const int center_idx = i * stride + j;
1268       int mat[3][3];
1269       for (int ii = -1; ii <= 1; ++ii) {
1270         for (int jj = -1; jj <= 1; ++jj) {
1271           const int idx = center_idx + ii * stride + jj;
1272           mat[ii + 1][jj + 1] = src16[idx];
1273         }
1274       }
1275       // Compute sobel gradients.
1276       const int Gx = (mat[0][0] - mat[0][2]) + (mat[2][0] - mat[2][2]) +
1277                      2 * (mat[1][0] - mat[1][2]);
1278       const int Gy = (mat[0][0] - mat[2][0]) + (mat[0][2] - mat[2][2]) +
1279                      2 * (mat[0][1] - mat[2][1]);
1280       const int Ga = ROUND_POWER_OF_TWO(abs(Gx) + abs(Gy), bit_depth - 8);
1281       // Accumulate Laplacian.
1282       if (Ga < edge_thresh) {  // Only count smooth pixels.
1283         const int v = 4 * mat[1][1] -
1284                       2 * (mat[0][1] + mat[2][1] + mat[1][0] + mat[1][2]) +
1285                       (mat[0][0] + mat[0][2] + mat[2][0] + mat[2][2]);
1286         accum += ROUND_POWER_OF_TWO(abs(v), bit_depth - 8);
1287         ++count;
1288       }
1289     }
1290   }
1291 
1292   // Return -1.0 (unreliable estimation) if there are too few smooth pixels.
1293   return (count < 16) ? -1.0 : (double)accum / (6 * count) * SQRT_PI_BY_2;
1294 }
1295 #endif
1296 
av1_estimate_noise_level(const YV12_BUFFER_CONFIG * frame,double * noise_level,int plane_from,int plane_to,int bit_depth,int edge_thresh)1297 void av1_estimate_noise_level(const YV12_BUFFER_CONFIG *frame,
1298                               double *noise_level, int plane_from, int plane_to,
1299                               int bit_depth, int edge_thresh) {
1300   for (int plane = plane_from; plane <= plane_to; plane++) {
1301     const bool is_uv_plane = (plane != AOM_PLANE_Y);
1302     const int height = frame->crop_heights[is_uv_plane];
1303     const int width = frame->crop_widths[is_uv_plane];
1304     const int stride = frame->strides[is_uv_plane];
1305     const uint8_t *src = frame->buffers[plane];
1306 
1307 #if CONFIG_AV1_HIGHBITDEPTH
1308     const uint16_t *src16 = CONVERT_TO_SHORTPTR(src);
1309     const int is_high_bitdepth = is_frame_high_bitdepth(frame);
1310     if (is_high_bitdepth) {
1311       noise_level[plane] = av1_highbd_estimate_noise_from_single_plane(
1312           src16, height, width, stride, bit_depth, edge_thresh);
1313     } else {
1314       noise_level[plane] = av1_estimate_noise_from_single_plane(
1315           src, height, width, stride, edge_thresh);
1316     }
1317 #else
1318     (void)bit_depth;
1319     noise_level[plane] = av1_estimate_noise_from_single_plane(
1320         src, height, width, stride, edge_thresh);
1321 #endif
1322   }
1323 }
1324 
1325 // Initializes the members of TemporalFilterCtx
1326 // Inputs:
1327 //   cpi: Top level encoder instance structure
1328 //   check_show_existing: If 1, check whether the filtered frame is similar
1329 //                        to the original frame.
1330 //   filter_frame_lookahead_idx: The index of the frame to be filtered in the
1331 //                               lookahead buffer cpi->lookahead.
1332 // Returns:
1333 //   Nothing will be returned. But the contents of cpi->tf_ctx will be modified.
init_tf_ctx(AV1_COMP * cpi,int filter_frame_lookahead_idx,int gf_frame_index,int compute_frame_diff,YV12_BUFFER_CONFIG * output_frame)1334 static void init_tf_ctx(AV1_COMP *cpi, int filter_frame_lookahead_idx,
1335                         int gf_frame_index, int compute_frame_diff,
1336                         YV12_BUFFER_CONFIG *output_frame) {
1337   TemporalFilterCtx *tf_ctx = &cpi->tf_ctx;
1338   // Setup frame buffer for filtering.
1339   YV12_BUFFER_CONFIG **frames = tf_ctx->frames;
1340   tf_ctx->num_frames = 0;
1341   tf_ctx->filter_frame_idx = -1;
1342   tf_ctx->output_frame = output_frame;
1343   tf_ctx->compute_frame_diff = compute_frame_diff;
1344   tf_setup_filtering_buffer(cpi, filter_frame_lookahead_idx, gf_frame_index);
1345   assert(tf_ctx->num_frames > 0);
1346   assert(tf_ctx->filter_frame_idx < tf_ctx->num_frames);
1347 
1348   // Setup scaling factors. Scaling on each of the arnr frames is not
1349   // supported.
1350   // ARF is produced at the native frame size and resized when coded.
1351   struct scale_factors *sf = &tf_ctx->sf;
1352   av1_setup_scale_factors_for_frame(
1353       sf, frames[0]->y_crop_width, frames[0]->y_crop_height,
1354       frames[0]->y_crop_width, frames[0]->y_crop_height);
1355 
1356   // Initialize temporal filter parameters.
1357   MACROBLOCKD *mbd = &cpi->td.mb.e_mbd;
1358   const int filter_frame_idx = tf_ctx->filter_frame_idx;
1359   const YV12_BUFFER_CONFIG *const frame_to_filter = frames[filter_frame_idx];
1360   const BLOCK_SIZE block_size = TF_BLOCK_SIZE;
1361   const int frame_height = frame_to_filter->y_crop_height;
1362   const int frame_width = frame_to_filter->y_crop_width;
1363   const int mb_width = block_size_wide[block_size];
1364   const int mb_height = block_size_high[block_size];
1365   const int mb_rows = get_num_blocks(frame_height, mb_height);
1366   const int mb_cols = get_num_blocks(frame_width, mb_width);
1367   const int mb_pels = mb_width * mb_height;
1368   const int is_highbitdepth = is_frame_high_bitdepth(frame_to_filter);
1369   const int num_planes = av1_num_planes(&cpi->common);
1370   int num_pels = 0;
1371   for (int i = 0; i < num_planes; i++) {
1372     const int subsampling_x = mbd->plane[i].subsampling_x;
1373     const int subsampling_y = mbd->plane[i].subsampling_y;
1374     num_pels += mb_pels >> (subsampling_x + subsampling_y);
1375   }
1376   tf_ctx->num_pels = num_pels;
1377   tf_ctx->mb_rows = mb_rows;
1378   tf_ctx->mb_cols = mb_cols;
1379   tf_ctx->is_highbitdepth = is_highbitdepth;
1380   tf_ctx->q_factor = get_q(cpi);
1381 }
1382 
av1_check_show_filtered_frame(const YV12_BUFFER_CONFIG * frame,const FRAME_DIFF * frame_diff,int q_index,aom_bit_depth_t bit_depth)1383 int av1_check_show_filtered_frame(const YV12_BUFFER_CONFIG *frame,
1384                                   const FRAME_DIFF *frame_diff, int q_index,
1385                                   aom_bit_depth_t bit_depth) {
1386   const int frame_height = frame->y_crop_height;
1387   const int frame_width = frame->y_crop_width;
1388   const int block_height = block_size_high[TF_BLOCK_SIZE];
1389   const int block_width = block_size_wide[TF_BLOCK_SIZE];
1390   const int mb_rows = get_num_blocks(frame_height, block_height);
1391   const int mb_cols = get_num_blocks(frame_width, block_width);
1392   const int num_mbs = AOMMAX(1, mb_rows * mb_cols);
1393   const float mean = (float)frame_diff->sum / num_mbs;
1394   const float std = (float)sqrt((float)frame_diff->sse / num_mbs - mean * mean);
1395 
1396   const int ac_q_step = av1_ac_quant_QTX(q_index, 0, bit_depth);
1397   const float threshold = 0.7f * ac_q_step * ac_q_step;
1398 
1399   if (mean < threshold && std < mean * 1.2) {
1400     return 1;
1401   }
1402   return 0;
1403 }
1404 
av1_temporal_filter(AV1_COMP * cpi,const int filter_frame_lookahead_idx,int gf_frame_index,FRAME_DIFF * frame_diff,YV12_BUFFER_CONFIG * output_frame)1405 void av1_temporal_filter(AV1_COMP *cpi, const int filter_frame_lookahead_idx,
1406                          int gf_frame_index, FRAME_DIFF *frame_diff,
1407                          YV12_BUFFER_CONFIG *output_frame) {
1408   MultiThreadInfo *const mt_info = &cpi->mt_info;
1409   // Basic informaton of the current frame.
1410   TemporalFilterCtx *tf_ctx = &cpi->tf_ctx;
1411   TemporalFilterData *tf_data = &cpi->td.tf_data;
1412   const int compute_frame_diff = frame_diff != NULL;
1413   // TODO(anyone): Currently, we enforce the filtering strength on internal
1414   // ARFs except the second ARF to be zero. We should investigate in which case
1415   // it is more beneficial to use non-zero strength filtering.
1416   // Only parallel level 0 frames go through temporal filtering.
1417   assert(cpi->ppi->gf_group.frame_parallel_level[gf_frame_index] == 0);
1418 
1419   // Initialize temporal filter context structure.
1420   init_tf_ctx(cpi, filter_frame_lookahead_idx, gf_frame_index,
1421               compute_frame_diff, output_frame);
1422 
1423   // Allocate and reset temporal filter buffers.
1424   const int is_highbitdepth = tf_ctx->is_highbitdepth;
1425   if (!tf_alloc_and_reset_data(tf_data, tf_ctx->num_pels, is_highbitdepth)) {
1426     aom_internal_error(cpi->common.error, AOM_CODEC_MEM_ERROR,
1427                        "Error allocating temporal filter data");
1428   }
1429 
1430   // Perform temporal filtering process.
1431   if (mt_info->num_workers > 1)
1432     av1_tf_do_filtering_mt(cpi);
1433   else
1434     tf_do_filtering(cpi);
1435 
1436   if (compute_frame_diff) {
1437     *frame_diff = tf_data->diff;
1438   }
1439   // Deallocate temporal filter buffers.
1440   tf_dealloc_data(tf_data, is_highbitdepth);
1441 }
1442 
av1_is_temporal_filter_on(const AV1EncoderConfig * oxcf)1443 int av1_is_temporal_filter_on(const AV1EncoderConfig *oxcf) {
1444   return oxcf->algo_cfg.arnr_max_frames > 0 && oxcf->gf_cfg.lag_in_frames > 1;
1445 }
1446 
av1_tf_info_alloc(TEMPORAL_FILTER_INFO * tf_info,const AV1_COMP * cpi)1447 bool av1_tf_info_alloc(TEMPORAL_FILTER_INFO *tf_info, const AV1_COMP *cpi) {
1448   const AV1EncoderConfig *oxcf = &cpi->oxcf;
1449   tf_info->is_temporal_filter_on = av1_is_temporal_filter_on(oxcf);
1450   if (tf_info->is_temporal_filter_on == 0) return true;
1451 
1452   const AV1_COMMON *cm = &cpi->common;
1453   const SequenceHeader *const seq_params = cm->seq_params;
1454   for (int i = 0; i < TF_INFO_BUF_COUNT; ++i) {
1455     if (aom_realloc_frame_buffer(
1456             &tf_info->tf_buf[i], oxcf->frm_dim_cfg.width,
1457             oxcf->frm_dim_cfg.height, seq_params->subsampling_x,
1458             seq_params->subsampling_y, seq_params->use_highbitdepth,
1459             cpi->oxcf.border_in_pixels, cm->features.byte_alignment, NULL, NULL,
1460             NULL, cpi->alloc_pyramid, 0)) {
1461       return false;
1462     }
1463   }
1464   return true;
1465 }
1466 
av1_tf_info_free(TEMPORAL_FILTER_INFO * tf_info)1467 void av1_tf_info_free(TEMPORAL_FILTER_INFO *tf_info) {
1468   if (tf_info->is_temporal_filter_on == 0) return;
1469   for (int i = 0; i < TF_INFO_BUF_COUNT; ++i) {
1470     aom_free_frame_buffer(&tf_info->tf_buf[i]);
1471   }
1472   aom_free_frame_buffer(&tf_info->tf_buf_second_arf);
1473 }
1474 
av1_tf_info_reset(TEMPORAL_FILTER_INFO * tf_info)1475 void av1_tf_info_reset(TEMPORAL_FILTER_INFO *tf_info) {
1476   av1_zero(tf_info->tf_buf_valid);
1477   av1_zero(tf_info->tf_buf_gf_index);
1478   av1_zero(tf_info->tf_buf_display_index_offset);
1479 }
1480 
av1_tf_info_filtering(TEMPORAL_FILTER_INFO * tf_info,AV1_COMP * cpi,const GF_GROUP * gf_group)1481 void av1_tf_info_filtering(TEMPORAL_FILTER_INFO *tf_info, AV1_COMP *cpi,
1482                            const GF_GROUP *gf_group) {
1483   if (tf_info->is_temporal_filter_on == 0) return;
1484   const AV1_COMMON *const cm = &cpi->common;
1485   for (int gf_index = 0; gf_index < gf_group->size; ++gf_index) {
1486     int update_type = gf_group->update_type[gf_index];
1487     if (update_type == KF_UPDATE || update_type == ARF_UPDATE) {
1488       int buf_idx = gf_group->frame_type[gf_index] == INTER_FRAME;
1489       int lookahead_idx = gf_group->arf_src_offset[gf_index] +
1490                           gf_group->cur_frame_idx[gf_index];
1491       // This function is designed to be called multiple times after
1492       // av1_tf_info_reset(). It will only generate the filtered frame that does
1493       // not exist yet.
1494       if (tf_info->tf_buf_valid[buf_idx] == 0 ||
1495           tf_info->tf_buf_display_index_offset[buf_idx] != lookahead_idx) {
1496         YV12_BUFFER_CONFIG *out_buf = &tf_info->tf_buf[buf_idx];
1497         av1_temporal_filter(cpi, lookahead_idx, gf_index,
1498                             &tf_info->frame_diff[buf_idx], out_buf);
1499         aom_extend_frame_borders(out_buf, av1_num_planes(cm));
1500         tf_info->tf_buf_gf_index[buf_idx] = gf_index;
1501         tf_info->tf_buf_display_index_offset[buf_idx] = lookahead_idx;
1502         tf_info->tf_buf_valid[buf_idx] = 1;
1503       }
1504     }
1505   }
1506 }
1507 
av1_tf_info_get_filtered_buf(TEMPORAL_FILTER_INFO * tf_info,int gf_index,FRAME_DIFF * frame_diff)1508 YV12_BUFFER_CONFIG *av1_tf_info_get_filtered_buf(TEMPORAL_FILTER_INFO *tf_info,
1509                                                  int gf_index,
1510                                                  FRAME_DIFF *frame_diff) {
1511   if (tf_info->is_temporal_filter_on == 0) return NULL;
1512   YV12_BUFFER_CONFIG *out_buf = NULL;
1513   for (int i = 0; i < TF_INFO_BUF_COUNT; ++i) {
1514     if (tf_info->tf_buf_valid[i] && tf_info->tf_buf_gf_index[i] == gf_index) {
1515       out_buf = &tf_info->tf_buf[i];
1516       *frame_diff = tf_info->frame_diff[i];
1517     }
1518   }
1519   return out_buf;
1520 }
1521 /*!\endcond */
1522