Coverage Report

Created: 2026-06-16 07:20

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