Coverage Report

Created: 2026-04-01 07:49

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