Coverage Report

Created: 2026-10-28 07:26

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