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