Coverage Report

Created: 2025-10-13 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libavif/ext/aom/av1/encoder/firstpass.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved.
3
 *
4
 * This source code is subject to the terms of the BSD 2 Clause License and
5
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6
 * was not distributed with this source code in the LICENSE file, you can
7
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8
 * Media Patent License 1.0 was not distributed with this source code in the
9
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10
 */
11
12
#include <limits.h>
13
#include <math.h>
14
#include <stdio.h>
15
16
#include "config/aom_dsp_rtcd.h"
17
#include "config/aom_scale_rtcd.h"
18
19
#include "aom_dsp/aom_dsp_common.h"
20
#include "aom_dsp/variance.h"
21
#include "aom_mem/aom_mem.h"
22
#include "aom_ports/mem.h"
23
#include "aom_scale/yv12config.h"
24
#include "aom_util/aom_pthread.h"
25
26
#include "av1/common/entropymv.h"
27
#include "av1/common/quant_common.h"
28
#include "av1/common/reconinter.h"  // av1_setup_dst_planes()
29
#include "av1/common/reconintra.h"
30
#include "av1/common/txb_common.h"
31
#include "av1/encoder/aq_variance.h"
32
#include "av1/encoder/av1_quantize.h"
33
#include "av1/encoder/block.h"
34
#include "av1/encoder/dwt.h"
35
#include "av1/encoder/encodeframe.h"
36
#include "av1/encoder/encodeframe_utils.h"
37
#include "av1/encoder/encodemb.h"
38
#include "av1/encoder/encodemv.h"
39
#include "av1/encoder/encoder.h"
40
#include "av1/encoder/encoder_utils.h"
41
#include "av1/encoder/encode_strategy.h"
42
#include "av1/encoder/ethread.h"
43
#include "av1/encoder/extend.h"
44
#include "av1/encoder/firstpass.h"
45
#include "av1/encoder/mcomp.h"
46
#include "av1/encoder/rd.h"
47
#include "av1/encoder/reconinter_enc.h"
48
49
#define OUTPUT_FPF 0
50
51
115k
#define FIRST_PASS_Q 10.0
52
301k
#define INTRA_MODE_PENALTY 1024
53
199k
#define NEW_MV_MODE_PENALTY 32
54
274k
#define DARK_THRESH 64
55
56
21.1k
#define NCOUNT_INTRA_THRESH 8192
57
21.1k
#define NCOUNT_INTRA_FACTOR 3
58
59
274k
#define INVALID_FP_STATS_TO_PREDICT_FLAT_GOP -1
60
61
static inline void output_stats(FIRSTPASS_STATS *stats,
62
0
                                struct aom_codec_pkt_list *pktlist) {
63
0
  struct aom_codec_cx_pkt pkt;
64
0
  pkt.kind = AOM_CODEC_STATS_PKT;
65
0
  pkt.data.twopass_stats.buf = stats;
66
0
  pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
67
0
  if (pktlist != NULL) aom_codec_pkt_list_add(pktlist, &pkt);
68
69
// TEMP debug code
70
#if OUTPUT_FPF
71
  {
72
    FILE *fpfile;
73
    fpfile = fopen("firstpass.stt", "a");
74
75
    fprintf(fpfile,
76
            "%12.0lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf"
77
            "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
78
            "%12.4lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf\n",
79
            stats->frame, stats->weight, stats->intra_error, stats->coded_error,
80
            stats->sr_coded_error, stats->pcnt_inter, stats->pcnt_motion,
81
            stats->pcnt_second_ref, stats->pcnt_neutral, stats->intra_skip_pct,
82
            stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
83
            stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
84
            stats->MVcv, stats->mv_in_out_count, stats->new_mv_count,
85
            stats->count, stats->duration);
86
    fclose(fpfile);
87
  }
88
#endif
89
0
}
90
91
136k
void av1_twopass_zero_stats(FIRSTPASS_STATS *section) {
92
136k
  section->frame = 0.0;
93
136k
  section->weight = 0.0;
94
136k
  section->intra_error = 0.0;
95
136k
  section->frame_avg_wavelet_energy = 0.0;
96
136k
  section->coded_error = 0.0;
97
136k
  section->log_intra_error = 0.0;
98
136k
  section->log_coded_error = 0.0;
99
136k
  section->sr_coded_error = 0.0;
100
136k
  section->pcnt_inter = 0.0;
101
136k
  section->pcnt_motion = 0.0;
102
136k
  section->pcnt_second_ref = 0.0;
103
136k
  section->pcnt_neutral = 0.0;
104
136k
  section->intra_skip_pct = 0.0;
105
136k
  section->inactive_zone_rows = 0.0;
106
136k
  section->inactive_zone_cols = 0.0;
107
136k
  section->MVr = 0.0;
108
136k
  section->mvr_abs = 0.0;
109
136k
  section->MVc = 0.0;
110
136k
  section->mvc_abs = 0.0;
111
136k
  section->MVrv = 0.0;
112
136k
  section->MVcv = 0.0;
113
136k
  section->mv_in_out_count = 0.0;
114
136k
  section->new_mv_count = 0.0;
115
136k
  section->count = 0.0;
116
136k
  section->duration = 1.0;
117
136k
  section->is_flash = 0;
118
136k
  section->noise_var = 0;
119
136k
  section->cor_coeff = 1.0;
120
136k
}
121
122
void av1_accumulate_stats(FIRSTPASS_STATS *section,
123
37.8k
                          const FIRSTPASS_STATS *frame) {
124
37.8k
  section->frame += frame->frame;
125
37.8k
  section->weight += frame->weight;
126
37.8k
  section->intra_error += frame->intra_error;
127
37.8k
  section->log_intra_error += log1p(frame->intra_error);
128
37.8k
  section->log_coded_error += log1p(frame->coded_error);
129
37.8k
  section->frame_avg_wavelet_energy += frame->frame_avg_wavelet_energy;
130
37.8k
  section->coded_error += frame->coded_error;
131
37.8k
  section->sr_coded_error += frame->sr_coded_error;
132
37.8k
  section->pcnt_inter += frame->pcnt_inter;
133
37.8k
  section->pcnt_motion += frame->pcnt_motion;
134
37.8k
  section->pcnt_second_ref += frame->pcnt_second_ref;
135
37.8k
  section->pcnt_neutral += frame->pcnt_neutral;
136
37.8k
  section->intra_skip_pct += frame->intra_skip_pct;
137
37.8k
  section->inactive_zone_rows += frame->inactive_zone_rows;
138
37.8k
  section->inactive_zone_cols += frame->inactive_zone_cols;
139
37.8k
  section->MVr += frame->MVr;
140
37.8k
  section->mvr_abs += frame->mvr_abs;
141
37.8k
  section->MVc += frame->MVc;
142
37.8k
  section->mvc_abs += frame->mvc_abs;
143
37.8k
  section->MVrv += frame->MVrv;
144
37.8k
  section->MVcv += frame->MVcv;
145
37.8k
  section->mv_in_out_count += frame->mv_in_out_count;
146
37.8k
  section->new_mv_count += frame->new_mv_count;
147
37.8k
  section->count += frame->count;
148
37.8k
  section->duration += frame->duration;
149
37.8k
}
150
151
158k
static int get_unit_rows(const BLOCK_SIZE fp_block_size, const int mb_rows) {
152
158k
  const int height_mi_log2 = mi_size_high_log2[fp_block_size];
153
158k
  const int mb_height_mi_log2 = mi_size_high_log2[BLOCK_16X16];
154
158k
  if (height_mi_log2 > mb_height_mi_log2) {
155
0
    return mb_rows >> (height_mi_log2 - mb_height_mi_log2);
156
0
  }
157
158
158k
  return mb_rows << (mb_height_mi_log2 - height_mi_log2);
159
158k
}
160
161
158k
static int get_unit_cols(const BLOCK_SIZE fp_block_size, const int mb_cols) {
162
158k
  const int width_mi_log2 = mi_size_wide_log2[fp_block_size];
163
158k
  const int mb_width_mi_log2 = mi_size_wide_log2[BLOCK_16X16];
164
158k
  if (width_mi_log2 > mb_width_mi_log2) {
165
0
    return mb_cols >> (width_mi_log2 - mb_width_mi_log2);
166
0
  }
167
168
158k
  return mb_cols << (mb_width_mi_log2 - width_mi_log2);
169
158k
}
170
171
// TODO(chengchen): can we simplify it even if resize has to be considered?
172
static int get_num_mbs(const BLOCK_SIZE fp_block_size,
173
37.8k
                       const int num_mbs_16X16) {
174
37.8k
  const int width_mi_log2 = mi_size_wide_log2[fp_block_size];
175
37.8k
  const int height_mi_log2 = mi_size_high_log2[fp_block_size];
176
37.8k
  const int mb_width_mi_log2 = mi_size_wide_log2[BLOCK_16X16];
177
37.8k
  const int mb_height_mi_log2 = mi_size_high_log2[BLOCK_16X16];
178
  // TODO(chengchen): Now this function assumes a square block is used.
179
  // It does not support rectangular block sizes.
180
37.8k
  assert(width_mi_log2 == height_mi_log2);
181
37.8k
  if (width_mi_log2 > mb_width_mi_log2) {
182
0
    return num_mbs_16X16 >> ((width_mi_log2 - mb_width_mi_log2) +
183
0
                             (height_mi_log2 - mb_height_mi_log2));
184
0
  }
185
186
37.8k
  return num_mbs_16X16 << ((mb_width_mi_log2 - width_mi_log2) +
187
37.8k
                           (mb_height_mi_log2 - height_mi_log2));
188
37.8k
}
189
190
0
void av1_end_first_pass(AV1_COMP *cpi) {
191
0
  if (cpi->ppi->twopass.stats_buf_ctx->total_stats && !cpi->ppi->lap_enabled)
192
0
    output_stats(cpi->ppi->twopass.stats_buf_ctx->total_stats,
193
0
                 cpi->ppi->output_pkt_list);
194
0
}
195
196
283k
static aom_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
197
283k
  switch (bsize) {
198
6.46k
    case BLOCK_8X8: return aom_mse8x8;
199
45.5k
    case BLOCK_16X8: return aom_mse16x8;
200
40.3k
    case BLOCK_8X16: return aom_mse8x16;
201
191k
    default: return aom_mse16x16;
202
283k
  }
203
283k
}
204
205
static unsigned int get_prediction_error(BLOCK_SIZE bsize,
206
                                         const struct buf_2d *src,
207
283k
                                         const struct buf_2d *ref) {
208
283k
  unsigned int sse;
209
283k
  const aom_variance_fn_t fn = get_block_variance_fn(bsize);
210
283k
  fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
211
283k
  return sse;
212
283k
}
213
214
#if CONFIG_AV1_HIGHBITDEPTH
215
static aom_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
216
53.7k
                                                      int bd) {
217
53.7k
  switch (bd) {
218
0
    default:
219
0
      switch (bsize) {
220
0
        case BLOCK_8X8: return aom_highbd_8_mse8x8;
221
0
        case BLOCK_16X8: return aom_highbd_8_mse16x8;
222
0
        case BLOCK_8X16: return aom_highbd_8_mse8x16;
223
0
        default: return aom_highbd_8_mse16x16;
224
0
      }
225
28.0k
    case 10:
226
28.0k
      switch (bsize) {
227
1.93k
        case BLOCK_8X8: return aom_highbd_10_mse8x8;
228
5.53k
        case BLOCK_16X8: return aom_highbd_10_mse16x8;
229
6.45k
        case BLOCK_8X16: return aom_highbd_10_mse8x16;
230
14.2k
        default: return aom_highbd_10_mse16x16;
231
28.0k
      }
232
25.7k
    case 12:
233
25.7k
      switch (bsize) {
234
1.61k
        case BLOCK_8X8: return aom_highbd_12_mse8x8;
235
5.09k
        case BLOCK_16X8: return aom_highbd_12_mse16x8;
236
5.95k
        case BLOCK_8X16: return aom_highbd_12_mse8x16;
237
13.1k
        default: return aom_highbd_12_mse16x16;
238
25.7k
      }
239
53.7k
  }
240
53.7k
}
241
242
static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
243
                                                const struct buf_2d *src,
244
                                                const struct buf_2d *ref,
245
53.7k
                                                int bd) {
246
53.7k
  unsigned int sse;
247
53.7k
  const aom_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
248
53.7k
  fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
249
53.7k
  return sse;
250
53.7k
}
251
#endif  // CONFIG_AV1_HIGHBITDEPTH
252
253
// Refine the motion search range according to the frame dimension
254
// for first pass test.
255
199k
static int get_search_range(int width, int height) {
256
199k
  int sr = 0;
257
199k
  const int dim = AOMMIN(width, height);
258
259
1.24M
  while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
260
199k
  return sr;
261
199k
}
262
263
static inline const search_site_config *av1_get_first_pass_search_site_config(
264
199k
    const AV1_COMP *cpi, MACROBLOCK *x, SEARCH_METHODS search_method) {
265
199k
  const int ref_stride = x->e_mbd.plane[0].pre[0].stride;
266
267
  // For AVIF applications, even the source frames can have changing resolution,
268
  // so we need to manually check for the strides :(
269
  // AV1_COMP::mv_search_params.search_site_config is a compressor level cache
270
  // that's shared by multiple threads. In most cases where all frames have the
271
  // same resolution, the cache contains the search site config that we need.
272
199k
  const MotionVectorSearchParams *mv_search_params = &cpi->mv_search_params;
273
199k
  if (ref_stride == mv_search_params->search_site_cfg[SS_CFG_FPF]->stride) {
274
199k
    return mv_search_params->search_site_cfg[SS_CFG_FPF];
275
199k
  }
276
277
  // If the cache does not contain the correct stride, then we will need to rely
278
  // on the thread level config MACROBLOCK::search_site_cfg_buf. If even the
279
  // thread level config doesn't match, then we need to update it.
280
18.4E
  search_method = search_method_lookup[search_method];
281
18.4E
  assert(search_method_lookup[search_method] == search_method &&
282
18.4E
         "The search_method_lookup table should be idempotent.");
283
18.4E
  if (ref_stride != x->search_site_cfg_buf[search_method].stride) {
284
0
    av1_refresh_search_site_config(x->search_site_cfg_buf, search_method,
285
0
                                   ref_stride);
286
0
  }
287
288
18.4E
  return x->search_site_cfg_buf;
289
199k
}
290
291
static inline void first_pass_motion_search(AV1_COMP *cpi, MACROBLOCK *x,
292
                                            const MV *ref_mv,
293
                                            FULLPEL_MV *best_mv,
294
199k
                                            int *best_motion_err) {
295
199k
  AV1_COMMON *const cm = &cpi->common;
296
199k
  MACROBLOCKD *const xd = &x->e_mbd;
297
199k
  FULLPEL_MV start_mv = get_fullmv_from_mv(ref_mv);
298
199k
  int tmp_err;
299
199k
  const BLOCK_SIZE bsize = xd->mi[0]->bsize;
300
199k
  const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
301
199k
  const int sr = get_search_range(cm->width, cm->height);
302
199k
  const int step_param = cpi->sf.fp_sf.reduce_mv_step_param + sr;
303
304
199k
  const search_site_config *first_pass_search_sites =
305
199k
      av1_get_first_pass_search_site_config(cpi, x, NSTEP);
306
199k
  const int fine_search_interval =
307
199k
      cpi->is_screen_content_type && cm->features.allow_intrabc;
308
199k
  FULLPEL_MOTION_SEARCH_PARAMS ms_params;
309
199k
  av1_make_default_fullpel_ms_params(&ms_params, cpi, x, bsize, ref_mv,
310
199k
                                     start_mv, first_pass_search_sites, NSTEP,
311
199k
                                     fine_search_interval);
312
313
199k
  FULLPEL_MV this_best_mv;
314
199k
  FULLPEL_MV_STATS best_mv_stats;
315
199k
  tmp_err = av1_full_pixel_search(start_mv, &ms_params, step_param, NULL,
316
199k
                                  &this_best_mv, &best_mv_stats, NULL);
317
318
199k
  if (tmp_err < INT_MAX) {
319
198k
    aom_variance_fn_ptr_t v_fn_ptr = cpi->ppi->fn_ptr[bsize];
320
198k
    const MSBuffers *ms_buffers = &ms_params.ms_buffers;
321
198k
    tmp_err = av1_get_mvpred_sse(&ms_params.mv_cost_params, this_best_mv,
322
198k
                                 &v_fn_ptr, ms_buffers->src, ms_buffers->ref) +
323
198k
              new_mv_mode_penalty;
324
198k
  }
325
326
199k
  if (tmp_err < *best_motion_err) {
327
137k
    *best_motion_err = tmp_err;
328
137k
    *best_mv = this_best_mv;
329
137k
  }
330
199k
}
331
332
static BLOCK_SIZE get_bsize(const CommonModeInfoParams *const mi_params,
333
                            const BLOCK_SIZE fp_block_size, const int unit_row,
334
412k
                            const int unit_col) {
335
412k
  const int unit_width = mi_size_wide[fp_block_size];
336
412k
  const int unit_height = mi_size_high[fp_block_size];
337
412k
  const int is_half_width =
338
412k
      unit_width * unit_col + unit_width / 2 >= mi_params->mi_cols;
339
412k
  const int is_half_height =
340
412k
      unit_height * unit_row + unit_height / 2 >= mi_params->mi_rows;
341
412k
  const int max_dimension =
342
412k
      AOMMAX(block_size_wide[fp_block_size], block_size_high[fp_block_size]);
343
412k
  int square_block_size = 0;
344
  // 4X4, 8X8, 16X16, 32X32, 64X64, 128X128
345
412k
  switch (max_dimension) {
346
0
    case 4: square_block_size = 0; break;
347
0
    case 8: square_block_size = 1; break;
348
412k
    case 16: square_block_size = 2; break;
349
0
    case 32: square_block_size = 3; break;
350
0
    case 64: square_block_size = 4; break;
351
0
    case 128: square_block_size = 5; break;
352
0
    default: assert(0 && "First pass block size is not supported!"); break;
353
412k
  }
354
412k
  if (is_half_width && is_half_height) {
355
12.5k
    return subsize_lookup[PARTITION_SPLIT][square_block_size];
356
399k
  } else if (is_half_width) {
357
64.6k
    return subsize_lookup[PARTITION_VERT][square_block_size];
358
334k
  } else if (is_half_height) {
359
70.5k
    return subsize_lookup[PARTITION_HORZ][square_block_size];
360
264k
  } else {
361
264k
    return fp_block_size;
362
264k
  }
363
412k
}
364
365
115k
static int find_fp_qindex(aom_bit_depth_t bit_depth) {
366
115k
  return av1_find_qindex(FIRST_PASS_Q, bit_depth, 0, QINDEX_RANGE - 1);
367
115k
}
368
369
static double raw_motion_error_stdev(int *raw_motion_err_list,
370
18.9k
                                     int raw_motion_err_counts) {
371
18.9k
  int64_t sum_raw_err = 0;
372
18.9k
  double raw_err_avg = 0;
373
18.9k
  double raw_err_stdev = 0;
374
18.9k
  if (raw_motion_err_counts == 0) return 0;
375
376
9.32k
  int i;
377
150k
  for (i = 0; i < raw_motion_err_counts; i++) {
378
141k
    sum_raw_err += raw_motion_err_list[i];
379
141k
  }
380
9.32k
  raw_err_avg = (double)sum_raw_err / raw_motion_err_counts;
381
150k
  for (i = 0; i < raw_motion_err_counts; i++) {
382
141k
    raw_err_stdev += (raw_motion_err_list[i] - raw_err_avg) *
383
141k
                     (raw_motion_err_list[i] - raw_err_avg);
384
141k
  }
385
  // Calculate the standard deviation for the motion error of all the inter
386
  // blocks of the 0,0 motion using the last source
387
  // frame as the reference.
388
9.32k
  raw_err_stdev = sqrt(raw_err_stdev / raw_motion_err_counts);
389
9.32k
  return raw_err_stdev;
390
18.9k
}
391
392
270k
static inline int calc_wavelet_energy(const AV1EncoderConfig *oxcf) {
393
270k
  return oxcf->q_cfg.deltaq_mode == DELTA_Q_PERCEPTUAL;
394
270k
}
395
typedef struct intra_pred_block_pass1_args {
396
  const SequenceHeader *seq_params;
397
  MACROBLOCK *x;
398
} intra_pred_block_pass1_args;
399
400
static inline void copy_rect(uint8_t *dst, int dstride, const uint8_t *src,
401
270k
                             int sstride, int width, int height, int use_hbd) {
402
270k
#if CONFIG_AV1_HIGHBITDEPTH
403
270k
  if (use_hbd) {
404
47.5k
    aom_highbd_convolve_copy(CONVERT_TO_SHORTPTR(src), sstride,
405
47.5k
                             CONVERT_TO_SHORTPTR(dst), dstride, width, height);
406
223k
  } else {
407
223k
    aom_convolve_copy(src, sstride, dst, dstride, width, height);
408
223k
  }
409
#else
410
  (void)use_hbd;
411
  aom_convolve_copy(src, sstride, dst, dstride, width, height);
412
#endif
413
270k
}
414
415
static void first_pass_intra_pred_and_calc_diff(int plane, int block,
416
                                                int blk_row, int blk_col,
417
                                                BLOCK_SIZE plane_bsize,
418
3.05M
                                                TX_SIZE tx_size, void *arg) {
419
3.05M
  (void)block;
420
3.05M
  struct intra_pred_block_pass1_args *const args = arg;
421
3.05M
  MACROBLOCK *const x = args->x;
422
3.05M
  MACROBLOCKD *const xd = &x->e_mbd;
423
3.05M
  MACROBLOCKD_PLANE *const pd = &xd->plane[plane];
424
3.05M
  MACROBLOCK_PLANE *const p = &x->plane[plane];
425
3.05M
  const int dst_stride = pd->dst.stride;
426
3.05M
  uint8_t *dst = &pd->dst.buf[(blk_row * dst_stride + blk_col) << MI_SIZE_LOG2];
427
3.05M
  const MB_MODE_INFO *const mbmi = xd->mi[0];
428
3.05M
  const SequenceHeader *seq_params = args->seq_params;
429
3.05M
  const int src_stride = p->src.stride;
430
3.05M
  uint8_t *src = &p->src.buf[(blk_row * src_stride + blk_col) << MI_SIZE_LOG2];
431
432
3.05M
  av1_predict_intra_block(
433
3.05M
      xd, seq_params->sb_size, seq_params->enable_intra_edge_filter, pd->width,
434
3.05M
      pd->height, tx_size, mbmi->mode, 0, 0, FILTER_INTRA_MODES, src,
435
3.05M
      src_stride, dst, dst_stride, blk_col, blk_row, plane);
436
437
3.05M
  av1_subtract_txb(x, plane, plane_bsize, blk_col, blk_row, tx_size);
438
3.05M
}
439
440
static void first_pass_predict_intra_block_for_luma_plane(
441
271k
    const SequenceHeader *seq_params, MACROBLOCK *x, BLOCK_SIZE bsize) {
442
271k
  assert(bsize < BLOCK_SIZES_ALL);
443
271k
  const MACROBLOCKD *const xd = &x->e_mbd;
444
271k
  const int plane = AOM_PLANE_Y;
445
271k
  const MACROBLOCKD_PLANE *const pd = &xd->plane[plane];
446
271k
  const int ss_x = pd->subsampling_x;
447
271k
  const int ss_y = pd->subsampling_y;
448
271k
  const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, ss_x, ss_y);
449
271k
  const int dst_stride = pd->dst.stride;
450
271k
  uint8_t *dst = pd->dst.buf;
451
271k
  const MACROBLOCK_PLANE *const p = &x->plane[plane];
452
271k
  const int src_stride = p->src.stride;
453
271k
  const uint8_t *src = p->src.buf;
454
455
271k
  intra_pred_block_pass1_args args = { seq_params, x };
456
271k
  av1_foreach_transformed_block_in_plane(
457
271k
      xd, plane_bsize, plane, first_pass_intra_pred_and_calc_diff, &args);
458
459
  // copy source data to recon buffer, as the recon buffer will be used as a
460
  // reference frame subsequently.
461
271k
  copy_rect(dst, dst_stride, src, src_stride, block_size_wide[bsize],
462
271k
            block_size_high[bsize], seq_params->use_highbitdepth);
463
271k
}
464
465
274k
#define UL_INTRA_THRESH 50
466
1.12M
#define INVALID_ROW -1
467
// Computes and returns the intra pred error of a block.
468
// intra pred error: sum of squared error of the intra predicted residual.
469
// Inputs:
470
//   cpi: the encoder setting. Only a few params in it will be used.
471
//   this_frame: the current frame buffer.
472
//   tile: tile information (not used in first pass, already init to zero)
473
//   unit_row: row index in the unit of first pass block size.
474
//   unit_col: column index in the unit of first pass block size.
475
//   y_offset: the offset of y frame buffer, indicating the starting point of
476
//             the current block.
477
//   uv_offset: the offset of u and v frame buffer, indicating the starting
478
//              point of the current block.
479
//   fp_block_size: first pass block size.
480
//   qindex: quantization step size to encode the frame.
481
//   stats: frame encoding stats.
482
// Modifies:
483
//   stats->intra_skip_count
484
//   stats->image_data_start_row
485
//   stats->intra_factor
486
//   stats->brightness_factor
487
//   stats->intra_error
488
//   stats->frame_avg_wavelet_energy
489
// Returns:
490
//   this_intra_error.
491
static int firstpass_intra_prediction(
492
    AV1_COMP *cpi, ThreadData *td, YV12_BUFFER_CONFIG *const this_frame,
493
    const TileInfo *const tile, const int unit_row, const int unit_col,
494
    const int y_offset, const int uv_offset, const BLOCK_SIZE fp_block_size,
495
274k
    const int qindex, FRAME_STATS *const stats) {
496
274k
  const AV1_COMMON *const cm = &cpi->common;
497
274k
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
498
274k
  const SequenceHeader *const seq_params = cm->seq_params;
499
274k
  MACROBLOCK *const x = &td->mb;
500
274k
  MACROBLOCKD *const xd = &x->e_mbd;
501
274k
  const int unit_scale = mi_size_wide[fp_block_size];
502
274k
  const int num_planes = av1_num_planes(cm);
503
274k
  const BLOCK_SIZE bsize =
504
274k
      get_bsize(mi_params, fp_block_size, unit_row, unit_col);
505
506
274k
  set_mi_offsets(mi_params, xd, unit_row * unit_scale, unit_col * unit_scale);
507
274k
  xd->plane[0].dst.buf = this_frame->y_buffer + y_offset;
508
274k
  if (num_planes > 1) {
509
155k
    xd->plane[1].dst.buf = this_frame->u_buffer + uv_offset;
510
155k
    xd->plane[2].dst.buf = this_frame->v_buffer + uv_offset;
511
155k
  }
512
274k
  xd->left_available = (unit_col != 0);
513
274k
  xd->mi[0]->bsize = bsize;
514
274k
  xd->mi[0]->ref_frame[0] = INTRA_FRAME;
515
274k
  set_mi_row_col(xd, tile, unit_row * unit_scale, mi_size_high[bsize],
516
274k
                 unit_col * unit_scale, mi_size_wide[bsize], mi_params->mi_rows,
517
274k
                 mi_params->mi_cols);
518
274k
  set_plane_n4(xd, mi_size_wide[bsize], mi_size_high[bsize], num_planes);
519
274k
  xd->mi[0]->segment_id = 0;
520
274k
  xd->lossless[xd->mi[0]->segment_id] = (qindex == 0);
521
274k
  xd->mi[0]->mode = DC_PRED;
522
274k
  xd->mi[0]->tx_size = TX_4X4;
523
524
274k
  if (cpi->sf.fp_sf.disable_recon)
525
271k
    first_pass_predict_intra_block_for_luma_plane(seq_params, x, bsize);
526
2.55k
  else
527
2.55k
    av1_encode_intra_block_plane(cpi, x, bsize, 0, DRY_RUN_NORMAL, 0);
528
274k
  int this_intra_error = aom_get_mb_ss(x->plane[0].src_diff);
529
274k
  if (seq_params->use_highbitdepth) {
530
47.7k
    switch (seq_params->bit_depth) {
531
0
      case AOM_BITS_8: break;
532
23.6k
      case AOM_BITS_10: this_intra_error >>= 4; break;
533
24.0k
      case AOM_BITS_12: this_intra_error >>= 8; break;
534
0
      default:
535
0
        assert(0 &&
536
0
               "seq_params->bit_depth should be AOM_BITS_8, "
537
0
               "AOM_BITS_10 or AOM_BITS_12");
538
0
        return -1;
539
47.7k
    }
540
47.7k
  }
541
542
274k
  if (this_intra_error < UL_INTRA_THRESH) {
543
68
    ++stats->intra_skip_count;
544
274k
  } else if ((unit_col > 0) && (stats->image_data_start_row == INVALID_ROW)) {
545
200k
    stats->image_data_start_row = unit_row;
546
200k
  }
547
548
274k
  double log_intra = log1p(this_intra_error);
549
274k
  if (log_intra < 10.0) {
550
391
    stats->intra_factor += 1.0 + ((10.0 - log_intra) * 0.05);
551
274k
  } else {
552
274k
    stats->intra_factor += 1.0;
553
274k
  }
554
555
274k
  int level_sample;
556
274k
  if (seq_params->use_highbitdepth) {
557
47.7k
    level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
558
226k
  } else {
559
226k
    level_sample = x->plane[0].src.buf[0];
560
226k
  }
561
562
274k
  if (seq_params->use_highbitdepth) {
563
47.7k
    switch (seq_params->bit_depth) {
564
0
      case AOM_BITS_8: break;
565
23.6k
      case AOM_BITS_10: level_sample >>= 2; break;
566
24.0k
      case AOM_BITS_12: level_sample >>= 4; break;
567
0
      default:
568
0
        assert(0 &&
569
0
               "seq_params->bit_depth should be AOM_BITS_8, "
570
0
               "AOM_BITS_10 or AOM_BITS_12");
571
0
        return -1;
572
47.7k
    }
573
47.7k
  }
574
274k
  if ((level_sample < DARK_THRESH) && (log_intra < 9.0)) {
575
41
    stats->brightness_factor += 1.0 + (0.01 * (DARK_THRESH - level_sample));
576
274k
  } else {
577
274k
    stats->brightness_factor += 1.0;
578
274k
  }
579
580
  // Intrapenalty below deals with situations where the intra and inter
581
  // error scores are very low (e.g. a plain black frame).
582
  // We do not have special cases in first pass for 0,0 and nearest etc so
583
  // all inter modes carry an overhead cost estimate for the mv.
584
  // When the error score is very low this causes us to pick all or lots of
585
  // INTRA modes and throw lots of key frames.
586
  // This penalty adds a cost matching that of a 0,0 mv to the intra case.
587
274k
  this_intra_error += INTRA_MODE_PENALTY;
588
589
  // Accumulate the intra error.
590
274k
  stats->intra_error += (int64_t)this_intra_error;
591
592
  // Stats based on wavelet energy is used in the following cases :
593
  // 1. ML model which predicts if a flat structure (golden-frame only structure
594
  // without ALT-REF and Internal-ARFs) is better. This ML model is enabled in
595
  // constant quality mode under certain conditions.
596
  // 2. Delta qindex mode is set as DELTA_Q_PERCEPTUAL.
597
  // Thus, wavelet energy calculation is enabled for the above cases.
598
274k
  if (calc_wavelet_energy(&cpi->oxcf)) {
599
0
    const int hbd = is_cur_buf_hbd(xd);
600
0
    const int stride = x->plane[0].src.stride;
601
0
    const int num_8x8_rows = block_size_high[fp_block_size] / 8;
602
0
    const int num_8x8_cols = block_size_wide[fp_block_size] / 8;
603
0
    const uint8_t *buf = x->plane[0].src.buf;
604
0
    stats->frame_avg_wavelet_energy += av1_haar_ac_sad_mxn_uint8_input(
605
0
        buf, stride, hbd, num_8x8_rows, num_8x8_cols);
606
274k
  } else {
607
274k
    stats->frame_avg_wavelet_energy = INVALID_FP_STATS_TO_PREDICT_FLAT_GOP;
608
274k
  }
609
610
274k
  return this_intra_error;
611
274k
}
612
613
// Returns the sum of square error between source and reference blocks.
614
static int get_prediction_error_bitdepth(const int is_high_bitdepth,
615
                                         const int bitdepth,
616
                                         const BLOCK_SIZE block_size,
617
                                         const struct buf_2d *src,
618
337k
                                         const struct buf_2d *ref) {
619
337k
  (void)is_high_bitdepth;
620
337k
  (void)bitdepth;
621
337k
#if CONFIG_AV1_HIGHBITDEPTH
622
337k
  if (is_high_bitdepth) {
623
53.7k
    return highbd_get_prediction_error(block_size, src, ref, bitdepth);
624
53.7k
  }
625
283k
#endif  // CONFIG_AV1_HIGHBITDEPTH
626
283k
  return get_prediction_error(block_size, src, ref);
627
337k
}
628
629
// Accumulates motion vector stats.
630
// Modifies member variables of "stats".
631
static void accumulate_mv_stats(const MV best_mv, const FULLPEL_MV mv,
632
                                const int mb_row, const int mb_col,
633
                                const int mb_rows, const int mb_cols,
634
21.1k
                                MV *last_non_zero_mv, FRAME_STATS *stats) {
635
21.1k
  if (is_zero_mv(&best_mv)) return;
636
637
12.9k
  ++stats->mv_count;
638
  // Non-zero vector, was it different from the last non zero vector?
639
12.9k
  if (!is_equal_mv(&best_mv, last_non_zero_mv)) ++stats->new_mv_count;
640
12.9k
  *last_non_zero_mv = best_mv;
641
642
  // Does the row vector point inwards or outwards?
643
12.9k
  if (mb_row < mb_rows / 2) {
644
5.75k
    if (mv.row > 0) {
645
1.41k
      --stats->sum_in_vectors;
646
4.33k
    } else if (mv.row < 0) {
647
3.97k
      ++stats->sum_in_vectors;
648
3.97k
    }
649
7.21k
  } else if (mb_row > mb_rows / 2) {
650
5.87k
    if (mv.row > 0) {
651
3.97k
      ++stats->sum_in_vectors;
652
3.97k
    } else if (mv.row < 0) {
653
1.08k
      --stats->sum_in_vectors;
654
1.08k
    }
655
5.87k
  }
656
657
  // Does the col vector point inwards or outwards?
658
12.9k
  if (mb_col < mb_cols / 2) {
659
3.15k
    if (mv.col > 0) {
660
329
      --stats->sum_in_vectors;
661
2.82k
    } else if (mv.col < 0) {
662
2.79k
      ++stats->sum_in_vectors;
663
2.79k
    }
664
9.81k
  } else if (mb_col > mb_cols / 2) {
665
7.93k
    if (mv.col > 0) {
666
4.42k
      ++stats->sum_in_vectors;
667
4.42k
    } else if (mv.col < 0) {
668
1.70k
      --stats->sum_in_vectors;
669
1.70k
    }
670
7.93k
  }
671
12.9k
}
672
673
// Computes and returns the inter prediction error from the last frame.
674
// Computes inter prediction errors from the golden and alt ref frams and
675
// Updates stats accordingly.
676
// Inputs:
677
//   cpi: the encoder setting. Only a few params in it will be used.
678
//   last_frame: the frame buffer of the last frame.
679
//   golden_frame: the frame buffer of the golden frame.
680
//   unit_row: row index in the unit of first pass block size.
681
//   unit_col: column index in the unit of first pass block size.
682
//   recon_yoffset: the y offset of the reconstructed  frame buffer,
683
//                  indicating the starting point of the current block.
684
//   recont_uvoffset: the u/v offset of the reconstructed frame buffer,
685
//                    indicating the starting point of the current block.
686
//   src_yoffset: the y offset of the source frame buffer.
687
//   fp_block_size: first pass block size.
688
//   this_intra_error: the intra prediction error of this block.
689
//   raw_motion_err_counts: the count of raw motion vectors.
690
//   raw_motion_err_list: the array that records the raw motion error.
691
//   ref_mv: the reference used to start the motion search
692
//   best_mv: the best mv found
693
//   last_non_zero_mv: the last non zero mv found in this tile row.
694
//   stats: frame encoding stats.
695
//  Modifies:
696
//    raw_motion_err_list
697
//    best_ref_mv
698
//    last_mv
699
//    stats: many member params in it.
700
//  Returns:
701
//    this_inter_error
702
static int firstpass_inter_prediction(
703
    AV1_COMP *cpi, ThreadData *td, const YV12_BUFFER_CONFIG *const last_frame,
704
    const YV12_BUFFER_CONFIG *const golden_frame, const int unit_row,
705
    const int unit_col, const int recon_yoffset, const int recon_uvoffset,
706
    const int src_yoffset, const BLOCK_SIZE fp_block_size,
707
    const int this_intra_error, const int raw_motion_err_counts,
708
    int *raw_motion_err_list, const MV ref_mv, MV *best_mv,
709
140k
    MV *last_non_zero_mv, FRAME_STATS *stats) {
710
140k
  int this_inter_error = this_intra_error;
711
140k
  AV1_COMMON *const cm = &cpi->common;
712
140k
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
713
140k
  CurrentFrame *const current_frame = &cm->current_frame;
714
140k
  MACROBLOCK *const x = &td->mb;
715
140k
  MACROBLOCKD *const xd = &x->e_mbd;
716
140k
  const int is_high_bitdepth = is_cur_buf_hbd(xd);
717
140k
  const int bitdepth = xd->bd;
718
140k
  const int unit_scale = mi_size_wide[fp_block_size];
719
140k
  const BLOCK_SIZE bsize =
720
140k
      get_bsize(mi_params, fp_block_size, unit_row, unit_col);
721
140k
  const int fp_block_size_height = block_size_wide[fp_block_size];
722
140k
  const int unit_width = mi_size_wide[fp_block_size];
723
140k
  const int unit_rows = get_unit_rows(fp_block_size, mi_params->mb_rows);
724
140k
  const int unit_cols = get_unit_cols(fp_block_size, mi_params->mb_cols);
725
  // Assume 0,0 motion with no mv overhead.
726
140k
  FULLPEL_MV mv = kZeroFullMv;
727
140k
  xd->plane[0].pre[0].buf = last_frame->y_buffer + recon_yoffset;
728
  // Set up limit values for motion vectors to prevent them extending
729
  // outside the UMV borders.
730
140k
  av1_set_mv_col_limits(mi_params, &x->mv_limits, unit_col * unit_width,
731
140k
                        fp_block_size_height >> MI_SIZE_LOG2,
732
140k
                        cpi->oxcf.border_in_pixels);
733
734
140k
  int motion_error =
735
140k
      get_prediction_error_bitdepth(is_high_bitdepth, bitdepth, bsize,
736
140k
                                    &x->plane[0].src, &xd->plane[0].pre[0]);
737
738
  // Compute the motion error of the 0,0 motion using the last source
739
  // frame as the reference. Skip the further motion search on
740
  // reconstructed frame if this error is small.
741
  // TODO(chiyotsai): The unscaled last source might be different dimension
742
  // as the current source. See BUG=aomedia:3413
743
140k
  struct buf_2d unscaled_last_source_buf_2d;
744
140k
  unscaled_last_source_buf_2d.buf =
745
140k
      cpi->unscaled_last_source->y_buffer + src_yoffset;
746
140k
  unscaled_last_source_buf_2d.stride = cpi->unscaled_last_source->y_stride;
747
140k
  const int raw_motion_error = get_prediction_error_bitdepth(
748
140k
      is_high_bitdepth, bitdepth, bsize, &x->plane[0].src,
749
140k
      &unscaled_last_source_buf_2d);
750
140k
  raw_motion_err_list[raw_motion_err_counts] = raw_motion_error;
751
140k
  const FIRST_PASS_SPEED_FEATURES *const fp_sf = &cpi->sf.fp_sf;
752
753
140k
  if (raw_motion_error > fp_sf->skip_motion_search_threshold) {
754
    // Test last reference frame using the previous best mv as the
755
    // starting point (best reference) for the search.
756
139k
    first_pass_motion_search(cpi, x, &ref_mv, &mv, &motion_error);
757
758
    // If the current best reference mv is not centered on 0,0 then do a
759
    // 0,0 based search as well.
760
139k
    if ((fp_sf->skip_zeromv_motion_search == 0) && !is_zero_mv(&ref_mv)) {
761
0
      FULLPEL_MV tmp_mv = kZeroFullMv;
762
0
      int tmp_err = INT_MAX;
763
0
      first_pass_motion_search(cpi, x, &kZeroMv, &tmp_mv, &tmp_err);
764
765
0
      if (tmp_err < motion_error) {
766
0
        motion_error = tmp_err;
767
0
        mv = tmp_mv;
768
0
      }
769
0
    }
770
139k
  }
771
772
  // Motion search in 2nd reference frame.
773
140k
  int gf_motion_error = motion_error;
774
140k
  if ((current_frame->frame_number > 1) && golden_frame != NULL) {
775
60.7k
    FULLPEL_MV tmp_mv = kZeroFullMv;
776
    // Assume 0,0 motion with no mv overhead.
777
60.7k
    av1_setup_pre_planes(xd, 0, golden_frame, 0, 0, NULL, 1);
778
60.7k
    xd->plane[0].pre[0].buf += recon_yoffset;
779
60.7k
    gf_motion_error =
780
60.7k
        get_prediction_error_bitdepth(is_high_bitdepth, bitdepth, bsize,
781
60.7k
                                      &x->plane[0].src, &xd->plane[0].pre[0]);
782
60.7k
    first_pass_motion_search(cpi, x, &kZeroMv, &tmp_mv, &gf_motion_error);
783
60.7k
  }
784
140k
  if (gf_motion_error < motion_error && gf_motion_error < this_intra_error) {
785
5.86k
    ++stats->second_ref_count;
786
5.86k
  }
787
  // In accumulating a score for the 2nd reference frame take the
788
  // best of the motion predicted score and the intra coded error
789
  // (just as will be done for) accumulation of "coded_error" for
790
  // the last frame.
791
140k
  if ((current_frame->frame_number > 1) && golden_frame != NULL) {
792
60.8k
    stats->sr_coded_error += AOMMIN(gf_motion_error, this_intra_error);
793
79.3k
  } else {
794
    // TODO(chengchen): I believe logically this should also be changed to
795
    // stats->sr_coded_error += AOMMIN(gf_motion_error, this_intra_error).
796
79.3k
    stats->sr_coded_error += motion_error;
797
79.3k
  }
798
799
  // Reset to last frame as reference buffer.
800
140k
  xd->plane[0].pre[0].buf = last_frame->y_buffer + recon_yoffset;
801
140k
  if (av1_num_planes(&cpi->common) > 1) {
802
79.3k
    xd->plane[1].pre[0].buf = last_frame->u_buffer + recon_uvoffset;
803
79.3k
    xd->plane[2].pre[0].buf = last_frame->v_buffer + recon_uvoffset;
804
79.3k
  }
805
806
  // Start by assuming that intra mode is best.
807
140k
  *best_mv = kZeroMv;
808
809
140k
  if (motion_error <= this_intra_error) {
810
    // Keep a count of cases where the inter and intra were very close
811
    // and very low. This helps with scene cut detection for example in
812
    // cropped clips with black bars at the sides or top and bottom.
813
21.1k
    if (((this_intra_error - INTRA_MODE_PENALTY) * 9 <= motion_error * 10) &&
814
5.98k
        (this_intra_error < (2 * INTRA_MODE_PENALTY))) {
815
9
      stats->neutral_count += 1.0;
816
      // Also track cases where the intra is not much worse than the inter
817
      // and use this in limiting the GF/arf group length.
818
21.1k
    } else if ((this_intra_error > NCOUNT_INTRA_THRESH) &&
819
21.1k
               (this_intra_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
820
20.3k
      stats->neutral_count +=
821
20.3k
          (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_intra_error);
822
20.3k
    }
823
824
21.1k
    *best_mv = get_mv_from_fullmv(&mv);
825
21.1k
    this_inter_error = motion_error;
826
21.1k
    xd->mi[0]->mode = NEWMV;
827
21.1k
    xd->mi[0]->mv[0].as_mv = *best_mv;
828
21.1k
    xd->mi[0]->tx_size = TX_4X4;
829
21.1k
    xd->mi[0]->ref_frame[0] = LAST_FRAME;
830
21.1k
    xd->mi[0]->ref_frame[1] = NONE_FRAME;
831
832
21.1k
    if (fp_sf->disable_recon == 0) {
833
0
      av1_enc_build_inter_predictor(cm, xd, unit_row * unit_scale,
834
0
                                    unit_col * unit_scale, NULL, bsize,
835
0
                                    AOM_PLANE_Y, AOM_PLANE_Y);
836
0
      av1_encode_sby_pass1(cpi, x, bsize);
837
0
    }
838
21.1k
    stats->sum_mvr += best_mv->row;
839
21.1k
    stats->sum_mvr_abs += abs(best_mv->row);
840
21.1k
    stats->sum_mvc += best_mv->col;
841
21.1k
    stats->sum_mvc_abs += abs(best_mv->col);
842
21.1k
    stats->sum_mvrs += best_mv->row * best_mv->row;
843
21.1k
    stats->sum_mvcs += best_mv->col * best_mv->col;
844
21.1k
    ++stats->inter_count;
845
846
21.1k
    accumulate_mv_stats(*best_mv, mv, unit_row, unit_col, unit_rows, unit_cols,
847
21.1k
                        last_non_zero_mv, stats);
848
21.1k
  }
849
850
140k
  return this_inter_error;
851
140k
}
852
853
// Normalize the first pass stats.
854
// Error / counters are normalized to each MB.
855
// MVs are normalized to the width/height of the frame.
856
static void normalize_firstpass_stats(FIRSTPASS_STATS *fps,
857
                                      double num_mbs_16x16, double f_w,
858
18.9k
                                      double f_h) {
859
18.9k
  fps->coded_error /= num_mbs_16x16;
860
18.9k
  fps->sr_coded_error /= num_mbs_16x16;
861
18.9k
  fps->intra_error /= num_mbs_16x16;
862
18.9k
  fps->frame_avg_wavelet_energy /= num_mbs_16x16;
863
18.9k
  fps->log_coded_error = log1p(fps->coded_error);
864
18.9k
  fps->log_intra_error = log1p(fps->intra_error);
865
18.9k
  fps->MVr /= f_h;
866
18.9k
  fps->mvr_abs /= f_h;
867
18.9k
  fps->MVc /= f_w;
868
18.9k
  fps->mvc_abs /= f_w;
869
18.9k
  fps->MVrv /= (f_h * f_h);
870
18.9k
  fps->MVcv /= (f_w * f_w);
871
18.9k
  fps->new_mv_count /= num_mbs_16x16;
872
18.9k
}
873
874
// Updates the first pass stats of this frame.
875
// Input:
876
//   cpi: the encoder setting. Only a few params in it will be used.
877
//   stats: stats accumulated for this frame.
878
//   raw_err_stdev: the statndard deviation for the motion error of all the
879
//                  inter blocks of the (0,0) motion using the last source
880
//                  frame as the reference.
881
//   frame_number: current frame number.
882
//   ts_duration: Duration of the frame / collection of frames.
883
// Updates:
884
//   twopass->total_stats: the accumulated stats.
885
//   twopass->stats_buf_ctx->stats_in_end: the pointer to the current stats,
886
//                                         update its value and its position
887
//                                         in the buffer.
888
static void update_firstpass_stats(AV1_COMP *cpi,
889
                                   const FRAME_STATS *const stats,
890
                                   const double raw_err_stdev,
891
                                   const int frame_number,
892
                                   const int64_t ts_duration,
893
18.9k
                                   const BLOCK_SIZE fp_block_size) {
894
18.9k
  TWO_PASS *twopass = &cpi->ppi->twopass;
895
18.9k
  AV1_COMMON *const cm = &cpi->common;
896
18.9k
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
897
18.9k
  FIRSTPASS_STATS *this_frame_stats = twopass->stats_buf_ctx->stats_in_end;
898
18.9k
  FIRSTPASS_STATS fps;
899
  // The minimum error here insures some bit allocation to frames even
900
  // in static regions. The allocation per MB declines for larger formats
901
  // where the typical "real" energy per MB also falls.
902
  // Initial estimate here uses sqrt(mbs) to define the min_err, where the
903
  // number of mbs is proportional to the image area.
904
18.9k
  const int num_mbs_16X16 = (cpi->oxcf.resize_cfg.resize_mode != RESIZE_NONE)
905
18.9k
                                ? cpi->initial_mbs
906
18.9k
                                : mi_params->MBs;
907
  // Number of actual units used in the first pass, it can be other square
908
  // block sizes than 16X16.
909
18.9k
  const int num_mbs = get_num_mbs(fp_block_size, num_mbs_16X16);
910
18.9k
  const double min_err = 200 * sqrt(num_mbs);
911
912
18.9k
  fps.weight = stats->intra_factor * stats->brightness_factor;
913
18.9k
  fps.frame = frame_number;
914
18.9k
  fps.coded_error = (double)(stats->coded_error >> 8) + min_err;
915
18.9k
  fps.sr_coded_error = (double)(stats->sr_coded_error >> 8) + min_err;
916
18.9k
  fps.intra_error = (double)(stats->intra_error >> 8) + min_err;
917
18.9k
  fps.frame_avg_wavelet_energy = (double)stats->frame_avg_wavelet_energy;
918
18.9k
  fps.count = 1.0;
919
18.9k
  fps.pcnt_inter = (double)stats->inter_count / num_mbs;
920
18.9k
  fps.pcnt_second_ref = (double)stats->second_ref_count / num_mbs;
921
18.9k
  fps.pcnt_neutral = (double)stats->neutral_count / num_mbs;
922
18.9k
  fps.intra_skip_pct = (double)stats->intra_skip_count / num_mbs;
923
18.9k
  fps.inactive_zone_rows = (double)stats->image_data_start_row;
924
18.9k
  fps.inactive_zone_cols = 0.0;  // Placeholder: not currently supported.
925
18.9k
  fps.raw_error_stdev = raw_err_stdev;
926
18.9k
  fps.is_flash = 0;
927
18.9k
  fps.noise_var = 0.0;
928
18.9k
  fps.cor_coeff = 1.0;
929
18.9k
  fps.log_coded_error = 0.0;
930
18.9k
  fps.log_intra_error = 0.0;
931
932
18.9k
  if (stats->mv_count > 0) {
933
1.71k
    fps.MVr = (double)stats->sum_mvr / stats->mv_count;
934
1.71k
    fps.mvr_abs = (double)stats->sum_mvr_abs / stats->mv_count;
935
1.71k
    fps.MVc = (double)stats->sum_mvc / stats->mv_count;
936
1.71k
    fps.mvc_abs = (double)stats->sum_mvc_abs / stats->mv_count;
937
1.71k
    fps.MVrv = ((double)stats->sum_mvrs -
938
1.71k
                ((double)stats->sum_mvr * stats->sum_mvr / stats->mv_count)) /
939
1.71k
               stats->mv_count;
940
1.71k
    fps.MVcv = ((double)stats->sum_mvcs -
941
1.71k
                ((double)stats->sum_mvc * stats->sum_mvc / stats->mv_count)) /
942
1.71k
               stats->mv_count;
943
1.71k
    fps.mv_in_out_count = (double)stats->sum_in_vectors / (stats->mv_count * 2);
944
1.71k
    fps.new_mv_count = stats->new_mv_count;
945
1.71k
    fps.pcnt_motion = (double)stats->mv_count / num_mbs;
946
17.2k
  } else {
947
17.2k
    fps.MVr = 0.0;
948
17.2k
    fps.mvr_abs = 0.0;
949
17.2k
    fps.MVc = 0.0;
950
17.2k
    fps.mvc_abs = 0.0;
951
17.2k
    fps.MVrv = 0.0;
952
17.2k
    fps.MVcv = 0.0;
953
17.2k
    fps.mv_in_out_count = 0.0;
954
17.2k
    fps.new_mv_count = 0.0;
955
17.2k
    fps.pcnt_motion = 0.0;
956
17.2k
  }
957
958
  // TODO(paulwilkins):  Handle the case when duration is set to 0, or
959
  // something less than the full time between subsequent values of
960
  // cpi->source_time_stamp.
961
18.9k
  fps.duration = (double)ts_duration;
962
963
18.9k
  normalize_firstpass_stats(&fps, num_mbs_16X16, cm->width, cm->height);
964
965
  // We will store the stats inside the persistent twopass struct (and NOT the
966
  // local variable 'fps'), and then cpi->output_pkt_list will point to it.
967
18.9k
  *this_frame_stats = fps;
968
18.9k
  if (!cpi->ppi->lap_enabled) {
969
0
    output_stats(this_frame_stats, cpi->ppi->output_pkt_list);
970
18.9k
  } else {
971
18.9k
    av1_firstpass_info_push(&twopass->firstpass_info, this_frame_stats);
972
18.9k
  }
973
18.9k
  if (cpi->ppi->twopass.stats_buf_ctx->total_stats != NULL) {
974
18.9k
    av1_accumulate_stats(cpi->ppi->twopass.stats_buf_ctx->total_stats, &fps);
975
18.9k
  }
976
18.9k
  twopass->stats_buf_ctx->stats_in_end++;
977
  // When ducky encode is on, we always use linear buffer for stats_buf_ctx.
978
18.9k
  if (cpi->use_ducky_encode == 0) {
979
    // TODO(angiebird): Figure out why first pass uses circular buffer.
980
    /* In the case of two pass, first pass uses it as a circular buffer,
981
     * when LAP is enabled it is used as a linear buffer*/
982
18.9k
    if ((cpi->oxcf.pass == AOM_RC_FIRST_PASS) &&
983
0
        (twopass->stats_buf_ctx->stats_in_end >=
984
0
         twopass->stats_buf_ctx->stats_in_buf_end)) {
985
0
      twopass->stats_buf_ctx->stats_in_end =
986
0
          twopass->stats_buf_ctx->stats_in_start;
987
0
    }
988
18.9k
  }
989
18.9k
}
990
991
static void print_reconstruction_frame(
992
    const YV12_BUFFER_CONFIG *const last_frame, int frame_number,
993
18.9k
    int do_print) {
994
18.9k
  if (!do_print) return;
995
996
0
  char filename[512];
997
0
  FILE *recon_file;
998
0
  snprintf(filename, sizeof(filename), "enc%04d.yuv", frame_number);
999
1000
0
  if (frame_number == 0) {
1001
0
    recon_file = fopen(filename, "wb");
1002
0
  } else {
1003
0
    recon_file = fopen(filename, "ab");
1004
0
  }
1005
1006
0
  fwrite(last_frame->buffer_alloc, last_frame->frame_size, 1, recon_file);
1007
0
  fclose(recon_file);
1008
0
}
1009
1010
static FRAME_STATS accumulate_frame_stats(FRAME_STATS *mb_stats, int mb_rows,
1011
18.9k
                                          int mb_cols) {
1012
18.9k
  FRAME_STATS stats = { 0 };
1013
18.9k
  int i, j;
1014
1015
18.9k
  stats.image_data_start_row = INVALID_ROW;
1016
90.3k
  for (j = 0; j < mb_rows; j++) {
1017
346k
    for (i = 0; i < mb_cols; i++) {
1018
275k
      FRAME_STATS mb_stat = mb_stats[j * mb_cols + i];
1019
275k
      stats.brightness_factor += mb_stat.brightness_factor;
1020
275k
      stats.coded_error += mb_stat.coded_error;
1021
275k
      stats.frame_avg_wavelet_energy += mb_stat.frame_avg_wavelet_energy;
1022
275k
      if (stats.image_data_start_row == INVALID_ROW &&
1023
58.4k
          mb_stat.image_data_start_row != INVALID_ROW) {
1024
9.72k
        stats.image_data_start_row = mb_stat.image_data_start_row;
1025
9.72k
      }
1026
275k
      stats.inter_count += mb_stat.inter_count;
1027
275k
      stats.intra_error += mb_stat.intra_error;
1028
275k
      stats.intra_factor += mb_stat.intra_factor;
1029
275k
      stats.intra_skip_count += mb_stat.intra_skip_count;
1030
275k
      stats.mv_count += mb_stat.mv_count;
1031
275k
      stats.neutral_count += mb_stat.neutral_count;
1032
275k
      stats.new_mv_count += mb_stat.new_mv_count;
1033
275k
      stats.second_ref_count += mb_stat.second_ref_count;
1034
275k
      stats.sr_coded_error += mb_stat.sr_coded_error;
1035
275k
      stats.sum_in_vectors += mb_stat.sum_in_vectors;
1036
275k
      stats.sum_mvc += mb_stat.sum_mvc;
1037
275k
      stats.sum_mvc_abs += mb_stat.sum_mvc_abs;
1038
275k
      stats.sum_mvcs += mb_stat.sum_mvcs;
1039
275k
      stats.sum_mvr += mb_stat.sum_mvr;
1040
275k
      stats.sum_mvr_abs += mb_stat.sum_mvr_abs;
1041
275k
      stats.sum_mvrs += mb_stat.sum_mvrs;
1042
275k
    }
1043
71.4k
  }
1044
18.9k
  return stats;
1045
18.9k
}
1046
1047
static void setup_firstpass_data(AV1_COMMON *const cm,
1048
                                 FirstPassData *firstpass_data,
1049
18.9k
                                 const int unit_rows, const int unit_cols) {
1050
18.9k
  CHECK_MEM_ERROR(cm, firstpass_data->raw_motion_err_list,
1051
18.9k
                  aom_calloc(unit_rows * unit_cols,
1052
18.9k
                             sizeof(*firstpass_data->raw_motion_err_list)));
1053
18.9k
  CHECK_MEM_ERROR(
1054
18.9k
      cm, firstpass_data->mb_stats,
1055
18.9k
      aom_calloc(unit_rows * unit_cols, sizeof(*firstpass_data->mb_stats)));
1056
90.3k
  for (int j = 0; j < unit_rows; j++) {
1057
346k
    for (int i = 0; i < unit_cols; i++) {
1058
275k
      firstpass_data->mb_stats[j * unit_cols + i].image_data_start_row =
1059
275k
          INVALID_ROW;
1060
275k
    }
1061
71.4k
  }
1062
18.9k
}
1063
1064
93.9k
void av1_free_firstpass_data(FirstPassData *firstpass_data) {
1065
93.9k
  aom_free(firstpass_data->raw_motion_err_list);
1066
93.9k
  firstpass_data->raw_motion_err_list = NULL;
1067
93.9k
  aom_free(firstpass_data->mb_stats);
1068
93.9k
  firstpass_data->mb_stats = NULL;
1069
93.9k
}
1070
1071
int av1_get_unit_rows_in_tile(const TileInfo *tile,
1072
121k
                              const BLOCK_SIZE fp_block_size) {
1073
121k
  const int unit_height_log2 = mi_size_high_log2[fp_block_size];
1074
121k
  const int mi_rows = tile->mi_row_end - tile->mi_row_start;
1075
121k
  const int unit_rows = CEIL_POWER_OF_TWO(mi_rows, unit_height_log2);
1076
1077
121k
  return unit_rows;
1078
121k
}
1079
1080
int av1_get_unit_cols_in_tile(const TileInfo *tile,
1081
217k
                              const BLOCK_SIZE fp_block_size) {
1082
217k
  const int unit_width_log2 = mi_size_wide_log2[fp_block_size];
1083
217k
  const int mi_cols = tile->mi_col_end - tile->mi_col_start;
1084
217k
  const int unit_cols = CEIL_POWER_OF_TWO(mi_cols, unit_width_log2);
1085
1086
217k
  return unit_cols;
1087
217k
}
1088
1089
#define FIRST_PASS_ALT_REF_DISTANCE 16
1090
static void first_pass_tile(AV1_COMP *cpi, ThreadData *td,
1091
                            TileDataEnc *tile_data,
1092
9.05k
                            const BLOCK_SIZE fp_block_size) {
1093
9.05k
  TileInfo *tile = &tile_data->tile_info;
1094
9.05k
  const int unit_height = mi_size_high[fp_block_size];
1095
9.05k
  const int unit_height_log2 = mi_size_high_log2[fp_block_size];
1096
27.4k
  for (int mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1097
18.3k
       mi_row += unit_height) {
1098
18.3k
    av1_first_pass_row(cpi, td, tile_data, mi_row >> unit_height_log2,
1099
18.3k
                       fp_block_size);
1100
18.3k
  }
1101
9.05k
}
1102
1103
7.14k
static void first_pass_tiles(AV1_COMP *cpi, const BLOCK_SIZE fp_block_size) {
1104
7.14k
  AV1_COMMON *const cm = &cpi->common;
1105
7.14k
  const int tile_cols = cm->tiles.cols;
1106
7.14k
  const int tile_rows = cm->tiles.rows;
1107
1108
7.14k
  av1_alloc_src_diff_buf(cm, &cpi->td.mb);
1109
15.2k
  for (int tile_row = 0; tile_row < tile_rows; ++tile_row) {
1110
17.1k
    for (int tile_col = 0; tile_col < tile_cols; ++tile_col) {
1111
9.05k
      TileDataEnc *const tile_data =
1112
9.05k
          &cpi->tile_data[tile_row * tile_cols + tile_col];
1113
9.05k
      first_pass_tile(cpi, &cpi->td, tile_data, fp_block_size);
1114
9.05k
    }
1115
8.06k
  }
1116
7.14k
}
1117
1118
void av1_first_pass_row(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data,
1119
96.7k
                        const int unit_row, const BLOCK_SIZE fp_block_size) {
1120
96.7k
  MACROBLOCK *const x = &td->mb;
1121
96.7k
  AV1_COMMON *const cm = &cpi->common;
1122
96.7k
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
1123
96.7k
  const SequenceHeader *const seq_params = cm->seq_params;
1124
96.7k
  const int num_planes = av1_num_planes(cm);
1125
96.7k
  MACROBLOCKD *const xd = &x->e_mbd;
1126
96.7k
  TileInfo *tile = &tile_data->tile_info;
1127
96.7k
  const int qindex = find_fp_qindex(seq_params->bit_depth);
1128
96.7k
  const int fp_block_size_width = block_size_high[fp_block_size];
1129
96.7k
  const int fp_block_size_height = block_size_wide[fp_block_size];
1130
96.7k
  const int unit_width = mi_size_wide[fp_block_size];
1131
96.7k
  const int unit_width_log2 = mi_size_wide_log2[fp_block_size];
1132
96.7k
  const int unit_height_log2 = mi_size_high_log2[fp_block_size];
1133
96.7k
  const int unit_cols = mi_params->mb_cols * 4 / unit_width;
1134
96.7k
  int raw_motion_err_counts = 0;
1135
96.7k
  int unit_row_in_tile = unit_row - (tile->mi_row_start >> unit_height_log2);
1136
96.7k
  int unit_col_start = tile->mi_col_start >> unit_width_log2;
1137
96.7k
  int unit_cols_in_tile = av1_get_unit_cols_in_tile(tile, fp_block_size);
1138
96.7k
  MultiThreadInfo *const mt_info = &cpi->mt_info;
1139
96.7k
  AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt;
1140
96.7k
  AV1EncRowMultiThreadSync *const row_mt_sync = &tile_data->row_mt_sync;
1141
1142
96.7k
  const YV12_BUFFER_CONFIG *last_frame =
1143
96.7k
      av1_get_scaled_ref_frame(cpi, LAST_FRAME);
1144
96.7k
  if (!last_frame) {
1145
96.1k
    last_frame = get_ref_frame_yv12_buf(cm, LAST_FRAME);
1146
96.1k
  }
1147
96.7k
  const YV12_BUFFER_CONFIG *golden_frame =
1148
96.7k
      av1_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
1149
96.7k
  if (!golden_frame) {
1150
96.0k
    golden_frame = get_ref_frame_yv12_buf(cm, GOLDEN_FRAME);
1151
96.0k
  }
1152
96.7k
  YV12_BUFFER_CONFIG *const this_frame = &cm->cur_frame->buf;
1153
1154
96.7k
  PICK_MODE_CONTEXT *ctx = td->firstpass_ctx;
1155
96.7k
  FRAME_STATS *mb_stats =
1156
96.7k
      cpi->firstpass_data.mb_stats + unit_row * unit_cols + unit_col_start;
1157
96.7k
  int *raw_motion_err_list = cpi->firstpass_data.raw_motion_err_list +
1158
96.7k
                             unit_row * unit_cols + unit_col_start;
1159
96.7k
  MV *first_top_mv = &tile_data->firstpass_top_mv;
1160
1161
294k
  for (int i = 0; i < num_planes; ++i) {
1162
197k
    x->plane[i].coeff = ctx->coeff[i];
1163
197k
    x->plane[i].qcoeff = ctx->qcoeff[i];
1164
197k
    x->plane[i].eobs = ctx->eobs[i];
1165
197k
    x->plane[i].txb_entropy_ctx = ctx->txb_entropy_ctx[i];
1166
197k
    x->plane[i].dqcoeff = ctx->dqcoeff[i];
1167
197k
  }
1168
1169
96.7k
  const int src_y_stride = cpi->source->y_stride;
1170
96.7k
  const int recon_y_stride = this_frame->y_stride;
1171
96.7k
  const int recon_uv_stride = this_frame->uv_stride;
1172
96.7k
  const int uv_mb_height =
1173
96.7k
      fp_block_size_height >> (this_frame->y_height > this_frame->uv_height);
1174
1175
96.7k
  MV best_ref_mv = kZeroMv;
1176
96.7k
  MV last_mv;
1177
1178
  // Reset above block coeffs.
1179
96.7k
  xd->up_available = (unit_row_in_tile != 0);
1180
96.7k
  int recon_yoffset = (unit_row * recon_y_stride * fp_block_size_height) +
1181
96.7k
                      (unit_col_start * fp_block_size_width);
1182
96.7k
  int src_yoffset = (unit_row * src_y_stride * fp_block_size_height) +
1183
96.7k
                    (unit_col_start * fp_block_size_width);
1184
96.7k
  int recon_uvoffset = (unit_row * recon_uv_stride * uv_mb_height) +
1185
96.7k
                       (unit_col_start * uv_mb_height);
1186
1187
  // Set up limit values for motion vectors to prevent them extending
1188
  // outside the UMV borders.
1189
96.7k
  av1_set_mv_row_limits(
1190
96.7k
      mi_params, &x->mv_limits, (unit_row << unit_height_log2),
1191
96.7k
      (fp_block_size_height >> MI_SIZE_LOG2), cpi->oxcf.border_in_pixels);
1192
1193
96.7k
  av1_setup_src_planes(x, cpi->source, unit_row << unit_height_log2,
1194
96.7k
                       tile->mi_col_start, num_planes, fp_block_size);
1195
1196
  // Fix - zero the 16x16 block first. This ensures correct this_intra_error for
1197
  // block sizes smaller than 16x16.
1198
96.7k
  av1_zero_array(x->plane[0].src_diff, 256);
1199
1200
370k
  for (int unit_col_in_tile = 0; unit_col_in_tile < unit_cols_in_tile;
1201
274k
       unit_col_in_tile++) {
1202
274k
    const int unit_col = unit_col_start + unit_col_in_tile;
1203
1204
274k
    enc_row_mt->sync_read_ptr(row_mt_sync, unit_row_in_tile, unit_col_in_tile);
1205
1206
274k
#if CONFIG_MULTITHREAD
1207
274k
    if (cpi->ppi->p_mt_info.num_workers > 1) {
1208
215k
      pthread_mutex_lock(enc_row_mt->mutex_);
1209
215k
      bool firstpass_mt_exit = enc_row_mt->firstpass_mt_exit;
1210
215k
      pthread_mutex_unlock(enc_row_mt->mutex_);
1211
      // Exit in case any worker has encountered an error.
1212
215k
      if (firstpass_mt_exit) return;
1213
215k
    }
1214
274k
#endif
1215
1216
274k
    if (unit_col_in_tile == 0) {
1217
96.6k
      last_mv = *first_top_mv;
1218
96.6k
    }
1219
274k
    int this_intra_error = firstpass_intra_prediction(
1220
274k
        cpi, td, this_frame, tile, unit_row, unit_col, recon_yoffset,
1221
274k
        recon_uvoffset, fp_block_size, qindex, mb_stats);
1222
1223
274k
    if (!frame_is_intra_only(cm)) {
1224
140k
      const int this_inter_error = firstpass_inter_prediction(
1225
140k
          cpi, td, last_frame, golden_frame, unit_row, unit_col, recon_yoffset,
1226
140k
          recon_uvoffset, src_yoffset, fp_block_size, this_intra_error,
1227
140k
          raw_motion_err_counts, raw_motion_err_list, best_ref_mv, &best_ref_mv,
1228
140k
          &last_mv, mb_stats);
1229
140k
      if (unit_col_in_tile == 0) {
1230
48.5k
        *first_top_mv = last_mv;
1231
48.5k
      }
1232
140k
      mb_stats->coded_error += this_inter_error;
1233
140k
      ++raw_motion_err_counts;
1234
140k
    } else {
1235
133k
      mb_stats->sr_coded_error += this_intra_error;
1236
133k
      mb_stats->coded_error += this_intra_error;
1237
133k
    }
1238
1239
    // Adjust to the next column of MBs.
1240
274k
    x->plane[0].src.buf += fp_block_size_width;
1241
274k
    if (num_planes > 1) {
1242
153k
      x->plane[1].src.buf += uv_mb_height;
1243
153k
      x->plane[2].src.buf += uv_mb_height;
1244
153k
    }
1245
1246
274k
    recon_yoffset += fp_block_size_width;
1247
274k
    src_yoffset += fp_block_size_width;
1248
274k
    recon_uvoffset += uv_mb_height;
1249
274k
    mb_stats++;
1250
1251
274k
    enc_row_mt->sync_write_ptr(row_mt_sync, unit_row_in_tile, unit_col_in_tile,
1252
274k
                               unit_cols_in_tile);
1253
274k
  }
1254
96.7k
}
1255
1256
0
void av1_noop_first_pass_frame(AV1_COMP *cpi, const int64_t ts_duration) {
1257
0
  AV1_COMMON *const cm = &cpi->common;
1258
0
  CurrentFrame *const current_frame = &cm->current_frame;
1259
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
1260
0
  int max_mb_rows = mi_params->mb_rows;
1261
0
  int max_mb_cols = mi_params->mb_cols;
1262
0
  if (cpi->oxcf.frm_dim_cfg.forced_max_frame_width) {
1263
0
    int max_mi_cols = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_width);
1264
0
    max_mb_cols = ROUND_POWER_OF_TWO(max_mi_cols, 2);
1265
0
  }
1266
0
  if (cpi->oxcf.frm_dim_cfg.forced_max_frame_height) {
1267
0
    int max_mi_rows = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_height);
1268
0
    max_mb_rows = ROUND_POWER_OF_TWO(max_mi_rows, 2);
1269
0
  }
1270
0
  const int unit_rows = get_unit_rows(BLOCK_16X16, max_mb_rows);
1271
0
  const int unit_cols = get_unit_cols(BLOCK_16X16, max_mb_cols);
1272
0
  setup_firstpass_data(cm, &cpi->firstpass_data, unit_rows, unit_cols);
1273
0
  FRAME_STATS *mb_stats = cpi->firstpass_data.mb_stats;
1274
0
  FRAME_STATS stats = accumulate_frame_stats(mb_stats, unit_rows, unit_cols);
1275
0
  av1_free_firstpass_data(&cpi->firstpass_data);
1276
0
  update_firstpass_stats(cpi, &stats, 1.0, current_frame->frame_number,
1277
0
                         ts_duration, BLOCK_16X16);
1278
0
}
1279
1280
18.9k
void av1_first_pass(AV1_COMP *cpi, const int64_t ts_duration) {
1281
18.9k
  MACROBLOCK *const x = &cpi->td.mb;
1282
18.9k
  AV1_COMMON *const cm = &cpi->common;
1283
18.9k
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
1284
18.9k
  CurrentFrame *const current_frame = &cm->current_frame;
1285
18.9k
  const SequenceHeader *const seq_params = cm->seq_params;
1286
18.9k
  const int num_planes = av1_num_planes(cm);
1287
18.9k
  MACROBLOCKD *const xd = &x->e_mbd;
1288
18.9k
  const int qindex = find_fp_qindex(seq_params->bit_depth);
1289
18.9k
  const int ref_frame_flags_backup = cpi->ref_frame_flags;
1290
18.9k
  cpi->ref_frame_flags = av1_ref_frame_flag_list[LAST_FRAME] |
1291
18.9k
                         av1_ref_frame_flag_list[GOLDEN_FRAME];
1292
1293
  // Detect if the key frame is screen content type.
1294
18.9k
  if (frame_is_intra_only(cm)) {
1295
9.62k
    FeatureFlags *const features = &cm->features;
1296
9.62k
    assert(cpi->source != NULL);
1297
9.62k
    xd->cur_buf = cpi->source;
1298
9.62k
    av1_set_screen_content_options(cpi, features);
1299
9.62k
  }
1300
1301
  // Prepare the speed features
1302
18.9k
  av1_set_speed_features_framesize_independent(cpi, cpi->oxcf.speed);
1303
1304
  // Unit size for the first pass encoding.
1305
18.9k
  const BLOCK_SIZE fp_block_size =
1306
18.9k
      get_fp_block_size(cpi->is_screen_content_type);
1307
1308
18.9k
  int max_mb_rows = mi_params->mb_rows;
1309
18.9k
  int max_mb_cols = mi_params->mb_cols;
1310
18.9k
  if (cpi->oxcf.frm_dim_cfg.forced_max_frame_width) {
1311
0
    int max_mi_cols = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_width);
1312
0
    max_mb_cols = ROUND_POWER_OF_TWO(max_mi_cols, 2);
1313
0
  }
1314
18.9k
  if (cpi->oxcf.frm_dim_cfg.forced_max_frame_height) {
1315
0
    int max_mi_rows = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_height);
1316
0
    max_mb_rows = ROUND_POWER_OF_TWO(max_mi_rows, 2);
1317
0
  }
1318
1319
  // Number of rows in the unit size.
1320
  // Note max_mb_rows and max_mb_cols are in the unit of 16x16.
1321
18.9k
  const int unit_rows = get_unit_rows(fp_block_size, max_mb_rows);
1322
18.9k
  const int unit_cols = get_unit_cols(fp_block_size, max_mb_cols);
1323
1324
  // Set fp_block_size, for the convenience of multi-thread usage.
1325
18.9k
  cpi->fp_block_size = fp_block_size;
1326
1327
18.9k
  setup_firstpass_data(cm, &cpi->firstpass_data, unit_rows, unit_cols);
1328
18.9k
  int *raw_motion_err_list = cpi->firstpass_data.raw_motion_err_list;
1329
18.9k
  FRAME_STATS *mb_stats = cpi->firstpass_data.mb_stats;
1330
1331
  // multi threading info
1332
18.9k
  MultiThreadInfo *const mt_info = &cpi->mt_info;
1333
18.9k
  AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt;
1334
1335
18.9k
  const int tile_cols = cm->tiles.cols;
1336
18.9k
  const int tile_rows = cm->tiles.rows;
1337
18.9k
  if (cpi->allocated_tiles < tile_cols * tile_rows) {
1338
6.98k
    av1_alloc_tile_data(cpi);
1339
6.98k
  }
1340
1341
18.9k
  av1_init_tile_data(cpi);
1342
1343
18.9k
  const YV12_BUFFER_CONFIG *last_frame = NULL;
1344
18.9k
  const YV12_BUFFER_CONFIG *golden_frame = NULL;
1345
18.9k
  if (!frame_is_intra_only(cm)) {
1346
9.32k
    av1_scale_references(cpi, EIGHTTAP_REGULAR, 0, 0);
1347
9.32k
    last_frame = av1_is_scaled(get_ref_scale_factors_const(cm, LAST_FRAME))
1348
9.32k
                     ? av1_get_scaled_ref_frame(cpi, LAST_FRAME)
1349
9.32k
                     : get_ref_frame_yv12_buf(cm, LAST_FRAME);
1350
9.32k
    golden_frame = av1_is_scaled(get_ref_scale_factors_const(cm, GOLDEN_FRAME))
1351
9.32k
                       ? av1_get_scaled_ref_frame(cpi, GOLDEN_FRAME)
1352
9.32k
                       : get_ref_frame_yv12_buf(cm, GOLDEN_FRAME);
1353
9.32k
  }
1354
1355
18.9k
  YV12_BUFFER_CONFIG *const this_frame = &cm->cur_frame->buf;
1356
  // First pass code requires valid last and new frame buffers.
1357
18.9k
  assert(this_frame != NULL);
1358
18.9k
  assert(frame_is_intra_only(cm) || (last_frame != NULL));
1359
1360
18.9k
  av1_setup_frame_size(cpi);
1361
18.9k
  av1_set_mv_search_params(cpi);
1362
1363
18.9k
  set_mi_offsets(mi_params, xd, 0, 0);
1364
18.9k
  xd->mi[0]->bsize = fp_block_size;
1365
1366
  // Do not use periodic key frames.
1367
18.9k
  cpi->rc.frames_to_key = INT_MAX;
1368
1369
18.9k
  av1_set_quantizer(
1370
18.9k
      cm, cpi->oxcf.q_cfg.qm_minlevel, cpi->oxcf.q_cfg.qm_maxlevel, qindex,
1371
18.9k
      cpi->oxcf.q_cfg.enable_chroma_deltaq, cpi->oxcf.q_cfg.enable_hdr_deltaq,
1372
18.9k
      cpi->oxcf.mode == ALLINTRA, cpi->oxcf.tune_cfg.tuning);
1373
1374
18.9k
  av1_setup_block_planes(xd, seq_params->subsampling_x,
1375
18.9k
                         seq_params->subsampling_y, num_planes);
1376
1377
18.9k
  av1_setup_src_planes(x, cpi->source, 0, 0, num_planes, fp_block_size);
1378
18.9k
  av1_setup_dst_planes(xd->plane, seq_params->sb_size, this_frame, 0, 0, 0,
1379
18.9k
                       num_planes);
1380
1381
18.9k
  if (!frame_is_intra_only(cm)) {
1382
9.32k
    av1_setup_pre_planes(xd, 0, last_frame, 0, 0, NULL, num_planes);
1383
9.32k
  }
1384
1385
18.9k
  set_mi_offsets(mi_params, xd, 0, 0);
1386
1387
  // Don't store luma on the fist pass since chroma is not computed
1388
18.9k
  xd->cfl.store_y = 0;
1389
18.9k
  av1_frame_init_quantizer(cpi);
1390
1391
18.9k
  av1_default_coef_probs(cm);
1392
18.9k
  av1_init_mode_probs(cm->fc);
1393
18.9k
  av1_init_mv_probs(cm);
1394
18.9k
  av1_initialize_rd_consts(cpi);
1395
1396
18.9k
  enc_row_mt->sync_read_ptr = av1_row_mt_sync_read_dummy;
1397
18.9k
  enc_row_mt->sync_write_ptr = av1_row_mt_sync_write_dummy;
1398
1399
18.9k
  if (mt_info->num_workers > 1) {
1400
11.8k
    enc_row_mt->sync_read_ptr = av1_row_mt_sync_read;
1401
11.8k
    enc_row_mt->sync_write_ptr = av1_row_mt_sync_write;
1402
11.8k
    av1_fp_encode_tiles_row_mt(cpi);
1403
11.8k
  } else {
1404
7.14k
    first_pass_tiles(cpi, fp_block_size);
1405
7.14k
  }
1406
1407
18.9k
  FRAME_STATS stats = accumulate_frame_stats(mb_stats, unit_rows, unit_cols);
1408
18.9k
  int total_raw_motion_err_count =
1409
18.9k
      frame_is_intra_only(cm) ? 0 : unit_rows * unit_cols;
1410
18.9k
  const double raw_err_stdev =
1411
18.9k
      raw_motion_error_stdev(raw_motion_err_list, total_raw_motion_err_count);
1412
18.9k
  av1_free_firstpass_data(&cpi->firstpass_data);
1413
18.9k
  av1_dealloc_src_diff_buf(&cpi->td.mb, av1_num_planes(cm));
1414
1415
  // Clamp the image start to rows/2. This number of rows is discarded top
1416
  // and bottom as dead data so rows / 2 means the frame is blank.
1417
18.9k
  if ((stats.image_data_start_row > unit_rows / 2) ||
1418
18.9k
      (stats.image_data_start_row == INVALID_ROW)) {
1419
9.21k
    stats.image_data_start_row = unit_rows / 2;
1420
9.21k
  }
1421
  // Exclude any image dead zone
1422
18.9k
  if (stats.image_data_start_row > 0) {
1423
4.76k
    stats.intra_skip_count =
1424
4.76k
        AOMMAX(0, stats.intra_skip_count -
1425
4.76k
                      (stats.image_data_start_row * unit_cols * 2));
1426
4.76k
  }
1427
1428
18.9k
  TWO_PASS *twopass = &cpi->ppi->twopass;
1429
18.9k
  const int num_mbs_16X16 = (cpi->oxcf.resize_cfg.resize_mode != RESIZE_NONE)
1430
18.9k
                                ? cpi->initial_mbs
1431
18.9k
                                : mi_params->MBs;
1432
  // Number of actual units used in the first pass, it can be other square
1433
  // block sizes than 16X16.
1434
18.9k
  const int num_mbs = get_num_mbs(fp_block_size, num_mbs_16X16);
1435
18.9k
  stats.intra_factor = stats.intra_factor / (double)num_mbs;
1436
18.9k
  stats.brightness_factor = stats.brightness_factor / (double)num_mbs;
1437
18.9k
  FIRSTPASS_STATS *this_frame_stats = twopass->stats_buf_ctx->stats_in_end;
1438
18.9k
  update_firstpass_stats(cpi, &stats, raw_err_stdev,
1439
18.9k
                         current_frame->frame_number, ts_duration,
1440
18.9k
                         fp_block_size);
1441
1442
  // Copy the previous Last Frame back into gf buffer if the prediction is good
1443
  // enough... but also don't allow it to lag too far.
1444
18.9k
  if ((twopass->sr_update_lag > 3) ||
1445
16.7k
      ((current_frame->frame_number > 0) &&
1446
7.66k
       (this_frame_stats->pcnt_inter > 0.20) &&
1447
2.51k
       ((this_frame_stats->intra_error /
1448
2.51k
         DOUBLE_DIVIDE_CHECK(this_frame_stats->coded_error)) > 2.0))) {
1449
2.34k
    if (golden_frame != NULL) {
1450
1.76k
      assign_frame_buffer_p(
1451
1.76k
          &cm->ref_frame_map[get_ref_frame_map_idx(cm, GOLDEN_FRAME)],
1452
1.76k
          cm->ref_frame_map[get_ref_frame_map_idx(cm, LAST_FRAME)]);
1453
1.76k
    }
1454
2.34k
    twopass->sr_update_lag = 1;
1455
16.6k
  } else {
1456
16.6k
    ++twopass->sr_update_lag;
1457
16.6k
  }
1458
1459
18.9k
  aom_extend_frame_borders(this_frame, num_planes);
1460
1461
  // The frame we just compressed now becomes the last frame.
1462
18.9k
  assign_frame_buffer_p(
1463
18.9k
      &cm->ref_frame_map[get_ref_frame_map_idx(cm, LAST_FRAME)], cm->cur_frame);
1464
1465
  // Special case for the first frame. Copy into the GF buffer as a second
1466
  // reference.
1467
18.9k
  if (current_frame->frame_number == 0 &&
1468
9.62k
      get_ref_frame_map_idx(cm, GOLDEN_FRAME) != INVALID_IDX) {
1469
9.62k
    assign_frame_buffer_p(
1470
9.62k
        &cm->ref_frame_map[get_ref_frame_map_idx(cm, GOLDEN_FRAME)],
1471
9.62k
        cm->ref_frame_map[get_ref_frame_map_idx(cm, LAST_FRAME)]);
1472
9.62k
  }
1473
1474
18.9k
  print_reconstruction_frame(last_frame, current_frame->frame_number,
1475
18.9k
                             /*do_print=*/0);
1476
1477
18.9k
  ++current_frame->frame_number;
1478
18.9k
  cpi->ref_frame_flags = ref_frame_flags_backup;
1479
18.9k
  if (!frame_is_intra_only(cm)) {
1480
9.32k
    release_scaled_references(cpi);
1481
9.32k
  }
1482
18.9k
}
1483
1484
aom_codec_err_t av1_firstpass_info_init(FIRSTPASS_INFO *firstpass_info,
1485
                                        FIRSTPASS_STATS *ext_stats_buf,
1486
6.98k
                                        int ext_stats_buf_size) {
1487
6.98k
  assert(IMPLIES(ext_stats_buf == NULL, ext_stats_buf_size == 0));
1488
6.98k
  if (ext_stats_buf == NULL) {
1489
6.98k
    firstpass_info->stats_buf = firstpass_info->static_stats_buf;
1490
6.98k
    firstpass_info->stats_buf_size =
1491
6.98k
        sizeof(firstpass_info->static_stats_buf) /
1492
6.98k
        sizeof(firstpass_info->static_stats_buf[0]);
1493
6.98k
    firstpass_info->start_index = 0;
1494
6.98k
    firstpass_info->cur_index = 0;
1495
6.98k
    firstpass_info->stats_count = 0;
1496
6.98k
    firstpass_info->future_stats_count = 0;
1497
6.98k
    firstpass_info->past_stats_count = 0;
1498
6.98k
    av1_zero(firstpass_info->total_stats);
1499
6.98k
    if (ext_stats_buf_size == 0) {
1500
6.98k
      return AOM_CODEC_OK;
1501
6.98k
    } else {
1502
0
      return AOM_CODEC_ERROR;
1503
0
    }
1504
6.98k
  } else {
1505
0
    firstpass_info->stats_buf = ext_stats_buf;
1506
0
    firstpass_info->stats_buf_size = ext_stats_buf_size;
1507
0
    firstpass_info->start_index = 0;
1508
0
    firstpass_info->cur_index = 0;
1509
0
    firstpass_info->stats_count = firstpass_info->stats_buf_size;
1510
0
    firstpass_info->future_stats_count = firstpass_info->stats_count;
1511
0
    firstpass_info->past_stats_count = 0;
1512
0
    av1_zero(firstpass_info->total_stats);
1513
0
    for (int i = 0; i < firstpass_info->stats_count; ++i) {
1514
0
      av1_accumulate_stats(&firstpass_info->total_stats,
1515
0
                           &firstpass_info->stats_buf[i]);
1516
0
    }
1517
0
  }
1518
0
  return AOM_CODEC_OK;
1519
6.98k
}
1520
1521
aom_codec_err_t av1_firstpass_info_move_cur_index(
1522
98.9k
    FIRSTPASS_INFO *firstpass_info) {
1523
98.9k
  assert(firstpass_info->future_stats_count +
1524
98.9k
             firstpass_info->past_stats_count ==
1525
98.9k
         firstpass_info->stats_count);
1526
98.9k
  if (firstpass_info->future_stats_count > 1) {
1527
10.6k
    firstpass_info->cur_index =
1528
10.6k
        (firstpass_info->cur_index + 1) % firstpass_info->stats_buf_size;
1529
10.6k
    --firstpass_info->future_stats_count;
1530
10.6k
    ++firstpass_info->past_stats_count;
1531
10.6k
    return AOM_CODEC_OK;
1532
88.3k
  } else {
1533
88.3k
    return AOM_CODEC_ERROR;
1534
88.3k
  }
1535
98.9k
}
1536
1537
1.61k
aom_codec_err_t av1_firstpass_info_pop(FIRSTPASS_INFO *firstpass_info) {
1538
1.61k
  if (firstpass_info->stats_count > 0 && firstpass_info->past_stats_count > 0) {
1539
1.61k
    const int next_start =
1540
1.61k
        (firstpass_info->start_index + 1) % firstpass_info->stats_buf_size;
1541
1.61k
    firstpass_info->start_index = next_start;
1542
1.61k
    --firstpass_info->stats_count;
1543
1.61k
    --firstpass_info->past_stats_count;
1544
1.61k
    return AOM_CODEC_OK;
1545
1.61k
  } else {
1546
0
    return AOM_CODEC_ERROR;
1547
0
  }
1548
1.61k
}
1549
1550
aom_codec_err_t av1_firstpass_info_move_cur_index_and_pop(
1551
3.39k
    FIRSTPASS_INFO *firstpass_info) {
1552
3.39k
  aom_codec_err_t ret = av1_firstpass_info_move_cur_index(firstpass_info);
1553
3.39k
  if (ret != AOM_CODEC_OK) return ret;
1554
1.61k
  ret = av1_firstpass_info_pop(firstpass_info);
1555
1.61k
  return ret;
1556
3.39k
}
1557
1558
aom_codec_err_t av1_firstpass_info_push(FIRSTPASS_INFO *firstpass_info,
1559
18.9k
                                        const FIRSTPASS_STATS *input_stats) {
1560
18.9k
  if (firstpass_info->stats_count < firstpass_info->stats_buf_size) {
1561
18.9k
    const int next_index =
1562
18.9k
        (firstpass_info->start_index + firstpass_info->stats_count) %
1563
18.9k
        firstpass_info->stats_buf_size;
1564
18.9k
    firstpass_info->stats_buf[next_index] = *input_stats;
1565
18.9k
    ++firstpass_info->stats_count;
1566
18.9k
    ++firstpass_info->future_stats_count;
1567
18.9k
    av1_accumulate_stats(&firstpass_info->total_stats, input_stats);
1568
18.9k
    return AOM_CODEC_OK;
1569
18.9k
  } else {
1570
0
    return AOM_CODEC_ERROR;
1571
0
  }
1572
18.9k
}
1573
1574
const FIRSTPASS_STATS *av1_firstpass_info_peek(
1575
79.4k
    const FIRSTPASS_INFO *firstpass_info, int offset_from_cur) {
1576
79.4k
  if (offset_from_cur >= -firstpass_info->past_stats_count &&
1577
73.9k
      offset_from_cur < firstpass_info->future_stats_count) {
1578
73.9k
    const int index = (firstpass_info->cur_index + offset_from_cur) %
1579
73.9k
                      firstpass_info->stats_buf_size;
1580
73.9k
    return &firstpass_info->stats_buf[index];
1581
73.9k
  } else {
1582
5.50k
    return NULL;
1583
5.50k
  }
1584
79.4k
}
1585
1586
int av1_firstpass_info_future_count(const FIRSTPASS_INFO *firstpass_info,
1587
33.3k
                                    int offset_from_cur) {
1588
33.3k
  if (offset_from_cur < firstpass_info->future_stats_count) {
1589
33.3k
    return firstpass_info->future_stats_count - offset_from_cur;
1590
33.3k
  }
1591
0
  return 0;
1592
33.3k
}