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