Coverage Report

Created: 2026-05-24 07:45

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
0
  }
2928
0
}
2929
2930
/*!\brief AV1 block partition application (minimal RD search).
2931
*
2932
* \ingroup partition_search
2933
* \callgraph
2934
* \callergraph
2935
* Encode the block by applying pre-calculated partition patterns that are
2936
* represented by coding block sizes stored in the mbmi array. The only
2937
* partition adjustment allowed is merging leaf split nodes if it leads to a
2938
* lower rd cost. The partition types are limited to a basic set: none, horz,
2939
* vert, and split. This function is only used in the real-time mode.
2940
*
2941
* \param[in]    cpi       Top-level encoder structure
2942
* \param[in]    td        Pointer to thread data
2943
* \param[in]    tile_data Pointer to struct holding adaptive
2944
data/contexts/models for the tile during encoding
2945
* \param[in]    mib       Array representing MB_MODE_INFO pointers for mi
2946
blocks starting from the first pixel of the current
2947
block
2948
* \param[in]    tp        Pointer to the starting token
2949
* \param[in]    mi_row    Row coordinate of the block in a step size of MI_SIZE
2950
* \param[in]    mi_col    Column coordinate of the block in a step size of
2951
MI_SIZE
2952
* \param[in]    bsize     Current block size
2953
* \param[in]    pc_tree   Pointer to the PC_TREE node holding the picked
2954
partitions and mode info for the current block
2955
*
2956
* \remark Nothing is returned. The pc_tree struct is modified to store the
2957
* picked partition and modes.
2958
*/
2959
void av1_nonrd_use_partition(AV1_COMP *cpi, ThreadData *td,
2960
                             TileDataEnc *tile_data, MB_MODE_INFO **mib,
2961
                             TokenExtra **tp, int mi_row, int mi_col,
2962
0
                             BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2963
0
  AV1_COMMON *const cm = &cpi->common;
2964
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
2965
0
  TileInfo *const tile_info = &tile_data->tile_info;
2966
0
  MACROBLOCK *const x = &td->mb;
2967
0
  MACROBLOCKD *const xd = &x->e_mbd;
2968
0
  const ModeCosts *mode_costs = &x->mode_costs;
2969
  // Only square blocks from 8x8 to 128x128 are supported
2970
0
  assert(bsize >= BLOCK_8X8 && bsize <= BLOCK_128X128);
2971
0
  const int bs = mi_size_wide[bsize];
2972
0
  const int hbs = bs / 2;
2973
0
  PARTITION_TYPE partition = (bsize >= BLOCK_8X8)
2974
0
                                 ? get_partition(cm, mi_row, mi_col, bsize)
2975
0
                                 : PARTITION_NONE;
2976
0
  BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
2977
0
  assert(subsize <= BLOCK_LARGEST);
2978
0
  const int pl = (bsize >= BLOCK_8X8)
2979
0
                     ? partition_plane_context(xd, mi_row, mi_col, bsize)
2980
0
                     : 0;
2981
2982
0
  RD_STATS dummy_cost;
2983
0
  av1_invalid_rd_stats(&dummy_cost);
2984
2985
0
  if (mi_row >= mi_params->mi_rows || mi_col >= mi_params->mi_cols) return;
2986
2987
0
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);
2988
2989
0
  xd->above_txfm_context =
2990
0
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
2991
0
  xd->left_txfm_context =
2992
0
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
2993
2994
  // Initialize default mode evaluation params
2995
0
  set_mode_eval_params(cpi, x, DEFAULT_EVAL);
2996
2997
0
  x->reuse_inter_pred = cpi->sf.rt_sf.reuse_inter_pred_nonrd;
2998
2999
0
  int change_none_to_split = 0;
3000
0
  if (partition == PARTITION_NONE &&
3001
0
      cpi->sf.rt_sf.nonrd_check_partition_split == 1) {
3002
0
    change_none_to_split =
3003
0
        try_split_partition(cpi, td, tile_data, tile_info, tp, x, xd, mi_params,
3004
0
                            mi_row, mi_col, bsize, pl, pc_tree);
3005
0
    if (change_none_to_split) {
3006
0
      partition = PARTITION_SPLIT;
3007
0
      subsize = get_partition_subsize(bsize, partition);
3008
0
      assert(subsize <= BLOCK_LARGEST);
3009
0
    }
3010
0
  }
3011
3012
0
  pc_tree->partitioning = partition;
3013
3014
0
  switch (partition) {
3015
0
    case PARTITION_NONE:
3016
0
      if (!pc_tree->none) {
3017
0
        pc_tree->none = av1_alloc_pmc(cpi, bsize, &td->shared_coeff_buf);
3018
0
        if (!pc_tree->none)
3019
0
          aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3020
0
                             "Failed to allocate PICK_MODE_CONTEXT");
3021
0
      } else {
3022
0
        av1_reset_pmc(pc_tree->none);
3023
0
      }
3024
0
      pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &dummy_cost, bsize,
3025
0
                          pc_tree->none);
3026
0
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col, 0, bsize,
3027
0
                     partition, pc_tree->none, NULL);
3028
0
      break;
3029
0
    case PARTITION_VERT:
3030
0
      for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
3031
0
        if (!pc_tree->vertical[i]) {
3032
0
          pc_tree->vertical[i] =
3033
0
              av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
3034
0
          if (!pc_tree->vertical[i])
3035
0
            aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3036
0
                               "Failed to allocate PICK_MODE_CONTEXT");
3037
0
        } else {
3038
0
          av1_reset_pmc(pc_tree->vertical[i]);
3039
0
        }
3040
0
      }
3041
0
      pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &dummy_cost,
3042
0
                          subsize, pc_tree->vertical[0]);
3043
0
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col, 0, subsize,
3044
0
                     PARTITION_VERT, pc_tree->vertical[0], NULL);
3045
0
      if (mi_col + hbs < mi_params->mi_cols && bsize > BLOCK_8X8) {
3046
0
        pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col + hbs,
3047
0
                            &dummy_cost, subsize, pc_tree->vertical[1]);
3048
0
        encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col + hbs, 0, subsize,
3049
0
                       PARTITION_VERT, pc_tree->vertical[1], NULL);
3050
0
      }
3051
0
      break;
3052
0
    case PARTITION_HORZ:
3053
0
      for (int i = 0; i < SUB_PARTITIONS_RECT; ++i) {
3054
0
        if (!pc_tree->horizontal[i]) {
3055
0
          pc_tree->horizontal[i] =
3056
0
              av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
3057
0
          if (!pc_tree->horizontal[i])
3058
0
            aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3059
0
                               "Failed to allocate PICK_MODE_CONTEXT");
3060
0
        } else {
3061
0
          av1_reset_pmc(pc_tree->horizontal[i]);
3062
0
        }
3063
0
      }
3064
0
      pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &dummy_cost,
3065
0
                          subsize, pc_tree->horizontal[0]);
3066
0
      encode_b_nonrd(cpi, tile_data, td, tp, mi_row, mi_col, 0, subsize,
3067
0
                     PARTITION_HORZ, pc_tree->horizontal[0], NULL);
3068
3069
0
      if (mi_row + hbs < mi_params->mi_rows && bsize > BLOCK_8X8) {
3070
0
        pick_sb_modes_nonrd(cpi, tile_data, x, mi_row + hbs, mi_col,
3071
0
                            &dummy_cost, subsize, pc_tree->horizontal[1]);
3072
0
        encode_b_nonrd(cpi, tile_data, td, tp, mi_row + hbs, mi_col, 0, subsize,
3073
0
                       PARTITION_HORZ, pc_tree->horizontal[1], NULL);
3074
0
      }
3075
0
      break;
3076
0
    case PARTITION_SPLIT:
3077
0
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
3078
0
        if (!pc_tree->split[i]) {
3079
0
          pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
3080
0
          if (!pc_tree->split[i])
3081
0
            aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
3082
0
                               "Failed to allocate PC_TREE");
3083
0
        }
3084
0
        pc_tree->split[i]->index = i;
3085
0
      }
3086
0
      if (cpi->sf.rt_sf.nonrd_check_partition_merge_mode &&
3087
0
          av1_is_leaf_split_partition(cm, mi_row, mi_col, bsize) &&
3088
0
          !frame_is_intra_only(cm) && bsize <= BLOCK_64X64) {
3089
0
        try_merge(cpi, td, tile_data, mib, tp, mi_row, mi_col, bsize, pc_tree,
3090
0
                  partition, subsize, pl);
3091
0
      } else {
3092
0
        for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
3093
0
          int x_idx = (i & 1) * hbs;
3094
0
          int y_idx = (i >> 1) * hbs;
3095
0
          int jj = i >> 1, ii = i & 0x01;
3096
0
          if ((mi_row + y_idx >= mi_params->mi_rows) ||
3097
0
              (mi_col + x_idx >= mi_params->mi_cols))
3098
0
            continue;
3099
0
          av1_nonrd_use_partition(
3100
0
              cpi, td, tile_data,
3101
0
              mib + jj * hbs * mi_params->mi_stride + ii * hbs, tp,
3102
0
              mi_row + y_idx, mi_col + x_idx, subsize, pc_tree->split[i]);
3103
0
        }
3104
3105
0
        if (!change_none_to_split) {
3106
          // Note: Palette, cfl are not supported.
3107
0
          if (!frame_is_intra_only(cm) && !tile_data->allow_update_cdf &&
3108
0
              cpi->sf.rt_sf.partition_direct_merging &&
3109
0
              mode_costs->partition_cost[pl][PARTITION_NONE] <
3110
0
                  mode_costs->partition_cost[pl][PARTITION_SPLIT] &&
3111
0
              (mi_row + bs <= mi_params->mi_rows) &&
3112
0
              (mi_col + bs <= mi_params->mi_cols)) {
3113
0
            direct_partition_merging(cpi, td, tile_data, mib, mi_row, mi_col,
3114
0
                                     bsize);
3115
0
          }
3116
0
        }
3117
0
      }
3118
0
      break;
3119
0
    case PARTITION_VERT_A:
3120
0
    case PARTITION_VERT_B:
3121
0
    case PARTITION_HORZ_A:
3122
0
    case PARTITION_HORZ_B:
3123
0
    case PARTITION_HORZ_4:
3124
0
    case PARTITION_VERT_4:
3125
0
      assert(0 && "Cannot handle extended partition types");
3126
0
    default: assert(0); break;
3127
0
  }
3128
0
}
3129
3130
#if !CONFIG_REALTIME_ONLY
3131
// Try searching for an encoding for the given subblock. Returns zero if the
3132
// rdcost is already too high (to tell the caller not to bother searching for
3133
// encodings of further subblocks).
3134
static int rd_try_subblock(AV1_COMP *const cpi, ThreadData *td,
3135
                           TileDataEnc *tile_data, TokenExtra **tp, int is_last,
3136
                           int mi_row, int mi_col, BLOCK_SIZE subsize,
3137
                           RD_STATS best_rdcost, RD_STATS *sum_rdc,
3138
                           PARTITION_TYPE partition,
3139
0
                           PICK_MODE_CONTEXT *this_ctx) {
3140
0
  MACROBLOCK *const x = &td->mb;
3141
0
  const int orig_mult = x->rdmult;
3142
0
  setup_block_rdmult(cpi, x, mi_row, mi_col, subsize, NO_AQ, NULL);
3143
3144
0
  av1_rd_cost_update(x->rdmult, &best_rdcost);
3145
3146
0
  RD_STATS rdcost_remaining;
3147
0
  av1_rd_stats_subtraction(x->rdmult, &best_rdcost, sum_rdc, &rdcost_remaining);
3148
0
  RD_STATS this_rdc;
3149
0
  pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, partition,
3150
0
                subsize, this_ctx, rdcost_remaining);
3151
3152
0
  if (this_rdc.rate == INT_MAX) {
3153
0
    sum_rdc->rdcost = INT64_MAX;
3154
0
  } else {
3155
0
    sum_rdc->rate += this_rdc.rate;
3156
0
    sum_rdc->dist += this_rdc.dist;
3157
0
    av1_rd_cost_update(x->rdmult, sum_rdc);
3158
0
  }
3159
3160
0
  if (sum_rdc->rdcost >= best_rdcost.rdcost) {
3161
0
    x->rdmult = orig_mult;
3162
0
    return 0;
3163
0
  }
3164
3165
0
  if (!is_last) {
3166
0
    av1_update_state(cpi, td, this_ctx, mi_row, mi_col, subsize, 1);
3167
0
    encode_superblock(cpi, tile_data, td, tp, DRY_RUN_NORMAL, subsize, NULL);
3168
0
  }
3169
3170
0
  x->rdmult = orig_mult;
3171
0
  return 1;
3172
0
}
3173
3174
// Tests an AB partition, and updates the encoder status, the pick mode
3175
// contexts, the best rdcost, and the best partition.
3176
static bool rd_test_partition3(AV1_COMP *const cpi, ThreadData *td,
3177
                               TileDataEnc *tile_data, TokenExtra **tp,
3178
                               PC_TREE *pc_tree, RD_STATS *best_rdc,
3179
                               int64_t *this_rdcost,
3180
                               PICK_MODE_CONTEXT *ctxs[SUB_PARTITIONS_AB],
3181
                               int mi_row, int mi_col, BLOCK_SIZE bsize,
3182
                               PARTITION_TYPE partition,
3183
                               const BLOCK_SIZE ab_subsize[SUB_PARTITIONS_AB],
3184
                               const int ab_mi_pos[SUB_PARTITIONS_AB][2],
3185
0
                               const MB_MODE_INFO **mode_cache) {
3186
0
  MACROBLOCK *const x = &td->mb;
3187
0
  const MACROBLOCKD *const xd = &x->e_mbd;
3188
0
  const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3189
0
  RD_STATS sum_rdc;
3190
0
  av1_init_rd_stats(&sum_rdc);
3191
0
  sum_rdc.rate = x->mode_costs.partition_cost[pl][partition];
3192
0
  sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, 0);
3193
  // Loop over sub-partitions in AB partition type.
3194
0
  for (int i = 0; i < SUB_PARTITIONS_AB; i++) {
3195
0
    if (mode_cache && mode_cache[i]) {
3196
0
      x->use_mb_mode_cache = 1;
3197
0
      x->mb_mode_cache = mode_cache[i];
3198
0
    }
3199
0
    const int mode_search_success =
3200
0
        rd_try_subblock(cpi, td, tile_data, tp, i == SUB_PARTITIONS_AB - 1,
3201
0
                        ab_mi_pos[i][0], ab_mi_pos[i][1], ab_subsize[i],
3202
0
                        *best_rdc, &sum_rdc, partition, ctxs[i]);
3203
0
    x->use_mb_mode_cache = 0;
3204
0
    x->mb_mode_cache = NULL;
3205
0
    if (!mode_search_success) {
3206
0
      return false;
3207
0
    }
3208
0
  }
3209
3210
0
  av1_rd_cost_update(x->rdmult, &sum_rdc);
3211
0
  *this_rdcost = sum_rdc.rdcost;
3212
0
  if (sum_rdc.rdcost >= best_rdc->rdcost) return false;
3213
0
  sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, sum_rdc.dist);
3214
0
  *this_rdcost = sum_rdc.rdcost;
3215
0
  if (sum_rdc.rdcost >= best_rdc->rdcost) return false;
3216
3217
0
  *best_rdc = sum_rdc;
3218
0
  pc_tree->partitioning = partition;
3219
0
  return true;
3220
0
}
3221
3222
#if CONFIG_COLLECT_PARTITION_STATS
3223
static void init_partition_block_timing_stats(
3224
    PartitionTimingStats *part_timing_stats) {
3225
  av1_zero(*part_timing_stats);
3226
}
3227
3228
static inline void start_partition_block_timer(
3229
    PartitionTimingStats *part_timing_stats, PARTITION_TYPE partition_type) {
3230
  assert(!part_timing_stats->timer_is_on);
3231
  part_timing_stats->partition_attempts[partition_type] += 1;
3232
  aom_usec_timer_start(&part_timing_stats->timer);
3233
  part_timing_stats->timer_is_on = 1;
3234
}
3235
3236
static inline void end_partition_block_timer(
3237
    PartitionTimingStats *part_timing_stats, PARTITION_TYPE partition_type,
3238
    int64_t rdcost) {
3239
  if (part_timing_stats->timer_is_on) {
3240
    aom_usec_timer_mark(&part_timing_stats->timer);
3241
    const int64_t time = aom_usec_timer_elapsed(&part_timing_stats->timer);
3242
    part_timing_stats->partition_times[partition_type] += time;
3243
    part_timing_stats->partition_rdcost[partition_type] = rdcost;
3244
    part_timing_stats->timer_is_on = 0;
3245
  }
3246
}
3247
static inline void print_partition_timing_stats_with_rdcost(
3248
    const PartitionTimingStats *part_timing_stats, int mi_row, int mi_col,
3249
    BLOCK_SIZE bsize, FRAME_UPDATE_TYPE frame_update_type, int frame_number,
3250
    const RD_STATS *best_rdc, const char *filename) {
3251
  FILE *f = fopen(filename, "a");
3252
  fprintf(f, "%d,%d,%d,%d,%d,%d,%" PRId64 ",%" PRId64 ",", bsize, frame_number,
3253
          frame_update_type, mi_row, mi_col, best_rdc->rate, best_rdc->dist,
3254
          best_rdc->rdcost);
3255
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3256
    fprintf(f, "%d,", part_timing_stats->partition_decisions[idx]);
3257
  }
3258
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3259
    fprintf(f, "%d,", part_timing_stats->partition_attempts[idx]);
3260
  }
3261
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3262
    fprintf(f, "%" PRId64 ",", part_timing_stats->partition_times[idx]);
3263
  }
3264
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3265
    if (part_timing_stats->partition_rdcost[idx] == INT64_MAX) {
3266
      fprintf(f, "%d,", -1);
3267
    } else {
3268
      fprintf(f, "%" PRId64 ",", part_timing_stats->partition_rdcost[idx]);
3269
    }
3270
  }
3271
  fprintf(f, "\n");
3272
  fclose(f);
3273
}
3274
3275
static inline void print_partition_timing_stats(
3276
    const PartitionTimingStats *part_timing_stats, int intra_only,
3277
    int show_frame, const BLOCK_SIZE bsize, const char *filename) {
3278
  FILE *f = fopen(filename, "a");
3279
  fprintf(f, "%d,%d,%d,", bsize, show_frame, intra_only);
3280
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3281
    fprintf(f, "%d,", part_timing_stats->partition_decisions[idx]);
3282
  }
3283
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3284
    fprintf(f, "%d,", part_timing_stats->partition_attempts[idx]);
3285
  }
3286
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3287
    fprintf(f, "%" PRId64 ",", part_timing_stats->partition_times[idx]);
3288
  }
3289
  fprintf(f, "\n");
3290
  fclose(f);
3291
}
3292
3293
static inline void accumulate_partition_timing_stats(
3294
    FramePartitionTimingStats *fr_part_timing_stats,
3295
    const PartitionTimingStats *part_timing_stats, BLOCK_SIZE bsize) {
3296
  const int bsize_idx = av1_get_bsize_idx_for_part_stats(bsize);
3297
  int *agg_attempts = fr_part_timing_stats->partition_attempts[bsize_idx];
3298
  int *agg_decisions = fr_part_timing_stats->partition_decisions[bsize_idx];
3299
  int64_t *agg_times = fr_part_timing_stats->partition_times[bsize_idx];
3300
  for (int idx = 0; idx < EXT_PARTITION_TYPES; idx++) {
3301
    agg_attempts[idx] += part_timing_stats->partition_attempts[idx];
3302
    agg_decisions[idx] += part_timing_stats->partition_decisions[idx];
3303
    agg_times[idx] += part_timing_stats->partition_times[idx];
3304
  }
3305
}
3306
#endif  // CONFIG_COLLECT_PARTITION_STATS
3307
3308
// Initialize state variables of partition search used in
3309
// av1_rd_pick_partition().
3310
static void init_partition_search_state_params(
3311
    MACROBLOCK *x, AV1_COMP *const cpi, PartitionSearchState *part_search_state,
3312
0
    int mi_row, int mi_col, BLOCK_SIZE bsize) {
3313
0
  MACROBLOCKD *const xd = &x->e_mbd;
3314
0
  const AV1_COMMON *const cm = &cpi->common;
3315
0
  PartitionBlkParams *blk_params = &part_search_state->part_blk_params;
3316
0
  const CommonModeInfoParams *const mi_params = &cpi->common.mi_params;
3317
3318
  // Initialization of block size related parameters.
3319
0
  blk_params->mi_step = mi_size_wide[bsize] / 2;
3320
0
  blk_params->mi_row = mi_row;
3321
0
  blk_params->mi_col = mi_col;
3322
0
  blk_params->mi_row_edge = mi_row + blk_params->mi_step;
3323
0
  blk_params->mi_col_edge = mi_col + blk_params->mi_step;
3324
0
  blk_params->width = block_size_wide[bsize];
3325
0
  blk_params->min_partition_size_1d =
3326
0
      block_size_wide[x->sb_enc.min_partition_size];
3327
0
  blk_params->subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
3328
0
  blk_params->split_bsize2 = blk_params->subsize;
3329
0
  blk_params->bsize_at_least_8x8 = (bsize >= BLOCK_8X8);
3330
0
  blk_params->bsize = bsize;
3331
3332
  // Check if the partition corresponds to edge block.
3333
0
  blk_params->has_rows = (blk_params->mi_row_edge < mi_params->mi_rows);
3334
0
  blk_params->has_cols = (blk_params->mi_col_edge < mi_params->mi_cols);
3335
3336
  // Update intra partitioning related info.
3337
0
  part_search_state->intra_part_info = &x->part_search_info;
3338
  // Prepare for segmentation CNN-based partitioning for intra-frame.
3339
0
  if (frame_is_intra_only(cm) && bsize == BLOCK_64X64) {
3340
0
    part_search_state->intra_part_info->quad_tree_idx = 0;
3341
0
    part_search_state->intra_part_info->cnn_output_valid = 0;
3342
0
  }
3343
3344
  // Set partition plane context index.
3345
0
  part_search_state->pl_ctx_idx =
3346
0
      blk_params->bsize_at_least_8x8
3347
0
          ? partition_plane_context(xd, mi_row, mi_col, bsize)
3348
0
          : 0;
3349
3350
  // Partition cost buffer update
3351
0
  ModeCosts *mode_costs = &x->mode_costs;
3352
0
  part_search_state->partition_cost =
3353
0
      mode_costs->partition_cost[part_search_state->pl_ctx_idx];
3354
3355
  // Initialize HORZ and VERT win flags as true for all split partitions.
3356
0
  for (int i = 0; i < SUB_PARTITIONS_SPLIT; i++) {
3357
0
    part_search_state->split_part_rect_win[i].rect_part_win[HORZ] = true;
3358
0
    part_search_state->split_part_rect_win[i].rect_part_win[VERT] = true;
3359
0
  }
3360
3361
  // Initialize the rd cost.
3362
0
  av1_init_rd_stats(&part_search_state->this_rdc);
3363
3364
  // Initialize RD costs for partition types to 0.
3365
0
  part_search_state->none_rd = 0;
3366
0
  av1_zero(part_search_state->split_rd);
3367
0
  av1_zero(part_search_state->rect_part_rd);
3368
3369
  // Initialize SPLIT partition to be not ready.
3370
0
  av1_zero(part_search_state->is_split_ctx_is_ready);
3371
  // Initialize HORZ and VERT partitions to be not ready.
3372
0
  av1_zero(part_search_state->is_rect_ctx_is_ready);
3373
3374
  // Chroma subsampling.
3375
0
  part_search_state->ss_x = x->e_mbd.plane[1].subsampling_x;
3376
0
  part_search_state->ss_y = x->e_mbd.plane[1].subsampling_y;
3377
3378
  // Initialize partition search flags to defaults.
3379
0
  part_search_state->terminate_partition_search = 0;
3380
0
  part_search_state->do_square_split = blk_params->bsize_at_least_8x8;
3381
0
  part_search_state->do_rectangular_split =
3382
0
      cpi->oxcf.part_cfg.enable_rect_partitions &&
3383
0
      blk_params->bsize_at_least_8x8;
3384
0
  av1_zero(part_search_state->prune_rect_part);
3385
3386
  // Initialize allowed partition types for the partition block.
3387
0
  part_search_state->partition_none_allowed =
3388
0
      av1_blk_has_rows_and_cols(blk_params);
3389
0
  part_search_state->partition_rect_allowed[HORZ] =
3390
0
      part_search_state->do_rectangular_split && blk_params->has_cols &&
3391
0
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_HORZ),
3392
0
                           part_search_state->ss_x,
3393
0
                           part_search_state->ss_y) != BLOCK_INVALID;
3394
0
  part_search_state->partition_rect_allowed[VERT] =
3395
0
      part_search_state->do_rectangular_split && blk_params->has_rows &&
3396
0
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_VERT),
3397
0
                           part_search_state->ss_x,
3398
0
                           part_search_state->ss_y) != BLOCK_INVALID;
3399
3400
  // Reset the flag indicating whether a partition leading to a rdcost lower
3401
  // than the bound best_rdc has been found.
3402
0
  part_search_state->found_best_partition = false;
3403
3404
#if CONFIG_COLLECT_PARTITION_STATS
3405
  init_partition_block_timing_stats(&part_search_state->part_timing_stats);
3406
#endif  // CONFIG_COLLECT_PARTITION_STATS
3407
0
}
3408
3409
// Override partition cost buffer for the edge blocks.
3410
static void set_partition_cost_for_edge_blk(
3411
0
    AV1_COMMON const *cm, PartitionSearchState *part_search_state) {
3412
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3413
0
  assert(blk_params.bsize_at_least_8x8 && part_search_state->pl_ctx_idx >= 0);
3414
0
  const aom_cdf_prob *partition_cdf =
3415
0
      cm->fc->partition_cdf[part_search_state->pl_ctx_idx];
3416
0
  const int max_cost = av1_cost_symbol(0);
3417
0
  for (PARTITION_TYPE i = 0; i < PARTITION_TYPES; ++i)
3418
0
    part_search_state->tmp_partition_cost[i] = max_cost;
3419
0
  if (blk_params.has_cols) {
3420
    // At the bottom, the two possibilities are HORZ and SPLIT.
3421
0
    aom_cdf_prob bot_cdf[2];
3422
0
    partition_gather_vert_alike(bot_cdf, partition_cdf, blk_params.bsize);
3423
0
    static const int bot_inv_map[2] = { PARTITION_HORZ, PARTITION_SPLIT };
3424
0
    av1_cost_tokens_from_cdf(part_search_state->tmp_partition_cost, bot_cdf,
3425
0
                             bot_inv_map);
3426
0
  } else if (blk_params.has_rows) {
3427
    // At the right, the two possibilities are VERT and SPLIT.
3428
0
    aom_cdf_prob rhs_cdf[2];
3429
0
    partition_gather_horz_alike(rhs_cdf, partition_cdf, blk_params.bsize);
3430
0
    static const int rhs_inv_map[2] = { PARTITION_VERT, PARTITION_SPLIT };
3431
0
    av1_cost_tokens_from_cdf(part_search_state->tmp_partition_cost, rhs_cdf,
3432
0
                             rhs_inv_map);
3433
0
  } else {
3434
    // At the bottom right, we always split.
3435
0
    part_search_state->tmp_partition_cost[PARTITION_SPLIT] = 0;
3436
0
  }
3437
  // Override the partition cost buffer.
3438
0
  part_search_state->partition_cost = part_search_state->tmp_partition_cost;
3439
0
}
3440
3441
// Reset the partition search state flags when
3442
// must_find_valid_partition is equal to 1.
3443
static inline void reset_part_limitations(
3444
0
    AV1_COMP *const cpi, PartitionSearchState *part_search_state) {
3445
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3446
0
  const int is_rect_part_allowed =
3447
0
      blk_params.bsize_at_least_8x8 &&
3448
0
      cpi->oxcf.part_cfg.enable_rect_partitions &&
3449
0
      (blk_params.width > blk_params.min_partition_size_1d);
3450
0
  part_search_state->do_square_split =
3451
0
      blk_params.bsize_at_least_8x8 &&
3452
0
      (blk_params.width > blk_params.min_partition_size_1d);
3453
0
  part_search_state->partition_none_allowed =
3454
0
      av1_blk_has_rows_and_cols(&blk_params) &&
3455
0
      (blk_params.width >= blk_params.min_partition_size_1d);
3456
0
  part_search_state->partition_rect_allowed[HORZ] =
3457
0
      blk_params.has_cols && is_rect_part_allowed &&
3458
0
      get_plane_block_size(
3459
0
          get_partition_subsize(blk_params.bsize, PARTITION_HORZ),
3460
0
          part_search_state->ss_x, part_search_state->ss_y) != BLOCK_INVALID;
3461
0
  part_search_state->partition_rect_allowed[VERT] =
3462
0
      blk_params.has_rows && is_rect_part_allowed &&
3463
0
      get_plane_block_size(
3464
0
          get_partition_subsize(blk_params.bsize, PARTITION_VERT),
3465
0
          part_search_state->ss_x, part_search_state->ss_y) != BLOCK_INVALID;
3466
0
  part_search_state->terminate_partition_search = 0;
3467
0
}
3468
3469
// Rectangular partitions evaluation at sub-block level.
3470
static void rd_pick_rect_partition(AV1_COMP *const cpi, TileDataEnc *tile_data,
3471
                                   MACROBLOCK *x,
3472
                                   PICK_MODE_CONTEXT *cur_partition_ctx,
3473
                                   PartitionSearchState *part_search_state,
3474
                                   RD_STATS *best_rdc, const int idx,
3475
                                   int mi_row, int mi_col, BLOCK_SIZE bsize,
3476
0
                                   PARTITION_TYPE partition_type) {
3477
  // Obtain the remainder from the best rd cost
3478
  // for further processing of partition.
3479
0
  RD_STATS best_remain_rdcost;
3480
0
  av1_rd_stats_subtraction(x->rdmult, best_rdc, &part_search_state->sum_rdc,
3481
0
                           &best_remain_rdcost);
3482
3483
  // Obtain the best mode for the partition sub-block.
3484
0
  pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &part_search_state->this_rdc,
3485
0
                partition_type, bsize, cur_partition_ctx, best_remain_rdcost);
3486
0
  av1_rd_cost_update(x->rdmult, &part_search_state->this_rdc);
3487
3488
  // Update the partition rd cost with the current sub-block rd.
3489
0
  if (part_search_state->this_rdc.rate == INT_MAX) {
3490
0
    part_search_state->sum_rdc.rdcost = INT64_MAX;
3491
0
  } else {
3492
0
    part_search_state->sum_rdc.rate += part_search_state->this_rdc.rate;
3493
0
    part_search_state->sum_rdc.dist += part_search_state->this_rdc.dist;
3494
0
    av1_rd_cost_update(x->rdmult, &part_search_state->sum_rdc);
3495
0
  }
3496
0
  const RECT_PART_TYPE rect_part =
3497
0
      partition_type == PARTITION_HORZ ? HORZ : VERT;
3498
0
  part_search_state->rect_part_rd[rect_part][idx] =
3499
0
      part_search_state->this_rdc.rdcost;
3500
0
}
3501
3502
typedef int (*active_edge_info)(const AV1_COMP *cpi, int mi_col, int mi_step);
3503
3504
// Checks if HORZ / VERT partition search is allowed.
3505
static inline int is_rect_part_allowed(
3506
    const AV1_COMP *cpi, const PartitionSearchState *part_search_state,
3507
    const active_edge_info *active_edge, RECT_PART_TYPE rect_part,
3508
0
    const int mi_pos) {
3509
0
  const PartitionBlkParams *blk_params = &part_search_state->part_blk_params;
3510
0
  const int is_part_allowed =
3511
0
      (!part_search_state->terminate_partition_search &&
3512
0
       part_search_state->partition_rect_allowed[rect_part] &&
3513
0
       !part_search_state->prune_rect_part[rect_part] &&
3514
0
       (part_search_state->do_rectangular_split ||
3515
0
        active_edge[rect_part](cpi, mi_pos, blk_params->mi_step)));
3516
0
  return is_part_allowed;
3517
0
}
3518
3519
static void rectangular_partition_search(
3520
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3521
    TokenExtra **tp, MACROBLOCK *x, PC_TREE *pc_tree,
3522
    RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3523
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
3524
    RD_RECT_PART_WIN_INFO *rect_part_win_info, const RECT_PART_TYPE start_type,
3525
0
    const RECT_PART_TYPE end_type) {
3526
0
  const AV1_COMMON *const cm = &cpi->common;
3527
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3528
0
  RD_STATS *sum_rdc = &part_search_state->sum_rdc;
3529
0
  const int rect_partition_type[NUM_RECT_PARTS] = { PARTITION_HORZ,
3530
0
                                                    PARTITION_VERT };
3531
3532
  // mi_pos_rect[NUM_RECT_PARTS][SUB_PARTITIONS_RECT][0]: mi_row postion of
3533
  //                                           HORZ and VERT partition types.
3534
  // mi_pos_rect[NUM_RECT_PARTS][SUB_PARTITIONS_RECT][1]: mi_col postion of
3535
  //                                           HORZ and VERT partition types.
3536
0
  const int mi_pos_rect[NUM_RECT_PARTS][SUB_PARTITIONS_RECT][2] = {
3537
0
    { { blk_params.mi_row, blk_params.mi_col },
3538
0
      { blk_params.mi_row_edge, blk_params.mi_col } },
3539
0
    { { blk_params.mi_row, blk_params.mi_col },
3540
0
      { blk_params.mi_row, blk_params.mi_col_edge } }
3541
0
  };
3542
3543
  // Initialize active edge_type function pointer
3544
  // for HOZR and VERT partition types.
3545
0
  active_edge_info active_edge_type[NUM_RECT_PARTS] = { av1_active_h_edge,
3546
0
                                                        av1_active_v_edge };
3547
3548
  // Indicates edge blocks for HORZ and VERT partition types.
3549
0
  const int is_not_edge_block[NUM_RECT_PARTS] = { blk_params.has_rows,
3550
0
                                                  blk_params.has_cols };
3551
3552
  // Initialize pc tree context for HORZ and VERT partition types.
3553
0
  PICK_MODE_CONTEXT **cur_ctx[NUM_RECT_PARTS][SUB_PARTITIONS_RECT] = {
3554
0
    { &pc_tree->horizontal[0], &pc_tree->horizontal[1] },
3555
0
    { &pc_tree->vertical[0], &pc_tree->vertical[1] }
3556
0
  };
3557
3558
  // Loop over rectangular partition types.
3559
0
  for (RECT_PART_TYPE i = start_type; i <= end_type; i++) {
3560
0
    assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
3561
0
                   !part_search_state->partition_rect_allowed[i]));
3562
3563
    // Check if the HORZ / VERT partition search is to be performed.
3564
0
    if (!is_rect_part_allowed(cpi, part_search_state, active_edge_type, i,
3565
0
                              mi_pos_rect[i][0][i]))
3566
0
      continue;
3567
3568
    // Sub-partition idx.
3569
0
    int sub_part_idx = 0;
3570
0
    PARTITION_TYPE partition_type = rect_partition_type[i];
3571
0
    blk_params.subsize =
3572
0
        get_partition_subsize(blk_params.bsize, partition_type);
3573
0
    assert(blk_params.subsize <= BLOCK_LARGEST);
3574
0
    av1_init_rd_stats(sum_rdc);
3575
0
    for (int j = 0; j < SUB_PARTITIONS_RECT; j++) {
3576
0
      if (cur_ctx[i][j][0] == NULL) {
3577
0
        cur_ctx[i][j][0] =
3578
0
            av1_alloc_pmc(cpi, blk_params.subsize, &td->shared_coeff_buf);
3579
0
        if (!cur_ctx[i][j][0])
3580
0
          aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
3581
0
                             "Failed to allocate PICK_MODE_CONTEXT");
3582
0
      }
3583
0
    }
3584
0
    sum_rdc->rate = part_search_state->partition_cost[partition_type];
3585
0
    sum_rdc->rdcost = RDCOST(x->rdmult, sum_rdc->rate, 0);
3586
#if CONFIG_COLLECT_PARTITION_STATS
3587
    PartitionTimingStats *part_timing_stats =
3588
        &part_search_state->part_timing_stats;
3589
    if (best_rdc->rdcost - sum_rdc->rdcost >= 0) {
3590
      start_partition_block_timer(part_timing_stats, partition_type);
3591
    }
3592
#endif
3593
3594
    // First sub-partition evaluation in HORZ / VERT partition type.
3595
0
    rd_pick_rect_partition(
3596
0
        cpi, tile_data, x, cur_ctx[i][sub_part_idx][0], part_search_state,
3597
0
        best_rdc, 0, mi_pos_rect[i][sub_part_idx][0],
3598
0
        mi_pos_rect[i][sub_part_idx][1], blk_params.subsize, partition_type);
3599
3600
    // Start of second sub-partition evaluation.
3601
    // Evaluate second sub-partition if the first sub-partition cost
3602
    // is less than the best cost and if it is not an edge block.
3603
0
    if (sum_rdc->rdcost < best_rdc->rdcost && is_not_edge_block[i]) {
3604
0
      const MB_MODE_INFO *const mbmi = &cur_ctx[i][sub_part_idx][0]->mic;
3605
0
      const PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
3606
      // Neither palette mode nor cfl predicted.
3607
0
      if (pmi->palette_size[PLANE_TYPE_Y] == 0 &&
3608
0
          pmi->palette_size[PLANE_TYPE_UV] == 0) {
3609
0
        if (mbmi->uv_mode != UV_CFL_PRED)
3610
0
          part_search_state->is_rect_ctx_is_ready[i] = 1;
3611
0
      }
3612
0
      av1_update_state(cpi, td, cur_ctx[i][sub_part_idx][0], blk_params.mi_row,
3613
0
                       blk_params.mi_col, blk_params.subsize, DRY_RUN_NORMAL);
3614
0
      encode_superblock(cpi, tile_data, td, tp, DRY_RUN_NORMAL,
3615
0
                        blk_params.subsize, NULL);
3616
3617
      // Second sub-partition evaluation in HORZ / VERT partition type.
3618
0
      sub_part_idx = 1;
3619
0
      rd_pick_rect_partition(
3620
0
          cpi, tile_data, x, cur_ctx[i][sub_part_idx][0], part_search_state,
3621
0
          best_rdc, 1, mi_pos_rect[i][sub_part_idx][0],
3622
0
          mi_pos_rect[i][sub_part_idx][1], blk_params.subsize, partition_type);
3623
0
    }
3624
    // Update HORZ / VERT best partition.
3625
0
    if (sum_rdc->rdcost < best_rdc->rdcost) {
3626
0
      sum_rdc->rdcost = RDCOST(x->rdmult, sum_rdc->rate, sum_rdc->dist);
3627
0
      if (sum_rdc->rdcost < best_rdc->rdcost) {
3628
0
        *best_rdc = *sum_rdc;
3629
0
        part_search_state->found_best_partition = true;
3630
0
        pc_tree->partitioning = partition_type;
3631
0
      }
3632
0
    } else {
3633
      // Update HORZ / VERT win flag.
3634
0
      if (rect_part_win_info != NULL)
3635
0
        rect_part_win_info->rect_part_win[i] = false;
3636
0
    }
3637
#if CONFIG_COLLECT_PARTITION_STATS
3638
    if (part_timing_stats->timer_is_on) {
3639
      end_partition_block_timer(part_timing_stats, partition_type,
3640
                                sum_rdc->rdcost);
3641
    }
3642
#endif
3643
0
    av1_restore_context(x, x_ctx, blk_params.mi_row, blk_params.mi_col,
3644
0
                        blk_params.bsize, av1_num_planes(cm));
3645
0
  }
3646
0
}
3647
3648
// AB partition type evaluation.
3649
static void rd_pick_ab_part(
3650
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3651
    TokenExtra **tp, MACROBLOCK *x, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3652
    PC_TREE *pc_tree, PICK_MODE_CONTEXT *dst_ctxs[SUB_PARTITIONS_AB],
3653
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
3654
    const BLOCK_SIZE ab_subsize[SUB_PARTITIONS_AB],
3655
    const int ab_mi_pos[SUB_PARTITIONS_AB][2], const PARTITION_TYPE part_type,
3656
0
    const MB_MODE_INFO **mode_cache) {
3657
0
  const AV1_COMMON *const cm = &cpi->common;
3658
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3659
0
  const int mi_row = blk_params.mi_row;
3660
0
  const int mi_col = blk_params.mi_col;
3661
0
  const BLOCK_SIZE bsize = blk_params.bsize;
3662
0
  int64_t this_rdcost = 0;
3663
3664
#if CONFIG_COLLECT_PARTITION_STATS
3665
  PartitionTimingStats *part_timing_stats =
3666
      &part_search_state->part_timing_stats;
3667
  {
3668
    RD_STATS tmp_sum_rdc;
3669
    av1_init_rd_stats(&tmp_sum_rdc);
3670
    tmp_sum_rdc.rate = part_search_state->partition_cost[part_type];
3671
    tmp_sum_rdc.rdcost = RDCOST(x->rdmult, tmp_sum_rdc.rate, 0);
3672
    if (best_rdc->rdcost - tmp_sum_rdc.rdcost >= 0) {
3673
      start_partition_block_timer(part_timing_stats, part_type);
3674
    }
3675
  }
3676
#endif
3677
3678
  // Test this partition and update the best partition.
3679
0
  const bool find_best_ab_part = rd_test_partition3(
3680
0
      cpi, td, tile_data, tp, pc_tree, best_rdc, &this_rdcost, dst_ctxs, mi_row,
3681
0
      mi_col, bsize, part_type, ab_subsize, ab_mi_pos, mode_cache);
3682
0
  part_search_state->found_best_partition |= find_best_ab_part;
3683
3684
#if CONFIG_COLLECT_PARTITION_STATS
3685
  if (part_timing_stats->timer_is_on) {
3686
    if (!find_best_ab_part) this_rdcost = INT64_MAX;
3687
    end_partition_block_timer(part_timing_stats, part_type, this_rdcost);
3688
  }
3689
#endif
3690
0
  av1_restore_context(x, x_ctx, mi_row, mi_col, bsize, av1_num_planes(cm));
3691
0
}
3692
3693
// Set mode search context.
3694
static inline void set_mode_search_ctx(
3695
    PC_TREE *pc_tree, const int is_ctx_ready[NUM_AB_PARTS][2],
3696
0
    PICK_MODE_CONTEXT **mode_srch_ctx[NUM_AB_PARTS][2]) {
3697
0
  mode_srch_ctx[HORZ_B][0] = &pc_tree->horizontal[0];
3698
0
  mode_srch_ctx[VERT_B][0] = &pc_tree->vertical[0];
3699
3700
0
  if (is_ctx_ready[HORZ_A][0])
3701
0
    mode_srch_ctx[HORZ_A][0] = &pc_tree->split[0]->none;
3702
3703
0
  if (is_ctx_ready[VERT_A][0])
3704
0
    mode_srch_ctx[VERT_A][0] = &pc_tree->split[0]->none;
3705
3706
0
  if (is_ctx_ready[HORZ_A][1])
3707
0
    mode_srch_ctx[HORZ_A][1] = &pc_tree->split[1]->none;
3708
0
}
3709
3710
static inline void copy_partition_mode_from_mode_context(
3711
0
    const MB_MODE_INFO **dst_mode, const PICK_MODE_CONTEXT *ctx) {
3712
0
  if (ctx && ctx->rd_stats.rate < INT_MAX) {
3713
0
    *dst_mode = &ctx->mic;
3714
0
  } else {
3715
0
    *dst_mode = NULL;
3716
0
  }
3717
0
}
3718
3719
static inline void copy_partition_mode_from_pc_tree(
3720
0
    const MB_MODE_INFO **dst_mode, const PC_TREE *pc_tree) {
3721
0
  if (pc_tree) {
3722
0
    copy_partition_mode_from_mode_context(dst_mode, pc_tree->none);
3723
0
  } else {
3724
0
    *dst_mode = NULL;
3725
0
  }
3726
0
}
3727
3728
static inline void set_mode_cache_for_partition_ab(
3729
    const MB_MODE_INFO **mode_cache, const PC_TREE *pc_tree,
3730
0
    AB_PART_TYPE ab_part_type) {
3731
0
  switch (ab_part_type) {
3732
0
    case HORZ_A:
3733
0
      copy_partition_mode_from_pc_tree(&mode_cache[0], pc_tree->split[0]);
3734
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[1]);
3735
0
      copy_partition_mode_from_mode_context(&mode_cache[2],
3736
0
                                            pc_tree->horizontal[1]);
3737
0
      break;
3738
0
    case HORZ_B:
3739
0
      copy_partition_mode_from_mode_context(&mode_cache[0],
3740
0
                                            pc_tree->horizontal[0]);
3741
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[2]);
3742
0
      copy_partition_mode_from_pc_tree(&mode_cache[2], pc_tree->split[3]);
3743
0
      break;
3744
0
    case VERT_A:
3745
0
      copy_partition_mode_from_pc_tree(&mode_cache[0], pc_tree->split[0]);
3746
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[2]);
3747
0
      copy_partition_mode_from_mode_context(&mode_cache[2],
3748
0
                                            pc_tree->vertical[1]);
3749
0
      break;
3750
0
    case VERT_B:
3751
0
      copy_partition_mode_from_mode_context(&mode_cache[0],
3752
0
                                            pc_tree->vertical[0]);
3753
0
      copy_partition_mode_from_pc_tree(&mode_cache[1], pc_tree->split[1]);
3754
0
      copy_partition_mode_from_pc_tree(&mode_cache[2], pc_tree->split[3]);
3755
0
      break;
3756
0
    default: assert(0 && "Invalid ab partition type!\n");
3757
0
  }
3758
0
}
3759
3760
// AB Partitions type search.
3761
static void ab_partitions_search(
3762
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3763
    TokenExtra **tp, MACROBLOCK *x, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3764
    PC_TREE *pc_tree, PartitionSearchState *part_search_state,
3765
    RD_STATS *best_rdc, RD_RECT_PART_WIN_INFO *rect_part_win_info,
3766
    int pb_source_variance, int ext_partition_allowed,
3767
0
    const AB_PART_TYPE start_type, const AB_PART_TYPE end_type) {
3768
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3769
0
  const int mi_row = blk_params.mi_row;
3770
0
  const int mi_col = blk_params.mi_col;
3771
0
  const BLOCK_SIZE bsize = blk_params.bsize;
3772
3773
0
  if (part_search_state->terminate_partition_search) {
3774
0
    return;
3775
0
  }
3776
3777
0
  int ab_partitions_allowed[NUM_AB_PARTS];
3778
  // Prune AB partitions
3779
0
  av1_prune_ab_partitions(cpi, x, pc_tree, pb_source_variance, best_rdc->rdcost,
3780
0
                          rect_part_win_info, ext_partition_allowed,
3781
0
                          part_search_state, ab_partitions_allowed);
3782
3783
  // Flags to indicate whether the mode search is done.
3784
0
  const int is_ctx_ready[NUM_AB_PARTS][2] = {
3785
0
    { part_search_state->is_split_ctx_is_ready[0],
3786
0
      part_search_state->is_split_ctx_is_ready[1] },
3787
0
    { part_search_state->is_rect_ctx_is_ready[HORZ], 0 },
3788
0
    { part_search_state->is_split_ctx_is_ready[0], 0 },
3789
0
    { part_search_state->is_rect_ctx_is_ready[VERT], 0 }
3790
0
  };
3791
3792
  // Current partition context.
3793
0
  PICK_MODE_CONTEXT **cur_part_ctxs[NUM_AB_PARTS] = { pc_tree->horizontala,
3794
0
                                                      pc_tree->horizontalb,
3795
0
                                                      pc_tree->verticala,
3796
0
                                                      pc_tree->verticalb };
3797
3798
  // Context of already evaluted partition types.
3799
0
  PICK_MODE_CONTEXT **mode_srch_ctx[NUM_AB_PARTS][2];
3800
  // Set context of already evaluted partition types.
3801
0
  set_mode_search_ctx(pc_tree, is_ctx_ready, mode_srch_ctx);
3802
3803
  // Array of sub-partition size of AB partition types.
3804
0
  const BLOCK_SIZE ab_subsize[NUM_AB_PARTS][SUB_PARTITIONS_AB] = {
3805
0
    { blk_params.split_bsize2, blk_params.split_bsize2,
3806
0
      get_partition_subsize(bsize, PARTITION_HORZ_A) },
3807
0
    { get_partition_subsize(bsize, PARTITION_HORZ_B), blk_params.split_bsize2,
3808
0
      blk_params.split_bsize2 },
3809
0
    { blk_params.split_bsize2, blk_params.split_bsize2,
3810
0
      get_partition_subsize(bsize, PARTITION_VERT_A) },
3811
0
    { get_partition_subsize(bsize, PARTITION_VERT_B), blk_params.split_bsize2,
3812
0
      blk_params.split_bsize2 }
3813
0
  };
3814
3815
  // Array of mi_row, mi_col positions corresponds to each sub-partition in AB
3816
  // partition types.
3817
0
  const int ab_mi_pos[NUM_AB_PARTS][SUB_PARTITIONS_AB][2] = {
3818
0
    { { mi_row, mi_col },
3819
0
      { mi_row, blk_params.mi_col_edge },
3820
0
      { blk_params.mi_row_edge, mi_col } },
3821
0
    { { mi_row, mi_col },
3822
0
      { blk_params.mi_row_edge, mi_col },
3823
0
      { blk_params.mi_row_edge, blk_params.mi_col_edge } },
3824
0
    { { mi_row, mi_col },
3825
0
      { blk_params.mi_row_edge, mi_col },
3826
0
      { mi_row, blk_params.mi_col_edge } },
3827
0
    { { mi_row, mi_col },
3828
0
      { mi_row, blk_params.mi_col_edge },
3829
0
      { blk_params.mi_row_edge, blk_params.mi_col_edge } }
3830
0
  };
3831
3832
  // Loop over AB partition types.
3833
0
  for (AB_PART_TYPE ab_part_type = start_type; ab_part_type <= end_type;
3834
0
       ab_part_type++) {
3835
0
    const PARTITION_TYPE part_type = ab_part_type + PARTITION_HORZ_A;
3836
3837
    // Check if the AB partition search is to be performed.
3838
0
    if (!ab_partitions_allowed[ab_part_type]) {
3839
0
      continue;
3840
0
    }
3841
3842
0
    blk_params.subsize = get_partition_subsize(bsize, part_type);
3843
0
    for (int i = 0; i < SUB_PARTITIONS_AB; i++) {
3844
      // Set AB partition context.
3845
0
      cur_part_ctxs[ab_part_type][i] = av1_alloc_pmc(
3846
0
          cpi, ab_subsize[ab_part_type][i], &td->shared_coeff_buf);
3847
0
      if (!cur_part_ctxs[ab_part_type][i])
3848
0
        aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
3849
0
                           "Failed to allocate PICK_MODE_CONTEXT");
3850
      // Set mode as not ready.
3851
0
      cur_part_ctxs[ab_part_type][i]->rd_mode_is_ready = 0;
3852
0
    }
3853
3854
0
    if (cpi->sf.part_sf.reuse_prev_rd_results_for_part_ab) {
3855
      // We can copy directly the mode search results if we have already
3856
      // searched the current block and the contexts match.
3857
0
      if (is_ctx_ready[ab_part_type][0]) {
3858
0
        av1_copy_tree_context(cur_part_ctxs[ab_part_type][0],
3859
0
                              mode_srch_ctx[ab_part_type][0][0]);
3860
0
        cur_part_ctxs[ab_part_type][0]->mic.partition = part_type;
3861
0
        cur_part_ctxs[ab_part_type][0]->rd_mode_is_ready = 1;
3862
0
        if (is_ctx_ready[ab_part_type][1]) {
3863
0
          av1_copy_tree_context(cur_part_ctxs[ab_part_type][1],
3864
0
                                mode_srch_ctx[ab_part_type][1][0]);
3865
0
          cur_part_ctxs[ab_part_type][1]->mic.partition = part_type;
3866
0
          cur_part_ctxs[ab_part_type][1]->rd_mode_is_ready = 1;
3867
0
        }
3868
0
      }
3869
0
    }
3870
3871
    // Even if the contexts don't match, we can still speed up by reusing the
3872
    // previous prediction mode.
3873
0
    const MB_MODE_INFO *mode_cache[3] = { NULL, NULL, NULL };
3874
0
    if (cpi->sf.part_sf.reuse_best_prediction_for_part_ab) {
3875
0
      set_mode_cache_for_partition_ab(mode_cache, pc_tree, ab_part_type);
3876
0
    }
3877
3878
    // Evaluation of AB partition type.
3879
0
    rd_pick_ab_part(cpi, td, tile_data, tp, x, x_ctx, pc_tree,
3880
0
                    cur_part_ctxs[ab_part_type], part_search_state, best_rdc,
3881
0
                    ab_subsize[ab_part_type], ab_mi_pos[ab_part_type],
3882
0
                    part_type, mode_cache);
3883
0
  }
3884
0
}
3885
3886
// Set mi positions for HORZ4 / VERT4 sub-block partitions.
3887
static void set_mi_pos_partition4(const int inc_step[NUM_PART4_TYPES],
3888
                                  int mi_pos[SUB_PARTITIONS_PART4][2],
3889
0
                                  const int mi_row, const int mi_col) {
3890
0
  for (PART4_TYPES i = 0; i < SUB_PARTITIONS_PART4; i++) {
3891
0
    mi_pos[i][0] = mi_row + i * inc_step[HORZ4];
3892
0
    mi_pos[i][1] = mi_col + i * inc_step[VERT4];
3893
0
  }
3894
0
}
3895
3896
// Set context and RD cost for HORZ4 / VERT4 partition types.
3897
static void set_4_part_ctx_and_rdcost(
3898
    MACROBLOCK *x, const AV1_COMP *const cpi, ThreadData *td,
3899
    PICK_MODE_CONTEXT *cur_part_ctx[SUB_PARTITIONS_PART4],
3900
    PartitionSearchState *part_search_state, PARTITION_TYPE partition_type,
3901
0
    BLOCK_SIZE bsize) {
3902
  // Initialize sum_rdc RD cost structure.
3903
0
  av1_init_rd_stats(&part_search_state->sum_rdc);
3904
0
  const int subsize = get_partition_subsize(bsize, partition_type);
3905
0
  part_search_state->sum_rdc.rate =
3906
0
      part_search_state->partition_cost[partition_type];
3907
0
  part_search_state->sum_rdc.rdcost =
3908
0
      RDCOST(x->rdmult, part_search_state->sum_rdc.rate, 0);
3909
0
  for (PART4_TYPES i = 0; i < SUB_PARTITIONS_PART4; ++i) {
3910
0
    cur_part_ctx[i] = av1_alloc_pmc(cpi, subsize, &td->shared_coeff_buf);
3911
0
    if (!cur_part_ctx[i])
3912
0
      aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
3913
0
                         "Failed to allocate PICK_MODE_CONTEXT");
3914
0
  }
3915
0
}
3916
3917
// Partition search of HORZ4 / VERT4 partition types.
3918
static void rd_pick_4partition(
3919
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
3920
    TokenExtra **tp, MACROBLOCK *x, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
3921
    PC_TREE *pc_tree, PICK_MODE_CONTEXT *cur_part_ctx[SUB_PARTITIONS_PART4],
3922
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
3923
0
    const int inc_step[NUM_PART4_TYPES], PARTITION_TYPE partition_type) {
3924
0
  const AV1_COMMON *const cm = &cpi->common;
3925
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
3926
  // mi positions needed for HORZ4 and VERT4 partition types.
3927
0
  int mi_pos_check[NUM_PART4_TYPES] = { cm->mi_params.mi_rows,
3928
0
                                        cm->mi_params.mi_cols };
3929
0
  const PART4_TYPES part4_idx = (partition_type != PARTITION_HORZ_4);
3930
0
  int mi_pos[SUB_PARTITIONS_PART4][2];
3931
3932
0
  blk_params.subsize = get_partition_subsize(blk_params.bsize, partition_type);
3933
  // Set partition context and RD cost.
3934
0
  set_4_part_ctx_and_rdcost(x, cpi, td, cur_part_ctx, part_search_state,
3935
0
                            partition_type, blk_params.bsize);
3936
  // Set mi positions for sub-block sizes.
3937
0
  set_mi_pos_partition4(inc_step, mi_pos, blk_params.mi_row, blk_params.mi_col);
3938
#if CONFIG_COLLECT_PARTITION_STATS
3939
  PartitionTimingStats *part_timing_stats =
3940
      &part_search_state->part_timing_stats;
3941
  if (best_rdc->rdcost - part_search_state->sum_rdc.rdcost >= 0) {
3942
    start_partition_block_timer(part_timing_stats, partition_type);
3943
  }
3944
#endif
3945
  // Loop over sub-block partitions.
3946
0
  for (PART4_TYPES i = 0; i < SUB_PARTITIONS_PART4; ++i) {
3947
0
    if (i > 0 && mi_pos[i][part4_idx] >= mi_pos_check[part4_idx]) break;
3948
3949
    // Sub-block evaluation of Horz4 / Vert4 partition type.
3950
0
    cur_part_ctx[i]->rd_mode_is_ready = 0;
3951
0
    if (!rd_try_subblock(
3952
0
            cpi, td, tile_data, tp, (i == SUB_PARTITIONS_PART4 - 1),
3953
0
            mi_pos[i][0], mi_pos[i][1], blk_params.subsize, *best_rdc,
3954
0
            &part_search_state->sum_rdc, partition_type, cur_part_ctx[i])) {
3955
0
      av1_invalid_rd_stats(&part_search_state->sum_rdc);
3956
0
      break;
3957
0
    }
3958
0
  }
3959
3960
  // Calculate the total cost and update the best partition.
3961
0
  av1_rd_cost_update(x->rdmult, &part_search_state->sum_rdc);
3962
0
  if (part_search_state->sum_rdc.rdcost < best_rdc->rdcost) {
3963
0
    *best_rdc = part_search_state->sum_rdc;
3964
0
    part_search_state->found_best_partition = true;
3965
0
    pc_tree->partitioning = partition_type;
3966
0
  }
3967
#if CONFIG_COLLECT_PARTITION_STATS
3968
  if (part_timing_stats->timer_is_on) {
3969
    end_partition_block_timer(part_timing_stats, partition_type,
3970
                              part_search_state->sum_rdc.rdcost);
3971
  }
3972
#endif
3973
0
  av1_restore_context(x, x_ctx, blk_params.mi_row, blk_params.mi_col,
3974
0
                      blk_params.bsize, av1_num_planes(cm));
3975
0
}
3976
3977
// Do not evaluate extended partitions if NONE partition is skippable.
3978
static inline int prune_ext_part_none_skippable(
3979
    PICK_MODE_CONTEXT *part_none, int must_find_valid_partition,
3980
0
    int skip_non_sq_part_based_on_none, BLOCK_SIZE bsize) {
3981
0
  if ((skip_non_sq_part_based_on_none >= 1) && (part_none != NULL)) {
3982
0
    if (part_none->skippable && !must_find_valid_partition &&
3983
0
        bsize >= BLOCK_16X16) {
3984
0
      return 1;
3985
0
    }
3986
0
  }
3987
0
  return 0;
3988
0
}
3989
3990
// Allow ab partition search
3991
static int allow_ab_partition_search(PartitionSearchState *part_search_state,
3992
                                     PARTITION_SPEED_FEATURES *part_sf,
3993
                                     PARTITION_TYPE curr_best_part,
3994
                                     int must_find_valid_partition,
3995
                                     int prune_ext_part_state,
3996
0
                                     int64_t best_rdcost) {
3997
0
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
3998
0
  const BLOCK_SIZE bsize = blk_params.bsize;
3999
4000
  // Do not prune if there is no valid partition
4001
0
  if (best_rdcost == INT64_MAX) return 1;
4002
4003
  // Determine bsize threshold to evaluate ab partitions
4004
0
  BLOCK_SIZE ab_bsize_thresh = part_sf->ext_partition_eval_thresh;
4005
0
  if (part_sf->ext_part_eval_based_on_cur_best && !must_find_valid_partition &&
4006
0
      !(curr_best_part == PARTITION_HORZ || curr_best_part == PARTITION_VERT))
4007
0
    ab_bsize_thresh = BLOCK_128X128;
4008
4009
  // ab partitions are only allowed for square block sizes BLOCK_16X16 or
4010
  // higher, so ab_bsize_thresh must be large enough to exclude BLOCK_4X4 and
4011
  // BLOCK_8X8.
4012
0
  assert(ab_bsize_thresh >= BLOCK_8X8);
4013
4014
0
  int ab_partition_allowed =
4015
0
      part_search_state->do_rectangular_split && bsize > ab_bsize_thresh &&
4016
0
      av1_blk_has_rows_and_cols(&blk_params) && !prune_ext_part_state;
4017
4018
0
  return ab_partition_allowed;
4019
0
}
4020
4021
// Prune 4-way partitions based on the number of horz/vert wins
4022
// in the current block and sub-blocks in PARTITION_SPLIT.
4023
static void prune_4_partition_using_split_info(
4024
    AV1_COMP *const cpi, MACROBLOCK *x, PartitionSearchState *part_search_state,
4025
0
    int part4_search_allowed[NUM_PART4_TYPES]) {
4026
0
  PART4_TYPES cur_part[NUM_PART4_TYPES] = { HORZ4, VERT4 };
4027
  // Count of child blocks in which HORZ or VERT partition has won
4028
0
  int num_child_rect_win[NUM_RECT_PARTS] = { 0, 0 };
4029
  // Prune HORZ4/VERT4 partitions based on number of HORZ/VERT winners of
4030
  // split partiitons.
4031
  // Conservative pruning for high quantizers.
4032
0
  const int num_win_thresh = AOMMIN(3 * (MAXQ - x->qindex) / MAXQ + 1, 3);
4033
4034
0
  for (RECT_PART_TYPE i = HORZ; i < NUM_RECT_PARTS; i++) {
4035
0
    if (!(cpi->sf.part_sf.prune_ext_part_using_split_info &&
4036
0
          part4_search_allowed[cur_part[i]]))
4037
0
      continue;
4038
    // Loop over split partitions.
4039
    // Get rectangular partitions winner info of split partitions.
4040
0
    for (int idx = 0; idx < SUB_PARTITIONS_SPLIT; idx++)
4041
0
      num_child_rect_win[i] +=
4042
0
          (part_search_state->split_part_rect_win[idx].rect_part_win[i]) ? 1
4043
0
                                                                         : 0;
4044
0
    if (num_child_rect_win[i] < num_win_thresh) {
4045
0
      part4_search_allowed[cur_part[i]] = 0;
4046
0
    }
4047
0
  }
4048
0
}
4049
4050
static void prune_part4_using_sms(AV1_COMP *const cpi, MACROBLOCK *x,
4051
                                  const PartitionSearchState *part_search_state,
4052
                                  SIMPLE_MOTION_DATA_TREE *sms_tree, int mi_row,
4053
                                  int mi_col, BLOCK_SIZE bsize,
4054
0
                                  int *part4_search_allowed) {
4055
0
  if (!part4_search_allowed[HORZ4] || !part4_search_allowed[VERT4]) return;
4056
4057
0
  unsigned int sms_h_part4_sse[4];
4058
0
  unsigned int sms_v_part4_sse[4];
4059
4060
0
  const BLOCK_SIZE subsize_h4 = get_partition_subsize(bsize, PARTITION_HORZ_4);
4061
0
  const BLOCK_SIZE subsize_v4 = get_partition_subsize(bsize, PARTITION_VERT_4);
4062
4063
0
  const int h_mi = mi_size_high[bsize];
4064
0
  const int w_mi = mi_size_wide[bsize];
4065
4066
0
  const int ref = cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
4067
0
  if (!(cpi->ref_frame_flags & av1_ref_frame_flag_list[ref])) return;
4068
4069
0
  int64_t part4_h_sse_sum = 0;
4070
0
  int64_t part4_v_sse_sum = 0;
4071
4072
  // ---- HORZ_4 ----
4073
0
  for (int r_idx = 0; r_idx < SUB_PARTITIONS_PART4; r_idx++) {
4074
0
    unsigned int part_var;
4075
0
    const int sub_mi_row = mi_row + r_idx * h_mi / 4;
4076
0
    const int sub_mi_col = mi_col;
4077
4078
0
    av1_simple_motion_search_sse_var(cpi, x, sub_mi_row, sub_mi_col, subsize_h4,
4079
0
                                     ref, sms_tree->start_mvs[ref],
4080
0
                                     /*num_planes=*/1, /*use_subpixel=*/1,
4081
0
                                     &sms_h_part4_sse[r_idx], &part_var);
4082
4083
0
    (void)part_var;
4084
4085
0
    part4_h_sse_sum += sms_h_part4_sse[r_idx];
4086
0
  }
4087
4088
  // ---- VERT_4 ----
4089
0
  for (int r_idx = 0; r_idx < SUB_PARTITIONS_PART4; r_idx++) {
4090
0
    unsigned int part_var;
4091
0
    const int sub_mi_row = mi_row;
4092
0
    const int sub_mi_col = mi_col + r_idx * w_mi / 4;
4093
4094
0
    av1_simple_motion_search_sse_var(cpi, x, sub_mi_row, sub_mi_col, subsize_v4,
4095
0
                                     ref, sms_tree->start_mvs[ref],
4096
0
                                     /*num_planes=*/1, /*use_subpixel=*/1,
4097
0
                                     &sms_v_part4_sse[r_idx], &part_var);
4098
0
    (void)part_var;
4099
4100
0
    part4_v_sse_sum += sms_v_part4_sse[r_idx];
4101
0
  }
4102
4103
  // ---- Skip RD calculation ----
4104
0
  const int64_t part4_h_rd =
4105
0
      RDCOST(x->rdmult, part_search_state->partition_cost[PARTITION_HORZ_4],
4106
0
             part4_h_sse_sum);
4107
4108
0
  const int64_t part4_v_rd =
4109
0
      RDCOST(x->rdmult, part_search_state->partition_cost[PARTITION_VERT_4],
4110
0
             part4_v_sse_sum);
4111
4112
  // ---- pruning ----
4113
0
  if (part4_h_rd > part4_v_rd) part4_search_allowed[HORZ4] = 0;
4114
4115
0
  if (part4_v_rd > part4_h_rd) part4_search_allowed[VERT4] = 0;
4116
0
}
4117
4118
// Prune 4-way partition search.
4119
static void prune_4_way_partition_search(
4120
    AV1_COMP *const cpi, MACROBLOCK *x, PC_TREE *pc_tree,
4121
    PartitionSearchState *part_search_state, SIMPLE_MOTION_DATA_TREE *sms_tree,
4122
    RD_STATS *best_rdc, int pb_source_variance, int prune_ext_part_state,
4123
0
    int mi_row, int mi_col, int part4_search_allowed[NUM_PART4_TYPES]) {
4124
0
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
4125
0
  const BLOCK_SIZE bsize = blk_params.bsize;
4126
4127
0
  const PartitionCfg *const part_cfg = &cpi->oxcf.part_cfg;
4128
4129
  // Do not prune if there is no valid partition
4130
0
  if (best_rdc->rdcost == INT64_MAX && part_cfg->enable_1to4_partitions &&
4131
0
      bsize != BLOCK_128X128)
4132
0
    return;
4133
4134
  // Determine bsize threshold to evaluate 4-way partitions
4135
0
  BLOCK_SIZE part4_bsize_thresh = cpi->sf.part_sf.ext_partition_eval_thresh;
4136
0
  if (cpi->sf.part_sf.ext_part_eval_based_on_cur_best &&
4137
0
      !x->must_find_valid_partition && pc_tree->partitioning == PARTITION_NONE)
4138
0
    part4_bsize_thresh = BLOCK_128X128;
4139
4140
  // 4-way partitions are only allowed for BLOCK_16X16, BLOCK_32X32, and
4141
  // BLOCK_64X64, so part4_bsize_thresh must be large enough to exclude
4142
  // BLOCK_4X4 and BLOCK_8X8.
4143
0
  assert(part4_bsize_thresh >= BLOCK_8X8);
4144
4145
0
  bool partition4_allowed =
4146
0
      part_search_state->do_rectangular_split && bsize > part4_bsize_thresh &&
4147
0
      av1_blk_has_rows_and_cols(&blk_params) && !prune_ext_part_state;
4148
4149
  // Disable 4-way partition search flags for width less than a multiple of the
4150
  // minimum partition width.
4151
0
  if (blk_params.width < (blk_params.min_partition_size_1d
4152
0
                          << cpi->sf.part_sf.prune_part4_search)) {
4153
0
    part4_search_allowed[HORZ4] = 0;
4154
0
    part4_search_allowed[VERT4] = 0;
4155
0
    return;
4156
0
  }
4157
4158
0
  PARTITION_TYPE cur_part[NUM_PART4_TYPES] = { PARTITION_HORZ_4,
4159
0
                                               PARTITION_VERT_4 };
4160
  // partition4_allowed is 1 if we can use a PARTITION_HORZ_4 or
4161
  // PARTITION_VERT_4 for this block. This is almost the same as
4162
  // partition4_allowed, except that we don't allow 128x32 or 32x128
4163
  // blocks, so we require that bsize is not BLOCK_128X128.
4164
0
  partition4_allowed &=
4165
0
      part_cfg->enable_1to4_partitions && bsize != BLOCK_128X128;
4166
4167
0
  for (PART4_TYPES i = HORZ4; i < NUM_PART4_TYPES; i++) {
4168
0
    part4_search_allowed[i] =
4169
0
        partition4_allowed && part_search_state->partition_rect_allowed[i] &&
4170
0
        get_plane_block_size(get_partition_subsize(bsize, cur_part[i]),
4171
0
                             part_search_state->ss_x,
4172
0
                             part_search_state->ss_y) != BLOCK_INVALID;
4173
0
  }
4174
  // Pruning: pruning out 4-way partitions based on the current best partition.
4175
0
  if (cpi->sf.part_sf.prune_ext_partition_types_search_level == 2) {
4176
0
    part4_search_allowed[HORZ4] &= (pc_tree->partitioning == PARTITION_HORZ ||
4177
0
                                    pc_tree->partitioning == PARTITION_HORZ_A ||
4178
0
                                    pc_tree->partitioning == PARTITION_HORZ_B ||
4179
0
                                    pc_tree->partitioning == PARTITION_SPLIT ||
4180
0
                                    pc_tree->partitioning == PARTITION_NONE);
4181
0
    part4_search_allowed[VERT4] &= (pc_tree->partitioning == PARTITION_VERT ||
4182
0
                                    pc_tree->partitioning == PARTITION_VERT_A ||
4183
0
                                    pc_tree->partitioning == PARTITION_VERT_B ||
4184
0
                                    pc_tree->partitioning == PARTITION_SPLIT ||
4185
0
                                    pc_tree->partitioning == PARTITION_NONE);
4186
0
  }
4187
4188
  // Pruning: pruning out some 4-way partitions using a DNN taking rd costs of
4189
  // sub-blocks from basic partition types.
4190
0
  if (cpi->sf.part_sf.ml_prune_partition && partition4_allowed &&
4191
0
      part_search_state->partition_rect_allowed[HORZ] &&
4192
0
      part_search_state->partition_rect_allowed[VERT]) {
4193
0
    av1_ml_prune_4_partition(cpi, x, pc_tree->partitioning, best_rdc->rdcost,
4194
0
                             part_search_state, part4_search_allowed,
4195
0
                             pb_source_variance);
4196
0
  }
4197
4198
  // Pruning: pruning out 4-way partitions based on the number of horz/vert wins
4199
  // in the current block and sub-blocks in PARTITION_SPLIT.
4200
0
  prune_4_partition_using_split_info(cpi, x, part_search_state,
4201
0
                                     part4_search_allowed);
4202
4203
0
  if (cpi->sf.part_sf.prune_h_or_v_4part_using_sms_info && partition4_allowed &&
4204
0
      best_rdc->rdcost != INT64_MAX &&
4205
0
      av1_is_whole_blk_in_frame(&part_search_state->part_blk_params,
4206
0
                                &cpi->common.mi_params) &&
4207
0
      !frame_is_intra_only(&cpi->common)) {
4208
0
    prune_part4_using_sms(cpi, x, part_search_state, sms_tree, mi_row, mi_col,
4209
0
                          bsize, part4_search_allowed);
4210
0
  }
4211
0
}
4212
4213
// Set params needed for PARTITION_NONE search.
4214
static void set_none_partition_params(const AV1_COMP *const cpi, ThreadData *td,
4215
                                      MACROBLOCK *x, PC_TREE *pc_tree,
4216
                                      PartitionSearchState *part_search_state,
4217
                                      RD_STATS *best_remain_rdcost,
4218
0
                                      RD_STATS *best_rdc, int *pt_cost) {
4219
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4220
0
  RD_STATS partition_rdcost;
4221
  // Set PARTITION_NONE context.
4222
0
  if (pc_tree->none == NULL)
4223
0
    pc_tree->none = av1_alloc_pmc(cpi, blk_params.bsize, &td->shared_coeff_buf);
4224
0
  if (!pc_tree->none)
4225
0
    aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
4226
0
                       "Failed to allocate PICK_MODE_CONTEXT");
4227
4228
  // Set PARTITION_NONE type cost.
4229
0
  if (part_search_state->partition_none_allowed) {
4230
0
    if (blk_params.bsize_at_least_8x8) {
4231
0
      *pt_cost = part_search_state->partition_cost[PARTITION_NONE] < INT_MAX
4232
0
                     ? part_search_state->partition_cost[PARTITION_NONE]
4233
0
                     : 0;
4234
0
    }
4235
4236
    // Initialize the RD stats structure.
4237
0
    av1_init_rd_stats(&partition_rdcost);
4238
0
    partition_rdcost.rate = *pt_cost;
4239
0
    av1_rd_cost_update(x->rdmult, &partition_rdcost);
4240
0
    av1_rd_stats_subtraction(x->rdmult, best_rdc, &partition_rdcost,
4241
0
                             best_remain_rdcost);
4242
0
  }
4243
0
}
4244
4245
// Skip other partitions based on PARTITION_NONE rd cost.
4246
static void prune_partitions_after_none(AV1_COMP *const cpi, MACROBLOCK *x,
4247
                                        SIMPLE_MOTION_DATA_TREE *sms_tree,
4248
                                        PICK_MODE_CONTEXT *ctx_none,
4249
                                        PartitionSearchState *part_search_state,
4250
                                        RD_STATS *best_rdc,
4251
0
                                        unsigned int *pb_source_variance) {
4252
0
  const AV1_COMMON *const cm = &cpi->common;
4253
0
  MACROBLOCKD *const xd = &x->e_mbd;
4254
0
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
4255
0
  RD_STATS *this_rdc = &part_search_state->this_rdc;
4256
0
  const BLOCK_SIZE bsize = blk_params.bsize;
4257
0
  assert(bsize < BLOCK_SIZES_ALL);
4258
4259
0
  if (!frame_is_intra_only(cm) &&
4260
0
      (part_search_state->do_square_split ||
4261
0
       part_search_state->do_rectangular_split) &&
4262
0
      !x->e_mbd.lossless[xd->mi[0]->segment_id] && ctx_none->skippable) {
4263
0
    const int use_ml_based_breakout =
4264
0
        bsize <= cpi->sf.part_sf.use_square_partition_only_threshold &&
4265
0
        bsize > BLOCK_4X4 && cpi->sf.part_sf.ml_predict_breakout_level >= 1;
4266
0
    if (use_ml_based_breakout) {
4267
0
      av1_ml_predict_breakout(cpi, x, this_rdc, *pb_source_variance, xd->bd,
4268
0
                              part_search_state);
4269
0
    }
4270
4271
    // Adjust dist breakout threshold according to the partition size.
4272
0
    const int64_t dist_breakout_thr =
4273
0
        cpi->sf.part_sf.partition_search_breakout_dist_thr >>
4274
0
        ((2 * (MAX_SB_SIZE_LOG2 - 2)) -
4275
0
         (mi_size_wide_log2[bsize] + mi_size_high_log2[bsize]));
4276
0
    const int rate_breakout_thr =
4277
0
        cpi->sf.part_sf.partition_search_breakout_rate_thr *
4278
0
        num_pels_log2_lookup[bsize];
4279
    // If all y, u, v transform blocks in this partition are skippable,
4280
    // and the dist & rate are within the thresholds, the partition
4281
    // search is terminated for current branch of the partition search
4282
    // tree. The dist & rate thresholds are set to 0 at speed 0 to
4283
    // disable the early termination at that speed.
4284
0
    if (best_rdc->dist < dist_breakout_thr &&
4285
0
        best_rdc->rate < rate_breakout_thr) {
4286
0
      part_search_state->do_square_split = 0;
4287
0
      part_search_state->do_rectangular_split = 0;
4288
0
    }
4289
0
  }
4290
4291
  // Early termination: using simple_motion_search features and the
4292
  // rate, distortion, and rdcost of PARTITION_NONE, a DNN will make a
4293
  // decision on early terminating at PARTITION_NONE.
4294
0
  if (cpi->sf.part_sf.simple_motion_search_early_term_none && cm->show_frame &&
4295
0
      !frame_is_intra_only(cm) && bsize >= BLOCK_16X16 &&
4296
0
      av1_blk_has_rows_and_cols(&blk_params) && this_rdc->rdcost < INT64_MAX &&
4297
0
      this_rdc->rdcost >= 0 && this_rdc->rate < INT_MAX &&
4298
0
      this_rdc->rate >= 0 &&
4299
0
      (part_search_state->do_square_split ||
4300
0
       part_search_state->do_rectangular_split)) {
4301
0
    av1_simple_motion_search_early_term_none(cpi, x, sms_tree, this_rdc,
4302
0
                                             part_search_state);
4303
0
  }
4304
0
}
4305
4306
// Decide early termination and rectangular partition pruning
4307
// based on PARTITION_NONE and PARTITION_SPLIT costs.
4308
static void prune_partitions_after_split(
4309
    AV1_COMP *const cpi, MACROBLOCK *x, SIMPLE_MOTION_DATA_TREE *sms_tree,
4310
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
4311
0
    int64_t part_none_rd, int64_t part_split_rd) {
4312
0
  const AV1_COMMON *const cm = &cpi->common;
4313
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4314
0
  const int mi_row = blk_params.mi_row;
4315
0
  const int mi_col = blk_params.mi_col;
4316
0
  const BLOCK_SIZE bsize = blk_params.bsize;
4317
0
  assert(bsize < BLOCK_SIZES_ALL);
4318
4319
  // Early termination: using the rd costs of PARTITION_NONE and subblocks
4320
  // from PARTITION_SPLIT to determine an early breakout.
4321
0
  if (cpi->sf.part_sf.ml_early_term_after_part_split_level &&
4322
0
      !frame_is_intra_only(cm) &&
4323
0
      !part_search_state->terminate_partition_search &&
4324
0
      part_search_state->do_rectangular_split &&
4325
0
      (part_search_state->partition_rect_allowed[HORZ] ||
4326
0
       part_search_state->partition_rect_allowed[VERT])) {
4327
0
    av1_ml_early_term_after_split(
4328
0
        cpi, x, sms_tree, best_rdc->rdcost, part_none_rd, part_split_rd,
4329
0
        part_search_state->split_rd, part_search_state);
4330
0
  }
4331
4332
  // Use the rd costs of PARTITION_NONE and subblocks from PARTITION_SPLIT
4333
  // to prune out rectangular partitions in some directions.
4334
0
  if (!cpi->sf.part_sf.ml_early_term_after_part_split_level &&
4335
0
      cpi->sf.part_sf.ml_prune_partition && !frame_is_intra_only(cm) &&
4336
0
      (part_search_state->partition_rect_allowed[HORZ] ||
4337
0
       part_search_state->partition_rect_allowed[VERT]) &&
4338
0
      !(part_search_state->prune_rect_part[HORZ] ||
4339
0
        part_search_state->prune_rect_part[VERT]) &&
4340
0
      !part_search_state->terminate_partition_search) {
4341
0
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, av1_num_planes(cm),
4342
0
                         bsize);
4343
0
    av1_ml_prune_rect_partition(cpi, x, best_rdc->rdcost,
4344
0
                                part_search_state->none_rd,
4345
0
                                part_search_state->split_rd, part_search_state);
4346
0
  }
4347
0
}
4348
4349
// Returns true if either of the left and top neighbor blocks is larger than
4350
// the current block; false otherwise.
4351
static inline bool is_neighbor_blk_larger_than_cur_blk(const MACROBLOCKD *xd,
4352
0
                                                       BLOCK_SIZE bsize) {
4353
0
  const int cur_blk_area = (block_size_high[bsize] * block_size_wide[bsize]);
4354
0
  if (xd->left_available) {
4355
0
    const BLOCK_SIZE left_bsize = xd->left_mbmi->bsize;
4356
0
    if (block_size_high[left_bsize] * block_size_wide[left_bsize] >
4357
0
        cur_blk_area)
4358
0
      return true;
4359
0
  }
4360
4361
0
  if (xd->up_available) {
4362
0
    const BLOCK_SIZE above_bsize = xd->above_mbmi->bsize;
4363
0
    if (block_size_high[above_bsize] * block_size_wide[above_bsize] >
4364
0
        cur_blk_area)
4365
0
      return true;
4366
0
  }
4367
0
  return false;
4368
0
}
4369
4370
static inline void prune_rect_part_using_none_pred_mode(
4371
    const MACROBLOCKD *xd, PartitionSearchState *part_state,
4372
0
    PREDICTION_MODE mode, BLOCK_SIZE bsize) {
4373
0
  if (mode == DC_PRED || mode == SMOOTH_PRED) {
4374
    // If the prediction mode of NONE partition is either DC_PRED or
4375
    // SMOOTH_PRED, it indicates that the current block has less variation. In
4376
    // this case, HORZ and VERT partitions are pruned if at least one of left
4377
    // and top neighbor blocks is larger than the current block.
4378
0
    if (is_neighbor_blk_larger_than_cur_blk(xd, bsize)) {
4379
0
      part_state->prune_rect_part[HORZ] = 1;
4380
0
      part_state->prune_rect_part[VERT] = 1;
4381
0
    }
4382
0
  } else if (mode == D67_PRED || mode == V_PRED || mode == D113_PRED) {
4383
    // If the prediction mode chosen by NONE partition is close to 90 degrees,
4384
    // it implies a dominant vertical pattern, and the chance of choosing a
4385
    // vertical rectangular partition is high. Hence, horizontal partition is
4386
    // pruned in these cases.
4387
0
    part_state->prune_rect_part[HORZ] = 1;
4388
0
  } else if (mode == D157_PRED || mode == H_PRED || mode == D203_PRED) {
4389
    // If the prediction mode chosen by NONE partition is close to 180 degrees,
4390
    // it implies a dominant horizontal pattern, and the chance of choosing a
4391
    // horizontal rectangular partition is high. Hence, vertical partition is
4392
    // pruned in these cases.
4393
0
    part_state->prune_rect_part[VERT] = 1;
4394
0
  }
4395
0
}
4396
4397
// PARTITION_NONE search.
4398
static void none_partition_search(
4399
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data, MACROBLOCK *x,
4400
    PC_TREE *pc_tree, SIMPLE_MOTION_DATA_TREE *sms_tree,
4401
    RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
4402
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
4403
0
    unsigned int *pb_source_variance, int64_t *none_rd, int64_t *part_none_rd) {
4404
0
  const AV1_COMMON *const cm = &cpi->common;
4405
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4406
0
  RD_STATS *this_rdc = &part_search_state->this_rdc;
4407
0
  const int mi_row = blk_params.mi_row;
4408
0
  const int mi_col = blk_params.mi_col;
4409
0
  const BLOCK_SIZE bsize = blk_params.bsize;
4410
0
  assert(bsize < BLOCK_SIZES_ALL);
4411
4412
0
  if (part_search_state->terminate_partition_search ||
4413
0
      !part_search_state->partition_none_allowed)
4414
0
    return;
4415
4416
0
  int pt_cost = 0;
4417
0
  RD_STATS best_remain_rdcost;
4418
0
  av1_invalid_rd_stats(&best_remain_rdcost);
4419
4420
  // Set PARTITION_NONE context and cost.
4421
0
  set_none_partition_params(cpi, td, x, pc_tree, part_search_state,
4422
0
                            &best_remain_rdcost, best_rdc, &pt_cost);
4423
4424
#if CONFIG_COLLECT_PARTITION_STATS
4425
  // Timer start for partition None.
4426
  PartitionTimingStats *part_timing_stats =
4427
      &part_search_state->part_timing_stats;
4428
  if (best_remain_rdcost.rdcost >= 0) {
4429
    start_partition_block_timer(part_timing_stats, PARTITION_NONE);
4430
  }
4431
#endif
4432
  // PARTITION_NONE evaluation and cost update.
4433
0
  pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, this_rdc, PARTITION_NONE,
4434
0
                bsize, pc_tree->none, best_remain_rdcost);
4435
4436
0
  av1_rd_cost_update(x->rdmult, this_rdc);
4437
4438
#if CONFIG_COLLECT_PARTITION_STATS
4439
  // Timer end for partition None.
4440
  if (part_timing_stats->timer_is_on) {
4441
    RD_STATS tmp_rdc;
4442
    av1_init_rd_stats(&tmp_rdc);
4443
    if (this_rdc->rate != INT_MAX) {
4444
      tmp_rdc.rate = this_rdc->rate;
4445
      tmp_rdc.dist = this_rdc->dist;
4446
      tmp_rdc.rdcost = this_rdc->rdcost;
4447
      if (blk_params.bsize_at_least_8x8) {
4448
        tmp_rdc.rate += pt_cost;
4449
        tmp_rdc.rdcost = RDCOST(x->rdmult, tmp_rdc.rate, tmp_rdc.dist);
4450
      }
4451
    }
4452
    end_partition_block_timer(part_timing_stats, PARTITION_NONE,
4453
                              tmp_rdc.rdcost);
4454
  }
4455
#endif
4456
0
  *pb_source_variance = x->source_variance;
4457
0
  if (none_rd) *none_rd = this_rdc->rdcost;
4458
0
  part_search_state->none_rd = this_rdc->rdcost;
4459
0
  if (this_rdc->rate != INT_MAX) {
4460
    // Record picked ref frame to prune ref frames for other partition types.
4461
0
    if (cpi->sf.inter_sf.prune_ref_frame_for_rect_partitions) {
4462
0
      const int ref_type = av1_ref_frame_type(pc_tree->none->mic.ref_frame);
4463
0
      av1_update_picked_ref_frames_mask(
4464
0
          x, ref_type, bsize, cm->seq_params->mib_size, mi_row, mi_col);
4465
0
    }
4466
4467
    // Calculate the total cost and update the best partition.
4468
0
    if (blk_params.bsize_at_least_8x8) {
4469
0
      this_rdc->rate += pt_cost;
4470
0
      this_rdc->rdcost = RDCOST(x->rdmult, this_rdc->rate, this_rdc->dist);
4471
0
    }
4472
0
    *part_none_rd = this_rdc->rdcost;
4473
0
    if (this_rdc->rdcost < best_rdc->rdcost) {
4474
0
      *best_rdc = *this_rdc;
4475
0
      part_search_state->found_best_partition = true;
4476
0
      if (blk_params.bsize_at_least_8x8) {
4477
0
        pc_tree->partitioning = PARTITION_NONE;
4478
0
      }
4479
4480
      // Disable split and rectangular partition search
4481
      // based on PARTITION_NONE cost.
4482
0
      prune_partitions_after_none(cpi, x, sms_tree, pc_tree->none,
4483
0
                                  part_search_state, best_rdc,
4484
0
                                  pb_source_variance);
4485
0
    }
4486
4487
0
    if (cpi->sf.part_sf.prune_rect_part_using_none_pred_mode)
4488
0
      prune_rect_part_using_none_pred_mode(&x->e_mbd, part_search_state,
4489
0
                                           pc_tree->none->mic.mode, bsize);
4490
0
  }
4491
0
  av1_restore_context(x, x_ctx, mi_row, mi_col, bsize, av1_num_planes(cm));
4492
0
}
4493
4494
static inline double get_split_partition_penalty(
4495
0
    BLOCK_SIZE bsize, int split_partition_penalty_level) {
4496
0
  if (!split_partition_penalty_level) return 1.00;
4497
4498
  // Higher penalty for smaller block sizes.
4499
0
  static const double penalty_factors[2][SQR_BLOCK_SIZES - 1] = {
4500
0
    { 1.080, 1.040, 1.020, 1.010, 1.000 },
4501
0
    { 1.100, 1.075, 1.050, 1.025, 1.000 },
4502
0
  };
4503
0
  const int sqr_bsize_idx = get_sqr_bsize_idx(bsize);
4504
0
  assert(sqr_bsize_idx > 0 && sqr_bsize_idx < SQR_BLOCK_SIZES);
4505
0
  const double this_penalty_factor =
4506
0
      penalty_factors[split_partition_penalty_level - 1][sqr_bsize_idx - 1];
4507
0
  return this_penalty_factor;
4508
0
}
4509
4510
// PARTITION_SPLIT search.
4511
static void split_partition_search(
4512
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
4513
    TokenExtra **tp, MACROBLOCK *x, PC_TREE *pc_tree,
4514
    SIMPLE_MOTION_DATA_TREE *sms_tree, RD_SEARCH_MACROBLOCK_CONTEXT *x_ctx,
4515
    PartitionSearchState *part_search_state, RD_STATS *best_rdc,
4516
0
    SB_MULTI_PASS_MODE multi_pass_mode, int64_t *part_split_rd) {
4517
0
  const AV1_COMMON *const cm = &cpi->common;
4518
0
  PartitionBlkParams blk_params = part_search_state->part_blk_params;
4519
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
4520
0
  const int mi_row = blk_params.mi_row;
4521
0
  const int mi_col = blk_params.mi_col;
4522
0
  const BLOCK_SIZE bsize = blk_params.bsize;
4523
0
  assert(bsize < BLOCK_SIZES_ALL);
4524
0
  RD_STATS sum_rdc = part_search_state->sum_rdc;
4525
0
  const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
4526
4527
  // Check if partition split is allowed.
4528
0
  if (part_search_state->terminate_partition_search ||
4529
0
      !part_search_state->do_square_split)
4530
0
    return;
4531
4532
0
  for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
4533
0
    if (pc_tree->split[i] == NULL)
4534
0
      pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
4535
0
    if (!pc_tree->split[i])
4536
0
      aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
4537
0
                         "Failed to allocate PC_TREE");
4538
0
    pc_tree->split[i]->index = i;
4539
0
  }
4540
4541
  // Initialization of this partition RD stats.
4542
0
  av1_init_rd_stats(&sum_rdc);
4543
0
  sum_rdc.rate = part_search_state->partition_cost[PARTITION_SPLIT];
4544
0
  sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, 0);
4545
4546
0
  int idx;
4547
#if CONFIG_COLLECT_PARTITION_STATS
4548
  PartitionTimingStats *part_timing_stats =
4549
      &part_search_state->part_timing_stats;
4550
  if (best_rdc->rdcost - sum_rdc.rdcost >= 0) {
4551
    start_partition_block_timer(part_timing_stats, PARTITION_SPLIT);
4552
  }
4553
#endif
4554
  // Recursive partition search on 4 sub-blocks.
4555
0
  for (idx = 0; idx < SUB_PARTITIONS_SPLIT && sum_rdc.rdcost < best_rdc->rdcost;
4556
0
       ++idx) {
4557
0
    const int x_idx = (idx & 1) * blk_params.mi_step;
4558
0
    const int y_idx = (idx >> 1) * blk_params.mi_step;
4559
4560
0
    if (mi_row + y_idx >= mi_params->mi_rows ||
4561
0
        mi_col + x_idx >= mi_params->mi_cols)
4562
0
      continue;
4563
4564
0
    pc_tree->split[idx]->index = idx;
4565
0
    int64_t *p_split_rd = &part_search_state->split_rd[idx];
4566
0
    RD_STATS best_remain_rdcost;
4567
0
    av1_rd_stats_subtraction(x->rdmult, best_rdc, &sum_rdc,
4568
0
                             &best_remain_rdcost);
4569
4570
0
    int curr_quad_tree_idx = 0;
4571
0
    if (frame_is_intra_only(cm) && bsize <= BLOCK_64X64) {
4572
0
      curr_quad_tree_idx = part_search_state->intra_part_info->quad_tree_idx;
4573
0
      part_search_state->intra_part_info->quad_tree_idx =
4574
0
          4 * curr_quad_tree_idx + idx + 1;
4575
0
    }
4576
    // Split partition evaluation of corresponding idx.
4577
    // If the RD cost exceeds the best cost then do not
4578
    // evaluate other split sub-partitions.
4579
0
    SIMPLE_MOTION_DATA_TREE *const sms_tree_split =
4580
0
        (sms_tree == NULL) ? NULL : sms_tree->split[idx];
4581
0
    if (!av1_rd_pick_partition(
4582
0
            cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
4583
0
            &part_search_state->this_rdc, best_remain_rdcost,
4584
0
            pc_tree->split[idx], sms_tree_split, p_split_rd, multi_pass_mode,
4585
0
            &part_search_state->split_part_rect_win[idx])) {
4586
0
      av1_invalid_rd_stats(&sum_rdc);
4587
0
      break;
4588
0
    }
4589
0
    if (frame_is_intra_only(cm) && bsize <= BLOCK_64X64) {
4590
0
      part_search_state->intra_part_info->quad_tree_idx = curr_quad_tree_idx;
4591
0
    }
4592
4593
0
    sum_rdc.rate += part_search_state->this_rdc.rate;
4594
0
    sum_rdc.dist += part_search_state->this_rdc.dist;
4595
0
    av1_rd_cost_update(x->rdmult, &sum_rdc);
4596
4597
    // Set split ctx as ready for use.
4598
0
    if (idx <= 1 && (bsize <= BLOCK_8X8 ||
4599
0
                     pc_tree->split[idx]->partitioning == PARTITION_NONE)) {
4600
0
      const MB_MODE_INFO *const mbmi = &pc_tree->split[idx]->none->mic;
4601
0
      const PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
4602
      // Neither palette mode nor cfl predicted.
4603
0
      if (pmi->palette_size[0] == 0 && pmi->palette_size[1] == 0) {
4604
0
        if (mbmi->uv_mode != UV_CFL_PRED)
4605
0
          part_search_state->is_split_ctx_is_ready[idx] = 1;
4606
0
      }
4607
0
    }
4608
0
  }
4609
#if CONFIG_COLLECT_PARTITION_STATS
4610
  if (part_timing_stats->timer_is_on) {
4611
    end_partition_block_timer(part_timing_stats, PARTITION_SPLIT,
4612
                              sum_rdc.rdcost);
4613
  }
4614
#endif
4615
0
  const int reached_last_index = (idx == SUB_PARTITIONS_SPLIT);
4616
4617
  // Calculate the total cost and update the best partition.
4618
0
  *part_split_rd = sum_rdc.rdcost;
4619
0
  if (reached_last_index && sum_rdc.rdcost < best_rdc->rdcost) {
4620
0
    sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, sum_rdc.dist);
4621
0
    const double penalty_factor = get_split_partition_penalty(
4622
0
        bsize, cpi->sf.part_sf.split_partition_penalty_level);
4623
0
    const int64_t this_rdcost = (int64_t)(sum_rdc.rdcost * penalty_factor);
4624
0
    if (this_rdcost < best_rdc->rdcost) {
4625
0
      *best_rdc = sum_rdc;
4626
0
      part_search_state->found_best_partition = true;
4627
0
      pc_tree->partitioning = PARTITION_SPLIT;
4628
0
    }
4629
0
  } else if (cpi->sf.part_sf.less_rectangular_check_level > 0) {
4630
    // Skip rectangular partition test when partition type none gives better
4631
    // rd than partition type split.
4632
0
    if (cpi->sf.part_sf.less_rectangular_check_level == 2 || idx <= 2) {
4633
0
      const int partition_none_valid = part_search_state->none_rd > 0;
4634
0
      const int partition_none_better =
4635
0
          part_search_state->none_rd < sum_rdc.rdcost;
4636
0
      part_search_state->do_rectangular_split &=
4637
0
          !(partition_none_valid && partition_none_better);
4638
0
    }
4639
0
  }
4640
  // Restore the context for the following cases:
4641
  // 1) Current block size not more than maximum partition size as dry run
4642
  // encode happens for these cases
4643
  // 2) Current block size same as superblock size as the final encode
4644
  // happens for this case
4645
0
  if (bsize <= x->sb_enc.max_partition_size || bsize == cm->seq_params->sb_size)
4646
0
    av1_restore_context(x, x_ctx, mi_row, mi_col, bsize, av1_num_planes(cm));
4647
0
}
4648
4649
#if COLLECT_MOTION_SEARCH_FEATURE_SB
4650
// The max number of nodes in the partition tree.
4651
// The number of leaf nodes is (128x128) / (4x4) = 1024.
4652
// The number of All possible parent nodes is 1 + 2 + ... + 512 = 1023.
4653
#define NUM_NODES 2048
4654
4655
static void write_partition_tree(AV1_COMP *const cpi,
4656
                                 const PC_TREE *const pc_tree,
4657
                                 const BLOCK_SIZE bsize, const int mi_row,
4658
                                 const int mi_col) {
4659
  (void)mi_row;
4660
  (void)mi_col;
4661
  const char *path = cpi->oxcf.partition_info_path;
4662
  char filename[256];
4663
  snprintf(filename, sizeof(filename), "%s/partition_tree_sb%d_c%d", path,
4664
           cpi->sb_counter, 0);
4665
  FILE *pfile = fopen(filename, "w");
4666
  fprintf(pfile, "%d", bsize);
4667
4668
  // Write partition type with BFS order.
4669
  const PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4670
  int q_idx = 0;
4671
  int last_idx = 1;
4672
  int num_nodes = 1;
4673
4674
  // First traversal to get number of leaf nodes.
4675
  tree_node_queue[q_idx] = pc_tree;
4676
  while (num_nodes > 0) {
4677
    const PC_TREE *node = tree_node_queue[q_idx];
4678
    if (node->partitioning == PARTITION_SPLIT) {
4679
      for (int i = 0; i < 4; ++i) {
4680
        tree_node_queue[last_idx] = node->split[i];
4681
        ++last_idx;
4682
      }
4683
      num_nodes += 4;
4684
    }
4685
    --num_nodes;
4686
    ++q_idx;
4687
  }
4688
  const int num_leafs = last_idx;
4689
  fprintf(pfile, ",%d,%d", num_leafs, /*num_configs=*/1);
4690
4691
  // Write partitions for each node.
4692
  q_idx = 0;
4693
  last_idx = 1;
4694
  num_nodes = 1;
4695
  tree_node_queue[q_idx] = pc_tree;
4696
  while (num_nodes > 0) {
4697
    const PC_TREE *node = tree_node_queue[q_idx];
4698
    fprintf(pfile, ",%d", node->partitioning);
4699
    if (node->partitioning == PARTITION_SPLIT) {
4700
      for (int i = 0; i < 4; ++i) {
4701
        tree_node_queue[last_idx] = node->split[i];
4702
        ++last_idx;
4703
      }
4704
      num_nodes += 4;
4705
    }
4706
    --num_nodes;
4707
    ++q_idx;
4708
  }
4709
  fprintf(pfile, "\n");
4710
4711
  fclose(pfile);
4712
}
4713
#endif  // COLLECT_MOTION_SEARCH_FEATURE_SB
4714
4715
#if CONFIG_PARTITION_SEARCH_ORDER
4716
static void verify_write_partition_tree(const AV1_COMP *const cpi,
4717
                                        const PC_TREE *const pc_tree,
4718
                                        const BLOCK_SIZE bsize,
4719
                                        const int config_id, const int mi_row,
4720
                                        const int mi_col) {
4721
  (void)mi_row;
4722
  (void)mi_col;
4723
  const char *path = cpi->oxcf.partition_info_path;
4724
  char filename[256];
4725
  snprintf(filename, sizeof(filename), "%s/verify_partition_tree_sb%d_c%d",
4726
           path, cpi->sb_counter, config_id);
4727
  FILE *pfile = fopen(filename, "w");
4728
  fprintf(pfile, "%d", bsize);
4729
4730
  // Write partition type with BFS order.
4731
  const PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4732
  int q_idx = 0;
4733
  int last_idx = 1;
4734
  int num_nodes = 1;
4735
4736
  // First traversal to get number of leaf nodes.
4737
  tree_node_queue[q_idx] = pc_tree;
4738
  while (num_nodes > 0) {
4739
    const PC_TREE *node = tree_node_queue[q_idx];
4740
    if (node != NULL && node->partitioning == PARTITION_SPLIT) {
4741
      for (int i = 0; i < 4; ++i) {
4742
        tree_node_queue[last_idx] = node->split[i];
4743
        ++last_idx;
4744
      }
4745
      num_nodes += 4;
4746
    }
4747
    --num_nodes;
4748
    ++q_idx;
4749
  }
4750
  const int num_leafs = last_idx;
4751
  fprintf(pfile, ",%d,%d", num_leafs, /*num_configs=*/1);
4752
4753
  // Write partitions for each node.
4754
  q_idx = 0;
4755
  last_idx = 1;
4756
  num_nodes = 1;
4757
  tree_node_queue[q_idx] = pc_tree;
4758
  while (num_nodes > 0) {
4759
    const PC_TREE *node = tree_node_queue[q_idx];
4760
    if (node != NULL) {  // suppress warning
4761
      fprintf(pfile, ",%d", node->partitioning);
4762
      if (node->partitioning == PARTITION_SPLIT) {
4763
        for (int i = 0; i < 4; ++i) {
4764
          tree_node_queue[last_idx] = node->split[i];
4765
          ++last_idx;
4766
        }
4767
        num_nodes += 4;
4768
      }
4769
    }
4770
    --num_nodes;
4771
    ++q_idx;
4772
  }
4773
  fprintf(pfile, "\n");
4774
4775
  fclose(pfile);
4776
}
4777
4778
static int read_partition_tree(AV1_COMP *const cpi, PC_TREE *const pc_tree,
4779
                               struct aom_internal_error_info *error_info,
4780
                               const int config_id) {
4781
  const AV1_COMMON *const cm = &cpi->common;
4782
  const char *path = cpi->oxcf.partition_info_path;
4783
  char filename[256];
4784
  snprintf(filename, sizeof(filename), "%s/partition_tree_sb%d_c%d", path,
4785
           cpi->sb_counter, config_id);
4786
  FILE *pfile = fopen(filename, "r");
4787
  if (pfile == NULL) {
4788
    aom_internal_error(cm->error, AOM_CODEC_ERROR, "Can't find input file: %s.",
4789
                       filename);
4790
  }
4791
4792
  int read_bsize;
4793
  int num_nodes;
4794
  int num_configs;
4795
  fscanf(pfile, "%d,%d,%d", &read_bsize, &num_nodes, &num_configs);
4796
  assert(read_bsize == cpi->common.seq_params->sb_size);
4797
  BLOCK_SIZE bsize = (BLOCK_SIZE)read_bsize;
4798
  assert(bsize == pc_tree->block_size);
4799
4800
  PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4801
  int last_idx = 1;
4802
  int q_idx = 0;
4803
  tree_node_queue[q_idx] = pc_tree;
4804
  while (num_nodes > 0) {
4805
    int partitioning;
4806
    fscanf(pfile, ",%d", &partitioning);
4807
    assert(partitioning >= PARTITION_NONE &&
4808
           partitioning < EXT_PARTITION_TYPES);
4809
    PC_TREE *node = tree_node_queue[q_idx];
4810
    if (node != NULL) {
4811
      node->partitioning = partitioning;
4812
      bsize = node->block_size;
4813
    }
4814
    if (partitioning == PARTITION_SPLIT) {
4815
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
4816
      for (int i = 0; i < 4; ++i) {
4817
        if (node != NULL) {  // Suppress warning
4818
          node->split[i] = av1_alloc_pc_tree_node(subsize);
4819
          if (!node->split[i])
4820
            aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
4821
                               "Failed to allocate PC_TREE");
4822
          node->split[i]->index = i;
4823
          tree_node_queue[last_idx] = node->split[i];
4824
          ++last_idx;
4825
        }
4826
      }
4827
    }
4828
    --num_nodes;
4829
    ++q_idx;
4830
  }
4831
  fclose(pfile);
4832
4833
  return num_configs;
4834
}
4835
4836
static RD_STATS rd_search_for_fixed_partition(
4837
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data,
4838
    TokenExtra **tp, SIMPLE_MOTION_DATA_TREE *sms_tree, int mi_row, int mi_col,
4839
    const BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4840
  const PARTITION_TYPE partition = pc_tree->partitioning;
4841
  const AV1_COMMON *const cm = &cpi->common;
4842
  const int num_planes = av1_num_planes(cm);
4843
  MACROBLOCK *const x = &td->mb;
4844
  MACROBLOCKD *const xd = &x->e_mbd;
4845
  TileInfo *const tile_info = &tile_data->tile_info;
4846
  RD_STATS best_rdc;
4847
  av1_invalid_rd_stats(&best_rdc);
4848
  int sum_subblock_rate = 0;
4849
  int64_t sum_subblock_dist = 0;
4850
  PartitionSearchState part_search_state;
4851
  init_partition_search_state_params(x, cpi, &part_search_state, mi_row, mi_col,
4852
                                     bsize);
4853
  // Override partition costs at the edges of the frame in the same
4854
  // way as in read_partition (see decodeframe.c).
4855
  PartitionBlkParams blk_params = part_search_state.part_blk_params;
4856
  if (!av1_blk_has_rows_and_cols(&blk_params))
4857
    set_partition_cost_for_edge_blk(cm, &part_search_state);
4858
4859
  av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4860
4861
  // Save rdmult before it might be changed, so it can be restored later.
4862
  const int orig_rdmult = x->rdmult;
4863
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
4864
  (void)orig_rdmult;
4865
4866
  // Set the context.
4867
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
4868
  xd->above_txfm_context =
4869
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
4870
  xd->left_txfm_context =
4871
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
4872
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
4873
4874
  assert(bsize < BLOCK_SIZES_ALL);
4875
  unsigned int pb_source_variance = UINT_MAX;
4876
  int64_t part_none_rd = INT64_MAX;
4877
  int64_t none_rd = INT64_MAX;
4878
  int inc_step[NUM_PART4_TYPES] = { 0 };
4879
  if (partition == PARTITION_HORZ_4) inc_step[HORZ4] = mi_size_high[bsize] / 4;
4880
  if (partition == PARTITION_VERT_4) inc_step[VERT4] = mi_size_wide[bsize] / 4;
4881
4882
  switch (partition) {
4883
    case PARTITION_NONE:
4884
      none_partition_search(cpi, td, tile_data, x, pc_tree, sms_tree, &x_ctx,
4885
                            &part_search_state, &best_rdc, &pb_source_variance,
4886
                            &none_rd, &part_none_rd);
4887
      break;
4888
    case PARTITION_HORZ:
4889
      rectangular_partition_search(cpi, td, tile_data, tp, x, pc_tree, &x_ctx,
4890
                                   &part_search_state, &best_rdc, NULL, HORZ,
4891
                                   HORZ);
4892
      break;
4893
    case PARTITION_VERT:
4894
      rectangular_partition_search(cpi, td, tile_data, tp, x, pc_tree, &x_ctx,
4895
                                   &part_search_state, &best_rdc, NULL, VERT,
4896
                                   VERT);
4897
      break;
4898
    case PARTITION_HORZ_A:
4899
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4900
                           &part_search_state, &best_rdc, NULL,
4901
                           pb_source_variance, 1, HORZ_A, HORZ_A);
4902
      break;
4903
    case PARTITION_HORZ_B:
4904
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4905
                           &part_search_state, &best_rdc, NULL,
4906
                           pb_source_variance, 1, HORZ_B, HORZ_B);
4907
      break;
4908
    case PARTITION_VERT_A:
4909
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4910
                           &part_search_state, &best_rdc, NULL,
4911
                           pb_source_variance, 1, VERT_A, VERT_A);
4912
      break;
4913
    case PARTITION_VERT_B:
4914
      ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4915
                           &part_search_state, &best_rdc, NULL,
4916
                           pb_source_variance, 1, VERT_B, VERT_B);
4917
      break;
4918
    case PARTITION_HORZ_4:
4919
      rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4920
                         pc_tree->horizontal4, &part_search_state, &best_rdc,
4921
                         inc_step, PARTITION_HORZ_4);
4922
      break;
4923
    case PARTITION_VERT_4:
4924
      rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
4925
                         pc_tree->vertical4, &part_search_state, &best_rdc,
4926
                         inc_step, PARTITION_VERT_4);
4927
      break;
4928
    case PARTITION_SPLIT:
4929
      for (int idx = 0; idx < SUB_PARTITIONS_SPLIT; ++idx) {
4930
        const BLOCK_SIZE subsize =
4931
            get_partition_subsize(bsize, PARTITION_SPLIT);
4932
        assert(subsize < BLOCK_SIZES_ALL);
4933
        const int next_mi_row =
4934
            idx < 2 ? mi_row : mi_row + mi_size_high[subsize];
4935
        const int next_mi_col =
4936
            idx % 2 == 0 ? mi_col : mi_col + mi_size_wide[subsize];
4937
        if (next_mi_row >= cm->mi_params.mi_rows ||
4938
            next_mi_col >= cm->mi_params.mi_cols) {
4939
          continue;
4940
        }
4941
        const RD_STATS subblock_rdc = rd_search_for_fixed_partition(
4942
            cpi, td, tile_data, tp, sms_tree->split[idx], next_mi_row,
4943
            next_mi_col, subsize, pc_tree->split[idx]);
4944
        sum_subblock_rate += subblock_rdc.rate;
4945
        sum_subblock_dist += subblock_rdc.dist;
4946
      }
4947
      best_rdc.rate = sum_subblock_rate;
4948
      best_rdc.rate += part_search_state.partition_cost[PARTITION_SPLIT];
4949
      best_rdc.dist = sum_subblock_dist;
4950
      best_rdc.rdcost = RDCOST(x->rdmult, best_rdc.rate, best_rdc.dist);
4951
      break;
4952
    default:
4953
      assert(0 && "invalid partition type.");
4954
      aom_internal_error(cm->error, AOM_CODEC_ERROR, "Invalid partition type.");
4955
  }
4956
  // Note: it is necessary to restore context information.
4957
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
4958
4959
  if (bsize != cm->seq_params->sb_size) {
4960
    encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_NORMAL, bsize,
4961
              pc_tree, NULL);
4962
  }
4963
  x->rdmult = orig_rdmult;
4964
4965
  return best_rdc;
4966
}
4967
4968
static void prepare_sb_features_before_search(
4969
    AV1_COMP *const cpi, ThreadData *td, TileDataEnc *tile_data, int mi_row,
4970
    int mi_col, const BLOCK_SIZE bsize, aom_partition_features_t *features) {
4971
  av1_collect_motion_search_features_sb(cpi, td, tile_data, mi_row, mi_col,
4972
                                        bsize, features);
4973
  collect_tpl_stats_sb(cpi, bsize, mi_row, mi_col, features);
4974
}
4975
4976
static void update_partition_stats(const RD_STATS *const this_rdcost,
4977
                                   aom_partition_stats_t *stats) {
4978
  stats->rate = this_rdcost->rate;
4979
  stats->dist = this_rdcost->dist;
4980
  stats->rdcost = this_rdcost->rdcost;
4981
}
4982
4983
static void build_pc_tree_from_part_decision(
4984
    const aom_partition_decision_t *partition_decision,
4985
    const BLOCK_SIZE this_bsize, PC_TREE *pc_tree,
4986
    struct aom_internal_error_info *error_info) {
4987
  BLOCK_SIZE bsize = this_bsize;
4988
  int num_nodes = partition_decision->num_nodes;
4989
  PC_TREE *tree_node_queue[NUM_NODES] = { NULL };
4990
  int last_idx = 1;
4991
  int q_idx = 0;
4992
  tree_node_queue[q_idx] = pc_tree;
4993
  while (num_nodes > 0) {
4994
    const int partitioning = partition_decision->partition_decision[q_idx];
4995
    assert(partitioning >= PARTITION_NONE &&
4996
           partitioning < EXT_PARTITION_TYPES);
4997
    PC_TREE *node = tree_node_queue[q_idx];
4998
    if (node != NULL) {
4999
      node->partitioning = partitioning;
5000
      bsize = node->block_size;
5001
    }
5002
    if (partitioning != PARTITION_NONE) {
5003
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, partitioning);
5004
      // Smaller block size for AB partition
5005
      const BLOCK_SIZE subsize2 = get_partition_subsize(bsize, PARTITION_SPLIT);
5006
5007
      switch (partitioning) {
5008
        case PARTITION_SPLIT:
5009
        case PARTITION_HORZ_4:
5010
        case PARTITION_VERT_4:
5011
          for (int i = 0; i < 4; ++i) {
5012
            if (node != NULL) {  // Suppress warning
5013
              node->split[i] = av1_alloc_pc_tree_node(subsize);
5014
              if (!node->split[i])
5015
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5016
                                   "Failed to allocate PC_TREE");
5017
              node->split[i]->index = i;
5018
              tree_node_queue[last_idx] = node->split[i];
5019
              ++last_idx;
5020
            }
5021
          }
5022
          break;
5023
        case PARTITION_HORZ:
5024
        case PARTITION_VERT:
5025
          for (int i = 0; i < 2; ++i) {
5026
            if (node != NULL) {  // Suppress warning
5027
              node->split[i] = av1_alloc_pc_tree_node(subsize);
5028
              if (!node->split[i])
5029
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5030
                                   "Failed to allocate PC_TREE");
5031
              node->split[i]->index = i;
5032
              tree_node_queue[last_idx] = node->split[i];
5033
              ++last_idx;
5034
            }
5035
          }
5036
          break;
5037
        case PARTITION_HORZ_A:
5038
        case PARTITION_VERT_A:
5039
          if (node != NULL) {  // Suppress warning
5040
            node->split[0] = av1_alloc_pc_tree_node(subsize2);
5041
            node->split[1] = av1_alloc_pc_tree_node(subsize2);
5042
            node->split[2] = av1_alloc_pc_tree_node(subsize);
5043
            for (int i = 0; i < 3; ++i) {
5044
              if (!node->split[i])
5045
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5046
                                   "Failed to allocate PC_TREE");
5047
              node->split[i]->index = i;
5048
              tree_node_queue[last_idx] = node->split[i];
5049
              ++last_idx;
5050
            }
5051
          }
5052
          break;
5053
        case PARTITION_HORZ_B:
5054
        case PARTITION_VERT_B:
5055
          if (node != NULL) {  // Suppress warning
5056
            node->split[0] = av1_alloc_pc_tree_node(subsize);
5057
            node->split[1] = av1_alloc_pc_tree_node(subsize2);
5058
            node->split[2] = av1_alloc_pc_tree_node(subsize2);
5059
            for (int i = 0; i < 3; ++i) {
5060
              if (!node->split[i])
5061
                aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5062
                                   "Failed to allocate PC_TREE");
5063
              node->split[i]->index = i;
5064
              tree_node_queue[last_idx] = node->split[i];
5065
              ++last_idx;
5066
            }
5067
          }
5068
          break;
5069
        case PARTITION_NONE:
5070
        default:
5071
          // Should not hit this case.
5072
          assert(0);
5073
      }
5074
    }
5075
    --num_nodes;
5076
    ++q_idx;
5077
  }
5078
}
5079
5080
// The ML model needs to provide the whole decision tree for the superblock.
5081
static bool ml_partition_search_whole_tree(AV1_COMP *const cpi, ThreadData *td,
5082
                                           TileDataEnc *tile_data,
5083
                                           TokenExtra **tp,
5084
                                           SIMPLE_MOTION_DATA_TREE *sms_root,
5085
                                           int mi_row, int mi_col,
5086
                                           const BLOCK_SIZE bsize) {
5087
  AV1_COMMON *const cm = &cpi->common;
5088
  MACROBLOCK *const x = &td->mb;
5089
  ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
5090
  struct aom_internal_error_info *error_info = x->e_mbd.error_info;
5091
  aom_partition_features_t features;
5092
  prepare_sb_features_before_search(cpi, td, tile_data, mi_row, mi_col, bsize,
5093
                                    &features);
5094
  features.mi_row = mi_row;
5095
  features.mi_col = mi_col;
5096
  features.frame_width = cpi->frame_info.frame_width;
5097
  features.frame_height = cpi->frame_info.frame_height;
5098
  features.block_size = bsize;
5099
  av1_ext_part_send_features(ext_part_controller, &features);
5100
5101
  // rd mode search (dry run) for a valid partition decision from the ml model.
5102
  aom_partition_decision_t partition_decision;
5103
  do {
5104
    const bool valid_decision = av1_ext_part_get_partition_decision(
5105
        ext_part_controller, &partition_decision);
5106
    if (!valid_decision) return false;
5107
5108
    // First, let's take the easy approach.
5109
    // We require that the ml model has to provide partition decisions for the
5110
    // whole superblock.
5111
    td->pc_root = av1_alloc_pc_tree_node(bsize);
5112
    if (!td->pc_root)
5113
      aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
5114
                         "Failed to allocate PC_TREE");
5115
    build_pc_tree_from_part_decision(&partition_decision, bsize, td->pc_root,
5116
                                     error_info);
5117
5118
    const RD_STATS this_rdcost = rd_search_for_fixed_partition(
5119
        cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize, td->pc_root);
5120
    aom_partition_stats_t stats;
5121
    update_partition_stats(&this_rdcost, &stats);
5122
    av1_ext_part_send_partition_stats(ext_part_controller, &stats);
5123
    if (!partition_decision.is_final_decision) {
5124
      av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5125
                                 cpi->sf.part_sf.partition_search_type);
5126
      td->pc_root = NULL;
5127
    }
5128
  } while (!partition_decision.is_final_decision);
5129
5130
  // Encode with the selected mode and partition.
5131
  set_cb_offsets(x->cb_offset, 0, 0);
5132
  encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
5133
            td->pc_root, NULL);
5134
  av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5135
                             cpi->sf.part_sf.partition_search_type);
5136
  td->pc_root = NULL;
5137
5138
  return true;
5139
}
5140
5141
// Use a bitmask to represent the valid partition types for the current
5142
// block. "1" represents the corresponding partition type is vaild.
5143
// The least significant bit represents "PARTITION_NONE", the
5144
// largest significant bit represents "PARTITION_VERT_4", follow
5145
// the enum order for PARTITION_TYPE in "enums.h"
5146
static int get_valid_partition_types(
5147
    const AV1_COMP *const cpi,
5148
    const PartitionSearchState *const part_search_state,
5149
    const BLOCK_SIZE bsize) {
5150
  const PartitionCfg *const part_cfg = &cpi->oxcf.part_cfg;
5151
  const PartitionBlkParams blk_params = part_search_state->part_blk_params;
5152
  int valid_types = 0;
5153
  // PARTITION_NONE
5154
  valid_types |= (part_search_state->partition_none_allowed << 0);
5155
  // PARTITION_HORZ
5156
  valid_types |= (part_search_state->partition_rect_allowed[HORZ] << 1);
5157
  // PARTITION_VERT
5158
  valid_types |= (part_search_state->partition_rect_allowed[VERT] << 2);
5159
  // PARTITION_SPLIT
5160
  valid_types |= (part_search_state->do_square_split << 3);
5161
  // PARTITION_HORZ_A
5162
  const int ext_partition_allowed = part_search_state->do_rectangular_split &&
5163
                                    av1_blk_has_rows_and_cols(&blk_params);
5164
  const int horzab_partition_allowed =
5165
      ext_partition_allowed && part_cfg->enable_ab_partitions &&
5166
      part_search_state->partition_rect_allowed[HORZ];
5167
  valid_types |= (horzab_partition_allowed << 4);
5168
  // PARTITION_HORZ_B
5169
  valid_types |= (horzab_partition_allowed << 5);
5170
  // PARTITION_VERT_A
5171
  const int vertab_partition_allowed =
5172
      ext_partition_allowed && part_cfg->enable_ab_partitions &&
5173
      part_search_state->partition_rect_allowed[VERT];
5174
  valid_types |= (vertab_partition_allowed << 6);
5175
  // PARTITION_VERT_B
5176
  valid_types |= (vertab_partition_allowed << 7);
5177
  // PARTITION_HORZ_4
5178
  const int partition4_allowed = part_cfg->enable_1to4_partitions &&
5179
                                 ext_partition_allowed &&
5180
                                 bsize != BLOCK_128X128;
5181
  const int horz4_allowed =
5182
      partition4_allowed && part_search_state->partition_rect_allowed[HORZ] &&
5183
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_HORZ_4),
5184
                           part_search_state->ss_x,
5185
                           part_search_state->ss_y) != BLOCK_INVALID;
5186
  valid_types |= (horz4_allowed << 8);
5187
  // PARTITION_VERT_4
5188
  const int vert4_allowed =
5189
      partition4_allowed && part_search_state->partition_rect_allowed[HORZ] &&
5190
      get_plane_block_size(get_partition_subsize(bsize, PARTITION_VERT_4),
5191
                           part_search_state->ss_x,
5192
                           part_search_state->ss_y) != BLOCK_INVALID;
5193
  valid_types |= (vert4_allowed << 9);
5194
5195
  return valid_types;
5196
}
5197
5198
static void prepare_tpl_stats_block(const AV1_COMP *const cpi,
5199
                                    const BLOCK_SIZE bsize, const int mi_row,
5200
                                    const int mi_col, int64_t *intra_cost,
5201
                                    int64_t *inter_cost, int64_t *mc_dep_cost) {
5202
  const AV1_COMMON *const cm = &cpi->common;
5203
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
5204
  if (gf_group->update_type[cpi->gf_frame_index] == INTNL_OVERLAY_UPDATE ||
5205
      gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE) {
5206
    return;
5207
  }
5208
5209
  TplParams *const tpl_data = &cpi->ppi->tpl_data;
5210
  TplDepFrame *tpl_frame = &tpl_data->tpl_frame[cpi->gf_frame_index];
5211
  TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
5212
  // If tpl stats is not established, early return
5213
  if (!tpl_data->ready || gf_group->max_layer_depth_allowed == 0) {
5214
    return;
5215
  }
5216
5217
  const int tpl_stride = tpl_frame->stride;
5218
  const int step = 1 << tpl_data->tpl_stats_block_mis_log2;
5219
  const int mi_width =
5220
      AOMMIN(mi_size_wide[bsize], cm->mi_params.mi_cols - mi_col);
5221
  const int mi_height =
5222
      AOMMIN(mi_size_high[bsize], cm->mi_params.mi_rows - mi_row);
5223
5224
  int64_t sum_intra_cost = 0;
5225
  int64_t sum_inter_cost = 0;
5226
  int64_t sum_mc_dep_cost = 0;
5227
  for (int row = 0; row < mi_height; row += step) {
5228
    for (int col = 0; col < mi_width; col += step) {
5229
      TplDepStats *this_stats =
5230
          &tpl_stats[av1_tpl_ptr_pos(mi_row + row, mi_col + col, tpl_stride,
5231
                                     tpl_data->tpl_stats_block_mis_log2)];
5232
      sum_intra_cost += this_stats->intra_cost;
5233
      sum_inter_cost += this_stats->inter_cost;
5234
      const int64_t mc_dep_delta =
5235
          RDCOST(tpl_frame->base_rdmult, this_stats->mc_dep_rate,
5236
                 this_stats->mc_dep_dist);
5237
      sum_mc_dep_cost += mc_dep_delta;
5238
    }
5239
  }
5240
5241
  *intra_cost = sum_intra_cost;
5242
  *inter_cost = sum_inter_cost;
5243
  *mc_dep_cost = sum_mc_dep_cost;
5244
}
5245
5246
static bool recursive_partition(AV1_COMP *const cpi, ThreadData *td,
5247
                                TileDataEnc *tile_data, TokenExtra **tp,
5248
                                SIMPLE_MOTION_DATA_TREE *sms_root,
5249
                                PC_TREE *pc_tree, int mi_row, int mi_col,
5250
                                const BLOCK_SIZE bsize, RD_STATS *this_rdcost) {
5251
  const AV1_COMMON *const cm = &cpi->common;
5252
  ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
5253
  MACROBLOCK *const x = &td->mb;
5254
  MACROBLOCKD *const xd = &x->e_mbd;
5255
  if (mi_row >= cm->mi_params.mi_rows || mi_col >= cm->mi_params.mi_cols) {
5256
    return false;
5257
  }
5258
  aom_partition_decision_t partition_decision;
5259
  do {
5260
    PartitionSearchState part_search_state;
5261
    // Initialization of state variables used in partition search.
5262
    // TODO(chengchen): check if there is hidden conditions that don't allow
5263
    // all possible partition types.
5264
    init_partition_search_state_params(x, cpi, &part_search_state, mi_row,
5265
                                       mi_col, bsize);
5266
    // Override partition costs at the edges of the frame in the same
5267
    // way as in read_partition (see decodeframe.c).
5268
    PartitionBlkParams blk_params = part_search_state.part_blk_params;
5269
    if (!av1_blk_has_rows_and_cols(&blk_params))
5270
      set_partition_cost_for_edge_blk(cm, &part_search_state);
5271
    const int orig_rdmult = x->rdmult;
5272
    setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
5273
    const int valid_partition_types =
5274
        get_valid_partition_types(cpi, &part_search_state, bsize);
5275
    const FRAME_UPDATE_TYPE update_type =
5276
        get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
5277
    const int qindex = av1_get_qindex(&cm->seg, xd->mi[0]->segment_id,
5278
                                      cm->quant_params.base_qindex);
5279
    // RD multiplier
5280
    const int rdmult = x->rdmult;
5281
    // pyramid level
5282
    const int pyramid_level =
5283
        cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index];
5284
    x->rdmult = orig_rdmult;
5285
    // Neighbor information
5286
    const int has_above = !!xd->above_mbmi;
5287
    const int has_left = !!xd->left_mbmi;
5288
    const BLOCK_SIZE above_bsize =
5289
        has_above ? xd->above_mbmi->bsize : BLOCK_INVALID;
5290
    const BLOCK_SIZE left_bsize =
5291
        has_left ? xd->left_mbmi->bsize : BLOCK_INVALID;
5292
    const int above_block_width =
5293
        above_bsize == BLOCK_INVALID ? -1 : block_size_wide[above_bsize];
5294
    const int above_block_height =
5295
        above_bsize == BLOCK_INVALID ? -1 : block_size_high[above_bsize];
5296
    const int left_block_width =
5297
        left_bsize == BLOCK_INVALID ? -1 : block_size_wide[left_bsize];
5298
    const int left_block_height =
5299
        left_bsize == BLOCK_INVALID ? -1 : block_size_high[left_bsize];
5300
    // Prepare simple motion search stats as features
5301
    unsigned int block_sse = -1;
5302
    unsigned int block_var = -1;
5303
    unsigned int sub_block_sse[4] = { -1, -1, -1, -1 };
5304
    unsigned int sub_block_var[4] = { -1, -1, -1, -1 };
5305
    unsigned int horz_block_sse[2] = { -1, -1 };
5306
    unsigned int horz_block_var[2] = { -1, -1 };
5307
    unsigned int vert_block_sse[2] = { -1, -1 };
5308
    unsigned int vert_block_var[2] = { -1, -1 };
5309
    av1_prepare_motion_search_features_block(
5310
        cpi, td, tile_data, mi_row, mi_col, bsize, valid_partition_types,
5311
        &block_sse, &block_var, sub_block_sse, sub_block_var, horz_block_sse,
5312
        horz_block_var, vert_block_sse, vert_block_var);
5313
    // Prepare tpl stats for the current block as features
5314
    int64_t tpl_intra_cost = -1;
5315
    int64_t tpl_inter_cost = -1;
5316
    int64_t tpl_mc_dep_cost = -1;
5317
    prepare_tpl_stats_block(cpi, bsize, mi_row, mi_col, &tpl_intra_cost,
5318
                            &tpl_inter_cost, &tpl_mc_dep_cost);
5319
5320
    aom_partition_features_t features;
5321
    features.mi_row = mi_row;
5322
    features.mi_col = mi_col;
5323
    features.frame_width = cpi->frame_info.frame_width;
5324
    features.frame_height = cpi->frame_info.frame_height;
5325
    features.block_size = bsize;
5326
    features.valid_partition_types = valid_partition_types;
5327
    features.update_type = update_type;
5328
    features.qindex = qindex;
5329
    features.rdmult = rdmult;
5330
    features.pyramid_level = pyramid_level;
5331
    features.has_above_block = has_above;
5332
    features.above_block_width = above_block_width;
5333
    features.above_block_height = above_block_height;
5334
    features.has_left_block = has_left;
5335
    features.left_block_width = left_block_width;
5336
    features.left_block_height = left_block_height;
5337
    features.block_sse = block_sse;
5338
    features.block_var = block_var;
5339
    for (int i = 0; i < 4; ++i) {
5340
      features.sub_block_sse[i] = sub_block_sse[i];
5341
      features.sub_block_var[i] = sub_block_var[i];
5342
    }
5343
    for (int i = 0; i < 2; ++i) {
5344
      features.horz_block_sse[i] = horz_block_sse[i];
5345
      features.horz_block_var[i] = horz_block_var[i];
5346
      features.vert_block_sse[i] = vert_block_sse[i];
5347
      features.vert_block_var[i] = vert_block_var[i];
5348
    }
5349
    features.tpl_intra_cost = tpl_intra_cost;
5350
    features.tpl_inter_cost = tpl_inter_cost;
5351
    features.tpl_mc_dep_cost = tpl_mc_dep_cost;
5352
    av1_ext_part_send_features(ext_part_controller, &features);
5353
    const bool valid_decision = av1_ext_part_get_partition_decision(
5354
        ext_part_controller, &partition_decision);
5355
    if (!valid_decision) return false;
5356
    pc_tree->partitioning = partition_decision.current_decision;
5357
5358
    av1_init_rd_stats(this_rdcost);
5359
    if (partition_decision.current_decision == PARTITION_SPLIT) {
5360
      assert(block_size_wide[bsize] >= 8 && block_size_high[bsize] >= 8);
5361
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
5362
      RD_STATS split_rdc[SUB_PARTITIONS_SPLIT];
5363
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
5364
        av1_init_rd_stats(&split_rdc[i]);
5365
        if (pc_tree->split[i] == NULL)
5366
          pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
5367
        if (!pc_tree->split[i])
5368
          aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
5369
                             "Failed to allocate PC_TREE");
5370
        pc_tree->split[i]->index = i;
5371
      }
5372
      const int orig_rdmult_tmp = x->rdmult;
5373
      setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
5374
      // TODO(chengchen): check boundary conditions
5375
      // top-left
5376
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[0],
5377
                          mi_row, mi_col, subsize, &split_rdc[0]);
5378
      // top-right
5379
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[1],
5380
                          mi_row, mi_col + mi_size_wide[subsize], subsize,
5381
                          &split_rdc[1]);
5382
      // bottom-left
5383
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[2],
5384
                          mi_row + mi_size_high[subsize], mi_col, subsize,
5385
                          &split_rdc[2]);
5386
      // bottom_right
5387
      recursive_partition(cpi, td, tile_data, tp, sms_root, pc_tree->split[3],
5388
                          mi_row + mi_size_high[subsize],
5389
                          mi_col + mi_size_wide[subsize], subsize,
5390
                          &split_rdc[3]);
5391
      this_rdcost->rate += part_search_state.partition_cost[PARTITION_SPLIT];
5392
      // problem is here, the rdmult is different from the rdmult in sub block.
5393
      for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
5394
        this_rdcost->rate += split_rdc[i].rate;
5395
        this_rdcost->dist += split_rdc[i].dist;
5396
        av1_rd_cost_update(x->rdmult, this_rdcost);
5397
      }
5398
      x->rdmult = orig_rdmult_tmp;
5399
    } else {
5400
      *this_rdcost = rd_search_for_fixed_partition(
5401
          cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize, pc_tree);
5402
    }
5403
5404
    aom_partition_stats_t stats;
5405
    update_partition_stats(this_rdcost, &stats);
5406
    av1_ext_part_send_partition_stats(ext_part_controller, &stats);
5407
    if (!partition_decision.is_final_decision) {
5408
      if (partition_decision.current_decision == PARTITION_SPLIT) {
5409
        for (int i = 0; i < 4; ++i) {
5410
          if (pc_tree->split[i] != NULL) {
5411
            av1_free_pc_tree_recursive(pc_tree->split[i], av1_num_planes(cm), 0,
5412
                                       0,
5413
                                       cpi->sf.part_sf.partition_search_type);
5414
            pc_tree->split[i] = NULL;
5415
          }
5416
        }
5417
      }
5418
    }
5419
  } while (!partition_decision.is_final_decision);
5420
5421
  return true;
5422
}
5423
5424
// The ML model only needs to make decisions for the current block each time.
5425
static bool ml_partition_search_partial(AV1_COMP *const cpi, ThreadData *td,
5426
                                        TileDataEnc *tile_data, TokenExtra **tp,
5427
                                        SIMPLE_MOTION_DATA_TREE *sms_root,
5428
                                        int mi_row, int mi_col,
5429
                                        const BLOCK_SIZE bsize) {
5430
  AV1_COMMON *const cm = &cpi->common;
5431
  MACROBLOCK *const x = &td->mb;
5432
  ExtPartController *const ext_part_controller = &cpi->ext_part_controller;
5433
  aom_partition_features_t features;
5434
  prepare_sb_features_before_search(cpi, td, tile_data, mi_row, mi_col, bsize,
5435
                                    &features);
5436
  features.mi_row = mi_row;
5437
  features.mi_col = mi_col;
5438
  features.frame_width = cpi->frame_info.frame_width;
5439
  features.frame_height = cpi->frame_info.frame_height;
5440
  features.block_size = bsize;
5441
  av1_ext_part_send_features(ext_part_controller, &features);
5442
  td->pc_root = av1_alloc_pc_tree_node(bsize);
5443
  if (!td->pc_root)
5444
    aom_internal_error(x->e_mbd.error_info, AOM_CODEC_MEM_ERROR,
5445
                       "Failed to allocate PC_TREE");
5446
5447
  RD_STATS rdcost;
5448
  const bool valid_partition =
5449
      recursive_partition(cpi, td, tile_data, tp, sms_root, td->pc_root, mi_row,
5450
                          mi_col, bsize, &rdcost);
5451
  if (!valid_partition) {
5452
    return false;
5453
  }
5454
5455
  // Encode with the selected mode and partition.
5456
  set_cb_offsets(x->cb_offset, 0, 0);
5457
  encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
5458
            td->pc_root, NULL);
5459
  av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5460
                             cpi->sf.part_sf.partition_search_type);
5461
  td->pc_root = NULL;
5462
5463
  return true;
5464
}
5465
5466
bool av1_rd_partition_search(AV1_COMP *const cpi, ThreadData *td,
5467
                             TileDataEnc *tile_data, TokenExtra **tp,
5468
                             SIMPLE_MOTION_DATA_TREE *sms_root, int mi_row,
5469
                             int mi_col, const BLOCK_SIZE bsize,
5470
                             RD_STATS *best_rd_cost) {
5471
  AV1_COMMON *const cm = &cpi->common;
5472
  if (cpi->ext_part_controller.ready) {
5473
    bool valid_search = true;
5474
    const aom_ext_part_decision_mode_t decision_mode =
5475
        av1_get_ext_part_decision_mode(&cpi->ext_part_controller);
5476
    if (decision_mode == AOM_EXT_PART_WHOLE_TREE) {
5477
      valid_search = ml_partition_search_whole_tree(
5478
          cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize);
5479
    } else if (decision_mode == AOM_EXT_PART_RECURSIVE) {
5480
      valid_search = ml_partition_search_partial(
5481
          cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize);
5482
    } else {
5483
      assert(0 && "Unknown decision mode.");
5484
      return false;
5485
    }
5486
    if (!valid_search) {
5487
      aom_internal_error(
5488
          cm->error, AOM_CODEC_ERROR,
5489
          "Invalid search from ML model, partition search failed");
5490
    }
5491
    return true;
5492
  }
5493
5494
  MACROBLOCK *const x = &td->mb;
5495
  MACROBLOCKD *const xd = &x->e_mbd;
5496
  int best_idx = 0;
5497
  int64_t min_rdcost = INT64_MAX;
5498
  int num_configs;
5499
  int i = 0;
5500
  do {
5501
    td->pc_root = av1_alloc_pc_tree_node(bsize);
5502
    if (!td->pc_root)
5503
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
5504
                         "Failed to allocate PC_TREE");
5505
    num_configs = read_partition_tree(cpi, td->pc_root, xd->error_info, i);
5506
    if (num_configs <= 0) {
5507
      av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5508
                                 cpi->sf.part_sf.partition_search_type);
5509
      td->pc_root = NULL;
5510
      aom_internal_error(xd->error_info, AOM_CODEC_ERROR, "Invalid configs.");
5511
    }
5512
    verify_write_partition_tree(cpi, td->pc_root, bsize, i, mi_row, mi_col);
5513
    if (i == 0) {
5514
      AOM_CHECK_MEM_ERROR(xd->error_info, x->rdcost,
5515
                          aom_calloc(num_configs, sizeof(*x->rdcost)));
5516
    }
5517
    // Encode the block with the given partition tree. Get rdcost and encoding
5518
    // time.
5519
    x->rdcost[i] = rd_search_for_fixed_partition(
5520
        cpi, td, tile_data, tp, sms_root, mi_row, mi_col, bsize, td->pc_root);
5521
5522
    if (x->rdcost[i].rdcost < min_rdcost) {
5523
      min_rdcost = x->rdcost[i].rdcost;
5524
      best_idx = i;
5525
      *best_rd_cost = x->rdcost[i];
5526
    }
5527
    av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5528
                               cpi->sf.part_sf.partition_search_type);
5529
    td->pc_root = NULL;
5530
    ++i;
5531
  } while (i < num_configs);
5532
5533
  aom_free(x->rdcost);
5534
  x->rdcost = NULL;
5535
  // Encode with the partition configuration with the smallest rdcost.
5536
  td->pc_root = av1_alloc_pc_tree_node(bsize);
5537
  if (!td->pc_root)
5538
    aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
5539
                       "Failed to allocate PC_TREE");
5540
  read_partition_tree(cpi, td->pc_root, xd->error_info, best_idx);
5541
  rd_search_for_fixed_partition(cpi, td, tile_data, tp, sms_root, mi_row,
5542
                                mi_col, bsize, td->pc_root);
5543
  set_cb_offsets(x->cb_offset, 0, 0);
5544
  encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
5545
            td->pc_root, NULL);
5546
  av1_free_pc_tree_recursive(td->pc_root, av1_num_planes(cm), 0, 0,
5547
                             cpi->sf.part_sf.partition_search_type);
5548
  td->pc_root = NULL;
5549
  ++cpi->sb_counter;
5550
5551
  return true;
5552
}
5553
#endif  // CONFIG_PARTITION_SEARCH_ORDER
5554
5555
static inline bool should_do_dry_run_encode_for_current_block(
5556
    BLOCK_SIZE sb_size, BLOCK_SIZE max_partition_size, int curr_block_index,
5557
0
    BLOCK_SIZE bsize) {
5558
0
  if (bsize > max_partition_size) return false;
5559
5560
  // Enable the reconstruction with dry-run for the 4th sub-block only if its
5561
  // parent block's reconstruction with dry-run is skipped. If
5562
  // max_partition_size is the same as immediate split of superblock, then avoid
5563
  // reconstruction of the 4th sub-block, as this data is not consumed.
5564
0
  if (curr_block_index != 3) return true;
5565
5566
0
  const BLOCK_SIZE sub_sb_size =
5567
0
      get_partition_subsize(sb_size, PARTITION_SPLIT);
5568
0
  return bsize == max_partition_size && sub_sb_size != max_partition_size;
5569
0
}
5570
5571
static void log_sub_block_var(const AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bs,
5572
0
                              double *var_min, double *var_max) {
5573
  // This functions returns a the minimum and maximum log variances for 4x4
5574
  // sub blocks in the current block.
5575
5576
0
  const MACROBLOCKD *const xd = &x->e_mbd;
5577
0
  const int is_hbd = is_cur_buf_hbd(xd);
5578
0
  const int right_overflow =
5579
0
      (xd->mb_to_right_edge < 0) ? ((-xd->mb_to_right_edge) >> 3) : 0;
5580
0
  const int bottom_overflow =
5581
0
      (xd->mb_to_bottom_edge < 0) ? ((-xd->mb_to_bottom_edge) >> 3) : 0;
5582
0
  const int bw = MI_SIZE * mi_size_wide[bs] - right_overflow;
5583
0
  const int bh = MI_SIZE * mi_size_high[bs] - bottom_overflow;
5584
5585
  // Initialize minimum variance to a large value and maximum variance to 0.
5586
0
  double min_var_4x4 = (double)INT_MAX;
5587
0
  double max_var_4x4 = 0.0;
5588
5589
0
  aom_variance_fn_t vf = cpi->ppi->fn_ptr[BLOCK_4X4].vf;
5590
0
  for (int i = 0; i < bh; i += MI_SIZE) {
5591
0
    for (int j = 0; j < bw; j += MI_SIZE) {
5592
0
      int var;
5593
      // Calculate the 4x4 sub-block variance.
5594
0
      var = av1_calc_normalized_variance(
5595
0
          vf, x->plane[0].src.buf + (i * x->plane[0].src.stride) + j,
5596
0
          x->plane[0].src.stride, is_hbd);
5597
5598
      // Record min and max for over-arching block
5599
0
      min_var_4x4 = AOMMIN(min_var_4x4, var);
5600
0
      max_var_4x4 = AOMMAX(max_var_4x4, var);
5601
0
    }
5602
0
  }
5603
0
  *var_min = log1p(min_var_4x4 / 16.0);
5604
0
  *var_max = log1p(max_var_4x4 / 16.0);
5605
0
}
5606
5607
static inline void set_sms_tree_partitioning(SIMPLE_MOTION_DATA_TREE *sms_tree,
5608
0
                                             PARTITION_TYPE partition) {
5609
0
  if (sms_tree == NULL) return;
5610
0
  sms_tree->partitioning = partition;
5611
0
}
5612
5613
/*!\brief AV1 block partition search (full search).
5614
*
5615
* \ingroup partition_search
5616
* \callgraph
5617
* Searches for the best partition pattern for a block based on the
5618
* rate-distortion cost, and returns a bool value to indicate whether a valid
5619
* partition pattern is found. The partition can recursively go down to the
5620
* smallest block size.
5621
*
5622
* \param[in]    cpi                Top-level encoder structure
5623
* \param[in]    td                 Pointer to thread data
5624
* \param[in]    tile_data          Pointer to struct holding adaptive
5625
data/contexts/models for the tile during
5626
encoding
5627
* \param[in]    tp                 Pointer to the starting token
5628
* \param[in]    mi_row             Row coordinate of the block in a step size
5629
of MI_SIZE
5630
* \param[in]    mi_col             Column coordinate of the block in a step
5631
size of MI_SIZE
5632
* \param[in]    bsize              Current block size
5633
* \param[in]    rd_cost            Pointer to the final rd cost of the block
5634
* \param[in]    best_rdc           Upper bound of rd cost of a valid partition
5635
* \param[in]    pc_tree            Pointer to the PC_TREE node storing the
5636
picked partitions and mode info for the
5637
current block
5638
* \param[in]    sms_tree           Pointer to struct holding simple motion
5639
search data for the current block
5640
* \param[in]    none_rd            Pointer to the rd cost in the case of not
5641
splitting the current block
5642
* \param[in]    multi_pass_mode    SB_SINGLE_PASS/SB_DRY_PASS/SB_WET_PASS
5643
* \param[in]    rect_part_win_info Pointer to struct storing whether horz/vert
5644
partition outperforms previously tested
5645
partitions
5646
*
5647
* \return A bool value is returned indicating if a valid partition is found.
5648
* The pc_tree struct is modified to store the picked partition and modes.
5649
* The rd_cost struct is also updated with the RD stats corresponding to the
5650
* best partition found.
5651
*/
5652
bool av1_rd_pick_partition(AV1_COMP *const cpi, ThreadData *td,
5653
                           TileDataEnc *tile_data, TokenExtra **tp, int mi_row,
5654
                           int mi_col, BLOCK_SIZE bsize, RD_STATS *rd_cost,
5655
                           RD_STATS best_rdc, PC_TREE *pc_tree,
5656
                           SIMPLE_MOTION_DATA_TREE *sms_tree, int64_t *none_rd,
5657
                           SB_MULTI_PASS_MODE multi_pass_mode,
5658
0
                           RD_RECT_PART_WIN_INFO *rect_part_win_info) {
5659
0
  const AV1_COMMON *const cm = &cpi->common;
5660
0
  const int num_planes = av1_num_planes(cm);
5661
0
  TileInfo *const tile_info = &tile_data->tile_info;
5662
0
  MACROBLOCK *const x = &td->mb;
5663
0
  MACROBLOCKD *const xd = &x->e_mbd;
5664
0
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
5665
0
  const TokenExtra *const tp_orig = *tp;
5666
0
  PartitionSearchState part_search_state;
5667
5668
  // Initialization of state variables used in partition search.
5669
0
  init_partition_search_state_params(x, cpi, &part_search_state, mi_row, mi_col,
5670
0
                                     bsize);
5671
0
  PartitionBlkParams blk_params = part_search_state.part_blk_params;
5672
5673
0
  set_sms_tree_partitioning(sms_tree, PARTITION_NONE);
5674
0
  if (best_rdc.rdcost < 0) {
5675
0
    av1_invalid_rd_stats(rd_cost);
5676
0
    return part_search_state.found_best_partition;
5677
0
  }
5678
0
  if (bsize == cm->seq_params->sb_size) x->must_find_valid_partition = 0;
5679
5680
  // Override skipping rectangular partition operations for edge blocks.
5681
0
  if (none_rd) *none_rd = 0;
5682
0
  (void)*tp_orig;
5683
5684
#if CONFIG_COLLECT_PARTITION_STATS
5685
  // Stats at the current quad tree
5686
  PartitionTimingStats *part_timing_stats =
5687
      &part_search_state.part_timing_stats;
5688
  // Stats aggregated at frame level
5689
  FramePartitionTimingStats *fr_part_timing_stats = &cpi->partition_stats;
5690
#endif  // CONFIG_COLLECT_PARTITION_STATS
5691
5692
  // Override partition costs at the edges of the frame in the same
5693
  // way as in read_partition (see decodeframe.c).
5694
0
  if (!av1_blk_has_rows_and_cols(&blk_params))
5695
0
    set_partition_cost_for_edge_blk(cm, &part_search_state);
5696
5697
  // Disable rectangular partitions for inner blocks when the current block is
5698
  // forced to only use square partitions.
5699
0
  if (bsize > cpi->sf.part_sf.use_square_partition_only_threshold) {
5700
0
    part_search_state.partition_rect_allowed[HORZ] &= !blk_params.has_rows;
5701
0
    part_search_state.partition_rect_allowed[VERT] &= !blk_params.has_cols;
5702
0
  }
5703
5704
0
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);
5705
5706
  // Set buffers and offsets.
5707
0
  av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
5708
5709
0
  if (cpi->oxcf.mode == ALLINTRA) {
5710
0
    if (bsize == cm->seq_params->sb_size) {
5711
0
      double var_min, var_max;
5712
0
      log_sub_block_var(cpi, x, bsize, &var_min, &var_max);
5713
5714
0
      x->intra_sb_rdmult_modifier = 128;
5715
0
      if ((var_min < 2.0) && (var_max > 4.0)) {
5716
0
        if ((var_max - var_min) > 8.0) {
5717
0
          x->intra_sb_rdmult_modifier -= 48;
5718
0
        } else {
5719
0
          x->intra_sb_rdmult_modifier -= (int)((var_max - var_min) * 6);
5720
0
        }
5721
0
      }
5722
0
    }
5723
0
  }
5724
5725
  // Save rdmult before it might be changed, so it can be restored later.
5726
0
  const int orig_rdmult = x->rdmult;
5727
0
  setup_block_rdmult(cpi, x, mi_row, mi_col, bsize, NO_AQ, NULL);
5728
5729
  // Apply simple motion search for the entire super block with fixed block
5730
  // size, e.g., 16x16, to collect features and write to files for the
5731
  // external ML model.
5732
  // TODO(chengchen): reduce motion search. This function is similar to
5733
  // av1_get_max_min_partition_features().
5734
#if COLLECT_MOTION_SEARCH_FEATURE_SB
5735
  if (!frame_is_intra_only(cm) && bsize == cm->seq_params->sb_size) {
5736
    av1_collect_motion_search_features_sb(cpi, td, tile_data, mi_row, mi_col,
5737
                                          bsize, /*features=*/NULL);
5738
    collect_tpl_stats_sb(cpi, bsize, mi_row, mi_col, /*features=*/NULL);
5739
  }
5740
#endif  // !COLLECT_MOTION_SEARCH_FEATURE_SB
5741
5742
  // Update rd cost of the bound using the current multiplier.
5743
0
  av1_rd_cost_update(x->rdmult, &best_rdc);
5744
5745
0
  if (bsize == BLOCK_16X16 && cpi->vaq_refresh)
5746
0
    x->mb_energy = av1_log_block_var(cpi, x, bsize);
5747
5748
  // Set the context.
5749
0
  xd->above_txfm_context =
5750
0
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
5751
0
  xd->left_txfm_context =
5752
0
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
5753
0
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, num_planes);
5754
5755
#if CONFIG_COLLECT_COMPONENT_TIMING
5756
  start_timing(cpi, av1_prune_partitions_time);
5757
#endif
5758
  // Pruning: before searching any partition type, using source and simple
5759
  // motion search results to prune out unlikely partitions.
5760
0
  av1_prune_partitions_before_search(cpi, x, sms_tree, &part_search_state);
5761
5762
  // Pruning: eliminating partition types leading to coding block sizes outside
5763
  // the min and max bsize limitations set from the encoder.
5764
0
  av1_prune_partitions_by_max_min_bsize(&x->sb_enc, &part_search_state);
5765
#if CONFIG_COLLECT_COMPONENT_TIMING
5766
  end_timing(cpi, av1_prune_partitions_time);
5767
#endif
5768
5769
  // Partition search
5770
0
BEGIN_PARTITION_SEARCH:
5771
  // If a valid partition is required, usually when the first round cannot find
5772
  // a valid one under the cost limit after pruning, reset the limitations on
5773
  // partition types and intra cnn output.
5774
0
  if (x->must_find_valid_partition) {
5775
0
    reset_part_limitations(cpi, &part_search_state);
5776
0
    av1_prune_partitions_by_max_min_bsize(&x->sb_enc, &part_search_state);
5777
    // Invalidate intra cnn output for key frames.
5778
0
    if (frame_is_intra_only(cm) && bsize == BLOCK_64X64) {
5779
0
      part_search_state.intra_part_info->quad_tree_idx = 0;
5780
0
      part_search_state.intra_part_info->cnn_output_valid = 0;
5781
0
    }
5782
0
  }
5783
  // Partition block source pixel variance.
5784
0
  unsigned int pb_source_variance = UINT_MAX;
5785
5786
#if CONFIG_COLLECT_COMPONENT_TIMING
5787
  start_timing(cpi, none_partition_search_time);
5788
#endif
5789
5790
0
  if (cpi->oxcf.mode == ALLINTRA) {
5791
0
    const bool bsize_at_least_16x16 = (bsize >= BLOCK_16X16);
5792
0
    const bool prune_rect_part_using_4x4_var_deviation =
5793
0
        (cpi->sf.part_sf.prune_rect_part_using_4x4_var_deviation &&
5794
0
         !x->must_find_valid_partition);
5795
5796
0
    if (bsize_at_least_16x16 || prune_rect_part_using_4x4_var_deviation) {
5797
0
      double var_min, var_max;
5798
0
      log_sub_block_var(cpi, x, bsize, &var_min, &var_max);
5799
5800
      // Further pruning or in some cases reverse pruning when allintra is set.
5801
      // This code helps visual and in some cases metrics quality where the
5802
      // current block comprises at least one very low variance sub-block and at
5803
      // least one where the variance is much higher.
5804
      //
5805
      // The idea is that in such cases there is danger of ringing and other
5806
      // visual artifacts from a high variance feature such as an edge into a
5807
      // very low variance region.
5808
      //
5809
      // The approach taken is to force break down / split to a smaller block
5810
      // size to try and separate out the low variance and well predicted blocks
5811
      // from the more complex ones and to prevent propagation of ringing over a
5812
      // large region.
5813
0
      if (bsize_at_least_16x16 && (var_min < 0.272) &&
5814
0
          ((var_max - var_min) > 3.0)) {
5815
0
        part_search_state.partition_none_allowed = 0;
5816
0
        part_search_state.terminate_partition_search = 0;
5817
0
        part_search_state.do_square_split = 1;
5818
0
      } else if (prune_rect_part_using_4x4_var_deviation &&
5819
0
                 (var_max - var_min < 3.0)) {
5820
        // Prune rectangular partitions if the variance deviation of 4x4
5821
        // sub-blocks within the block is less than a threshold (derived
5822
        // empirically).
5823
0
        part_search_state.do_rectangular_split = 0;
5824
0
      }
5825
0
    }
5826
0
  }
5827
5828
  // PARTITION_NONE search stage.
5829
0
  int64_t part_none_rd = INT64_MAX;
5830
0
  none_partition_search(cpi, td, tile_data, x, pc_tree, sms_tree, &x_ctx,
5831
0
                        &part_search_state, &best_rdc, &pb_source_variance,
5832
0
                        none_rd, &part_none_rd);
5833
5834
#if CONFIG_COLLECT_COMPONENT_TIMING
5835
  end_timing(cpi, none_partition_search_time);
5836
#endif
5837
#if CONFIG_COLLECT_COMPONENT_TIMING
5838
  start_timing(cpi, split_partition_search_time);
5839
#endif
5840
  // PARTITION_SPLIT search stage.
5841
0
  int64_t part_split_rd = INT64_MAX;
5842
0
  split_partition_search(cpi, td, tile_data, tp, x, pc_tree, sms_tree, &x_ctx,
5843
0
                         &part_search_state, &best_rdc, multi_pass_mode,
5844
0
                         &part_split_rd);
5845
#if CONFIG_COLLECT_COMPONENT_TIMING
5846
  end_timing(cpi, split_partition_search_time);
5847
#endif
5848
  // Terminate partition search for child partition,
5849
  // when NONE and SPLIT partition rd_costs are INT64_MAX.
5850
0
  if (cpi->sf.part_sf.early_term_after_none_split &&
5851
0
      part_none_rd == INT64_MAX && part_split_rd == INT64_MAX &&
5852
0
      !x->must_find_valid_partition && (bsize != cm->seq_params->sb_size)) {
5853
0
    part_search_state.terminate_partition_search = 1;
5854
0
  }
5855
5856
  // Do not evaluate non-square partitions if NONE partition did not choose a
5857
  // newmv mode and is skippable.
5858
0
  if ((cpi->sf.part_sf.skip_non_sq_part_based_on_none >= 2) &&
5859
0
      (pc_tree->none != NULL)) {
5860
0
    if (x->qindex <= 200 && is_inter_mode(pc_tree->none->mic.mode) &&
5861
0
        !have_newmv_in_inter_mode(pc_tree->none->mic.mode) &&
5862
0
        pc_tree->none->skippable && !x->must_find_valid_partition &&
5863
0
        bsize >= BLOCK_16X16)
5864
0
      part_search_state.do_rectangular_split = 0;
5865
0
  }
5866
5867
  // Prune partitions based on PARTITION_NONE and PARTITION_SPLIT.
5868
0
  prune_partitions_after_split(cpi, x, sms_tree, &part_search_state, &best_rdc,
5869
0
                               part_none_rd, part_split_rd);
5870
#if CONFIG_COLLECT_COMPONENT_TIMING
5871
  start_timing(cpi, rectangular_partition_search_time);
5872
#endif
5873
  // Rectangular partitions search stage.
5874
0
  rectangular_partition_search(cpi, td, tile_data, tp, x, pc_tree, &x_ctx,
5875
0
                               &part_search_state, &best_rdc,
5876
0
                               rect_part_win_info, HORZ, VERT);
5877
#if CONFIG_COLLECT_COMPONENT_TIMING
5878
  end_timing(cpi, rectangular_partition_search_time);
5879
#endif
5880
5881
0
  if (pb_source_variance == UINT_MAX) {
5882
0
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, num_planes, bsize);
5883
0
    pb_source_variance = av1_get_perpixel_variance_facade(
5884
0
        cpi, xd, &x->plane[0].src, bsize, AOM_PLANE_Y);
5885
0
  }
5886
5887
0
  assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
5888
0
                 !part_search_state.do_rectangular_split));
5889
5890
0
  const int prune_ext_part_state = prune_ext_part_none_skippable(
5891
0
      pc_tree->none, x->must_find_valid_partition,
5892
0
      cpi->sf.part_sf.skip_non_sq_part_based_on_none, bsize);
5893
5894
0
  const int ab_partition_allowed = allow_ab_partition_search(
5895
0
      &part_search_state, &cpi->sf.part_sf, pc_tree->partitioning,
5896
0
      x->must_find_valid_partition, prune_ext_part_state, best_rdc.rdcost);
5897
5898
#if CONFIG_COLLECT_COMPONENT_TIMING
5899
  start_timing(cpi, ab_partitions_search_time);
5900
#endif
5901
  // AB partitions search stage.
5902
0
  ab_partitions_search(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
5903
0
                       &part_search_state, &best_rdc, rect_part_win_info,
5904
0
                       pb_source_variance, ab_partition_allowed, HORZ_A,
5905
0
                       VERT_B);
5906
#if CONFIG_COLLECT_COMPONENT_TIMING
5907
  end_timing(cpi, ab_partitions_search_time);
5908
#endif
5909
5910
  // 4-way partitions search stage.
5911
0
  int part4_search_allowed[NUM_PART4_TYPES] = { 1, 1 };
5912
  // Prune 4-way partition search.
5913
0
  prune_4_way_partition_search(cpi, x, pc_tree, &part_search_state, sms_tree,
5914
0
                               &best_rdc, pb_source_variance,
5915
0
                               prune_ext_part_state, mi_row, mi_col,
5916
0
                               part4_search_allowed);
5917
5918
#if CONFIG_COLLECT_COMPONENT_TIMING
5919
  start_timing(cpi, rd_pick_4partition_time);
5920
#endif
5921
  // PARTITION_HORZ_4
5922
0
  assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
5923
0
                 !part4_search_allowed[HORZ4]));
5924
0
  if (!part_search_state.terminate_partition_search &&
5925
0
      part4_search_allowed[HORZ4]) {
5926
0
    const int inc_step[NUM_PART4_TYPES] = { mi_size_high[blk_params.bsize] / 4,
5927
0
                                            0 };
5928
    // Evaluation of Horz4 partition type.
5929
0
    rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
5930
0
                       pc_tree->horizontal4, &part_search_state, &best_rdc,
5931
0
                       inc_step, PARTITION_HORZ_4);
5932
0
  }
5933
5934
  // PARTITION_VERT_4
5935
0
  assert(IMPLIES(!cpi->oxcf.part_cfg.enable_rect_partitions,
5936
0
                 !part4_search_allowed[VERT4]));
5937
0
  if (!part_search_state.terminate_partition_search &&
5938
0
      part4_search_allowed[VERT4] && blk_params.has_cols) {
5939
0
    const int inc_step[NUM_PART4_TYPES] = { 0, mi_size_wide[blk_params.bsize] /
5940
0
                                                   4 };
5941
    // Evaluation of Vert4 partition type.
5942
0
    rd_pick_4partition(cpi, td, tile_data, tp, x, &x_ctx, pc_tree,
5943
0
                       pc_tree->vertical4, &part_search_state, &best_rdc,
5944
0
                       inc_step, PARTITION_VERT_4);
5945
0
  }
5946
#if CONFIG_COLLECT_COMPONENT_TIMING
5947
  end_timing(cpi, rd_pick_4partition_time);
5948
#endif
5949
5950
0
  if (bsize == cm->seq_params->sb_size &&
5951
0
      !part_search_state.found_best_partition) {
5952
    // Did not find a valid partition, go back and search again, with less
5953
    // constraint on which partition types to search.
5954
0
    x->must_find_valid_partition = 1;
5955
#if CONFIG_COLLECT_PARTITION_STATS
5956
    fr_part_timing_stats->partition_redo += 1;
5957
#endif  // CONFIG_COLLECT_PARTITION_STATS
5958
0
    goto BEGIN_PARTITION_SEARCH;
5959
0
  }
5960
5961
  // Store the final rd cost
5962
0
  *rd_cost = best_rdc;
5963
5964
  // Also record the best partition in simple motion data tree because it is
5965
  // necessary for the related speed features.
5966
0
  set_sms_tree_partitioning(sms_tree, pc_tree->partitioning);
5967
5968
#if CONFIG_COLLECT_PARTITION_STATS
5969
  if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX) {
5970
    part_timing_stats->partition_decisions[pc_tree->partitioning] += 1;
5971
  }
5972
5973
  // If CONFIG_COLLECT_PARTITION_STATS is 1, then print out the stats for each
5974
  // prediction block.
5975
  print_partition_timing_stats_with_rdcost(
5976
      part_timing_stats, mi_row, mi_col, bsize,
5977
      cpi->ppi->gf_group.update_type[cpi->gf_frame_index],
5978
      cm->current_frame.frame_number, &best_rdc, "part_timing.csv");
5979
  const bool print_timing_stats = false;
5980
  if (print_timing_stats) {
5981
    print_partition_timing_stats(part_timing_stats, cm->show_frame,
5982
                                 frame_is_intra_only(cm), bsize,
5983
                                 "part_timing_data.csv");
5984
  }
5985
  // If CONFIG_COLLECTION_PARTITION_STATS is 2, then we print out the stats for
5986
  // the whole clip. So we need to pass the information upstream to the encoder.
5987
  accumulate_partition_timing_stats(fr_part_timing_stats, part_timing_stats,
5988
                                    bsize);
5989
#endif  // CONFIG_COLLECT_PARTITION_STATS
5990
5991
  // Reset the PC_TREE deallocation flag.
5992
0
  int pc_tree_dealloc = 0;
5993
5994
#if CONFIG_COLLECT_COMPONENT_TIMING
5995
  start_timing(cpi, encode_sb_time);
5996
#endif
5997
0
  if (part_search_state.found_best_partition) {
5998
0
    if (bsize == cm->seq_params->sb_size) {
5999
      // Encode the superblock.
6000
0
      const int emit_output = multi_pass_mode != SB_DRY_PASS;
6001
0
      const RUN_TYPE run_type = emit_output ? OUTPUT_ENABLED : DRY_RUN_NORMAL;
6002
6003
#if COLLECT_MOTION_SEARCH_FEATURE_SB
6004
      // Write partition tree to file. Not used by default.
6005
      write_partition_tree(cpi, pc_tree, bsize, mi_row, mi_col);
6006
      ++cpi->sb_counter;
6007
#endif  // COLLECT_MOTION_SEARCH_FEATURE_SB
6008
0
      set_cb_offsets(x->cb_offset, 0, 0);
6009
0
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, run_type, bsize,
6010
0
                pc_tree, NULL);
6011
0
      assert(pc_tree == td->pc_root);
6012
      // Dealloc the whole PC_TREE after a superblock is done.
6013
0
      av1_free_pc_tree_recursive(pc_tree, num_planes, 0, 0,
6014
0
                                 cpi->sf.part_sf.partition_search_type);
6015
0
      pc_tree = NULL;
6016
0
      td->pc_root = NULL;
6017
0
      pc_tree_dealloc = 1;
6018
0
    } else if (should_do_dry_run_encode_for_current_block(
6019
0
                   cm->seq_params->sb_size, x->sb_enc.max_partition_size,
6020
0
                   pc_tree->index, bsize)) {
6021
      // Encode the smaller blocks in DRY_RUN mode.
6022
0
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_NORMAL, bsize,
6023
0
                pc_tree, NULL);
6024
0
    }
6025
0
  }
6026
#if CONFIG_COLLECT_COMPONENT_TIMING
6027
  end_timing(cpi, encode_sb_time);
6028
#endif
6029
6030
  // If the tree still exists (non-superblock), dealloc most nodes, only keep
6031
  // nodes for the best partition and PARTITION_NONE.
6032
0
  if (pc_tree_dealloc == 0)
6033
0
    av1_free_pc_tree_recursive(pc_tree, num_planes, 1, 1,
6034
0
                               cpi->sf.part_sf.partition_search_type);
6035
6036
0
  if (bsize == cm->seq_params->sb_size) {
6037
0
    assert(best_rdc.rate < INT_MAX);
6038
0
    assert(best_rdc.dist < INT64_MAX);
6039
0
  } else {
6040
0
    assert(tp_orig == *tp);
6041
0
  }
6042
6043
  // Restore the rd multiplier.
6044
0
  x->rdmult = orig_rdmult;
6045
0
  return part_search_state.found_best_partition;
6046
0
}
6047
#endif  // !CONFIG_REALTIME_ONLY
6048
6049
#undef COLLECT_MOTION_SEARCH_FEATURE_SB
6050
6051
#if CONFIG_RT_ML_PARTITIONING
6052
#define FEATURES 6
6053
#define LABELS 2
6054
static int ml_predict_var_partitioning(AV1_COMP *cpi, MACROBLOCK *x,
6055
                                       BLOCK_SIZE bsize, int mi_row,
6056
                                       int mi_col) {
6057
  AV1_COMMON *const cm = &cpi->common;
6058
  const NN_CONFIG *nn_config = NULL;
6059
  const float *means = NULL;
6060
  const float *vars = NULL;
6061
  switch (bsize) {
6062
    case BLOCK_64X64:
6063
      nn_config = &av1_var_part_nnconfig_64;
6064
      means = av1_var_part_means_64;
6065
      vars = av1_var_part_vars_64;
6066
      break;
6067
    case BLOCK_32X32:
6068
      nn_config = &av1_var_part_nnconfig_32;
6069
      means = av1_var_part_means_32;
6070
      vars = av1_var_part_vars_32;
6071
      break;
6072
    case BLOCK_16X16:
6073
      nn_config = &av1_var_part_nnconfig_16;
6074
      means = av1_var_part_means_16;
6075
      vars = av1_var_part_vars_16;
6076
      break;
6077
    case BLOCK_8X8:
6078
    default: assert(0 && "Unexpected block size."); return -1;
6079
  }
6080
6081
  if (!nn_config) return -1;
6082
6083
  {
6084
    const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
6085
    float features[FEATURES] = { 0.0f };
6086
    const int dc_q = av1_dc_quant_QTX(cm->quant_params.base_qindex, 0,
6087
                                      cm->seq_params->bit_depth);
6088
    int feature_idx = 0;
6089
    float score[LABELS];
6090
6091
    features[feature_idx] =
6092
        (log1pf((float)(dc_q * dc_q) / 256.0f) - means[feature_idx]) /
6093
        sqrtf(vars[feature_idx]);
6094
    feature_idx++;
6095
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, 1, bsize);
6096
    {
6097
      const int bs = block_size_wide[bsize];
6098
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
6099
      const int sb_offset_row = 4 * (mi_row & 15);
6100
      const int sb_offset_col = 4 * (mi_col & 15);
6101
      const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
6102
      const uint8_t *src = x->plane[0].src.buf;
6103
      const int src_stride = x->plane[0].src.stride;
6104
      const int pred_stride = 64;
6105
      unsigned int sse;
6106
      int i;
6107
      // Variance of whole block.
6108
      const unsigned int var =
6109
          cpi->ppi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
6110
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
6111
6112
      features[feature_idx] =
6113
          (log1pf((float)var) - means[feature_idx]) / sqrtf(vars[feature_idx]);
6114
      feature_idx++;
6115
      for (i = 0; i < 4; ++i) {
6116
        const int x_idx = (i & 1) * bs / 2;
6117
        const int y_idx = (i >> 1) * bs / 2;
6118
        const int src_offset = y_idx * src_stride + x_idx;
6119
        const int pred_offset = y_idx * pred_stride + x_idx;
6120
        // Variance of quarter block.
6121
        const unsigned int sub_var =
6122
            cpi->ppi->fn_ptr[subsize].vf(src + src_offset, src_stride,
6123
                                         pred + pred_offset, pred_stride, &sse);
6124
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
6125
        features[feature_idx] =
6126
            (var_ratio - means[feature_idx]) / sqrtf(vars[feature_idx]);
6127
        feature_idx++;
6128
      }
6129
    }
6130
    //    for (int i = 0; i<FEATURES; i++)
6131
    //      printf("F_%d, %f; ", i, features[i]);
6132
    assert(feature_idx == FEATURES);
6133
    av1_nn_predict(features, nn_config, 1, score);
6134
    //    printf("Score %f, thr %f ", (float)score[0], thresh);
6135
    if (score[0] > thresh) return PARTITION_SPLIT;
6136
    if (score[0] < -thresh) return PARTITION_NONE;
6137
    return -1;
6138
  }
6139
}
6140
#undef FEATURES
6141
#undef LABELS
6142
6143
// Uncomment for collecting data for ML-based partitioning
6144
// #define _COLLECT_GROUND_TRUTH_
6145
6146
#ifdef _COLLECT_GROUND_TRUTH_
6147
static int store_partition_data(AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
6148
                                int mi_row, int mi_col, PARTITION_TYPE part) {
6149
  AV1_COMMON *const cm = &cpi->common;
6150
  char fname[128];
6151
  switch (bsize) {
6152
    case BLOCK_64X64: sprintf(fname, "data_64x64.txt"); break;
6153
    case BLOCK_32X32: sprintf(fname, "data_32x32.txt"); break;
6154
    case BLOCK_16X16: sprintf(fname, "data_16x16.txt"); break;
6155
    case BLOCK_8X8: sprintf(fname, "data_8x8.txt"); break;
6156
    default: assert(0 && "Unexpected block size."); return -1;
6157
  }
6158
6159
  float features[6];  // DC_Q, VAR, VAR_RATIO-0..3
6160
6161
  FILE *f = fopen(fname, "a");
6162
6163
  {
6164
    const int dc_q = av1_dc_quant_QTX(cm->quant_params.base_qindex, 0,
6165
                                      cm->seq_params->bit_depth);
6166
    int feature_idx = 0;
6167
6168
    features[feature_idx++] = log1pf((float)(dc_q * dc_q) / 256.0f);
6169
    av1_setup_src_planes(x, cpi->source, mi_row, mi_col, 1, bsize);
6170
    {
6171
      const int bs = block_size_wide[bsize];
6172
      const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
6173
      const int sb_offset_row = 4 * (mi_row & 15);
6174
      const int sb_offset_col = 4 * (mi_col & 15);
6175
      const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
6176
      const uint8_t *src = x->plane[0].src.buf;
6177
      const int src_stride = x->plane[0].src.stride;
6178
      const int pred_stride = 64;
6179
      unsigned int sse;
6180
      int i;
6181
      // Variance of whole block.
6182
      /*
6183
                if (bs == 8)
6184
                {
6185
                  int r, c;
6186
                  printf("%d %d\n", mi_row, mi_col);
6187
                  for (r = 0; r < bs; ++r) {
6188
                    for (c = 0; c < bs; ++c) {
6189
                      printf("%3d ",
6190
                             src[r * src_stride + c] - pred[64 * r + c]);
6191
                    }
6192
                    printf("\n");
6193
                  }
6194
                  printf("\n");
6195
                }
6196
      */
6197
      const unsigned int var =
6198
          cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
6199
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
6200
6201
      features[feature_idx++] = log1pf((float)var);
6202
6203
      fprintf(f, "%f,%f,", features[0], features[1]);
6204
      for (i = 0; i < 4; ++i) {
6205
        const int x_idx = (i & 1) * bs / 2;
6206
        const int y_idx = (i >> 1) * bs / 2;
6207
        const int src_offset = y_idx * src_stride + x_idx;
6208
        const int pred_offset = y_idx * pred_stride + x_idx;
6209
        // Variance of quarter block.
6210
        const unsigned int sub_var =
6211
            cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
6212
                                    pred + pred_offset, pred_stride, &sse);
6213
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
6214
        features[feature_idx++] = var_ratio;
6215
        fprintf(f, "%f,", var_ratio);
6216
      }
6217
6218
      fprintf(f, "%d\n", part == PARTITION_NONE ? 0 : 1);
6219
    }
6220
6221
    fclose(f);
6222
    return -1;
6223
  }
6224
}
6225
#endif
6226
6227
static void duplicate_mode_info_in_sb(AV1_COMMON *cm, MACROBLOCKD *xd,
6228
                                      int mi_row, int mi_col,
6229
                                      BLOCK_SIZE bsize) {
6230
  const int block_width =
6231
      AOMMIN(mi_size_wide[bsize], cm->mi_params.mi_cols - mi_col);
6232
  const int block_height =
6233
      AOMMIN(mi_size_high[bsize], cm->mi_params.mi_rows - mi_row);
6234
  const int mi_stride = xd->mi_stride;
6235
  MB_MODE_INFO *const src_mi = xd->mi[0];
6236
  int i, j;
6237
6238
  for (j = 0; j < block_height; ++j)
6239
    for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
6240
}
6241
6242
static inline void copy_mbmi_ext_frame_to_mbmi_ext(
6243
    MB_MODE_INFO_EXT *const mbmi_ext,
6244
    const MB_MODE_INFO_EXT_FRAME *mbmi_ext_best, uint8_t ref_frame_type) {
6245
  memcpy(mbmi_ext->ref_mv_stack[ref_frame_type], mbmi_ext_best->ref_mv_stack,
6246
         sizeof(mbmi_ext->ref_mv_stack[USABLE_REF_MV_STACK_SIZE]));
6247
  memcpy(mbmi_ext->weight[ref_frame_type], mbmi_ext_best->weight,
6248
         sizeof(mbmi_ext->weight[USABLE_REF_MV_STACK_SIZE]));
6249
  mbmi_ext->mode_context[ref_frame_type] = mbmi_ext_best->mode_context;
6250
  mbmi_ext->ref_mv_count[ref_frame_type] = mbmi_ext_best->ref_mv_count;
6251
  memcpy(mbmi_ext->global_mvs, mbmi_ext_best->global_mvs,
6252
         sizeof(mbmi_ext->global_mvs));
6253
}
6254
6255
static void fill_mode_info_sb(AV1_COMP *cpi, MACROBLOCK *x, int mi_row,
6256
                              int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
6257
  AV1_COMMON *const cm = &cpi->common;
6258
  MACROBLOCKD *xd = &x->e_mbd;
6259
  int hbs = mi_size_wide[bsize] >> 1;
6260
  PARTITION_TYPE partition = pc_tree->partitioning;
6261
  BLOCK_SIZE subsize = get_partition_subsize(bsize, partition);
6262
6263
  assert(bsize >= BLOCK_8X8);
6264
6265
  if (mi_row >= cm->mi_params.mi_rows || mi_col >= cm->mi_params.mi_cols)
6266
    return;
6267
6268
  switch (partition) {
6269
    case PARTITION_NONE:
6270
      set_mode_info_offsets(&cm->mi_params, &cpi->mbmi_ext_info, x, xd, mi_row,
6271
                            mi_col);
6272
      *(xd->mi[0]) = pc_tree->none->mic;
6273
      copy_mbmi_ext_frame_to_mbmi_ext(
6274
          &x->mbmi_ext, &pc_tree->none->mbmi_ext_best, LAST_FRAME);
6275
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
6276
      break;
6277
    case PARTITION_SPLIT: {
6278
      fill_mode_info_sb(cpi, x, mi_row, mi_col, subsize, pc_tree->split[0]);
6279
      fill_mode_info_sb(cpi, x, mi_row, mi_col + hbs, subsize,
6280
                        pc_tree->split[1]);
6281
      fill_mode_info_sb(cpi, x, mi_row + hbs, mi_col, subsize,
6282
                        pc_tree->split[2]);
6283
      fill_mode_info_sb(cpi, x, mi_row + hbs, mi_col + hbs, subsize,
6284
                        pc_tree->split[3]);
6285
      break;
6286
    }
6287
    default: break;
6288
  }
6289
}
6290
6291
void av1_nonrd_pick_partition(AV1_COMP *cpi, ThreadData *td,
6292
                              TileDataEnc *tile_data, TokenExtra **tp,
6293
                              int mi_row, int mi_col, BLOCK_SIZE bsize,
6294
                              RD_STATS *rd_cost, int do_recon, int64_t best_rd,
6295
                              PC_TREE *pc_tree) {
6296
  AV1_COMMON *const cm = &cpi->common;
6297
  TileInfo *const tile_info = &tile_data->tile_info;
6298
  MACROBLOCK *const x = &td->mb;
6299
  MACROBLOCKD *const xd = &x->e_mbd;
6300
  const int hbs = mi_size_wide[bsize] >> 1;
6301
  TokenExtra *tp_orig = *tp;
6302
  const ModeCosts *mode_costs = &x->mode_costs;
6303
  RD_STATS this_rdc, best_rdc;
6304
  RD_SEARCH_MACROBLOCK_CONTEXT x_ctx;
6305
  int do_split = bsize > BLOCK_8X8;
6306
  // Override skipping rectangular partition operations for edge blocks
6307
  const int force_horz_split = (mi_row + 2 * hbs > cm->mi_params.mi_rows);
6308
  const int force_vert_split = (mi_col + 2 * hbs > cm->mi_params.mi_cols);
6309
6310
  int partition_none_allowed = !force_horz_split && !force_vert_split;
6311
6312
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);  // Square partition only
6313
  assert(cm->seq_params->sb_size == BLOCK_64X64);      // Small SB so far
6314
6315
  (void)*tp_orig;
6316
6317
  av1_invalid_rd_stats(&best_rdc);
6318
  best_rdc.rdcost = best_rd;
6319
#ifndef _COLLECT_GROUND_TRUTH_
6320
  if (partition_none_allowed && do_split) {
6321
    const int ml_predicted_partition =
6322
        ml_predict_var_partitioning(cpi, x, bsize, mi_row, mi_col);
6323
    if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
6324
    if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
6325
  }
6326
#endif
6327
6328
  xd->above_txfm_context =
6329
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
6330
  xd->left_txfm_context =
6331
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
6332
  av1_save_context(x, &x_ctx, mi_row, mi_col, bsize, 3);
6333
6334
  // PARTITION_NONE
6335
  if (partition_none_allowed) {
6336
    pc_tree->none = av1_alloc_pmc(cpi, bsize, &td->shared_coeff_buf);
6337
    if (!pc_tree->none)
6338
      aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
6339
                         "Failed to allocate PICK_MODE_CONTEXT");
6340
    PICK_MODE_CONTEXT *ctx = pc_tree->none;
6341
6342
// Flip for RDO based pick mode
6343
#if 0
6344
    RD_STATS dummy;
6345
    av1_invalid_rd_stats(&dummy);
6346
    pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc,
6347
                  PARTITION_NONE, bsize, ctx, dummy);
6348
#else
6349
    pick_sb_modes_nonrd(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
6350
                        ctx);
6351
#endif
6352
    if (this_rdc.rate != INT_MAX) {
6353
      const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
6354
6355
      this_rdc.rate += mode_costs->partition_cost[pl][PARTITION_NONE];
6356
      this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
6357
      if (this_rdc.rdcost < best_rdc.rdcost) {
6358
        best_rdc = this_rdc;
6359
        if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
6360
      }
6361
    }
6362
  }
6363
6364
  // PARTITION_SPLIT
6365
  if (do_split) {
6366
    RD_STATS sum_rdc;
6367
    const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
6368
6369
    av1_init_rd_stats(&sum_rdc);
6370
6371
    for (int i = 0; i < SUB_PARTITIONS_SPLIT; ++i) {
6372
      pc_tree->split[i] = av1_alloc_pc_tree_node(subsize);
6373
      if (!pc_tree->split[i])
6374
        aom_internal_error(xd->error_info, AOM_CODEC_MEM_ERROR,
6375
                           "Failed to allocate PC_TREE");
6376
      pc_tree->split[i]->index = i;
6377
    }
6378
6379
    int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
6380
    sum_rdc.rate += mode_costs->partition_cost[pl][PARTITION_SPLIT];
6381
    sum_rdc.rdcost = RDCOST(x->rdmult, sum_rdc.rate, sum_rdc.dist);
6382
    for (int i = 0;
6383
         i < SUB_PARTITIONS_SPLIT && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
6384
      const int x_idx = (i & 1) * hbs;
6385
      const int y_idx = (i >> 1) * hbs;
6386
6387
      if (mi_row + y_idx >= cm->mi_params.mi_rows ||
6388
          mi_col + x_idx >= cm->mi_params.mi_cols)
6389
        continue;
6390
      av1_nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
6391
                               mi_col + x_idx, subsize, &this_rdc, i < 3,
6392
                               best_rdc.rdcost - sum_rdc.rdcost,
6393
                               pc_tree->split[i]);
6394
6395
      if (this_rdc.rate == INT_MAX) {
6396
        av1_invalid_rd_stats(&sum_rdc);
6397
      } else {
6398
        sum_rdc.rate += this_rdc.rate;
6399
        sum_rdc.dist += this_rdc.dist;
6400
        sum_rdc.rdcost += this_rdc.rdcost;
6401
      }
6402
    }
6403
    if (sum_rdc.rdcost < best_rdc.rdcost) {
6404
      best_rdc = sum_rdc;
6405
      pc_tree->partitioning = PARTITION_SPLIT;
6406
    }
6407
  }
6408
6409
#ifdef _COLLECT_GROUND_TRUTH_
6410
  store_partition_data(cpi, x, bsize, mi_row, mi_col, pc_tree->partitioning);
6411
#endif
6412
6413
  *rd_cost = best_rdc;
6414
6415
  av1_restore_context(x, &x_ctx, mi_row, mi_col, bsize, 3);
6416
6417
  if (best_rdc.rate == INT_MAX) {
6418
    av1_invalid_rd_stats(rd_cost);
6419
    return;
6420
  }
6421
6422
  // update mode info array
6423
  fill_mode_info_sb(cpi, x, mi_row, mi_col, bsize, pc_tree);
6424
6425
  if (do_recon) {
6426
    if (bsize == cm->seq_params->sb_size) {
6427
      // NOTE: To get estimate for rate due to the tokens, use:
6428
      // int rate_coeffs = 0;
6429
      // encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_COSTCOEFFS,
6430
      //           bsize, pc_tree, &rate_coeffs);
6431
      set_cb_offsets(x->cb_offset, 0, 0);
6432
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, OUTPUT_ENABLED, bsize,
6433
                pc_tree, NULL);
6434
    } else {
6435
      encode_sb(cpi, td, tile_data, tp, mi_row, mi_col, DRY_RUN_NORMAL, bsize,
6436
                pc_tree, NULL);
6437
    }
6438
  }
6439
6440
  if (bsize == BLOCK_64X64 && do_recon) {
6441
    assert(best_rdc.rate < INT_MAX);
6442
    assert(best_rdc.dist < INT64_MAX);
6443
  } else {
6444
    assert(tp_orig == *tp);
6445
  }
6446
}
6447
#endif  // CONFIG_RT_ML_PARTITIONING