Coverage Report

Created: 2026-06-10 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libavif/ext/aom/av1/encoder/partition_search.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2020, Alliance for Open Media. All rights reserved.
3
 *
4
 * This source code is subject to the terms of the BSD 2 Clause License and
5
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6
 * was not distributed with this source code in the LICENSE file, you can
7
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8
 * Media Patent License 1.0 was not distributed with this source code in the
9
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10
 */
11
12
#include <float.h>
13
#include <inttypes.h>
14
15
#include "config/aom_config.h"
16
17
#include "aom_dsp/txfm_common.h"
18
19
#include "av1/common/av1_common_int.h"
20
#include "av1/common/blockd.h"
21
#include "av1/common/enums.h"
22
#include "av1/common/reconintra.h"
23
24
#include "av1/encoder/aq_complexity.h"
25
#include "av1/encoder/aq_variance.h"
26
#include "av1/encoder/context_tree.h"
27
#include "av1/encoder/encoder.h"
28
#include "av1/encoder/encodeframe.h"
29
#include "av1/encoder/encodeframe_utils.h"
30
#include "av1/encoder/encodemv.h"
31
#include "av1/encoder/intra_mode_search_utils.h"
32
#include "av1/encoder/motion_search_facade.h"
33
#include "av1/encoder/nonrd_opt.h"
34
#include "av1/encoder/partition_search.h"
35
#include "av1/encoder/partition_strategy.h"
36
#include "av1/encoder/reconinter_enc.h"
37
#include "av1/encoder/tokenize.h"
38
#include "av1/encoder/var_based_part.h"
39
#include "av1/encoder/av1_ml_partition_models.h"
40
41
#if CONFIG_TUNE_VMAF
42
#include "av1/encoder/tune_vmaf.h"
43
#endif
44
45
#ifndef COLLECT_MOTION_SEARCH_FEATURE_SB
46
#define COLLECT_MOTION_SEARCH_FEATURE_SB CONFIG_PARTITION_SEARCH_ORDER
47
#endif
48
49
#if CONFIG_PARTITION_SEARCH_ORDER
50
void av1_reset_part_sf(PARTITION_SPEED_FEATURES *part_sf) {
51
  part_sf->partition_search_type = SEARCH_PARTITION;
52
  part_sf->less_rectangular_check_level = 0;
53
  part_sf->use_square_partition_only_threshold = BLOCK_128X128;
54
  part_sf->auto_max_partition_based_on_simple_motion = NOT_IN_USE;
55
  part_sf->default_max_partition_size = BLOCK_LARGEST;
56
  part_sf->default_min_partition_size = BLOCK_4X4;
57
  part_sf->adjust_var_based_rd_partitioning = 0;
58
  part_sf->max_intra_bsize = BLOCK_LARGEST;
59
  // This setting only takes effect when partition_search_type is set
60
  // to FIXED_PARTITION.
61
  part_sf->fixed_partition_size = BLOCK_16X16;
62
  // Recode loop tolerance %.
63
  part_sf->partition_search_breakout_dist_thr = 0;
64
  part_sf->partition_search_breakout_rate_thr = 0;
65
  part_sf->prune_ext_partition_types_search_level = 0;
66
  part_sf->prune_part4_search = 0;
67
  part_sf->ml_prune_partition = 0;
68
  part_sf->ml_early_term_after_part_split_level = 0;
69
  for (int i = 0; i < PARTITION_BLOCK_SIZES; ++i) {
70
    part_sf->ml_partition_search_breakout_thresh[i] =
71
        -1;  // -1 means not enabled.
72
  }
73
  part_sf->simple_motion_search_prune_agg = SIMPLE_AGG_LVL0;
74
  part_sf->simple_motion_search_split = 0;
75
  part_sf->simple_motion_search_prune_rect = 0;
76
  part_sf->simple_motion_search_early_term_none = 0;
77
  part_sf->simple_motion_search_reduce_search_steps = 0;
78
  part_sf->intra_cnn_based_part_prune_level = 0;
79
  part_sf->ext_partition_eval_thresh = BLOCK_8X8;
80
  part_sf->rect_partition_eval_thresh = BLOCK_128X128;
81
  part_sf->ext_part_eval_based_on_cur_best = 0;
82
  part_sf->prune_ext_part_using_split_info = 0;
83
  part_sf->prune_rectangular_split_based_on_qidx = 0;
84
  part_sf->early_term_after_none_split = 0;
85
  part_sf->ml_predict_breakout_level = 0;
86
  part_sf->prune_sub_8x8_partition_level = 0;
87
  part_sf->simple_motion_search_rect_split = 0;
88
  part_sf->reuse_prev_rd_results_for_part_ab = 0;
89
  part_sf->reuse_best_prediction_for_part_ab = 0;
90
  part_sf->use_best_rd_for_pruning = 0;
91
  part_sf->skip_non_sq_part_based_on_none = 0;
92
}
93
94
// Reset speed features that works for the baseline encoding, but
95
// blocks the external partition search.
96
void av1_reset_sf_for_ext_part(AV1_COMP *const cpi) {
97
  cpi->sf.inter_sf.prune_ref_frame_for_rect_partitions = 0;
98
}
99
#endif  // CONFIG_PARTITION_SEARCH_ORDER
100
101
#if !CONFIG_REALTIME_ONLY
102
#if COLLECT_MOTION_SEARCH_FEATURE_SB
103
// If input |features| is NULL, write tpl stats to file for each super block.
104
// Otherwise, store tpl stats to |features|.
105
// The tpl stats is computed in the unit of tpl_bsize_1d (16x16).
106
// When writing to text file:
107
// The first row contains super block position, super block size,
108
// tpl unit length, number of units in the super block.
109
// The second row contains the intra prediction cost for each unit.
110
// The third row contains the inter prediction cost for each unit.
111
// The forth row contains the motion compensated dependency cost for each unit.
112
static void collect_tpl_stats_sb(const AV1_COMP *const cpi,
113
                                 const BLOCK_SIZE bsize, const int mi_row,
114
                                 const int mi_col,
115
                                 aom_partition_features_t *features) {
116
  const AV1_COMMON *const cm = &cpi->common;
117
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
118
  if (gf_group->update_type[cpi->gf_frame_index] == INTNL_OVERLAY_UPDATE ||
119
      gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE) {
120
    return;
121
  }
122
123
  TplParams *const tpl_data = &cpi->ppi->tpl_data;
124
  TplDepFrame *tpl_frame = &tpl_data->tpl_frame[cpi->gf_frame_index];
125
  TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
126
  // If tpl stats is not established, early return
127
  if (!tpl_data->ready || gf_group->max_layer_depth_allowed == 0) {
128
    if (features != NULL) features->sb_features.tpl_features.available = 0;
129
    return;
130
  }
131
132
  const int tpl_stride = tpl_frame->stride;
133
  const int step = 1 << tpl_data->tpl_stats_block_mis_log2;
134
  const int mi_width =
135
      AOMMIN(mi_size_wide[bsize], cm->mi_params.mi_cols - mi_col);
136
  const int mi_height =
137
      AOMMIN(mi_size_high[bsize], cm->mi_params.mi_rows - mi_row);
138
  const int col_steps = (mi_width / step) + ((mi_width % step) > 0);
139
  const int row_steps = (mi_height / step) + ((mi_height % step) > 0);
140
  const int num_blocks = col_steps * row_steps;
141
142
  if (features == NULL) {
143
    char filename[256];
144
    snprintf(filename, sizeof(filename), "%s/tpl_feature_sb%d",
145
             cpi->oxcf.partition_info_path, cpi->sb_counter);
146
    FILE *pfile = fopen(filename, "w");
147
    fprintf(pfile, "%d,%d,%d,%d,%d\n", mi_row, mi_col, bsize,
148
            tpl_data->tpl_bsize_1d, num_blocks);
149
    int count = 0;
150
    for (int row = 0; row < mi_height; row += step) {
151
      for (int col = 0; col < mi_width; col += step) {
152
        TplDepStats *this_stats =
153
            &tpl_stats[av1_tpl_ptr_pos(mi_row + row, mi_col + col, tpl_stride,
154
                                       tpl_data->tpl_stats_block_mis_log2)];
155
        fprintf(pfile, "%.0f", (double)this_stats->intra_cost);
156
        if (count < num_blocks - 1) fprintf(pfile, ",");
157
        ++count;
158
      }
159
    }
160
    fprintf(pfile, "\n");
161
    count = 0;
162
    for (int row = 0; row < mi_height; row += step) {
163
      for (int col = 0; col < mi_width; col += step) {
164
        TplDepStats *this_stats =
165
            &tpl_stats[av1_tpl_ptr_pos(mi_row + row, mi_col + col, tpl_stride,
166
                                       tpl_data->tpl_stats_block_mis_log2)];
167
        fprintf(pfile, "%.0f", (double)this_stats->inter_cost);
168
        if (count < num_blocks - 1) fprintf(pfile, ",");
169
        ++count;
170
      }
171
    }
172
    fprintf(pfile, "\n");
173
    count = 0;
174
    for (int row = 0; row < mi_height; row += step) {
175
      for (int col = 0; col < mi_width; col += step) {
176
        TplDepStats *this_stats =
177
            &tpl_stats[av1_tpl_ptr_pos(mi_row + row, mi_col + col, tpl_stride,
178
                                       tpl_data->tpl_stats_block_mis_log2)];
179
        const int64_t mc_dep_delta =
180
            RDCOST(tpl_frame->base_rdmult, this_stats->mc_dep_rate,
181
                   this_stats->mc_dep_dist);
182
        fprintf(pfile, "%.0f", (double)mc_dep_delta);
183
        if (count < num_blocks - 1) fprintf(pfile, ",");
184
        ++count;
185
      }
186
    }
187
    fclose(pfile);
188
  } else {
189
    features->sb_features.tpl_features.available = 1;
190
    features->sb_features.tpl_features.tpl_unit_length = tpl_data->tpl_bsize_1d;
191
    features->sb_features.tpl_features.num_units = num_blocks;
192
    int count = 0;
193
    for (int row = 0; row < mi_height; row += step) {
194
      for (int col = 0; col < mi_width; col += step) {
195
        TplDepStats *this_stats =
196
            &tpl_stats[av1_tpl_ptr_pos(mi_row + row, mi_col + col, tpl_stride,
197
                                       tpl_data->tpl_stats_block_mis_log2)];
198
        const int64_t mc_dep_delta =
199
            RDCOST(tpl_frame->base_rdmult, this_stats->mc_dep_rate,
200
                   this_stats->mc_dep_dist);
201
        features->sb_features.tpl_features.intra_cost[count] =
202
            this_stats->intra_cost;
203
        features->sb_features.tpl_features.inter_cost[count] =
204
            this_stats->inter_cost;
205
        features->sb_features.tpl_features.mc_dep_cost[count] = mc_dep_delta;
206
        ++count;
207
      }
208
    }
209
  }
210
}
211
#endif  // COLLECT_MOTION_SEARCH_FEATURE_SB
212
#endif  // !CONFIG_REALTIME_ONLY
213
214
static void update_txfm_count(MACROBLOCK *x, MACROBLOCKD *xd,
215
                              FRAME_COUNTS *counts, TX_SIZE tx_size, int depth,
216
                              int blk_row, int blk_col,
217
458k
                              uint8_t allow_update_cdf) {
218
458k
  MB_MODE_INFO *mbmi = xd->mi[0];
219
458k
  const BLOCK_SIZE bsize = mbmi->bsize;
220
458k
  const int max_blocks_high = max_block_high(xd, bsize, 0);
221
458k
  const int max_blocks_wide = max_block_wide(xd, bsize, 0);
222
458k
  int ctx = txfm_partition_context(xd->above_txfm_context + blk_col,
223
458k
                                   xd->left_txfm_context + blk_row, mbmi->bsize,
224
458k
                                   tx_size);
225
458k
  const int txb_size_index = av1_get_txb_size_index(bsize, blk_row, blk_col);
226
458k
  const TX_SIZE plane_tx_size = mbmi->inter_tx_size[txb_size_index];
227
228
458k
  if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
229
458k
  assert(tx_size > TX_4X4);
230
231
455k
  if (depth == MAX_VARTX_DEPTH) {
232
    // Don't add to counts in this case
233
16.3k
    mbmi->tx_size = tx_size;
234
16.3k
    txfm_partition_update(xd->above_txfm_context + blk_col,
235
16.3k
                          xd->left_txfm_context + blk_row, tx_size, tx_size);
236
16.3k
    return;
237
16.3k
  }
238
239
439k
  if (tx_size == plane_tx_size) {
240
#if CONFIG_ENTROPY_STATS
241
    ++counts->txfm_partition[ctx][0];
242
#endif
243
387k
    if (allow_update_cdf)
244
387k
      update_cdf(xd->tile_ctx->txfm_partition_cdf[ctx], 0, 2);
245
387k
    mbmi->tx_size = tx_size;
246
387k
    txfm_partition_update(xd->above_txfm_context + blk_col,
247
387k
                          xd->left_txfm_context + blk_row, tx_size, tx_size);
248
387k
  } else {
249
52.0k
    const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
250
52.0k
    const int bsw = tx_size_wide_unit[sub_txs];
251
52.0k
    const int bsh = tx_size_high_unit[sub_txs];
252
253
#if CONFIG_ENTROPY_STATS
254
    ++counts->txfm_partition[ctx][1];
255
#endif
256
52.0k
    if (allow_update_cdf)
257
52.3k
      update_cdf(xd->tile_ctx->txfm_partition_cdf[ctx], 1, 2);
258
52.0k
    ++x->txfm_search_info.txb_split_count;
259
260
52.0k
    if (sub_txs == TX_4X4) {
261
9.83k
      mbmi->inter_tx_size[txb_size_index] = TX_4X4;
262
9.83k
      mbmi->tx_size = TX_4X4;
263
9.83k
      txfm_partition_update(xd->above_txfm_context + blk_col,
264
9.83k
                            xd->left_txfm_context + blk_row, TX_4X4, tx_size);
265
9.83k
      return;
266
9.83k
    }
267
268
120k
    for (int row = 0; row < tx_size_high_unit[tx_size]; row += bsh) {
269
221k
      for (int col = 0; col < tx_size_wide_unit[tx_size]; col += bsw) {
270
143k
        int offsetr = row;
271
143k
        int offsetc = col;
272
273
143k
        update_txfm_count(x, xd, counts, sub_txs, depth + 1, blk_row + offsetr,
274
143k
                          blk_col + offsetc, allow_update_cdf);
275
143k
      }
276
78.0k
    }
277
42.2k
  }
278
439k
}
279
280
static void tx_partition_count_update(const AV1_COMMON *const cm, MACROBLOCK *x,
281
                                      BLOCK_SIZE plane_bsize,
282
                                      FRAME_COUNTS *td_counts,
283
314k
                                      uint8_t allow_update_cdf) {
284
314k
  MACROBLOCKD *xd = &x->e_mbd;
285
314k
  const int mi_width = mi_size_wide[plane_bsize];
286
314k
  const int mi_height = mi_size_high[plane_bsize];
287
314k
  const TX_SIZE max_tx_size = get_vartx_max_txsize(xd, plane_bsize, 0);
288
314k
  const int bh = tx_size_high_unit[max_tx_size];
289
314k
  const int bw = tx_size_wide_unit[max_tx_size];
290
291
314k
  xd->above_txfm_context =
292
314k
      cm->above_contexts.txfm[xd->tile.tile_row] + xd->mi_col;
293
314k
  xd->left_txfm_context =
294
314k
      xd->left_txfm_context_buffer + (xd->mi_row & MAX_MIB_MASK);
295
296
628k
  for (int idy = 0; idy < mi_height; idy += bh) {
297
628k
    for (int idx = 0; idx < mi_width; idx += bw) {
298
314k
      update_txfm_count(x, xd, td_counts, max_tx_size, 0, idy, idx,
299
314k
                        allow_update_cdf);
300
314k
    }
301
314k
  }
302
314k
}
303
304
static void set_txfm_context(MACROBLOCKD *xd, TX_SIZE tx_size, int blk_row,
305
428k
                             int blk_col) {
306
428k
  MB_MODE_INFO *mbmi = xd->mi[0];
307
428k
  const BLOCK_SIZE bsize = mbmi->bsize;
308
428k
  const int max_blocks_high = max_block_high(xd, bsize, 0);
309
428k
  const int max_blocks_wide = max_block_wide(xd, bsize, 0);
310
428k
  const int txb_size_index = av1_get_txb_size_index(bsize, blk_row, blk_col);
311
428k
  const TX_SIZE plane_tx_size = mbmi->inter_tx_size[txb_size_index];
312
313
428k
  if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
314
315
428k
  if (tx_size == plane_tx_size) {
316
397k
    mbmi->tx_size = tx_size;
317
397k
    txfm_partition_update(xd->above_txfm_context + blk_col,
318
397k
                          xd->left_txfm_context + blk_row, tx_size, tx_size);
319
320
397k
  } else {
321
31.3k
    if (tx_size == TX_8X8) {
322
25.6k
      mbmi->inter_tx_size[txb_size_index] = TX_4X4;
323
25.6k
      mbmi->tx_size = TX_4X4;
324
25.6k
      txfm_partition_update(xd->above_txfm_context + blk_col,
325
25.6k
                            xd->left_txfm_context + blk_row, TX_4X4, tx_size);
326
25.6k
      return;
327
25.6k
    }
328
5.66k
    const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
329
5.66k
    const int bsw = tx_size_wide_unit[sub_txs];
330
5.66k
    const int bsh = tx_size_high_unit[sub_txs];
331
5.66k
    const int row_end =
332
5.66k
        AOMMIN(tx_size_high_unit[tx_size], max_blocks_high - blk_row);
333
5.66k
    const int col_end =
334
5.66k
        AOMMIN(tx_size_wide_unit[tx_size], max_blocks_wide - blk_col);
335
16.9k
    for (int row = 0; row < row_end; row += bsh) {
336
11.2k
      const int offsetr = blk_row + row;
337
33.7k
      for (int col = 0; col < col_end; col += bsw) {
338
22.4k
        const int offsetc = blk_col + col;
339
22.4k
        set_txfm_context(xd, sub_txs, offsetr, offsetc);
340
22.4k
      }
341
11.2k
    }
342
5.66k
  }
343
428k
}
344
345
static void tx_partition_set_contexts(const AV1_COMMON *const cm,
346
405k
                                      MACROBLOCKD *xd, BLOCK_SIZE plane_bsize) {
347
405k
  const int mi_width = mi_size_wide[plane_bsize];
348
405k
  const int mi_height = mi_size_high[plane_bsize];
349
405k
  const TX_SIZE max_tx_size = get_vartx_max_txsize(xd, plane_bsize, 0);
350
405k
  const int bh = tx_size_high_unit[max_tx_size];
351
405k
  const int bw = tx_size_wide_unit[max_tx_size];
352
353
405k
  xd->above_txfm_context =
354
405k
      cm->above_contexts.txfm[xd->tile.tile_row] + xd->mi_col;
355
405k
  xd->left_txfm_context =
356
405k
      xd->left_txfm_context_buffer + (xd->mi_row & MAX_MIB_MASK);
357
358
811k
  for (int idy = 0; idy < mi_height; idy += bh) {
359
811k
    for (int idx = 0; idx < mi_width; idx += bw) {
360
405k
      set_txfm_context(xd, max_tx_size, idy, idx);
361
405k
    }
362
405k
  }
363
405k
}
364
365
static void update_zeromv_cnt(const AV1_COMP *const cpi,
366
                              const MB_MODE_INFO *const mi, int mi_row,
367
0
                              int mi_col, BLOCK_SIZE bsize) {
368
0
  if (mi->ref_frame[0] != LAST_FRAME || !is_inter_block(mi) ||
369
0
      mi->segment_id > CR_SEGMENT_ID_BOOST2) {
370
0
    return;
371
0
  }
372
0
  const AV1_COMMON *const cm = &cpi->common;
373
0
  const MV mv = mi->mv[0].as_mv;
374
0
  const int bw = mi_size_wide[bsize] >> 1;
375
0
  const int bh = mi_size_high[bsize] >> 1;
376
0
  const int xmis = AOMMIN((cm->mi_params.mi_cols - mi_col) >> 1, bw);
377
0
  const int ymis = AOMMIN((cm->mi_params.mi_rows - mi_row) >> 1, bh);
378
0
  const int block_index =
379
0
      (mi_row >> 1) * (cm->mi_params.mi_cols >> 1) + (mi_col >> 1);
380
0
  for (int y = 0; y < ymis; y++) {
381
0
    for (int x = 0; x < xmis; x++) {
382
      // consec_zero_mv is in the scale of 8x8 blocks
383
0
      const int map_offset = block_index + y * (cm->mi_params.mi_cols >> 1) + x;
384
0
      if (abs(mv.row) < 10 && abs(mv.col) < 10) {
385
0
        if (cpi->consec_zero_mv[map_offset] < 255)
386
0
          cpi->consec_zero_mv[map_offset]++;
387
0
      } else {
388
0
        cpi->consec_zero_mv[map_offset] = 0;
389
0
      }
390
0
    }
391
0
  }
392
0
}
393
394
static void encode_superblock(const AV1_COMP *const cpi, TileDataEnc *tile_data,
395
                              ThreadData *td, TokenExtra **t, RUN_TYPE dry_run,
396
36.3M
                              BLOCK_SIZE bsize, int *rate) {
397
36.3M
  const AV1_COMMON *const cm = &cpi->common;
398
36.3M
  const int num_planes = av1_num_planes(cm);
399
36.3M
  MACROBLOCK *const x = &td->mb;
400
36.3M
  MACROBLOCKD *const xd = &x->e_mbd;
401
36.3M
  MB_MODE_INFO **mi_4x4 = xd->mi;
402
36.3M
  MB_MODE_INFO *mbmi = mi_4x4[0];
403
36.3M
  const int seg_skip =
404
36.3M
      segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP);
405
36.3M
  const int mis = cm->mi_params.mi_stride;
406
36.3M
  const int mi_width = mi_size_wide[bsize];
407
36.3M
  const int mi_height = mi_size_high[bsize];
408
36.3M
  const int is_inter = is_inter_block(mbmi);
409
410
  // Initialize tx_mode and tx_size_search_method
411
36.3M
  TxfmSearchParams *txfm_params = &x->txfm_search_params;
412
36.3M
  set_tx_size_search_method(
413
36.3M
      cm, &cpi->winner_mode_params, txfm_params,
414
36.3M
      cpi->sf.winner_mode_sf.enable_winner_mode_for_tx_size_srch, 1);
415
416
36.3M
  const int mi_row = xd->mi_row;
417
36.3M
  const int mi_col = xd->mi_col;
418
36.3M
  if (!is_inter) {
419
35.0M
    xd->cfl.store_y = store_cfl_required(cm, xd);
420
101M
    for (int plane = 0; plane < num_planes; ++plane) {
421
66.1M
      av1_encode_intra_block_plane(cpi, x, bsize, plane, dry_run,
422
66.1M
                                   cpi->optimize_seg_arr[mbmi->segment_id]);
423
66.1M
    }
424
425
    // If there is at least one lossless segment, force the skip for intra
426
    // block to be 0, in order to avoid the segment_id to be changed by in
427
    // write_segment_id().
428
35.1M
    if (!cpi->common.seg.segid_preskip && cpi->common.seg.update_map &&
429
0
        cpi->enc_seg.has_lossless_segment)
430
0
      mbmi->skip_txfm = 0;
431
432
35.0M
    xd->cfl.store_y = 0;
433
35.0M
    if (av1_allow_palette(cm->features.allow_screen_content_tools, bsize)) {
434
      // Gather the stats to determine whether to use screen content tools in
435
      // function av1_determine_sc_tools_with_encoding().
436
1.31M
      if (mbmi->palette_mode_info.palette_size[0] > 0 &&
437
1.20M
          dry_run == OUTPUT_ENABLED)
438
343k
        x->palette_pixels += (block_size_wide[bsize] * block_size_high[bsize]);
439
3.33M
      for (int plane = 0; plane < AOMMIN(2, num_planes); ++plane) {
440
2.02M
        if (mbmi->palette_mode_info.palette_size[plane] > 0) {
441
1.75M
          if (!dry_run) {
442
503k
            av1_tokenize_color_map(x, plane, t, bsize, mbmi->tx_size,
443
503k
                                   PALETTE_MAP, tile_data->allow_update_cdf,
444
503k
                                   td->counts);
445
1.25M
          } else if (dry_run == DRY_RUN_COSTCOEFFS) {
446
0
            *rate +=
447
0
                av1_cost_color_map(x, plane, bsize, mbmi->tx_size, PALETTE_MAP);
448
0
          }
449
1.75M
        }
450
2.02M
      }
451
1.31M
    }
452
453
35.0M
    av1_update_intra_mb_txb_context(cpi, td, dry_run, bsize,
454
35.0M
                                    tile_data->allow_update_cdf);
455
35.0M
  } else {
456
1.31M
    int ref;
457
1.31M
    const int is_compound = has_second_ref(mbmi);
458
459
1.31M
    set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
460
2.63M
    for (ref = 0; ref < 1 + is_compound; ++ref) {
461
1.31M
      const YV12_BUFFER_CONFIG *cfg =
462
1.31M
          get_ref_frame_yv12_buf(cm, mbmi->ref_frame[ref]);
463
1.31M
      assert(IMPLIES(!is_intrabc_block(mbmi), cfg));
464
1.31M
      av1_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
465
1.31M
                           xd->block_ref_scale_factors[ref], num_planes);
466
1.31M
    }
467
    // Predicted sample of inter mode (for Luma plane) cannot be reused if
468
    // nonrd_check_partition_split speed feature is enabled, Since in such cases
469
    // the buffer may not contain the predicted sample of best mode.
470
1.31M
    const int start_plane =
471
1.31M
        (x->reuse_inter_pred && (!cpi->sf.rt_sf.nonrd_check_partition_split) &&
472
0
         cm->seq_params->bit_depth == AOM_BITS_8)
473
1.31M
            ? 1
474
1.31M
            : 0;
475
1.31M
    av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
476
1.31M
                                  start_plane, av1_num_planes(cm) - 1);
477
1.31M
    if (mbmi->motion_mode == OBMC_CAUSAL) {
478
0
      assert(cpi->oxcf.motion_mode_cfg.enable_obmc);
479
0
      av1_build_obmc_inter_predictors_sb(cm, xd);
480
0
    }
481
482
#if CONFIG_MISMATCH_DEBUG
483
    if (dry_run == OUTPUT_ENABLED) {
484
      for (int plane = 0; plane < num_planes; ++plane) {
485
        const struct macroblockd_plane *pd = &xd->plane[plane];
486
        int pixel_c, pixel_r;
487
        mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, 0, 0,
488
                        pd->subsampling_x, pd->subsampling_y);
489
        if (!is_chroma_reference(mi_row, mi_col, bsize, pd->subsampling_x,
490
                                 pd->subsampling_y))
491
          continue;
492
        mismatch_record_block_pre(pd->dst.buf, pd->dst.stride,
493
                                  cm->current_frame.order_hint, plane, pixel_c,
494
                                  pixel_r, pd->width, pd->height,
495
                                  xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
496
      }
497
    }
498
#else
499
1.31M
    (void)num_planes;
500
1.31M
#endif
501
502
1.31M
    av1_encode_sb(cpi, x, bsize, dry_run);
503
1.31M
    av1_tokenize_sb_vartx(cpi, td, dry_run, bsize, rate,
504
1.31M
                          tile_data->allow_update_cdf);
505
1.31M
  }
506
507
36.3M
  if (!dry_run) {
508
10.9M
    if (av1_allow_intrabc(cm) && is_intrabc_block(mbmi)) td->intrabc_used = 1;
509
10.9M
    if (txfm_params->tx_mode_search_type == TX_MODE_SELECT &&
510
8.94M
        !xd->lossless[mbmi->segment_id] && mbmi->bsize > BLOCK_4X4 &&
511
7.65M
        !(is_inter && (mbmi->skip_txfm || seg_skip))) {
512
7.54M
      if (is_inter) {
513
314k
        tx_partition_count_update(cm, x, bsize, td->counts,
514
314k
                                  tile_data->allow_update_cdf);
515
7.22M
      } else {
516
7.22M
        if (mbmi->tx_size != max_txsize_rect_lookup[bsize])
517
1.38M
          ++x->txfm_search_info.txb_split_count;
518
7.22M
        if (block_signals_txsize(bsize)) {
519
7.22M
          const int tx_size_ctx = get_tx_size_context(xd);
520
7.22M
          const int32_t tx_size_cat = bsize_to_tx_size_cat(bsize);
521
7.22M
          const int depth = tx_size_to_depth(mbmi->tx_size, bsize);
522
7.22M
          const int max_depths = bsize_to_max_depth(bsize);
523
524
7.22M
          if (tile_data->allow_update_cdf)
525
5.96M
            update_cdf(xd->tile_ctx->tx_size_cdf[tx_size_cat][tx_size_ctx],
526
5.96M
                       depth, max_depths + 1);
527
#if CONFIG_ENTROPY_STATS
528
          ++td->counts->intra_tx_size[tx_size_cat][tx_size_ctx][depth];
529
#endif
530
7.22M
        }
531
7.22M
      }
532
7.54M
      assert(IMPLIES(is_rect_tx(mbmi->tx_size), is_rect_tx_allowed(xd, mbmi)));
533
7.54M
    } else {
534
3.40M
      int i, j;
535
3.40M
      TX_SIZE intra_tx_size;
536
      // The new intra coding scheme requires no change of transform size
537
3.40M
      if (is_inter) {
538
140k
        if (xd->lossless[mbmi->segment_id]) {
539
19.4k
          intra_tx_size = TX_4X4;
540
121k
        } else {
541
121k
          intra_tx_size =
542
121k
              tx_size_from_tx_mode(bsize, txfm_params->tx_mode_search_type);
543
121k
        }
544
3.26M
      } else {
545
3.26M
        intra_tx_size = mbmi->tx_size;
546
3.26M
      }
547
548
3.40M
      const int cols = AOMMIN(cm->mi_params.mi_cols - mi_col, mi_width);
549
3.40M
      const int rows = AOMMIN(cm->mi_params.mi_rows - mi_row, mi_height);
550
7.83M
      for (j = 0; j < rows; j++) {
551
11.6M
        for (i = 0; i < cols; i++) mi_4x4[mis * j + i]->tx_size = intra_tx_size;
552
4.42M
      }
553
554
3.40M
      if (intra_tx_size != max_txsize_rect_lookup[bsize])
555
763k
        ++x->txfm_search_info.txb_split_count;
556
3.40M
    }
557
10.9M
  }
558
559
36.3M
  if (txfm_params->tx_mode_search_type == TX_MODE_SELECT &&
560
28.2M
      block_signals_txsize(mbmi->bsize) && is_inter &&
561
1.16M
      !(mbmi->skip_txfm || seg_skip) && !xd->lossless[mbmi->segment_id]) {
562
720k
    if (dry_run) tx_partition_set_contexts(cm, xd, bsize);
563
35.6M
  } else {
564
35.6M
    TX_SIZE tx_size = mbmi->tx_size;
565
    // The new intra coding scheme requires no change of transform size
566
35.6M
    if (is_inter) {
567
552k
      if (xd->lossless[mbmi->segment_id]) {
568
49.1k
        tx_size = TX_4X4;
569
503k
      } else {
570
503k
        tx_size = tx_size_from_tx_mode(bsize, txfm_params->tx_mode_search_type);
571
503k
      }
572
35.0M
    } else {
573
35.0M
      tx_size = (bsize > BLOCK_4X4) ? tx_size : TX_4X4;
574
35.0M
    }
575
35.6M
    mbmi->tx_size = tx_size;
576
35.6M
    set_txfm_ctxs(tx_size, xd->width, xd->height,
577
35.6M
                  (mbmi->skip_txfm || seg_skip) && is_inter_block(mbmi), xd);
578
35.6M
  }
579
580
36.3M
#if !CONFIG_REALTIME_ONLY
581
36.3M
  if (is_inter_block(mbmi) && !xd->is_chroma_ref && is_cfl_allowed(xd)) {
582
13.3k
    cfl_store_block(xd, mbmi->bsize, mbmi->tx_size);
583
13.3k
  }
584
36.3M
#endif
585
36.3M
  if (!dry_run) {
586
10.9M
    if (cpi->oxcf.pass == AOM_RC_ONE_PASS && cpi->svc.temporal_layer_id == 0 &&
587
10.9M
        cpi->sf.rt_sf.use_temporal_noise_estimate &&
588
0
        (!cpi->ppi->use_svc ||
589
0
         (cpi->ppi->use_svc &&
590
0
          !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
591
0
          cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
592
0
      update_zeromv_cnt(cpi, mbmi, mi_row, mi_col, bsize);
593
10.9M
  }
594
36.3M
}
595
596
static void setup_block_rdmult(const AV1_COMP *const cpi, MACROBLOCK *const x,
597
                               int mi_row, int mi_col, BLOCK_SIZE bsize,
598
75.1M
                               AQ_MODE aq_mode, MB_MODE_INFO *mbmi) {
599
75.1M
  x->rdmult = cpi->rd.RDMULT;
600
601
75.1M
  if (aq_mode != NO_AQ) {
602
0
    assert(mbmi != NULL);
603
0
    if (aq_mode == VARIANCE_AQ) {
604
0
      if (cpi->vaq_refresh) {
605
0
        const int energy = bsize <= BLOCK_16X16
606
0
                               ? x->mb_energy
607
0
                               : av1_log_block_var(cpi, x, bsize);
608
0
        mbmi->segment_id = energy;
609
0
      }
610
0
      x->rdmult = set_rdmult(cpi, x, mbmi->segment_id);
611
0
    } else if (aq_mode == COMPLEXITY_AQ) {
612
0
      x->rdmult = set_rdmult(cpi, x, mbmi->segment_id);
613
0
    } else if (aq_mode == CYCLIC_REFRESH_AQ) {
614
      // If segment is boosted, use rdmult for that segment.
615
0
      if (cyclic_refresh_segment_id_boosted(mbmi->segment_id))
616
0
        x->rdmult = av1_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
617
0
    }
618
0
  }
619
620
75.1M
#if !CONFIG_REALTIME_ONLY
621
75.1M
  if (cpi->common.delta_q_info.delta_q_present_flag &&
622
37.6M
      !cpi->sf.rt_sf.use_nonrd_pick_mode) {
623
33.7M
    x->rdmult = av1_get_cb_rdmult(cpi, x, bsize, mi_row, mi_col);
624
33.7M
  }
625
75.1M
#endif  // !CONFIG_REALTIME_ONLY
626
627
75.1M
  if (cpi->oxcf.tune_cfg.tuning == AOM_TUNE_SSIM ||
628
67.8M
      cpi->oxcf.tune_cfg.tuning == AOM_TUNE_IQ ||
629
44.7M
      cpi->oxcf.tune_cfg.tuning == AOM_TUNE_SSIMULACRA2) {
630
44.7M
    av1_set_ssim_rdmult(cpi, &x->errorperbit, bsize, mi_row, mi_col,
631
44.7M
                        &x->rdmult);
632
44.7M
  }
633
#if CONFIG_SALIENCY_MAP
634
  else if (cpi->oxcf.tune_cfg.tuning == AOM_TUNE_VMAF_SALIENCY_MAP) {
635
    av1_set_saliency_map_vmaf_rdmult(cpi, &x->errorperbit,
636
                                     cpi->common.seq_params->sb_size, mi_row,
637
                                     mi_col, &x->rdmult);
638
  }
639
#endif
640
#if CONFIG_TUNE_VMAF
641
  else if (cpi->oxcf.tune_cfg.tuning == AOM_TUNE_VMAF_WITHOUT_PREPROCESSING ||
642
           cpi->oxcf.tune_cfg.tuning == AOM_TUNE_VMAF_MAX_GAIN ||
643
           cpi->oxcf.tune_cfg.tuning == AOM_TUNE_VMAF_NEG_MAX_GAIN) {
644
    av1_set_vmaf_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
645
  }
646
#endif
647
#if CONFIG_TUNE_BUTTERAUGLI
648
  else if (cpi->oxcf.tune_cfg.tuning == AOM_TUNE_BUTTERAUGLI) {
649
    av1_set_butteraugli_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
650
  }
651
#endif
652
75.1M
  if (cpi->oxcf.mode == ALLINTRA) {
653
63.9M
    x->rdmult = (int)(((int64_t)x->rdmult * x->intra_sb_rdmult_modifier) >> 7);
654
63.9M
  }
655
656
  // Check to make sure that the adjustments above have not caused the
657
  // rd multiplier to be truncated to 0.
658
75.1M
  x->rdmult = (x->rdmult > 0) ? x->rdmult : 1;
659
75.1M
}
660
661
void av1_set_offsets_without_segment_id(const AV1_COMP *const cpi,
662
                                        const TileInfo *const tile,
663
                                        MACROBLOCK *const x, int mi_row,
664
73.3M
                                        int mi_col, BLOCK_SIZE bsize) {
665
73.3M
  const AV1_COMMON *const cm = &cpi->common;
666
73.3M
  const int num_planes = av1_num_planes(cm);
667
73.3M
  MACROBLOCKD *const xd = &x->e_mbd;
668
73.3M
  assert(bsize < BLOCK_SIZES_ALL);
669
73.3M
  const int mi_width = mi_size_wide[bsize];
670
73.3M
  const int mi_height = mi_size_high[bsize];
671
672
73.3M
  set_mode_info_offsets(&cpi->common.mi_params, &cpi->mbmi_ext_info, x, xd,
673
73.3M
                        mi_row, mi_col);
674
675
73.3M
  set_entropy_context(xd, mi_row, mi_col, num_planes);
676
73.3M
  xd->above_txfm_context = cm->above_contexts.txfm[tile->tile_row] + mi_col;
677
73.3M
  xd->left_txfm_context =
678
73.3M
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
679
680
  // Set up destination pointers.
681
73.3M
  av1_setup_dst_planes(xd->plane, bsize, &cm->cur_frame->buf, mi_row, mi_col, 0,
682
73.3M
                       num_planes);
683
684
  // Set up limit values for MV components.
685
  // Mv beyond the range do not produce new/different prediction block.
686
73.3M
  av1_set_mv_limits(&cm->mi_params, &x->mv_limits, mi_row, mi_col, mi_height,
687
73.3M
                    mi_width, cpi->oxcf.border_in_pixels);
688
689
73.3M
  set_plane_n4(xd, mi_width, mi_height, num_planes);
690
691
  // Set up distance of MB to edge of frame in 1/8th pel units.
692
73.3M
  assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
693
73.3M
  set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width,
694
73.3M
                 cm->mi_params.mi_rows, cm->mi_params.mi_cols);
695
696
  // Set up source buffers.
697
73.3M
  av1_setup_src_planes(x, cpi->source, mi_row, mi_col, num_planes, bsize);
698
699
  // required by av1_append_sub8x8_mvs_for_idx() and av1_find_best_ref_mvs()
700
73.3M
  xd->tile = *tile;
701
73.3M
}
702
703
void av1_set_offsets(const AV1_COMP *const cpi, const TileInfo *const tile,
704
                     MACROBLOCK *const x, int mi_row, int mi_col,
705
37.4M
                     BLOCK_SIZE bsize) {
706
37.4M
  const AV1_COMMON *const cm = &cpi->common;
707
37.4M
  const struct segmentation *const seg = &cm->seg;
708
37.4M
  MACROBLOCKD *const xd = &x->e_mbd;
709
37.4M
  MB_MODE_INFO *mbmi;
710
711
37.4M
  av1_set_offsets_without_segment_id(cpi, tile, x, mi_row, mi_col, bsize);
712
713
  // Setup segment ID.
714
37.4M
  mbmi = xd->mi[0];
715
37.4M
  mbmi->segment_id = 0;
716
37.4M
  if (seg->enabled) {
717
0
    if (seg->enabled && !cpi->vaq_refresh) {
718
0
      const uint8_t *const map =
719
0
          seg->update_map ? cpi->enc_seg.map : cm->last_frame_seg_map;
720
0
      mbmi->segment_id =
721
0
          map ? get_segment_id(&cm->mi_params, map, bsize, mi_row, mi_col) : 0;
722
0
    }
723
0
    av1_init_plane_quantizers(cpi, x, mbmi->segment_id, 0);
724
0
  }
725
#ifndef NDEBUG
726
  x->last_set_offsets_loc.mi_row = mi_row;
727
  x->last_set_offsets_loc.mi_col = mi_col;
728
  x->last_set_offsets_loc.bsize = bsize;
729
#endif  // NDEBUG
730
37.4M
}
731
732
/*!\brief Hybrid intra mode search.
733
 *
734
 * \ingroup intra_mode_search
735
 * \callgraph
736
 * \callergraph
737
 * This is top level function for mode search for intra frames in non-RD
738
 * optimized case. Depending on speed feature and block size it calls
739
 * either non-RD or RD optimized intra mode search.
740
 *
741
 * \param[in]    cpi            Top-level encoder structure
742
 * \param[in]    x              Pointer to structure holding all the data for
743
                                the current macroblock
744
 * \param[in]    rd_cost        Struct to keep track of the RD information
745
 * \param[in]    bsize          Current block size
746
 * \param[in]    ctx            Structure to hold snapshot of coding context
747
                                during the mode picking process
748
 *
749
 * \remark Nothing is returned. Instead, the MB_MODE_INFO struct inside x
750
 * is modified to store information about the best mode computed
751
 * in this function. The rd_cost struct is also updated with the RD stats
752
 * corresponding to the best mode found.
753
 */
754
755
static inline void hybrid_intra_mode_search(AV1_COMP *cpi, MACROBLOCK *const x,
756
                                            RD_STATS *rd_cost, BLOCK_SIZE bsize,
757
3.59M
                                            PICK_MODE_CONTEXT *ctx) {
758
3.59M
  int use_rdopt = 0;
759
3.59M
  const int hybrid_intra_pickmode = cpi->sf.rt_sf.hybrid_intra_pickmode;
760
  // Use rd pick for intra mode search based on block size and variance.
761
3.59M
  if (hybrid_intra_pickmode && bsize < BLOCK_16X16) {
762
2.06M
    unsigned int var_thresh[3] = { 0, 101, 201 };
763
2.06M
    assert(hybrid_intra_pickmode <= 3);
764
2.06M
    if (x->source_variance >= var_thresh[hybrid_intra_pickmode - 1])
765
2.06M
      use_rdopt = 1;
766
2.06M
  }
767
768
3.59M
  if (use_rdopt)
769
2.06M
    av1_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
770
1.53M
  else
771
1.53M
    av1_nonrd_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
772
3.59M
}
773
774
// For real time/allintra row-mt enabled multi-threaded encoding with cost
775
// update frequency set to COST_UPD_TILE/COST_UPD_OFF, tile ctxt is not updated
776
// at superblock level. Thus, it is not required for the encoding of top-right
777
// superblock be complete for updating tile ctxt. However, when encoding a block
778
// whose right edge is also the superblock edge, intra and inter mode evaluation
779
// (ref mv list population) require the encoding of the top-right superblock to
780
// be complete. So, here, we delay the waiting of threads until the need for the
781
// data from the top-right superblock region.
782
static inline void wait_for_top_right_sb(AV1EncRowMultiThreadInfo *enc_row_mt,
783
                                         AV1EncRowMultiThreadSync *row_mt_sync,
784
                                         TileInfo *tile_info,
785
                                         BLOCK_SIZE sb_size,
786
                                         int sb_mi_size_log2, BLOCK_SIZE bsize,
787
21.2M
                                         int mi_row, int mi_col) {
788
21.2M
  const int sb_size_in_mi = mi_size_wide[sb_size];
789
21.2M
  const int bw_in_mi = mi_size_wide[bsize];
790
21.2M
  const int blk_row_in_sb = mi_row & (sb_size_in_mi - 1);
791
21.2M
  const int blk_col_in_sb = mi_col & (sb_size_in_mi - 1);
792
21.2M
  const int top_right_block_in_sb =
793
21.2M
      (blk_row_in_sb == 0) && (blk_col_in_sb + bw_in_mi >= sb_size_in_mi);
794
795
  // Don't wait if the block is the not the top-right block in the superblock.
796
21.2M
  if (!top_right_block_in_sb) return;
797
798
  // Wait for the top-right superblock to finish encoding.
799
553k
  const int sb_row_in_tile =
800
553k
      (mi_row - tile_info->mi_row_start) >> sb_mi_size_log2;
801
553k
  const int sb_col_in_tile =
802
553k
      (mi_col - tile_info->mi_col_start) >> sb_mi_size_log2;
803
804
553k
  enc_row_mt->sync_read_ptr(row_mt_sync, sb_row_in_tile, sb_col_in_tile);
805
553k
}
806
807
/*!\brief Interface for AV1 mode search for an individual coding block
808
 *
809
 * \ingroup partition_search
810
 * \callgraph
811
 * \callergraph
812
 * Searches prediction modes, transform, and coefficient coding modes for an
813
 * individual coding block. This function is the top-level interface that
814
 * directs the encoder to the proper mode search function, among these
815
 * implemented for inter/intra + rd/non-rd + non-skip segment/skip segment.
816
 *
817
 * \param[in]    cpi            Top-level encoder structure
818
 * \param[in]    tile_data      Pointer to struct holding adaptive
819
 *                              data/contexts/models for the tile during
820
 *                              encoding
821
 * \param[in]    x              Pointer to structure holding all the data for
822
 *                              the current macroblock
823
 * \param[in]    mi_row         Row coordinate of the block in a step size of
824
 *                              MI_SIZE
825
 * \param[in]    mi_col         Column coordinate of the block in a step size of
826
 *                              MI_SIZE
827
 * \param[in]    rd_cost        Pointer to structure holding rate and distortion
828
 *                              stats for the current block
829
 * \param[in]    partition      Partition mode of the parent block
830
 * \param[in]    bsize          Current block size
831
 * \param[in]    ctx            Pointer to structure holding coding contexts and
832
 *                              chosen modes for the current block
833
 * \param[in]    best_rd        Upper bound of rd cost of a valid partition
834
 *
835
 * \remark Nothing is returned. Instead, the chosen modes and contexts necessary
836
 * for reconstruction are stored in ctx, the rate-distortion stats are stored in
837
 * rd_cost. If no valid mode leading to rd_cost <= best_rd, the status will be
838
 * signalled by an INT64_MAX rd_cost->rdcost.
839
 */
840
static void pick_sb_modes(AV1_COMP *const cpi, TileDataEnc *tile_data,
841
                          MACROBLOCK *const x, int mi_row, int mi_col,
842
                          RD_STATS *rd_cost, PARTITION_TYPE partition,
843
                          BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
844
17.2M
                          RD_STATS best_rd) {
845
17.2M
  if (cpi->sf.part_sf.use_best_rd_for_pruning && best_rd.rdcost < 0) {
846
165
    ctx->rd_stats.rdcost = INT64_MAX;
847
165
    ctx->rd_stats.skip_txfm = 0;
848
165
    av1_invalid_rd_stats(rd_cost);
849
165
    return;
850
165
  }
851
852
17.2M
  av1_set_offsets(cpi, &tile_data->tile_info, x, mi_row, mi_col, bsize);
853
854
17.2M
  if (cpi->sf.part_sf.reuse_prev_rd_results_for_part_ab &&
855
17.2M
      ctx->rd_mode_is_ready) {
856
0
    assert(ctx->mic.bsize == bsize);
857
0
    assert(ctx->mic.partition == partition);
858
0
    rd_cost->rate = ctx->rd_stats.rate;
859
0
    rd_cost->dist = ctx->rd_stats.dist;
860
0
    rd_cost->rdcost = ctx->rd_stats.rdcost;
861
0
    return;
862
0
  }
863
864
17.2M
  AV1_COMMON *const cm = &cpi->common;
865
17.2M
  const int num_planes = av1_num_planes(cm);
866
17.2M
  MACROBLOCKD *const xd = &x->e_mbd;
867
17.2M
  MB_MODE_INFO *mbmi;
868
17.2M
  struct macroblock_plane *const p = x->plane;
869
17.2M
  struct macroblockd_plane *const pd = xd->plane;
870
17.2M
  const AQ_MODE aq_mode = cpi->oxcf.q_cfg.aq_mode;
871
17.2M
  TxfmSearchInfo *txfm_info = &x->txfm_search_info;
872
873
17.2M
  int i;
874
875
  // This is only needed for real time/allintra row-mt enabled multi-threaded
876
  // encoding with cost update frequency set to COST_UPD_TILE/COST_UPD_OFF.
877
17.2M
  wait_for_top_right_sb(&cpi->mt_info.enc_row_mt, &tile_data->row_mt_sync,
878
17.2M
                        &tile_data->tile_info, cm->seq_params->sb_size,
879
17.2M
                        cm->seq_params->mib_size_log2, bsize, mi_row, mi_col);
880
881
#if CONFIG_COLLECT_COMPONENT_TIMING
882
  start_timing(cpi, rd_pick_sb_modes_time);
883
#endif
884
885
17.2M
  mbmi = xd->mi[0];
886
17.2M
  mbmi->bsize = bsize;
887
17.2M
  mbmi->partition = partition;
888
889
#if CONFIG_RD_DEBUG
890
  mbmi->mi_row = mi_row;
891
  mbmi->mi_col = mi_col;
892
#endif
893
894
  // Sets up the tx_type_map buffer in MACROBLOCKD.
895
17.2M
  xd->tx_type_map = txfm_info->tx_type_map_;
896
17.2M
  xd->tx_type_map_stride = mi_size_wide[bsize];
897
898
49.5M
  for (i = 0; i < num_planes; ++i) {
899
32.2M
    p[i].coeff = ctx->coeff[i];
900
32.2M
    p[i].qcoeff = ctx->qcoeff[i];
901
32.2M
    p[i].dqcoeff = ctx->dqcoeff[i];
902
32.2M
    p[i].eobs = ctx->eobs[i];
903
32.2M
    p[i].txb_entropy_ctx = ctx->txb_entropy_ctx[i];
904
32.2M
  }
905
906
51.6M
  for (i = 0; i < 2; ++i) pd[i].color_index_map = ctx->color_index_map[i];
907
908
17.2M
  ctx->skippable = 0;
909
  // Set to zero to make sure we do not use the previous encoded frame stats
910
17.2M
  mbmi->skip_txfm = 0;
911
  // Reset skip mode flag.
912
17.2M
  mbmi->skip_mode = 0;
913
914
17.2M
  x->source_variance = av1_get_perpixel_variance_facade(
915
17.2M
      cpi, xd, &x->plane[0].src, bsize, AOM_PLANE_Y);
916
917
  // Initialize default mode evaluation params
918
17.2M
  set_mode_eval_params(cpi, x, DEFAULT_EVAL);
919
920
  // Save rdmult before it might be changed, so it can be restored later.
921
17.2M
  const int orig_rdmult = x->rdmult;
922
17.2M
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode, mbmi);
923
  // Set error per bit for current rdmult
924
17.2M
  av1_set_error_per_bit(&x->errorperbit, x->rdmult);
925
17.2M
  av1_rd_cost_update(x->rdmult, &best_rd);
926
927
  // If set best_rd.rdcost to INT64_MAX, the encoder will not use any previous
928
  // rdcost information for the following mode search.
929
  // Disabling the feature could get some coding gain, with encoder slowdown.
930
17.2M
  if (!cpi->sf.part_sf.use_best_rd_for_pruning) {
931
0
    av1_invalid_rd_stats(&best_rd);
932
0
  }
933
934
  // Find best coding mode & reconstruct the MB so it is available
935
  // as a predictor for MBs that follow in the SB
936
17.2M
  if (frame_is_intra_only(cm)) {
937
#if CONFIG_COLLECT_COMPONENT_TIMING
938
    start_timing(cpi, av1_rd_pick_intra_mode_sb_time);
939
#endif
940
16.3M
    av1_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd.rdcost);
941
#if CONFIG_COLLECT_COMPONENT_TIMING
942
    end_timing(cpi, av1_rd_pick_intra_mode_sb_time);
943
#endif
944
16.3M
  } else {
945
#if CONFIG_COLLECT_COMPONENT_TIMING
946
    start_timing(cpi, av1_rd_pick_inter_mode_sb_time);
947
#endif
948
912k
    if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
949
0
      av1_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, mi_row, mi_col,
950
0
                                         rd_cost, bsize, ctx, best_rd.rdcost);
951
912k
    } else {
952
912k
      av1_rd_pick_inter_mode(cpi, tile_data, x, rd_cost, bsize, ctx,
953
912k
                             best_rd.rdcost);
954
912k
    }
955
#if CONFIG_COLLECT_COMPONENT_TIMING
956
    end_timing(cpi, av1_rd_pick_inter_mode_sb_time);
957
#endif
958
912k
  }
959
960
  // Examine the resulting rate and for AQ mode 2 make a segment choice.
961
17.2M
  if (rd_cost->rate != INT_MAX && aq_mode == COMPLEXITY_AQ &&
962
0
      bsize >= BLOCK_16X16) {
963
0
    av1_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
964
0
  }
965
966
17.2M
  x->rdmult = orig_rdmult;
967
968
  // TODO(jingning) The rate-distortion optimization flow needs to be
969
  // refactored to provide proper exit/return handle.
970
17.2M
  if (rd_cost->rate == INT_MAX) rd_cost->rdcost = INT64_MAX;
971
972
17.2M
  ctx->rd_stats.rate = rd_cost->rate;
973
17.2M
  ctx->rd_stats.dist = rd_cost->dist;
974
17.2M
  ctx->rd_stats.rdcost = rd_cost->rdcost;
975
976
#if CONFIG_COLLECT_COMPONENT_TIMING
977
  end_timing(cpi, rd_pick_sb_modes_time);
978
#endif
979
17.2M
}
980
981
9.47M
static void update_stats(const AV1_COMMON *const cm, ThreadData *td) {
982
9.47M
  MACROBLOCK *x = &td->mb;
983
9.47M
  MACROBLOCKD *const xd = &x->e_mbd;
984
9.47M
  const MB_MODE_INFO *const mbmi = xd->mi[0];
985
9.47M
  const MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
986
9.47M
  const CurrentFrame *const current_frame = &cm->current_frame;
987
9.47M
  const BLOCK_SIZE bsize = mbmi->bsize;
988
9.47M
  FRAME_CONTEXT *fc = xd->tile_ctx;
989
9.47M
  const int seg_ref_active =
990
9.47M
      segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_REF_FRAME);
991
992
9.47M
  if (current_frame->skip_mode_info.skip_mode_flag && !seg_ref_active &&
993
185k
      is_comp_ref_allowed(bsize)) {
994
185k
    const int skip_mode_ctx = av1_get_skip_mode_context(xd);
995
#if CONFIG_ENTROPY_STATS
996
    td->counts->skip_mode[skip_mode_ctx][mbmi->skip_mode]++;
997
#endif
998
185k
    update_cdf(fc->skip_mode_cdfs[skip_mode_ctx], mbmi->skip_mode, 2);
999
185k
  }
1000
1001
9.47M
  if (!mbmi->skip_mode && !seg_ref_active) {
1002
9.47M
    const int skip_ctx = av1_get_skip_txfm_context(xd);
1003
#if CONFIG_ENTROPY_STATS
1004
    td->counts->skip_txfm[skip_ctx][mbmi->skip_txfm]++;
1005
#endif
1006
9.47M
    update_cdf(fc->skip_txfm_cdfs[skip_ctx], mbmi->skip_txfm, 2);
1007
9.47M
  }
1008
1009
#if CONFIG_ENTROPY_STATS
1010
  // delta quant applies to both intra and inter
1011
  const int super_block_upper_left =
1012
      ((xd->mi_row & (cm->seq_params->mib_size - 1)) == 0) &&
1013
      ((xd->mi_col & (cm->seq_params->mib_size - 1)) == 0);
1014
  const DeltaQInfo *const delta_q_info = &cm->delta_q_info;
1015
  if (delta_q_info->delta_q_present_flag &&
1016
      (bsize != cm->seq_params->sb_size || !mbmi->skip_txfm) &&
1017
      super_block_upper_left) {
1018
    const int dq = (mbmi->current_qindex - xd->current_base_qindex) /
1019
                   delta_q_info->delta_q_res;
1020
    const int absdq = abs(dq);
1021
    for (int i = 0; i < AOMMIN(absdq, DELTA_Q_SMALL); ++i) {
1022
      td->counts->delta_q[i][1]++;
1023
    }
1024
    if (absdq < DELTA_Q_SMALL) td->counts->delta_q[absdq][0]++;
1025
    if (delta_q_info->delta_lf_present_flag) {
1026
      if (delta_q_info->delta_lf_multi) {
1027
        const int frame_lf_count =
1028
            av1_num_planes(cm) > 1 ? FRAME_LF_COUNT : FRAME_LF_COUNT - 2;
1029
        for (int lf_id = 0; lf_id < frame_lf_count; ++lf_id) {
1030
          const int delta_lf = (mbmi->delta_lf[lf_id] - xd->delta_lf[lf_id]) /
1031
                               delta_q_info->delta_lf_res;
1032
          const int abs_delta_lf = abs(delta_lf);
1033
          for (int i = 0; i < AOMMIN(abs_delta_lf, DELTA_LF_SMALL); ++i) {
1034
            td->counts->delta_lf_multi[lf_id][i][1]++;
1035
          }
1036
          if (abs_delta_lf < DELTA_LF_SMALL)
1037
            td->counts->delta_lf_multi[lf_id][abs_delta_lf][0]++;
1038
        }
1039
      } else {
1040
        const int delta_lf =
1041
            (mbmi->delta_lf_from_base - xd->delta_lf_from_base) /
1042
            delta_q_info->delta_lf_res;
1043
        const int abs_delta_lf = abs(delta_lf);
1044
        for (int i = 0; i < AOMMIN(abs_delta_lf, DELTA_LF_SMALL); ++i) {
1045
          td->counts->delta_lf[i][1]++;
1046
        }
1047
        if (abs_delta_lf < DELTA_LF_SMALL)
1048
          td->counts->delta_lf[abs_delta_lf][0]++;
1049
      }
1050
    }
1051
  }
1052
#endif
1053
1054
9.47M
  if (!is_inter_block(mbmi)) {
1055
9.02M
    av1_sum_intra_stats(cm, td->counts, xd, mbmi, xd->above_mbmi, xd->left_mbmi,
1056
9.02M
                        frame_is_intra_only(cm));
1057
9.02M
  }
1058
1059
9.47M
  if (av1_allow_intrabc(cm)) {
1060
401k
    const int is_intrabc = is_intrabc_block(mbmi);
1061
401k
    update_cdf(fc->intrabc_cdf, is_intrabc, 2);
1062
#if CONFIG_ENTROPY_STATS
1063
    ++td->counts->intrabc[is_intrabc];
1064
#endif  // CONFIG_ENTROPY_STATS
1065
401k
    if (is_intrabc) {
1066
10.3k
      const int8_t ref_frame_type = av1_ref_frame_type(mbmi->ref_frame);
1067
10.3k
      const int_mv dv_ref = mbmi_ext->ref_mv_stack[ref_frame_type][0].this_mv;
1068
10.3k
      av1_update_mv_stats(&mbmi->mv[0].as_mv, &dv_ref.as_mv, &fc->ndvc,
1069
10.3k
                          MV_SUBPEL_NONE);
1070
10.3k
    }
1071
401k
  }
1072
1073
9.47M
  if (frame_is_intra_only(cm) || mbmi->skip_mode) return;
1074
1075
1.15M
  FRAME_COUNTS *const counts = td->counts;
1076
1.15M
  const int inter_block = is_inter_block(mbmi);
1077
1078
1.16M
  if (!seg_ref_active) {
1079
#if CONFIG_ENTROPY_STATS
1080
    counts->intra_inter[av1_get_intra_inter_context(xd)][inter_block]++;
1081
#endif
1082
1.16M
    update_cdf(fc->intra_inter_cdf[av1_get_intra_inter_context(xd)],
1083
1.16M
               inter_block, 2);
1084
    // If the segment reference feature is enabled we have only a single
1085
    // reference frame allowed for the segment so exclude it from
1086
    // the reference frame counts used to work out probabilities.
1087
1.16M
    if (inter_block) {
1088
438k
      const MV_REFERENCE_FRAME ref0 = mbmi->ref_frame[0];
1089
438k
      const MV_REFERENCE_FRAME ref1 = mbmi->ref_frame[1];
1090
438k
      if (current_frame->reference_mode == REFERENCE_MODE_SELECT) {
1091
416k
        if (is_comp_ref_allowed(bsize)) {
1092
#if CONFIG_ENTROPY_STATS
1093
          counts->comp_inter[av1_get_reference_mode_context(xd)]
1094
                            [has_second_ref(mbmi)]++;
1095
#endif  // CONFIG_ENTROPY_STATS
1096
416k
          update_cdf(av1_get_reference_mode_cdf(xd), has_second_ref(mbmi), 2);
1097
416k
        }
1098
416k
      }
1099
1100
438k
      if (has_second_ref(mbmi)) {
1101
7.04k
        const COMP_REFERENCE_TYPE comp_ref_type = has_uni_comp_refs(mbmi)
1102
7.04k
                                                      ? UNIDIR_COMP_REFERENCE
1103
7.04k
                                                      : BIDIR_COMP_REFERENCE;
1104
7.04k
        update_cdf(av1_get_comp_reference_type_cdf(xd), comp_ref_type,
1105
7.04k
                   COMP_REFERENCE_TYPES);
1106
#if CONFIG_ENTROPY_STATS
1107
        counts->comp_ref_type[av1_get_comp_reference_type_context(xd)]
1108
                             [comp_ref_type]++;
1109
#endif  // CONFIG_ENTROPY_STATS
1110
1111
7.04k
        if (comp_ref_type == UNIDIR_COMP_REFERENCE) {
1112
0
          const int bit = (ref0 == BWDREF_FRAME);
1113
0
          update_cdf(av1_get_pred_cdf_uni_comp_ref_p(xd), bit, 2);
1114
#if CONFIG_ENTROPY_STATS
1115
          counts
1116
              ->uni_comp_ref[av1_get_pred_context_uni_comp_ref_p(xd)][0][bit]++;
1117
#endif  // CONFIG_ENTROPY_STATS
1118
0
          if (!bit) {
1119
0
            const int bit1 = (ref1 == LAST3_FRAME || ref1 == GOLDEN_FRAME);
1120
0
            update_cdf(av1_get_pred_cdf_uni_comp_ref_p1(xd), bit1, 2);
1121
#if CONFIG_ENTROPY_STATS
1122
            counts->uni_comp_ref[av1_get_pred_context_uni_comp_ref_p1(xd)][1]
1123
                                [bit1]++;
1124
#endif  // CONFIG_ENTROPY_STATS
1125
0
            if (bit1) {
1126
0
              update_cdf(av1_get_pred_cdf_uni_comp_ref_p2(xd),
1127
0
                         ref1 == GOLDEN_FRAME, 2);
1128
#if CONFIG_ENTROPY_STATS
1129
              counts->uni_comp_ref[av1_get_pred_context_uni_comp_ref_p2(xd)][2]
1130
                                  [ref1 == GOLDEN_FRAME]++;
1131
#endif  // CONFIG_ENTROPY_STATS
1132
0
            }
1133
0
          }
1134
7.04k
        } else {
1135
7.04k
          const int bit = (ref0 == GOLDEN_FRAME || ref0 == LAST3_FRAME);
1136
7.04k
          update_cdf(av1_get_pred_cdf_comp_ref_p(xd), bit, 2);
1137
#if CONFIG_ENTROPY_STATS
1138
          counts->comp_ref[av1_get_pred_context_comp_ref_p(xd)][0][bit]++;
1139
#endif  // CONFIG_ENTROPY_STATS
1140
7.04k
          if (!bit) {
1141
7.03k
            update_cdf(av1_get_pred_cdf_comp_ref_p1(xd), ref0 == LAST2_FRAME,
1142
7.03k
                       2);
1143
#if CONFIG_ENTROPY_STATS
1144
            counts->comp_ref[av1_get_pred_context_comp_ref_p1(xd)][1]
1145
                            [ref0 == LAST2_FRAME]++;
1146
#endif  // CONFIG_ENTROPY_STATS
1147
7.03k
          } else {
1148
2
            update_cdf(av1_get_pred_cdf_comp_ref_p2(xd), ref0 == GOLDEN_FRAME,
1149
2
                       2);
1150
#if CONFIG_ENTROPY_STATS
1151
            counts->comp_ref[av1_get_pred_context_comp_ref_p2(xd)][2]
1152
                            [ref0 == GOLDEN_FRAME]++;
1153
#endif  // CONFIG_ENTROPY_STATS
1154
2
          }
1155
7.04k
          update_cdf(av1_get_pred_cdf_comp_bwdref_p(xd), ref1 == ALTREF_FRAME,
1156
7.04k
                     2);
1157
#if CONFIG_ENTROPY_STATS
1158
          counts->comp_bwdref[av1_get_pred_context_comp_bwdref_p(xd)][0]
1159
                             [ref1 == ALTREF_FRAME]++;
1160
#endif  // CONFIG_ENTROPY_STATS
1161
7.04k
          if (ref1 != ALTREF_FRAME) {
1162
4.25k
            update_cdf(av1_get_pred_cdf_comp_bwdref_p1(xd),
1163
4.25k
                       ref1 == ALTREF2_FRAME, 2);
1164
#if CONFIG_ENTROPY_STATS
1165
            counts->comp_bwdref[av1_get_pred_context_comp_bwdref_p1(xd)][1]
1166
                               [ref1 == ALTREF2_FRAME]++;
1167
#endif  // CONFIG_ENTROPY_STATS
1168
4.25k
          }
1169
7.04k
        }
1170
431k
      } else {
1171
431k
        const int bit = (ref0 >= BWDREF_FRAME);
1172
431k
        update_cdf(av1_get_pred_cdf_single_ref_p1(xd), bit, 2);
1173
#if CONFIG_ENTROPY_STATS
1174
        counts->single_ref[av1_get_pred_context_single_ref_p1(xd)][0][bit]++;
1175
#endif  // CONFIG_ENTROPY_STATS
1176
431k
        if (bit) {
1177
40.6k
          assert(ref0 <= ALTREF_FRAME);
1178
40.6k
          update_cdf(av1_get_pred_cdf_single_ref_p2(xd), ref0 == ALTREF_FRAME,
1179
40.6k
                     2);
1180
#if CONFIG_ENTROPY_STATS
1181
          counts->single_ref[av1_get_pred_context_single_ref_p2(xd)][1]
1182
                            [ref0 == ALTREF_FRAME]++;
1183
#endif  // CONFIG_ENTROPY_STATS
1184
40.6k
          if (ref0 != ALTREF_FRAME) {
1185
7.89k
            update_cdf(av1_get_pred_cdf_single_ref_p6(xd),
1186
7.89k
                       ref0 == ALTREF2_FRAME, 2);
1187
#if CONFIG_ENTROPY_STATS
1188
            counts->single_ref[av1_get_pred_context_single_ref_p6(xd)][5]
1189
                              [ref0 == ALTREF2_FRAME]++;
1190
#endif  // CONFIG_ENTROPY_STATS
1191
7.89k
          }
1192
391k
        } else {
1193
391k
          const int bit1 = !(ref0 == LAST2_FRAME || ref0 == LAST_FRAME);
1194
391k
          update_cdf(av1_get_pred_cdf_single_ref_p3(xd), bit1, 2);
1195
#if CONFIG_ENTROPY_STATS
1196
          counts->single_ref[av1_get_pred_context_single_ref_p3(xd)][2][bit1]++;
1197
#endif  // CONFIG_ENTROPY_STATS
1198
391k
          if (!bit1) {
1199
388k
            update_cdf(av1_get_pred_cdf_single_ref_p4(xd), ref0 != LAST_FRAME,
1200
388k
                       2);
1201
#if CONFIG_ENTROPY_STATS
1202
            counts->single_ref[av1_get_pred_context_single_ref_p4(xd)][3]
1203
                              [ref0 != LAST_FRAME]++;
1204
#endif  // CONFIG_ENTROPY_STATS
1205
388k
          } else {
1206
2.72k
            update_cdf(av1_get_pred_cdf_single_ref_p5(xd), ref0 != LAST3_FRAME,
1207
2.72k
                       2);
1208
#if CONFIG_ENTROPY_STATS
1209
            counts->single_ref[av1_get_pred_context_single_ref_p5(xd)][4]
1210
                              [ref0 != LAST3_FRAME]++;
1211
#endif  // CONFIG_ENTROPY_STATS
1212
2.72k
          }
1213
391k
        }
1214
431k
      }
1215
1216
438k
      if (cm->seq_params->enable_interintra_compound &&
1217
0
          is_interintra_allowed(mbmi)) {
1218
0
        const int bsize_group = size_group_lookup[bsize];
1219
0
        if (mbmi->ref_frame[1] == INTRA_FRAME) {
1220
#if CONFIG_ENTROPY_STATS
1221
          counts->interintra[bsize_group][1]++;
1222
#endif
1223
0
          update_cdf(fc->interintra_cdf[bsize_group], 1, 2);
1224
#if CONFIG_ENTROPY_STATS
1225
          counts->interintra_mode[bsize_group][mbmi->interintra_mode]++;
1226
#endif
1227
0
          update_cdf(fc->interintra_mode_cdf[bsize_group],
1228
0
                     mbmi->interintra_mode, INTERINTRA_MODES);
1229
0
          if (av1_is_wedge_used(bsize)) {
1230
#if CONFIG_ENTROPY_STATS
1231
            counts->wedge_interintra[bsize][mbmi->use_wedge_interintra]++;
1232
#endif
1233
0
            update_cdf(fc->wedge_interintra_cdf[bsize],
1234
0
                       mbmi->use_wedge_interintra, 2);
1235
0
            if (mbmi->use_wedge_interintra) {
1236
#if CONFIG_ENTROPY_STATS
1237
              counts->wedge_idx[bsize][mbmi->interintra_wedge_index]++;
1238
#endif
1239
0
              update_cdf(fc->wedge_idx_cdf[bsize], mbmi->interintra_wedge_index,
1240
0
                         16);
1241
0
            }
1242
0
          }
1243
0
        } else {
1244
#if CONFIG_ENTROPY_STATS
1245
          counts->interintra[bsize_group][0]++;
1246
#endif
1247
0
          update_cdf(fc->interintra_cdf[bsize_group], 0, 2);
1248
0
        }
1249
0
      }
1250
1251
438k
      const MOTION_MODE motion_allowed =
1252
438k
          cm->features.switchable_motion_mode
1253
439k
              ? motion_mode_allowed(xd->global_motion, xd, mbmi,
1254
439k
                                    cm->features.allow_warped_motion)
1255
18.4E
              : SIMPLE_TRANSLATION;
1256
439k
      if (mbmi->ref_frame[1] != INTRA_FRAME) {
1257
439k
        if (motion_allowed == WARPED_CAUSAL) {
1258
#if CONFIG_ENTROPY_STATS
1259
          counts->motion_mode[bsize][mbmi->motion_mode]++;
1260
#endif
1261
300k
          update_cdf(fc->motion_mode_cdf[bsize], mbmi->motion_mode,
1262
300k
                     MOTION_MODES);
1263
300k
        } else if (motion_allowed == OBMC_CAUSAL) {
1264
#if CONFIG_ENTROPY_STATS
1265
          counts->obmc[bsize][mbmi->motion_mode == OBMC_CAUSAL]++;
1266
#endif
1267
17.3k
          update_cdf(fc->obmc_cdf[bsize], mbmi->motion_mode == OBMC_CAUSAL, 2);
1268
17.3k
        }
1269
439k
      }
1270
1271
438k
      if (has_second_ref(mbmi)) {
1272
7.04k
        assert(current_frame->reference_mode != SINGLE_REFERENCE &&
1273
7.04k
               is_inter_compound_mode(mbmi->mode) &&
1274
7.04k
               mbmi->motion_mode == SIMPLE_TRANSLATION);
1275
1276
7.04k
        const int masked_compound_used = is_any_masked_compound_used(bsize) &&
1277
7.04k
                                         cm->seq_params->enable_masked_compound;
1278
7.04k
        if (masked_compound_used) {
1279
7.04k
          const int comp_group_idx_ctx = get_comp_group_idx_context(xd);
1280
#if CONFIG_ENTROPY_STATS
1281
          ++counts->comp_group_idx[comp_group_idx_ctx][mbmi->comp_group_idx];
1282
#endif
1283
7.04k
          update_cdf(fc->comp_group_idx_cdf[comp_group_idx_ctx],
1284
7.04k
                     mbmi->comp_group_idx, 2);
1285
7.04k
        }
1286
1287
7.04k
        if (mbmi->comp_group_idx == 0) {
1288
6.66k
          const int comp_index_ctx = get_comp_index_context(cm, xd);
1289
#if CONFIG_ENTROPY_STATS
1290
          ++counts->compound_index[comp_index_ctx][mbmi->compound_idx];
1291
#endif
1292
6.66k
          update_cdf(fc->compound_index_cdf[comp_index_ctx], mbmi->compound_idx,
1293
6.66k
                     2);
1294
6.66k
        } else {
1295
374
          assert(masked_compound_used);
1296
375
          if (is_interinter_compound_used(COMPOUND_WEDGE, bsize)) {
1297
#if CONFIG_ENTROPY_STATS
1298
            ++counts->compound_type[bsize][mbmi->interinter_comp.type -
1299
                                           COMPOUND_WEDGE];
1300
#endif
1301
375
            update_cdf(fc->compound_type_cdf[bsize],
1302
375
                       mbmi->interinter_comp.type - COMPOUND_WEDGE,
1303
375
                       MASKED_COMPOUND_TYPES);
1304
375
          }
1305
374
        }
1306
7.04k
      }
1307
438k
      if (mbmi->interinter_comp.type == COMPOUND_WEDGE) {
1308
0
        if (is_interinter_compound_used(COMPOUND_WEDGE, bsize)) {
1309
#if CONFIG_ENTROPY_STATS
1310
          counts->wedge_idx[bsize][mbmi->interinter_comp.wedge_index]++;
1311
#endif
1312
0
          update_cdf(fc->wedge_idx_cdf[bsize],
1313
0
                     mbmi->interinter_comp.wedge_index, 16);
1314
0
        }
1315
0
      }
1316
438k
    }
1317
1.16M
  }
1318
1319
1.15M
  if (inter_block && cm->features.interp_filter == SWITCHABLE &&
1320
439k
      av1_is_interp_needed(xd)) {
1321
374k
    update_filter_type_cdf(xd, mbmi, cm->seq_params->enable_dual_filter);
1322
374k
  }
1323
1.15M
  if (inter_block &&
1324
439k
      !segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
1325
439k
    const PREDICTION_MODE mode = mbmi->mode;
1326
439k
    const int16_t mode_ctx =
1327
439k
        av1_mode_context_analyzer(mbmi_ext->mode_context, mbmi->ref_frame);
1328
439k
    if (has_second_ref(mbmi)) {
1329
#if CONFIG_ENTROPY_STATS
1330
      ++counts->inter_compound_mode[mode_ctx][INTER_COMPOUND_OFFSET(mode)];
1331
#endif
1332
7.04k
      update_cdf(fc->inter_compound_mode_cdf[mode_ctx],
1333
7.04k
                 INTER_COMPOUND_OFFSET(mode), INTER_COMPOUND_MODES);
1334
432k
    } else {
1335
432k
      av1_update_inter_mode_stats(fc, counts, mode, mode_ctx);
1336
432k
    }
1337
1338
439k
    const int new_mv = mbmi->mode == NEWMV || mbmi->mode == NEW_NEWMV;
1339
439k
    if (new_mv) {
1340
248k
      const uint8_t ref_frame_type = av1_ref_frame_type(mbmi->ref_frame);
1341
498k
      for (int idx = 0; idx < 2; ++idx) {
1342
377k
        if (mbmi_ext->ref_mv_count[ref_frame_type] > idx + 1) {
1343
153k
          const uint8_t drl_ctx =
1344
153k
              av1_drl_ctx(mbmi_ext->weight[ref_frame_type], idx);
1345
153k
          update_cdf(fc->drl_cdf[drl_ctx], mbmi->ref_mv_idx != idx, 2);
1346
#if CONFIG_ENTROPY_STATS
1347
          ++counts->drl_mode[drl_ctx][mbmi->ref_mv_idx != idx];
1348
#endif
1349
153k
          if (mbmi->ref_mv_idx == idx) break;
1350
153k
        }
1351
377k
      }
1352
248k
    }
1353
1354
439k
    if (have_nearmv_in_inter_mode(mbmi->mode)) {
1355
57.6k
      const uint8_t ref_frame_type = av1_ref_frame_type(mbmi->ref_frame);
1356
116k
      for (int idx = 1; idx < 3; ++idx) {
1357
88.7k
        if (mbmi_ext->ref_mv_count[ref_frame_type] > idx + 1) {
1358
39.0k
          const uint8_t drl_ctx =
1359
39.0k
              av1_drl_ctx(mbmi_ext->weight[ref_frame_type], idx);
1360
39.0k
          update_cdf(fc->drl_cdf[drl_ctx], mbmi->ref_mv_idx != idx - 1, 2);
1361
#if CONFIG_ENTROPY_STATS
1362
          ++counts->drl_mode[drl_ctx][mbmi->ref_mv_idx != idx - 1];
1363
#endif
1364
39.0k
          if (mbmi->ref_mv_idx == idx - 1) break;
1365
39.0k
        }
1366
88.7k
      }
1367
57.6k
    }
1368
439k
    if (have_newmv_in_inter_mode(mbmi->mode)) {
1369
248k
      const int allow_hp = cm->features.cur_frame_force_integer_mv
1370
248k
                               ? MV_SUBPEL_NONE
1371
248k
                               : cm->features.allow_high_precision_mv;
1372
248k
      if (new_mv) {
1373
500k
        for (int ref = 0; ref < 1 + has_second_ref(mbmi); ++ref) {
1374
251k
          const int_mv ref_mv = av1_get_ref_mv(x, ref);
1375
251k
          av1_update_mv_stats(&mbmi->mv[ref].as_mv, &ref_mv.as_mv, &fc->nmvc,
1376
251k
                              allow_hp);
1377
251k
        }
1378
248k
      } else if (mbmi->mode == NEAREST_NEWMV || mbmi->mode == NEAR_NEWMV) {
1379
0
        const int ref = 1;
1380
0
        const int_mv ref_mv = av1_get_ref_mv(x, ref);
1381
0
        av1_update_mv_stats(&mbmi->mv[ref].as_mv, &ref_mv.as_mv, &fc->nmvc,
1382
0
                            allow_hp);
1383
22
      } else if (mbmi->mode == NEW_NEARESTMV || mbmi->mode == NEW_NEARMV) {
1384
0
        const int ref = 0;
1385
0
        const int_mv ref_mv = av1_get_ref_mv(x, ref);
1386
0
        av1_update_mv_stats(&mbmi->mv[ref].as_mv, &ref_mv.as_mv, &fc->nmvc,
1387
0
                            allow_hp);
1388
0
      }
1389
248k
    }
1390
439k
  }
1391
1.15M
}
1392
1393
/*!\brief Reconstructs an individual coding block
1394
 *
1395
 * \ingroup partition_search
1396
 * Reconstructs an individual coding block by applying the chosen modes stored
1397
 * in ctx, also updates mode counts and entropy models.
1398
 *
1399
 * \param[in]    cpi       Top-level encoder structure
1400
 * \param[in]    tile_data Pointer to struct holding adaptive
1401
 *                         data/contexts/models for the tile during encoding
1402
 * \param[in]    td        Pointer to thread data
1403
 * \param[in]    tp        Pointer to the starting token
1404
 * \param[in]    mi_row    Row coordinate of the block in a step size of MI_SIZE
1405
 * \param[in]    mi_col    Column coordinate of the block in a step size of
1406
 *                         MI_SIZE
1407
 * \param[in]    dry_run   A code indicating whether it is part of the final
1408
 *                         pass for reconstructing the superblock
1409
 * \param[in]    bsize     Current block size
1410
 * \param[in]    partition Partition mode of the parent block
1411
 * \param[in]    ctx       Pointer to structure holding coding contexts and the
1412
 *                         chosen modes for the current block
1413
 * \param[in]    rate      Pointer to the total rate for the current block
1414
 *
1415
 * \remark Nothing is returned. Instead, reconstructions (w/o in-loop filters)
1416
 * will be updated in the pixel buffers in td->mb.e_mbd. Also, the chosen modes
1417
 * will be stored in the MB_MODE_INFO buffer td->mb.e_mbd.mi[0].
1418
 */
1419
static void encode_b(const AV1_COMP *const cpi, TileDataEnc *tile_data,
1420
                     ThreadData *td, TokenExtra **tp, int mi_row, int mi_col,
1421
                     RUN_TYPE dry_run, BLOCK_SIZE bsize,
1422
                     PARTITION_TYPE partition, PICK_MODE_CONTEXT *const ctx,
1423
31.8M
                     int *rate) {
1424
31.8M
  const AV1_COMMON *const cm = &cpi->common;
1425
31.8M
  TileInfo *const tile = &tile_data->tile_info;
1426
31.8M
  MACROBLOCK *const x = &td->mb;
1427
31.8M
  MACROBLOCKD *xd = &x->e_mbd;
1428
31.8M
  const int subsampling_x = cm->seq_params->subsampling_x;
1429
31.8M
  const int subsampling_y = cm->seq_params->subsampling_y;
1430
1431
31.8M
  av1_set_offsets_without_segment_id(cpi, tile, x, mi_row, mi_col, bsize);
1432
31.8M
  const int origin_mult = x->rdmult;
1433
31.8M
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
1434
31.8M
  MB_MODE_INFO *mbmi = xd->mi[0];
1435
31.8M
  mbmi->partition = partition;
1436
31.8M
  av1_update_state(cpi, td, ctx, mi_row, mi_col, bsize, dry_run);
1437
1438
31.8M
  if (!dry_run) {
1439
6.99M
    set_cb_offsets(x->mbmi_ext_frame->cb_offset, x->cb_offset[PLANE_TYPE_Y],
1440
6.99M
                   x->cb_offset[PLANE_TYPE_UV]);
1441
6.99M
    assert(x->cb_offset[PLANE_TYPE_Y] <
1442
6.99M
           (1 << num_pels_log2_lookup[cpi->common.seq_params->sb_size]));
1443
6.99M
    assert(x->cb_offset[PLANE_TYPE_UV] <
1444
6.99M
           ((1 << num_pels_log2_lookup[cpi->common.seq_params->sb_size]) >>
1445
6.99M
            (subsampling_x + subsampling_y)));
1446
6.99M
  }
1447
1448
31.8M
  encode_superblock(cpi, tile_data, td, tp, dry_run, bsize, rate);
1449
1450
31.8M
  if (!dry_run) {
1451
6.99M
    update_cb_offsets(x, bsize, subsampling_x, subsampling_y);
1452
6.99M
    if (bsize == cpi->common.seq_params->sb_size && mbmi->skip_txfm == 1 &&
1453
219
        cm->delta_q_info.delta_lf_present_flag) {
1454
0
      const int frame_lf_count =
1455
0
          av1_num_planes(cm) > 1 ? FRAME_LF_COUNT : FRAME_LF_COUNT - 2;
1456
0
      for (int lf_id = 0; lf_id < frame_lf_count; ++lf_id)
1457
0
        mbmi->delta_lf[lf_id] = xd->delta_lf[lf_id];
1458
0
      mbmi->delta_lf_from_base = xd->delta_lf_from_base;
1459
0
    }
1460
6.99M
    if (has_second_ref(mbmi)) {
1461
12.4k
      if (mbmi->compound_idx == 0 ||
1462
12.4k
          mbmi->interinter_comp.type == COMPOUND_AVERAGE)
1463
12.0k
        mbmi->comp_group_idx = 0;
1464
376
      else
1465
376
        mbmi->comp_group_idx = 1;
1466
12.4k
    }
1467
1468
    // delta quant applies to both intra and inter
1469
6.99M
    const int super_block_upper_left =
1470
6.99M
        ((mi_row & (cm->seq_params->mib_size - 1)) == 0) &&
1471
1.35M
        ((mi_col & (cm->seq_params->mib_size - 1)) == 0);
1472
6.99M
    const DeltaQInfo *const delta_q_info = &cm->delta_q_info;
1473
6.99M
    if (delta_q_info->delta_q_present_flag &&
1474
3.41M
        (bsize != cm->seq_params->sb_size || !mbmi->skip_txfm) &&
1475
3.41M
        super_block_upper_left) {
1476
179k
      xd->current_base_qindex = mbmi->current_qindex;
1477
179k
      if (delta_q_info->delta_lf_present_flag) {
1478
0
        if (delta_q_info->delta_lf_multi) {
1479
0
          const int frame_lf_count =
1480
0
              av1_num_planes(cm) > 1 ? FRAME_LF_COUNT : FRAME_LF_COUNT - 2;
1481
0
          for (int lf_id = 0; lf_id < frame_lf_count; ++lf_id) {
1482
0
            xd->delta_lf[lf_id] = mbmi->delta_lf[lf_id];
1483
0
          }
1484
0
        } else {
1485
0
          xd->delta_lf_from_base = mbmi->delta_lf_from_base;
1486
0
        }
1487
0
      }
1488
179k
    }
1489
1490
6.99M
    RD_COUNTS *rdc = &td->rd_counts;
1491
6.99M
    if (mbmi->skip_mode) {
1492
5.39k
      assert(!frame_is_intra_only(cm));
1493
5.39k
      rdc->skip_mode_used_flag = 1;
1494
5.39k
      if (cm->current_frame.reference_mode == REFERENCE_MODE_SELECT) {
1495
5.39k
        assert(has_second_ref(mbmi));
1496
5.39k
        rdc->compound_ref_used_flag = 1;
1497
5.39k
      }
1498
5.39k
      set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
1499
6.98M
    } else {
1500
6.98M
      const int seg_ref_active =
1501
6.98M
          segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_REF_FRAME);
1502
6.98M
      if (!seg_ref_active) {
1503
        // If the segment reference feature is enabled we have only a single
1504
        // reference frame allowed for the segment so exclude it from
1505
        // the reference frame counts used to work out probabilities.
1506
6.98M
        if (is_inter_block(mbmi)) {
1507
237k
          av1_collect_neighbors_ref_counts(xd);
1508
237k
          if (cm->current_frame.reference_mode == REFERENCE_MODE_SELECT) {
1509
226k
            if (has_second_ref(mbmi)) {
1510
              // This flag is also updated for 4x4 blocks
1511
7.03k
              rdc->compound_ref_used_flag = 1;
1512
7.03k
            }
1513
226k
          }
1514
237k
          set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
1515
237k
        }
1516
6.98M
      }
1517
6.98M
    }
1518
1519
6.99M
    if (tile_data->allow_update_cdf) update_stats(&cpi->common, td);
1520
1521
    // Gather obmc and warped motion count to update the probability.
1522
6.99M
    if ((cpi->sf.inter_sf.prune_obmc_prob_thresh > 0 &&
1523
1.16M
         cpi->sf.inter_sf.prune_obmc_prob_thresh < INT_MAX) ||
1524
6.99M
        (cm->features.allow_warped_motion &&
1525
818k
         cpi->sf.inter_sf.prune_warped_prob_thresh > 0)) {
1526
0
      const int inter_block = is_inter_block(mbmi);
1527
0
      const int seg_ref_active =
1528
0
          segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_REF_FRAME);
1529
0
      if (!seg_ref_active && inter_block) {
1530
0
        const MOTION_MODE motion_allowed =
1531
0
            cm->features.switchable_motion_mode
1532
0
                ? motion_mode_allowed(xd->global_motion, xd, mbmi,
1533
0
                                      cm->features.allow_warped_motion)
1534
0
                : SIMPLE_TRANSLATION;
1535
1536
0
        if (mbmi->ref_frame[1] != INTRA_FRAME) {
1537
0
          if (motion_allowed >= OBMC_CAUSAL) {
1538
0
            td->rd_counts.obmc_used[bsize][mbmi->motion_mode == OBMC_CAUSAL]++;
1539
0
          }
1540
0
          if (motion_allowed == WARPED_CAUSAL) {
1541
0
            td->rd_counts.warped_used[mbmi->motion_mode == WARPED_CAUSAL]++;
1542
0
          }
1543
0
        }
1544
0
      }
1545
0
    }
1546
6.99M
  }
1547
  // TODO(Ravi/Remya): Move this copy function to a better logical place
1548
  // This function will copy the best mode information from block
1549
  // level (x->mbmi_ext) to frame level (cpi->mbmi_ext_info.frame_base). This
1550
  // frame level buffer (cpi->mbmi_ext_info.frame_base) will be used during
1551
  // bitstream preparation.
1552
31.8M
  av1_copy_mbmi_ext_to_mbmi_ext_frame(x->mbmi_ext_frame, &x->mbmi_ext,
1553
31.8M
                                      av1_ref_frame_type(xd->mi[0]->ref_frame));
1554
31.8M
  x->rdmult = origin_mult;
1555
31.8M
}
1556
1557
/*!\brief Reconstructs a partition (may contain multiple coding blocks)
1558
 *
1559
 * \ingroup partition_search
1560
 * Reconstructs a sub-partition of the superblock by applying the chosen modes
1561
 * and partition trees stored in pc_tree.
1562
 *
1563
 * \param[in]    cpi       Top-level encoder structure
1564
 * \param[in]    td        Pointer to thread data
1565
 * \param[in]    tile_data Pointer to struct holding adaptive
1566
 *                         data/contexts/models for the tile during encoding
1567
 * \param[in]    tp        Pointer to the starting token
1568
 * \param[in]    mi_row    Row coordinate of the block in a step size of MI_SIZE
1569
 * \param[in]    mi_col    Column coordinate of the block in a step size of
1570
 *                         MI_SIZE
1571
 * \param[in]    dry_run   A code indicating whether it is part of the final
1572
 *                         pass for reconstructing the superblock
1573
 * \param[in]    bsize     Current block size
1574
 * \param[in]    pc_tree   Pointer to the PC_TREE node storing the picked
1575
 *                         partitions and mode info for the current block
1576
 * \param[in]    rate      Pointer to the total rate for the current block
1577
 *
1578
 * \remark Nothing is returned. Instead, reconstructions (w/o in-loop filters)
1579
 * will be updated in the pixel buffers in td->mb.e_mbd.
1580
 */
1581
static void encode_sb(const AV1_COMP *const cpi, ThreadData *td,
1582
                      TileDataEnc *tile_data, TokenExtra **tp, int mi_row,
1583
                      int mi_col, RUN_TYPE dry_run, BLOCK_SIZE bsize,
1584
43.2M
                      PC_TREE *pc_tree, int *rate) {
1585
43.2M
  assert(bsize < BLOCK_SIZES_ALL);
1586
43.2M
  const AV1_COMMON *const cm = &cpi->common;
1587
43.2M
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
1588
43.2M
  MACROBLOCK *const x = &td->mb;
1589
43.2M
  MACROBLOCKD *const xd = &x->e_mbd;
1590
43.2M
  assert(bsize < BLOCK_SIZES_ALL);
1591
43.2M
  const int hbs = mi_size_wide[bsize] / 2;
1592
43.2M
  const int is_partition_root = bsize >= BLOCK_8X8;
1593
43.2M
  const int ctx = is_partition_root
1594
43.2M
                      ? partition_plane_context(xd, mi_row, mi_col, bsize)
1595
43.2M
                      : -1;
1596
43.2M
  const PARTITION_TYPE partition = pc_tree->partitioning;
1597
43.2M
  const BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
1598
43.2M
#if !CONFIG_REALTIME_ONLY
1599
43.2M
  int quarter_step = mi_size_wide[bsize] / 4;
1600
43.2M
  int i;
1601
43.2M
  BLOCK_SIZE bsize2 = get_partition_subsize(bsize, PARTITION_SPLIT);
1602
43.2M
#endif
1603
1604
43.2M
  if (mi_row >= mi_params->mi_rows || mi_col >= mi_params->mi_cols) return;
1605
38.9M
  if (subsize == BLOCK_INVALID) return;
1606
1607
38.9M
  if (!dry_run && ctx >= 0) {
1608
7.25M
    const int has_rows = (mi_row + hbs) < mi_params->mi_rows;
1609
7.25M
    const int has_cols = (mi_col + hbs) < mi_params->mi_cols;
1610
1611
7.25M
    if (has_rows && has_cols) {
1612
#if CONFIG_ENTROPY_STATS
1613
      td->counts->partition[ctx][partition]++;
1614
#endif
1615
1616
6.19M
      if (tile_data->allow_update_cdf) {
1617
6.19M
        FRAME_CONTEXT *fc = xd->tile_ctx;
1618
6.19M
        update_cdf(fc->partition_cdf[ctx], partition,
1619
6.19M
                   partition_cdf_length(bsize));
1620
6.19M
      }
1621
6.19M
    }
1622
7.25M
  }
1623
1624
38.9M
  switch (partition) {
1625
31.0M
    case PARTITION_NONE:
1626
31.0M
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col, dry_run, subsize,
1627
31.0M
               partition, pc_tree->none, rate);
1628
31.0M
      break;
1629
279k
    case PARTITION_VERT:
1630
279k
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col, dry_run, subsize,
1631
279k
               partition, pc_tree->vertical[0], rate);
1632
279k
      if (mi_col + hbs < mi_params->mi_cols) {
1633
92.1k
        encode_b(cpi, tile_data, td, tp, mi_row, mi_col + hbs, dry_run, subsize,
1634
92.1k
                 partition, pc_tree->vertical[1], rate);
1635
92.1k
      }
1636
279k
      break;
1637
336k
    case PARTITION_HORZ:
1638
336k
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col, dry_run, subsize,
1639
336k
               partition, pc_tree->horizontal[0], rate);
1640
336k
      if (mi_row + hbs < mi_params->mi_rows) {
1641
133k
        encode_b(cpi, tile_data, td, tp, mi_row + hbs, mi_col, dry_run, subsize,
1642
133k
                 partition, pc_tree->horizontal[1], rate);
1643
133k
      }
1644
336k
      break;
1645
7.33M
    case PARTITION_SPLIT:
1646
7.33M
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, dry_run, subsize,
1647
7.33M
                pc_tree->split[0], rate);
1648
7.33M
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col + hbs, dry_run, subsize,
1649
7.33M
                pc_tree->split[1], rate);
1650
7.33M
      encode_sb(cpi, td, tile_data, tp, mi_row + hbs, mi_col, dry_run, subsize,
1651
7.33M
                pc_tree->split[2], rate);
1652
7.33M
      encode_sb(cpi, td, tile_data, tp, mi_row + hbs, mi_col + hbs, dry_run,
1653
7.33M
                subsize, pc_tree->split[3], rate);
1654
7.33M
      break;
1655
1656
0
#if !CONFIG_REALTIME_ONLY
1657
0
    case PARTITION_HORZ_A:
1658
0
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col, dry_run, bsize2,
1659
0
               partition, pc_tree->horizontala[0], rate);
1660
0
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col + hbs, dry_run, bsize2,
1661
0
               partition, pc_tree->horizontala[1], rate);
1662
0
      encode_b(cpi, tile_data, td, tp, mi_row + hbs, mi_col, dry_run, subsize,
1663
0
               partition, pc_tree->horizontala[2], rate);
1664
0
      break;
1665
0
    case PARTITION_HORZ_B:
1666
0
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col, dry_run, subsize,
1667
0
               partition, pc_tree->horizontalb[0], rate);
1668
0
      encode_b(cpi, tile_data, td, tp, mi_row + hbs, mi_col, dry_run, bsize2,
1669
0
               partition, pc_tree->horizontalb[1], rate);
1670
0
      encode_b(cpi, tile_data, td, tp, mi_row + hbs, mi_col + hbs, dry_run,
1671
0
               bsize2, partition, pc_tree->horizontalb[2], rate);
1672
0
      break;
1673
0
    case PARTITION_VERT_A:
1674
0
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col, dry_run, bsize2,
1675
0
               partition, pc_tree->verticala[0], rate);
1676
0
      encode_b(cpi, tile_data, td, tp, mi_row + hbs, mi_col, dry_run, bsize2,
1677
0
               partition, pc_tree->verticala[1], rate);
1678
0
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col + hbs, dry_run, subsize,
1679
0
               partition, pc_tree->verticala[2], rate);
1680
1681
0
      break;
1682
0
    case PARTITION_VERT_B:
1683
0
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col, dry_run, subsize,
1684
0
               partition, pc_tree->verticalb[0], rate);
1685
0
      encode_b(cpi, tile_data, td, tp, mi_row, mi_col + hbs, dry_run, bsize2,
1686
0
               partition, pc_tree->verticalb[1], rate);
1687
0
      encode_b(cpi, tile_data, td, tp, mi_row + hbs, mi_col + hbs, dry_run,
1688
0
               bsize2, partition, pc_tree->verticalb[2], rate);
1689
0
      break;
1690
0
    case PARTITION_HORZ_4:
1691
0
      for (i = 0; i < SUB_PARTITIONS_PART4; ++i) {
1692
0
        int this_mi_row = mi_row + i * quarter_step;
1693
0
        if (i > 0 && this_mi_row >= mi_params->mi_rows) break;
1694
1695
0
        encode_b(cpi, tile_data, td, tp, this_mi_row, mi_col, dry_run, subsize,
1696
0
                 partition, pc_tree->horizontal4[i], rate);
1697
0
      }
1698
0
      break;
1699
0
    case PARTITION_VERT_4:
1700
0
      for (i = 0; i < SUB_PARTITIONS_PART4; ++i) {
1701
0
        int this_mi_col = mi_col + i * quarter_step;
1702
0
        if (i > 0 && this_mi_col >= mi_params->mi_cols) break;
1703
0
        encode_b(cpi, tile_data, td, tp, mi_row, this_mi_col, dry_run, subsize,
1704
0
                 partition, pc_tree->vertical4[i], rate);
1705
0
      }
1706
0
      break;
1707
0
#endif
1708
0
    default: assert(0 && "Invalid partition type."); break;
1709
38.9M
  }
1710
1711
38.9M
  update_ext_partition_context(xd, mi_row, mi_col, subsize, bsize, partition);
1712
38.9M
}
1713
1714
static inline int is_adjust_var_based_part_enabled(
1715
    AV1_COMMON *const cm, const PARTITION_SPEED_FEATURES *const part_sf,
1716
633k
    BLOCK_SIZE bsize) {
1717
633k
  if (part_sf->partition_search_type != VAR_BASED_PARTITION) return 0;
1718
633k
  if (part_sf->adjust_var_based_rd_partitioning == 0 ||
1719
0
      part_sf->adjust_var_based_rd_partitioning > 2)
1720
633k
    return 0;
1721
1722
18.4E
  if (bsize <= BLOCK_32X32) return 1;
1723
18.4E
  if (part_sf->adjust_var_based_rd_partitioning == 2) {
1724
0
    const int is_larger_qindex = cm->quant_params.base_qindex > 190;
1725
0
    const int is_360p_or_larger = AOMMIN(cm->width, cm->height) >= 360;
1726
0
    return is_360p_or_larger && is_larger_qindex && bsize == BLOCK_64X64;
1727
0
  }
1728
18.4E
  return 0;
1729
18.4E
}
1730
1731
/*!\brief AV1 block partition search (partition estimation and partial search).
1732
*
1733
* \ingroup partition_search
1734
* Encode the block by applying pre-calculated partition patterns that are
1735
* represented by coding block sizes stored in the mbmi array. Minor partition
1736
* adjustments are tested and applied if they lead to lower rd costs. The
1737
* partition types are limited to a basic set: none, horz, vert, and split.
1738
*
1739
* \param[in]    cpi       Top-level encoder structure
1740
* \param[in]    td        Pointer to thread data
1741
* \param[in]    tile_data Pointer to struct holding adaptive
1742
data/contexts/models for the tile during encoding
1743
* \param[in]    mib       Array representing MB_MODE_INFO pointers for mi
1744
blocks starting from the first pixel of the current
1745
block
1746
* \param[in]    tp        Pointer to the starting token
1747
* \param[in]    mi_row    Row coordinate of the block in a step size of MI_SIZE
1748
* \param[in]    mi_col    Column coordinate of the block in a step size of
1749
MI_SIZE
1750
* \param[in]    bsize     Current block size
1751
* \param[in]    rate      Pointer to the final rate for encoding the current
1752
block
1753
* \param[in]    dist      Pointer to the final distortion of the current block
1754
* \param[in]    do_recon  Whether the reconstruction function needs to be run,
1755
either for finalizing a superblock or providing
1756
reference for future sub-partitions
1757
* \param[in]    pc_tree   Pointer to the PC_TREE node holding the picked
1758
partitions and mode info for the current block
1759
*
1760
* \remark Nothing is returned. The pc_tree struct is modified to store the
1761
* picked partition and modes. The rate and dist are also updated with those
1762
* corresponding to the best partition found.
1763
*/
1764
void av1_rd_use_partition(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data,
1765
                          MB_MODE_INFO **mib, TokenExtra **tp, int mi_row,
1766
                          int mi_col, BLOCK_SIZE bsize, int *rate,
1767
2.29M
                          int64_t *dist, int do_recon, PC_TREE *pc_tree) {
1768
2.29M
  AV1_COMMON *const cm = &cpi->common;
1769
2.29M
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
1770
2.29M
  const int num_planes = av1_num_planes(cm);
1771
2.29M
  TileInfo *const tile_info = &tile_data->tile_info;
1772
2.29M
  MACROBLOCK *const x = &td->mb;
1773
2.29M
  MACROBLOCKD *const xd = &x->e_mbd;
1774
2.29M
  const ModeCosts *mode_costs = &x->mode_costs;
1775
2.29M
  const int bs = mi_size_wide[bsize];
1776
2.29M
  const int hbs = bs / 2;
1777
2.29M
  const int pl = (bsize >= BLOCK_8X8)
1778
2.29M
                     ? partition_plane_context(xd, mi_row, mi_col, bsize)
1779
2.29M
                     : 0;
1780
2.29M
  const PARTITION_TYPE partition =
1781
2.29M
      (bsize >= BLOCK_8X8) ? get_partition(cm, mi_row, mi_col, bsize)
1782
2.29M
                           : PARTITION_NONE;
1783
2.29M
  const BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
1784
2.29M
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
1785
2.29M
  RD_STATS last_part_rdc, none_rdc, chosen_rdc, invalid_rdc;
1786
2.29M
  BLOCK_SIZE bs_type = mib[0]->bsize;
1787
2.29M
  int use_partition_none = 0;
1788
2.29M
  x->try_merge_partition = 0;
1789
1790
2.29M
  if (pc_tree->none == NULL) {
1791
2.29M
    pc_tree->none = av1_alloc_pmc(cpi, bsize, &td->shared_coeff_buf);
1792
2.29M
    if (!pc_tree->none)
1793
0
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
1794
0
                         "Failed to allocate PICK_MODE_CONTEXT");
1795
2.29M
  }
1796
2.29M
  PICK_MODE_CONTEXT *ctx_none = pc_tree->none;
1797
1798
2.29M
  if (mi_row >= mi_params->mi_rows || mi_col >= mi_params->mi_cols) return;
1799
1800
2.29M
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);
1801
  // In rt mode, currently the min partition size is BLOCK_8X8.
1802
2.29M
  assert(bsize >= cpi->sf.part_sf.default_min_partition_size);
1803
1804
2.29M
  av1_invalid_rd_stats(&last_part_rdc);
1805
2.29M
  av1_invalid_rd_stats(&none_rdc);
1806
2.29M
  av1_invalid_rd_stats(&chosen_rdc);
1807
2.29M
  av1_invalid_rd_stats(&invalid_rdc);
1808
1809
2.29M
  pc_tree->partitioning = partition;
1810
1811
2.29M
  xd->above_txfm_context =
1812
2.29M
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
1813
2.29M
  xd->left_txfm_context =
1814
2.29M
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
1815
2.29M
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
1816
1817
2.29M
  if (bsize == BLOCK_16X16 && cpi->vaq_refresh) {
1818
0
    av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1819
0
    x->mb_energy = av1_log_block_var(cpi, x, bsize);
1820
0
  }
1821
1822
  // Save rdmult before it might be changed, so it can be restored later.
1823
2.29M
  const int orig_rdmult = x->rdmult;
1824
2.29M
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
1825
1826
2.29M
  if (partition != PARTITION_NONE &&
1827
633k
      is_adjust_var_based_part_enabled(cm, &cpi->sf.part_sf, bsize) &&
1828
0
      (mi_row + hbs < mi_params->mi_rows &&
1829
0
       mi_col + hbs < mi_params->mi_cols)) {
1830
0
    assert(bsize > cpi->sf.part_sf.default_min_partition_size);
1831
0
    mib[0]->bsize = bsize;
1832
0
    pc_tree->partitioning = PARTITION_NONE;
1833
0
    x->try_merge_partition = 1;
1834
0
    pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, PARTITION_NONE,
1835
0
                  bsize, ctx_none, invalid_rdc);
1836
1837
0
    if (none_rdc.rate < INT_MAX) {
1838
0
      none_rdc.rate += mode_costs->partition_cost[pl][PARTITION_NONE];
1839
0
      none_rdc.rdcost = RDCOST(x->rdmult, none_rdc.rate, none_rdc.dist);
1840
0
    }
1841
1842
    // Try to skip split partition evaluation based on none partition
1843
    // characteristics.
1844
0
    if (none_rdc.rate < INT_MAX && none_rdc.skip_txfm == 1) {
1845
0
      use_partition_none = 1;
1846
0
    }
1847
1848
0
    av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
1849
0
    mib[0]->bsize = bs_type;
1850
0
    pc_tree->partitioning = partition;
1851
0
  }
1852
1853
11.4M
  for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
1854
9.17M
    pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
1855
9.17M
    if (!pc_tree->split[i])
1856
0
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
1857
0
                         "Failed to allocate PC_TREE");
1858
9.17M
    pc_tree->split[i]->index = i;
1859
9.17M
  }
1860
2.29M
  switch (partition) {
1861
1.66M
    case PARTITION_NONE:
1862
1.66M
      pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1863
1.66M
                    PARTITION_NONE, bsize, ctx_none, invalid_rdc);
1864
1.66M
      break;
1865
1.32k
    case PARTITION_HORZ:
1866
1.32k
      if (use_partition_none) {
1867
0
        av1_invalid_rd_stats(&last_part_rdc);
1868
0
        break;
1869
0
      }
1870
1871
3.97k
      for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1872
2.65k
        pc_tree->horizontal[i] =
1873
2.65k
            av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
1874
2.65k
        if (!pc_tree->horizontal[i])
1875
0
          aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
1876
0
                             "Failed to allocate PICK_MODE_CONTEXT");
1877
2.65k
      }
1878
1.32k
      pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1879
1.32k
                    PARTITION_HORZ, subsize, pc_tree->horizontal[0],
1880
1.32k
                    invalid_rdc);
1881
1.32k
      if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
1882
1.32k
          mi_row + hbs < mi_params->mi_rows) {
1883
8
        RD_STATS tmp_rdc;
1884
8
        const PICK_MODE_CONTEXT *const ctx_h = pc_tree->horizontal[0];
1885
8
        av1_init_rd_stats(&tmp_rdc);
1886
8
        av1_update_state(cpi, td, ctx_h, mi_row, mi_col, subsize, 1);
1887
8
        encode_superblock(cpi, tile_data, td, tp, DRY_RUN_NORMAL, subsize,
1888
8
                          NULL);
1889
8
        pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, &tmp_rdc,
1890
8
                      PARTITION_HORZ, subsize, pc_tree->horizontal[1],
1891
8
                      invalid_rdc);
1892
8
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1893
0
          av1_invalid_rd_stats(&last_part_rdc);
1894
0
          break;
1895
0
        }
1896
8
        last_part_rdc.rate += tmp_rdc.rate;
1897
8
        last_part_rdc.dist += tmp_rdc.dist;
1898
8
        last_part_rdc.rdcost += tmp_rdc.rdcost;
1899
8
      }
1900
1.32k
      break;
1901
1.32k
    case PARTITION_VERT:
1902
1.08k
      if (use_partition_none) {
1903
0
        av1_invalid_rd_stats(&last_part_rdc);
1904
0
        break;
1905
0
      }
1906
1907
3.25k
      for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
1908
2.17k
        pc_tree->vertical[i] =
1909
2.17k
            av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
1910
2.17k
        if (!pc_tree->vertical[i])
1911
0
          aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
1912
0
                             "Failed to allocate PICK_MODE_CONTEXT");
1913
2.17k
      }
1914
1.08k
      pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1915
1.08k
                    PARTITION_VERT, subsize, pc_tree->vertical[0], invalid_rdc);
1916
1.08k
      if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
1917
1.08k
          mi_col + hbs < mi_params->mi_cols) {
1918
25
        RD_STATS tmp_rdc;
1919
25
        const PICK_MODE_CONTEXT *const ctx_v = pc_tree->vertical[0];
1920
25
        av1_init_rd_stats(&tmp_rdc);
1921
25
        av1_update_state(cpi, td, ctx_v, mi_row, mi_col, subsize, 1);
1922
25
        encode_superblock(cpi, tile_data, td, tp, DRY_RUN_NORMAL, subsize,
1923
25
                          NULL);
1924
25
        pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, &tmp_rdc,
1925
25
                      PARTITION_VERT, subsize,
1926
25
                      pc_tree->vertical[bsize > BLOCK_8X8], invalid_rdc);
1927
25
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1928
0
          av1_invalid_rd_stats(&last_part_rdc);
1929
0
          break;
1930
0
        }
1931
25
        last_part_rdc.rate += tmp_rdc.rate;
1932
25
        last_part_rdc.dist += tmp_rdc.dist;
1933
25
        last_part_rdc.rdcost += tmp_rdc.rdcost;
1934
25
      }
1935
1.08k
      break;
1936
631k
    case PARTITION_SPLIT:
1937
631k
      if (use_partition_none) {
1938
0
        av1_invalid_rd_stats(&last_part_rdc);
1939
0
        break;
1940
0
      }
1941
1942
631k
      last_part_rdc.rate = 0;
1943
631k
      last_part_rdc.dist = 0;
1944
631k
      last_part_rdc.rdcost = 0;
1945
3.15M
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
1946
2.52M
        int x_idx = (i & 1) * hbs;
1947
2.52M
        int y_idx = (i >> 1) * hbs;
1948
2.52M
        int jj = i >> 1, ii = i & 0x01;
1949
2.52M
        RD_STATS tmp_rdc;
1950
2.52M
        if ((mi_row + y_idx >= mi_params->mi_rows) ||
1951
2.37M
            (mi_col + x_idx >= mi_params->mi_cols))
1952
278k
          continue;
1953
1954
2.24M
        av1_init_rd_stats(&tmp_rdc);
1955
2.24M
        av1_rd_use_partition(
1956
2.24M
            cpi, td, tile_data,
1957
2.24M
            mib + jj * hbs * mi_params->mi_stride + ii * hbs, tp,
1958
2.24M
            mi_row + y_idx, mi_col + x_idx, subsize, &tmp_rdc.rate,
1959
2.24M
            &tmp_rdc.dist, i != (SUB_PARTITIONS_SPLIT - 1), pc_tree->split[i]);
1960
2.24M
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1961
0
          av1_invalid_rd_stats(&last_part_rdc);
1962
0
          break;
1963
0
        }
1964
2.24M
        last_part_rdc.rate += tmp_rdc.rate;
1965
2.24M
        last_part_rdc.dist += tmp_rdc.dist;
1966
2.24M
      }
1967
631k
      break;
1968
0
    case PARTITION_VERT_A:
1969
0
    case PARTITION_VERT_B:
1970
0
    case PARTITION_HORZ_A:
1971
0
    case PARTITION_HORZ_B:
1972
0
    case PARTITION_HORZ_4:
1973
0
    case PARTITION_VERT_4:
1974
0
      assert(0 && "Cannot handle extended partition types");
1975
0
    default: assert(0); break;
1976
2.29M
  }
1977
1978
2.29M
  if (last_part_rdc.rate < INT_MAX) {
1979
2.29M
    last_part_rdc.rate += mode_costs->partition_cost[pl][partition];
1980
2.29M
    last_part_rdc.rdcost =
1981
2.29M
        RDCOST(x->rdmult, last_part_rdc.rate, last_part_rdc.dist);
1982
2.29M
  }
1983
1984
2.29M
  if ((cpi->sf.part_sf.partition_search_type == VAR_BASED_PARTITION &&
1985
2.29M
       cpi->sf.part_sf.adjust_var_based_rd_partitioning > 2) &&
1986
0
      partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
1987
0
      (mi_row + bs < mi_params->mi_rows ||
1988
0
       mi_row + hbs == mi_params->mi_rows) &&
1989
0
      (mi_col + bs < mi_params->mi_cols ||
1990
0
       mi_col + hbs == mi_params->mi_cols)) {
1991
0
    BLOCK_SIZE split_subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
1992
0
    chosen_rdc.rate = 0;
1993
0
    chosen_rdc.dist = 0;
1994
1995
0
    av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
1996
0
    pc_tree->partitioning = PARTITION_SPLIT;
1997
1998
    // Split partition.
1999
0
    for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
2000
0
      int x_idx = (i & 1) * hbs;
2001
0
      int y_idx = (i >> 1) * hbs;
2002
0
      RD_STATS tmp_rdc;
2003
2004
0
      if ((mi_row + y_idx >= mi_params->mi_rows) ||
2005
0
          (mi_col + x_idx >= mi_params->mi_cols))
2006
0
        continue;
2007
2008
0
      av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
2009
0
      pc_tree->split[i]->partitioning = PARTITION_NONE;
2010
0
      if (pc_tree->split[i]->none == NULL)
2011
0
        pc_tree->split[i]->none =
2012
0
            av1_alloc_pmc(cpi, split_subsize, &td->shared_coeff_buf);
2013
0
      if (!pc_tree->split[i]->none)
2014
0
        aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2015
0
                           "Failed to allocate PICK_MODE_CONTEXT");
2016
0
      pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx, &tmp_rdc,
2017
0
                    PARTITION_SPLIT, split_subsize, pc_tree->split[i]->none,
2018
0
                    invalid_rdc);
2019
2020
0
      av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
2021
0
      if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2022
0
        av1_invalid_rd_stats(&chosen_rdc);
2023
0
        break;
2024
0
      }
2025
2026
0
      chosen_rdc.rate += tmp_rdc.rate;
2027
0
      chosen_rdc.dist += tmp_rdc.dist;
2028
2029
0
      if (i != SUB_PARTITIONS_SPLIT - 1)
2030
0
        encode_sb(cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx,
2031
0
                  OUTPUT_ENABLED, split_subsize, pc_tree->split[i], NULL);
2032
2033
0
      chosen_rdc.rate += mode_costs->partition_cost[pl][PARTITION_NONE];
2034
0
    }
2035
0
    if (chosen_rdc.rate < INT_MAX) {
2036
0
      chosen_rdc.rate += mode_costs->partition_cost[pl][PARTITION_SPLIT];
2037
0
      chosen_rdc.rdcost = RDCOST(x->rdmult, chosen_rdc.rate, chosen_rdc.dist);
2038
0
    }
2039
0
  }
2040
2041
  // If last_part is better set the partitioning to that.
2042
2.29M
  if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2043
2.29M
    mib[0]->bsize = bs_type;
2044
2.29M
    if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2045
2046
2.29M
    chosen_rdc = last_part_rdc;
2047
2.29M
  }
2048
  // If none was better set the partitioning to that.
2049
2.29M
  if (none_rdc.rdcost < INT64_MAX &&
2050
0
      none_rdc.rdcost - (none_rdc.rdcost >> 9) < chosen_rdc.rdcost) {
2051
0
    mib[0]->bsize = bsize;
2052
0
    if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2053
0
    chosen_rdc = none_rdc;
2054
0
  }
2055
2056
2.29M
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
2057
2058
  // We must have chosen a partitioning and encoding or we'll fail later on.
2059
  // No other opportunities for success.
2060
2.29M
  if (bsize == cm->seq_params->sb_size)
2061
2.29M
    assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2062
2063
#if CONFIG_COLLECT_COMPONENT_TIMING
2064
  start_timing(cpi, encode_sb_time);
2065
#endif
2066
2.29M
  if (do_recon) {
2067
1.79M
    if (bsize == cm->seq_params->sb_size) {
2068
      // NOTE: To get estimate for rate due to the tokens, use:
2069
      // int rate_coeffs = 0;
2070
      // encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_COSTCOEFFS,
2071
      //           bsize, pc_tree, &rate_coeffs);
2072
48.2k
      set_cb_offsets(x->cb_offset, 0, 0);
2073
48.2k
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
2074
48.2k
                pc_tree, NULL);
2075
1.74M
    } else {
2076
1.74M
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_NORMAL, bsize,
2077
1.74M
                pc_tree, NULL);
2078
1.74M
    }
2079
1.79M
  }
2080
#if CONFIG_COLLECT_COMPONENT_TIMING
2081
  end_timing(cpi, encode_sb_time);
2082
#endif
2083
2084
2.29M
  *rate = chosen_rdc.rate;
2085
2.29M
  *dist = chosen_rdc.dist;
2086
2.29M
  x->rdmult = orig_rdmult;
2087
2.29M
}
2088
2089
static void encode_b_nonrd(const AV1_COMP *const cpi, TileDataEnc *tile_data,
2090
                           ThreadData *td, TokenExtra **tp, int mi_row,
2091
                           int mi_col, RUN_TYPE dry_run, BLOCK_SIZE bsize,
2092
                           PARTITION_TYPE partition,
2093
4.10M
                           PICK_MODE_CONTEXT *const ctx, int *rate) {
2094
#if CONFIG_COLLECT_COMPONENT_TIMING
2095
  start_timing((AV1_COMP *)cpi, encode_b_nonrd_time);
2096
#endif
2097
4.10M
  const AV1_COMMON *const cm = &cpi->common;
2098
4.10M
  TileInfo *const tile = &tile_data->tile_info;
2099
4.10M
  MACROBLOCK *const x = &td->mb;
2100
4.10M
  MACROBLOCKD *xd = &x->e_mbd;
2101
4.10M
  av1_set_offsets_without_segment_id(cpi, tile, x, mi_row, mi_col, bsize);
2102
4.10M
  const int origin_mult = x->rdmult;
2103
4.10M
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
2104
4.10M
  MB_MODE_INFO *mbmi = xd->mi[0];
2105
4.10M
  mbmi->partition = partition;
2106
4.10M
  av1_update_state(cpi, td, ctx, mi_row, mi_col, bsize, dry_run);
2107
4.10M
  const int subsampling_x = cpi->common.seq_params->subsampling_x;
2108
4.10M
  const int subsampling_y = cpi->common.seq_params->subsampling_y;
2109
4.10M
  if (!dry_run) {
2110
3.94M
    set_cb_offsets(x->mbmi_ext_frame->cb_offset, x->cb_offset[PLANE_TYPE_Y],
2111
3.94M
                   x->cb_offset[PLANE_TYPE_UV]);
2112
3.94M
    assert(x->cb_offset[PLANE_TYPE_Y] <
2113
3.94M
           (1 << num_pels_log2_lookup[cpi->common.seq_params->sb_size]));
2114
3.94M
    assert(x->cb_offset[PLANE_TYPE_UV] <
2115
3.94M
           ((1 << num_pels_log2_lookup[cpi->common.seq_params->sb_size]) >>
2116
3.94M
            (subsampling_x + subsampling_y)));
2117
3.94M
  }
2118
2119
4.10M
  if (!is_inter_block(xd->mi[0])) xd->mi[0]->skip_txfm = 0;
2120
4.10M
  encode_superblock(cpi, tile_data, td, tp, dry_run, bsize, rate);
2121
4.10M
  if (!dry_run) {
2122
3.95M
    update_cb_offsets(x, bsize, subsampling_x, subsampling_y);
2123
3.95M
    if (has_second_ref(mbmi)) {
2124
3
      if (mbmi->compound_idx == 0 ||
2125
3
          mbmi->interinter_comp.type == COMPOUND_AVERAGE)
2126
3
        mbmi->comp_group_idx = 0;
2127
0
      else
2128
0
        mbmi->comp_group_idx = 1;
2129
3
      mbmi->compound_idx = 1;
2130
3
    }
2131
3.95M
    RD_COUNTS *const rdc = &td->rd_counts;
2132
3.95M
    if (mbmi->skip_mode) {
2133
0
      assert(!frame_is_intra_only(cm));
2134
0
      rdc->skip_mode_used_flag = 1;
2135
0
      if (cm->current_frame.reference_mode == REFERENCE_MODE_SELECT &&
2136
0
          has_second_ref(mbmi)) {
2137
0
        rdc->compound_ref_used_flag = 1;
2138
0
      }
2139
0
      set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
2140
3.95M
    } else {
2141
3.95M
      const int seg_ref_active =
2142
3.95M
          segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_REF_FRAME);
2143
3.95M
      if (!seg_ref_active) {
2144
        // If the segment reference feature is enabled we have only a single
2145
        // reference frame allowed for the segment so exclude it from
2146
        // the reference frame counts used to work out probabilities.
2147
3.94M
        if (is_inter_block(mbmi)) {
2148
212k
          av1_collect_neighbors_ref_counts(xd);
2149
212k
          if (cm->current_frame.reference_mode == REFERENCE_MODE_SELECT &&
2150
189k
              has_second_ref(mbmi)) {
2151
            // This flag is also updated for 4x4 blocks
2152
3
            rdc->compound_ref_used_flag = 1;
2153
3
          }
2154
212k
          set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
2155
212k
        }
2156
3.94M
      }
2157
3.95M
    }
2158
3.95M
    if (cpi->oxcf.algo_cfg.loopfilter_control == LOOPFILTER_SELECTIVELY &&
2159
0
        (mbmi->mode == NEWMV || mbmi->mode < INTRA_MODE_END)) {
2160
0
      int32_t blocks = mi_size_high[bsize] * mi_size_wide[bsize];
2161
0
      rdc->newmv_or_intra_blocks += blocks;
2162
0
    }
2163
3.95M
    if (tile_data->allow_update_cdf) update_stats(&cpi->common, td);
2164
3.95M
  }
2165
4.10M
  if ((cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ ||
2166
4.09M
       cpi->active_map.enabled || cpi->roi.enabled) &&
2167
0
      mbmi->skip_txfm && !cpi->rc.rtc_external_ratectrl && cm->seg.enabled)
2168
0
    av1_cyclic_reset_segment_skip(cpi, x, mi_row, mi_col, bsize, dry_run);
2169
  // TODO(Ravi/Remya): Move this copy function to a better logical place
2170
  // This function will copy the best mode information from block
2171
  // level (x->mbmi_ext) to frame level (cpi->mbmi_ext_info.frame_base). This
2172
  // frame level buffer (cpi->mbmi_ext_info.frame_base) will be used during
2173
  // bitstream preparation.
2174
4.10M
  av1_copy_mbmi_ext_to_mbmi_ext_frame(x->mbmi_ext_frame, &x->mbmi_ext,
2175
4.10M
                                      av1_ref_frame_type(xd->mi[0]->ref_frame));
2176
4.10M
  x->rdmult = origin_mult;
2177
#if CONFIG_COLLECT_COMPONENT_TIMING
2178
  end_timing((AV1_COMP *)cpi, encode_b_nonrd_time);
2179
#endif
2180
4.10M
}
2181
2182
static int get_force_zeromv_skip_flag_for_blk(const AV1_COMP *cpi,
2183
                                              const MACROBLOCK *x,
2184
4.07M
                                              BLOCK_SIZE bsize) {
2185
  // Force zero MV skip based on SB level decision
2186
4.07M
  if (x->force_zeromv_skip_for_sb < 2) return x->force_zeromv_skip_for_sb;
2187
2188
  // For blocks of size equal to superblock size, the decision would have been
2189
  // already done at superblock level. Hence zeromv-skip decision is skipped.
2190
18.4E
  const AV1_COMMON *const cm = &cpi->common;
2191
18.4E
  if (bsize == cm->seq_params->sb_size) return 0;
2192
2193
18.4E
  const int num_planes = av1_num_planes(cm);
2194
18.4E
  const MACROBLOCKD *const xd = &x->e_mbd;
2195
18.4E
  const unsigned int thresh_exit_part_y =
2196
18.4E
      cpi->zeromv_skip_thresh_exit_part[bsize];
2197
18.4E
  const unsigned int thresh_exit_part_uv =
2198
18.4E
      CALC_CHROMA_THRESH_FOR_ZEROMV_SKIP(thresh_exit_part_y);
2199
18.4E
  const unsigned int thresh_exit_part[MAX_MB_PLANE] = { thresh_exit_part_y,
2200
18.4E
                                                        thresh_exit_part_uv,
2201
18.4E
                                                        thresh_exit_part_uv };
2202
18.4E
  const YV12_BUFFER_CONFIG *const yv12 = get_ref_frame_yv12_buf(cm, LAST_FRAME);
2203
18.4E
  const struct scale_factors *const sf =
2204
18.4E
      get_ref_scale_factors_const(cm, LAST_FRAME);
2205
2206
18.4E
  struct buf_2d yv12_mb[MAX_MB_PLANE];
2207
18.4E
  av1_setup_pred_block(xd, yv12_mb, yv12, sf, sf, num_planes);
2208
2209
18.4E
  for (int plane = 0; plane < num_planes; ++plane) {
2210
0
    const struct macroblock_plane *const p = &x->plane[plane];
2211
0
    const struct macroblockd_plane *const pd = &xd->plane[plane];
2212
0
    const BLOCK_SIZE bs =
2213
0
        get_plane_block_size(bsize, pd->subsampling_x, pd->subsampling_y);
2214
0
    const unsigned int plane_sad = cpi->ppi->fn_ptr[bs].sdf(
2215
0
        p->src.buf, p->src.stride, yv12_mb[plane].buf, yv12_mb[plane].stride);
2216
0
    assert(plane < MAX_MB_PLANE);
2217
0
    if (plane_sad >= thresh_exit_part[plane]) return 0;
2218
0
  }
2219
18.4E
  return 1;
2220
18.4E
}
2221
2222
/*!\brief Top level function to pick block mode for non-RD optimized case
2223
 *
2224
 * \ingroup partition_search
2225
 * \callgraph
2226
 * \callergraph
2227
 * Searches prediction modes, transform, and coefficient coding modes for an
2228
 * individual coding block. This function is the top-level function that is
2229
 * used for non-RD optimized mode search (controlled by
2230
 * \c cpi->sf.rt_sf.use_nonrd_pick_mode). Depending on frame type it calls
2231
 * inter/skip/hybrid-intra mode search functions
2232
 *
2233
 * \param[in]    cpi            Top-level encoder structure
2234
 * \param[in]    tile_data      Pointer to struct holding adaptive
2235
 *                              data/contexts/models for the tile during
2236
 *                              encoding
2237
 * \param[in]    x              Pointer to structure holding all the data for
2238
 *                              the current macroblock
2239
 * \param[in]    mi_row         Row coordinate of the block in a step size of
2240
 *                              MI_SIZE
2241
 * \param[in]    mi_col         Column coordinate of the block in a step size of
2242
 *                              MI_SIZE
2243
 * \param[in]    rd_cost        Pointer to structure holding rate and distortion
2244
 *                              stats for the current block
2245
 * \param[in]    bsize          Current block size
2246
 * \param[in]    ctx            Pointer to structure holding coding contexts and
2247
 *                              chosen modes for the current block
2248
 *
2249
 * \remark Nothing is returned. Instead, the chosen modes and contexts necessary
2250
 * for reconstruction are stored in ctx, the rate-distortion stats are stored in
2251
 * rd_cost. If no valid mode leading to rd_cost <= best_rd, the status will be
2252
 * signalled by an INT64_MAX rd_cost->rdcost.
2253
 */
2254
static void pick_sb_modes_nonrd(AV1_COMP *const cpi, TileDataEnc *tile_data,
2255
                                MACROBLOCK *const x, int mi_row, int mi_col,
2256
                                RD_STATS *rd_cost, BLOCK_SIZE bsize,
2257
4.08M
                                PICK_MODE_CONTEXT *ctx) {
2258
  // For nonrd mode, av1_set_offsets is already called at the superblock level
2259
  // in encode_nonrd_sb when we determine the partitioning.
2260
4.08M
  if (bsize != cpi->common.seq_params->sb_size ||
2261
4.08M
      cpi->sf.rt_sf.nonrd_check_partition_split == 1) {
2262
4.08M
    av1_set_offsets(cpi, &tile_data->tile_info, x, mi_row, mi_col, bsize);
2263
4.08M
  }
2264
4.08M
  assert(x->last_set_offsets_loc.mi_row == mi_row &&
2265
4.08M
         x->last_set_offsets_loc.mi_col == mi_col &&
2266
4.08M
         x->last_set_offsets_loc.bsize == bsize);
2267
4.08M
  AV1_COMMON *const cm = &cpi->common;
2268
4.08M
  const int num_planes = av1_num_planes(cm);
2269
4.08M
  MACROBLOCKD *const xd = &x->e_mbd;
2270
4.08M
  MB_MODE_INFO *mbmi = xd->mi[0];
2271
4.08M
  struct macroblock_plane *const p = x->plane;
2272
4.08M
  struct macroblockd_plane *const pd = xd->plane;
2273
4.08M
  const AQ_MODE aq_mode = cpi->oxcf.q_cfg.aq_mode;
2274
4.08M
  TxfmSearchInfo *txfm_info = &x->txfm_search_info;
2275
4.08M
  int i;
2276
4.08M
  const int seg_skip =
2277
4.08M
      segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP);
2278
2279
  // This is only needed for real time/allintra row-mt enabled multi-threaded
2280
  // encoding with cost update frequency set to COST_UPD_TILE/COST_UPD_OFF.
2281
4.08M
  wait_for_top_right_sb(&cpi->mt_info.enc_row_mt, &tile_data->row_mt_sync,
2282
4.08M
                        &tile_data->tile_info, cm->seq_params->sb_size,
2283
4.08M
                        cm->seq_params->mib_size_log2, bsize, mi_row, mi_col);
2284
2285
#if CONFIG_COLLECT_COMPONENT_TIMING
2286
  start_timing(cpi, pick_sb_modes_nonrd_time);
2287
#endif
2288
  // Sets up the tx_type_map buffer in MACROBLOCKD.
2289
4.08M
  xd->tx_type_map = txfm_info->tx_type_map_;
2290
4.08M
  xd->tx_type_map_stride = mi_size_wide[bsize];
2291
10.7M
  for (i = 0; i < num_planes; ++i) {
2292
6.66M
    p[i].coeff = ctx->coeff[i];
2293
6.66M
    p[i].qcoeff = ctx->qcoeff[i];
2294
6.66M
    p[i].dqcoeff = ctx->dqcoeff[i];
2295
6.66M
    p[i].eobs = ctx->eobs[i];
2296
6.66M
    p[i].txb_entropy_ctx = ctx->txb_entropy_ctx[i];
2297
6.66M
  }
2298
12.2M
  for (i = 0; i < 2; ++i) pd[i].color_index_map = ctx->color_index_map[i];
2299
2300
4.08M
  if (!seg_skip) {
2301
4.07M
    x->force_zeromv_skip_for_blk =
2302
4.07M
        get_force_zeromv_skip_flag_for_blk(cpi, x, bsize);
2303
2304
    // Source variance may be already compute at superblock level, so no need
2305
    // to recompute, unless bsize < sb_size or source_variance is not yet set.
2306
4.07M
    if (!x->force_zeromv_skip_for_blk &&
2307
4.07M
        (x->source_variance == UINT_MAX || bsize < cm->seq_params->sb_size))
2308
4.07M
      x->source_variance = av1_get_perpixel_variance_facade(
2309
4.07M
          cpi, xd, &x->plane[0].src, bsize, AOM_PLANE_Y);
2310
4.07M
  }
2311
2312
  // Save rdmult before it might be changed, so it can be restored later.
2313
4.08M
  const int orig_rdmult = x->rdmult;
2314
4.08M
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode, mbmi);
2315
4.08M
  if (cpi->roi.enabled && cpi->roi.delta_qp_enabled && mbmi->segment_id)
2316
0
    x->rdmult = cpi->roi.rdmult_delta_qp;
2317
  // Set error per bit for current rdmult
2318
4.08M
  av1_set_error_per_bit(&x->errorperbit, x->rdmult);
2319
  // Find best coding mode & reconstruct the MB so it is available
2320
  // as a predictor for MBs that follow in the SB
2321
4.08M
  if (frame_is_intra_only(cm)) {
2322
#if CONFIG_COLLECT_COMPONENT_TIMING
2323
    start_timing(cpi, hybrid_intra_mode_search_time);
2324
#endif
2325
3.60M
    hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
2326
#if CONFIG_COLLECT_COMPONENT_TIMING
2327
    end_timing(cpi, hybrid_intra_mode_search_time);
2328
#endif
2329
3.60M
  } else {
2330
#if CONFIG_COLLECT_COMPONENT_TIMING
2331
    start_timing(cpi, nonrd_pick_inter_mode_sb_time);
2332
#endif
2333
482k
    if (seg_skip) {
2334
0
      x->force_zeromv_skip_for_blk = 1;
2335
      // TODO(marpan): Consider adding a function for nonrd:
2336
      // av1_nonrd_pick_inter_mode_sb_seg_skip(), instead of setting
2337
      // x->force_zeromv_skip flag and entering av1_nonrd_pick_inter_mode_sb().
2338
0
    }
2339
482k
    av1_nonrd_pick_inter_mode_sb(cpi, tile_data, x, rd_cost, bsize, ctx);
2340
#if CONFIG_COLLECT_COMPONENT_TIMING
2341
    end_timing(cpi, nonrd_pick_inter_mode_sb_time);
2342
#endif
2343
482k
  }
2344
4.08M
  if (cpi->sf.rt_sf.skip_cdef_sb) {
2345
    // cdef_strength is initialized to 1 which means skip_cdef, and is updated
2346
    // here. Check to see is skipping cdef is allowed. Never skip on slide/scene
2347
    // change, near a key frame, or when color sensitivity is set. Always allow
2348
    // cdef_skip for seg_skip = 1.
2349
0
    const int allow_cdef_skipping =
2350
0
        seg_skip ||
2351
0
        (cpi->rc.frames_since_key > 10 && !cpi->rc.high_source_sad &&
2352
0
         !(x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] ||
2353
0
           x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)]));
2354
2355
    // Find the corresponding 64x64 block. It'll be the 128x128 block if that's
2356
    // the block size.
2357
0
    const int mi_row_sb = mi_row - mi_row % MI_SIZE_64X64;
2358
0
    const int mi_col_sb = mi_col - mi_col % MI_SIZE_64X64;
2359
0
    MB_MODE_INFO **mi_sb =
2360
0
        cm->mi_params.mi_grid_base +
2361
0
        get_mi_grid_idx(&cm->mi_params, mi_row_sb, mi_col_sb);
2362
0
    const int is_720p_or_larger = AOMMIN(cm->width, cm->height) >= 720;
2363
0
    unsigned int thresh_spatial_var =
2364
0
        (cpi->oxcf.speed >= 11 && !is_720p_or_larger &&
2365
0
         cpi->oxcf.tune_cfg.content != AOM_CONTENT_SCREEN)
2366
0
            ? 400
2367
0
            : UINT_MAX;
2368
    // For skip_cdef_sb = 1: do not skip if allow_cdef_skipping is false or
2369
    // intra or new mv is picked, with possible conidition on spatial variance.
2370
    // For skip_cdef_sb >= 2: more aggressive mode to always skip unless
2371
    // allow_cdef_skipping is false and source_variance is non-zero.
2372
0
    if (cpi->sf.rt_sf.skip_cdef_sb >= 2) {
2373
0
      mi_sb[0]->cdef_strength =
2374
0
          mi_sb[0]->cdef_strength &&
2375
0
          (allow_cdef_skipping || x->source_variance == 0);
2376
0
    } else {
2377
0
      mi_sb[0]->cdef_strength =
2378
0
          mi_sb[0]->cdef_strength && allow_cdef_skipping &&
2379
0
          !(x->source_variance < thresh_spatial_var &&
2380
0
            (mbmi->mode < INTRA_MODES || mbmi->mode == NEWMV));
2381
0
    }
2382
    // Store in the pickmode context.
2383
0
    ctx->mic.cdef_strength = mi_sb[0]->cdef_strength;
2384
0
  }
2385
4.08M
  x->rdmult = orig_rdmult;
2386
4.08M
  ctx->rd_stats.rate = rd_cost->rate;
2387
4.08M
  ctx->rd_stats.dist = rd_cost->dist;
2388
4.08M
  ctx->rd_stats.rdcost = rd_cost->rdcost;
2389
#if CONFIG_COLLECT_COMPONENT_TIMING
2390
  end_timing(cpi, pick_sb_modes_nonrd_time);
2391
#endif
2392
4.08M
}
2393
2394
static int try_split_partition(AV1_COMP *const cpi, ThreadData *const td,
2395
                               TileDataEnc *const tile_data,
2396
                               TileInfo *const tile_info, TokenExtra **tp,
2397
                               MACROBLOCK *const x, MACROBLOCKD *const xd,
2398
                               const CommonModeInfoParams *const mi_params,
2399
                               const int mi_row, const int mi_col,
2400
                               const BLOCK_SIZE bsize, const int pl,
2401
0
                               PC_TREE *pc_tree) {
2402
0
  AV1_COMMON *const cm = &cpi->common;
2403
0
  const ModeCosts *mode_costs = &x->mode_costs;
2404
0
  const int hbs = mi_size_wide[bsize] / 2;
2405
0
  if (mi_row + mi_size_high[bsize] >= mi_params->mi_rows ||
2406
0
      mi_col + mi_size_wide[bsize] >= mi_params->mi_cols)
2407
0
    return 0;
2408
0
  if (bsize <= BLOCK_8X8 || frame_is_intra_only(cm)) return 0;
2409
0
  if (x->content_state_sb.source_sad_nonrd <= kLowSad) return 0;
2410
2411
  // Do not try split partition when the source sad is small, or
2412
  // the prediction residual is small.
2413
0
  const YV12_BUFFER_CONFIG *const yv12 = get_ref_frame_yv12_buf(cm, LAST_FRAME);
2414
0
  const struct scale_factors *const sf =
2415
0
      get_ref_scale_factors_const(cm, LAST_FRAME);
2416
0
  const int num_planes = av1_num_planes(cm);
2417
0
  av1_setup_src_planes(x, cpi->source, mi_row, mi_col, num_planes, bsize);
2418
0
  av1_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, sf, num_planes);
2419
0
  int block_sad = 0;
2420
0
  for (int plane = 0; plane < num_planes; ++plane) {
2421
0
    const struct macroblock_plane *const p = &x->plane[plane];
2422
0
    const struct macroblockd_plane *const pd = &xd->plane[plane];
2423
0
    const BLOCK_SIZE bs =
2424
0
        get_plane_block_size(bsize, pd->subsampling_x, pd->subsampling_y);
2425
0
    const unsigned int plane_sad = cpi->ppi->fn_ptr[bs].sdf(
2426
0
        p->src.buf, p->src.stride, pd->pre[0].buf, pd->pre[0].stride);
2427
0
    block_sad += plane_sad;
2428
0
  }
2429
0
  const int blk_pix = block_size_wide[bsize] * block_size_high[bsize];
2430
0
  const int block_avg_sad = block_sad / blk_pix;
2431
  // TODO(chengchen): find a proper threshold. It might change according to
2432
  // q as well.
2433
0
  const int threshold = 25;
2434
0
  if (block_avg_sad < threshold) return 0;
2435
2436
0
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
2437
0
  RD_STATS split_rdc, none_rdc;
2438
0
  av1_invalid_rd_stats(&split_rdc);
2439
0
  av1_invalid_rd_stats(&none_rdc);
2440
0
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, 3);
2441
0
  xd->above_txfm_context =
2442
0
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
2443
0
  xd->left_txfm_context =
2444
0
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
2445
2446
  // Calculate rdcost for none partition
2447
0
  pc_tree->partitioning = PARTITION_NONE;
2448
0
  av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2449
0
  if (!pc_tree->none) {
2450
0
    pc_tree->none = av1_alloc_pmc(cpi, bsize, &td->shared_coeff_buf);
2451
0
    if (!pc_tree->none)
2452
0
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2453
0
                         "Failed to allocate PICK_MODE_CONTEXT");
2454
0
  } else {
2455
0
    av1_reset_pmc(pc_tree->none);
2456
0
  }
2457
0
  pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize,
2458
0
                      pc_tree->none);
2459
0
  none_rdc.rate += mode_costs->partition_cost[pl][PARTITION_NONE];
2460
0
  none_rdc.rdcost = RDCOST(x->rdmult, none_rdc.rate, none_rdc.dist);
2461
0
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, 3);
2462
2463
  // Calculate rdcost for split partition
2464
0
  pc_tree->partitioning = PARTITION_SPLIT;
2465
0
  const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
2466
0
  av1_init_rd_stats(&split_rdc);
2467
0
  split_rdc.rate += mode_costs->partition_cost[pl][PARTITION_SPLIT];
2468
0
  if (subsize >= BLOCK_8X8) {
2469
0
    split_rdc.rate += (mode_costs->partition_cost[pl][PARTITION_NONE] * 4);
2470
0
  }
2471
0
  for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
2472
0
    if (!pc_tree->split[i]) {
2473
0
      pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
2474
0
      if (!pc_tree->split[i])
2475
0
        aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2476
0
                           "Failed to allocate PC_TREE");
2477
0
    }
2478
0
    pc_tree->split[i]->index = i;
2479
0
  }
2480
0
  for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
2481
0
    RD_STATS block_rdc;
2482
0
    av1_invalid_rd_stats(&block_rdc);
2483
0
    int x_idx = (i & 1) * hbs;
2484
0
    int y_idx = (i >> 1) * hbs;
2485
0
    if ((mi_row + y_idx >= mi_params->mi_rows) ||
2486
0
        (mi_col + x_idx >= mi_params->mi_cols))
2487
0
      continue;
2488
0
    xd->above_txfm_context =
2489
0
        cm->above_contexts.txfm[tile_info->tile_row] + mi_col + x_idx;
2490
0
    xd->left_txfm_context =
2491
0
        xd->left_txfm_context_buffer + ((mi_row + y_idx) & MAX_MIB_MASK);
2492
0
    if (!pc_tree->split[i]->none) {
2493
0
      pc_tree->split[i]->none =
2494
0
          av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
2495
0
      if (!pc_tree->split[i]->none)
2496
0
        aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2497
0
                           "Failed to allocate PICK_MODE_CONTEXT");
2498
0
    } else {
2499
0
      av1_reset_pmc(pc_tree->split[i]->none);
2500
0
    }
2501
0
    pc_tree->split[i]->partitioning = PARTITION_NONE;
2502
0
    pick_sb_modes_nonrd(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2503
0
                        &block_rdc, subsize, pc_tree->split[i]->none);
2504
0
    split_rdc.rate += block_rdc.rate;
2505
0
    split_rdc.dist += block_rdc.dist;
2506
0
    av1_rd_cost_update(x->rdmult, &split_rdc);
2507
0
    if (none_rdc.rdcost < split_rdc.rdcost) break;
2508
0
    if (i != SUB_PARTITIONS_SPLIT - 1)
2509
0
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row + y_idx, mi_col + x_idx, 1,
2510
0
                     subsize, PARTITION_NONE, pc_tree->split[i]->none, NULL);
2511
0
  }
2512
0
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, 3);
2513
0
  split_rdc.rdcost = RDCOST(x->rdmult, split_rdc.rate, split_rdc.dist);
2514
0
  const int split = split_rdc.rdcost < none_rdc.rdcost;
2515
2516
0
  return split;
2517
0
}
2518
2519
// Returns if SPLIT partitions should be evaluated
2520
static bool calc_do_split_flag(const AV1_COMP *cpi, const MACROBLOCK *x,
2521
                               const PC_TREE *pc_tree, const RD_STATS *none_rdc,
2522
                               const CommonModeInfoParams *mi_params,
2523
                               int mi_row, int mi_col, int hbs,
2524
49.0k
                               BLOCK_SIZE bsize, PARTITION_TYPE partition) {
2525
49.0k
  const AV1_COMMON *const cm = &cpi->common;
2526
49.0k
  const int is_larger_qindex = cm->quant_params.base_qindex > 100;
2527
49.0k
  const MACROBLOCKD *const xd = &x->e_mbd;
2528
49.0k
  bool do_split =
2529
49.0k
      (cpi->sf.rt_sf.nonrd_check_partition_merge_mode == 3)
2530
49.0k
          ? (bsize <= BLOCK_32X32 || (is_larger_qindex && bsize <= BLOCK_64X64))
2531
49.0k
          : true;
2532
49.0k
  if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN ||
2533
49.0k
      cpi->sf.rt_sf.nonrd_check_partition_merge_mode < 2 ||
2534
49.0k
      cyclic_refresh_segment_id_boosted(xd->mi[0]->segment_id) ||
2535
49.0k
      !none_rdc->skip_txfm)
2536
48.7k
    return do_split;
2537
2538
316
  const int use_model_yrd_large = get_model_rd_flag(cpi, xd, bsize);
2539
2540
  // When model based skip is not used (i.e.,use_model_yrd_large = 0), skip_txfm
2541
  // would have been populated based on Hadamard transform and skip_txfm flag is
2542
  // more reliable. Hence SPLIT evaluation is disabled at all quantizers for 8x8
2543
  // and 16x16 blocks.
2544
  // When model based skip is used (i.e.,use_model_yrd_large = 1), skip_txfm may
2545
  // not be reliable. Hence SPLIT evaluation is disabled only at lower
2546
  // quantizers for blocks >= 32x32.
2547
316
  if ((!use_model_yrd_large) || (!is_larger_qindex)) return false;
2548
2549
  // Use residual statistics to decide if SPLIT partition should be evaluated
2550
  // for 32x32 blocks. The pruning logic is avoided for larger block size to
2551
  // avoid the visual artifacts
2552
261
  if (pc_tree->none->mic.mode == NEWMV && bsize == BLOCK_32X32 && do_split) {
2553
208
    const BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
2554
208
    assert(subsize < BLOCK_SIZES_ALL);
2555
208
    double min_per_pixel_error = DBL_MAX;
2556
208
    double max_per_pixel_error = 0.;
2557
208
    int i;
2558
1.03k
    for (i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
2559
824
      const int x_idx = (i & 1) * hbs;
2560
824
      const int y_idx = (i >> 1) * hbs;
2561
824
      if ((mi_row + y_idx >= mi_params->mi_rows) ||
2562
826
          (mi_col + x_idx >= mi_params->mi_cols)) {
2563
0
        break;
2564
0
      }
2565
2566
      // Populate the appropriate buffer pointers.
2567
      // Pass scale factors as NULL as the base pointer of the block would have
2568
      // been calculated appropriately.
2569
824
      struct buf_2d src_split_buf_2d, pred_split_buf_2d;
2570
824
      const struct buf_2d *src_none_buf_2d = &x->plane[AOM_PLANE_Y].src;
2571
824
      setup_pred_plane(&src_split_buf_2d, subsize, src_none_buf_2d->buf,
2572
824
                       src_none_buf_2d->width, src_none_buf_2d->height,
2573
824
                       src_none_buf_2d->stride, y_idx, x_idx, NULL, 0, 0);
2574
824
      const struct buf_2d *pred_none_buf_2d = &xd->plane[AOM_PLANE_Y].dst;
2575
824
      setup_pred_plane(&pred_split_buf_2d, subsize, pred_none_buf_2d->buf,
2576
824
                       pred_none_buf_2d->width, pred_none_buf_2d->height,
2577
824
                       pred_none_buf_2d->stride, y_idx, x_idx, NULL, 0, 0);
2578
2579
824
      unsigned int curr_uint_mse;
2580
824
      const unsigned int curr_uint_var = cpi->ppi->fn_ptr[subsize].vf(
2581
824
          src_split_buf_2d.buf, src_split_buf_2d.stride, pred_split_buf_2d.buf,
2582
824
          pred_split_buf_2d.stride, &curr_uint_mse);
2583
824
      const double curr_per_pixel_error =
2584
824
          sqrt((double)curr_uint_var / block_size_wide[subsize] /
2585
824
               block_size_high[subsize]);
2586
824
      if (curr_per_pixel_error < min_per_pixel_error)
2587
383
        min_per_pixel_error = curr_per_pixel_error;
2588
824
      if (curr_per_pixel_error > max_per_pixel_error)
2589
464
        max_per_pixel_error = curr_per_pixel_error;
2590
824
    }
2591
2592
    // Prune based on residual statistics only if all the sub-partitions are
2593
    // valid.
2594
208
    if (i == SUB_PARTITIONS_SPLIT) {
2595
208
      if (max_per_pixel_error - min_per_pixel_error <= 1.5) do_split = false;
2596
208
    }
2597
208
  }
2598
2599
261
  return do_split;
2600
316
}
2601
2602
static void try_merge(AV1_COMP *const cpi, ThreadData *td,
2603
                      TileDataEnc *tile_data, MB_MODE_INFO **mib,
2604
                      TokenExtra **tp, const int mi_row, const int mi_col,
2605
                      const BLOCK_SIZE bsize, PC_TREE *const pc_tree,
2606
                      const PARTITION_TYPE partition, const BLOCK_SIZE subsize,
2607
49.3k
                      const int pl) {
2608
49.3k
  AV1_COMMON *const cm = &cpi->common;
2609
49.3k
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
2610
49.3k
  TileInfo *const tile_info = &tile_data->tile_info;
2611
49.3k
  MACROBLOCK *const x = &td->mb;
2612
49.3k
  MACROBLOCKD *const xd = &x->e_mbd;
2613
49.3k
  const ModeCosts *mode_costs = &x->mode_costs;
2614
49.3k
  const int num_planes = av1_num_planes(cm);
2615
  // Only square blocks from 8x8 to 128x128 are supported
2616
49.3k
  assert(bsize >= BLOCK_8X8 && bsize <= BLOCK_128X128);
2617
49.3k
  const int bs = mi_size_wide[bsize];
2618
49.3k
  const int hbs = bs / 2;
2619
49.3k
  bool do_split = false;
2620
49.3k
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
2621
49.3k
  RD_STATS split_rdc, none_rdc;
2622
49.3k
  av1_invalid_rd_stats(&split_rdc);
2623
49.3k
  av1_invalid_rd_stats(&none_rdc);
2624
49.3k
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
2625
49.3k
  xd->above_txfm_context =
2626
49.3k
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
2627
49.3k
  xd->left_txfm_context =
2628
49.3k
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
2629
49.3k
  pc_tree->partitioning = PARTITION_NONE;
2630
49.3k
  if (!pc_tree->none) {
2631
26.5k
    pc_tree->none = av1_alloc_pmc(cpi, bsize, &td->shared_coeff_buf);
2632
26.5k
    if (!pc_tree->none)
2633
0
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2634
0
                         "Failed to allocate PICK_MODE_CONTEXT");
2635
26.5k
  } else {
2636
22.7k
    av1_reset_pmc(pc_tree->none);
2637
22.7k
  }
2638
49.3k
  pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize,
2639
49.3k
                      pc_tree->none);
2640
49.3k
  none_rdc.rate += mode_costs->partition_cost[pl][PARTITION_NONE];
2641
49.3k
  none_rdc.rdcost = RDCOST(x->rdmult, none_rdc.rate, none_rdc.dist);
2642
49.3k
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
2643
2644
49.3k
  if (cpi->sf.rt_sf.nonrd_check_partition_merge_mode < 2 ||
2645
49.2k
      none_rdc.skip_txfm != 1 || pc_tree->none->mic.mode == NEWMV) {
2646
49.0k
    do_split = calc_do_split_flag(cpi, x, pc_tree, &none_rdc, mi_params, mi_row,
2647
49.0k
                                  mi_col, hbs, bsize, partition);
2648
49.0k
    if (do_split) {
2649
48.9k
      av1_init_rd_stats(&split_rdc);
2650
48.9k
      split_rdc.rate += mode_costs->partition_cost[pl][PARTITION_SPLIT];
2651
217k
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
2652
194k
        RD_STATS block_rdc;
2653
194k
        av1_invalid_rd_stats(&block_rdc);
2654
194k
        int x_idx = (i & 1) * hbs;
2655
194k
        int y_idx = (i >> 1) * hbs;
2656
194k
        if ((mi_row + y_idx >= mi_params->mi_rows) ||
2657
194k
            (mi_col + x_idx >= mi_params->mi_cols))
2658
0
          continue;
2659
194k
        xd->above_txfm_context =
2660
194k
            cm->above_contexts.txfm[tile_info->tile_row] + mi_col + x_idx;
2661
194k
        xd->left_txfm_context =
2662
194k
            xd->left_txfm_context_buffer + ((mi_row + y_idx) & MAX_MIB_MASK);
2663
194k
        if (!pc_tree->split[i]->none) {
2664
106k
          pc_tree->split[i]->none =
2665
106k
              av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
2666
106k
          if (!pc_tree->split[i]->none)
2667
0
            aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2668
0
                               "Failed to allocate PICK_MODE_CONTEXT");
2669
106k
        } else {
2670
88.5k
          av1_reset_pmc(pc_tree->split[i]->none);
2671
88.5k
        }
2672
194k
        pc_tree->split[i]->partitioning = PARTITION_NONE;
2673
194k
        pick_sb_modes_nonrd(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2674
194k
                            &block_rdc, subsize, pc_tree->split[i]->none);
2675
        // TODO(yunqingwang): The rate here did not include the cost of
2676
        // signaling PARTITION_NONE token in the sub-blocks.
2677
194k
        split_rdc.rate += block_rdc.rate;
2678
194k
        split_rdc.dist += block_rdc.dist;
2679
2680
194k
        av1_rd_cost_update(x->rdmult, &split_rdc);
2681
2682
194k
        if (none_rdc.rdcost < split_rdc.rdcost) {
2683
26.3k
          break;
2684
26.3k
        }
2685
2686
168k
        if (i != SUB_PARTITIONS_SPLIT - 1)
2687
146k
          encode_b_nonrd(cpi, tile_data, td, tp, mi_row + y_idx, mi_col + x_idx,
2688
146k
                         1, subsize, PARTITION_NONE, pc_tree->split[i]->none,
2689
146k
                         NULL);
2690
168k
      }
2691
48.9k
      av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
2692
48.9k
      split_rdc.rdcost = RDCOST(x->rdmult, split_rdc.rate, split_rdc.dist);
2693
48.9k
    }
2694
49.0k
  }
2695
2696
49.3k
  if (none_rdc.rdcost < split_rdc.rdcost) {
2697
    /* Predicted samples can not be reused for PARTITION_NONE since same
2698
     * buffer is being used to store the reconstructed samples of
2699
     * PARTITION_SPLIT block. */
2700
26.5k
    if (do_split) x->reuse_inter_pred = false;
2701
2702
26.5k
    mib[0]->bsize = bsize;
2703
26.5k
    pc_tree->partitioning = PARTITION_NONE;
2704
26.5k
    encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col, 0, bsize, partition,
2705
26.5k
                   pc_tree->none, NULL);
2706
26.5k
  } else {
2707
22.7k
    mib[0]->bsize = subsize;
2708
22.7k
    pc_tree->partitioning = PARTITION_SPLIT;
2709
    /* Predicted samples can not be reused for PARTITION_SPLIT since same
2710
     * buffer is being used to write the reconstructed samples. */
2711
    // TODO(Cherma): Store and reuse predicted samples generated by
2712
    // encode_b_nonrd() in DRY_RUN_NORMAL mode.
2713
22.7k
    x->reuse_inter_pred = false;
2714
2715
113k
    for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
2716
90.7k
      int x_idx = (i & 1) * hbs;
2717
90.7k
      int y_idx = (i >> 1) * hbs;
2718
90.7k
      if ((mi_row + y_idx >= mi_params->mi_rows) ||
2719
90.8k
          (mi_col + x_idx >= mi_params->mi_cols))
2720
0
        continue;
2721
2722
      // Note: We don't reset pc_tree->split[i]->none here because it
2723
      // could contain results from the additional check. Instead, it is
2724
      // reset before we enter the nonrd_check_partition_merge_mode
2725
      // condition.
2726
90.7k
      if (!pc_tree->split[i]->none) {
2727
0
        pc_tree->split[i]->none =
2728
0
            av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
2729
0
        if (!pc_tree->split[i]->none)
2730
0
          aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
2731
0
                             "Failed to allocate PICK_MODE_CONTEXT");
2732
0
      }
2733
90.7k
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row + y_idx, mi_col + x_idx, 0,
2734
90.7k
                     subsize, PARTITION_NONE, pc_tree->split[i]->none, NULL);
2735
90.7k
    }
2736
22.7k
  }
2737
49.3k
}
2738
2739
// Evaluate if the sub-partitions can be merged directly into a large partition
2740
// without calculating the RD cost.
2741
static void direct_partition_merging(AV1_COMP *cpi, ThreadData *td,
2742
                                     TileDataEnc *tile_data, MB_MODE_INFO **mib,
2743
0
                                     int mi_row, int mi_col, BLOCK_SIZE bsize) {
2744
0
  AV1_COMMON *const cm = &cpi->common;
2745
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
2746
0
  TileInfo *const tile_info = &tile_data->tile_info;
2747
0
  MACROBLOCK *const x = &td->mb;
2748
0
  MACROBLOCKD *const xd = &x->e_mbd;
2749
0
  const int bs = mi_size_wide[bsize];
2750
0
  const int hbs = bs / 2;
2751
0
  const PARTITION_TYPE partition =
2752
0
      (bsize >= BLOCK_8X8) ? get_partition(cm, mi_row, mi_col, bsize)
2753
0
                           : PARTITION_NONE;
2754
0
  BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
2755
2756
0
  MB_MODE_INFO **b0 = mib;
2757
0
  MB_MODE_INFO **b1 = mib + hbs;
2758
0
  MB_MODE_INFO **b2 = mib + hbs * mi_params->mi_stride;
2759
0
  MB_MODE_INFO **b3 = mib + hbs * mi_params->mi_stride + hbs;
2760
2761
  // Check if the following conditions are met. This can be updated
2762
  // later with more support added.
2763
0
  const int further_split = b0[0]->bsize < subsize || b1[0]->bsize < subsize ||
2764
0
                            b2[0]->bsize < subsize || b3[0]->bsize < subsize;
2765
0
  if (further_split) return;
2766
2767
0
  const int no_skip = !b0[0]->skip_txfm || !b1[0]->skip_txfm ||
2768
0
                      !b2[0]->skip_txfm || !b3[0]->skip_txfm;
2769
0
  if (no_skip) return;
2770
2771
0
  const int compound = (b0[0]->ref_frame[1] != b1[0]->ref_frame[1] ||
2772
0
                        b0[0]->ref_frame[1] != b2[0]->ref_frame[1] ||
2773
0
                        b0[0]->ref_frame[1] != b3[0]->ref_frame[1] ||
2774
0
                        b0[0]->ref_frame[1] > NONE_FRAME);
2775
0
  if (compound) return;
2776
2777
  // Intra modes aren't considered here.
2778
0
  const int different_ref = (b0[0]->ref_frame[0] != b1[0]->ref_frame[0] ||
2779
0
                             b0[0]->ref_frame[0] != b2[0]->ref_frame[0] ||
2780
0
                             b0[0]->ref_frame[0] != b3[0]->ref_frame[0] ||
2781
0
                             b0[0]->ref_frame[0] <= INTRA_FRAME);
2782
0
  if (different_ref) return;
2783
2784
0
  const int different_mode =
2785
0
      (b0[0]->mode != b1[0]->mode || b0[0]->mode != b2[0]->mode ||
2786
0
       b0[0]->mode != b3[0]->mode);
2787
0
  if (different_mode) return;
2788
2789
0
  const int unsupported_mode =
2790
0
      (b0[0]->mode != NEARESTMV && b0[0]->mode != GLOBALMV);
2791
0
  if (unsupported_mode) return;
2792
2793
0
  const int different_mv = (b0[0]->mv[0].as_int != b1[0]->mv[0].as_int ||
2794
0
                            b0[0]->mv[0].as_int != b2[0]->mv[0].as_int ||
2795
0
                            b0[0]->mv[0].as_int != b3[0]->mv[0].as_int);
2796
0
  if (different_mv) return;
2797
2798
0
  const int unsupported_motion_mode =
2799
0
      (b0[0]->motion_mode != b1[0]->motion_mode ||
2800
0
       b0[0]->motion_mode != b2[0]->motion_mode ||
2801
0
       b0[0]->motion_mode != b3[0]->motion_mode ||
2802
0
       b0[0]->motion_mode != SIMPLE_TRANSLATION);
2803
0
  if (unsupported_motion_mode) return;
2804
2805
0
  const int diffent_filter =
2806
0
      (b0[0]->interp_filters.as_int != b1[0]->interp_filters.as_int ||
2807
0
       b0[0]->interp_filters.as_int != b2[0]->interp_filters.as_int ||
2808
0
       b0[0]->interp_filters.as_int != b3[0]->interp_filters.as_int);
2809
0
  if (diffent_filter) return;
2810
2811
0
  const int different_seg = (b0[0]->segment_id != b1[0]->segment_id ||
2812
0
                             b0[0]->segment_id != b2[0]->segment_id ||
2813
0
                             b0[0]->segment_id != b3[0]->segment_id);
2814
0
  if (different_seg) return;
2815
2816
  // Evaluate the ref_mv.
2817
0
  MB_MODE_INFO **this_mi = mib;
2818
0
  BLOCK_SIZE orig_bsize = this_mi[0]->bsize;
2819
0
  const PARTITION_TYPE orig_partition = this_mi[0]->partition;
2820
2821
0
  this_mi[0]->bsize = bsize;
2822
0
  this_mi[0]->partition = PARTITION_NONE;
2823
0
  this_mi[0]->skip_txfm = 1;
2824
2825
  // TODO(yunqing): functions called below can be optimized by
2826
  // removing unrelated operations.
2827
0
  av1_set_offsets_without_segment_id(cpi, &tile_data->tile_info, x, mi_row,
2828
0
                                     mi_col, bsize);
2829
2830
0
  const MV_REFERENCE_FRAME ref_frame = this_mi[0]->ref_frame[0];
2831
0
  int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES];
2832
0
  struct buf_2d yv12_mb[REF_FRAMES][MAX_MB_PLANE];
2833
0
  int force_skip_low_temp_var = 0;
2834
0
  int skip_pred_mv = 0;
2835
0
  bool use_scaled_ref;
2836
2837
0
  for (int i = 0; i < MB_MODE_COUNT; ++i) {
2838
0
    for (int j = 0; j < REF_FRAMES; ++j) {
2839
0
      frame_mv[i][j].as_int = INVALID_MV;
2840
0
    }
2841
0
  }
2842
0
  av1_copy(x->color_sensitivity, x->color_sensitivity_sb);
2843
0
  skip_pred_mv = (x->nonrd_prune_ref_frame_search > 2 &&
2844
0
                  x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_U)] != 2 &&
2845
0
                  x->color_sensitivity[COLOR_SENS_IDX(AOM_PLANE_V)] != 2);
2846
2847
0
  find_predictors(cpi, x, ref_frame, frame_mv, yv12_mb, bsize,
2848
0
                  force_skip_low_temp_var, skip_pred_mv, &use_scaled_ref);
2849
2850
0
  int continue_merging = 1;
2851
0
  if (frame_mv[NEARESTMV][ref_frame].as_mv.row != b0[0]->mv[0].as_mv.row ||
2852
0
      frame_mv[NEARESTMV][ref_frame].as_mv.col != b0[0]->mv[0].as_mv.col)
2853
0
    continue_merging = 0;
2854
2855
0
  if (!continue_merging) {
2856
0
    this_mi[0]->bsize = orig_bsize;
2857
0
    this_mi[0]->partition = orig_partition;
2858
2859
    // TODO(yunqing): Store the results and restore here instead of
2860
    // calling find_predictors() again.
2861
0
    av1_set_offsets_without_segment_id(cpi, &tile_data->tile_info, x, mi_row,
2862
0
                                       mi_col, this_mi[0]->bsize);
2863
0
    find_predictors(cpi, x, ref_frame, frame_mv, yv12_mb, this_mi[0]->bsize,
2864
0
                    force_skip_low_temp_var, skip_pred_mv, &use_scaled_ref);
2865
0
  } else {
2866
0
    struct scale_factors *sf = get_ref_scale_factors(cm, ref_frame);
2867
0
    const int is_scaled = av1_is_scaled(sf);
2868
0
    const int is_y_subpel_mv = (abs(this_mi[0]->mv[0].as_mv.row) % 8) ||
2869
0
                               (abs(this_mi[0]->mv[0].as_mv.col) % 8);
2870
0
    const int is_uv_subpel_mv = (abs(this_mi[0]->mv[0].as_mv.row) % 16) ||
2871
0
                                (abs(this_mi[0]->mv[0].as_mv.col) % 16);
2872
2873
0
    if (cpi->ppi->use_svc || is_scaled || is_y_subpel_mv || is_uv_subpel_mv) {
2874
0
      const int num_planes = av1_num_planes(cm);
2875
0
      set_ref_ptrs(cm, xd, ref_frame, this_mi[0]->ref_frame[1]);
2876
0
      const YV12_BUFFER_CONFIG *cfg = get_ref_frame_yv12_buf(cm, ref_frame);
2877
0
      av1_setup_pre_planes(xd, 0, cfg, mi_row, mi_col,
2878
0
                           xd->block_ref_scale_factors[0], num_planes);
2879
2880
0
      if (!cpi->ppi->use_svc && !is_scaled && !is_y_subpel_mv) {
2881
0
        assert(is_uv_subpel_mv == 1);
2882
0
        av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize, 1,
2883
0
                                      num_planes - 1);
2884
0
      } else {
2885
0
        av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize, 0,
2886
0
                                      num_planes - 1);
2887
0
      }
2888
0
    }
2889
2890
    // Copy out mbmi_ext information.
2891
0
    MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
2892
0
    MB_MODE_INFO_EXT_FRAME *mbmi_ext_frame = x->mbmi_ext_frame;
2893
0
    av1_copy_mbmi_ext_to_mbmi_ext_frame(
2894
0
        mbmi_ext_frame, mbmi_ext, av1_ref_frame_type(this_mi[0]->ref_frame));
2895
2896
0
    const BLOCK_SIZE this_subsize =
2897
0
        get_partition_subsize(bsize, this_mi[0]->partition);
2898
    // Update partition contexts.
2899
0
    update_ext_partition_context(xd, mi_row, mi_col, this_subsize, bsize,
2900
0
                                 this_mi[0]->partition);
2901
2902
0
    const int num_planes = av1_num_planes(cm);
2903
0
    av1_reset_entropy_context(xd, bsize, num_planes);
2904
2905
    // Note: use x->txfm_search_params.tx_mode_search_type instead of
2906
    // cm->features.tx_mode here.
2907
0
    TX_SIZE tx_size =
2908
0
        tx_size_from_tx_mode(bsize, x->txfm_search_params.tx_mode_search_type);
2909
0
    if (xd->lossless[this_mi[0]->segment_id]) tx_size = TX_4X4;
2910
0
    this_mi[0]->tx_size = tx_size;
2911
0
    memset(this_mi[0]->inter_tx_size, this_mi[0]->tx_size,
2912
0
           sizeof(this_mi[0]->inter_tx_size));
2913
2914
    // Update txfm contexts.
2915
0
    xd->above_txfm_context =
2916
0
        cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
2917
0
    xd->left_txfm_context =
2918
0
        xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
2919
0
    set_txfm_ctxs(this_mi[0]->tx_size, xd->width, xd->height,
2920
0
                  this_mi[0]->skip_txfm && is_inter_block(this_mi[0]), xd);
2921
2922
    // Update mi for this partition block.
2923
0
    for (int y = 0; y < bs; y++) {
2924
0
      for (int x_idx = 0; x_idx < bs; x_idx++) {
2925
0
        this_mi[x_idx + y * mi_params->mi_stride] = this_mi[0];
2926
0
      }
2927
0
    }
2928
0
  }
2929
0
}
2930
2931
/*!\brief AV1 block partition application (minimal RD search).
2932
*
2933
* \ingroup partition_search
2934
* \callgraph
2935
* \callergraph
2936
* Encode the block by applying pre-calculated partition patterns that are
2937
* represented by coding block sizes stored in the mbmi array. The only
2938
* partition adjustment allowed is merging leaf split nodes if it leads to a
2939
* lower rd cost. The partition types are limited to a basic set: none, horz,
2940
* vert, and split. This function is only used in the real-time mode.
2941
*
2942
* \param[in]    cpi       Top-level encoder structure
2943
* \param[in]    td        Pointer to thread data
2944
* \param[in]    tile_data Pointer to struct holding adaptive
2945
data/contexts/models for the tile during encoding
2946
* \param[in]    mib       Array representing MB_MODE_INFO pointers for mi
2947
blocks starting from the first pixel of the current
2948
block
2949
* \param[in]    tp        Pointer to the starting token
2950
* \param[in]    mi_row    Row coordinate of the block in a step size of MI_SIZE
2951
* \param[in]    mi_col    Column coordinate of the block in a step size of
2952
MI_SIZE
2953
* \param[in]    bsize     Current block size
2954
* \param[in]    pc_tree   Pointer to the PC_TREE node holding the picked
2955
partitions and mode info for the current block
2956
*
2957
* \remark Nothing is returned. The pc_tree struct is modified to store the
2958
* picked partition and modes.
2959
*/
2960
void av1_nonrd_use_partition(AV1_COMP *cpi, ThreadData *td,
2961
                             TileDataEnc *tile_data, MB_MODE_INFO **mib,
2962
                             TokenExtra **tp, int mi_row, int mi_col,
2963
5.45M
                             BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2964
5.45M
  AV1_COMMON *const cm = &cpi->common;
2965
5.45M
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
2966
5.45M
  TileInfo *const tile_info = &tile_data->tile_info;
2967
5.45M
  MACROBLOCK *const x = &td->mb;
2968
5.45M
  MACROBLOCKD *const xd = &x->e_mbd;
2969
5.45M
  const ModeCosts *mode_costs = &x->mode_costs;
2970
  // Only square blocks from 8x8 to 128x128 are supported
2971
5.45M
  assert(bsize >= BLOCK_8X8 && bsize <= BLOCK_128X128);
2972
5.45M
  const int bs = mi_size_wide[bsize];
2973
5.45M
  const int hbs = bs / 2;
2974
5.45M
  PARTITION_TYPE partition = (bsize >= BLOCK_8X8)
2975
5.45M
                                 ? get_partition(cm, mi_row, mi_col, bsize)
2976
18.4E
                                 : PARTITION_NONE;
2977
5.45M
  BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
2978
5.45M
  assert(subsize <= BLOCK_LARGEST);
2979
5.45M
  const int pl = (bsize >= BLOCK_8X8)
2980
5.45M
                     ? partition_plane_context(xd, mi_row, mi_col, bsize)
2981
18.4E
                     : 0;
2982
2983
5.45M
  RD_STATS dummy_cost;
2984
5.45M
  av1_invalid_rd_stats(&dummy_cost);
2985
2986
5.45M
  if (mi_row >= mi_params->mi_rows || mi_col >= mi_params->mi_cols) return;
2987
2988
5.45M
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);
2989
2990
5.45M
  xd->above_txfm_context =
2991
5.45M
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
2992
5.45M
  xd->left_txfm_context =
2993
5.45M
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
2994
2995
  // Initialize default mode evaluation params
2996
5.45M
  set_mode_eval_params(cpi, x, DEFAULT_EVAL);
2997
2998
5.45M
  x->reuse_inter_pred = cpi->sf.rt_sf.reuse_inter_pred_nonrd;
2999
3000
5.45M
  int change_none_to_split = 0;
3001
5.45M
  if (partition == PARTITION_NONE &&
3002
3.80M
      cpi->sf.rt_sf.nonrd_check_partition_split == 1) {
3003
0
    change_none_to_split =
3004
0
        try_split_partition(cpi, td, tile_data, tile_info, tp, x, xd, mi_params,
3005
0
                            mi_row, mi_col, bsize, pl, pc_tree);
3006
0
    if (change_none_to_split) {
3007
0
      partition = PARTITION_SPLIT;
3008
0
      subsize = get_partition_subsize(bsize, partition);
3009
0
      assert(subsize <= BLOCK_LARGEST);
3010
0
    }
3011
0
  }
3012
3013
5.45M
  pc_tree->partitioning = partition;
3014
3015
5.45M
  switch (partition) {
3016
3.79M
    case PARTITION_NONE:
3017
3.79M
      if (!pc_tree->none) {
3018
2.07M
        pc_tree->none = av1_alloc_pmc(cpi, bsize, &td->shared_coeff_buf);
3019
2.07M
        if (!pc_tree->none)
3020
0
          aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3021
0
                             "Failed to allocate PICK_MODE_CONTEXT");
3022
2.07M
      } else {
3023
1.72M
        av1_reset_pmc(pc_tree->none);
3024
1.72M
      }
3025
3.79M
      pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &dummy_cost, bsize,
3026
3.79M
                          pc_tree->none);
3027
3.79M
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col, 0, bsize,
3028
3.79M
                     partition, pc_tree->none, NULL);
3029
3.79M
      break;
3030
12.7k
    case PARTITION_VERT:
3031
38.3k
      for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
3032
25.5k
        if (!pc_tree->vertical[i]) {
3033
19.1k
          pc_tree->vertical[i] =
3034
19.1k
              av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
3035
19.1k
          if (!pc_tree->vertical[i])
3036
0
            aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3037
0
                               "Failed to allocate PICK_MODE_CONTEXT");
3038
19.1k
        } else {
3039
6.47k
          av1_reset_pmc(pc_tree->vertical[i]);
3040
6.47k
        }
3041
25.5k
      }
3042
12.7k
      pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &dummy_cost,
3043
12.7k
                          subsize, pc_tree->vertical[0]);
3044
12.7k
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col, 0, subsize,
3045
12.7k
                     PARTITION_VERT, pc_tree->vertical[0], NULL);
3046
12.7k
      if (mi_col + hbs < mi_params->mi_cols && bsize > BLOCK_8X8) {
3047
38
        pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col + hbs,
3048
38
                            &dummy_cost, subsize, pc_tree->vertical[1]);
3049
38
        encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col + hbs, 0, subsize,
3050
38
                       PARTITION_VERT, pc_tree->vertical[1], NULL);
3051
38
      }
3052
12.7k
      break;
3053
14.6k
    case PARTITION_HORZ:
3054
44.0k
      for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
3055
29.3k
        if (!pc_tree->horizontal[i]) {
3056
23.2k
          pc_tree->horizontal[i] =
3057
23.2k
              av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
3058
23.2k
          if (!pc_tree->horizontal[i])
3059
0
            aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3060
0
                               "Failed to allocate PICK_MODE_CONTEXT");
3061
23.2k
        } else {
3062
6.15k
          av1_reset_pmc(pc_tree->horizontal[i]);
3063
6.15k
        }
3064
29.3k
      }
3065
14.6k
      pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &dummy_cost,
3066
14.6k
                          subsize, pc_tree->horizontal[0]);
3067
14.6k
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col, 0, subsize,
3068
14.6k
                     PARTITION_HORZ, pc_tree->horizontal[0], NULL);
3069
3070
14.6k
      if (mi_row + hbs < mi_params->mi_rows && bsize > BLOCK_8X8) {
3071
31
        pick_sb_modes_nonrd(cpi, tile_data, x, mi_row + hbs, mi_col,
3072
31
                            &dummy_cost, subsize, pc_tree->horizontal[1]);
3073
31
        encode_b_nonrd(cpi, tile_data, td, tp, mi_row + hbs, mi_col, 0, subsize,
3074
31
                       PARTITION_HORZ, pc_tree->horizontal[1], NULL);
3075
31
      }
3076
14.6k
      break;
3077
1.62M
    case PARTITION_SPLIT:
3078
8.11M
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
3079
6.48M
        if (!pc_tree->split[i]) {
3080
3.58M
          pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
3081
3.58M
          if (!pc_tree->split[i])
3082
0
            aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3083
0
                               "Failed to allocate PC_TREE");
3084
3.58M
        }
3085
6.48M
        pc_tree->split[i]->index = i;
3086
6.48M
      }
3087
1.62M
      if (cpi->sf.rt_sf.nonrd_check_partition_merge_mode &&
3088
1.28M
          av1_is_leaf_split_partition(cm, mi_row, mi_col, bsize) &&
3089
696k
          !frame_is_intra_only(cm) && bsize <= BLOCK_64X64) {
3090
49.3k
        try_merge(cpi, td, tile_data, mib, tp, mi_row, mi_col, bsize, pc_tree,
3091
49.3k
                  partition, subsize, pl);
3092
1.57M
      } else {
3093
7.85M
        for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
3094
6.27M
          int x_idx = (i & 1) * hbs;
3095
6.27M
          int y_idx = (i >> 1) * hbs;
3096
6.27M
          int jj = i >> 1, ii = i & 0x01;
3097
6.27M
          if ((mi_row + y_idx >= mi_params->mi_rows) ||
3098
5.75M
              (mi_col + x_idx >= mi_params->mi_cols))
3099
996k
            continue;
3100
5.28M
          av1_nonrd_use_partition(
3101
5.28M
              cpi, td, tile_data,
3102
5.28M
              mib + jj * hbs * mi_params->mi_stride + ii * hbs, tp,
3103
5.28M
              mi_row + y_idx, mi_col + x_idx, subsize, pc_tree->split[i]);
3104
5.28M
        }
3105
3106
1.57M
        if (!change_none_to_split) {
3107
          // Note: Palette, cfl are not supported.
3108
1.57M
          if (!frame_is_intra_only(cm) && !tile_data->allow_update_cdf &&
3109
0
              cpi->sf.rt_sf.partition_direct_merging &&
3110
0
              mode_costs->partition_cost[pl][PARTITION_NONE] <
3111
0
                  mode_costs->partition_cost[pl][PARTITION_SPLIT] &&
3112
0
              (mi_row + bs <= mi_params->mi_rows) &&
3113
0
              (mi_col + bs <= mi_params->mi_cols)) {
3114
0
            direct_partition_merging(cpi, td, tile_data, mib, mi_row, mi_col,
3115
0
                                     bsize);
3116
0
          }
3117
1.57M
        }
3118
1.57M
      }
3119
1.62M
      break;
3120
0
    case PARTITION_VERT_A:
3121
0
    case PARTITION_VERT_B:
3122
0
    case PARTITION_HORZ_A:
3123
0
    case PARTITION_HORZ_B:
3124
0
    case PARTITION_HORZ_4:
3125
0
    case PARTITION_VERT_4:
3126
0
      assert(0 && "Cannot handle extended partition types");
3127
0
    default: assert(0); break;
3128
5.45M
  }
3129
5.45M
}
3130
3131
#if !CONFIG_REALTIME_ONLY
3132
// Try searching for an encoding for the given subblock. Returns zero if the
3133
// rdcost is already too high (to tell the caller not to bother searching for
3134
// encodings of further subblocks).
3135
static int rd_try_subblock(AV1_COMP *const cpi, ThreadData *td,
3136
                           TileDataEnc *tile_data, TokenExtra **tp, int is_last,
3137
                           int mi_row, int mi_col, BLOCK_SIZE subsize,
3138
                           RD_STATS best_rdcost, RD_STATS *sum_rdc,
3139
                           PARTITION_TYPE partition,
3140
0
                           PICK_MODE_CONTEXT *this_ctx) {
3141
0
  MACROBLOCK *const x = &td->mb;
3142
0
  const int orig_mult = x->rdmult;
3143
0
  setup_block_rdmult(cpi, x, mi_row, mi_col, subsize, NO_AQ, NULL);
3144
3145
0
  av1_rd_cost_update(x->rdmult, &best_rdcost);
3146
3147
0
  RD_STATS rdcost_remaining;
3148
0
  av1_rd_stats_subtraction(x->rdmult, &best_rdcost, sum_rdc, &rdcost_remaining);
3149
0
  RD_STATS this_rdc;
3150
0
  pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, partition,
3151
0
                subsize, this_ctx, rdcost_remaining);
3152
3153
0
  if (this_rdc.rate == INT_MAX) {
3154
0
    sum_rdc->rdcost = INT64_MAX;
3155
0
  } else {
3156
0
    sum_rdc->rate += this_rdc.rate;
3157
0
    sum_rdc->dist += this_rdc.dist;
3158
0
    av1_rd_cost_update(x->rdmult, sum_rdc);
3159
0
  }
3160
3161
0
  if (sum_rdc->rdcost >= best_rdcost.rdcost) {
3162
0
    x->rdmult = orig_mult;
3163
0
    return 0;
3164
0
  }
3165
3166
0
  if (!is_last) {
3167
0
    av1_update_state(cpi, td, this_ctx, mi_row, mi_col, subsize, 1);
3168
0
    encode_superblock(cpi, tile_data, td, tp, DRY_RUN_NORMAL, subsize, NULL);
3169
0
  }
3170
3171
0
  x->rdmult = orig_mult;
3172
0
  return 1;
3173
0
}
3174
3175
// Tests an AB partition, and updates the encoder status, the pick mode
3176
// contexts, the best rdcost, and the best partition.
3177
static bool rd_test_partition3(AV1_COMP *const cpi, ThreadData *td,
3178
                               TileDataEnc *tile_data, TokenExtra **tp,
3179
                               PC_TREE *pc_tree, RD_STATS *best_rdc,
3180
                               int64_t *this_rdcost,
3181
                               PICK_MODE_CONTEXT *ctxs[SUB_PARTITIONS_AB],
3182
                               int mi_row, int mi_col, BLOCK_SIZE bsize,
3183
                               PARTITION_TYPE partition,
3184
                               const BLOCK_SIZE ab_subsize[SUB_PARTITIONS_AB],
3185
                               const int ab_mi_pos[SUB_PARTITIONS_AB][2],
3186
0
                               const MB_MODE_INFO **mode_cache) {
3187
0
  MACROBLOCK *const x = &td->mb;
3188
0
  const MACROBLOCKD *const xd = &x->e_mbd;
3189
0
  const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3190
0
  RD_STATS sum_rdc;
3191
0
  av1_init_rd_stats(&sum_rdc);
3192
0
  sum_rdc.rate = x->mode_costs.partition_cost[pl][partition];
3193
0
  sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, 0);
3194
  // Loop over sub-partitions in AB partition type.
3195
0
  for (int i = 0; i < SUB_PARTITIONS_AB; i++) {
3196
0
    if (mode_cache && mode_cache[i]) {
3197
0
      x->use_mb_mode_cache = 1;
3198
0
      x->mb_mode_cache = mode_cache[i];
3199
0
    }
3200
0
    const int mode_search_success =
3201
0
        rd_try_subblock(cpi, td, tile_data, tp, i == SUB_PARTITIONS_AB - 1,
3202
0
                        ab_mi_pos[i][0], ab_mi_pos[i][1], ab_subsize[i],
3203
0
                        *best_rdc, &sum_rdc, partition, ctxs[i]);
3204
0
    x->use_mb_mode_cache = 0;
3205
0
    x->mb_mode_cache = NULL;
3206
0
    if (!mode_search_success) {
3207
0
      return false;
3208
0
    }
3209
0
  }
3210
3211
0
  av1_rd_cost_update(x->rdmult, &sum_rdc);
3212
0
  *this_rdcost = sum_rdc.rdcost;
3213
0
  if (sum_rdc.rdcost >= best_rdc->rdcost) return false;
3214
0
  sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, sum_rdc.dist);
3215
0
  *this_rdcost = sum_rdc.rdcost;
3216
0
  if (sum_rdc.rdcost >= best_rdc->rdcost) return false;
3217
3218
0
  *best_rdc = sum_rdc;
3219
0
  pc_tree->partitioning = partition;
3220
0
  return true;
3221
0
}
3222
3223
#if CONFIG_COLLECT_PARTITION_STATS
3224
static void init_partition_block_timing_stats(
3225
    PartitionTimingStats *part_timing_stats) {
3226
  av1_zero(*part_timing_stats);
3227
}
3228
3229
static inline void start_partition_block_timer(
3230
    PartitionTimingStats *part_timing_stats, PARTITION_TYPE partition_type) {
3231
  assert(!part_timing_stats->timer_is_on);
3232
  part_timing_stats->partition_attempts[partition_type] += 1;
3233
  aom_usec_timer_start(&part_timing_stats->timer);
3234
  part_timing_stats->timer_is_on = 1;
3235
}
3236
3237
static inline void end_partition_block_timer(
3238
    PartitionTimingStats *part_timing_stats, PARTITION_TYPE partition_type,
3239
    int64_t rdcost) {
3240
  if (part_timing_stats->timer_is_on) {
3241
    aom_usec_timer_mark(&part_timing_stats->timer);
3242
    const int64_t time = aom_usec_timer_elapsed(&part_timing_stats->timer);
3243
    part_timing_stats->partition_times[partition_type] += time;
3244
    part_timing_stats->partition_rdcost[partition_type] = rdcost;
3245
    part_timing_stats->timer_is_on = 0;
3246
  }
3247
}
3248
static inline void print_partition_timing_stats_with_rdcost(
3249
    const PartitionTimingStats *part_timing_stats, int mi_row, int mi_col,
3250
    BLOCK_SIZE bsize, FRAME_UPDATE_TYPE frame_update_type, int frame_number,
3251
    const RD_STATS *best_rdc, const char *filename) {
3252
  FILE *f = fopen(filename, "a");
3253
  fprintf(f, "%d,%d,%d,%d,%d,%d,%" PRId64 ",%" PRId64 ",", bsize, frame_number,
3254
          frame_update_type, mi_row, mi_col, best_rdc->rate, best_rdc->dist,
3255
          best_rdc->rdcost);
3256
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3257
    fprintf(f, "%d,", part_timing_stats->partition_decisions[idx]);
3258
  }
3259
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3260
    fprintf(f, "%d,", part_timing_stats->partition_attempts[idx]);
3261
  }
3262
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3263
    fprintf(f, "%" PRId64 ",", part_timing_stats->partition_times[idx]);
3264
  }
3265
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3266
    if (part_timing_stats->partition_rdcost[idx] == INT64_MAX) {
3267
      fprintf(f, "%d,", -1);
3268
    } else {
3269
      fprintf(f, "%" PRId64 ",", part_timing_stats->partition_rdcost[idx]);
3270
    }
3271
  }
3272
  fprintf(f, "\n");
3273
  fclose(f);
3274
}
3275
3276
static inline void print_partition_timing_stats(
3277
    const PartitionTimingStats *part_timing_stats, int intra_only,
3278
    int show_frame, const BLOCK_SIZE bsize, const char *filename) {
3279
  FILE *f = fopen(filename, "a");
3280
  fprintf(f, "%d,%d,%d,", bsize, show_frame, intra_only);
3281
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3282
    fprintf(f, "%d,", part_timing_stats->partition_decisions[idx]);
3283
  }
3284
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3285
    fprintf(f, "%d,", part_timing_stats->partition_attempts[idx]);
3286
  }
3287
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3288
    fprintf(f, "%" PRId64 ",", part_timing_stats->partition_times[idx]);
3289
  }
3290
  fprintf(f, "\n");
3291
  fclose(f);
3292
}
3293
3294
static inline void accumulate_partition_timing_stats(
3295
    FramePartitionTimingStats *fr_part_timing_stats,
3296
    const PartitionTimingStats *part_timing_stats, BLOCK_SIZE bsize) {
3297
  const int bsize_idx = av1_get_bsize_idx_for_part_stats(bsize);
3298
  int *agg_attempts = fr_part_timing_stats->partition_attempts[bsize_idx];
3299
  int *agg_decisions = fr_part_timing_stats->partition_decisions[bsize_idx];
3300
  int64_t *agg_times = fr_part_timing_stats->partition_times[bsize_idx];
3301
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3302
    agg_attempts[idx] += part_timing_stats->partition_attempts[idx];
3303
    agg_decisions[idx] += part_timing_stats->partition_decisions[idx];
3304
    agg_times[idx] += part_timing_stats->partition_times[idx];
3305
  }
3306
}
3307
#endif  // CONFIG_COLLECT_PARTITION_STATS
3308
3309
// Initialize state variables of partition search used in
3310
// av1_rd_pick_partition().
3311
static void init_partition_search_state_params(
3312
    MACROBLOCK *x, AV1_COMP *const cpi, PartitionSearchState *part_search_state,
3313
15.6M
    int mi_row, int mi_col, BLOCK_SIZE bsize) {
3314
15.6M
  MACROBLOCKD *const xd = &x->e_mbd;
3315
15.6M
  const AV1_COMMON *const cm = &cpi->common;
3316
15.6M
  PartitionBlkParams *blk_params = &part_search_state->part_blk_params;
3317
15.6M
  const CommonModeInfoParams *const mi_params = &cpi->common.mi_params;
3318
3319
  // Initialization of block size related parameters.
3320
15.6M
  blk_params->mi_step = mi_size_wide[bsize] / 2;
3321
15.6M
  blk_params->mi_row = mi_row;
3322
15.6M
  blk_params->mi_col = mi_col;
3323
15.6M
  blk_params->mi_row_edge = mi_row + blk_params->mi_step;
3324
15.6M
  blk_params->mi_col_edge = mi_col + blk_params->mi_step;
3325
15.6M
  blk_params->width = block_size_wide[bsize];
3326
15.6M
  blk_params->min_partition_size_1d =
3327
15.6M
      block_size_wide[x->sb_enc.min_partition_size];
3328
15.6M
  blk_params->subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
3329
15.6M
  blk_params->split_bsize2 = blk_params->subsize;
3330
15.6M
  blk_params->bsize_at_least_8x8 = (bsize >= BLOCK_8X8);
3331
15.6M
  blk_params->bsize = bsize;
3332
3333
  // Check if the partition corresponds to edge block.
3334
15.6M
  blk_params->has_rows = (blk_params->mi_row_edge < mi_params->mi_rows);
3335
15.6M
  blk_params->has_cols = (blk_params->mi_col_edge < mi_params->mi_cols);
3336
3337
  // Update intra partitioning related info.
3338
15.6M
  part_search_state->intra_part_info = &x->part_search_info;
3339
  // Prepare for segmentation CNN-based partitioning for intra-frame.
3340
15.6M
  if (frame_is_intra_only(cm) && bsize == BLOCK_64X64) {
3341
252k
    part_search_state->intra_part_info->quad_tree_idx = 0;
3342
252k
    part_search_state->intra_part_info->cnn_output_valid = 0;
3343
252k
  }
3344
3345
  // Set partition plane context index.
3346
15.6M
  part_search_state->pl_ctx_idx =
3347
15.6M
      blk_params->bsize_at_least_8x8
3348
15.6M
          ? partition_plane_context(xd, mi_row, mi_col, bsize)
3349
15.6M
          : 0;
3350
3351
  // Partition cost buffer update
3352
15.6M
  ModeCosts *mode_costs = &x->mode_costs;
3353
15.6M
  part_search_state->partition_cost =
3354
15.6M
      mode_costs->partition_cost[part_search_state->pl_ctx_idx];
3355
3356
  // Initialize HORZ and VERT win flags as true for all split partitions.
3357
78.4M
  for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
3358
62.7M
    part_search_state->split_part_rect_win[i].rect_part_win[HORZ] = true;
3359
62.7M
    part_search_state->split_part_rect_win[i].rect_part_win[VERT] = true;
3360
62.7M
  }
3361
3362
  // Initialize the rd cost.
3363
15.6M
  av1_init_rd_stats(&part_search_state->this_rdc);
3364
3365
  // Initialize RD costs for partition types to 0.
3366
15.6M
  part_search_state->none_rd = 0;
3367
15.6M
  av1_zero(part_search_state->split_rd);
3368
15.6M
  av1_zero(part_search_state->rect_part_rd);
3369
3370
  // Initialize SPLIT partition to be not ready.
3371
15.6M
  av1_zero(part_search_state->is_split_ctx_is_ready);
3372
  // Initialize HORZ and VERT partitions to be not ready.
3373
15.6M
  av1_zero(part_search_state->is_rect_ctx_is_ready);
3374
3375
  // Chroma subsampling.
3376
15.6M
  part_search_state->ss_x = x->e_mbd.plane[1].subsampling_x;
3377
15.6M
  part_search_state->ss_y = x->e_mbd.plane[1].subsampling_y;
3378
3379
  // Initialize partition search flags to defaults.
3380
15.6M
  part_search_state->terminate_partition_search = 0;
3381
15.6M
  part_search_state->do_square_split = blk_params->bsize_at_least_8x8;
3382
15.6M
  part_search_state->do_rectangular_split =
3383
15.6M
      cpi->oxcf.part_cfg.enable_rect_partitions &&
3384
15.6M
      blk_params->bsize_at_least_8x8;
3385
15.6M
  av1_zero(part_search_state->prune_rect_part);
3386
3387
  // Initialize allowed partition types for the partition block.
3388
15.6M
  part_search_state->partition_none_allowed =
3389
15.6M
      av1_blk_has_rows_and_cols(blk_params);
3390
15.6M
  part_search_state->partition_rect_allowed[HORZ] =
3391
15.6M
      part_search_state->do_rectangular_split && blk_params->has_cols &&
3392
7.08M
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_HORZ),
3393
7.08M
                           part_search_state->ss_x,
3394
7.08M
                           part_search_state->ss_y) != BLOCK_INVALID;
3395
15.6M
  part_search_state->partition_rect_allowed[VERT] =
3396
15.6M
      part_search_state->do_rectangular_split && blk_params->has_rows &&
3397
7.04M
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_VERT),
3398
7.04M
                           part_search_state->ss_x,
3399
7.04M
                           part_search_state->ss_y) != BLOCK_INVALID;
3400
3401
  // Reset the flag indicating whether a partition leading to a rdcost lower
3402
  // than the bound best_rdc has been found.
3403
15.6M
  part_search_state->found_best_partition = false;
3404
3405
#if CONFIG_COLLECT_PARTITION_STATS
3406
  init_partition_block_timing_stats(&part_search_state->part_timing_stats);
3407
#endif  // CONFIG_COLLECT_PARTITION_STATS
3408
15.6M
}
3409
3410
// Override partition cost buffer for the edge blocks.
3411
static void set_partition_cost_for_edge_blk(
3412
993k
    AV1_COMMON const *cm, PartitionSearchState *part_search_state) {
3413
993k
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3414
993k
  assert(blk_params.bsize_at_least_8x8 && part_search_state->pl_ctx_idx >= 0);
3415
993k
  const aom_cdf_prob *partition_cdf =
3416
993k
      cm->fc->partition_cdf[part_search_state->pl_ctx_idx];
3417
993k
  const int max_cost = av1_cost_symbol(0);
3418
4.96M
  for (PARTITION_TYPE i = 0; i < PARTITION_TYPES; ++i)
3419
3.97M
    part_search_state->tmp_partition_cost[i] = max_cost;
3420
993k
  if (blk_params.has_cols) {
3421
    // At the bottom, the two possibilities are HORZ and SPLIT.
3422
460k
    aom_cdf_prob bot_cdf[2];
3423
460k
    partition_gather_vert_alike(bot_cdf, partition_cdf, blk_params.bsize);
3424
460k
    static const int bot_inv_map[2] = { PARTITION_HORZ, PARTITION_SPLIT };
3425
460k
    av1_cost_tokens_from_cdf(part_search_state->tmp_partition_cost, bot_cdf,
3426
460k
                             bot_inv_map);
3427
533k
  } else if (blk_params.has_rows) {
3428
    // At the right, the two possibilities are VERT and SPLIT.
3429
422k
    aom_cdf_prob rhs_cdf[2];
3430
422k
    partition_gather_horz_alike(rhs_cdf, partition_cdf, blk_params.bsize);
3431
422k
    static const int rhs_inv_map[2] = { PARTITION_VERT, PARTITION_SPLIT };
3432
422k
    av1_cost_tokens_from_cdf(part_search_state->tmp_partition_cost, rhs_cdf,
3433
422k
                             rhs_inv_map);
3434
422k
  } else {
3435
    // At the bottom right, we always split.
3436
110k
    part_search_state->tmp_partition_cost[PARTITION_SPLIT] = 0;
3437
110k
  }
3438
  // Override the partition cost buffer.
3439
993k
  part_search_state->partition_cost = part_search_state->tmp_partition_cost;
3440
993k
}
3441
3442
// Reset the partition search state flags when
3443
// must_find_valid_partition is equal to 1.
3444
static inline void reset_part_limitations(
3445
0
    AV1_COMP *const cpi, PartitionSearchState *part_search_state) {
3446
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3447
0
  const int is_rect_part_allowed =
3448
0
      blk_params.bsize_at_least_8x8 &&
3449
0
      cpi->oxcf.part_cfg.enable_rect_partitions &&
3450
0
      (blk_params.width > blk_params.min_partition_size_1d);
3451
0
  part_search_state->do_square_split =
3452
0
      blk_params.bsize_at_least_8x8 &&
3453
0
      (blk_params.width > blk_params.min_partition_size_1d);
3454
0
  part_search_state->partition_none_allowed =
3455
0
      av1_blk_has_rows_and_cols(&blk_params) &&
3456
0
      (blk_params.width >= blk_params.min_partition_size_1d);
3457
0
  part_search_state->partition_rect_allowed[HORZ] =
3458
0
      blk_params.has_cols && is_rect_part_allowed &&
3459
0
      get_plane_block_size(
3460
0
          get_partition_subsize(blk_params.bsize, PARTITION_HORZ),
3461
0
          part_search_state->ss_x, part_search_state->ss_y) != BLOCK_INVALID;
3462
0
  part_search_state->partition_rect_allowed[VERT] =
3463
0
      blk_params.has_rows && is_rect_part_allowed &&
3464
0
      get_plane_block_size(
3465
0
          get_partition_subsize(blk_params.bsize, PARTITION_VERT),
3466
0
          part_search_state->ss_x, part_search_state->ss_y) != BLOCK_INVALID;
3467
0
  part_search_state->terminate_partition_search = 0;
3468
0
}
3469
3470
// Rectangular partitions evaluation at sub-block level.
3471
static void rd_pick_rect_partition(AV1_COMP *const cpi, TileDataEnc *tile_data,
3472
                                   MACROBLOCK *x,
3473
                                   PICK_MODE_CONTEXT *cur_partition_ctx,
3474
                                   PartitionSearchState *part_search_state,
3475
                                   RD_STATS *best_rdc, const int idx,
3476
                                   int mi_row, int mi_col, BLOCK_SIZE bsize,
3477
1.37M
                                   PARTITION_TYPE partition_type) {
3478
  // Obtain the remainder from the best rd cost
3479
  // for further processing of partition.
3480
1.37M
  RD_STATS best_remain_rdcost;
3481
1.37M
  av1_rd_stats_subtraction(x->rdmult, best_rdc, &part_search_state->sum_rdc,
3482
1.37M
                           &best_remain_rdcost);
3483
3484
  // Obtain the best mode for the partition sub-block.
3485
1.37M
  pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &part_search_state->this_rdc,
3486
1.37M
                partition_type, bsize, cur_partition_ctx, best_remain_rdcost);
3487
1.37M
  av1_rd_cost_update(x->rdmult, &part_search_state->this_rdc);
3488
3489
  // Update the partition rd cost with the current sub-block rd.
3490
1.37M
  if (part_search_state->this_rdc.rate == INT_MAX) {
3491
475k
    part_search_state->sum_rdc.rdcost = INT64_MAX;
3492
898k
  } else {
3493
898k
    part_search_state->sum_rdc.rate += part_search_state->this_rdc.rate;
3494
898k
    part_search_state->sum_rdc.dist += part_search_state->this_rdc.dist;
3495
898k
    av1_rd_cost_update(x->rdmult, &part_search_state->sum_rdc);
3496
898k
  }
3497
1.37M
  const RECT_PART_TYPE rect_part =
3498
1.37M
      partition_type == PARTITION_HORZ ? HORZ : VERT;
3499
1.37M
  part_search_state->rect_part_rd[rect_part][idx] =
3500
1.37M
      part_search_state->this_rdc.rdcost;
3501
1.37M
}
3502
3503
typedef int (*active_edge_info)(const AV1_COMP *cpi, int mi_col, int mi_step);
3504
3505
// Checks if HORZ / VERT partition search is allowed.
3506
static inline int is_rect_part_allowed(
3507
    const AV1_COMP *cpi, const PartitionSearchState *part_search_state,
3508
    const active_edge_info *active_edge, RECT_PART_TYPE rect_part,
3509
31.3M
    const int mi_pos) {
3510
31.3M
  const PartitionBlkParams *blk_params = &part_search_state->part_blk_params;
3511
31.3M
  const int is_part_allowed =
3512
31.3M
      (!part_search_state->terminate_partition_search &&
3513
28.6M
       part_search_state->partition_rect_allowed[rect_part] &&
3514
3.15M
       !part_search_state->prune_rect_part[rect_part] &&
3515
2.42M
       (part_search_state->do_rectangular_split ||
3516
2.04M
        active_edge[rect_part](cpi, mi_pos, blk_params->mi_step)));
3517
31.3M
  return is_part_allowed;
3518
31.3M
}
3519
3520
static void rectangular_partition_search(
3521
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3522
    TokenExtra **tp, MACROBLOCK *x, PC_TREE *pc_tree,
3523
    RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3524
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
3525
    RD_RECT_PART_WIN_INFO *rect_part_win_info, const RECT_PART_TYPE start_type,
3526
15.6M
    const RECT_PART_TYPE end_type) {
3527
15.6M
  const AV1_COMMON *const cm = &cpi->common;
3528
15.6M
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3529
15.6M
  RD_STATS *sum_rdc = &part_search_state->sum_rdc;
3530
15.6M
  const int rect_partition_type[NUM_RECT_PARTS] = { PARTITION_HORZ,
3531
15.6M
                                                    PARTITION_VERT };
3532
3533
  // mi_pos_rect[NUM_RECT_PARTS][SUB_PARTITIONS_RECT][0]: mi_row postion of
3534
  //                                           HORZ and VERT partition types.
3535
  // mi_pos_rect[NUM_RECT_PARTS][SUB_PARTITIONS_RECT][1]: mi_col postion of
3536
  //                                           HORZ and VERT partition types.
3537
15.6M
  const int mi_pos_rect[NUM_RECT_PARTS][SUB_PARTITIONS_RECT][2] = {
3538
15.6M
    { { blk_params.mi_row, blk_params.mi_col },
3539
15.6M
      { blk_params.mi_row_edge, blk_params.mi_col } },
3540
15.6M
    { { blk_params.mi_row, blk_params.mi_col },
3541
15.6M
      { blk_params.mi_row, blk_params.mi_col_edge } }
3542
15.6M
  };
3543
3544
  // Initialize active edge_type function pointer
3545
  // for HOZR and VERT partition types.
3546
15.6M
  active_edge_info active_edge_type[NUM_RECT_PARTS] = { av1_active_h_edge,
3547
15.6M
                                                        av1_active_v_edge };
3548
3549
  // Indicates edge blocks for HORZ and VERT partition types.
3550
15.6M
  const int is_not_edge_block[NUM_RECT_PARTS] = { blk_params.has_rows,
3551
15.6M
                                                  blk_params.has_cols };
3552
3553
  // Initialize pc tree context for HORZ and VERT partition types.
3554
15.6M
  PICK_MODE_CONTEXT **cur_ctx[NUM_RECT_PARTS][SUB_PARTITIONS_RECT] = {
3555
15.6M
    { &pc_tree->horizontal[0], &pc_tree->horizontal[1] },
3556
15.6M
    { &pc_tree->vertical[0], &pc_tree->vertical[1] }
3557
15.6M
  };
3558
3559
  // Loop over rectangular partition types.
3560
47.0M
  for (RECT_PART_TYPE i = start_type; i <= end_type; i++) {
3561
31.3M
    assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
3562
31.3M
                   !part_search_state->partition_rect_allowed[i]));
3563
3564
    // Check if the HORZ / VERT partition search is to be performed.
3565
31.3M
    if (!is_rect_part_allowed(cpi, part_search_state, active_edge_type, i,
3566
31.3M
                              mi_pos_rect[i][0][i]))
3567
30.4M
      continue;
3568
3569
    // Sub-partition idx.
3570
932k
    int sub_part_idx = 0;
3571
932k
    PARTITION_TYPE partition_type = rect_partition_type[i];
3572
932k
    blk_params.subsize =
3573
932k
        get_partition_subsize(blk_params.bsize, partition_type);
3574
932k
    assert(blk_params.subsize <= BLOCK_LARGEST);
3575
932k
    av1_init_rd_stats(sum_rdc);
3576
2.80M
    for (int j = 0; j < SUB_PARTITIONS_RECT; j++) {
3577
1.87M
      if (cur_ctx[i][j][0] == NULL) {
3578
1.87M
        cur_ctx[i][j][0] =
3579
1.87M
            av1_alloc_pmc(cpi, blk_params.subsize, &td->shared_coeff_buf);
3580
1.87M
        if (!cur_ctx[i][j][0])
3581
0
          aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
3582
0
                             "Failed to allocate PICK_MODE_CONTEXT");
3583
1.87M
      }
3584
1.87M
    }
3585
932k
    sum_rdc->rate = part_search_state->partition_cost[partition_type];
3586
932k
    sum_rdc->rdcost = RDCOST(x->rdmult, sum_rdc->rate, 0);
3587
#if CONFIG_COLLECT_PARTITION_STATS
3588
    PartitionTimingStats *part_timing_stats =
3589
        &part_search_state->part_timing_stats;
3590
    if (best_rdc->rdcost - sum_rdc->rdcost >= 0) {
3591
      start_partition_block_timer(part_timing_stats, partition_type);
3592
    }
3593
#endif
3594
3595
    // First sub-partition evaluation in HORZ / VERT partition type.
3596
932k
    rd_pick_rect_partition(
3597
932k
        cpi, tile_data, x, cur_ctx[i][sub_part_idx][0], part_search_state,
3598
932k
        best_rdc, 0, mi_pos_rect[i][sub_part_idx][0],
3599
932k
        mi_pos_rect[i][sub_part_idx][1], blk_params.subsize, partition_type);
3600
3601
    // Start of second sub-partition evaluation.
3602
    // Evaluate second sub-partition if the first sub-partition cost
3603
    // is less than the best cost and if it is not an edge block.
3604
932k
    if (sum_rdc->rdcost < best_rdc->rdcost && is_not_edge_block[i]) {
3605
436k
      const MB_MODE_INFO *const mbmi = &cur_ctx[i][sub_part_idx][0]->mic;
3606
436k
      const PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
3607
      // Neither palette mode nor cfl predicted.
3608
436k
      if (pmi->palette_size[PLANE_TYPE_Y] == 0 &&
3609
374k
          pmi->palette_size[PLANE_TYPE_UV] == 0) {
3610
373k
        if (mbmi->uv_mode != UV_CFL_PRED)
3611
333k
          part_search_state->is_rect_ctx_is_ready[i] = 1;
3612
373k
      }
3613
436k
      av1_update_state(cpi, td, cur_ctx[i][sub_part_idx][0], blk_params.mi_row,
3614
436k
                       blk_params.mi_col, blk_params.subsize, DRY_RUN_NORMAL);
3615
436k
      encode_superblock(cpi, tile_data, td, tp, DRY_RUN_NORMAL,
3616
436k
                        blk_params.subsize, NULL);
3617
3618
      // Second sub-partition evaluation in HORZ / VERT partition type.
3619
436k
      sub_part_idx = 1;
3620
436k
      rd_pick_rect_partition(
3621
436k
          cpi, tile_data, x, cur_ctx[i][sub_part_idx][0], part_search_state,
3622
436k
          best_rdc, 1, mi_pos_rect[i][sub_part_idx][0],
3623
436k
          mi_pos_rect[i][sub_part_idx][1], blk_params.subsize, partition_type);
3624
436k
    }
3625
    // Update HORZ / VERT best partition.
3626
932k
    if (sum_rdc->rdcost < best_rdc->rdcost) {
3627
234k
      sum_rdc->rdcost = RDCOST(x->rdmult, sum_rdc->rate, sum_rdc->dist);
3628
234k
      if (sum_rdc->rdcost < best_rdc->rdcost) {
3629
234k
        *best_rdc = *sum_rdc;
3630
234k
        part_search_state->found_best_partition = true;
3631
234k
        pc_tree->partitioning = partition_type;
3632
234k
      }
3633
698k
    } else {
3634
      // Update HORZ / VERT win flag.
3635
698k
      if (rect_part_win_info != NULL)
3636
679k
        rect_part_win_info->rect_part_win[i] = false;
3637
698k
    }
3638
#if CONFIG_COLLECT_PARTITION_STATS
3639
    if (part_timing_stats->timer_is_on) {
3640
      end_partition_block_timer(part_timing_stats, partition_type,
3641
                                sum_rdc->rdcost);
3642
    }
3643
#endif
3644
932k
    av1_restore_context(x, x_ctx, blk_params.mi_row, blk_params.mi_col,
3645
932k
                        blk_params.bsize, av1_num_planes(cm));
3646
932k
  }
3647
15.6M
}
3648
3649
// AB partition type evaluation.
3650
static void rd_pick_ab_part(
3651
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3652
    TokenExtra **tp, MACROBLOCK *x, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3653
    PC_TREE *pc_tree, PICK_MODE_CONTEXT *dst_ctxs[SUB_PARTITIONS_AB],
3654
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
3655
    const BLOCK_SIZE ab_subsize[SUB_PARTITIONS_AB],
3656
    const int ab_mi_pos[SUB_PARTITIONS_AB][2], const PARTITION_TYPE part_type,
3657
0
    const MB_MODE_INFO **mode_cache) {
3658
0
  const AV1_COMMON *const cm = &cpi->common;
3659
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3660
0
  const int mi_row = blk_params.mi_row;
3661
0
  const int mi_col = blk_params.mi_col;
3662
0
  const BLOCK_SIZE bsize = blk_params.bsize;
3663
0
  int64_t this_rdcost = 0;
3664
3665
#if CONFIG_COLLECT_PARTITION_STATS
3666
  PartitionTimingStats *part_timing_stats =
3667
      &part_search_state->part_timing_stats;
3668
  {
3669
    RD_STATS tmp_sum_rdc;
3670
    av1_init_rd_stats(&tmp_sum_rdc);
3671
    tmp_sum_rdc.rate = part_search_state->partition_cost[part_type];
3672
    tmp_sum_rdc.rdcost = RDCOST(x->rdmult, tmp_sum_rdc.rate, 0);
3673
    if (best_rdc->rdcost - tmp_sum_rdc.rdcost >= 0) {
3674
      start_partition_block_timer(part_timing_stats, part_type);
3675
    }
3676
  }
3677
#endif
3678
3679
  // Test this partition and update the best partition.
3680
0
  const bool find_best_ab_part = rd_test_partition3(
3681
0
      cpi, td, tile_data, tp, pc_tree, best_rdc, &this_rdcost, dst_ctxs, mi_row,
3682
0
      mi_col, bsize, part_type, ab_subsize, ab_mi_pos, mode_cache);
3683
0
  part_search_state->found_best_partition |= find_best_ab_part;
3684
3685
#if CONFIG_COLLECT_PARTITION_STATS
3686
  if (part_timing_stats->timer_is_on) {
3687
    if (!find_best_ab_part) this_rdcost = INT64_MAX;
3688
    end_partition_block_timer(part_timing_stats, part_type, this_rdcost);
3689
  }
3690
#endif
3691
0
  av1_restore_context(x, x_ctx, mi_row, mi_col, bsize, av1_num_planes(cm));
3692
0
}
3693
3694
// Set mode search context.
3695
static inline void set_mode_search_ctx(
3696
    PC_TREE *pc_tree, const int is_ctx_ready[NUM_AB_PARTS][2],
3697
14.3M
    PICK_MODE_CONTEXT **mode_srch_ctx[NUM_AB_PARTS][2]) {
3698
14.3M
  mode_srch_ctx[HORZ_B][0] = &pc_tree->horizontal[0];
3699
14.3M
  mode_srch_ctx[VERT_B][0] = &pc_tree->vertical[0];
3700
3701
14.3M
  if (is_ctx_ready[HORZ_A][0])
3702
3.13M
    mode_srch_ctx[HORZ_A][0] = &pc_tree->split[0]->none;
3703
3704
14.3M
  if (is_ctx_ready[VERT_A][0])
3705
3.13M
    mode_srch_ctx[VERT_A][0] = &pc_tree->split[0]->none;
3706
3707
14.3M
  if (is_ctx_ready[HORZ_A][1])
3708
2.73M
    mode_srch_ctx[HORZ_A][1] = &pc_tree->split[1]->none;
3709
14.3M
}
3710
3711
static inline void copy_partition_mode_from_mode_context(
3712
0
    const MB_MODE_INFO **dst_mode, const PICK_MODE_CONTEXT *ctx) {
3713
0
  if (ctx && ctx->rd_stats.rate < INT_MAX) {
3714
0
    *dst_mode = &ctx->mic;
3715
0
  } else {
3716
0
    *dst_mode = NULL;
3717
0
  }
3718
0
}
3719
3720
static inline void copy_partition_mode_from_pc_tree(
3721
0
    const MB_MODE_INFO **dst_mode, const PC_TREE *pc_tree) {
3722
0
  if (pc_tree) {
3723
0
    copy_partition_mode_from_mode_context(dst_mode, pc_tree->none);
3724
0
  } else {
3725
0
    *dst_mode = NULL;
3726
0
  }
3727
0
}
3728
3729
static inline void set_mode_cache_for_partition_ab(
3730
    const MB_MODE_INFO **mode_cache, const PC_TREE *pc_tree,
3731
0
    AB_PART_TYPE ab_part_type) {
3732
0
  switch (ab_part_type) {
3733
0
    case HORZ_A:
3734
0
      copy_partition_mode_from_pc_tree(&mode_cache[0], pc_tree->split[0]);
3735
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[1]);
3736
0
      copy_partition_mode_from_mode_context(&mode_cache[2],
3737
0
                                            pc_tree->horizontal[1]);
3738
0
      break;
3739
0
    case HORZ_B:
3740
0
      copy_partition_mode_from_mode_context(&mode_cache[0],
3741
0
                                            pc_tree->horizontal[0]);
3742
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[2]);
3743
0
      copy_partition_mode_from_pc_tree(&mode_cache[2], pc_tree->split[3]);
3744
0
      break;
3745
0
    case VERT_A:
3746
0
      copy_partition_mode_from_pc_tree(&mode_cache[0], pc_tree->split[0]);
3747
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[2]);
3748
0
      copy_partition_mode_from_mode_context(&mode_cache[2],
3749
0
                                            pc_tree->vertical[1]);
3750
0
      break;
3751
0
    case VERT_B:
3752
0
      copy_partition_mode_from_mode_context(&mode_cache[0],
3753
0
                                            pc_tree->vertical[0]);
3754
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[1]);
3755
0
      copy_partition_mode_from_pc_tree(&mode_cache[2], pc_tree->split[3]);
3756
0
      break;
3757
0
    default: assert(0 && "Invalid ab partition type!\n");
3758
0
  }
3759
0
}
3760
3761
// AB Partitions type search.
3762
static void ab_partitions_search(
3763
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3764
    TokenExtra **tp, MACROBLOCK *x, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3765
    PC_TREE *pc_tree, PartitionSearchState *part_search_state,
3766
    RD_STATS *best_rdc, RD_RECT_PART_WIN_INFO *rect_part_win_info,
3767
    int pb_source_variance, int ext_partition_allowed,
3768
15.6M
    const AB_PART_TYPE start_type, const AB_PART_TYPE end_type) {
3769
15.6M
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3770
15.6M
  const int mi_row = blk_params.mi_row;
3771
15.6M
  const int mi_col = blk_params.mi_col;
3772
15.6M
  const BLOCK_SIZE bsize = blk_params.bsize;
3773
3774
15.6M
  if (part_search_state->terminate_partition_search) {
3775
1.37M
    return;
3776
1.37M
  }
3777
3778
14.3M
  int ab_partitions_allowed[NUM_AB_PARTS];
3779
  // Prune AB partitions
3780
14.3M
  av1_prune_ab_partitions(cpi, x, pc_tree, pb_source_variance, best_rdc->rdcost,
3781
14.3M
                          rect_part_win_info, ext_partition_allowed,
3782
14.3M
                          part_search_state, ab_partitions_allowed);
3783
3784
  // Flags to indicate whether the mode search is done.
3785
14.3M
  const int is_ctx_ready[NUM_AB_PARTS][2] = {
3786
14.3M
    { part_search_state->is_split_ctx_is_ready[0],
3787
14.3M
      part_search_state->is_split_ctx_is_ready[1] },
3788
14.3M
    { part_search_state->is_rect_ctx_is_ready[HORZ], 0 },
3789
14.3M
    { part_search_state->is_split_ctx_is_ready[0], 0 },
3790
14.3M
    { part_search_state->is_rect_ctx_is_ready[VERT], 0 }
3791
14.3M
  };
3792
3793
  // Current partition context.
3794
14.3M
  PICK_MODE_CONTEXT **cur_part_ctxs[NUM_AB_PARTS] = { pc_tree->horizontala,
3795
14.3M
                                                      pc_tree->horizontalb,
3796
14.3M
                                                      pc_tree->verticala,
3797
14.3M
                                                      pc_tree->verticalb };
3798
3799
  // Context of already evaluted partition types.
3800
14.3M
  PICK_MODE_CONTEXT **mode_srch_ctx[NUM_AB_PARTS][2];
3801
  // Set context of already evaluted partition types.
3802
14.3M
  set_mode_search_ctx(pc_tree, is_ctx_ready, mode_srch_ctx);
3803
3804
  // Array of sub-partition size of AB partition types.
3805
14.3M
  const BLOCK_SIZE ab_subsize[NUM_AB_PARTS][SUB_PARTITIONS_AB] = {
3806
14.3M
    { blk_params.split_bsize2, blk_params.split_bsize2,
3807
14.3M
      get_partition_subsize(bsize, PARTITION_HORZ_A) },
3808
14.3M
    { get_partition_subsize(bsize, PARTITION_HORZ_B), blk_params.split_bsize2,
3809
14.3M
      blk_params.split_bsize2 },
3810
14.3M
    { blk_params.split_bsize2, blk_params.split_bsize2,
3811
14.3M
      get_partition_subsize(bsize, PARTITION_VERT_A) },
3812
14.3M
    { get_partition_subsize(bsize, PARTITION_VERT_B), blk_params.split_bsize2,
3813
14.3M
      blk_params.split_bsize2 }
3814
14.3M
  };
3815
3816
  // Array of mi_row, mi_col positions corresponds to each sub-partition in AB
3817
  // partition types.
3818
14.3M
  const int ab_mi_pos[NUM_AB_PARTS][SUB_PARTITIONS_AB][2] = {
3819
14.3M
    { { mi_row, mi_col },
3820
14.3M
      { mi_row, blk_params.mi_col_edge },
3821
14.3M
      { blk_params.mi_row_edge, mi_col } },
3822
14.3M
    { { mi_row, mi_col },
3823
14.3M
      { blk_params.mi_row_edge, mi_col },
3824
14.3M
      { blk_params.mi_row_edge, blk_params.mi_col_edge } },
3825
14.3M
    { { mi_row, mi_col },
3826
14.3M
      { blk_params.mi_row_edge, mi_col },
3827
14.3M
      { mi_row, blk_params.mi_col_edge } },
3828
14.3M
    { { mi_row, mi_col },
3829
14.3M
      { mi_row, blk_params.mi_col_edge },
3830
14.3M
      { blk_params.mi_row_edge, blk_params.mi_col_edge } }
3831
14.3M
  };
3832
3833
  // Loop over AB partition types.
3834
71.5M
  for (AB_PART_TYPE ab_part_type = start_type; ab_part_type <= end_type;
3835
57.2M
       ab_part_type++) {
3836
57.2M
    const PARTITION_TYPE part_type = ab_part_type + PARTITION_HORZ_A;
3837
3838
    // Check if the AB partition search is to be performed.
3839
57.2M
    if (!ab_partitions_allowed[ab_part_type]) {
3840
57.2M
      continue;
3841
57.2M
    }
3842
3843
18.4E
    blk_params.subsize = get_partition_subsize(bsize, part_type);
3844
18.4E
    for (int i = 0; i < SUB_PARTITIONS_AB; i++) {
3845
      // Set AB partition context.
3846
0
      cur_part_ctxs[ab_part_type][i] = av1_alloc_pmc(
3847
0
          cpi, ab_subsize[ab_part_type][i], &td->shared_coeff_buf);
3848
0
      if (!cur_part_ctxs[ab_part_type][i])
3849
0
        aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
3850
0
                           "Failed to allocate PICK_MODE_CONTEXT");
3851
      // Set mode as not ready.
3852
0
      cur_part_ctxs[ab_part_type][i]->rd_mode_is_ready = 0;
3853
0
    }
3854
3855
18.4E
    if (cpi->sf.part_sf.reuse_prev_rd_results_for_part_ab) {
3856
      // We can copy directly the mode search results if we have already
3857
      // searched the current block and the contexts match.
3858
0
      if (is_ctx_ready[ab_part_type][0]) {
3859
0
        av1_copy_tree_context(cur_part_ctxs[ab_part_type][0],
3860
0
                              mode_srch_ctx[ab_part_type][0][0]);
3861
0
        cur_part_ctxs[ab_part_type][0]->mic.partition = part_type;
3862
0
        cur_part_ctxs[ab_part_type][0]->rd_mode_is_ready = 1;
3863
0
        if (is_ctx_ready[ab_part_type][1]) {
3864
0
          av1_copy_tree_context(cur_part_ctxs[ab_part_type][1],
3865
0
                                mode_srch_ctx[ab_part_type][1][0]);
3866
0
          cur_part_ctxs[ab_part_type][1]->mic.partition = part_type;
3867
0
          cur_part_ctxs[ab_part_type][1]->rd_mode_is_ready = 1;
3868
0
        }
3869
0
      }
3870
0
    }
3871
3872
    // Even if the contexts don't match, we can still speed up by reusing the
3873
    // previous prediction mode.
3874
18.4E
    const MB_MODE_INFO *mode_cache[3] = { NULL, NULL, NULL };
3875
18.4E
    if (cpi->sf.part_sf.reuse_best_prediction_for_part_ab) {
3876
0
      set_mode_cache_for_partition_ab(mode_cache, pc_tree, ab_part_type);
3877
0
    }
3878
3879
    // Evaluation of AB partition type.
3880
18.4E
    rd_pick_ab_part(cpi, td, tile_data, tp, x, x_ctx, pc_tree,
3881
18.4E
                    cur_part_ctxs[ab_part_type], part_search_state, best_rdc,
3882
18.4E
                    ab_subsize[ab_part_type], ab_mi_pos[ab_part_type],
3883
18.4E
                    part_type, mode_cache);
3884
18.4E
  }
3885
14.3M
}
3886
3887
// Set mi positions for HORZ4 / VERT4 sub-block partitions.
3888
static void set_mi_pos_partition4(const int inc_step[NUM_PART4_TYPES],
3889
                                  int mi_pos[SUB_PARTITIONS_PART4][2],
3890
0
                                  const int mi_row, const int mi_col) {
3891
0
  for (PART4_TYPES i = 0; i < SUB_PARTITIONS_PART4; i++) {
3892
0
    mi_pos[i][0] = mi_row + i * inc_step[HORZ4];
3893
0
    mi_pos[i][1] = mi_col + i * inc_step[VERT4];
3894
0
  }
3895
0
}
3896
3897
// Set context and RD cost for HORZ4 / VERT4 partition types.
3898
static void set_4_part_ctx_and_rdcost(
3899
    MACROBLOCK *x, const AV1_COMP *const cpi, ThreadData *td,
3900
    PICK_MODE_CONTEXT *cur_part_ctx[SUB_PARTITIONS_PART4],
3901
    PartitionSearchState *part_search_state, PARTITION_TYPE partition_type,
3902
0
    BLOCK_SIZE bsize) {
3903
  // Initialize sum_rdc RD cost structure.
3904
0
  av1_init_rd_stats(&part_search_state->sum_rdc);
3905
0
  const int subsize = get_partition_subsize(bsize, partition_type);
3906
0
  part_search_state->sum_rdc.rate =
3907
0
      part_search_state->partition_cost[partition_type];
3908
0
  part_search_state->sum_rdc.rdcost =
3909
0
      RDCOST(x->rdmult, part_search_state->sum_rdc.rate, 0);
3910
0
  for (PART4_TYPES i = 0; i < SUB_PARTITIONS_PART4; ++i) {
3911
0
    cur_part_ctx[i] = av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
3912
0
    if (!cur_part_ctx[i])
3913
0
      aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
3914
0
                         "Failed to allocate PICK_MODE_CONTEXT");
3915
0
  }
3916
0
}
3917
3918
// Partition search of HORZ4 / VERT4 partition types.
3919
static void rd_pick_4partition(
3920
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3921
    TokenExtra **tp, MACROBLOCK *x, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3922
    PC_TREE *pc_tree, PICK_MODE_CONTEXT *cur_part_ctx[SUB_PARTITIONS_PART4],
3923
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
3924
0
    const int inc_step[NUM_PART4_TYPES], PARTITION_TYPE partition_type) {
3925
0
  const AV1_COMMON *const cm = &cpi->common;
3926
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3927
  // mi positions needed for HORZ4 and VERT4 partition types.
3928
0
  int mi_pos_check[NUM_PART4_TYPES] = { cm->mi_params.mi_rows,
3929
0
                                        cm->mi_params.mi_cols };
3930
0
  const PART4_TYPES part4_idx = (partition_type != PARTITION_HORZ_4);
3931
0
  int mi_pos[SUB_PARTITIONS_PART4][2];
3932
3933
0
  blk_params.subsize = get_partition_subsize(blk_params.bsize, partition_type);
3934
  // Set partition context and RD cost.
3935
0
  set_4_part_ctx_and_rdcost(x, cpi, td, cur_part_ctx, part_search_state,
3936
0
                            partition_type, blk_params.bsize);
3937
  // Set mi positions for sub-block sizes.
3938
0
  set_mi_pos_partition4(inc_step, mi_pos, blk_params.mi_row, blk_params.mi_col);
3939
#if CONFIG_COLLECT_PARTITION_STATS
3940
  PartitionTimingStats *part_timing_stats =
3941
      &part_search_state->part_timing_stats;
3942
  if (best_rdc->rdcost - part_search_state->sum_rdc.rdcost >= 0) {
3943
    start_partition_block_timer(part_timing_stats, partition_type);
3944
  }
3945
#endif
3946
  // Loop over sub-block partitions.
3947
0
  for (PART4_TYPES i = 0; i < SUB_PARTITIONS_PART4; ++i) {
3948
0
    if (i > 0 && mi_pos[i][part4_idx] >= mi_pos_check[part4_idx]) break;
3949
3950
    // Sub-block evaluation of Horz4 / Vert4 partition type.
3951
0
    cur_part_ctx[i]->rd_mode_is_ready = 0;
3952
0
    if (!rd_try_subblock(
3953
0
            cpi, td, tile_data, tp, (i == SUB_PARTITIONS_PART4 - 1),
3954
0
            mi_pos[i][0], mi_pos[i][1], blk_params.subsize, *best_rdc,
3955
0
            &part_search_state->sum_rdc, partition_type, cur_part_ctx[i])) {
3956
0
      av1_invalid_rd_stats(&part_search_state->sum_rdc);
3957
0
      break;
3958
0
    }
3959
0
  }
3960
3961
  // Calculate the total cost and update the best partition.
3962
0
  av1_rd_cost_update(x->rdmult, &part_search_state->sum_rdc);
3963
0
  if (part_search_state->sum_rdc.rdcost < best_rdc->rdcost) {
3964
0
    *best_rdc = part_search_state->sum_rdc;
3965
0
    part_search_state->found_best_partition = true;
3966
0
    pc_tree->partitioning = partition_type;
3967
0
  }
3968
#if CONFIG_COLLECT_PARTITION_STATS
3969
  if (part_timing_stats->timer_is_on) {
3970
    end_partition_block_timer(part_timing_stats, partition_type,
3971
                              part_search_state->sum_rdc.rdcost);
3972
  }
3973
#endif
3974
0
  av1_restore_context(x, x_ctx, blk_params.mi_row, blk_params.mi_col,
3975
0
                      blk_params.bsize, av1_num_planes(cm));
3976
0
}
3977
3978
// Do not evaluate extended partitions if NONE partition is skippable.
3979
static inline int prune_ext_part_none_skippable(
3980
    PICK_MODE_CONTEXT *part_none, int must_find_valid_partition,
3981
15.6M
    int skip_non_sq_part_based_on_none, BLOCK_SIZE bsize) {
3982
15.6M
  if ((skip_non_sq_part_based_on_none >= 1) && (part_none != NULL)) {
3983
804k
    if (part_none->skippable && !must_find_valid_partition &&
3984
8.92k
        bsize >= BLOCK_16X16) {
3985
228
      return 1;
3986
228
    }
3987
804k
  }
3988
15.6M
  return 0;
3989
15.6M
}
3990
3991
// Allow ab partition search
3992
static int allow_ab_partition_search(PartitionSearchState *part_search_state,
3993
                                     PARTITION_SPEED_FEATURES *part_sf,
3994
                                     PARTITION_TYPE curr_best_part,
3995
                                     int must_find_valid_partition,
3996
                                     int prune_ext_part_state,
3997
15.6M
                                     int64_t best_rdcost) {
3998
15.6M
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
3999
15.6M
  const BLOCK_SIZE bsize = blk_params.bsize;
4000
4001
  // Do not prune if there is no valid partition
4002
15.6M
  if (best_rdcost == INT64_MAX) return 1;
4003
4004
  // Determine bsize threshold to evaluate ab partitions
4005
15.6M
  BLOCK_SIZE ab_bsize_thresh = part_sf->ext_partition_eval_thresh;
4006
15.6M
  if (part_sf->ext_part_eval_based_on_cur_best && !must_find_valid_partition &&
4007
0
      !(curr_best_part == PARTITION_HORZ || curr_best_part == PARTITION_VERT))
4008
0
    ab_bsize_thresh = BLOCK_128X128;
4009
4010
  // ab partitions are only allowed for square block sizes BLOCK_16X16 or
4011
  // higher, so ab_bsize_thresh must be large enough to exclude BLOCK_4X4 and
4012
  // BLOCK_8X8.
4013
15.6M
  assert(ab_bsize_thresh >= BLOCK_8X8);
4014
4015
15.6M
  int ab_partition_allowed =
4016
15.6M
      part_search_state->do_rectangular_split && bsize > ab_bsize_thresh &&
4017
0
      av1_blk_has_rows_and_cols(&blk_params) && !prune_ext_part_state;
4018
4019
15.6M
  return ab_partition_allowed;
4020
15.6M
}
4021
4022
// Prune 4-way partitions based on the number of horz/vert wins
4023
// in the current block and sub-blocks in PARTITION_SPLIT.
4024
static void prune_4_partition_using_split_info(
4025
    AV1_COMP *const cpi, MACROBLOCK *x, PartitionSearchState *part_search_state,
4026
1.06M
    int part4_search_allowed[NUM_PART4_TYPES]) {
4027
1.06M
  PART4_TYPES cur_part[NUM_PART4_TYPES] = { HORZ4, VERT4 };
4028
  // Count of child blocks in which HORZ or VERT partition has won
4029
1.06M
  int num_child_rect_win[NUM_RECT_PARTS] = { 0, 0 };
4030
  // Prune HORZ4/VERT4 partitions based on number of HORZ/VERT winners of
4031
  // split partiitons.
4032
  // Conservative pruning for high quantizers.
4033
1.06M
  const int num_win_thresh = AOMMIN(3 * (MAXQ - x->qindex) / MAXQ + 1, 3);
4034
4035
3.20M
  for (RECT_PART_TYPE i = HORZ; i < NUM_RECT_PARTS; i++) {
4036
2.13M
    if (!(cpi->sf.part_sf.prune_ext_part_using_split_info &&
4037
2.13M
          part4_search_allowed[cur_part[i]]))
4038
2.13M
      continue;
4039
    // Loop over split partitions.
4040
    // Get rectangular partitions winner info of split partitions.
4041
18.4E
    for (int idx = 0; idx < SUB_PARTITIONS_SPLIT; idx++)
4042
0
      num_child_rect_win[i] +=
4043
0
          (part_search_state->split_part_rect_win[idx].rect_part_win[i]) ? 1
4044
0
                                                                         : 0;
4045
18.4E
    if (num_child_rect_win[i] < num_win_thresh) {
4046
0
      part4_search_allowed[cur_part[i]] = 0;
4047
0
    }
4048
18.4E
  }
4049
1.06M
}
4050
4051
static void prune_part4_using_sms(AV1_COMP *const cpi, MACROBLOCK *x,
4052
                                  const PartitionSearchState *part_search_state,
4053
                                  SIMPLE_MOTION_DATA_TREE *sms_tree, int mi_row,
4054
                                  int mi_col, BLOCK_SIZE bsize,
4055
0
                                  int *part4_search_allowed) {
4056
0
  if (!part4_search_allowed[HORZ4] || !part4_search_allowed[VERT4]) return;
4057
4058
0
  unsigned int sms_h_part4_sse[4];
4059
0
  unsigned int sms_v_part4_sse[4];
4060
4061
0
  const BLOCK_SIZE subsize_h4 = get_partition_subsize(bsize, PARTITION_HORZ_4);
4062
0
  const BLOCK_SIZE subsize_v4 = get_partition_subsize(bsize, PARTITION_VERT_4);
4063
4064
0
  const int h_mi = mi_size_high[bsize];
4065
0
  const int w_mi = mi_size_wide[bsize];
4066
4067
0
  const int ref = cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
4068
0
  if (!(cpi->ref_frame_flags & av1_ref_frame_flag_list[ref])) return;
4069
4070
0
  int64_t part4_h_sse_sum = 0;
4071
0
  int64_t part4_v_sse_sum = 0;
4072
4073
  // ---- HORZ_4 ----
4074
0
  for (int r_idx = 0; r_idx < SUB_PARTITIONS_PART4; r_idx++) {
4075
0
    unsigned int part_var;
4076
0
    const int sub_mi_row = mi_row + r_idx * h_mi / 4;
4077
0
    const int sub_mi_col = mi_col;
4078
4079
0
    av1_simple_motion_search_sse_var(cpi, x, sub_mi_row, sub_mi_col, subsize_h4,
4080
0
                                     ref, sms_tree->start_mvs[ref],
4081
0
                                     /*num_planes=*/1, /*use_subpixel=*/1,
4082
0
                                     &sms_h_part4_sse[r_idx], &part_var);
4083
4084
0
    (void)part_var;
4085
4086
0
    part4_h_sse_sum += sms_h_part4_sse[r_idx];
4087
0
  }
4088
4089
  // ---- VERT_4 ----
4090
0
  for (int r_idx = 0; r_idx < SUB_PARTITIONS_PART4; r_idx++) {
4091
0
    unsigned int part_var;
4092
0
    const int sub_mi_row = mi_row;
4093
0
    const int sub_mi_col = mi_col + r_idx * w_mi / 4;
4094
4095
0
    av1_simple_motion_search_sse_var(cpi, x, sub_mi_row, sub_mi_col, subsize_v4,
4096
0
                                     ref, sms_tree->start_mvs[ref],
4097
0
                                     /*num_planes=*/1, /*use_subpixel=*/1,
4098
0
                                     &sms_v_part4_sse[r_idx], &part_var);
4099
0
    (void)part_var;
4100
4101
0
    part4_v_sse_sum += sms_v_part4_sse[r_idx];
4102
0
  }
4103
4104
  // ---- Skip RD calculation ----
4105
0
  const int64_t part4_h_rd =
4106
0
      RDCOST(x->rdmult, part_search_state->partition_cost[PARTITION_HORZ_4],
4107
0
             part4_h_sse_sum);
4108
4109
0
  const int64_t part4_v_rd =
4110
0
      RDCOST(x->rdmult, part_search_state->partition_cost[PARTITION_VERT_4],
4111
0
             part4_v_sse_sum);
4112
4113
  // ---- pruning ----
4114
0
  if (part4_h_rd > part4_v_rd) part4_search_allowed[HORZ4] = 0;
4115
4116
0
  if (part4_v_rd > part4_h_rd) part4_search_allowed[VERT4] = 0;
4117
0
}
4118
4119
// Prune 4-way partition search.
4120
static void prune_4_way_partition_search(
4121
    AV1_COMP *const cpi, MACROBLOCK *x, PC_TREE *pc_tree,
4122
    PartitionSearchState *part_search_state, SIMPLE_MOTION_DATA_TREE *sms_tree,
4123
    RD_STATS *best_rdc, int pb_source_variance, int prune_ext_part_state,
4124
15.6M
    int mi_row, int mi_col, int part4_search_allowed[NUM_PART4_TYPES]) {
4125
15.6M
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
4126
15.6M
  const BLOCK_SIZE bsize = blk_params.bsize;
4127
4128
15.6M
  const PartitionCfg *const part_cfg = &cpi->oxcf.part_cfg;
4129
4130
  // Do not prune if there is no valid partition
4131
15.6M
  if (best_rdc->rdcost == INT64_MAX && part_cfg->enable_1to4_partitions &&
4132
0
      bsize != BLOCK_128X128)
4133
0
    return;
4134
4135
  // Determine bsize threshold to evaluate 4-way partitions
4136
15.6M
  BLOCK_SIZE part4_bsize_thresh = cpi->sf.part_sf.ext_partition_eval_thresh;
4137
15.6M
  if (cpi->sf.part_sf.ext_part_eval_based_on_cur_best &&
4138
0
      !x->must_find_valid_partition && pc_tree->partitioning == PARTITION_NONE)
4139
0
    part4_bsize_thresh = BLOCK_128X128;
4140
4141
  // 4-way partitions are only allowed for BLOCK_16X16, BLOCK_32X32, and
4142
  // BLOCK_64X64, so part4_bsize_thresh must be large enough to exclude
4143
  // BLOCK_4X4 and BLOCK_8X8.
4144
15.6M
  assert(part4_bsize_thresh >= BLOCK_8X8);
4145
4146
15.6M
  bool partition4_allowed =
4147
15.6M
      part_search_state->do_rectangular_split && bsize > part4_bsize_thresh &&
4148
0
      av1_blk_has_rows_and_cols(&blk_params) && !prune_ext_part_state;
4149
4150
  // Disable 4-way partition search flags for width less than a multiple of the
4151
  // minimum partition width.
4152
15.6M
  if (blk_params.width < (blk_params.min_partition_size_1d
4153
15.6M
                          << cpi->sf.part_sf.prune_part4_search)) {
4154
14.6M
    part4_search_allowed[HORZ4] = 0;
4155
14.6M
    part4_search_allowed[VERT4] = 0;
4156
14.6M
    return;
4157
14.6M
  }
4158
4159
1.06M
  PARTITION_TYPE cur_part[NUM_PART4_TYPES] = { PARTITION_HORZ_4,
4160
1.06M
                                               PARTITION_VERT_4 };
4161
  // partition4_allowed is 1 if we can use a PARTITION_HORZ_4 or
4162
  // PARTITION_VERT_4 for this block. This is almost the same as
4163
  // partition4_allowed, except that we don't allow 128x32 or 32x128
4164
  // blocks, so we require that bsize is not BLOCK_128X128.
4165
1.06M
  partition4_allowed &=
4166
1.06M
      part_cfg->enable_1to4_partitions && bsize != BLOCK_128X128;
4167
4168
3.20M
  for (PART4_TYPES i = HORZ4; i < NUM_PART4_TYPES; i++) {
4169
2.13M
    part4_search_allowed[i] =
4170
2.13M
        partition4_allowed && part_search_state->partition_rect_allowed[i] &&
4171
0
        get_plane_block_size(get_partition_subsize(bsize, cur_part[i]),
4172
0
                             part_search_state->ss_x,
4173
0
                             part_search_state->ss_y) != BLOCK_INVALID;
4174
2.13M
  }
4175
  // Pruning: pruning out 4-way partitions based on the current best partition.
4176
1.06M
  if (cpi->sf.part_sf.prune_ext_partition_types_search_level == 2) {
4177
0
    part4_search_allowed[HORZ4] &= (pc_tree->partitioning == PARTITION_HORZ ||
4178
0
                                    pc_tree->partitioning == PARTITION_HORZ_A ||
4179
0
                                    pc_tree->partitioning == PARTITION_HORZ_B ||
4180
0
                                    pc_tree->partitioning == PARTITION_SPLIT ||
4181
0
                                    pc_tree->partitioning == PARTITION_NONE);
4182
0
    part4_search_allowed[VERT4] &= (pc_tree->partitioning == PARTITION_VERT ||
4183
0
                                    pc_tree->partitioning == PARTITION_VERT_A ||
4184
0
                                    pc_tree->partitioning == PARTITION_VERT_B ||
4185
0
                                    pc_tree->partitioning == PARTITION_SPLIT ||
4186
0
                                    pc_tree->partitioning == PARTITION_NONE);
4187
0
  }
4188
4189
  // Pruning: pruning out some 4-way partitions using a DNN taking rd costs of
4190
  // sub-blocks from basic partition types.
4191
1.06M
  if (cpi->sf.part_sf.ml_prune_partition && partition4_allowed &&
4192
0
      part_search_state->partition_rect_allowed[HORZ] &&
4193
0
      part_search_state->partition_rect_allowed[VERT]) {
4194
0
    av1_ml_prune_4_partition(cpi, x, pc_tree->partitioning, best_rdc->rdcost,
4195
0
                             part_search_state, part4_search_allowed,
4196
0
                             pb_source_variance);
4197
0
  }
4198
4199
  // Pruning: pruning out 4-way partitions based on the number of horz/vert wins
4200
  // in the current block and sub-blocks in PARTITION_SPLIT.
4201
1.06M
  prune_4_partition_using_split_info(cpi, x, part_search_state,
4202
1.06M
                                     part4_search_allowed);
4203
4204
1.06M
  if (cpi->sf.part_sf.prune_h_or_v_4part_using_sms_info && partition4_allowed &&
4205
0
      best_rdc->rdcost != INT64_MAX &&
4206
0
      av1_is_whole_blk_in_frame(&part_search_state->part_blk_params,
4207
0
                                &cpi->common.mi_params) &&
4208
0
      !frame_is_intra_only(&cpi->common)) {
4209
0
    prune_part4_using_sms(cpi, x, part_search_state, sms_tree, mi_row, mi_col,
4210
0
                          bsize, part4_search_allowed);
4211
0
  }
4212
1.06M
}
4213
4214
// Set params needed for PARTITION_NONE search.
4215
static void set_none_partition_params(const AV1_COMP *const cpi, ThreadData *td,
4216
                                      MACROBLOCK *x, PC_TREE *pc_tree,
4217
                                      PartitionSearchState *part_search_state,
4218
                                      RD_STATS *best_remain_rdcost,
4219
14.1M
                                      RD_STATS *best_rdc, int *pt_cost) {
4220
14.1M
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4221
14.1M
  RD_STATS partition_rdcost;
4222
  // Set PARTITION_NONE context.
4223
14.1M
  if (pc_tree->none == NULL)
4224
14.1M
    pc_tree->none = av1_alloc_pmc(cpi, blk_params.bsize, &td->shared_coeff_buf);
4225
14.1M
  if (!pc_tree->none)
4226
0
    aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
4227
0
                       "Failed to allocate PICK_MODE_CONTEXT");
4228
4229
  // Set PARTITION_NONE type cost.
4230
14.1M
  if (part_search_state->partition_none_allowed) {
4231
14.1M
    if (blk_params.bsize_at_least_8x8) {
4232
6.10M
      *pt_cost = part_search_state->partition_cost[PARTITION_NONE] < INT_MAX
4233
6.10M
                     ? part_search_state->partition_cost[PARTITION_NONE]
4234
18.4E
                     : 0;
4235
6.10M
    }
4236
4237
    // Initialize the RD stats structure.
4238
14.1M
    av1_init_rd_stats(&partition_rdcost);
4239
14.1M
    partition_rdcost.rate = *pt_cost;
4240
14.1M
    av1_rd_cost_update(x->rdmult, &partition_rdcost);
4241
14.1M
    av1_rd_stats_subtraction(x->rdmult, best_rdc, &partition_rdcost,
4242
14.1M
                             best_remain_rdcost);
4243
14.1M
  }
4244
14.1M
}
4245
4246
// Skip other partitions based on PARTITION_NONE rd cost.
4247
static void prune_partitions_after_none(AV1_COMP *const cpi, MACROBLOCK *x,
4248
                                        SIMPLE_MOTION_DATA_TREE *sms_tree,
4249
                                        PICK_MODE_CONTEXT *ctx_none,
4250
                                        PartitionSearchState *part_search_state,
4251
                                        RD_STATS *best_rdc,
4252
12.1M
                                        unsigned int *pb_source_variance) {
4253
12.1M
  const AV1_COMMON *const cm = &cpi->common;
4254
12.1M
  MACROBLOCKD *const xd = &x->e_mbd;
4255
12.1M
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
4256
12.1M
  RD_STATS *this_rdc = &part_search_state->this_rdc;
4257
12.1M
  const BLOCK_SIZE bsize = blk_params.bsize;
4258
12.1M
  assert(bsize < BLOCK_SIZES_ALL);
4259
4260
12.1M
  if (!frame_is_intra_only(cm) &&
4261
882k
      (part_search_state->do_square_split ||
4262
867k
       part_search_state->do_rectangular_split) &&
4263
17.3k
      !x->e_mbd.lossless[xd->mi[0]->segment_id] && ctx_none->skippable) {
4264
286
    const int use_ml_based_breakout =
4265
286
        bsize <= cpi->sf.part_sf.use_square_partition_only_threshold &&
4266
119
        bsize > BLOCK_4X4 && cpi->sf.part_sf.ml_predict_breakout_level >= 1;
4267
286
    if (use_ml_based_breakout) {
4268
119
      av1_ml_predict_breakout(cpi, x, this_rdc, *pb_source_variance, xd->bd,
4269
119
                              part_search_state);
4270
119
    }
4271
4272
    // Adjust dist breakout threshold according to the partition size.
4273
286
    const int64_t dist_breakout_thr =
4274
286
        cpi->sf.part_sf.partition_search_breakout_dist_thr >>
4275
286
        ((2 * (MAX_SB_SIZE_LOG2 - 2)) -
4276
286
         (mi_size_wide_log2[bsize] + mi_size_high_log2[bsize]));
4277
286
    const int rate_breakout_thr =
4278
286
        cpi->sf.part_sf.partition_search_breakout_rate_thr *
4279
286
        num_pels_log2_lookup[bsize];
4280
    // If all y, u, v transform blocks in this partition are skippable,
4281
    // and the dist & rate are within the thresholds, the partition
4282
    // search is terminated for current branch of the partition search
4283
    // tree. The dist & rate thresholds are set to 0 at speed 0 to
4284
    // disable the early termination at that speed.
4285
286
    if (best_rdc->dist < dist_breakout_thr &&
4286
50
        best_rdc->rate < rate_breakout_thr) {
4287
0
      part_search_state->do_square_split = 0;
4288
0
      part_search_state->do_rectangular_split = 0;
4289
0
    }
4290
286
  }
4291
4292
  // Early termination: using simple_motion_search features and the
4293
  // rate, distortion, and rdcost of PARTITION_NONE, a DNN will make a
4294
  // decision on early terminating at PARTITION_NONE.
4295
12.1M
  if (cpi->sf.part_sf.simple_motion_search_early_term_none && cm->show_frame &&
4296
12.1M
      !frame_is_intra_only(cm) && bsize >= BLOCK_16X16 &&
4297
17.7k
      av1_blk_has_rows_and_cols(&blk_params) && this_rdc->rdcost < INT64_MAX &&
4298
17.7k
      this_rdc->rdcost >= 0 && this_rdc->rate < INT_MAX &&
4299
17.7k
      this_rdc->rate >= 0 &&
4300
17.7k
      (part_search_state->do_square_split ||
4301
16.7k
       part_search_state->do_rectangular_split)) {
4302
16.7k
    av1_simple_motion_search_early_term_none(cpi, x, sms_tree, this_rdc,
4303
16.7k
                                             part_search_state);
4304
16.7k
  }
4305
12.1M
}
4306
4307
// Decide early termination and rectangular partition pruning
4308
// based on PARTITION_NONE and PARTITION_SPLIT costs.
4309
static void prune_partitions_after_split(
4310
    AV1_COMP *const cpi, MACROBLOCK *x, SIMPLE_MOTION_DATA_TREE *sms_tree,
4311
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
4312
15.6M
    int64_t part_none_rd, int64_t part_split_rd) {
4313
15.6M
  const AV1_COMMON *const cm = &cpi->common;
4314
15.6M
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4315
15.6M
  const int mi_row = blk_params.mi_row;
4316
15.6M
  const int mi_col = blk_params.mi_col;
4317
15.6M
  const BLOCK_SIZE bsize = blk_params.bsize;
4318
15.6M
  assert(bsize < BLOCK_SIZES_ALL);
4319
4320
  // Early termination: using the rd costs of PARTITION_NONE and subblocks
4321
  // from PARTITION_SPLIT to determine an early breakout.
4322
15.6M
  if (cpi->sf.part_sf.ml_early_term_after_part_split_level &&
4323
0
      !frame_is_intra_only(cm) &&
4324
0
      !part_search_state->terminate_partition_search &&
4325
0
      part_search_state->do_rectangular_split &&
4326
0
      (part_search_state->partition_rect_allowed[HORZ] ||
4327
0
       part_search_state->partition_rect_allowed[VERT])) {
4328
0
    av1_ml_early_term_after_split(
4329
0
        cpi, x, sms_tree, best_rdc->rdcost, part_none_rd, part_split_rd,
4330
0
        part_search_state->split_rd, part_search_state);
4331
0
  }
4332
4333
  // Use the rd costs of PARTITION_NONE and subblocks from PARTITION_SPLIT
4334
  // to prune out rectangular partitions in some directions.
4335
15.6M
  if (!cpi->sf.part_sf.ml_early_term_after_part_split_level &&
4336
15.6M
      cpi->sf.part_sf.ml_prune_partition && !frame_is_intra_only(cm) &&
4337
1.26M
      (part_search_state->partition_rect_allowed[HORZ] ||
4338
1.20M
       part_search_state->partition_rect_allowed[VERT]) &&
4339
122k
      !(part_search_state->prune_rect_part[HORZ] ||
4340
667
        part_search_state->prune_rect_part[VERT]) &&
4341
22
      !part_search_state->terminate_partition_search) {
4342
21
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, av1_num_planes(cm),
4343
21
                         bsize);
4344
21
    av1_ml_prune_rect_partition(cpi, x, best_rdc->rdcost,
4345
21
                                part_search_state->none_rd,
4346
21
                                part_search_state->split_rd, part_search_state);
4347
21
  }
4348
15.6M
}
4349
4350
// Returns true if either of the left and top neighbor blocks is larger than
4351
// the current block; false otherwise.
4352
static inline bool is_neighbor_blk_larger_than_cur_blk(const MACROBLOCKD *xd,
4353
9.61M
                                                       BLOCK_SIZE bsize) {
4354
9.61M
  const int cur_blk_area = (block_size_high[bsize] * block_size_wide[bsize]);
4355
9.61M
  if (xd->left_available) {
4356
7.97M
    const BLOCK_SIZE left_bsize = xd->left_mbmi->bsize;
4357
7.97M
    if (block_size_high[left_bsize] * block_size_wide[left_bsize] >
4358
7.97M
        cur_blk_area)
4359
2.44M
      return true;
4360
7.97M
  }
4361
4362
7.16M
  if (xd->up_available) {
4363
5.84M
    const BLOCK_SIZE above_bsize = xd->above_mbmi->bsize;
4364
5.84M
    if (block_size_high[above_bsize] * block_size_wide[above_bsize] >
4365
5.84M
        cur_blk_area)
4366
1.82M
      return true;
4367
5.84M
  }
4368
5.34M
  return false;
4369
7.16M
}
4370
4371
static inline void prune_rect_part_using_none_pred_mode(
4372
    const MACROBLOCKD *xd, PartitionSearchState *part_state,
4373
11.0M
    PREDICTION_MODE mode, BLOCK_SIZE bsize) {
4374
11.0M
  if (mode == DC_PRED || mode == SMOOTH_PRED) {
4375
    // If the prediction mode of NONE partition is either DC_PRED or
4376
    // SMOOTH_PRED, it indicates that the current block has less variation. In
4377
    // this case, HORZ and VERT partitions are pruned if at least one of left
4378
    // and top neighbor blocks is larger than the current block.
4379
9.61M
    if (is_neighbor_blk_larger_than_cur_blk(xd, bsize)) {
4380
4.26M
      part_state->prune_rect_part[HORZ] = 1;
4381
4.26M
      part_state->prune_rect_part[VERT] = 1;
4382
4.26M
    }
4383
9.61M
  } else if (mode == D67_PRED || mode == V_PRED || mode == D113_PRED) {
4384
    // If the prediction mode chosen by NONE partition is close to 90 degrees,
4385
    // it implies a dominant vertical pattern, and the chance of choosing a
4386
    // vertical rectangular partition is high. Hence, horizontal partition is
4387
    // pruned in these cases.
4388
392k
    part_state->prune_rect_part[HORZ] = 1;
4389
1.06M
  } else if (mode == D157_PRED || mode == H_PRED || mode == D203_PRED) {
4390
    // If the prediction mode chosen by NONE partition is close to 180 degrees,
4391
    // it implies a dominant horizontal pattern, and the chance of choosing a
4392
    // horizontal rectangular partition is high. Hence, vertical partition is
4393
    // pruned in these cases.
4394
637k
    part_state->prune_rect_part[VERT] = 1;
4395
637k
  }
4396
11.0M
}
4397
4398
// PARTITION_NONE search.
4399
static void none_partition_search(
4400
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data, MACROBLOCK *x,
4401
    PC_TREE *pc_tree, SIMPLE_MOTION_DATA_TREE *sms_tree,
4402
    RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
4403
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
4404
15.6M
    unsigned int *pb_source_variance, int64_t *none_rd, int64_t *part_none_rd) {
4405
15.6M
  const AV1_COMMON *const cm = &cpi->common;
4406
15.6M
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4407
15.6M
  RD_STATS *this_rdc = &part_search_state->this_rdc;
4408
15.6M
  const int mi_row = blk_params.mi_row;
4409
15.6M
  const int mi_col = blk_params.mi_col;
4410
15.6M
  const BLOCK_SIZE bsize = blk_params.bsize;
4411
15.6M
  assert(bsize < BLOCK_SIZES_ALL);
4412
4413
15.6M
  if (part_search_state->terminate_partition_search ||
4414
15.6M
      !part_search_state->partition_none_allowed)
4415
1.51M
    return;
4416
4417
14.1M
  int pt_cost = 0;
4418
14.1M
  RD_STATS best_remain_rdcost;
4419
14.1M
  av1_invalid_rd_stats(&best_remain_rdcost);
4420
4421
  // Set PARTITION_NONE context and cost.
4422
14.1M
  set_none_partition_params(cpi, td, x, pc_tree, part_search_state,
4423
14.1M
                            &best_remain_rdcost, best_rdc, &pt_cost);
4424
4425
#if CONFIG_COLLECT_PARTITION_STATS
4426
  // Timer start for partition None.
4427
  PartitionTimingStats *part_timing_stats =
4428
      &part_search_state->part_timing_stats;
4429
  if (best_remain_rdcost.rdcost >= 0) {
4430
    start_partition_block_timer(part_timing_stats, PARTITION_NONE);
4431
  }
4432
#endif
4433
  // PARTITION_NONE evaluation and cost update.
4434
14.1M
  pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, this_rdc, PARTITION_NONE,
4435
14.1M
                bsize, pc_tree->none, best_remain_rdcost);
4436
4437
14.1M
  av1_rd_cost_update(x->rdmult, this_rdc);
4438
4439
#if CONFIG_COLLECT_PARTITION_STATS
4440
  // Timer end for partition None.
4441
  if (part_timing_stats->timer_is_on) {
4442
    RD_STATS tmp_rdc;
4443
    av1_init_rd_stats(&tmp_rdc);
4444
    if (this_rdc->rate != INT_MAX) {
4445
      tmp_rdc.rate = this_rdc->rate;
4446
      tmp_rdc.dist = this_rdc->dist;
4447
      tmp_rdc.rdcost = this_rdc->rdcost;
4448
      if (blk_params.bsize_at_least_8x8) {
4449
        tmp_rdc.rate += pt_cost;
4450
        tmp_rdc.rdcost = RDCOST(x->rdmult, tmp_rdc.rate, tmp_rdc.dist);
4451
      }
4452
    }
4453
    end_partition_block_timer(part_timing_stats, PARTITION_NONE,
4454
                              tmp_rdc.rdcost);
4455
  }
4456
#endif
4457
14.1M
  *pb_source_variance = x->source_variance;
4458
14.1M
  if (none_rd) *none_rd = this_rdc->rdcost;
4459
14.1M
  part_search_state->none_rd = this_rdc->rdcost;
4460
14.1M
  if (this_rdc->rate != INT_MAX) {
4461
    // Record picked ref frame to prune ref frames for other partition types.
4462
12.7M
    if (cpi->sf.inter_sf.prune_ref_frame_for_rect_partitions) {
4463
882k
      const int ref_type = av1_ref_frame_type(pc_tree->none->mic.ref_frame);
4464
882k
      av1_update_picked_ref_frames_mask(
4465
882k
          x, ref_type, bsize, cm->seq_params->mib_size, mi_row, mi_col);
4466
882k
    }
4467
4468
    // Calculate the total cost and update the best partition.
4469
12.7M
    if (blk_params.bsize_at_least_8x8) {
4470
5.72M
      this_rdc->rate += pt_cost;
4471
5.72M
      this_rdc->rdcost = RDCOST(x->rdmult, this_rdc->rate, this_rdc->dist);
4472
5.72M
    }
4473
12.7M
    *part_none_rd = this_rdc->rdcost;
4474
12.7M
    if (this_rdc->rdcost < best_rdc->rdcost) {
4475
12.1M
      *best_rdc = *this_rdc;
4476
12.1M
      part_search_state->found_best_partition = true;
4477
12.1M
      if (blk_params.bsize_at_least_8x8) {
4478
5.58M
        pc_tree->partitioning = PARTITION_NONE;
4479
5.58M
      }
4480
4481
      // Disable split and rectangular partition search
4482
      // based on PARTITION_NONE cost.
4483
12.1M
      prune_partitions_after_none(cpi, x, sms_tree, pc_tree->none,
4484
12.1M
                                  part_search_state, best_rdc,
4485
12.1M
                                  pb_source_variance);
4486
12.1M
    }
4487
4488
12.7M
    if (cpi->sf.part_sf.prune_rect_part_using_none_pred_mode)
4489
11.0M
      prune_rect_part_using_none_pred_mode(&x->e_mbd, part_search_state,
4490
11.0M
                                           pc_tree->none->mic.mode, bsize);
4491
12.7M
  }
4492
14.1M
  av1_restore_context(x, x_ctx, mi_row, mi_col, bsize, av1_num_planes(cm));
4493
14.1M
}
4494
4495
static inline double get_split_partition_penalty(
4496
2.58M
    BLOCK_SIZE bsize, int split_partition_penalty_level) {
4497
2.58M
  if (!split_partition_penalty_level) return 1.00;
4498
4499
  // Higher penalty for smaller block sizes.
4500
18.4E
  static const double penalty_factors[2][SQR_BLOCK_SIZES - 1] = {
4501
18.4E
    { 1.080, 1.040, 1.020, 1.010, 1.000 },
4502
18.4E
    { 1.100, 1.075, 1.050, 1.025, 1.000 },
4503
18.4E
  };
4504
18.4E
  const int sqr_bsize_idx = get_sqr_bsize_idx(bsize);
4505
18.4E
  assert(sqr_bsize_idx > 0 && sqr_bsize_idx < SQR_BLOCK_SIZES);
4506
18.4E
  const double this_penalty_factor =
4507
18.4E
      penalty_factors[split_partition_penalty_level - 1][sqr_bsize_idx - 1];
4508
18.4E
  return this_penalty_factor;
4509
2.58M
}
4510
4511
// PARTITION_SPLIT search.
4512
static void split_partition_search(
4513
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
4514
    TokenExtra **tp, MACROBLOCK *x, PC_TREE *pc_tree,
4515
    SIMPLE_MOTION_DATA_TREE *sms_tree, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
4516
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
4517
15.6M
    SB_MULTI_PASS_MODE multi_pass_mode, int64_t *part_split_rd) {
4518
15.6M
  const AV1_COMMON *const cm = &cpi->common;
4519
15.6M
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4520
15.6M
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
4521
15.6M
  const int mi_row = blk_params.mi_row;
4522
15.6M
  const int mi_col = blk_params.mi_col;
4523
15.6M
  const BLOCK_SIZE bsize = blk_params.bsize;
4524
15.6M
  assert(bsize < BLOCK_SIZES_ALL);
4525
15.6M
  RD_STATS sum_rdc = part_search_state->sum_rdc;
4526
15.6M
  const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
4527
4528
  // Check if partition split is allowed.
4529
15.6M
  if (part_search_state->terminate_partition_search ||
4530
15.6M
      !part_search_state->do_square_split)
4531
11.1M
    return;
4532
4533
22.8M
  for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
4534
18.2M
    if (pc_tree->split[i] == NULL)
4535
18.2M
      pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
4536
18.2M
    if (!pc_tree->split[i])
4537
0
      aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
4538
0
                         "Failed to allocate PC_TREE");
4539
18.2M
    pc_tree->split[i]->index = i;
4540
18.2M
  }
4541
4542
  // Initialization of this partition RD stats.
4543
4.56M
  av1_init_rd_stats(&sum_rdc);
4544
4.56M
  sum_rdc.rate = part_search_state->partition_cost[PARTITION_SPLIT];
4545
4.56M
  sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, 0);
4546
4547
4.56M
  int idx;
4548
#if CONFIG_COLLECT_PARTITION_STATS
4549
  PartitionTimingStats *part_timing_stats =
4550
      &part_search_state->part_timing_stats;
4551
  if (best_rdc->rdcost - sum_rdc.rdcost >= 0) {
4552
    start_partition_block_timer(part_timing_stats, PARTITION_SPLIT);
4553
  }
4554
#endif
4555
  // Recursive partition search on 4 sub-blocks.
4556
20.0M
  for (idx = 0; idx < SUB_PARTITIONS_SPLIT && sum_rdc.rdcost < best_rdc->rdcost;
4557
17.4M
       ++idx) {
4558
17.4M
    const int x_idx = (idx & 1) * blk_params.mi_step;
4559
17.4M
    const int y_idx = (idx >> 1) * blk_params.mi_step;
4560
4561
17.4M
    if (mi_row + y_idx >= mi_params->mi_rows ||
4562
16.3M
        mi_col + x_idx >= mi_params->mi_cols)
4563
2.09M
      continue;
4564
4565
15.4M
    pc_tree->split[idx]->index = idx;
4566
15.4M
    int64_t *p_split_rd = &part_search_state->split_rd[idx];
4567
15.4M
    RD_STATS best_remain_rdcost;
4568
15.4M
    av1_rd_stats_subtraction(x->rdmult, best_rdc, &sum_rdc,
4569
15.4M
                             &best_remain_rdcost);
4570
4571
15.4M
    int curr_quad_tree_idx = 0;
4572
15.4M
    if (frame_is_intra_only(cm) && bsize <= BLOCK_64X64) {
4573
14.1M
      curr_quad_tree_idx = part_search_state->intra_part_info->quad_tree_idx;
4574
14.1M
      part_search_state->intra_part_info->quad_tree_idx =
4575
14.1M
          4 * curr_quad_tree_idx + idx + 1;
4576
14.1M
    }
4577
    // Split partition evaluation of corresponding idx.
4578
    // If the RD cost exceeds the best cost then do not
4579
    // evaluate other split sub-partitions.
4580
15.4M
    SIMPLE_MOTION_DATA_TREE *const sms_tree_split =
4581
15.4M
        (sms_tree == NULL) ? NULL : sms_tree->split[idx];
4582
15.4M
    if (!av1_rd_pick_partition(
4583
15.4M
            cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
4584
15.4M
            &part_search_state->this_rdc, best_remain_rdcost,
4585
15.4M
            pc_tree->split[idx], sms_tree_split, p_split_rd, multi_pass_mode,
4586
15.4M
            &part_search_state->split_part_rect_win[idx])) {
4587
1.99M
      av1_invalid_rd_stats(&sum_rdc);
4588
1.99M
      break;
4589
1.99M
    }
4590
13.4M
    if (frame_is_intra_only(cm) && bsize <= BLOCK_64X64) {
4591
12.1M
      part_search_state->intra_part_info->quad_tree_idx = curr_quad_tree_idx;
4592
12.1M
    }
4593
4594
13.4M
    sum_rdc.rate += part_search_state->this_rdc.rate;
4595
13.4M
    sum_rdc.dist += part_search_state->this_rdc.dist;
4596
13.4M
    av1_rd_cost_update(x->rdmult, &sum_rdc);
4597
4598
    // Set split ctx as ready for use.
4599
13.4M
    if (idx <= 1 && (bsize <= BLOCK_8X8 ||
4600
6.92M
                     pc_tree->split[idx]->partitioning == PARTITION_NONE)) {
4601
6.92M
      const MB_MODE_INFO *const mbmi = &pc_tree->split[idx]->none->mic;
4602
6.92M
      const PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
4603
      // Neither palette mode nor cfl predicted.
4604
6.92M
      if (pmi->palette_size[0] == 0 && pmi->palette_size[1] == 0) {
4605
6.74M
        if (mbmi->uv_mode != UV_CFL_PRED)
4606
6.16M
          part_search_state->is_split_ctx_is_ready[idx] = 1;
4607
6.74M
      }
4608
6.92M
    }
4609
13.4M
  }
4610
#if CONFIG_COLLECT_PARTITION_STATS
4611
  if (part_timing_stats->timer_is_on) {
4612
    end_partition_block_timer(part_timing_stats, PARTITION_SPLIT,
4613
                              sum_rdc.rdcost);
4614
  }
4615
#endif
4616
4.56M
  const int reached_last_index = (idx == SUB_PARTITIONS_SPLIT);
4617
4618
  // Calculate the total cost and update the best partition.
4619
4.56M
  *part_split_rd = sum_rdc.rdcost;
4620
4.56M
  if (reached_last_index && sum_rdc.rdcost < best_rdc->rdcost) {
4621
2.58M
    sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, sum_rdc.dist);
4622
2.58M
    const double penalty_factor = get_split_partition_penalty(
4623
2.58M
        bsize, cpi->sf.part_sf.split_partition_penalty_level);
4624
2.58M
    const int64_t this_rdcost = (int64_t)(sum_rdc.rdcost * penalty_factor);
4625
2.58M
    if (this_rdcost < best_rdc->rdcost) {
4626
2.58M
      *best_rdc = sum_rdc;
4627
2.58M
      part_search_state->found_best_partition = true;
4628
2.58M
      pc_tree->partitioning = PARTITION_SPLIT;
4629
2.58M
    }
4630
2.58M
  } else if (cpi->sf.part_sf.less_rectangular_check_level > 0) {
4631
    // Skip rectangular partition test when partition type none gives better
4632
    // rd than partition type split.
4633
1.99M
    if (cpi->sf.part_sf.less_rectangular_check_level == 2 || idx <= 2) {
4634
1.99M
      const int partition_none_valid = part_search_state->none_rd > 0;
4635
1.99M
      const int partition_none_better =
4636
1.99M
          part_search_state->none_rd < sum_rdc.rdcost;
4637
1.99M
      part_search_state->do_rectangular_split &=
4638
1.99M
          !(partition_none_valid && partition_none_better);
4639
1.99M
    }
4640
1.99M
  }
4641
  // Restore the context for the following cases:
4642
  // 1) Current block size not more than maximum partition size as dry run
4643
  // encode happens for these cases
4644
  // 2) Current block size same as superblock size as the final encode
4645
  // happens for this case
4646
4.56M
  if (bsize <= x->sb_enc.max_partition_size || bsize == cm->seq_params->sb_size)
4647
4.57M
    av1_restore_context(x, x_ctx, mi_row, mi_col, bsize, av1_num_planes(cm));
4648
4.56M
}
4649
4650
#if COLLECT_MOTION_SEARCH_FEATURE_SB
4651
// The max number of nodes in the partition tree.
4652
// The number of leaf nodes is (128x128) / (4x4) = 1024.
4653
// The number of All possible parent nodes is 1 + 2 + ... + 512 = 1023.
4654
#define NUM_NODES 2048
4655
4656
static void write_partition_tree(AV1_COMP *const cpi,
4657
                                 const PC_TREE *const pc_tree,
4658
                                 const BLOCK_SIZE bsize, const int mi_row,
4659
                                 const int mi_col) {
4660
  (void)mi_row;
4661
  (void)mi_col;
4662
  const char *path = cpi->oxcf.partition_info_path;
4663
  char filename[256];
4664
  snprintf(filename, sizeof(filename), "%s/partition_tree_sb%d_c%d", path,
4665
           cpi->sb_counter, 0);
4666
  FILE *pfile = fopen(filename, "w");
4667
  fprintf(pfile, "%d", bsize);
4668
4669
  // Write partition type with BFS order.
4670
  const PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4671
  int q_idx = 0;
4672
  int last_idx = 1;
4673
  int num_nodes = 1;
4674
4675
  // First traversal to get number of leaf nodes.
4676
  tree_node_queue[q_idx] = pc_tree;
4677
  while (num_nodes > 0) {
4678
    const PC_TREE *node = tree_node_queue[q_idx];
4679
    if (node->partitioning == PARTITION_SPLIT) {
4680
      for (int i = 0; i < 4; ++i) {
4681
        tree_node_queue[last_idx] = node->split[i];
4682
        ++last_idx;
4683
      }
4684
      num_nodes += 4;
4685
    }
4686
    --num_nodes;
4687
    ++q_idx;
4688
  }
4689
  const int num_leafs = last_idx;
4690
  fprintf(pfile, ",%d,%d", num_leafs, /*num_configs=*/1);
4691
4692
  // Write partitions for each node.
4693
  q_idx = 0;
4694
  last_idx = 1;
4695
  num_nodes = 1;
4696
  tree_node_queue[q_idx] = pc_tree;
4697
  while (num_nodes > 0) {
4698
    const PC_TREE *node = tree_node_queue[q_idx];
4699
    fprintf(pfile, ",%d", node->partitioning);
4700
    if (node->partitioning == PARTITION_SPLIT) {
4701
      for (int i = 0; i < 4; ++i) {
4702
        tree_node_queue[last_idx] = node->split[i];
4703
        ++last_idx;
4704
      }
4705
      num_nodes += 4;
4706
    }
4707
    --num_nodes;
4708
    ++q_idx;
4709
  }
4710
  fprintf(pfile, "\n");
4711
4712
  fclose(pfile);
4713
}
4714
#endif  // COLLECT_MOTION_SEARCH_FEATURE_SB
4715
4716
#if CONFIG_PARTITION_SEARCH_ORDER
4717
static void verify_write_partition_tree(const AV1_COMP *const cpi,
4718
                                        const PC_TREE *const pc_tree,
4719
                                        const BLOCK_SIZE bsize,
4720
                                        const int config_id, const int mi_row,
4721
                                        const int mi_col) {
4722
  (void)mi_row;
4723
  (void)mi_col;
4724
  const char *path = cpi->oxcf.partition_info_path;
4725
  char filename[256];
4726
  snprintf(filename, sizeof(filename), "%s/verify_partition_tree_sb%d_c%d",
4727
           path, cpi->sb_counter, config_id);
4728
  FILE *pfile = fopen(filename, "w");
4729
  fprintf(pfile, "%d", bsize);
4730
4731
  // Write partition type with BFS order.
4732
  const PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4733
  int q_idx = 0;
4734
  int last_idx = 1;
4735
  int num_nodes = 1;
4736
4737
  // First traversal to get number of leaf nodes.
4738
  tree_node_queue[q_idx] = pc_tree;
4739
  while (num_nodes > 0) {
4740
    const PC_TREE *node = tree_node_queue[q_idx];
4741
    if (node != NULL && node->partitioning == PARTITION_SPLIT) {
4742
      for (int i = 0; i < 4; ++i) {
4743
        tree_node_queue[last_idx] = node->split[i];
4744
        ++last_idx;
4745
      }
4746
      num_nodes += 4;
4747
    }
4748
    --num_nodes;
4749
    ++q_idx;
4750
  }
4751
  const int num_leafs = last_idx;
4752
  fprintf(pfile, ",%d,%d", num_leafs, /*num_configs=*/1);
4753
4754
  // Write partitions for each node.
4755
  q_idx = 0;
4756
  last_idx = 1;
4757
  num_nodes = 1;
4758
  tree_node_queue[q_idx] = pc_tree;
4759
  while (num_nodes > 0) {
4760
    const PC_TREE *node = tree_node_queue[q_idx];
4761
    if (node != NULL) {  // suppress warning
4762
      fprintf(pfile, ",%d", node->partitioning);
4763
      if (node->partitioning == PARTITION_SPLIT) {
4764
        for (int i = 0; i < 4; ++i) {
4765
          tree_node_queue[last_idx] = node->split[i];
4766
          ++last_idx;
4767
        }
4768
        num_nodes += 4;
4769
      }
4770
    }
4771
    --num_nodes;
4772
    ++q_idx;
4773
  }
4774
  fprintf(pfile, "\n");
4775
4776
  fclose(pfile);
4777
}
4778
4779
static int read_partition_tree(AV1_COMP *const cpi, PC_TREE *const pc_tree,
4780
                               struct aom_internal_error_info *error_info,
4781
                               const int config_id) {
4782
  const AV1_COMMON *const cm = &cpi->common;
4783
  const char *path = cpi->oxcf.partition_info_path;
4784
  char filename[256];
4785
  snprintf(filename, sizeof(filename), "%s/partition_tree_sb%d_c%d", path,
4786
           cpi->sb_counter, config_id);
4787
  FILE *pfile = fopen(filename, "r");
4788
  if (pfile == NULL) {
4789
    aom_internal_error(cm->error, AOM_CODEC_ERROR, "Can't find input file: %s.",
4790
                       filename);
4791
  }
4792
4793
  int read_bsize;
4794
  int num_nodes;
4795
  int num_configs;
4796
  fscanf(pfile, "%d,%d,%d", &read_bsize, &num_nodes, &num_configs);
4797
  assert(read_bsize == cpi->common.seq_params->sb_size);
4798
  BLOCK_SIZE bsize = (BLOCK_SIZE)read_bsize;
4799
  assert(bsize == pc_tree->block_size);
4800
4801
  PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4802
  int last_idx = 1;
4803
  int q_idx = 0;
4804
  tree_node_queue[q_idx] = pc_tree;
4805
  while (num_nodes > 0) {
4806
    int partitioning;
4807
    fscanf(pfile, ",%d", &partitioning);
4808
    assert(partitioning >= PARTITION_NONE &&
4809
           partitioning < EXT_PARTITION_TYPES);
4810
    PC_TREE *node = tree_node_queue[q_idx];
4811
    if (node != NULL) {
4812
      node->partitioning = partitioning;
4813
      bsize = node->block_size;
4814
    }
4815
    if (partitioning == PARTITION_SPLIT) {
4816
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
4817
      for (int i = 0; i < 4; ++i) {
4818
        if (node != NULL) {  // Suppress warning
4819
          node->split[i] = av1_alloc_pc_tree_node(subsize);
4820
          if (!node->split[i])
4821
            aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
4822
                               "Failed to allocate PC_TREE");
4823
          node->split[i]->index = i;
4824
          tree_node_queue[last_idx] = node->split[i];
4825
          ++last_idx;
4826
        }
4827
      }
4828
    }
4829
    --num_nodes;
4830
    ++q_idx;
4831
  }
4832
  fclose(pfile);
4833
4834
  return num_configs;
4835
}
4836
4837
static RD_STATS rd_search_for_fixed_partition(
4838
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
4839
    TokenExtra **tp, SIMPLE_MOTION_DATA_TREE *sms_tree, int mi_row, int mi_col,
4840
    const BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4841
  const PARTITION_TYPE partition = pc_tree->partitioning;
4842
  const AV1_COMMON *const cm = &cpi->common;
4843
  const int num_planes = av1_num_planes(cm);
4844
  MACROBLOCK *const x = &td->mb;
4845
  MACROBLOCKD *const xd = &x->e_mbd;
4846
  TileInfo *const tile_info = &tile_data->tile_info;
4847
  RD_STATS best_rdc;
4848
  av1_invalid_rd_stats(&best_rdc);
4849
  int sum_subblock_rate = 0;
4850
  int64_t sum_subblock_dist = 0;
4851
  PartitionSearchState part_search_state;
4852
  init_partition_search_state_params(x, cpi, &part_search_state, mi_row, mi_col,
4853
                                     bsize);
4854
  // Override partition costs at the edges of the frame in the same
4855
  // way as in read_partition (see decodeframe.c).
4856
  PartitionBlkParams blk_params = part_search_state.part_blk_params;
4857
  if (!av1_blk_has_rows_and_cols(&blk_params))
4858
    set_partition_cost_for_edge_blk(cm, &part_search_state);
4859
4860
  av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4861
4862
  // Save rdmult before it might be changed, so it can be restored later.
4863
  const int orig_rdmult = x->rdmult;
4864
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
4865
  (void)orig_rdmult;
4866
4867
  // Set the context.
4868
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
4869
  xd->above_txfm_context =
4870
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
4871
  xd->left_txfm_context =
4872
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
4873
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
4874
4875
  assert(bsize < BLOCK_SIZES_ALL);
4876
  unsigned int pb_source_variance = UINT_MAX;
4877
  int64_t part_none_rd = INT64_MAX;
4878
  int64_t none_rd = INT64_MAX;
4879
  int inc_step[NUM_PART4_TYPES] = { 0 };
4880
  if (partition == PARTITION_HORZ_4) inc_step[HORZ4] = mi_size_high[bsize] / 4;
4881
  if (partition == PARTITION_VERT_4) inc_step[VERT4] = mi_size_wide[bsize] / 4;
4882
4883
  switch (partition) {
4884
    case PARTITION_NONE:
4885
      none_partition_search(cpi, td, tile_data, x, pc_tree, sms_tree, &x_ctx,
4886
                            &part_search_state, &best_rdc, &pb_source_variance,
4887
                            &none_rd, &part_none_rd);
4888
      break;
4889
    case PARTITION_HORZ:
4890
      rectangular_partition_search(cpi, td, tile_data, tp, x, pc_tree, &x_ctx,
4891
                                   &part_search_state, &best_rdc, NULL, HORZ,
4892
                                   HORZ);
4893
      break;
4894
    case PARTITION_VERT:
4895
      rectangular_partition_search(cpi, td, tile_data, tp, x, pc_tree, &x_ctx,
4896
                                   &part_search_state, &best_rdc, NULL, VERT,
4897
                                   VERT);
4898
      break;
4899
    case PARTITION_HORZ_A:
4900
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4901
                           &part_search_state, &best_rdc, NULL,
4902
                           pb_source_variance, 1, HORZ_A, HORZ_A);
4903
      break;
4904
    case PARTITION_HORZ_B:
4905
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4906
                           &part_search_state, &best_rdc, NULL,
4907
                           pb_source_variance, 1, HORZ_B, HORZ_B);
4908
      break;
4909
    case PARTITION_VERT_A:
4910
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4911
                           &part_search_state, &best_rdc, NULL,
4912
                           pb_source_variance, 1, VERT_A, VERT_A);
4913
      break;
4914
    case PARTITION_VERT_B:
4915
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4916
                           &part_search_state, &best_rdc, NULL,
4917
                           pb_source_variance, 1, VERT_B, VERT_B);
4918
      break;
4919
    case PARTITION_HORZ_4:
4920
      rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4921
                         pc_tree->horizontal4, &part_search_state, &best_rdc,
4922
                         inc_step, PARTITION_HORZ_4);
4923
      break;
4924
    case PARTITION_VERT_4:
4925
      rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4926
                         pc_tree->vertical4, &part_search_state, &best_rdc,
4927
                         inc_step, PARTITION_VERT_4);
4928
      break;
4929
    case PARTITION_SPLIT:
4930
      for (int idx = 0; idx < SUB_PARTITIONS_SPLIT; ++idx) {
4931
        const BLOCK_SIZE subsize =
4932
            get_partition_subsize(bsize, PARTITION_SPLIT);
4933
        assert(subsize < BLOCK_SIZES_ALL);
4934
        const int next_mi_row =
4935
            idx < 2 ? mi_row : mi_row + mi_size_high[subsize];
4936
        const int next_mi_col =
4937
            idx % 2 == 0 ? mi_col : mi_col + mi_size_wide[subsize];
4938
        if (next_mi_row >= cm->mi_params.mi_rows ||
4939
            next_mi_col >= cm->mi_params.mi_cols) {
4940
          continue;
4941
        }
4942
        const RD_STATS subblock_rdc = rd_search_for_fixed_partition(
4943
            cpi, td, tile_data, tp, sms_tree->split[idx], next_mi_row,
4944
            next_mi_col, subsize, pc_tree->split[idx]);
4945
        sum_subblock_rate += subblock_rdc.rate;
4946
        sum_subblock_dist += subblock_rdc.dist;
4947
      }
4948
      best_rdc.rate = sum_subblock_rate;
4949
      best_rdc.rate += part_search_state.partition_cost[PARTITION_SPLIT];
4950
      best_rdc.dist = sum_subblock_dist;
4951
      best_rdc.rdcost = RDCOST(x->rdmult, best_rdc.rate, best_rdc.dist);
4952
      break;
4953
    default:
4954
      assert(0 && "invalid partition type.");
4955
      aom_internal_error(cm->error, AOM_CODEC_ERROR, "Invalid partition type.");
4956
  }
4957
  // Note: it is necessary to restore context information.
4958
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
4959
4960
  if (bsize != cm->seq_params->sb_size) {
4961
    encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_NORMAL, bsize,
4962
              pc_tree, NULL);
4963
  }
4964
  x->rdmult = orig_rdmult;
4965
4966
  return best_rdc;
4967
}
4968
4969
static void prepare_sb_features_before_search(
4970
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data, int mi_row,
4971
    int mi_col, const BLOCK_SIZE bsize, aom_partition_features_t *features) {
4972
  av1_collect_motion_search_features_sb(cpi, td, tile_data, mi_row, mi_col,
4973
                                        bsize, features);
4974
  collect_tpl_stats_sb(cpi, bsize, mi_row, mi_col, features);
4975
}
4976
4977
static void update_partition_stats(const RD_STATS *const this_rdcost,
4978
                                   aom_partition_stats_t *stats) {
4979
  stats->rate = this_rdcost->rate;
4980
  stats->dist = this_rdcost->dist;
4981
  stats->rdcost = this_rdcost->rdcost;
4982
}
4983
4984
static void build_pc_tree_from_part_decision(
4985
    const aom_partition_decision_t *partition_decision,
4986
    const BLOCK_SIZE this_bsize, PC_TREE *pc_tree,
4987
    struct aom_internal_error_info *error_info) {
4988
  BLOCK_SIZE bsize = this_bsize;
4989
  int num_nodes = partition_decision->num_nodes;
4990
  PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4991
  int last_idx = 1;
4992
  int q_idx = 0;
4993
  tree_node_queue[q_idx] = pc_tree;
4994
  while (num_nodes > 0) {
4995
    const int partitioning = partition_decision->partition_decision[q_idx];
4996
    assert(partitioning >= PARTITION_NONE &&
4997
           partitioning < EXT_PARTITION_TYPES);
4998
    PC_TREE *node = tree_node_queue[q_idx];
4999
    if (node != NULL) {
5000
      node->partitioning = partitioning;
5001
      bsize = node->block_size;
5002
    }
5003
    if (partitioning != PARTITION_NONE) {
5004
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, partitioning);
5005
      // Smaller block size for AB partition
5006
      const BLOCK_SIZE subsize2 = get_partition_subsize(bsize, PARTITION_SPLIT);
5007
5008
      switch (partitioning) {
5009
        case PARTITION_SPLIT:
5010
        case PARTITION_HORZ_4:
5011
        case PARTITION_VERT_4:
5012
          for (int i = 0; i < 4; ++i) {
5013
            if (node != NULL) {  // Suppress warning
5014
              node->split[i] = av1_alloc_pc_tree_node(subsize);
5015
              if (!node->split[i])
5016
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5017
                                   "Failed to allocate PC_TREE");
5018
              node->split[i]->index = i;
5019
              tree_node_queue[last_idx] = node->split[i];
5020
              ++last_idx;
5021
            }
5022
          }
5023
          break;
5024
        case PARTITION_HORZ:
5025
        case PARTITION_VERT:
5026
          for (int i = 0; i < 2; ++i) {
5027
            if (node != NULL) {  // Suppress warning
5028
              node->split[i] = av1_alloc_pc_tree_node(subsize);
5029
              if (!node->split[i])
5030
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5031
                                   "Failed to allocate PC_TREE");
5032
              node->split[i]->index = i;
5033
              tree_node_queue[last_idx] = node->split[i];
5034
              ++last_idx;
5035
            }
5036
          }
5037
          break;
5038
        case PARTITION_HORZ_A:
5039
        case PARTITION_VERT_A:
5040
          if (node != NULL) {  // Suppress warning
5041
            node->split[0] = av1_alloc_pc_tree_node(subsize2);
5042
            node->split[1] = av1_alloc_pc_tree_node(subsize2);
5043
            node->split[2] = av1_alloc_pc_tree_node(subsize);
5044
            for (int i = 0; i < 3; ++i) {
5045
              if (!node->split[i])
5046
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5047
                                   "Failed to allocate PC_TREE");
5048
              node->split[i]->index = i;
5049
              tree_node_queue[last_idx] = node->split[i];
5050
              ++last_idx;
5051
            }
5052
          }
5053
          break;
5054
        case PARTITION_HORZ_B:
5055
        case PARTITION_VERT_B:
5056
          if (node != NULL) {  // Suppress warning
5057
            node->split[0] = av1_alloc_pc_tree_node(subsize);
5058
            node->split[1] = av1_alloc_pc_tree_node(subsize2);
5059
            node->split[2] = av1_alloc_pc_tree_node(subsize2);
5060
            for (int i = 0; i < 3; ++i) {
5061
              if (!node->split[i])
5062
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5063
                                   "Failed to allocate PC_TREE");
5064
              node->split[i]->index = i;
5065
              tree_node_queue[last_idx] = node->split[i];
5066
              ++last_idx;
5067
            }
5068
          }
5069
          break;
5070
        case PARTITION_NONE:
5071
        default:
5072
          // Should not hit this case.
5073
          assert(0);
5074
      }
5075
    }
5076
    --num_nodes;
5077
    ++q_idx;
5078
  }
5079
}
5080
5081
// The ML model needs to provide the whole decision tree for the superblock.
5082
static bool ml_partition_search_whole_tree(AV1_COMP *const cpi, ThreadData *td,
5083
                                           TileDataEnc *tile_data,
5084
                                           TokenExtra **tp,
5085
                                           SIMPLE_MOTION_DATA_TREE *sms_root,
5086
                                           int mi_row, int mi_col,
5087
                                           const BLOCK_SIZE bsize) {
5088
  AV1_COMMON *const cm = &cpi->common;
5089
  MACROBLOCK *const x = &td->mb;
5090
  ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
5091
  struct aom_internal_error_info *error_info = x->e_mbd.error_info;
5092
  aom_partition_features_t features;
5093
  prepare_sb_features_before_search(cpi, td, tile_data, mi_row, mi_col, bsize,
5094
                                    &features);
5095
  features.mi_row = mi_row;
5096
  features.mi_col = mi_col;
5097
  features.frame_width = cpi->frame_info.frame_width;
5098
  features.frame_height = cpi->frame_info.frame_height;
5099
  features.block_size = bsize;
5100
  av1_ext_part_send_features(ext_part_controller, &features);
5101
5102
  // rd mode search (dry run) for a valid partition decision from the ml model.
5103
  aom_partition_decision_t partition_decision;
5104
  do {
5105
    const bool valid_decision = av1_ext_part_get_partition_decision(
5106
        ext_part_controller, &partition_decision);
5107
    if (!valid_decision) return false;
5108
5109
    // First, let's take the easy approach.
5110
    // We require that the ml model has to provide partition decisions for the
5111
    // whole superblock.
5112
    td->pc_root = av1_alloc_pc_tree_node(bsize);
5113
    if (!td->pc_root)
5114
      aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5115
                         "Failed to allocate PC_TREE");
5116
    build_pc_tree_from_part_decision(&partition_decision, bsize, td->pc_root,
5117
                                     error_info);
5118
5119
    const RD_STATS this_rdcost = rd_search_for_fixed_partition(
5120
        cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize, td->pc_root);
5121
    aom_partition_stats_t stats;
5122
    update_partition_stats(&this_rdcost, &stats);
5123
    av1_ext_part_send_partition_stats(ext_part_controller, &stats);
5124
    if (!partition_decision.is_final_decision) {
5125
      av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5126
                                 cpi->sf.part_sf.partition_search_type);
5127
      td->pc_root = NULL;
5128
    }
5129
  } while (!partition_decision.is_final_decision);
5130
5131
  // Encode with the selected mode and partition.
5132
  set_cb_offsets(x->cb_offset, 0, 0);
5133
  encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
5134
            td->pc_root, NULL);
5135
  av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5136
                             cpi->sf.part_sf.partition_search_type);
5137
  td->pc_root = NULL;
5138
5139
  return true;
5140
}
5141
5142
// Use a bitmask to represent the valid partition types for the current
5143
// block. "1" represents the corresponding partition type is vaild.
5144
// The least significant bit represents "PARTITION_NONE", the
5145
// largest significant bit represents "PARTITION_VERT_4", follow
5146
// the enum order for PARTITION_TYPE in "enums.h"
5147
static int get_valid_partition_types(
5148
    const AV1_COMP *const cpi,
5149
    const PartitionSearchState *const part_search_state,
5150
    const BLOCK_SIZE bsize) {
5151
  const PartitionCfg *const part_cfg = &cpi->oxcf.part_cfg;
5152
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
5153
  int valid_types = 0;
5154
  // PARTITION_NONE
5155
  valid_types |= (part_search_state->partition_none_allowed << 0);
5156
  // PARTITION_HORZ
5157
  valid_types |= (part_search_state->partition_rect_allowed[HORZ] << 1);
5158
  // PARTITION_VERT
5159
  valid_types |= (part_search_state->partition_rect_allowed[VERT] << 2);
5160
  // PARTITION_SPLIT
5161
  valid_types |= (part_search_state->do_square_split << 3);
5162
  // PARTITION_HORZ_A
5163
  const int ext_partition_allowed = part_search_state->do_rectangular_split &&
5164
                                    av1_blk_has_rows_and_cols(&blk_params);
5165
  const int horzab_partition_allowed =
5166
      ext_partition_allowed && part_cfg->enable_ab_partitions &&
5167
      part_search_state->partition_rect_allowed[HORZ];
5168
  valid_types |= (horzab_partition_allowed << 4);
5169
  // PARTITION_HORZ_B
5170
  valid_types |= (horzab_partition_allowed << 5);
5171
  // PARTITION_VERT_A
5172
  const int vertab_partition_allowed =
5173
      ext_partition_allowed && part_cfg->enable_ab_partitions &&
5174
      part_search_state->partition_rect_allowed[VERT];
5175
  valid_types |= (vertab_partition_allowed << 6);
5176
  // PARTITION_VERT_B
5177
  valid_types |= (vertab_partition_allowed << 7);
5178
  // PARTITION_HORZ_4
5179
  const int partition4_allowed = part_cfg->enable_1to4_partitions &&
5180
                                 ext_partition_allowed &&
5181
                                 bsize != BLOCK_128X128;
5182
  const int horz4_allowed =
5183
      partition4_allowed && part_search_state->partition_rect_allowed[HORZ] &&
5184
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_HORZ_4),
5185
                           part_search_state->ss_x,
5186
                           part_search_state->ss_y) != BLOCK_INVALID;
5187
  valid_types |= (horz4_allowed << 8);
5188
  // PARTITION_VERT_4
5189
  const int vert4_allowed =
5190
      partition4_allowed && part_search_state->partition_rect_allowed[HORZ] &&
5191
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_VERT_4),
5192
                           part_search_state->ss_x,
5193
                           part_search_state->ss_y) != BLOCK_INVALID;
5194
  valid_types |= (vert4_allowed << 9);
5195
5196
  return valid_types;
5197
}
5198
5199
static void prepare_tpl_stats_block(const AV1_COMP *const cpi,
5200
                                    const BLOCK_SIZE bsize, const int mi_row,
5201
                                    const int mi_col, int64_t *intra_cost,
5202
                                    int64_t *inter_cost, int64_t *mc_dep_cost) {
5203
  const AV1_COMMON *const cm = &cpi->common;
5204
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
5205
  if (gf_group->update_type[cpi->gf_frame_index] == INTNL_OVERLAY_UPDATE ||
5206
      gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE) {
5207
    return;
5208
  }
5209
5210
  TplParams *const tpl_data = &cpi->ppi->tpl_data;
5211
  TplDepFrame *tpl_frame = &tpl_data->tpl_frame[cpi->gf_frame_index];
5212
  TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
5213
  // If tpl stats is not established, early return
5214
  if (!tpl_data->ready || gf_group->max_layer_depth_allowed == 0) {
5215
    return;
5216
  }
5217
5218
  const int tpl_stride = tpl_frame->stride;
5219
  const int step = 1 << tpl_data->tpl_stats_block_mis_log2;
5220
  const int mi_width =
5221
      AOMMIN(mi_size_wide[bsize], cm->mi_params.mi_cols - mi_col);
5222
  const int mi_height =
5223
      AOMMIN(mi_size_high[bsize], cm->mi_params.mi_rows - mi_row);
5224
5225
  int64_t sum_intra_cost = 0;
5226
  int64_t sum_inter_cost = 0;
5227
  int64_t sum_mc_dep_cost = 0;
5228
  for (int row = 0; row < mi_height; row += step) {
5229
    for (int col = 0; col < mi_width; col += step) {
5230
      TplDepStats *this_stats =
5231
          &tpl_stats[av1_tpl_ptr_pos(mi_row + row, mi_col + col, tpl_stride,
5232
                                     tpl_data->tpl_stats_block_mis_log2)];
5233
      sum_intra_cost += this_stats->intra_cost;
5234
      sum_inter_cost += this_stats->inter_cost;
5235
      const int64_t mc_dep_delta =
5236
          RDCOST(tpl_frame->base_rdmult, this_stats->mc_dep_rate,
5237
                 this_stats->mc_dep_dist);
5238
      sum_mc_dep_cost += mc_dep_delta;
5239
    }
5240
  }
5241
5242
  *intra_cost = sum_intra_cost;
5243
  *inter_cost = sum_inter_cost;
5244
  *mc_dep_cost = sum_mc_dep_cost;
5245
}
5246
5247
static bool recursive_partition(AV1_COMP *const cpi, ThreadData *td,
5248
                                TileDataEnc *tile_data, TokenExtra **tp,
5249
                                SIMPLE_MOTION_DATA_TREE *sms_root,
5250
                                PC_TREE *pc_tree, int mi_row, int mi_col,
5251
                                const BLOCK_SIZE bsize, RD_STATS *this_rdcost) {
5252
  const AV1_COMMON *const cm = &cpi->common;
5253
  ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
5254
  MACROBLOCK *const x = &td->mb;
5255
  MACROBLOCKD *const xd = &x->e_mbd;
5256
  if (mi_row >= cm->mi_params.mi_rows || mi_col >= cm->mi_params.mi_cols) {
5257
    return false;
5258
  }
5259
  aom_partition_decision_t partition_decision;
5260
  do {
5261
    PartitionSearchState part_search_state;
5262
    // Initialization of state variables used in partition search.
5263
    // TODO(chengchen): check if there is hidden conditions that don't allow
5264
    // all possible partition types.
5265
    init_partition_search_state_params(x, cpi, &part_search_state, mi_row,
5266
                                       mi_col, bsize);
5267
    // Override partition costs at the edges of the frame in the same
5268
    // way as in read_partition (see decodeframe.c).
5269
    PartitionBlkParams blk_params = part_search_state.part_blk_params;
5270
    if (!av1_blk_has_rows_and_cols(&blk_params))
5271
      set_partition_cost_for_edge_blk(cm, &part_search_state);
5272
    const int orig_rdmult = x->rdmult;
5273
    setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
5274
    const int valid_partition_types =
5275
        get_valid_partition_types(cpi, &part_search_state, bsize);
5276
    const FRAME_UPDATE_TYPE update_type =
5277
        get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
5278
    const int qindex = av1_get_qindex(&cm->seg, xd->mi[0]->segment_id,
5279
                                      cm->quant_params.base_qindex);
5280
    // RD multiplier
5281
    const int rdmult = x->rdmult;
5282
    // pyramid level
5283
    const int pyramid_level =
5284
        cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index];
5285
    x->rdmult = orig_rdmult;
5286
    // Neighbor information
5287
    const int has_above = !!xd->above_mbmi;
5288
    const int has_left = !!xd->left_mbmi;
5289
    const BLOCK_SIZE above_bsize =
5290
        has_above ? xd->above_mbmi->bsize : BLOCK_INVALID;
5291
    const BLOCK_SIZE left_bsize =
5292
        has_left ? xd->left_mbmi->bsize : BLOCK_INVALID;
5293
    const int above_block_width =
5294
        above_bsize == BLOCK_INVALID ? -1 : block_size_wide[above_bsize];
5295
    const int above_block_height =
5296
        above_bsize == BLOCK_INVALID ? -1 : block_size_high[above_bsize];
5297
    const int left_block_width =
5298
        left_bsize == BLOCK_INVALID ? -1 : block_size_wide[left_bsize];
5299
    const int left_block_height =
5300
        left_bsize == BLOCK_INVALID ? -1 : block_size_high[left_bsize];
5301
    // Prepare simple motion search stats as features
5302
    unsigned int block_sse = -1;
5303
    unsigned int block_var = -1;
5304
    unsigned int sub_block_sse[4] = { -1, -1, -1, -1 };
5305
    unsigned int sub_block_var[4] = { -1, -1, -1, -1 };
5306
    unsigned int horz_block_sse[2] = { -1, -1 };
5307
    unsigned int horz_block_var[2] = { -1, -1 };
5308
    unsigned int vert_block_sse[2] = { -1, -1 };
5309
    unsigned int vert_block_var[2] = { -1, -1 };
5310
    av1_prepare_motion_search_features_block(
5311
        cpi, td, tile_data, mi_row, mi_col, bsize, valid_partition_types,
5312
        &block_sse, &block_var, sub_block_sse, sub_block_var, horz_block_sse,
5313
        horz_block_var, vert_block_sse, vert_block_var);
5314
    // Prepare tpl stats for the current block as features
5315
    int64_t tpl_intra_cost = -1;
5316
    int64_t tpl_inter_cost = -1;
5317
    int64_t tpl_mc_dep_cost = -1;
5318
    prepare_tpl_stats_block(cpi, bsize, mi_row, mi_col, &tpl_intra_cost,
5319
                            &tpl_inter_cost, &tpl_mc_dep_cost);
5320
5321
    aom_partition_features_t features;
5322
    features.mi_row = mi_row;
5323
    features.mi_col = mi_col;
5324
    features.frame_width = cpi->frame_info.frame_width;
5325
    features.frame_height = cpi->frame_info.frame_height;
5326
    features.block_size = bsize;
5327
    features.valid_partition_types = valid_partition_types;
5328
    features.update_type = update_type;
5329
    features.qindex = qindex;
5330
    features.rdmult = rdmult;
5331
    features.pyramid_level = pyramid_level;
5332
    features.has_above_block = has_above;
5333
    features.above_block_width = above_block_width;
5334
    features.above_block_height = above_block_height;
5335
    features.has_left_block = has_left;
5336
    features.left_block_width = left_block_width;
5337
    features.left_block_height = left_block_height;
5338
    features.block_sse = block_sse;
5339
    features.block_var = block_var;
5340
    for (int i = 0; i < 4; ++i) {
5341
      features.sub_block_sse[i] = sub_block_sse[i];
5342
      features.sub_block_var[i] = sub_block_var[i];
5343
    }
5344
    for (int i = 0; i < 2; ++i) {
5345
      features.horz_block_sse[i] = horz_block_sse[i];
5346
      features.horz_block_var[i] = horz_block_var[i];
5347
      features.vert_block_sse[i] = vert_block_sse[i];
5348
      features.vert_block_var[i] = vert_block_var[i];
5349
    }
5350
    features.tpl_intra_cost = tpl_intra_cost;
5351
    features.tpl_inter_cost = tpl_inter_cost;
5352
    features.tpl_mc_dep_cost = tpl_mc_dep_cost;
5353
    av1_ext_part_send_features(ext_part_controller, &features);
5354
    const bool valid_decision = av1_ext_part_get_partition_decision(
5355
        ext_part_controller, &partition_decision);
5356
    if (!valid_decision) return false;
5357
    pc_tree->partitioning = partition_decision.current_decision;
5358
5359
    av1_init_rd_stats(this_rdcost);
5360
    if (partition_decision.current_decision == PARTITION_SPLIT) {
5361
      assert(block_size_wide[bsize] >= 8 && block_size_high[bsize] >= 8);
5362
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
5363
      RD_STATS split_rdc[SUB_PARTITIONS_SPLIT];
5364
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
5365
        av1_init_rd_stats(&split_rdc[i]);
5366
        if (pc_tree->split[i] == NULL)
5367
          pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
5368
        if (!pc_tree->split[i])
5369
          aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
5370
                             "Failed to allocate PC_TREE");
5371
        pc_tree->split[i]->index = i;
5372
      }
5373
      const int orig_rdmult_tmp = x->rdmult;
5374
      setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
5375
      // TODO(chengchen): check boundary conditions
5376
      // top-left
5377
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[0],
5378
                          mi_row, mi_col, subsize, &split_rdc[0]);
5379
      // top-right
5380
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[1],
5381
                          mi_row, mi_col + mi_size_wide[subsize], subsize,
5382
                          &split_rdc[1]);
5383
      // bottom-left
5384
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[2],
5385
                          mi_row + mi_size_high[subsize], mi_col, subsize,
5386
                          &split_rdc[2]);
5387
      // bottom_right
5388
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[3],
5389
                          mi_row + mi_size_high[subsize],
5390
                          mi_col + mi_size_wide[subsize], subsize,
5391
                          &split_rdc[3]);
5392
      this_rdcost->rate += part_search_state.partition_cost[PARTITION_SPLIT];
5393
      // problem is here, the rdmult is different from the rdmult in sub block.
5394
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
5395
        this_rdcost->rate += split_rdc[i].rate;
5396
        this_rdcost->dist += split_rdc[i].dist;
5397
        av1_rd_cost_update(x->rdmult, this_rdcost);
5398
      }
5399
      x->rdmult = orig_rdmult_tmp;
5400
    } else {
5401
      *this_rdcost = rd_search_for_fixed_partition(
5402
          cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize, pc_tree);
5403
    }
5404
5405
    aom_partition_stats_t stats;
5406
    update_partition_stats(this_rdcost, &stats);
5407
    av1_ext_part_send_partition_stats(ext_part_controller, &stats);
5408
    if (!partition_decision.is_final_decision) {
5409
      if (partition_decision.current_decision == PARTITION_SPLIT) {
5410
        for (int i = 0; i < 4; ++i) {
5411
          if (pc_tree->split[i] != NULL) {
5412
            av1_free_pc_tree_recursive(pc_tree->split[i], av1_num_planes(cm), 0,
5413
                                       0,
5414
                                       cpi->sf.part_sf.partition_search_type);
5415
            pc_tree->split[i] = NULL;
5416
          }
5417
        }
5418
      }
5419
    }
5420
  } while (!partition_decision.is_final_decision);
5421
5422
  return true;
5423
}
5424
5425
// The ML model only needs to make decisions for the current block each time.
5426
static bool ml_partition_search_partial(AV1_COMP *const cpi, ThreadData *td,
5427
                                        TileDataEnc *tile_data, TokenExtra **tp,
5428
                                        SIMPLE_MOTION_DATA_TREE *sms_root,
5429
                                        int mi_row, int mi_col,
5430
                                        const BLOCK_SIZE bsize) {
5431
  AV1_COMMON *const cm = &cpi->common;
5432
  MACROBLOCK *const x = &td->mb;
5433
  ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
5434
  aom_partition_features_t features;
5435
  prepare_sb_features_before_search(cpi, td, tile_data, mi_row, mi_col, bsize,
5436
                                    &features);
5437
  features.mi_row = mi_row;
5438
  features.mi_col = mi_col;
5439
  features.frame_width = cpi->frame_info.frame_width;
5440
  features.frame_height = cpi->frame_info.frame_height;
5441
  features.block_size = bsize;
5442
  av1_ext_part_send_features(ext_part_controller, &features);
5443
  td->pc_root = av1_alloc_pc_tree_node(bsize);
5444
  if (!td->pc_root)
5445
    aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
5446
                       "Failed to allocate PC_TREE");
5447
5448
  RD_STATS rdcost;
5449
  const bool valid_partition =
5450
      recursive_partition(cpi, td, tile_data, tp, sms_root, td->pc_root, mi_row,
5451
                          mi_col, bsize, &rdcost);
5452
  if (!valid_partition) {
5453
    return false;
5454
  }
5455
5456
  // Encode with the selected mode and partition.
5457
  set_cb_offsets(x->cb_offset, 0, 0);
5458
  encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
5459
            td->pc_root, NULL);
5460
  av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5461
                             cpi->sf.part_sf.partition_search_type);
5462
  td->pc_root = NULL;
5463
5464
  return true;
5465
}
5466
5467
bool av1_rd_partition_search(AV1_COMP *const cpi, ThreadData *td,
5468
                             TileDataEnc *tile_data, TokenExtra **tp,
5469
                             SIMPLE_MOTION_DATA_TREE *sms_root, int mi_row,
5470
                             int mi_col, const BLOCK_SIZE bsize,
5471
                             RD_STATS *best_rd_cost) {
5472
  AV1_COMMON *const cm = &cpi->common;
5473
  if (cpi->ext_part_controller.ready) {
5474
    bool valid_search = true;
5475
    const aom_ext_part_decision_mode_t decision_mode =
5476
        av1_get_ext_part_decision_mode(&cpi->ext_part_controller);
5477
    if (decision_mode == AOM_EXT_PART_WHOLE_TREE) {
5478
      valid_search = ml_partition_search_whole_tree(
5479
          cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize);
5480
    } else if (decision_mode == AOM_EXT_PART_RECURSIVE) {
5481
      valid_search = ml_partition_search_partial(
5482
          cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize);
5483
    } else {
5484
      assert(0 && "Unknown decision mode.");
5485
      return false;
5486
    }
5487
    if (!valid_search) {
5488
      aom_internal_error(
5489
          cm->error, AOM_CODEC_ERROR,
5490
          "Invalid search from ML model, partition search failed");
5491
    }
5492
    return true;
5493
  }
5494
5495
  MACROBLOCK *const x = &td->mb;
5496
  MACROBLOCKD *const xd = &x->e_mbd;
5497
  int best_idx = 0;
5498
  int64_t min_rdcost = INT64_MAX;
5499
  int num_configs;
5500
  int i = 0;
5501
  do {
5502
    td->pc_root = av1_alloc_pc_tree_node(bsize);
5503
    if (!td->pc_root)
5504
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
5505
                         "Failed to allocate PC_TREE");
5506
    num_configs = read_partition_tree(cpi, td->pc_root, xd->error_info, i);
5507
    if (num_configs <= 0) {
5508
      av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5509
                                 cpi->sf.part_sf.partition_search_type);
5510
      td->pc_root = NULL;
5511
      aom_internal_error(xd->error_info, AOM_CODEC_ERROR, "Invalid configs.");
5512
    }
5513
    verify_write_partition_tree(cpi, td->pc_root, bsize, i, mi_row, mi_col);
5514
    if (i == 0) {
5515
      AOM_CHECK_MEM_ERROR(xd->error_info, x->rdcost,
5516
                          aom_calloc(num_configs, sizeof(*x->rdcost)));
5517
    }
5518
    // Encode the block with the given partition tree. Get rdcost and encoding
5519
    // time.
5520
    x->rdcost[i] = rd_search_for_fixed_partition(
5521
        cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize, td->pc_root);
5522
5523
    if (x->rdcost[i].rdcost < min_rdcost) {
5524
      min_rdcost = x->rdcost[i].rdcost;
5525
      best_idx = i;
5526
      *best_rd_cost = x->rdcost[i];
5527
    }
5528
    av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5529
                               cpi->sf.part_sf.partition_search_type);
5530
    td->pc_root = NULL;
5531
    ++i;
5532
  } while (i < num_configs);
5533
5534
  aom_free(x->rdcost);
5535
  x->rdcost = NULL;
5536
  // Encode with the partition configuration with the smallest rdcost.
5537
  td->pc_root = av1_alloc_pc_tree_node(bsize);
5538
  if (!td->pc_root)
5539
    aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
5540
                       "Failed to allocate PC_TREE");
5541
  read_partition_tree(cpi, td->pc_root, xd->error_info, best_idx);
5542
  rd_search_for_fixed_partition(cpi, td, tile_data, tp, sms_root, mi_row,
5543
                                mi_col, bsize, td->pc_root);
5544
  set_cb_offsets(x->cb_offset, 0, 0);
5545
  encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
5546
            td->pc_root, NULL);
5547
  av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5548
                             cpi->sf.part_sf.partition_search_type);
5549
  td->pc_root = NULL;
5550
  ++cpi->sb_counter;
5551
5552
  return true;
5553
}
5554
#endif  // CONFIG_PARTITION_SEARCH_ORDER
5555
5556
static inline bool should_do_dry_run_encode_for_current_block(
5557
    BLOCK_SIZE sb_size, BLOCK_SIZE max_partition_size, int curr_block_index,
5558
13.4M
    BLOCK_SIZE bsize) {
5559
13.4M
  if (bsize > max_partition_size) return false;
5560
5561
  // Enable the reconstruction with dry-run for the 4th sub-block only if its
5562
  // parent block's reconstruction with dry-run is skipped. If
5563
  // max_partition_size is the same as immediate split of superblock, then avoid
5564
  // reconstruction of the 4th sub-block, as this data is not consumed.
5565
13.4M
  if (curr_block_index != 3) return true;
5566
5567
1.59M
  const BLOCK_SIZE sub_sb_size =
5568
1.59M
      get_partition_subsize(sb_size, PARTITION_SPLIT);
5569
1.59M
  return bsize == max_partition_size && sub_sb_size != max_partition_size;
5570
13.4M
}
5571
5572
static void log_sub_block_var(const AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bs,
5573
13.4M
                              double *var_min, double *var_max) {
5574
  // This functions returns a the minimum and maximum log variances for 4x4
5575
  // sub blocks in the current block.
5576
5577
13.4M
  const MACROBLOCKD *const xd = &x->e_mbd;
5578
13.4M
  const int is_hbd = is_cur_buf_hbd(xd);
5579
13.4M
  const int right_overflow =
5580
13.4M
      (xd->mb_to_right_edge < 0) ? ((-xd->mb_to_right_edge) >> 3) : 0;
5581
13.4M
  const int bottom_overflow =
5582
13.4M
      (xd->mb_to_bottom_edge < 0) ? ((-xd->mb_to_bottom_edge) >> 3) : 0;
5583
13.4M
  const int bw = MI_SIZE * mi_size_wide[bs] - right_overflow;
5584
13.4M
  const int bh = MI_SIZE * mi_size_high[bs] - bottom_overflow;
5585
5586
  // Initialize minimum variance to a large value and maximum variance to 0.
5587
13.4M
  double min_var_4x4 = (double)INT_MAX;
5588
13.4M
  double max_var_4x4 = 0.0;
5589
5590
13.4M
  aom_variance_fn_t vf = cpi->ppi->fn_ptr[BLOCK_4X4].vf;
5591
40.5M
  for (int i = 0; i < bh; i += MI_SIZE) {
5592
143M
    for (int j = 0; j < bw; j += MI_SIZE) {
5593
116M
      int var;
5594
      // Calculate the 4x4 sub-block variance.
5595
116M
      var = av1_calc_normalized_variance(
5596
116M
          vf, x->plane[0].src.buf + (i * x->plane[0].src.stride) + j,
5597
116M
          x->plane[0].src.stride, is_hbd);
5598
5599
      // Record min and max for over-arching block
5600
116M
      min_var_4x4 = AOMMIN(min_var_4x4, var);
5601
116M
      max_var_4x4 = AOMMAX(max_var_4x4, var);
5602
116M
    }
5603
27.1M
  }
5604
13.4M
  *var_min = log1p(min_var_4x4 / 16.0);
5605
13.4M
  *var_max = log1p(max_var_4x4 / 16.0);
5606
13.4M
}
5607
5608
static inline void set_sms_tree_partitioning(SIMPLE_MOTION_DATA_TREE *sms_tree,
5609
31.3M
                                             PARTITION_TYPE partition) {
5610
31.3M
  if (sms_tree == NULL) return;
5611
4.80M
  sms_tree->partitioning = partition;
5612
4.80M
}
5613
5614
/*!\brief AV1 block partition search (full search).
5615
*
5616
* \ingroup partition_search
5617
* \callgraph
5618
* Searches for the best partition pattern for a block based on the
5619
* rate-distortion cost, and returns a bool value to indicate whether a valid
5620
* partition pattern is found. The partition can recursively go down to the
5621
* smallest block size.
5622
*
5623
* \param[in]    cpi                Top-level encoder structure
5624
* \param[in]    td                 Pointer to thread data
5625
* \param[in]    tile_data          Pointer to struct holding adaptive
5626
data/contexts/models for the tile during
5627
encoding
5628
* \param[in]    tp                 Pointer to the starting token
5629
* \param[in]    mi_row             Row coordinate of the block in a step size
5630
of MI_SIZE
5631
* \param[in]    mi_col             Column coordinate of the block in a step
5632
size of MI_SIZE
5633
* \param[in]    bsize              Current block size
5634
* \param[in]    rd_cost            Pointer to the final rd cost of the block
5635
* \param[in]    best_rdc           Upper bound of rd cost of a valid partition
5636
* \param[in]    pc_tree            Pointer to the PC_TREE node storing the
5637
picked partitions and mode info for the
5638
current block
5639
* \param[in]    sms_tree           Pointer to struct holding simple motion
5640
search data for the current block
5641
* \param[in]    none_rd            Pointer to the rd cost in the case of not
5642
splitting the current block
5643
* \param[in]    multi_pass_mode    SB_SINGLE_PASS/SB_DRY_PASS/SB_WET_PASS
5644
* \param[in]    rect_part_win_info Pointer to struct storing whether horz/vert
5645
partition outperforms previously tested
5646
partitions
5647
*
5648
* \return A bool value is returned indicating if a valid partition is found.
5649
* The pc_tree struct is modified to store the picked partition and modes.
5650
* The rd_cost struct is also updated with the RD stats corresponding to the
5651
* best partition found.
5652
*/
5653
bool av1_rd_pick_partition(AV1_COMP *const cpi, ThreadData *td,
5654
                           TileDataEnc *tile_data, TokenExtra **tp, int mi_row,
5655
                           int mi_col, BLOCK_SIZE bsize, RD_STATS *rd_cost,
5656
                           RD_STATS best_rdc, PC_TREE *pc_tree,
5657
                           SIMPLE_MOTION_DATA_TREE *sms_tree, int64_t *none_rd,
5658
                           SB_MULTI_PASS_MODE multi_pass_mode,
5659
15.6M
                           RD_RECT_PART_WIN_INFO *rect_part_win_info) {
5660
15.6M
  const AV1_COMMON *const cm = &cpi->common;
5661
15.6M
  const int num_planes = av1_num_planes(cm);
5662
15.6M
  TileInfo *const tile_info = &tile_data->tile_info;
5663
15.6M
  MACROBLOCK *const x = &td->mb;
5664
15.6M
  MACROBLOCKD *const xd = &x->e_mbd;
5665
15.6M
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
5666
15.6M
  const TokenExtra *const tp_orig = *tp;
5667
15.6M
  PartitionSearchState part_search_state;
5668
5669
  // Initialization of state variables used in partition search.
5670
15.6M
  init_partition_search_state_params(x, cpi, &part_search_state, mi_row, mi_col,
5671
15.6M
                                     bsize);
5672
15.6M
  PartitionBlkParams blk_params = part_search_state.part_blk_params;
5673
5674
15.6M
  set_sms_tree_partitioning(sms_tree, PARTITION_NONE);
5675
15.6M
  if (best_rdc.rdcost < 0) {
5676
0
    av1_invalid_rd_stats(rd_cost);
5677
0
    return part_search_state.found_best_partition;
5678
0
  }
5679
15.6M
  if (bsize == cm->seq_params->sb_size) x->must_find_valid_partition = 0;
5680
5681
  // Override skipping rectangular partition operations for edge blocks.
5682
15.6M
  if (none_rd) *none_rd = 0;
5683
15.6M
  (void)*tp_orig;
5684
5685
#if CONFIG_COLLECT_PARTITION_STATS
5686
  // Stats at the current quad tree
5687
  PartitionTimingStats *part_timing_stats =
5688
      &part_search_state.part_timing_stats;
5689
  // Stats aggregated at frame level
5690
  FramePartitionTimingStats *fr_part_timing_stats = &cpi->partition_stats;
5691
#endif  // CONFIG_COLLECT_PARTITION_STATS
5692
5693
  // Override partition costs at the edges of the frame in the same
5694
  // way as in read_partition (see decodeframe.c).
5695
15.6M
  if (!av1_blk_has_rows_and_cols(&blk_params))
5696
994k
    set_partition_cost_for_edge_blk(cm, &part_search_state);
5697
5698
  // Disable rectangular partitions for inner blocks when the current block is
5699
  // forced to only use square partitions.
5700
15.6M
  if (bsize > cpi->sf.part_sf.use_square_partition_only_threshold) {
5701
1.06M
    part_search_state.partition_rect_allowed[HORZ] &= !blk_params.has_rows;
5702
1.06M
    part_search_state.partition_rect_allowed[VERT] &= !blk_params.has_cols;
5703
1.06M
  }
5704
5705
15.6M
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);
5706
5707
  // Set buffers and offsets.
5708
15.6M
  av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
5709
5710
15.6M
  if (cpi->oxcf.mode == ALLINTRA) {
5711
13.2M
    if (bsize == cm->seq_params->sb_size) {
5712
197k
      double var_min, var_max;
5713
197k
      log_sub_block_var(cpi, x, bsize, &var_min, &var_max);
5714
5715
197k
      x->intra_sb_rdmult_modifier = 128;
5716
197k
      if ((var_min < 2.0) && (var_max > 4.0)) {
5717
41.6k
        if ((var_max - var_min) > 8.0) {
5718
39.8k
          x->intra_sb_rdmult_modifier -= 48;
5719
39.8k
        } else {
5720
1.80k
          x->intra_sb_rdmult_modifier -= (int)((var_max - var_min) * 6);
5721
1.80k
        }
5722
41.6k
      }
5723
197k
    }
5724
13.2M
  }
5725
5726
  // Save rdmult before it might be changed, so it can be restored later.
5727
15.6M
  const int orig_rdmult = x->rdmult;
5728
15.6M
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
5729
5730
  // Apply simple motion search for the entire super block with fixed block
5731
  // size, e.g., 16x16, to collect features and write to files for the
5732
  // external ML model.
5733
  // TODO(chengchen): reduce motion search. This function is similar to
5734
  // av1_get_max_min_partition_features().
5735
#if COLLECT_MOTION_SEARCH_FEATURE_SB
5736
  if (!frame_is_intra_only(cm) && bsize == cm->seq_params->sb_size) {
5737
    av1_collect_motion_search_features_sb(cpi, td, tile_data, mi_row, mi_col,
5738
                                          bsize, /*features=*/NULL);
5739
    collect_tpl_stats_sb(cpi, bsize, mi_row, mi_col, /*features=*/NULL);
5740
  }
5741
#endif  // !COLLECT_MOTION_SEARCH_FEATURE_SB
5742
5743
  // Update rd cost of the bound using the current multiplier.
5744
15.6M
  av1_rd_cost_update(x->rdmult, &best_rdc);
5745
5746
15.6M
  if (bsize == BLOCK_16X16 && cpi->vaq_refresh)
5747
0
    x->mb_energy = av1_log_block_var(cpi, x, bsize);
5748
5749
  // Set the context.
5750
15.6M
  xd->above_txfm_context =
5751
15.6M
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
5752
15.6M
  xd->left_txfm_context =
5753
15.6M
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
5754
15.6M
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
5755
5756
#if CONFIG_COLLECT_COMPONENT_TIMING
5757
  start_timing(cpi, av1_prune_partitions_time);
5758
#endif
5759
  // Pruning: before searching any partition type, using source and simple
5760
  // motion search results to prune out unlikely partitions.
5761
15.6M
  av1_prune_partitions_before_search(cpi, x, sms_tree, &part_search_state);
5762
5763
  // Pruning: eliminating partition types leading to coding block sizes outside
5764
  // the min and max bsize limitations set from the encoder.
5765
15.6M
  av1_prune_partitions_by_max_min_bsize(&x->sb_enc, &part_search_state);
5766
#if CONFIG_COLLECT_COMPONENT_TIMING
5767
  end_timing(cpi, av1_prune_partitions_time);
5768
#endif
5769
5770
  // Partition search
5771
15.6M
BEGIN_PARTITION_SEARCH:
5772
  // If a valid partition is required, usually when the first round cannot find
5773
  // a valid one under the cost limit after pruning, reset the limitations on
5774
  // partition types and intra cnn output.
5775
15.6M
  if (x->must_find_valid_partition) {
5776
0
    reset_part_limitations(cpi, &part_search_state);
5777
0
    av1_prune_partitions_by_max_min_bsize(&x->sb_enc, &part_search_state);
5778
    // Invalidate intra cnn output for key frames.
5779
0
    if (frame_is_intra_only(cm) && bsize == BLOCK_64X64) {
5780
0
      part_search_state.intra_part_info->quad_tree_idx = 0;
5781
0
      part_search_state.intra_part_info->cnn_output_valid = 0;
5782
0
    }
5783
0
  }
5784
  // Partition block source pixel variance.
5785
15.6M
  unsigned int pb_source_variance = UINT_MAX;
5786
5787
#if CONFIG_COLLECT_COMPONENT_TIMING
5788
  start_timing(cpi, none_partition_search_time);
5789
#endif
5790
5791
15.6M
  if (cpi->oxcf.mode == ALLINTRA) {
5792
13.2M
    const bool bsize_at_least_16x16 = (bsize >= BLOCK_16X16);
5793
13.2M
    const bool prune_rect_part_using_4x4_var_deviation =
5794
13.2M
        (cpi->sf.part_sf.prune_rect_part_using_4x4_var_deviation &&
5795
13.2M
         !x->must_find_valid_partition);
5796
5797
13.2M
    if (bsize_at_least_16x16 || prune_rect_part_using_4x4_var_deviation) {
5798
13.2M
      double var_min, var_max;
5799
13.2M
      log_sub_block_var(cpi, x, bsize, &var_min, &var_max);
5800
5801
      // Further pruning or in some cases reverse pruning when allintra is set.
5802
      // This code helps visual and in some cases metrics quality where the
5803
      // current block comprises at least one very low variance sub-block and at
5804
      // least one where the variance is much higher.
5805
      //
5806
      // The idea is that in such cases there is danger of ringing and other
5807
      // visual artifacts from a high variance feature such as an edge into a
5808
      // very low variance region.
5809
      //
5810
      // The approach taken is to force break down / split to a smaller block
5811
      // size to try and separate out the low variance and well predicted blocks
5812
      // from the more complex ones and to prevent propagation of ringing over a
5813
      // large region.
5814
13.2M
      if (bsize_at_least_16x16 && (var_min < 0.272) &&
5815
146k
          ((var_max - var_min) > 3.0)) {
5816
138k
        part_search_state.partition_none_allowed = 0;
5817
138k
        part_search_state.terminate_partition_search = 0;
5818
138k
        part_search_state.do_square_split = 1;
5819
13.1M
      } else if (prune_rect_part_using_4x4_var_deviation &&
5820
13.1M
                 (var_max - var_min < 3.0)) {
5821
        // Prune rectangular partitions if the variance deviation of 4x4
5822
        // sub-blocks within the block is less than a threshold (derived
5823
        // empirically).
5824
12.9M
        part_search_state.do_rectangular_split = 0;
5825
12.9M
      }
5826
13.2M
    }
5827
13.2M
  }
5828
5829
  // PARTITION_NONE search stage.
5830
15.6M
  int64_t part_none_rd = INT64_MAX;
5831
15.6M
  none_partition_search(cpi, td, tile_data, x, pc_tree, sms_tree, &x_ctx,
5832
15.6M
                        &part_search_state, &best_rdc, &pb_source_variance,
5833
15.6M
                        none_rd, &part_none_rd);
5834
5835
#if CONFIG_COLLECT_COMPONENT_TIMING
5836
  end_timing(cpi, none_partition_search_time);
5837
#endif
5838
#if CONFIG_COLLECT_COMPONENT_TIMING
5839
  start_timing(cpi, split_partition_search_time);
5840
#endif
5841
  // PARTITION_SPLIT search stage.
5842
15.6M
  int64_t part_split_rd = INT64_MAX;
5843
15.6M
  split_partition_search(cpi, td, tile_data, tp, x, pc_tree, sms_tree, &x_ctx,
5844
15.6M
                         &part_search_state, &best_rdc, multi_pass_mode,
5845
15.6M
                         &part_split_rd);
5846
#if CONFIG_COLLECT_COMPONENT_TIMING
5847
  end_timing(cpi, split_partition_search_time);
5848
#endif
5849
  // Terminate partition search for child partition,
5850
  // when NONE and SPLIT partition rd_costs are INT64_MAX.
5851
15.6M
  if (cpi->sf.part_sf.early_term_after_none_split &&
5852
15.6M
      part_none_rd == INT64_MAX && part_split_rd == INT64_MAX &&
5853
1.37M
      !x->must_find_valid_partition && (bsize != cm->seq_params->sb_size)) {
5854
1.37M
    part_search_state.terminate_partition_search = 1;
5855
1.37M
  }
5856
5857
  // Do not evaluate non-square partitions if NONE partition did not choose a
5858
  // newmv mode and is skippable.
5859
15.6M
  if ((cpi->sf.part_sf.skip_non_sq_part_based_on_none >= 2) &&
5860
0
      (pc_tree->none != NULL)) {
5861
0
    if (x->qindex <= 200 && is_inter_mode(pc_tree->none->mic.mode) &&
5862
0
        !have_newmv_in_inter_mode(pc_tree->none->mic.mode) &&
5863
0
        pc_tree->none->skippable && !x->must_find_valid_partition &&
5864
0
        bsize >= BLOCK_16X16)
5865
0
      part_search_state.do_rectangular_split = 0;
5866
0
  }
5867
5868
  // Prune partitions based on PARTITION_NONE and PARTITION_SPLIT.
5869
15.6M
  prune_partitions_after_split(cpi, x, sms_tree, &part_search_state, &best_rdc,
5870
15.6M
                               part_none_rd, part_split_rd);
5871
#if CONFIG_COLLECT_COMPONENT_TIMING
5872
  start_timing(cpi, rectangular_partition_search_time);
5873
#endif
5874
  // Rectangular partitions search stage.
5875
15.6M
  rectangular_partition_search(cpi, td, tile_data, tp, x, pc_tree, &x_ctx,
5876
15.6M
                               &part_search_state, &best_rdc,
5877
15.6M
                               rect_part_win_info, HORZ, VERT);
5878
#if CONFIG_COLLECT_COMPONENT_TIMING
5879
  end_timing(cpi, rectangular_partition_search_time);
5880
#endif
5881
5882
15.6M
  if (pb_source_variance == UINT_MAX) {
5883
1.51M
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, num_planes, bsize);
5884
1.51M
    pb_source_variance = av1_get_perpixel_variance_facade(
5885
1.51M
        cpi, xd, &x->plane[0].src, bsize, AOM_PLANE_Y);
5886
1.51M
  }
5887
5888
15.6M
  assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
5889
15.6M
                 !part_search_state.do_rectangular_split));
5890
5891
15.6M
  const int prune_ext_part_state = prune_ext_part_none_skippable(
5892
15.6M
      pc_tree->none, x->must_find_valid_partition,
5893
15.6M
      cpi->sf.part_sf.skip_non_sq_part_based_on_none, bsize);
5894
5895
15.6M
  const int ab_partition_allowed = allow_ab_partition_search(
5896
15.6M
      &part_search_state, &cpi->sf.part_sf, pc_tree->partitioning,
5897
15.6M
      x->must_find_valid_partition, prune_ext_part_state, best_rdc.rdcost);
5898
5899
#if CONFIG_COLLECT_COMPONENT_TIMING
5900
  start_timing(cpi, ab_partitions_search_time);
5901
#endif
5902
  // AB partitions search stage.
5903
15.6M
  ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
5904
15.6M
                       &part_search_state, &best_rdc, rect_part_win_info,
5905
15.6M
                       pb_source_variance, ab_partition_allowed, HORZ_A,
5906
15.6M
                       VERT_B);
5907
#if CONFIG_COLLECT_COMPONENT_TIMING
5908
  end_timing(cpi, ab_partitions_search_time);
5909
#endif
5910
5911
  // 4-way partitions search stage.
5912
15.6M
  int part4_search_allowed[NUM_PART4_TYPES] = { 1, 1 };
5913
  // Prune 4-way partition search.
5914
15.6M
  prune_4_way_partition_search(cpi, x, pc_tree, &part_search_state, sms_tree,
5915
15.6M
                               &best_rdc, pb_source_variance,
5916
15.6M
                               prune_ext_part_state, mi_row, mi_col,
5917
15.6M
                               part4_search_allowed);
5918
5919
#if CONFIG_COLLECT_COMPONENT_TIMING
5920
  start_timing(cpi, rd_pick_4partition_time);
5921
#endif
5922
  // PARTITION_HORZ_4
5923
15.6M
  assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
5924
15.6M
                 !part4_search_allowed[HORZ4]));
5925
15.6M
  if (!part_search_state.terminate_partition_search &&
5926
14.3M
      part4_search_allowed[HORZ4]) {
5927
0
    const int inc_step[NUM_PART4_TYPES] = { mi_size_high[blk_params.bsize] / 4,
5928
0
                                            0 };
5929
    // Evaluation of Horz4 partition type.
5930
0
    rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
5931
0
                       pc_tree->horizontal4, &part_search_state, &best_rdc,
5932
0
                       inc_step, PARTITION_HORZ_4);
5933
0
  }
5934
5935
  // PARTITION_VERT_4
5936
15.6M
  assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
5937
15.6M
                 !part4_search_allowed[VERT4]));
5938
15.6M
  if (!part_search_state.terminate_partition_search &&
5939
14.3M
      part4_search_allowed[VERT4] && blk_params.has_cols) {
5940
0
    const int inc_step[NUM_PART4_TYPES] = { 0, mi_size_wide[blk_params.bsize] /
5941
0
                                                   4 };
5942
    // Evaluation of Vert4 partition type.
5943
0
    rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
5944
0
                       pc_tree->vertical4, &part_search_state, &best_rdc,
5945
0
                       inc_step, PARTITION_VERT_4);
5946
0
  }
5947
#if CONFIG_COLLECT_COMPONENT_TIMING
5948
  end_timing(cpi, rd_pick_4partition_time);
5949
#endif
5950
5951
15.6M
  if (bsize == cm->seq_params->sb_size &&
5952
288k
      !part_search_state.found_best_partition) {
5953
    // Did not find a valid partition, go back and search again, with less
5954
    // constraint on which partition types to search.
5955
0
    x->must_find_valid_partition = 1;
5956
#if CONFIG_COLLECT_PARTITION_STATS
5957
    fr_part_timing_stats->partition_redo += 1;
5958
#endif  // CONFIG_COLLECT_PARTITION_STATS
5959
0
    goto BEGIN_PARTITION_SEARCH;
5960
0
  }
5961
5962
  // Store the final rd cost
5963
15.6M
  *rd_cost = best_rdc;
5964
5965
  // Also record the best partition in simple motion data tree because it is
5966
  // necessary for the related speed features.
5967
15.6M
  set_sms_tree_partitioning(sms_tree, pc_tree->partitioning);
5968
5969
#if CONFIG_COLLECT_PARTITION_STATS
5970
  if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX) {
5971
    part_timing_stats->partition_decisions[pc_tree->partitioning] += 1;
5972
  }
5973
5974
  // If CONFIG_COLLECT_PARTITION_STATS is 1, then print out the stats for each
5975
  // prediction block.
5976
  print_partition_timing_stats_with_rdcost(
5977
      part_timing_stats, mi_row, mi_col, bsize,
5978
      cpi->ppi->gf_group.update_type[cpi->gf_frame_index],
5979
      cm->current_frame.frame_number, &best_rdc, "part_timing.csv");
5980
  const bool print_timing_stats = false;
5981
  if (print_timing_stats) {
5982
    print_partition_timing_stats(part_timing_stats, cm->show_frame,
5983
                                 frame_is_intra_only(cm), bsize,
5984
                                 "part_timing_data.csv");
5985
  }
5986
  // If CONFIG_COLLECTION_PARTITION_STATS is 2, then we print out the stats for
5987
  // the whole clip. So we need to pass the information upstream to the encoder.
5988
  accumulate_partition_timing_stats(fr_part_timing_stats, part_timing_stats,
5989
                                    bsize);
5990
#endif  // CONFIG_COLLECT_PARTITION_STATS
5991
5992
  // Reset the PC_TREE deallocation flag.
5993
15.6M
  int pc_tree_dealloc = 0;
5994
5995
#if CONFIG_COLLECT_COMPONENT_TIMING
5996
  start_timing(cpi, encode_sb_time);
5997
#endif
5998
15.6M
  if (part_search_state.found_best_partition) {
5999
13.6M
    if (bsize == cm->seq_params->sb_size) {
6000
      // Encode the superblock.
6001
288k
      const int emit_output = multi_pass_mode != SB_DRY_PASS;
6002
288k
      const RUN_TYPE run_type = emit_output ? OUTPUT_ENABLED : DRY_RUN_NORMAL;
6003
6004
#if COLLECT_MOTION_SEARCH_FEATURE_SB
6005
      // Write partition tree to file. Not used by default.
6006
      write_partition_tree(cpi, pc_tree, bsize, mi_row, mi_col);
6007
      ++cpi->sb_counter;
6008
#endif  // COLLECT_MOTION_SEARCH_FEATURE_SB
6009
288k
      set_cb_offsets(x->cb_offset, 0, 0);
6010
288k
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, run_type, bsize,
6011
288k
                pc_tree, NULL);
6012
288k
      assert(pc_tree == td->pc_root);
6013
      // Dealloc the whole PC_TREE after a superblock is done.
6014
288k
      av1_free_pc_tree_recursive(pc_tree, num_planes, 0, 0,
6015
288k
                                 cpi->sf.part_sf.partition_search_type);
6016
288k
      pc_tree = NULL;
6017
288k
      td->pc_root = NULL;
6018
288k
      pc_tree_dealloc = 1;
6019
13.4M
    } else if (should_do_dry_run_encode_for_current_block(
6020
13.4M
                   cm->seq_params->sb_size, x->sb_enc.max_partition_size,
6021
13.4M
                   pc_tree->index, bsize)) {
6022
      // Encode the smaller blocks in DRY_RUN mode.
6023
11.8M
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_NORMAL, bsize,
6024
11.8M
                pc_tree, NULL);
6025
11.8M
    }
6026
13.6M
  }
6027
#if CONFIG_COLLECT_COMPONENT_TIMING
6028
  end_timing(cpi, encode_sb_time);
6029
#endif
6030
6031
  // If the tree still exists (non-superblock), dealloc most nodes, only keep
6032
  // nodes for the best partition and PARTITION_NONE.
6033
15.6M
  if (pc_tree_dealloc == 0)
6034
15.3M
    av1_free_pc_tree_recursive(pc_tree, num_planes, 1, 1,
6035
15.3M
                               cpi->sf.part_sf.partition_search_type);
6036
6037
15.6M
  if (bsize == cm->seq_params->sb_size) {
6038
288k
    assert(best_rdc.rate < INT_MAX);
6039
288k
    assert(best_rdc.dist < INT64_MAX);
6040
15.4M
  } else {
6041
15.4M
    assert(tp_orig == *tp);
6042
15.4M
  }
6043
6044
  // Restore the rd multiplier.
6045
15.6M
  x->rdmult = orig_rdmult;
6046
15.6M
  return part_search_state.found_best_partition;
6047
15.6M
}
6048
#endif  // !CONFIG_REALTIME_ONLY
6049
6050
#undef COLLECT_MOTION_SEARCH_FEATURE_SB
6051
6052
#if CONFIG_RT_ML_PARTITIONING
6053
#define FEATURES 6
6054
#define LABELS 2
6055
static int ml_predict_var_partitioning(AV1_COMP *cpi, MACROBLOCK *x,
6056
                                       BLOCK_SIZE bsize, int mi_row,
6057
                                       int mi_col) {
6058
  AV1_COMMON *const cm = &cpi->common;
6059
  const NN_CONFIG *nn_config = NULL;
6060
  const float *means = NULL;
6061
  const float *vars = NULL;
6062
  switch (bsize) {
6063
    case BLOCK_64X64:
6064
      nn_config = &av1_var_part_nnconfig_64;
6065
      means = av1_var_part_means_64;
6066
      vars = av1_var_part_vars_64;
6067
      break;
6068
    case BLOCK_32X32:
6069
      nn_config = &av1_var_part_nnconfig_32;
6070
      means = av1_var_part_means_32;
6071
      vars = av1_var_part_vars_32;
6072
      break;
6073
    case BLOCK_16X16:
6074
      nn_config = &av1_var_part_nnconfig_16;
6075
      means = av1_var_part_means_16;
6076
      vars = av1_var_part_vars_16;
6077
      break;
6078
    case BLOCK_8X8:
6079
    default: assert(0 && "Unexpected block size."); return -1;
6080
  }
6081
6082
  if (!nn_config) return -1;
6083
6084
  {
6085
    const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
6086
    float features[FEATURES] = { 0.0f };
6087
    const int dc_q = av1_dc_quant_QTX(cm->quant_params.base_qindex, 0,
6088
                                      cm->seq_params->bit_depth);
6089
    int feature_idx = 0;
6090
    float score[LABELS];
6091
6092
    features[feature_idx] =
6093
        (log1pf((float)(dc_q * dc_q) / 256.0f) - means[feature_idx]) /
6094
        sqrtf(vars[feature_idx]);
6095
    feature_idx++;
6096
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, 1, bsize);
6097
    {
6098
      const int bs = block_size_wide[bsize];
6099
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
6100
      const int sb_offset_row = 4 * (mi_row & 15);
6101
      const int sb_offset_col = 4 * (mi_col & 15);
6102
      const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
6103
      const uint8_t *src = x->plane[0].src.buf;
6104
      const int src_stride = x->plane[0].src.stride;
6105
      const int pred_stride = 64;
6106
      unsigned int sse;
6107
      int i;
6108
      // Variance of whole block.
6109
      const unsigned int var =
6110
          cpi->ppi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
6111
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
6112
6113
      features[feature_idx] =
6114
          (log1pf((float)var) - means[feature_idx]) / sqrtf(vars[feature_idx]);
6115
      feature_idx++;
6116
      for (i = 0; i < 4; ++i) {
6117
        const int x_idx = (i & 1) * bs / 2;
6118
        const int y_idx = (i >> 1) * bs / 2;
6119
        const int src_offset = y_idx * src_stride + x_idx;
6120
        const int pred_offset = y_idx * pred_stride + x_idx;
6121
        // Variance of quarter block.
6122
        const unsigned int sub_var =
6123
            cpi->ppi->fn_ptr[subsize].vf(src + src_offset, src_stride,
6124
                                         pred + pred_offset, pred_stride, &sse);
6125
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
6126
        features[feature_idx] =
6127
            (var_ratio - means[feature_idx]) / sqrtf(vars[feature_idx]);
6128
        feature_idx++;
6129
      }
6130
    }
6131
    //    for (int i = 0; i<FEATURES; i++)
6132
    //      printf("F_%d, %f; ", i, features[i]);
6133
    assert(feature_idx == FEATURES);
6134
    av1_nn_predict(features, nn_config, 1, score);
6135
    //    printf("Score %f, thr %f ", (float)score[0], thresh);
6136
    if (score[0] > thresh) return PARTITION_SPLIT;
6137
    if (score[0] < -thresh) return PARTITION_NONE;
6138
    return -1;
6139
  }
6140
}
6141
#undef FEATURES
6142
#undef LABELS
6143
6144
// Uncomment for collecting data for ML-based partitioning
6145
// #define _COLLECT_GROUND_TRUTH_
6146
6147
#ifdef _COLLECT_GROUND_TRUTH_
6148
static int store_partition_data(AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
6149
                                int mi_row, int mi_col, PARTITION_TYPE part) {
6150
  AV1_COMMON *const cm = &cpi->common;
6151
  char fname[128];
6152
  switch (bsize) {
6153
    case BLOCK_64X64: sprintf(fname, "data_64x64.txt"); break;
6154
    case BLOCK_32X32: sprintf(fname, "data_32x32.txt"); break;
6155
    case BLOCK_16X16: sprintf(fname, "data_16x16.txt"); break;
6156
    case BLOCK_8X8: sprintf(fname, "data_8x8.txt"); break;
6157
    default: assert(0 && "Unexpected block size."); return -1;
6158
  }
6159
6160
  float features[6];  // DC_Q, VAR, VAR_RATIO-0..3
6161
6162
  FILE *f = fopen(fname, "a");
6163
6164
  {
6165
    const int dc_q = av1_dc_quant_QTX(cm->quant_params.base_qindex, 0,
6166
                                      cm->seq_params->bit_depth);
6167
    int feature_idx = 0;
6168
6169
    features[feature_idx++] = log1pf((float)(dc_q * dc_q) / 256.0f);
6170
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, 1, bsize);
6171
    {
6172
      const int bs = block_size_wide[bsize];
6173
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
6174
      const int sb_offset_row = 4 * (mi_row & 15);
6175
      const int sb_offset_col = 4 * (mi_col & 15);
6176
      const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
6177
      const uint8_t *src = x->plane[0].src.buf;
6178
      const int src_stride = x->plane[0].src.stride;
6179
      const int pred_stride = 64;
6180
      unsigned int sse;
6181
      int i;
6182
      // Variance of whole block.
6183
      /*
6184
                if (bs == 8)
6185
                {
6186
                  int r, c;
6187
                  printf("%d %d\n", mi_row, mi_col);
6188
                  for (r = 0; r < bs; ++r) {
6189
                    for (c = 0; c < bs; ++c) {
6190
                      printf("%3d ",
6191
                             src[r * src_stride + c] - pred[64 * r + c]);
6192
                    }
6193
                    printf("\n");
6194
                  }
6195
                  printf("\n");
6196
                }
6197
      */
6198
      const unsigned int var =
6199
          cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
6200
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
6201
6202
      features[feature_idx++] = log1pf((float)var);
6203
6204
      fprintf(f, "%f,%f,", features[0], features[1]);
6205
      for (i = 0; i < 4; ++i) {
6206
        const int x_idx = (i & 1) * bs / 2;
6207
        const int y_idx = (i >> 1) * bs / 2;
6208
        const int src_offset = y_idx * src_stride + x_idx;
6209
        const int pred_offset = y_idx * pred_stride + x_idx;
6210
        // Variance of quarter block.
6211
        const unsigned int sub_var =
6212
            cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
6213
                                    pred + pred_offset, pred_stride, &sse);
6214
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
6215
        features[feature_idx++] = var_ratio;
6216
        fprintf(f, "%f,", var_ratio);
6217
      }
6218
6219
      fprintf(f, "%d\n", part == PARTITION_NONE ? 0 : 1);
6220
    }
6221
6222
    fclose(f);
6223
    return -1;
6224
  }
6225
}
6226
#endif
6227
6228
static void duplicate_mode_info_in_sb(AV1_COMMON *cm, MACROBLOCKD *xd,
6229
                                      int mi_row, int mi_col,
6230
                                      BLOCK_SIZE bsize) {
6231
  const int block_width =
6232
      AOMMIN(mi_size_wide[bsize], cm->mi_params.mi_cols - mi_col);
6233
  const int block_height =
6234
      AOMMIN(mi_size_high[bsize], cm->mi_params.mi_rows - mi_row);
6235
  const int mi_stride = xd->mi_stride;
6236
  MB_MODE_INFO *const src_mi = xd->mi[0];
6237
  int i, j;
6238
6239
  for (j = 0; j < block_height; ++j)
6240
    for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
6241
}
6242
6243
static inline void copy_mbmi_ext_frame_to_mbmi_ext(
6244
    MB_MODE_INFO_EXT *const mbmi_ext,
6245
    const MB_MODE_INFO_EXT_FRAME *mbmi_ext_best, uint8_t ref_frame_type) {
6246
  memcpy(mbmi_ext->ref_mv_stack[ref_frame_type], mbmi_ext_best->ref_mv_stack,
6247
         sizeof(mbmi_ext->ref_mv_stack[USABLE_REF_MV_STACK_SIZE]));
6248
  memcpy(mbmi_ext->weight[ref_frame_type], mbmi_ext_best->weight,
6249
         sizeof(mbmi_ext->weight[USABLE_REF_MV_STACK_SIZE]));
6250
  mbmi_ext->mode_context[ref_frame_type] = mbmi_ext_best->mode_context;
6251
  mbmi_ext->ref_mv_count[ref_frame_type] = mbmi_ext_best->ref_mv_count;
6252
  memcpy(mbmi_ext->global_mvs, mbmi_ext_best->global_mvs,
6253
         sizeof(mbmi_ext->global_mvs));
6254
}
6255
6256
static void fill_mode_info_sb(AV1_COMP *cpi, MACROBLOCK *x, int mi_row,
6257
                              int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
6258
  AV1_COMMON *const cm = &cpi->common;
6259
  MACROBLOCKD *xd = &x->e_mbd;
6260
  int hbs = mi_size_wide[bsize] >> 1;
6261
  PARTITION_TYPE partition = pc_tree->partitioning;
6262
  BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
6263
6264
  assert(bsize >= BLOCK_8X8);
6265
6266
  if (mi_row >= cm->mi_params.mi_rows || mi_col >= cm->mi_params.mi_cols)
6267
    return;
6268
6269
  switch (partition) {
6270
    case PARTITION_NONE:
6271
      set_mode_info_offsets(&cm->mi_params, &cpi->mbmi_ext_info, x, xd, mi_row,
6272
                            mi_col);
6273
      *(xd->mi[0]) = pc_tree->none->mic;
6274
      copy_mbmi_ext_frame_to_mbmi_ext(
6275
          &x->mbmi_ext, &pc_tree->none->mbmi_ext_best, LAST_FRAME);
6276
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
6277
      break;
6278
    case PARTITION_SPLIT: {
6279
      fill_mode_info_sb(cpi, x, mi_row, mi_col, subsize, pc_tree->split[0]);
6280
      fill_mode_info_sb(cpi, x, mi_row, mi_col + hbs, subsize,
6281
                        pc_tree->split[1]);
6282
      fill_mode_info_sb(cpi, x, mi_row + hbs, mi_col, subsize,
6283
                        pc_tree->split[2]);
6284
      fill_mode_info_sb(cpi, x, mi_row + hbs, mi_col + hbs, subsize,
6285
                        pc_tree->split[3]);
6286
      break;
6287
    }
6288
    default: break;
6289
  }
6290
}
6291
6292
void av1_nonrd_pick_partition(AV1_COMP *cpi, ThreadData *td,
6293
                              TileDataEnc *tile_data, TokenExtra **tp,
6294
                              int mi_row, int mi_col, BLOCK_SIZE bsize,
6295
                              RD_STATS *rd_cost, int do_recon, int64_t best_rd,
6296
                              PC_TREE *pc_tree) {
6297
  AV1_COMMON *const cm = &cpi->common;
6298
  TileInfo *const tile_info = &tile_data->tile_info;
6299
  MACROBLOCK *const x = &td->mb;
6300
  MACROBLOCKD *const xd = &x->e_mbd;
6301
  const int hbs = mi_size_wide[bsize] >> 1;
6302
  TokenExtra *tp_orig = *tp;
6303
  const ModeCosts *mode_costs = &x->mode_costs;
6304
  RD_STATS this_rdc, best_rdc;
6305
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
6306
  int do_split = bsize > BLOCK_8X8;
6307
  // Override skipping rectangular partition operations for edge blocks
6308
  const int force_horz_split = (mi_row + 2 * hbs > cm->mi_params.mi_rows);
6309
  const int force_vert_split = (mi_col + 2 * hbs > cm->mi_params.mi_cols);
6310
6311
  int partition_none_allowed = !force_horz_split && !force_vert_split;
6312
6313
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);  // Square partition only
6314
  assert(cm->seq_params->sb_size == BLOCK_64X64);      // Small SB so far
6315
6316
  (void)*tp_orig;
6317
6318
  av1_invalid_rd_stats(&best_rdc);
6319
  best_rdc.rdcost = best_rd;
6320
#ifndef _COLLECT_GROUND_TRUTH_
6321
  if (partition_none_allowed && do_split) {
6322
    const int ml_predicted_partition =
6323
        ml_predict_var_partitioning(cpi, x, bsize, mi_row, mi_col);
6324
    if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
6325
    if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
6326
  }
6327
#endif
6328
6329
  xd->above_txfm_context =
6330
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
6331
  xd->left_txfm_context =
6332
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
6333
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, 3);
6334
6335
  // PARTITION_NONE
6336
  if (partition_none_allowed) {
6337
    pc_tree->none = av1_alloc_pmc(cpi, bsize, &td->shared_coeff_buf);
6338
    if (!pc_tree->none)
6339
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
6340
                         "Failed to allocate PICK_MODE_CONTEXT");
6341
    PICK_MODE_CONTEXT *ctx = pc_tree->none;
6342
6343
// Flip for RDO based pick mode
6344
#if 0
6345
    RD_STATS dummy;
6346
    av1_invalid_rd_stats(&dummy);
6347
    pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc,
6348
                  PARTITION_NONE, bsize, ctx, dummy);
6349
#else
6350
    pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
6351
                        ctx);
6352
#endif
6353
    if (this_rdc.rate != INT_MAX) {
6354
      const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
6355
6356
      this_rdc.rate += mode_costs->partition_cost[pl][PARTITION_NONE];
6357
      this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
6358
      if (this_rdc.rdcost < best_rdc.rdcost) {
6359
        best_rdc = this_rdc;
6360
        if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
6361
      }
6362
    }
6363
  }
6364
6365
  // PARTITION_SPLIT
6366
  if (do_split) {
6367
    RD_STATS sum_rdc;
6368
    const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
6369
6370
    av1_init_rd_stats(&sum_rdc);
6371
6372
    for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
6373
      pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
6374
      if (!pc_tree->split[i])
6375
        aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
6376
                           "Failed to allocate PC_TREE");
6377
      pc_tree->split[i]->index = i;
6378
    }
6379
6380
    int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
6381
    sum_rdc.rate += mode_costs->partition_cost[pl][PARTITION_SPLIT];
6382
    sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, sum_rdc.dist);
6383
    for (int i = 0;
6384
         i < SUB_PARTITIONS_SPLIT && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
6385
      const int x_idx = (i & 1) * hbs;
6386
      const int y_idx = (i >> 1) * hbs;
6387
6388
      if (mi_row + y_idx >= cm->mi_params.mi_rows ||
6389
          mi_col + x_idx >= cm->mi_params.mi_cols)
6390
        continue;
6391
      av1_nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
6392
                               mi_col + x_idx, subsize, &this_rdc, i < 3,
6393
                               best_rdc.rdcost - sum_rdc.rdcost,
6394
                               pc_tree->split[i]);
6395
6396
      if (this_rdc.rate == INT_MAX) {
6397
        av1_invalid_rd_stats(&sum_rdc);
6398
      } else {
6399
        sum_rdc.rate += this_rdc.rate;
6400
        sum_rdc.dist += this_rdc.dist;
6401
        sum_rdc.rdcost += this_rdc.rdcost;
6402
      }
6403
    }
6404
    if (sum_rdc.rdcost < best_rdc.rdcost) {
6405
      best_rdc = sum_rdc;
6406
      pc_tree->partitioning = PARTITION_SPLIT;
6407
    }
6408
  }
6409
6410
#ifdef _COLLECT_GROUND_TRUTH_
6411
  store_partition_data(cpi, x, bsize, mi_row, mi_col, pc_tree->partitioning);
6412
#endif
6413
6414
  *rd_cost = best_rdc;
6415
6416
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, 3);
6417
6418
  if (best_rdc.rate == INT_MAX) {
6419
    av1_invalid_rd_stats(rd_cost);
6420
    return;
6421
  }
6422
6423
  // update mode info array
6424
  fill_mode_info_sb(cpi, x, mi_row, mi_col, bsize, pc_tree);
6425
6426
  if (do_recon) {
6427
    if (bsize == cm->seq_params->sb_size) {
6428
      // NOTE: To get estimate for rate due to the tokens, use:
6429
      // int rate_coeffs = 0;
6430
      // encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_COSTCOEFFS,
6431
      //           bsize, pc_tree, &rate_coeffs);
6432
      set_cb_offsets(x->cb_offset, 0, 0);
6433
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
6434
                pc_tree, NULL);
6435
    } else {
6436
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_NORMAL, bsize,
6437
                pc_tree, NULL);
6438
    }
6439
  }
6440
6441
  if (bsize == BLOCK_64X64 && do_recon) {
6442
    assert(best_rdc.rate < INT_MAX);
6443
    assert(best_rdc.dist < INT64_MAX);
6444
  } else {
6445
    assert(tp_orig == *tp);
6446
  }
6447
}
6448
#endif  // CONFIG_RT_ML_PARTITIONING