Coverage Report

Created: 2026-07-25 07:06

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