Coverage Report

Created: 2026-04-01 07:49

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