Coverage Report

Created: 2025-06-22 08:04

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