Coverage Report

Created: 2022-08-24 06:15

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