Coverage Report

Created: 2025-10-13 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libavif/ext/aom/av1/encoder/pass2_strategy.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2019, 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
/*!\defgroup gf_group_algo Golden Frame Group
13
 * \ingroup high_level_algo
14
 * Algorithms regarding determining the length of GF groups and defining GF
15
 * group structures.
16
 * @{
17
 */
18
/*! @} - end defgroup gf_group_algo */
19
20
#include <assert.h>
21
#include <limits.h>
22
#include <stdint.h>
23
24
#include "aom_dsp/aom_dsp_common.h"
25
#include "aom_mem/aom_mem.h"
26
#include "config/aom_config.h"
27
#include "config/aom_scale_rtcd.h"
28
29
#include "aom/aom_codec.h"
30
#include "aom/aom_encoder.h"
31
32
#include "av1/common/av1_common_int.h"
33
34
#include "av1/encoder/encoder.h"
35
#include "av1/encoder/firstpass.h"
36
#include "av1/encoder/gop_structure.h"
37
#include "av1/encoder/pass2_strategy.h"
38
#include "av1/encoder/ratectrl.h"
39
#include "av1/encoder/rc_utils.h"
40
#include "av1/encoder/temporal_filter.h"
41
#if CONFIG_THREE_PASS
42
#include "av1/encoder/thirdpass.h"
43
#endif
44
#include "av1/encoder/tpl_model.h"
45
#include "av1/encoder/encode_strategy.h"
46
47
59.7k
#define DEFAULT_KF_BOOST 2300
48
138k
#define DEFAULT_GF_BOOST 2000
49
#define GROUP_ADAPTIVE_MAXQ 1
50
51
static void init_gf_stats(GF_GROUP_STATS *gf_stats);
52
#if CONFIG_THREE_PASS
53
static int define_gf_group_pass3(AV1_COMP *cpi, EncodeFrameParams *frame_params,
54
                                 int is_final_pass);
55
#endif
56
57
// Calculate an active area of the image that discounts formatting
58
// bars and partially discounts other 0 energy areas.
59
77.9k
#define MIN_ACTIVE_AREA 0.5
60
77.9k
#define MAX_ACTIVE_AREA 1.0
61
static double calculate_active_area(const FRAME_INFO *frame_info,
62
77.9k
                                    const FIRSTPASS_STATS *this_frame) {
63
77.9k
  const double active_pct =
64
77.9k
      1.0 -
65
77.9k
      ((this_frame->intra_skip_pct / 2) +
66
77.9k
       ((this_frame->inactive_zone_rows * 2) / (double)frame_info->mb_rows));
67
77.9k
  return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
68
77.9k
}
69
70
// Calculate a modified Error used in distributing bits between easier and
71
// harder frames.
72
40.7k
#define ACT_AREA_CORRECTION 0.5
73
static double calculate_modified_err_new(const FRAME_INFO *frame_info,
74
                                         const FIRSTPASS_STATS *total_stats,
75
                                         const FIRSTPASS_STATS *this_stats,
76
                                         int vbrbias, double modified_error_min,
77
40.7k
                                         double modified_error_max) {
78
40.7k
  if (total_stats == NULL) {
79
0
    return 0;
80
0
  }
81
40.7k
  const double av_weight = total_stats->weight / total_stats->count;
82
40.7k
  const double av_err =
83
40.7k
      (total_stats->coded_error * av_weight) / total_stats->count;
84
40.7k
  double modified_error =
85
40.7k
      av_err * pow(this_stats->coded_error * this_stats->weight /
86
40.7k
                       DOUBLE_DIVIDE_CHECK(av_err),
87
40.7k
                   vbrbias / 100.0);
88
89
  // Correction for active area. Frames with a reduced active area
90
  // (eg due to formatting bars) have a higher error per mb for the
91
  // remaining active MBs. The correction here assumes that coding
92
  // 0.5N blocks of complexity 2X is a little easier than coding N
93
  // blocks of complexity X.
94
40.7k
  modified_error *=
95
40.7k
      pow(calculate_active_area(frame_info, this_stats), ACT_AREA_CORRECTION);
96
97
40.7k
  return fclamp(modified_error, modified_error_min, modified_error_max);
98
40.7k
}
99
100
static double calculate_modified_err(const FRAME_INFO *frame_info,
101
                                     const TWO_PASS *twopass,
102
                                     const AV1EncoderConfig *oxcf,
103
26.4k
                                     const FIRSTPASS_STATS *this_frame) {
104
26.4k
  const FIRSTPASS_STATS *total_stats = twopass->stats_buf_ctx->total_stats;
105
26.4k
  return calculate_modified_err_new(
106
26.4k
      frame_info, total_stats, this_frame, oxcf->rc_cfg.vbrbias,
107
26.4k
      twopass->modified_error_min, twopass->modified_error_max);
108
26.4k
}
109
110
// Resets the first pass file to the given position using a relative seek from
111
// the current position.
112
static void reset_fpf_position(TWO_PASS_FRAME *p_frame,
113
114k
                               const FIRSTPASS_STATS *position) {
114
114k
  p_frame->stats_in = position;
115
114k
}
116
117
static int input_stats(TWO_PASS *p, TWO_PASS_FRAME *p_frame,
118
67.7k
                       FIRSTPASS_STATS *fps) {
119
67.7k
  if (p_frame->stats_in >= p->stats_buf_ctx->stats_in_end) return EOF;
120
121
53.8k
  *fps = *p_frame->stats_in;
122
53.8k
  ++p_frame->stats_in;
123
53.8k
  return 1;
124
67.7k
}
125
126
static int input_stats_lap(TWO_PASS *p, TWO_PASS_FRAME *p_frame,
127
18.9k
                           FIRSTPASS_STATS *fps) {
128
18.9k
  if (p_frame->stats_in >= p->stats_buf_ctx->stats_in_end) return EOF;
129
130
18.9k
  *fps = *p_frame->stats_in;
131
  /* Move old stats[0] out to accommodate for next frame stats  */
132
18.9k
  memmove(p->frame_stats_arr[0], p->frame_stats_arr[1],
133
18.9k
          (p->stats_buf_ctx->stats_in_end - p_frame->stats_in - 1) *
134
18.9k
              sizeof(FIRSTPASS_STATS));
135
18.9k
  p->stats_buf_ctx->stats_in_end--;
136
18.9k
  return 1;
137
18.9k
}
138
139
// Read frame stats at an offset from the current position.
140
static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p,
141
                                               const TWO_PASS_FRAME *p_frame,
142
110k
                                               int offset) {
143
110k
  if ((offset >= 0 &&
144
110k
       p_frame->stats_in + offset >= p->stats_buf_ctx->stats_in_end) ||
145
81.2k
      (offset < 0 &&
146
29.1k
       p_frame->stats_in + offset < p->stats_buf_ctx->stats_in_start)) {
147
29.1k
    return NULL;
148
29.1k
  }
149
150
81.2k
  return &p_frame->stats_in[offset];
151
110k
}
152
153
// This function returns the maximum target rate per frame.
154
static int frame_max_bits(const RATE_CONTROL *rc,
155
22.9k
                          const AV1EncoderConfig *oxcf) {
156
22.9k
  int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
157
22.9k
                      (int64_t)oxcf->rc_cfg.vbrmax_section) /
158
22.9k
                     100;
159
22.9k
  if (max_bits < 0)
160
0
    max_bits = 0;
161
22.9k
  else if (max_bits > rc->max_frame_bandwidth)
162
0
    max_bits = rc->max_frame_bandwidth;
163
164
22.9k
  return (int)max_bits;
165
22.9k
}
166
167
// Based on history adjust expectations of bits per macroblock.
168
0
static void twopass_update_bpm_factor(AV1_COMP *cpi, int rate_err_tol) {
169
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
170
0
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
171
172
  // Based on recent history adjust expectations of bits per macroblock.
173
0
  double rate_err_factor = 1.0;
174
0
  const double adj_limit = AOMMAX(0.2, (double)(100 - rate_err_tol) / 200.0);
175
0
  const double min_fac = 1.0 - adj_limit;
176
0
  const double max_fac = 1.0 + adj_limit;
177
178
#if CONFIG_THREE_PASS
179
  if (cpi->third_pass_ctx && cpi->third_pass_ctx->frame_info_count > 0) {
180
    int64_t actual_bits = 0;
181
    int64_t target_bits = 0;
182
    double factor = 0.0;
183
    int count = 0;
184
    for (int i = 0; i < cpi->third_pass_ctx->frame_info_count; i++) {
185
      actual_bits += cpi->third_pass_ctx->frame_info[i].actual_bits;
186
      target_bits += cpi->third_pass_ctx->frame_info[i].bits_allocated;
187
      factor += cpi->third_pass_ctx->frame_info[i].bpm_factor;
188
      count++;
189
    }
190
191
    if (count == 0) {
192
      factor = 1.0;
193
    } else {
194
      factor /= (double)count;
195
    }
196
197
    factor *= (double)actual_bits / DOUBLE_DIVIDE_CHECK((double)target_bits);
198
199
    if ((twopass->bpm_factor <= 1 && factor < twopass->bpm_factor) ||
200
        (twopass->bpm_factor >= 1 && factor > twopass->bpm_factor)) {
201
      twopass->bpm_factor = fclamp(factor, min_fac, max_fac);
202
    }
203
  }
204
#endif  // CONFIG_THREE_PASS
205
206
0
  int err_estimate = p_rc->rate_error_estimate;
207
0
  int64_t total_actual_bits = p_rc->total_actual_bits;
208
0
  double rolling_arf_group_actual_bits =
209
0
      (double)twopass->rolling_arf_group_actual_bits;
210
0
  double rolling_arf_group_target_bits =
211
0
      (double)twopass->rolling_arf_group_target_bits;
212
213
#if CONFIG_FPMT_TEST
214
  const int is_parallel_frame =
215
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 ? 1 : 0;
216
  const int simulate_parallel_frame =
217
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE
218
          ? is_parallel_frame
219
          : 0;
220
  total_actual_bits = simulate_parallel_frame ? p_rc->temp_total_actual_bits
221
                                              : p_rc->total_actual_bits;
222
  rolling_arf_group_target_bits =
223
      (double)(simulate_parallel_frame
224
                   ? p_rc->temp_rolling_arf_group_target_bits
225
                   : twopass->rolling_arf_group_target_bits);
226
  rolling_arf_group_actual_bits =
227
      (double)(simulate_parallel_frame
228
                   ? p_rc->temp_rolling_arf_group_actual_bits
229
                   : twopass->rolling_arf_group_actual_bits);
230
  err_estimate = simulate_parallel_frame ? p_rc->temp_rate_error_estimate
231
                                         : p_rc->rate_error_estimate;
232
#endif
233
234
0
  if ((p_rc->bits_off_target && total_actual_bits > 0) &&
235
0
      (rolling_arf_group_target_bits >= 1.0)) {
236
0
    if (rolling_arf_group_actual_bits > rolling_arf_group_target_bits) {
237
0
      double error_fraction =
238
0
          (rolling_arf_group_actual_bits - rolling_arf_group_target_bits) /
239
0
          rolling_arf_group_target_bits;
240
0
      error_fraction = (error_fraction > 1.0) ? 1.0 : error_fraction;
241
0
      rate_err_factor = 1.0 + error_fraction;
242
0
    } else {
243
0
      double error_fraction =
244
0
          (rolling_arf_group_target_bits - rolling_arf_group_actual_bits) /
245
0
          rolling_arf_group_target_bits;
246
0
      rate_err_factor = 1.0 - error_fraction;
247
0
    }
248
249
0
    rate_err_factor = fclamp(rate_err_factor, min_fac, max_fac);
250
0
  }
251
252
  // Is the rate control trending in the right direction. Only make
253
  // an adjustment if things are getting worse.
254
0
  if ((rate_err_factor < 1.0 && err_estimate >= 0) ||
255
0
      (rate_err_factor > 1.0 && err_estimate <= 0)) {
256
0
    twopass->bpm_factor *= rate_err_factor;
257
0
    twopass->bpm_factor = fclamp(twopass->bpm_factor, min_fac, max_fac);
258
0
  }
259
0
}
260
261
static const double q_div_term[(QINDEX_RANGE >> 4) + 1] = {
262
  18.0, 30.0, 38.0, 44.0, 47.0, 50.0, 52.0, 54.0, 56.0,
263
  58.0, 60.0, 62.0, 64.0, 66.0, 68.0, 70.0, 72.0
264
};
265
266
0
#define EPMB_SCALER 1250000
267
0
static double calc_correction_factor(double err_per_mb, int q) {
268
0
  double power_term = 0.90;
269
0
  const int index = q >> 4;
270
0
  const double divisor =
271
0
      q_div_term[index] +
272
0
      (((q_div_term[index + 1] - q_div_term[index]) * (q % 16)) / 16.0);
273
0
  double error_term = EPMB_SCALER * pow(err_per_mb, power_term);
274
0
  return error_term / divisor;
275
0
}
276
277
// Similar to find_qindex_by_rate() function in ratectrl.c, but includes
278
// calculation of a correction_factor.
279
static int find_qindex_by_rate_with_correction(uint64_t desired_bits_per_mb,
280
                                               aom_bit_depth_t bit_depth,
281
                                               double error_per_mb,
282
                                               double group_weight_factor,
283
                                               int best_qindex,
284
0
                                               int worst_qindex) {
285
0
  assert(best_qindex <= worst_qindex);
286
0
  int low = best_qindex;
287
0
  int high = worst_qindex;
288
289
0
  while (low < high) {
290
0
    const int mid = (low + high) >> 1;
291
0
    const double q_factor = calc_correction_factor(error_per_mb, mid);
292
0
    const double q = av1_convert_qindex_to_q(mid, bit_depth);
293
0
    const uint64_t mid_bits_per_mb =
294
0
        (uint64_t)((q_factor * group_weight_factor) / q);
295
296
0
    if (mid_bits_per_mb > desired_bits_per_mb) {
297
0
      low = mid + 1;
298
0
    } else {
299
0
      high = mid;
300
0
    }
301
0
  }
302
0
  return low;
303
0
}
304
305
/*!\brief Choose a target maximum Q for a group of frames
306
 *
307
 * \ingroup rate_control
308
 *
309
 * This function is used to estimate a suitable maximum Q for a
310
 * group of frames. Inititally it is called to get a crude estimate
311
 * for the whole clip. It is then called for each ARF/GF group to get
312
 * a revised estimate for that group.
313
 *
314
 * \param[in]    cpi                 Top-level encoder structure
315
 * \param[in]    av_frame_err        The average per frame coded error score
316
 *                                   for frames making up this section/group.
317
 * \param[in]    inactive_zone       Used to mask off /ignore part of the
318
 *                                   frame. The most common use case is where
319
 *                                   a wide format video (e.g. 16:9) is
320
 *                                   letter-boxed into a more square format.
321
 *                                   Here we want to ignore the bands at the
322
 *                                   top and bottom.
323
 * \param[in]    av_target_bandwidth The target bits per frame
324
 *
325
 * \return The maximum Q for frames in the group.
326
 */
327
static int get_twopass_worst_quality(AV1_COMP *cpi, const double av_frame_err,
328
                                     double inactive_zone,
329
0
                                     int av_target_bandwidth) {
330
0
  const RATE_CONTROL *const rc = &cpi->rc;
331
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
332
0
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
333
0
  inactive_zone = fclamp(inactive_zone, 0.0, 0.9999);
334
335
0
  if (av_target_bandwidth <= 0) {
336
0
    return rc->worst_quality;  // Highest value allowed
337
0
  } else {
338
0
    const int num_mbs = (oxcf->resize_cfg.resize_mode != RESIZE_NONE)
339
0
                            ? cpi->initial_mbs
340
0
                            : cpi->common.mi_params.MBs;
341
0
    const int active_mbs = AOMMAX(1, num_mbs - (int)(num_mbs * inactive_zone));
342
0
    const double av_err_per_mb = av_frame_err / (1.0 - inactive_zone);
343
0
    const uint64_t target_norm_bits_per_mb =
344
0
        ((uint64_t)av_target_bandwidth << BPER_MB_NORMBITS) / active_mbs;
345
0
    int rate_err_tol = AOMMIN(rc_cfg->under_shoot_pct, rc_cfg->over_shoot_pct);
346
0
    const double size_factor =
347
0
        (active_mbs < 500) ? 0.925 : ((active_mbs > 3000) ? 1.05 : 1.0);
348
0
    const double speed_factor =
349
0
        AOMMIN(1.02, (0.975 + (0.005 * cpi->oxcf.speed)));
350
351
    // Update bpm correction factor based on previous GOP rate error.
352
0
    twopass_update_bpm_factor(cpi, rate_err_tol);
353
354
    // Try and pick a max Q that will be high enough to encode the
355
    // content at the given rate.
356
0
    int q = find_qindex_by_rate_with_correction(
357
0
        target_norm_bits_per_mb, cpi->common.seq_params->bit_depth,
358
0
        av_err_per_mb,
359
0
        cpi->ppi->twopass.bpm_factor * speed_factor * size_factor,
360
0
        rc->best_quality, rc->worst_quality);
361
362
    // Restriction on active max q for constrained quality mode.
363
0
    if (rc_cfg->mode == AOM_CQ) q = AOMMAX(q, rc_cfg->cq_level);
364
0
    return q;
365
0
  }
366
0
}
367
368
35.1k
#define INTRA_PART 0.005
369
#define DEFAULT_DECAY_LIMIT 0.75
370
66.7k
#define LOW_SR_DIFF_TRHESH 0.01
371
66.7k
#define NCOUNT_FRAME_II_THRESH 5.0
372
66.7k
#define LOW_CODED_ERR_PER_MB 0.01
373
374
/* This function considers how the quality of prediction may be deteriorating
375
 * with distance. It comapres the coded error for the last frame and the
376
 * second reference frame (usually two frames old) and also applies a factor
377
 * based on the extent of INTRA coding.
378
 *
379
 * The decay factor is then used to reduce the contribution of frames further
380
 * from the alt-ref or golden frame, to the bitframe boost calculation for that
381
 * alt-ref or golden frame.
382
 */
383
66.7k
static double get_sr_decay_rate(const FIRSTPASS_STATS *frame) {
384
66.7k
  double sr_diff = (frame->sr_coded_error - frame->coded_error);
385
66.7k
  double sr_decay = 1.0;
386
66.7k
  double modified_pct_inter;
387
66.7k
  double modified_pcnt_intra;
388
389
66.7k
  modified_pct_inter = frame->pcnt_inter;
390
66.7k
  if ((frame->coded_error > LOW_CODED_ERR_PER_MB) &&
391
66.7k
      ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
392
66.7k
       (double)NCOUNT_FRAME_II_THRESH)) {
393
66.3k
    modified_pct_inter = frame->pcnt_inter - frame->pcnt_neutral;
394
66.3k
  }
395
66.7k
  modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
396
397
66.7k
  if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
398
35.1k
    double sr_diff_part = ((sr_diff * 0.25) / frame->intra_error);
399
35.1k
    sr_decay = 1.0 - sr_diff_part - (INTRA_PART * modified_pcnt_intra);
400
35.1k
  }
401
66.7k
  return AOMMAX(sr_decay, DEFAULT_DECAY_LIMIT);
402
66.7k
}
403
404
// This function gives an estimate of how badly we believe the prediction
405
// quality is decaying from frame to frame.
406
7.38k
static double get_zero_motion_factor(const FIRSTPASS_STATS *frame) {
407
7.38k
  const double zero_motion_pct = frame->pcnt_inter - frame->pcnt_motion;
408
7.38k
  double sr_decay = get_sr_decay_rate(frame);
409
7.38k
  return AOMMIN(sr_decay, zero_motion_pct);
410
7.38k
}
411
412
59.4k
#define DEFAULT_ZM_FACTOR 0.5
413
59.4k
static double get_prediction_decay_rate(const FIRSTPASS_STATS *frame_stats) {
414
59.4k
  const double sr_decay_rate = get_sr_decay_rate(frame_stats);
415
59.4k
  double zero_motion_factor =
416
59.4k
      DEFAULT_ZM_FACTOR * (frame_stats->pcnt_inter - frame_stats->pcnt_motion);
417
418
  // Clamp value to range 0.0 to 1.0
419
  // This should happen anyway if input values are sensibly clamped but checked
420
  // here just in case.
421
59.4k
  if (zero_motion_factor > 1.0)
422
0
    zero_motion_factor = 1.0;
423
59.4k
  else if (zero_motion_factor < 0.0)
424
0
    zero_motion_factor = 0.0;
425
426
59.4k
  return AOMMAX(zero_motion_factor,
427
59.4k
                (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
428
59.4k
}
429
430
// Function to test for a condition where a complex transition is followed
431
// by a static section. For example in slide shows where there is a fade
432
// between slides. This is to help with more optimal kf and gf positioning.
433
static int detect_transition_to_still(const FIRSTPASS_INFO *firstpass_info,
434
                                      int next_stats_index,
435
                                      const int min_gf_interval,
436
                                      const int frame_interval,
437
                                      const int still_interval,
438
                                      const double loop_decay_rate,
439
23.2k
                                      const double last_decay_rate) {
440
  // Break clause to detect very still sections after motion
441
  // For example a static image after a fade or other transition
442
  // instead of a clean scene cut.
443
23.2k
  if (frame_interval > min_gf_interval && loop_decay_rate >= 0.999 &&
444
0
      last_decay_rate < 0.9) {
445
0
    int stats_left =
446
0
        av1_firstpass_info_future_count(firstpass_info, next_stats_index);
447
0
    if (stats_left >= still_interval) {
448
0
      int j;
449
      // Look ahead a few frames to see if static condition persists...
450
0
      for (j = 0; j < still_interval; ++j) {
451
0
        const FIRSTPASS_STATS *stats =
452
0
            av1_firstpass_info_peek(firstpass_info, next_stats_index + j);
453
0
        if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
454
0
      }
455
      // Only if it does do we signal a transition to still.
456
0
      return j == still_interval;
457
0
    }
458
0
  }
459
23.2k
  return 0;
460
23.2k
}
461
462
// This function detects a flash through the high relative pcnt_second_ref
463
// score in the frame following a flash frame. The offset passed in should
464
// reflect this.
465
static int detect_flash(const TWO_PASS *twopass,
466
74.1k
                        const TWO_PASS_FRAME *twopass_frame, const int offset) {
467
74.1k
  const FIRSTPASS_STATS *const next_frame =
468
74.1k
      read_frame_stats(twopass, twopass_frame, offset);
469
470
  // What we are looking for here is a situation where there is a
471
  // brief break in prediction (such as a flash) but subsequent frames
472
  // are reasonably well predicted by an earlier (pre flash) frame.
473
  // The recovery after a flash is indicated by a high pcnt_second_ref
474
  // compared to pcnt_inter.
475
74.1k
  return next_frame != NULL &&
476
51.3k
         next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
477
5.77k
         next_frame->pcnt_second_ref >= 0.5;
478
74.1k
}
479
480
// Update the motion related elements to the GF arf boost calculation.
481
static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
482
                                          GF_GROUP_STATS *gf_stats, double f_w,
483
45.0k
                                          double f_h) {
484
45.0k
  const double pct = stats->pcnt_motion;
485
486
  // Accumulate Motion In/Out of frame stats.
487
45.0k
  gf_stats->this_frame_mv_in_out = stats->mv_in_out_count * pct;
488
45.0k
  gf_stats->mv_in_out_accumulator += gf_stats->this_frame_mv_in_out;
489
45.0k
  gf_stats->abs_mv_in_out_accumulator += fabs(gf_stats->this_frame_mv_in_out);
490
491
  // Accumulate a measure of how uniform (or conversely how random) the motion
492
  // field is (a ratio of abs(mv) / mv).
493
45.0k
  if (pct > 0.05) {
494
7.31k
    const double mvr_ratio =
495
7.31k
        fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
496
7.31k
    const double mvc_ratio =
497
7.31k
        fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
498
499
7.31k
    gf_stats->mv_ratio_accumulator +=
500
7.31k
        pct *
501
7.31k
        (mvr_ratio < stats->mvr_abs * f_h ? mvr_ratio : stats->mvr_abs * f_h);
502
7.31k
    gf_stats->mv_ratio_accumulator +=
503
7.31k
        pct *
504
7.31k
        (mvc_ratio < stats->mvc_abs * f_w ? mvc_ratio : stats->mvc_abs * f_w);
505
7.31k
  }
506
45.0k
}
507
508
static void accumulate_this_frame_stats(const FIRSTPASS_STATS *stats,
509
                                        const double mod_frame_err,
510
14.9k
                                        GF_GROUP_STATS *gf_stats) {
511
14.9k
  gf_stats->gf_group_err += mod_frame_err;
512
14.9k
#if GROUP_ADAPTIVE_MAXQ
513
14.9k
  gf_stats->gf_group_raw_error += stats->coded_error;
514
14.9k
#endif
515
14.9k
  gf_stats->gf_group_skip_pct += stats->intra_skip_pct;
516
14.9k
  gf_stats->gf_group_inactive_zone_rows += stats->inactive_zone_rows;
517
14.9k
}
518
519
static void accumulate_next_frame_stats(const FIRSTPASS_STATS *stats,
520
                                        const int flash_detected,
521
                                        const int frames_since_key,
522
                                        const int cur_idx,
523
                                        GF_GROUP_STATS *gf_stats, int f_w,
524
15.1k
                                        int f_h) {
525
15.1k
  accumulate_frame_motion_stats(stats, gf_stats, f_w, f_h);
526
  // sum up the metric values of current gf group
527
15.1k
  gf_stats->avg_sr_coded_error += stats->sr_coded_error;
528
15.1k
  gf_stats->avg_pcnt_second_ref += stats->pcnt_second_ref;
529
15.1k
  gf_stats->avg_new_mv_count += stats->new_mv_count;
530
15.1k
  gf_stats->avg_wavelet_energy += stats->frame_avg_wavelet_energy;
531
15.1k
  if (fabs(stats->raw_error_stdev) > 0.000001) {
532
10.8k
    gf_stats->non_zero_stdev_count++;
533
10.8k
    gf_stats->avg_raw_err_stdev += stats->raw_error_stdev;
534
10.8k
  }
535
536
  // Accumulate the effect of prediction quality decay
537
15.1k
  if (!flash_detected) {
538
14.9k
    gf_stats->last_loop_decay_rate = gf_stats->loop_decay_rate;
539
14.9k
    gf_stats->loop_decay_rate = get_prediction_decay_rate(stats);
540
541
14.9k
    gf_stats->decay_accumulator =
542
14.9k
        gf_stats->decay_accumulator * gf_stats->loop_decay_rate;
543
544
    // Monitor for static sections.
545
14.9k
    if ((frames_since_key + cur_idx - 1) > 1) {
546
950
      gf_stats->zero_motion_accumulator = AOMMIN(
547
950
          gf_stats->zero_motion_accumulator, get_zero_motion_factor(stats));
548
950
    }
549
14.9k
  }
550
15.1k
}
551
552
22.9k
static void average_gf_stats(const int total_frame, GF_GROUP_STATS *gf_stats) {
553
22.9k
  if (total_frame) {
554
22.9k
    gf_stats->avg_sr_coded_error /= total_frame;
555
22.9k
    gf_stats->avg_pcnt_second_ref /= total_frame;
556
22.9k
    gf_stats->avg_new_mv_count /= total_frame;
557
22.9k
    gf_stats->avg_wavelet_energy /= total_frame;
558
22.9k
  }
559
560
22.9k
  if (gf_stats->non_zero_stdev_count)
561
3.46k
    gf_stats->avg_raw_err_stdev /= gf_stats->non_zero_stdev_count;
562
22.9k
}
563
564
31.4k
#define BOOST_FACTOR 12.5
565
38.1k
static double baseline_err_per_mb(const FRAME_INFO *frame_info) {
566
38.1k
  unsigned int screen_area = frame_info->frame_height * frame_info->frame_width;
567
568
  // Use a different error per mb factor for calculating boost for
569
  //  different formats.
570
38.1k
  if (screen_area <= 640 * 360) {
571
38.1k
    return 500.0;
572
38.1k
  } else {
573
0
    return 1000.0;
574
0
  }
575
38.1k
}
576
577
static double calc_frame_boost(const PRIMARY_RATE_CONTROL *p_rc,
578
                               const FRAME_INFO *frame_info,
579
                               const FIRSTPASS_STATS *this_frame,
580
29.8k
                               double this_frame_mv_in_out, double max_boost) {
581
29.8k
  double frame_boost;
582
29.8k
  const double lq = av1_convert_qindex_to_q(p_rc->avg_frame_qindex[INTER_FRAME],
583
29.8k
                                            frame_info->bit_depth);
584
29.8k
  const double boost_q_correction = AOMMIN((0.5 + (lq * 0.015)), 1.5);
585
29.8k
  const double active_area = calculate_active_area(frame_info, this_frame);
586
587
  // Underlying boost factor is based on inter error ratio.
588
29.8k
  frame_boost = AOMMAX(baseline_err_per_mb(frame_info) * active_area,
589
29.8k
                       this_frame->intra_error * active_area) /
590
29.8k
                DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
591
29.8k
  frame_boost = frame_boost * BOOST_FACTOR * boost_q_correction;
592
593
  // Increase boost for frames where new data coming into frame (e.g. zoom out).
594
  // Slightly reduce boost if there is a net balance of motion out of the frame
595
  // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
596
29.8k
  if (this_frame_mv_in_out > 0.0)
597
3.13k
    frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
598
  // In the extreme case the boost is halved.
599
26.7k
  else
600
26.7k
    frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
601
602
29.8k
  return AOMMIN(frame_boost, max_boost * boost_q_correction);
603
29.8k
}
604
605
static double calc_kf_frame_boost(const PRIMARY_RATE_CONTROL *p_rc,
606
                                  const FRAME_INFO *frame_info,
607
                                  const FIRSTPASS_STATS *this_frame,
608
7.28k
                                  double *sr_accumulator, double max_boost) {
609
7.28k
  double frame_boost;
610
7.28k
  const double lq = av1_convert_qindex_to_q(p_rc->avg_frame_qindex[INTER_FRAME],
611
7.28k
                                            frame_info->bit_depth);
612
7.28k
  const double boost_q_correction = AOMMIN((0.50 + (lq * 0.015)), 2.00);
613
7.28k
  const double active_area = calculate_active_area(frame_info, this_frame);
614
615
  // Underlying boost factor is based on inter error ratio.
616
7.28k
  frame_boost = AOMMAX(baseline_err_per_mb(frame_info) * active_area,
617
7.28k
                       this_frame->intra_error * active_area) /
618
7.28k
                DOUBLE_DIVIDE_CHECK(
619
7.28k
                    (this_frame->coded_error + *sr_accumulator) * active_area);
620
621
  // Update the accumulator for second ref error difference.
622
  // This is intended to give an indication of how much the coded error is
623
  // increasing over time.
624
7.28k
  *sr_accumulator += (this_frame->sr_coded_error - this_frame->coded_error);
625
7.28k
  *sr_accumulator = AOMMAX(0.0, *sr_accumulator);
626
627
  // Q correction and scaling
628
  // The 40.0 value here is an experimentally derived baseline minimum.
629
  // This value is in line with the minimum per frame boost in the alt_ref
630
  // boost calculation.
631
7.28k
  frame_boost = ((frame_boost + 40.0) * boost_q_correction);
632
633
7.28k
  return AOMMIN(frame_boost, max_boost * boost_q_correction);
634
7.28k
}
635
636
static int get_projected_gfu_boost(const PRIMARY_RATE_CONTROL *p_rc,
637
                                   int gfu_boost, int frames_to_project,
638
45.8k
                                   int num_stats_used_for_gfu_boost) {
639
  /*
640
   * If frames_to_project is equal to num_stats_used_for_gfu_boost,
641
   * it means that gfu_boost was calculated over frames_to_project to
642
   * begin with(ie; all stats required were available), hence return
643
   * the original boost.
644
   */
645
45.8k
  if (num_stats_used_for_gfu_boost >= frames_to_project) return gfu_boost;
646
647
0
  double min_boost_factor = sqrt(p_rc->baseline_gf_interval);
648
  // Get the current tpl factor (number of frames = frames_to_project).
649
0
  double tpl_factor = av1_get_gfu_boost_projection_factor(
650
0
      min_boost_factor, MAX_GFUBOOST_FACTOR, frames_to_project);
651
  // Get the tpl factor when number of frames = num_stats_used_for_prior_boost.
652
0
  double tpl_factor_num_stats = av1_get_gfu_boost_projection_factor(
653
0
      min_boost_factor, MAX_GFUBOOST_FACTOR, num_stats_used_for_gfu_boost);
654
0
  int projected_gfu_boost =
655
0
      (int)rint((tpl_factor * gfu_boost) / tpl_factor_num_stats);
656
0
  return projected_gfu_boost;
657
45.8k
}
658
659
29.8k
#define GF_MAX_BOOST 90.0
660
55.6k
#define GF_MIN_BOOST 50
661
28.5k
#define MIN_DECAY_FACTOR 0.01
662
int av1_calc_arf_boost(const TWO_PASS *twopass,
663
                       const TWO_PASS_FRAME *twopass_frame,
664
                       const PRIMARY_RATE_CONTROL *p_rc, FRAME_INFO *frame_info,
665
                       int offset, int f_frames, int b_frames,
666
                       int *num_fpstats_used, int *num_fpstats_required,
667
52.1k
                       int project_gfu_boost) {
668
52.1k
  int i;
669
52.1k
  GF_GROUP_STATS gf_stats;
670
52.1k
  init_gf_stats(&gf_stats);
671
52.1k
  double boost_score = (double)NORMAL_BOOST;
672
52.1k
  int arf_boost;
673
52.1k
  int flash_detected = 0;
674
52.1k
  if (num_fpstats_used) *num_fpstats_used = 0;
675
676
  // Search forward from the proposed arf/next gf position.
677
82.0k
  for (i = 0; i < f_frames; ++i) {
678
36.1k
    const FIRSTPASS_STATS *this_frame =
679
36.1k
        read_frame_stats(twopass, twopass_frame, i + offset);
680
36.1k
    if (this_frame == NULL) break;
681
682
    // Update the motion related elements to the boost calculation.
683
29.8k
    accumulate_frame_motion_stats(this_frame, &gf_stats,
684
29.8k
                                  frame_info->frame_width,
685
29.8k
                                  frame_info->frame_height);
686
687
    // We want to discount the flash frame itself and the recovery
688
    // frame that follows as both will have poor scores.
689
29.8k
    flash_detected = detect_flash(twopass, twopass_frame, i + offset) ||
690
29.1k
                     detect_flash(twopass, twopass_frame, i + offset + 1);
691
692
    // Accumulate the effect of prediction quality decay.
693
29.8k
    if (!flash_detected) {
694
28.5k
      gf_stats.decay_accumulator *= get_prediction_decay_rate(this_frame);
695
28.5k
      gf_stats.decay_accumulator = gf_stats.decay_accumulator < MIN_DECAY_FACTOR
696
28.5k
                                       ? MIN_DECAY_FACTOR
697
28.5k
                                       : gf_stats.decay_accumulator;
698
28.5k
    }
699
700
29.8k
    boost_score +=
701
29.8k
        gf_stats.decay_accumulator *
702
29.8k
        calc_frame_boost(p_rc, frame_info, this_frame,
703
29.8k
                         gf_stats.this_frame_mv_in_out, GF_MAX_BOOST);
704
29.8k
    if (num_fpstats_used) (*num_fpstats_used)++;
705
29.8k
  }
706
707
52.1k
  arf_boost = (int)boost_score;
708
709
  // Reset for backward looking loop.
710
52.1k
  boost_score = 0.0;
711
52.1k
  init_gf_stats(&gf_stats);
712
  // Search backward towards last gf position.
713
52.1k
  for (i = -1; i >= -b_frames; --i) {
714
0
    const FIRSTPASS_STATS *this_frame =
715
0
        read_frame_stats(twopass, twopass_frame, i + offset);
716
0
    if (this_frame == NULL) break;
717
718
    // Update the motion related elements to the boost calculation.
719
0
    accumulate_frame_motion_stats(this_frame, &gf_stats,
720
0
                                  frame_info->frame_width,
721
0
                                  frame_info->frame_height);
722
723
    // We want to discount the the flash frame itself and the recovery
724
    // frame that follows as both will have poor scores.
725
0
    flash_detected = detect_flash(twopass, twopass_frame, i + offset) ||
726
0
                     detect_flash(twopass, twopass_frame, i + offset + 1);
727
728
    // Cumulative effect of prediction quality decay.
729
0
    if (!flash_detected) {
730
0
      gf_stats.decay_accumulator *= get_prediction_decay_rate(this_frame);
731
0
      gf_stats.decay_accumulator = gf_stats.decay_accumulator < MIN_DECAY_FACTOR
732
0
                                       ? MIN_DECAY_FACTOR
733
0
                                       : gf_stats.decay_accumulator;
734
0
    }
735
736
0
    boost_score +=
737
0
        gf_stats.decay_accumulator *
738
0
        calc_frame_boost(p_rc, frame_info, this_frame,
739
0
                         gf_stats.this_frame_mv_in_out, GF_MAX_BOOST);
740
0
    if (num_fpstats_used) (*num_fpstats_used)++;
741
0
  }
742
52.1k
  arf_boost += (int)boost_score;
743
744
52.1k
  if (project_gfu_boost) {
745
45.8k
    assert(num_fpstats_required != NULL);
746
45.8k
    assert(num_fpstats_used != NULL);
747
45.8k
    *num_fpstats_required = f_frames + b_frames;
748
45.8k
    arf_boost = get_projected_gfu_boost(p_rc, arf_boost, *num_fpstats_required,
749
45.8k
                                        *num_fpstats_used);
750
45.8k
  }
751
752
52.1k
  if (arf_boost < ((b_frames + f_frames) * GF_MIN_BOOST))
753
3.51k
    arf_boost = ((b_frames + f_frames) * GF_MIN_BOOST);
754
755
52.1k
  return arf_boost;
756
52.1k
}
757
758
// Calculate a section intra ratio used in setting max loop filter.
759
static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
760
                                         const FIRSTPASS_STATS *end,
761
11.4k
                                         int section_length) {
762
11.4k
  const FIRSTPASS_STATS *s = begin;
763
11.4k
  double intra_error = 0.0;
764
11.4k
  double coded_error = 0.0;
765
11.4k
  int i = 0;
766
767
20.6k
  while (s < end && i < section_length) {
768
9.18k
    intra_error += s->intra_error;
769
9.18k
    coded_error += s->coded_error;
770
9.18k
    ++s;
771
9.18k
    ++i;
772
9.18k
  }
773
774
11.4k
  return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
775
11.4k
}
776
777
/*!\brief Calculates the bit target for this GF/ARF group
778
 *
779
 * \ingroup rate_control
780
 *
781
 * Calculates the total bits to allocate in this GF/ARF group.
782
 *
783
 * \param[in]    cpi              Top-level encoder structure
784
 * \param[in]    gf_group_err     Cumulative coded error score for the
785
 *                                frames making up this group.
786
 *
787
 * \return The target total number of bits for this GF/ARF group.
788
 */
789
static int64_t calculate_total_gf_group_bits(AV1_COMP *cpi,
790
22.9k
                                             double gf_group_err) {
791
22.9k
  const RATE_CONTROL *const rc = &cpi->rc;
792
22.9k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
793
22.9k
  const TWO_PASS *const twopass = &cpi->ppi->twopass;
794
22.9k
  const int max_bits = frame_max_bits(rc, &cpi->oxcf);
795
22.9k
  int64_t total_group_bits;
796
797
  // Calculate the bits to be allocated to the group as a whole.
798
22.9k
  if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
799
0
    total_group_bits = (int64_t)(twopass->kf_group_bits *
800
0
                                 (gf_group_err / twopass->kf_group_error_left));
801
22.9k
  } else {
802
22.9k
    total_group_bits = 0;
803
22.9k
  }
804
805
  // Clamp odd edge cases.
806
22.9k
  total_group_bits = (total_group_bits < 0) ? 0
807
22.9k
                     : (total_group_bits > twopass->kf_group_bits)
808
22.9k
                         ? twopass->kf_group_bits
809
22.9k
                         : total_group_bits;
810
811
  // Clip based on user supplied data rate variability limit.
812
22.9k
  if (total_group_bits > (int64_t)max_bits * p_rc->baseline_gf_interval)
813
0
    total_group_bits = (int64_t)max_bits * p_rc->baseline_gf_interval;
814
815
22.9k
  return total_group_bits;
816
22.9k
}
817
818
// Calculate the number of bits to assign to boosted frames in a group.
819
static int calculate_boost_bits(int frame_count, int boost,
820
34.4k
                                int64_t total_group_bits) {
821
34.4k
  int allocation_chunks;
822
823
  // return 0 for invalid inputs (could arise e.g. through rounding errors)
824
34.4k
  if (!boost || (total_group_bits <= 0)) return 0;
825
826
0
  if (frame_count <= 0) return (int)(AOMMIN(total_group_bits, INT_MAX));
827
828
0
  allocation_chunks = (frame_count * 100) + boost;
829
830
  // Prevent overflow.
831
0
  if (boost > 1023) {
832
0
    int divisor = boost >> 10;
833
0
    boost /= divisor;
834
0
    allocation_chunks /= divisor;
835
0
  }
836
837
  // Calculate the number of extra bits for use in the boosted frame or frames.
838
0
  return AOMMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
839
0
                0);
840
0
}
841
842
// Calculate the boost factor based on the number of bits assigned, i.e. the
843
// inverse of calculate_boost_bits().
844
static int calculate_boost_factor(int frame_count, int bits,
845
0
                                  int64_t total_group_bits) {
846
0
  return (int)(100.0 * frame_count * bits / (total_group_bits - bits));
847
0
}
848
849
// Reduce the number of bits assigned to keyframe or arf if necessary, to
850
// prevent bitrate spikes that may break level constraints.
851
// frame_type: 0: keyframe; 1: arf.
852
static int adjust_boost_bits_for_target_level(const AV1_COMP *const cpi,
853
                                              RATE_CONTROL *const rc,
854
                                              int bits_assigned,
855
                                              int64_t group_bits,
856
34.4k
                                              int frame_type) {
857
34.4k
  const AV1_COMMON *const cm = &cpi->common;
858
34.4k
  const SequenceHeader *const seq_params = cm->seq_params;
859
34.4k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
860
34.4k
  const int temporal_layer_id = cm->temporal_layer_id;
861
34.4k
  const int spatial_layer_id = cm->spatial_layer_id;
862
68.8k
  for (int index = 0; index < seq_params->operating_points_cnt_minus_1 + 1;
863
34.4k
       ++index) {
864
34.4k
    if (!is_in_operating_point(seq_params->operating_point_idc[index],
865
34.4k
                               temporal_layer_id, spatial_layer_id)) {
866
0
      continue;
867
0
    }
868
869
34.4k
    const AV1_LEVEL target_level =
870
34.4k
        cpi->ppi->level_params.target_seq_level_idx[index];
871
34.4k
    if (target_level >= SEQ_LEVELS) continue;
872
873
34.4k
    assert(is_valid_seq_level_idx(target_level));
874
875
0
    const double level_bitrate_limit = av1_get_max_bitrate_for_level(
876
0
        target_level, seq_params->tier[0], seq_params->profile);
877
0
    const int target_bits_per_frame =
878
0
        (int)(level_bitrate_limit / cpi->framerate);
879
0
    if (frame_type == 0) {
880
      // Maximum bits for keyframe is 8 times the target_bits_per_frame.
881
0
      const int level_enforced_max_kf_bits = target_bits_per_frame * 8;
882
0
      if (bits_assigned > level_enforced_max_kf_bits) {
883
0
        const int frames = rc->frames_to_key - 1;
884
0
        p_rc->kf_boost = calculate_boost_factor(
885
0
            frames, level_enforced_max_kf_bits, group_bits);
886
0
        bits_assigned =
887
0
            calculate_boost_bits(frames, p_rc->kf_boost, group_bits);
888
0
      }
889
0
    } else if (frame_type == 1) {
890
      // Maximum bits for arf is 4 times the target_bits_per_frame.
891
0
      const int level_enforced_max_arf_bits = target_bits_per_frame * 4;
892
0
      if (bits_assigned > level_enforced_max_arf_bits) {
893
0
        p_rc->gfu_boost =
894
0
            calculate_boost_factor(p_rc->baseline_gf_interval,
895
0
                                   level_enforced_max_arf_bits, group_bits);
896
0
        bits_assigned = calculate_boost_bits(p_rc->baseline_gf_interval,
897
0
                                             p_rc->gfu_boost, group_bits);
898
0
      }
899
0
    } else {
900
0
      assert(0);
901
0
    }
902
0
  }
903
904
34.4k
  return bits_assigned;
905
34.4k
}
906
907
// Allocate bits to each frame in a GF / ARF group
908
static void allocate_gf_group_bits(GF_GROUP *gf_group,
909
                                   PRIMARY_RATE_CONTROL *const p_rc,
910
                                   RATE_CONTROL *const rc,
911
                                   int64_t gf_group_bits, int gf_arf_bits,
912
22.9k
                                   int key_frame, int use_arf) {
913
22.9k
  static const double layer_fraction[MAX_ARF_LAYERS + 1] = { 1.0,  0.70, 0.55,
914
22.9k
                                                             0.60, 0.60, 1.0,
915
22.9k
                                                             1.0 };
916
22.9k
  int64_t total_group_bits = gf_group_bits;
917
22.9k
  int base_frame_bits;
918
22.9k
  const int gf_group_size = gf_group->size;
919
22.9k
  int layer_frames[MAX_ARF_LAYERS + 1] = { 0 };
920
921
  // For key frames the frame target rate is already set and it
922
  // is also the golden frame.
923
  // === [frame_index == 0] ===
924
22.9k
  int frame_index = !!key_frame;
925
926
  // Subtract the extra bits set aside for ARF frames from the Group Total
927
22.9k
  if (use_arf) total_group_bits -= gf_arf_bits;
928
929
22.9k
  int num_frames =
930
22.9k
      AOMMAX(1, p_rc->baseline_gf_interval - (rc->frames_since_key == 0));
931
22.9k
  base_frame_bits = (int)(total_group_bits / num_frames);
932
933
  // Check the number of frames in each layer in case we have a
934
  // non standard group length.
935
22.9k
  int max_arf_layer = gf_group->max_layer_depth - 1;
936
37.8k
  for (int idx = frame_index; idx < gf_group_size; ++idx) {
937
14.9k
    if ((gf_group->update_type[idx] == ARF_UPDATE) ||
938
14.9k
        (gf_group->update_type[idx] == INTNL_ARF_UPDATE)) {
939
0
      layer_frames[gf_group->layer_depth[idx]]++;
940
0
    }
941
14.9k
  }
942
943
  // Allocate extra bits to each ARF layer
944
22.9k
  int i;
945
22.9k
  int layer_extra_bits[MAX_ARF_LAYERS + 1] = { 0 };
946
22.9k
  assert(max_arf_layer <= MAX_ARF_LAYERS);
947
27.3k
  for (i = 1; i <= max_arf_layer; ++i) {
948
4.38k
    double fraction = (i == max_arf_layer) ? 1.0 : layer_fraction[i];
949
4.38k
    layer_extra_bits[i] =
950
4.38k
        (int)((gf_arf_bits * fraction) / AOMMAX(1, layer_frames[i]));
951
4.38k
    gf_arf_bits -= (int)(gf_arf_bits * fraction);
952
4.38k
  }
953
954
  // Now combine ARF layer and baseline bits to give total bits for each frame.
955
22.9k
  int arf_extra_bits;
956
37.8k
  for (int idx = frame_index; idx < gf_group_size; ++idx) {
957
14.9k
    switch (gf_group->update_type[idx]) {
958
0
      case ARF_UPDATE:
959
0
      case INTNL_ARF_UPDATE:
960
0
        arf_extra_bits = layer_extra_bits[gf_group->layer_depth[idx]];
961
0
        gf_group->bit_allocation[idx] =
962
0
            (base_frame_bits > INT_MAX - arf_extra_bits)
963
0
                ? INT_MAX
964
0
                : (base_frame_bits + arf_extra_bits);
965
0
        break;
966
0
      case INTNL_OVERLAY_UPDATE:
967
0
      case OVERLAY_UPDATE: gf_group->bit_allocation[idx] = 0; break;
968
14.9k
      default: gf_group->bit_allocation[idx] = base_frame_bits; break;
969
14.9k
    }
970
14.9k
  }
971
972
  // Set the frame following the current GOP to 0 bit allocation. For ARF
973
  // groups, this next frame will be overlay frame, which is the first frame
974
  // in the next GOP. For GF group, next GOP will overwrite the rate allocation.
975
  // Setting this frame to use 0 bit (of out the current GOP budget) will
976
  // simplify logics in reference frame management.
977
22.9k
  if (gf_group_size < MAX_STATIC_GF_GROUP_LENGTH)
978
22.9k
    gf_group->bit_allocation[gf_group_size] = 0;
979
22.9k
}
980
981
// Returns true if KF group and GF group both are almost completely static.
982
static inline int is_almost_static(double gf_zero_motion, int kf_zero_motion,
983
22.9k
                                   int is_lap_enabled) {
984
22.9k
  if (is_lap_enabled) {
985
    /*
986
     * when LAP enabled kf_zero_motion is not reliable, so use strict
987
     * constraint on gf_zero_motion.
988
     */
989
22.9k
    return (gf_zero_motion >= 0.999);
990
22.9k
  } else {
991
0
    return (gf_zero_motion >= 0.995) &&
992
0
           (kf_zero_motion >= STATIC_KF_GROUP_THRESH);
993
0
  }
994
22.9k
}
995
996
0
#define ARF_ABS_ZOOM_THRESH 4.4
997
static inline int detect_gf_cut(AV1_COMP *cpi, int frame_index, int cur_start,
998
                                int flash_detected, int active_max_gf_interval,
999
                                int active_min_gf_interval,
1000
7.47k
                                GF_GROUP_STATS *gf_stats) {
1001
7.47k
  RATE_CONTROL *const rc = &cpi->rc;
1002
7.47k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
1003
7.47k
  AV1_COMMON *const cm = &cpi->common;
1004
  // Motion breakout threshold for loop below depends on image size.
1005
7.47k
  const double mv_ratio_accumulator_thresh = (cm->height + cm->width) / 4.0;
1006
1007
7.47k
  if (!flash_detected) {
1008
    // Break clause to detect very still sections after motion. For example,
1009
    // a static image after a fade or other transition.
1010
1011
    // TODO(angiebird): This is a temporary change, we will avoid using
1012
    // twopass_frame.stats_in in the follow-up CL
1013
7.32k
    int index = (int)(cpi->twopass_frame.stats_in -
1014
7.32k
                      twopass->stats_buf_ctx->stats_in_start);
1015
7.32k
    if (detect_transition_to_still(&twopass->firstpass_info, index,
1016
7.32k
                                   rc->min_gf_interval, frame_index - cur_start,
1017
7.32k
                                   5, gf_stats->loop_decay_rate,
1018
7.32k
                                   gf_stats->last_loop_decay_rate)) {
1019
0
      return 1;
1020
0
    }
1021
7.32k
  }
1022
1023
  // Some conditions to breakout after min interval.
1024
7.47k
  if (frame_index - cur_start >= active_min_gf_interval &&
1025
      // If possible don't break very close to a kf
1026
0
      (rc->frames_to_key - frame_index >= rc->min_gf_interval) &&
1027
0
      ((frame_index - cur_start) & 0x01) && !flash_detected &&
1028
0
      (gf_stats->mv_ratio_accumulator > mv_ratio_accumulator_thresh ||
1029
0
       gf_stats->abs_mv_in_out_accumulator > ARF_ABS_ZOOM_THRESH)) {
1030
0
    return 1;
1031
0
  }
1032
1033
  // If almost totally static, we will not use the the max GF length later,
1034
  // so we can continue for more frames.
1035
7.47k
  if (((frame_index - cur_start) >= active_max_gf_interval + 1) &&
1036
0
      !is_almost_static(gf_stats->zero_motion_accumulator,
1037
0
                        twopass->kf_zeromotion_pct, cpi->ppi->lap_enabled)) {
1038
0
    return 1;
1039
0
  }
1040
7.47k
  return 0;
1041
7.47k
}
1042
1043
static int is_shorter_gf_interval_better(
1044
0
    AV1_COMP *cpi, const EncodeFrameParams *frame_params) {
1045
0
  const RATE_CONTROL *const rc = &cpi->rc;
1046
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1047
0
  int gop_length_decision_method = cpi->sf.tpl_sf.gop_length_decision_method;
1048
0
  int shorten_gf_interval;
1049
1050
0
  av1_tpl_preload_rc_estimate(cpi, frame_params);
1051
1052
0
  if (gop_length_decision_method == 2) {
1053
    // GF group length is decided based on GF boost and tpl stats of ARFs from
1054
    // base layer, (base+1) layer.
1055
0
    shorten_gf_interval =
1056
0
        (p_rc->gfu_boost <
1057
0
         p_rc->num_stats_used_for_gfu_boost * GF_MIN_BOOST * 1.4) &&
1058
0
        !av1_tpl_setup_stats(cpi, 3, frame_params);
1059
0
  } else {
1060
0
    int do_complete_tpl = 1;
1061
0
    GF_GROUP *const gf_group = &cpi->ppi->gf_group;
1062
0
    int is_temporal_filter_enabled =
1063
0
        (rc->frames_since_key > 0 && gf_group->arf_index > -1);
1064
1065
0
    if (gop_length_decision_method == 1) {
1066
      // Check if tpl stats of ARFs from base layer, (base+1) layer,
1067
      // (base+2) layer can decide the GF group length.
1068
0
      int gop_length_eval = av1_tpl_setup_stats(cpi, 2, frame_params);
1069
1070
0
      if (gop_length_eval != 2) {
1071
0
        do_complete_tpl = 0;
1072
0
        shorten_gf_interval = !gop_length_eval;
1073
0
      }
1074
0
    }
1075
1076
0
    if (do_complete_tpl) {
1077
      // Decide GF group length based on complete tpl stats.
1078
0
      shorten_gf_interval = !av1_tpl_setup_stats(cpi, 1, frame_params);
1079
      // Tpl stats is reused when the ARF is temporally filtered and GF
1080
      // interval is not shortened.
1081
0
      if (is_temporal_filter_enabled && !shorten_gf_interval) {
1082
0
        cpi->skip_tpl_setup_stats = 1;
1083
#if CONFIG_BITRATE_ACCURACY && !CONFIG_THREE_PASS
1084
        assert(cpi->gf_frame_index == 0);
1085
        av1_vbr_rc_update_q_index_list(&cpi->vbr_rc_info, &cpi->ppi->tpl_data,
1086
                                       gf_group,
1087
                                       cpi->common.seq_params->bit_depth);
1088
#endif  // CONFIG_BITRATE_ACCURACY
1089
0
      }
1090
0
    }
1091
0
  }
1092
0
  return shorten_gf_interval;
1093
0
}
1094
1095
#define MIN_SHRINK_LEN 6  // the minimum length of gf if we are shrinking
1096
717k
#define SMOOTH_FILT_LEN 7
1097
717k
#define HALF_FILT_LEN (SMOOTH_FILT_LEN / 2)
1098
122k
#define WINDOW_SIZE 7
1099
116k
#define HALF_WIN (WINDOW_SIZE / 2)
1100
1101
// Smooth filter intra_error and coded_error in firstpass stats.
1102
// If stats[i].is_flash==1, the ith element should not be used in the filtering.
1103
static void smooth_filter_stats(const FIRSTPASS_STATS *stats, int start_idx,
1104
                                int last_idx, double *filt_intra_err,
1105
5.66k
                                double *filt_coded_err) {
1106
  // A 7-tap gaussian smooth filter
1107
5.66k
  static const double smooth_filt[SMOOTH_FILT_LEN] = { 0.006, 0.061, 0.242,
1108
5.66k
                                                       0.383, 0.242, 0.061,
1109
5.66k
                                                       0.006 };
1110
5.66k
  int i, j;
1111
16.1k
  for (i = start_idx; i <= last_idx; i++) {
1112
10.4k
    double total_wt = 0;
1113
83.8k
    for (j = -HALF_FILT_LEN; j <= HALF_FILT_LEN; j++) {
1114
73.3k
      int idx = clamp(i + j, start_idx, last_idx);
1115
73.3k
      if (stats[idx].is_flash) continue;
1116
1117
72.3k
      filt_intra_err[i] +=
1118
72.3k
          smooth_filt[j + HALF_FILT_LEN] * stats[idx].intra_error;
1119
72.3k
      total_wt += smooth_filt[j + HALF_FILT_LEN];
1120
72.3k
    }
1121
10.4k
    if (total_wt > 0.01) {
1122
10.4k
      filt_intra_err[i] /= total_wt;
1123
10.4k
    } else {
1124
0
      filt_intra_err[i] = stats[i].intra_error;
1125
0
    }
1126
10.4k
  }
1127
16.1k
  for (i = start_idx; i <= last_idx; i++) {
1128
10.4k
    double total_wt = 0;
1129
83.8k
    for (j = -HALF_FILT_LEN; j <= HALF_FILT_LEN; j++) {
1130
73.3k
      int idx = clamp(i + j, start_idx, last_idx);
1131
      // Coded error involves idx and idx - 1.
1132
73.3k
      if (stats[idx].is_flash || (idx > 0 && stats[idx - 1].is_flash)) continue;
1133
1134
71.6k
      filt_coded_err[i] +=
1135
71.6k
          smooth_filt[j + HALF_FILT_LEN] * stats[idx].coded_error;
1136
71.6k
      total_wt += smooth_filt[j + HALF_FILT_LEN];
1137
71.6k
    }
1138
10.4k
    if (total_wt > 0.01) {
1139
10.3k
      filt_coded_err[i] /= total_wt;
1140
10.3k
    } else {
1141
148
      filt_coded_err[i] = stats[i].coded_error;
1142
148
    }
1143
10.4k
  }
1144
5.66k
}
1145
1146
// Calculate gradient
1147
static void get_gradient(const double *values, int start, int last,
1148
5.66k
                         double *grad) {
1149
5.66k
  if (start == last) {
1150
1.29k
    grad[start] = 0;
1151
1.29k
    return;
1152
1.29k
  }
1153
13.5k
  for (int i = start; i <= last; i++) {
1154
9.18k
    int prev = AOMMAX(i - 1, start);
1155
9.18k
    int next = AOMMIN(i + 1, last);
1156
9.18k
    grad[i] = (values[next] - values[prev]) / (next - prev);
1157
9.18k
  }
1158
4.36k
}
1159
1160
static int find_next_scenecut(const FIRSTPASS_STATS *const stats_start,
1161
5.66k
                              int first, int last) {
1162
  // Identify unstable areas caused by scenecuts.
1163
  // Find the max and 2nd max coded error, and the average of the rest frames.
1164
  // If there is only one frame that yields a huge coded error, it is likely a
1165
  // scenecut.
1166
5.66k
  double this_ratio, max_prev_ratio, max_next_ratio, max_prev_coded,
1167
5.66k
      max_next_coded;
1168
1169
5.66k
  if (last - first == 0) return -1;
1170
1171
13.6k
  for (int i = first; i <= last; i++) {
1172
10.5k
    if (stats_start[i].is_flash || (i > 0 && stats_start[i - 1].is_flash))
1173
288
      continue;
1174
10.2k
    double temp_intra = AOMMAX(stats_start[i].intra_error, 0.01);
1175
10.2k
    this_ratio = stats_start[i].coded_error / temp_intra;
1176
    // find the avg ratio in the preceding neighborhood
1177
10.2k
    max_prev_ratio = 0;
1178
10.2k
    max_prev_coded = 0;
1179
20.1k
    for (int j = AOMMAX(first, i - HALF_WIN); j < i; j++) {
1180
9.91k
      if (stats_start[j].is_flash || (j > 0 && stats_start[j - 1].is_flash))
1181
288
        continue;
1182
9.62k
      temp_intra = AOMMAX(stats_start[j].intra_error, 0.01);
1183
9.62k
      double temp_ratio = stats_start[j].coded_error / temp_intra;
1184
9.62k
      if (temp_ratio > max_prev_ratio) {
1185
7.04k
        max_prev_ratio = temp_ratio;
1186
7.04k
      }
1187
9.62k
      if (stats_start[j].coded_error > max_prev_coded) {
1188
7.54k
        max_prev_coded = stats_start[j].coded_error;
1189
7.54k
      }
1190
9.62k
    }
1191
    // find the avg ratio in the following neighborhood
1192
10.2k
    max_next_ratio = 0;
1193
10.2k
    max_next_coded = 0;
1194
21.3k
    for (int j = i + 1; j <= AOMMIN(i + HALF_WIN, last); j++) {
1195
11.0k
      if (stats_start[i].is_flash || (i > 0 && stats_start[i - 1].is_flash))
1196
0
        continue;
1197
11.0k
      temp_intra = AOMMAX(stats_start[j].intra_error, 0.01);
1198
11.0k
      double temp_ratio = stats_start[j].coded_error / temp_intra;
1199
11.0k
      if (temp_ratio > max_next_ratio) {
1200
4.72k
        max_next_ratio = temp_ratio;
1201
4.72k
      }
1202
11.0k
      if (stats_start[j].coded_error > max_next_coded) {
1203
4.89k
        max_next_coded = stats_start[j].coded_error;
1204
4.89k
      }
1205
11.0k
    }
1206
1207
10.2k
    if (max_prev_ratio < 0.001 && max_next_ratio < 0.001) {
1208
      // the ratios are very small, only check a small fixed threshold
1209
1.27k
      if (this_ratio < 0.02) continue;
1210
9.00k
    } else {
1211
      // check if this frame has a larger ratio than the neighborhood
1212
9.00k
      double max_sr = stats_start[i].sr_coded_error;
1213
9.00k
      if (i < last) max_sr = AOMMAX(max_sr, stats_start[i + 1].sr_coded_error);
1214
9.00k
      double max_sr_fr_ratio =
1215
9.00k
          max_sr / AOMMAX(stats_start[i].coded_error, 0.01);
1216
1217
9.00k
      if (max_sr_fr_ratio > 1.2) continue;
1218
6.47k
      if (this_ratio < 2 * AOMMAX(max_prev_ratio, max_next_ratio) &&
1219
6.44k
          stats_start[i].coded_error <
1220
6.44k
              2 * AOMMAX(max_prev_coded, max_next_coded)) {
1221
6.37k
        continue;
1222
6.37k
      }
1223
6.47k
    }
1224
1.32k
    return i;
1225
10.2k
  }
1226
3.09k
  return -1;
1227
4.42k
}
1228
1229
// Remove the region with index next_region.
1230
// parameter merge: 0: merge with previous; 1: merge with next; 2:
1231
// merge with both, take type from previous if possible
1232
// After removing, next_region will be the index of the next region.
1233
static void remove_region(int merge, REGIONS *regions, int *num_regions,
1234
3.25k
                          int *next_region) {
1235
3.25k
  int k = *next_region;
1236
3.25k
  assert(k < *num_regions);
1237
3.25k
  if (*num_regions == 1) {
1238
1.25k
    *num_regions = 0;
1239
1.25k
    return;
1240
1.25k
  }
1241
2.00k
  if (k == 0) {
1242
0
    merge = 1;
1243
2.00k
  } else if (k == *num_regions - 1) {
1244
1.66k
    merge = 0;
1245
1.66k
  }
1246
2.00k
  int num_merge = (merge == 2) ? 2 : 1;
1247
2.00k
  switch (merge) {
1248
2.00k
    case 0:
1249
2.00k
      regions[k - 1].last = regions[k].last;
1250
2.00k
      *next_region = k;
1251
2.00k
      break;
1252
0
    case 1:
1253
0
      regions[k + 1].start = regions[k].start;
1254
0
      *next_region = k + 1;
1255
0
      break;
1256
0
    case 2:
1257
0
      regions[k - 1].last = regions[k + 1].last;
1258
0
      *next_region = k;
1259
0
      break;
1260
0
    default: assert(0);
1261
2.00k
  }
1262
2.00k
  *num_regions -= num_merge;
1263
2.35k
  for (k = *next_region - (merge == 1); k < *num_regions; k++) {
1264
344
    regions[k] = regions[k + num_merge];
1265
344
  }
1266
2.00k
}
1267
1268
// Insert a region in the cur_region_idx. The start and last should both be in
1269
// the current region. After insertion, the cur_region_idx will point to the
1270
// last region that was splitted from the original region.
1271
static void insert_region(int start, int last, REGION_TYPES type,
1272
                          REGIONS *regions, int *num_regions,
1273
3.17k
                          int *cur_region_idx) {
1274
3.17k
  int k = *cur_region_idx;
1275
3.17k
  REGION_TYPES this_region_type = regions[k].type;
1276
3.17k
  int this_region_last = regions[k].last;
1277
3.17k
  int num_add = (start != regions[k].start) + (last != regions[k].last);
1278
  // move the following regions further to the back
1279
3.17k
  for (int r = *num_regions - 1; r > k; r--) {
1280
0
    regions[r + num_add] = regions[r];
1281
0
  }
1282
3.17k
  *num_regions += num_add;
1283
3.17k
  if (start > regions[k].start) {
1284
911
    regions[k].last = start - 1;
1285
911
    k++;
1286
911
    regions[k].start = start;
1287
911
  }
1288
3.17k
  regions[k].type = type;
1289
3.17k
  if (last < this_region_last) {
1290
1.07k
    regions[k].last = last;
1291
1.07k
    k++;
1292
1.07k
    regions[k].start = last + 1;
1293
1.07k
    regions[k].last = this_region_last;
1294
1.07k
    regions[k].type = this_region_type;
1295
2.09k
  } else {
1296
2.09k
    regions[k].last = this_region_last;
1297
2.09k
  }
1298
3.17k
  *cur_region_idx = k;
1299
3.17k
}
1300
1301
// Get the average of stats inside a region.
1302
static void analyze_region(const FIRSTPASS_STATS *stats, int k,
1303
37.5k
                           REGIONS *regions) {
1304
37.5k
  int i;
1305
37.5k
  regions[k].avg_cor_coeff = 0;
1306
37.5k
  regions[k].avg_sr_fr_ratio = 0;
1307
37.5k
  regions[k].avg_intra_err = 0;
1308
37.5k
  regions[k].avg_coded_err = 0;
1309
1310
37.5k
  int check_first_sr = (k != 0);
1311
1312
113k
  for (i = regions[k].start; i <= regions[k].last; i++) {
1313
76.0k
    if (i > regions[k].start || check_first_sr) {
1314
45.2k
      double num_frames =
1315
45.2k
          (double)(regions[k].last - regions[k].start + check_first_sr);
1316
45.2k
      double max_coded_error =
1317
45.2k
          AOMMAX(stats[i].coded_error, stats[i - 1].coded_error);
1318
45.2k
      double this_ratio =
1319
45.2k
          stats[i].sr_coded_error / AOMMAX(max_coded_error, 0.001);
1320
45.2k
      regions[k].avg_sr_fr_ratio += this_ratio / num_frames;
1321
45.2k
    }
1322
1323
76.0k
    regions[k].avg_intra_err +=
1324
76.0k
        stats[i].intra_error / (double)(regions[k].last - regions[k].start + 1);
1325
76.0k
    regions[k].avg_coded_err +=
1326
76.0k
        stats[i].coded_error / (double)(regions[k].last - regions[k].start + 1);
1327
1328
76.0k
    regions[k].avg_cor_coeff +=
1329
76.0k
        AOMMAX(stats[i].cor_coeff, 0.001) /
1330
76.0k
        (double)(regions[k].last - regions[k].start + 1);
1331
76.0k
    regions[k].avg_noise_var +=
1332
76.0k
        AOMMAX(stats[i].noise_var, 0.001) /
1333
76.0k
        (double)(regions[k].last - regions[k].start + 1);
1334
76.0k
  }
1335
37.5k
}
1336
1337
// Calculate the regions stats of every region.
1338
static void get_region_stats(const FIRSTPASS_STATS *stats, REGIONS *regions,
1339
36.9k
                             int num_regions) {
1340
74.4k
  for (int k = 0; k < num_regions; k++) {
1341
37.5k
    analyze_region(stats, k, regions);
1342
37.5k
  }
1343
36.9k
}
1344
1345
// Find tentative stable regions
1346
static int find_stable_regions(const FIRSTPASS_STATS *stats,
1347
                               const double *grad_coded, int this_start,
1348
5.66k
                               int this_last, REGIONS *regions) {
1349
5.66k
  int i, j, k = 0;
1350
5.66k
  regions[k].start = this_start;
1351
16.1k
  for (i = this_start; i <= this_last; i++) {
1352
    // Check mean and variance of stats in a window
1353
10.4k
    double mean_intra = 0.001, var_intra = 0.001;
1354
10.4k
    double mean_coded = 0.001, var_coded = 0.001;
1355
10.4k
    int count = 0;
1356
83.8k
    for (j = -HALF_WIN; j <= HALF_WIN; j++) {
1357
73.3k
      int idx = clamp(i + j, this_start, this_last);
1358
73.3k
      if (stats[idx].is_flash || (idx > 0 && stats[idx - 1].is_flash)) continue;
1359
71.6k
      mean_intra += stats[idx].intra_error;
1360
71.6k
      var_intra += stats[idx].intra_error * stats[idx].intra_error;
1361
71.6k
      mean_coded += stats[idx].coded_error;
1362
71.6k
      var_coded += stats[idx].coded_error * stats[idx].coded_error;
1363
71.6k
      count++;
1364
71.6k
    }
1365
1366
10.4k
    REGION_TYPES cur_type;
1367
10.4k
    if (count > 0) {
1368
10.3k
      mean_intra /= (double)count;
1369
10.3k
      var_intra /= (double)count;
1370
10.3k
      mean_coded /= (double)count;
1371
10.3k
      var_coded /= (double)count;
1372
10.3k
      int is_intra_stable = (var_intra / (mean_intra * mean_intra) < 1.03);
1373
10.3k
      int is_coded_stable = (var_coded / (mean_coded * mean_coded) < 1.04 &&
1374
2.87k
                             fabs(grad_coded[i]) / mean_coded < 0.05) ||
1375
8.02k
                            mean_coded / mean_intra < 0.05;
1376
10.3k
      int is_coded_small = mean_coded < 0.5 * mean_intra;
1377
10.3k
      cur_type = (is_intra_stable && is_coded_stable && is_coded_small)
1378
10.3k
                     ? STABLE_REGION
1379
10.3k
                     : HIGH_VAR_REGION;
1380
10.3k
    } else {
1381
144
      cur_type = HIGH_VAR_REGION;
1382
144
    }
1383
1384
    // mark a new region if type changes
1385
10.4k
    if (i == regions[k].start) {
1386
      // first frame in the region
1387
4.41k
      regions[k].type = cur_type;
1388
6.06k
    } else if (cur_type != regions[k].type) {
1389
      // Append a new region
1390
1
      regions[k].last = i - 1;
1391
1
      regions[k + 1].start = i;
1392
1
      regions[k + 1].type = cur_type;
1393
1
      k++;
1394
1
    }
1395
10.4k
  }
1396
5.66k
  regions[k].last = this_last;
1397
5.66k
  return k + 1;
1398
5.66k
}
1399
1400
// Clean up regions that should be removed or merged.
1401
55.3k
static void cleanup_regions(REGIONS *regions, int *num_regions) {
1402
55.3k
  int k = 0;
1403
104k
  while (k < *num_regions) {
1404
48.6k
    if ((k > 0 && regions[k - 1].type == regions[k].type &&
1405
2.02k
         regions[k].type != SCENECUT_REGION) ||
1406
46.6k
        regions[k].last < regions[k].start) {
1407
3.25k
      remove_region(0, regions, num_regions, &k);
1408
45.4k
    } else {
1409
45.4k
      k++;
1410
45.4k
    }
1411
48.6k
  }
1412
55.3k
}
1413
1414
// Remove regions that are of type and shorter than length.
1415
// Merge it with its neighboring regions.
1416
static void remove_short_regions(REGIONS *regions, int *num_regions,
1417
28.3k
                                 REGION_TYPES type, int length) {
1418
28.3k
  int k = 0;
1419
28.3k
  while (k < *num_regions && (*num_regions) > 1) {
1420
2
    if ((regions[k].last - regions[k].start + 1 < length &&
1421
2
         regions[k].type == type)) {
1422
      // merge current region with the previous and next regions
1423
1
      remove_region(2, regions, num_regions, &k);
1424
1
    } else {
1425
1
      k++;
1426
1
    }
1427
2
  }
1428
28.3k
  cleanup_regions(regions, num_regions);
1429
28.3k
}
1430
1431
static void adjust_unstable_region_bounds(const FIRSTPASS_STATS *stats,
1432
5.66k
                                          REGIONS *regions, int *num_regions) {
1433
5.66k
  int i, j, k;
1434
  // Remove regions that are too short. Likely noise.
1435
5.66k
  remove_short_regions(regions, num_regions, STABLE_REGION, HALF_WIN);
1436
5.66k
  remove_short_regions(regions, num_regions, HIGH_VAR_REGION, HALF_WIN);
1437
1438
5.66k
  get_region_stats(stats, regions, *num_regions);
1439
1440
  // Adjust region boundaries. The thresholds are empirically obtained, but
1441
  // overall the performance is not very sensitive to small changes to them.
1442
10.0k
  for (k = 0; k < *num_regions; k++) {
1443
4.41k
    if (regions[k].type == STABLE_REGION) continue;
1444
4.38k
    if (k > 0) {
1445
      // Adjust previous boundary.
1446
      // First find the average intra/coded error in the previous
1447
      // neighborhood.
1448
0
      double avg_intra_err = 0;
1449
0
      const int starti = AOMMAX(regions[k - 1].last - WINDOW_SIZE + 1,
1450
0
                                regions[k - 1].start + 1);
1451
0
      const int lasti = regions[k - 1].last;
1452
0
      int counti = 0;
1453
0
      for (i = starti; i <= lasti; i++) {
1454
0
        avg_intra_err += stats[i].intra_error;
1455
0
        counti++;
1456
0
      }
1457
0
      if (counti > 0) {
1458
0
        avg_intra_err = AOMMAX(avg_intra_err / (double)counti, 0.001);
1459
0
        int count_coded = 0, count_grad = 0;
1460
0
        for (j = lasti + 1; j <= regions[k].last; j++) {
1461
0
          const int intra_close =
1462
0
              fabs(stats[j].intra_error - avg_intra_err) / avg_intra_err < 0.1;
1463
0
          const int coded_small = stats[j].coded_error / avg_intra_err < 0.1;
1464
0
          const int coeff_close = stats[j].cor_coeff > 0.995;
1465
0
          if (!coeff_close || !coded_small) count_coded--;
1466
0
          if (intra_close && count_coded >= 0 && count_grad >= 0) {
1467
            // this frame probably belongs to the previous stable region
1468
0
            regions[k - 1].last = j;
1469
0
            regions[k].start = j + 1;
1470
0
          } else {
1471
0
            break;
1472
0
          }
1473
0
        }
1474
0
      }
1475
0
    }  // if k > 0
1476
4.38k
    if (k < *num_regions - 1) {
1477
      // Adjust next boundary.
1478
      // First find the average intra/coded error in the next neighborhood.
1479
0
      double avg_intra_err = 0;
1480
0
      const int starti = regions[k + 1].start;
1481
0
      const int lasti = AOMMIN(regions[k + 1].last - 1,
1482
0
                               regions[k + 1].start + WINDOW_SIZE - 1);
1483
0
      int counti = 0;
1484
0
      for (i = starti; i <= lasti; i++) {
1485
0
        avg_intra_err += stats[i].intra_error;
1486
0
        counti++;
1487
0
      }
1488
0
      if (counti > 0) {
1489
0
        avg_intra_err = AOMMAX(avg_intra_err / (double)counti, 0.001);
1490
        // At the boundary, coded error is large, but still the frame is stable
1491
0
        int count_coded = 1, count_grad = 1;
1492
0
        for (j = starti - 1; j >= regions[k].start; j--) {
1493
0
          const int intra_close =
1494
0
              fabs(stats[j].intra_error - avg_intra_err) / avg_intra_err < 0.1;
1495
0
          const int coded_small =
1496
0
              stats[j + 1].coded_error / avg_intra_err < 0.1;
1497
0
          const int coeff_close = stats[j].cor_coeff > 0.995;
1498
0
          if (!coeff_close || !coded_small) count_coded--;
1499
0
          if (intra_close && count_coded >= 0 && count_grad >= 0) {
1500
            // this frame probably belongs to the next stable region
1501
0
            regions[k + 1].start = j;
1502
0
            regions[k].last = j - 1;
1503
0
          } else {
1504
0
            break;
1505
0
          }
1506
0
        }
1507
0
      }
1508
0
    }  // if k < *num_regions - 1
1509
4.38k
  }  // end of loop over all regions
1510
1511
5.66k
  cleanup_regions(regions, num_regions);
1512
5.66k
  remove_short_regions(regions, num_regions, HIGH_VAR_REGION, HALF_WIN);
1513
5.66k
  get_region_stats(stats, regions, *num_regions);
1514
1515
  // If a stable regions has higher error than neighboring high var regions,
1516
  // or if the stable region has a lower average correlation,
1517
  // then it should be merged with them
1518
5.66k
  k = 0;
1519
5.66k
  while (k < *num_regions && (*num_regions) > 1) {
1520
0
    if (regions[k].type == STABLE_REGION &&
1521
0
        (regions[k].last - regions[k].start + 1) < 2 * WINDOW_SIZE &&
1522
0
        ((k > 0 &&  // previous regions
1523
0
          (regions[k].avg_coded_err > regions[k - 1].avg_coded_err * 1.01 ||
1524
0
           regions[k].avg_cor_coeff < regions[k - 1].avg_cor_coeff * 0.999)) &&
1525
0
         (k < *num_regions - 1 &&  // next region
1526
0
          (regions[k].avg_coded_err > regions[k + 1].avg_coded_err * 1.01 ||
1527
0
           regions[k].avg_cor_coeff < regions[k + 1].avg_cor_coeff * 0.999)))) {
1528
      // merge current region with the previous and next regions
1529
0
      remove_region(2, regions, num_regions, &k);
1530
0
      analyze_region(stats, k - 1, regions);
1531
0
    } else if (regions[k].type == HIGH_VAR_REGION &&
1532
0
               (regions[k].last - regions[k].start + 1) < 2 * WINDOW_SIZE &&
1533
0
               ((k > 0 &&  // previous regions
1534
0
                 (regions[k].avg_coded_err <
1535
0
                      regions[k - 1].avg_coded_err * 0.99 ||
1536
0
                  regions[k].avg_cor_coeff >
1537
0
                      regions[k - 1].avg_cor_coeff * 1.001)) &&
1538
0
                (k < *num_regions - 1 &&  // next region
1539
0
                 (regions[k].avg_coded_err <
1540
0
                      regions[k + 1].avg_coded_err * 0.99 ||
1541
0
                  regions[k].avg_cor_coeff >
1542
0
                      regions[k + 1].avg_cor_coeff * 1.001)))) {
1543
      // merge current region with the previous and next regions
1544
0
      remove_region(2, regions, num_regions, &k);
1545
0
      analyze_region(stats, k - 1, regions);
1546
0
    } else {
1547
0
      k++;
1548
0
    }
1549
0
  }
1550
1551
5.66k
  remove_short_regions(regions, num_regions, STABLE_REGION, WINDOW_SIZE);
1552
5.66k
  remove_short_regions(regions, num_regions, HIGH_VAR_REGION, HALF_WIN);
1553
5.66k
}
1554
1555
// Identify blending regions.
1556
static void find_blending_regions(const FIRSTPASS_STATS *stats,
1557
5.66k
                                  REGIONS *regions, int *num_regions) {
1558
5.66k
  int i, k = 0;
1559
  // Blending regions will have large content change, therefore will have a
1560
  // large consistent change in intra error.
1561
5.66k
  int count_stable = 0;
1562
10.0k
  while (k < *num_regions) {
1563
4.41k
    if (regions[k].type == STABLE_REGION) {
1564
31
      k++;
1565
31
      count_stable++;
1566
31
      continue;
1567
31
    }
1568
4.38k
    int dir = 0;
1569
4.38k
    int start = 0, last;
1570
14.8k
    for (i = regions[k].start; i <= regions[k].last; i++) {
1571
      // First mark the regions that has consistent large change of intra error.
1572
10.4k
      if (k == 0 && i == regions[k].start) continue;
1573
6.04k
      if (stats[i].is_flash || (i > 0 && stats[i - 1].is_flash)) continue;
1574
5.87k
      double grad = stats[i].intra_error - stats[i - 1].intra_error;
1575
5.87k
      int large_change = fabs(grad) / AOMMAX(stats[i].intra_error, 0.01) > 0.05;
1576
5.87k
      int this_dir = 0;
1577
5.87k
      if (large_change) {
1578
3.76k
        this_dir = (grad > 0) ? 1 : -1;
1579
3.76k
      }
1580
      // the current trend continues
1581
5.87k
      if (dir == this_dir) continue;
1582
3.45k
      if (dir != 0) {
1583
        // Mark the end of a new large change group and add it
1584
1.07k
        last = i - 1;
1585
1.07k
        insert_region(start, last, BLENDING_REGION, regions, num_regions, &k);
1586
1.07k
      }
1587
3.45k
      dir = this_dir;
1588
3.45k
      if (k == 0 && i == regions[k].start + 1) {
1589
1.46k
        start = i - 1;
1590
1.99k
      } else {
1591
1.99k
        start = i;
1592
1.99k
      }
1593
3.45k
    }
1594
4.38k
    if (dir != 0) {
1595
2.09k
      last = regions[k].last;
1596
2.09k
      insert_region(start, last, BLENDING_REGION, regions, num_regions, &k);
1597
2.09k
    }
1598
4.38k
    k++;
1599
4.38k
  }
1600
1601
  // If the blending region has very low correlation, mark it as high variance
1602
  // since we probably cannot benefit from it anyways.
1603
5.66k
  get_region_stats(stats, regions, *num_regions);
1604
12.0k
  for (k = 0; k < *num_regions; k++) {
1605
6.40k
    if (regions[k].type != BLENDING_REGION) continue;
1606
3.17k
    if (regions[k].last == regions[k].start || regions[k].avg_cor_coeff < 0.6 ||
1607
397
        count_stable == 0)
1608
3.17k
      regions[k].type = HIGH_VAR_REGION;
1609
3.17k
  }
1610
5.66k
  get_region_stats(stats, regions, *num_regions);
1611
1612
  // It is possible for blending to result in a "dip" in intra error (first
1613
  // decrease then increase). Therefore we need to find the dip and combine the
1614
  // two regions.
1615
5.66k
  k = 1;
1616
7.65k
  while (k < *num_regions) {
1617
1.99k
    if (k < *num_regions - 1 && regions[k].type == HIGH_VAR_REGION) {
1618
      // Check if this short high variance regions is actually in the middle of
1619
      // a blending region.
1620
342
      if (regions[k - 1].type == BLENDING_REGION &&
1621
0
          regions[k + 1].type == BLENDING_REGION &&
1622
0
          regions[k].last - regions[k].start < 3) {
1623
0
        int prev_dir = (stats[regions[k - 1].last].intra_error -
1624
0
                        stats[regions[k - 1].last - 1].intra_error) > 0
1625
0
                           ? 1
1626
0
                           : -1;
1627
0
        int next_dir = (stats[regions[k + 1].last].intra_error -
1628
0
                        stats[regions[k + 1].last - 1].intra_error) > 0
1629
0
                           ? 1
1630
0
                           : -1;
1631
0
        if (prev_dir < 0 && next_dir > 0) {
1632
          // This is possibly a mid region of blending. Check the ratios
1633
0
          double ratio_thres = AOMMIN(regions[k - 1].avg_sr_fr_ratio,
1634
0
                                      regions[k + 1].avg_sr_fr_ratio) *
1635
0
                               0.95;
1636
0
          if (regions[k].avg_sr_fr_ratio > ratio_thres) {
1637
0
            regions[k].type = BLENDING_REGION;
1638
0
            remove_region(2, regions, num_regions, &k);
1639
0
            analyze_region(stats, k - 1, regions);
1640
0
            continue;
1641
0
          }
1642
0
        }
1643
0
      }
1644
342
    }
1645
    // Check if we have a pair of consecutive blending regions.
1646
1.99k
    if (regions[k - 1].type == BLENDING_REGION &&
1647
0
        regions[k].type == BLENDING_REGION) {
1648
0
      int prev_dir = (stats[regions[k - 1].last].intra_error -
1649
0
                      stats[regions[k - 1].last - 1].intra_error) > 0
1650
0
                         ? 1
1651
0
                         : -1;
1652
0
      int next_dir = (stats[regions[k].last].intra_error -
1653
0
                      stats[regions[k].last - 1].intra_error) > 0
1654
0
                         ? 1
1655
0
                         : -1;
1656
1657
      // if both are too short, no need to check
1658
0
      int total_length = regions[k].last - regions[k - 1].start + 1;
1659
0
      if (total_length < 4) {
1660
0
        regions[k - 1].type = HIGH_VAR_REGION;
1661
0
        k++;
1662
0
        continue;
1663
0
      }
1664
1665
0
      int to_merge = 0;
1666
0
      if (prev_dir < 0 && next_dir > 0) {
1667
        // In this case we check the last frame in the previous region.
1668
0
        double prev_length =
1669
0
            (double)(regions[k - 1].last - regions[k - 1].start + 1);
1670
0
        double last_ratio, ratio_thres;
1671
0
        if (prev_length < 2.01) {
1672
          // if the previous region is very short
1673
0
          double max_coded_error =
1674
0
              AOMMAX(stats[regions[k - 1].last].coded_error,
1675
0
                     stats[regions[k - 1].last - 1].coded_error);
1676
0
          last_ratio = stats[regions[k - 1].last].sr_coded_error /
1677
0
                       AOMMAX(max_coded_error, 0.001);
1678
0
          ratio_thres = regions[k].avg_sr_fr_ratio * 0.95;
1679
0
        } else {
1680
0
          double max_coded_error =
1681
0
              AOMMAX(stats[regions[k - 1].last].coded_error,
1682
0
                     stats[regions[k - 1].last - 1].coded_error);
1683
0
          last_ratio = stats[regions[k - 1].last].sr_coded_error /
1684
0
                       AOMMAX(max_coded_error, 0.001);
1685
0
          double prev_ratio =
1686
0
              (regions[k - 1].avg_sr_fr_ratio * prev_length - last_ratio) /
1687
0
              (prev_length - 1.0);
1688
0
          ratio_thres = AOMMIN(prev_ratio, regions[k].avg_sr_fr_ratio) * 0.95;
1689
0
        }
1690
0
        if (last_ratio > ratio_thres) {
1691
0
          to_merge = 1;
1692
0
        }
1693
0
      }
1694
1695
0
      if (to_merge) {
1696
0
        remove_region(0, regions, num_regions, &k);
1697
0
        analyze_region(stats, k - 1, regions);
1698
0
        continue;
1699
0
      } else {
1700
        // These are possibly two separate blending regions. Mark the boundary
1701
        // frame as HIGH_VAR_REGION to separate the two.
1702
0
        int prev_k = k - 1;
1703
0
        insert_region(regions[prev_k].last, regions[prev_k].last,
1704
0
                      HIGH_VAR_REGION, regions, num_regions, &prev_k);
1705
0
        analyze_region(stats, prev_k, regions);
1706
0
        k = prev_k + 1;
1707
0
        analyze_region(stats, k, regions);
1708
0
      }
1709
0
    }
1710
1.99k
    k++;
1711
1.99k
  }
1712
5.66k
  cleanup_regions(regions, num_regions);
1713
5.66k
}
1714
1715
// Clean up decision for blendings. Remove blending regions that are too short.
1716
// Also if a very short high var region is between a blending and a stable
1717
// region, just merge it with one of them.
1718
5.66k
static void cleanup_blendings(REGIONS *regions, int *num_regions) {
1719
5.66k
  int k = 0;
1720
5.66k
  while (k < (*num_regions) && (*num_regions) > 1) {
1721
0
    int is_short_blending = regions[k].type == BLENDING_REGION &&
1722
0
                            regions[k].last - regions[k].start + 1 < 5;
1723
0
    int is_short_hv = regions[k].type == HIGH_VAR_REGION &&
1724
0
                      regions[k].last - regions[k].start + 1 < 5;
1725
0
    int has_stable_neighbor =
1726
0
        ((k > 0 && regions[k - 1].type == STABLE_REGION) ||
1727
0
         (k < *num_regions - 1 && regions[k + 1].type == STABLE_REGION));
1728
0
    int has_blend_neighbor =
1729
0
        ((k > 0 && regions[k - 1].type == BLENDING_REGION) ||
1730
0
         (k < *num_regions - 1 && regions[k + 1].type == BLENDING_REGION));
1731
0
    int total_neighbors = (k > 0) + (k < *num_regions - 1);
1732
1733
0
    if (is_short_blending ||
1734
0
        (is_short_hv &&
1735
0
         has_stable_neighbor + has_blend_neighbor >= total_neighbors)) {
1736
      // Remove this region.Try to determine whether to combine it with the
1737
      // previous or next region.
1738
0
      int merge;
1739
0
      double prev_diff =
1740
0
          (k > 0)
1741
0
              ? fabs(regions[k].avg_cor_coeff - regions[k - 1].avg_cor_coeff)
1742
0
              : 1;
1743
0
      double next_diff =
1744
0
          (k < *num_regions - 1)
1745
0
              ? fabs(regions[k].avg_cor_coeff - regions[k + 1].avg_cor_coeff)
1746
0
              : 1;
1747
      // merge == 0 means to merge with previous, 1 means to merge with next
1748
0
      merge = prev_diff > next_diff;
1749
0
      remove_region(merge, regions, num_regions, &k);
1750
0
    } else {
1751
0
      k++;
1752
0
    }
1753
0
  }
1754
5.66k
  cleanup_regions(regions, num_regions);
1755
5.66k
}
1756
1757
static void free_firstpass_stats_buffers(REGIONS *temp_regions,
1758
                                         double *filt_intra_err,
1759
                                         double *filt_coded_err,
1760
4.33k
                                         double *grad_coded) {
1761
4.33k
  aom_free(temp_regions);
1762
4.33k
  aom_free(filt_intra_err);
1763
4.33k
  aom_free(filt_coded_err);
1764
4.33k
  aom_free(grad_coded);
1765
4.33k
}
1766
1767
// Identify stable and unstable regions from first pass stats.
1768
// stats_start points to the first frame to analyze.
1769
// |offset| is the offset from the current frame to the frame stats_start is
1770
// pointing to.
1771
// Returns 0 on success, -1 on memory allocation failure.
1772
static int identify_regions(const FIRSTPASS_STATS *const stats_start,
1773
                            int total_frames, int offset, REGIONS *regions,
1774
80.9k
                            int *total_regions) {
1775
80.9k
  int k;
1776
80.9k
  if (total_frames <= 1) return 0;
1777
1778
  // store the initial decisions
1779
4.33k
  REGIONS *temp_regions =
1780
4.33k
      (REGIONS *)aom_malloc(total_frames * sizeof(temp_regions[0]));
1781
  // buffers for filtered stats
1782
4.33k
  double *filt_intra_err =
1783
4.33k
      (double *)aom_calloc(total_frames, sizeof(*filt_intra_err));
1784
4.33k
  double *filt_coded_err =
1785
4.33k
      (double *)aom_calloc(total_frames, sizeof(*filt_coded_err));
1786
4.33k
  double *grad_coded = (double *)aom_calloc(total_frames, sizeof(*grad_coded));
1787
4.33k
  if (!(temp_regions && filt_intra_err && filt_coded_err && grad_coded)) {
1788
0
    free_firstpass_stats_buffers(temp_regions, filt_intra_err, filt_coded_err,
1789
0
                                 grad_coded);
1790
0
    return -1;
1791
0
  }
1792
4.33k
  av1_zero_array(temp_regions, total_frames);
1793
1794
4.33k
  int cur_region = 0, this_start = 0, this_last;
1795
1796
4.33k
  int next_scenecut = -1;
1797
5.66k
  do {
1798
    // first get the obvious scenecuts
1799
5.66k
    next_scenecut =
1800
5.66k
        find_next_scenecut(stats_start, this_start, total_frames - 1);
1801
5.66k
    this_last = (next_scenecut >= 0) ? (next_scenecut - 1) : total_frames - 1;
1802
1803
    // low-pass filter the needed stats
1804
5.66k
    smooth_filter_stats(stats_start, this_start, this_last, filt_intra_err,
1805
5.66k
                        filt_coded_err);
1806
5.66k
    get_gradient(filt_coded_err, this_start, this_last, grad_coded);
1807
1808
    // find tentative stable regions and unstable regions
1809
5.66k
    int num_regions = find_stable_regions(stats_start, grad_coded, this_start,
1810
5.66k
                                          this_last, temp_regions);
1811
1812
5.66k
    adjust_unstable_region_bounds(stats_start, temp_regions, &num_regions);
1813
1814
5.66k
    get_region_stats(stats_start, temp_regions, num_regions);
1815
1816
    // Try to identify blending regions in the unstable regions
1817
5.66k
    find_blending_regions(stats_start, temp_regions, &num_regions);
1818
5.66k
    cleanup_blendings(temp_regions, &num_regions);
1819
1820
    // The flash points should all be considered high variance points
1821
5.66k
    k = 0;
1822
10.0k
    while (k < num_regions) {
1823
4.41k
      if (temp_regions[k].type != STABLE_REGION) {
1824
4.38k
        k++;
1825
4.38k
        continue;
1826
4.38k
      }
1827
31
      int start = temp_regions[k].start;
1828
31
      int last = temp_regions[k].last;
1829
79
      for (int i = start; i <= last; i++) {
1830
48
        if (stats_start[i].is_flash) {
1831
0
          insert_region(i, i, HIGH_VAR_REGION, temp_regions, &num_regions, &k);
1832
0
        }
1833
48
      }
1834
31
      k++;
1835
31
    }
1836
5.66k
    cleanup_regions(temp_regions, &num_regions);
1837
1838
    // copy the regions in the scenecut group
1839
10.0k
    for (k = 0; k < num_regions; k++) {
1840
4.41k
      if (temp_regions[k].last < temp_regions[k].start &&
1841
0
          k == num_regions - 1) {
1842
0
        num_regions--;
1843
0
        break;
1844
0
      }
1845
4.41k
      regions[k + cur_region] = temp_regions[k];
1846
4.41k
    }
1847
5.66k
    cur_region += num_regions;
1848
1849
    // add the scenecut region
1850
5.66k
    if (next_scenecut > -1) {
1851
      // add the scenecut region, and find the next scenecut
1852
1.32k
      regions[cur_region].type = SCENECUT_REGION;
1853
1.32k
      regions[cur_region].start = next_scenecut;
1854
1.32k
      regions[cur_region].last = next_scenecut;
1855
1.32k
      cur_region++;
1856
1.32k
      this_start = next_scenecut + 1;
1857
1.32k
    }
1858
5.66k
  } while (next_scenecut >= 0);
1859
1860
4.33k
  *total_regions = cur_region;
1861
4.33k
  get_region_stats(stats_start, regions, *total_regions);
1862
1863
10.0k
  for (k = 0; k < *total_regions; k++) {
1864
    // If scenecuts are very minor, mark them as high variance.
1865
5.74k
    if (regions[k].type != SCENECUT_REGION ||
1866
1.32k
        regions[k].avg_cor_coeff *
1867
1.32k
                (1 - stats_start[regions[k].start].noise_var /
1868
1.32k
                         regions[k].avg_intra_err) <
1869
5.72k
            0.8) {
1870
5.72k
      continue;
1871
5.72k
    }
1872
16
    regions[k].type = HIGH_VAR_REGION;
1873
16
  }
1874
4.33k
  cleanup_regions(regions, total_regions);
1875
4.33k
  get_region_stats(stats_start, regions, *total_regions);
1876
1877
10.0k
  for (k = 0; k < *total_regions; k++) {
1878
5.72k
    regions[k].start += offset;
1879
5.72k
    regions[k].last += offset;
1880
5.72k
  }
1881
1882
4.33k
  free_firstpass_stats_buffers(temp_regions, filt_intra_err, filt_coded_err,
1883
4.33k
                               grad_coded);
1884
4.33k
  return 0;
1885
4.33k
}
1886
1887
static int find_regions_index(const REGIONS *regions, int num_regions,
1888
105k
                              int frame_idx) {
1889
125k
  for (int k = 0; k < num_regions; k++) {
1890
29.1k
    if (regions[k].start <= frame_idx && regions[k].last >= frame_idx) {
1891
9.55k
      return k;
1892
9.55k
    }
1893
29.1k
  }
1894
95.8k
  return -1;
1895
105k
}
1896
1897
/*!\brief Determine the length of future GF groups.
1898
 *
1899
 * \ingroup gf_group_algo
1900
 * This function decides the gf group length of future frames in batch
1901
 *
1902
 * \param[in]    cpi              Top-level encoder structure
1903
 * \param[in]    max_gop_length   Maximum length of the GF group
1904
 * \param[in]    max_intervals    Maximum number of intervals to decide
1905
 *
1906
 * \remark Nothing is returned. Instead, cpi->ppi->rc.gf_intervals is
1907
 * changed to store the decided GF group lengths.
1908
 */
1909
static void calculate_gf_length(AV1_COMP *cpi, int max_gop_length,
1910
80.9k
                                int max_intervals) {
1911
80.9k
  RATE_CONTROL *const rc = &cpi->rc;
1912
80.9k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1913
80.9k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
1914
80.9k
  FIRSTPASS_STATS next_frame;
1915
80.9k
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
1916
80.9k
  const FIRSTPASS_STATS *const stats = start_pos - (rc->frames_since_key == 0);
1917
1918
80.9k
  const int f_w = cpi->common.width;
1919
80.9k
  const int f_h = cpi->common.height;
1920
80.9k
  int i;
1921
1922
80.9k
  int flash_detected;
1923
1924
80.9k
  av1_zero(next_frame);
1925
1926
80.9k
  if (has_no_stats_stage(cpi)) {
1927
1.11M
    for (i = 0; i < MAX_NUM_GF_INTERVALS; i++) {
1928
1.04M
      p_rc->gf_intervals[i] = AOMMIN(rc->max_gf_interval, max_gop_length);
1929
1.04M
    }
1930
69.4k
    p_rc->cur_gf_index = 0;
1931
69.4k
    rc->intervals_till_gf_calculate_due = MAX_NUM_GF_INTERVALS;
1932
69.4k
    return;
1933
69.4k
  }
1934
1935
  // TODO(urvang): Try logic to vary min and max interval based on q.
1936
11.4k
  const int active_min_gf_interval = rc->min_gf_interval;
1937
11.4k
  const int active_max_gf_interval =
1938
11.4k
      AOMMIN(rc->max_gf_interval, max_gop_length);
1939
11.4k
  const int min_shrink_int = AOMMAX(MIN_SHRINK_LEN, active_min_gf_interval);
1940
1941
11.4k
  i = (rc->frames_since_key == 0);
1942
11.4k
  max_intervals = cpi->ppi->lap_enabled ? 1 : max_intervals;
1943
11.4k
  int count_cuts = 1;
1944
  // If cpi->gf_state.arf_gf_boost_lst is 0, we are starting with a KF or GF.
1945
11.4k
  int cur_start = -1 + !cpi->ppi->gf_state.arf_gf_boost_lst, cur_last;
1946
11.4k
  int cut_pos[MAX_NUM_GF_INTERVALS + 1] = { -1 };
1947
11.4k
  int cut_here;
1948
11.4k
  GF_GROUP_STATS gf_stats;
1949
11.4k
  init_gf_stats(&gf_stats);
1950
18.9k
  while (count_cuts < max_intervals + 1) {
1951
    // reaches next key frame, break here
1952
18.9k
    if (i >= rc->frames_to_key) {
1953
11.4k
      cut_here = 2;
1954
11.4k
    } else if (i - cur_start >= rc->static_scene_max_gf_interval) {
1955
      // reached maximum len, but nothing special yet (almost static)
1956
      // let's look at the next interval
1957
0
      cut_here = 1;
1958
7.47k
    } else if (EOF == input_stats(twopass, &cpi->twopass_frame, &next_frame)) {
1959
      // reaches last frame, break
1960
0
      cut_here = 2;
1961
7.47k
    } else {
1962
      // Test for the case where there is a brief flash but the prediction
1963
      // quality back to an earlier frame is then restored.
1964
7.47k
      flash_detected = detect_flash(twopass, &cpi->twopass_frame, 0);
1965
      // TODO(bohanli): remove redundant accumulations here, or unify
1966
      // this and the ones in define_gf_group
1967
7.47k
      accumulate_next_frame_stats(&next_frame, flash_detected,
1968
7.47k
                                  rc->frames_since_key, i, &gf_stats, f_w, f_h);
1969
1970
7.47k
      cut_here = detect_gf_cut(cpi, i, cur_start, flash_detected,
1971
7.47k
                               active_max_gf_interval, active_min_gf_interval,
1972
7.47k
                               &gf_stats);
1973
7.47k
    }
1974
18.9k
    if (cut_here) {
1975
11.4k
      cur_last = i - 1;  // the current last frame in the gf group
1976
11.4k
      int ori_last = cur_last;
1977
      // The region frame idx does not start from the same frame as cur_start
1978
      // and cur_last. Need to offset them.
1979
11.4k
      int offset = rc->frames_since_key - p_rc->regions_offset;
1980
11.4k
      REGIONS *regions = p_rc->regions;
1981
11.4k
      int num_regions = p_rc->num_regions;
1982
1983
11.4k
      int scenecut_idx = -1;
1984
      // only try shrinking if interval smaller than active_max_gf_interval
1985
11.4k
      if (cur_last - cur_start <= active_max_gf_interval &&
1986
11.4k
          cur_last > cur_start) {
1987
        // find the region indices of where the first and last frame belong.
1988
4.33k
        int k_start =
1989
4.33k
            find_regions_index(regions, num_regions, cur_start + offset);
1990
4.33k
        int k_last =
1991
4.33k
            find_regions_index(regions, num_regions, cur_last + offset);
1992
4.33k
        if (cur_start + offset == 0) k_start = 0;
1993
1994
        // See if we have a scenecut in between
1995
4.44k
        for (int r = k_start + 1; r <= k_last; r++) {
1996
106
          if (regions[r].type == SCENECUT_REGION &&
1997
89
              regions[r].last - offset - cur_start > active_min_gf_interval) {
1998
0
            scenecut_idx = r;
1999
0
            break;
2000
0
          }
2001
106
        }
2002
2003
        // if the found scenecut is very close to the end, ignore it.
2004
4.33k
        if (regions[num_regions - 1].last - regions[scenecut_idx].last < 4) {
2005
3.38k
          scenecut_idx = -1;
2006
3.38k
        }
2007
2008
4.33k
        if (scenecut_idx != -1) {
2009
          // If we have a scenecut, then stop at it.
2010
          // TODO(bohanli): add logic here to stop before the scenecut and for
2011
          // the next gop start from the scenecut with GF
2012
0
          int is_minor_sc =
2013
0
              (regions[scenecut_idx].avg_cor_coeff *
2014
0
                   (1 - stats[regions[scenecut_idx].start - offset].noise_var /
2015
0
                            regions[scenecut_idx].avg_intra_err) >
2016
0
               0.6);
2017
0
          cur_last = regions[scenecut_idx].last - offset - !is_minor_sc;
2018
4.33k
        } else {
2019
4.33k
          int is_last_analysed = (k_last == num_regions - 1) &&
2020
3.05k
                                 (cur_last + offset == regions[k_last].last);
2021
4.33k
          int not_enough_regions =
2022
4.33k
              k_last - k_start <=
2023
4.33k
              1 + (regions[k_start].type == SCENECUT_REGION);
2024
          // if we are very close to the end, then do not shrink since it may
2025
          // introduce intervals that are too short
2026
4.33k
          if (!(is_last_analysed && not_enough_regions)) {
2027
4.33k
            const double arf_length_factor = 0.1;
2028
4.33k
            double best_score = 0;
2029
4.33k
            int best_j = -1;
2030
4.33k
            const int first_frame = regions[0].start - offset;
2031
4.33k
            const int last_frame = regions[num_regions - 1].last - offset;
2032
            // score of how much the arf helps the whole GOP
2033
4.33k
            double base_score = 0.0;
2034
            // Accumulate base_score in
2035
12.6k
            for (int j = cur_start + 1; j < cur_start + min_shrink_int; j++) {
2036
12.6k
              if (stats + j >= twopass->stats_buf_ctx->stats_in_end) break;
2037
8.36k
              base_score = (base_score + 1.0) * stats[j].cor_coeff;
2038
8.36k
            }
2039
4.33k
            int met_blending = 0;   // Whether we have met blending areas before
2040
4.33k
            int last_blending = 0;  // Whether the previous frame if blending
2041
4.33k
            for (int j = cur_start + min_shrink_int; j <= cur_last; j++) {
2042
0
              if (stats + j >= twopass->stats_buf_ctx->stats_in_end) break;
2043
0
              base_score = (base_score + 1.0) * stats[j].cor_coeff;
2044
0
              int this_reg =
2045
0
                  find_regions_index(regions, num_regions, j + offset);
2046
0
              if (this_reg < 0) continue;
2047
              // A GOP should include at most 1 blending region.
2048
0
              if (regions[this_reg].type == BLENDING_REGION) {
2049
0
                last_blending = 1;
2050
0
                if (met_blending) {
2051
0
                  break;
2052
0
                } else {
2053
0
                  base_score = 0;
2054
0
                  continue;
2055
0
                }
2056
0
              } else {
2057
0
                if (last_blending) met_blending = 1;
2058
0
                last_blending = 0;
2059
0
              }
2060
2061
              // Add the factor of how good the neighborhood is for this
2062
              // candidate arf.
2063
0
              double this_score = arf_length_factor * base_score;
2064
0
              double temp_accu_coeff = 1.0;
2065
              // following frames
2066
0
              int count_f = 0;
2067
0
              for (int n = j + 1; n <= j + 3 && n <= last_frame; n++) {
2068
0
                if (stats + n >= twopass->stats_buf_ctx->stats_in_end) break;
2069
0
                temp_accu_coeff *= stats[n].cor_coeff;
2070
0
                this_score +=
2071
0
                    temp_accu_coeff *
2072
0
                    sqrt(AOMMAX(0.5,
2073
0
                                1 - stats[n].noise_var /
2074
0
                                        AOMMAX(stats[n].intra_error, 0.001)));
2075
0
                count_f++;
2076
0
              }
2077
              // preceding frames
2078
0
              temp_accu_coeff = 1.0;
2079
0
              for (int n = j; n > j - 3 * 2 + count_f && n > first_frame; n--) {
2080
0
                if (stats + n < twopass->stats_buf_ctx->stats_in_start) break;
2081
0
                temp_accu_coeff *= stats[n].cor_coeff;
2082
0
                this_score +=
2083
0
                    temp_accu_coeff *
2084
0
                    sqrt(AOMMAX(0.5,
2085
0
                                1 - stats[n].noise_var /
2086
0
                                        AOMMAX(stats[n].intra_error, 0.001)));
2087
0
              }
2088
2089
0
              if (this_score > best_score) {
2090
0
                best_score = this_score;
2091
0
                best_j = j;
2092
0
              }
2093
0
            }
2094
2095
            // For blending areas, move one more frame in case we missed the
2096
            // first blending frame.
2097
4.33k
            int best_reg =
2098
4.33k
                find_regions_index(regions, num_regions, best_j + offset);
2099
4.33k
            if (best_reg < num_regions - 1 && best_reg > 0) {
2100
0
              if (regions[best_reg - 1].type == BLENDING_REGION &&
2101
0
                  regions[best_reg + 1].type == BLENDING_REGION) {
2102
0
                if (best_j + offset == regions[best_reg].start &&
2103
0
                    best_j + offset < regions[best_reg].last) {
2104
0
                  best_j += 1;
2105
0
                } else if (best_j + offset == regions[best_reg].last &&
2106
0
                           best_j + offset > regions[best_reg].start) {
2107
0
                  best_j -= 1;
2108
0
                }
2109
0
              }
2110
0
            }
2111
2112
4.33k
            if (cur_last - best_j < 2) best_j = cur_last;
2113
4.33k
            if (best_j > 0 && best_score > 0.1) cur_last = best_j;
2114
            // if cannot find anything, just cut at the original place.
2115
4.33k
          }
2116
4.33k
        }
2117
4.33k
      }
2118
11.4k
      cut_pos[count_cuts] = cur_last;
2119
11.4k
      count_cuts++;
2120
2121
      // reset pointers to the shrunken location
2122
11.4k
      cpi->twopass_frame.stats_in = start_pos + cur_last;
2123
11.4k
      cur_start = cur_last;
2124
11.4k
      int cur_region_idx =
2125
11.4k
          find_regions_index(regions, num_regions, cur_start + 1 + offset);
2126
11.4k
      if (cur_region_idx >= 0)
2127
5.22k
        if (regions[cur_region_idx].type == SCENECUT_REGION) cur_start++;
2128
2129
11.4k
      i = cur_last;
2130
2131
11.4k
      if (cut_here > 1 && cur_last == ori_last) break;
2132
2133
      // reset accumulators
2134
0
      init_gf_stats(&gf_stats);
2135
0
    }
2136
7.47k
    ++i;
2137
7.47k
  }
2138
2139
  // save intervals
2140
11.4k
  rc->intervals_till_gf_calculate_due = count_cuts - 1;
2141
22.9k
  for (int n = 1; n < count_cuts; n++) {
2142
11.4k
    p_rc->gf_intervals[n - 1] = cut_pos[n] - cut_pos[n - 1];
2143
11.4k
  }
2144
11.4k
  p_rc->cur_gf_index = 0;
2145
11.4k
  cpi->twopass_frame.stats_in = start_pos;
2146
11.4k
}
2147
2148
233k
static void correct_frames_to_key(AV1_COMP *cpi) {
2149
233k
  int lookahead_size =
2150
233k
      av1_lookahead_depth(cpi->ppi->lookahead, cpi->compressor_stage);
2151
233k
  if (lookahead_size <
2152
233k
      av1_lookahead_pop_sz(cpi->ppi->lookahead, cpi->compressor_stage)) {
2153
34.4k
    assert(
2154
34.4k
        IMPLIES(cpi->oxcf.pass != AOM_RC_ONE_PASS && cpi->ppi->frames_left > 0,
2155
34.4k
                lookahead_size == cpi->ppi->frames_left));
2156
34.4k
    cpi->rc.frames_to_key = AOMMIN(cpi->rc.frames_to_key, lookahead_size);
2157
198k
  } else if (cpi->ppi->frames_left > 0) {
2158
    // Correct frames to key based on limit
2159
136k
    cpi->rc.frames_to_key =
2160
136k
        AOMMIN(cpi->rc.frames_to_key, cpi->ppi->frames_left);
2161
136k
  }
2162
233k
}
2163
2164
/*!\brief Define a GF group in one pass mode when no look ahead stats are
2165
 * available.
2166
 *
2167
 * \ingroup gf_group_algo
2168
 * This function defines the structure of a GF group, along with various
2169
 * parameters regarding bit-allocation and quality setup in the special
2170
 * case of one pass encoding where no lookahead stats are avialable.
2171
 *
2172
 * \param[in]    cpi             Top-level encoder structure
2173
 *
2174
 * \remark Nothing is returned. Instead, cpi->ppi->gf_group is changed.
2175
 */
2176
138k
static void define_gf_group_pass0(AV1_COMP *cpi) {
2177
138k
  RATE_CONTROL *const rc = &cpi->rc;
2178
138k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2179
138k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
2180
138k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2181
138k
  const GFConfig *const gf_cfg = &oxcf->gf_cfg;
2182
138k
  int target;
2183
2184
138k
  if (oxcf->q_cfg.aq_mode == CYCLIC_REFRESH_AQ) {
2185
0
    av1_cyclic_refresh_set_golden_update(cpi);
2186
138k
  } else {
2187
138k
    p_rc->baseline_gf_interval = p_rc->gf_intervals[p_rc->cur_gf_index];
2188
138k
    rc->intervals_till_gf_calculate_due--;
2189
138k
    p_rc->cur_gf_index++;
2190
138k
  }
2191
2192
  // correct frames_to_key when lookahead queue is flushing
2193
138k
  correct_frames_to_key(cpi);
2194
2195
138k
  if (p_rc->baseline_gf_interval > rc->frames_to_key)
2196
0
    p_rc->baseline_gf_interval = rc->frames_to_key;
2197
2198
138k
  p_rc->gfu_boost = DEFAULT_GF_BOOST;
2199
138k
  p_rc->constrained_gf_group =
2200
138k
      (p_rc->baseline_gf_interval >= rc->frames_to_key) ? 1 : 0;
2201
2202
138k
  gf_group->max_layer_depth_allowed = oxcf->gf_cfg.gf_max_pyr_height;
2203
2204
  // Rare case when the look-ahead is less than the target GOP length, can't
2205
  // generate ARF frame.
2206
138k
  if (p_rc->baseline_gf_interval > gf_cfg->lag_in_frames ||
2207
138k
      !is_altref_enabled(gf_cfg->lag_in_frames, gf_cfg->enable_auto_arf) ||
2208
0
      p_rc->baseline_gf_interval < rc->min_gf_interval)
2209
138k
    gf_group->max_layer_depth_allowed = 0;
2210
2211
  // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
2212
138k
  av1_gop_setup_structure(cpi);
2213
2214
  // Allocate bits to each of the frames in the GF group.
2215
  // TODO(sarahparker) Extend this to work with pyramid structure.
2216
277k
  for (int cur_index = 0; cur_index < gf_group->size; ++cur_index) {
2217
138k
    const FRAME_UPDATE_TYPE cur_update_type = gf_group->update_type[cur_index];
2218
138k
    if (oxcf->rc_cfg.mode == AOM_CBR) {
2219
0
      if (cur_update_type == KF_UPDATE) {
2220
0
        target = av1_calc_iframe_target_size_one_pass_cbr(cpi);
2221
0
      } else {
2222
0
        target = av1_calc_pframe_target_size_one_pass_cbr(cpi, cur_update_type);
2223
0
      }
2224
138k
    } else {
2225
138k
      if (cur_update_type == KF_UPDATE) {
2226
119k
        target = av1_calc_iframe_target_size_one_pass_vbr(cpi);
2227
119k
      } else {
2228
19.4k
        target = av1_calc_pframe_target_size_one_pass_vbr(cpi, cur_update_type);
2229
19.4k
      }
2230
138k
    }
2231
138k
    gf_group->bit_allocation[cur_index] = target;
2232
138k
  }
2233
138k
}
2234
2235
static inline void set_baseline_gf_interval(PRIMARY_RATE_CONTROL *p_rc,
2236
22.9k
                                            int arf_position) {
2237
22.9k
  p_rc->baseline_gf_interval = arf_position;
2238
22.9k
}
2239
2240
// initialize GF_GROUP_STATS
2241
138k
static void init_gf_stats(GF_GROUP_STATS *gf_stats) {
2242
138k
  gf_stats->gf_group_err = 0.0;
2243
138k
  gf_stats->gf_group_raw_error = 0.0;
2244
138k
  gf_stats->gf_group_skip_pct = 0.0;
2245
138k
  gf_stats->gf_group_inactive_zone_rows = 0.0;
2246
2247
138k
  gf_stats->mv_ratio_accumulator = 0.0;
2248
138k
  gf_stats->decay_accumulator = 1.0;
2249
138k
  gf_stats->zero_motion_accumulator = 1.0;
2250
138k
  gf_stats->loop_decay_rate = 1.0;
2251
138k
  gf_stats->last_loop_decay_rate = 1.0;
2252
138k
  gf_stats->this_frame_mv_in_out = 0.0;
2253
138k
  gf_stats->mv_in_out_accumulator = 0.0;
2254
138k
  gf_stats->abs_mv_in_out_accumulator = 0.0;
2255
2256
138k
  gf_stats->avg_sr_coded_error = 0.0;
2257
138k
  gf_stats->avg_pcnt_second_ref = 0.0;
2258
138k
  gf_stats->avg_new_mv_count = 0.0;
2259
138k
  gf_stats->avg_wavelet_energy = 0.0;
2260
138k
  gf_stats->avg_raw_err_stdev = 0.0;
2261
138k
  gf_stats->non_zero_stdev_count = 0;
2262
138k
}
2263
2264
static void accumulate_gop_stats(AV1_COMP *cpi, int is_intra_only, int f_w,
2265
                                 int f_h, FIRSTPASS_STATS *next_frame,
2266
                                 const FIRSTPASS_STATS *start_pos,
2267
22.9k
                                 GF_GROUP_STATS *gf_stats, int *idx) {
2268
22.9k
  int i, flash_detected;
2269
22.9k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
2270
22.9k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2271
22.9k
  RATE_CONTROL *const rc = &cpi->rc;
2272
22.9k
  FRAME_INFO *frame_info = &cpi->frame_info;
2273
22.9k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2274
2275
22.9k
  init_gf_stats(gf_stats);
2276
22.9k
  av1_zero(*next_frame);
2277
2278
  // If this is a key frame or the overlay from a previous arf then
2279
  // the error score / cost of this frame has already been accounted for.
2280
22.9k
  i = is_intra_only;
2281
  // get the determined gf group length from p_rc->gf_intervals
2282
37.8k
  while (i < p_rc->gf_intervals[p_rc->cur_gf_index]) {
2283
    // read in the next frame
2284
14.9k
    if (EOF == input_stats(twopass, &cpi->twopass_frame, next_frame)) break;
2285
    // Accumulate error score of frames in this gf group.
2286
14.9k
    double mod_frame_err =
2287
14.9k
        calculate_modified_err(frame_info, twopass, oxcf, next_frame);
2288
    // accumulate stats for this frame
2289
14.9k
    accumulate_this_frame_stats(next_frame, mod_frame_err, gf_stats);
2290
14.9k
    ++i;
2291
14.9k
  }
2292
2293
22.9k
  reset_fpf_position(&cpi->twopass_frame, start_pos);
2294
2295
22.9k
  i = is_intra_only;
2296
22.9k
  input_stats(twopass, &cpi->twopass_frame, next_frame);
2297
30.6k
  while (i < p_rc->gf_intervals[p_rc->cur_gf_index]) {
2298
    // read in the next frame
2299
14.9k
    if (EOF == input_stats(twopass, &cpi->twopass_frame, next_frame)) break;
2300
2301
    // Test for the case where there is a brief flash but the prediction
2302
    // quality back to an earlier frame is then restored.
2303
7.66k
    flash_detected = detect_flash(twopass, &cpi->twopass_frame, 0);
2304
2305
    // accumulate stats for next frame
2306
7.66k
    accumulate_next_frame_stats(next_frame, flash_detected,
2307
7.66k
                                rc->frames_since_key, i, gf_stats, f_w, f_h);
2308
2309
7.66k
    ++i;
2310
7.66k
  }
2311
2312
22.9k
  i = p_rc->gf_intervals[p_rc->cur_gf_index];
2313
22.9k
  average_gf_stats(i, gf_stats);
2314
2315
22.9k
  *idx = i;
2316
22.9k
}
2317
2318
static void update_gop_length(RATE_CONTROL *rc, PRIMARY_RATE_CONTROL *p_rc,
2319
22.9k
                              int idx, int is_final_pass) {
2320
22.9k
  if (is_final_pass) {
2321
11.4k
    rc->intervals_till_gf_calculate_due--;
2322
11.4k
    p_rc->cur_gf_index++;
2323
11.4k
  }
2324
2325
  // Was the group length constrained by the requirement for a new KF?
2326
22.9k
  p_rc->constrained_gf_group = (idx >= rc->frames_to_key) ? 1 : 0;
2327
2328
22.9k
  set_baseline_gf_interval(p_rc, idx);
2329
22.9k
  rc->frames_till_gf_update_due = p_rc->baseline_gf_interval;
2330
22.9k
}
2331
2332
// #define FIXED_ARF_BITS
2333
#ifdef FIXED_ARF_BITS
2334
#define ARF_BITS_FRACTION 0.75
2335
#endif
2336
/*!\brief Distributes bits to frames in a group
2337
 *
2338
 *\ingroup rate_control
2339
 *
2340
 * This function decides on the allocation of bits between the different
2341
 * frames and types of frame in a GF/ARF group.
2342
 *
2343
 * \param[in]   cpi           Top - level encoder instance structure
2344
 * \param[in]   rc            Rate control data
2345
 * \param[in]   gf_group      GF/ARF group data structure
2346
 * \param[in]   is_key_frame  Indicates if the first frame in the group is
2347
 *                            also a key frame.
2348
 * \param[in]   use_arf       Are ARF frames enabled or is this a GF only
2349
 *                            uni-directional group.
2350
 * \param[in]   gf_group_bits Bits available to be allocated.
2351
 *
2352
 * \remark No return but updates the rate control and group data structures
2353
 *         to reflect the allocation of bits.
2354
 */
2355
void av1_gop_bit_allocation(const AV1_COMP *cpi, RATE_CONTROL *const rc,
2356
                            GF_GROUP *gf_group, int is_key_frame, int use_arf,
2357
22.9k
                            int64_t gf_group_bits) {
2358
22.9k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2359
  // Calculate the extra bits to be used for boosted frame(s)
2360
#ifdef FIXED_ARF_BITS
2361
  int gf_arf_bits = (int)(ARF_BITS_FRACTION * gf_group_bits);
2362
#else
2363
22.9k
  int gf_arf_bits = calculate_boost_bits(
2364
22.9k
      p_rc->baseline_gf_interval - (rc->frames_since_key == 0), p_rc->gfu_boost,
2365
22.9k
      gf_group_bits);
2366
22.9k
#endif
2367
2368
22.9k
  gf_arf_bits = adjust_boost_bits_for_target_level(cpi, rc, gf_arf_bits,
2369
22.9k
                                                   gf_group_bits, 1);
2370
2371
  // Allocate bits to each of the frames in the GF group.
2372
22.9k
  allocate_gf_group_bits(gf_group, p_rc, rc, gf_group_bits, gf_arf_bits,
2373
22.9k
                         is_key_frame, use_arf);
2374
22.9k
}
2375
#undef ARF_BITS_FRACTION
2376
2377
#define MAX_GF_BOOST 5400
2378
0
#define REDUCE_GF_LENGTH_THRESH 4
2379
0
#define REDUCE_GF_LENGTH_TO_KEY_THRESH 9
2380
0
#define REDUCE_GF_LENGTH_BY 1
2381
static void set_gop_bits_boost(AV1_COMP *cpi, int i, int is_intra_only,
2382
                               int is_final_pass, int use_alt_ref,
2383
                               int alt_offset, const FIRSTPASS_STATS *start_pos,
2384
22.9k
                               GF_GROUP_STATS *gf_stats) {
2385
  // Should we use the alternate reference frame.
2386
22.9k
  AV1_COMMON *const cm = &cpi->common;
2387
22.9k
  RATE_CONTROL *const rc = &cpi->rc;
2388
22.9k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2389
22.9k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
2390
22.9k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
2391
22.9k
  FRAME_INFO *frame_info = &cpi->frame_info;
2392
22.9k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2393
22.9k
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
2394
2395
22.9k
  int ext_len = i - is_intra_only;
2396
22.9k
  if (use_alt_ref) {
2397
0
    const int forward_frames = (rc->frames_to_key - i >= ext_len)
2398
0
                                   ? ext_len
2399
0
                                   : AOMMAX(0, rc->frames_to_key - i);
2400
2401
    // Calculate the boost for alt ref.
2402
0
    p_rc->gfu_boost = av1_calc_arf_boost(
2403
0
        twopass, &cpi->twopass_frame, p_rc, frame_info, alt_offset,
2404
0
        forward_frames, ext_len, &p_rc->num_stats_used_for_gfu_boost,
2405
0
        &p_rc->num_stats_required_for_gfu_boost, cpi->ppi->lap_enabled);
2406
22.9k
  } else {
2407
22.9k
    reset_fpf_position(&cpi->twopass_frame, start_pos);
2408
22.9k
    p_rc->gfu_boost = AOMMIN(
2409
22.9k
        MAX_GF_BOOST,
2410
22.9k
        av1_calc_arf_boost(
2411
22.9k
            twopass, &cpi->twopass_frame, p_rc, frame_info, alt_offset, ext_len,
2412
22.9k
            0, &p_rc->num_stats_used_for_gfu_boost,
2413
22.9k
            &p_rc->num_stats_required_for_gfu_boost, cpi->ppi->lap_enabled));
2414
22.9k
  }
2415
2416
22.9k
#define LAST_ALR_BOOST_FACTOR 0.2f
2417
22.9k
  p_rc->arf_boost_factor = 1.0;
2418
22.9k
  if (use_alt_ref && !is_lossless_requested(rc_cfg)) {
2419
    // Reduce the boost of altref in the last gf group
2420
0
    if (rc->frames_to_key - ext_len == REDUCE_GF_LENGTH_BY ||
2421
0
        rc->frames_to_key - ext_len == 0) {
2422
0
      p_rc->arf_boost_factor = LAST_ALR_BOOST_FACTOR;
2423
0
    }
2424
0
  }
2425
2426
  // Reset the file position.
2427
22.9k
  reset_fpf_position(&cpi->twopass_frame, start_pos);
2428
22.9k
  if (cpi->ppi->lap_enabled) {
2429
    // Since we don't have enough stats to know the actual error of the
2430
    // gf group, we assume error of each frame to be equal to 1 and set
2431
    // the error of the group as baseline_gf_interval.
2432
22.9k
    gf_stats->gf_group_err = p_rc->baseline_gf_interval;
2433
22.9k
  }
2434
  // Calculate the bits to be allocated to the gf/arf group as a whole
2435
22.9k
  p_rc->gf_group_bits =
2436
22.9k
      calculate_total_gf_group_bits(cpi, gf_stats->gf_group_err);
2437
2438
22.9k
#if GROUP_ADAPTIVE_MAXQ
2439
  // Calculate an estimate of the maxq needed for the group.
2440
  // We are more aggressive about correcting for sections
2441
  // where there could be significant overshoot than for easier
2442
  // sections where we do not wish to risk creating an overshoot
2443
  // of the allocated bit budget.
2444
22.9k
  if ((rc_cfg->mode != AOM_Q) && (p_rc->baseline_gf_interval > 1) &&
2445
0
      is_final_pass) {
2446
0
    const int vbr_group_bits_per_frame =
2447
0
        (int)(p_rc->gf_group_bits / p_rc->baseline_gf_interval);
2448
0
    const double group_av_err =
2449
0
        gf_stats->gf_group_raw_error / p_rc->baseline_gf_interval;
2450
0
    const double group_av_skip_pct =
2451
0
        gf_stats->gf_group_skip_pct / p_rc->baseline_gf_interval;
2452
0
    const double group_av_inactive_zone =
2453
0
        ((gf_stats->gf_group_inactive_zone_rows * 2) /
2454
0
         (p_rc->baseline_gf_interval * (double)cm->mi_params.mb_rows));
2455
2456
0
    int tmp_q;
2457
0
    tmp_q = get_twopass_worst_quality(
2458
0
        cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2459
0
        vbr_group_bits_per_frame);
2460
0
    rc->active_worst_quality = AOMMAX(tmp_q, rc->active_worst_quality >> 1);
2461
0
  }
2462
22.9k
#endif
2463
2464
  // Adjust KF group bits and error remaining.
2465
22.9k
  if (is_final_pass) twopass->kf_group_error_left -= gf_stats->gf_group_err;
2466
2467
  // Reset the file position.
2468
22.9k
  reset_fpf_position(&cpi->twopass_frame, start_pos);
2469
2470
  // Calculate a section intra ratio used in setting max loop filter.
2471
22.9k
  if (rc->frames_since_key != 0) {
2472
0
    twopass->section_intra_rating = calculate_section_intra_ratio(
2473
0
        start_pos, twopass->stats_buf_ctx->stats_in_end,
2474
0
        p_rc->baseline_gf_interval);
2475
0
  }
2476
2477
22.9k
  av1_gop_bit_allocation(cpi, rc, gf_group, rc->frames_since_key == 0,
2478
22.9k
                         use_alt_ref, p_rc->gf_group_bits);
2479
2480
  // TODO(jingning): Generalize this condition.
2481
22.9k
  if (is_final_pass) {
2482
11.4k
    cpi->ppi->gf_state.arf_gf_boost_lst = use_alt_ref;
2483
2484
    // Reset rolling actual and target bits counters for ARF groups.
2485
11.4k
    twopass->rolling_arf_group_target_bits = 1;
2486
11.4k
    twopass->rolling_arf_group_actual_bits = 1;
2487
11.4k
  }
2488
#if CONFIG_BITRATE_ACCURACY
2489
  if (is_final_pass) {
2490
    av1_vbr_rc_set_gop_bit_budget(&cpi->vbr_rc_info,
2491
                                  p_rc->baseline_gf_interval);
2492
  }
2493
#endif
2494
22.9k
}
2495
2496
/*!\brief Define a GF group.
2497
 *
2498
 * \ingroup gf_group_algo
2499
 * This function defines the structure of a GF group, along with various
2500
 * parameters regarding bit-allocation and quality setup.
2501
 *
2502
 * \param[in]    cpi             Top-level encoder structure
2503
 * \param[in]    frame_params    Structure with frame parameters
2504
 * \param[in]    is_final_pass   Whether this is the final pass for the
2505
 *                               GF group, or a trial (non-zero)
2506
 *
2507
 * \remark Nothing is returned. Instead, cpi->ppi->gf_group is changed.
2508
 */
2509
static void define_gf_group(AV1_COMP *cpi, EncodeFrameParams *frame_params,
2510
161k
                            int is_final_pass) {
2511
161k
  AV1_COMMON *const cm = &cpi->common;
2512
161k
  RATE_CONTROL *const rc = &cpi->rc;
2513
161k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2514
161k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2515
161k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
2516
161k
  FIRSTPASS_STATS next_frame;
2517
161k
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
2518
161k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
2519
161k
  const GFConfig *const gf_cfg = &oxcf->gf_cfg;
2520
161k
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
2521
161k
  const int f_w = cm->width;
2522
161k
  const int f_h = cm->height;
2523
161k
  int i;
2524
161k
  const int is_intra_only = rc->frames_since_key == 0;
2525
2526
161k
  cpi->ppi->internal_altref_allowed = (gf_cfg->gf_max_pyr_height > 1);
2527
2528
  // Reset the GF group data structures unless this is a key
2529
  // frame in which case it will already have been done.
2530
161k
  if (!is_intra_only) {
2531
19.4k
    av1_zero(cpi->ppi->gf_group);
2532
19.4k
    cpi->gf_frame_index = 0;
2533
19.4k
  }
2534
2535
161k
  if (has_no_stats_stage(cpi)) {
2536
138k
    define_gf_group_pass0(cpi);
2537
138k
    return;
2538
138k
  }
2539
2540
#if CONFIG_THREE_PASS
2541
  if (cpi->third_pass_ctx && oxcf->pass == AOM_RC_THIRD_PASS) {
2542
    int ret = define_gf_group_pass3(cpi, frame_params, is_final_pass);
2543
    if (ret == 0) return;
2544
2545
    av1_free_thirdpass_ctx(cpi->third_pass_ctx);
2546
    cpi->third_pass_ctx = NULL;
2547
  }
2548
#endif  // CONFIG_THREE_PASS
2549
2550
  // correct frames_to_key when lookahead queue is emptying
2551
22.9k
  if (cpi->ppi->lap_enabled) {
2552
22.9k
    correct_frames_to_key(cpi);
2553
22.9k
  }
2554
2555
22.9k
  GF_GROUP_STATS gf_stats;
2556
22.9k
  accumulate_gop_stats(cpi, is_intra_only, f_w, f_h, &next_frame, start_pos,
2557
22.9k
                       &gf_stats, &i);
2558
2559
22.9k
  const int can_disable_arf = !gf_cfg->gf_min_pyr_height;
2560
2561
  // If this is a key frame or the overlay from a previous arf then
2562
  // the error score / cost of this frame has already been accounted for.
2563
22.9k
  const int active_min_gf_interval = rc->min_gf_interval;
2564
2565
  // Disable internal ARFs for "still" gf groups.
2566
  //   zero_motion_accumulator: minimum percentage of (0,0) motion;
2567
  //   avg_sr_coded_error:      average of the SSE per pixel of each frame;
2568
  //   avg_raw_err_stdev:       average of the standard deviation of (0,0)
2569
  //                            motion error per block of each frame.
2570
22.9k
  const int can_disable_internal_arfs = gf_cfg->gf_min_pyr_height <= 1;
2571
22.9k
  if (can_disable_internal_arfs &&
2572
22.9k
      gf_stats.zero_motion_accumulator > MIN_ZERO_MOTION &&
2573
22.9k
      gf_stats.avg_sr_coded_error < MAX_SR_CODED_ERROR &&
2574
17.5k
      gf_stats.avg_raw_err_stdev < MAX_RAW_ERR_VAR) {
2575
17.5k
    cpi->ppi->internal_altref_allowed = 0;
2576
17.5k
  }
2577
2578
22.9k
  int use_alt_ref;
2579
22.9k
  if (can_disable_arf) {
2580
22.9k
    use_alt_ref =
2581
22.9k
        !is_almost_static(gf_stats.zero_motion_accumulator,
2582
22.9k
                          twopass->kf_zeromotion_pct, cpi->ppi->lap_enabled) &&
2583
0
        p_rc->use_arf_in_this_kf_group && (i < gf_cfg->lag_in_frames) &&
2584
0
        (i >= MIN_GF_INTERVAL);
2585
22.9k
  } else {
2586
0
    use_alt_ref = p_rc->use_arf_in_this_kf_group &&
2587
0
                  (i < gf_cfg->lag_in_frames) && (i > 2);
2588
0
  }
2589
22.9k
  if (use_alt_ref) {
2590
0
    gf_group->max_layer_depth_allowed = gf_cfg->gf_max_pyr_height;
2591
22.9k
  } else {
2592
22.9k
    gf_group->max_layer_depth_allowed = 0;
2593
22.9k
  }
2594
2595
22.9k
  int alt_offset = 0;
2596
  // The length reduction strategy is tweaked for certain cases, and doesn't
2597
  // work well for certain other cases.
2598
22.9k
  const int allow_gf_length_reduction =
2599
22.9k
      ((rc_cfg->mode == AOM_Q && rc_cfg->cq_level <= 128) ||
2600
12.2k
       !cpi->ppi->internal_altref_allowed) &&
2601
20.0k
      !is_lossless_requested(rc_cfg);
2602
2603
22.9k
  if (allow_gf_length_reduction && use_alt_ref) {
2604
    // adjust length of this gf group if one of the following condition met
2605
    // 1: only one overlay frame left and this gf is too long
2606
    // 2: next gf group is too short to have arf compared to the current gf
2607
2608
    // maximum length of next gf group
2609
0
    const int next_gf_len = rc->frames_to_key - i;
2610
0
    const int single_overlay_left =
2611
0
        next_gf_len == 0 && i > REDUCE_GF_LENGTH_THRESH;
2612
    // the next gf is probably going to have a ARF but it will be shorter than
2613
    // this gf
2614
0
    const int unbalanced_gf =
2615
0
        i > REDUCE_GF_LENGTH_TO_KEY_THRESH &&
2616
0
        next_gf_len + 1 < REDUCE_GF_LENGTH_TO_KEY_THRESH &&
2617
0
        next_gf_len + 1 >= rc->min_gf_interval;
2618
2619
0
    if (single_overlay_left || unbalanced_gf) {
2620
0
      const int roll_back = REDUCE_GF_LENGTH_BY;
2621
      // Reduce length only if active_min_gf_interval will be respected later.
2622
0
      if (i - roll_back >= active_min_gf_interval + 1) {
2623
0
        alt_offset = -roll_back;
2624
0
        i -= roll_back;
2625
0
        if (is_final_pass) rc->intervals_till_gf_calculate_due = 0;
2626
0
        p_rc->gf_intervals[p_rc->cur_gf_index] -= roll_back;
2627
0
        reset_fpf_position(&cpi->twopass_frame, start_pos);
2628
0
        accumulate_gop_stats(cpi, is_intra_only, f_w, f_h, &next_frame,
2629
0
                             start_pos, &gf_stats, &i);
2630
0
      }
2631
0
    }
2632
0
  }
2633
2634
22.9k
  update_gop_length(rc, p_rc, i, is_final_pass);
2635
2636
  // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
2637
22.9k
  av1_gop_setup_structure(cpi);
2638
2639
22.9k
  set_gop_bits_boost(cpi, i, is_intra_only, is_final_pass, use_alt_ref,
2640
22.9k
                     alt_offset, start_pos, &gf_stats);
2641
2642
22.9k
  frame_params->frame_type =
2643
22.9k
      rc->frames_since_key == 0 ? KEY_FRAME : INTER_FRAME;
2644
22.9k
  frame_params->show_frame =
2645
22.9k
      !(gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE ||
2646
22.9k
        gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE);
2647
22.9k
}
2648
2649
#if CONFIG_THREE_PASS
2650
/*!\brief Define a GF group for the third apss.
2651
 *
2652
 * \ingroup gf_group_algo
2653
 * This function defines the structure of a GF group for the third pass, along
2654
 * with various parameters regarding bit-allocation and quality setup based on
2655
 * the two-pass bitstream.
2656
 * Much of the function still uses the strategies used for the second pass and
2657
 * relies on first pass statistics. It is expected that over time these portions
2658
 * would be replaced with strategies specific to the third pass.
2659
 *
2660
 * \param[in]    cpi             Top-level encoder structure
2661
 * \param[in]    frame_params    Structure with frame parameters
2662
 * \param[in]    is_final_pass   Whether this is the final pass for the
2663
 *                               GF group, or a trial (non-zero)
2664
 *
2665
 * \return       0: Success;
2666
 *              -1: There are conflicts between the bitstream and current config
2667
 *               The values in cpi->ppi->gf_group are also changed.
2668
 */
2669
static int define_gf_group_pass3(AV1_COMP *cpi, EncodeFrameParams *frame_params,
2670
                                 int is_final_pass) {
2671
  if (!cpi->third_pass_ctx) return -1;
2672
  AV1_COMMON *const cm = &cpi->common;
2673
  RATE_CONTROL *const rc = &cpi->rc;
2674
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2675
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2676
  FIRSTPASS_STATS next_frame;
2677
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
2678
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
2679
  const GFConfig *const gf_cfg = &oxcf->gf_cfg;
2680
  const int f_w = cm->width;
2681
  const int f_h = cm->height;
2682
  int i;
2683
  const int is_intra_only = rc->frames_since_key == 0;
2684
2685
  cpi->ppi->internal_altref_allowed = (gf_cfg->gf_max_pyr_height > 1);
2686
2687
  // Reset the GF group data structures unless this is a key
2688
  // frame in which case it will already have been done.
2689
  if (!is_intra_only) {
2690
    av1_zero(cpi->ppi->gf_group);
2691
    cpi->gf_frame_index = 0;
2692
  }
2693
2694
  GF_GROUP_STATS gf_stats;
2695
  accumulate_gop_stats(cpi, is_intra_only, f_w, f_h, &next_frame, start_pos,
2696
                       &gf_stats, &i);
2697
2698
  const int can_disable_arf = !gf_cfg->gf_min_pyr_height;
2699
2700
  // TODO(any): set cpi->ppi->internal_altref_allowed accordingly;
2701
2702
  int use_alt_ref = av1_check_use_arf(cpi->third_pass_ctx);
2703
  if (use_alt_ref == 0 && !can_disable_arf) return -1;
2704
  if (use_alt_ref) {
2705
    gf_group->max_layer_depth_allowed = gf_cfg->gf_max_pyr_height;
2706
  } else {
2707
    gf_group->max_layer_depth_allowed = 0;
2708
  }
2709
2710
  update_gop_length(rc, p_rc, i, is_final_pass);
2711
2712
  // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
2713
  av1_gop_setup_structure(cpi);
2714
2715
  set_gop_bits_boost(cpi, i, is_intra_only, is_final_pass, use_alt_ref, 0,
2716
                     start_pos, &gf_stats);
2717
2718
  frame_params->frame_type = cpi->third_pass_ctx->frame_info[0].frame_type;
2719
  frame_params->show_frame = cpi->third_pass_ctx->frame_info[0].is_show_frame;
2720
  return 0;
2721
}
2722
#endif  // CONFIG_THREE_PASS
2723
2724
// Minimum % intra coding observed in first pass (1.0 = 100%)
2725
832
#define MIN_INTRA_LEVEL 0.25
2726
// Minimum ratio between the % of intra coding and inter coding in the first
2727
// pass after discounting neutral blocks (discounting neutral blocks in this
2728
// way helps catch scene cuts in clips with very flat areas or letter box
2729
// format clips with image padding.
2730
718
#define INTRA_VS_INTER_THRESH 2.0
2731
// Hard threshold where the first pass chooses intra for almost all blocks.
2732
// In such a case even if the frame is not a scene cut coding a key frame
2733
// may be a good option.
2734
2.26k
#define VERY_LOW_INTER_THRESH 0.05
2735
// Maximum threshold for the relative ratio of intra error score vs best
2736
// inter error score.
2737
669
#define KF_II_ERR_THRESHOLD 1.9
2738
// In real scene cuts there is almost always a sharp change in the intra
2739
// or inter error score.
2740
1.30k
#define ERR_CHANGE_THRESHOLD 0.4
2741
// For real scene cuts we expect an improvment in the intra inter error
2742
// ratio in the next frame.
2743
638
#define II_IMPROVEMENT_THRESHOLD 3.5
2744
1.54k
#define KF_II_MAX 128.0
2745
// Intra / Inter threshold very low
2746
832
#define VERY_LOW_II 1.5
2747
// Clean slide transitions we expect a sharp single frame spike in error.
2748
759
#define ERROR_SPIKE 5.0
2749
2750
// Slide show transition detection.
2751
// Tests for case where there is very low error either side of the current frame
2752
// but much higher just for this frame. This can help detect key frames in
2753
// slide shows even where the slides are pictures of different sizes.
2754
// Also requires that intra and inter errors are very similar to help eliminate
2755
// harmful false positives.
2756
// It will not help if the transition is a fade or other multi-frame effect.
2757
static int slide_transition(const FIRSTPASS_STATS *this_frame,
2758
                            const FIRSTPASS_STATS *last_frame,
2759
832
                            const FIRSTPASS_STATS *next_frame) {
2760
832
  return (this_frame->intra_error < (this_frame->coded_error * VERY_LOW_II)) &&
2761
758
         (this_frame->coded_error > (last_frame->coded_error * ERROR_SPIKE)) &&
2762
1
         (this_frame->coded_error > (next_frame->coded_error * ERROR_SPIKE));
2763
832
}
2764
2765
// Threshold for use of the lagging second reference frame. High second ref
2766
// usage may point to a transient event like a flash or occlusion rather than
2767
// a real scene cut.
2768
// We adapt the threshold based on number of frames in this key-frame group so
2769
// far.
2770
10.4k
static double get_second_ref_usage_thresh(int frame_count_so_far) {
2771
10.4k
  const int adapt_upto = 32;
2772
10.4k
  const double min_second_ref_usage_thresh = 0.085;
2773
10.4k
  const double second_ref_usage_thresh_max_delta = 0.035;
2774
10.4k
  if (frame_count_so_far >= adapt_upto) {
2775
0
    return min_second_ref_usage_thresh + second_ref_usage_thresh_max_delta;
2776
0
  }
2777
10.4k
  return min_second_ref_usage_thresh +
2778
10.4k
         ((double)frame_count_so_far / (adapt_upto - 1)) *
2779
10.4k
             second_ref_usage_thresh_max_delta;
2780
10.4k
}
2781
2782
static int test_candidate_kf(const FIRSTPASS_INFO *firstpass_info,
2783
                             int this_stats_index, int frame_count_so_far,
2784
                             enum aom_rc_mode rc_mode, int scenecut_mode,
2785
15.9k
                             int num_mbs) {
2786
15.9k
  const FIRSTPASS_STATS *last_stats =
2787
15.9k
      av1_firstpass_info_peek(firstpass_info, this_stats_index - 1);
2788
15.9k
  const FIRSTPASS_STATS *this_stats =
2789
15.9k
      av1_firstpass_info_peek(firstpass_info, this_stats_index);
2790
15.9k
  const FIRSTPASS_STATS *next_stats =
2791
15.9k
      av1_firstpass_info_peek(firstpass_info, this_stats_index + 1);
2792
15.9k
  if (last_stats == NULL || this_stats == NULL || next_stats == NULL) {
2793
5.50k
    return 0;
2794
5.50k
  }
2795
2796
10.4k
  int is_viable_kf = 0;
2797
10.4k
  double pcnt_intra = 1.0 - this_stats->pcnt_inter;
2798
10.4k
  double modified_pcnt_inter =
2799
10.4k
      this_stats->pcnt_inter - this_stats->pcnt_neutral;
2800
10.4k
  const double second_ref_usage_thresh =
2801
10.4k
      get_second_ref_usage_thresh(frame_count_so_far);
2802
10.4k
  int frames_to_test_after_candidate_key = SCENE_CUT_KEY_TEST_INTERVAL;
2803
10.4k
  int count_for_tolerable_prediction = 3;
2804
2805
  // We do "-1" because the candidate key is not counted.
2806
10.4k
  int stats_after_this_stats =
2807
10.4k
      av1_firstpass_info_future_count(firstpass_info, this_stats_index) - 1;
2808
2809
10.4k
  if (scenecut_mode == ENABLE_SCENECUT_MODE_1) {
2810
0
    if (stats_after_this_stats < 3) {
2811
0
      return 0;
2812
0
    } else {
2813
0
      frames_to_test_after_candidate_key = 3;
2814
0
      count_for_tolerable_prediction = 1;
2815
0
    }
2816
0
  }
2817
  // Make sure we have enough stats after the candidate key.
2818
10.4k
  frames_to_test_after_candidate_key =
2819
10.4k
      AOMMIN(frames_to_test_after_candidate_key, stats_after_this_stats);
2820
2821
  // Does the frame satisfy the primary criteria of a key frame?
2822
  // See above for an explanation of the test criteria.
2823
  // If so, then examine how well it predicts subsequent frames.
2824
10.4k
  if (IMPLIES(rc_mode == AOM_Q, frame_count_so_far >= 3) &&
2825
3.86k
      (this_stats->pcnt_second_ref < second_ref_usage_thresh) &&
2826
3.28k
      (next_stats->pcnt_second_ref < second_ref_usage_thresh) &&
2827
2.26k
      ((this_stats->pcnt_inter < VERY_LOW_INTER_THRESH) ||
2828
832
       slide_transition(this_stats, last_stats, next_stats) ||
2829
832
       ((pcnt_intra > MIN_INTRA_LEVEL) &&
2830
718
        (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
2831
669
        ((this_stats->intra_error /
2832
669
          DOUBLE_DIVIDE_CHECK(this_stats->coded_error)) <
2833
669
         KF_II_ERR_THRESHOLD) &&
2834
669
        ((fabs(last_stats->coded_error - this_stats->coded_error) /
2835
669
              DOUBLE_DIVIDE_CHECK(this_stats->coded_error) >
2836
669
          ERR_CHANGE_THRESHOLD) ||
2837
639
         (fabs(last_stats->intra_error - this_stats->intra_error) /
2838
639
              DOUBLE_DIVIDE_CHECK(this_stats->intra_error) >
2839
639
          ERR_CHANGE_THRESHOLD) ||
2840
638
         ((next_stats->intra_error /
2841
638
           DOUBLE_DIVIDE_CHECK(next_stats->coded_error)) >
2842
1.46k
          II_IMPROVEMENT_THRESHOLD))))) {
2843
1.46k
    int i;
2844
1.46k
    double boost_score = 0.0;
2845
1.46k
    double old_boost_score = 0.0;
2846
1.46k
    double decay_accumulator = 1.0;
2847
2848
    // Examine how well the key frame predicts subsequent frames.
2849
1.72k
    for (i = 1; i <= frames_to_test_after_candidate_key; ++i) {
2850
      // Get the next frame details
2851
1.54k
      const FIRSTPASS_STATS *local_next_frame =
2852
1.54k
          av1_firstpass_info_peek(firstpass_info, this_stats_index + i);
2853
1.54k
      double next_iiratio =
2854
1.54k
          (BOOST_FACTOR * local_next_frame->intra_error /
2855
1.54k
           DOUBLE_DIVIDE_CHECK(local_next_frame->coded_error));
2856
2857
1.54k
      if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
2858
2859
      // Cumulative effect of decay in prediction quality.
2860
1.54k
      if (local_next_frame->pcnt_inter > 0.85)
2861
68
        decay_accumulator *= local_next_frame->pcnt_inter;
2862
1.47k
      else
2863
1.47k
        decay_accumulator *= (0.85 + local_next_frame->pcnt_inter) / 2.0;
2864
2865
      // Keep a running total.
2866
1.54k
      boost_score += (decay_accumulator * next_iiratio);
2867
2868
      // Test various breakout clauses.
2869
      // TODO(any): Test of intra error should be normalized to an MB.
2870
1.54k
      if ((local_next_frame->pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
2871
267
          (((local_next_frame->pcnt_inter - local_next_frame->pcnt_neutral) <
2872
267
            0.20) &&
2873
183
           (next_iiratio < 3.0)) ||
2874
267
          ((boost_score - old_boost_score) < 3.0) ||
2875
1.28k
          (local_next_frame->intra_error < (200.0 / (double)num_mbs))) {
2876
1.28k
        break;
2877
1.28k
      }
2878
2879
262
      old_boost_score = boost_score;
2880
262
    }
2881
2882
    // If there is tolerable prediction for at least the next 3 frames then
2883
    // break out else discard this potential key frame and move on
2884
1.46k
    if (boost_score > 30.0 && (i > count_for_tolerable_prediction)) {
2885
0
      is_viable_kf = 1;
2886
1.46k
    } else {
2887
1.46k
      is_viable_kf = 0;
2888
1.46k
    }
2889
1.46k
  }
2890
10.4k
  return is_viable_kf;
2891
10.4k
}
2892
2893
365k
#define FRAMES_TO_CHECK_DECAY 8
2894
11.4k
#define KF_MIN_FRAME_BOOST 80.0
2895
11.4k
#define KF_MAX_FRAME_BOOST 128.0
2896
#define MIN_KF_BOOST 600  // Minimum boost for non-static KF interval
2897
#define MAX_KF_BOOST 3200
2898
#define MIN_STATIC_KF_BOOST 5400  // Minimum boost for static KF interval
2899
2900
171k
static int detect_app_forced_key(AV1_COMP *cpi) {
2901
171k
  int num_frames_to_app_forced_key = is_forced_keyframe_pending(
2902
171k
      cpi->ppi->lookahead, cpi->ppi->lookahead->max_sz, cpi->compressor_stage);
2903
171k
  return num_frames_to_app_forced_key;
2904
171k
}
2905
2906
11.4k
static int get_projected_kf_boost(AV1_COMP *cpi) {
2907
  /*
2908
   * If num_stats_used_for_kf_boost >= frames_to_key, then
2909
   * all stats needed for prior boost calculation are available.
2910
   * Hence projecting the prior boost is not needed in this cases.
2911
   */
2912
11.4k
  if (cpi->ppi->p_rc.num_stats_used_for_kf_boost >= cpi->rc.frames_to_key)
2913
11.4k
    return cpi->ppi->p_rc.kf_boost;
2914
2915
  // Get the current tpl factor (number of frames = frames_to_key).
2916
0
  double tpl_factor = av1_get_kf_boost_projection_factor(cpi->rc.frames_to_key);
2917
  // Get the tpl factor when number of frames = num_stats_used_for_kf_boost.
2918
0
  double tpl_factor_num_stats = av1_get_kf_boost_projection_factor(
2919
0
      cpi->ppi->p_rc.num_stats_used_for_kf_boost);
2920
0
  int projected_kf_boost =
2921
0
      (int)rint((tpl_factor * cpi->ppi->p_rc.kf_boost) / tpl_factor_num_stats);
2922
0
  return projected_kf_boost;
2923
11.4k
}
2924
2925
/*!\brief Determine the location of the next key frame
2926
 *
2927
 * \ingroup gf_group_algo
2928
 * This function decides the placement of the next key frame when a
2929
 * scenecut is detected or the maximum key frame distance is reached.
2930
 *
2931
 * \param[in]    cpi              Top-level encoder structure
2932
 * \param[in]    firstpass_info   struct for firstpass info
2933
 * \param[in]    num_frames_to_detect_scenecut Maximum lookahead frames.
2934
 * \param[in]    search_start_idx   the start index for searching key frame.
2935
 *                                  Set it to one if we already know the
2936
 *                                  current frame is key frame. Otherwise,
2937
 *                                  set it to zero.
2938
 *
2939
 * \return       Number of frames to the next key including the current frame.
2940
 */
2941
static int define_kf_interval(AV1_COMP *cpi,
2942
                              const FIRSTPASS_INFO *firstpass_info,
2943
                              int num_frames_to_detect_scenecut,
2944
22.9k
                              int search_start_idx) {
2945
22.9k
  const TWO_PASS *const twopass = &cpi->ppi->twopass;
2946
22.9k
  const RATE_CONTROL *const rc = &cpi->rc;
2947
22.9k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2948
22.9k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2949
22.9k
  const KeyFrameCfg *const kf_cfg = &oxcf->kf_cfg;
2950
22.9k
  double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
2951
22.9k
  double decay_accumulator = 1.0;
2952
22.9k
  int i = 0, j;
2953
22.9k
  int frames_to_key = search_start_idx;
2954
22.9k
  int frames_since_key = rc->frames_since_key + 1;
2955
22.9k
  int scenecut_detected = 0;
2956
2957
22.9k
  int num_frames_to_next_key = detect_app_forced_key(cpi);
2958
2959
22.9k
  if (num_frames_to_detect_scenecut == 0) {
2960
0
    if (num_frames_to_next_key != -1)
2961
0
      return num_frames_to_next_key;
2962
0
    else
2963
0
      return rc->frames_to_key;
2964
0
  }
2965
2966
22.9k
  if (num_frames_to_next_key != -1)
2967
12.6k
    num_frames_to_detect_scenecut =
2968
12.6k
        AOMMIN(num_frames_to_detect_scenecut, num_frames_to_next_key);
2969
2970
  // Initialize the decay rates for the recent frames to check
2971
206k
  for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
2972
2973
22.9k
  i = 0;
2974
22.9k
  const int num_mbs = (oxcf->resize_cfg.resize_mode != RESIZE_NONE)
2975
22.9k
                          ? cpi->initial_mbs
2976
22.9k
                          : cpi->common.mi_params.MBs;
2977
22.9k
  const int future_stats_count =
2978
22.9k
      av1_firstpass_info_future_count(firstpass_info, 0);
2979
48.3k
  while (frames_to_key < future_stats_count &&
2980
36.9k
         frames_to_key < num_frames_to_detect_scenecut) {
2981
    // Provided that we are not at the end of the file...
2982
25.4k
    if ((cpi->ppi->p_rc.enable_scenecut_detection > 0) && kf_cfg->auto_key &&
2983
25.4k
        frames_to_key + 1 < future_stats_count) {
2984
15.9k
      double loop_decay_rate;
2985
2986
      // Check for a scene cut.
2987
15.9k
      if (frames_since_key >= kf_cfg->key_freq_min) {
2988
15.9k
        scenecut_detected = test_candidate_kf(
2989
15.9k
            &twopass->firstpass_info, frames_to_key, frames_since_key,
2990
15.9k
            oxcf->rc_cfg.mode, cpi->ppi->p_rc.enable_scenecut_detection,
2991
15.9k
            num_mbs);
2992
15.9k
        if (scenecut_detected) {
2993
0
          break;
2994
0
        }
2995
15.9k
      }
2996
2997
      // How fast is the prediction quality decaying?
2998
15.9k
      const FIRSTPASS_STATS *next_stats =
2999
15.9k
          av1_firstpass_info_peek(firstpass_info, frames_to_key + 1);
3000
15.9k
      loop_decay_rate = get_prediction_decay_rate(next_stats);
3001
3002
      // We want to know something about the recent past... rather than
3003
      // as used elsewhere where we are concerned with decay in prediction
3004
      // quality since the last GF or KF.
3005
15.9k
      recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
3006
15.9k
      decay_accumulator = 1.0;
3007
143k
      for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
3008
127k
        decay_accumulator *= recent_loop_decay[j];
3009
3010
      // Special check for transition or high motion followed by a
3011
      // static scene.
3012
15.9k
      if (frames_since_key >= kf_cfg->key_freq_min) {
3013
15.9k
        scenecut_detected = detect_transition_to_still(
3014
15.9k
            firstpass_info, frames_to_key + 1, rc->min_gf_interval, i,
3015
15.9k
            kf_cfg->key_freq_max - i, loop_decay_rate, decay_accumulator);
3016
15.9k
        if (scenecut_detected) {
3017
          // In the case of transition followed by a static scene, the key frame
3018
          // could be a good predictor for the following frames, therefore we
3019
          // do not use an arf.
3020
0
          p_rc->use_arf_in_this_kf_group = 0;
3021
0
          break;
3022
0
        }
3023
15.9k
      }
3024
3025
      // Step on to the next frame.
3026
15.9k
      ++frames_to_key;
3027
15.9k
      ++frames_since_key;
3028
3029
      // If we don't have a real key frame within the next two
3030
      // key_freq_max intervals then break out of the loop.
3031
15.9k
      if (frames_to_key >= 2 * kf_cfg->key_freq_max) {
3032
0
        break;
3033
0
      }
3034
15.9k
    } else {
3035
9.51k
      ++frames_to_key;
3036
9.51k
      ++frames_since_key;
3037
9.51k
    }
3038
25.4k
    ++i;
3039
25.4k
  }
3040
22.9k
  if (cpi->ppi->lap_enabled && !scenecut_detected)
3041
22.9k
    frames_to_key = num_frames_to_next_key;
3042
3043
22.9k
  return frames_to_key;
3044
22.9k
}
3045
3046
static double get_kf_group_avg_error(TWO_PASS *twopass,
3047
                                     TWO_PASS_FRAME *twopass_frame,
3048
                                     const FIRSTPASS_STATS *first_frame,
3049
                                     const FIRSTPASS_STATS *start_position,
3050
0
                                     int frames_to_key) {
3051
0
  FIRSTPASS_STATS cur_frame = *first_frame;
3052
0
  int num_frames, i;
3053
0
  double kf_group_avg_error = 0.0;
3054
3055
0
  reset_fpf_position(twopass_frame, start_position);
3056
3057
0
  for (i = 0; i < frames_to_key; ++i) {
3058
0
    kf_group_avg_error += cur_frame.coded_error;
3059
0
    if (EOF == input_stats(twopass, twopass_frame, &cur_frame)) break;
3060
0
  }
3061
0
  num_frames = i + 1;
3062
0
  num_frames = AOMMIN(num_frames, frames_to_key);
3063
0
  kf_group_avg_error = kf_group_avg_error / num_frames;
3064
3065
0
  return (kf_group_avg_error);
3066
0
}
3067
3068
static int64_t get_kf_group_bits(AV1_COMP *cpi, double kf_group_err,
3069
0
                                 double kf_group_avg_error) {
3070
0
  RATE_CONTROL *const rc = &cpi->rc;
3071
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3072
0
  int64_t kf_group_bits;
3073
0
  if (cpi->ppi->lap_enabled) {
3074
0
    kf_group_bits = (int64_t)rc->frames_to_key * rc->avg_frame_bandwidth;
3075
0
    if (cpi->oxcf.rc_cfg.vbr_corpus_complexity_lap) {
3076
0
      double vbr_corpus_complexity_lap =
3077
0
          cpi->oxcf.rc_cfg.vbr_corpus_complexity_lap / 10.0;
3078
      /* Get the average corpus complexity of the frame */
3079
0
      kf_group_bits = (int64_t)(kf_group_bits * (kf_group_avg_error /
3080
0
                                                 vbr_corpus_complexity_lap));
3081
0
    }
3082
0
  } else {
3083
0
    kf_group_bits = (int64_t)(twopass->bits_left *
3084
0
                              (kf_group_err / twopass->modified_error_left));
3085
0
  }
3086
3087
0
  return kf_group_bits;
3088
0
}
3089
3090
0
static int calc_avg_stats(AV1_COMP *cpi, FIRSTPASS_STATS *avg_frame_stat) {
3091
0
  RATE_CONTROL *const rc = &cpi->rc;
3092
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3093
0
  FIRSTPASS_STATS cur_frame;
3094
0
  av1_zero(cur_frame);
3095
0
  int num_frames = 0;
3096
  // Accumulate total stat using available number of stats.
3097
0
  for (num_frames = 0; num_frames < (rc->frames_to_key - 1); ++num_frames) {
3098
0
    if (EOF == input_stats(twopass, &cpi->twopass_frame, &cur_frame)) break;
3099
0
    av1_accumulate_stats(avg_frame_stat, &cur_frame);
3100
0
  }
3101
3102
0
  if (num_frames < 2) {
3103
0
    return num_frames;
3104
0
  }
3105
  // Average the total stat
3106
0
  avg_frame_stat->weight = avg_frame_stat->weight / num_frames;
3107
0
  avg_frame_stat->intra_error = avg_frame_stat->intra_error / num_frames;
3108
0
  avg_frame_stat->frame_avg_wavelet_energy =
3109
0
      avg_frame_stat->frame_avg_wavelet_energy / num_frames;
3110
0
  avg_frame_stat->coded_error = avg_frame_stat->coded_error / num_frames;
3111
0
  avg_frame_stat->sr_coded_error = avg_frame_stat->sr_coded_error / num_frames;
3112
0
  avg_frame_stat->pcnt_inter = avg_frame_stat->pcnt_inter / num_frames;
3113
0
  avg_frame_stat->pcnt_motion = avg_frame_stat->pcnt_motion / num_frames;
3114
0
  avg_frame_stat->pcnt_second_ref =
3115
0
      avg_frame_stat->pcnt_second_ref / num_frames;
3116
0
  avg_frame_stat->pcnt_neutral = avg_frame_stat->pcnt_neutral / num_frames;
3117
0
  avg_frame_stat->intra_skip_pct = avg_frame_stat->intra_skip_pct / num_frames;
3118
0
  avg_frame_stat->inactive_zone_rows =
3119
0
      avg_frame_stat->inactive_zone_rows / num_frames;
3120
0
  avg_frame_stat->inactive_zone_cols =
3121
0
      avg_frame_stat->inactive_zone_cols / num_frames;
3122
0
  avg_frame_stat->MVr = avg_frame_stat->MVr / num_frames;
3123
0
  avg_frame_stat->mvr_abs = avg_frame_stat->mvr_abs / num_frames;
3124
0
  avg_frame_stat->MVc = avg_frame_stat->MVc / num_frames;
3125
0
  avg_frame_stat->mvc_abs = avg_frame_stat->mvc_abs / num_frames;
3126
0
  avg_frame_stat->MVrv = avg_frame_stat->MVrv / num_frames;
3127
0
  avg_frame_stat->MVcv = avg_frame_stat->MVcv / num_frames;
3128
0
  avg_frame_stat->mv_in_out_count =
3129
0
      avg_frame_stat->mv_in_out_count / num_frames;
3130
0
  avg_frame_stat->new_mv_count = avg_frame_stat->new_mv_count / num_frames;
3131
0
  avg_frame_stat->count = avg_frame_stat->count / num_frames;
3132
0
  avg_frame_stat->duration = avg_frame_stat->duration / num_frames;
3133
3134
0
  return num_frames;
3135
0
}
3136
3137
static double get_kf_boost_score(AV1_COMP *cpi, double kf_raw_err,
3138
                                 double *zero_motion_accumulator,
3139
11.4k
                                 double *sr_accumulator, int use_avg_stat) {
3140
11.4k
  RATE_CONTROL *const rc = &cpi->rc;
3141
11.4k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3142
11.4k
  FRAME_INFO *const frame_info = &cpi->frame_info;
3143
11.4k
  FIRSTPASS_STATS frame_stat;
3144
11.4k
  av1_zero(frame_stat);
3145
11.4k
  int i = 0, num_stat_used = 0;
3146
11.4k
  double boost_score = 0.0;
3147
11.4k
  const double kf_max_boost =
3148
11.4k
      cpi->oxcf.rc_cfg.mode == AOM_Q
3149
11.4k
          ? fclamp(rc->frames_to_key * 2.0, KF_MIN_FRAME_BOOST,
3150
11.4k
                   KF_MAX_FRAME_BOOST)
3151
11.4k
          : KF_MAX_FRAME_BOOST;
3152
3153
  // Calculate the average using available number of stats.
3154
11.4k
  if (use_avg_stat) num_stat_used = calc_avg_stats(cpi, &frame_stat);
3155
3156
18.9k
  for (i = num_stat_used; i < (rc->frames_to_key - 1); ++i) {
3157
7.47k
    if (!use_avg_stat &&
3158
7.47k
        EOF == input_stats(twopass, &cpi->twopass_frame, &frame_stat))
3159
0
      break;
3160
3161
    // Monitor for static sections.
3162
    // For the first frame in kf group, the second ref indicator is invalid.
3163
7.47k
    if (i > 0) {
3164
3.14k
      *zero_motion_accumulator =
3165
3.14k
          AOMMIN(*zero_motion_accumulator, get_zero_motion_factor(&frame_stat));
3166
4.33k
    } else {
3167
4.33k
      *zero_motion_accumulator = frame_stat.pcnt_inter - frame_stat.pcnt_motion;
3168
4.33k
    }
3169
3170
    // Not all frames in the group are necessarily used in calculating boost.
3171
7.47k
    if ((*sr_accumulator < (kf_raw_err * 1.50)) &&
3172
7.28k
        (i <= rc->max_gf_interval * 2)) {
3173
7.28k
      double frame_boost;
3174
7.28k
      double zm_factor;
3175
3176
      // Factor 0.75-1.25 based on how much of frame is static.
3177
7.28k
      zm_factor = (0.75 + (*zero_motion_accumulator / 2.0));
3178
3179
7.28k
      if (i < 2) *sr_accumulator = 0.0;
3180
7.28k
      frame_boost =
3181
7.28k
          calc_kf_frame_boost(&cpi->ppi->p_rc, frame_info, &frame_stat,
3182
7.28k
                              sr_accumulator, kf_max_boost);
3183
7.28k
      boost_score += frame_boost * zm_factor;
3184
7.28k
    }
3185
7.47k
  }
3186
11.4k
  return boost_score;
3187
11.4k
}
3188
3189
/*!\brief Interval(in seconds) to clip key-frame distance to in LAP.
3190
 */
3191
11.4k
#define MAX_KF_BITS_INTERVAL_SINGLE_PASS 5
3192
3193
/*!\brief Determine the next key frame group
3194
 *
3195
 * \ingroup gf_group_algo
3196
 * This function decides the placement of the next key frame, and
3197
 * calculates the bit allocation of the KF group and the keyframe itself.
3198
 *
3199
 * \param[in]    cpi              Top-level encoder structure
3200
 * \param[in]    this_frame       Pointer to first pass stats
3201
 */
3202
71.2k
static void find_next_key_frame(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame) {
3203
71.2k
  RATE_CONTROL *const rc = &cpi->rc;
3204
71.2k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3205
71.2k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3206
71.2k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3207
71.2k
  FRAME_INFO *const frame_info = &cpi->frame_info;
3208
71.2k
  AV1_COMMON *const cm = &cpi->common;
3209
71.2k
  CurrentFrame *const current_frame = &cm->current_frame;
3210
71.2k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3211
71.2k
  const KeyFrameCfg *const kf_cfg = &oxcf->kf_cfg;
3212
71.2k
  const FIRSTPASS_STATS first_frame = *this_frame;
3213
71.2k
  FIRSTPASS_STATS next_frame;
3214
71.2k
  const FIRSTPASS_INFO *firstpass_info = &twopass->firstpass_info;
3215
71.2k
  av1_zero(next_frame);
3216
3217
71.2k
  rc->frames_since_key = 0;
3218
  // Use arfs if possible.
3219
71.2k
  p_rc->use_arf_in_this_kf_group = is_altref_enabled(
3220
71.2k
      oxcf->gf_cfg.lag_in_frames, oxcf->gf_cfg.enable_auto_arf);
3221
3222
  // Reset the GF group data structures.
3223
71.2k
  av1_zero(*gf_group);
3224
71.2k
  cpi->gf_frame_index = 0;
3225
3226
  // KF is always a GF so clear frames till next gf counter.
3227
71.2k
  rc->frames_till_gf_update_due = 0;
3228
3229
71.2k
  if (has_no_stats_stage(cpi)) {
3230
59.7k
    int num_frames_to_app_forced_key = detect_app_forced_key(cpi);
3231
59.7k
    p_rc->this_key_frame_forced =
3232
59.7k
        current_frame->frame_number != 0 && rc->frames_to_key == 0;
3233
59.7k
    if (num_frames_to_app_forced_key != -1)
3234
6.69k
      rc->frames_to_key = num_frames_to_app_forced_key;
3235
53.0k
    else
3236
53.0k
      rc->frames_to_key = AOMMAX(1, kf_cfg->key_freq_max);
3237
59.7k
    correct_frames_to_key(cpi);
3238
59.7k
    p_rc->kf_boost = DEFAULT_KF_BOOST;
3239
59.7k
    gf_group->update_type[0] = KF_UPDATE;
3240
59.7k
    return;
3241
59.7k
  }
3242
11.4k
  int i;
3243
11.4k
  const FIRSTPASS_STATS *const start_position = cpi->twopass_frame.stats_in;
3244
11.4k
  int kf_bits = 0;
3245
11.4k
  double zero_motion_accumulator = 1.0;
3246
11.4k
  double boost_score = 0.0;
3247
11.4k
  double kf_raw_err = 0.0;
3248
11.4k
  double kf_mod_err = 0.0;
3249
11.4k
  double sr_accumulator = 0.0;
3250
11.4k
  double kf_group_avg_error = 0.0;
3251
11.4k
  int frames_to_key, frames_to_key_clipped = INT_MAX;
3252
11.4k
  int64_t kf_group_bits_clipped = INT64_MAX;
3253
3254
  // Is this a forced key frame by interval.
3255
11.4k
  p_rc->this_key_frame_forced = p_rc->next_key_frame_forced;
3256
3257
11.4k
  twopass->kf_group_bits = 0;        // Total bits available to kf group
3258
11.4k
  twopass->kf_group_error_left = 0;  // Group modified error score.
3259
3260
11.4k
  kf_raw_err = this_frame->intra_error;
3261
11.4k
  kf_mod_err = calculate_modified_err(frame_info, twopass, oxcf, this_frame);
3262
3263
  // We assume the current frame is a key frame and we are looking for the next
3264
  // key frame. Therefore search_start_idx = 1
3265
11.4k
  frames_to_key = define_kf_interval(cpi, firstpass_info, kf_cfg->key_freq_max,
3266
11.4k
                                     /*search_start_idx=*/1);
3267
3268
11.4k
  if (frames_to_key != -1) {
3269
6.34k
    rc->frames_to_key = AOMMIN(kf_cfg->key_freq_max, frames_to_key);
3270
6.34k
  } else {
3271
5.13k
    rc->frames_to_key = kf_cfg->key_freq_max;
3272
5.13k
  }
3273
3274
11.4k
  if (cpi->ppi->lap_enabled) correct_frames_to_key(cpi);
3275
3276
  // If there is a max kf interval set by the user we must obey it.
3277
  // We already breakout of the loop above at 2x max.
3278
  // This code centers the extra kf if the actual natural interval
3279
  // is between 1x and 2x.
3280
11.4k
  if (kf_cfg->auto_key && rc->frames_to_key > kf_cfg->key_freq_max) {
3281
0
    FIRSTPASS_STATS tmp_frame = first_frame;
3282
3283
0
    rc->frames_to_key /= 2;
3284
3285
    // Reset to the start of the group.
3286
0
    reset_fpf_position(&cpi->twopass_frame, start_position);
3287
    // Rescan to get the correct error data for the forced kf group.
3288
0
    for (i = 0; i < rc->frames_to_key; ++i) {
3289
0
      if (EOF == input_stats(twopass, &cpi->twopass_frame, &tmp_frame)) break;
3290
0
    }
3291
0
    p_rc->next_key_frame_forced = 1;
3292
11.4k
  } else if ((cpi->twopass_frame.stats_in ==
3293
11.4k
                  twopass->stats_buf_ctx->stats_in_end &&
3294
3.34k
              is_stat_consumption_stage_twopass(cpi)) ||
3295
11.4k
             rc->frames_to_key >= kf_cfg->key_freq_max) {
3296
0
    p_rc->next_key_frame_forced = 1;
3297
11.4k
  } else {
3298
11.4k
    p_rc->next_key_frame_forced = 0;
3299
11.4k
  }
3300
3301
11.4k
  double kf_group_err = 0;
3302
25.7k
  for (i = 0; i < rc->frames_to_key; ++i) {
3303
14.3k
    const FIRSTPASS_STATS *this_stats =
3304
14.3k
        av1_firstpass_info_peek(&twopass->firstpass_info, i);
3305
14.3k
    if (this_stats != NULL) {
3306
      // Accumulate kf group error.
3307
14.3k
      kf_group_err += calculate_modified_err_new(
3308
14.3k
          frame_info, &firstpass_info->total_stats, this_stats,
3309
14.3k
          oxcf->rc_cfg.vbrbias, twopass->modified_error_min,
3310
14.3k
          twopass->modified_error_max);
3311
14.3k
      ++p_rc->num_stats_used_for_kf_boost;
3312
14.3k
    }
3313
14.3k
  }
3314
3315
  // Calculate the number of bits that should be assigned to the kf group.
3316
11.4k
  if ((twopass->bits_left > 0 && twopass->modified_error_left > 0.0) ||
3317
11.4k
      (cpi->ppi->lap_enabled && oxcf->rc_cfg.mode != AOM_Q)) {
3318
    // Maximum number of bits for a single normal frame (not key frame).
3319
0
    const int max_bits = frame_max_bits(rc, oxcf);
3320
3321
    // Maximum number of bits allocated to the key frame group.
3322
0
    int64_t max_grp_bits;
3323
3324
0
    if (oxcf->rc_cfg.vbr_corpus_complexity_lap) {
3325
0
      kf_group_avg_error =
3326
0
          get_kf_group_avg_error(twopass, &cpi->twopass_frame, &first_frame,
3327
0
                                 start_position, rc->frames_to_key);
3328
0
    }
3329
3330
    // Default allocation based on bits left and relative
3331
    // complexity of the section.
3332
0
    twopass->kf_group_bits =
3333
0
        get_kf_group_bits(cpi, kf_group_err, kf_group_avg_error);
3334
    // Clip based on maximum per frame rate defined by the user.
3335
0
    max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
3336
0
    if (twopass->kf_group_bits > max_grp_bits)
3337
0
      twopass->kf_group_bits = max_grp_bits;
3338
11.4k
  } else {
3339
11.4k
    twopass->kf_group_bits = 0;
3340
11.4k
  }
3341
11.4k
  twopass->kf_group_bits = AOMMAX(0, twopass->kf_group_bits);
3342
3343
11.4k
  if (cpi->ppi->lap_enabled) {
3344
    // In the case of single pass based on LAP, frames to  key may have an
3345
    // inaccurate value, and hence should be clipped to an appropriate
3346
    // interval.
3347
11.4k
    frames_to_key_clipped =
3348
11.4k
        (int)(MAX_KF_BITS_INTERVAL_SINGLE_PASS * cpi->framerate);
3349
3350
    // This variable calculates the bits allocated to kf_group with a clipped
3351
    // frames_to_key.
3352
11.4k
    if (rc->frames_to_key > frames_to_key_clipped) {
3353
0
      kf_group_bits_clipped =
3354
0
          (int64_t)((double)twopass->kf_group_bits * frames_to_key_clipped /
3355
0
                    rc->frames_to_key);
3356
0
    }
3357
11.4k
  }
3358
3359
  // Reset the first pass file position.
3360
11.4k
  reset_fpf_position(&cpi->twopass_frame, start_position);
3361
3362
  // Scan through the kf group collating various stats used to determine
3363
  // how many bits to spend on it.
3364
11.4k
  boost_score = get_kf_boost_score(cpi, kf_raw_err, &zero_motion_accumulator,
3365
11.4k
                                   &sr_accumulator, 0);
3366
11.4k
  reset_fpf_position(&cpi->twopass_frame, start_position);
3367
  // Store the zero motion percentage
3368
11.4k
  twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
3369
3370
  // Calculate a section intra ratio used in setting max loop filter.
3371
11.4k
  twopass->section_intra_rating = calculate_section_intra_ratio(
3372
11.4k
      start_position, twopass->stats_buf_ctx->stats_in_end, rc->frames_to_key);
3373
3374
11.4k
  p_rc->kf_boost = (int)boost_score;
3375
3376
11.4k
  if (cpi->ppi->lap_enabled) {
3377
11.4k
    if (oxcf->rc_cfg.mode == AOM_Q) {
3378
11.4k
      p_rc->kf_boost = get_projected_kf_boost(cpi);
3379
11.4k
    } else {
3380
      // TODO(any): Explore using average frame stats for AOM_Q as well.
3381
0
      boost_score = get_kf_boost_score(
3382
0
          cpi, kf_raw_err, &zero_motion_accumulator, &sr_accumulator, 1);
3383
0
      reset_fpf_position(&cpi->twopass_frame, start_position);
3384
0
      p_rc->kf_boost += (int)boost_score;
3385
0
    }
3386
11.4k
  }
3387
3388
  // Special case for static / slide show content but don't apply
3389
  // if the kf group is very short.
3390
11.4k
  if ((zero_motion_accumulator > STATIC_KF_GROUP_FLOAT_THRESH) &&
3391
7.23k
      (rc->frames_to_key > 8)) {
3392
0
    p_rc->kf_boost = AOMMAX(p_rc->kf_boost, MIN_STATIC_KF_BOOST);
3393
11.4k
  } else {
3394
    // Apply various clamps for min and max boost
3395
11.4k
    p_rc->kf_boost = AOMMAX(p_rc->kf_boost, (rc->frames_to_key * 3));
3396
11.4k
    p_rc->kf_boost = AOMMAX(p_rc->kf_boost, MIN_KF_BOOST);
3397
#ifdef STRICT_RC
3398
    p_rc->kf_boost = AOMMIN(p_rc->kf_boost, MAX_KF_BOOST);
3399
#endif
3400
11.4k
  }
3401
3402
  // Work out how many bits to allocate for the key frame itself.
3403
  // In case of LAP enabled for VBR, if the frames_to_key value is
3404
  // very high, we calculate the bits based on a clipped value of
3405
  // frames_to_key.
3406
11.4k
  kf_bits = calculate_boost_bits(
3407
11.4k
      AOMMIN(rc->frames_to_key, frames_to_key_clipped) - 1, p_rc->kf_boost,
3408
11.4k
      AOMMIN(twopass->kf_group_bits, kf_group_bits_clipped));
3409
11.4k
  kf_bits = adjust_boost_bits_for_target_level(cpi, rc, kf_bits,
3410
11.4k
                                               twopass->kf_group_bits, 0);
3411
3412
11.4k
  twopass->kf_group_bits -= kf_bits;
3413
3414
  // Save the bits to spend on the key frame.
3415
11.4k
  gf_group->bit_allocation[0] = kf_bits;
3416
11.4k
  gf_group->update_type[0] = KF_UPDATE;
3417
3418
  // Note the total error score of the kf group minus the key frame itself.
3419
11.4k
  if (cpi->ppi->lap_enabled)
3420
    // As we don't have enough stats to know the actual error of the group,
3421
    // we assume the complexity of each frame to be equal to 1, and set the
3422
    // error as the number of frames in the group(minus the keyframe).
3423
11.4k
    twopass->kf_group_error_left = (double)(rc->frames_to_key - 1);
3424
0
  else
3425
0
    twopass->kf_group_error_left = kf_group_err - kf_mod_err;
3426
3427
  // Adjust the count of total modified error left.
3428
  // The count of bits left is adjusted elsewhere based on real coded frame
3429
  // sizes.
3430
11.4k
  twopass->modified_error_left -= kf_group_err;
3431
11.4k
}
3432
3433
#define ARF_STATS_OUTPUT 0
3434
#if ARF_STATS_OUTPUT
3435
unsigned int arf_count = 0;
3436
#endif
3437
3438
0
static int get_section_target_bandwidth(AV1_COMP *cpi) {
3439
0
  AV1_COMMON *const cm = &cpi->common;
3440
0
  CurrentFrame *const current_frame = &cm->current_frame;
3441
0
  RATE_CONTROL *const rc = &cpi->rc;
3442
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3443
0
  int64_t section_target_bandwidth;
3444
0
  const int frames_left = (int)(twopass->stats_buf_ctx->total_stats->count -
3445
0
                                current_frame->frame_number);
3446
0
  if (cpi->ppi->lap_enabled)
3447
0
    section_target_bandwidth = rc->avg_frame_bandwidth;
3448
0
  else {
3449
0
    section_target_bandwidth = twopass->bits_left / frames_left;
3450
0
    section_target_bandwidth = AOMMIN(section_target_bandwidth, INT_MAX);
3451
0
  }
3452
0
  return (int)section_target_bandwidth;
3453
0
}
3454
3455
static inline void set_twopass_params_based_on_fp_stats(
3456
28.6k
    AV1_COMP *cpi, const FIRSTPASS_STATS *this_frame_ptr) {
3457
28.6k
  if (this_frame_ptr == NULL) return;
3458
3459
28.6k
  TWO_PASS_FRAME *twopass_frame = &cpi->twopass_frame;
3460
  // The multiplication by 256 reverses a scaling factor of (>> 8)
3461
  // applied when combining MB error values for the frame.
3462
28.6k
  twopass_frame->mb_av_energy = log1p(this_frame_ptr->intra_error);
3463
3464
28.6k
  const FIRSTPASS_STATS *const total_stats =
3465
28.6k
      cpi->ppi->twopass.stats_buf_ctx->total_stats;
3466
28.6k
  if (is_fp_wavelet_energy_invalid(total_stats) == 0) {
3467
9.73k
    twopass_frame->frame_avg_haar_energy =
3468
9.73k
        log1p(this_frame_ptr->frame_avg_wavelet_energy);
3469
9.73k
  }
3470
3471
  // Set the frame content type flag.
3472
28.6k
  if (this_frame_ptr->intra_skip_pct >= FC_ANIMATION_THRESH)
3473
25
    twopass_frame->fr_content_type = FC_GRAPHICS_ANIMATION;
3474
28.6k
  else
3475
28.6k
    twopass_frame->fr_content_type = FC_NORMAL;
3476
28.6k
}
3477
3478
static void process_first_pass_stats(AV1_COMP *cpi,
3479
28.6k
                                     FIRSTPASS_STATS *this_frame) {
3480
28.6k
  AV1_COMMON *const cm = &cpi->common;
3481
28.6k
  CurrentFrame *const current_frame = &cm->current_frame;
3482
28.6k
  RATE_CONTROL *const rc = &cpi->rc;
3483
28.6k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3484
28.6k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3485
28.6k
  FIRSTPASS_STATS *total_stats = twopass->stats_buf_ctx->total_stats;
3486
3487
28.6k
  if (cpi->oxcf.rc_cfg.mode != AOM_Q && current_frame->frame_number == 0 &&
3488
0
      cpi->gf_frame_index == 0 && total_stats &&
3489
0
      twopass->stats_buf_ctx->total_left_stats) {
3490
0
    if (cpi->ppi->lap_enabled) {
3491
      /*
3492
       * Accumulate total_stats using available limited number of stats,
3493
       * and assign it to total_left_stats.
3494
       */
3495
0
      *twopass->stats_buf_ctx->total_left_stats = *total_stats;
3496
0
    }
3497
    // Special case code for first frame.
3498
0
    const int section_target_bandwidth = get_section_target_bandwidth(cpi);
3499
0
    const double section_length =
3500
0
        twopass->stats_buf_ctx->total_left_stats->count;
3501
0
    const double section_error =
3502
0
        twopass->stats_buf_ctx->total_left_stats->coded_error / section_length;
3503
0
    const double section_intra_skip =
3504
0
        twopass->stats_buf_ctx->total_left_stats->intra_skip_pct /
3505
0
        section_length;
3506
0
    const double section_inactive_zone =
3507
0
        (twopass->stats_buf_ctx->total_left_stats->inactive_zone_rows * 2) /
3508
0
        ((double)cm->mi_params.mb_rows * section_length);
3509
0
    const int tmp_q = get_twopass_worst_quality(
3510
0
        cpi, section_error, section_intra_skip + section_inactive_zone,
3511
0
        section_target_bandwidth);
3512
3513
0
    rc->active_worst_quality = tmp_q;
3514
0
    rc->ni_av_qi = tmp_q;
3515
0
    p_rc->last_q[INTER_FRAME] = tmp_q;
3516
0
    p_rc->avg_q = av1_convert_qindex_to_q(tmp_q, cm->seq_params->bit_depth);
3517
0
    p_rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
3518
0
    p_rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.rc_cfg.best_allowed_q) / 2;
3519
0
    p_rc->avg_frame_qindex[KEY_FRAME] = p_rc->last_q[KEY_FRAME];
3520
0
  }
3521
3522
28.6k
  if (cpi->twopass_frame.stats_in < twopass->stats_buf_ctx->stats_in_end) {
3523
18.9k
    *this_frame = *cpi->twopass_frame.stats_in;
3524
18.9k
    ++cpi->twopass_frame.stats_in;
3525
18.9k
  }
3526
28.6k
  set_twopass_params_based_on_fp_stats(cpi, this_frame);
3527
28.6k
}
3528
3529
95.9k
void av1_setup_target_rate(AV1_COMP *cpi) {
3530
95.9k
  RATE_CONTROL *const rc = &cpi->rc;
3531
95.9k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3532
3533
95.9k
  int target_rate = gf_group->bit_allocation[cpi->gf_frame_index];
3534
3535
95.9k
  if (has_no_stats_stage(cpi)) {
3536
69.4k
    av1_rc_set_frame_target(cpi, target_rate, cpi->common.width,
3537
69.4k
                            cpi->common.height);
3538
69.4k
  }
3539
3540
95.9k
  rc->base_frame_target = target_rate;
3541
95.9k
}
3542
3543
static void mark_flashes(FIRSTPASS_STATS *first_stats,
3544
11.4k
                         FIRSTPASS_STATS *last_stats) {
3545
11.4k
  FIRSTPASS_STATS *this_stats = first_stats, *next_stats;
3546
26.8k
  while (this_stats < last_stats - 1) {
3547
15.3k
    next_stats = this_stats + 1;
3548
15.3k
    if (next_stats->pcnt_second_ref > next_stats->pcnt_inter &&
3549
910
        next_stats->pcnt_second_ref >= 0.5) {
3550
243
      this_stats->is_flash = 1;
3551
15.0k
    } else {
3552
15.0k
      this_stats->is_flash = 0;
3553
15.0k
    }
3554
15.3k
    this_stats = next_stats;
3555
15.3k
  }
3556
  // We always treat the last one as none flash.
3557
11.4k
  if (last_stats - 1 >= first_stats) {
3558
11.4k
    (last_stats - 1)->is_flash = 0;
3559
11.4k
  }
3560
11.4k
}
3561
3562
// Smooth-out the noise variance so it is more stable
3563
// Returns 0 on success, -1 on memory allocation failure.
3564
// TODO(bohanli): Use a better low-pass filter than averaging
3565
static int smooth_filter_noise(FIRSTPASS_STATS *first_stats,
3566
11.4k
                               FIRSTPASS_STATS *last_stats) {
3567
11.4k
  int len = (int)(last_stats - first_stats);
3568
11.4k
  double *smooth_noise = aom_malloc(len * sizeof(*smooth_noise));
3569
11.4k
  if (!smooth_noise) return -1;
3570
3571
38.2k
  for (int i = 0; i < len; i++) {
3572
26.8k
    double total_noise = 0;
3573
26.8k
    double total_wt = 0;
3574
214k
    for (int j = -HALF_FILT_LEN; j <= HALF_FILT_LEN; j++) {
3575
187k
      int idx = clamp(i + j, 0, len - 1);
3576
187k
      if (first_stats[idx].is_flash) continue;
3577
3578
186k
      total_noise += first_stats[idx].noise_var;
3579
186k
      total_wt += 1.0;
3580
186k
    }
3581
26.8k
    if (total_wt > 0.01) {
3582
26.8k
      total_noise /= total_wt;
3583
26.8k
    } else {
3584
0
      total_noise = first_stats[i].noise_var;
3585
0
    }
3586
26.8k
    smooth_noise[i] = total_noise;
3587
26.8k
  }
3588
3589
38.2k
  for (int i = 0; i < len; i++) {
3590
26.8k
    first_stats[i].noise_var = smooth_noise[i];
3591
26.8k
  }
3592
3593
11.4k
  aom_free(smooth_noise);
3594
11.4k
  return 0;
3595
11.4k
}
3596
3597
// Estimate the noise variance of each frame from the first pass stats
3598
static void estimate_noise(FIRSTPASS_STATS *first_stats,
3599
                           FIRSTPASS_STATS *last_stats,
3600
11.4k
                           struct aom_internal_error_info *error_info) {
3601
11.4k
  FIRSTPASS_STATS *this_stats, *next_stats;
3602
11.4k
  double C1, C2, C3, noise;
3603
18.6k
  for (this_stats = first_stats + 2; this_stats < last_stats; this_stats++) {
3604
7.20k
    this_stats->noise_var = 0.0;
3605
    // flashes tend to have high correlation of innovations, so ignore them.
3606
7.20k
    if (this_stats->is_flash || (this_stats - 1)->is_flash ||
3607
6.95k
        (this_stats - 2)->is_flash)
3608
356
      continue;
3609
3610
6.85k
    C1 = (this_stats - 1)->intra_error *
3611
6.85k
         (this_stats->intra_error - this_stats->coded_error);
3612
6.85k
    C2 = (this_stats - 2)->intra_error *
3613
6.85k
         ((this_stats - 1)->intra_error - (this_stats - 1)->coded_error);
3614
6.85k
    C3 = (this_stats - 2)->intra_error *
3615
6.85k
         (this_stats->intra_error - this_stats->sr_coded_error);
3616
6.85k
    if (C1 <= 0 || C2 <= 0 || C3 <= 0) continue;
3617
1.79k
    C1 = sqrt(C1);
3618
1.79k
    C2 = sqrt(C2);
3619
1.79k
    C3 = sqrt(C3);
3620
3621
1.79k
    noise = (this_stats - 1)->intra_error - C1 * C2 / C3;
3622
1.79k
    noise = AOMMAX(noise, 0.01);
3623
1.79k
    this_stats->noise_var = noise;
3624
1.79k
  }
3625
3626
  // Copy noise from the neighbor if the noise value is not trustworthy
3627
18.6k
  for (this_stats = first_stats + 2; this_stats < last_stats; this_stats++) {
3628
7.20k
    if (this_stats->is_flash || (this_stats - 1)->is_flash ||
3629
6.95k
        (this_stats - 2)->is_flash)
3630
356
      continue;
3631
6.85k
    if (this_stats->noise_var < 1.0) {
3632
5.09k
      int found = 0;
3633
      // TODO(bohanli): consider expanding to two directions at the same time
3634
6.50k
      for (next_stats = this_stats + 1; next_stats < last_stats; next_stats++) {
3635
1.54k
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3636
1.54k
            (next_stats - 2)->is_flash || next_stats->noise_var < 1.0)
3637
1.40k
          continue;
3638
139
        found = 1;
3639
139
        this_stats->noise_var = next_stats->noise_var;
3640
139
        break;
3641
1.54k
      }
3642
5.09k
      if (found) continue;
3643
6.36k
      for (next_stats = this_stats - 1; next_stats >= first_stats + 2;
3644
4.95k
           next_stats--) {
3645
1.56k
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3646
1.56k
            (next_stats - 2)->is_flash || next_stats->noise_var < 1.0)
3647
1.40k
          continue;
3648
157
        this_stats->noise_var = next_stats->noise_var;
3649
157
        break;
3650
1.56k
      }
3651
4.95k
    }
3652
6.85k
  }
3653
3654
  // copy the noise if this is a flash
3655
18.6k
  for (this_stats = first_stats + 2; this_stats < last_stats; this_stats++) {
3656
7.20k
    if (this_stats->is_flash || (this_stats - 1)->is_flash ||
3657
6.95k
        (this_stats - 2)->is_flash) {
3658
356
      int found = 0;
3659
493
      for (next_stats = this_stats + 1; next_stats < last_stats; next_stats++) {
3660
137
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3661
84
            (next_stats - 2)->is_flash)
3662
137
          continue;
3663
0
        found = 1;
3664
0
        this_stats->noise_var = next_stats->noise_var;
3665
0
        break;
3666
137
      }
3667
356
      if (found) continue;
3668
493
      for (next_stats = this_stats - 1; next_stats >= first_stats + 2;
3669
356
           next_stats--) {
3670
137
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3671
0
            (next_stats - 2)->is_flash)
3672
137
          continue;
3673
0
        this_stats->noise_var = next_stats->noise_var;
3674
0
        break;
3675
137
      }
3676
356
    }
3677
7.20k
  }
3678
3679
  // if we are at the first 2 frames, copy the noise
3680
11.4k
  for (this_stats = first_stats;
3681
21.3k
       this_stats < first_stats + 2 && (first_stats + 2) < last_stats;
3682
11.4k
       this_stats++) {
3683
9.85k
    this_stats->noise_var = (first_stats + 2)->noise_var;
3684
9.85k
  }
3685
3686
11.4k
  if (smooth_filter_noise(first_stats, last_stats) == -1) {
3687
0
    aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
3688
0
                       "Error allocating buffers in smooth_filter_noise()");
3689
0
  }
3690
11.4k
}
3691
3692
// Estimate correlation coefficient of each frame with its previous frame.
3693
static void estimate_coeff(FIRSTPASS_STATS *first_stats,
3694
11.4k
                           FIRSTPASS_STATS *last_stats) {
3695
11.4k
  FIRSTPASS_STATS *this_stats;
3696
26.8k
  for (this_stats = first_stats + 1; this_stats < last_stats; this_stats++) {
3697
15.3k
    const double C =
3698
15.3k
        sqrt(AOMMAX((this_stats - 1)->intra_error *
3699
15.3k
                        (this_stats->intra_error - this_stats->coded_error),
3700
15.3k
                    0.001));
3701
15.3k
    const double cor_coeff =
3702
15.3k
        C /
3703
15.3k
        AOMMAX((this_stats - 1)->intra_error - this_stats->noise_var, 0.001);
3704
3705
15.3k
    this_stats->cor_coeff =
3706
15.3k
        cor_coeff *
3707
15.3k
        sqrt(AOMMAX((this_stats - 1)->intra_error - this_stats->noise_var,
3708
15.3k
                    0.001) /
3709
15.3k
             AOMMAX(this_stats->intra_error - this_stats->noise_var, 0.001));
3710
    // clip correlation coefficient.
3711
15.3k
    this_stats->cor_coeff = fclamp(this_stats->cor_coeff, 0.0, 1.0);
3712
15.3k
  }
3713
11.4k
  first_stats->cor_coeff = 1.0;
3714
11.4k
}
3715
3716
void av1_get_second_pass_params(AV1_COMP *cpi,
3717
                                EncodeFrameParams *const frame_params,
3718
88.4k
                                unsigned int frame_flags) {
3719
88.4k
  RATE_CONTROL *const rc = &cpi->rc;
3720
88.4k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3721
88.4k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3722
88.4k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3723
88.4k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3724
3725
88.4k
  if (cpi->use_ducky_encode &&
3726
0
      cpi->ducky_encode_info.frame_info.gop_mode == DUCKY_ENCODE_GOP_MODE_RCL) {
3727
0
    frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
3728
0
    frame_params->show_frame =
3729
0
        !(gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE ||
3730
0
          gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE);
3731
0
    if (cpi->gf_frame_index == 0) {
3732
0
      av1_tf_info_reset(&cpi->ppi->tf_info);
3733
0
      av1_tf_info_filtering(&cpi->ppi->tf_info, cpi, gf_group);
3734
0
    }
3735
0
    return;
3736
0
  }
3737
3738
88.4k
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
3739
88.4k
  int update_total_stats = 0;
3740
3741
88.4k
  if (is_stat_consumption_stage(cpi) && !cpi->twopass_frame.stats_in) return;
3742
3743
  // Check forced key frames.
3744
88.4k
  const int frames_to_next_forced_key = detect_app_forced_key(cpi);
3745
88.4k
  if (frames_to_next_forced_key == 0) {
3746
11.3k
    rc->frames_to_key = 0;
3747
11.3k
    frame_flags &= FRAMEFLAGS_KEY;
3748
77.1k
  } else if (frames_to_next_forced_key > 0 &&
3749
2.58k
             frames_to_next_forced_key < rc->frames_to_key) {
3750
0
    rc->frames_to_key = frames_to_next_forced_key;
3751
0
  }
3752
3753
88.4k
  assert(cpi->twopass_frame.stats_in != NULL);
3754
88.4k
  const int update_type = gf_group->update_type[cpi->gf_frame_index];
3755
88.4k
  frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
3756
3757
88.4k
  if (cpi->gf_frame_index < gf_group->size && !(frame_flags & FRAMEFLAGS_KEY)) {
3758
7.47k
    assert(cpi->gf_frame_index < gf_group->size);
3759
3760
7.47k
    av1_setup_target_rate(cpi);
3761
3762
    // If this is an arf frame then we dont want to read the stats file or
3763
    // advance the input pointer as we already have what we need.
3764
7.47k
    if (update_type == ARF_UPDATE || update_type == INTNL_ARF_UPDATE) {
3765
0
      const FIRSTPASS_STATS *const this_frame_ptr =
3766
0
          read_frame_stats(twopass, &cpi->twopass_frame,
3767
0
                           gf_group->arf_src_offset[cpi->gf_frame_index]);
3768
0
      set_twopass_params_based_on_fp_stats(cpi, this_frame_ptr);
3769
0
      return;
3770
0
    }
3771
7.47k
  }
3772
3773
88.4k
  if (oxcf->rc_cfg.mode == AOM_Q)
3774
88.4k
    rc->active_worst_quality = oxcf->rc_cfg.cq_level;
3775
3776
88.4k
  if (cpi->gf_frame_index == gf_group->size) {
3777
80.9k
    if (cpi->ppi->lap_enabled && cpi->ppi->p_rc.enable_scenecut_detection) {
3778
11.4k
      const int num_frames_to_detect_scenecut = MAX_GF_LENGTH_LAP + 1;
3779
11.4k
      const int frames_to_key = define_kf_interval(
3780
11.4k
          cpi, &twopass->firstpass_info, num_frames_to_detect_scenecut,
3781
11.4k
          /*search_start_idx=*/0);
3782
11.4k
      if (frames_to_key != -1)
3783
6.34k
        rc->frames_to_key = AOMMIN(rc->frames_to_key, frames_to_key);
3784
11.4k
    }
3785
80.9k
  }
3786
3787
88.4k
  FIRSTPASS_STATS this_frame;
3788
88.4k
  av1_zero(this_frame);
3789
  // call above fn
3790
88.4k
  if (is_stat_consumption_stage(cpi)) {
3791
18.9k
    if (cpi->gf_frame_index < gf_group->size || rc->frames_to_key == 0) {
3792
18.9k
      process_first_pass_stats(cpi, &this_frame);
3793
18.9k
      update_total_stats = 1;
3794
18.9k
    }
3795
69.4k
  } else {
3796
69.4k
    rc->active_worst_quality = oxcf->rc_cfg.cq_level;
3797
69.4k
  }
3798
3799
  // Keyframe and section processing.
3800
88.4k
  FIRSTPASS_STATS this_frame_copy;
3801
88.4k
  this_frame_copy = this_frame;
3802
88.4k
  if (rc->frames_to_key <= 0) {
3803
71.2k
    assert(rc->frames_to_key == 0);
3804
    // Define next KF group and assign bits to it.
3805
71.2k
    frame_params->frame_type = KEY_FRAME;
3806
71.2k
    find_next_key_frame(cpi, &this_frame);
3807
71.2k
    this_frame = this_frame_copy;
3808
71.2k
  }
3809
3810
88.4k
  if (rc->frames_to_fwd_kf <= 0)
3811
88.4k
    rc->frames_to_fwd_kf = oxcf->kf_cfg.fwd_kf_dist;
3812
3813
  // Define a new GF/ARF group. (Should always enter here for key frames).
3814
88.4k
  if (cpi->gf_frame_index == gf_group->size) {
3815
80.9k
    av1_tf_info_reset(&cpi->ppi->tf_info);
3816
#if CONFIG_BITRATE_ACCURACY && !CONFIG_THREE_PASS
3817
    vbr_rc_reset_gop_data(&cpi->vbr_rc_info);
3818
#endif  // CONFIG_BITRATE_ACCURACY
3819
80.9k
    int max_gop_length =
3820
80.9k
        (oxcf->gf_cfg.lag_in_frames >= 32)
3821
80.9k
            ? AOMMIN(MAX_GF_INTERVAL, oxcf->gf_cfg.lag_in_frames -
3822
80.9k
                                          oxcf->algo_cfg.arnr_max_frames / 2)
3823
80.9k
            : MAX_GF_LENGTH_LAP;
3824
3825
    // Handle forward key frame when enabled.
3826
80.9k
    if (oxcf->kf_cfg.fwd_kf_dist > 0)
3827
0
      max_gop_length = AOMMIN(rc->frames_to_fwd_kf + 1, max_gop_length);
3828
3829
    // Use the provided gop size in low delay setting
3830
80.9k
    if (oxcf->gf_cfg.lag_in_frames == 0) max_gop_length = rc->max_gf_interval;
3831
3832
    // Limit the max gop length for the last gop in 1 pass setting.
3833
80.9k
    max_gop_length = AOMMIN(max_gop_length, rc->frames_to_key);
3834
3835
    // Identify regions if needed.
3836
    // TODO(bohanli): identify regions for all stats available.
3837
80.9k
    if (rc->frames_since_key == 0 || rc->frames_since_key == 1 ||
3838
4.50k
        (p_rc->frames_till_regions_update - rc->frames_since_key <
3839
4.50k
             rc->frames_to_key &&
3840
4.50k
         p_rc->frames_till_regions_update - rc->frames_since_key <
3841
80.9k
             max_gop_length + 1)) {
3842
      // how many frames we can analyze from this frame
3843
80.9k
      int rest_frames =
3844
80.9k
          AOMMIN(rc->frames_to_key, MAX_FIRSTPASS_ANALYSIS_FRAMES);
3845
80.9k
      rest_frames =
3846
80.9k
          AOMMIN(rest_frames, (int)(twopass->stats_buf_ctx->stats_in_end -
3847
80.9k
                                    cpi->twopass_frame.stats_in +
3848
80.9k
                                    (rc->frames_since_key == 0)));
3849
80.9k
      p_rc->frames_till_regions_update = rest_frames;
3850
3851
80.9k
      int ret;
3852
80.9k
      if (cpi->ppi->lap_enabled) {
3853
11.4k
        mark_flashes(twopass->stats_buf_ctx->stats_in_start,
3854
11.4k
                     twopass->stats_buf_ctx->stats_in_end);
3855
11.4k
        estimate_noise(twopass->stats_buf_ctx->stats_in_start,
3856
11.4k
                       twopass->stats_buf_ctx->stats_in_end, cpi->common.error);
3857
11.4k
        estimate_coeff(twopass->stats_buf_ctx->stats_in_start,
3858
11.4k
                       twopass->stats_buf_ctx->stats_in_end);
3859
11.4k
        ret = identify_regions(cpi->twopass_frame.stats_in, rest_frames,
3860
11.4k
                               (rc->frames_since_key == 0), p_rc->regions,
3861
11.4k
                               &p_rc->num_regions);
3862
69.4k
      } else {
3863
69.4k
        ret = identify_regions(
3864
69.4k
            cpi->twopass_frame.stats_in - (rc->frames_since_key == 0),
3865
69.4k
            rest_frames, 0, p_rc->regions, &p_rc->num_regions);
3866
69.4k
      }
3867
80.9k
      if (ret == -1) {
3868
0
        aom_internal_error(cpi->common.error, AOM_CODEC_MEM_ERROR,
3869
0
                           "Error allocating buffers in identify_regions");
3870
0
      }
3871
80.9k
    }
3872
3873
80.9k
    int cur_region_idx =
3874
80.9k
        find_regions_index(p_rc->regions, p_rc->num_regions,
3875
80.9k
                           rc->frames_since_key - p_rc->regions_offset);
3876
80.9k
    if ((cur_region_idx >= 0 &&
3877
0
         p_rc->regions[cur_region_idx].type == SCENECUT_REGION) ||
3878
80.9k
        rc->frames_since_key == 0) {
3879
      // If we start from a scenecut, then the last GOP's arf boost is not
3880
      // needed for this GOP.
3881
71.2k
      cpi->ppi->gf_state.arf_gf_boost_lst = 0;
3882
71.2k
    }
3883
3884
80.9k
    int need_gf_len = 1;
3885
#if CONFIG_THREE_PASS
3886
    if (cpi->third_pass_ctx && oxcf->pass == AOM_RC_THIRD_PASS) {
3887
      // set up bitstream to read
3888
      if (!cpi->third_pass_ctx->input_file_name && oxcf->two_pass_output) {
3889
        cpi->third_pass_ctx->input_file_name = oxcf->two_pass_output;
3890
      }
3891
      av1_open_second_pass_log(cpi, 1);
3892
      THIRD_PASS_GOP_INFO *gop_info = &cpi->third_pass_ctx->gop_info;
3893
      // Read in GOP information from the second pass file.
3894
      av1_read_second_pass_gop_info(cpi->second_pass_log_stream, gop_info,
3895
                                    cpi->common.error);
3896
#if CONFIG_BITRATE_ACCURACY
3897
      TPL_INFO *tpl_info;
3898
      AOM_CHECK_MEM_ERROR(cpi->common.error, tpl_info,
3899
                          aom_malloc(sizeof(*tpl_info)));
3900
      av1_read_tpl_info(tpl_info, cpi->second_pass_log_stream,
3901
                        cpi->common.error);
3902
      aom_free(tpl_info);
3903
#if CONFIG_THREE_PASS
3904
      // TODO(angiebird): Put this part into a func
3905
      cpi->vbr_rc_info.cur_gop_idx++;
3906
#endif  // CONFIG_THREE_PASS
3907
#endif  // CONFIG_BITRATE_ACCURACY
3908
      // Read in third_pass_info from the bitstream.
3909
      av1_set_gop_third_pass(cpi->third_pass_ctx);
3910
      // Read in per-frame info from second-pass encoding
3911
      av1_read_second_pass_per_frame_info(
3912
          cpi->second_pass_log_stream, cpi->third_pass_ctx->frame_info,
3913
          gop_info->num_frames, cpi->common.error);
3914
3915
      p_rc->cur_gf_index = 0;
3916
      p_rc->gf_intervals[0] = cpi->third_pass_ctx->gop_info.gf_length;
3917
      need_gf_len = 0;
3918
    }
3919
#endif  // CONFIG_THREE_PASS
3920
3921
80.9k
    if (need_gf_len) {
3922
      // If we cannot obtain GF group length from second_pass_file
3923
      // TODO(jingning): Resolve the redundant calls here.
3924
80.9k
      if (rc->intervals_till_gf_calculate_due == 0 || 1) {
3925
80.9k
        calculate_gf_length(cpi, max_gop_length, MAX_NUM_GF_INTERVALS);
3926
80.9k
      }
3927
3928
80.9k
      if (max_gop_length > 16 && oxcf->algo_cfg.enable_tpl_model &&
3929
0
          oxcf->gf_cfg.lag_in_frames >= 32 &&
3930
0
          cpi->sf.tpl_sf.gop_length_decision_method != 3) {
3931
0
        int this_idx = rc->frames_since_key +
3932
0
                       p_rc->gf_intervals[p_rc->cur_gf_index] -
3933
0
                       p_rc->regions_offset - 1;
3934
0
        int this_region =
3935
0
            find_regions_index(p_rc->regions, p_rc->num_regions, this_idx);
3936
0
        int next_region =
3937
0
            find_regions_index(p_rc->regions, p_rc->num_regions, this_idx + 1);
3938
        // TODO(angiebird): Figure out why this_region and next_region are -1 in
3939
        // unit test like AltRefFramePresenceTestLarge (aomedia:3134)
3940
0
        int is_last_scenecut =
3941
0
            p_rc->gf_intervals[p_rc->cur_gf_index] >= rc->frames_to_key ||
3942
0
            (this_region != -1 &&
3943
0
             p_rc->regions[this_region].type == SCENECUT_REGION) ||
3944
0
            (next_region != -1 &&
3945
0
             p_rc->regions[next_region].type == SCENECUT_REGION);
3946
3947
0
        int ori_gf_int = p_rc->gf_intervals[p_rc->cur_gf_index];
3948
3949
0
        if (p_rc->gf_intervals[p_rc->cur_gf_index] > 16 &&
3950
0
            rc->min_gf_interval <= 16) {
3951
          // The calculate_gf_length function is previously used with
3952
          // max_gop_length = 32 with look-ahead gf intervals.
3953
0
          define_gf_group(cpi, frame_params, 0);
3954
0
          av1_tf_info_filtering(&cpi->ppi->tf_info, cpi, gf_group);
3955
0
          this_frame = this_frame_copy;
3956
3957
0
          if (is_shorter_gf_interval_better(cpi, frame_params)) {
3958
            // A shorter gf interval is better.
3959
            // TODO(jingning): Remove redundant computations here.
3960
0
            max_gop_length = 16;
3961
0
            calculate_gf_length(cpi, max_gop_length, 1);
3962
0
            if (is_last_scenecut &&
3963
0
                (ori_gf_int - p_rc->gf_intervals[p_rc->cur_gf_index] < 4)) {
3964
0
              p_rc->gf_intervals[p_rc->cur_gf_index] = ori_gf_int;
3965
0
            }
3966
0
          }
3967
0
        }
3968
0
      }
3969
80.9k
    }
3970
3971
80.9k
    define_gf_group(cpi, frame_params, 0);
3972
3973
80.9k
    if (gf_group->update_type[cpi->gf_frame_index] != ARF_UPDATE &&
3974
80.9k
        rc->frames_since_key > 0)
3975
9.73k
      process_first_pass_stats(cpi, &this_frame);
3976
3977
80.9k
    define_gf_group(cpi, frame_params, 1);
3978
3979
#if CONFIG_THREE_PASS
3980
    // write gop info if needed for third pass. Per-frame info is written after
3981
    // each frame is encoded.
3982
    av1_write_second_pass_gop_info(cpi);
3983
#endif  // CONFIG_THREE_PASS
3984
3985
80.9k
    av1_tf_info_filtering(&cpi->ppi->tf_info, cpi, gf_group);
3986
3987
80.9k
    rc->frames_till_gf_update_due = p_rc->baseline_gf_interval;
3988
80.9k
    assert(cpi->gf_frame_index == 0);
3989
#if ARF_STATS_OUTPUT
3990
    {
3991
      FILE *fpfile;
3992
      fpfile = fopen("arf.stt", "a");
3993
      ++arf_count;
3994
      fprintf(fpfile, "%10d %10d %10d %10d %10d\n",
3995
              cpi->common.current_frame.frame_number,
3996
              rc->frames_till_gf_update_due, cpi->ppi->p_rc.kf_boost, arf_count,
3997
              p_rc->gfu_boost);
3998
3999
      fclose(fpfile);
4000
    }
4001
#endif
4002
80.9k
  }
4003
88.4k
  assert(cpi->gf_frame_index < gf_group->size);
4004
4005
88.4k
  if (gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE ||
4006
88.4k
      gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE) {
4007
0
    reset_fpf_position(&cpi->twopass_frame, start_pos);
4008
4009
0
    const FIRSTPASS_STATS *const this_frame_ptr =
4010
0
        read_frame_stats(twopass, &cpi->twopass_frame,
4011
0
                         gf_group->arf_src_offset[cpi->gf_frame_index]);
4012
0
    set_twopass_params_based_on_fp_stats(cpi, this_frame_ptr);
4013
88.4k
  } else {
4014
    // Back up this frame's stats for updating total stats during post encode.
4015
88.4k
    cpi->twopass_frame.this_frame = update_total_stats ? start_pos : NULL;
4016
88.4k
  }
4017
4018
88.4k
  frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
4019
88.4k
  av1_setup_target_rate(cpi);
4020
88.4k
}
4021
4022
0
void av1_init_second_pass(AV1_COMP *cpi) {
4023
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
4024
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
4025
0
  FRAME_INFO *const frame_info = &cpi->frame_info;
4026
0
  double frame_rate;
4027
0
  FIRSTPASS_STATS *stats;
4028
4029
0
  if (!twopass->stats_buf_ctx->stats_in_end) return;
4030
4031
0
  mark_flashes(twopass->stats_buf_ctx->stats_in_start,
4032
0
               twopass->stats_buf_ctx->stats_in_end);
4033
0
  estimate_noise(twopass->stats_buf_ctx->stats_in_start,
4034
0
                 twopass->stats_buf_ctx->stats_in_end, cpi->common.error);
4035
0
  estimate_coeff(twopass->stats_buf_ctx->stats_in_start,
4036
0
                 twopass->stats_buf_ctx->stats_in_end);
4037
4038
0
  stats = twopass->stats_buf_ctx->total_stats;
4039
4040
0
  *stats = *twopass->stats_buf_ctx->stats_in_end;
4041
0
  *twopass->stats_buf_ctx->total_left_stats = *stats;
4042
4043
0
  frame_rate = 10000000.0 * stats->count / stats->duration;
4044
  // Each frame can have a different duration, as the frame rate in the source
4045
  // isn't guaranteed to be constant. The frame rate prior to the first frame
4046
  // encoded in the second pass is a guess. However, the sum duration is not.
4047
  // It is calculated based on the actual durations of all frames from the
4048
  // first pass.
4049
0
  av1_new_framerate(cpi, frame_rate);
4050
0
  twopass->bits_left =
4051
0
      (int64_t)(stats->duration * oxcf->rc_cfg.target_bandwidth / 10000000.0);
4052
4053
#if CONFIG_BITRATE_ACCURACY
4054
  av1_vbr_rc_init(&cpi->vbr_rc_info, twopass->bits_left,
4055
                  (int)round(stats->count));
4056
#endif
4057
4058
#if CONFIG_RATECTRL_LOG
4059
  rc_log_init(&cpi->rc_log);
4060
#endif
4061
4062
  // This variable monitors how far behind the second ref update is lagging.
4063
0
  twopass->sr_update_lag = 1;
4064
4065
  // Scan the first pass file and calculate a modified total error based upon
4066
  // the bias/power function used to allocate bits.
4067
0
  {
4068
0
    const double avg_error =
4069
0
        stats->coded_error / DOUBLE_DIVIDE_CHECK(stats->count);
4070
0
    const FIRSTPASS_STATS *s = cpi->twopass_frame.stats_in;
4071
0
    double modified_error_total = 0.0;
4072
0
    twopass->modified_error_min =
4073
0
        (avg_error * oxcf->rc_cfg.vbrmin_section) / 100;
4074
0
    twopass->modified_error_max =
4075
0
        (avg_error * oxcf->rc_cfg.vbrmax_section) / 100;
4076
0
    while (s < twopass->stats_buf_ctx->stats_in_end) {
4077
0
      modified_error_total +=
4078
0
          calculate_modified_err(frame_info, twopass, oxcf, s);
4079
0
      ++s;
4080
0
    }
4081
0
    twopass->modified_error_left = modified_error_total;
4082
0
  }
4083
4084
  // Reset the vbr bits off target counters
4085
0
  cpi->ppi->p_rc.vbr_bits_off_target = 0;
4086
0
  cpi->ppi->p_rc.vbr_bits_off_target_fast = 0;
4087
4088
0
  cpi->ppi->p_rc.rate_error_estimate = 0;
4089
4090
  // Static sequence monitor variables.
4091
0
  twopass->kf_zeromotion_pct = 100;
4092
0
  twopass->last_kfgroup_zeromotion_pct = 100;
4093
4094
  // Initialize bits per macro_block estimate correction factor.
4095
0
  twopass->bpm_factor = 1.0;
4096
  // Initialize actual and target bits counters for ARF groups so that
4097
  // at the start we have a neutral bpm adjustment.
4098
0
  twopass->rolling_arf_group_target_bits = 1;
4099
0
  twopass->rolling_arf_group_actual_bits = 1;
4100
0
}
4101
4102
6.98k
void av1_init_single_pass_lap(AV1_COMP *cpi) {
4103
6.98k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
4104
4105
6.98k
  if (!twopass->stats_buf_ctx->stats_in_end) return;
4106
4107
  // This variable monitors how far behind the second ref update is lagging.
4108
6.98k
  twopass->sr_update_lag = 1;
4109
4110
6.98k
  twopass->bits_left = 0;
4111
6.98k
  twopass->modified_error_min = 0.0;
4112
6.98k
  twopass->modified_error_max = 0.0;
4113
6.98k
  twopass->modified_error_left = 0.0;
4114
4115
  // Reset the vbr bits off target counters
4116
6.98k
  cpi->ppi->p_rc.vbr_bits_off_target = 0;
4117
6.98k
  cpi->ppi->p_rc.vbr_bits_off_target_fast = 0;
4118
4119
6.98k
  cpi->ppi->p_rc.rate_error_estimate = 0;
4120
4121
  // Static sequence monitor variables.
4122
6.98k
  twopass->kf_zeromotion_pct = 100;
4123
6.98k
  twopass->last_kfgroup_zeromotion_pct = 100;
4124
4125
  // Initialize bits per macro_block estimate correction factor.
4126
6.98k
  twopass->bpm_factor = 1.0;
4127
  // Initialize actual and target bits counters for ARF groups so that
4128
  // at the start we have a neutral bpm adjustment.
4129
6.98k
  twopass->rolling_arf_group_target_bits = 1;
4130
6.98k
  twopass->rolling_arf_group_actual_bits = 1;
4131
6.98k
}
4132
4133
0
#define MINQ_ADJ_LIMIT 48
4134
0
#define MINQ_ADJ_LIMIT_CQ 20
4135
0
#define HIGH_UNDERSHOOT_RATIO 2
4136
18.9k
void av1_twopass_postencode_update(AV1_COMP *cpi) {
4137
18.9k
  TWO_PASS *const twopass = &cpi->ppi->twopass;
4138
18.9k
  RATE_CONTROL *const rc = &cpi->rc;
4139
18.9k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
4140
18.9k
  const RateControlCfg *const rc_cfg = &cpi->oxcf.rc_cfg;
4141
4142
  // Increment the stats_in pointer.
4143
18.9k
  if (is_stat_consumption_stage(cpi) &&
4144
18.9k
      !(cpi->use_ducky_encode && cpi->ducky_encode_info.frame_info.gop_mode ==
4145
0
                                     DUCKY_ENCODE_GOP_MODE_RCL) &&
4146
18.9k
      (cpi->gf_frame_index < cpi->ppi->gf_group.size ||
4147
18.9k
       rc->frames_to_key == 0)) {
4148
18.9k
    const int update_type = cpi->ppi->gf_group.update_type[cpi->gf_frame_index];
4149
18.9k
    if (update_type != ARF_UPDATE && update_type != INTNL_ARF_UPDATE) {
4150
18.9k
      FIRSTPASS_STATS this_frame;
4151
18.9k
      assert(cpi->twopass_frame.stats_in >
4152
18.9k
             twopass->stats_buf_ctx->stats_in_start);
4153
18.9k
      --cpi->twopass_frame.stats_in;
4154
18.9k
      if (cpi->ppi->lap_enabled) {
4155
18.9k
        input_stats_lap(twopass, &cpi->twopass_frame, &this_frame);
4156
18.9k
      } else {
4157
0
        input_stats(twopass, &cpi->twopass_frame, &this_frame);
4158
0
      }
4159
18.9k
    } else if (cpi->ppi->lap_enabled) {
4160
0
      cpi->twopass_frame.stats_in = twopass->stats_buf_ctx->stats_in_start;
4161
0
    }
4162
18.9k
  }
4163
4164
  // VBR correction is done through rc->vbr_bits_off_target. Based on the
4165
  // sign of this value, a limited % adjustment is made to the target rate
4166
  // of subsequent frames, to try and push it back towards 0. This method
4167
  // is designed to prevent extreme behaviour at the end of a clip
4168
  // or group of frames.
4169
18.9k
  p_rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
4170
18.9k
  twopass->bits_left = AOMMAX(twopass->bits_left - rc->base_frame_target, 0);
4171
4172
18.9k
  if (cpi->do_update_vbr_bits_off_target_fast) {
4173
    // Subtract current frame's fast_extra_bits.
4174
0
    p_rc->vbr_bits_off_target_fast -= rc->frame_level_fast_extra_bits;
4175
0
    rc->frame_level_fast_extra_bits = 0;
4176
0
  }
4177
4178
  // Target vs actual bits for this arf group.
4179
18.9k
  if (twopass->rolling_arf_group_target_bits >
4180
18.9k
      INT_MAX - rc->base_frame_target) {
4181
0
    twopass->rolling_arf_group_target_bits = INT_MAX;
4182
18.9k
  } else {
4183
18.9k
    twopass->rolling_arf_group_target_bits += rc->base_frame_target;
4184
18.9k
  }
4185
18.9k
  twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
4186
4187
  // Calculate the pct rc error.
4188
18.9k
  if (p_rc->total_actual_bits) {
4189
18.9k
    p_rc->rate_error_estimate =
4190
18.9k
        (int)((p_rc->vbr_bits_off_target * 100) / p_rc->total_actual_bits);
4191
18.9k
    p_rc->rate_error_estimate = clamp(p_rc->rate_error_estimate, -100, 100);
4192
18.9k
  } else {
4193
0
    p_rc->rate_error_estimate = 0;
4194
0
  }
4195
4196
#if CONFIG_FPMT_TEST
4197
  /* The variables temp_vbr_bits_off_target, temp_bits_left,
4198
   * temp_rolling_arf_group_target_bits, temp_rolling_arf_group_actual_bits
4199
   * temp_rate_error_estimate are introduced for quality simulation purpose,
4200
   * it retains the value previous to the parallel encode frames. The
4201
   * variables are updated based on the update flag.
4202
   *
4203
   * If there exist show_existing_frames between parallel frames, then to
4204
   * retain the temp state do not update it. */
4205
  const int simulate_parallel_frame =
4206
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
4207
  int show_existing_between_parallel_frames =
4208
      (cpi->ppi->gf_group.update_type[cpi->gf_frame_index] ==
4209
           INTNL_OVERLAY_UPDATE &&
4210
       cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index + 1] == 2);
4211
4212
  if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
4213
      simulate_parallel_frame) {
4214
    cpi->ppi->p_rc.temp_vbr_bits_off_target = p_rc->vbr_bits_off_target;
4215
    cpi->ppi->p_rc.temp_bits_left = twopass->bits_left;
4216
    cpi->ppi->p_rc.temp_rolling_arf_group_target_bits =
4217
        twopass->rolling_arf_group_target_bits;
4218
    cpi->ppi->p_rc.temp_rolling_arf_group_actual_bits =
4219
        twopass->rolling_arf_group_actual_bits;
4220
    cpi->ppi->p_rc.temp_rate_error_estimate = p_rc->rate_error_estimate;
4221
  }
4222
#endif
4223
  // Update the active best quality pyramid.
4224
18.9k
  if (!rc->is_src_frame_alt_ref) {
4225
18.9k
    const int pyramid_level =
4226
18.9k
        cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index];
4227
18.9k
    int i;
4228
140k
    for (i = pyramid_level; i <= MAX_ARF_LAYERS; ++i) {
4229
122k
      p_rc->active_best_quality[i] = cpi->common.quant_params.base_qindex;
4230
#if CONFIG_TUNE_VMAF
4231
      if (cpi->vmaf_info.original_qindex != -1 &&
4232
          (cpi->oxcf.tune_cfg.tuning >= AOM_TUNE_VMAF_WITH_PREPROCESSING &&
4233
           cpi->oxcf.tune_cfg.tuning <= AOM_TUNE_VMAF_NEG_MAX_GAIN)) {
4234
        p_rc->active_best_quality[i] = cpi->vmaf_info.original_qindex;
4235
      }
4236
#endif
4237
122k
    }
4238
18.9k
  }
4239
4240
#if 0
4241
  {
4242
    AV1_COMMON *cm = &cpi->common;
4243
    FILE *fpfile;
4244
    fpfile = fopen("details.stt", "a");
4245
    fprintf(fpfile,
4246
            "%10d %10d %10d %10" PRId64 " %10" PRId64
4247
            " %10d %10d %10d %10.4lf %10.4lf %10.4lf %10.4lf\n",
4248
            cm->current_frame.frame_number, rc->base_frame_target,
4249
            rc->projected_frame_size, rc->total_actual_bits,
4250
            rc->vbr_bits_off_target, p_rc->rate_error_estimate,
4251
            twopass->rolling_arf_group_target_bits,
4252
            twopass->rolling_arf_group_actual_bits,
4253
            (double)twopass->rolling_arf_group_actual_bits /
4254
                (double)twopass->rolling_arf_group_target_bits,
4255
            twopass->bpm_factor,
4256
            av1_convert_qindex_to_q(cpi->common.quant_params.base_qindex,
4257
                                    cm->seq_params->bit_depth),
4258
            av1_convert_qindex_to_q(rc->active_worst_quality,
4259
                                    cm->seq_params->bit_depth));
4260
    fclose(fpfile);
4261
  }
4262
#endif
4263
4264
18.9k
  if (cpi->common.current_frame.frame_type != KEY_FRAME) {
4265
7.47k
    twopass->kf_group_bits -= rc->base_frame_target;
4266
7.47k
    twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
4267
7.47k
  }
4268
18.9k
  twopass->kf_group_bits = AOMMAX(twopass->kf_group_bits, 0);
4269
4270
  // If the rate control is drifting consider adjustment to min or maxq.
4271
18.9k
  if ((rc_cfg->mode != AOM_Q) && !cpi->rc.is_src_frame_alt_ref &&
4272
0
      (p_rc->rolling_target_bits > 0)) {
4273
0
    int minq_adj_limit;
4274
0
    int maxq_adj_limit;
4275
0
    minq_adj_limit =
4276
0
        (rc_cfg->mode == AOM_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
4277
0
    maxq_adj_limit = (rc->worst_quality - rc->active_worst_quality);
4278
4279
    // Undershoot
4280
0
    if ((rc_cfg->under_shoot_pct < 100) &&
4281
0
        (p_rc->rolling_actual_bits < p_rc->rolling_target_bits)) {
4282
0
      int pct_error =
4283
0
          ((p_rc->rolling_target_bits - p_rc->rolling_actual_bits) * 100) /
4284
0
          p_rc->rolling_target_bits;
4285
4286
0
      if ((pct_error >= rc_cfg->under_shoot_pct) &&
4287
0
          (p_rc->rate_error_estimate > 0)) {
4288
0
        twopass->extend_minq += 1;
4289
0
        twopass->extend_maxq -= 1;
4290
0
      }
4291
4292
      // Overshoot
4293
0
    } else if ((rc_cfg->over_shoot_pct < 100) &&
4294
0
               (p_rc->rolling_actual_bits > p_rc->rolling_target_bits)) {
4295
0
      int pct_error =
4296
0
          ((p_rc->rolling_actual_bits - p_rc->rolling_target_bits) * 100) /
4297
0
          p_rc->rolling_target_bits;
4298
4299
0
      pct_error = clamp(pct_error, 0, 100);
4300
0
      if ((pct_error >= rc_cfg->over_shoot_pct) &&
4301
0
          (p_rc->rate_error_estimate < 0)) {
4302
0
        twopass->extend_maxq += 1;
4303
0
        twopass->extend_minq -= 1;
4304
0
      }
4305
0
    }
4306
0
    twopass->extend_minq =
4307
0
        clamp(twopass->extend_minq, -minq_adj_limit, minq_adj_limit);
4308
0
    twopass->extend_maxq = clamp(twopass->extend_maxq, 0, maxq_adj_limit);
4309
4310
    // If there is a big and undexpected undershoot then feed the extra
4311
    // bits back in quickly. One situation where this may happen is if a
4312
    // frame is unexpectedly almost perfectly predicted by the ARF or GF
4313
    // but not very well predcited by the previous frame.
4314
0
    if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
4315
0
      int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
4316
0
      if (rc->projected_frame_size < fast_extra_thresh) {
4317
0
        p_rc->vbr_bits_off_target_fast +=
4318
0
            fast_extra_thresh - rc->projected_frame_size;
4319
0
        p_rc->vbr_bits_off_target_fast =
4320
0
            AOMMIN(p_rc->vbr_bits_off_target_fast,
4321
0
                   (4 * (int64_t)rc->avg_frame_bandwidth));
4322
0
      }
4323
0
    }
4324
4325
#if CONFIG_FPMT_TEST
4326
    if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
4327
        simulate_parallel_frame) {
4328
      cpi->ppi->p_rc.temp_vbr_bits_off_target_fast =
4329
          p_rc->vbr_bits_off_target_fast;
4330
      cpi->ppi->p_rc.temp_extend_minq = twopass->extend_minq;
4331
      cpi->ppi->p_rc.temp_extend_maxq = twopass->extend_maxq;
4332
    }
4333
#endif
4334
0
  }
4335
4336
  // Update the frame probabilities obtained from parallel encode frames
4337
18.9k
  FrameProbInfo *const frame_probs = &cpi->ppi->frame_probs;
4338
#if CONFIG_FPMT_TEST
4339
  /* The variable temp_active_best_quality is introduced only for quality
4340
   * simulation purpose, it retains the value previous to the parallel
4341
   * encode frames. The variable is updated based on the update flag.
4342
   *
4343
   * If there exist show_existing_frames between parallel frames, then to
4344
   * retain the temp state do not update it. */
4345
  if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
4346
      simulate_parallel_frame) {
4347
    int i;
4348
    const int pyramid_level =
4349
        cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index];
4350
    if (!rc->is_src_frame_alt_ref) {
4351
      for (i = pyramid_level; i <= MAX_ARF_LAYERS; ++i)
4352
        cpi->ppi->p_rc.temp_active_best_quality[i] =
4353
            p_rc->active_best_quality[i];
4354
    }
4355
  }
4356
4357
  // Update the frame probabilities obtained from parallel encode frames
4358
  FrameProbInfo *const temp_frame_probs_simulation =
4359
      simulate_parallel_frame ? &cpi->ppi->temp_frame_probs_simulation
4360
                              : frame_probs;
4361
  FrameProbInfo *const temp_frame_probs =
4362
      simulate_parallel_frame ? &cpi->ppi->temp_frame_probs : NULL;
4363
#endif
4364
18.9k
  int i, j, loop;
4365
  // Sequentially do average on temp_frame_probs_simulation which holds
4366
  // probabilities of last frame before parallel encode
4367
37.8k
  for (loop = 0; loop <= cpi->num_frame_recode; loop++) {
4368
    // Sequentially update tx_type_probs
4369
18.9k
    if (cpi->do_update_frame_probs_txtype[loop] &&
4370
0
        (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)) {
4371
0
      const FRAME_UPDATE_TYPE update_type =
4372
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4373
0
      for (i = 0; i < TX_SIZES_ALL; i++) {
4374
0
        int left = 1024;
4375
4376
0
        for (j = TX_TYPES - 1; j >= 0; j--) {
4377
0
          const int new_prob =
4378
0
              cpi->frame_new_probs[loop].tx_type_probs[update_type][i][j];
4379
#if CONFIG_FPMT_TEST
4380
          int prob =
4381
              (temp_frame_probs_simulation->tx_type_probs[update_type][i][j] +
4382
               new_prob) >>
4383
              1;
4384
          left -= prob;
4385
          if (j == 0) prob += left;
4386
          temp_frame_probs_simulation->tx_type_probs[update_type][i][j] = prob;
4387
#else
4388
0
          int prob =
4389
0
              (frame_probs->tx_type_probs[update_type][i][j] + new_prob) >> 1;
4390
0
          left -= prob;
4391
0
          if (j == 0) prob += left;
4392
0
          frame_probs->tx_type_probs[update_type][i][j] = prob;
4393
0
#endif
4394
0
        }
4395
0
      }
4396
0
    }
4397
4398
    // Sequentially update obmc_probs
4399
18.9k
    if (cpi->do_update_frame_probs_obmc[loop] &&
4400
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
4401
0
      const FRAME_UPDATE_TYPE update_type =
4402
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4403
4404
0
      for (i = 0; i < BLOCK_SIZES_ALL; i++) {
4405
0
        const int new_prob =
4406
0
            cpi->frame_new_probs[loop].obmc_probs[update_type][i];
4407
#if CONFIG_FPMT_TEST
4408
        temp_frame_probs_simulation->obmc_probs[update_type][i] =
4409
            (temp_frame_probs_simulation->obmc_probs[update_type][i] +
4410
             new_prob) >>
4411
            1;
4412
#else
4413
0
        frame_probs->obmc_probs[update_type][i] =
4414
0
            (frame_probs->obmc_probs[update_type][i] + new_prob) >> 1;
4415
0
#endif
4416
0
      }
4417
0
    }
4418
4419
    // Sequentially update warped_probs
4420
18.9k
    if (cpi->do_update_frame_probs_warp[loop] &&
4421
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
4422
0
      const FRAME_UPDATE_TYPE update_type =
4423
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4424
0
      const int new_prob = cpi->frame_new_probs[loop].warped_probs[update_type];
4425
#if CONFIG_FPMT_TEST
4426
      temp_frame_probs_simulation->warped_probs[update_type] =
4427
          (temp_frame_probs_simulation->warped_probs[update_type] + new_prob) >>
4428
          1;
4429
#else
4430
0
      frame_probs->warped_probs[update_type] =
4431
0
          (frame_probs->warped_probs[update_type] + new_prob) >> 1;
4432
0
#endif
4433
0
    }
4434
4435
    // Sequentially update switchable_interp_probs
4436
18.9k
    if (cpi->do_update_frame_probs_interpfilter[loop] &&
4437
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
4438
0
      const FRAME_UPDATE_TYPE update_type =
4439
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4440
4441
0
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4442
0
        int left = 1536;
4443
4444
0
        for (j = SWITCHABLE_FILTERS - 1; j >= 0; j--) {
4445
0
          const int new_prob = cpi->frame_new_probs[loop]
4446
0
                                   .switchable_interp_probs[update_type][i][j];
4447
#if CONFIG_FPMT_TEST
4448
          int prob = (temp_frame_probs_simulation
4449
                          ->switchable_interp_probs[update_type][i][j] +
4450
                      new_prob) >>
4451
                     1;
4452
          left -= prob;
4453
          if (j == 0) prob += left;
4454
4455
          temp_frame_probs_simulation
4456
              ->switchable_interp_probs[update_type][i][j] = prob;
4457
#else
4458
0
          int prob = (frame_probs->switchable_interp_probs[update_type][i][j] +
4459
0
                      new_prob) >>
4460
0
                     1;
4461
0
          left -= prob;
4462
0
          if (j == 0) prob += left;
4463
0
          frame_probs->switchable_interp_probs[update_type][i][j] = prob;
4464
0
#endif
4465
0
        }
4466
0
      }
4467
0
    }
4468
18.9k
  }
4469
4470
#if CONFIG_FPMT_TEST
4471
  // Copying temp_frame_probs_simulation to temp_frame_probs based on
4472
  // the flag
4473
  if (cpi->do_frame_data_update &&
4474
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
4475
      simulate_parallel_frame) {
4476
    for (int update_type_idx = 0; update_type_idx < FRAME_UPDATE_TYPES;
4477
         update_type_idx++) {
4478
      for (i = 0; i < BLOCK_SIZES_ALL; i++) {
4479
        temp_frame_probs->obmc_probs[update_type_idx][i] =
4480
            temp_frame_probs_simulation->obmc_probs[update_type_idx][i];
4481
      }
4482
      temp_frame_probs->warped_probs[update_type_idx] =
4483
          temp_frame_probs_simulation->warped_probs[update_type_idx];
4484
      for (i = 0; i < TX_SIZES_ALL; i++) {
4485
        for (j = 0; j < TX_TYPES; j++) {
4486
          temp_frame_probs->tx_type_probs[update_type_idx][i][j] =
4487
              temp_frame_probs_simulation->tx_type_probs[update_type_idx][i][j];
4488
        }
4489
      }
4490
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4491
        for (j = 0; j < SWITCHABLE_FILTERS; j++) {
4492
          temp_frame_probs->switchable_interp_probs[update_type_idx][i][j] =
4493
              temp_frame_probs_simulation
4494
                  ->switchable_interp_probs[update_type_idx][i][j];
4495
        }
4496
      }
4497
    }
4498
  }
4499
#endif
4500
  // Update framerate obtained from parallel encode frames
4501
18.9k
  if (cpi->common.show_frame &&
4502
18.9k
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
4503
0
    cpi->framerate = cpi->new_framerate;
4504
#if CONFIG_FPMT_TEST
4505
  // SIMULATION PURPOSE
4506
  int show_existing_between_parallel_frames_cndn =
4507
      (cpi->ppi->gf_group.update_type[cpi->gf_frame_index] ==
4508
           INTNL_OVERLAY_UPDATE &&
4509
       cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index + 1] == 2);
4510
  if (cpi->common.show_frame && !show_existing_between_parallel_frames_cndn &&
4511
      cpi->do_frame_data_update && simulate_parallel_frame)
4512
    cpi->temp_framerate = cpi->framerate;
4513
#endif
4514
18.9k
}