Coverage Report

Created: 2026-07-25 07:06

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