xref: /aosp_15_r20/external/libaom/av1/encoder/partition_strategy.c (revision 77c1e3ccc04c968bd2bc212e87364f250e820521)
1 /*
2  * Copyright (c) 2019, 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 
14 #include "config/aom_config.h"
15 
16 #include "av1/encoder/encodeframe_utils.h"
17 #if CONFIG_THREE_PASS
18 #include "av1/encoder/thirdpass.h"
19 #endif
20 #include "config/aom_dsp_rtcd.h"
21 
22 #include "av1/common/enums.h"
23 #include "av1/common/reconinter.h"
24 
25 #if !CONFIG_REALTIME_ONLY
26 #include "av1/encoder/cnn.h"
27 #include "av1/encoder/partition_model_weights.h"
28 #include "av1/encoder/partition_cnn_weights.h"
29 #endif
30 #include "av1/encoder/encoder.h"
31 
32 #include "av1/encoder/motion_search_facade.h"
33 #include "av1/encoder/partition_strategy.h"
34 #include "av1/encoder/partition_search.h"
35 #include "av1/encoder/rdopt.h"
36 
37 #if !CONFIG_REALTIME_ONLY
38 static inline void simple_motion_search_prune_part_features(
39     AV1_COMP *const cpi, MACROBLOCK *x, SIMPLE_MOTION_DATA_TREE *sms_tree,
40     int mi_row, int mi_col, BLOCK_SIZE bsize, float *features,
41     int features_to_get);
42 
43 static bool ext_ml_model_decision_before_none(
44     AV1_COMP *cpi, const float features_from_motion[FEATURE_SIZE_SMS_SPLIT],
45     int *partition_none_allowed, int *partition_horz_allowed,
46     int *partition_vert_allowed, int *do_rectangular_split,
47     int *do_square_split);
48 
49 static bool ext_ml_model_decision_before_none_part2(
50     AV1_COMP *cpi,
51     const float features_from_motion[FEATURE_SIZE_SMS_PRUNE_PART],
52     int *prune_horz, int *prune_vert);
53 
54 static bool ext_ml_model_decision_after_none(
55     ExtPartController *const ext_part_controller, const int is_intra_frame,
56     const float *const features_after_none, int *do_square_split,
57     int *do_rectangular_split);
58 
59 static bool ext_ml_model_decision_after_none_part2(
60     AV1_COMP *const cpi, const float *const features_terminate,
61     int *terminate_partition_search);
62 
63 static bool ext_ml_model_decision_after_split(
64     AV1_COMP *const cpi, const float *const features_terminate,
65     int *terminate_partition_search);
66 
67 static bool ext_ml_model_decision_after_split_part2(
68     ExtPartController *const ext_part_controller, const int is_intra_frame,
69     const float *const features_prune, int *prune_rect_part_horz,
70     int *prune_rect_part_vert);
71 
72 static bool ext_ml_model_decision_after_rect(
73     ExtPartController *const ext_part_controller, const int is_intra_frame,
74     const float *const features_after_rect, int *horza_partition_allowed,
75     int *horzb_partition_allowed, int *verta_partition_allowed,
76     int *vertb_partition_allowed);
77 
78 static bool ext_ml_model_decision_after_part_ab(
79     AV1_COMP *const cpi, MACROBLOCK *const x, BLOCK_SIZE bsize, int part_ctx,
80     int64_t best_rd, int64_t rect_part_rd[NUM_RECT_PARTS][SUB_PARTITIONS_RECT],
81     int64_t split_rd[SUB_PARTITIONS_SPLIT], int *const partition_horz4_allowed,
82     int *const partition_vert4_allowed, unsigned int pb_source_variance,
83     int mi_row, int mi_col);
84 
convert_bsize_to_idx(BLOCK_SIZE bsize)85 static inline int convert_bsize_to_idx(BLOCK_SIZE bsize) {
86   switch (bsize) {
87     case BLOCK_128X128: return 0;
88     case BLOCK_64X64: return 1;
89     case BLOCK_32X32: return 2;
90     case BLOCK_16X16: return 3;
91     case BLOCK_8X8: return 4;
92     default: assert(0 && "Invalid bsize"); return -1;
93   }
94 }
95 
get_feature_file_name(int id)96 static char *get_feature_file_name(int id) {
97   static char *feature_file_names[] = {
98     "feature_before_partition_none",
99     "feature_before_partition_none_prune_rect",
100     "feature_after_partition_none_prune",
101     "feature_after_partition_none_terminate",
102     "feature_after_partition_split_terminate",
103     "feature_after_partition_split_prune_rect",
104     "feature_after_partition_rect",
105     "feature_after_partition_ab",
106   };
107 
108   return feature_file_names[id];
109 }
110 
write_features_to_file(const char * const path,const bool is_test_mode,const float * features,const int feature_size,const int id,const BLOCK_SIZE bsize,const int mi_row,const int mi_col)111 static void write_features_to_file(const char *const path,
112                                    const bool is_test_mode,
113                                    const float *features,
114                                    const int feature_size, const int id,
115                                    const BLOCK_SIZE bsize, const int mi_row,
116                                    const int mi_col) {
117   if (!WRITE_FEATURE_TO_FILE && !is_test_mode) return;
118 
119   char filename[256];
120   snprintf(filename, sizeof(filename), "%s/%s", path,
121            get_feature_file_name(id));
122   FILE *pfile = fopen(filename, "a");
123   if (pfile == NULL) return;
124   if (!is_test_mode) {
125     fprintf(pfile, "%d,%d,%d,%d,%d\n", id, (int)bsize, mi_row, mi_col,
126             feature_size);
127   }
128   for (int i = 0; i < feature_size; ++i) {
129     fprintf(pfile, "%.6f", features[i]);
130     if (i < feature_size - 1) fprintf(pfile, ",");
131   }
132   fprintf(pfile, "\n");
133   fclose(pfile);
134 }
135 
136 // TODO([email protected]): This is very much a work in progress. We still
137 // need to the following:
138 //   -- add support for hdres
139 //   -- add support for pruning rectangular partitions
140 //   -- use reconstructed pixels instead of source pixels for padding
141 //   -- use chroma pixels in addition to luma pixels
intra_mode_cnn_partition(const AV1_COMMON * const cm,MACROBLOCK * x,int quad_tree_idx,int intra_cnn_based_part_prune_level,PartitionSearchState * part_state)142 static void intra_mode_cnn_partition(const AV1_COMMON *const cm, MACROBLOCK *x,
143                                      int quad_tree_idx,
144                                      int intra_cnn_based_part_prune_level,
145                                      PartitionSearchState *part_state) {
146   assert(cm->seq_params->sb_size >= BLOCK_64X64 &&
147          "Invalid sb_size for intra_cnn!");
148   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
149   const BLOCK_SIZE bsize = blk_params->bsize;
150 
151   const int bsize_idx = convert_bsize_to_idx(bsize);
152 
153   if (bsize == BLOCK_128X128) {
154     return;
155   }
156 
157   PartitionSearchInfo *part_info = &x->part_search_info;
158 
159   // Precompute the CNN part and cache the result in MACROBLOCK
160   if (bsize == BLOCK_64X64 && !part_info->cnn_output_valid) {
161     const CNN_CONFIG *cnn_config = &av1_intra_mode_cnn_partition_cnn_config;
162 
163     // Prepare the output
164     const CNN_THREAD_DATA thread_data = { .num_workers = 1, .workers = NULL };
165     const int num_outputs = 4;
166     const int output_dims[4] = { 1, 2, 4, 8 };
167     const int out_chs[4] = { CNN_BRANCH_0_OUT_CH, CNN_BRANCH_1_OUT_CH,
168                              CNN_BRANCH_2_OUT_CH, CNN_BRANCH_3_OUT_CH };
169     float *output_buffer[CNN_TOT_OUT_CH];
170 
171     float **cur_output_buf = output_buffer;
172     float *curr_buf_ptr = part_info->cnn_buffer;
173     for (int output_idx = 0; output_idx < num_outputs; output_idx++) {
174       const int num_chs = out_chs[output_idx];
175       const int ch_size = output_dims[output_idx] * output_dims[output_idx];
176       for (int ch = 0; ch < num_chs; ch++) {
177         cur_output_buf[ch] = curr_buf_ptr;
178         curr_buf_ptr += ch_size;
179       }
180       cur_output_buf += num_chs;
181     }
182 
183     CNN_MULTI_OUT output = {
184       .num_outputs = 4,
185       .output_channels = out_chs,
186       .output_strides = output_dims,
187       .output_buffer = output_buffer,
188     };
189 
190     // Prepare the input
191     const MACROBLOCKD *xd = &x->e_mbd;
192     const int bit_depth = xd->bd;
193     const int dc_q =
194         av1_dc_quant_QTX(x->qindex, 0, bit_depth) >> (bit_depth - 8);
195     part_info->log_q = log1pf((float)(dc_q * dc_q) / 256.0f);
196     part_info->log_q =
197         (part_info->log_q - av1_intra_mode_cnn_partition_mean[0]) /
198         av1_intra_mode_cnn_partition_std[0];
199 
200     const int width = 65, height = 65,
201               stride = x->plane[AOM_PLANE_Y].src.stride;
202 
203     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
204       uint16_t *image[1] = {
205         CONVERT_TO_SHORTPTR(x->plane[AOM_PLANE_Y].src.buf) - stride - 1
206       };
207 
208       if (!av1_cnn_predict_img_multi_out_highbd(image, width, height, stride,
209                                                 cnn_config, &thread_data,
210                                                 bit_depth, &output)) {
211         aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
212                            "Error allocating CNN data");
213         return;
214       }
215     } else {
216       uint8_t *image[1] = { x->plane[AOM_PLANE_Y].src.buf - stride - 1 };
217 
218       if (!av1_cnn_predict_img_multi_out(image, width, height, stride,
219                                          cnn_config, &thread_data, &output)) {
220         aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
221                            "Error allocating CNN data");
222         return;
223       }
224     }
225 
226     part_info->cnn_output_valid = 1;
227   }
228 
229   if (!part_info->cnn_output_valid) {
230     return;
231   }
232 
233   const NN_CONFIG *dnn_configs[5] = {
234     NULL,
235     &av1_intra_mode_cnn_partition_branch_0_dnn_config,
236     &av1_intra_mode_cnn_partition_branch_1_dnn_config,
237     &av1_intra_mode_cnn_partition_branch_2_dnn_config,
238     &av1_intra_mode_cnn_partition_branch_3_dnn_config,
239   };
240 
241   const NN_CONFIG *dnn_config = dnn_configs[bsize_idx];
242 
243   float dnn_features[100];
244   float logits[4] = { 0.0f };
245 
246   const float *branch_0 = part_info->cnn_buffer;
247   const float *branch_1 = branch_0 + CNN_BRANCH_0_OUT_SIZE;
248   const float *branch_2 = branch_1 + CNN_BRANCH_1_OUT_SIZE;
249   const float *branch_3 = branch_2 + CNN_BRANCH_2_OUT_SIZE;
250 
251   if (bsize == BLOCK_64X64) {
252     int f_idx = 0;
253     for (int ch_idx = 0; ch_idx < CNN_BRANCH_0_OUT_CH; ch_idx++) {
254       dnn_features[f_idx++] = branch_0[ch_idx];
255     }
256 
257     const int spa_stride = 2 * 2;
258     for (int lin_idx = 0; lin_idx < spa_stride; lin_idx++) {
259       for (int ch_idx = 0; ch_idx < CNN_BRANCH_1_OUT_CH; ch_idx++) {
260         dnn_features[f_idx++] = branch_1[lin_idx + ch_idx * spa_stride];
261       }
262     }
263     dnn_features[f_idx++] = part_info->log_q;
264   } else if (bsize == BLOCK_32X32) {
265     int f_idx = 0;
266     for (int idx = 0; idx < CNN_BRANCH_0_OUT_CH; idx++) {
267       dnn_features[f_idx++] = branch_0[idx];
268     }
269 
270     const int curr_lin_idx = quad_to_linear_1[quad_tree_idx - 1];
271     const int spa_stride = 2 * 2;
272     for (int ch_idx = 0; ch_idx < CNN_BRANCH_1_OUT_CH; ch_idx++) {
273       dnn_features[f_idx++] = branch_1[curr_lin_idx + ch_idx * spa_stride];
274     }
275     dnn_features[f_idx++] = part_info->log_q;
276   } else if (bsize == BLOCK_16X16) {
277     int f_idx = 0;
278     const int prev_quad_idx = (quad_tree_idx - 1) / 4;
279     const int prev_lin_idx = quad_to_linear_1[prev_quad_idx - 1];
280     const int prev_spa_stride = 2 * 2;
281     for (int ch_idx = 0; ch_idx < CNN_BRANCH_1_OUT_CH; ch_idx++) {
282       dnn_features[f_idx++] = branch_1[prev_lin_idx + ch_idx * prev_spa_stride];
283     }
284 
285     const int curr_lin_idx = quad_to_linear_2[quad_tree_idx - 5];
286     const int spa_stride = 4 * 4;
287     for (int ch_idx = 0; ch_idx < CNN_BRANCH_2_OUT_CH; ch_idx++) {
288       dnn_features[f_idx++] = branch_2[curr_lin_idx + ch_idx * spa_stride];
289     }
290     dnn_features[f_idx++] = part_info->log_q;
291   } else if (bsize == BLOCK_8X8) {
292     int f_idx = 0;
293     const int prev_quad_idx = (quad_tree_idx - 1) / 4;
294     const int prev_lin_idx = quad_to_linear_2[prev_quad_idx - 5];
295     const int prev_spa_stride = 4 * 4;
296     for (int ch_idx = 0; ch_idx < CNN_BRANCH_2_OUT_CH; ch_idx++) {
297       dnn_features[f_idx++] = branch_2[prev_lin_idx + ch_idx * prev_spa_stride];
298     }
299 
300     const int curr_lin_idx = quad_to_linear_3[quad_tree_idx - 21];
301     const int spa_stride = 8 * 8;
302     for (int ch_idx = 0; ch_idx < CNN_BRANCH_3_OUT_CH; ch_idx++) {
303       dnn_features[f_idx++] = branch_3[curr_lin_idx + ch_idx * spa_stride];
304     }
305     dnn_features[f_idx++] = part_info->log_q;
306   } else {
307     assert(0 && "Invalid bsize in intra_cnn partition");
308   }
309 
310   // Make decision
311   av1_nn_predict(dnn_features, dnn_config, 1, logits);
312 
313   const int is_720p_or_larger = AOMMIN(cm->width, cm->height) >= 720;
314   const int is_480p_or_larger = AOMMIN(cm->width, cm->height) >= 480;
315   float split_only_thresh = 100.0f, no_split_thresh = -100.0f;
316   if (is_720p_or_larger) {
317     split_only_thresh =
318         av1_intra_mode_cnn_partition_split_thresh_hdres[bsize_idx];
319     no_split_thresh =
320         av1_intra_mode_cnn_partition_no_split_thresh_hdres[bsize_idx];
321   } else if (is_480p_or_larger) {
322     split_only_thresh =
323         av1_intra_mode_cnn_partition_split_thresh_midres[bsize_idx];
324     no_split_thresh =
325         av1_intra_mode_cnn_partition_no_split_thresh_midres[bsize_idx];
326   } else {
327     split_only_thresh =
328         av1_intra_mode_cnn_partition_split_thresh_lowres[bsize_idx];
329     no_split_thresh =
330         av1_intra_mode_cnn_partition_no_split_thresh_lowres[bsize_idx];
331   }
332 
333   if (logits[0] > split_only_thresh) {
334     // As screen contents tend to choose larger partitions, do not prune
335     // PARTITION_NONE when intra_cnn_based_part_prune_level=1.
336     if (intra_cnn_based_part_prune_level != 1) {
337       part_state->partition_none_allowed = 0;
338     }
339     part_state->do_square_split = 1;
340     av1_disable_rect_partitions(part_state);
341   }
342 
343   if (logits[0] < no_split_thresh) {
344     av1_disable_square_split_partition(part_state);
345   }
346 }
347 
get_simple_motion_search_prune_agg(int qindex,int prune_level,int is_rect_part)348 static inline int get_simple_motion_search_prune_agg(int qindex,
349                                                      int prune_level,
350                                                      int is_rect_part) {
351   assert(prune_level < TOTAL_AGG_LVLS);
352   if (prune_level == NO_PRUNING) {
353     return -1;
354   }
355 
356   // Aggressiveness value for SIMPLE_MOTION_SEARCH_PRUNE_LEVEL except
357   // QIDX_BASED_AGG_LVL
358   const int sms_prune_agg_levels[TOTAL_SIMPLE_AGG_LVLS] = { 0, 1, 2, 3 };
359   if (prune_level < TOTAL_SIMPLE_AGG_LVLS) {
360     return sms_prune_agg_levels[prune_level];
361   }
362 
363   // Map the QIDX_BASED_AGG_LVL to corresponding aggressiveness value.
364   // Aggressive pruning for lower quantizers in non-boosted frames to prune
365   // rectangular partitions.
366   const int qband = is_rect_part ? (qindex <= 90 ? 1 : 0) : 0;
367   const int sms_prune_agg_qindex_based[2] = { 1, 2 };
368   return sms_prune_agg_qindex_based[qband];
369 }
370 
371 // Performs a simple_motion_search with a single reference frame and extract
372 // the variance of residues. Then use the features to determine whether we want
373 // to go straight to splitting without trying PARTITION_NONE
simple_motion_search_based_split(AV1_COMP * const cpi,MACROBLOCK * x,SIMPLE_MOTION_DATA_TREE * sms_tree,PartitionSearchState * part_state)374 static void simple_motion_search_based_split(AV1_COMP *const cpi, MACROBLOCK *x,
375                                              SIMPLE_MOTION_DATA_TREE *sms_tree,
376                                              PartitionSearchState *part_state) {
377   const AV1_COMMON *const cm = &cpi->common;
378   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
379   const int mi_row = blk_params->mi_row, mi_col = blk_params->mi_col;
380   const BLOCK_SIZE bsize = blk_params->bsize;
381 
382   const int bsize_idx = convert_bsize_to_idx(bsize);
383   const int is_720p_or_larger = AOMMIN(cm->width, cm->height) >= 720;
384   const int is_480p_or_larger = AOMMIN(cm->width, cm->height) >= 480;
385   // res_idx is 0 for res < 480p, 1 for 480p, 2 for 720p+
386   const int res_idx = is_480p_or_larger + is_720p_or_larger;
387 
388   assert(bsize_idx >= 0 && bsize_idx <= 4 &&
389          "Invalid bsize in simple_motion_search_based_split");
390 
391   const float *ml_mean = av1_simple_motion_search_split_mean[bsize_idx];
392   const float *ml_std = av1_simple_motion_search_split_std[bsize_idx];
393   const NN_CONFIG *nn_config =
394       av1_simple_motion_search_split_nn_config[bsize_idx];
395 
396   const int agg = get_simple_motion_search_prune_agg(
397       x->qindex, cpi->sf.part_sf.simple_motion_search_prune_agg, 0);
398   if (agg < 0) {
399     return;
400   }
401 
402   const float split_only_thresh =
403       av1_simple_motion_search_split_thresh[agg][res_idx][bsize_idx];
404   const float no_split_thresh =
405       av1_simple_motion_search_no_split_thresh[agg][res_idx][bsize_idx];
406 
407   float features[FEATURE_SIZE_SMS_SPLIT] = { 0.0f };
408   simple_motion_search_prune_part_features(cpi, x, sms_tree, mi_row, mi_col,
409                                            bsize, features,
410                                            FEATURE_SMS_SPLIT_MODEL_FLAG);
411 
412   // Write features to file
413   write_features_to_file(cpi->oxcf.partition_info_path,
414                          cpi->ext_part_controller.test_mode, features,
415                          FEATURE_SIZE_SMS_SPLIT, 0, bsize, mi_row, mi_col);
416 
417   // Note: it is intended to not normalize the features here, to keep it
418   // consistent for all features collected and passed to the external model.
419   if (ext_ml_model_decision_before_none(
420           cpi, features, &part_state->partition_none_allowed,
421           &part_state->partition_rect_allowed[HORZ],
422           &part_state->partition_rect_allowed[VERT],
423           &part_state->do_rectangular_split, &part_state->do_square_split)) {
424     return;
425   }
426 
427   for (int idx = 0; idx < FEATURE_SIZE_SMS_SPLIT; idx++) {
428     features[idx] = (features[idx] - ml_mean[idx]) / ml_std[idx];
429   }
430 
431   float score = 0.0f;
432 
433   av1_nn_predict(features, nn_config, 1, &score);
434 
435   if (score > split_only_thresh) {
436     av1_set_square_split_only(part_state);
437   }
438 
439   if (cpi->sf.part_sf.simple_motion_search_split >= 2 &&
440       score < no_split_thresh) {
441     av1_disable_square_split_partition(part_state);
442   }
443 
444   // If the score is very low, prune rectangular split since it is unlikely to
445   // occur.
446   if (cpi->sf.part_sf.simple_motion_search_rect_split) {
447     const float scale = res_idx >= 2 ? 3.0f : 2.0f;
448     const float rect_split_thresh =
449         scale * av1_simple_motion_search_no_split_thresh
450                     [cpi->sf.part_sf.simple_motion_search_rect_split][res_idx]
451                     [bsize_idx];
452     if (score < rect_split_thresh) {
453       part_state->do_rectangular_split = 0;
454     }
455   }
456 }
457 
458 // Given a list of ref frames in refs, performs simple_motion_search on each of
459 // the refs and returns the ref with the smallest sse. Returns -1 if none of the
460 // ref in the list is available. Also stores the best sse and var in best_sse,
461 // best_var, respectively. If save_mv is 0, don't update mv_ref_fulls in
462 // sms_tree. If save_mv is 1, update mv_ref_fulls under sms_tree and the
463 // subtrees.
simple_motion_search_get_best_ref(AV1_COMP * const cpi,MACROBLOCK * x,SIMPLE_MOTION_DATA_TREE * sms_tree,int mi_row,int mi_col,BLOCK_SIZE bsize,const int * const refs,int num_refs,int use_subpixel,int save_mv,unsigned int * best_sse,unsigned int * best_var)464 static int simple_motion_search_get_best_ref(
465     AV1_COMP *const cpi, MACROBLOCK *x, SIMPLE_MOTION_DATA_TREE *sms_tree,
466     int mi_row, int mi_col, BLOCK_SIZE bsize, const int *const refs,
467     int num_refs, int use_subpixel, int save_mv, unsigned int *best_sse,
468     unsigned int *best_var) {
469   const AV1_COMMON *const cm = &cpi->common;
470   int best_ref = -1;
471 
472   if (mi_col >= cm->mi_params.mi_cols || mi_row >= cm->mi_params.mi_rows) {
473     // If the whole block is outside of the image, set the var and sse to 0.
474     *best_var = 0;
475     *best_sse = 0;
476 
477     return best_ref;
478   }
479 
480   // Otherwise do loop through the reference frames and find the one with the
481   // minimum SSE
482   const int num_planes = 1;
483 
484   *best_sse = INT_MAX;
485 
486   for (int ref_idx = 0; ref_idx < num_refs; ref_idx++) {
487     const int ref = refs[ref_idx];
488 
489     if (cpi->ref_frame_flags & av1_ref_frame_flag_list[ref]) {
490       const FULLPEL_MV *start_mvs = sms_tree->start_mvs;
491       unsigned int curr_sse = 0, curr_var = 0;
492       const int_mv best_mv = av1_simple_motion_search_sse_var(
493           cpi, x, mi_row, mi_col, bsize, ref, start_mvs[ref], num_planes,
494           use_subpixel, &curr_sse, &curr_var);
495       if (curr_sse < *best_sse) {
496         *best_sse = curr_sse;
497         *best_var = curr_var;
498         best_ref = ref;
499       }
500 
501       if (save_mv) {
502         sms_tree->start_mvs[ref].row = best_mv.as_mv.row / 8;
503         sms_tree->start_mvs[ref].col = best_mv.as_mv.col / 8;
504 
505         if (bsize >= BLOCK_8X8) {
506           for (int r_idx = 0; r_idx < SUB_PARTITIONS_SPLIT; r_idx++) {
507             // Propagate the new motion vectors to a lower level
508             SIMPLE_MOTION_DATA_TREE *sub_tree = sms_tree->split[r_idx];
509             sub_tree->start_mvs[ref] = sms_tree->start_mvs[ref];
510           }
511         }
512       }
513     }
514   }
515 
516   return best_ref;
517 }
518 
519 // Collects features using simple_motion_search and store them in features. The
520 // features are also cached in SIMPLE_MOTION_DATA_TREE. By default, the features
521 // collected are the sse and var from the subblocks flagged by features_to_get.
522 // Furthermore, if features is not NULL, then 7 more features are appended to
523 // the end of features:
524 //  - log(1.0 + dc_q ** 2)
525 //  - whether an above macroblock exists
526 //  - width of above macroblock
527 //  - height of above macroblock
528 //  - whether a left marcoblock exists
529 //  - width of left macroblock
530 //  - height of left macroblock
simple_motion_search_prune_part_features(AV1_COMP * const cpi,MACROBLOCK * x,SIMPLE_MOTION_DATA_TREE * sms_tree,int mi_row,int mi_col,BLOCK_SIZE bsize,float * features,int features_to_get)531 static inline void simple_motion_search_prune_part_features(
532     AV1_COMP *const cpi, MACROBLOCK *x, SIMPLE_MOTION_DATA_TREE *sms_tree,
533     int mi_row, int mi_col, BLOCK_SIZE bsize, float *features,
534     int features_to_get) {
535   const int w_mi = mi_size_wide[bsize];
536   const int h_mi = mi_size_high[bsize];
537   assert(mi_size_wide[bsize] == mi_size_high[bsize]);
538   assert(bsize >= BLOCK_8X8);
539   assert(cpi->ref_frame_flags & av1_ref_frame_flag_list[LAST_FRAME] ||
540          cpi->ref_frame_flags & av1_ref_frame_flag_list[ALTREF_FRAME]);
541 
542   // Setting up motion search
543   const int ref_list[] = { cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME
544                                                         : LAST_FRAME };
545   const int num_refs = 1;
546   const int use_subpixel = 1;
547 
548   // Doing whole block first to update the mv
549   if (!sms_tree->sms_none_valid && features_to_get & FEATURE_SMS_NONE_FLAG) {
550     simple_motion_search_get_best_ref(cpi, x, sms_tree, mi_row, mi_col, bsize,
551                                       ref_list, num_refs, use_subpixel, 1,
552                                       &sms_tree->sms_none_feat[0],
553                                       &sms_tree->sms_none_feat[1]);
554     sms_tree->sms_none_valid = 1;
555   }
556 
557   // Split subblocks
558   if (features_to_get & FEATURE_SMS_SPLIT_FLAG) {
559     const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
560     for (int r_idx = 0; r_idx < SUB_PARTITIONS_SPLIT; r_idx++) {
561       const int sub_mi_col = mi_col + (r_idx & 1) * w_mi / 2;
562       const int sub_mi_row = mi_row + (r_idx >> 1) * h_mi / 2;
563       SIMPLE_MOTION_DATA_TREE *sub_tree = sms_tree->split[r_idx];
564 
565       if (!sub_tree->sms_none_valid) {
566         simple_motion_search_get_best_ref(
567             cpi, x, sub_tree, sub_mi_row, sub_mi_col, subsize, ref_list,
568             num_refs, use_subpixel, 1, &sub_tree->sms_none_feat[0],
569             &sub_tree->sms_none_feat[1]);
570         sub_tree->sms_none_valid = 1;
571       }
572     }
573   }
574 
575   // Rectangular subblocks
576   if (!sms_tree->sms_rect_valid && features_to_get & FEATURE_SMS_RECT_FLAG) {
577     // Horz subblock
578     BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_HORZ);
579     for (int r_idx = 0; r_idx < SUB_PARTITIONS_RECT; r_idx++) {
580       const int sub_mi_col = mi_col + 0;
581       const int sub_mi_row = mi_row + r_idx * h_mi / 2;
582 
583       simple_motion_search_get_best_ref(
584           cpi, x, sms_tree, sub_mi_row, sub_mi_col, subsize, ref_list, num_refs,
585           use_subpixel, 0, &sms_tree->sms_rect_feat[2 * r_idx],
586           &sms_tree->sms_rect_feat[2 * r_idx + 1]);
587     }
588 
589     // Vert subblock
590     subsize = get_partition_subsize(bsize, PARTITION_VERT);
591     for (int r_idx = 0; r_idx < SUB_PARTITIONS_RECT; r_idx++) {
592       const int sub_mi_col = mi_col + r_idx * w_mi / 2;
593       const int sub_mi_row = mi_row + 0;
594 
595       simple_motion_search_get_best_ref(
596           cpi, x, sms_tree, sub_mi_row, sub_mi_col, subsize, ref_list, num_refs,
597           use_subpixel, 0, &sms_tree->sms_rect_feat[4 + 2 * r_idx],
598           &sms_tree->sms_rect_feat[4 + 2 * r_idx + 1]);
599     }
600     sms_tree->sms_rect_valid = 1;
601   }
602 
603   if (!features) return;
604 
605   int f_idx = 0;
606   if (features_to_get & FEATURE_SMS_NONE_FLAG) {
607     for (int sub_idx = 0; sub_idx < 2; sub_idx++) {
608       features[f_idx++] = log1pf((float)sms_tree->sms_none_feat[sub_idx]);
609     }
610   }
611 
612   if (features_to_get & FEATURE_SMS_SPLIT_FLAG) {
613     for (int sub_idx = 0; sub_idx < SUB_PARTITIONS_SPLIT; sub_idx++) {
614       SIMPLE_MOTION_DATA_TREE *sub_tree = sms_tree->split[sub_idx];
615       features[f_idx++] = log1pf((float)sub_tree->sms_none_feat[0]);
616       features[f_idx++] = log1pf((float)sub_tree->sms_none_feat[1]);
617     }
618   }
619 
620   if (features_to_get & FEATURE_SMS_RECT_FLAG) {
621     for (int sub_idx = 0; sub_idx < 8; sub_idx++) {
622       features[f_idx++] = log1pf((float)sms_tree->sms_rect_feat[sub_idx]);
623     }
624   }
625 
626   const MACROBLOCKD *xd = &x->e_mbd;
627   set_offsets_for_motion_search(cpi, x, mi_row, mi_col, bsize);
628 
629   // Q_INDEX
630   const int dc_q = av1_dc_quant_QTX(x->qindex, 0, xd->bd) >> (xd->bd - 8);
631   features[f_idx++] = log1pf((float)(dc_q * dc_q) / 256.0f);
632 
633   // Neighbor stuff
634   const int has_above = !!xd->above_mbmi;
635   const int has_left = !!xd->left_mbmi;
636   const BLOCK_SIZE above_bsize = has_above ? xd->above_mbmi->bsize : bsize;
637   const BLOCK_SIZE left_bsize = has_left ? xd->left_mbmi->bsize : bsize;
638   features[f_idx++] = (float)has_above;
639   features[f_idx++] = (float)mi_size_wide_log2[above_bsize];
640   features[f_idx++] = (float)mi_size_high_log2[above_bsize];
641   features[f_idx++] = (float)has_left;
642   features[f_idx++] = (float)mi_size_wide_log2[left_bsize];
643   features[f_idx++] = (float)mi_size_high_log2[left_bsize];
644 }
645 
646 // Performs a simple_motion_search with two reference frames and extract
647 // the variance of residues. Then use the features to determine whether we want
648 // to prune some partitions.
simple_motion_search_prune_rect(AV1_COMP * const cpi,MACROBLOCK * x,SIMPLE_MOTION_DATA_TREE * sms_tree,PartitionSearchState * part_state)649 static void simple_motion_search_prune_rect(AV1_COMP *const cpi, MACROBLOCK *x,
650                                             SIMPLE_MOTION_DATA_TREE *sms_tree,
651                                             PartitionSearchState *part_state) {
652   const AV1_COMMON *const cm = &cpi->common;
653   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
654   const int mi_row = blk_params->mi_row, mi_col = blk_params->mi_col;
655   const BLOCK_SIZE bsize = blk_params->bsize;
656 
657   const int bsize_idx = convert_bsize_to_idx(bsize);
658   const int is_720p_or_larger = AOMMIN(cm->width, cm->height) >= 720;
659   const int is_480p_or_larger = AOMMIN(cm->width, cm->height) >= 480;
660   // res_idx is 0 for lowres, 1 for 48p, 2 for 720p+
661   const int res_idx = is_480p_or_larger + is_720p_or_larger;
662 
663   // Get model parameters
664   const NN_CONFIG *nn_config =
665       av1_simple_motion_search_prune_rect_nn_config[bsize_idx];
666   const float *ml_mean = av1_simple_motion_search_prune_rect_mean[bsize_idx],
667               *ml_std = av1_simple_motion_search_prune_rect_std[bsize_idx];
668 
669   const int agg = get_simple_motion_search_prune_agg(
670       x->qindex, cpi->sf.part_sf.simple_motion_search_prune_agg, 1);
671   if (agg < 0) {
672     return;
673   }
674 
675   const float prune_thresh =
676       av1_simple_motion_search_prune_rect_thresh[agg][res_idx][bsize_idx];
677 
678   // If there is no valid threshold, return immediately.
679   if (!nn_config || prune_thresh == 0.0f) {
680     return;
681   }
682 
683   // Get features
684   float features[FEATURE_SIZE_SMS_PRUNE_PART] = { 0.0f };
685   simple_motion_search_prune_part_features(cpi, x, sms_tree, mi_row, mi_col,
686                                            bsize, features,
687                                            FEATURE_SMS_PRUNE_PART_FLAG);
688 
689   // Note: it is intended to not normalize the features here, to keep it
690   // consistent for all features collected and passed to the external model.
691   if (cpi->sf.part_sf.simple_motion_search_prune_rect &&
692       !frame_is_intra_only(cm) &&
693       (part_state->partition_rect_allowed[HORZ] ||
694        part_state->partition_rect_allowed[VERT]) &&
695       bsize >= BLOCK_8X8 && !av1_superres_scaled(cm)) {
696     // Write features to file
697     write_features_to_file(
698         cpi->oxcf.partition_info_path, cpi->ext_part_controller.test_mode,
699         features, FEATURE_SIZE_SMS_PRUNE_PART, 1, bsize, mi_row, mi_col);
700 
701     if (ext_ml_model_decision_before_none_part2(
702             cpi, features, &part_state->prune_rect_part[HORZ],
703             &part_state->prune_rect_part[VERT])) {
704       return;
705     }
706   }
707 
708   for (int f_idx = 0; f_idx < FEATURE_SIZE_SMS_PRUNE_PART; f_idx++) {
709     features[f_idx] = (features[f_idx] - ml_mean[f_idx]) / ml_std[f_idx];
710   }
711 
712   // Get probabilities
713   float scores[EXT_PARTITION_TYPES] = { 0.0f },
714         probs[EXT_PARTITION_TYPES] = { 0.0f };
715   const int num_classes = (bsize == BLOCK_128X128 || bsize == BLOCK_8X8)
716                               ? PARTITION_TYPES
717                               : EXT_PARTITION_TYPES;
718 
719   av1_nn_predict(features, nn_config, 1, scores);
720 
721   av1_nn_softmax(scores, probs, num_classes);
722 
723   // Determine if we should prune rectangular partitions.
724   if (probs[PARTITION_HORZ] <= prune_thresh) {
725     part_state->prune_rect_part[HORZ] = 1;
726   }
727   if (probs[PARTITION_VERT] <= prune_thresh) {
728     part_state->prune_rect_part[VERT] = 1;
729   }
730 }
731 
732 // Early terminates PARTITION_NONE using simple_motion_search features and the
733 // rate, distortion, and rdcost of PARTITION_NONE. This is only called when:
734 //  - The frame is a show frame
735 //  - The frame is not intra only
736 //  - The current bsize is > BLOCK_8X8
737 //  - blk_row + blk_height/2 < total_rows and blk_col + blk_width/2 < total_cols
av1_simple_motion_search_early_term_none(AV1_COMP * const cpi,MACROBLOCK * x,SIMPLE_MOTION_DATA_TREE * sms_tree,const RD_STATS * none_rdc,PartitionSearchState * part_state)738 void av1_simple_motion_search_early_term_none(
739     AV1_COMP *const cpi, MACROBLOCK *x, SIMPLE_MOTION_DATA_TREE *sms_tree,
740     const RD_STATS *none_rdc, PartitionSearchState *part_state) {
741   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
742   const int mi_row = blk_params->mi_row, mi_col = blk_params->mi_col;
743   const BLOCK_SIZE bsize = blk_params->bsize;
744 
745   float features[FEATURE_SIZE_SMS_TERM_NONE] = { 0.0f };
746   simple_motion_search_prune_part_features(cpi, x, sms_tree, mi_row, mi_col,
747                                            bsize, features,
748                                            FEATURE_SMS_PRUNE_PART_FLAG);
749   int f_idx = FEATURE_SIZE_SMS_PRUNE_PART;
750 
751   features[f_idx++] = log1pf((float)none_rdc->rate);
752   features[f_idx++] = log1pf((float)none_rdc->dist);
753   features[f_idx++] = log1pf((float)none_rdc->rdcost);
754 
755   assert(f_idx == FEATURE_SIZE_SMS_TERM_NONE);
756 
757   const float *ml_mean = NULL;
758   const float *ml_std = NULL;
759   const float *ml_model = NULL;
760 
761   if (bsize == BLOCK_128X128) {
762     ml_mean = av1_simple_motion_search_term_none_mean_128;
763     ml_std = av1_simple_motion_search_term_none_std_128;
764     ml_model = av1_simple_motion_search_term_none_model_128;
765   } else if (bsize == BLOCK_64X64) {
766     ml_mean = av1_simple_motion_search_term_none_mean_64;
767     ml_std = av1_simple_motion_search_term_none_std_64;
768     ml_model = av1_simple_motion_search_term_none_model_64;
769   } else if (bsize == BLOCK_32X32) {
770     ml_mean = av1_simple_motion_search_term_none_mean_32;
771     ml_std = av1_simple_motion_search_term_none_std_32;
772     ml_model = av1_simple_motion_search_term_none_model_32;
773   } else if (bsize == BLOCK_16X16) {
774     ml_mean = av1_simple_motion_search_term_none_mean_16;
775     ml_std = av1_simple_motion_search_term_none_std_16;
776     ml_model = av1_simple_motion_search_term_none_model_16;
777   } else {
778     assert(0 && "Unexpected block size in simple_motion_term_none");
779   }
780 
781   // Write features to file
782   write_features_to_file(cpi->oxcf.partition_info_path,
783                          cpi->ext_part_controller.test_mode, features,
784                          FEATURE_SIZE_SMS_TERM_NONE, 3, bsize, mi_row, mi_col);
785 
786   if (ext_ml_model_decision_after_none_part2(
787           cpi, features, &part_state->terminate_partition_search)) {
788     return;
789   }
790 
791   if (ml_model) {
792     float score = 0.0f;
793     for (f_idx = 0; f_idx < FEATURE_SIZE_SMS_TERM_NONE; f_idx++) {
794       score +=
795           ml_model[f_idx] * (features[f_idx] - ml_mean[f_idx]) / ml_std[f_idx];
796     }
797     score += ml_model[FEATURE_SIZE_SMS_TERM_NONE];
798 
799     if (score >= 0.0f) {
800       part_state->terminate_partition_search = 1;
801     }
802   }
803 }
804 
av1_get_max_min_partition_features(AV1_COMP * const cpi,MACROBLOCK * x,int mi_row,int mi_col,float * features)805 void av1_get_max_min_partition_features(AV1_COMP *const cpi, MACROBLOCK *x,
806                                         int mi_row, int mi_col,
807                                         float *features) {
808   AV1_COMMON *const cm = &cpi->common;
809   MACROBLOCKD *xd = &x->e_mbd;
810   const BLOCK_SIZE sb_size = cm->seq_params->sb_size;
811 
812   // Currently this only allows 128X128 SB size. May extend it to 64X64 SB size.
813   assert(sb_size == BLOCK_128X128);
814 
815   int f_idx = 0;
816 
817   const int dc_q = av1_dc_quant_QTX(x->qindex, 0, xd->bd) >> (xd->bd - 8);
818   const float log_q_sq = log1pf((float)(dc_q * dc_q) / 256.0f);
819 
820   // Perform full-pixel single motion search in Y plane of 16x16 mbs in the sb
821   float sum_mv_row_sq = 0;
822   float sum_mv_row = 0;
823   float min_abs_mv_row = FLT_MAX;
824   float max_abs_mv_row = 0;
825 
826   float sum_mv_col_sq = 0;
827   float sum_mv_col = 0;
828   float min_abs_mv_col = FLT_MAX;
829   float max_abs_mv_col = 0;
830 
831   float sum_log_sse_sq = 0;
832   float sum_log_sse = 0;
833   float min_log_sse = FLT_MAX;
834   float max_log_sse = 0;
835 
836   const BLOCK_SIZE mb_size = BLOCK_16X16;
837   const int mb_rows = block_size_high[sb_size] / block_size_high[mb_size];
838   const int mb_cols = block_size_wide[sb_size] / block_size_wide[mb_size];
839   const int mb_in_mi_size_high_log2 = mi_size_high_log2[mb_size];
840   const int mb_in_mi_size_wide_log2 = mi_size_wide_log2[mb_size];
841 
842   for (int mb_row = 0; mb_row < mb_rows; mb_row++)
843     for (int mb_col = 0; mb_col < mb_cols; mb_col++) {
844       const int this_mi_row = mi_row + (mb_row << mb_in_mi_size_high_log2);
845       const int this_mi_col = mi_col + (mb_col << mb_in_mi_size_wide_log2);
846       unsigned int sse = 0;
847       unsigned int var = 0;
848       const FULLPEL_MV start_mv = kZeroFullMv;
849       const MV_REFERENCE_FRAME ref =
850           cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
851       const int_mv best_mv = av1_simple_motion_search_sse_var(
852           cpi, x, this_mi_row, this_mi_col, mb_size, ref, start_mv, 1, 0, &sse,
853           &var);
854 
855       const float mv_row = (float)(best_mv.as_mv.row / 8);
856       const float mv_col = (float)(best_mv.as_mv.col / 8);
857       const float log_sse = log1pf((float)sse);
858       const float abs_mv_row = fabsf(mv_row);
859       const float abs_mv_col = fabsf(mv_col);
860 
861       sum_mv_row_sq += mv_row * mv_row;
862       sum_mv_row += mv_row;
863       sum_mv_col_sq += mv_col * mv_col;
864       sum_mv_col += mv_col;
865 
866       if (abs_mv_row < min_abs_mv_row) min_abs_mv_row = abs_mv_row;
867       if (abs_mv_row > max_abs_mv_row) max_abs_mv_row = abs_mv_row;
868       if (abs_mv_col < min_abs_mv_col) min_abs_mv_col = abs_mv_col;
869       if (abs_mv_col > max_abs_mv_col) max_abs_mv_col = abs_mv_col;
870 
871       sum_log_sse_sq += log_sse * log_sse;
872       sum_log_sse += log_sse;
873       if (log_sse < min_log_sse) min_log_sse = log_sse;
874       if (log_sse > max_log_sse) max_log_sse = log_sse;
875     }
876   const int blks = mb_rows * mb_cols;
877   const float avg_mv_row = sum_mv_row / (float)blks;
878   const float var_mv_row =
879       sum_mv_row_sq / (float)blks - avg_mv_row * avg_mv_row;
880 
881   const float avg_mv_col = sum_mv_col / (float)blks;
882   const float var_mv_col =
883       sum_mv_col_sq / (float)blks - avg_mv_col * avg_mv_col;
884 
885   const float avg_log_sse = sum_log_sse / (float)blks;
886   const float var_log_sse =
887       sum_log_sse_sq / (float)blks - avg_log_sse * avg_log_sse;
888 
889   features[f_idx++] = avg_log_sse;
890   features[f_idx++] = avg_mv_col;
891   features[f_idx++] = avg_mv_row;
892   features[f_idx++] = log_q_sq;
893   features[f_idx++] = max_abs_mv_col;
894   features[f_idx++] = max_abs_mv_row;
895   features[f_idx++] = max_log_sse;
896   features[f_idx++] = min_abs_mv_col;
897   features[f_idx++] = min_abs_mv_row;
898   features[f_idx++] = min_log_sse;
899   features[f_idx++] = var_log_sse;
900   features[f_idx++] = var_mv_col;
901   features[f_idx++] = var_mv_row;
902 
903   assert(f_idx == FEATURE_SIZE_MAX_MIN_PART_PRED);
904 }
905 
906 // Convert result index to block size.
907 // result idx     block size
908 //     0          BLOCK_16X16
909 //     1          BLOCK_32X32
910 //     2          BLOCK_64X64
911 //     3          BLOCK_128X128
get_block_size(int idx)912 static BLOCK_SIZE get_block_size(int idx) {
913   return (BLOCK_SIZE)((idx + 2) * 3);
914 }
915 
av1_predict_max_partition(const AV1_COMP * const cpi,const MACROBLOCK * const x,const float * features)916 BLOCK_SIZE av1_predict_max_partition(const AV1_COMP *const cpi,
917                                      const MACROBLOCK *const x,
918                                      const float *features) {
919   float scores[MAX_NUM_CLASSES_MAX_MIN_PART_PRED] = { 0.0f };
920   const NN_CONFIG *nn_config = &av1_max_part_pred_nn_config;
921 
922   assert(cpi->sf.part_sf.auto_max_partition_based_on_simple_motion !=
923          NOT_IN_USE);
924 
925   av1_nn_predict(features, nn_config, 1, scores);
926 
927   int result = MAX_NUM_CLASSES_MAX_MIN_PART_PRED - 1;
928   if (cpi->sf.part_sf.auto_max_partition_based_on_simple_motion ==
929       DIRECT_PRED) {
930     result = 0;
931     float max_score = scores[0];
932     for (int i = 1; i < MAX_NUM_CLASSES_MAX_MIN_PART_PRED; ++i) {
933       if (scores[i] > max_score) {
934         max_score = scores[i];
935         result = i;
936       }
937     }
938     return get_block_size(result);
939   }
940 
941   float probs[MAX_NUM_CLASSES_MAX_MIN_PART_PRED] = { 0.0f };
942   av1_nn_softmax(scores, probs, MAX_NUM_CLASSES_MAX_MIN_PART_PRED);
943 
944   if (cpi->sf.part_sf.auto_max_partition_based_on_simple_motion ==
945       RELAXED_PRED) {
946     for (result = MAX_NUM_CLASSES_MAX_MIN_PART_PRED - 1; result >= 0;
947          --result) {
948       if (result < MAX_NUM_CLASSES_MAX_MIN_PART_PRED - 1) {
949         probs[result] += probs[result + 1];
950       }
951       if (probs[result] > 0.2) break;
952     }
953   } else if (cpi->sf.part_sf.auto_max_partition_based_on_simple_motion ==
954              ADAPT_PRED) {
955     const BLOCK_SIZE sb_size = cpi->common.seq_params->sb_size;
956     // TODO(debargha): x->source_variance is unavailable at this point,
957     // so compute. The redundant recomputation later can be removed.
958     const unsigned int source_variance = av1_get_perpixel_variance_facade(
959         cpi, &x->e_mbd, &x->plane[0].src, sb_size, AOM_PLANE_Y);
960     if (source_variance > 16) {
961       const double thresh = source_variance < 128 ? 0.05 : 0.1;
962       for (result = MAX_NUM_CLASSES_MAX_MIN_PART_PRED - 1; result >= 0;
963            --result) {
964         if (result < MAX_NUM_CLASSES_MAX_MIN_PART_PRED - 1) {
965           probs[result] += probs[result + 1];
966         }
967         if (probs[result] > thresh) break;
968       }
969     }
970   }
971 
972   return get_block_size(result);
973 }
974 
975 // Get the minimum partition block width and height(in log scale) under a
976 // SIMPLE_MOTION_DATA_TREE.
get_min_bsize(const SIMPLE_MOTION_DATA_TREE * sms_tree,int * min_bw,int * min_bh)977 static inline void get_min_bsize(const SIMPLE_MOTION_DATA_TREE *sms_tree,
978                                  int *min_bw, int *min_bh) {
979   if (!sms_tree) return;
980 
981   const BLOCK_SIZE bsize = sms_tree->block_size;
982   if (bsize == BLOCK_4X4) {
983     *min_bw = 0;
984     *min_bh = 0;
985     return;
986   }
987 
988   PARTITION_TYPE part_type = sms_tree->partitioning;
989   if (part_type == PARTITION_INVALID) return;
990 
991   if (part_type == PARTITION_SPLIT) {
992     for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
993       get_min_bsize(sms_tree->split[i], min_bw, min_bh);
994     }
995   } else {
996     if (part_type == PARTITION_HORZ_A || part_type == PARTITION_HORZ_B ||
997         part_type == PARTITION_VERT_A || part_type == PARTITION_VERT_B)
998       part_type = PARTITION_SPLIT;
999     const BLOCK_SIZE subsize = get_partition_subsize(bsize, part_type);
1000     if (subsize != BLOCK_INVALID) {
1001       *min_bw = AOMMIN(*min_bw, mi_size_wide_log2[subsize]);
1002       *min_bh = AOMMIN(*min_bh, mi_size_high_log2[subsize]);
1003     }
1004   }
1005 }
1006 
add_rd_feature(int64_t rd,int64_t best_rd,float * features,int * feature_idx)1007 static inline void add_rd_feature(int64_t rd, int64_t best_rd, float *features,
1008                                   int *feature_idx) {
1009   const int rd_valid = rd > 0 && rd < INT64_MAX;
1010   const float rd_ratio = rd_valid ? (float)rd / best_rd : 1.0f;
1011   features[(*feature_idx)++] = (float)rd_valid;
1012   features[(*feature_idx)++] = rd_ratio;
1013 }
1014 
1015 #define FEATURES 31
av1_ml_early_term_after_split(AV1_COMP * const cpi,MACROBLOCK * const x,SIMPLE_MOTION_DATA_TREE * const sms_tree,int64_t best_rd,int64_t part_none_rd,int64_t part_split_rd,int64_t * split_block_rd,PartitionSearchState * part_state)1016 void av1_ml_early_term_after_split(AV1_COMP *const cpi, MACROBLOCK *const x,
1017                                    SIMPLE_MOTION_DATA_TREE *const sms_tree,
1018                                    int64_t best_rd, int64_t part_none_rd,
1019                                    int64_t part_split_rd,
1020                                    int64_t *split_block_rd,
1021                                    PartitionSearchState *part_state) {
1022   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
1023   const int mi_row = blk_params->mi_row, mi_col = blk_params->mi_col;
1024   const BLOCK_SIZE bsize = blk_params->bsize;
1025 
1026   if (best_rd <= 0 || best_rd == INT64_MAX ||
1027       part_state->terminate_partition_search)
1028     return;
1029 
1030   const AV1_COMMON *const cm = &cpi->common;
1031   const int is_480p_or_larger = AOMMIN(cm->width, cm->height) >= 480;
1032   const NN_CONFIG *nn_config = NULL;
1033   float thresh = -1e6;
1034   switch (bsize) {
1035     case BLOCK_128X128: break;
1036     case BLOCK_64X64:
1037       nn_config = &av1_early_term_after_split_nnconfig_64;
1038       thresh = is_480p_or_larger ? -2.0f : -1.2f;
1039       break;
1040     case BLOCK_32X32:
1041       nn_config = &av1_early_term_after_split_nnconfig_32;
1042       thresh = is_480p_or_larger ? -2.6f : -2.3f;
1043       break;
1044     case BLOCK_16X16:
1045       nn_config = &av1_early_term_after_split_nnconfig_16;
1046       thresh = is_480p_or_larger ? -2.0f : -2.4f;
1047       break;
1048     case BLOCK_8X8:
1049       nn_config = &av1_early_term_after_split_nnconfig_8;
1050       thresh = is_480p_or_larger ? -1.0f : -1.4f;
1051       break;
1052     case BLOCK_4X4: break;
1053     default:
1054       assert(0 && "Invalid block size in av1_ml_early_term_after_split().");
1055       break;
1056   }
1057   if (!nn_config) return;
1058 
1059   // Use more conservative threshold for level 1.
1060   if (cpi->sf.part_sf.ml_early_term_after_part_split_level < 2) thresh -= 0.3f;
1061 
1062   const MACROBLOCKD *const xd = &x->e_mbd;
1063   const int dc_q = av1_dc_quant_QTX(x->qindex, 0, xd->bd) >> (xd->bd - 8);
1064   const int bs = block_size_wide[bsize];
1065   int f_idx = 0;
1066   float features[FEATURES] = { 0.0f };
1067 
1068   features[f_idx++] = log1pf((float)dc_q / 4.0f);
1069   features[f_idx++] = log1pf((float)best_rd / bs / bs / 1024.0f);
1070 
1071   add_rd_feature(part_none_rd, best_rd, features, &f_idx);
1072   add_rd_feature(part_split_rd, best_rd, features, &f_idx);
1073 
1074   for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
1075     add_rd_feature(split_block_rd[i], best_rd, features, &f_idx);
1076     int min_bw = MAX_SB_SIZE_LOG2;
1077     int min_bh = MAX_SB_SIZE_LOG2;
1078     get_min_bsize(sms_tree->split[i], &min_bw, &min_bh);
1079     features[f_idx++] = (float)min_bw;
1080     features[f_idx++] = (float)min_bh;
1081   }
1082 
1083   simple_motion_search_prune_part_features(cpi, x, sms_tree, mi_row, mi_col,
1084                                            bsize, NULL,
1085                                            FEATURE_SMS_PRUNE_PART_FLAG);
1086 
1087   features[f_idx++] = log1pf((float)sms_tree->sms_none_feat[1]);
1088 
1089   features[f_idx++] = log1pf((float)sms_tree->split[0]->sms_none_feat[1]);
1090   features[f_idx++] = log1pf((float)sms_tree->split[1]->sms_none_feat[1]);
1091   features[f_idx++] = log1pf((float)sms_tree->split[2]->sms_none_feat[1]);
1092   features[f_idx++] = log1pf((float)sms_tree->split[3]->sms_none_feat[1]);
1093 
1094   features[f_idx++] = log1pf((float)sms_tree->sms_rect_feat[1]);
1095   features[f_idx++] = log1pf((float)sms_tree->sms_rect_feat[3]);
1096   features[f_idx++] = log1pf((float)sms_tree->sms_rect_feat[5]);
1097   features[f_idx++] = log1pf((float)sms_tree->sms_rect_feat[7]);
1098 
1099   assert(f_idx == FEATURES);
1100 
1101   // Write features to file
1102   write_features_to_file(cpi->oxcf.partition_info_path,
1103                          cpi->ext_part_controller.test_mode, features, FEATURES,
1104                          4, bsize, mi_row, mi_col);
1105 
1106   if (ext_ml_model_decision_after_split(
1107           cpi, features, &part_state->terminate_partition_search)) {
1108     return;
1109   }
1110 
1111   float score = 0.0f;
1112   av1_nn_predict(features, nn_config, 1, &score);
1113   // Score is indicator of confidence that we should NOT terminate.
1114   if (score < thresh) {
1115     part_state->terminate_partition_search = 1;
1116   }
1117 }
1118 #undef FEATURES
1119 
av1_ml_prune_rect_partition(AV1_COMP * const cpi,const MACROBLOCK * const x,int64_t best_rd,int64_t none_rd,const int64_t * split_rd,PartitionSearchState * part_state)1120 void av1_ml_prune_rect_partition(AV1_COMP *const cpi, const MACROBLOCK *const x,
1121                                  int64_t best_rd, int64_t none_rd,
1122                                  const int64_t *split_rd,
1123                                  PartitionSearchState *part_state) {
1124   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
1125   const int mi_row = blk_params->mi_row, mi_col = blk_params->mi_col;
1126   const BLOCK_SIZE bsize = blk_params->bsize;
1127 
1128   if (bsize < BLOCK_8X8 || best_rd >= 1000000000) return;
1129   best_rd = AOMMAX(best_rd, 1);
1130   const NN_CONFIG *nn_config = NULL;
1131   const float prob_thresholds[5] = { 0.01f, 0.01f, 0.004f, 0.002f, 0.002f };
1132   float cur_thresh = 0.0f;
1133   switch (bsize) {
1134     case BLOCK_8X8:
1135       nn_config = &av1_rect_partition_nnconfig_8;
1136       cur_thresh = prob_thresholds[0];
1137       break;
1138     case BLOCK_16X16:
1139       nn_config = &av1_rect_partition_nnconfig_16;
1140       cur_thresh = prob_thresholds[1];
1141       break;
1142     case BLOCK_32X32:
1143       nn_config = &av1_rect_partition_nnconfig_32;
1144       cur_thresh = prob_thresholds[2];
1145       break;
1146     case BLOCK_64X64:
1147       nn_config = &av1_rect_partition_nnconfig_64;
1148       cur_thresh = prob_thresholds[3];
1149       break;
1150     case BLOCK_128X128:
1151       nn_config = &av1_rect_partition_nnconfig_128;
1152       cur_thresh = prob_thresholds[4];
1153       break;
1154     default: assert(0 && "Unexpected bsize.");
1155   }
1156   if (!nn_config) return;
1157 
1158   // 1. Compute input features
1159   float features[9];
1160 
1161   // RD cost ratios
1162   for (int i = 0; i < 5; i++) features[i] = 1.0f;
1163   if (none_rd > 0 && none_rd < 1000000000)
1164     features[0] = (float)none_rd / (float)best_rd;
1165   for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
1166     if (split_rd[i] > 0 && split_rd[i] < 1000000000)
1167       features[1 + i] = (float)split_rd[i] / (float)best_rd;
1168   }
1169 
1170   // Variance ratios
1171   const MACROBLOCKD *const xd = &x->e_mbd;
1172   int whole_block_variance;
1173   whole_block_variance = av1_get_perpixel_variance_facade(
1174       cpi, xd, &x->plane[0].src, bsize, AOM_PLANE_Y);
1175   whole_block_variance = AOMMAX(whole_block_variance, 1);
1176 
1177   int split_variance[SUB_PARTITIONS_SPLIT];
1178   const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
1179   struct buf_2d buf;
1180   buf.stride = x->plane[0].src.stride;
1181   const int bw = block_size_wide[bsize];
1182   for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
1183     const int x_idx = (i & 1) * bw / 2;
1184     const int y_idx = (i >> 1) * bw / 2;
1185     buf.buf = x->plane[0].src.buf + x_idx + y_idx * buf.stride;
1186     split_variance[i] =
1187         av1_get_perpixel_variance_facade(cpi, xd, &buf, subsize, AOM_PLANE_Y);
1188   }
1189 
1190   for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++)
1191     features[5 + i] = (float)split_variance[i] / (float)whole_block_variance;
1192 
1193   // Write features to file
1194   write_features_to_file(cpi->oxcf.partition_info_path,
1195                          cpi->ext_part_controller.test_mode, features,
1196                          /*feature_size=*/9, 5, bsize, mi_row, mi_col);
1197 
1198   if (ext_ml_model_decision_after_split_part2(
1199           &cpi->ext_part_controller, frame_is_intra_only(&cpi->common),
1200           features, &part_state->prune_rect_part[HORZ],
1201           &part_state->prune_rect_part[VERT])) {
1202     return;
1203   }
1204 
1205   // 2. Do the prediction and prune 0-2 partitions based on their probabilities
1206   float raw_scores[3] = { 0.0f };
1207   av1_nn_predict(features, nn_config, 1, raw_scores);
1208   float probs[3] = { 0.0f };
1209   av1_nn_softmax(raw_scores, probs, 3);
1210 
1211   // probs[0] is the probability of the fact that both rectangular partitions
1212   // are worse than current best_rd
1213   if (probs[1] <= cur_thresh) part_state->prune_rect_part[HORZ] = 1;
1214   if (probs[2] <= cur_thresh) part_state->prune_rect_part[VERT] = 1;
1215 }
1216 
1217 // Use a ML model to predict if horz_a, horz_b, vert_a, and vert_b should be
1218 // considered.
ml_prune_ab_partition(AV1_COMP * const cpi,int part_ctx,int var_ctx,int64_t best_rd,PartitionSearchState * part_state,int * ab_partitions_allowed)1219 static void ml_prune_ab_partition(AV1_COMP *const cpi, int part_ctx,
1220                                   int var_ctx, int64_t best_rd,
1221                                   PartitionSearchState *part_state,
1222                                   int *ab_partitions_allowed) {
1223   const PartitionBlkParams blk_params = part_state->part_blk_params;
1224   const int mi_row = blk_params.mi_row;
1225   const int mi_col = blk_params.mi_col;
1226   const BLOCK_SIZE bsize = blk_params.bsize;
1227 
1228   if (bsize < BLOCK_8X8 || best_rd >= 1000000000) return;
1229   const NN_CONFIG *nn_config = NULL;
1230   switch (bsize) {
1231     case BLOCK_8X8: nn_config = NULL; break;
1232     case BLOCK_16X16: nn_config = &av1_ab_partition_nnconfig_16; break;
1233     case BLOCK_32X32: nn_config = &av1_ab_partition_nnconfig_32; break;
1234     case BLOCK_64X64: nn_config = &av1_ab_partition_nnconfig_64; break;
1235     case BLOCK_128X128: nn_config = &av1_ab_partition_nnconfig_128; break;
1236     default: assert(0 && "Unexpected bsize.");
1237   }
1238   if (!nn_config) return;
1239 
1240   // Generate features.
1241   float features[10];
1242   int feature_index = 0;
1243   features[feature_index++] = (float)part_ctx;
1244   features[feature_index++] = (float)var_ctx;
1245   const int rdcost = (int)AOMMIN(INT_MAX, best_rd);
1246   int sub_block_rdcost[8] = { 0 };
1247   int rd_index = 0;
1248   for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1249     const int64_t *horz_rd = part_state->rect_part_rd[HORZ];
1250     if (horz_rd[i] > 0 && horz_rd[i] < 1000000000)
1251       sub_block_rdcost[rd_index] = (int)horz_rd[i];
1252     ++rd_index;
1253   }
1254   for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1255     const int64_t *vert_rd = part_state->rect_part_rd[VERT];
1256     if (vert_rd[i] > 0 && vert_rd[i] < 1000000000)
1257       sub_block_rdcost[rd_index] = (int)vert_rd[i];
1258     ++rd_index;
1259   }
1260   for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
1261     const int64_t *split_rd = part_state->split_rd;
1262     if (split_rd[i] > 0 && split_rd[i] < 1000000000)
1263       sub_block_rdcost[rd_index] = (int)split_rd[i];
1264     ++rd_index;
1265   }
1266   for (int i = 0; i < 8; ++i) {
1267     // Ratio between the sub-block RD and the whole-block RD.
1268     float rd_ratio = 1.0f;
1269     if (sub_block_rdcost[i] > 0 && sub_block_rdcost[i] < rdcost)
1270       rd_ratio = (float)sub_block_rdcost[i] / (float)rdcost;
1271     features[feature_index++] = rd_ratio;
1272   }
1273   assert(feature_index == 10);
1274 
1275   // Write features to file
1276   if (!frame_is_intra_only(&cpi->common)) {
1277     write_features_to_file(cpi->oxcf.partition_info_path,
1278                            cpi->ext_part_controller.test_mode, features,
1279                            /*feature_size=*/10, 6, bsize, mi_row, mi_col);
1280   }
1281 
1282   if (ext_ml_model_decision_after_rect(
1283           &cpi->ext_part_controller, frame_is_intra_only(&cpi->common),
1284           features, &ab_partitions_allowed[HORZ_A],
1285           &ab_partitions_allowed[HORZ_B], &ab_partitions_allowed[VERT_A],
1286           &ab_partitions_allowed[VERT_B])) {
1287     return;
1288   }
1289 
1290   // Calculate scores using the NN model.
1291   float score[16] = { 0.0f };
1292   av1_nn_predict(features, nn_config, 1, score);
1293   int int_score[16];
1294   int max_score = -1000;
1295   for (int i = 0; i < 16; ++i) {
1296     int_score[i] = (int)(100 * score[i]);
1297     max_score = AOMMAX(int_score[i], max_score);
1298   }
1299 
1300   // Make decisions based on the model scores.
1301   int thresh = max_score;
1302   switch (bsize) {
1303     case BLOCK_16X16: thresh -= 150; break;
1304     case BLOCK_32X32: thresh -= 100; break;
1305     default: break;
1306   }
1307   av1_zero_array(ab_partitions_allowed, NUM_AB_PARTS);
1308   for (int i = 0; i < 16; ++i) {
1309     if (int_score[i] >= thresh) {
1310       if ((i >> 0) & 1) ab_partitions_allowed[HORZ_A] = 1;
1311       if ((i >> 1) & 1) ab_partitions_allowed[HORZ_B] = 1;
1312       if ((i >> 2) & 1) ab_partitions_allowed[VERT_A] = 1;
1313       if ((i >> 3) & 1) ab_partitions_allowed[VERT_B] = 1;
1314     }
1315   }
1316 }
1317 
1318 #define FEATURES 18
1319 #define LABELS 4
1320 // Use a ML model to predict if horz4 and vert4 should be considered.
av1_ml_prune_4_partition(AV1_COMP * const cpi,MACROBLOCK * const x,int part_ctx,int64_t best_rd,PartitionSearchState * part_state,int * part4_allowed,unsigned int pb_source_variance)1321 void av1_ml_prune_4_partition(AV1_COMP *const cpi, MACROBLOCK *const x,
1322                               int part_ctx, int64_t best_rd,
1323                               PartitionSearchState *part_state,
1324                               int *part4_allowed,
1325                               unsigned int pb_source_variance) {
1326   const PartitionBlkParams blk_params = part_state->part_blk_params;
1327   const int mi_row = blk_params.mi_row;
1328   const int mi_col = blk_params.mi_col;
1329   const BLOCK_SIZE bsize = blk_params.bsize;
1330 
1331   int64_t(*rect_part_rd)[SUB_PARTITIONS_RECT] = part_state->rect_part_rd;
1332   int64_t *split_rd = part_state->split_rd;
1333   if (ext_ml_model_decision_after_part_ab(
1334           cpi, x, bsize, part_ctx, best_rd, rect_part_rd, split_rd,
1335           &part4_allowed[HORZ4], &part4_allowed[VERT4], pb_source_variance,
1336           mi_row, mi_col))
1337     return;
1338 
1339   if (best_rd >= 1000000000) return;
1340   int64_t *horz_rd = rect_part_rd[HORZ4];
1341   int64_t *vert_rd = rect_part_rd[VERT4];
1342   const NN_CONFIG *nn_config = NULL;
1343   // 4-way partitions are only allowed for these three square block sizes.
1344   switch (bsize) {
1345     case BLOCK_16X16: nn_config = &av1_4_partition_nnconfig_16; break;
1346     case BLOCK_32X32: nn_config = &av1_4_partition_nnconfig_32; break;
1347     case BLOCK_64X64: nn_config = &av1_4_partition_nnconfig_64; break;
1348     default: assert(0 && "Unexpected bsize.");
1349   }
1350   if (!nn_config) return;
1351 
1352   // Generate features.
1353   float features[FEATURES];
1354   int feature_index = 0;
1355   features[feature_index++] = (float)part_ctx;
1356   features[feature_index++] = (float)get_unsigned_bits(pb_source_variance);
1357 
1358   const int rdcost = (int)AOMMIN(INT_MAX, best_rd);
1359   int sub_block_rdcost[8] = { 0 };
1360   int rd_index = 0;
1361   for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1362     if (horz_rd[i] > 0 && horz_rd[i] < 1000000000)
1363       sub_block_rdcost[rd_index] = (int)horz_rd[i];
1364     ++rd_index;
1365   }
1366   for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1367     if (vert_rd[i] > 0 && vert_rd[i] < 1000000000)
1368       sub_block_rdcost[rd_index] = (int)vert_rd[i];
1369     ++rd_index;
1370   }
1371   for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
1372     if (split_rd[i] > 0 && split_rd[i] < 1000000000)
1373       sub_block_rdcost[rd_index] = (int)split_rd[i];
1374     ++rd_index;
1375   }
1376   for (int i = 0; i < 8; ++i) {
1377     // Ratio between the sub-block RD and the whole-block RD.
1378     float rd_ratio = 1.0f;
1379     if (sub_block_rdcost[i] > 0 && sub_block_rdcost[i] < rdcost)
1380       rd_ratio = (float)sub_block_rdcost[i] / (float)rdcost;
1381     features[feature_index++] = rd_ratio;
1382   }
1383 
1384   // Get variance of the 1:4 and 4:1 sub-blocks.
1385   unsigned int horz_4_source_var[SUB_PARTITIONS_PART4] = { 0 };
1386   unsigned int vert_4_source_var[SUB_PARTITIONS_PART4] = { 0 };
1387   {
1388     BLOCK_SIZE horz_4_bs = get_partition_subsize(bsize, PARTITION_HORZ_4);
1389     BLOCK_SIZE vert_4_bs = get_partition_subsize(bsize, PARTITION_VERT_4);
1390 
1391     assert(horz_4_bs != BLOCK_INVALID);
1392     assert(vert_4_bs != BLOCK_INVALID);
1393 
1394     av1_setup_src_planes(x, cpi->source, mi_row, mi_col,
1395                          av1_num_planes(&cpi->common), bsize);
1396     const int src_stride = x->plane[0].src.stride;
1397     uint8_t *src = x->plane[0].src.buf;
1398     const MACROBLOCKD *const xd = &x->e_mbd;
1399 
1400     struct buf_2d horz_4_src, vert_4_src;
1401     horz_4_src.stride = src_stride;
1402     vert_4_src.stride = src_stride;
1403 
1404     for (int i = 0; i < SUB_PARTITIONS_PART4; ++i) {
1405       horz_4_src.buf = src + i * block_size_high[horz_4_bs] * src_stride;
1406       vert_4_src.buf = src + i * block_size_wide[vert_4_bs];
1407 
1408       horz_4_source_var[i] = av1_get_perpixel_variance_facade(
1409           cpi, xd, &horz_4_src, horz_4_bs, AOM_PLANE_Y);
1410       vert_4_source_var[i] = av1_get_perpixel_variance_facade(
1411           cpi, xd, &vert_4_src, vert_4_bs, AOM_PLANE_Y);
1412     }
1413   }
1414 
1415   const float denom = (float)(pb_source_variance + 1);
1416   const float low_b = 0.1f;
1417   const float high_b = 10.0f;
1418   for (int i = 0; i < SUB_PARTITIONS_PART4; ++i) {
1419     // Ratio between the 4:1 sub-block variance and the whole-block variance.
1420     float var_ratio = (float)(horz_4_source_var[i] + 1) / denom;
1421     if (var_ratio < low_b) var_ratio = low_b;
1422     if (var_ratio > high_b) var_ratio = high_b;
1423     features[feature_index++] = var_ratio;
1424   }
1425   for (int i = 0; i < SUB_PARTITIONS_PART4; ++i) {
1426     // Ratio between the 1:4 sub-block RD and the whole-block RD.
1427     float var_ratio = (float)(vert_4_source_var[i] + 1) / denom;
1428     if (var_ratio < low_b) var_ratio = low_b;
1429     if (var_ratio > high_b) var_ratio = high_b;
1430     features[feature_index++] = var_ratio;
1431   }
1432   assert(feature_index == FEATURES);
1433 
1434   // Write features to file
1435   if (!frame_is_intra_only(&cpi->common)) {
1436     write_features_to_file(cpi->oxcf.partition_info_path,
1437                            cpi->ext_part_controller.test_mode, features,
1438                            FEATURES, 7, bsize, mi_row, mi_col);
1439   }
1440 
1441   // Calculate scores using the NN model.
1442   float score[LABELS] = { 0.0f };
1443   av1_nn_predict(features, nn_config, 1, score);
1444   int int_score[LABELS];
1445   int max_score = -1000;
1446   for (int i = 0; i < LABELS; ++i) {
1447     int_score[i] = (int)(100 * score[i]);
1448     max_score = AOMMAX(int_score[i], max_score);
1449   }
1450 
1451   // Make decisions based on the model scores.
1452   int thresh = max_score;
1453   switch (bsize) {
1454     case BLOCK_16X16: thresh -= 500; break;
1455     case BLOCK_32X32: thresh -= 500; break;
1456     case BLOCK_64X64: thresh -= 200; break;
1457     default: break;
1458   }
1459   av1_zero_array(part4_allowed, NUM_PART4_TYPES);
1460   for (int i = 0; i < LABELS; ++i) {
1461     if (int_score[i] >= thresh) {
1462       if ((i >> 0) & 1) part4_allowed[HORZ4] = 1;
1463       if ((i >> 1) & 1) part4_allowed[VERT4] = 1;
1464     }
1465   }
1466 }
1467 #undef FEATURES
1468 #undef LABELS
1469 
1470 #define FEATURES 4
av1_ml_predict_breakout(AV1_COMP * const cpi,const MACROBLOCK * const x,const RD_STATS * const rd_stats,unsigned int pb_source_variance,int bit_depth,PartitionSearchState * part_state)1471 void av1_ml_predict_breakout(AV1_COMP *const cpi, const MACROBLOCK *const x,
1472                              const RD_STATS *const rd_stats,
1473                              unsigned int pb_source_variance, int bit_depth,
1474                              PartitionSearchState *part_state) {
1475   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
1476   const int mi_row = blk_params->mi_row, mi_col = blk_params->mi_col;
1477   const BLOCK_SIZE bsize = blk_params->bsize;
1478 
1479   const NN_CONFIG *nn_config = NULL;
1480   int thresh = 0;
1481   switch (bsize) {
1482     case BLOCK_8X8:
1483       nn_config = &av1_partition_breakout_nnconfig_8;
1484       thresh = cpi->sf.part_sf.ml_partition_search_breakout_thresh[0];
1485       break;
1486     case BLOCK_16X16:
1487       nn_config = &av1_partition_breakout_nnconfig_16;
1488       thresh = cpi->sf.part_sf.ml_partition_search_breakout_thresh[1];
1489       break;
1490     case BLOCK_32X32:
1491       nn_config = &av1_partition_breakout_nnconfig_32;
1492       thresh = cpi->sf.part_sf.ml_partition_search_breakout_thresh[2];
1493       break;
1494     case BLOCK_64X64:
1495       nn_config = &av1_partition_breakout_nnconfig_64;
1496       thresh = cpi->sf.part_sf.ml_partition_search_breakout_thresh[3];
1497       break;
1498     case BLOCK_128X128:
1499       nn_config = &av1_partition_breakout_nnconfig_128;
1500       thresh = cpi->sf.part_sf.ml_partition_search_breakout_thresh[4];
1501       break;
1502     default: assert(0 && "Unexpected bsize.");
1503   }
1504   if (!nn_config || thresh < 0) return;
1505 
1506   const float ml_predict_breakout_thresh_scale[3] = { 1.15f, 1.05f, 1.0f };
1507   thresh = (int)((float)thresh *
1508                  ml_predict_breakout_thresh_scale
1509                      [cpi->sf.part_sf.ml_predict_breakout_level - 1]);
1510 
1511   // Generate feature values.
1512   float features[FEATURES];
1513   int feature_index = 0;
1514 
1515   const int num_pels_log2 = num_pels_log2_lookup[bsize];
1516   float rate_f = (float)AOMMIN(rd_stats->rate, INT_MAX);
1517   rate_f = ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
1518            rate_f;
1519   features[feature_index++] = rate_f;
1520 
1521   const float dist_f =
1522       (float)(AOMMIN(rd_stats->dist, INT_MAX) >> num_pels_log2);
1523   features[feature_index++] = dist_f;
1524 
1525   features[feature_index++] = (float)pb_source_variance;
1526 
1527   const int dc_q = (int)x->plane[0].dequant_QTX[0] >> (bit_depth - 8);
1528   features[feature_index++] = (float)(dc_q * dc_q) / 256.0f;
1529   assert(feature_index == FEATURES);
1530 
1531   // Write features to file
1532   write_features_to_file(cpi->oxcf.partition_info_path,
1533                          cpi->ext_part_controller.test_mode, features, FEATURES,
1534                          2, bsize, mi_row, mi_col);
1535 
1536   if (ext_ml_model_decision_after_none(&cpi->ext_part_controller,
1537                                        frame_is_intra_only(&cpi->common),
1538                                        features, &part_state->do_square_split,
1539                                        &part_state->do_rectangular_split)) {
1540     return;
1541   }
1542 
1543   // Calculate score using the NN model.
1544   float score = 0.0f;
1545   av1_nn_predict(features, nn_config, 1, &score);
1546 
1547   // Make decision.
1548   if ((int)(score * 100) >= thresh) {
1549     part_state->do_square_split = 0;
1550     part_state->do_rectangular_split = 0;
1551   }
1552 }
1553 #undef FEATURES
1554 
av1_prune_partitions_before_search(AV1_COMP * const cpi,MACROBLOCK * const x,SIMPLE_MOTION_DATA_TREE * const sms_tree,PartitionSearchState * part_state)1555 void av1_prune_partitions_before_search(AV1_COMP *const cpi,
1556                                         MACROBLOCK *const x,
1557                                         SIMPLE_MOTION_DATA_TREE *const sms_tree,
1558                                         PartitionSearchState *part_state) {
1559   const AV1_COMMON *const cm = &cpi->common;
1560   const CommonModeInfoParams *const mi_params = &cm->mi_params;
1561 
1562   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
1563   const BLOCK_SIZE bsize = blk_params->bsize;
1564 
1565 #if CONFIG_THREE_PASS
1566   if (cpi->third_pass_ctx) {
1567     int mi_row = blk_params->mi_row;
1568     int mi_col = blk_params->mi_col;
1569     double ratio_h, ratio_w;
1570     av1_get_third_pass_ratio(cpi->third_pass_ctx, 0, cm->height, cm->width,
1571                              &ratio_h, &ratio_w);
1572     THIRD_PASS_MI_INFO *this_mi = av1_get_third_pass_mi(
1573         cpi->third_pass_ctx, 0, mi_row, mi_col, ratio_h, ratio_w);
1574     BLOCK_SIZE third_pass_bsize =
1575         av1_get_third_pass_adjusted_blk_size(this_mi, ratio_h, ratio_w);
1576     // check the actual partition of this block in the second pass
1577     PARTITION_TYPE third_pass_part =
1578         av1_third_pass_get_sb_part_type(cpi->third_pass_ctx, this_mi);
1579 
1580     int is_edge = (mi_row + mi_size_high[bsize] >= cm->mi_params.mi_rows) ||
1581                   (mi_col + mi_size_wide[bsize] >= cm->mi_params.mi_cols);
1582 
1583     if (!is_edge && block_size_wide[bsize] >= 16) {
1584       // If in second pass we used rectangular partition, then do not search for
1585       // rectangular partition in the different direction.
1586       if (third_pass_part != PARTITION_NONE) {
1587         if (third_pass_part == PARTITION_HORZ ||
1588             third_pass_part == PARTITION_HORZ_4 ||
1589             third_pass_part == PARTITION_HORZ_A ||
1590             third_pass_part == PARTITION_HORZ_B) {
1591           part_state->partition_rect_allowed[VERT] = 0;
1592         } else if (third_pass_part == PARTITION_VERT ||
1593                    third_pass_part == PARTITION_VERT_4 ||
1594                    third_pass_part == PARTITION_VERT_A ||
1595                    third_pass_part == PARTITION_VERT_B) {
1596           part_state->partition_rect_allowed[HORZ] = 0;
1597         }
1598       }
1599 
1600       int minSize = AOMMIN(block_size_wide[third_pass_bsize],
1601                            block_size_high[third_pass_bsize]);
1602       int maxSize = AOMMAX(block_size_wide[third_pass_bsize],
1603                            block_size_high[third_pass_bsize]);
1604       if (block_size_wide[bsize] < minSize / 4) {
1605         // Current partition is too small, just terminate
1606         part_state->terminate_partition_search = 1;
1607         return;
1608       } else if (block_size_wide[bsize] < minSize / 2) {
1609         if (third_pass_part != PARTITION_NONE) {
1610           // Current partition is very small, and in second pass we used
1611           // rectangular partition. Terminate the search here then.
1612           part_state->terminate_partition_search = 1;
1613           return;
1614         } else {
1615           // Partition is small, but we still check this partition, only disable
1616           // further splits.
1617           // TODO(any): check why this is not covered by the termination for <
1618           // minSize/4.
1619           av1_disable_square_split_partition(part_state);
1620           av1_disable_rect_partitions(part_state);
1621           return;
1622         }
1623       } else if (block_size_wide[bsize] > maxSize) {
1624         // Partition is larger than in the second pass. Only allow split.
1625         av1_set_square_split_only(part_state);
1626         return;
1627       } else if (block_size_wide[bsize] >= minSize &&
1628                  block_size_wide[bsize] <= maxSize) {
1629         // Partition is within a range where it is very likely to find a good
1630         // choice, so do not prune anything.
1631         return;
1632       }
1633     }
1634   }
1635 #endif  // CONFIG_THREE_PASS
1636 
1637   // Prune rectangular partitions for larger blocks.
1638   if (bsize > cpi->sf.part_sf.rect_partition_eval_thresh) {
1639     part_state->do_rectangular_split = 0;
1640     part_state->partition_rect_allowed[HORZ] = 0;
1641     part_state->partition_rect_allowed[VERT] = 0;
1642   }
1643 
1644   // Prune rectangular, AB and 4-way partition based on q index and block size
1645   if (cpi->sf.part_sf.prune_rectangular_split_based_on_qidx == 1) {
1646     if (bsize == BLOCK_8X8 && x->qindex < 35)
1647       av1_disable_rect_partitions(part_state);
1648 
1649   } else if (cpi->sf.part_sf.prune_rectangular_split_based_on_qidx == 2) {
1650     // Enumeration difference between two square partitions
1651     const int sqr_bsize_step = BLOCK_32X32 - BLOCK_16X16;
1652     int max_bsize =
1653         BLOCK_32X32 - (x->qindex * 3 / QINDEX_RANGE) * sqr_bsize_step;
1654     max_bsize = AOMMAX(max_bsize, BLOCK_4X4);
1655     const BLOCK_SIZE max_prune_bsize =
1656         (BLOCK_SIZE)AOMMIN(max_bsize, BLOCK_32X32);
1657 
1658     // Prune partition
1659     // qidx 0 to 85: prune bsize below BLOCK_32X32
1660     // qidx 86 to 170: prune bsize below BLOCK_16X16
1661     // qidx 171 to 255: prune bsize below BLOCK_8X8
1662     if (bsize < max_prune_bsize) {
1663       av1_disable_rect_partitions(part_state);
1664     }
1665   }
1666 
1667   if (cpi->sf.part_sf.prune_sub_8x8_partition_level && (bsize == BLOCK_8X8)) {
1668     const MACROBLOCKD *const xd = &x->e_mbd;
1669     int prune_sub_8x8;
1670     if (cpi->sf.part_sf.prune_sub_8x8_partition_level == 2) {
1671       prune_sub_8x8 = 1;
1672     } else {
1673       assert(cpi->sf.part_sf.prune_sub_8x8_partition_level == 1);
1674       // Prune if both neighbors are available and either is > BLOCK_8X8
1675       prune_sub_8x8 = xd->left_available && xd->up_available &&
1676                       (xd->left_mbmi->bsize > BLOCK_8X8 ||
1677                        xd->above_mbmi->bsize > BLOCK_8X8);
1678     }
1679     if (prune_sub_8x8) {
1680       av1_disable_all_splits(part_state);
1681     }
1682   }
1683 
1684   // A CNN-based speed feature pruning out either split or all non-split
1685   // partition in INTRA frame coding.
1686   const int try_intra_cnn_based_part_prune =
1687       frame_is_intra_only(cm) &&
1688       cpi->sf.part_sf.intra_cnn_based_part_prune_level &&
1689       cm->seq_params->sb_size >= BLOCK_64X64 && bsize <= BLOCK_64X64 &&
1690       blk_params->bsize_at_least_8x8 &&
1691       av1_is_whole_blk_in_frame(blk_params, mi_params);
1692 
1693   if (try_intra_cnn_based_part_prune) {
1694     intra_mode_cnn_partition(&cpi->common, x, x->part_search_info.quad_tree_idx,
1695                              cpi->sf.part_sf.intra_cnn_based_part_prune_level,
1696                              part_state);
1697   }
1698 
1699   // Use simple motion search to prune out split or non-split partitions. This
1700   // must be done prior to PARTITION_SPLIT to propagate the initial mvs to a
1701   // smaller blocksize.
1702   const int try_split_only =
1703       cpi->sf.part_sf.simple_motion_search_split &&
1704       part_state->do_square_split && blk_params->bsize_at_least_8x8 &&
1705       av1_is_whole_blk_in_frame(blk_params, mi_params) &&
1706       !frame_is_intra_only(cm) && !av1_superres_scaled(cm);
1707 
1708   if (try_split_only) {
1709     simple_motion_search_based_split(cpi, x, sms_tree, part_state);
1710   }
1711 
1712   // Use simple motion search to prune out rectangular partition in some
1713   // direction. The results are stored in prune_horz and prune_vert in order to
1714   // bypass future related pruning checks if a pruning decision has been made.
1715 
1716   // We want to search at least one partition mode, so don't prune if NONE and
1717   // SPLIT are disabled.
1718   const int non_rect_part_allowed =
1719       part_state->do_square_split || part_state->partition_none_allowed;
1720   // Only run the model if the partitions are not already pruned.
1721   const int rect_part_allowed = part_state->do_rectangular_split &&
1722                                 ((part_state->partition_rect_allowed[HORZ] &&
1723                                   !part_state->prune_rect_part[HORZ]) ||
1724                                  (part_state->partition_rect_allowed[VERT] &&
1725                                   !part_state->prune_rect_part[VERT]));
1726 
1727   const int try_prune_rect = cpi->sf.part_sf.simple_motion_search_prune_rect &&
1728                              !frame_is_intra_only(cm) &&
1729                              non_rect_part_allowed && rect_part_allowed &&
1730                              !av1_superres_scaled(cm);
1731 
1732   if (try_prune_rect) {
1733     simple_motion_search_prune_rect(cpi, x, sms_tree, part_state);
1734   }
1735 }
1736 
1737 #ifndef NDEBUG
is_bsize_square(BLOCK_SIZE bsize)1738 static inline int is_bsize_square(BLOCK_SIZE bsize) {
1739   return block_size_wide[bsize] == block_size_high[bsize];
1740 }
1741 #endif  // NDEBUG
1742 
av1_prune_partitions_by_max_min_bsize(SuperBlockEnc * sb_enc,PartitionSearchState * part_state)1743 void av1_prune_partitions_by_max_min_bsize(SuperBlockEnc *sb_enc,
1744                                            PartitionSearchState *part_state) {
1745   assert(is_bsize_square(sb_enc->max_partition_size));
1746   assert(is_bsize_square(sb_enc->min_partition_size));
1747   assert(sb_enc->min_partition_size <= sb_enc->max_partition_size);
1748   const PartitionBlkParams *blk_params = &part_state->part_blk_params;
1749   const BLOCK_SIZE bsize = blk_params->bsize;
1750   assert(is_bsize_square(bsize));
1751   const int max_partition_size_1d = block_size_wide[sb_enc->max_partition_size];
1752   const int min_partition_size_1d = block_size_wide[sb_enc->min_partition_size];
1753   const int bsize_1d = block_size_wide[bsize];
1754   assert(min_partition_size_1d <= max_partition_size_1d);
1755   const int is_le_min_sq_part = bsize_1d <= min_partition_size_1d;
1756   const int is_gt_max_sq_part = bsize_1d > max_partition_size_1d;
1757   if (is_gt_max_sq_part) {
1758     // If current block size is larger than max, only allow split.
1759     av1_set_square_split_only(part_state);
1760   } else if (is_le_min_sq_part) {
1761     // If current block size is less or equal to min, only allow none if valid
1762     // block large enough; only allow split otherwise.
1763     av1_disable_rect_partitions(part_state);
1764 
1765     // only disable square split when current block is not at the picture
1766     // boundary. otherwise, inherit the square split flag from previous logic
1767     if (av1_blk_has_rows_and_cols(blk_params)) {
1768       part_state->do_square_split = 0;
1769     }
1770     part_state->partition_none_allowed = !(part_state->do_square_split);
1771   }
1772 }
1773 
1774 // Decide whether to evaluate the AB partition specified by part_type based on
1775 // split and HORZ/VERT info
evaluate_ab_partition_based_on_split(const PC_TREE * pc_tree,PARTITION_TYPE rect_part,const RD_RECT_PART_WIN_INFO * rect_part_win_info,int qindex,int split_idx1,int split_idx2)1776 static int evaluate_ab_partition_based_on_split(
1777     const PC_TREE *pc_tree, PARTITION_TYPE rect_part,
1778     const RD_RECT_PART_WIN_INFO *rect_part_win_info, int qindex, int split_idx1,
1779     int split_idx2) {
1780   int num_win = 0;
1781   // Threshold for number of winners
1782   // Conservative pruning for high quantizers
1783   const int num_win_thresh = AOMMIN(3 * (2 * (MAXQ - qindex) / MAXQ), 3);
1784   int sub_part_win =
1785       (rect_part_win_info == NULL)    ? (pc_tree->partitioning == rect_part)
1786       : (rect_part == PARTITION_HORZ) ? rect_part_win_info->rect_part_win[HORZ]
1787                                       : rect_part_win_info->rect_part_win[VERT];
1788   num_win += (sub_part_win) ? 1 : 0;
1789   if (pc_tree->split[split_idx1]) {
1790     num_win +=
1791         (pc_tree->split[split_idx1]->partitioning == PARTITION_NONE) ? 1 : 0;
1792   } else {
1793     num_win += 1;
1794   }
1795   if (pc_tree->split[split_idx2]) {
1796     num_win +=
1797         (pc_tree->split[split_idx2]->partitioning == PARTITION_NONE) ? 1 : 0;
1798   } else {
1799     num_win += 1;
1800   }
1801   if (num_win < num_win_thresh) {
1802     return 0;
1803   }
1804   return 1;
1805 }
1806 
av1_prune_ab_partitions(AV1_COMP * cpi,const MACROBLOCK * x,const PC_TREE * pc_tree,int pb_source_variance,int64_t best_rdcost,const RD_RECT_PART_WIN_INFO * rect_part_win_info,bool ext_partition_allowed,PartitionSearchState * part_state,int * ab_partitions_allowed)1807 void av1_prune_ab_partitions(AV1_COMP *cpi, const MACROBLOCK *x,
1808                              const PC_TREE *pc_tree, int pb_source_variance,
1809                              int64_t best_rdcost,
1810                              const RD_RECT_PART_WIN_INFO *rect_part_win_info,
1811                              bool ext_partition_allowed,
1812                              PartitionSearchState *part_state,
1813                              int *ab_partitions_allowed) {
1814   int64_t *horz_rd = part_state->rect_part_rd[HORZ];
1815   int64_t *vert_rd = part_state->rect_part_rd[VERT];
1816   int64_t *split_rd = part_state->split_rd;
1817   const PartitionCfg *const part_cfg = &cpi->oxcf.part_cfg;
1818   // The standard AB partitions are allowed initially if ext-partition-types are
1819   // allowed.
1820   int horzab_partition_allowed = ext_partition_allowed &&
1821                                  part_cfg->enable_ab_partitions &&
1822                                  part_state->partition_rect_allowed[HORZ];
1823   int vertab_partition_allowed = ext_partition_allowed &&
1824                                  part_cfg->enable_ab_partitions &&
1825                                  part_state->partition_rect_allowed[VERT];
1826 
1827   // Pruning: pruning out AB partitions on one main direction based on the
1828   // current best partition and source variance.
1829   if (cpi->sf.part_sf.prune_ext_partition_types_search_level) {
1830     if (cpi->sf.part_sf.prune_ext_partition_types_search_level == 1) {
1831       // TODO(debargha,[email protected]): may need to tune the threshold for
1832       // pb_source_variance.
1833       horzab_partition_allowed &= (pc_tree->partitioning == PARTITION_HORZ ||
1834                                    (pc_tree->partitioning == PARTITION_NONE &&
1835                                     pb_source_variance < 32) ||
1836                                    pc_tree->partitioning == PARTITION_SPLIT);
1837       vertab_partition_allowed &= (pc_tree->partitioning == PARTITION_VERT ||
1838                                    (pc_tree->partitioning == PARTITION_NONE &&
1839                                     pb_source_variance < 32) ||
1840                                    pc_tree->partitioning == PARTITION_SPLIT);
1841     } else {
1842       horzab_partition_allowed &= (pc_tree->partitioning == PARTITION_HORZ ||
1843                                    pc_tree->partitioning == PARTITION_SPLIT);
1844       vertab_partition_allowed &= (pc_tree->partitioning == PARTITION_VERT ||
1845                                    pc_tree->partitioning == PARTITION_SPLIT);
1846     }
1847     horz_rd[0] = (horz_rd[0] < INT64_MAX ? horz_rd[0] : 0);
1848     horz_rd[1] = (horz_rd[1] < INT64_MAX ? horz_rd[1] : 0);
1849     vert_rd[0] = (vert_rd[0] < INT64_MAX ? vert_rd[0] : 0);
1850     vert_rd[1] = (vert_rd[1] < INT64_MAX ? vert_rd[1] : 0);
1851     split_rd[0] = (split_rd[0] < INT64_MAX ? split_rd[0] : 0);
1852     split_rd[1] = (split_rd[1] < INT64_MAX ? split_rd[1] : 0);
1853     split_rd[2] = (split_rd[2] < INT64_MAX ? split_rd[2] : 0);
1854     split_rd[3] = (split_rd[3] < INT64_MAX ? split_rd[3] : 0);
1855   }
1856 
1857   // Pruning: pruning out horz_a or horz_b if the combined rdcost of its
1858   // subblocks estimated from previous partitions is much higher than the best
1859   // rd so far.
1860   ab_partitions_allowed[HORZ_A] = horzab_partition_allowed;
1861   ab_partitions_allowed[HORZ_B] = horzab_partition_allowed;
1862   if (cpi->sf.part_sf.prune_ext_partition_types_search_level) {
1863     const int64_t horz_a_rd = horz_rd[1] + split_rd[0] + split_rd[1];
1864     const int64_t horz_b_rd = horz_rd[0] + split_rd[2] + split_rd[3];
1865     switch (cpi->sf.part_sf.prune_ext_partition_types_search_level) {
1866       case 1:
1867         ab_partitions_allowed[HORZ_A] &= (horz_a_rd / 16 * 14 < best_rdcost);
1868         ab_partitions_allowed[HORZ_B] &= (horz_b_rd / 16 * 14 < best_rdcost);
1869         break;
1870       case 2:
1871       default:
1872         ab_partitions_allowed[HORZ_A] &= (horz_a_rd / 16 * 15 < best_rdcost);
1873         ab_partitions_allowed[HORZ_B] &= (horz_b_rd / 16 * 15 < best_rdcost);
1874         break;
1875     }
1876   }
1877 
1878   // Pruning: pruning out vert_a or vert_b if the combined rdcost of its
1879   // subblocks estimated from previous partitions is much higher than the best
1880   // rd so far.
1881   ab_partitions_allowed[VERT_A] = vertab_partition_allowed;
1882   ab_partitions_allowed[VERT_B] = vertab_partition_allowed;
1883   if (cpi->sf.part_sf.prune_ext_partition_types_search_level) {
1884     const int64_t vert_a_rd = vert_rd[1] + split_rd[0] + split_rd[2];
1885     const int64_t vert_b_rd = vert_rd[0] + split_rd[1] + split_rd[3];
1886     switch (cpi->sf.part_sf.prune_ext_partition_types_search_level) {
1887       case 1:
1888         ab_partitions_allowed[VERT_A] &= (vert_a_rd / 16 * 14 < best_rdcost);
1889         ab_partitions_allowed[VERT_B] &= (vert_b_rd / 16 * 14 < best_rdcost);
1890         break;
1891       case 2:
1892       default:
1893         ab_partitions_allowed[VERT_A] &= (vert_a_rd / 16 * 15 < best_rdcost);
1894         ab_partitions_allowed[VERT_B] &= (vert_b_rd / 16 * 15 < best_rdcost);
1895         break;
1896     }
1897   }
1898 
1899   // Pruning: pruning out some ab partitions using a DNN taking rd costs of
1900   // sub-blocks from previous basic partition types.
1901   if (cpi->sf.part_sf.ml_prune_partition && ext_partition_allowed &&
1902       part_state->partition_rect_allowed[HORZ] &&
1903       part_state->partition_rect_allowed[VERT]) {
1904     // TODO([email protected]): x->source_variance may not be the current
1905     // block's variance. The correct one to use is pb_source_variance. Need to
1906     // re-train the model to fix it.
1907     ml_prune_ab_partition(cpi, pc_tree->partitioning,
1908                           get_unsigned_bits(x->source_variance), best_rdcost,
1909                           part_state, ab_partitions_allowed);
1910   }
1911 
1912   // Pruning: pruning AB partitions based on the number of horz/vert wins
1913   // in the current block and sub-blocks in PARTITION_SPLIT.
1914   if (cpi->sf.part_sf.prune_ext_part_using_split_info >= 2 &&
1915       ab_partitions_allowed[HORZ_A]) {
1916     ab_partitions_allowed[HORZ_A] &= evaluate_ab_partition_based_on_split(
1917         pc_tree, PARTITION_HORZ, rect_part_win_info, x->qindex, 0, 1);
1918   }
1919   if (cpi->sf.part_sf.prune_ext_part_using_split_info >= 2 &&
1920       ab_partitions_allowed[HORZ_B]) {
1921     ab_partitions_allowed[HORZ_B] &= evaluate_ab_partition_based_on_split(
1922         pc_tree, PARTITION_HORZ, rect_part_win_info, x->qindex, 2, 3);
1923   }
1924   if (cpi->sf.part_sf.prune_ext_part_using_split_info >= 2 &&
1925       ab_partitions_allowed[VERT_A]) {
1926     ab_partitions_allowed[VERT_A] &= evaluate_ab_partition_based_on_split(
1927         pc_tree, PARTITION_VERT, rect_part_win_info, x->qindex, 0, 2);
1928   }
1929   if (cpi->sf.part_sf.prune_ext_part_using_split_info >= 2 &&
1930       ab_partitions_allowed[VERT_B]) {
1931     ab_partitions_allowed[VERT_B] &= evaluate_ab_partition_based_on_split(
1932         pc_tree, PARTITION_VERT, rect_part_win_info, x->qindex, 1, 3);
1933   }
1934 }
1935 
1936 // Prepare features for the external model. Specifically, features after
1937 // ab partition is searched.
prepare_features_after_part_ab(const AV1_COMP * const cpi,MACROBLOCK * const x,BLOCK_SIZE bsize,int part_ctx,int64_t best_rd,int64_t rect_part_rd[NUM_RECT_PARTS][SUB_PARTITIONS_RECT],int64_t split_rd[SUB_PARTITIONS_SPLIT],unsigned int pb_source_variance,int mi_row,int mi_col,aom_partition_features_t * const features)1938 static void prepare_features_after_part_ab(
1939     const AV1_COMP *const cpi, MACROBLOCK *const x, BLOCK_SIZE bsize,
1940     int part_ctx, int64_t best_rd,
1941     int64_t rect_part_rd[NUM_RECT_PARTS][SUB_PARTITIONS_RECT],
1942     int64_t split_rd[SUB_PARTITIONS_SPLIT], unsigned int pb_source_variance,
1943     int mi_row, int mi_col, aom_partition_features_t *const features) {
1944   int64_t *horz_rd = rect_part_rd[HORZ];
1945   int64_t *vert_rd = rect_part_rd[VERT];
1946 
1947   // Generate features.
1948   int feature_index = 0;
1949   features->after_part_ab.f[feature_index++] = (float)part_ctx;
1950   features->after_part_ab.f[feature_index++] =
1951       (float)get_unsigned_bits(pb_source_variance);
1952 
1953   const int rdcost = (int)AOMMIN(INT_MAX, best_rd);
1954   int sub_block_rdcost[8] = { 0 };
1955   int rd_index = 0;
1956   for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1957     if (horz_rd[i] > 0 && horz_rd[i] < 1000000000)
1958       sub_block_rdcost[rd_index] = (int)horz_rd[i];
1959     ++rd_index;
1960   }
1961   for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1962     if (vert_rd[i] > 0 && vert_rd[i] < 1000000000)
1963       sub_block_rdcost[rd_index] = (int)vert_rd[i];
1964     ++rd_index;
1965   }
1966   for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
1967     if (split_rd[i] > 0 && split_rd[i] < 1000000000)
1968       sub_block_rdcost[rd_index] = (int)split_rd[i];
1969     ++rd_index;
1970   }
1971   for (int i = 0; i < 8; ++i) {
1972     // Ratio between the sub-block RD and the whole-block RD.
1973     float rd_ratio = 1.0f;
1974     if (sub_block_rdcost[i] > 0 && sub_block_rdcost[i] < rdcost)
1975       rd_ratio = (float)sub_block_rdcost[i] / (float)rdcost;
1976     features->after_part_ab.f[feature_index++] = rd_ratio;
1977   }
1978 
1979   // 4-way partitions are only allowed for these three square block sizes.
1980   assert(bsize == BLOCK_16X16 || bsize == BLOCK_32X32 || bsize == BLOCK_64X64);
1981 
1982   // Get variance of the 1:4 and 4:1 sub-blocks.
1983   unsigned int horz_4_source_var[SUB_PARTITIONS_PART4] = { 0 };
1984   unsigned int vert_4_source_var[SUB_PARTITIONS_PART4] = { 0 };
1985   {
1986     BLOCK_SIZE horz_4_bs = get_partition_subsize(bsize, PARTITION_HORZ_4);
1987     BLOCK_SIZE vert_4_bs = get_partition_subsize(bsize, PARTITION_VERT_4);
1988 
1989     assert(horz_4_bs != BLOCK_INVALID);
1990     assert(vert_4_bs != BLOCK_INVALID);
1991 
1992     av1_setup_src_planes(x, cpi->source, mi_row, mi_col,
1993                          av1_num_planes(&cpi->common), bsize);
1994     const int src_stride = x->plane[0].src.stride;
1995     uint8_t *src = x->plane[0].src.buf;
1996     const MACROBLOCKD *const xd = &x->e_mbd;
1997 
1998     struct buf_2d horz_4_src, vert_4_src;
1999     horz_4_src.stride = src_stride;
2000     vert_4_src.stride = src_stride;
2001 
2002     for (int i = 0; i < SUB_PARTITIONS_PART4; ++i) {
2003       horz_4_src.buf = src + i * block_size_high[horz_4_bs] * src_stride;
2004       vert_4_src.buf = src + i * block_size_wide[vert_4_bs];
2005 
2006       horz_4_source_var[i] = av1_get_perpixel_variance_facade(
2007           cpi, xd, &horz_4_src, horz_4_bs, AOM_PLANE_Y);
2008       vert_4_source_var[i] = av1_get_perpixel_variance_facade(
2009           cpi, xd, &vert_4_src, vert_4_bs, AOM_PLANE_Y);
2010     }
2011   }
2012 
2013   const float denom = (float)(pb_source_variance + 1);
2014   const float low_b = 0.1f;
2015   const float high_b = 10.0f;
2016   for (int i = 0; i < SUB_PARTITIONS_PART4; ++i) {
2017     // Ratio between the 4:1 sub-block variance and the whole-block variance.
2018     float var_ratio = (float)(horz_4_source_var[i] + 1) / denom;
2019     if (var_ratio < low_b) var_ratio = low_b;
2020     if (var_ratio > high_b) var_ratio = high_b;
2021     features->after_part_ab.f[feature_index++] = var_ratio;
2022   }
2023   for (int i = 0; i < SUB_PARTITIONS_PART4; ++i) {
2024     // Ratio between the 1:4 sub-block RD and the whole-block RD.
2025     float var_ratio = (float)(vert_4_source_var[i] + 1) / denom;
2026     if (var_ratio < low_b) var_ratio = low_b;
2027     if (var_ratio > high_b) var_ratio = high_b;
2028     features->after_part_ab.f[feature_index++] = var_ratio;
2029   }
2030   assert(feature_index == 18);
2031 }
2032 
2033 // If the external partition model is used, we let it determine partition
2034 // decisions before partition none. Specifically, these parameters:
2035 // partition_none_allowed
2036 // partition_horz_allowed
2037 // partition_vert_allowed
2038 // do_rectangular_split
2039 // do_square_split
ext_ml_model_decision_before_none(AV1_COMP * cpi,const float features_from_motion[FEATURE_SIZE_SMS_SPLIT],int * partition_none_allowed,int * partition_horz_allowed,int * partition_vert_allowed,int * do_rectangular_split,int * do_square_split)2040 static bool ext_ml_model_decision_before_none(
2041     AV1_COMP *cpi, const float features_from_motion[FEATURE_SIZE_SMS_SPLIT],
2042     int *partition_none_allowed, int *partition_horz_allowed,
2043     int *partition_vert_allowed, int *do_rectangular_split,
2044     int *do_square_split) {
2045   ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
2046   if (!ext_part_controller->ready) return false;
2047 
2048   // Setup features.
2049   aom_partition_features_t features;
2050   features.id = AOM_EXT_PART_FEATURE_BEFORE_NONE;
2051   for (int i = 0; i < FEATURE_SIZE_SMS_SPLIT; ++i) {
2052     features.before_part_none.f[i] = features_from_motion[i];
2053   }
2054 
2055   // Send necessary features to the external model.
2056   av1_ext_part_send_features(ext_part_controller, &features);
2057 
2058   // Get partition decisions from the external model.
2059   aom_partition_decision_t decision;
2060   const bool valid_decision =
2061       av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2062   if (!valid_decision) return false;
2063 
2064   // Populate decisions
2065   *partition_none_allowed = decision.partition_none_allowed;
2066   *partition_horz_allowed = decision.partition_rect_allowed[HORZ];
2067   *partition_vert_allowed = decision.partition_rect_allowed[VERT];
2068   *do_rectangular_split = decision.do_rectangular_split;
2069   *do_square_split = decision.do_square_split;
2070 
2071   return true;
2072 }
2073 
2074 // If the external partition model is used, we let it determine partition
2075 // decisions before partition none. Specifically, these parameters:
2076 // prune_horz
2077 // prune_vert
ext_ml_model_decision_before_none_part2(AV1_COMP * cpi,const float features_from_motion[FEATURE_SIZE_SMS_PRUNE_PART],int * prune_horz,int * prune_vert)2078 static bool ext_ml_model_decision_before_none_part2(
2079     AV1_COMP *cpi,
2080     const float features_from_motion[FEATURE_SIZE_SMS_PRUNE_PART],
2081     int *prune_horz, int *prune_vert) {
2082   ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
2083   if (!ext_part_controller->ready) return false;
2084 
2085   // Setup features.
2086   aom_partition_features_t features;
2087   features.id = AOM_EXT_PART_FEATURE_BEFORE_NONE_PART2;
2088   for (int i = 0; i < FEATURE_SIZE_SMS_PRUNE_PART; ++i) {
2089     features.before_part_none.f_part2[i] = features_from_motion[i];
2090   }
2091 
2092   // Send necessary features to the external model.
2093   av1_ext_part_send_features(ext_part_controller, &features);
2094 
2095   // Get partition decisions from the external model.
2096   aom_partition_decision_t decision;
2097   const bool valid_decision =
2098       av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2099   if (!valid_decision) return false;
2100 
2101   // Populate decisions
2102   *prune_horz = decision.prune_rect_part[HORZ];
2103   *prune_vert = decision.prune_rect_part[VERT];
2104 
2105   return true;
2106 }
2107 
2108 // If the external partition model is used, we let it determine partition
2109 // decisions after none partition. Specifically, these parameters:
2110 // do_square_split
2111 // do_rectangular_split
ext_ml_model_decision_after_none(ExtPartController * const ext_part_controller,const int is_intra_frame,const float * const features_after_none,int * do_square_split,int * do_rectangular_split)2112 bool ext_ml_model_decision_after_none(
2113     ExtPartController *const ext_part_controller, const int is_intra_frame,
2114     const float *const features_after_none, int *do_square_split,
2115     int *do_rectangular_split) {
2116   if (!ext_part_controller->ready || is_intra_frame) return false;
2117 
2118   // Setup features.
2119   aom_partition_features_t features;
2120   features.id = AOM_EXT_PART_FEATURE_AFTER_NONE;
2121   for (int i = 0; i < 4; ++i) {
2122     features.after_part_none.f[i] = features_after_none[i];
2123   }
2124 
2125   // Send necessary features to the external model.
2126   av1_ext_part_send_features(ext_part_controller, &features);
2127 
2128   // Get partition decisions from the external model.
2129   aom_partition_decision_t decision;
2130   const bool valid_decision =
2131       av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2132   if (!valid_decision) return false;
2133 
2134   // Populate decisions
2135   *do_square_split = decision.do_square_split;
2136   *do_rectangular_split = decision.do_rectangular_split;
2137 
2138   return true;
2139 }
2140 
2141 // If the external partition model is used, we let it determine partition
2142 // decisions after none partition. Specifically, these parameters:
2143 // terminate_partition_search
ext_ml_model_decision_after_none_part2(AV1_COMP * const cpi,const float * const features_terminate,int * terminate_partition_search)2144 bool ext_ml_model_decision_after_none_part2(
2145     AV1_COMP *const cpi, const float *const features_terminate,
2146     int *terminate_partition_search) {
2147   AV1_COMMON *const cm = &cpi->common;
2148   ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
2149   if (!ext_part_controller->ready || frame_is_intra_only(cm)) return false;
2150 
2151   // Setup features.
2152   aom_partition_features_t features;
2153   features.id = AOM_EXT_PART_FEATURE_AFTER_NONE_PART2;
2154   for (int i = 0; i < FEATURE_SIZE_SMS_TERM_NONE; ++i) {
2155     features.after_part_none.f_terminate[i] = features_terminate[i];
2156   }
2157 
2158   // Send necessary features to the external model.
2159   av1_ext_part_send_features(ext_part_controller, &features);
2160 
2161   // Get partition decisions from the external model.
2162   aom_partition_decision_t decision;
2163   const bool valid_decision =
2164       av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2165   if (!valid_decision) return false;
2166 
2167   // Populate decisions
2168   *terminate_partition_search = decision.terminate_partition_search;
2169 
2170   return true;
2171 }
2172 
2173 // If the external partition model is used, we let it determine partition
2174 // decisions after none partition. Specifically, these parameters:
2175 // terminate_partition_search
ext_ml_model_decision_after_split(AV1_COMP * const cpi,const float * const features_terminate,int * terminate_partition_search)2176 bool ext_ml_model_decision_after_split(AV1_COMP *const cpi,
2177                                        const float *const features_terminate,
2178                                        int *terminate_partition_search) {
2179   const AV1_COMMON *const cm = &cpi->common;
2180   ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
2181   if (frame_is_intra_only(cm) || !cpi->ext_part_controller.ready) {
2182     return false;
2183   }
2184 
2185   // Setup features.
2186   aom_partition_features_t features;
2187   features.id = AOM_EXT_PART_FEATURE_AFTER_SPLIT;
2188   for (int i = 0; i < 31; ++i) {
2189     features.after_part_split.f_terminate[i] = features_terminate[i];
2190   }
2191 
2192   // Send necessary features to the external model.
2193   av1_ext_part_send_features(ext_part_controller, &features);
2194 
2195   // Get partition decisions from the external model.
2196   aom_partition_decision_t decision;
2197   const bool valid_decision =
2198       av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2199   if (!valid_decision) return false;
2200 
2201   // Populate decisions
2202   *terminate_partition_search = decision.terminate_partition_search;
2203 
2204   return true;
2205 }
2206 
2207 // If the external partition model is used, we let it determine partition
2208 // decisions after none partition. Specifically, these parameters:
2209 // prune_rect_part[HORZ]
2210 // prune_rect_part[VERT]
ext_ml_model_decision_after_split_part2(ExtPartController * const ext_part_controller,const int is_intra_frame,const float * const features_prune,int * prune_rect_part_horz,int * prune_rect_part_vert)2211 bool ext_ml_model_decision_after_split_part2(
2212     ExtPartController *const ext_part_controller, const int is_intra_frame,
2213     const float *const features_prune, int *prune_rect_part_horz,
2214     int *prune_rect_part_vert) {
2215   if (is_intra_frame || !ext_part_controller->ready) {
2216     return false;
2217   }
2218 
2219   // Setup features.
2220   aom_partition_features_t features;
2221   features.id = AOM_EXT_PART_FEATURE_AFTER_SPLIT_PART2;
2222   for (int i = 0; i < 9; ++i) {
2223     features.after_part_split.f_prune_rect[i] = features_prune[i];
2224   }
2225 
2226   // Send necessary features to the external model.
2227   av1_ext_part_send_features(ext_part_controller, &features);
2228 
2229   // Get partition decisions from the external model.
2230   aom_partition_decision_t decision;
2231   const bool valid_decision =
2232       av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2233   if (!valid_decision) return false;
2234 
2235   // Populate decisions
2236   *prune_rect_part_horz = decision.prune_rect_part[0];
2237   *prune_rect_part_vert = decision.prune_rect_part[1];
2238 
2239   return true;
2240 }
2241 
2242 // If the external partition model is used, we let it determine partition
2243 // decisions after rectangular partition. Specifically, these parameters:
2244 // horza_partition_allowed
2245 // horzb_partition_allowed
2246 // verta_partition_allowed
2247 // vertb_partition_allowed
ext_ml_model_decision_after_rect(ExtPartController * const ext_part_controller,const int is_intra_frame,const float * const features_after_rect,int * horza_partition_allowed,int * horzb_partition_allowed,int * verta_partition_allowed,int * vertb_partition_allowed)2248 static bool ext_ml_model_decision_after_rect(
2249     ExtPartController *const ext_part_controller, const int is_intra_frame,
2250     const float *const features_after_rect, int *horza_partition_allowed,
2251     int *horzb_partition_allowed, int *verta_partition_allowed,
2252     int *vertb_partition_allowed) {
2253   if (is_intra_frame || !ext_part_controller->ready) return false;
2254 
2255   // Setup features.
2256   aom_partition_features_t features;
2257   features.id = AOM_EXT_PART_FEATURE_AFTER_RECT;
2258   for (int i = 0; i < 10; ++i) {
2259     features.after_part_rect.f[i] = features_after_rect[i];
2260   }
2261 
2262   // Send necessary features to the external model.
2263   av1_ext_part_send_features(ext_part_controller, &features);
2264 
2265   // Get partition decisions from the external model.
2266   aom_partition_decision_t decision;
2267   const bool valid_decision =
2268       av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2269   if (!valid_decision) return false;
2270 
2271   // Populate decisions
2272   *horza_partition_allowed = decision.horza_partition_allowed;
2273   *horzb_partition_allowed = decision.horzb_partition_allowed;
2274   *verta_partition_allowed = decision.verta_partition_allowed;
2275   *vertb_partition_allowed = decision.vertb_partition_allowed;
2276 
2277   return true;
2278 }
2279 
2280 // If the external partition model is used, we let it determine partition
2281 // decisions after AB partition. Specifically, these parameters:
2282 // partition_vert4_allowed
2283 // partition_horz4_allowed
ext_ml_model_decision_after_part_ab(AV1_COMP * const cpi,MACROBLOCK * const x,BLOCK_SIZE bsize,int part_ctx,int64_t best_rd,int64_t rect_part_rd[NUM_RECT_PARTS][SUB_PARTITIONS_RECT],int64_t split_rd[SUB_PARTITIONS_SPLIT],int * const partition_horz4_allowed,int * const partition_vert4_allowed,unsigned int pb_source_variance,int mi_row,int mi_col)2284 static bool ext_ml_model_decision_after_part_ab(
2285     AV1_COMP *const cpi, MACROBLOCK *const x, BLOCK_SIZE bsize, int part_ctx,
2286     int64_t best_rd, int64_t rect_part_rd[NUM_RECT_PARTS][SUB_PARTITIONS_RECT],
2287     int64_t split_rd[SUB_PARTITIONS_SPLIT], int *const partition_horz4_allowed,
2288     int *const partition_vert4_allowed, unsigned int pb_source_variance,
2289     int mi_row, int mi_col) {
2290   const AV1_COMMON *const cm = &cpi->common;
2291   ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
2292 
2293   if (!frame_is_intra_only(cm) && ext_part_controller->ready) {
2294     // Setup features.
2295     aom_partition_features_t features;
2296     features.id = AOM_EXT_PART_FEATURE_AFTER_AB;
2297     prepare_features_after_part_ab(cpi, x, bsize, part_ctx, best_rd,
2298                                    rect_part_rd, split_rd, pb_source_variance,
2299                                    mi_row, mi_col, &features);
2300 
2301     // Send necessary features to the external model.
2302     av1_ext_part_send_features(ext_part_controller, &features);
2303 
2304     // Get partition decisions from the external model.
2305     aom_partition_decision_t decision;
2306     const bool valid_decision =
2307         av1_ext_part_get_partition_decision(ext_part_controller, &decision);
2308     if (!valid_decision) return false;
2309 
2310     // Populate decisions
2311     *partition_horz4_allowed = decision.partition_horz4_allowed;
2312     *partition_vert4_allowed = decision.partition_vert4_allowed;
2313 
2314     return true;
2315   }
2316 
2317   return false;
2318 }
2319 
2320 // This function resembles "av1_setup_sms_tree()" in context_tree.c
2321 // with function signature change.
setup_sms_tree(AV1_COMP * const cpi,SIMPLE_MOTION_DATA_TREE * sms_tree)2322 static SIMPLE_MOTION_DATA_TREE *setup_sms_tree(
2323     AV1_COMP *const cpi, SIMPLE_MOTION_DATA_TREE *sms_tree) {
2324   AV1_COMMON *const cm = &cpi->common;
2325   const int stat_generation_stage = is_stat_generation_stage(cpi);
2326   const int is_sb_size_128 = cm->seq_params->sb_size == BLOCK_128X128;
2327   const int tree_nodes =
2328       av1_get_pc_tree_nodes(is_sb_size_128, stat_generation_stage);
2329   int sms_tree_index = 0;
2330   SIMPLE_MOTION_DATA_TREE *this_sms;
2331   int square_index = 1;
2332   int nodes;
2333   this_sms = &sms_tree[0];
2334 
2335   if (!stat_generation_stage) {
2336     const int leaf_factor = is_sb_size_128 ? 4 : 1;
2337     const int leaf_nodes = 256 * leaf_factor;
2338 
2339     // Sets up all the leaf nodes in the tree.
2340     for (sms_tree_index = 0; sms_tree_index < leaf_nodes; ++sms_tree_index) {
2341       SIMPLE_MOTION_DATA_TREE *const tree = &sms_tree[sms_tree_index];
2342       tree->block_size = square[0];
2343     }
2344 
2345     // Each node has 4 leaf nodes, fill each block_size level of the tree
2346     // from leafs to the root.
2347     for (nodes = leaf_nodes >> 2; nodes > 0; nodes >>= 2) {
2348       for (int i = 0; i < nodes; ++i) {
2349         SIMPLE_MOTION_DATA_TREE *const tree = &sms_tree[sms_tree_index];
2350         tree->block_size = square[square_index];
2351         for (int j = 0; j < 4; j++) tree->split[j] = this_sms++;
2352         ++sms_tree_index;
2353       }
2354       ++square_index;
2355     }
2356   } else {
2357     // Allocation for firstpass/LAP stage
2358     // TODO(Mufaddal): refactor square_index to use a common block_size macro
2359     // from firstpass.c
2360     SIMPLE_MOTION_DATA_TREE *const tree = &sms_tree[sms_tree_index];
2361     square_index = 2;
2362     tree->block_size = square[square_index];
2363   }
2364 
2365   // Set up the root node for the largest superblock size
2366   return &sms_tree[tree_nodes - 1];
2367 }
2368 
write_motion_feature_to_file(const char * const path,const int sb_counter,const unsigned int * block_sse,const unsigned int * block_var,const int num_blocks,const BLOCK_SIZE bsize,const BLOCK_SIZE fixed_block_size,const int mi_row,const int mi_col)2369 static void write_motion_feature_to_file(
2370     const char *const path, const int sb_counter, const unsigned int *block_sse,
2371     const unsigned int *block_var, const int num_blocks, const BLOCK_SIZE bsize,
2372     const BLOCK_SIZE fixed_block_size, const int mi_row, const int mi_col) {
2373   char filename[256];
2374   snprintf(filename, sizeof(filename), "%s/motion_search_feature_sb%d", path,
2375            sb_counter);
2376   FILE *pfile = fopen(filename, "w");
2377   fprintf(pfile, "%d,%d,%d,%d,%d\n", mi_row, mi_col, bsize,
2378           block_size_wide[fixed_block_size], num_blocks);
2379   for (int i = 0; i < num_blocks; ++i) {
2380     fprintf(pfile, "%d", block_sse[i]);
2381     if (i < num_blocks - 1) fprintf(pfile, ",");
2382   }
2383   fprintf(pfile, "\n");
2384   for (int i = 0; i < num_blocks; ++i) {
2385     fprintf(pfile, "%d", block_var[i]);
2386     if (i < num_blocks - 1) fprintf(pfile, ",");
2387   }
2388   fprintf(pfile, "\n");
2389   fclose(pfile);
2390 }
2391 
av1_collect_motion_search_features_sb(AV1_COMP * const cpi,ThreadData * td,TileDataEnc * tile_data,const int mi_row,const int mi_col,const BLOCK_SIZE bsize,aom_partition_features_t * features)2392 void av1_collect_motion_search_features_sb(AV1_COMP *const cpi, ThreadData *td,
2393                                            TileDataEnc *tile_data,
2394                                            const int mi_row, const int mi_col,
2395                                            const BLOCK_SIZE bsize,
2396                                            aom_partition_features_t *features) {
2397   const AV1_COMMON *const cm = &cpi->common;
2398   if (frame_is_intra_only(cm)) return;
2399 
2400   MACROBLOCK *const x = &td->mb;
2401   const BLOCK_SIZE fixed_block_size = BLOCK_16X16;
2402   const int col_step = mi_size_wide[fixed_block_size];
2403   const int row_step = mi_size_high[fixed_block_size];
2404   SIMPLE_MOTION_DATA_TREE *sms_tree = NULL;
2405   const int stat_generation_stage = is_stat_generation_stage(cpi);
2406   const int is_sb_size_128 = cm->seq_params->sb_size == BLOCK_128X128;
2407   const int tree_nodes =
2408       av1_get_pc_tree_nodes(is_sb_size_128, stat_generation_stage);
2409   CHECK_MEM_ERROR(cm, sms_tree, aom_calloc(tree_nodes, sizeof(*sms_tree)));
2410   SIMPLE_MOTION_DATA_TREE *sms_root = setup_sms_tree(cpi, sms_tree);
2411   TileInfo *const tile_info = &tile_data->tile_info;
2412   av1_set_offsets_without_segment_id(cpi, tile_info, x, mi_row, mi_col, bsize);
2413   av1_init_simple_motion_search_mvs_for_sb(cpi, NULL, x, sms_root, mi_row,
2414                                            mi_col);
2415   av1_reset_simple_motion_tree_partition(sms_root, bsize);
2416   const int ref_list[] = { cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME
2417                                                         : LAST_FRAME };
2418   const int mi_width =
2419       AOMMIN(mi_size_wide[bsize], cm->mi_params.mi_cols - mi_col);
2420   const int mi_height =
2421       AOMMIN(mi_size_high[bsize], cm->mi_params.mi_rows - mi_row);
2422   const int col_steps = (mi_width / col_step) + ((mi_width % col_step) > 0);
2423   const int row_steps = (mi_height / row_step) + ((mi_height % row_step) > 0);
2424   const int num_blocks = col_steps * row_steps;
2425   unsigned int *block_sse = aom_calloc(num_blocks, sizeof(*block_sse));
2426   unsigned int *block_var = aom_calloc(num_blocks, sizeof(*block_var));
2427   if (!(block_sse && block_var)) {
2428     aom_free(sms_tree);
2429     aom_free(block_sse);
2430     aom_free(block_var);
2431     aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
2432                        "Error allocating block_sse & block_var");
2433   }
2434   int idx = 0;
2435 
2436   for (int row = mi_row;
2437        row < AOMMIN(mi_row + mi_size_high[bsize], cm->mi_params.mi_rows);
2438        row += row_step) {
2439     for (int col = mi_col;
2440          col < AOMMIN(mi_col + mi_size_wide[bsize], cm->mi_params.mi_cols);
2441          col += col_step) {
2442       simple_motion_search_get_best_ref(
2443           cpi, x, sms_root, row, col, fixed_block_size, ref_list,
2444           /*num_refs=*/1, /*use_subpixel=*/1,
2445           /*save_mv=*/1, &block_sse[idx], &block_var[idx]);
2446       ++idx;
2447     }
2448   }
2449   if (features == NULL) {
2450     write_motion_feature_to_file(cpi->oxcf.partition_info_path, cpi->sb_counter,
2451                                  block_sse, block_var, idx, bsize,
2452                                  fixed_block_size, mi_row, mi_col);
2453   } else {
2454     features->sb_features.motion_features.unit_length =
2455         block_size_wide[fixed_block_size];
2456     features->sb_features.motion_features.num_units = idx;
2457     for (int i = 0; i < idx; ++i) {
2458       features->sb_features.motion_features.block_sse[i] = block_sse[i];
2459       features->sb_features.motion_features.block_var[i] = block_var[i];
2460     }
2461   }
2462 
2463   aom_free(block_sse);
2464   aom_free(block_var);
2465   aom_free(sms_tree);
2466 }
2467 
av1_prepare_motion_search_features_block(AV1_COMP * const cpi,ThreadData * td,TileDataEnc * tile_data,const int mi_row,const int mi_col,const BLOCK_SIZE bsize,const int valid_partition_types,unsigned int * block_sse,unsigned int * block_var,unsigned int sub_block_sse[4],unsigned int sub_block_var[4],unsigned int horz_block_sse[2],unsigned int horz_block_var[2],unsigned int vert_block_sse[2],unsigned int vert_block_var[2])2468 void av1_prepare_motion_search_features_block(
2469     AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
2470     const int mi_row, const int mi_col, const BLOCK_SIZE bsize,
2471     const int valid_partition_types, unsigned int *block_sse,
2472     unsigned int *block_var, unsigned int sub_block_sse[4],
2473     unsigned int sub_block_var[4], unsigned int horz_block_sse[2],
2474     unsigned int horz_block_var[2], unsigned int vert_block_sse[2],
2475     unsigned int vert_block_var[2]) {
2476   const AV1_COMMON *const cm = &cpi->common;
2477   if (frame_is_intra_only(cm)) return;
2478   MACROBLOCK *const x = &td->mb;
2479   SIMPLE_MOTION_DATA_TREE *sms_tree = NULL;
2480   const int stat_generation_stage = is_stat_generation_stage(cpi);
2481   const int is_sb_size_128 = cm->seq_params->sb_size == BLOCK_128X128;
2482   const int tree_nodes =
2483       av1_get_pc_tree_nodes(is_sb_size_128, stat_generation_stage);
2484   CHECK_MEM_ERROR(cm, sms_tree, aom_calloc(tree_nodes, sizeof(*sms_tree)));
2485   SIMPLE_MOTION_DATA_TREE *sms_root = setup_sms_tree(cpi, sms_tree);
2486   TileInfo *const tile_info = &tile_data->tile_info;
2487   av1_set_offsets_without_segment_id(cpi, tile_info, x, mi_row, mi_col, bsize);
2488   av1_reset_simple_motion_tree_partition(sms_root, bsize);
2489   const int ref_list[] = { cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME
2490                                                         : LAST_FRAME };
2491   const int sub_mi_width = mi_size_wide[bsize] / 2;
2492   const int sub_mi_height = sub_mi_width;
2493   simple_motion_search_get_best_ref(
2494       cpi, x, sms_root, mi_row, mi_col, bsize, ref_list, /*num_refs=*/1,
2495       /*use_subpixel=*/1, /*save_mv=*/1, block_sse, block_var);
2496   // Split to 4 sub blocks.
2497   if (valid_partition_types & (1 << PARTITION_SPLIT)) {
2498     const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
2499     for (int i = 0; i < 4; ++i) {
2500       const int row = mi_row + (i >> 1) * sub_mi_height;
2501       const int col = mi_col + (i & 1) * sub_mi_width;
2502       simple_motion_search_get_best_ref(cpi, x, sms_root, row, col, subsize,
2503                                         ref_list, /*num_refs=*/1,
2504                                         /*use_subpixel=*/1, /*save_mv=*/1,
2505                                         &sub_block_sse[i], &sub_block_var[i]);
2506     }
2507   }
2508   // Horizontal split
2509   if (valid_partition_types & (1 << PARTITION_HORZ)) {
2510     const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_HORZ);
2511     for (int i = 0; i < 2; ++i) {
2512       const int row = mi_row + (i & 1) * sub_mi_height;
2513       const int col = mi_col;
2514       simple_motion_search_get_best_ref(cpi, x, sms_root, row, col, subsize,
2515                                         ref_list, /*num_refs=*/1,
2516                                         /*use_subpixel=*/1, /*save_mv=*/1,
2517                                         &horz_block_sse[i], &horz_block_var[i]);
2518     }
2519   }
2520   // Vertical split
2521   if (valid_partition_types & (1 << PARTITION_VERT)) {
2522     const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_VERT);
2523     for (int i = 0; i < 2; ++i) {
2524       const int row = mi_row;
2525       const int col = mi_col + (i & 1) * sub_mi_width;
2526       simple_motion_search_get_best_ref(cpi, x, sms_root, row, col, subsize,
2527                                         ref_list, /*num_refs=*/1,
2528                                         /*use_subpixel=*/1, /*save_mv=*/1,
2529                                         &vert_block_sse[i], &vert_block_var[i]);
2530     }
2531   }
2532 
2533   aom_free(sms_tree);
2534 }
2535 #endif  // !CONFIG_REALTIME_ONLY
2536 
init_simple_motion_search_mvs(SIMPLE_MOTION_DATA_TREE * sms_tree,const FULLPEL_MV * start_mvs)2537 static inline void init_simple_motion_search_mvs(
2538     SIMPLE_MOTION_DATA_TREE *sms_tree, const FULLPEL_MV *start_mvs) {
2539   memcpy(sms_tree->start_mvs, start_mvs, sizeof(sms_tree->start_mvs));
2540   av1_zero(sms_tree->sms_none_feat);
2541   av1_zero(sms_tree->sms_rect_feat);
2542   av1_zero(sms_tree->sms_none_valid);
2543   av1_zero(sms_tree->sms_rect_valid);
2544 
2545   if (sms_tree->block_size >= BLOCK_8X8) {
2546     init_simple_motion_search_mvs(sms_tree->split[0], start_mvs);
2547     init_simple_motion_search_mvs(sms_tree->split[1], start_mvs);
2548     init_simple_motion_search_mvs(sms_tree->split[2], start_mvs);
2549     init_simple_motion_search_mvs(sms_tree->split[3], start_mvs);
2550   }
2551 }
2552 
av1_init_simple_motion_search_mvs_for_sb(const AV1_COMP * cpi,const TileInfo * tile_info,MACROBLOCK * x,SIMPLE_MOTION_DATA_TREE * sms_root,int mi_row,int mi_col)2553 void av1_init_simple_motion_search_mvs_for_sb(const AV1_COMP *cpi,
2554                                               const TileInfo *tile_info,
2555                                               MACROBLOCK *x,
2556                                               SIMPLE_MOTION_DATA_TREE *sms_root,
2557                                               int mi_row, int mi_col) {
2558   // Use the NEARESTMV of the sb as the start mv
2559   const AV1_COMMON *cm = &cpi->common;
2560   MACROBLOCKD *const xd = &x->e_mbd;
2561   FULLPEL_MV ref_mvs[REF_FRAMES];
2562   const BLOCK_SIZE sb_size = cm->seq_params->sb_size;
2563   av1_zero(ref_mvs);
2564   // If tile_info is NULL, assume that the offsets have already been set.
2565   if (tile_info) {
2566     av1_set_offsets_without_segment_id(cpi, tile_info, x, mi_row, mi_col,
2567                                        sb_size);
2568   }
2569 
2570   MB_MODE_INFO_EXT mbmi_ext;
2571   const int ref_frame =
2572       cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
2573   av1_find_mv_refs(cm, xd, xd->mi[0], ref_frame, mbmi_ext.ref_mv_count,
2574                    xd->ref_mv_stack, xd->weight, NULL, mbmi_ext.global_mvs,
2575                    mbmi_ext.mode_context);
2576   if (mbmi_ext.ref_mv_count[ref_frame] > 0) {
2577     ref_mvs[ref_frame] =
2578         get_fullmv_from_mv(&xd->ref_mv_stack[ref_frame][0].this_mv.as_mv);
2579   } else {
2580     ref_mvs[ref_frame] =
2581         get_fullmv_from_mv(&mbmi_ext.global_mvs[ref_frame].as_mv);
2582   }
2583 
2584   init_simple_motion_search_mvs(sms_root, ref_mvs);
2585 }
2586