Coverage Report

Created: 2026-04-01 07:49

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