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