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