Coverage Report

Created: 2026-07-25 07:06

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