Coverage Report

Created: 2025-06-22 08:04

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