Coverage Report

Created: 2026-11-12 08:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/aom/av1/encoder/encodeframe_utils.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2020, Alliance for Open Media. All rights reserved.
3
 *
4
 * This source code is subject to the terms of the BSD 2 Clause License and
5
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6
 * was not distributed with this source code in the LICENSE file, you can
7
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8
 * Media Patent License 1.0 was not distributed with this source code in the
9
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10
 */
11
12
#include "aom/aom_codec.h"
13
#include "aom/internal/aom_codec_internal.h"
14
15
#include "av1/common/common_data.h"
16
#include "av1/common/quant_common.h"
17
#include "av1/common/reconintra.h"
18
19
#include "av1/encoder/encoder.h"
20
#include "av1/encoder/encodeframe_utils.h"
21
#include "av1/encoder/encoder_utils.h"
22
#include "av1/encoder/rdopt.h"
23
24
void av1_set_ssim_rdmult(const AV1_COMP *const cpi, int *errorperbit,
25
                         const BLOCK_SIZE bsize, const int mi_row,
26
0
                         const int mi_col, int *const rdmult) {
27
0
  const AV1_COMMON *const cm = &cpi->common;
28
29
0
  const BLOCK_SIZE bsize_base = BLOCK_16X16;
30
0
  const int num_mi_w = mi_size_wide[bsize_base];
31
0
  const int num_mi_h = mi_size_high[bsize_base];
32
0
  const int num_cols = (cm->mi_params.mi_cols + num_mi_w - 1) / num_mi_w;
33
0
  double geom_mean_of_scale;
34
35
  // To avoid overflow of 'geom_mean_of_scale', bsize_base must be at least
36
  // BLOCK_8X8.
37
  //
38
  // For bsize=BLOCK_128X128 and bsize_base=BLOCK_8X8, the loop below would
39
  // iterate 256 times. Considering the maximum value of
40
  // cpi->ssim_rdmult_scaling_factors (see av1_set_mb_ssim_rdmult_scaling()),
41
  // geom_mean_of_scale can go up to 4.8323^256, which is within DBL_MAX
42
  // (maximum value a double data type can hold). If bsize_base is modified to
43
  // BLOCK_4X4 (minimum possible block size), geom_mean_of_scale can go up
44
  // to 4.8323^1024 and exceed DBL_MAX, resulting in data overflow.
45
0
  assert(bsize_base >= BLOCK_8X8);
46
0
  assert(cpi->oxcf.tune_cfg.tuning == AOM_TUNE_SSIM ||
47
0
         cpi->oxcf.tune_cfg.tuning == AOM_TUNE_IQ ||
48
0
         cpi->oxcf.tune_cfg.tuning == AOM_TUNE_SSIMULACRA2);
49
50
0
  if (mi_size_wide[bsize] <= 4 && mi_size_high[bsize] <= 4) {
51
0
    geom_mean_of_scale =
52
0
        cpi->ssim_rdmult_scaling_factors[(mi_row >> 2) * num_cols +
53
0
                                         (mi_col >> 2)];
54
0
  } else {
55
0
    const int num_rows = (cm->mi_params.mi_rows + num_mi_h - 1) / num_mi_h;
56
0
    const int num_bcols = (mi_size_wide[bsize] + num_mi_w - 1) / num_mi_w;
57
0
    const int num_brows = (mi_size_high[bsize] + num_mi_h - 1) / num_mi_h;
58
0
    double num_of_mi = 0.0;
59
0
    geom_mean_of_scale = 1.0;
60
0
    for (int row = mi_row / num_mi_w;
61
0
         row < num_rows && row < mi_row / num_mi_w + num_brows; ++row) {
62
0
      for (int col = mi_col / num_mi_h;
63
0
           col < num_cols && col < mi_col / num_mi_h + num_bcols; ++col) {
64
0
        const int index = row * num_cols + col;
65
0
        assert(cpi->ssim_rdmult_scaling_factors[index] != 0.0);
66
0
        geom_mean_of_scale *= cpi->ssim_rdmult_scaling_factors[index];
67
0
        num_of_mi += 1.0;
68
0
      }
69
0
    }
70
0
    if (num_of_mi > 1.0) {
71
0
      geom_mean_of_scale = pow(geom_mean_of_scale, (1.0 / num_of_mi));
72
0
    }
73
0
  }
74
75
0
  *rdmult = (int)((double)(*rdmult) * geom_mean_of_scale + 0.5);
76
0
  *rdmult = AOMMAX(*rdmult, 0);
77
0
  av1_set_error_per_bit(errorperbit, *rdmult);
78
0
}
79
80
#if CONFIG_SALIENCY_MAP
81
void av1_set_saliency_map_vmaf_rdmult(const AV1_COMP *const cpi,
82
                                      int *errorperbit, const BLOCK_SIZE bsize,
83
                                      const int mi_row, const int mi_col,
84
                                      int *const rdmult) {
85
  const AV1_COMMON *const cm = &cpi->common;
86
  const int num_mi_w = mi_size_wide[bsize];
87
  const int num_mi_h = mi_size_high[bsize];
88
  const int num_cols = (cm->mi_params.mi_cols + num_mi_w - 1) / num_mi_w;
89
90
  *rdmult =
91
      (int)(*rdmult * cpi->sm_scaling_factor[(mi_row / num_mi_h) * num_cols +
92
                                             (mi_col / num_mi_w)]);
93
94
  *rdmult = AOMMAX(*rdmult, 0);
95
  av1_set_error_per_bit(errorperbit, *rdmult);
96
}
97
#endif
98
99
// TODO(angiebird): Move this function to tpl_model.c
100
#if !CONFIG_REALTIME_ONLY
101
int av1_get_cb_rdmult(const AV1_COMP *const cpi, MACROBLOCK *const x,
102
                      const BLOCK_SIZE bsize, const int mi_row,
103
0
                      const int mi_col) {
104
0
  const AV1_COMMON *const cm = &cpi->common;
105
0
  assert(IMPLIES(cpi->ppi->gf_group.size > 0,
106
0
                 cpi->gf_frame_index < cpi->ppi->gf_group.size));
107
0
  const int tpl_idx = cpi->gf_frame_index;
108
0
  int deltaq_rdmult = set_rdmult(cpi, x, -1);
109
0
  if (!av1_tpl_stats_ready(&cpi->ppi->tpl_data, tpl_idx)) return deltaq_rdmult;
110
0
  if (cm->superres_scale_denominator != SCALE_NUMERATOR) return deltaq_rdmult;
111
0
  if (cpi->oxcf.q_cfg.aq_mode != NO_AQ) return deltaq_rdmult;
112
0
  if (x->rb == 0) return deltaq_rdmult;
113
114
0
  TplParams *const tpl_data = &cpi->ppi->tpl_data;
115
0
  TplDepFrame *tpl_frame = &tpl_data->tpl_frame[tpl_idx];
116
0
  TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
117
118
0
  const int mi_wide = mi_size_wide[bsize];
119
0
  const int mi_high = mi_size_high[bsize];
120
121
0
  int tpl_stride = tpl_frame->stride;
122
0
  double intra_cost_base = 0;
123
0
  double mc_dep_cost_base = 0;
124
0
  double cbcmp_base = 0;
125
0
  const int step = 1 << tpl_data->tpl_stats_block_mis_log2;
126
127
0
  for (int row = mi_row; row < mi_row + mi_high; row += step) {
128
0
    for (int col = mi_col; col < mi_col + mi_wide; col += step) {
129
0
      if (row >= cm->mi_params.mi_rows || col >= cm->mi_params.mi_cols)
130
0
        continue;
131
132
0
      TplDepStats *this_stats = &tpl_stats[av1_tpl_ptr_pos(
133
0
          row, col, tpl_stride, tpl_data->tpl_stats_block_mis_log2)];
134
135
0
      double cbcmp = (double)this_stats->srcrf_dist;
136
0
      int64_t mc_dep_delta =
137
0
          RDCOST(tpl_frame->base_rdmult, this_stats->mc_dep_rate,
138
0
                 this_stats->mc_dep_dist);
139
0
      double dist_scaled = (double)(this_stats->recrf_dist << RDDIV_BITS);
140
0
      intra_cost_base += log(dist_scaled) * cbcmp;
141
0
      mc_dep_cost_base += log(3 * dist_scaled + mc_dep_delta) * cbcmp;
142
0
      cbcmp_base += cbcmp;
143
0
    }
144
0
  }
145
146
0
  if (cbcmp_base == 0) return deltaq_rdmult;
147
148
0
  double rk = exp((intra_cost_base - mc_dep_cost_base) / cbcmp_base);
149
0
  deltaq_rdmult = (int)(deltaq_rdmult * (rk / x->rb));
150
151
0
  return AOMMAX(deltaq_rdmult, 1);
152
0
}
153
#endif  // !CONFIG_REALTIME_ONLY
154
155
static inline void update_filter_type_count(FRAME_COUNTS *counts,
156
                                            const MACROBLOCKD *xd,
157
0
                                            const MB_MODE_INFO *mbmi) {
158
0
  int dir;
159
0
  for (dir = 0; dir < 2; ++dir) {
160
0
    const int ctx = av1_get_pred_context_switchable_interp(xd, dir);
161
0
    InterpFilter filter = av1_extract_interp_filter(mbmi->interp_filters, dir);
162
163
    // Only allow the 3 valid SWITCHABLE_FILTERS.
164
0
    assert(filter < SWITCHABLE_FILTERS);
165
0
    ++counts->switchable_interp[ctx][filter];
166
0
  }
167
0
}
168
169
// This function will copy the best reference mode information from
170
// MB_MODE_INFO_EXT_FRAME to MB_MODE_INFO_EXT.
171
static inline void copy_mbmi_ext_frame_to_mbmi_ext(
172
    MB_MODE_INFO_EXT *mbmi_ext,
173
0
    const MB_MODE_INFO_EXT_FRAME *const mbmi_ext_best, uint8_t ref_frame_type) {
174
0
  memcpy(mbmi_ext->ref_mv_stack[ref_frame_type], mbmi_ext_best->ref_mv_stack,
175
0
         sizeof(mbmi_ext->ref_mv_stack[USABLE_REF_MV_STACK_SIZE]));
176
0
  memcpy(mbmi_ext->weight[ref_frame_type], mbmi_ext_best->weight,
177
0
         sizeof(mbmi_ext->weight[USABLE_REF_MV_STACK_SIZE]));
178
0
  mbmi_ext->mode_context[ref_frame_type] = mbmi_ext_best->mode_context;
179
0
  mbmi_ext->ref_mv_count[ref_frame_type] = mbmi_ext_best->ref_mv_count;
180
0
  memcpy(mbmi_ext->global_mvs, mbmi_ext_best->global_mvs,
181
0
         sizeof(mbmi_ext->global_mvs));
182
0
}
183
184
void av1_update_state(const AV1_COMP *const cpi, ThreadData *td,
185
                      const PICK_MODE_CONTEXT *const ctx, int mi_row,
186
0
                      int mi_col, BLOCK_SIZE bsize, RUN_TYPE dry_run) {
187
0
  int i, x_idx, y;
188
0
  const AV1_COMMON *const cm = &cpi->common;
189
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
190
0
  const int num_planes = av1_num_planes(cm);
191
0
  MACROBLOCK *const x = &td->mb;
192
0
  MACROBLOCKD *const xd = &x->e_mbd;
193
0
  struct macroblock_plane *const p = x->plane;
194
0
  struct macroblockd_plane *const pd = xd->plane;
195
0
  const MB_MODE_INFO *const mi = &ctx->mic;
196
0
  if (ctx == NULL) {
197
0
    aom_internal_error(cm->error, AOM_CODEC_ERROR,
198
0
                       "ctx is NULL in av1_update_state: %d %d %d %d %d %d \n",
199
0
                       cm->current_frame.frame_type, cm->width, cm->height,
200
0
                       mi_col, mi_row, bsize);
201
0
  }
202
0
  if (mi == NULL) {
203
0
    aom_internal_error(cm->error, AOM_CODEC_ERROR,
204
0
                       "mi is NULL in av1_update_state: %d %d %d %d %d %d \n",
205
0
                       cm->current_frame.frame_type, cm->width, cm->height,
206
0
                       mi_col, mi_row, bsize);
207
0
  }
208
0
  MB_MODE_INFO *const mi_addr = xd->mi[0];
209
0
  const struct segmentation *const seg = &cm->seg;
210
0
  assert(bsize < BLOCK_SIZES_ALL);
211
0
  assert(mi->bsize == bsize);
212
0
  const int bw = mi_size_wide[bsize];
213
0
  const int bh = mi_size_high[bsize];
214
0
  const int mis = mi_params->mi_stride;
215
0
  const int mi_width = mi_size_wide[bsize];
216
0
  const int mi_height = mi_size_high[bsize];
217
0
  TxfmSearchInfo *txfm_info = &x->txfm_search_info;
218
219
0
  *mi_addr = *mi;
220
0
  copy_mbmi_ext_frame_to_mbmi_ext(&x->mbmi_ext, &ctx->mbmi_ext_best,
221
0
                                  av1_ref_frame_type(ctx->mic.ref_frame));
222
223
0
  txfm_info->skip_txfm = ctx->rd_stats.skip_txfm;
224
225
0
  xd->tx_type_map = ctx->tx_type_map;
226
0
  xd->tx_type_map_stride = mi_size_wide[bsize];
227
  // If not dry_run, copy the transform type data into the frame level buffer.
228
  // Encoder will fetch tx types when writing bitstream.
229
0
  if (!dry_run) {
230
0
    const int grid_idx = get_mi_grid_idx(mi_params, mi_row, mi_col);
231
0
    uint8_t *const tx_type_map = mi_params->tx_type_map + grid_idx;
232
0
    const int mi_stride = mi_params->mi_stride;
233
0
    for (int blk_row = 0; blk_row < bh; ++blk_row) {
234
0
      av1_copy_array(tx_type_map + blk_row * mi_stride,
235
0
                     xd->tx_type_map + blk_row * xd->tx_type_map_stride, bw);
236
0
    }
237
0
    xd->tx_type_map = tx_type_map;
238
0
    xd->tx_type_map_stride = mi_stride;
239
0
  }
240
241
  // If segmentation in use
242
0
  if (seg->enabled) {
243
    // For in frame complexity AQ or ROI copy the segment id from the
244
    // segment map.
245
0
    if (cpi->oxcf.q_cfg.aq_mode == COMPLEXITY_AQ || cpi->roi.enabled) {
246
0
      const uint8_t *const map =
247
0
          seg->update_map ? cpi->enc_seg.map : cm->last_frame_seg_map;
248
0
      mi_addr->segment_id =
249
0
          map ? get_segment_id(mi_params, map, bsize, mi_row, mi_col) : 0;
250
0
    }
251
    // Else for cyclic refresh mode update the segment map, set the segment id
252
    // and then update the quantizer.
253
0
    if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ && !cpi->roi.enabled &&
254
0
        mi_addr->segment_id != AM_SEGMENT_ID_INACTIVE &&
255
0
        !cpi->rc.rtc_external_ratectrl) {
256
0
      av1_cyclic_refresh_update_segment(cpi, x, mi_row, mi_col, bsize,
257
0
                                        ctx->rd_stats.rate, ctx->rd_stats.dist,
258
0
                                        txfm_info->skip_txfm, dry_run);
259
0
    }
260
0
    if (mi_addr->uv_mode == UV_CFL_PRED && !is_cfl_allowed(xd))
261
0
      mi_addr->uv_mode = UV_DC_PRED;
262
263
0
    if (!dry_run && !mi_addr->skip_txfm) {
264
0
      int cdf_num;
265
0
      const uint8_t spatial_pred = av1_get_spatial_seg_pred(
266
0
          cm, xd, &cdf_num, cpi->cyclic_refresh->skip_over4x4);
267
0
      const uint8_t coded_id = av1_neg_interleave(
268
0
          mi_addr->segment_id, spatial_pred, seg->last_active_segid + 1);
269
0
      int64_t spatial_cost = x->mode_costs.spatial_pred_cost[cdf_num][coded_id];
270
0
      td->rd_counts.seg_tmp_pred_cost[0] += spatial_cost;
271
272
0
      const int pred_segment_id =
273
0
          cm->last_frame_seg_map
274
0
              ? get_segment_id(mi_params, cm->last_frame_seg_map, bsize, mi_row,
275
0
                               mi_col)
276
0
              : 0;
277
0
      const int use_tmp_pred = pred_segment_id == mi_addr->segment_id;
278
0
      const uint8_t tmp_pred_ctx = av1_get_pred_context_seg_id(xd);
279
0
      td->rd_counts.seg_tmp_pred_cost[1] +=
280
0
          x->mode_costs.tmp_pred_cost[tmp_pred_ctx][use_tmp_pred];
281
0
      if (!use_tmp_pred) {
282
0
        td->rd_counts.seg_tmp_pred_cost[1] += spatial_cost;
283
0
      }
284
0
    }
285
0
  }
286
287
  // Count zero motion vector.
288
0
  if (!dry_run && !frame_is_intra_only(cm)) {
289
0
    const MV mv = mi->mv[0].as_mv;
290
0
    if (is_inter_block(mi) && mi->ref_frame[0] == LAST_FRAME &&
291
0
        abs(mv.row) < 8 && abs(mv.col) < 8) {
292
0
      const int ymis = AOMMIN(cm->mi_params.mi_rows - mi_row, bh);
293
      // Accumulate low_content_frame.
294
0
      for (int mi_y = 0; mi_y < ymis; mi_y += 2) x->cnt_zeromv += bw << 1;
295
0
    }
296
0
  }
297
298
0
  for (i = 0; i < num_planes; ++i) {
299
0
    p[i].coeff = ctx->coeff[i];
300
0
    p[i].qcoeff = ctx->qcoeff[i];
301
0
    p[i].dqcoeff = ctx->dqcoeff[i];
302
0
    p[i].eobs = ctx->eobs[i];
303
0
    p[i].txb_entropy_ctx = ctx->txb_entropy_ctx[i];
304
0
  }
305
0
  for (i = 0; i < 2; ++i) pd[i].color_index_map = ctx->color_index_map[i];
306
  // Restore the coding context of the MB to that that was in place
307
  // when the mode was picked for it
308
309
0
  const int cols =
310
0
      AOMMIN((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width, mi_width);
311
0
  const int rows = AOMMIN(
312
0
      (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height, mi_height);
313
0
  for (y = 0; y < rows; y++) {
314
0
    for (x_idx = 0; x_idx < cols; x_idx++) xd->mi[x_idx + y * mis] = mi_addr;
315
0
  }
316
317
0
  if (cpi->oxcf.q_cfg.aq_mode ||
318
0
      (cpi->roi.enabled && cpi->roi.delta_qp_enabled))
319
0
    av1_init_plane_quantizers(cpi, x, mi_addr->segment_id, 0);
320
321
0
  if (dry_run) return;
322
323
#if CONFIG_INTERNAL_STATS
324
  {
325
    unsigned int *const mode_chosen_counts =
326
        (unsigned int *)cpi->mode_chosen_counts;  // Cast const away.
327
    if (frame_is_intra_only(cm)) {
328
      static const int kf_mode_index[] = {
329
        THR_DC /*DC_PRED*/,
330
        THR_V_PRED /*V_PRED*/,
331
        THR_H_PRED /*H_PRED*/,
332
        THR_D45_PRED /*D45_PRED*/,
333
        THR_D135_PRED /*D135_PRED*/,
334
        THR_D113_PRED /*D113_PRED*/,
335
        THR_D157_PRED /*D157_PRED*/,
336
        THR_D203_PRED /*D203_PRED*/,
337
        THR_D67_PRED /*D67_PRED*/,
338
        THR_SMOOTH,   /*SMOOTH_PRED*/
339
        THR_SMOOTH_V, /*SMOOTH_V_PRED*/
340
        THR_SMOOTH_H, /*SMOOTH_H_PRED*/
341
        THR_PAETH /*PAETH_PRED*/,
342
      };
343
      ++mode_chosen_counts[kf_mode_index[mi_addr->mode]];
344
    } else {
345
      // Note how often each mode chosen as best
346
      ++mode_chosen_counts[ctx->best_mode_index];
347
    }
348
  }
349
#endif
350
0
  if (!frame_is_intra_only(cm)) {
351
0
    if (is_inter_block(mi) && cm->features.interp_filter == SWITCHABLE) {
352
      // When the frame interp filter is SWITCHABLE, several cases that always
353
      // use the default type (EIGHTTAP_REGULAR) are described in
354
      // av1_is_interp_needed(). Here, we should keep the counts for all
355
      // applicable blocks, so the frame filter resetting decision in
356
      // fix_interp_filter() is made correctly.
357
0
      update_filter_type_count(td->counts, xd, mi_addr);
358
0
    }
359
0
  }
360
361
0
  const int x_mis = AOMMIN(bw, mi_params->mi_cols - mi_col);
362
0
  const int y_mis = AOMMIN(bh, mi_params->mi_rows - mi_row);
363
0
  if (cm->seq_params->order_hint_info.enable_ref_frame_mvs)
364
0
    av1_copy_frame_mvs(cm, mi, mi_row, mi_col, x_mis, y_mis);
365
0
}
366
367
void av1_update_inter_mode_stats(FRAME_CONTEXT *fc, FRAME_COUNTS *counts,
368
0
                                 PREDICTION_MODE mode, int16_t mode_context) {
369
0
  (void)counts;
370
371
0
  int16_t mode_ctx = mode_context & NEWMV_CTX_MASK;
372
0
  if (mode == NEWMV) {
373
#if CONFIG_ENTROPY_STATS
374
    ++counts->newmv_mode[mode_ctx][0];
375
#endif
376
0
    update_cdf(fc->newmv_cdf[mode_ctx], 0, 2);
377
0
    return;
378
0
  }
379
380
#if CONFIG_ENTROPY_STATS
381
  ++counts->newmv_mode[mode_ctx][1];
382
#endif
383
0
  update_cdf(fc->newmv_cdf[mode_ctx], 1, 2);
384
385
0
  mode_ctx = (mode_context >> GLOBALMV_OFFSET) & GLOBALMV_CTX_MASK;
386
0
  if (mode == GLOBALMV) {
387
#if CONFIG_ENTROPY_STATS
388
    ++counts->zeromv_mode[mode_ctx][0];
389
#endif
390
0
    update_cdf(fc->zeromv_cdf[mode_ctx], 0, 2);
391
0
    return;
392
0
  }
393
394
#if CONFIG_ENTROPY_STATS
395
  ++counts->zeromv_mode[mode_ctx][1];
396
#endif
397
0
  update_cdf(fc->zeromv_cdf[mode_ctx], 1, 2);
398
399
0
  mode_ctx = (mode_context >> REFMV_OFFSET) & REFMV_CTX_MASK;
400
#if CONFIG_ENTROPY_STATS
401
  ++counts->refmv_mode[mode_ctx][mode != NEARESTMV];
402
#endif
403
0
  update_cdf(fc->refmv_cdf[mode_ctx], mode != NEARESTMV, 2);
404
0
}
405
406
static void update_palette_cdf(MACROBLOCKD *xd, const MB_MODE_INFO *const mbmi,
407
0
                               FRAME_COUNTS *counts) {
408
0
  FRAME_CONTEXT *fc = xd->tile_ctx;
409
0
  const BLOCK_SIZE bsize = mbmi->bsize;
410
0
  const PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
411
0
  const int palette_bsize_ctx = av1_get_palette_bsize_ctx(bsize);
412
413
0
  (void)counts;
414
415
0
  if (mbmi->mode == DC_PRED) {
416
0
    const int n = pmi->palette_size[0];
417
0
    const int palette_mode_ctx = av1_get_palette_mode_ctx(xd);
418
419
#if CONFIG_ENTROPY_STATS
420
    ++counts->palette_y_mode[palette_bsize_ctx][palette_mode_ctx][n > 0];
421
#endif
422
0
    update_cdf(fc->palette_y_mode_cdf[palette_bsize_ctx][palette_mode_ctx],
423
0
               n > 0, 2);
424
0
    if (n > 0) {
425
#if CONFIG_ENTROPY_STATS
426
      ++counts->palette_y_size[palette_bsize_ctx][n - PALETTE_MIN_SIZE];
427
#endif
428
0
      update_cdf(fc->palette_y_size_cdf[palette_bsize_ctx],
429
0
                 n - PALETTE_MIN_SIZE, PALETTE_SIZES);
430
0
    }
431
0
  }
432
433
0
  if (mbmi->uv_mode == UV_DC_PRED) {
434
0
    const int n = pmi->palette_size[1];
435
0
    const int palette_uv_mode_ctx = (pmi->palette_size[0] > 0);
436
437
#if CONFIG_ENTROPY_STATS
438
    ++counts->palette_uv_mode[palette_uv_mode_ctx][n > 0];
439
#endif
440
0
    update_cdf(fc->palette_uv_mode_cdf[palette_uv_mode_ctx], n > 0, 2);
441
442
0
    if (n > 0) {
443
#if CONFIG_ENTROPY_STATS
444
      ++counts->palette_uv_size[palette_bsize_ctx][n - PALETTE_MIN_SIZE];
445
#endif
446
0
      update_cdf(fc->palette_uv_size_cdf[palette_bsize_ctx],
447
0
                 n - PALETTE_MIN_SIZE, PALETTE_SIZES);
448
0
    }
449
0
  }
450
0
}
451
452
void av1_sum_intra_stats(const AV1_COMMON *const cm, FRAME_COUNTS *counts,
453
                         MACROBLOCKD *xd, const MB_MODE_INFO *const mbmi,
454
                         const MB_MODE_INFO *above_mi,
455
0
                         const MB_MODE_INFO *left_mi, const int intraonly) {
456
0
  FRAME_CONTEXT *fc = xd->tile_ctx;
457
0
  const PREDICTION_MODE y_mode = mbmi->mode;
458
0
  (void)counts;
459
0
  const BLOCK_SIZE bsize = mbmi->bsize;
460
461
0
  if (intraonly) {
462
#if CONFIG_ENTROPY_STATS
463
    const PREDICTION_MODE above = av1_above_block_mode(above_mi);
464
    const PREDICTION_MODE left = av1_left_block_mode(left_mi);
465
    const int above_ctx = intra_mode_context[above];
466
    const int left_ctx = intra_mode_context[left];
467
    ++counts->kf_y_mode[above_ctx][left_ctx][y_mode];
468
#endif  // CONFIG_ENTROPY_STATS
469
0
    update_cdf(get_y_mode_cdf(fc, above_mi, left_mi), y_mode, INTRA_MODES);
470
0
  } else {
471
#if CONFIG_ENTROPY_STATS
472
    ++counts->y_mode[size_group_lookup[bsize]][y_mode];
473
#endif  // CONFIG_ENTROPY_STATS
474
0
    update_cdf(fc->y_mode_cdf[size_group_lookup[bsize]], y_mode, INTRA_MODES);
475
0
  }
476
477
0
  if (av1_filter_intra_allowed(cm, mbmi)) {
478
0
    const int use_filter_intra_mode =
479
0
        mbmi->filter_intra_mode_info.use_filter_intra;
480
#if CONFIG_ENTROPY_STATS
481
    ++counts->filter_intra[mbmi->bsize][use_filter_intra_mode];
482
    if (use_filter_intra_mode) {
483
      ++counts
484
            ->filter_intra_mode[mbmi->filter_intra_mode_info.filter_intra_mode];
485
    }
486
#endif  // CONFIG_ENTROPY_STATS
487
0
    update_cdf(fc->filter_intra_cdfs[mbmi->bsize], use_filter_intra_mode, 2);
488
0
    if (use_filter_intra_mode) {
489
0
      update_cdf(fc->filter_intra_mode_cdf,
490
0
                 mbmi->filter_intra_mode_info.filter_intra_mode,
491
0
                 FILTER_INTRA_MODES);
492
0
    }
493
0
  }
494
0
  if (av1_is_directional_mode(mbmi->mode) && av1_use_angle_delta(bsize)) {
495
#if CONFIG_ENTROPY_STATS
496
    ++counts->angle_delta[mbmi->mode - V_PRED]
497
                         [mbmi->angle_delta[PLANE_TYPE_Y] + MAX_ANGLE_DELTA];
498
#endif
499
0
    update_cdf(fc->angle_delta_cdf[mbmi->mode - V_PRED],
500
0
               mbmi->angle_delta[PLANE_TYPE_Y] + MAX_ANGLE_DELTA,
501
0
               2 * MAX_ANGLE_DELTA + 1);
502
0
  }
503
504
0
  if (!xd->is_chroma_ref) return;
505
506
0
  const UV_PREDICTION_MODE uv_mode = mbmi->uv_mode;
507
0
  const CFL_ALLOWED_TYPE cfl_allowed = is_cfl_allowed(xd);
508
#if CONFIG_ENTROPY_STATS
509
  ++counts->uv_mode[cfl_allowed][y_mode][uv_mode];
510
#endif  // CONFIG_ENTROPY_STATS
511
0
  update_cdf(fc->uv_mode_cdf[cfl_allowed][y_mode], uv_mode,
512
0
             UV_INTRA_MODES - !cfl_allowed);
513
0
  if (uv_mode == UV_CFL_PRED) {
514
0
    const int8_t joint_sign = mbmi->cfl_alpha_signs;
515
0
    const uint8_t idx = mbmi->cfl_alpha_idx;
516
517
#if CONFIG_ENTROPY_STATS
518
    ++counts->cfl_sign[joint_sign];
519
#endif
520
0
    update_cdf(fc->cfl_sign_cdf, joint_sign, CFL_JOINT_SIGNS);
521
0
    if (CFL_SIGN_U(joint_sign) != CFL_SIGN_ZERO) {
522
0
      aom_cdf_prob *cdf_u = fc->cfl_alpha_cdf[CFL_CONTEXT_U(joint_sign)];
523
524
#if CONFIG_ENTROPY_STATS
525
      ++counts->cfl_alpha[CFL_CONTEXT_U(joint_sign)][CFL_IDX_U(idx)];
526
#endif
527
0
      update_cdf(cdf_u, CFL_IDX_U(idx), CFL_ALPHABET_SIZE);
528
0
    }
529
0
    if (CFL_SIGN_V(joint_sign) != CFL_SIGN_ZERO) {
530
0
      aom_cdf_prob *cdf_v = fc->cfl_alpha_cdf[CFL_CONTEXT_V(joint_sign)];
531
532
#if CONFIG_ENTROPY_STATS
533
      ++counts->cfl_alpha[CFL_CONTEXT_V(joint_sign)][CFL_IDX_V(idx)];
534
#endif
535
0
      update_cdf(cdf_v, CFL_IDX_V(idx), CFL_ALPHABET_SIZE);
536
0
    }
537
0
  }
538
0
  const PREDICTION_MODE intra_mode = get_uv_mode(uv_mode);
539
0
  if (av1_is_directional_mode(intra_mode) && av1_use_angle_delta(bsize)) {
540
#if CONFIG_ENTROPY_STATS
541
    ++counts->angle_delta[intra_mode - V_PRED]
542
                         [mbmi->angle_delta[PLANE_TYPE_UV] + MAX_ANGLE_DELTA];
543
#endif
544
0
    update_cdf(fc->angle_delta_cdf[intra_mode - V_PRED],
545
0
               mbmi->angle_delta[PLANE_TYPE_UV] + MAX_ANGLE_DELTA,
546
0
               2 * MAX_ANGLE_DELTA + 1);
547
0
  }
548
0
  if (av1_allow_palette(cm->features.allow_screen_content_tools, bsize)) {
549
0
    update_palette_cdf(xd, mbmi, counts);
550
0
  }
551
0
}
552
553
void av1_restore_context(MACROBLOCK *x, const RD_SEARCH_MACROBLOCK_CONTEXT *ctx,
554
                         int mi_row, int mi_col, BLOCK_SIZE bsize,
555
0
                         const int num_planes) {
556
0
  MACROBLOCKD *xd = &x->e_mbd;
557
0
  int p;
558
0
  const int num_4x4_blocks_wide = mi_size_wide[bsize];
559
0
  const int num_4x4_blocks_high = mi_size_high[bsize];
560
0
  int mi_width = mi_size_wide[bsize];
561
0
  int mi_height = mi_size_high[bsize];
562
0
  for (p = 0; p < num_planes; p++) {
563
0
    int tx_col = mi_col;
564
0
    int tx_row = mi_row & MAX_MIB_MASK;
565
0
    memcpy(
566
0
        xd->above_entropy_context[p] + (tx_col >> xd->plane[p].subsampling_x),
567
0
        ctx->a + num_4x4_blocks_wide * p,
568
0
        (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
569
0
            xd->plane[p].subsampling_x);
570
0
    memcpy(xd->left_entropy_context[p] + (tx_row >> xd->plane[p].subsampling_y),
571
0
           ctx->l + num_4x4_blocks_high * p,
572
0
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
573
0
               xd->plane[p].subsampling_y);
574
0
  }
575
0
  memcpy(xd->above_partition_context + mi_col, ctx->sa,
576
0
         sizeof(*xd->above_partition_context) * mi_width);
577
0
  memcpy(xd->left_partition_context + (mi_row & MAX_MIB_MASK), ctx->sl,
578
0
         sizeof(xd->left_partition_context[0]) * mi_height);
579
0
  xd->above_txfm_context = ctx->p_ta;
580
0
  xd->left_txfm_context = ctx->p_tl;
581
0
  memcpy(xd->above_txfm_context, ctx->ta,
582
0
         sizeof(*xd->above_txfm_context) * mi_width);
583
0
  memcpy(xd->left_txfm_context, ctx->tl,
584
0
         sizeof(*xd->left_txfm_context) * mi_height);
585
0
}
586
587
void av1_save_context(const MACROBLOCK *x, RD_SEARCH_MACROBLOCK_CONTEXT *ctx,
588
                      int mi_row, int mi_col, BLOCK_SIZE bsize,
589
0
                      const int num_planes) {
590
0
  const MACROBLOCKD *xd = &x->e_mbd;
591
0
  int p;
592
0
  int mi_width = mi_size_wide[bsize];
593
0
  int mi_height = mi_size_high[bsize];
594
595
  // buffer the above/left context information of the block in search.
596
0
  for (p = 0; p < num_planes; ++p) {
597
0
    int tx_col = mi_col;
598
0
    int tx_row = mi_row & MAX_MIB_MASK;
599
0
    memcpy(
600
0
        ctx->a + mi_width * p,
601
0
        xd->above_entropy_context[p] + (tx_col >> xd->plane[p].subsampling_x),
602
0
        (sizeof(ENTROPY_CONTEXT) * mi_width) >> xd->plane[p].subsampling_x);
603
0
    memcpy(ctx->l + mi_height * p,
604
0
           xd->left_entropy_context[p] + (tx_row >> xd->plane[p].subsampling_y),
605
0
           (sizeof(ENTROPY_CONTEXT) * mi_height) >> xd->plane[p].subsampling_y);
606
0
  }
607
0
  memcpy(ctx->sa, xd->above_partition_context + mi_col,
608
0
         sizeof(*xd->above_partition_context) * mi_width);
609
0
  memcpy(ctx->sl, xd->left_partition_context + (mi_row & MAX_MIB_MASK),
610
0
         sizeof(xd->left_partition_context[0]) * mi_height);
611
0
  memcpy(ctx->ta, xd->above_txfm_context,
612
0
         sizeof(*xd->above_txfm_context) * mi_width);
613
0
  memcpy(ctx->tl, xd->left_txfm_context,
614
0
         sizeof(*xd->left_txfm_context) * mi_height);
615
0
  ctx->p_ta = xd->above_txfm_context;
616
0
  ctx->p_tl = xd->left_txfm_context;
617
0
}
618
619
static void set_partial_sb_partition(const AV1_COMMON *const cm,
620
                                     MB_MODE_INFO *mi, int bh_in, int bw_in,
621
                                     int mi_rows_remaining,
622
                                     int mi_cols_remaining, BLOCK_SIZE bsize,
623
0
                                     MB_MODE_INFO **mib) {
624
0
  int bh = bh_in;
625
0
  int r, c;
626
0
  for (r = 0; r < cm->seq_params->mib_size; r += bh) {
627
0
    int bw = bw_in;
628
0
    for (c = 0; c < cm->seq_params->mib_size; c += bw) {
629
0
      const int grid_index = get_mi_grid_idx(&cm->mi_params, r, c);
630
0
      const int mi_index = get_alloc_mi_idx(&cm->mi_params, r, c);
631
0
      mib[grid_index] = mi + mi_index;
632
0
      mib[grid_index]->bsize = find_partition_size(
633
0
          bsize, mi_rows_remaining - r, mi_cols_remaining - c, &bh, &bw);
634
0
    }
635
0
  }
636
0
}
637
638
// This function attempts to set all mode info entries in a given superblock
639
// to the same block partition size.
640
// However, at the bottom and right borders of the image the requested size
641
// may not be allowed in which case this code attempts to choose the largest
642
// allowable partition.
643
void av1_set_fixed_partitioning(AV1_COMP *cpi, const TileInfo *const tile,
644
                                MB_MODE_INFO **mib, int mi_row, int mi_col,
645
0
                                BLOCK_SIZE bsize) {
646
0
  AV1_COMMON *const cm = &cpi->common;
647
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
648
0
  const int mi_rows_remaining = tile->mi_row_end - mi_row;
649
0
  const int mi_cols_remaining = tile->mi_col_end - mi_col;
650
0
  MB_MODE_INFO *const mi_upper_left =
651
0
      mi_params->mi_alloc + get_alloc_mi_idx(mi_params, mi_row, mi_col);
652
0
  int bh = mi_size_high[bsize];
653
0
  int bw = mi_size_wide[bsize];
654
655
0
  assert(bsize >= mi_params->mi_alloc_bsize &&
656
0
         "Attempted to use bsize < mi_params->mi_alloc_bsize");
657
0
  assert((mi_rows_remaining > 0) && (mi_cols_remaining > 0));
658
659
  // Apply the requested partition size to the SB if it is all "in image"
660
0
  if ((mi_cols_remaining >= cm->seq_params->mib_size) &&
661
0
      (mi_rows_remaining >= cm->seq_params->mib_size)) {
662
0
    for (int block_row = 0; block_row < cm->seq_params->mib_size;
663
0
         block_row += bh) {
664
0
      for (int block_col = 0; block_col < cm->seq_params->mib_size;
665
0
           block_col += bw) {
666
0
        const int grid_index = get_mi_grid_idx(mi_params, block_row, block_col);
667
0
        const int mi_index = get_alloc_mi_idx(mi_params, block_row, block_col);
668
0
        mib[grid_index] = mi_upper_left + mi_index;
669
0
        mib[grid_index]->bsize = bsize;
670
0
      }
671
0
    }
672
0
  } else {
673
    // Else this is a partial SB.
674
0
    set_partial_sb_partition(cm, mi_upper_left, bh, bw, mi_rows_remaining,
675
0
                             mi_cols_remaining, bsize, mib);
676
0
  }
677
0
}
678
679
int av1_is_leaf_split_partition(AV1_COMMON *cm, int mi_row, int mi_col,
680
0
                                BLOCK_SIZE bsize) {
681
0
  const int bs = mi_size_wide[bsize];
682
0
  const int hbs = bs / 2;
683
0
  assert(bsize >= BLOCK_8X8);
684
0
  const BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
685
686
0
  for (int i = 0; i < 4; i++) {
687
0
    int x_idx = (i & 1) * hbs;
688
0
    int y_idx = (i >> 1) * hbs;
689
0
    if ((mi_row + y_idx >= cm->mi_params.mi_rows) ||
690
0
        (mi_col + x_idx >= cm->mi_params.mi_cols))
691
0
      return 0;
692
0
    if (get_partition(cm, mi_row + y_idx, mi_col + x_idx, subsize) !=
693
0
            PARTITION_NONE &&
694
0
        subsize != BLOCK_8X8)
695
0
      return 0;
696
0
  }
697
0
  return 1;
698
0
}
699
700
#if !CONFIG_REALTIME_ONLY
701
int av1_get_rdmult_delta(AV1_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
702
0
                         int mi_col, int orig_rdmult) {
703
0
  AV1_COMMON *const cm = &cpi->common;
704
0
  const GF_GROUP *const gf_group = &cpi->ppi->gf_group;
705
0
  assert(IMPLIES(cpi->ppi->gf_group.size > 0,
706
0
                 cpi->gf_frame_index < cpi->ppi->gf_group.size));
707
0
  const int tpl_idx = cpi->gf_frame_index;
708
0
  TplParams *const tpl_data = &cpi->ppi->tpl_data;
709
0
  const uint8_t block_mis_log2 = tpl_data->tpl_stats_block_mis_log2;
710
0
  int64_t intra_cost = 0;
711
0
  int64_t mc_dep_cost = 0;
712
0
  const int mi_wide = mi_size_wide[bsize];
713
0
  const int mi_high = mi_size_high[bsize];
714
715
0
  TplDepFrame *tpl_frame = &tpl_data->tpl_frame[tpl_idx];
716
0
  TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
717
0
  int tpl_stride = tpl_frame->stride;
718
719
0
  if (!av1_tpl_stats_ready(&cpi->ppi->tpl_data, cpi->gf_frame_index)) {
720
0
    return orig_rdmult;
721
0
  }
722
0
  if (!is_frame_tpl_eligible(gf_group, cpi->gf_frame_index)) {
723
0
    return orig_rdmult;
724
0
  }
725
726
0
#ifndef NDEBUG
727
0
  int mi_count = 0;
728
0
#endif
729
0
  const int mi_col_sr =
730
0
      coded_to_superres_mi(mi_col, cm->superres_scale_denominator);
731
0
  const int mi_col_end_sr =
732
0
      coded_to_superres_mi(mi_col + mi_wide, cm->superres_scale_denominator);
733
0
  const int mi_cols_sr = av1_pixels_to_mi(cm->superres_upscaled_width);
734
0
  const int step = 1 << block_mis_log2;
735
0
  const int row_step = step;
736
0
  const int col_step_sr =
737
0
      coded_to_superres_mi(step, cm->superres_scale_denominator);
738
0
  for (int row = mi_row; row < mi_row + mi_high; row += row_step) {
739
0
    for (int col = mi_col_sr; col < mi_col_end_sr; col += col_step_sr) {
740
0
      if (row >= cm->mi_params.mi_rows || col >= mi_cols_sr) continue;
741
0
      TplDepStats *this_stats =
742
0
          &tpl_stats[av1_tpl_ptr_pos(row, col, tpl_stride, block_mis_log2)];
743
0
      int64_t mc_dep_delta =
744
0
          RDCOST(tpl_frame->base_rdmult, this_stats->mc_dep_rate,
745
0
                 this_stats->mc_dep_dist);
746
0
      intra_cost += this_stats->recrf_dist << RDDIV_BITS;
747
0
      mc_dep_cost += (this_stats->recrf_dist << RDDIV_BITS) + mc_dep_delta;
748
0
#ifndef NDEBUG
749
0
      mi_count++;
750
0
#endif
751
0
    }
752
0
  }
753
0
  assert(mi_count <= MAX_TPL_BLK_IN_SB * MAX_TPL_BLK_IN_SB);
754
755
0
  double beta = 1.0;
756
0
  if (mc_dep_cost > 0 && intra_cost > 0) {
757
0
    const double r0 = cpi->rd.r0;
758
0
    const double rk = (double)intra_cost / mc_dep_cost;
759
0
    beta = (r0 / rk);
760
0
  }
761
762
0
  int rdmult = av1_get_adaptive_rdmult(cpi, beta);
763
764
0
  rdmult = AOMMIN(rdmult, orig_rdmult * 3 / 2);
765
0
  rdmult = AOMMAX(rdmult, orig_rdmult * 1 / 2);
766
767
0
  rdmult = AOMMAX(1, rdmult);
768
769
0
  return rdmult;
770
0
}
771
772
// Checks to see if a super block is on a horizontal image edge.
773
// In most cases this is the "real" edge unless there are formatting
774
// bars embedded in the stream.
775
0
int av1_active_h_edge(const AV1_COMP *cpi, int mi_row, int mi_step) {
776
0
  int top_edge = 0;
777
0
  int bottom_edge = cpi->common.mi_params.mi_rows;
778
0
  int is_active_h_edge = 0;
779
780
  // For two pass account for any formatting bars detected.
781
0
  if (is_stat_consumption_stage_twopass(cpi)) {
782
0
    const AV1_COMMON *const cm = &cpi->common;
783
0
    const FIRSTPASS_STATS *const this_frame_stats = read_one_frame_stats(
784
0
        &cpi->ppi->twopass, cm->current_frame.display_order_hint);
785
0
    if (this_frame_stats == NULL) return AOM_CODEC_ERROR;
786
787
    // The inactive region is specified in MBs not mi units.
788
    // The image edge is in the following MB row.
789
0
    top_edge += (int)(this_frame_stats->inactive_zone_rows * 4);
790
791
0
    bottom_edge -= (int)(this_frame_stats->inactive_zone_rows * 4);
792
0
    bottom_edge = AOMMAX(top_edge, bottom_edge);
793
0
  }
794
795
0
  if (((top_edge >= mi_row) && (top_edge < (mi_row + mi_step))) ||
796
0
      ((bottom_edge >= mi_row) && (bottom_edge < (mi_row + mi_step)))) {
797
0
    is_active_h_edge = 1;
798
0
  }
799
0
  return is_active_h_edge;
800
0
}
801
802
// Checks to see if a super block is on a vertical image edge.
803
// In most cases this is the "real" edge unless there are formatting
804
// bars embedded in the stream.
805
0
int av1_active_v_edge(const AV1_COMP *cpi, int mi_col, int mi_step) {
806
0
  int left_edge = 0;
807
0
  int right_edge = cpi->common.mi_params.mi_cols;
808
0
  int is_active_v_edge = 0;
809
810
  // For two pass account for any formatting bars detected.
811
0
  if (is_stat_consumption_stage_twopass(cpi)) {
812
0
    const AV1_COMMON *const cm = &cpi->common;
813
0
    const FIRSTPASS_STATS *const this_frame_stats = read_one_frame_stats(
814
0
        &cpi->ppi->twopass, cm->current_frame.display_order_hint);
815
0
    if (this_frame_stats == NULL) return AOM_CODEC_ERROR;
816
817
    // The inactive region is specified in MBs not mi units.
818
    // The image edge is in the following MB row.
819
0
    left_edge += (int)(this_frame_stats->inactive_zone_cols * 4);
820
821
0
    right_edge -= (int)(this_frame_stats->inactive_zone_cols * 4);
822
0
    right_edge = AOMMAX(left_edge, right_edge);
823
0
  }
824
825
0
  if (((left_edge >= mi_col) && (left_edge < (mi_col + mi_step))) ||
826
0
      ((right_edge >= mi_col) && (right_edge < (mi_col + mi_step)))) {
827
0
    is_active_v_edge = 1;
828
0
  }
829
0
  return is_active_v_edge;
830
0
}
831
832
void av1_get_tpl_stats_sb(AV1_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
833
0
                          int mi_col, SuperBlockEnc *sb_enc) {
834
0
  sb_enc->tpl_data_count = 0;
835
836
0
  if (!cpi->oxcf.algo_cfg.enable_tpl_model) return;
837
0
  if (cpi->common.current_frame.frame_type == KEY_FRAME) return;
838
0
  const FRAME_UPDATE_TYPE update_type =
839
0
      get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
840
0
  if (update_type == INTNL_OVERLAY_UPDATE || update_type == OVERLAY_UPDATE)
841
0
    return;
842
0
  assert(IMPLIES(cpi->ppi->gf_group.size > 0,
843
0
                 cpi->gf_frame_index < cpi->ppi->gf_group.size));
844
845
0
  AV1_COMMON *const cm = &cpi->common;
846
0
  const int gf_group_index = cpi->gf_frame_index;
847
0
  TplParams *const tpl_data = &cpi->ppi->tpl_data;
848
0
  if (!av1_tpl_stats_ready(tpl_data, gf_group_index)) return;
849
0
  const int mi_wide = mi_size_wide[bsize];
850
0
  const int mi_high = mi_size_high[bsize];
851
852
0
  TplDepFrame *tpl_frame = &tpl_data->tpl_frame[gf_group_index];
853
0
  TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
854
0
  int tpl_stride = tpl_frame->stride;
855
856
0
  int mi_count = 0;
857
0
  int count = 0;
858
0
  const int mi_col_sr =
859
0
      coded_to_superres_mi(mi_col, cm->superres_scale_denominator);
860
0
  const int mi_col_end_sr =
861
0
      coded_to_superres_mi(mi_col + mi_wide, cm->superres_scale_denominator);
862
  // mi_cols_sr is mi_cols at superres case.
863
0
  const int mi_cols_sr = av1_pixels_to_mi(cm->superres_upscaled_width);
864
865
  // TPL store unit size is not the same as the motion estimation unit size.
866
  // Here always use motion estimation size to avoid getting repetitive inter/
867
  // intra cost.
868
0
  const BLOCK_SIZE tpl_bsize = convert_length_to_bsize(tpl_data->tpl_bsize_1d);
869
0
  assert(mi_size_wide[tpl_bsize] == mi_size_high[tpl_bsize]);
870
0
  const int row_step = mi_size_high[tpl_bsize];
871
0
  const int col_step_sr = coded_to_superres_mi(mi_size_wide[tpl_bsize],
872
0
                                               cm->superres_scale_denominator);
873
874
  // Stride is only based on SB size, and we fill in values for every 16x16
875
  // block in a SB.
876
0
  sb_enc->tpl_stride = (mi_col_end_sr - mi_col_sr) / col_step_sr;
877
878
0
  for (int row = mi_row; row < mi_row + mi_high; row += row_step) {
879
0
    for (int col = mi_col_sr; col < mi_col_end_sr; col += col_step_sr) {
880
0
      assert(count < MAX_TPL_BLK_IN_SB * MAX_TPL_BLK_IN_SB);
881
      // Handle partial SB, so that no invalid values are used later.
882
0
      if (row >= cm->mi_params.mi_rows || col >= mi_cols_sr) {
883
0
        sb_enc->tpl_inter_cost[count] = INT64_MAX;
884
0
        sb_enc->tpl_intra_cost[count] = INT64_MAX;
885
0
        for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
886
0
          sb_enc->tpl_mv[count][i].as_int = INVALID_MV;
887
0
        }
888
0
        count++;
889
0
        continue;
890
0
      }
891
892
0
      TplDepStats *this_stats = &tpl_stats[av1_tpl_ptr_pos(
893
0
          row, col, tpl_stride, tpl_data->tpl_stats_block_mis_log2)];
894
0
      sb_enc->tpl_inter_cost[count] = this_stats->inter_cost
895
0
                                      << TPL_DEP_COST_SCALE_LOG2;
896
0
      sb_enc->tpl_intra_cost[count] = this_stats->intra_cost
897
0
                                      << TPL_DEP_COST_SCALE_LOG2;
898
0
      memcpy(sb_enc->tpl_mv[count], this_stats->mv, sizeof(this_stats->mv));
899
0
      mi_count++;
900
0
      count++;
901
0
    }
902
0
  }
903
904
0
  assert(mi_count <= MAX_TPL_BLK_IN_SB * MAX_TPL_BLK_IN_SB);
905
0
  sb_enc->tpl_data_count = mi_count;
906
0
}
907
908
// analysis_type 0: Use mc_dep_cost and intra_cost
909
// analysis_type 1: Use count of best inter predictor chosen
910
// analysis_type 2: Use cost reduction from intra to inter for best inter
911
//                  predictor chosen
912
int av1_get_q_for_deltaq_objective(AV1_COMP *const cpi, ThreadData *td,
913
                                   int64_t *delta_dist, BLOCK_SIZE bsize,
914
0
                                   int mi_row, int mi_col) {
915
0
  AV1_COMMON *const cm = &cpi->common;
916
0
  assert(IMPLIES(cpi->ppi->gf_group.size > 0,
917
0
                 cpi->gf_frame_index < cpi->ppi->gf_group.size));
918
0
  const int tpl_idx = cpi->gf_frame_index;
919
0
  TplParams *const tpl_data = &cpi->ppi->tpl_data;
920
0
  const uint8_t block_mis_log2 = tpl_data->tpl_stats_block_mis_log2;
921
0
  double intra_cost = 0;
922
0
  double mc_dep_reg = 0;
923
0
  double mc_dep_cost = 0;
924
0
  double cbcmp_base = 1;
925
0
  double srcrf_dist = 0;
926
0
  double srcrf_sse = 0;
927
0
  double srcrf_rate = 0;
928
0
  const int mi_wide = mi_size_wide[bsize];
929
0
  const int mi_high = mi_size_high[bsize];
930
0
  const int base_qindex = cm->quant_params.base_qindex;
931
932
0
  if (tpl_idx >= MAX_TPL_FRAME_IDX) return base_qindex;
933
934
0
  TplDepFrame *tpl_frame = &tpl_data->tpl_frame[tpl_idx];
935
0
  TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
936
0
  int tpl_stride = tpl_frame->stride;
937
0
  if (!tpl_frame->is_valid) return base_qindex;
938
939
0
#ifndef NDEBUG
940
0
  int mi_count = 0;
941
0
#endif
942
0
  const int mi_col_sr =
943
0
      coded_to_superres_mi(mi_col, cm->superres_scale_denominator);
944
0
  const int mi_col_end_sr =
945
0
      coded_to_superres_mi(mi_col + mi_wide, cm->superres_scale_denominator);
946
0
  const int mi_cols_sr = av1_pixels_to_mi(cm->superres_upscaled_width);
947
0
  const int step = 1 << block_mis_log2;
948
0
  const int row_step = step;
949
0
  const int col_step_sr =
950
0
      coded_to_superres_mi(step, cm->superres_scale_denominator);
951
0
  for (int row = mi_row; row < mi_row + mi_high; row += row_step) {
952
0
    for (int col = mi_col_sr; col < mi_col_end_sr; col += col_step_sr) {
953
0
      if (row >= cm->mi_params.mi_rows || col >= mi_cols_sr) continue;
954
0
      TplDepStats *this_stats =
955
0
          &tpl_stats[av1_tpl_ptr_pos(row, col, tpl_stride, block_mis_log2)];
956
0
      double cbcmp = (double)this_stats->srcrf_dist;
957
0
      int64_t mc_dep_delta =
958
0
          RDCOST(tpl_frame->base_rdmult, this_stats->mc_dep_rate,
959
0
                 this_stats->mc_dep_dist);
960
0
      double dist_scaled = (double)(this_stats->recrf_dist << RDDIV_BITS);
961
0
      intra_cost += log(dist_scaled) * cbcmp;
962
0
      mc_dep_cost += log(dist_scaled + mc_dep_delta) * cbcmp;
963
0
      mc_dep_reg += log(3 * dist_scaled + mc_dep_delta) * cbcmp;
964
0
      srcrf_dist += (double)(this_stats->srcrf_dist << RDDIV_BITS);
965
0
      srcrf_sse += (double)(this_stats->srcrf_sse << RDDIV_BITS);
966
0
      srcrf_rate += (double)(this_stats->srcrf_rate << TPL_DEP_COST_SCALE_LOG2);
967
0
#ifndef NDEBUG
968
0
      mi_count++;
969
0
#endif
970
0
      cbcmp_base += cbcmp;
971
0
    }
972
0
  }
973
0
  assert(mi_count <= MAX_TPL_BLK_IN_SB * MAX_TPL_BLK_IN_SB);
974
975
0
  int offset = 0;
976
0
  double beta = 1.0;
977
0
  double rk;
978
0
  if (mc_dep_cost > 0 && intra_cost > 0) {
979
0
    const double r0 = cpi->rd.r0;
980
0
    rk = exp((intra_cost - mc_dep_cost) / cbcmp_base);
981
0
    td->mb.rb = exp((intra_cost - mc_dep_reg) / cbcmp_base);
982
0
    beta = (r0 / rk);
983
0
    assert(beta > 0.0);
984
0
  } else {
985
0
    return base_qindex;
986
0
  }
987
0
  offset = av1_get_deltaq_offset(cm->seq_params->bit_depth, base_qindex, beta);
988
989
0
  const DeltaQInfo *const delta_q_info = &cm->delta_q_info;
990
0
  offset = AOMMIN(offset, delta_q_info->delta_q_res * 9 - 1);
991
0
  offset = AOMMAX(offset, -delta_q_info->delta_q_res * 9 + 1);
992
0
  int qindex = cm->quant_params.base_qindex + offset;
993
0
  qindex = AOMMIN(qindex, MAXQ);
994
0
  qindex = AOMMAX(qindex, MINQ);
995
996
0
  int frm_qstep = av1_dc_quant_QTX(base_qindex, 0, cm->seq_params->bit_depth);
997
0
  int sbs_qstep =
998
0
      av1_dc_quant_QTX(base_qindex, offset, cm->seq_params->bit_depth);
999
1000
0
  if (delta_dist) {
1001
0
    double sbs_dist = srcrf_dist * pow((double)sbs_qstep / frm_qstep, 2.0);
1002
0
    double sbs_rate = srcrf_rate * ((double)frm_qstep / sbs_qstep);
1003
0
    sbs_dist = AOMMIN(sbs_dist, srcrf_sse);
1004
0
    *delta_dist = (int64_t)((sbs_dist - srcrf_dist) / rk);
1005
0
    *delta_dist += RDCOST(tpl_frame->base_rdmult, 4 * 256, 0);
1006
0
    *delta_dist += RDCOST(tpl_frame->base_rdmult, sbs_rate - srcrf_rate, 0);
1007
0
  }
1008
0
  return qindex;
1009
0
}
1010
1011
#if !DISABLE_HDR_LUMA_DELTAQ
1012
// offset table defined in Table3 of T-REC-H.Sup15 document.
1013
static const int hdr_thres[HDR_QP_LEVELS + 1] = { 0,   301, 367, 434, 501, 567,
1014
                                                  634, 701, 767, 834, 1024 };
1015
1016
static const int hdr10_qp_offset[HDR_QP_LEVELS] = { 3,  2,  1,  0,  -1,
1017
                                                    -2, -3, -4, -5, -6 };
1018
#endif
1019
1020
int av1_get_q_for_hdr(AV1_COMP *const cpi, MACROBLOCK *const x,
1021
0
                      BLOCK_SIZE bsize, int mi_row, int mi_col) {
1022
0
  AV1_COMMON *const cm = &cpi->common;
1023
0
  assert(cm->seq_params->bit_depth == AOM_BITS_10);
1024
1025
0
#if DISABLE_HDR_LUMA_DELTAQ
1026
0
  (void)x;
1027
0
  (void)bsize;
1028
0
  (void)mi_row;
1029
0
  (void)mi_col;
1030
0
  return cm->quant_params.base_qindex;
1031
#else
1032
  // calculate pixel average
1033
  const int block_luma_avg = av1_log_block_avg(cpi, x, bsize, mi_row, mi_col);
1034
  // adjust offset based on average of the pixel block
1035
  int offset = 0;
1036
  for (int i = 0; i < HDR_QP_LEVELS; i++) {
1037
    if (block_luma_avg >= hdr_thres[i] && block_luma_avg < hdr_thres[i + 1]) {
1038
      offset = (int)(hdr10_qp_offset[i] * QP_SCALE_FACTOR);
1039
      break;
1040
    }
1041
  }
1042
1043
  const DeltaQInfo *const delta_q_info = &cm->delta_q_info;
1044
  offset = AOMMIN(offset, delta_q_info->delta_q_res * 9 - 1);
1045
  offset = AOMMAX(offset, -delta_q_info->delta_q_res * 9 + 1);
1046
  int qindex = cm->quant_params.base_qindex + offset;
1047
  qindex = AOMMIN(qindex, MAXQ);
1048
  qindex = AOMMAX(qindex, MINQ);
1049
1050
  return qindex;
1051
#endif
1052
0
}
1053
#endif  // !CONFIG_REALTIME_ONLY
1054
1055
void av1_reset_simple_motion_tree_partition(SIMPLE_MOTION_DATA_TREE *sms_tree,
1056
0
                                            BLOCK_SIZE bsize) {
1057
0
  if (sms_tree == NULL) return;
1058
0
  sms_tree->partitioning = PARTITION_NONE;
1059
1060
0
  if (bsize >= BLOCK_8X8) {
1061
0
    BLOCK_SIZE subsize = get_partition_subsize(bsize, PARTITION_SPLIT);
1062
0
    for (int idx = 0; idx < 4; ++idx)
1063
0
      av1_reset_simple_motion_tree_partition(sms_tree->split[idx], subsize);
1064
0
  }
1065
0
}
1066
1067
// Record the ref frames that have been selected by square partition blocks.
1068
void av1_update_picked_ref_frames_mask(MACROBLOCK *const x, int ref_type,
1069
                                       BLOCK_SIZE bsize, int mib_size,
1070
0
                                       int mi_row, int mi_col) {
1071
0
  assert(mi_size_wide[bsize] == mi_size_high[bsize]);
1072
0
  const int sb_size_mask = mib_size - 1;
1073
0
  const int mi_row_in_sb = mi_row & sb_size_mask;
1074
0
  const int mi_col_in_sb = mi_col & sb_size_mask;
1075
0
  const int mi_size = mi_size_wide[bsize];
1076
0
  for (int i = mi_row_in_sb; i < mi_row_in_sb + mi_size; ++i) {
1077
0
    for (int j = mi_col_in_sb; j < mi_col_in_sb + mi_size; ++j) {
1078
0
      x->picked_ref_frames_mask[i * 32 + j] |= 1 << ref_type;
1079
0
    }
1080
0
  }
1081
0
}
1082
1083
#if defined(__GNUC__) || defined(__clang__)
1084
__attribute__((noinline))
1085
#endif
1086
static void avg_cdf_symbol_general(aom_cdf_prob *cdf_ptr_left,
1087
                                   const aom_cdf_prob *cdf_ptr_tr, int num_cdfs,
1088
                                   int cdf_stride, int nsymbs, int wt_left,
1089
0
                                   int wt_tr) {
1090
0
  for (int i = 0; i < num_cdfs; i++) {
1091
0
    for (int j = 0; j <= nsymbs; j++) {
1092
0
      cdf_ptr_left[i * cdf_stride + j] =
1093
0
          (aom_cdf_prob)(((int)cdf_ptr_left[i * cdf_stride + j] * wt_left +
1094
0
                          (int)cdf_ptr_tr[i * cdf_stride + j] * wt_tr +
1095
0
                          ((wt_left + wt_tr) / 2)) /
1096
0
                         (wt_left + wt_tr));
1097
0
      assert(cdf_ptr_left[i * cdf_stride + j] >= 0 &&
1098
0
             cdf_ptr_left[i * cdf_stride + j] < CDF_PROB_TOP);
1099
0
    }
1100
0
  }
1101
0
}
1102
1103
// Precondition for the 3:1 fast path: a, b < CDF_PROB_TOP (32768), so
1104
// (uint16_t)(a + b) <= 65534 never wraps uint16_t. Kept as a comment rather
1105
// than an inner-loop assert so !NDEBUG builds preserve SIMD
1106
// auto-vectorization (vpavgw/pavgw).
1107
static inline void avg_cdf_symbol(aom_cdf_prob *restrict cdf_ptr_left,
1108
                                  const aom_cdf_prob *restrict cdf_ptr_tr,
1109
                                  int num_cdfs, int cdf_stride, int nsymbs,
1110
0
                                  int wt_left, int wt_tr) {
1111
  // Fast path for the common 3:1 row-mt CDF weighting:
1112
  // (3 * a + b + 2) >> 2 == (a + ((a + b) >> 1) + 1) >> 1, which compilers
1113
  // auto-vectorize using unsigned 16-bit average instructions.
1114
0
  if (wt_left == 3 && wt_tr == 1) {
1115
0
    if (cdf_stride == nsymbs + 1) {
1116
0
      const int total = num_cdfs * cdf_stride;
1117
0
      for (int idx = 0; idx < total; idx++) {
1118
0
        const uint16_t a = cdf_ptr_left[idx];
1119
0
        const uint16_t b = cdf_ptr_tr[idx];
1120
0
        cdf_ptr_left[idx] =
1121
0
            (aom_cdf_prob)((a + ((uint16_t)(a + b) >> 1) + 1) >> 1);
1122
0
      }
1123
0
    } else {
1124
0
      for (int i = 0; i < num_cdfs; i++) {
1125
0
        for (int j = 0; j <= nsymbs; j++) {
1126
0
          const uint16_t a = cdf_ptr_left[i * cdf_stride + j];
1127
0
          const uint16_t b = cdf_ptr_tr[i * cdf_stride + j];
1128
0
          cdf_ptr_left[i * cdf_stride + j] =
1129
0
              (aom_cdf_prob)((a + ((uint16_t)(a + b) >> 1) + 1) >> 1);
1130
0
        }
1131
0
      }
1132
0
    }
1133
0
  } else {
1134
0
    avg_cdf_symbol_general(cdf_ptr_left, cdf_ptr_tr, num_cdfs, cdf_stride,
1135
0
                           nsymbs, wt_left, wt_tr);
1136
0
  }
1137
0
}
1138
1139
#define AVERAGE_CDF(cname_left, cname_tr, nsymbs) \
1140
0
  AVG_CDF_STRIDE(cname_left, cname_tr, nsymbs, CDF_SIZE(nsymbs))
1141
1142
#define AVG_CDF_STRIDE(cname_left, cname_tr, nsymbs, cdf_stride)           \
1143
0
  do {                                                                     \
1144
0
    aom_cdf_prob *cdf_ptr_left = (aom_cdf_prob *)cname_left;               \
1145
0
    aom_cdf_prob *cdf_ptr_tr = (aom_cdf_prob *)cname_tr;                   \
1146
0
    int array_size = (int)sizeof(cname_left) / sizeof(aom_cdf_prob);       \
1147
0
    int num_cdfs = array_size / cdf_stride;                                \
1148
0
    avg_cdf_symbol(cdf_ptr_left, cdf_ptr_tr, num_cdfs, cdf_stride, nsymbs, \
1149
0
                   wt_left, wt_tr);                                        \
1150
0
  } while (0)
1151
1152
static void avg_nmv(nmv_context *nmv_left, nmv_context *nmv_tr, int wt_left,
1153
0
                    int wt_tr) {
1154
0
  AVERAGE_CDF(nmv_left->joints_cdf, nmv_tr->joints_cdf, 4);
1155
0
  for (int i = 0; i < 2; i++) {
1156
0
    AVERAGE_CDF(nmv_left->comps[i].classes_cdf, nmv_tr->comps[i].classes_cdf,
1157
0
                MV_CLASSES);
1158
0
    AVERAGE_CDF(nmv_left->comps[i].class0_fp_cdf,
1159
0
                nmv_tr->comps[i].class0_fp_cdf, MV_FP_SIZE);
1160
0
    AVERAGE_CDF(nmv_left->comps[i].fp_cdf, nmv_tr->comps[i].fp_cdf, MV_FP_SIZE);
1161
0
    AVERAGE_CDF(nmv_left->comps[i].sign_cdf, nmv_tr->comps[i].sign_cdf, 2);
1162
0
    AVERAGE_CDF(nmv_left->comps[i].class0_hp_cdf,
1163
0
                nmv_tr->comps[i].class0_hp_cdf, 2);
1164
0
    AVERAGE_CDF(nmv_left->comps[i].hp_cdf, nmv_tr->comps[i].hp_cdf, 2);
1165
0
    AVERAGE_CDF(nmv_left->comps[i].class0_cdf, nmv_tr->comps[i].class0_cdf,
1166
0
                CLASS0_SIZE);
1167
0
    AVERAGE_CDF(nmv_left->comps[i].bits_cdf, nmv_tr->comps[i].bits_cdf, 2);
1168
0
  }
1169
0
}
1170
1171
// In case of row-based multi-threading of encoder, since we always
1172
// keep a top - right sync, we can average the top - right SB's CDFs and
1173
// the left SB's CDFs and use the same for current SB's encoding to
1174
// improve the performance. This function facilitates the averaging
1175
// of CDF and used only when row-mt is enabled in encoder.
1176
void av1_avg_cdf_symbols(FRAME_CONTEXT *ctx_left, FRAME_CONTEXT *ctx_tr,
1177
0
                         int wt_left, int wt_tr) {
1178
0
  assert(ctx_left != ctx_tr);
1179
0
  AVERAGE_CDF(ctx_left->txb_skip_cdf, ctx_tr->txb_skip_cdf, 2);
1180
0
  AVERAGE_CDF(ctx_left->eob_extra_cdf, ctx_tr->eob_extra_cdf, 2);
1181
0
  AVERAGE_CDF(ctx_left->dc_sign_cdf, ctx_tr->dc_sign_cdf, 2);
1182
0
  AVERAGE_CDF(ctx_left->eob_flag_cdf16, ctx_tr->eob_flag_cdf16, 5);
1183
0
  AVERAGE_CDF(ctx_left->eob_flag_cdf32, ctx_tr->eob_flag_cdf32, 6);
1184
0
  AVERAGE_CDF(ctx_left->eob_flag_cdf64, ctx_tr->eob_flag_cdf64, 7);
1185
0
  AVERAGE_CDF(ctx_left->eob_flag_cdf128, ctx_tr->eob_flag_cdf128, 8);
1186
0
  AVERAGE_CDF(ctx_left->eob_flag_cdf256, ctx_tr->eob_flag_cdf256, 9);
1187
0
  AVERAGE_CDF(ctx_left->eob_flag_cdf512, ctx_tr->eob_flag_cdf512, 10);
1188
0
  AVERAGE_CDF(ctx_left->eob_flag_cdf1024, ctx_tr->eob_flag_cdf1024, 11);
1189
0
  AVERAGE_CDF(ctx_left->coeff_base_eob_cdf, ctx_tr->coeff_base_eob_cdf, 3);
1190
0
  AVERAGE_CDF(ctx_left->coeff_base_cdf, ctx_tr->coeff_base_cdf, 4);
1191
0
  AVERAGE_CDF(ctx_left->coeff_br_cdf, ctx_tr->coeff_br_cdf, BR_CDF_SIZE);
1192
0
  AVERAGE_CDF(ctx_left->newmv_cdf, ctx_tr->newmv_cdf, 2);
1193
0
  AVERAGE_CDF(ctx_left->zeromv_cdf, ctx_tr->zeromv_cdf, 2);
1194
0
  AVERAGE_CDF(ctx_left->refmv_cdf, ctx_tr->refmv_cdf, 2);
1195
0
  AVERAGE_CDF(ctx_left->drl_cdf, ctx_tr->drl_cdf, 2);
1196
0
  AVERAGE_CDF(ctx_left->inter_compound_mode_cdf,
1197
0
              ctx_tr->inter_compound_mode_cdf, INTER_COMPOUND_MODES);
1198
0
  AVERAGE_CDF(ctx_left->compound_type_cdf, ctx_tr->compound_type_cdf,
1199
0
              MASKED_COMPOUND_TYPES);
1200
0
  AVERAGE_CDF(ctx_left->wedge_idx_cdf, ctx_tr->wedge_idx_cdf, 16);
1201
0
  AVERAGE_CDF(ctx_left->interintra_cdf, ctx_tr->interintra_cdf, 2);
1202
0
  AVERAGE_CDF(ctx_left->wedge_interintra_cdf, ctx_tr->wedge_interintra_cdf, 2);
1203
0
  AVERAGE_CDF(ctx_left->interintra_mode_cdf, ctx_tr->interintra_mode_cdf,
1204
0
              INTERINTRA_MODES);
1205
0
  AVERAGE_CDF(ctx_left->motion_mode_cdf, ctx_tr->motion_mode_cdf, MOTION_MODES);
1206
0
  AVERAGE_CDF(ctx_left->obmc_cdf, ctx_tr->obmc_cdf, 2);
1207
0
  AVERAGE_CDF(ctx_left->palette_y_size_cdf, ctx_tr->palette_y_size_cdf,
1208
0
              PALETTE_SIZES);
1209
0
  AVERAGE_CDF(ctx_left->palette_uv_size_cdf, ctx_tr->palette_uv_size_cdf,
1210
0
              PALETTE_SIZES);
1211
0
  for (int j = 0; j < PALETTE_SIZES; j++) {
1212
0
    int nsymbs = j + PALETTE_MIN_SIZE;
1213
0
    AVG_CDF_STRIDE(ctx_left->palette_y_color_index_cdf[j],
1214
0
                   ctx_tr->palette_y_color_index_cdf[j], nsymbs,
1215
0
                   CDF_SIZE(PALETTE_COLORS));
1216
0
    AVG_CDF_STRIDE(ctx_left->palette_uv_color_index_cdf[j],
1217
0
                   ctx_tr->palette_uv_color_index_cdf[j], nsymbs,
1218
0
                   CDF_SIZE(PALETTE_COLORS));
1219
0
  }
1220
0
  AVERAGE_CDF(ctx_left->palette_y_mode_cdf, ctx_tr->palette_y_mode_cdf, 2);
1221
0
  AVERAGE_CDF(ctx_left->palette_uv_mode_cdf, ctx_tr->palette_uv_mode_cdf, 2);
1222
0
  AVERAGE_CDF(ctx_left->comp_inter_cdf, ctx_tr->comp_inter_cdf, 2);
1223
0
  AVERAGE_CDF(ctx_left->single_ref_cdf, ctx_tr->single_ref_cdf, 2);
1224
0
  AVERAGE_CDF(ctx_left->comp_ref_type_cdf, ctx_tr->comp_ref_type_cdf, 2);
1225
0
  AVERAGE_CDF(ctx_left->uni_comp_ref_cdf, ctx_tr->uni_comp_ref_cdf, 2);
1226
0
  AVERAGE_CDF(ctx_left->comp_ref_cdf, ctx_tr->comp_ref_cdf, 2);
1227
0
  AVERAGE_CDF(ctx_left->comp_bwdref_cdf, ctx_tr->comp_bwdref_cdf, 2);
1228
0
  AVERAGE_CDF(ctx_left->txfm_partition_cdf, ctx_tr->txfm_partition_cdf, 2);
1229
0
  AVERAGE_CDF(ctx_left->compound_index_cdf, ctx_tr->compound_index_cdf, 2);
1230
0
  AVERAGE_CDF(ctx_left->comp_group_idx_cdf, ctx_tr->comp_group_idx_cdf, 2);
1231
0
  AVERAGE_CDF(ctx_left->skip_mode_cdfs, ctx_tr->skip_mode_cdfs, 2);
1232
0
  AVERAGE_CDF(ctx_left->skip_txfm_cdfs, ctx_tr->skip_txfm_cdfs, 2);
1233
0
  AVERAGE_CDF(ctx_left->intra_inter_cdf, ctx_tr->intra_inter_cdf, 2);
1234
0
  avg_nmv(&ctx_left->nmvc, &ctx_tr->nmvc, wt_left, wt_tr);
1235
0
  avg_nmv(&ctx_left->ndvc, &ctx_tr->ndvc, wt_left, wt_tr);
1236
0
  AVERAGE_CDF(ctx_left->intrabc_cdf, ctx_tr->intrabc_cdf, 2);
1237
0
  AVERAGE_CDF(ctx_left->seg.pred_cdf, ctx_tr->seg.pred_cdf, 2);
1238
0
  AVERAGE_CDF(ctx_left->seg.spatial_pred_seg_cdf,
1239
0
              ctx_tr->seg.spatial_pred_seg_cdf, MAX_SEGMENTS);
1240
0
  AVERAGE_CDF(ctx_left->filter_intra_cdfs, ctx_tr->filter_intra_cdfs, 2);
1241
0
  AVERAGE_CDF(ctx_left->filter_intra_mode_cdf, ctx_tr->filter_intra_mode_cdf,
1242
0
              FILTER_INTRA_MODES);
1243
0
  AVERAGE_CDF(ctx_left->switchable_restore_cdf, ctx_tr->switchable_restore_cdf,
1244
0
              RESTORE_SWITCHABLE_TYPES);
1245
0
  AVERAGE_CDF(ctx_left->wiener_restore_cdf, ctx_tr->wiener_restore_cdf, 2);
1246
0
  AVERAGE_CDF(ctx_left->sgrproj_restore_cdf, ctx_tr->sgrproj_restore_cdf, 2);
1247
0
  AVERAGE_CDF(ctx_left->y_mode_cdf, ctx_tr->y_mode_cdf, INTRA_MODES);
1248
0
  AVG_CDF_STRIDE(ctx_left->uv_mode_cdf[0], ctx_tr->uv_mode_cdf[0],
1249
0
                 UV_INTRA_MODES - 1, CDF_SIZE(UV_INTRA_MODES));
1250
0
  AVERAGE_CDF(ctx_left->uv_mode_cdf[1], ctx_tr->uv_mode_cdf[1], UV_INTRA_MODES);
1251
0
  for (int i = 0; i < PARTITION_CONTEXTS; i++) {
1252
0
    if (i < 4) {
1253
0
      AVG_CDF_STRIDE(ctx_left->partition_cdf[i], ctx_tr->partition_cdf[i], 4,
1254
0
                     CDF_SIZE(10));
1255
0
    } else if (i < 16) {
1256
0
      AVERAGE_CDF(ctx_left->partition_cdf[i], ctx_tr->partition_cdf[i], 10);
1257
0
    } else {
1258
0
      AVG_CDF_STRIDE(ctx_left->partition_cdf[i], ctx_tr->partition_cdf[i], 8,
1259
0
                     CDF_SIZE(10));
1260
0
    }
1261
0
  }
1262
0
  AVERAGE_CDF(ctx_left->switchable_interp_cdf, ctx_tr->switchable_interp_cdf,
1263
0
              SWITCHABLE_FILTERS);
1264
0
  AVERAGE_CDF(ctx_left->kf_y_cdf, ctx_tr->kf_y_cdf, INTRA_MODES);
1265
0
  AVERAGE_CDF(ctx_left->angle_delta_cdf, ctx_tr->angle_delta_cdf,
1266
0
              2 * MAX_ANGLE_DELTA + 1);
1267
0
  AVG_CDF_STRIDE(ctx_left->tx_size_cdf[0], ctx_tr->tx_size_cdf[0], MAX_TX_DEPTH,
1268
0
                 CDF_SIZE(MAX_TX_DEPTH + 1));
1269
0
  AVERAGE_CDF(ctx_left->tx_size_cdf[1], ctx_tr->tx_size_cdf[1],
1270
0
              MAX_TX_DEPTH + 1);
1271
0
  AVERAGE_CDF(ctx_left->tx_size_cdf[2], ctx_tr->tx_size_cdf[2],
1272
0
              MAX_TX_DEPTH + 1);
1273
0
  AVERAGE_CDF(ctx_left->tx_size_cdf[3], ctx_tr->tx_size_cdf[3],
1274
0
              MAX_TX_DEPTH + 1);
1275
0
  AVERAGE_CDF(ctx_left->delta_q_cdf, ctx_tr->delta_q_cdf, DELTA_Q_PROBS + 1);
1276
0
  AVERAGE_CDF(ctx_left->delta_lf_cdf, ctx_tr->delta_lf_cdf, DELTA_LF_PROBS + 1);
1277
0
  for (int i = 0; i < FRAME_LF_COUNT; i++) {
1278
0
    AVERAGE_CDF(ctx_left->delta_lf_multi_cdf[i], ctx_tr->delta_lf_multi_cdf[i],
1279
0
                DELTA_LF_PROBS + 1);
1280
0
  }
1281
0
  AVG_CDF_STRIDE(ctx_left->intra_ext_tx_cdf[1], ctx_tr->intra_ext_tx_cdf[1], 7,
1282
0
                 CDF_SIZE(TX_TYPES));
1283
0
  AVG_CDF_STRIDE(ctx_left->intra_ext_tx_cdf[2], ctx_tr->intra_ext_tx_cdf[2], 5,
1284
0
                 CDF_SIZE(TX_TYPES));
1285
0
  AVG_CDF_STRIDE(ctx_left->inter_ext_tx_cdf[1], ctx_tr->inter_ext_tx_cdf[1], 16,
1286
0
                 CDF_SIZE(TX_TYPES));
1287
0
  AVG_CDF_STRIDE(ctx_left->inter_ext_tx_cdf[2], ctx_tr->inter_ext_tx_cdf[2], 12,
1288
0
                 CDF_SIZE(TX_TYPES));
1289
0
  AVG_CDF_STRIDE(ctx_left->inter_ext_tx_cdf[3], ctx_tr->inter_ext_tx_cdf[3], 2,
1290
0
                 CDF_SIZE(TX_TYPES));
1291
0
  AVERAGE_CDF(ctx_left->cfl_sign_cdf, ctx_tr->cfl_sign_cdf, CFL_JOINT_SIGNS);
1292
0
  AVERAGE_CDF(ctx_left->cfl_alpha_cdf, ctx_tr->cfl_alpha_cdf,
1293
0
              CFL_ALPHABET_SIZE);
1294
0
}
1295
1296
// Check neighbor blocks' motion information.
1297
static int check_neighbor_blocks(MB_MODE_INFO **mi, int mi_stride,
1298
                                 const TileInfo *const tile_info, int mi_row,
1299
0
                                 int mi_col) {
1300
0
  int is_above_low_motion = 1;
1301
0
  int is_left_low_motion = 1;
1302
0
  const int thr = 24;
1303
1304
  // Check above block.
1305
0
  if (mi_row > tile_info->mi_row_start) {
1306
0
    const MB_MODE_INFO *above_mbmi = mi[-mi_stride];
1307
0
    const int_mv above_mv = above_mbmi->mv[0];
1308
0
    if (above_mbmi->mode >= INTRA_MODE_END &&
1309
0
        (abs(above_mv.as_mv.row) > thr || abs(above_mv.as_mv.col) > thr))
1310
0
      is_above_low_motion = 0;
1311
0
  }
1312
1313
  // Check left block.
1314
0
  if (mi_col > tile_info->mi_col_start) {
1315
0
    const MB_MODE_INFO *left_mbmi = mi[-1];
1316
0
    const int_mv left_mv = left_mbmi->mv[0];
1317
0
    if (left_mbmi->mode >= INTRA_MODE_END &&
1318
0
        (abs(left_mv.as_mv.row) > thr || abs(left_mv.as_mv.col) > thr))
1319
0
      is_left_low_motion = 0;
1320
0
  }
1321
1322
0
  return (is_above_low_motion && is_left_low_motion);
1323
0
}
1324
1325
// Check this block's motion in a fast way.
1326
static int fast_detect_non_zero_motion(AV1_COMP *cpi, const uint8_t *src_y,
1327
                                       int src_ystride,
1328
                                       const uint8_t *last_src_y,
1329
                                       int last_src_ystride, int mi_row,
1330
0
                                       int mi_col) {
1331
0
  AV1_COMMON *const cm = &cpi->common;
1332
0
  const BLOCK_SIZE bsize = cm->seq_params->sb_size;
1333
0
  unsigned int blk_sad = INT_MAX;
1334
0
  if (cpi->src_sad_blk_64x64 != NULL) {
1335
0
    const int sb_size_by_mb = (bsize == BLOCK_128X128)
1336
0
                                  ? (cm->seq_params->mib_size >> 1)
1337
0
                                  : cm->seq_params->mib_size;
1338
0
    const int sb_cols =
1339
0
        (cm->mi_params.mi_cols + sb_size_by_mb - 1) / sb_size_by_mb;
1340
0
    const int sbi_col = mi_col / sb_size_by_mb;
1341
0
    const int sbi_row = mi_row / sb_size_by_mb;
1342
0
    blk_sad = (unsigned int)cpi->src_sad_blk_64x64[sbi_col + sbi_row * sb_cols];
1343
0
  } else {
1344
0
    blk_sad = cpi->ppi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y,
1345
0
                                          last_src_ystride);
1346
0
  }
1347
1348
  // Search 4 1-away points.
1349
0
  const uint8_t *const search_pos[4] = {
1350
0
    last_src_y - last_src_ystride,
1351
0
    last_src_y - 1,
1352
0
    last_src_y + 1,
1353
0
    last_src_y + last_src_ystride,
1354
0
  };
1355
0
  unsigned int sad_arr[4];
1356
0
  cpi->ppi->fn_ptr[bsize].sdx4df(src_y, src_ystride, search_pos,
1357
0
                                 last_src_ystride, sad_arr);
1358
1359
0
  blk_sad = (blk_sad * 5) >> 3;
1360
0
  return (blk_sad < sad_arr[0] && blk_sad < sad_arr[1] &&
1361
0
          blk_sad < sad_arr[2] && blk_sad < sad_arr[3]);
1362
0
}
1363
1364
// Grade the temporal variation of the source by comparing the current sb and
1365
// its collocated block in the last frame.
1366
void av1_source_content_sb(AV1_COMP *cpi, MACROBLOCK *x, TileDataEnc *tile_data,
1367
0
                           int mi_row, int mi_col) {
1368
0
  if (cpi->last_source->y_width != cpi->source->y_width ||
1369
0
      cpi->last_source->y_height != cpi->source->y_height)
1370
0
    return;
1371
0
#if CONFIG_AV1_HIGHBITDEPTH
1372
0
  if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) return;
1373
0
#endif
1374
1375
0
  unsigned int tmp_sse;
1376
0
  unsigned int tmp_variance;
1377
0
  const BLOCK_SIZE bsize = cpi->common.seq_params->sb_size;
1378
0
  uint8_t *src_y = cpi->source->y_buffer;
1379
0
  const int src_ystride = cpi->source->y_stride;
1380
0
  const int src_offset = src_ystride * (mi_row << 2) + (mi_col << 2);
1381
0
  uint8_t *last_src_y = cpi->last_source->y_buffer;
1382
0
  const int last_src_ystride = cpi->last_source->y_stride;
1383
0
  const int last_src_offset = last_src_ystride * (mi_row << 2) + (mi_col << 2);
1384
0
  uint64_t avg_source_sse_threshold_verylow = 10000;     // ~1.5*1.5*(64*64)
1385
0
  uint64_t avg_source_sse_threshold_low[2] = { 100000,   // ~5*5*(64*64)
1386
0
                                               36000 };  // ~3*3*(64*64)
1387
1388
0
  uint64_t avg_source_sse_threshold_high = 1000000;  // ~15*15*(64*64)
1389
0
  if (cpi->sf.rt_sf.increase_source_sad_thresh) {
1390
0
    avg_source_sse_threshold_high = avg_source_sse_threshold_high << 1;
1391
0
    avg_source_sse_threshold_low[0] = avg_source_sse_threshold_low[0] << 1;
1392
0
    avg_source_sse_threshold_verylow = avg_source_sse_threshold_verylow << 1;
1393
0
  }
1394
0
  uint64_t sum_sq_thresh = 10000;  // sum = sqrt(thresh / 64*64)) ~1.5
1395
0
  src_y += src_offset;
1396
0
  last_src_y += last_src_offset;
1397
0
  tmp_variance = cpi->ppi->fn_ptr[bsize].vf(src_y, src_ystride, last_src_y,
1398
0
                                            last_src_ystride, &tmp_sse);
1399
  // rd thresholds
1400
0
  if (tmp_sse < avg_source_sse_threshold_low[1])
1401
0
    x->content_state_sb.source_sad_rd = kLowSad;
1402
1403
  // nonrd thresholds
1404
0
  if (tmp_sse == 0) {
1405
0
    x->content_state_sb.source_sad_nonrd = kZeroSad;
1406
0
    return;
1407
0
  }
1408
0
  if (tmp_sse < avg_source_sse_threshold_verylow)
1409
0
    x->content_state_sb.source_sad_nonrd = kVeryLowSad;
1410
0
  else if (tmp_sse < avg_source_sse_threshold_low[0])
1411
0
    x->content_state_sb.source_sad_nonrd = kLowSad;
1412
0
  else if (tmp_sse > avg_source_sse_threshold_high)
1413
0
    x->content_state_sb.source_sad_nonrd = kHighSad;
1414
1415
  // Detect large lighting change.
1416
  // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1417
0
  if (tmp_variance < (tmp_sse >> 1) && (tmp_sse - tmp_variance) > sum_sq_thresh)
1418
0
    x->content_state_sb.lighting_change = 1;
1419
0
  if ((tmp_sse - tmp_variance) < (sum_sq_thresh >> 1))
1420
0
    x->content_state_sb.low_sumdiff = 1;
1421
1422
0
  if (tmp_sse > ((avg_source_sse_threshold_high * 7) >> 3) &&
1423
0
      !x->content_state_sb.lighting_change && !x->content_state_sb.low_sumdiff)
1424
0
    x->sb_force_fixed_part = 0;
1425
1426
0
  if (!cpi->sf.rt_sf.use_rtc_tf || cpi->rc.high_source_sad ||
1427
0
      cpi->rc.frame_source_sad > 20000 || cpi->svc.number_spatial_layers > 1)
1428
0
    return;
1429
1430
  // In-place temporal filter. If psnr calculation is enabled, we store the
1431
  // source for that.
1432
0
  AV1_COMMON *const cm = &cpi->common;
1433
  // Calculate n*mean^2
1434
0
  const unsigned int nmean2 = tmp_sse - tmp_variance;
1435
0
  const int ac_q_step = av1_ac_quant_QTX(cm->quant_params.base_qindex, 0,
1436
0
                                         cm->seq_params->bit_depth);
1437
0
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1438
0
  const int avg_q_step = av1_ac_quant_QTX(p_rc->avg_frame_qindex[INTER_FRAME],
1439
0
                                          0, cm->seq_params->bit_depth);
1440
1441
0
  const unsigned int threshold = (cpi->sf.rt_sf.use_rtc_tf == 1)
1442
0
                                     ? clamp(avg_q_step, 250, 1000) * ac_q_step
1443
0
                                     : 250 * ac_q_step;
1444
1445
  // TODO(yunqing): use a weighted sum instead of averaging in filtering.
1446
0
  if (tmp_variance <= threshold && nmean2 <= 15) {
1447
    // Check neighbor blocks. If neighbor blocks aren't low-motion blocks,
1448
    // skip temporal filtering for this block.
1449
0
    MB_MODE_INFO **mi = cm->mi_params.mi_grid_base +
1450
0
                        get_mi_grid_idx(&cm->mi_params, mi_row, mi_col);
1451
0
    const TileInfo *const tile_info = &tile_data->tile_info;
1452
0
    const int is_neighbor_blocks_low_motion = check_neighbor_blocks(
1453
0
        mi, cm->mi_params.mi_stride, tile_info, mi_row, mi_col);
1454
0
    if (!is_neighbor_blocks_low_motion) return;
1455
1456
    // Only consider 64x64 SB for now. Need to extend to 128x128 for large SB
1457
    // size.
1458
    // Test several nearby points. If non-zero mv exists, don't do temporal
1459
    // filtering.
1460
0
    const int is_this_blk_low_motion = fast_detect_non_zero_motion(
1461
0
        cpi, src_y, src_ystride, last_src_y, last_src_ystride, mi_row, mi_col);
1462
1463
0
    if (!is_this_blk_low_motion) return;
1464
1465
0
    const int shift_x[2] = { 0, cpi->source->subsampling_x };
1466
0
    const int shift_y[2] = { 0, cpi->source->subsampling_y };
1467
0
    const uint8_t h = block_size_high[bsize];
1468
0
    const uint8_t w = block_size_wide[bsize];
1469
1470
0
    for (int plane = 0; plane < av1_num_planes(cm); ++plane) {
1471
0
      uint8_t *src = cpi->source->buffers[plane];
1472
0
      const int src_stride = cpi->source->strides[plane != 0];
1473
0
      uint8_t *last_src = cpi->last_source->buffers[plane];
1474
0
      const int last_src_stride = cpi->last_source->strides[plane != 0];
1475
0
      src += src_stride * (mi_row << (2 - shift_y[plane != 0])) +
1476
0
             (mi_col << (2 - shift_x[plane != 0]));
1477
0
      last_src += last_src_stride * (mi_row << (2 - shift_y[plane != 0])) +
1478
0
                  (mi_col << (2 - shift_x[plane != 0]));
1479
1480
0
      for (int i = 0; i < (h >> shift_y[plane != 0]); ++i) {
1481
0
        for (int j = 0; j < (w >> shift_x[plane != 0]); ++j) {
1482
0
          src[j] = (last_src[j] + src[j]) >> 1;
1483
0
        }
1484
0
        src += src_stride;
1485
0
        last_src += last_src_stride;
1486
0
      }
1487
0
    }
1488
0
  }
1489
0
}
1490
1491
// Memset the mbmis at the current superblock to 0
1492
void av1_reset_mbmi(CommonModeInfoParams *const mi_params, BLOCK_SIZE sb_size,
1493
0
                    int mi_row, int mi_col) {
1494
  // size of sb in unit of mi (BLOCK_4X4)
1495
0
  const int sb_size_mi = mi_size_wide[sb_size];
1496
0
  const int mi_alloc_size_1d = mi_size_wide[mi_params->mi_alloc_bsize];
1497
  // size of sb in unit of allocated mi size
1498
0
  const int sb_size_alloc_mi = mi_size_wide[sb_size] / mi_alloc_size_1d;
1499
0
  assert(mi_params->mi_alloc_stride % sb_size_alloc_mi == 0 &&
1500
0
         "mi is not allocated as a multiple of sb!");
1501
0
  assert(mi_params->mi_stride % sb_size_mi == 0 &&
1502
0
         "mi_grid_base is not allocated as a multiple of sb!");
1503
1504
0
  const int mi_rows = mi_size_high[sb_size];
1505
0
  for (int cur_mi_row = 0; cur_mi_row < mi_rows; cur_mi_row++) {
1506
0
    assert(get_mi_grid_idx(mi_params, 0, mi_col + mi_alloc_size_1d) <
1507
0
           mi_params->mi_stride);
1508
0
    const int mi_grid_idx =
1509
0
        get_mi_grid_idx(mi_params, mi_row + cur_mi_row, mi_col);
1510
0
    const int alloc_mi_idx =
1511
0
        get_alloc_mi_idx(mi_params, mi_row + cur_mi_row, mi_col);
1512
0
    memset(&mi_params->mi_grid_base[mi_grid_idx], 0,
1513
0
           sb_size_mi * sizeof(*mi_params->mi_grid_base));
1514
0
    memset(&mi_params->tx_type_map[mi_grid_idx], 0,
1515
0
           sb_size_mi * sizeof(*mi_params->tx_type_map));
1516
0
    if (cur_mi_row % mi_alloc_size_1d == 0) {
1517
0
      memset(&mi_params->mi_alloc[alloc_mi_idx], 0,
1518
0
             sb_size_alloc_mi * sizeof(*mi_params->mi_alloc));
1519
0
    }
1520
0
  }
1521
0
}
1522
1523
void av1_backup_sb_state(SB_FIRST_PASS_STATS *sb_fp_stats, const AV1_COMP *cpi,
1524
                         ThreadData *td, const TileDataEnc *tile_data,
1525
0
                         int mi_row, int mi_col) {
1526
0
  MACROBLOCK *x = &td->mb;
1527
0
  MACROBLOCKD *xd = &x->e_mbd;
1528
0
  const TileInfo *tile_info = &tile_data->tile_info;
1529
1530
0
  const AV1_COMMON *cm = &cpi->common;
1531
0
  const int num_planes = av1_num_planes(cm);
1532
0
  const BLOCK_SIZE sb_size = cm->seq_params->sb_size;
1533
1534
0
  xd->above_txfm_context =
1535
0
      cm->above_contexts.txfm[tile_info->tile_row] + mi_col;
1536
0
  xd->left_txfm_context =
1537
0
      xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
1538
0
  av1_save_context(x, &sb_fp_stats->x_ctx, mi_row, mi_col, sb_size, num_planes);
1539
1540
0
  sb_fp_stats->rd_count = td->rd_counts;
1541
0
  sb_fp_stats->split_count = x->txfm_search_info.txb_split_count;
1542
1543
0
  sb_fp_stats->fc = *td->counts;
1544
1545
  // Don't copy in row_mt case, otherwise run into data race. No behavior change
1546
  // in row_mt case.
1547
0
  if (cpi->sf.inter_sf.inter_mode_rd_model_estimation == 1) {
1548
0
    memcpy(sb_fp_stats->inter_mode_rd_models, tile_data->inter_mode_rd_models,
1549
0
           sizeof(sb_fp_stats->inter_mode_rd_models));
1550
0
  }
1551
1552
0
  memcpy(sb_fp_stats->thresh_freq_fact, x->thresh_freq_fact,
1553
0
         sizeof(sb_fp_stats->thresh_freq_fact));
1554
1555
0
  const int alloc_mi_idx = get_alloc_mi_idx(&cm->mi_params, mi_row, mi_col);
1556
0
  sb_fp_stats->current_qindex =
1557
0
      cm->mi_params.mi_alloc[alloc_mi_idx].current_qindex;
1558
1559
#if CONFIG_INTERNAL_STATS
1560
  memcpy(sb_fp_stats->mode_chosen_counts, cpi->mode_chosen_counts,
1561
         sizeof(sb_fp_stats->mode_chosen_counts));
1562
#endif  // CONFIG_INTERNAL_STATS
1563
0
}
1564
1565
void av1_restore_sb_state(const SB_FIRST_PASS_STATS *sb_fp_stats, AV1_COMP *cpi,
1566
                          ThreadData *td, TileDataEnc *tile_data, int mi_row,
1567
0
                          int mi_col) {
1568
0
  MACROBLOCK *x = &td->mb;
1569
1570
0
  const AV1_COMMON *cm = &cpi->common;
1571
0
  const int num_planes = av1_num_planes(cm);
1572
0
  const BLOCK_SIZE sb_size = cm->seq_params->sb_size;
1573
1574
0
  av1_restore_context(x, &sb_fp_stats->x_ctx, mi_row, mi_col, sb_size,
1575
0
                      num_planes);
1576
1577
0
  td->rd_counts = sb_fp_stats->rd_count;
1578
0
  x->txfm_search_info.txb_split_count = sb_fp_stats->split_count;
1579
1580
0
  *td->counts = sb_fp_stats->fc;
1581
1582
0
  if (cpi->sf.inter_sf.inter_mode_rd_model_estimation == 1) {
1583
0
    memcpy(tile_data->inter_mode_rd_models, sb_fp_stats->inter_mode_rd_models,
1584
0
           sizeof(sb_fp_stats->inter_mode_rd_models));
1585
0
  }
1586
1587
0
  memcpy(x->thresh_freq_fact, sb_fp_stats->thresh_freq_fact,
1588
0
         sizeof(sb_fp_stats->thresh_freq_fact));
1589
1590
0
  const int alloc_mi_idx = get_alloc_mi_idx(&cm->mi_params, mi_row, mi_col);
1591
0
  cm->mi_params.mi_alloc[alloc_mi_idx].current_qindex =
1592
0
      sb_fp_stats->current_qindex;
1593
1594
#if CONFIG_INTERNAL_STATS
1595
  memcpy(cpi->mode_chosen_counts, sb_fp_stats->mode_chosen_counts,
1596
         sizeof(sb_fp_stats->mode_chosen_counts));
1597
#endif  // CONFIG_INTERNAL_STATS
1598
0
}
1599
1600
/*! Checks whether to skip updating the entropy cost based on tile info.
1601
 *
1602
 * This function contains the common code used to skip the cost update of coeff,
1603
 * mode, mv and dv symbols.
1604
 */
1605
static int skip_cost_update(const SequenceHeader *seq_params,
1606
                            const TileInfo *const tile_info, const int mi_row,
1607
                            const int mi_col,
1608
0
                            INTERNAL_COST_UPDATE_TYPE upd_level) {
1609
0
  if (upd_level == INTERNAL_COST_UPD_SB) return 0;
1610
0
  if (upd_level == INTERNAL_COST_UPD_OFF) return 1;
1611
1612
  // upd_level is at most as frequent as each sb_row in a tile.
1613
0
  if (mi_col != tile_info->mi_col_start) return 1;
1614
1615
0
  if (upd_level == INTERNAL_COST_UPD_SBROW_SET) {
1616
0
    const int mib_size_log2 = seq_params->mib_size_log2;
1617
0
    const int sb_row = (mi_row - tile_info->mi_row_start) >> mib_size_log2;
1618
0
    const int sb_size = seq_params->mib_size * MI_SIZE;
1619
0
    const int tile_height =
1620
0
        (tile_info->mi_row_end - tile_info->mi_row_start) * MI_SIZE;
1621
    // When upd_level = INTERNAL_COST_UPD_SBROW_SET, the cost update happens
1622
    // once for 2, 4 sb rows for sb size 128, sb size 64 respectively. However,
1623
    // as the update will not be equally spaced in smaller resolutions making
1624
    // it equally spaced by calculating (mv_num_rows_cost_update) the number of
1625
    // rows after which the cost update should happen.
1626
0
    const int sb_size_update_freq_map[2] = { 2, 4 };
1627
0
    const int update_freq_sb_rows =
1628
0
        sb_size_update_freq_map[sb_size != MAX_SB_SIZE];
1629
0
    const int update_freq_num_rows = sb_size * update_freq_sb_rows;
1630
    // Round-up the division result to next integer.
1631
0
    const int num_updates_per_tile =
1632
0
        (tile_height + update_freq_num_rows - 1) / update_freq_num_rows;
1633
0
    const int num_rows_update_per_tile = num_updates_per_tile * sb_size;
1634
    // Round-up the division result to next integer.
1635
0
    const int num_sb_rows_per_update =
1636
0
        (tile_height + num_rows_update_per_tile - 1) / num_rows_update_per_tile;
1637
0
    if ((sb_row % num_sb_rows_per_update) != 0) return 1;
1638
0
  }
1639
0
  return 0;
1640
0
}
1641
1642
// Checks for skip status of mv cost update.
1643
static int skip_mv_cost_update(AV1_COMP *cpi, const TileInfo *const tile_info,
1644
0
                               const int mi_row, const int mi_col) {
1645
0
  const AV1_COMMON *cm = &cpi->common;
1646
  // For intra frames, mv cdfs are not updated during the encode. Hence, the mv
1647
  // cost calculation is skipped in this case.
1648
0
  if (frame_is_intra_only(cm)) return 1;
1649
1650
0
  return skip_cost_update(cm->seq_params, tile_info, mi_row, mi_col,
1651
0
                          cpi->sf.inter_sf.mv_cost_upd_level);
1652
0
}
1653
1654
// Checks for skip status of dv cost update.
1655
static int skip_dv_cost_update(AV1_COMP *cpi, const TileInfo *const tile_info,
1656
0
                               const int mi_row, const int mi_col) {
1657
0
  const AV1_COMMON *cm = &cpi->common;
1658
  // Intrabc is only applicable to intra frames. So skip if intrabc is not
1659
  // allowed.
1660
0
  if (!av1_allow_intrabc(cm) || is_stat_generation_stage(cpi)) {
1661
0
    return 1;
1662
0
  }
1663
1664
0
  return skip_cost_update(cm->seq_params, tile_info, mi_row, mi_col,
1665
0
                          cpi->sf.intra_sf.dv_cost_upd_level);
1666
0
}
1667
1668
// Update the rate costs of some symbols according to the frequency directed
1669
// by speed features
1670
void av1_set_cost_upd_freq(AV1_COMP *cpi, ThreadData *td,
1671
                           const TileInfo *const tile_info, const int mi_row,
1672
0
                           const int mi_col) {
1673
0
  AV1_COMMON *const cm = &cpi->common;
1674
0
  const int num_planes = av1_num_planes(cm);
1675
0
  MACROBLOCK *const x = &td->mb;
1676
0
  MACROBLOCKD *const xd = &x->e_mbd;
1677
1678
0
  if (cm->features.disable_cdf_update) {
1679
0
    return;
1680
0
  }
1681
1682
0
  switch (cpi->sf.inter_sf.coeff_cost_upd_level) {
1683
0
    case INTERNAL_COST_UPD_OFF:
1684
0
    case INTERNAL_COST_UPD_TILE:  // Tile level
1685
0
      break;
1686
0
    case INTERNAL_COST_UPD_SBROW_SET:  // SB row set level in tile
1687
0
    case INTERNAL_COST_UPD_SBROW:      // SB row level in tile
1688
0
    case INTERNAL_COST_UPD_SB:         // SB level
1689
0
      if (skip_cost_update(cm->seq_params, tile_info, mi_row, mi_col,
1690
0
                           cpi->sf.inter_sf.coeff_cost_upd_level))
1691
0
        break;
1692
0
      av1_fill_coeff_costs(&x->coeff_costs, xd->tile_ctx, num_planes);
1693
0
      break;
1694
0
    default: assert(0);
1695
0
  }
1696
1697
0
  switch (cpi->sf.inter_sf.mode_cost_upd_level) {
1698
0
    case INTERNAL_COST_UPD_OFF:
1699
0
    case INTERNAL_COST_UPD_TILE:  // Tile level
1700
0
      break;
1701
0
    case INTERNAL_COST_UPD_SBROW_SET:  // SB row set level in tile
1702
0
    case INTERNAL_COST_UPD_SBROW:      // SB row level in tile
1703
0
    case INTERNAL_COST_UPD_SB:         // SB level
1704
0
      if (skip_cost_update(cm->seq_params, tile_info, mi_row, mi_col,
1705
0
                           cpi->sf.inter_sf.mode_cost_upd_level))
1706
0
        break;
1707
0
      av1_fill_mode_rates(cm, &x->mode_costs, xd->tile_ctx);
1708
0
      break;
1709
0
    default: assert(0);
1710
0
  }
1711
1712
0
  switch (cpi->sf.inter_sf.mv_cost_upd_level) {
1713
0
    case INTERNAL_COST_UPD_OFF:
1714
0
    case INTERNAL_COST_UPD_TILE:  // Tile level
1715
0
      break;
1716
0
    case INTERNAL_COST_UPD_SBROW_SET:  // SB row set level in tile
1717
0
    case INTERNAL_COST_UPD_SBROW:      // SB row level in tile
1718
0
    case INTERNAL_COST_UPD_SB:         // SB level
1719
      // Checks for skip status of mv cost update.
1720
0
      if (skip_mv_cost_update(cpi, tile_info, mi_row, mi_col)) break;
1721
0
      av1_fill_mv_costs(&xd->tile_ctx->nmvc,
1722
0
                        cm->features.cur_frame_force_integer_mv,
1723
0
                        cm->features.allow_high_precision_mv, x->mv_costs);
1724
0
      break;
1725
0
    default: assert(0);
1726
0
  }
1727
1728
0
  switch (cpi->sf.intra_sf.dv_cost_upd_level) {
1729
0
    case INTERNAL_COST_UPD_OFF:
1730
0
    case INTERNAL_COST_UPD_TILE:  // Tile level
1731
0
      break;
1732
0
    case INTERNAL_COST_UPD_SBROW_SET:  // SB row set level in tile
1733
0
    case INTERNAL_COST_UPD_SBROW:      // SB row level in tile
1734
0
    case INTERNAL_COST_UPD_SB:         // SB level
1735
      // Checks for skip status of dv cost update.
1736
0
      if (skip_dv_cost_update(cpi, tile_info, mi_row, mi_col)) break;
1737
0
      av1_fill_dv_costs(&xd->tile_ctx->ndvc, x->dv_costs);
1738
0
      break;
1739
0
    default: assert(0);
1740
0
  }
1741
0
}
1742
1743
0
void av1_dealloc_src_diff_buf(struct macroblock *mb, int num_planes) {
1744
0
  for (int plane = 0; plane < num_planes; ++plane) {
1745
0
    aom_free(mb->plane[plane].src_diff);
1746
0
    mb->plane[plane].src_diff = NULL;
1747
0
  }
1748
0
}
1749
1750
0
void av1_alloc_src_diff_buf(const struct AV1Common *cm, struct macroblock *mb) {
1751
0
  const int num_planes = av1_num_planes(cm);
1752
0
#ifndef NDEBUG
1753
0
  for (int plane = 0; plane < num_planes; ++plane) {
1754
0
    assert(!mb->plane[plane].src_diff);
1755
0
  }
1756
0
#endif
1757
0
  for (int plane = 0; plane < num_planes; ++plane) {
1758
0
    const int subsampling_xy =
1759
0
        plane ? cm->seq_params->subsampling_x + cm->seq_params->subsampling_y
1760
0
              : 0;
1761
0
    const int sb_size = MAX_SB_SQUARE >> subsampling_xy;
1762
    CHECK_MEM_ERROR(cm, mb->plane[plane].src_diff,
1763
0
                    (int16_t *)aom_memalign(
1764
0
                        32, sizeof(*mb->plane[plane].src_diff) * sb_size));
1765
0
  }
1766
0
}