Coverage Report

Created: 2025-06-22 08:04

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