Coverage Report

Created: 2026-09-14 07:37

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