• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016, 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 
13 #include <assert.h>
14 #include <limits.h>
15 #include <math.h>
16 #include <stdio.h>
17 
18 #include "config/aom_dsp_rtcd.h"
19 #include "config/av1_rtcd.h"
20 
21 #include "aom_dsp/aom_dsp_common.h"
22 #include "aom_dsp/blend.h"
23 #include "aom_mem/aom_mem.h"
24 #include "aom_ports/aom_timer.h"
25 #include "aom_ports/mem.h"
26 
27 #include "av1/encoder/model_rd.h"
28 #include "av1/common/mvref_common.h"
29 #include "av1/common/pred_common.h"
30 #include "av1/common/reconinter.h"
31 #include "av1/common/reconintra.h"
32 
33 #include "av1/encoder/encodemv.h"
34 #include "av1/encoder/rdopt.h"
35 #include "av1/encoder/reconinter_enc.h"
36 
37 extern int g_pick_inter_mode_cnt;
38 /*!\cond */
39 typedef struct {
40   uint8_t *data;
41   int stride;
42   int in_use;
43 } PRED_BUFFER;
44 
45 typedef struct {
46   PRED_BUFFER *best_pred;
47   PREDICTION_MODE best_mode;
48   TX_SIZE best_tx_size;
49   MV_REFERENCE_FRAME best_ref_frame;
50   MV_REFERENCE_FRAME best_second_ref_frame;
51   uint8_t best_mode_skip_txfm;
52   uint8_t best_mode_initial_skip_flag;
53   int_interpfilters best_pred_filter;
54   MOTION_MODE best_motion_mode;
55   WarpedMotionParams wm_params;
56   int num_proj_ref;
57 } BEST_PICKMODE;
58 
59 typedef struct {
60   MV_REFERENCE_FRAME ref_frame;
61   PREDICTION_MODE pred_mode;
62 } REF_MODE;
63 
64 typedef struct {
65   InterpFilter filter_x;
66   InterpFilter filter_y;
67 } INTER_FILTER;
68 /*!\endcond */
69 
70 static const int pos_shift_16x16[4][4] = {
71   { 9, 10, 13, 14 }, { 11, 12, 15, 16 }, { 17, 18, 21, 22 }, { 19, 20, 23, 24 }
72 };
73 
74 #define NUM_INTER_MODES_RT 9
75 #define NUM_INTER_MODES_REDUCED 8
76 
77 static const REF_MODE ref_mode_set_rt[NUM_INTER_MODES_RT] = {
78   { LAST_FRAME, NEARESTMV },   { LAST_FRAME, NEARMV },
79   { LAST_FRAME, NEWMV },       { GOLDEN_FRAME, NEARESTMV },
80   { GOLDEN_FRAME, NEARMV },    { GOLDEN_FRAME, NEWMV },
81   { ALTREF_FRAME, NEARESTMV }, { ALTREF_FRAME, NEARMV },
82   { ALTREF_FRAME, NEWMV }
83 };
84 
85 // GLOBALMV in the set below is in fact ZEROMV as we don't do global ME in RT
86 // mode
87 static const REF_MODE ref_mode_set_reduced[NUM_INTER_MODES_REDUCED] = {
88   { LAST_FRAME, GLOBALMV },   { LAST_FRAME, NEARESTMV },
89   { GOLDEN_FRAME, GLOBALMV }, { LAST_FRAME, NEARMV },
90   { LAST_FRAME, NEWMV },      { GOLDEN_FRAME, NEARESTMV },
91   { GOLDEN_FRAME, NEARMV },   { GOLDEN_FRAME, NEWMV }
92 };
93 
94 static const THR_MODES mode_idx[REF_FRAMES][4] = {
95   { THR_DC, THR_V_PRED, THR_H_PRED, THR_SMOOTH },
96   { THR_NEARESTMV, THR_NEARMV, THR_GLOBALMV, THR_NEWMV },
97   { THR_NEARESTL2, THR_NEARL2, THR_GLOBALL2, THR_NEWL2 },
98   { THR_NEARESTL3, THR_NEARL3, THR_GLOBALL3, THR_NEWL3 },
99   { THR_NEARESTG, THR_NEARG, THR_GLOBALMV, THR_NEWG },
100 };
101 
102 static const PREDICTION_MODE intra_mode_list[] = { DC_PRED, V_PRED, H_PRED,
103                                                    SMOOTH_PRED };
104 
105 static const INTER_FILTER filters_ref_set[9] = {
106   { EIGHTTAP_REGULAR, EIGHTTAP_REGULAR }, { EIGHTTAP_SMOOTH, EIGHTTAP_SMOOTH },
107   { EIGHTTAP_REGULAR, EIGHTTAP_SMOOTH },  { EIGHTTAP_SMOOTH, EIGHTTAP_REGULAR },
108   { MULTITAP_SHARP, MULTITAP_SHARP },     { EIGHTTAP_REGULAR, MULTITAP_SHARP },
109   { MULTITAP_SHARP, EIGHTTAP_REGULAR },   { EIGHTTAP_SMOOTH, MULTITAP_SHARP },
110   { MULTITAP_SHARP, EIGHTTAP_SMOOTH }
111 };
112 
mode_offset(const PREDICTION_MODE mode)113 static INLINE int mode_offset(const PREDICTION_MODE mode) {
114   if (mode >= NEARESTMV) {
115     return INTER_OFFSET(mode);
116   } else {
117     switch (mode) {
118       case DC_PRED: return 0;
119       case V_PRED: return 1;
120       case H_PRED: return 2;
121       case SMOOTH_PRED: return 3;
122       default: assert(0); return -1;
123     }
124   }
125 }
126 
127 enum {
128   //  INTER_ALL = (1 << NEARESTMV) | (1 << NEARMV) | (1 << NEWMV),
129   INTER_NEAREST = (1 << NEARESTMV),
130   INTER_NEAREST_NEW = (1 << NEARESTMV) | (1 << NEWMV),
131   INTER_NEAREST_NEAR = (1 << NEARESTMV) | (1 << NEARMV),
132   INTER_NEAR_NEW = (1 << NEARMV) | (1 << NEWMV),
133 };
134 
init_best_pickmode(BEST_PICKMODE * bp)135 static INLINE void init_best_pickmode(BEST_PICKMODE *bp) {
136   bp->best_mode = NEARESTMV;
137   bp->best_ref_frame = LAST_FRAME;
138   bp->best_second_ref_frame = NONE_FRAME;
139   bp->best_tx_size = TX_8X8;
140   bp->best_pred_filter = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
141   bp->best_mode_skip_txfm = 0;
142   bp->best_mode_initial_skip_flag = 0;
143   bp->best_pred = NULL;
144   bp->best_motion_mode = SIMPLE_TRANSLATION;
145   bp->num_proj_ref = 0;
146   memset(&bp->wm_params, 0, sizeof(bp->wm_params));
147 }
148 
149 /*!\brief Runs Motion Estimation for a specific block and specific ref frame.
150  *
151  * \ingroup nonrd_mode_search
152  * \callgraph
153  * \callergraph
154  * Finds the best Motion Vector by running Motion Estimation for a specific
155  * block and a specific reference frame. Exits early if RDCost of Full Pel part
156  * exceeds best RD Cost fund so far
157  * \param[in]    cpi                      Top-level encoder structure
158  * \param[in]    x                        Pointer to structure holding all the
159  *                                        data for the current macroblock
160  * \param[in]    bsize                    Current block size
161  * \param[in]    mi_row                   Row index in 4x4 units
162  * \param[in]    mi_col                   Column index in 4x4 units
163  * \param[in]    tmp_mv                   Pointer to best found New MV
164  * \param[in]    rate_mv                  Pointer to Rate of the best new MV
165  * \param[in]    best_rd_sofar            RD Cost of the best mode found so far
166  * \param[in]    use_base_mv              Flag, indicating that tmp_mv holds
167  *                                        specific MV to start the search with
168  *
169  * \return Returns 0 if ME was terminated after Full Pel Search because too
170  * high RD Cost. Otherwise returns 1. Best New MV is placed into \c tmp_mv.
171  * Rate estimation for this vector is placed to \c rate_mv
172  */
combined_motion_search(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int mi_row,int mi_col,int_mv * tmp_mv,int * rate_mv,int64_t best_rd_sofar,int use_base_mv)173 static int combined_motion_search(AV1_COMP *cpi, MACROBLOCK *x,
174                                   BLOCK_SIZE bsize, int mi_row, int mi_col,
175                                   int_mv *tmp_mv, int *rate_mv,
176                                   int64_t best_rd_sofar, int use_base_mv) {
177   MACROBLOCKD *xd = &x->e_mbd;
178   const AV1_COMMON *cm = &cpi->common;
179   const int num_planes = av1_num_planes(cm);
180   MB_MODE_INFO *mi = xd->mi[0];
181   struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0, 0, 0, 0 } };
182   int step_param = (cpi->sf.rt_sf.fullpel_search_step_param)
183                        ? cpi->sf.rt_sf.fullpel_search_step_param
184                        : cpi->mv_search_params.mv_step_param;
185   FULLPEL_MV start_mv;
186   const int ref = mi->ref_frame[0];
187   const MV ref_mv = av1_get_ref_mv(x, mi->ref_mv_idx).as_mv;
188   MV center_mv;
189   int dis;
190   int rv = 0;
191   int cost_list[5];
192   int search_subpel = 1;
193   const YV12_BUFFER_CONFIG *scaled_ref_frame =
194       av1_get_scaled_ref_frame(cpi, ref);
195 
196   if (scaled_ref_frame) {
197     int i;
198     // Swap out the reference frame for a version that's been scaled to
199     // match the resolution of the current frame, allowing the existing
200     // motion search code to be used without additional modifications.
201     for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
202     av1_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL,
203                          num_planes);
204   }
205 
206   start_mv = get_fullmv_from_mv(&ref_mv);
207 
208   if (!use_base_mv)
209     center_mv = ref_mv;
210   else
211     center_mv = tmp_mv->as_mv;
212   const search_site_config *src_search_sites =
213       cpi->mv_search_params.search_site_cfg[SS_CFG_SRC];
214   FULLPEL_MOTION_SEARCH_PARAMS full_ms_params;
215   av1_make_default_fullpel_ms_params(&full_ms_params, cpi, x, bsize, &center_mv,
216                                      src_search_sites,
217                                      /*fine_search_interval=*/0);
218 
219   av1_full_pixel_search(start_mv, &full_ms_params, step_param,
220                         cond_cost_list(cpi, cost_list), &tmp_mv->as_fullmv,
221                         NULL);
222 
223   // calculate the bit cost on motion vector
224   MV mvp_full = get_mv_from_fullmv(&tmp_mv->as_fullmv);
225 
226   *rate_mv = av1_mv_bit_cost(&mvp_full, &ref_mv, x->mv_costs->nmv_joint_cost,
227                              x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
228 
229   // TODO(kyslov) Account for Rate Mode!
230   rv = !(RDCOST(x->rdmult, (*rate_mv), 0) > best_rd_sofar);
231 
232   if (rv && search_subpel) {
233     SUBPEL_MOTION_SEARCH_PARAMS ms_params;
234     av1_make_default_subpel_ms_params(&ms_params, cpi, x, bsize, &ref_mv,
235                                       cost_list);
236     MV subpel_start_mv = get_mv_from_fullmv(&tmp_mv->as_fullmv);
237     cpi->mv_search_params.find_fractional_mv_step(
238         xd, cm, &ms_params, subpel_start_mv, &tmp_mv->as_mv, &dis,
239         &x->pred_sse[ref], NULL);
240 
241     *rate_mv =
242         av1_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->mv_costs->nmv_joint_cost,
243                         x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
244   }
245 
246   if (scaled_ref_frame) {
247     int i;
248     for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
249   }
250   // Final MV can not be equal to referance MV as this will trigger assert
251   // later. This can happen if both NEAREST and NEAR modes were skipped
252   rv = (tmp_mv->as_mv.col != ref_mv.col || tmp_mv->as_mv.row != ref_mv.row);
253   return rv;
254 }
255 
256 /*!\brief Searches for the best New Motion Vector.
257  *
258  * \ingroup nonrd_mode_search
259  * \callgraph
260  * \callergraph
261  * Finds the best Motion Vector by doing Motion Estimation. Uses reduced
262  * complexity ME for non-LAST frames or calls \c combined_motion_search
263  * for LAST reference frame
264  * \param[in]    cpi                      Top-level encoder structure
265  * \param[in]    x                        Pointer to structure holding all the
266  *                                        data for the current macroblock
267  * \param[in]    frame_mv                 Array that holds MVs for all modes
268  *                                        and ref frames
269  * \param[in]    ref_frame                Reference freme for which to find
270  *                                        the best New MVs
271  * \param[in]    gf_temporal_ref          Flag, indicating temporal reference
272  *                                        for GOLDEN frame
273  * \param[in]    bsize                    Current block size
274  * \param[in]    mi_row                   Row index in 4x4 units
275  * \param[in]    mi_col                   Column index in 4x4 units
276  * \param[in]    rate_mv                  Pointer to Rate of the best new MV
277  * \param[in]    best_rdc                 Pointer to the RD Cost for the best
278  *                                        mode found so far
279  *
280  * \return Returns -1 if the search was not done, otherwise returns 0.
281  * Best New MV is placed into \c frame_mv array, Rate estimation for this
282  * vector is placed to \c rate_mv
283  */
search_new_mv(AV1_COMP * cpi,MACROBLOCK * x,int_mv frame_mv[][REF_FRAMES],MV_REFERENCE_FRAME ref_frame,int gf_temporal_ref,BLOCK_SIZE bsize,int mi_row,int mi_col,int * rate_mv,RD_STATS * best_rdc)284 static int search_new_mv(AV1_COMP *cpi, MACROBLOCK *x,
285                          int_mv frame_mv[][REF_FRAMES],
286                          MV_REFERENCE_FRAME ref_frame, int gf_temporal_ref,
287                          BLOCK_SIZE bsize, int mi_row, int mi_col, int *rate_mv,
288                          RD_STATS *best_rdc) {
289   MACROBLOCKD *const xd = &x->e_mbd;
290   MB_MODE_INFO *const mi = xd->mi[0];
291   AV1_COMMON *cm = &cpi->common;
292   if (ref_frame > LAST_FRAME && cpi->oxcf.rc_cfg.mode == AOM_CBR &&
293       gf_temporal_ref) {
294     int tmp_sad;
295     int dis;
296     int cost_list[5] = { INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX };
297 
298     if (bsize < BLOCK_16X16) return -1;
299 
300     tmp_sad = av1_int_pro_motion_estimation(
301         cpi, x, bsize, mi_row, mi_col,
302         &x->mbmi_ext.ref_mv_stack[ref_frame][0].this_mv.as_mv);
303 
304     if (tmp_sad > x->pred_mv_sad[LAST_FRAME]) return -1;
305 
306     frame_mv[NEWMV][ref_frame].as_int = mi->mv[0].as_int;
307     int_mv best_mv = mi->mv[0];
308     best_mv.as_mv.row >>= 3;
309     best_mv.as_mv.col >>= 3;
310     MV ref_mv = av1_get_ref_mv(x, 0).as_mv;
311 
312     *rate_mv = av1_mv_bit_cost(&frame_mv[NEWMV][ref_frame].as_mv, &ref_mv,
313                                x->mv_costs->nmv_joint_cost,
314                                x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
315     frame_mv[NEWMV][ref_frame].as_mv.row >>= 3;
316     frame_mv[NEWMV][ref_frame].as_mv.col >>= 3;
317 
318     SUBPEL_MOTION_SEARCH_PARAMS ms_params;
319     av1_make_default_subpel_ms_params(&ms_params, cpi, x, bsize, &ref_mv,
320                                       cost_list);
321     MV start_mv = get_mv_from_fullmv(&best_mv.as_fullmv);
322     cpi->mv_search_params.find_fractional_mv_step(
323         xd, cm, &ms_params, start_mv, &best_mv.as_mv, &dis,
324         &x->pred_sse[ref_frame], NULL);
325     frame_mv[NEWMV][ref_frame].as_int = best_mv.as_int;
326   } else if (!combined_motion_search(cpi, x, bsize, mi_row, mi_col,
327                                      &frame_mv[NEWMV][ref_frame], rate_mv,
328                                      best_rdc->rdcost, 0)) {
329     return -1;
330   }
331 
332   return 0;
333 }
334 
335 /*!\brief Finds predicted motion vectors for a block.
336  *
337  * \ingroup nonrd_mode_search
338  * \callgraph
339  * \callergraph
340  * Finds predicted motion vectors for a block from a certain reference frame.
341  * First, it fills reference MV stack, then picks the test from the stack and
342  * predicts the final MV for a block for each mode.
343  * \param[in]    cpi                      Top-level encoder structure
344  * \param[in]    x                        Pointer to structure holding all the
345  *                                        data for the current macroblock
346  * \param[in]    ref_frame                Reference freme for which to find
347  *                                        ref MVs
348  * \param[in]    frame_mv                 Predicted MVs for a block
349  * \param[in]    tile_data                Pointer to struct holding adaptive
350  *                                        data/contexts/models for the tile
351  *                                        during encoding
352  * \param[in]    yv12_mb                  Buffer to hold predicted block
353  * \param[in]    bsize                    Current block size
354  * \param[in]    force_skip_low_temp_var  Flag indicating possible mode search
355  *                                        prune for low temporal variace  block
356  *
357  * \return Nothing is returned. Instead, predicted MVs are placed into
358  * \c frame_mv array
359  */
find_predictors(AV1_COMP * cpi,MACROBLOCK * x,MV_REFERENCE_FRAME ref_frame,int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],TileDataEnc * tile_data,struct buf_2d yv12_mb[8][MAX_MB_PLANE],BLOCK_SIZE bsize,int force_skip_low_temp_var)360 static INLINE void find_predictors(AV1_COMP *cpi, MACROBLOCK *x,
361                                    MV_REFERENCE_FRAME ref_frame,
362                                    int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],
363                                    TileDataEnc *tile_data,
364                                    struct buf_2d yv12_mb[8][MAX_MB_PLANE],
365                                    BLOCK_SIZE bsize,
366                                    int force_skip_low_temp_var) {
367   AV1_COMMON *const cm = &cpi->common;
368   MACROBLOCKD *const xd = &x->e_mbd;
369   MB_MODE_INFO *const mbmi = xd->mi[0];
370   MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
371   const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_yv12_buf(cm, ref_frame);
372   const int num_planes = av1_num_planes(cm);
373   (void)tile_data;
374 
375   x->pred_mv_sad[ref_frame] = INT_MAX;
376   x->pred_mv0_sad[ref_frame] = INT_MAX;
377   x->pred_mv1_sad[ref_frame] = INT_MAX;
378   frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
379   // TODO(kyslov) this needs various further optimizations. to be continued..
380   assert(yv12 != NULL);
381   if (yv12 != NULL) {
382     const struct scale_factors *const sf =
383         get_ref_scale_factors_const(cm, ref_frame);
384     av1_setup_pred_block(xd, yv12_mb[ref_frame], yv12, sf, sf, num_planes);
385     av1_find_mv_refs(cm, xd, mbmi, ref_frame, mbmi_ext->ref_mv_count,
386                      xd->ref_mv_stack, xd->weight, NULL, mbmi_ext->global_mvs,
387                      mbmi_ext->mode_context);
388     // TODO(Ravi): Populate mbmi_ext->ref_mv_stack[ref_frame][4] and
389     // mbmi_ext->weight[ref_frame][4] inside av1_find_mv_refs.
390     av1_copy_usable_ref_mv_stack_and_weight(xd, mbmi_ext, ref_frame);
391     av1_find_best_ref_mvs_from_stack(
392         cm->features.allow_high_precision_mv, mbmi_ext, ref_frame,
393         &frame_mv[NEARESTMV][ref_frame], &frame_mv[NEARMV][ref_frame], 0);
394     frame_mv[GLOBALMV][ref_frame] = mbmi_ext->global_mvs[ref_frame];
395     // Early exit for non-LAST frame if force_skip_low_temp_var is set.
396     if (!av1_is_scaled(sf) && bsize >= BLOCK_8X8 &&
397         !(force_skip_low_temp_var && ref_frame != LAST_FRAME)) {
398       av1_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
399                   bsize);
400     }
401   }
402   av1_count_overlappable_neighbors(cm, xd);
403   mbmi->num_proj_ref = 1;
404 }
405 
estimate_single_ref_frame_costs(const AV1_COMMON * cm,const MACROBLOCKD * xd,const ModeCosts * mode_costs,int segment_id,unsigned int * ref_costs_single)406 static void estimate_single_ref_frame_costs(const AV1_COMMON *cm,
407                                             const MACROBLOCKD *xd,
408                                             const ModeCosts *mode_costs,
409                                             int segment_id,
410                                             unsigned int *ref_costs_single) {
411   int seg_ref_active =
412       segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
413   if (seg_ref_active) {
414     memset(ref_costs_single, 0, REF_FRAMES * sizeof(*ref_costs_single));
415   } else {
416     int intra_inter_ctx = av1_get_intra_inter_context(xd);
417     ref_costs_single[INTRA_FRAME] =
418         mode_costs->intra_inter_cost[intra_inter_ctx][0];
419     unsigned int base_cost = mode_costs->intra_inter_cost[intra_inter_ctx][1];
420     ref_costs_single[LAST_FRAME] = base_cost;
421     ref_costs_single[GOLDEN_FRAME] = base_cost;
422     ref_costs_single[ALTREF_FRAME] = base_cost;
423     // add cost for last, golden, altref
424     ref_costs_single[LAST_FRAME] += mode_costs->single_ref_cost[0][0][0];
425     ref_costs_single[GOLDEN_FRAME] += mode_costs->single_ref_cost[0][0][1];
426     ref_costs_single[GOLDEN_FRAME] += mode_costs->single_ref_cost[0][1][0];
427     ref_costs_single[ALTREF_FRAME] += mode_costs->single_ref_cost[0][0][1];
428     ref_costs_single[ALTREF_FRAME] += mode_costs->single_ref_cost[0][2][0];
429   }
430 }
431 
calculate_tx_size(const AV1_COMP * const cpi,BLOCK_SIZE bsize,MACROBLOCK * const x,unsigned int var,unsigned int sse)432 static TX_SIZE calculate_tx_size(const AV1_COMP *const cpi, BLOCK_SIZE bsize,
433                                  MACROBLOCK *const x, unsigned int var,
434                                  unsigned int sse) {
435   MACROBLOCKD *const xd = &x->e_mbd;
436   TX_SIZE tx_size;
437   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
438   if (txfm_params->tx_mode_search_type == TX_MODE_SELECT) {
439     if (sse > (var << 1))
440       tx_size =
441           AOMMIN(max_txsize_lookup[bsize],
442                  tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]);
443     else
444       tx_size = TX_8X8;
445 
446     if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
447         cyclic_refresh_segment_id_boosted(xd->mi[0]->segment_id))
448       tx_size = TX_8X8;
449     else if (tx_size > TX_16X16)
450       tx_size = TX_16X16;
451   } else {
452     tx_size =
453         AOMMIN(max_txsize_lookup[bsize],
454                tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]);
455   }
456 
457   if (txfm_params->tx_mode_search_type != ONLY_4X4 && bsize > BLOCK_32X32)
458     tx_size = TX_16X16;
459 
460   return AOMMIN(tx_size, TX_16X16);
461 }
462 
463 static const uint8_t b_width_log2_lookup[BLOCK_SIZES] = { 0, 0, 1, 1, 1, 2,
464                                                           2, 2, 3, 3, 3, 4,
465                                                           4, 4, 5, 5 };
466 static const uint8_t b_height_log2_lookup[BLOCK_SIZES] = { 0, 1, 0, 1, 2, 1,
467                                                            2, 3, 2, 3, 4, 3,
468                                                            4, 5, 4, 5 };
469 
block_variance(const uint8_t * src,int src_stride,const uint8_t * ref,int ref_stride,int w,int h,unsigned int * sse,int * sum,int block_size,uint32_t * sse8x8,int * sum8x8,uint32_t * var8x8)470 static void block_variance(const uint8_t *src, int src_stride,
471                            const uint8_t *ref, int ref_stride, int w, int h,
472                            unsigned int *sse, int *sum, int block_size,
473                            uint32_t *sse8x8, int *sum8x8, uint32_t *var8x8) {
474   int i, j, k = 0;
475 
476   *sse = 0;
477   *sum = 0;
478 
479   for (i = 0; i < h; i += block_size) {
480     for (j = 0; j < w; j += block_size) {
481       aom_get8x8var(src + src_stride * i + j, src_stride,
482                     ref + ref_stride * i + j, ref_stride, &sse8x8[k],
483                     &sum8x8[k]);
484       *sse += sse8x8[k];
485       *sum += sum8x8[k];
486       var8x8[k] = sse8x8[k] - (uint32_t)(((int64_t)sum8x8[k] * sum8x8[k]) >> 6);
487       k++;
488     }
489   }
490 }
491 
calculate_variance(int bw,int bh,TX_SIZE tx_size,unsigned int * sse_i,int * sum_i,unsigned int * var_o,unsigned int * sse_o,int * sum_o)492 static void calculate_variance(int bw, int bh, TX_SIZE tx_size,
493                                unsigned int *sse_i, int *sum_i,
494                                unsigned int *var_o, unsigned int *sse_o,
495                                int *sum_o) {
496   const BLOCK_SIZE unit_size = txsize_to_bsize[tx_size];
497   const int nw = 1 << (bw - b_width_log2_lookup[unit_size]);
498   const int nh = 1 << (bh - b_height_log2_lookup[unit_size]);
499   int i, j, k = 0;
500 
501   for (i = 0; i < nh; i += 2) {
502     for (j = 0; j < nw; j += 2) {
503       sse_o[k] = sse_i[i * nw + j] + sse_i[i * nw + j + 1] +
504                  sse_i[(i + 1) * nw + j] + sse_i[(i + 1) * nw + j + 1];
505       sum_o[k] = sum_i[i * nw + j] + sum_i[i * nw + j + 1] +
506                  sum_i[(i + 1) * nw + j] + sum_i[(i + 1) * nw + j + 1];
507       var_o[k] = sse_o[k] - (uint32_t)(((int64_t)sum_o[k] * sum_o[k]) >>
508                                        (b_width_log2_lookup[unit_size] +
509                                         b_height_log2_lookup[unit_size] + 6));
510       k++;
511     }
512   }
513 }
514 
515 // Adjust the ac_thr according to speed, width, height and normalized sum
ac_thr_factor(const int speed,const int width,const int height,const int norm_sum)516 static int ac_thr_factor(const int speed, const int width, const int height,
517                          const int norm_sum) {
518   if (speed >= 8 && norm_sum < 5) {
519     if (width <= 640 && height <= 480)
520       return 4;
521     else
522       return 2;
523   }
524   return 1;
525 }
526 
model_skip_for_sb_y_large(AV1_COMP * cpi,BLOCK_SIZE bsize,int mi_row,int mi_col,MACROBLOCK * x,MACROBLOCKD * xd,RD_STATS * rd_stats,int * early_term,int calculate_rd)527 static void model_skip_for_sb_y_large(AV1_COMP *cpi, BLOCK_SIZE bsize,
528                                       int mi_row, int mi_col, MACROBLOCK *x,
529                                       MACROBLOCKD *xd, RD_STATS *rd_stats,
530                                       int *early_term, int calculate_rd) {
531   // Note our transform coeffs are 8 times an orthogonal transform.
532   // Hence quantizer step is also 8 times. To get effective quantizer
533   // we need to divide by 8 before sending to modeling function.
534   unsigned int sse;
535   struct macroblock_plane *const p = &x->plane[0];
536   struct macroblockd_plane *const pd = &xd->plane[0];
537   const uint32_t dc_quant = p->dequant_QTX[0];
538   const uint32_t ac_quant = p->dequant_QTX[1];
539   const int64_t dc_thr = dc_quant * dc_quant >> 6;
540   int64_t ac_thr = ac_quant * ac_quant >> 6;
541   unsigned int var;
542   int sum;
543 
544   const int bw = b_width_log2_lookup[bsize];
545   const int bh = b_height_log2_lookup[bsize];
546   const int num8x8 = 1 << (bw + bh - 2);
547   unsigned int sse8x8[256] = { 0 };
548   int sum8x8[256] = { 0 };
549   unsigned int var8x8[256] = { 0 };
550   TX_SIZE tx_size;
551   int k;
552   // Calculate variance for whole partition, and also save 8x8 blocks' variance
553   // to be used in following transform skipping test.
554   block_variance(p->src.buf, p->src.stride, pd->dst.buf, pd->dst.stride,
555                  4 << bw, 4 << bh, &sse, &sum, 8, sse8x8, sum8x8, var8x8);
556   var = sse - (unsigned int)(((int64_t)sum * sum) >> (bw + bh + 4));
557 
558   rd_stats->sse = sse;
559 
560 #if CONFIG_AV1_TEMPORAL_DENOISING
561   if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
562       cpi->oxcf.speed > 5)
563     ac_thr = av1_scale_acskip_thresh(ac_thr, cpi->denoiser.denoising_level,
564                                      (abs(sum) >> (bw + bh)),
565                                      cpi->svc.temporal_layer_id);
566   else
567     ac_thr *= ac_thr_factor(cpi->oxcf.speed, cpi->common.width,
568                             cpi->common.height, abs(sum) >> (bw + bh));
569 #else
570   ac_thr *= ac_thr_factor(cpi->oxcf.speed, cpi->common.width,
571                           cpi->common.height, abs(sum) >> (bw + bh));
572 
573 #endif
574   tx_size = calculate_tx_size(cpi, bsize, x, var, sse);
575   // The code below for setting skip flag assumes tranform size of at least 8x8,
576   // so force this lower limit on transform.
577   if (tx_size < TX_8X8) tx_size = TX_8X8;
578   xd->mi[0]->tx_size = tx_size;
579 
580   // Evaluate if the partition block is a skippable block in Y plane.
581   {
582     unsigned int sse16x16[64] = { 0 };
583     int sum16x16[64] = { 0 };
584     unsigned int var16x16[64] = { 0 };
585     const int num16x16 = num8x8 >> 2;
586 
587     unsigned int sse32x32[16] = { 0 };
588     int sum32x32[16] = { 0 };
589     unsigned int var32x32[16] = { 0 };
590     const int num32x32 = num8x8 >> 4;
591 
592     int ac_test = 1;
593     int dc_test = 1;
594     const int num = (tx_size == TX_8X8)
595                         ? num8x8
596                         : ((tx_size == TX_16X16) ? num16x16 : num32x32);
597     const unsigned int *sse_tx =
598         (tx_size == TX_8X8) ? sse8x8
599                             : ((tx_size == TX_16X16) ? sse16x16 : sse32x32);
600     const unsigned int *var_tx =
601         (tx_size == TX_8X8) ? var8x8
602                             : ((tx_size == TX_16X16) ? var16x16 : var32x32);
603 
604     // Calculate variance if tx_size > TX_8X8
605     if (tx_size >= TX_16X16)
606       calculate_variance(bw, bh, TX_8X8, sse8x8, sum8x8, var16x16, sse16x16,
607                          sum16x16);
608     if (tx_size == TX_32X32)
609       calculate_variance(bw, bh, TX_16X16, sse16x16, sum16x16, var32x32,
610                          sse32x32, sum32x32);
611 
612     // Skipping test
613     *early_term = 0;
614     for (k = 0; k < num; k++)
615       // Check if all ac coefficients can be quantized to zero.
616       if (!(var_tx[k] < ac_thr || var == 0)) {
617         ac_test = 0;
618         break;
619       }
620 
621     for (k = 0; k < num; k++)
622       // Check if dc coefficient can be quantized to zero.
623       if (!(sse_tx[k] - var_tx[k] < dc_thr || sse == var)) {
624         dc_test = 0;
625         break;
626       }
627 
628     if (ac_test && dc_test) {
629       int skip_uv[2] = { 0 };
630       unsigned int var_uv[2];
631       unsigned int sse_uv[2];
632       AV1_COMMON *const cm = &cpi->common;
633       // Transform skipping test in UV planes.
634       for (int i = 1; i <= 2; i++) {
635         int j = i - 1;
636         skip_uv[j] = 1;
637         if (x->color_sensitivity[j]) {
638           skip_uv[j] = 0;
639           struct macroblock_plane *const puv = &x->plane[i];
640           struct macroblockd_plane *const puvd = &xd->plane[i];
641           const BLOCK_SIZE uv_bsize = get_plane_block_size(
642               bsize, puvd->subsampling_x, puvd->subsampling_y);
643           // Adjust these thresholds for UV.
644           const int64_t uv_dc_thr =
645               (puv->dequant_QTX[0] * puv->dequant_QTX[0]) >> 3;
646           const int64_t uv_ac_thr =
647               (puv->dequant_QTX[1] * puv->dequant_QTX[1]) >> 3;
648           av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize, i,
649                                         i);
650           var_uv[j] = cpi->ppi->fn_ptr[uv_bsize].vf(
651               puv->src.buf, puv->src.stride, puvd->dst.buf, puvd->dst.stride,
652               &sse_uv[j]);
653           if ((var_uv[j] < uv_ac_thr || var_uv[j] == 0) &&
654               (sse_uv[j] - var_uv[j] < uv_dc_thr || sse_uv[j] == var_uv[j]))
655             skip_uv[j] = 1;
656           else
657             break;
658         }
659       }
660       if (skip_uv[0] & skip_uv[1]) {
661         *early_term = 1;
662       }
663     }
664   }
665   if (calculate_rd) {
666     if (!*early_term) {
667       const int bwide = block_size_wide[bsize];
668       const int bhigh = block_size_high[bsize];
669 
670       model_rd_with_curvfit(cpi, x, bsize, AOM_PLANE_Y, sse, bwide * bhigh,
671                             &rd_stats->rate, &rd_stats->dist);
672     }
673 
674     if (*early_term) {
675       rd_stats->rate = 0;
676       rd_stats->dist = sse << 4;
677     }
678   }
679 }
680 
model_rd_for_sb_y(const AV1_COMP * const cpi,BLOCK_SIZE bsize,MACROBLOCK * x,MACROBLOCKD * xd,RD_STATS * rd_stats,int calculate_rd)681 static void model_rd_for_sb_y(const AV1_COMP *const cpi, BLOCK_SIZE bsize,
682                               MACROBLOCK *x, MACROBLOCKD *xd,
683                               RD_STATS *rd_stats, int calculate_rd) {
684   // Note our transform coeffs are 8 times an orthogonal transform.
685   // Hence quantizer step is also 8 times. To get effective quantizer
686   // we need to divide by 8 before sending to modeling function.
687   const int ref = xd->mi[0]->ref_frame[0];
688 
689   assert(bsize < BLOCK_SIZES_ALL);
690 
691   struct macroblock_plane *const p = &x->plane[0];
692   struct macroblockd_plane *const pd = &xd->plane[0];
693   unsigned int sse;
694   int rate;
695   int64_t dist;
696 
697   unsigned int var = cpi->ppi->fn_ptr[bsize].vf(
698       p->src.buf, p->src.stride, pd->dst.buf, pd->dst.stride, &sse);
699   xd->mi[0]->tx_size = calculate_tx_size(cpi, bsize, x, var, sse);
700 
701   if (calculate_rd) {
702     const int bwide = block_size_wide[bsize];
703     const int bhigh = block_size_high[bsize];
704     model_rd_with_curvfit(cpi, x, bsize, AOM_PLANE_Y, sse, bwide * bhigh, &rate,
705                           &dist);
706   } else {
707     rate = INT_MAX;  // this will be overwritten later with block_yrd
708     dist = INT_MAX;
709   }
710   rd_stats->sse = sse;
711   x->pred_sse[ref] = (unsigned int)AOMMIN(sse, UINT_MAX);
712 
713   assert(rate >= 0);
714 
715   rd_stats->skip_txfm = (rate == 0);
716   rate = AOMMIN(rate, INT_MAX);
717   rd_stats->rate = rate;
718   rd_stats->dist = dist;
719 }
720 
721 /*!\brief Calculates RD Cost using Hadamard transform.
722  *
723  * \ingroup nonrd_mode_search
724  * \callgraph
725  * \callergraph
726  * Calculates RD Cost using Hadamard transform. For low bit depth this function
727  * uses low-precision set of functions (16-bit) and 32 bit for high bit depth
728  * \param[in]    cpi            Top-level encoder structure
729  * \param[in]    x              Pointer to structure holding all the data for
730                                 the current macroblock
731  * \param[in]    mi_row         Row index in 4x4 units
732  * \param[in]    mi_col         Column index in 4x4 units
733  * \param[in]    this_rdc       Pointer to calculated RD Cost
734  * \param[in]    skippable      Pointer to a flag indicating possible tx skip
735  * \param[in]    bsize          Current block size
736  * \param[in]    tx_size        Transform size
737  *
738  * \return Nothing is returned. Instead, calculated RD cost is placed to
739  * \c this_rdc. \c skippable flag is set if there is no non-zero quantized
740  * coefficients for Hadamard transform
741  */
block_yrd(AV1_COMP * cpi,MACROBLOCK * x,int mi_row,int mi_col,RD_STATS * this_rdc,int * skippable,BLOCK_SIZE bsize,TX_SIZE tx_size)742 static void block_yrd(AV1_COMP *cpi, MACROBLOCK *x, int mi_row, int mi_col,
743                       RD_STATS *this_rdc, int *skippable, BLOCK_SIZE bsize,
744                       TX_SIZE tx_size) {
745   MACROBLOCKD *xd = &x->e_mbd;
746   const struct macroblockd_plane *pd = &xd->plane[0];
747   struct macroblock_plane *const p = &x->plane[0];
748   const int num_4x4_w = mi_size_wide[bsize];
749   const int num_4x4_h = mi_size_high[bsize];
750   const int step = 1 << (tx_size << 1);
751   const int block_step = (1 << tx_size);
752   int block = 0;
753   const int max_blocks_wide =
754       num_4x4_w + (xd->mb_to_right_edge >= 0 ? 0 : xd->mb_to_right_edge >> 5);
755   const int max_blocks_high =
756       num_4x4_h + (xd->mb_to_bottom_edge >= 0 ? 0 : xd->mb_to_bottom_edge >> 5);
757   int eob_cost = 0;
758   const int bw = 4 * num_4x4_w;
759   const int bh = 4 * num_4x4_h;
760 
761   (void)mi_row;
762   (void)mi_col;
763   (void)cpi;
764 
765 #if CONFIG_AV1_HIGHBITDEPTH
766   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
767     aom_highbd_subtract_block(bh, bw, p->src_diff, bw, p->src.buf,
768                               p->src.stride, pd->dst.buf, pd->dst.stride,
769                               x->e_mbd.bd);
770   } else {
771     aom_subtract_block(bh, bw, p->src_diff, bw, p->src.buf, p->src.stride,
772                        pd->dst.buf, pd->dst.stride);
773   }
774 #else
775   aom_subtract_block(bh, bw, p->src_diff, bw, p->src.buf, p->src.stride,
776                      pd->dst.buf, pd->dst.stride);
777 #endif
778 
779   *skippable = 1;
780   // Keep track of the row and column of the blocks we use so that we know
781   // if we are in the unrestricted motion border.
782   for (int r = 0; r < max_blocks_high; r += block_step) {
783     for (int c = 0; c < num_4x4_w; c += block_step) {
784       if (c < max_blocks_wide) {
785         const SCAN_ORDER *const scan_order = &av1_scan_orders[tx_size][DCT_DCT];
786         const int block_offset = BLOCK_OFFSET(block);
787 #if CONFIG_AV1_HIGHBITDEPTH
788         tran_low_t *const coeff = p->coeff + block_offset;
789         tran_low_t *const qcoeff = p->qcoeff + block_offset;
790         tran_low_t *const dqcoeff = p->dqcoeff + block_offset;
791 #else
792         int16_t *const low_coeff = (int16_t *)p->coeff + block_offset;
793         int16_t *const low_qcoeff = (int16_t *)p->qcoeff + block_offset;
794         int16_t *const low_dqcoeff = (int16_t *)p->dqcoeff + block_offset;
795 #endif
796         uint16_t *const eob = &p->eobs[block];
797         const int diff_stride = bw;
798         const int16_t *src_diff;
799         src_diff = &p->src_diff[(r * diff_stride + c) << 2];
800 
801         switch (tx_size) {
802           case TX_64X64:
803             assert(0);  // Not implemented
804             break;
805           case TX_32X32:
806             assert(0);  // Not used
807             break;
808 #if CONFIG_AV1_HIGHBITDEPTH
809           case TX_16X16:
810             aom_hadamard_16x16(src_diff, diff_stride, coeff);
811             av1_quantize_fp(coeff, 16 * 16, p->zbin_QTX, p->round_fp_QTX,
812                             p->quant_fp_QTX, p->quant_shift_QTX, qcoeff,
813                             dqcoeff, p->dequant_QTX, eob, scan_order->scan,
814                             scan_order->iscan);
815             break;
816           case TX_8X8:
817             aom_hadamard_8x8(src_diff, diff_stride, coeff);
818             av1_quantize_fp(coeff, 8 * 8, p->zbin_QTX, p->round_fp_QTX,
819                             p->quant_fp_QTX, p->quant_shift_QTX, qcoeff,
820                             dqcoeff, p->dequant_QTX, eob, scan_order->scan,
821                             scan_order->iscan);
822             break;
823           default:
824             assert(tx_size == TX_4X4);
825             aom_fdct4x4(src_diff, coeff, diff_stride);
826             av1_quantize_fp(coeff, 4 * 4, p->zbin_QTX, p->round_fp_QTX,
827                             p->quant_fp_QTX, p->quant_shift_QTX, qcoeff,
828                             dqcoeff, p->dequant_QTX, eob, scan_order->scan,
829                             scan_order->iscan);
830             break;
831 #else
832           case TX_16X16:
833             aom_hadamard_lp_16x16(src_diff, diff_stride, low_coeff);
834             av1_quantize_lp(low_coeff, 16 * 16, p->round_fp_QTX,
835                             p->quant_fp_QTX, low_qcoeff, low_dqcoeff,
836                             p->dequant_QTX, eob, scan_order->scan,
837                             scan_order->iscan);
838             break;
839           case TX_8X8:
840             aom_hadamard_lp_8x8(src_diff, diff_stride, low_coeff);
841             av1_quantize_lp(low_coeff, 8 * 8, p->round_fp_QTX, p->quant_fp_QTX,
842                             low_qcoeff, low_dqcoeff, p->dequant_QTX, eob,
843                             scan_order->scan, scan_order->iscan);
844             break;
845           default:
846             assert(tx_size == TX_4X4);
847             aom_fdct4x4_lp(src_diff, low_coeff, diff_stride);
848             av1_quantize_lp(low_coeff, 4 * 4, p->round_fp_QTX, p->quant_fp_QTX,
849                             low_qcoeff, low_dqcoeff, p->dequant_QTX, eob,
850                             scan_order->scan, scan_order->iscan);
851             break;
852 #endif
853         }
854         assert(*eob <= 1024);
855         *skippable &= (*eob == 0);
856         eob_cost += 1;
857       }
858       block += step;
859     }
860   }
861   this_rdc->skip_txfm = *skippable;
862   this_rdc->rate = 0;
863   if (this_rdc->sse < INT64_MAX) {
864     this_rdc->sse = (this_rdc->sse << 6) >> 2;
865     if (*skippable) {
866       this_rdc->dist = this_rdc->sse;
867       return;
868     }
869   }
870 
871   block = 0;
872   this_rdc->dist = 0;
873   for (int r = 0; r < max_blocks_high; r += block_step) {
874     for (int c = 0; c < num_4x4_w; c += block_step) {
875       if (c < max_blocks_wide) {
876         const int block_offset = BLOCK_OFFSET(block);
877         uint16_t *const eob = &p->eobs[block];
878 #if CONFIG_AV1_HIGHBITDEPTH
879         int64_t dummy;
880         tran_low_t *const coeff = p->coeff + block_offset;
881         tran_low_t *const qcoeff = p->qcoeff + block_offset;
882         tran_low_t *const dqcoeff = p->dqcoeff + block_offset;
883 
884         if (*eob == 1)
885           this_rdc->rate += (int)abs(qcoeff[0]);
886         else if (*eob > 1)
887           this_rdc->rate += aom_satd(qcoeff, step << 4);
888 
889         this_rdc->dist +=
890             av1_block_error(coeff, dqcoeff, step << 4, &dummy) >> 2;
891 #else
892         int16_t *const low_coeff = (int16_t *)p->coeff + block_offset;
893         int16_t *const low_qcoeff = (int16_t *)p->qcoeff + block_offset;
894         int16_t *const low_dqcoeff = (int16_t *)p->dqcoeff + block_offset;
895 
896         if (*eob == 1)
897           this_rdc->rate += (int)abs(low_qcoeff[0]);
898         else if (*eob > 1)
899           this_rdc->rate += aom_satd_lp(low_qcoeff, step << 4);
900 
901         this_rdc->dist +=
902             av1_block_error_lp(low_coeff, low_dqcoeff, step << 4) >> 2;
903 #endif
904       }
905       block += step;
906     }
907   }
908 
909   // If skippable is set, rate gets clobbered later.
910   this_rdc->rate <<= (2 + AV1_PROB_COST_SHIFT);
911   this_rdc->rate += (eob_cost << AV1_PROB_COST_SHIFT);
912 }
913 
init_mbmi(MB_MODE_INFO * mbmi,PREDICTION_MODE pred_mode,MV_REFERENCE_FRAME ref_frame0,MV_REFERENCE_FRAME ref_frame1,const AV1_COMMON * cm)914 static INLINE void init_mbmi(MB_MODE_INFO *mbmi, PREDICTION_MODE pred_mode,
915                              MV_REFERENCE_FRAME ref_frame0,
916                              MV_REFERENCE_FRAME ref_frame1,
917                              const AV1_COMMON *cm) {
918   PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
919   mbmi->ref_mv_idx = 0;
920   mbmi->mode = pred_mode;
921   mbmi->uv_mode = UV_DC_PRED;
922   mbmi->ref_frame[0] = ref_frame0;
923   mbmi->ref_frame[1] = ref_frame1;
924   pmi->palette_size[0] = 0;
925   pmi->palette_size[1] = 0;
926   mbmi->filter_intra_mode_info.use_filter_intra = 0;
927   mbmi->mv[0].as_int = mbmi->mv[1].as_int = 0;
928   mbmi->motion_mode = SIMPLE_TRANSLATION;
929   mbmi->num_proj_ref = 1;
930   mbmi->interintra_mode = 0;
931   set_default_interp_filters(mbmi, cm->features.interp_filter);
932 }
933 
934 #if CONFIG_INTERNAL_STATS
store_coding_context(MACROBLOCK * x,PICK_MODE_CONTEXT * ctx,int mode_index)935 static void store_coding_context(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx,
936                                  int mode_index) {
937 #else
938 static void store_coding_context(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
939 #endif  // CONFIG_INTERNAL_STATS
940   MACROBLOCKD *const xd = &x->e_mbd;
941   TxfmSearchInfo *txfm_info = &x->txfm_search_info;
942 
943   // Take a snapshot of the coding context so it can be
944   // restored if we decide to encode this way
945   ctx->rd_stats.skip_txfm = txfm_info->skip_txfm;
946 
947   memset(ctx->blk_skip, 0, sizeof(ctx->blk_skip[0]) * ctx->num_4x4_blk);
948   memset(ctx->tx_type_map, DCT_DCT,
949          sizeof(ctx->tx_type_map[0]) * ctx->num_4x4_blk);
950   ctx->skippable = txfm_info->skip_txfm;
951 #if CONFIG_INTERNAL_STATS
952   ctx->best_mode_index = mode_index;
953 #endif  // CONFIG_INTERNAL_STATS
954   ctx->mic = *xd->mi[0];
955   ctx->skippable = txfm_info->skip_txfm;
956   av1_copy_mbmi_ext_to_mbmi_ext_frame(&ctx->mbmi_ext_best, &x->mbmi_ext,
957                                       av1_ref_frame_type(xd->mi[0]->ref_frame));
958   ctx->comp_pred_diff = 0;
959   ctx->hybrid_pred_diff = 0;
960   ctx->single_pred_diff = 0;
961 }
962 
963 static int get_pred_buffer(PRED_BUFFER *p, int len) {
964   for (int i = 0; i < len; i++) {
965     if (!p[i].in_use) {
966       p[i].in_use = 1;
967       return i;
968     }
969   }
970   return -1;
971 }
972 
973 static void free_pred_buffer(PRED_BUFFER *p) {
974   if (p != NULL) p->in_use = 0;
975 }
976 
977 static int cost_mv_ref(const ModeCosts *const mode_costs, PREDICTION_MODE mode,
978                        int16_t mode_context) {
979   if (is_inter_compound_mode(mode)) {
980     return mode_costs
981         ->inter_compound_mode_cost[mode_context][INTER_COMPOUND_OFFSET(mode)];
982   }
983 
984   int mode_cost = 0;
985   int16_t mode_ctx = mode_context & NEWMV_CTX_MASK;
986 
987   assert(is_inter_mode(mode));
988 
989   if (mode == NEWMV) {
990     mode_cost = mode_costs->newmv_mode_cost[mode_ctx][0];
991     return mode_cost;
992   } else {
993     mode_cost = mode_costs->newmv_mode_cost[mode_ctx][1];
994     mode_ctx = (mode_context >> GLOBALMV_OFFSET) & GLOBALMV_CTX_MASK;
995 
996     if (mode == GLOBALMV) {
997       mode_cost += mode_costs->zeromv_mode_cost[mode_ctx][0];
998       return mode_cost;
999     } else {
1000       mode_cost += mode_costs->zeromv_mode_cost[mode_ctx][1];
1001       mode_ctx = (mode_context >> REFMV_OFFSET) & REFMV_CTX_MASK;
1002       mode_cost += mode_costs->refmv_mode_cost[mode_ctx][mode != NEARESTMV];
1003       return mode_cost;
1004     }
1005   }
1006 }
1007 
1008 static void newmv_diff_bias(MACROBLOCKD *xd, PREDICTION_MODE this_mode,
1009                             RD_STATS *this_rdc, BLOCK_SIZE bsize, int mv_row,
1010                             int mv_col, int speed, uint32_t spatial_variance,
1011                             CONTENT_STATE_SB content_state_sb) {
1012   // Bias against MVs associated with NEWMV mode that are very different from
1013   // top/left neighbors.
1014   if (this_mode == NEWMV) {
1015     int al_mv_average_row;
1016     int al_mv_average_col;
1017     int left_row, left_col;
1018     int row_diff, col_diff;
1019     int above_mv_valid = 0;
1020     int left_mv_valid = 0;
1021     int above_row = 0;
1022     int above_col = 0;
1023     if (bsize >= BLOCK_64X64 && content_state_sb.source_sad != kHighSad &&
1024         spatial_variance < 300 &&
1025         (mv_row > 16 || mv_row < -16 || mv_col > 16 || mv_col < -16)) {
1026       this_rdc->rdcost = this_rdc->rdcost << 2;
1027       return;
1028     }
1029     if (xd->above_mbmi) {
1030       above_mv_valid = xd->above_mbmi->mv[0].as_int != INVALID_MV;
1031       above_row = xd->above_mbmi->mv[0].as_mv.row;
1032       above_col = xd->above_mbmi->mv[0].as_mv.col;
1033     }
1034     if (xd->left_mbmi) {
1035       left_mv_valid = xd->left_mbmi->mv[0].as_int != INVALID_MV;
1036       left_row = xd->left_mbmi->mv[0].as_mv.row;
1037       left_col = xd->left_mbmi->mv[0].as_mv.col;
1038     }
1039     if (above_mv_valid && left_mv_valid) {
1040       al_mv_average_row = (above_row + left_row + 1) >> 1;
1041       al_mv_average_col = (above_col + left_col + 1) >> 1;
1042     } else if (above_mv_valid) {
1043       al_mv_average_row = above_row;
1044       al_mv_average_col = above_col;
1045     } else if (left_mv_valid) {
1046       al_mv_average_row = left_row;
1047       al_mv_average_col = left_col;
1048     } else {
1049       al_mv_average_row = al_mv_average_col = 0;
1050     }
1051     row_diff = al_mv_average_row - mv_row;
1052     col_diff = al_mv_average_col - mv_col;
1053     if (row_diff > 80 || row_diff < -80 || col_diff > 80 || col_diff < -80) {
1054       if (bsize >= BLOCK_32X32)
1055         this_rdc->rdcost = this_rdc->rdcost << 1;
1056       else
1057         this_rdc->rdcost = 5 * this_rdc->rdcost >> 2;
1058     }
1059   } else {
1060     // Bias for speed >= 8 for low spatial variance.
1061     if (speed >= 8 && spatial_variance < 150 &&
1062         (mv_row > 64 || mv_row < -64 || mv_col > 64 || mv_col < -64))
1063       this_rdc->rdcost = 5 * this_rdc->rdcost >> 2;
1064   }
1065 }
1066 
1067 static void model_rd_for_sb_uv(AV1_COMP *cpi, BLOCK_SIZE plane_bsize,
1068                                MACROBLOCK *x, MACROBLOCKD *xd,
1069                                RD_STATS *this_rdc, int64_t *sse_y,
1070                                int start_plane, int stop_plane) {
1071   // Note our transform coeffs are 8 times an orthogonal transform.
1072   // Hence quantizer step is also 8 times. To get effective quantizer
1073   // we need to divide by 8 before sending to modeling function.
1074   unsigned int sse;
1075   int rate;
1076   int64_t dist;
1077   int i;
1078   int64_t tot_sse = *sse_y;
1079 
1080   this_rdc->rate = 0;
1081   this_rdc->dist = 0;
1082   this_rdc->skip_txfm = 0;
1083 
1084   for (i = start_plane; i <= stop_plane; ++i) {
1085     struct macroblock_plane *const p = &x->plane[i];
1086     struct macroblockd_plane *const pd = &xd->plane[i];
1087     const uint32_t dc_quant = p->dequant_QTX[0];
1088     const uint32_t ac_quant = p->dequant_QTX[1];
1089     const BLOCK_SIZE bs = plane_bsize;
1090     unsigned int var;
1091     if (!x->color_sensitivity[i - 1]) continue;
1092 
1093     var = cpi->ppi->fn_ptr[bs].vf(p->src.buf, p->src.stride, pd->dst.buf,
1094                                   pd->dst.stride, &sse);
1095     assert(sse >= var);
1096     tot_sse += sse;
1097 
1098     av1_model_rd_from_var_lapndz(sse - var, num_pels_log2_lookup[bs],
1099                                  dc_quant >> 3, &rate, &dist);
1100 
1101     this_rdc->rate += rate >> 1;
1102     this_rdc->dist += dist << 3;
1103 
1104     av1_model_rd_from_var_lapndz(var, num_pels_log2_lookup[bs], ac_quant >> 3,
1105                                  &rate, &dist);
1106 
1107     this_rdc->rate += rate;
1108     this_rdc->dist += dist << 4;
1109   }
1110 
1111   if (this_rdc->rate == 0) {
1112     this_rdc->skip_txfm = 1;
1113   }
1114 
1115   if (RDCOST(x->rdmult, this_rdc->rate, this_rdc->dist) >=
1116       RDCOST(x->rdmult, 0, tot_sse << 4)) {
1117     this_rdc->rate = 0;
1118     this_rdc->dist = tot_sse << 4;
1119     this_rdc->skip_txfm = 1;
1120   }
1121 
1122   *sse_y = tot_sse;
1123 }
1124 
1125 /*!\cond */
1126 struct estimate_block_intra_args {
1127   AV1_COMP *cpi;
1128   MACROBLOCK *x;
1129   PREDICTION_MODE mode;
1130   int skippable;
1131   RD_STATS *rdc;
1132 };
1133 /*!\endcond */
1134 
1135 /*!\brief Estimation of RD cost of an intra mode for Non-RD optimized case.
1136  *
1137  * \ingroup nonrd_mode_search
1138  * \callgraph
1139  * \callergraph
1140  * Calculates RD Cost for an intra mode for a single TX block using Hadamard
1141  * transform.
1142  * \param[in]    plane          Color plane
1143  * \param[in]    block          Index of a TX block in a prediction block
1144  * \param[in]    row            Row of a current TX block
1145  * \param[in]    col            Column of a current TX block
1146  * \param[in]    plane_bsize    Block size of a current prediction block
1147  * \param[in]    tx_size        Transform size
1148  * \param[in]    arg            Pointer to a structure that holds paramaters
1149  *                              for intra mode search
1150  *
1151  * \return Nothing is returned. Instead, best mode and RD Cost of the best mode
1152  * are set in \c args->rdc and \c args->mode
1153  */
1154 static void estimate_block_intra(int plane, int block, int row, int col,
1155                                  BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
1156                                  void *arg) {
1157   struct estimate_block_intra_args *const args = arg;
1158   AV1_COMP *const cpi = args->cpi;
1159   AV1_COMMON *const cm = &cpi->common;
1160   MACROBLOCK *const x = args->x;
1161   MACROBLOCKD *const xd = &x->e_mbd;
1162   struct macroblock_plane *const p = &x->plane[plane];
1163   struct macroblockd_plane *const pd = &xd->plane[plane];
1164   const BLOCK_SIZE bsize_tx = txsize_to_bsize[tx_size];
1165   uint8_t *const src_buf_base = p->src.buf;
1166   uint8_t *const dst_buf_base = pd->dst.buf;
1167   const int64_t src_stride = p->src.stride;
1168   const int64_t dst_stride = pd->dst.stride;
1169   RD_STATS this_rdc;
1170 
1171   (void)block;
1172 
1173   av1_predict_intra_block_facade(cm, xd, plane, col, row, tx_size);
1174   av1_invalid_rd_stats(&this_rdc);
1175 
1176   p->src.buf = &src_buf_base[4 * (row * src_stride + col)];
1177   pd->dst.buf = &dst_buf_base[4 * (row * dst_stride + col)];
1178 
1179   if (plane == 0) {
1180     block_yrd(cpi, x, 0, 0, &this_rdc, &args->skippable, bsize_tx,
1181               AOMMIN(tx_size, TX_16X16));
1182   } else {
1183     int64_t sse = 0;
1184     model_rd_for_sb_uv(cpi, plane_bsize, x, xd, &this_rdc, &sse, plane, plane);
1185   }
1186 
1187   p->src.buf = src_buf_base;
1188   pd->dst.buf = dst_buf_base;
1189   args->rdc->rate += this_rdc.rate;
1190   args->rdc->dist += this_rdc.dist;
1191 }
1192 
1193 static INLINE void update_thresh_freq_fact(AV1_COMP *cpi, MACROBLOCK *x,
1194                                            BLOCK_SIZE bsize,
1195                                            MV_REFERENCE_FRAME ref_frame,
1196                                            THR_MODES best_mode_idx,
1197                                            PREDICTION_MODE mode) {
1198   const THR_MODES thr_mode_idx = mode_idx[ref_frame][mode_offset(mode)];
1199   const BLOCK_SIZE min_size = AOMMAX(bsize - 3, BLOCK_4X4);
1200   const BLOCK_SIZE max_size = AOMMIN(bsize + 6, BLOCK_128X128);
1201   for (BLOCK_SIZE bs = min_size; bs <= max_size; bs += 3) {
1202     int *freq_fact = &x->thresh_freq_fact[bs][thr_mode_idx];
1203     if (thr_mode_idx == best_mode_idx) {
1204       *freq_fact -= (*freq_fact >> 4);
1205     } else {
1206       *freq_fact =
1207           AOMMIN(*freq_fact + RD_THRESH_INC,
1208                  cpi->sf.inter_sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT);
1209     }
1210   }
1211 }
1212 
1213 #if CONFIG_AV1_TEMPORAL_DENOISING
1214 static void av1_pickmode_ctx_den_update(
1215     AV1_PICKMODE_CTX_DEN *ctx_den, int64_t zero_last_cost_orig,
1216     unsigned int ref_frame_cost[REF_FRAMES],
1217     int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES], int reuse_inter_pred,
1218     BEST_PICKMODE *bp) {
1219   ctx_den->zero_last_cost_orig = zero_last_cost_orig;
1220   ctx_den->ref_frame_cost = ref_frame_cost;
1221   ctx_den->frame_mv = frame_mv;
1222   ctx_den->reuse_inter_pred = reuse_inter_pred;
1223   ctx_den->best_tx_size = bp->best_tx_size;
1224   ctx_den->best_mode = bp->best_mode;
1225   ctx_den->best_ref_frame = bp->best_ref_frame;
1226   ctx_den->best_pred_filter = bp->best_pred_filter;
1227   ctx_den->best_mode_skip_txfm = bp->best_mode_skip_txfm;
1228 }
1229 
1230 static void recheck_zeromv_after_denoising(
1231     AV1_COMP *cpi, MB_MODE_INFO *const mi, MACROBLOCK *x, MACROBLOCKD *const xd,
1232     AV1_DENOISER_DECISION decision, AV1_PICKMODE_CTX_DEN *ctx_den,
1233     struct buf_2d yv12_mb[4][MAX_MB_PLANE], RD_STATS *best_rdc,
1234     BEST_PICKMODE *best_pickmode, BLOCK_SIZE bsize, int mi_row, int mi_col) {
1235   // If INTRA or GOLDEN reference was selected, re-evaluate ZEROMV on
1236   // denoised result. Only do this under noise conditions, and if rdcost of
1237   // ZEROMV onoriginal source is not significantly higher than rdcost of best
1238   // mode.
1239   if (cpi->noise_estimate.enabled && cpi->noise_estimate.level > kLow &&
1240       ctx_den->zero_last_cost_orig < (best_rdc->rdcost << 3) &&
1241       ((ctx_den->best_ref_frame == INTRA_FRAME && decision >= FILTER_BLOCK) ||
1242        (ctx_den->best_ref_frame == GOLDEN_FRAME &&
1243         cpi->svc.number_spatial_layers == 1 &&
1244         decision == FILTER_ZEROMV_BLOCK))) {
1245     // Check if we should pick ZEROMV on denoised signal.
1246     AV1_COMMON *const cm = &cpi->common;
1247     RD_STATS this_rdc;
1248     const ModeCosts *mode_costs = &x->mode_costs;
1249     TxfmSearchInfo *txfm_info = &x->txfm_search_info;
1250     MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
1251 
1252     mi->mode = GLOBALMV;
1253     mi->ref_frame[0] = LAST_FRAME;
1254     mi->ref_frame[1] = NONE_FRAME;
1255     set_ref_ptrs(cm, xd, mi->ref_frame[0], NONE_FRAME);
1256     mi->mv[0].as_int = 0;
1257     mi->interp_filters = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
1258     xd->plane[0].pre[0] = yv12_mb[LAST_FRAME][0];
1259     av1_enc_build_inter_predictor_y(xd, mi_row, mi_col);
1260     model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc, 1);
1261 
1262     const int16_t mode_ctx =
1263         av1_mode_context_analyzer(mbmi_ext->mode_context, mi->ref_frame);
1264     this_rdc.rate += cost_mv_ref(mode_costs, GLOBALMV, mode_ctx);
1265 
1266     this_rdc.rate += ctx_den->ref_frame_cost[LAST_FRAME];
1267     this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
1268     txfm_info->skip_txfm = this_rdc.skip_txfm;
1269     // Don't switch to ZEROMV if the rdcost for ZEROMV on denoised source
1270     // is higher than best_ref mode (on original source).
1271     if (this_rdc.rdcost > best_rdc->rdcost) {
1272       this_rdc = *best_rdc;
1273       mi->mode = best_pickmode->best_mode;
1274       mi->ref_frame[0] = best_pickmode->best_ref_frame;
1275       set_ref_ptrs(cm, xd, mi->ref_frame[0], NONE_FRAME);
1276       mi->interp_filters = best_pickmode->best_pred_filter;
1277       if (best_pickmode->best_ref_frame == INTRA_FRAME) {
1278         mi->mv[0].as_int = INVALID_MV;
1279       } else {
1280         mi->mv[0].as_int = ctx_den
1281                                ->frame_mv[best_pickmode->best_mode]
1282                                          [best_pickmode->best_ref_frame]
1283                                .as_int;
1284         if (ctx_den->reuse_inter_pred) {
1285           xd->plane[0].pre[0] = yv12_mb[GOLDEN_FRAME][0];
1286           av1_enc_build_inter_predictor_y(xd, mi_row, mi_col);
1287         }
1288       }
1289       mi->tx_size = best_pickmode->best_tx_size;
1290       txfm_info->skip_txfm = best_pickmode->best_mode_skip_txfm;
1291     } else {
1292       ctx_den->best_ref_frame = LAST_FRAME;
1293       *best_rdc = this_rdc;
1294     }
1295   }
1296 }
1297 #endif  // CONFIG_AV1_TEMPORAL_DENOISING
1298 
1299 static INLINE int get_force_skip_low_temp_var_small_sb(uint8_t *variance_low,
1300                                                        int mi_row, int mi_col,
1301                                                        BLOCK_SIZE bsize) {
1302   // Relative indices of MB inside the superblock.
1303   const int mi_x = mi_row & 0xF;
1304   const int mi_y = mi_col & 0xF;
1305   // Relative indices of 16x16 block inside the superblock.
1306   const int i = mi_x >> 2;
1307   const int j = mi_y >> 2;
1308   int force_skip_low_temp_var = 0;
1309   // Set force_skip_low_temp_var based on the block size and block offset.
1310   switch (bsize) {
1311     case BLOCK_64X64: force_skip_low_temp_var = variance_low[0]; break;
1312     case BLOCK_64X32:
1313       if (!mi_y && !mi_x) {
1314         force_skip_low_temp_var = variance_low[1];
1315       } else if (!mi_y && mi_x) {
1316         force_skip_low_temp_var = variance_low[2];
1317       }
1318       break;
1319     case BLOCK_32X64:
1320       if (!mi_y && !mi_x) {
1321         force_skip_low_temp_var = variance_low[3];
1322       } else if (mi_y && !mi_x) {
1323         force_skip_low_temp_var = variance_low[4];
1324       }
1325       break;
1326     case BLOCK_32X32:
1327       if (!mi_y && !mi_x) {
1328         force_skip_low_temp_var = variance_low[5];
1329       } else if (mi_y && !mi_x) {
1330         force_skip_low_temp_var = variance_low[6];
1331       } else if (!mi_y && mi_x) {
1332         force_skip_low_temp_var = variance_low[7];
1333       } else if (mi_y && mi_x) {
1334         force_skip_low_temp_var = variance_low[8];
1335       }
1336       break;
1337     case BLOCK_32X16:
1338     case BLOCK_16X32:
1339     case BLOCK_16X16:
1340       force_skip_low_temp_var = variance_low[pos_shift_16x16[i][j]];
1341       break;
1342     default: break;
1343   }
1344 
1345   return force_skip_low_temp_var;
1346 }
1347 
1348 static INLINE int get_force_skip_low_temp_var(uint8_t *variance_low, int mi_row,
1349                                               int mi_col, BLOCK_SIZE bsize) {
1350   int force_skip_low_temp_var = 0;
1351   int x, y;
1352   x = (mi_col & 0x1F) >> 4;
1353   // y = (mi_row & 0x1F) >> 4;
1354   // const int idx64 = (y << 1) + x;
1355   y = (mi_row & 0x17) >> 3;
1356   const int idx64 = y + x;
1357 
1358   x = (mi_col & 0xF) >> 3;
1359   // y = (mi_row & 0xF) >> 3;
1360   // const int idx32 = (y << 1) + x;
1361   y = (mi_row & 0xB) >> 2;
1362   const int idx32 = y + x;
1363 
1364   x = (mi_col & 0x7) >> 2;
1365   // y = (mi_row & 0x7) >> 2;
1366   // const int idx16 = (y << 1) + x;
1367   y = (mi_row & 0x5) >> 1;
1368   const int idx16 = y + x;
1369   // Set force_skip_low_temp_var based on the block size and block offset.
1370   switch (bsize) {
1371     case BLOCK_128X128: force_skip_low_temp_var = variance_low[0]; break;
1372     case BLOCK_128X64:
1373       assert((mi_col & 0x1F) == 0);
1374       force_skip_low_temp_var = variance_low[1 + ((mi_row & 0x1F) != 0)];
1375       break;
1376     case BLOCK_64X128:
1377       assert((mi_row & 0x1F) == 0);
1378       force_skip_low_temp_var = variance_low[3 + ((mi_col & 0x1F) != 0)];
1379       break;
1380     case BLOCK_64X64:
1381       // Location of this 64x64 block inside the 128x128 superblock
1382       force_skip_low_temp_var = variance_low[5 + idx64];
1383       break;
1384     case BLOCK_64X32:
1385       x = (mi_col & 0x1F) >> 4;
1386       y = (mi_row & 0x1F) >> 3;
1387       /*
1388       .---------------.---------------.
1389       | x=0,y=0,idx=0 | x=0,y=0,idx=2 |
1390       :---------------+---------------:
1391       | x=0,y=1,idx=1 | x=1,y=1,idx=3 |
1392       :---------------+---------------:
1393       | x=0,y=2,idx=4 | x=1,y=2,idx=6 |
1394       :---------------+---------------:
1395       | x=0,y=3,idx=5 | x=1,y=3,idx=7 |
1396       '---------------'---------------'
1397       */
1398       const int idx64x32 = (x << 1) + (y % 2) + ((y >> 1) << 2);
1399       force_skip_low_temp_var = variance_low[9 + idx64x32];
1400       break;
1401     case BLOCK_32X64:
1402       x = (mi_col & 0x1F) >> 3;
1403       y = (mi_row & 0x1F) >> 4;
1404       const int idx32x64 = (y << 2) + x;
1405       force_skip_low_temp_var = variance_low[17 + idx32x64];
1406       break;
1407     case BLOCK_32X32:
1408       force_skip_low_temp_var = variance_low[25 + (idx64 << 2) + idx32];
1409       break;
1410     case BLOCK_32X16:
1411     case BLOCK_16X32:
1412     case BLOCK_16X16:
1413       force_skip_low_temp_var =
1414           variance_low[41 + (idx64 << 4) + (idx32 << 2) + idx16];
1415       break;
1416     default: break;
1417   }
1418   return force_skip_low_temp_var;
1419 }
1420 
1421 #define FILTER_SEARCH_SIZE 2
1422 
1423 /*!\brief Searches for the best intrpolation filter
1424  *
1425  * \ingroup nonrd_mode_search
1426  * \callgraph
1427  * \callergraph
1428  * Iterates through subset of possible interpolation filters (EIGHTTAP_REGULAR,
1429  * EIGTHTAP_SMOOTH, MULTITAP_SHARP, depending on FILTER_SEARCH_SIZE) and selects
1430  * the one that gives lowest RD cost. RD cost is calculated using curvfit model.
1431  * Support for dual filters (different filters in the x & y directions) is
1432  * allowed if sf.interp_sf.disable_dual_filter = 0.
1433  *
1434  * \param[in]    cpi                  Top-level encoder structure
1435  * \param[in]    x                    Pointer to structure holding all the
1436  *                                    data for the current macroblock
1437  * \param[in]    this_rdc             Pointer to calculated RD Cost
1438  * \param[in]    mi_row               Row index in 4x4 units
1439  * \param[in]    mi_col               Column index in 4x4 units
1440  * \param[in]    tmp                  Pointer to a temporary buffer for
1441  *                                    prediction re-use
1442  * \param[in]    bsize                Current block size
1443  * \param[in]    reuse_inter_pred     Flag, indicating prediction re-use
1444  * \param[out]   this_mode_pred       Pointer to store prediction buffer
1445  *                                    for prediction re-use
1446  * \param[out]   this_early_term      Flag, indicating that transform can be
1447  *                                    skipped
1448  * \param[in]    use_model_yrd_large  Flag, indicating special logic to handle
1449  *                                    large blocks
1450  *
1451  * \return Nothing is returned. Instead, calculated RD cost is placed to
1452  * \c this_rdc and best filter is placed to \c mi->interp_filters. In case
1453  * \c reuse_inter_pred flag is set, this function also ouputs
1454  * \c this_mode_pred. Also \c this_early_temp is set if transform can be
1455  * skipped
1456  */
1457 static void search_filter_ref(AV1_COMP *cpi, MACROBLOCK *x, RD_STATS *this_rdc,
1458                               int mi_row, int mi_col, PRED_BUFFER *tmp,
1459                               BLOCK_SIZE bsize, int reuse_inter_pred,
1460                               PRED_BUFFER **this_mode_pred,
1461                               int *this_early_term, int use_model_yrd_large) {
1462   AV1_COMMON *const cm = &cpi->common;
1463   MACROBLOCKD *const xd = &x->e_mbd;
1464   struct macroblockd_plane *const pd = &xd->plane[0];
1465   MB_MODE_INFO *const mi = xd->mi[0];
1466   const int bw = block_size_wide[bsize];
1467   int dim_factor =
1468       (cpi->sf.interp_sf.disable_dual_filter == 0) ? FILTER_SEARCH_SIZE : 1;
1469   RD_STATS pf_rd_stats[FILTER_SEARCH_SIZE * FILTER_SEARCH_SIZE] = { 0 };
1470   TX_SIZE pf_tx_size[FILTER_SEARCH_SIZE * FILTER_SEARCH_SIZE] = { 0 };
1471   PRED_BUFFER *current_pred = *this_mode_pred;
1472   int best_skip = 0;
1473   int best_early_term = 0;
1474   int64_t best_cost = INT64_MAX;
1475   int best_filter_index = -1;
1476   for (int i = 0; i < FILTER_SEARCH_SIZE * FILTER_SEARCH_SIZE; ++i) {
1477     int64_t cost;
1478     if (cpi->sf.interp_sf.disable_dual_filter &&
1479         filters_ref_set[i].filter_x != filters_ref_set[i].filter_y)
1480       continue;
1481     mi->interp_filters.as_filters.x_filter = filters_ref_set[i].filter_x;
1482     mi->interp_filters.as_filters.y_filter = filters_ref_set[i].filter_y;
1483     av1_enc_build_inter_predictor_y(xd, mi_row, mi_col);
1484     if (use_model_yrd_large)
1485       model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd,
1486                                 &pf_rd_stats[i], this_early_term, 1);
1487     else
1488       model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rd_stats[i], 1);
1489     pf_rd_stats[i].rate += av1_get_switchable_rate(
1490         x, xd, cm->features.interp_filter, cm->seq_params->enable_dual_filter);
1491     cost = RDCOST(x->rdmult, pf_rd_stats[i].rate, pf_rd_stats[i].dist);
1492     pf_tx_size[i] = mi->tx_size;
1493     if (cost < best_cost) {
1494       best_filter_index = i;
1495       best_cost = cost;
1496       best_skip = pf_rd_stats[i].skip_txfm;
1497       best_early_term = *this_early_term;
1498       if (reuse_inter_pred) {
1499         if (*this_mode_pred != current_pred) {
1500           free_pred_buffer(*this_mode_pred);
1501           *this_mode_pred = current_pred;
1502         }
1503         current_pred = &tmp[get_pred_buffer(tmp, 3)];
1504         pd->dst.buf = current_pred->data;
1505         pd->dst.stride = bw;
1506       }
1507     }
1508   }
1509   assert(best_filter_index >= 0 &&
1510          best_filter_index < dim_factor * FILTER_SEARCH_SIZE);
1511   if (reuse_inter_pred && *this_mode_pred != current_pred)
1512     free_pred_buffer(current_pred);
1513 
1514   mi->interp_filters.as_filters.x_filter =
1515       filters_ref_set[best_filter_index].filter_x;
1516   mi->interp_filters.as_filters.y_filter =
1517       filters_ref_set[best_filter_index].filter_y;
1518   mi->tx_size = pf_tx_size[best_filter_index];
1519   this_rdc->rate = pf_rd_stats[best_filter_index].rate;
1520   this_rdc->dist = pf_rd_stats[best_filter_index].dist;
1521   this_rdc->sse = pf_rd_stats[best_filter_index].sse;
1522   this_rdc->skip_txfm = (best_skip || best_early_term);
1523   *this_early_term = best_early_term;
1524   if (reuse_inter_pred) {
1525     pd->dst.buf = (*this_mode_pred)->data;
1526     pd->dst.stride = (*this_mode_pred)->stride;
1527   } else if (best_filter_index < dim_factor * FILTER_SEARCH_SIZE - 1) {
1528     av1_enc_build_inter_predictor_y(xd, mi_row, mi_col);
1529   }
1530 }
1531 #if !CONFIG_REALTIME_ONLY
1532 #define MOTION_MODE_SEARCH_SIZE 2
1533 
1534 static AOM_INLINE int is_warped_mode_allowed(const AV1_COMMON *cm,
1535                                              MACROBLOCK *const x,
1536                                              const MB_MODE_INFO *mbmi) {
1537   const FeatureFlags *const features = &cm->features;
1538   const MACROBLOCKD *xd = &x->e_mbd;
1539 
1540   if (has_second_ref(mbmi)) return 0;
1541   MOTION_MODE last_motion_mode_allowed = SIMPLE_TRANSLATION;
1542 
1543   if (features->switchable_motion_mode) {
1544     // Determine which motion modes to search if more than SIMPLE_TRANSLATION
1545     // is allowed.
1546     last_motion_mode_allowed = motion_mode_allowed(
1547         xd->global_motion, xd, mbmi, features->allow_warped_motion);
1548   }
1549 
1550   if (last_motion_mode_allowed == WARPED_CAUSAL) {
1551     return 1;
1552   }
1553 
1554   return 0;
1555 }
1556 
1557 static void calc_num_proj_ref(AV1_COMP *cpi, MACROBLOCK *x, MB_MODE_INFO *mi) {
1558   AV1_COMMON *const cm = &cpi->common;
1559   MACROBLOCKD *const xd = &x->e_mbd;
1560   const FeatureFlags *const features = &cm->features;
1561 
1562   mi->num_proj_ref = 1;
1563   WARP_SAMPLE_INFO *const warp_sample_info =
1564       &x->warp_sample_info[mi->ref_frame[0]];
1565   int *pts0 = warp_sample_info->pts;
1566   int *pts_inref0 = warp_sample_info->pts_inref;
1567   MOTION_MODE last_motion_mode_allowed = SIMPLE_TRANSLATION;
1568 
1569   if (features->switchable_motion_mode) {
1570     // Determine which motion modes to search if more than SIMPLE_TRANSLATION
1571     // is allowed.
1572     last_motion_mode_allowed = motion_mode_allowed(
1573         xd->global_motion, xd, mi, features->allow_warped_motion);
1574   }
1575 
1576   if (last_motion_mode_allowed == WARPED_CAUSAL) {
1577     if (warp_sample_info->num < 0) {
1578       warp_sample_info->num = av1_findSamples(cm, xd, pts0, pts_inref0);
1579     }
1580     mi->num_proj_ref = warp_sample_info->num;
1581   }
1582 }
1583 
1584 static void search_motion_mode(AV1_COMP *cpi, MACROBLOCK *x, RD_STATS *this_rdc,
1585                                int mi_row, int mi_col, BLOCK_SIZE bsize,
1586                                int *this_early_term, int use_model_yrd_large,
1587                                int *rate_mv) {
1588   AV1_COMMON *const cm = &cpi->common;
1589   MACROBLOCKD *const xd = &x->e_mbd;
1590   const FeatureFlags *const features = &cm->features;
1591   MB_MODE_INFO *const mi = xd->mi[0];
1592   RD_STATS pf_rd_stats[MOTION_MODE_SEARCH_SIZE] = { 0 };
1593   int best_skip = 0;
1594   int best_early_term = 0;
1595   int64_t best_cost = INT64_MAX;
1596   int best_mode_index = -1;
1597   const int interp_filter = features->interp_filter;
1598 
1599   const MOTION_MODE motion_modes[MOTION_MODE_SEARCH_SIZE] = {
1600     SIMPLE_TRANSLATION, WARPED_CAUSAL
1601   };
1602   int mode_search_size = is_warped_mode_allowed(cm, x, mi) ? 2 : 1;
1603 
1604   WARP_SAMPLE_INFO *const warp_sample_info =
1605       &x->warp_sample_info[mi->ref_frame[0]];
1606   int *pts0 = warp_sample_info->pts;
1607   int *pts_inref0 = warp_sample_info->pts_inref;
1608 
1609   const int total_samples = mi->num_proj_ref;
1610   if (total_samples == 0) {
1611     // Do not search WARPED_CAUSAL if there are no samples to use to determine
1612     // warped parameters.
1613     mode_search_size = 1;
1614   }
1615 
1616   const MB_MODE_INFO base_mbmi = *mi;
1617   MB_MODE_INFO best_mbmi;
1618 
1619   for (int i = 0; i < mode_search_size; ++i) {
1620     int64_t cost = INT64_MAX;
1621     MOTION_MODE motion_mode = motion_modes[i];
1622     *mi = base_mbmi;
1623     mi->motion_mode = motion_mode;
1624     if (motion_mode == SIMPLE_TRANSLATION) {
1625       mi->interp_filters = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
1626 
1627       av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize, 0, 0);
1628       if (use_model_yrd_large)
1629         model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd,
1630                                   &pf_rd_stats[i], this_early_term, 1);
1631       else
1632         model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rd_stats[i], 1);
1633       pf_rd_stats[i].rate +=
1634           av1_get_switchable_rate(x, xd, cm->features.interp_filter,
1635                                   cm->seq_params->enable_dual_filter);
1636       cost = RDCOST(x->rdmult, pf_rd_stats[i].rate, pf_rd_stats[i].dist);
1637     } else if (motion_mode == WARPED_CAUSAL) {
1638       int pts[SAMPLES_ARRAY_SIZE], pts_inref[SAMPLES_ARRAY_SIZE];
1639       const ModeCosts *mode_costs = &x->mode_costs;
1640       mi->wm_params.wmtype = DEFAULT_WMTYPE;
1641       mi->interp_filters =
1642           av1_broadcast_interp_filter(av1_unswitchable_filter(interp_filter));
1643 
1644       memcpy(pts, pts0, total_samples * 2 * sizeof(*pts0));
1645       memcpy(pts_inref, pts_inref0, total_samples * 2 * sizeof(*pts_inref0));
1646       // Select the samples according to motion vector difference
1647       if (mi->num_proj_ref > 1) {
1648         mi->num_proj_ref = av1_selectSamples(&mi->mv[0].as_mv, pts, pts_inref,
1649                                              mi->num_proj_ref, bsize);
1650       }
1651 
1652       // Compute the warped motion parameters with a least squares fit
1653       //  using the collected samples
1654       if (!av1_find_projection(mi->num_proj_ref, pts, pts_inref, bsize,
1655                                mi->mv[0].as_mv.row, mi->mv[0].as_mv.col,
1656                                &mi->wm_params, mi_row, mi_col)) {
1657         if (mi->mode == NEWMV) {
1658           const int_mv mv0 = mi->mv[0];
1659           const WarpedMotionParams wm_params0 = mi->wm_params;
1660           const int num_proj_ref0 = mi->num_proj_ref;
1661 
1662           const int_mv ref_mv = av1_get_ref_mv(x, 0);
1663           SUBPEL_MOTION_SEARCH_PARAMS ms_params;
1664           av1_make_default_subpel_ms_params(&ms_params, cpi, x, bsize,
1665                                             &ref_mv.as_mv, NULL);
1666 
1667           // Refine MV in a small range.
1668           av1_refine_warped_mv(xd, cm, &ms_params, bsize, pts0, pts_inref0,
1669                                total_samples);
1670           if (mi->mv[0].as_int == ref_mv.as_int) {
1671             continue;
1672           }
1673 
1674           if (mv0.as_int != mi->mv[0].as_int) {
1675             // Keep the refined MV and WM parameters.
1676             int tmp_rate_mv = av1_mv_bit_cost(
1677                 &mi->mv[0].as_mv, &ref_mv.as_mv, x->mv_costs->nmv_joint_cost,
1678                 x->mv_costs->mv_cost_stack, MV_COST_WEIGHT);
1679             *rate_mv = tmp_rate_mv;
1680           } else {
1681             // Restore the old MV and WM parameters.
1682             mi->mv[0] = mv0;
1683             mi->wm_params = wm_params0;
1684             mi->num_proj_ref = num_proj_ref0;
1685           }
1686         }
1687         // Build the warped predictor
1688         av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize, 0,
1689                                       av1_num_planes(cm) - 1);
1690         if (use_model_yrd_large)
1691           model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd,
1692                                     &pf_rd_stats[i], this_early_term, 1);
1693         else
1694           model_rd_for_sb_y(cpi, bsize, x, xd, &pf_rd_stats[i], 1);
1695 
1696         pf_rd_stats[i].rate +=
1697             mode_costs->motion_mode_cost[bsize][mi->motion_mode];
1698         cost = RDCOST(x->rdmult, pf_rd_stats[i].rate, pf_rd_stats[i].dist);
1699       } else {
1700         cost = INT64_MAX;
1701       }
1702     }
1703     if (cost < best_cost) {
1704       best_mode_index = i;
1705       best_cost = cost;
1706       best_skip = pf_rd_stats[i].skip_txfm;
1707       best_early_term = *this_early_term;
1708       best_mbmi = *mi;
1709     }
1710   }
1711   assert(best_mode_index >= 0 && best_mode_index < FILTER_SEARCH_SIZE);
1712 
1713   *mi = best_mbmi;
1714   this_rdc->rate = pf_rd_stats[best_mode_index].rate;
1715   this_rdc->dist = pf_rd_stats[best_mode_index].dist;
1716   this_rdc->sse = pf_rd_stats[best_mode_index].sse;
1717   this_rdc->skip_txfm = (best_skip || best_early_term);
1718   *this_early_term = best_early_term;
1719   if (best_mode_index < FILTER_SEARCH_SIZE - 1) {
1720     av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize, 0, 0);
1721   }
1722 }
1723 #endif  // !CONFIG_REALTIME_ONLY
1724 
1725 #define COLLECT_PICK_MODE_STAT 0
1726 
1727 #if COLLECT_PICK_MODE_STAT
1728 typedef struct _mode_search_stat {
1729   int32_t num_blocks[BLOCK_SIZES];
1730   int64_t avg_block_times[BLOCK_SIZES];
1731   int32_t num_searches[BLOCK_SIZES][MB_MODE_COUNT];
1732   int32_t num_nonskipped_searches[BLOCK_SIZES][MB_MODE_COUNT];
1733   int64_t search_times[BLOCK_SIZES][MB_MODE_COUNT];
1734   int64_t nonskipped_search_times[BLOCK_SIZES][MB_MODE_COUNT];
1735   struct aom_usec_timer timer1;
1736   struct aom_usec_timer timer2;
1737 } mode_search_stat;
1738 #endif  // COLLECT_PICK_MODE_STAT
1739 
1740 static void compute_intra_yprediction(const AV1_COMMON *cm,
1741                                       PREDICTION_MODE mode, BLOCK_SIZE bsize,
1742                                       MACROBLOCK *x, MACROBLOCKD *xd) {
1743   const SequenceHeader *seq_params = cm->seq_params;
1744   struct macroblockd_plane *const pd = &xd->plane[0];
1745   struct macroblock_plane *const p = &x->plane[0];
1746   uint8_t *const src_buf_base = p->src.buf;
1747   uint8_t *const dst_buf_base = pd->dst.buf;
1748   const int src_stride = p->src.stride;
1749   const int dst_stride = pd->dst.stride;
1750   int plane = 0;
1751   int row, col;
1752   // block and transform sizes, in number of 4x4 blocks log 2 ("*_b")
1753   // 4x4=0, 8x8=2, 16x16=4, 32x32=6, 64x64=8
1754   // transform size varies per plane, look it up in a common way.
1755   const TX_SIZE tx_size = max_txsize_lookup[bsize];
1756   const BLOCK_SIZE plane_bsize =
1757       get_plane_block_size(bsize, pd->subsampling_x, pd->subsampling_y);
1758   // If mb_to_right_edge is < 0 we are in a situation in which
1759   // the current block size extends into the UMV and we won't
1760   // visit the sub blocks that are wholly within the UMV.
1761   const int max_blocks_wide = max_block_wide(xd, plane_bsize, plane);
1762   const int max_blocks_high = max_block_high(xd, plane_bsize, plane);
1763   // Keep track of the row and column of the blocks we use so that we know
1764   // if we are in the unrestricted motion border.
1765   for (row = 0; row < max_blocks_high; row += (1 << tx_size)) {
1766     // Skip visiting the sub blocks that are wholly within the UMV.
1767     for (col = 0; col < max_blocks_wide; col += (1 << tx_size)) {
1768       p->src.buf = &src_buf_base[4 * (row * (int64_t)src_stride + col)];
1769       pd->dst.buf = &dst_buf_base[4 * (row * (int64_t)dst_stride + col)];
1770       av1_predict_intra_block(
1771           xd, seq_params->sb_size, seq_params->enable_intra_edge_filter,
1772           block_size_wide[bsize], block_size_high[bsize], tx_size, mode, 0, 0,
1773           FILTER_INTRA_MODES, pd->dst.buf, dst_stride, pd->dst.buf, dst_stride,
1774           0, 0, plane);
1775     }
1776   }
1777   p->src.buf = src_buf_base;
1778   pd->dst.buf = dst_buf_base;
1779 }
1780 
1781 void av1_nonrd_pick_intra_mode(AV1_COMP *cpi, MACROBLOCK *x, RD_STATS *rd_cost,
1782                                BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
1783   AV1_COMMON *const cm = &cpi->common;
1784   MACROBLOCKD *const xd = &x->e_mbd;
1785   MB_MODE_INFO *const mi = xd->mi[0];
1786   RD_STATS this_rdc, best_rdc;
1787   struct estimate_block_intra_args args = { cpi, x, DC_PRED, 1, 0 };
1788   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
1789   const TX_SIZE intra_tx_size =
1790       AOMMIN(max_txsize_lookup[bsize],
1791              tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]);
1792   int *bmode_costs;
1793   PREDICTION_MODE best_mode = DC_PRED;
1794   const MB_MODE_INFO *above_mi = xd->above_mbmi;
1795   const MB_MODE_INFO *left_mi = xd->left_mbmi;
1796   const PREDICTION_MODE A = av1_above_block_mode(above_mi);
1797   const PREDICTION_MODE L = av1_left_block_mode(left_mi);
1798   const int above_ctx = intra_mode_context[A];
1799   const int left_ctx = intra_mode_context[L];
1800   bmode_costs = x->mode_costs.y_mode_costs[above_ctx][left_ctx];
1801 
1802   av1_invalid_rd_stats(&best_rdc);
1803   av1_invalid_rd_stats(&this_rdc);
1804 
1805   init_mbmi(mi, DC_PRED, INTRA_FRAME, NONE_FRAME, cm);
1806   mi->mv[0].as_int = mi->mv[1].as_int = INVALID_MV;
1807 
1808   // Change the limit of this loop to add other intra prediction
1809   // mode tests.
1810   for (int i = 0; i < 4; ++i) {
1811     PREDICTION_MODE this_mode = intra_mode_list[i];
1812     this_rdc.dist = this_rdc.rate = 0;
1813     args.mode = this_mode;
1814     args.skippable = 1;
1815     args.rdc = &this_rdc;
1816     mi->tx_size = intra_tx_size;
1817     mi->mode = this_mode;
1818     av1_foreach_transformed_block_in_plane(xd, bsize, 0, estimate_block_intra,
1819                                            &args);
1820     const int skip_ctx = av1_get_skip_txfm_context(xd);
1821     if (args.skippable) {
1822       this_rdc.rate = x->mode_costs.skip_txfm_cost[skip_ctx][1];
1823     } else {
1824       this_rdc.rate += x->mode_costs.skip_txfm_cost[skip_ctx][0];
1825     }
1826     this_rdc.rate += bmode_costs[this_mode];
1827     this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
1828 
1829     if (this_rdc.rdcost < best_rdc.rdcost) {
1830       best_rdc = this_rdc;
1831       best_mode = this_mode;
1832     }
1833   }
1834 
1835   mi->mode = best_mode;
1836   // Keep DC for UV since mode test is based on Y channel only.
1837   mi->uv_mode = DC_PRED;
1838   *rd_cost = best_rdc;
1839 
1840 #if CONFIG_INTERNAL_STATS
1841   store_coding_context(x, ctx, mi->mode);
1842 #else
1843   store_coding_context(x, ctx);
1844 #endif  // CONFIG_INTERNAL_STATS
1845 }
1846 
1847 static AOM_INLINE int is_same_gf_and_last_scale(AV1_COMMON *cm) {
1848   struct scale_factors *const sf_last = get_ref_scale_factors(cm, LAST_FRAME);
1849   struct scale_factors *const sf_golden =
1850       get_ref_scale_factors(cm, GOLDEN_FRAME);
1851   return ((sf_last->x_scale_fp == sf_golden->x_scale_fp) &&
1852           (sf_last->y_scale_fp == sf_golden->y_scale_fp));
1853 }
1854 
1855 static AOM_INLINE void get_ref_frame_use_mask(AV1_COMP *cpi, MACROBLOCK *x,
1856                                               MB_MODE_INFO *mi, int mi_row,
1857                                               int mi_col, int bsize,
1858                                               int gf_temporal_ref,
1859                                               int use_ref_frame[],
1860                                               int *force_skip_low_temp_var) {
1861   AV1_COMMON *const cm = &cpi->common;
1862   const struct segmentation *const seg = &cm->seg;
1863   const int is_small_sb = (cm->seq_params->sb_size == BLOCK_64X64);
1864 
1865   // For SVC the usage of alt_ref is determined by the ref_frame_flags.
1866   int use_alt_ref_frame =
1867       cpi->ppi->use_svc || cpi->sf.rt_sf.use_nonrd_altref_frame;
1868   int use_golden_ref_frame = 1;
1869 
1870   use_ref_frame[LAST_FRAME] = 1;  // we never skip LAST
1871 
1872   if (cpi->rc.frames_since_golden == 0 && gf_temporal_ref) {
1873     use_golden_ref_frame = 0;
1874   }
1875   if (cpi->sf.rt_sf.short_circuit_low_temp_var &&
1876       x->nonrd_prune_ref_frame_search) {
1877     if (is_small_sb)
1878       *force_skip_low_temp_var = get_force_skip_low_temp_var_small_sb(
1879           &x->part_search_info.variance_low[0], mi_row, mi_col, bsize);
1880     else
1881       *force_skip_low_temp_var = get_force_skip_low_temp_var(
1882           &x->part_search_info.variance_low[0], mi_row, mi_col, bsize);
1883     // If force_skip_low_temp_var is set, skip golden reference.
1884     if (*force_skip_low_temp_var) {
1885       use_golden_ref_frame = 0;
1886       use_alt_ref_frame = 0;
1887     }
1888   }
1889 
1890   if (segfeature_active(seg, mi->segment_id, SEG_LVL_REF_FRAME) &&
1891       get_segdata(seg, mi->segment_id, SEG_LVL_REF_FRAME) == GOLDEN_FRAME) {
1892     use_golden_ref_frame = 1;
1893     use_alt_ref_frame = 0;
1894   }
1895 
1896   use_alt_ref_frame =
1897       cpi->ref_frame_flags & AOM_ALT_FLAG ? use_alt_ref_frame : 0;
1898   use_golden_ref_frame =
1899       cpi->ref_frame_flags & AOM_GOLD_FLAG ? use_golden_ref_frame : 0;
1900 
1901   use_ref_frame[ALTREF_FRAME] = use_alt_ref_frame;
1902   use_ref_frame[GOLDEN_FRAME] = use_golden_ref_frame;
1903 }
1904 
1905 /*!\brief Estimates best intra mode for inter mode search
1906  *
1907  * \ingroup nonrd_mode_search
1908  * \callgraph
1909  * \callergraph
1910  *
1911  * Using heuristics based on best inter mode, block size, and other decides
1912  * whether to check intra modes. If so, estimates and selects best intra mode
1913  * from the reduced set of intra modes (max 4 intra modes checked)
1914  *
1915  * \param[in]    cpi                      Top-level encoder structure
1916  * \param[in]    x                        Pointer to structure holding all the
1917  *                                        data for the current macroblock
1918  * \param[in]    bsize                    Current block size
1919  * \param[in]    use_modeled_non_rd_cost  Flag, indicating usage of curvfit
1920  *                                        model for RD cost
1921  * \param[in]    best_early_term          Flag, indicating that TX for the
1922  *                                        best inter mode was skipped
1923  * \param[in]    ref_cost_intra           Cost of signalling intra mode
1924  * \param[in]    reuse_prediction         Flag, indicating prediction re-use
1925  * \param[in]    orig_dst                 Original destination buffer
1926  * \param[in]    tmp_buffers              Pointer to a temporary buffers for
1927  *                                        prediction re-use
1928  * \param[out]   this_mode_pred           Pointer to store prediction buffer
1929  *                                        for prediction re-use
1930  * \param[in]    best_rdc                 Pointer to RD cost for the best
1931  *                                        selected intra mode
1932  * \param[in]    best_pickmode            Pointer to a structure containing
1933  *                                        best mode picked so far
1934  *
1935  * \return Nothing is returned. Instead, calculated RD cost is placed to
1936  * \c best_rdc and best selected mode is placed to \c best_pickmode
1937  */
1938 static void estimate_intra_mode(
1939     AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int use_modeled_non_rd_cost,
1940     int best_early_term, unsigned int ref_cost_intra, int reuse_prediction,
1941     struct buf_2d *orig_dst, PRED_BUFFER *tmp_buffers,
1942     PRED_BUFFER **this_mode_pred, RD_STATS *best_rdc,
1943     BEST_PICKMODE *best_pickmode) {
1944   AV1_COMMON *const cm = &cpi->common;
1945   MACROBLOCKD *const xd = &x->e_mbd;
1946   MB_MODE_INFO *const mi = xd->mi[0];
1947   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
1948   const unsigned char segment_id = mi->segment_id;
1949   const int *const rd_threshes = cpi->rd.threshes[segment_id][bsize];
1950   const int *const rd_thresh_freq_fact = x->thresh_freq_fact[bsize];
1951   const int mi_row = xd->mi_row;
1952   const int mi_col = xd->mi_col;
1953   struct macroblockd_plane *const pd = &xd->plane[0];
1954 
1955   const CommonQuantParams *quant_params = &cm->quant_params;
1956 
1957   RD_STATS this_rdc;
1958 
1959   int intra_cost_penalty = av1_get_intra_cost_penalty(
1960       quant_params->base_qindex, quant_params->y_dc_delta_q,
1961       cm->seq_params->bit_depth);
1962   int64_t inter_mode_thresh = RDCOST(x->rdmult, intra_cost_penalty, 0);
1963   int perform_intra_pred = cpi->sf.rt_sf.check_intra_pred_nonrd;
1964   // For spatial enhancemanent layer: turn off intra prediction if the
1965   // previous spatial layer as golden ref is not chosen as best reference.
1966   // only do this for temporal enhancement layer and on non-key frames.
1967   if (cpi->svc.spatial_layer_id > 0 &&
1968       best_pickmode->best_ref_frame != GOLDEN_FRAME &&
1969       cpi->svc.temporal_layer_id > 0 &&
1970       !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
1971     perform_intra_pred = 0;
1972 
1973   int do_early_exit_rdthresh = 1;
1974 
1975   uint32_t spatial_var_thresh = 50;
1976   int motion_thresh = 32;
1977   // Adjust thresholds to make intra mode likely tested if the other
1978   // references (golden, alt) are skipped/not checked. For now always
1979   // adjust for svc mode.
1980   if (cpi->ppi->use_svc || (cpi->sf.rt_sf.use_nonrd_altref_frame == 0 &&
1981                             cpi->sf.rt_sf.nonrd_prune_ref_frame_search > 0)) {
1982     spatial_var_thresh = 150;
1983     motion_thresh = 0;
1984   }
1985 
1986   // Some adjustments to checking intra mode based on source variance.
1987   if (x->source_variance < spatial_var_thresh) {
1988     // If the best inter mode is large motion or non-LAST ref reduce intra cost
1989     // penalty, so intra mode is more likely tested.
1990     if (best_rdc->rdcost != INT64_MAX &&
1991         (best_pickmode->best_ref_frame != LAST_FRAME ||
1992          abs(mi->mv[0].as_mv.row) >= motion_thresh ||
1993          abs(mi->mv[0].as_mv.col) >= motion_thresh)) {
1994       intra_cost_penalty = intra_cost_penalty >> 2;
1995       inter_mode_thresh = RDCOST(x->rdmult, intra_cost_penalty, 0);
1996       do_early_exit_rdthresh = 0;
1997     }
1998     // For big blocks worth checking intra (since only DC will be checked),
1999     // even if best_early_term is set.
2000     if (bsize >= BLOCK_32X32) best_early_term = 0;
2001   } else if (cpi->sf.rt_sf.source_metrics_sb_nonrd &&
2002              x->content_state_sb.source_sad == kLowSad) {
2003     perform_intra_pred = 0;
2004   }
2005 
2006   if (cpi->sf.rt_sf.skip_intra_pred_if_tx_skip && best_rdc->skip_txfm &&
2007       best_pickmode->best_mode_initial_skip_flag) {
2008     perform_intra_pred = 0;
2009   }
2010 
2011   if (!(best_rdc->rdcost == INT64_MAX ||
2012         (perform_intra_pred && !best_early_term &&
2013          best_rdc->rdcost > inter_mode_thresh &&
2014          bsize <= cpi->sf.part_sf.max_intra_bsize))) {
2015     return;
2016   }
2017 
2018   struct estimate_block_intra_args args = { cpi, x, DC_PRED, 1, 0 };
2019   TX_SIZE intra_tx_size = AOMMIN(
2020       AOMMIN(max_txsize_lookup[bsize],
2021              tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]),
2022       TX_16X16);
2023 
2024   PRED_BUFFER *const best_pred = best_pickmode->best_pred;
2025   if (reuse_prediction && best_pred != NULL) {
2026     const int bh = block_size_high[bsize];
2027     const int bw = block_size_wide[bsize];
2028     if (best_pred->data == orig_dst->buf) {
2029       *this_mode_pred = &tmp_buffers[get_pred_buffer(tmp_buffers, 3)];
2030       aom_convolve_copy(best_pred->data, best_pred->stride,
2031                         (*this_mode_pred)->data, (*this_mode_pred)->stride, bw,
2032                         bh);
2033       best_pickmode->best_pred = *this_mode_pred;
2034     }
2035   }
2036   pd->dst = *orig_dst;
2037 
2038   for (int i = 0; i < 4; ++i) {
2039     const PREDICTION_MODE this_mode = intra_mode_list[i];
2040     const THR_MODES mode_index = mode_idx[INTRA_FRAME][mode_offset(this_mode)];
2041     const int64_t mode_rd_thresh = rd_threshes[mode_index];
2042 
2043     if (!((1 << this_mode) & cpi->sf.rt_sf.intra_y_mode_bsize_mask_nrd[bsize]))
2044       continue;
2045 
2046     if (rd_less_than_thresh(best_rdc->rdcost, mode_rd_thresh,
2047                             rd_thresh_freq_fact[mode_index]) &&
2048         (do_early_exit_rdthresh || this_mode == SMOOTH_PRED)) {
2049       continue;
2050     }
2051     const BLOCK_SIZE uv_bsize = get_plane_block_size(
2052         bsize, xd->plane[1].subsampling_x, xd->plane[1].subsampling_y);
2053 
2054     mi->mode = this_mode;
2055     mi->ref_frame[0] = INTRA_FRAME;
2056     mi->ref_frame[1] = NONE_FRAME;
2057 
2058     av1_invalid_rd_stats(&this_rdc);
2059     args.mode = this_mode;
2060     args.skippable = 1;
2061     args.rdc = &this_rdc;
2062     mi->tx_size = intra_tx_size;
2063     compute_intra_yprediction(cm, this_mode, bsize, x, xd);
2064     // Look into selecting tx_size here, based on prediction residual.
2065     if (use_modeled_non_rd_cost)
2066       model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc, 1);
2067     else
2068       block_yrd(cpi, x, mi_row, mi_col, &this_rdc, &args.skippable, bsize,
2069                 mi->tx_size);
2070     // TODO(kyslov@) Need to account for skippable
2071     if (x->color_sensitivity[0]) {
2072       av1_foreach_transformed_block_in_plane(xd, uv_bsize, 1,
2073                                              estimate_block_intra, &args);
2074     }
2075     if (x->color_sensitivity[1]) {
2076       av1_foreach_transformed_block_in_plane(xd, uv_bsize, 2,
2077                                              estimate_block_intra, &args);
2078     }
2079 
2080     int mode_cost = 0;
2081     if (av1_is_directional_mode(this_mode) && av1_use_angle_delta(bsize)) {
2082       mode_cost +=
2083           x->mode_costs.angle_delta_cost[this_mode - V_PRED]
2084                                         [MAX_ANGLE_DELTA +
2085                                          mi->angle_delta[PLANE_TYPE_Y]];
2086     }
2087     if (this_mode == DC_PRED && av1_filter_intra_allowed_bsize(cm, bsize)) {
2088       mode_cost += x->mode_costs.filter_intra_cost[bsize][0];
2089     }
2090     this_rdc.rate += ref_cost_intra;
2091     this_rdc.rate += intra_cost_penalty;
2092     this_rdc.rate += mode_cost;
2093     this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
2094 
2095     if (this_rdc.rdcost < best_rdc->rdcost) {
2096       *best_rdc = this_rdc;
2097       best_pickmode->best_mode = this_mode;
2098       best_pickmode->best_tx_size = mi->tx_size;
2099       best_pickmode->best_ref_frame = INTRA_FRAME;
2100       best_pickmode->best_second_ref_frame = NONE;
2101       mi->uv_mode = this_mode;
2102       mi->mv[0].as_int = INVALID_MV;
2103       mi->mv[1].as_int = INVALID_MV;
2104     }
2105   }
2106   mi->tx_size = best_pickmode->best_tx_size;
2107 }
2108 
2109 static AOM_INLINE int is_filter_search_enabled(const AV1_COMP *cpi, int mi_row,
2110                                                int mi_col, BLOCK_SIZE bsize,
2111                                                int segment_id) {
2112   const AV1_COMMON *const cm = &cpi->common;
2113   int enable_filter_search = 0;
2114 
2115   if (cpi->sf.rt_sf.use_nonrd_filter_search) {
2116     enable_filter_search = 1;
2117     if (cpi->sf.interp_sf.cb_pred_filter_search) {
2118       const int bsl = mi_size_wide_log2[bsize];
2119       enable_filter_search =
2120           (((mi_row + mi_col) >> bsl) +
2121            get_chessboard_index(cm->current_frame.frame_number)) &
2122           0x1;
2123       if (cyclic_refresh_segment_id_boosted(segment_id))
2124         enable_filter_search = 1;
2125     }
2126   }
2127   return enable_filter_search;
2128 }
2129 
2130 static AOM_INLINE int skip_mode_by_threshold(
2131     PREDICTION_MODE mode, MV_REFERENCE_FRAME ref_frame, int_mv mv,
2132     int frames_since_golden, const int *const rd_threshes,
2133     const int *const rd_thresh_freq_fact, int64_t best_cost, int best_skip,
2134     int extra_shift) {
2135   int skip_this_mode = 0;
2136   const THR_MODES mode_index = mode_idx[ref_frame][INTER_OFFSET(mode)];
2137   int64_t mode_rd_thresh =
2138       best_skip ? ((int64_t)rd_threshes[mode_index]) << (extra_shift + 1)
2139                 : ((int64_t)rd_threshes[mode_index]) << extra_shift;
2140 
2141   // Increase mode_rd_thresh value for non-LAST for improved encoding
2142   // speed
2143   if (ref_frame != LAST_FRAME) {
2144     mode_rd_thresh = mode_rd_thresh << 1;
2145     if (ref_frame == GOLDEN_FRAME && frames_since_golden > 4)
2146       mode_rd_thresh = mode_rd_thresh << (extra_shift + 1);
2147   }
2148 
2149   if (rd_less_than_thresh(best_cost, mode_rd_thresh,
2150                           rd_thresh_freq_fact[mode_index]))
2151     if (mv.as_int != 0) skip_this_mode = 1;
2152 
2153   return skip_this_mode;
2154 }
2155 
2156 static AOM_INLINE int skip_mode_by_low_temp(
2157     PREDICTION_MODE mode, MV_REFERENCE_FRAME ref_frame, BLOCK_SIZE bsize,
2158     CONTENT_STATE_SB content_state_sb, int_mv mv, int force_skip_low_temp_var) {
2159   // Skip non-zeromv mode search for non-LAST frame if force_skip_low_temp_var
2160   // is set. If nearestmv for golden frame is 0, zeromv mode will be skipped
2161   // later.
2162   if (force_skip_low_temp_var && ref_frame != LAST_FRAME && mv.as_int != 0) {
2163     return 1;
2164   }
2165 
2166   if (content_state_sb.source_sad != kHighSad && bsize >= BLOCK_64X64 &&
2167       force_skip_low_temp_var && mode == NEWMV) {
2168     return 1;
2169   }
2170   return 0;
2171 }
2172 
2173 static AOM_INLINE int skip_mode_by_bsize_and_ref_frame(
2174     PREDICTION_MODE mode, MV_REFERENCE_FRAME ref_frame, BLOCK_SIZE bsize,
2175     int extra_prune, unsigned int sse_zeromv_norm, int more_prune) {
2176   const unsigned int thresh_skip_golden = 500;
2177 
2178   if (ref_frame != LAST_FRAME && sse_zeromv_norm < thresh_skip_golden &&
2179       mode == NEWMV)
2180     return 1;
2181 
2182   if (bsize == BLOCK_128X128 && mode == NEWMV) return 1;
2183 
2184   // Skip testing non-LAST if this flag is set.
2185   if (extra_prune) {
2186     if (extra_prune > 1 && ref_frame != LAST_FRAME &&
2187         (bsize > BLOCK_64X64 || (bsize > BLOCK_16X16 && mode == NEWMV)))
2188       return 1;
2189 
2190     if (ref_frame != LAST_FRAME && mode == NEARMV) return 1;
2191 
2192     if (more_prune && bsize >= BLOCK_32X32 && mode == NEARMV) return 1;
2193 
2194     if (extra_prune > 2 && ref_frame != LAST_FRAME) {
2195       return 1;
2196     }
2197   }
2198   return 0;
2199 }
2200 
2201 void set_color_sensitivity(AV1_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
2202                            BLOCK_SIZE bsize, int y_sad,
2203                            unsigned int source_variance) {
2204   const int factor = (bsize >= BLOCK_32X32) ? 2 : 3;
2205   NOISE_LEVEL noise_level = kLow;
2206   int norm_sad =
2207       y_sad >> (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
2208   // If the spatial source variance is high and the normalized y_sad
2209   // is low, then y-channel is likely good for mode estimation, so keep
2210   // color_sensitivity off. For low noise content for now, since there is
2211   // some bdrate regression for noisy color clip.
2212   if (cpi->noise_estimate.enabled)
2213     noise_level = av1_noise_estimate_extract_level(&cpi->noise_estimate);
2214   if (noise_level == kLow && source_variance > 1000 && norm_sad < 50) {
2215     x->color_sensitivity[0] = 0;
2216     x->color_sensitivity[1] = 0;
2217     return;
2218   }
2219   for (int i = 1; i <= 2; ++i) {
2220     if (x->color_sensitivity[i - 1] == 2) {
2221       struct macroblock_plane *const p = &x->plane[i];
2222       struct macroblockd_plane *const pd = &xd->plane[i];
2223       const BLOCK_SIZE bs =
2224           get_plane_block_size(bsize, pd->subsampling_x, pd->subsampling_y);
2225       const int uv_sad = cpi->ppi->fn_ptr[bs].sdf(p->src.buf, p->src.stride,
2226                                                   pd->dst.buf, pd->dst.stride);
2227       const int norm_uv_sad =
2228           uv_sad >> (b_width_log2_lookup[bs] + b_height_log2_lookup[bs]);
2229       x->color_sensitivity[i - 1] =
2230           uv_sad > (factor * (y_sad >> 3)) && norm_uv_sad > 40;
2231     }
2232   }
2233 }
2234 
2235 void setup_compound_prediction(AV1_COMP *cpi, MACROBLOCK *x,
2236                                struct buf_2d yv12_mb[8][MAX_MB_PLANE],
2237                                int *use_ref_frame_mask, int flag_comp,
2238                                int *ref_mv_idx) {
2239   AV1_COMMON *const cm = &cpi->common;
2240   MACROBLOCKD *const xd = &x->e_mbd;
2241   MB_MODE_INFO *const mbmi = xd->mi[0];
2242   MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
2243   MV_REFERENCE_FRAME rf[2] = { LAST_FRAME, GOLDEN_FRAME };
2244   MV_REFERENCE_FRAME ref_frame_comp;
2245   if (flag_comp == 1) {
2246     rf[1] = LAST2_FRAME;
2247   } else if (flag_comp == 2) {
2248     rf[1] = ALTREF_FRAME;
2249   }
2250   if (!use_ref_frame_mask[rf[1]]) {
2251     // Need to setup pred_block, if it hasn't been done in find_predictors.
2252     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_yv12_buf(cm, rf[1]);
2253     const int num_planes = av1_num_planes(cm);
2254     if (yv12 != NULL) {
2255       const struct scale_factors *const sf =
2256           get_ref_scale_factors_const(cm, rf[1]);
2257       av1_setup_pred_block(xd, yv12_mb[rf[1]], yv12, sf, sf, num_planes);
2258     }
2259   }
2260   ref_frame_comp = av1_ref_frame_type(rf);
2261   mbmi_ext->mode_context[ref_frame_comp] = 0;
2262   mbmi_ext->ref_mv_count[ref_frame_comp] = UINT8_MAX;
2263   av1_find_mv_refs(cm, xd, mbmi, ref_frame_comp, mbmi_ext->ref_mv_count,
2264                    xd->ref_mv_stack, xd->weight, NULL, mbmi_ext->global_mvs,
2265                    mbmi_ext->mode_context);
2266   av1_copy_usable_ref_mv_stack_and_weight(xd, mbmi_ext, ref_frame_comp);
2267   *ref_mv_idx = mbmi->ref_mv_idx + 1;
2268 }
2269 
2270 static void set_compound_mode(MACROBLOCK *x, int comp_index, int ref_frame,
2271                               int ref_frame2, int ref_mv_idx,
2272                               int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES],
2273                               PREDICTION_MODE *this_mode) {
2274   MACROBLOCKD *const xd = &x->e_mbd;
2275   MB_MODE_INFO *const mi = xd->mi[0];
2276   *this_mode = GLOBAL_GLOBALMV;
2277   mi->ref_frame[0] = ref_frame;
2278   mi->ref_frame[1] = ref_frame2;
2279   mi->compound_idx = 1;
2280   mi->comp_group_idx = 0;
2281   mi->interinter_comp.type = COMPOUND_AVERAGE;
2282   MV_REFERENCE_FRAME ref_frame_comp = av1_ref_frame_type(mi->ref_frame);
2283   if (comp_index % 3 == 0) {
2284     frame_mv[*this_mode][ref_frame].as_int = 0;
2285     frame_mv[*this_mode][ref_frame2].as_int = 0;
2286   } else if (comp_index % 3 == 1) {
2287     *this_mode = NEAREST_NEARESTMV;
2288     frame_mv[*this_mode][ref_frame].as_int =
2289         xd->ref_mv_stack[ref_frame_comp][0].this_mv.as_int;
2290     frame_mv[*this_mode][ref_frame2].as_int =
2291         xd->ref_mv_stack[ref_frame_comp][0].comp_mv.as_int;
2292   } else if (comp_index % 3 == 2) {
2293     *this_mode = NEAR_NEARMV;
2294     frame_mv[*this_mode][ref_frame].as_int =
2295         xd->ref_mv_stack[ref_frame_comp][ref_mv_idx].this_mv.as_int;
2296     frame_mv[*this_mode][ref_frame2].as_int =
2297         xd->ref_mv_stack[ref_frame_comp][ref_mv_idx].comp_mv.as_int;
2298   }
2299 }
2300 
2301 void av1_nonrd_pick_inter_mode_sb(AV1_COMP *cpi, TileDataEnc *tile_data,
2302                                   MACROBLOCK *x, RD_STATS *rd_cost,
2303                                   BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
2304   AV1_COMMON *const cm = &cpi->common;
2305   SVC *const svc = &cpi->svc;
2306   MACROBLOCKD *const xd = &x->e_mbd;
2307   MB_MODE_INFO *const mi = xd->mi[0];
2308   struct macroblockd_plane *const pd = &xd->plane[0];
2309   const InterpFilter filter_ref = cm->features.interp_filter;
2310   const InterpFilter default_interp_filter = EIGHTTAP_REGULAR;
2311   BEST_PICKMODE best_pickmode;
2312 #if COLLECT_PICK_MODE_STAT
2313   static mode_search_stat ms_stat;
2314 #endif
2315   MV_REFERENCE_FRAME ref_frame, ref_frame2;
2316   int_mv frame_mv[MB_MODE_COUNT][REF_FRAMES];
2317   int_mv frame_mv_best[MB_MODE_COUNT][REF_FRAMES];
2318   uint8_t mode_checked[MB_MODE_COUNT][REF_FRAMES];
2319   struct buf_2d yv12_mb[REF_FRAMES][MAX_MB_PLANE];
2320   RD_STATS this_rdc, best_rdc;
2321   const unsigned char segment_id = mi->segment_id;
2322   const int *const rd_threshes = cpi->rd.threshes[segment_id][bsize];
2323   const int *const rd_thresh_freq_fact = x->thresh_freq_fact[bsize];
2324   int best_early_term = 0;
2325   unsigned int ref_costs_single[REF_FRAMES];
2326   int force_skip_low_temp_var = 0;
2327   int use_ref_frame_mask[REF_FRAMES] = { 0 };
2328   unsigned int sse_zeromv_norm = UINT_MAX;
2329   // Use mode set that includes zeromv (via globalmv) for speed >= 9 for
2330   // content with low motion.
2331   int use_zeromv =
2332       ((cpi->oxcf.speed >= 9 && cpi->rc.avg_frame_low_motion > 70) ||
2333        cpi->sf.rt_sf.nonrd_agressive_skip);
2334   const int num_inter_modes =
2335       use_zeromv ? NUM_INTER_MODES_REDUCED : NUM_INTER_MODES_RT;
2336   const REF_MODE *const ref_mode_set =
2337       use_zeromv ? ref_mode_set_reduced : ref_mode_set_rt;
2338   PRED_BUFFER tmp[4];
2339   DECLARE_ALIGNED(16, uint8_t, pred_buf[3 * 128 * 128]);
2340   PRED_BUFFER *this_mode_pred = NULL;
2341   const int reuse_inter_pred = cpi->sf.rt_sf.reuse_inter_pred_nonrd &&
2342                                cm->seq_params->bit_depth == AOM_BITS_8;
2343 
2344   const int bh = block_size_high[bsize];
2345   const int bw = block_size_wide[bsize];
2346   const int pixels_in_block = bh * bw;
2347   struct buf_2d orig_dst = pd->dst;
2348   const CommonQuantParams *quant_params = &cm->quant_params;
2349   const TxfmSearchParams *txfm_params = &x->txfm_search_params;
2350   TxfmSearchInfo *txfm_info = &x->txfm_search_info;
2351 #if COLLECT_PICK_MODE_STAT
2352   aom_usec_timer_start(&ms_stat.timer2);
2353 #endif
2354   int64_t thresh_sad_pred = INT64_MAX;
2355   const int mi_row = xd->mi_row;
2356   const int mi_col = xd->mi_col;
2357   int svc_mv_col = 0;
2358   int svc_mv_row = 0;
2359   int force_mv_inter_layer = 0;
2360   int use_modeled_non_rd_cost = 0;
2361   int comp_pred = 0;
2362   int num_comp_modes_ref = 0;
2363   int tot_num_comp_modes = 9;
2364   int ref_mv_idx = 0;
2365 #if CONFIG_AV1_TEMPORAL_DENOISING
2366   const int denoise_recheck_zeromv = 1;
2367   AV1_PICKMODE_CTX_DEN ctx_den;
2368   int64_t zero_last_cost_orig = INT64_MAX;
2369   int denoise_svc_pickmode = 1;
2370   const int resize_pending =
2371       (cpi->resize_pending_params.width && cpi->resize_pending_params.height &&
2372        (cpi->common.width != cpi->resize_pending_params.width ||
2373         cpi->common.height != cpi->resize_pending_params.height));
2374 
2375 #endif
2376   x->color_sensitivity[0] = x->color_sensitivity_sb[0];
2377   x->color_sensitivity[1] = x->color_sensitivity_sb[1];
2378   init_best_pickmode(&best_pickmode);
2379 
2380   const ModeCosts *mode_costs = &x->mode_costs;
2381 
2382   estimate_single_ref_frame_costs(cm, xd, mode_costs, segment_id,
2383                                   ref_costs_single);
2384 
2385   memset(&mode_checked[0][0], 0, MB_MODE_COUNT * REF_FRAMES);
2386   if (reuse_inter_pred) {
2387     for (int i = 0; i < 3; i++) {
2388       tmp[i].data = &pred_buf[pixels_in_block * i];
2389       tmp[i].stride = bw;
2390       tmp[i].in_use = 0;
2391     }
2392     tmp[3].data = pd->dst.buf;
2393     tmp[3].stride = pd->dst.stride;
2394     tmp[3].in_use = 0;
2395   }
2396 
2397   txfm_info->skip_txfm = 0;
2398 
2399   // initialize mode decisions
2400   av1_invalid_rd_stats(&best_rdc);
2401   av1_invalid_rd_stats(&this_rdc);
2402   av1_invalid_rd_stats(rd_cost);
2403   for (int i = 0; i < REF_FRAMES; ++i) {
2404     x->warp_sample_info[i].num = -1;
2405   }
2406 
2407   mi->bsize = bsize;
2408   mi->ref_frame[0] = NONE_FRAME;
2409   mi->ref_frame[1] = NONE_FRAME;
2410 
2411 #if CONFIG_AV1_TEMPORAL_DENOISING
2412   if (cpi->oxcf.noise_sensitivity > 0) {
2413     // if (cpi->ppi->use_svc) denoise_svc_pickmode =
2414     // av1_denoise_svc_non_key(cpi);
2415     if (cpi->denoiser.denoising_level > kDenLowLow && denoise_svc_pickmode)
2416       av1_denoiser_reset_frame_stats(ctx);
2417   }
2418 #endif
2419 
2420   const int gf_temporal_ref = is_same_gf_and_last_scale(cm);
2421 
2422   // If the lower spatial layer uses an averaging filter for downsampling
2423   // (phase = 8), the target decimated pixel is shifted by (1/2, 1/2) relative
2424   // to source, so use subpel motion vector to compensate. The nonzero motion
2425   // is half pixel shifted to left and top, so (-4, -4). This has more effect
2426   // on higher resolutins, so condition it on that for now.
2427   if (cpi->ppi->use_svc && svc->spatial_layer_id > 0 &&
2428       svc->downsample_filter_phase[svc->spatial_layer_id - 1] == 8 &&
2429       cm->width * cm->height > 640 * 480) {
2430     svc_mv_col = -4;
2431     svc_mv_row = -4;
2432   }
2433 
2434   get_ref_frame_use_mask(cpi, x, mi, mi_row, mi_col, bsize, gf_temporal_ref,
2435                          use_ref_frame_mask, &force_skip_low_temp_var);
2436 
2437   // Compound modes per reference pair (GOLDEN_LAST/LAST2_LAST/ALTREF_LAST):
2438   // (0_0)/(NEAREST_NEAREST)/(NEAR_NEAR).
2439   // For now to reduce slowdowm, use only (0,0) for blocks above 16x16
2440   // for non-svc case or on enhancement layers for svc.
2441   if (cpi->sf.rt_sf.use_comp_ref_nonrd && is_comp_ref_allowed(bsize)) {
2442     if (cpi->ppi->use_svc && cpi->svc.temporal_layer_id == 0)
2443       num_comp_modes_ref = 2;
2444     else if (bsize > BLOCK_16X16)
2445       num_comp_modes_ref = 1;
2446     else
2447       tot_num_comp_modes = 0;
2448   } else {
2449     tot_num_comp_modes = 0;
2450   }
2451 
2452   for (MV_REFERENCE_FRAME ref_frame_iter = LAST_FRAME;
2453        ref_frame_iter <= ALTREF_FRAME; ++ref_frame_iter) {
2454     if (use_ref_frame_mask[ref_frame_iter]) {
2455       find_predictors(cpi, x, ref_frame_iter, frame_mv, tile_data, yv12_mb,
2456                       bsize, force_skip_low_temp_var);
2457     }
2458   }
2459 
2460   thresh_sad_pred = ((int64_t)x->pred_mv_sad[LAST_FRAME]) << 1;
2461   // Increase threshold for less agressive pruning.
2462   if (cpi->sf.rt_sf.nonrd_prune_ref_frame_search == 1)
2463     thresh_sad_pred += (x->pred_mv_sad[LAST_FRAME] >> 2);
2464 
2465   const int large_block = bsize >= BLOCK_32X32;
2466   const int use_model_yrd_large =
2467       cpi->oxcf.rc_cfg.mode == AOM_CBR && large_block &&
2468       !cyclic_refresh_segment_id_boosted(xd->mi[0]->segment_id) &&
2469       quant_params->base_qindex && cm->seq_params->bit_depth == 8;
2470 
2471   const int enable_filter_search =
2472       is_filter_search_enabled(cpi, mi_row, mi_col, bsize, segment_id);
2473 
2474   // TODO(marpan): Look into reducing these conditions. For now constrain
2475   // it to avoid significant bdrate loss.
2476   if (cpi->sf.rt_sf.use_modeled_non_rd_cost) {
2477     if (cpi->svc.non_reference_frame)
2478       use_modeled_non_rd_cost = 1;
2479     else if (cpi->svc.number_temporal_layers > 1 &&
2480              cpi->svc.temporal_layer_id == 0)
2481       use_modeled_non_rd_cost = 0;
2482     else
2483       use_modeled_non_rd_cost =
2484           (quant_params->base_qindex > 120 && x->source_variance > 100 &&
2485            bsize <= BLOCK_16X16 && !x->content_state_sb.lighting_change &&
2486            x->content_state_sb.source_sad != kHighSad);
2487   }
2488 
2489 #if COLLECT_PICK_MODE_STAT
2490   ms_stat.num_blocks[bsize]++;
2491 #endif
2492   init_mbmi(mi, DC_PRED, NONE_FRAME, NONE_FRAME, cm);
2493   mi->tx_size = AOMMIN(
2494       AOMMIN(max_txsize_lookup[bsize],
2495              tx_mode_to_biggest_tx_size[txfm_params->tx_mode_search_type]),
2496       TX_16X16);
2497 
2498   for (int idx = 0; idx < num_inter_modes + tot_num_comp_modes; ++idx) {
2499     const struct segmentation *const seg = &cm->seg;
2500 
2501     int rate_mv = 0;
2502     int is_skippable;
2503     int this_early_term = 0;
2504     int skip_this_mv = 0;
2505     comp_pred = 0;
2506     PREDICTION_MODE this_mode;
2507     MB_MODE_INFO_EXT *const mbmi_ext = &x->mbmi_ext;
2508     RD_STATS nonskip_rdc;
2509     av1_invalid_rd_stats(&nonskip_rdc);
2510 
2511     if (idx >= num_inter_modes) {
2512       int comp_index = idx - num_inter_modes;
2513       if (comp_index % 3 == 0) {
2514         int i = 0;
2515         ref_mv_idx = 0;
2516         // Only needs to be done once per reference pair.
2517         if (comp_index == 3) i = 1;
2518         if (comp_index == 6) i = 2;
2519         if (cpi->sf.rt_sf.ref_frame_comp_nonrd[i])
2520           setup_compound_prediction(cpi, x, yv12_mb, use_ref_frame_mask, i,
2521                                     &ref_mv_idx);
2522       }
2523       // num_comp_modes_ref == 1 only do (0,0)
2524       if (num_comp_modes_ref == 1 && comp_index % 3 != 0) continue;
2525       // num_comp_modes_ref == 2 only do (0,0) and (NEAREST_NEAREST)
2526       if (num_comp_modes_ref == 2 && comp_index % 3 == 2) continue;
2527       ref_frame = LAST_FRAME;
2528       ref_frame2 = GOLDEN_FRAME;
2529       if (comp_index >= 0 && comp_index < 3) {
2530         // comp_index = 0,1,2 for (0/NEAREST/NEAR) for GOLDEN_LAST.
2531         if (cpi->sf.rt_sf.ref_frame_comp_nonrd[0] == 0 ||
2532             !(cpi->ref_frame_flags & AOM_GOLD_FLAG))
2533           continue;
2534       } else if (comp_index >= 3 && comp_index < 6) {
2535         // comp_index = 3,4,5 for (0/NEAREST/NEAR) for LAST2_LAST.
2536         ref_frame2 = LAST2_FRAME;
2537         if (cpi->sf.rt_sf.ref_frame_comp_nonrd[1] == 0 ||
2538             !(cpi->ref_frame_flags & AOM_LAST2_FLAG))
2539           continue;
2540       } else if (comp_index >= 6 && comp_index < 9) {
2541         // comp_index = 6,7,8 for (0/NEAREST/NEAR) for ALTREF_LAST.
2542         ref_frame2 = ALTREF_FRAME;
2543         if (cpi->sf.rt_sf.ref_frame_comp_nonrd[2] == 0 ||
2544             !(cpi->ref_frame_flags & AOM_ALT_FLAG))
2545           continue;
2546       }
2547       set_compound_mode(x, comp_index, ref_frame, ref_frame2, ref_mv_idx,
2548                         frame_mv, &this_mode);
2549       if (this_mode != GLOBAL_GLOBALMV &&
2550           frame_mv[this_mode][ref_frame].as_int == 0 &&
2551           frame_mv[this_mode][ref_frame2].as_int == 0)
2552         continue;
2553       comp_pred = 1;
2554     } else {
2555       this_mode = ref_mode_set[idx].pred_mode;
2556       ref_frame = ref_mode_set[idx].ref_frame;
2557       ref_frame2 = NONE_FRAME;
2558     }
2559 
2560 #if COLLECT_PICK_MODE_STAT
2561     aom_usec_timer_start(&ms_stat.timer1);
2562     ms_stat.num_searches[bsize][this_mode]++;
2563 #endif
2564     mi->mode = this_mode;
2565     mi->ref_frame[0] = ref_frame;
2566     mi->ref_frame[1] = ref_frame2;
2567 
2568     if (!use_ref_frame_mask[ref_frame]) continue;
2569 
2570     force_mv_inter_layer = 0;
2571     if (cpi->ppi->use_svc && svc->spatial_layer_id > 0 &&
2572         ((ref_frame == LAST_FRAME && svc->skip_mvsearch_last) ||
2573          (ref_frame == GOLDEN_FRAME && svc->skip_mvsearch_gf))) {
2574       // Only test mode if NEARESTMV/NEARMV is (svc_mv_col, svc_mv_row),
2575       // otherwise set NEWMV to (svc_mv_col, svc_mv_row).
2576       // Skip newmv and filter search.
2577       force_mv_inter_layer = 1;
2578       if (this_mode == NEWMV) {
2579         frame_mv[this_mode][ref_frame].as_mv.col = svc_mv_col;
2580         frame_mv[this_mode][ref_frame].as_mv.row = svc_mv_row;
2581       } else if (frame_mv[this_mode][ref_frame].as_mv.col != svc_mv_col ||
2582                  frame_mv[this_mode][ref_frame].as_mv.row != svc_mv_row) {
2583         continue;
2584       }
2585     }
2586 
2587     // If the segment reference frame feature is enabled then do nothing if the
2588     // current ref frame is not allowed.
2589     if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
2590         get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame)
2591       continue;
2592 
2593     if (skip_mode_by_bsize_and_ref_frame(
2594             this_mode, ref_frame, bsize, x->nonrd_prune_ref_frame_search,
2595             sse_zeromv_norm, cpi->sf.rt_sf.nonrd_agressive_skip))
2596       continue;
2597 
2598     if (skip_mode_by_low_temp(this_mode, ref_frame, bsize, x->content_state_sb,
2599                               frame_mv[this_mode][ref_frame],
2600                               force_skip_low_temp_var))
2601       continue;
2602 
2603     // Disable this drop out case if the ref frame segment level feature is
2604     // enabled for this segment. This is to prevent the possibility that we
2605     // end up unable to pick any mode.
2606     if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
2607       // Check for skipping GOLDEN and ALTREF based pred_mv_sad.
2608       if (cpi->sf.rt_sf.nonrd_prune_ref_frame_search > 0 &&
2609           x->pred_mv_sad[ref_frame] != INT_MAX && ref_frame != LAST_FRAME) {
2610         if ((int64_t)(x->pred_mv_sad[ref_frame]) > thresh_sad_pred) continue;
2611       }
2612     }
2613     // Check for skipping NEARMV based on pred_mv_sad.
2614     if (this_mode == NEARMV && x->pred_mv1_sad[ref_frame] != INT_MAX &&
2615         x->pred_mv1_sad[ref_frame] > (x->pred_mv0_sad[ref_frame] << 1))
2616       continue;
2617 
2618     if (!comp_pred) {
2619       if (skip_mode_by_threshold(
2620               this_mode, ref_frame, frame_mv[this_mode][ref_frame],
2621               cpi->rc.frames_since_golden, rd_threshes, rd_thresh_freq_fact,
2622               best_rdc.rdcost, best_pickmode.best_mode_skip_txfm,
2623               (cpi->sf.rt_sf.nonrd_agressive_skip ? 1 : 0)))
2624         continue;
2625     }
2626 
2627     // Select prediction reference frames.
2628     for (int i = 0; i < MAX_MB_PLANE; i++) {
2629       xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
2630       if (comp_pred) xd->plane[i].pre[1] = yv12_mb[ref_frame2][i];
2631     }
2632 
2633     mi->ref_frame[0] = ref_frame;
2634     mi->ref_frame[1] = ref_frame2;
2635     set_ref_ptrs(cm, xd, ref_frame, ref_frame2);
2636 
2637     if (this_mode == NEWMV && !force_mv_inter_layer) {
2638       if (search_new_mv(cpi, x, frame_mv, ref_frame, gf_temporal_ref, bsize,
2639                         mi_row, mi_col, &rate_mv, &best_rdc))
2640         continue;
2641     }
2642 
2643     for (PREDICTION_MODE inter_mv_mode = NEARESTMV; inter_mv_mode <= NEWMV;
2644          inter_mv_mode++) {
2645       if (inter_mv_mode == this_mode) continue;
2646       if (mode_checked[inter_mv_mode][ref_frame] &&
2647           frame_mv[this_mode][ref_frame].as_int ==
2648               frame_mv[inter_mv_mode][ref_frame].as_int) {
2649         skip_this_mv = 1;
2650         break;
2651       }
2652     }
2653 
2654     if (skip_this_mv && !comp_pred) continue;
2655 
2656     mi->mode = this_mode;
2657     mi->mv[0].as_int = frame_mv[this_mode][ref_frame].as_int;
2658     mi->mv[1].as_int = 0;
2659     if (comp_pred) mi->mv[1].as_int = frame_mv[this_mode][ref_frame2].as_int;
2660 
2661     if (reuse_inter_pred) {
2662       if (!this_mode_pred) {
2663         this_mode_pred = &tmp[3];
2664       } else {
2665         this_mode_pred = &tmp[get_pred_buffer(tmp, 3)];
2666         pd->dst.buf = this_mode_pred->data;
2667         pd->dst.stride = bw;
2668       }
2669     }
2670 #if COLLECT_PICK_MODE_STAT
2671     ms_stat.num_nonskipped_searches[bsize][this_mode]++;
2672 #endif
2673 
2674     if (idx == 0) {
2675       // Set color sensitivity on first tested mode only.
2676       // Use y-sad already computed in find_predictors: take the sad with motion
2677       // vector closest to 0; the uv-sad computed below in set_color_sensitivity
2678       // is for zeromv.
2679       int y_sad = x->pred_mv0_sad[LAST_FRAME];
2680       if (x->pred_mv1_sad[LAST_FRAME] != INT_MAX &&
2681           (abs(frame_mv[NEARMV][LAST_FRAME].as_mv.col) +
2682            abs(frame_mv[NEARMV][LAST_FRAME].as_mv.row)) <
2683               (abs(frame_mv[NEARESTMV][LAST_FRAME].as_mv.col) +
2684                abs(frame_mv[NEARESTMV][LAST_FRAME].as_mv.row)))
2685         y_sad = x->pred_mv1_sad[LAST_FRAME];
2686       set_color_sensitivity(cpi, x, xd, bsize, y_sad, x->source_variance);
2687     }
2688     mi->motion_mode = SIMPLE_TRANSLATION;
2689 #if !CONFIG_REALTIME_ONLY
2690     if (cpi->oxcf.motion_mode_cfg.allow_warped_motion) {
2691       calc_num_proj_ref(cpi, x, mi);
2692     }
2693 #endif
2694 
2695     if (enable_filter_search && !force_mv_inter_layer && !comp_pred &&
2696         ((mi->mv[0].as_mv.row & 0x07) || (mi->mv[0].as_mv.col & 0x07)) &&
2697         (ref_frame == LAST_FRAME || !x->nonrd_prune_ref_frame_search)) {
2698       search_filter_ref(cpi, x, &this_rdc, mi_row, mi_col, tmp, bsize,
2699                         reuse_inter_pred, &this_mode_pred, &this_early_term,
2700                         use_model_yrd_large);
2701 #if !CONFIG_REALTIME_ONLY
2702     } else if (cpi->oxcf.motion_mode_cfg.allow_warped_motion &&
2703                this_mode == NEWMV) {
2704       search_motion_mode(cpi, x, &this_rdc, mi_row, mi_col, bsize,
2705                          &this_early_term, use_model_yrd_large, &rate_mv);
2706       if (this_mode == NEWMV) {
2707         frame_mv[this_mode][ref_frame] = mi->mv[0];
2708       }
2709 #endif
2710     } else {
2711       mi->interp_filters =
2712           (filter_ref == SWITCHABLE)
2713               ? av1_broadcast_interp_filter(default_interp_filter)
2714               : av1_broadcast_interp_filter(filter_ref);
2715       if (force_mv_inter_layer)
2716         mi->interp_filters = av1_broadcast_interp_filter(EIGHTTAP_REGULAR);
2717 
2718       // If it is sub-pel motion and best filter was not selected in
2719       // search_filter_ref() for all blocks, then check top and left values and
2720       // force smooth if both were selected to be smooth.
2721       if (cpi->sf.interp_sf.cb_pred_filter_search &&
2722           (mi->mv[0].as_mv.row & 0x07 || mi->mv[0].as_mv.col & 0x07)) {
2723         if (xd->left_mbmi && xd->above_mbmi) {
2724           if ((xd->left_mbmi->interp_filters.as_filters.x_filter ==
2725                    EIGHTTAP_SMOOTH &&
2726                xd->above_mbmi->interp_filters.as_filters.x_filter ==
2727                    EIGHTTAP_SMOOTH))
2728             mi->interp_filters = av1_broadcast_interp_filter(EIGHTTAP_SMOOTH);
2729         }
2730       }
2731 
2732       av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize, 0, 0);
2733 
2734       if (use_model_yrd_large) {
2735         model_skip_for_sb_y_large(cpi, bsize, mi_row, mi_col, x, xd, &this_rdc,
2736                                   &this_early_term, use_modeled_non_rd_cost);
2737       } else {
2738         model_rd_for_sb_y(cpi, bsize, x, xd, &this_rdc,
2739                           use_modeled_non_rd_cost);
2740       }
2741     }
2742 
2743     if (ref_frame == LAST_FRAME && frame_mv[this_mode][ref_frame].as_int == 0) {
2744       sse_zeromv_norm =
2745           (unsigned int)(this_rdc.sse >> (b_width_log2_lookup[bsize] +
2746                                           b_height_log2_lookup[bsize]));
2747     }
2748 
2749     const int skip_ctx = av1_get_skip_txfm_context(xd);
2750     const int skip_txfm_cost = mode_costs->skip_txfm_cost[skip_ctx][1];
2751     const int no_skip_txfm_cost = mode_costs->skip_txfm_cost[skip_ctx][0];
2752     const int64_t sse_y = this_rdc.sse;
2753     if (this_early_term) {
2754       this_rdc.skip_txfm = 1;
2755       this_rdc.rate = skip_txfm_cost;
2756       this_rdc.dist = this_rdc.sse << 4;
2757     } else {
2758       if (use_modeled_non_rd_cost) {
2759         if (this_rdc.skip_txfm) {
2760           this_rdc.rate = skip_txfm_cost;
2761         } else {
2762           this_rdc.rate += no_skip_txfm_cost;
2763         }
2764       } else {
2765         block_yrd(cpi, x, mi_row, mi_col, &this_rdc, &is_skippable, bsize,
2766                   mi->tx_size);
2767         if (this_rdc.skip_txfm ||
2768             RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist) >=
2769                 RDCOST(x->rdmult, 0, this_rdc.sse)) {
2770           if (!this_rdc.skip_txfm) {
2771             // Need to store "real" rdc for possible furure use if UV rdc
2772             // disallows tx skip
2773             nonskip_rdc = this_rdc;
2774             nonskip_rdc.rate += no_skip_txfm_cost;
2775           }
2776           this_rdc.rate = skip_txfm_cost;
2777           this_rdc.skip_txfm = 1;
2778           this_rdc.dist = this_rdc.sse;
2779         } else {
2780           this_rdc.rate += no_skip_txfm_cost;
2781         }
2782       }
2783       if ((x->color_sensitivity[0] || x->color_sensitivity[1])) {
2784         RD_STATS rdc_uv;
2785         const BLOCK_SIZE uv_bsize = get_plane_block_size(
2786             bsize, xd->plane[1].subsampling_x, xd->plane[1].subsampling_y);
2787         if (x->color_sensitivity[0]) {
2788           av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
2789                                         AOM_PLANE_U, AOM_PLANE_U);
2790         }
2791         if (x->color_sensitivity[1]) {
2792           av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
2793                                         AOM_PLANE_V, AOM_PLANE_V);
2794         }
2795         model_rd_for_sb_uv(cpi, uv_bsize, x, xd, &rdc_uv, &this_rdc.sse, 1, 2);
2796         // Restore Y rdc if UV rdc disallows txfm skip
2797         if (this_rdc.skip_txfm && !rdc_uv.skip_txfm &&
2798             nonskip_rdc.rate != INT_MAX)
2799           this_rdc = nonskip_rdc;
2800         this_rdc.rate += rdc_uv.rate;
2801         this_rdc.dist += rdc_uv.dist;
2802         this_rdc.skip_txfm = this_rdc.skip_txfm && rdc_uv.skip_txfm;
2803       }
2804     }
2805 
2806     // TODO(kyslov) account for UV prediction cost
2807     this_rdc.rate += rate_mv;
2808     const int16_t mode_ctx =
2809         av1_mode_context_analyzer(mbmi_ext->mode_context, mi->ref_frame);
2810     this_rdc.rate += cost_mv_ref(mode_costs, this_mode, mode_ctx);
2811 
2812     this_rdc.rate += ref_costs_single[ref_frame];
2813 
2814     this_rdc.rdcost = RDCOST(x->rdmult, this_rdc.rate, this_rdc.dist);
2815     if (cpi->oxcf.rc_cfg.mode == AOM_CBR && !comp_pred) {
2816       newmv_diff_bias(xd, this_mode, &this_rdc, bsize,
2817                       frame_mv[this_mode][ref_frame].as_mv.row,
2818                       frame_mv[this_mode][ref_frame].as_mv.col, cpi->speed,
2819                       x->source_variance, x->content_state_sb);
2820     }
2821 #if CONFIG_AV1_TEMPORAL_DENOISING
2822     if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc_pickmode &&
2823         cpi->denoiser.denoising_level > kDenLowLow) {
2824       av1_denoiser_update_frame_stats(mi, sse_y, this_mode, ctx);
2825       // Keep track of zero_last cost.
2826       if (ref_frame == LAST_FRAME && frame_mv[this_mode][ref_frame].as_int == 0)
2827         zero_last_cost_orig = this_rdc.rdcost;
2828     }
2829 #else
2830     (void)sse_y;
2831 #endif
2832 
2833     mode_checked[this_mode][ref_frame] = 1;
2834 #if COLLECT_PICK_MODE_STAT
2835     aom_usec_timer_mark(&ms_stat.timer1);
2836     ms_stat.nonskipped_search_times[bsize][this_mode] +=
2837         aom_usec_timer_elapsed(&ms_stat.timer1);
2838 #endif
2839     if (this_rdc.rdcost < best_rdc.rdcost) {
2840       best_rdc = this_rdc;
2841       best_early_term = this_early_term;
2842       best_pickmode.best_mode = this_mode;
2843       best_pickmode.best_motion_mode = mi->motion_mode;
2844       best_pickmode.wm_params = mi->wm_params;
2845       best_pickmode.num_proj_ref = mi->num_proj_ref;
2846       best_pickmode.best_pred_filter = mi->interp_filters;
2847       best_pickmode.best_tx_size = mi->tx_size;
2848       best_pickmode.best_ref_frame = ref_frame;
2849       best_pickmode.best_second_ref_frame = ref_frame2;
2850       best_pickmode.best_mode_skip_txfm = this_rdc.skip_txfm;
2851       best_pickmode.best_mode_initial_skip_flag =
2852           (nonskip_rdc.rate == INT_MAX && this_rdc.skip_txfm);
2853 
2854       // This is needed for the compound modes.
2855       frame_mv_best[this_mode][ref_frame].as_int =
2856           frame_mv[this_mode][ref_frame].as_int;
2857       if (ref_frame2 > NONE_FRAME)
2858         frame_mv_best[this_mode][ref_frame2].as_int =
2859             frame_mv[this_mode][ref_frame2].as_int;
2860 
2861       if (reuse_inter_pred) {
2862         free_pred_buffer(best_pickmode.best_pred);
2863         best_pickmode.best_pred = this_mode_pred;
2864       }
2865     } else {
2866       if (reuse_inter_pred) free_pred_buffer(this_mode_pred);
2867     }
2868     if (best_early_term && (idx > 0 || cpi->sf.rt_sf.nonrd_agressive_skip)) {
2869       txfm_info->skip_txfm = 1;
2870       break;
2871     }
2872   }
2873 
2874   mi->mode = best_pickmode.best_mode;
2875   mi->motion_mode = best_pickmode.best_motion_mode;
2876   mi->wm_params = best_pickmode.wm_params;
2877   mi->num_proj_ref = best_pickmode.num_proj_ref;
2878   mi->interp_filters = best_pickmode.best_pred_filter;
2879   mi->tx_size = best_pickmode.best_tx_size;
2880   memset(mi->inter_tx_size, mi->tx_size, sizeof(mi->inter_tx_size));
2881   mi->ref_frame[0] = best_pickmode.best_ref_frame;
2882   mi->mv[0].as_int =
2883       frame_mv_best[best_pickmode.best_mode][best_pickmode.best_ref_frame]
2884           .as_int;
2885   mi->mv[1].as_int = 0;
2886   if (best_pickmode.best_second_ref_frame > INTRA_FRAME) {
2887     mi->ref_frame[1] = best_pickmode.best_second_ref_frame;
2888     mi->mv[1].as_int = frame_mv_best[best_pickmode.best_mode]
2889                                     [best_pickmode.best_second_ref_frame]
2890                                         .as_int;
2891   }
2892   // Perform intra prediction search, if the best SAD is above a certain
2893   // threshold.
2894   mi->angle_delta[PLANE_TYPE_Y] = 0;
2895   mi->angle_delta[PLANE_TYPE_UV] = 0;
2896   mi->filter_intra_mode_info.use_filter_intra = 0;
2897 
2898   estimate_intra_mode(cpi, x, bsize, use_modeled_non_rd_cost, best_early_term,
2899                       ref_costs_single[INTRA_FRAME], reuse_inter_pred,
2900                       &orig_dst, tmp, &this_mode_pred, &best_rdc,
2901                       &best_pickmode);
2902 
2903   pd->dst = orig_dst;
2904   mi->mode = best_pickmode.best_mode;
2905   mi->ref_frame[0] = best_pickmode.best_ref_frame;
2906   mi->ref_frame[1] = best_pickmode.best_second_ref_frame;
2907   txfm_info->skip_txfm = best_rdc.skip_txfm;
2908   if (has_second_ref(mi)) {
2909     mi->comp_group_idx = 0;
2910     mi->compound_idx = 1;
2911     mi->interinter_comp.type = COMPOUND_AVERAGE;
2912   }
2913 
2914   if (!is_inter_block(mi)) {
2915     mi->interp_filters = av1_broadcast_interp_filter(SWITCHABLE_FILTERS);
2916   }
2917 
2918   if (reuse_inter_pred && best_pickmode.best_pred != NULL) {
2919     PRED_BUFFER *const best_pred = best_pickmode.best_pred;
2920     if (best_pred->data != orig_dst.buf && is_inter_mode(mi->mode)) {
2921       aom_convolve_copy(best_pred->data, best_pred->stride, pd->dst.buf,
2922                         pd->dst.stride, bw, bh);
2923     }
2924   }
2925 
2926 #if CONFIG_AV1_TEMPORAL_DENOISING
2927   if (cpi->oxcf.noise_sensitivity > 0 && resize_pending == 0 &&
2928       denoise_svc_pickmode && cpi->denoiser.denoising_level > kDenLowLow &&
2929       cpi->denoiser.reset == 0) {
2930     AV1_DENOISER_DECISION decision = COPY_BLOCK;
2931     ctx->sb_skip_denoising = 0;
2932     av1_pickmode_ctx_den_update(&ctx_den, zero_last_cost_orig, ref_costs_single,
2933                                 frame_mv, reuse_inter_pred, &best_pickmode);
2934     av1_denoiser_denoise(cpi, x, mi_row, mi_col, bsize, ctx, &decision,
2935                          gf_temporal_ref);
2936     if (denoise_recheck_zeromv)
2937       recheck_zeromv_after_denoising(cpi, mi, x, xd, decision, &ctx_den,
2938                                      yv12_mb, &best_rdc, &best_pickmode, bsize,
2939                                      mi_row, mi_col);
2940     best_pickmode.best_ref_frame = ctx_den.best_ref_frame;
2941   }
2942 #endif
2943 
2944   if (cpi->sf.inter_sf.adaptive_rd_thresh && !has_second_ref(mi)) {
2945     THR_MODES best_mode_idx =
2946         mode_idx[best_pickmode.best_ref_frame][mode_offset(mi->mode)];
2947     if (best_pickmode.best_ref_frame == INTRA_FRAME) {
2948       // Only consider the modes that are included in the intra_mode_list.
2949       int intra_modes = sizeof(intra_mode_list) / sizeof(PREDICTION_MODE);
2950       for (int i = 0; i < intra_modes; i++) {
2951         update_thresh_freq_fact(cpi, x, bsize, INTRA_FRAME, best_mode_idx,
2952                                 intra_mode_list[i]);
2953       }
2954     } else {
2955       PREDICTION_MODE this_mode;
2956       for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
2957         update_thresh_freq_fact(cpi, x, bsize, best_pickmode.best_ref_frame,
2958                                 best_mode_idx, this_mode);
2959       }
2960     }
2961   }
2962 
2963 #if CONFIG_INTERNAL_STATS
2964   store_coding_context(x, ctx, mi->mode);
2965 #else
2966   store_coding_context(x, ctx);
2967 #endif  // CONFIG_INTERNAL_STATS
2968 #if COLLECT_PICK_MODE_STAT
2969   aom_usec_timer_mark(&ms_stat.timer2);
2970   ms_stat.avg_block_times[bsize] += aom_usec_timer_elapsed(&ms_stat.timer2);
2971   //
2972   if ((mi_row + mi_size_high[bsize] >= (cpi->common.mi_params.mi_rows)) &&
2973       (mi_col + mi_size_wide[bsize] >= (cpi->common.mi_params.mi_cols))) {
2974     int i, j;
2975     PREDICTION_MODE used_modes[3] = { NEARESTMV, NEARMV, NEWMV };
2976     BLOCK_SIZE bss[5] = { BLOCK_8X8, BLOCK_16X16, BLOCK_32X32, BLOCK_64X64,
2977                           BLOCK_128X128 };
2978     int64_t total_time = 0l;
2979     int32_t total_blocks = 0;
2980 
2981     printf("\n");
2982     for (i = 0; i < 5; i++) {
2983       printf("BS(%d) Num %d, Avg_time %f: ", bss[i], ms_stat.num_blocks[bss[i]],
2984              ms_stat.num_blocks[bss[i]] > 0
2985                  ? (float)ms_stat.avg_block_times[bss[i]] /
2986                        ms_stat.num_blocks[bss[i]]
2987                  : 0);
2988       total_time += ms_stat.avg_block_times[bss[i]];
2989       total_blocks += ms_stat.num_blocks[bss[i]];
2990       for (j = 0; j < 3; j++) {
2991         printf("Mode %d, %d/%d tps %f ", used_modes[j],
2992                ms_stat.num_nonskipped_searches[bss[i]][used_modes[j]],
2993                ms_stat.num_searches[bss[i]][used_modes[j]],
2994                ms_stat.num_nonskipped_searches[bss[i]][used_modes[j]] > 0
2995                    ? (float)ms_stat
2996                              .nonskipped_search_times[bss[i]][used_modes[j]] /
2997                          ms_stat.num_nonskipped_searches[bss[i]][used_modes[j]]
2998                    : 0l);
2999       }
3000       printf("\n");
3001     }
3002     printf("Total time = %ld. Total blocks = %d\n", total_time, total_blocks);
3003   }
3004   //
3005 #endif  // COLLECT_PICK_MODE_STAT
3006   *rd_cost = best_rdc;
3007 }
3008