Coverage Report

Created: 2026-10-28 07:26

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
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1122
0
  int gop_length_decision_method = cpi->sf.tpl_sf.gop_length_decision_method;
1123
0
  int shorten_gf_interval = 0;
1124
1125
0
  av1_tpl_preload_rc_estimate(cpi, frame_params);
1126
1127
0
  if (gop_length_decision_method == 1) {
1128
    // GF group length is decided based on GF boost and tpl stats of ARFs from
1129
    // base layer, (base+1) layer.
1130
0
    shorten_gf_interval =
1131
0
        (p_rc->gfu_boost <
1132
0
         p_rc->num_stats_used_for_gfu_boost * GF_MIN_BOOST * 1.4) &&
1133
0
        !av1_tpl_setup_stats(cpi, /*approx_gop_eval=*/true, frame_params);
1134
0
  } else if (gop_length_decision_method == 0) {
1135
    // Check if tpl stats of ARFs from base layer, (base+1) layer,
1136
    // (base+2) layer can decide the GF group length.
1137
0
    int gop_length_eval =
1138
0
        av1_tpl_setup_stats(cpi, /*approx_gop_eval=*/true, frame_params);
1139
0
    assert(gop_length_eval != -1);
1140
0
    shorten_gf_interval = !gop_length_eval;
1141
0
  }
1142
0
  return shorten_gf_interval;
1143
0
}
1144
1145
#define MIN_SHRINK_LEN 6  // the minimum length of gf if we are shrinking
1146
0
#define SMOOTH_FILT_LEN 7
1147
0
#define HALF_FILT_LEN (SMOOTH_FILT_LEN / 2)
1148
0
#define WINDOW_SIZE 7
1149
0
#define HALF_WIN (WINDOW_SIZE / 2)
1150
1151
// Smooth filter intra_error and coded_error in firstpass stats.
1152
// If stats[i].is_flash==1, the ith element should not be used in the filtering.
1153
static void smooth_filter_stats(const FIRSTPASS_STATS *stats, int start_idx,
1154
                                int last_idx, double *filt_intra_err,
1155
0
                                double *filt_coded_err) {
1156
  // A 7-tap gaussian smooth filter
1157
0
  static const double smooth_filt[SMOOTH_FILT_LEN] = { 0.006, 0.061, 0.242,
1158
0
                                                       0.383, 0.242, 0.061,
1159
0
                                                       0.006 };
1160
0
  int i, j;
1161
0
  for (i = start_idx; i <= last_idx; i++) {
1162
0
    double total_wt = 0;
1163
0
    for (j = -HALF_FILT_LEN; j <= HALF_FILT_LEN; j++) {
1164
0
      int idx = clamp(i + j, start_idx, last_idx);
1165
0
      if (stats[idx].is_flash) continue;
1166
1167
0
      filt_intra_err[i] +=
1168
0
          smooth_filt[j + HALF_FILT_LEN] * stats[idx].intra_error;
1169
0
      total_wt += smooth_filt[j + HALF_FILT_LEN];
1170
0
    }
1171
0
    if (total_wt > 0.01) {
1172
0
      filt_intra_err[i] /= total_wt;
1173
0
    } else {
1174
0
      filt_intra_err[i] = stats[i].intra_error;
1175
0
    }
1176
0
  }
1177
0
  for (i = start_idx; i <= last_idx; i++) {
1178
0
    double total_wt = 0;
1179
0
    for (j = -HALF_FILT_LEN; j <= HALF_FILT_LEN; j++) {
1180
0
      int idx = clamp(i + j, start_idx, last_idx);
1181
      // Coded error involves idx and idx - 1.
1182
0
      if (stats[idx].is_flash || (idx > 0 && stats[idx - 1].is_flash)) continue;
1183
1184
0
      filt_coded_err[i] +=
1185
0
          smooth_filt[j + HALF_FILT_LEN] * stats[idx].coded_error;
1186
0
      total_wt += smooth_filt[j + HALF_FILT_LEN];
1187
0
    }
1188
0
    if (total_wt > 0.01) {
1189
0
      filt_coded_err[i] /= total_wt;
1190
0
    } else {
1191
0
      filt_coded_err[i] = stats[i].coded_error;
1192
0
    }
1193
0
  }
1194
0
}
1195
1196
// Calculate gradient
1197
static void get_gradient(const double *values, int start, int last,
1198
0
                         double *grad) {
1199
0
  if (start == last) {
1200
0
    grad[start] = 0;
1201
0
    return;
1202
0
  }
1203
0
  for (int i = start; i <= last; i++) {
1204
0
    int prev = AOMMAX(i - 1, start);
1205
0
    int next = AOMMIN(i + 1, last);
1206
0
    grad[i] = (values[next] - values[prev]) / (next - prev);
1207
0
  }
1208
0
}
1209
1210
static int find_next_scenecut(const FIRSTPASS_STATS *const stats_start,
1211
0
                              int first, int last) {
1212
  // Identify unstable areas caused by scenecuts.
1213
  // Find the max and 2nd max coded error, and the average of the rest frames.
1214
  // If there is only one frame that yields a huge coded error, it is likely a
1215
  // scenecut.
1216
0
  double this_ratio, max_prev_ratio, max_next_ratio, max_prev_coded,
1217
0
      max_next_coded;
1218
1219
0
  if (last - first == 0) return -1;
1220
1221
0
  for (int i = first; i <= last; i++) {
1222
0
    if (stats_start[i].is_flash || (i > 0 && stats_start[i - 1].is_flash))
1223
0
      continue;
1224
0
    double temp_intra = AOMMAX(stats_start[i].intra_error, 0.01);
1225
0
    this_ratio = stats_start[i].coded_error / temp_intra;
1226
    // find the avg ratio in the preceding neighborhood
1227
0
    max_prev_ratio = 0;
1228
0
    max_prev_coded = 0;
1229
0
    for (int j = AOMMAX(first, i - HALF_WIN); j < i; j++) {
1230
0
      if (stats_start[j].is_flash || (j > 0 && stats_start[j - 1].is_flash))
1231
0
        continue;
1232
0
      temp_intra = AOMMAX(stats_start[j].intra_error, 0.01);
1233
0
      double temp_ratio = stats_start[j].coded_error / temp_intra;
1234
0
      if (temp_ratio > max_prev_ratio) {
1235
0
        max_prev_ratio = temp_ratio;
1236
0
      }
1237
0
      if (stats_start[j].coded_error > max_prev_coded) {
1238
0
        max_prev_coded = stats_start[j].coded_error;
1239
0
      }
1240
0
    }
1241
    // find the avg ratio in the following neighborhood
1242
0
    max_next_ratio = 0;
1243
0
    max_next_coded = 0;
1244
0
    for (int j = i + 1; j <= AOMMIN(i + HALF_WIN, last); j++) {
1245
0
      if (stats_start[i].is_flash || (i > 0 && stats_start[i - 1].is_flash))
1246
0
        continue;
1247
0
      temp_intra = AOMMAX(stats_start[j].intra_error, 0.01);
1248
0
      double temp_ratio = stats_start[j].coded_error / temp_intra;
1249
0
      if (temp_ratio > max_next_ratio) {
1250
0
        max_next_ratio = temp_ratio;
1251
0
      }
1252
0
      if (stats_start[j].coded_error > max_next_coded) {
1253
0
        max_next_coded = stats_start[j].coded_error;
1254
0
      }
1255
0
    }
1256
1257
0
    if (max_prev_ratio < 0.001 && max_next_ratio < 0.001) {
1258
      // the ratios are very small, only check a small fixed threshold
1259
0
      if (this_ratio < 0.02) continue;
1260
0
    } else {
1261
      // check if this frame has a larger ratio than the neighborhood
1262
0
      double max_sr = stats_start[i].sr_coded_error;
1263
0
      if (i < last) max_sr = AOMMAX(max_sr, stats_start[i + 1].sr_coded_error);
1264
0
      double max_sr_fr_ratio =
1265
0
          max_sr / AOMMAX(stats_start[i].coded_error, 0.01);
1266
1267
0
      if (max_sr_fr_ratio > 1.2) continue;
1268
0
      if (this_ratio < 2 * AOMMAX(max_prev_ratio, max_next_ratio) &&
1269
0
          stats_start[i].coded_error <
1270
0
              2 * AOMMAX(max_prev_coded, max_next_coded)) {
1271
0
        continue;
1272
0
      }
1273
0
    }
1274
0
    return i;
1275
0
  }
1276
0
  return -1;
1277
0
}
1278
1279
// Remove the region with index next_region.
1280
// parameter merge: 0: merge with previous; 1: merge with next; 2:
1281
// merge with both, take type from previous if possible
1282
// After removing, next_region will be the index of the next region.
1283
static void remove_region(int merge, REGIONS *regions, int *num_regions,
1284
0
                          int *next_region) {
1285
0
  int k = *next_region;
1286
0
  assert(k < *num_regions);
1287
0
  if (*num_regions == 1) {
1288
0
    *num_regions = 0;
1289
0
    return;
1290
0
  }
1291
0
  if (k == 0) {
1292
0
    merge = 1;
1293
0
  } else if (k == *num_regions - 1) {
1294
0
    merge = 0;
1295
0
  }
1296
0
  int num_merge = (merge == 2) ? 2 : 1;
1297
0
  switch (merge) {
1298
0
    case 0:
1299
0
      regions[k - 1].last = regions[k].last;
1300
0
      *next_region = k;
1301
0
      break;
1302
0
    case 1:
1303
0
      regions[k + 1].start = regions[k].start;
1304
0
      *next_region = k + 1;
1305
0
      break;
1306
0
    case 2:
1307
0
      regions[k - 1].last = regions[k + 1].last;
1308
0
      *next_region = k;
1309
0
      break;
1310
0
    default: assert(0);
1311
0
  }
1312
0
  *num_regions -= num_merge;
1313
0
  for (k = *next_region - (merge == 1); k < *num_regions; k++) {
1314
0
    regions[k] = regions[k + num_merge];
1315
0
  }
1316
0
}
1317
1318
// Insert a region in the cur_region_idx. The start and last should both be in
1319
// the current region. After insertion, the cur_region_idx will point to the
1320
// last region that was splitted from the original region.
1321
static void insert_region(int start, int last, REGION_TYPES type,
1322
                          REGIONS *regions, int *num_regions,
1323
0
                          int *cur_region_idx) {
1324
0
  int k = *cur_region_idx;
1325
0
  REGION_TYPES this_region_type = regions[k].type;
1326
0
  int this_region_last = regions[k].last;
1327
0
  int num_add = (start != regions[k].start) + (last != regions[k].last);
1328
  // move the following regions further to the back
1329
0
  for (int r = *num_regions - 1; r > k; r--) {
1330
0
    regions[r + num_add] = regions[r];
1331
0
  }
1332
0
  *num_regions += num_add;
1333
0
  if (start > regions[k].start) {
1334
0
    regions[k].last = start - 1;
1335
0
    k++;
1336
0
    regions[k].start = start;
1337
0
  }
1338
0
  regions[k].type = type;
1339
0
  if (last < this_region_last) {
1340
0
    regions[k].last = last;
1341
0
    k++;
1342
0
    regions[k].start = last + 1;
1343
0
    regions[k].last = this_region_last;
1344
0
    regions[k].type = this_region_type;
1345
0
  } else {
1346
0
    regions[k].last = this_region_last;
1347
0
  }
1348
0
  *cur_region_idx = k;
1349
0
}
1350
1351
// Get the average of stats inside a region.
1352
static void analyze_region(const FIRSTPASS_STATS *stats, int k,
1353
0
                           REGIONS *regions) {
1354
0
  int i;
1355
0
  regions[k].avg_cor_coeff = 0;
1356
0
  regions[k].avg_sr_fr_ratio = 0;
1357
0
  regions[k].avg_intra_err = 0;
1358
0
  regions[k].avg_coded_err = 0;
1359
1360
0
  int check_first_sr = (k != 0);
1361
1362
0
  for (i = regions[k].start; i <= regions[k].last; i++) {
1363
0
    if (i > regions[k].start || check_first_sr) {
1364
0
      double num_frames =
1365
0
          (double)(regions[k].last - regions[k].start + check_first_sr);
1366
0
      double max_coded_error =
1367
0
          AOMMAX(stats[i].coded_error, stats[i - 1].coded_error);
1368
0
      double this_ratio =
1369
0
          stats[i].sr_coded_error / AOMMAX(max_coded_error, 0.001);
1370
0
      regions[k].avg_sr_fr_ratio += this_ratio / num_frames;
1371
0
    }
1372
1373
0
    regions[k].avg_intra_err +=
1374
0
        stats[i].intra_error / (double)(regions[k].last - regions[k].start + 1);
1375
0
    regions[k].avg_coded_err +=
1376
0
        stats[i].coded_error / (double)(regions[k].last - regions[k].start + 1);
1377
1378
0
    regions[k].avg_cor_coeff +=
1379
0
        AOMMAX(stats[i].cor_coeff, 0.001) /
1380
0
        (double)(regions[k].last - regions[k].start + 1);
1381
0
    regions[k].avg_noise_var +=
1382
0
        AOMMAX(stats[i].noise_var, 0.001) /
1383
0
        (double)(regions[k].last - regions[k].start + 1);
1384
0
  }
1385
0
}
1386
1387
// Calculate the regions stats of every region.
1388
static void get_region_stats(const FIRSTPASS_STATS *stats, REGIONS *regions,
1389
0
                             int num_regions) {
1390
0
  for (int k = 0; k < num_regions; k++) {
1391
0
    analyze_region(stats, k, regions);
1392
0
  }
1393
0
}
1394
1395
// Find tentative stable regions
1396
static int find_stable_regions(const FIRSTPASS_STATS *stats,
1397
                               const double *grad_coded, int this_start,
1398
0
                               int this_last, REGIONS *regions) {
1399
0
  int i, j, k = 0;
1400
0
  regions[k].start = this_start;
1401
0
  for (i = this_start; i <= this_last; i++) {
1402
    // Check mean and variance of stats in a window
1403
0
    double mean_intra = 0.001, var_intra = 0.001;
1404
0
    double mean_coded = 0.001, var_coded = 0.001;
1405
0
    int count = 0;
1406
0
    for (j = -HALF_WIN; j <= HALF_WIN; j++) {
1407
0
      int idx = clamp(i + j, this_start, this_last);
1408
0
      if (stats[idx].is_flash || (idx > 0 && stats[idx - 1].is_flash)) continue;
1409
0
      mean_intra += stats[idx].intra_error;
1410
0
      var_intra += stats[idx].intra_error * stats[idx].intra_error;
1411
0
      mean_coded += stats[idx].coded_error;
1412
0
      var_coded += stats[idx].coded_error * stats[idx].coded_error;
1413
0
      count++;
1414
0
    }
1415
1416
0
    REGION_TYPES cur_type;
1417
0
    if (count > 0) {
1418
0
      mean_intra /= (double)count;
1419
0
      var_intra /= (double)count;
1420
0
      mean_coded /= (double)count;
1421
0
      var_coded /= (double)count;
1422
0
      int is_intra_stable = (var_intra / (mean_intra * mean_intra) < 1.03);
1423
0
      int is_coded_stable = (var_coded / (mean_coded * mean_coded) < 1.04 &&
1424
0
                             fabs(grad_coded[i]) / mean_coded < 0.05) ||
1425
0
                            mean_coded / mean_intra < 0.05;
1426
0
      int is_coded_small = mean_coded < 0.5 * mean_intra;
1427
0
      cur_type = (is_intra_stable && is_coded_stable && is_coded_small)
1428
0
                     ? STABLE_REGION
1429
0
                     : HIGH_VAR_REGION;
1430
0
    } else {
1431
0
      cur_type = HIGH_VAR_REGION;
1432
0
    }
1433
1434
    // mark a new region if type changes
1435
0
    if (i == regions[k].start) {
1436
      // first frame in the region
1437
0
      regions[k].type = cur_type;
1438
0
    } else if (cur_type != regions[k].type) {
1439
      // Append a new region
1440
0
      regions[k].last = i - 1;
1441
0
      regions[k + 1].start = i;
1442
0
      regions[k + 1].type = cur_type;
1443
0
      k++;
1444
0
    }
1445
0
  }
1446
0
  regions[k].last = this_last;
1447
0
  return k + 1;
1448
0
}
1449
1450
// Clean up regions that should be removed or merged.
1451
0
static void cleanup_regions(REGIONS *regions, int *num_regions) {
1452
0
  int k = 0;
1453
0
  while (k < *num_regions) {
1454
0
    if ((k > 0 && regions[k - 1].type == regions[k].type &&
1455
0
         regions[k].type != SCENECUT_REGION) ||
1456
0
        regions[k].last < regions[k].start) {
1457
0
      remove_region(0, regions, num_regions, &k);
1458
0
    } else {
1459
0
      k++;
1460
0
    }
1461
0
  }
1462
0
}
1463
1464
// Remove regions that are of type and shorter than length.
1465
// Merge it with its neighboring regions.
1466
static void remove_short_regions(REGIONS *regions, int *num_regions,
1467
0
                                 REGION_TYPES type, int length) {
1468
0
  int k = 0;
1469
0
  while (k < *num_regions && (*num_regions) > 1) {
1470
0
    if ((regions[k].last - regions[k].start + 1 < length &&
1471
0
         regions[k].type == type)) {
1472
      // merge current region with the previous and next regions
1473
0
      remove_region(2, regions, num_regions, &k);
1474
0
    } else {
1475
0
      k++;
1476
0
    }
1477
0
  }
1478
0
  cleanup_regions(regions, num_regions);
1479
0
}
1480
1481
static void adjust_unstable_region_bounds(const FIRSTPASS_STATS *stats,
1482
0
                                          REGIONS *regions, int *num_regions) {
1483
0
  int i, j, k;
1484
  // Remove regions that are too short. Likely noise.
1485
0
  remove_short_regions(regions, num_regions, STABLE_REGION, HALF_WIN);
1486
0
  remove_short_regions(regions, num_regions, HIGH_VAR_REGION, HALF_WIN);
1487
1488
0
  get_region_stats(stats, regions, *num_regions);
1489
1490
  // Adjust region boundaries. The thresholds are empirically obtained, but
1491
  // overall the performance is not very sensitive to small changes to them.
1492
0
  for (k = 0; k < *num_regions; k++) {
1493
0
    if (regions[k].type == STABLE_REGION) continue;
1494
0
    if (k > 0) {
1495
      // Adjust previous boundary.
1496
      // First find the average intra/coded error in the previous
1497
      // neighborhood.
1498
0
      double avg_intra_err = 0;
1499
0
      const int starti = AOMMAX(regions[k - 1].last - WINDOW_SIZE + 1,
1500
0
                                regions[k - 1].start + 1);
1501
0
      const int lasti = regions[k - 1].last;
1502
0
      int counti = 0;
1503
0
      for (i = starti; i <= lasti; i++) {
1504
0
        avg_intra_err += stats[i].intra_error;
1505
0
        counti++;
1506
0
      }
1507
0
      if (counti > 0) {
1508
0
        avg_intra_err = AOMMAX(avg_intra_err / (double)counti, 0.001);
1509
0
        int count_coded = 0, count_grad = 0;
1510
0
        for (j = lasti + 1; j <= regions[k].last; j++) {
1511
0
          const int intra_close =
1512
0
              fabs(stats[j].intra_error - avg_intra_err) / avg_intra_err < 0.1;
1513
0
          const int coded_small = stats[j].coded_error / avg_intra_err < 0.1;
1514
0
          const int coeff_close = stats[j].cor_coeff > 0.995;
1515
0
          if (!coeff_close || !coded_small) count_coded--;
1516
0
          if (intra_close && count_coded >= 0 && count_grad >= 0) {
1517
            // this frame probably belongs to the previous stable region
1518
0
            regions[k - 1].last = j;
1519
0
            regions[k].start = j + 1;
1520
0
          } else {
1521
0
            break;
1522
0
          }
1523
0
        }
1524
0
      }
1525
0
    }  // if k > 0
1526
0
    if (k < *num_regions - 1) {
1527
      // Adjust next boundary.
1528
      // First find the average intra/coded error in the next neighborhood.
1529
0
      double avg_intra_err = 0;
1530
0
      const int starti = regions[k + 1].start;
1531
0
      const int lasti = AOMMIN(regions[k + 1].last - 1,
1532
0
                               regions[k + 1].start + WINDOW_SIZE - 1);
1533
0
      int counti = 0;
1534
0
      for (i = starti; i <= lasti; i++) {
1535
0
        avg_intra_err += stats[i].intra_error;
1536
0
        counti++;
1537
0
      }
1538
0
      if (counti > 0) {
1539
0
        avg_intra_err = AOMMAX(avg_intra_err / (double)counti, 0.001);
1540
        // At the boundary, coded error is large, but still the frame is stable
1541
0
        int count_coded = 1, count_grad = 1;
1542
0
        for (j = starti - 1; j >= regions[k].start; j--) {
1543
0
          const int intra_close =
1544
0
              fabs(stats[j].intra_error - avg_intra_err) / avg_intra_err < 0.1;
1545
0
          const int coded_small =
1546
0
              stats[j + 1].coded_error / avg_intra_err < 0.1;
1547
0
          const int coeff_close = stats[j].cor_coeff > 0.995;
1548
0
          if (!coeff_close || !coded_small) count_coded--;
1549
0
          if (intra_close && count_coded >= 0 && count_grad >= 0) {
1550
            // this frame probably belongs to the next stable region
1551
0
            regions[k + 1].start = j;
1552
0
            regions[k].last = j - 1;
1553
0
          } else {
1554
0
            break;
1555
0
          }
1556
0
        }
1557
0
      }
1558
0
    }  // if k < *num_regions - 1
1559
0
  }  // end of loop over all regions
1560
1561
0
  cleanup_regions(regions, num_regions);
1562
0
  remove_short_regions(regions, num_regions, HIGH_VAR_REGION, HALF_WIN);
1563
0
  get_region_stats(stats, regions, *num_regions);
1564
1565
  // If a stable regions has higher error than neighboring high var regions,
1566
  // or if the stable region has a lower average correlation,
1567
  // then it should be merged with them
1568
0
  k = 0;
1569
0
  while (k < *num_regions && (*num_regions) > 1) {
1570
0
    if (regions[k].type == STABLE_REGION &&
1571
0
        (regions[k].last - regions[k].start + 1) < 2 * WINDOW_SIZE &&
1572
0
        ((k > 0 &&  // previous regions
1573
0
          (regions[k].avg_coded_err > regions[k - 1].avg_coded_err * 1.01 ||
1574
0
           regions[k].avg_cor_coeff < regions[k - 1].avg_cor_coeff * 0.999)) &&
1575
0
         (k < *num_regions - 1 &&  // next region
1576
0
          (regions[k].avg_coded_err > regions[k + 1].avg_coded_err * 1.01 ||
1577
0
           regions[k].avg_cor_coeff < regions[k + 1].avg_cor_coeff * 0.999)))) {
1578
      // merge current region with the previous and next regions
1579
0
      remove_region(2, regions, num_regions, &k);
1580
0
      analyze_region(stats, k - 1, regions);
1581
0
    } else if (regions[k].type == HIGH_VAR_REGION &&
1582
0
               (regions[k].last - regions[k].start + 1) < 2 * WINDOW_SIZE &&
1583
0
               ((k > 0 &&  // previous regions
1584
0
                 (regions[k].avg_coded_err <
1585
0
                      regions[k - 1].avg_coded_err * 0.99 ||
1586
0
                  regions[k].avg_cor_coeff >
1587
0
                      regions[k - 1].avg_cor_coeff * 1.001)) &&
1588
0
                (k < *num_regions - 1 &&  // next region
1589
0
                 (regions[k].avg_coded_err <
1590
0
                      regions[k + 1].avg_coded_err * 0.99 ||
1591
0
                  regions[k].avg_cor_coeff >
1592
0
                      regions[k + 1].avg_cor_coeff * 1.001)))) {
1593
      // merge current region with the previous and next regions
1594
0
      remove_region(2, regions, num_regions, &k);
1595
0
      analyze_region(stats, k - 1, regions);
1596
0
    } else {
1597
0
      k++;
1598
0
    }
1599
0
  }
1600
1601
0
  remove_short_regions(regions, num_regions, STABLE_REGION, WINDOW_SIZE);
1602
0
  remove_short_regions(regions, num_regions, HIGH_VAR_REGION, HALF_WIN);
1603
0
}
1604
1605
// Identify blending regions.
1606
static void find_blending_regions(const FIRSTPASS_STATS *stats,
1607
0
                                  REGIONS *regions, int *num_regions) {
1608
0
  int i, k = 0;
1609
  // Blending regions will have large content change, therefore will have a
1610
  // large consistent change in intra error.
1611
0
  int count_stable = 0;
1612
0
  while (k < *num_regions) {
1613
0
    if (regions[k].type == STABLE_REGION) {
1614
0
      k++;
1615
0
      count_stable++;
1616
0
      continue;
1617
0
    }
1618
0
    int dir = 0;
1619
0
    int start = 0, last;
1620
0
    for (i = regions[k].start; i <= regions[k].last; i++) {
1621
      // First mark the regions that has consistent large change of intra error.
1622
0
      if (k == 0 && i == regions[k].start) continue;
1623
0
      if (stats[i].is_flash || (i > 0 && stats[i - 1].is_flash)) continue;
1624
0
      double grad = stats[i].intra_error - stats[i - 1].intra_error;
1625
0
      int large_change = fabs(grad) / AOMMAX(stats[i].intra_error, 0.01) > 0.05;
1626
0
      int this_dir = 0;
1627
0
      if (large_change) {
1628
0
        this_dir = (grad > 0) ? 1 : -1;
1629
0
      }
1630
      // the current trend continues
1631
0
      if (dir == this_dir) continue;
1632
0
      if (dir != 0) {
1633
        // Mark the end of a new large change group and add it
1634
0
        last = i - 1;
1635
0
        insert_region(start, last, BLENDING_REGION, regions, num_regions, &k);
1636
0
      }
1637
0
      dir = this_dir;
1638
0
      if (k == 0 && i == regions[k].start + 1) {
1639
0
        start = i - 1;
1640
0
      } else {
1641
0
        start = i;
1642
0
      }
1643
0
    }
1644
0
    if (dir != 0) {
1645
0
      last = regions[k].last;
1646
0
      insert_region(start, last, BLENDING_REGION, regions, num_regions, &k);
1647
0
    }
1648
0
    k++;
1649
0
  }
1650
1651
  // If the blending region has very low correlation, mark it as high variance
1652
  // since we probably cannot benefit from it anyways.
1653
0
  get_region_stats(stats, regions, *num_regions);
1654
0
  for (k = 0; k < *num_regions; k++) {
1655
0
    if (regions[k].type != BLENDING_REGION) continue;
1656
0
    if (regions[k].last == regions[k].start || regions[k].avg_cor_coeff < 0.6 ||
1657
0
        count_stable == 0)
1658
0
      regions[k].type = HIGH_VAR_REGION;
1659
0
  }
1660
0
  get_region_stats(stats, regions, *num_regions);
1661
1662
  // It is possible for blending to result in a "dip" in intra error (first
1663
  // decrease then increase). Therefore we need to find the dip and combine the
1664
  // two regions.
1665
0
  k = 1;
1666
0
  while (k < *num_regions) {
1667
0
    if (k < *num_regions - 1 && regions[k].type == HIGH_VAR_REGION) {
1668
      // Check if this short high variance regions is actually in the middle of
1669
      // a blending region.
1670
0
      if (regions[k - 1].type == BLENDING_REGION &&
1671
0
          regions[k + 1].type == BLENDING_REGION &&
1672
0
          regions[k].last - regions[k].start < 3) {
1673
0
        int prev_dir = (stats[regions[k - 1].last].intra_error -
1674
0
                        stats[regions[k - 1].last - 1].intra_error) > 0
1675
0
                           ? 1
1676
0
                           : -1;
1677
0
        int next_dir = (stats[regions[k + 1].last].intra_error -
1678
0
                        stats[regions[k + 1].last - 1].intra_error) > 0
1679
0
                           ? 1
1680
0
                           : -1;
1681
0
        if (prev_dir < 0 && next_dir > 0) {
1682
          // This is possibly a mid region of blending. Check the ratios
1683
0
          double ratio_thres = AOMMIN(regions[k - 1].avg_sr_fr_ratio,
1684
0
                                      regions[k + 1].avg_sr_fr_ratio) *
1685
0
                               0.95;
1686
0
          if (regions[k].avg_sr_fr_ratio > ratio_thres) {
1687
0
            regions[k].type = BLENDING_REGION;
1688
0
            remove_region(2, regions, num_regions, &k);
1689
0
            analyze_region(stats, k - 1, regions);
1690
0
            continue;
1691
0
          }
1692
0
        }
1693
0
      }
1694
0
    }
1695
    // Check if we have a pair of consecutive blending regions.
1696
0
    if (regions[k - 1].type == BLENDING_REGION &&
1697
0
        regions[k].type == BLENDING_REGION) {
1698
0
      int prev_dir = (stats[regions[k - 1].last].intra_error -
1699
0
                      stats[regions[k - 1].last - 1].intra_error) > 0
1700
0
                         ? 1
1701
0
                         : -1;
1702
0
      int next_dir = (stats[regions[k].last].intra_error -
1703
0
                      stats[regions[k].last - 1].intra_error) > 0
1704
0
                         ? 1
1705
0
                         : -1;
1706
1707
      // if both are too short, no need to check
1708
0
      int total_length = regions[k].last - regions[k - 1].start + 1;
1709
0
      if (total_length < 4) {
1710
0
        regions[k - 1].type = HIGH_VAR_REGION;
1711
0
        k++;
1712
0
        continue;
1713
0
      }
1714
1715
0
      int to_merge = 0;
1716
0
      if (prev_dir < 0 && next_dir > 0) {
1717
        // In this case we check the last frame in the previous region.
1718
0
        double prev_length =
1719
0
            (double)(regions[k - 1].last - regions[k - 1].start + 1);
1720
0
        double last_ratio, ratio_thres;
1721
0
        if (prev_length < 2.01) {
1722
          // if the previous region is very short
1723
0
          double max_coded_error =
1724
0
              AOMMAX(stats[regions[k - 1].last].coded_error,
1725
0
                     stats[regions[k - 1].last - 1].coded_error);
1726
0
          last_ratio = stats[regions[k - 1].last].sr_coded_error /
1727
0
                       AOMMAX(max_coded_error, 0.001);
1728
0
          ratio_thres = regions[k].avg_sr_fr_ratio * 0.95;
1729
0
        } else {
1730
0
          double max_coded_error =
1731
0
              AOMMAX(stats[regions[k - 1].last].coded_error,
1732
0
                     stats[regions[k - 1].last - 1].coded_error);
1733
0
          last_ratio = stats[regions[k - 1].last].sr_coded_error /
1734
0
                       AOMMAX(max_coded_error, 0.001);
1735
0
          double prev_ratio =
1736
0
              (regions[k - 1].avg_sr_fr_ratio * prev_length - last_ratio) /
1737
0
              (prev_length - 1.0);
1738
0
          ratio_thres = AOMMIN(prev_ratio, regions[k].avg_sr_fr_ratio) * 0.95;
1739
0
        }
1740
0
        if (last_ratio > ratio_thres) {
1741
0
          to_merge = 1;
1742
0
        }
1743
0
      }
1744
1745
0
      if (to_merge) {
1746
0
        remove_region(0, regions, num_regions, &k);
1747
0
        analyze_region(stats, k - 1, regions);
1748
0
        continue;
1749
0
      } else {
1750
        // These are possibly two separate blending regions. Mark the boundary
1751
        // frame as HIGH_VAR_REGION to separate the two.
1752
0
        int prev_k = k - 1;
1753
0
        insert_region(regions[prev_k].last, regions[prev_k].last,
1754
0
                      HIGH_VAR_REGION, regions, num_regions, &prev_k);
1755
0
        analyze_region(stats, prev_k, regions);
1756
0
        k = prev_k + 1;
1757
0
        analyze_region(stats, k, regions);
1758
0
      }
1759
0
    }
1760
0
    k++;
1761
0
  }
1762
0
  cleanup_regions(regions, num_regions);
1763
0
}
1764
1765
// Clean up decision for blendings. Remove blending regions that are too short.
1766
// Also if a very short high var region is between a blending and a stable
1767
// region, just merge it with one of them.
1768
0
static void cleanup_blendings(REGIONS *regions, int *num_regions) {
1769
0
  int k = 0;
1770
0
  while (k < (*num_regions) && (*num_regions) > 1) {
1771
0
    int is_short_blending = regions[k].type == BLENDING_REGION &&
1772
0
                            regions[k].last - regions[k].start + 1 < 5;
1773
0
    int is_short_hv = regions[k].type == HIGH_VAR_REGION &&
1774
0
                      regions[k].last - regions[k].start + 1 < 5;
1775
0
    int has_stable_neighbor =
1776
0
        ((k > 0 && regions[k - 1].type == STABLE_REGION) ||
1777
0
         (k < *num_regions - 1 && regions[k + 1].type == STABLE_REGION));
1778
0
    int has_blend_neighbor =
1779
0
        ((k > 0 && regions[k - 1].type == BLENDING_REGION) ||
1780
0
         (k < *num_regions - 1 && regions[k + 1].type == BLENDING_REGION));
1781
0
    int total_neighbors = (k > 0) + (k < *num_regions - 1);
1782
1783
0
    if (is_short_blending ||
1784
0
        (is_short_hv &&
1785
0
         has_stable_neighbor + has_blend_neighbor >= total_neighbors)) {
1786
      // Remove this region.Try to determine whether to combine it with the
1787
      // previous or next region.
1788
0
      int merge;
1789
0
      double prev_diff =
1790
0
          (k > 0)
1791
0
              ? fabs(regions[k].avg_cor_coeff - regions[k - 1].avg_cor_coeff)
1792
0
              : 1;
1793
0
      double next_diff =
1794
0
          (k < *num_regions - 1)
1795
0
              ? fabs(regions[k].avg_cor_coeff - regions[k + 1].avg_cor_coeff)
1796
0
              : 1;
1797
      // merge == 0 means to merge with previous, 1 means to merge with next
1798
0
      merge = prev_diff > next_diff;
1799
0
      remove_region(merge, regions, num_regions, &k);
1800
0
    } else {
1801
0
      k++;
1802
0
    }
1803
0
  }
1804
0
  cleanup_regions(regions, num_regions);
1805
0
}
1806
1807
static void free_firstpass_stats_buffers(REGIONS *temp_regions,
1808
                                         double *filt_intra_err,
1809
                                         double *filt_coded_err,
1810
0
                                         double *grad_coded) {
1811
0
  aom_free(temp_regions);
1812
0
  aom_free(filt_intra_err);
1813
0
  aom_free(filt_coded_err);
1814
0
  aom_free(grad_coded);
1815
0
}
1816
1817
// Identify stable and unstable regions from first pass stats.
1818
// stats_start points to the first frame to analyze.
1819
// |offset| is the offset from the current frame to the frame stats_start is
1820
// pointing to.
1821
// Returns 0 on success, -1 on memory allocation failure.
1822
static int identify_regions(const FIRSTPASS_STATS *const stats_start,
1823
                            int total_frames, int offset, REGIONS *regions,
1824
0
                            int *total_regions) {
1825
0
  int k;
1826
0
  if (total_frames <= 1) return 0;
1827
1828
  // store the initial decisions
1829
0
  REGIONS *temp_regions =
1830
0
      (REGIONS *)aom_malloc(total_frames * sizeof(temp_regions[0]));
1831
  // buffers for filtered stats
1832
0
  double *filt_intra_err =
1833
0
      (double *)aom_calloc(total_frames, sizeof(*filt_intra_err));
1834
0
  double *filt_coded_err =
1835
0
      (double *)aom_calloc(total_frames, sizeof(*filt_coded_err));
1836
0
  double *grad_coded = (double *)aom_calloc(total_frames, sizeof(*grad_coded));
1837
0
  if (!(temp_regions && filt_intra_err && filt_coded_err && grad_coded)) {
1838
0
    free_firstpass_stats_buffers(temp_regions, filt_intra_err, filt_coded_err,
1839
0
                                 grad_coded);
1840
0
    return -1;
1841
0
  }
1842
0
  av1_zero_array(temp_regions, total_frames);
1843
1844
0
  int cur_region = 0, this_start = 0, this_last;
1845
1846
0
  int next_scenecut = -1;
1847
0
  do {
1848
    // first get the obvious scenecuts
1849
0
    next_scenecut =
1850
0
        find_next_scenecut(stats_start, this_start, total_frames - 1);
1851
0
    this_last = (next_scenecut >= 0) ? (next_scenecut - 1) : total_frames - 1;
1852
1853
    // low-pass filter the needed stats
1854
0
    smooth_filter_stats(stats_start, this_start, this_last, filt_intra_err,
1855
0
                        filt_coded_err);
1856
0
    get_gradient(filt_coded_err, this_start, this_last, grad_coded);
1857
1858
    // find tentative stable regions and unstable regions
1859
0
    int num_regions = find_stable_regions(stats_start, grad_coded, this_start,
1860
0
                                          this_last, temp_regions);
1861
1862
0
    adjust_unstable_region_bounds(stats_start, temp_regions, &num_regions);
1863
1864
0
    get_region_stats(stats_start, temp_regions, num_regions);
1865
1866
    // Try to identify blending regions in the unstable regions
1867
0
    find_blending_regions(stats_start, temp_regions, &num_regions);
1868
0
    cleanup_blendings(temp_regions, &num_regions);
1869
1870
    // The flash points should all be considered high variance points
1871
0
    k = 0;
1872
0
    while (k < num_regions) {
1873
0
      if (temp_regions[k].type != STABLE_REGION) {
1874
0
        k++;
1875
0
        continue;
1876
0
      }
1877
0
      int start = temp_regions[k].start;
1878
0
      int last = temp_regions[k].last;
1879
0
      for (int i = start; i <= last; i++) {
1880
0
        if (stats_start[i].is_flash) {
1881
0
          insert_region(i, i, HIGH_VAR_REGION, temp_regions, &num_regions, &k);
1882
0
        }
1883
0
      }
1884
0
      k++;
1885
0
    }
1886
0
    cleanup_regions(temp_regions, &num_regions);
1887
1888
    // copy the regions in the scenecut group
1889
0
    for (k = 0; k < num_regions; k++) {
1890
0
      if (temp_regions[k].last < temp_regions[k].start &&
1891
0
          k == num_regions - 1) {
1892
0
        num_regions--;
1893
0
        break;
1894
0
      }
1895
0
      regions[k + cur_region] = temp_regions[k];
1896
0
    }
1897
0
    cur_region += num_regions;
1898
1899
    // add the scenecut region
1900
0
    if (next_scenecut > -1) {
1901
      // add the scenecut region, and find the next scenecut
1902
0
      regions[cur_region].type = SCENECUT_REGION;
1903
0
      regions[cur_region].start = next_scenecut;
1904
0
      regions[cur_region].last = next_scenecut;
1905
0
      cur_region++;
1906
0
      this_start = next_scenecut + 1;
1907
0
    }
1908
0
  } while (next_scenecut >= 0);
1909
1910
0
  *total_regions = cur_region;
1911
0
  get_region_stats(stats_start, regions, *total_regions);
1912
1913
0
  for (k = 0; k < *total_regions; k++) {
1914
    // If scenecuts are very minor, mark them as high variance.
1915
0
    if (regions[k].type != SCENECUT_REGION ||
1916
0
        regions[k].avg_cor_coeff *
1917
0
                (1 - stats_start[regions[k].start].noise_var /
1918
0
                         regions[k].avg_intra_err) <
1919
0
            0.8) {
1920
0
      continue;
1921
0
    }
1922
0
    regions[k].type = HIGH_VAR_REGION;
1923
0
  }
1924
0
  cleanup_regions(regions, total_regions);
1925
0
  get_region_stats(stats_start, regions, *total_regions);
1926
1927
0
  for (k = 0; k < *total_regions; k++) {
1928
0
    regions[k].start += offset;
1929
0
    regions[k].last += offset;
1930
0
  }
1931
1932
0
  free_firstpass_stats_buffers(temp_regions, filt_intra_err, filt_coded_err,
1933
0
                               grad_coded);
1934
0
  return 0;
1935
0
}
1936
1937
static int find_regions_index(const REGIONS *regions, int num_regions,
1938
0
                              int frame_idx) {
1939
0
  for (int k = 0; k < num_regions; k++) {
1940
0
    if (regions[k].start <= frame_idx && regions[k].last >= frame_idx) {
1941
0
      return k;
1942
0
    }
1943
0
  }
1944
0
  return -1;
1945
0
}
1946
1947
/*!\brief Determine the length of future GF groups.
1948
 *
1949
 * \ingroup gf_group_algo
1950
 * This function decides the gf group length of future frames in batch
1951
 *
1952
 * \param[in]    cpi              Top-level encoder structure
1953
 * \param[in]    max_gop_length   Maximum length of the GF group
1954
 * \param[in]    max_intervals    Maximum number of intervals to decide
1955
 *
1956
 * \remark Nothing is returned. Instead, cpi->ppi->rc.gf_intervals is
1957
 * changed to store the decided GF group lengths.
1958
 */
1959
static void calculate_gf_length(AV1_COMP *cpi, int max_gop_length,
1960
0
                                int max_intervals) {
1961
0
  RATE_CONTROL *const rc = &cpi->rc;
1962
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1963
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
1964
0
  FIRSTPASS_STATS next_frame;
1965
0
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
1966
0
  const FIRSTPASS_STATS *const stats = start_pos - (rc->frames_since_key == 0);
1967
1968
0
  const int f_w = cpi->common.width;
1969
0
  const int f_h = cpi->common.height;
1970
0
  int i;
1971
1972
0
  int flash_detected;
1973
1974
0
  av1_zero(next_frame);
1975
1976
0
  if (has_no_stats_stage(cpi)) {
1977
0
    for (i = 0; i < MAX_NUM_GF_INTERVALS; i++) {
1978
0
      p_rc->gf_intervals[i] = AOMMIN(rc->max_gf_interval, max_gop_length);
1979
0
    }
1980
0
    p_rc->cur_gf_index = 0;
1981
0
    rc->intervals_till_gf_calculate_due = MAX_NUM_GF_INTERVALS;
1982
0
    return;
1983
0
  }
1984
1985
  // TODO(urvang): Try logic to vary min and max interval based on q.
1986
0
  const int active_min_gf_interval = rc->min_gf_interval;
1987
0
  const int active_max_gf_interval =
1988
0
      AOMMIN(rc->max_gf_interval, max_gop_length);
1989
0
  const int min_shrink_int = AOMMAX(MIN_SHRINK_LEN, active_min_gf_interval);
1990
1991
0
  i = (rc->frames_since_key == 0);
1992
0
  max_intervals = cpi->ppi->lap_enabled ? 1 : max_intervals;
1993
0
  int count_cuts = 1;
1994
  // If cpi->gf_state.arf_gf_boost_lst is 0, we are starting with a KF or GF.
1995
0
  int cur_start = -1 + !cpi->ppi->gf_state.arf_gf_boost_lst, cur_last;
1996
0
  int cut_pos[MAX_NUM_GF_INTERVALS + 1] = { -1 };
1997
0
  int cut_here;
1998
0
  GF_GROUP_STATS gf_stats;
1999
0
  init_gf_stats(&gf_stats);
2000
0
  while (count_cuts < max_intervals + 1) {
2001
    // reaches next key frame, break here
2002
0
    if (i >= rc->frames_to_key) {
2003
0
      cut_here = 2;
2004
0
    } else if (i - cur_start >= rc->static_scene_max_gf_interval) {
2005
      // reached maximum len, but nothing special yet (almost static)
2006
      // let's look at the next interval
2007
0
      cut_here = 1;
2008
0
    } else if (EOF == input_stats(twopass, &cpi->twopass_frame, &next_frame)) {
2009
      // reaches last frame, break
2010
0
      cut_here = 2;
2011
0
    } else {
2012
      // Test for the case where there is a brief flash but the prediction
2013
      // quality back to an earlier frame is then restored.
2014
0
      flash_detected = detect_flash(twopass, &cpi->twopass_frame, 0);
2015
      // TODO(bohanli): remove redundant accumulations here, or unify
2016
      // this and the ones in define_gf_group
2017
0
      accumulate_next_frame_stats(&next_frame, flash_detected,
2018
0
                                  rc->frames_since_key, i, &gf_stats, f_w, f_h);
2019
2020
0
      cut_here = detect_gf_cut(cpi, i, cur_start, flash_detected,
2021
0
                               active_max_gf_interval, active_min_gf_interval,
2022
0
                               &gf_stats);
2023
0
    }
2024
0
    if (cut_here) {
2025
0
      cur_last = i - 1;  // the current last frame in the gf group
2026
0
      int ori_last = cur_last;
2027
      // The region frame idx does not start from the same frame as cur_start
2028
      // and cur_last. Need to offset them.
2029
0
      int offset = rc->frames_since_key - p_rc->regions_offset;
2030
0
      REGIONS *regions = p_rc->regions;
2031
0
      int num_regions = p_rc->num_regions;
2032
2033
0
      int scenecut_idx = -1;
2034
      // only try shrinking if interval smaller than active_max_gf_interval
2035
0
      if (cur_last - cur_start <= active_max_gf_interval &&
2036
0
          cur_last > cur_start) {
2037
        // find the region indices of where the first and last frame belong.
2038
0
        int k_start =
2039
0
            find_regions_index(regions, num_regions, cur_start + offset);
2040
0
        int k_last =
2041
0
            find_regions_index(regions, num_regions, cur_last + offset);
2042
0
        if (cur_start + offset == 0) k_start = 0;
2043
2044
        // See if we have a scenecut in between
2045
0
        for (int r = k_start + 1; r <= k_last; r++) {
2046
0
          if (regions[r].type == SCENECUT_REGION &&
2047
0
              regions[r].last - offset - cur_start > active_min_gf_interval) {
2048
0
            scenecut_idx = r;
2049
0
            break;
2050
0
          }
2051
0
        }
2052
2053
        // if the found scenecut is very close to the end, ignore it.
2054
0
        if (regions[num_regions - 1].last - regions[scenecut_idx].last < 4) {
2055
0
          scenecut_idx = -1;
2056
0
        }
2057
2058
0
        if (scenecut_idx != -1) {
2059
          // If we have a scenecut, then stop at it.
2060
          // TODO(bohanli): add logic here to stop before the scenecut and for
2061
          // the next gop start from the scenecut with GF
2062
0
          int is_minor_sc =
2063
0
              (regions[scenecut_idx].avg_cor_coeff *
2064
0
                   (1 - stats[regions[scenecut_idx].start - offset].noise_var /
2065
0
                            regions[scenecut_idx].avg_intra_err) >
2066
0
               0.6);
2067
0
          cur_last = regions[scenecut_idx].last - offset - !is_minor_sc;
2068
0
        } else {
2069
0
          int is_last_analysed = (k_last == num_regions - 1) &&
2070
0
                                 (cur_last + offset == regions[k_last].last);
2071
0
          int not_enough_regions =
2072
0
              k_last - k_start <=
2073
0
              1 + (regions[k_start].type == SCENECUT_REGION);
2074
          // if we are very close to the end, then do not shrink since it may
2075
          // introduce intervals that are too short
2076
0
          if (!(is_last_analysed && not_enough_regions)) {
2077
0
            const double arf_length_factor = 0.1;
2078
0
            double best_score = 0;
2079
0
            int best_j = -1;
2080
0
            const int first_frame = regions[0].start - offset;
2081
0
            const int last_frame = regions[num_regions - 1].last - offset;
2082
            // score of how much the arf helps the whole GOP
2083
0
            double base_score = 0.0;
2084
0
            int count_base = 0;
2085
0
            bool static_frames = false;
2086
2087
            // Accumulate base_score in
2088
0
            for (int j = cur_start + 1; j < cur_start + min_shrink_int; j++) {
2089
0
              if (stats + j >= twopass->stats_buf_ctx->stats_in_end) break;
2090
0
              base_score = (base_score + 1.0) * stats[j].cor_coeff;
2091
0
              count_base++;
2092
0
            }
2093
2094
0
            if (count_base && base_score / count_base > 0.992) {
2095
0
              static_frames = true;
2096
0
            }
2097
2098
0
            int met_blending = 0;   // Whether we have met blending areas before
2099
0
            int last_blending = 0;  // Whether the previous frame if blending
2100
0
            for (int j = cur_start + min_shrink_int; j <= cur_last; j++) {
2101
0
              if (stats + j >= twopass->stats_buf_ctx->stats_in_end) break;
2102
0
              base_score = (base_score + 1.0) * stats[j].cor_coeff;
2103
0
              int this_reg =
2104
0
                  find_regions_index(regions, num_regions, j + offset);
2105
0
              if (this_reg < 0) continue;
2106
              // A GOP should include at most 1 blending region.
2107
0
              if (regions[this_reg].type == BLENDING_REGION) {
2108
0
                last_blending = 1;
2109
0
                if (met_blending) {
2110
0
                  break;
2111
0
                } else {
2112
0
                  base_score = 0;
2113
0
                  continue;
2114
0
                }
2115
0
              } else {
2116
0
                if (last_blending) met_blending = 1;
2117
0
                last_blending = 0;
2118
0
              }
2119
2120
              // Add the factor of how good the neighborhood is for this
2121
              // candidate arf.
2122
0
              double this_score = arf_length_factor * base_score;
2123
0
              double temp_accu_coeff = 1.0;
2124
              // following frames
2125
0
              int count_f = 0;
2126
0
              for (int n = j + 1; n <= j + 3 && n <= last_frame; n++) {
2127
0
                if (stats + n >= twopass->stats_buf_ctx->stats_in_end) break;
2128
0
                temp_accu_coeff *= stats[n].cor_coeff;
2129
0
                this_score +=
2130
0
                    temp_accu_coeff *
2131
0
                    sqrt(AOMMAX(0.5,
2132
0
                                1 - stats[n].noise_var /
2133
0
                                        AOMMAX(stats[n].intra_error, 0.001)));
2134
0
                count_f++;
2135
0
              }
2136
              // preceding frames
2137
0
              temp_accu_coeff = 1.0;
2138
0
              for (int n = j; n > j - 3 * 2 + count_f && n > first_frame; n--) {
2139
0
                if (stats + n < twopass->stats_buf_ctx->stats_in_start) break;
2140
0
                temp_accu_coeff *= stats[n].cor_coeff;
2141
0
                this_score +=
2142
0
                    temp_accu_coeff *
2143
0
                    sqrt(AOMMAX(0.5,
2144
0
                                1 - stats[n].noise_var /
2145
0
                                        AOMMAX(stats[n].intra_error, 0.001)));
2146
0
              }
2147
2148
              // Slightly relax the condition for videos starting with frozen
2149
              // frames.
2150
0
              if (this_score + (static_frames ? 0.5 : 0) > best_score) {
2151
0
                best_score = this_score;
2152
0
                best_j = j;
2153
0
              }
2154
0
            }
2155
2156
            // For blending areas, move one more frame in case we missed the
2157
            // first blending frame.
2158
0
            int best_reg =
2159
0
                find_regions_index(regions, num_regions, best_j + offset);
2160
0
            if (best_reg < num_regions - 1 && best_reg > 0) {
2161
0
              if (regions[best_reg - 1].type == BLENDING_REGION &&
2162
0
                  regions[best_reg + 1].type == BLENDING_REGION) {
2163
0
                if (best_j + offset == regions[best_reg].start &&
2164
0
                    best_j + offset < regions[best_reg].last) {
2165
0
                  best_j += 1;
2166
0
                } else if (best_j + offset == regions[best_reg].last &&
2167
0
                           best_j + offset > regions[best_reg].start) {
2168
0
                  best_j -= 1;
2169
0
                }
2170
0
              }
2171
0
            }
2172
2173
0
            if (cur_last - best_j < 2) best_j = cur_last;
2174
0
            if (best_j > 0 && best_score > 0.1) cur_last = best_j;
2175
            // if cannot find anything, just cut at the original place.
2176
0
          }
2177
0
        }
2178
0
      }
2179
0
      cut_pos[count_cuts] = cur_last;
2180
0
      count_cuts++;
2181
2182
      // reset pointers to the shrunken location
2183
0
      cpi->twopass_frame.stats_in = start_pos + cur_last;
2184
0
      cur_start = cur_last;
2185
0
      int cur_region_idx =
2186
0
          find_regions_index(regions, num_regions, cur_start + 1 + offset);
2187
0
      if (cur_region_idx >= 0)
2188
0
        if (regions[cur_region_idx].type == SCENECUT_REGION) cur_start++;
2189
2190
0
      i = cur_last;
2191
2192
0
      if (cut_here > 1 && cur_last == ori_last) break;
2193
2194
      // reset accumulators
2195
0
      init_gf_stats(&gf_stats);
2196
0
    }
2197
0
    ++i;
2198
0
  }
2199
2200
  // save intervals
2201
0
  rc->intervals_till_gf_calculate_due = count_cuts - 1;
2202
0
  for (int n = 1; n < count_cuts; n++) {
2203
0
    p_rc->gf_intervals[n - 1] = cut_pos[n] - cut_pos[n - 1];
2204
0
  }
2205
0
  p_rc->cur_gf_index = 0;
2206
0
  cpi->twopass_frame.stats_in = start_pos;
2207
0
}
2208
2209
0
static void correct_frames_to_key(AV1_COMP *cpi) {
2210
0
  int lookahead_size =
2211
0
      av1_lookahead_depth(cpi->ppi->lookahead, cpi->compressor_stage);
2212
0
  if (lookahead_size <
2213
0
      av1_lookahead_pop_sz(cpi->ppi->lookahead, cpi->compressor_stage)) {
2214
0
    assert(
2215
0
        IMPLIES(cpi->oxcf.pass != AOM_RC_ONE_PASS && cpi->ppi->frames_left > 0,
2216
0
                lookahead_size == cpi->ppi->frames_left));
2217
0
    cpi->rc.frames_to_key = AOMMIN(cpi->rc.frames_to_key, lookahead_size);
2218
0
  } else if (cpi->ppi->frames_left > 0) {
2219
    // Correct frames to key based on limit
2220
0
    cpi->rc.frames_to_key =
2221
0
        AOMMIN(cpi->rc.frames_to_key, cpi->ppi->frames_left);
2222
0
  }
2223
0
}
2224
2225
/*!\brief Define a GF group in one pass mode when no look ahead stats are
2226
 * available.
2227
 *
2228
 * \ingroup gf_group_algo
2229
 * This function defines the structure of a GF group, along with various
2230
 * parameters regarding bit-allocation and quality setup in the special
2231
 * case of one pass encoding where no lookahead stats are avialable.
2232
 *
2233
 * \param[in]    cpi             Top-level encoder structure
2234
 * \param[in]    is_final_pass   Whether it is the second call to
2235
 *                               define_gf_group().
2236
 *
2237
 * \remark Nothing is returned. Instead, cpi->ppi->gf_group is changed.
2238
 */
2239
0
static void define_gf_group_pass0(AV1_COMP *cpi, const int is_final_pass) {
2240
0
  RATE_CONTROL *const rc = &cpi->rc;
2241
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2242
0
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
2243
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2244
0
  const GFConfig *const gf_cfg = &oxcf->gf_cfg;
2245
0
  int target;
2246
2247
0
  p_rc->baseline_gf_interval = p_rc->gf_intervals[p_rc->cur_gf_index];
2248
0
  rc->intervals_till_gf_calculate_due--;
2249
0
  p_rc->cur_gf_index++;
2250
2251
  // correct frames_to_key when lookahead queue is flushing
2252
0
  correct_frames_to_key(cpi);
2253
2254
0
  if (p_rc->baseline_gf_interval > rc->frames_to_key)
2255
0
    p_rc->baseline_gf_interval = rc->frames_to_key;
2256
2257
0
  p_rc->gfu_boost = DEFAULT_GF_BOOST;
2258
0
  p_rc->constrained_gf_group =
2259
0
      (p_rc->baseline_gf_interval >= rc->frames_to_key) ? 1 : 0;
2260
2261
  // Default for pyr_height if inputs not set.
2262
0
  if (oxcf->gf_cfg.gf_max_pyr_height == 0 ||
2263
0
      oxcf->gf_cfg.gf_min_pyr_height == 0) {
2264
0
    gf_group->max_layer_depth_allowed = 1;
2265
0
  } else {
2266
0
    gf_group->max_layer_depth_allowed = oxcf->gf_cfg.gf_max_pyr_height;
2267
0
  }
2268
2269
  // Rare case when the look-ahead is less than the target GOP length, can't
2270
  // generate ARF frame.
2271
  // Also disable ARF frame if the motion content (source_sad) is high in
2272
  // lookahead buffer.
2273
0
  const uint64_t thresh_sad = 8 * 64 * 64;
2274
0
  if (p_rc->baseline_gf_interval > gf_cfg->lag_in_frames ||
2275
0
      !is_altref_enabled(gf_cfg->lag_in_frames, gf_cfg->enable_auto_arf) ||
2276
0
      p_rc->baseline_gf_interval < rc->min_gf_interval ||
2277
0
      rc->frame_source_sad_lag[0] > thresh_sad) {
2278
0
    gf_group->max_layer_depth_allowed = 0;
2279
0
  }
2280
2281
  // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
2282
0
  av1_gop_setup_structure(cpi, is_final_pass);
2283
2284
  // Allocate bits to each of the frames in the GF group.
2285
  // TODO(sarahparker) Extend this to work with pyramid structure.
2286
0
  for (int cur_index = 0; cur_index < gf_group->size; ++cur_index) {
2287
0
    const FRAME_UPDATE_TYPE cur_update_type = gf_group->update_type[cur_index];
2288
0
    if (oxcf->rc_cfg.mode == AOM_CBR) {
2289
0
      if (cur_update_type == KF_UPDATE) {
2290
0
        target = av1_calc_iframe_target_size_one_pass_cbr(cpi);
2291
0
      } else {
2292
0
        target = av1_calc_pframe_target_size_one_pass_cbr(cpi, cur_update_type);
2293
0
      }
2294
0
    } else {
2295
0
      if (cur_update_type == KF_UPDATE) {
2296
0
        target = av1_calc_iframe_target_size_one_pass_vbr(cpi);
2297
0
      } else {
2298
0
        target = av1_calc_pframe_target_size_one_pass_vbr(cpi, cur_update_type);
2299
0
      }
2300
0
    }
2301
0
    gf_group->bit_allocation[cur_index] = target;
2302
0
  }
2303
0
}
2304
2305
static inline void set_baseline_gf_interval(PRIMARY_RATE_CONTROL *p_rc,
2306
0
                                            int arf_position) {
2307
0
  p_rc->baseline_gf_interval = arf_position;
2308
0
}
2309
2310
// initialize GF_GROUP_STATS
2311
0
static void init_gf_stats(GF_GROUP_STATS *gf_stats) {
2312
0
  gf_stats->gf_group_err = 0.0;
2313
0
  gf_stats->gf_group_raw_error = 0.0;
2314
0
  gf_stats->gf_group_skip_pct = 0.0;
2315
0
  gf_stats->gf_group_inactive_zone_rows = 0.0;
2316
2317
0
  gf_stats->mv_ratio_accumulator = 0.0;
2318
0
  gf_stats->decay_accumulator = 1.0;
2319
0
  gf_stats->zero_motion_accumulator = 1.0;
2320
0
  gf_stats->loop_decay_rate = 1.0;
2321
0
  gf_stats->last_loop_decay_rate = 1.0;
2322
0
  gf_stats->this_frame_mv_in_out = 0.0;
2323
0
  gf_stats->mv_in_out_accumulator = 0.0;
2324
0
  gf_stats->abs_mv_in_out_accumulator = 0.0;
2325
2326
0
  gf_stats->avg_sr_coded_error = 0.0;
2327
0
  gf_stats->avg_pcnt_second_ref = 0.0;
2328
0
  gf_stats->avg_new_mv_count = 0.0;
2329
0
  gf_stats->avg_wavelet_energy = 0.0;
2330
0
  gf_stats->avg_raw_err_stdev = 0.0;
2331
0
  gf_stats->non_zero_stdev_count = 0;
2332
0
}
2333
2334
static void accumulate_gop_stats(AV1_COMP *cpi, int is_intra_only, int f_w,
2335
                                 int f_h, FIRSTPASS_STATS *next_frame,
2336
                                 const FIRSTPASS_STATS *start_pos,
2337
0
                                 GF_GROUP_STATS *gf_stats, int *idx) {
2338
0
  int i, flash_detected;
2339
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
2340
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2341
0
  RATE_CONTROL *const rc = &cpi->rc;
2342
0
  FRAME_INFO *frame_info = &cpi->frame_info;
2343
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2344
2345
0
  init_gf_stats(gf_stats);
2346
0
  av1_zero(*next_frame);
2347
2348
  // If this is a key frame or the overlay from a previous arf then
2349
  // the error score / cost of this frame has already been accounted for.
2350
0
  i = is_intra_only;
2351
  // get the determined gf group length from p_rc->gf_intervals
2352
0
  while (i < p_rc->gf_intervals[p_rc->cur_gf_index]) {
2353
    // read in the next frame
2354
0
    if (EOF == input_stats(twopass, &cpi->twopass_frame, next_frame)) break;
2355
    // Accumulate error score of frames in this gf group.
2356
0
    double mod_frame_err =
2357
0
        calculate_modified_err(frame_info, twopass, oxcf, next_frame);
2358
    // accumulate stats for this frame
2359
0
    accumulate_this_frame_stats(next_frame, mod_frame_err, gf_stats);
2360
0
    ++i;
2361
0
  }
2362
2363
0
  reset_fpf_position(&cpi->twopass_frame, start_pos);
2364
2365
0
  i = is_intra_only;
2366
0
  input_stats(twopass, &cpi->twopass_frame, next_frame);
2367
0
  while (i < p_rc->gf_intervals[p_rc->cur_gf_index]) {
2368
    // read in the next frame
2369
0
    if (EOF == input_stats(twopass, &cpi->twopass_frame, next_frame)) break;
2370
2371
    // Test for the case where there is a brief flash but the prediction
2372
    // quality back to an earlier frame is then restored.
2373
0
    flash_detected = detect_flash(twopass, &cpi->twopass_frame, 0);
2374
2375
    // accumulate stats for next frame
2376
0
    accumulate_next_frame_stats(next_frame, flash_detected,
2377
0
                                rc->frames_since_key, i, gf_stats, f_w, f_h);
2378
2379
0
    ++i;
2380
0
  }
2381
2382
0
  i = p_rc->gf_intervals[p_rc->cur_gf_index];
2383
0
  average_gf_stats(i, gf_stats);
2384
2385
0
  *idx = i;
2386
0
}
2387
2388
static void update_gop_length(RATE_CONTROL *rc, PRIMARY_RATE_CONTROL *p_rc,
2389
0
                              int idx, int is_final_pass) {
2390
0
  if (is_final_pass) {
2391
0
    rc->intervals_till_gf_calculate_due--;
2392
0
    p_rc->cur_gf_index++;
2393
0
  }
2394
2395
  // Was the group length constrained by the requirement for a new KF?
2396
0
  p_rc->constrained_gf_group = (idx >= rc->frames_to_key) ? 1 : 0;
2397
2398
0
  set_baseline_gf_interval(p_rc, idx);
2399
0
  rc->frames_till_gf_update_due = p_rc->baseline_gf_interval;
2400
0
}
2401
2402
// #define FIXED_ARF_BITS
2403
#ifdef FIXED_ARF_BITS
2404
#define ARF_BITS_FRACTION 0.75
2405
#endif
2406
/*!\brief Distributes bits to frames in a group
2407
 *
2408
 *\ingroup rate_control
2409
 *
2410
 * This function decides on the allocation of bits between the different
2411
 * frames and types of frame in a GF/ARF group.
2412
 *
2413
 * \param[in]   cpi           Top - level encoder instance structure
2414
 * \param[in]   rc            Rate control data
2415
 * \param[in]   gf_group      GF/ARF group data structure
2416
 * \param[in]   is_key_frame  Indicates if the first frame in the group is
2417
 *                            also a key frame.
2418
 * \param[in]   use_arf       Are ARF frames enabled or is this a GF only
2419
 *                            uni-directional group.
2420
 * \param[in]   gf_group_bits Bits available to be allocated.
2421
 *
2422
 * \remark No return but updates the rate control and group data structures
2423
 *         to reflect the allocation of bits.
2424
 */
2425
void av1_gop_bit_allocation(const AV1_COMP *cpi, RATE_CONTROL *const rc,
2426
                            GF_GROUP *gf_group, int is_key_frame, int use_arf,
2427
0
                            int64_t gf_group_bits) {
2428
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2429
  // Calculate the extra bits to be used for boosted frame(s)
2430
#ifdef FIXED_ARF_BITS
2431
  int gf_arf_bits = (int)(ARF_BITS_FRACTION * gf_group_bits);
2432
#else
2433
0
  int gf_arf_bits = calculate_boost_bits(
2434
0
      p_rc->baseline_gf_interval - (rc->frames_since_key == 0), p_rc->gfu_boost,
2435
0
      gf_group_bits);
2436
0
#endif
2437
2438
0
  gf_arf_bits = adjust_boost_bits_for_target_level(cpi, rc, gf_arf_bits,
2439
0
                                                   gf_group_bits, 1);
2440
2441
  // Allocate bits to each of the frames in the GF group.
2442
0
  allocate_gf_group_bits(gf_group, p_rc, rc, gf_group_bits, gf_arf_bits,
2443
0
                         is_key_frame, use_arf);
2444
0
}
2445
#undef ARF_BITS_FRACTION
2446
2447
#define MAX_GF_BOOST 5400
2448
0
#define REDUCE_GF_LENGTH_THRESH 4
2449
0
#define REDUCE_GF_LENGTH_TO_KEY_THRESH 9
2450
0
#define REDUCE_GF_LENGTH_BY 1
2451
static void set_gop_bits_boost(AV1_COMP *cpi, int i, int is_intra_only,
2452
                               int is_final_pass, int use_alt_ref,
2453
                               int alt_offset, const FIRSTPASS_STATS *start_pos,
2454
0
                               GF_GROUP_STATS *gf_stats) {
2455
  // Should we use the alternate reference frame.
2456
0
  AV1_COMMON *const cm = &cpi->common;
2457
0
  RATE_CONTROL *const rc = &cpi->rc;
2458
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2459
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
2460
0
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
2461
0
  FRAME_INFO *frame_info = &cpi->frame_info;
2462
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2463
0
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
2464
2465
0
  if (cpi->oxcf.mode != REALTIME) {
2466
0
    TWO_PASS_FRAME stats_in_backup = cpi->twopass_frame;
2467
0
    int gfu_boost_sum = 0;
2468
0
    int gfu_count = 0;
2469
0
    int accumulate_i = 0;
2470
0
    if (rc->frames_since_key == 0) {
2471
0
      for (int k = 0; k < MAX_NUM_GF_INTERVALS; k++) {
2472
0
        if (p_rc->gf_intervals[k] == 0) {
2473
0
          break;
2474
0
        }
2475
2476
0
        int new_i = p_rc->gf_intervals[k];
2477
0
        int ext_len_new = new_i - (k == 0 ? is_intra_only : 0);
2478
0
        if (use_alt_ref) {
2479
0
          if (accumulate_i >= rc->frames_to_key) {
2480
0
            break;
2481
0
          }
2482
0
          const int forward_frames =
2483
0
              (rc->frames_to_key - accumulate_i - new_i >= ext_len_new)
2484
0
                  ? ext_len_new
2485
0
                  : AOMMAX(0, rc->frames_to_key - accumulate_i - new_i);
2486
0
          if (k) {
2487
0
            cpi->twopass_frame.stats_in += new_i;
2488
0
            if (cpi->twopass_frame.stats_in >=
2489
0
                twopass->stats_buf_ctx->stats_in_end) {
2490
0
              cpi->twopass_frame.stats_in =
2491
0
                  twopass->stats_buf_ctx->stats_in_end;
2492
0
            }
2493
0
          }
2494
0
          reset_fpf_position(&cpi->twopass_frame, cpi->twopass_frame.stats_in);
2495
          // Calculate the boost for alt ref. Note that we pass the
2496
          // scale_max_boost=false to derive gfu_boost_average, which can help
2497
          // the coding efficiency for some clips with global motion.
2498
0
          int gfu_boost_tmp = av1_calc_arf_boost(
2499
0
              twopass, &cpi->twopass_frame, p_rc, frame_info, alt_offset,
2500
0
              forward_frames, ext_len_new, &p_rc->num_stats_used_for_gfu_boost,
2501
0
              &p_rc->num_stats_required_for_gfu_boost, cpi->ppi->lap_enabled,
2502
0
              /*scale_max_boost=*/false);
2503
0
          gfu_boost_sum += gfu_boost_tmp;
2504
0
        }
2505
0
        gfu_count++;
2506
0
        accumulate_i += new_i;
2507
0
      }
2508
0
      assert(gfu_count > 0);
2509
0
      p_rc->gfu_boost_average = gfu_boost_sum / gfu_count;
2510
0
    }
2511
0
    cpi->twopass_frame = stats_in_backup;
2512
0
  }
2513
2514
0
  int ext_len = i - is_intra_only;
2515
0
  const bool scale_max_boost = (cpi->oxcf.mode != REALTIME);
2516
2517
0
  if (use_alt_ref) {
2518
0
    const int forward_frames = (rc->frames_to_key - i >= ext_len)
2519
0
                                   ? ext_len
2520
0
                                   : AOMMAX(0, rc->frames_to_key - i);
2521
2522
    // Calculate the boost for alt ref.
2523
0
    p_rc->gfu_boost = av1_calc_arf_boost(
2524
0
        twopass, &cpi->twopass_frame, p_rc, frame_info, alt_offset,
2525
0
        forward_frames, ext_len, &p_rc->num_stats_used_for_gfu_boost,
2526
0
        &p_rc->num_stats_required_for_gfu_boost, cpi->ppi->lap_enabled,
2527
0
        scale_max_boost);
2528
0
  } else {
2529
0
    reset_fpf_position(&cpi->twopass_frame, start_pos);
2530
0
    p_rc->gfu_boost =
2531
0
        AOMMIN(MAX_GF_BOOST,
2532
0
               av1_calc_arf_boost(twopass, &cpi->twopass_frame, p_rc,
2533
0
                                  frame_info, alt_offset, ext_len, 0,
2534
0
                                  &p_rc->num_stats_used_for_gfu_boost,
2535
0
                                  &p_rc->num_stats_required_for_gfu_boost,
2536
0
                                  cpi->ppi->lap_enabled, scale_max_boost));
2537
0
  }
2538
2539
0
#define LAST_ALR_BOOST_FACTOR 0.2f
2540
0
  p_rc->arf_boost_factor = 1.0;
2541
0
  if (use_alt_ref && !is_lossless_requested(rc_cfg)) {
2542
    // Reduce the boost of altref in the last gf group
2543
0
    if (rc->frames_to_key - ext_len == REDUCE_GF_LENGTH_BY ||
2544
0
        rc->frames_to_key - ext_len == 0) {
2545
0
      p_rc->arf_boost_factor = LAST_ALR_BOOST_FACTOR;
2546
0
    }
2547
0
  }
2548
2549
  // Reset the file position.
2550
0
  reset_fpf_position(&cpi->twopass_frame, start_pos);
2551
0
  if (cpi->ppi->lap_enabled) {
2552
    // Since we don't have enough stats to know the actual error of the
2553
    // gf group, we assume error of each frame to be equal to 1 and set
2554
    // the error of the group as baseline_gf_interval.
2555
0
    gf_stats->gf_group_err = p_rc->baseline_gf_interval;
2556
0
  }
2557
  // Calculate the bits to be allocated to the gf/arf group as a whole
2558
0
  p_rc->gf_group_bits =
2559
0
      calculate_total_gf_group_bits(cpi, gf_stats->gf_group_err);
2560
2561
0
#if GROUP_ADAPTIVE_MAXQ
2562
  // Calculate an estimate of the maxq needed for the group.
2563
  // We are more aggressive about correcting for sections
2564
  // where there could be significant overshoot than for easier
2565
  // sections where we do not wish to risk creating an overshoot
2566
  // of the allocated bit budget.
2567
0
  if ((rc_cfg->mode != AOM_Q) && (p_rc->baseline_gf_interval > 1) &&
2568
0
      is_final_pass) {
2569
0
    const int vbr_group_bits_per_frame =
2570
0
        (int)(p_rc->gf_group_bits / p_rc->baseline_gf_interval);
2571
0
    const double group_av_err =
2572
0
        gf_stats->gf_group_raw_error / p_rc->baseline_gf_interval;
2573
0
    const double group_av_skip_pct =
2574
0
        gf_stats->gf_group_skip_pct / p_rc->baseline_gf_interval;
2575
0
    const double group_av_inactive_zone =
2576
0
        ((gf_stats->gf_group_inactive_zone_rows * 2) /
2577
0
         (p_rc->baseline_gf_interval * (double)cm->mi_params.mb_rows));
2578
2579
0
    int tmp_q;
2580
0
    tmp_q = get_twopass_worst_quality(
2581
0
        cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2582
0
        vbr_group_bits_per_frame);
2583
0
    rc->active_worst_quality = AOMMAX(tmp_q, rc->active_worst_quality >> 1);
2584
0
  }
2585
0
#endif
2586
2587
  // Adjust KF group bits and error remaining.
2588
0
  if (is_final_pass) twopass->kf_group_error_left -= gf_stats->gf_group_err;
2589
2590
  // Reset the file position.
2591
0
  reset_fpf_position(&cpi->twopass_frame, start_pos);
2592
2593
  // Calculate a section intra ratio used in setting max loop filter.
2594
0
  if (rc->frames_since_key != 0) {
2595
0
    twopass->section_intra_rating = calculate_section_intra_ratio(
2596
0
        start_pos, twopass->stats_buf_ctx->stats_in_end,
2597
0
        p_rc->baseline_gf_interval);
2598
0
  }
2599
2600
0
  av1_gop_bit_allocation(cpi, rc, gf_group, rc->frames_since_key == 0,
2601
0
                         use_alt_ref, p_rc->gf_group_bits);
2602
2603
  // TODO(jingning): Generalize this condition.
2604
0
  if (is_final_pass) {
2605
0
    cpi->ppi->gf_state.arf_gf_boost_lst = use_alt_ref;
2606
2607
    // Reset rolling actual and target bits counters for ARF groups.
2608
0
    twopass->rolling_arf_group_target_bits = 1;
2609
0
    twopass->rolling_arf_group_actual_bits = 1;
2610
0
  }
2611
#if CONFIG_BITRATE_ACCURACY
2612
  if (is_final_pass) {
2613
    av1_vbr_rc_set_gop_bit_budget(&cpi->vbr_rc_info,
2614
                                  p_rc->baseline_gf_interval);
2615
  }
2616
#endif
2617
0
}
2618
2619
/*!\brief Define a GF group.
2620
 *
2621
 * \ingroup gf_group_algo
2622
 * This function defines the structure of a GF group, along with various
2623
 * parameters regarding bit-allocation and quality setup.
2624
 *
2625
 * \param[in]    cpi             Top-level encoder structure
2626
 * \param[in]    frame_params    Structure with frame parameters
2627
 * \param[in]    is_final_pass   Whether this is the final pass for the
2628
 *                               GF group, or a trial (non-zero)
2629
 *
2630
 * \remark Nothing is returned. Instead, cpi->ppi->gf_group is changed.
2631
 */
2632
static void define_gf_group(AV1_COMP *cpi, EncodeFrameParams *frame_params,
2633
0
                            int is_final_pass) {
2634
0
  AV1_COMMON *const cm = &cpi->common;
2635
0
  RATE_CONTROL *const rc = &cpi->rc;
2636
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2637
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2638
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
2639
0
  FIRSTPASS_STATS next_frame;
2640
0
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
2641
0
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
2642
0
  const GFConfig *const gf_cfg = &oxcf->gf_cfg;
2643
0
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
2644
0
  const int f_w = cm->width;
2645
0
  const int f_h = cm->height;
2646
0
  int i;
2647
0
  const int is_intra_only = rc->frames_since_key == 0;
2648
2649
0
  cpi->ppi->internal_altref_allowed = (gf_cfg->gf_max_pyr_height > 1);
2650
2651
  // Reset the GF group data structures unless this is a key
2652
  // frame in which case it will already have been done.
2653
0
  if (!is_intra_only) {
2654
0
    av1_zero(cpi->ppi->gf_group);
2655
0
    cpi->gf_frame_index = 0;
2656
0
  }
2657
2658
0
  if (has_no_stats_stage(cpi)) {
2659
0
    define_gf_group_pass0(cpi, is_final_pass);
2660
0
    return;
2661
0
  }
2662
2663
#if CONFIG_THREE_PASS
2664
  if (cpi->third_pass_ctx && oxcf->pass == AOM_RC_THIRD_PASS) {
2665
    int ret = define_gf_group_pass3(cpi, frame_params, is_final_pass);
2666
    if (ret == 0) return;
2667
2668
    av1_free_thirdpass_ctx(cpi->third_pass_ctx);
2669
    cpi->third_pass_ctx = NULL;
2670
  }
2671
#endif  // CONFIG_THREE_PASS
2672
2673
  // correct frames_to_key when lookahead queue is emptying
2674
0
  if (cpi->ppi->lap_enabled) {
2675
0
    correct_frames_to_key(cpi);
2676
0
  }
2677
2678
0
  GF_GROUP_STATS gf_stats;
2679
0
  accumulate_gop_stats(cpi, is_intra_only, f_w, f_h, &next_frame, start_pos,
2680
0
                       &gf_stats, &i);
2681
2682
0
  const int can_disable_arf = !gf_cfg->gf_min_pyr_height;
2683
2684
  // If this is a key frame or the overlay from a previous arf then
2685
  // the error score / cost of this frame has already been accounted for.
2686
0
  const int active_min_gf_interval = rc->min_gf_interval;
2687
2688
  // Disable internal ARFs for "still" gf groups.
2689
  //   zero_motion_accumulator: minimum percentage of (0,0) motion;
2690
  //   avg_sr_coded_error:      average of the SSE per pixel of each frame;
2691
  //   avg_raw_err_stdev:       average of the standard deviation of (0,0)
2692
  //                            motion error per block of each frame.
2693
0
  const int can_disable_internal_arfs = gf_cfg->gf_min_pyr_height <= 1;
2694
0
  if (can_disable_internal_arfs &&
2695
0
      gf_stats.zero_motion_accumulator > MIN_ZERO_MOTION &&
2696
0
      gf_stats.avg_sr_coded_error < MAX_SR_CODED_ERROR &&
2697
0
      gf_stats.avg_raw_err_stdev < MAX_RAW_ERR_VAR) {
2698
0
    cpi->ppi->internal_altref_allowed = 0;
2699
0
  }
2700
2701
0
  int use_alt_ref;
2702
0
  if (can_disable_arf) {
2703
0
    use_alt_ref =
2704
0
        p_rc->use_arf_in_this_kf_group && (i < gf_cfg->lag_in_frames) &&
2705
0
        (i >= MIN_GF_INTERVAL) &&
2706
0
        ((cpi->oxcf.mode != REALTIME) ||
2707
0
         !is_almost_static(gf_stats.zero_motion_accumulator,
2708
0
                           twopass->kf_zeromotion_pct, cpi->ppi->lap_enabled));
2709
0
  } else {
2710
0
    use_alt_ref = p_rc->use_arf_in_this_kf_group &&
2711
0
                  (i < gf_cfg->lag_in_frames) && (i > 2);
2712
0
  }
2713
0
  if (use_alt_ref) {
2714
0
    gf_group->max_layer_depth_allowed = gf_cfg->gf_max_pyr_height;
2715
0
  } else {
2716
0
    gf_group->max_layer_depth_allowed = 0;
2717
0
  }
2718
2719
0
  int alt_offset = 0;
2720
  // The length reduction strategy is tweaked for certain cases, and doesn't
2721
  // work well for certain other cases.
2722
0
  const int allow_gf_length_reduction =
2723
0
      ((rc_cfg->mode == AOM_Q && rc_cfg->cq_level <= 128) ||
2724
0
       !cpi->ppi->internal_altref_allowed) &&
2725
0
      !is_lossless_requested(rc_cfg);
2726
2727
0
  if (allow_gf_length_reduction && use_alt_ref) {
2728
    // adjust length of this gf group if one of the following condition met
2729
    // 1: only one overlay frame left and this gf is too long
2730
    // 2: next gf group is too short to have arf compared to the current gf
2731
2732
    // maximum length of next gf group
2733
0
    const int next_gf_len = rc->frames_to_key - i;
2734
0
    const int single_overlay_left =
2735
0
        next_gf_len == 0 && i > REDUCE_GF_LENGTH_THRESH;
2736
    // the next gf is probably going to have a ARF but it will be shorter than
2737
    // this gf
2738
0
    const int unbalanced_gf =
2739
0
        i > REDUCE_GF_LENGTH_TO_KEY_THRESH &&
2740
0
        next_gf_len + 1 < REDUCE_GF_LENGTH_TO_KEY_THRESH &&
2741
0
        next_gf_len + 1 >= rc->min_gf_interval;
2742
2743
0
    if (single_overlay_left || unbalanced_gf) {
2744
0
      const int roll_back = REDUCE_GF_LENGTH_BY;
2745
      // Reduce length only if active_min_gf_interval will be respected later.
2746
0
      if (i - roll_back >= active_min_gf_interval + 1) {
2747
0
        alt_offset = -roll_back;
2748
0
        i -= roll_back;
2749
0
        if (is_final_pass) rc->intervals_till_gf_calculate_due = 0;
2750
0
        p_rc->gf_intervals[p_rc->cur_gf_index] -= roll_back;
2751
0
        reset_fpf_position(&cpi->twopass_frame, start_pos);
2752
0
        accumulate_gop_stats(cpi, is_intra_only, f_w, f_h, &next_frame,
2753
0
                             start_pos, &gf_stats, &i);
2754
0
      }
2755
0
    }
2756
0
  }
2757
2758
0
  update_gop_length(rc, p_rc, i, is_final_pass);
2759
2760
  // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
2761
0
  av1_gop_setup_structure(cpi, is_final_pass);
2762
2763
0
  set_gop_bits_boost(cpi, i, is_intra_only, is_final_pass, use_alt_ref,
2764
0
                     alt_offset, start_pos, &gf_stats);
2765
2766
0
  frame_params->frame_type =
2767
0
      rc->frames_since_key == 0 ? KEY_FRAME : INTER_FRAME;
2768
0
  frame_params->show_frame =
2769
0
      !(gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE ||
2770
0
        gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE);
2771
0
}
2772
2773
#if CONFIG_THREE_PASS
2774
/*!\brief Define a GF group for the third apss.
2775
 *
2776
 * \ingroup gf_group_algo
2777
 * This function defines the structure of a GF group for the third pass, along
2778
 * with various parameters regarding bit-allocation and quality setup based on
2779
 * the two-pass bitstream.
2780
 * Much of the function still uses the strategies used for the second pass and
2781
 * relies on first pass statistics. It is expected that over time these portions
2782
 * would be replaced with strategies specific to the third pass.
2783
 *
2784
 * \param[in]    cpi             Top-level encoder structure
2785
 * \param[in]    frame_params    Structure with frame parameters
2786
 * \param[in]    is_final_pass   Whether this is the final pass for the
2787
 *                               GF group, or a trial (non-zero)
2788
 *
2789
 * \return       0: Success;
2790
 *              -1: There are conflicts between the bitstream and current config
2791
 *               The values in cpi->ppi->gf_group are also changed.
2792
 */
2793
static int define_gf_group_pass3(AV1_COMP *cpi, EncodeFrameParams *frame_params,
2794
                                 int is_final_pass) {
2795
  if (!cpi->third_pass_ctx) return -1;
2796
  AV1_COMMON *const cm = &cpi->common;
2797
  RATE_CONTROL *const rc = &cpi->rc;
2798
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2799
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2800
  FIRSTPASS_STATS next_frame;
2801
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
2802
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
2803
  const GFConfig *const gf_cfg = &oxcf->gf_cfg;
2804
  const int f_w = cm->width;
2805
  const int f_h = cm->height;
2806
  int i;
2807
  const int is_intra_only = rc->frames_since_key == 0;
2808
2809
  cpi->ppi->internal_altref_allowed = (gf_cfg->gf_max_pyr_height > 1);
2810
2811
  // Reset the GF group data structures unless this is a key
2812
  // frame in which case it will already have been done.
2813
  if (!is_intra_only) {
2814
    av1_zero(cpi->ppi->gf_group);
2815
    cpi->gf_frame_index = 0;
2816
  }
2817
2818
  GF_GROUP_STATS gf_stats;
2819
  accumulate_gop_stats(cpi, is_intra_only, f_w, f_h, &next_frame, start_pos,
2820
                       &gf_stats, &i);
2821
2822
  const int can_disable_arf = !gf_cfg->gf_min_pyr_height;
2823
2824
  // TODO(any): set cpi->ppi->internal_altref_allowed accordingly;
2825
2826
  int use_alt_ref = av1_check_use_arf(cpi->third_pass_ctx);
2827
  if (use_alt_ref == 0 && !can_disable_arf) return -1;
2828
  if (use_alt_ref) {
2829
    gf_group->max_layer_depth_allowed = gf_cfg->gf_max_pyr_height;
2830
  } else {
2831
    gf_group->max_layer_depth_allowed = 0;
2832
  }
2833
2834
  update_gop_length(rc, p_rc, i, is_final_pass);
2835
2836
  // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
2837
  av1_gop_setup_structure(cpi, is_final_pass);
2838
2839
  set_gop_bits_boost(cpi, i, is_intra_only, is_final_pass, use_alt_ref, 0,
2840
                     start_pos, &gf_stats);
2841
2842
  frame_params->frame_type = cpi->third_pass_ctx->frame_info[0].frame_type;
2843
  frame_params->show_frame = cpi->third_pass_ctx->frame_info[0].is_show_frame;
2844
  return 0;
2845
}
2846
#endif  // CONFIG_THREE_PASS
2847
2848
// Minimum % intra coding observed in first pass (1.0 = 100%)
2849
0
#define MIN_INTRA_LEVEL 0.25
2850
// Minimum ratio between the % of intra coding and inter coding in the first
2851
// pass after discounting neutral blocks (discounting neutral blocks in this
2852
// way helps catch scene cuts in clips with very flat areas or letter box
2853
// format clips with image padding.
2854
0
#define INTRA_VS_INTER_THRESH 2.0
2855
// Hard threshold where the first pass chooses intra for almost all blocks.
2856
// In such a case even if the frame is not a scene cut coding a key frame
2857
// may be a good option.
2858
0
#define VERY_LOW_INTER_THRESH 0.05
2859
// Maximum threshold for the relative ratio of intra error score vs best
2860
// inter error score.
2861
0
#define KF_II_ERR_THRESHOLD 1.9
2862
// In real scene cuts there is almost always a sharp change in the intra
2863
// or inter error score.
2864
0
#define ERR_CHANGE_THRESHOLD 0.4
2865
// For real scene cuts we expect an improvment in the intra inter error
2866
// ratio in the next frame.
2867
0
#define II_IMPROVEMENT_THRESHOLD 3.5
2868
0
#define KF_II_MAX 128.0
2869
// Intra / Inter threshold very low
2870
0
#define VERY_LOW_II 1.5
2871
// Clean slide transitions we expect a sharp single frame spike in error.
2872
0
#define ERROR_SPIKE 5.0
2873
2874
// Slide show transition detection.
2875
// Tests for case where there is very low error either side of the current frame
2876
// but much higher just for this frame. This can help detect key frames in
2877
// slide shows even where the slides are pictures of different sizes.
2878
// Also requires that intra and inter errors are very similar to help eliminate
2879
// harmful false positives.
2880
// It will not help if the transition is a fade or other multi-frame effect.
2881
static int slide_transition(const FIRSTPASS_STATS *this_frame,
2882
                            const FIRSTPASS_STATS *last_frame,
2883
0
                            const FIRSTPASS_STATS *next_frame) {
2884
0
  return (this_frame->intra_error < (this_frame->coded_error * VERY_LOW_II)) &&
2885
0
         (this_frame->coded_error > (last_frame->coded_error * ERROR_SPIKE)) &&
2886
0
         (this_frame->coded_error > (next_frame->coded_error * ERROR_SPIKE));
2887
0
}
2888
2889
// Threshold for use of the lagging second reference frame. High second ref
2890
// usage may point to a transient event like a flash or occlusion rather than
2891
// a real scene cut.
2892
// We adapt the threshold based on number of frames in this key-frame group so
2893
// far.
2894
0
static double get_second_ref_usage_thresh(int frame_count_so_far) {
2895
0
  const int adapt_upto = 32;
2896
0
  const double min_second_ref_usage_thresh = 0.085;
2897
0
  const double second_ref_usage_thresh_max_delta = 0.035;
2898
0
  if (frame_count_so_far >= adapt_upto) {
2899
0
    return min_second_ref_usage_thresh + second_ref_usage_thresh_max_delta;
2900
0
  }
2901
0
  return min_second_ref_usage_thresh +
2902
0
         ((double)frame_count_so_far / (adapt_upto - 1)) *
2903
0
             second_ref_usage_thresh_max_delta;
2904
0
}
2905
2906
static int test_candidate_kf(const FIRSTPASS_INFO *firstpass_info,
2907
                             int this_stats_index, int frame_count_so_far,
2908
                             enum aom_rc_mode rc_mode, int scenecut_mode,
2909
0
                             int num_mbs) {
2910
0
  const FIRSTPASS_STATS *last_stats =
2911
0
      av1_firstpass_info_peek(firstpass_info, this_stats_index - 1);
2912
0
  const FIRSTPASS_STATS *this_stats =
2913
0
      av1_firstpass_info_peek(firstpass_info, this_stats_index);
2914
0
  const FIRSTPASS_STATS *next_stats =
2915
0
      av1_firstpass_info_peek(firstpass_info, this_stats_index + 1);
2916
0
  if (last_stats == NULL || this_stats == NULL || next_stats == NULL) {
2917
0
    return 0;
2918
0
  }
2919
2920
0
  int is_viable_kf = 0;
2921
0
  double pcnt_intra = 1.0 - this_stats->pcnt_inter;
2922
0
  double modified_pcnt_inter =
2923
0
      this_stats->pcnt_inter - this_stats->pcnt_neutral;
2924
0
  const double second_ref_usage_thresh =
2925
0
      get_second_ref_usage_thresh(frame_count_so_far);
2926
0
  int frames_to_test_after_candidate_key = SCENE_CUT_KEY_TEST_INTERVAL;
2927
0
  int count_for_tolerable_prediction = 3;
2928
2929
  // We do "-1" because the candidate key is not counted.
2930
0
  int stats_after_this_stats =
2931
0
      av1_firstpass_info_future_count(firstpass_info, this_stats_index) - 1;
2932
2933
0
  if (scenecut_mode == ENABLE_SCENECUT_MODE_1) {
2934
0
    if (stats_after_this_stats < 3) {
2935
0
      return 0;
2936
0
    } else {
2937
0
      frames_to_test_after_candidate_key = 3;
2938
0
      count_for_tolerable_prediction = 1;
2939
0
    }
2940
0
  }
2941
  // Make sure we have enough stats after the candidate key.
2942
0
  frames_to_test_after_candidate_key =
2943
0
      AOMMIN(frames_to_test_after_candidate_key, stats_after_this_stats);
2944
2945
  // Does the frame satisfy the primary criteria of a key frame?
2946
  // See above for an explanation of the test criteria.
2947
  // If so, then examine how well it predicts subsequent frames.
2948
0
  if (IMPLIES(rc_mode == AOM_Q, frame_count_so_far >= 3) &&
2949
0
      (this_stats->pcnt_second_ref < second_ref_usage_thresh) &&
2950
0
      (next_stats->pcnt_second_ref < second_ref_usage_thresh) &&
2951
0
      ((this_stats->pcnt_inter < VERY_LOW_INTER_THRESH) ||
2952
0
       slide_transition(this_stats, last_stats, next_stats) ||
2953
0
       ((pcnt_intra > MIN_INTRA_LEVEL) &&
2954
0
        (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
2955
0
        ((this_stats->intra_error /
2956
0
          DOUBLE_DIVIDE_CHECK(this_stats->coded_error)) <
2957
0
         KF_II_ERR_THRESHOLD) &&
2958
0
        ((fabs(last_stats->coded_error - this_stats->coded_error) /
2959
0
              DOUBLE_DIVIDE_CHECK(this_stats->coded_error) >
2960
0
          ERR_CHANGE_THRESHOLD) ||
2961
0
         (fabs(last_stats->intra_error - this_stats->intra_error) /
2962
0
              DOUBLE_DIVIDE_CHECK(this_stats->intra_error) >
2963
0
          ERR_CHANGE_THRESHOLD) ||
2964
0
         ((next_stats->intra_error /
2965
0
           DOUBLE_DIVIDE_CHECK(next_stats->coded_error)) >
2966
0
          II_IMPROVEMENT_THRESHOLD))))) {
2967
0
    int i;
2968
0
    double boost_score = 0.0;
2969
0
    double old_boost_score = 0.0;
2970
0
    double decay_accumulator = 1.0;
2971
2972
    // Examine how well the key frame predicts subsequent frames.
2973
0
    for (i = 1; i <= frames_to_test_after_candidate_key; ++i) {
2974
      // Get the next frame details
2975
0
      const FIRSTPASS_STATS *local_next_frame =
2976
0
          av1_firstpass_info_peek(firstpass_info, this_stats_index + i);
2977
2978
0
      if ((local_next_frame->intra_error - this_stats->intra_error) /
2979
0
                  DOUBLE_DIVIDE_CHECK(this_stats->intra_error) >
2980
0
              0.1 &&
2981
0
          this_stats->coded_error > local_next_frame->coded_error * 6) {
2982
0
        break;
2983
0
      }
2984
2985
0
      double next_iiratio =
2986
0
          (BOOST_FACTOR * local_next_frame->intra_error /
2987
0
           DOUBLE_DIVIDE_CHECK(local_next_frame->coded_error));
2988
2989
0
      if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
2990
2991
      // Cumulative effect of decay in prediction quality.
2992
0
      if (local_next_frame->pcnt_inter > 0.85)
2993
0
        decay_accumulator *= local_next_frame->pcnt_inter;
2994
0
      else
2995
0
        decay_accumulator *= (0.85 + local_next_frame->pcnt_inter) / 2.0;
2996
2997
      // Keep a running total.
2998
0
      boost_score += (decay_accumulator * next_iiratio);
2999
3000
      // Test various breakout clauses.
3001
      // TODO(any): Test of intra error should be normalized to an MB.
3002
0
      if ((local_next_frame->pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
3003
0
          (((local_next_frame->pcnt_inter - local_next_frame->pcnt_neutral) <
3004
0
            0.20) &&
3005
0
           (next_iiratio < 3.0)) ||
3006
0
          ((boost_score - old_boost_score) < 3.0) ||
3007
0
          (local_next_frame->intra_error < (200.0 / (double)num_mbs))) {
3008
0
        break;
3009
0
      }
3010
3011
0
      old_boost_score = boost_score;
3012
0
    }
3013
3014
    // If there is tolerable prediction for at least the next 3 frames then
3015
    // break out else discard this potential key frame and move on
3016
0
    if (boost_score > 30.0 && (i > count_for_tolerable_prediction)) {
3017
0
      is_viable_kf = 1;
3018
0
    } else {
3019
0
      is_viable_kf = 0;
3020
0
    }
3021
0
  }
3022
0
  return is_viable_kf;
3023
0
}
3024
3025
0
#define FRAMES_TO_CHECK_DECAY 8
3026
0
#define KF_MIN_FRAME_BOOST 80.0
3027
0
#define KF_MAX_FRAME_BOOST 128.0
3028
#define MIN_KF_BOOST 600  // Minimum boost for non-static KF interval
3029
#define MAX_KF_BOOST 3200
3030
#define MIN_STATIC_KF_BOOST 5400  // Minimum boost for static KF interval
3031
3032
0
static int detect_app_forced_key(AV1_COMP *cpi) {
3033
0
  int num_frames_to_app_forced_key = is_forced_keyframe_pending(
3034
0
      cpi->ppi->lookahead, cpi->ppi->lookahead->max_sz, cpi->compressor_stage);
3035
0
  return num_frames_to_app_forced_key;
3036
0
}
3037
3038
0
static int get_projected_kf_boost(AV1_COMP *cpi) {
3039
  /*
3040
   * If num_stats_used_for_kf_boost >= frames_to_key, then
3041
   * all stats needed for prior boost calculation are available.
3042
   * Hence projecting the prior boost is not needed in this cases.
3043
   */
3044
0
  if (cpi->ppi->p_rc.num_stats_used_for_kf_boost >= cpi->rc.frames_to_key)
3045
0
    return cpi->ppi->p_rc.kf_boost;
3046
3047
  // Get the current tpl factor (number of frames = frames_to_key).
3048
0
  double tpl_factor = av1_get_kf_boost_projection_factor(cpi->rc.frames_to_key);
3049
  // Get the tpl factor when number of frames = num_stats_used_for_kf_boost.
3050
0
  double tpl_factor_num_stats = av1_get_kf_boost_projection_factor(
3051
0
      cpi->ppi->p_rc.num_stats_used_for_kf_boost);
3052
0
  int projected_kf_boost =
3053
0
      (int)rint((tpl_factor * cpi->ppi->p_rc.kf_boost) / tpl_factor_num_stats);
3054
0
  return projected_kf_boost;
3055
0
}
3056
3057
/*!\brief Determine the location of the next key frame
3058
 *
3059
 * \ingroup gf_group_algo
3060
 * This function decides the placement of the next key frame when a
3061
 * scenecut is detected or the maximum key frame distance is reached.
3062
 *
3063
 * \param[in]    cpi              Top-level encoder structure
3064
 * \param[in]    firstpass_info   struct for firstpass info
3065
 * \param[in]    num_frames_to_detect_scenecut Maximum lookahead frames.
3066
 * \param[in]    search_start_idx   the start index for searching key frame.
3067
 *                                  Set it to one if we already know the
3068
 *                                  current frame is key frame. Otherwise,
3069
 *                                  set it to zero.
3070
 *
3071
 * \return       Number of frames to the next key including the current frame.
3072
 */
3073
static int define_kf_interval(AV1_COMP *cpi,
3074
                              const FIRSTPASS_INFO *firstpass_info,
3075
                              int num_frames_to_detect_scenecut,
3076
0
                              int search_start_idx) {
3077
0
  const TWO_PASS *const twopass = &cpi->ppi->twopass;
3078
0
  const RATE_CONTROL *const rc = &cpi->rc;
3079
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3080
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3081
0
  const KeyFrameCfg *const kf_cfg = &oxcf->kf_cfg;
3082
0
  double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
3083
0
  double decay_accumulator = 1.0;
3084
0
  int i = 0, j;
3085
0
  int frames_to_key = search_start_idx;
3086
0
  int frames_since_key = rc->frames_since_key + 1;
3087
0
  int scenecut_detected = 0;
3088
3089
0
  int num_frames_to_next_key = detect_app_forced_key(cpi);
3090
3091
0
  if (num_frames_to_detect_scenecut == 0) {
3092
0
    if (num_frames_to_next_key != -1)
3093
0
      return num_frames_to_next_key;
3094
0
    else
3095
0
      return rc->frames_to_key;
3096
0
  }
3097
3098
0
  if (num_frames_to_next_key != -1)
3099
0
    num_frames_to_detect_scenecut =
3100
0
        AOMMIN(num_frames_to_detect_scenecut, num_frames_to_next_key);
3101
3102
  // Initialize the decay rates for the recent frames to check
3103
0
  for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
3104
3105
0
  i = 0;
3106
0
  const int num_mbs = (oxcf->resize_cfg.resize_mode != RESIZE_NONE)
3107
0
                          ? cpi->initial_mbs
3108
0
                          : cpi->common.mi_params.MBs;
3109
0
  const int future_stats_count =
3110
0
      av1_firstpass_info_future_count(firstpass_info, 0);
3111
3112
0
  while (frames_to_key < future_stats_count &&
3113
0
         frames_to_key < num_frames_to_detect_scenecut) {
3114
    // Provided that we are not at the end of the file...
3115
0
    if ((cpi->ppi->p_rc.enable_scenecut_detection > 0) && kf_cfg->auto_key &&
3116
0
        frames_to_key + 1 < future_stats_count) {
3117
0
      double loop_decay_rate;
3118
3119
      // Check for a scene cut.
3120
0
      if (frames_since_key >= kf_cfg->key_freq_min) {
3121
0
        scenecut_detected = test_candidate_kf(
3122
0
            &twopass->firstpass_info, frames_to_key, frames_since_key,
3123
0
            oxcf->rc_cfg.mode, cpi->ppi->p_rc.enable_scenecut_detection,
3124
0
            num_mbs);
3125
0
        if (scenecut_detected) {
3126
0
          int test_next_gop = 0;
3127
3128
0
          for (int idx = 0; idx < 32; ++idx) {
3129
0
            const FIRSTPASS_STATS *next_stats =
3130
0
                av1_firstpass_info_peek(firstpass_info, frames_to_key + idx);
3131
3132
0
            if (next_stats == NULL) continue;
3133
3134
0
            if (cpi->common.current_frame.frame_number + frames_to_key + idx >
3135
0
                    2 &&
3136
0
                next_stats->lt_coded_error * 2.5 < next_stats->coded_error)
3137
0
              test_next_gop = 1;
3138
0
          }
3139
3140
0
          if (!test_next_gop) break;
3141
0
        }
3142
0
      }
3143
3144
      // How fast is the prediction quality decaying?
3145
0
      const FIRSTPASS_STATS *next_stats =
3146
0
          av1_firstpass_info_peek(firstpass_info, frames_to_key + 1);
3147
0
      loop_decay_rate = get_prediction_decay_rate(next_stats);
3148
3149
      // We want to know something about the recent past... rather than
3150
      // as used elsewhere where we are concerned with decay in prediction
3151
      // quality since the last GF or KF.
3152
0
      recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
3153
0
      decay_accumulator = 1.0;
3154
0
      for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
3155
0
        decay_accumulator *= recent_loop_decay[j];
3156
3157
      // Special check for transition or high motion followed by a
3158
      // static scene.
3159
0
      if (frames_since_key >= kf_cfg->key_freq_min) {
3160
0
        scenecut_detected = detect_transition_to_still(
3161
0
            firstpass_info, frames_to_key + 1, rc->min_gf_interval, i,
3162
0
            kf_cfg->key_freq_max - i, loop_decay_rate, decay_accumulator);
3163
0
        if (scenecut_detected) {
3164
          // In the case of transition followed by a static scene, the key frame
3165
          // could be a good predictor for the following frames, therefore we
3166
          // do not use an arf.
3167
0
          p_rc->use_arf_in_this_kf_group = 0;
3168
0
          break;
3169
0
        }
3170
0
      }
3171
3172
      // Step on to the next frame.
3173
0
      ++frames_to_key;
3174
0
      ++frames_since_key;
3175
3176
      // If we don't have a real key frame within the next two
3177
      // key_freq_max intervals then break out of the loop.
3178
0
      if (frames_to_key >= 2 * kf_cfg->key_freq_max) {
3179
0
        break;
3180
0
      }
3181
0
    } else {
3182
0
      ++frames_to_key;
3183
0
      ++frames_since_key;
3184
0
    }
3185
0
    ++i;
3186
0
  }
3187
0
  if (cpi->ppi->lap_enabled && !scenecut_detected)
3188
0
    frames_to_key = num_frames_to_next_key;
3189
3190
0
  return frames_to_key;
3191
0
}
3192
3193
static double get_kf_group_avg_error(TWO_PASS *twopass,
3194
                                     TWO_PASS_FRAME *twopass_frame,
3195
                                     const FIRSTPASS_STATS *first_frame,
3196
                                     const FIRSTPASS_STATS *start_position,
3197
0
                                     int frames_to_key) {
3198
0
  FIRSTPASS_STATS cur_frame = *first_frame;
3199
0
  int num_frames, i;
3200
0
  double kf_group_avg_error = 0.0;
3201
3202
0
  reset_fpf_position(twopass_frame, start_position);
3203
3204
0
  for (i = 0; i < frames_to_key; ++i) {
3205
0
    kf_group_avg_error += cur_frame.coded_error;
3206
0
    if (EOF == input_stats(twopass, twopass_frame, &cur_frame)) break;
3207
0
  }
3208
0
  num_frames = i + 1;
3209
0
  num_frames = AOMMIN(num_frames, frames_to_key);
3210
0
  kf_group_avg_error = kf_group_avg_error / num_frames;
3211
3212
0
  return (kf_group_avg_error);
3213
0
}
3214
3215
static int64_t get_kf_group_bits(AV1_COMP *cpi, double kf_group_err,
3216
0
                                 double kf_group_avg_error) {
3217
0
  RATE_CONTROL *const rc = &cpi->rc;
3218
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3219
0
  int64_t kf_group_bits;
3220
0
  if (cpi->ppi->lap_enabled) {
3221
0
    kf_group_bits = (int64_t)rc->frames_to_key * rc->avg_frame_bandwidth;
3222
0
    if (cpi->oxcf.rc_cfg.vbr_corpus_complexity_lap) {
3223
0
      double vbr_corpus_complexity_lap =
3224
0
          cpi->oxcf.rc_cfg.vbr_corpus_complexity_lap / 10.0;
3225
      /* Get the average corpus complexity of the frame */
3226
0
      kf_group_bits = (int64_t)(kf_group_bits * (kf_group_avg_error /
3227
0
                                                 vbr_corpus_complexity_lap));
3228
0
    }
3229
0
  } else {
3230
0
    kf_group_bits = (int64_t)(twopass->bits_left *
3231
0
                              (kf_group_err / twopass->modified_error_left));
3232
0
  }
3233
3234
0
  return kf_group_bits;
3235
0
}
3236
3237
0
static int calc_avg_stats(AV1_COMP *cpi, FIRSTPASS_STATS *avg_frame_stat) {
3238
0
  RATE_CONTROL *const rc = &cpi->rc;
3239
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3240
0
  FIRSTPASS_STATS cur_frame;
3241
0
  av1_zero(cur_frame);
3242
0
  int num_frames = 0;
3243
  // Accumulate total stat using available number of stats.
3244
0
  for (num_frames = 0; num_frames < (rc->frames_to_key - 1); ++num_frames) {
3245
0
    if (EOF == input_stats(twopass, &cpi->twopass_frame, &cur_frame)) break;
3246
0
    av1_accumulate_stats(avg_frame_stat, &cur_frame);
3247
0
  }
3248
3249
0
  if (num_frames < 2) {
3250
0
    return num_frames;
3251
0
  }
3252
  // Average the total stat
3253
0
  avg_frame_stat->weight = avg_frame_stat->weight / num_frames;
3254
0
  avg_frame_stat->intra_error = avg_frame_stat->intra_error / num_frames;
3255
0
  avg_frame_stat->frame_avg_wavelet_energy =
3256
0
      avg_frame_stat->frame_avg_wavelet_energy / num_frames;
3257
0
  avg_frame_stat->coded_error = avg_frame_stat->coded_error / num_frames;
3258
0
  avg_frame_stat->sr_coded_error = avg_frame_stat->sr_coded_error / num_frames;
3259
0
  avg_frame_stat->pcnt_inter = avg_frame_stat->pcnt_inter / num_frames;
3260
0
  avg_frame_stat->pcnt_motion = avg_frame_stat->pcnt_motion / num_frames;
3261
0
  avg_frame_stat->pcnt_second_ref =
3262
0
      avg_frame_stat->pcnt_second_ref / num_frames;
3263
0
  avg_frame_stat->pcnt_neutral = avg_frame_stat->pcnt_neutral / num_frames;
3264
0
  avg_frame_stat->intra_skip_pct = avg_frame_stat->intra_skip_pct / num_frames;
3265
0
  avg_frame_stat->inactive_zone_rows =
3266
0
      avg_frame_stat->inactive_zone_rows / num_frames;
3267
0
  avg_frame_stat->inactive_zone_cols =
3268
0
      avg_frame_stat->inactive_zone_cols / num_frames;
3269
0
  avg_frame_stat->MVr = avg_frame_stat->MVr / num_frames;
3270
0
  avg_frame_stat->mvr_abs = avg_frame_stat->mvr_abs / num_frames;
3271
0
  avg_frame_stat->MVc = avg_frame_stat->MVc / num_frames;
3272
0
  avg_frame_stat->mvc_abs = avg_frame_stat->mvc_abs / num_frames;
3273
0
  avg_frame_stat->MVrv = avg_frame_stat->MVrv / num_frames;
3274
0
  avg_frame_stat->MVcv = avg_frame_stat->MVcv / num_frames;
3275
0
  avg_frame_stat->mv_in_out_count =
3276
0
      avg_frame_stat->mv_in_out_count / num_frames;
3277
0
  avg_frame_stat->new_mv_count = avg_frame_stat->new_mv_count / num_frames;
3278
0
  avg_frame_stat->count = avg_frame_stat->count / num_frames;
3279
0
  avg_frame_stat->duration = avg_frame_stat->duration / num_frames;
3280
3281
0
  return num_frames;
3282
0
}
3283
3284
static double get_kf_boost_score(AV1_COMP *cpi, double kf_raw_err,
3285
                                 double *zero_motion_accumulator,
3286
0
                                 double *sr_accumulator, int use_avg_stat) {
3287
0
  RATE_CONTROL *const rc = &cpi->rc;
3288
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3289
0
  FRAME_INFO *const frame_info = &cpi->frame_info;
3290
0
  FIRSTPASS_STATS frame_stat;
3291
0
  av1_zero(frame_stat);
3292
0
  int i = 0, num_stat_used = 0;
3293
0
  double boost_score = 0.0;
3294
0
  const double kf_max_boost =
3295
0
      cpi->oxcf.rc_cfg.mode == AOM_Q
3296
0
          ? fclamp(rc->frames_to_key * 2.0, KF_MIN_FRAME_BOOST,
3297
0
                   KF_MAX_FRAME_BOOST)
3298
0
          : KF_MAX_FRAME_BOOST;
3299
3300
  // Calculate the average using available number of stats.
3301
0
  if (use_avg_stat) num_stat_used = calc_avg_stats(cpi, &frame_stat);
3302
3303
0
  for (i = num_stat_used; i < (rc->frames_to_key - 1); ++i) {
3304
0
    if (!use_avg_stat &&
3305
0
        EOF == input_stats(twopass, &cpi->twopass_frame, &frame_stat))
3306
0
      break;
3307
3308
    // Monitor for static sections.
3309
    // For the first frame in kf group, the second ref indicator is invalid.
3310
0
    if (i > 0) {
3311
0
      *zero_motion_accumulator =
3312
0
          AOMMIN(*zero_motion_accumulator, get_zero_motion_factor(&frame_stat));
3313
0
    } else {
3314
0
      *zero_motion_accumulator = frame_stat.pcnt_inter - frame_stat.pcnt_motion;
3315
0
    }
3316
3317
    // Not all frames in the group are necessarily used in calculating boost.
3318
0
    if ((*sr_accumulator < (kf_raw_err * 1.50)) &&
3319
0
        (i <= rc->max_gf_interval * 2)) {
3320
0
      double frame_boost;
3321
0
      double zm_factor;
3322
3323
      // Factor 0.75-1.25 based on how much of frame is static.
3324
0
      zm_factor = (0.75 + (*zero_motion_accumulator / 2.0));
3325
3326
0
      if (i < 2) *sr_accumulator = 0.0;
3327
0
      frame_boost =
3328
0
          calc_kf_frame_boost(&cpi->ppi->p_rc, frame_info, &frame_stat,
3329
0
                              sr_accumulator, kf_max_boost);
3330
0
      boost_score += frame_boost * zm_factor;
3331
0
    }
3332
0
  }
3333
0
  return boost_score;
3334
0
}
3335
3336
/*!\brief Interval(in seconds) to clip key-frame distance to in LAP.
3337
 */
3338
0
#define MAX_KF_BITS_INTERVAL_SINGLE_PASS 5
3339
3340
/*!\brief Determine the next key frame group
3341
 *
3342
 * \ingroup gf_group_algo
3343
 * This function decides the placement of the next key frame, and
3344
 * calculates the bit allocation of the KF group and the keyframe itself.
3345
 *
3346
 * \param[in]    cpi              Top-level encoder structure
3347
 * \param[in]    this_frame       Pointer to first pass stats
3348
 */
3349
0
static void find_next_key_frame(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame) {
3350
0
  RATE_CONTROL *const rc = &cpi->rc;
3351
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3352
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3353
0
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3354
0
  FRAME_INFO *const frame_info = &cpi->frame_info;
3355
0
  AV1_COMMON *const cm = &cpi->common;
3356
0
  CurrentFrame *const current_frame = &cm->current_frame;
3357
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3358
0
  const KeyFrameCfg *const kf_cfg = &oxcf->kf_cfg;
3359
0
  const FIRSTPASS_STATS first_frame = *this_frame;
3360
0
  FIRSTPASS_STATS next_frame;
3361
0
  const FIRSTPASS_INFO *firstpass_info = &twopass->firstpass_info;
3362
0
  av1_zero(next_frame);
3363
3364
0
  rc->frames_since_key = 0;
3365
  // Use arfs if possible.
3366
0
  p_rc->use_arf_in_this_kf_group = is_altref_enabled(
3367
0
      oxcf->gf_cfg.lag_in_frames, oxcf->gf_cfg.enable_auto_arf);
3368
3369
  // Reset the GF group data structures.
3370
0
  av1_zero(*gf_group);
3371
0
  cpi->gf_frame_index = 0;
3372
3373
  // KF is always a GF so clear frames till next gf counter.
3374
0
  rc->frames_till_gf_update_due = 0;
3375
3376
0
  if (has_no_stats_stage(cpi)) {
3377
0
    int num_frames_to_app_forced_key = detect_app_forced_key(cpi);
3378
0
    p_rc->this_key_frame_forced =
3379
0
        current_frame->frame_number != 0 && rc->frames_to_key == 0;
3380
0
    if (num_frames_to_app_forced_key != -1)
3381
0
      rc->frames_to_key = num_frames_to_app_forced_key;
3382
0
    else
3383
0
      rc->frames_to_key = AOMMAX(1, kf_cfg->key_freq_max);
3384
0
    correct_frames_to_key(cpi);
3385
0
    p_rc->kf_boost = DEFAULT_KF_BOOST;
3386
0
    gf_group->update_type[0] = KF_UPDATE;
3387
0
    return;
3388
0
  }
3389
0
  int i;
3390
0
  const FIRSTPASS_STATS *const start_position = cpi->twopass_frame.stats_in;
3391
0
  int kf_bits = 0;
3392
0
  double zero_motion_accumulator = 1.0;
3393
0
  double boost_score = 0.0;
3394
0
  double kf_raw_err = 0.0;
3395
0
  double kf_mod_err = 0.0;
3396
0
  double sr_accumulator = 0.0;
3397
0
  double kf_group_avg_error = 0.0;
3398
0
  int frames_to_key, frames_to_key_clipped = INT_MAX;
3399
0
  int64_t kf_group_bits_clipped = INT64_MAX;
3400
3401
  // Is this a forced key frame by interval.
3402
0
  p_rc->this_key_frame_forced = p_rc->next_key_frame_forced;
3403
3404
0
  twopass->kf_group_bits = 0;        // Total bits available to kf group
3405
0
  twopass->kf_group_error_left = 0;  // Group modified error score.
3406
3407
0
  kf_raw_err = this_frame->intra_error;
3408
0
  kf_mod_err = calculate_modified_err(frame_info, twopass, oxcf, this_frame);
3409
3410
0
  if (cpi->ext_ratectrl.ready &&
3411
0
      (cpi->ext_ratectrl.funcs.rc_type & AOM_RC_GOP) != 0 &&
3412
0
      cpi->ext_ratectrl.funcs.get_key_frame_decision != NULL) {
3413
0
    aom_rc_key_frame_decision_t key_frame_decision;
3414
0
    aom_codec_err_t codec_status = av1_extrc_get_key_frame_decision(
3415
0
        &cpi->ext_ratectrl, &key_frame_decision);
3416
0
    if (codec_status == AOM_CODEC_OK) {
3417
0
      rc->frames_to_key = key_frame_decision.key_frame_group_size;
3418
0
    } else {
3419
0
      aom_internal_error(cpi->common.error, codec_status,
3420
0
                         "av1_extrc_get_key_frame_decision() failed");
3421
0
    }
3422
0
  } else {
3423
    // We assume the current frame is a key frame and we are looking for the
3424
    // next key frame. Therefore search_start_idx = 1
3425
0
    frames_to_key =
3426
0
        define_kf_interval(cpi, firstpass_info, kf_cfg->key_freq_max,
3427
0
                           /*search_start_idx=*/1);
3428
3429
0
    if (frames_to_key != -1) {
3430
0
      rc->frames_to_key = AOMMIN(kf_cfg->key_freq_max, frames_to_key);
3431
0
    } else {
3432
0
      rc->frames_to_key = kf_cfg->key_freq_max;
3433
0
    }
3434
0
  }
3435
3436
0
  if (cpi->ppi->lap_enabled) correct_frames_to_key(cpi);
3437
3438
  // If there is a max kf interval set by the user we must obey it.
3439
  // We already breakout of the loop above at 2x max.
3440
  // This code centers the extra kf if the actual natural interval
3441
  // is between 1x and 2x.
3442
0
  if (kf_cfg->auto_key && rc->frames_to_key > kf_cfg->key_freq_max) {
3443
0
    FIRSTPASS_STATS tmp_frame = first_frame;
3444
3445
0
    rc->frames_to_key /= 2;
3446
3447
    // Reset to the start of the group.
3448
0
    reset_fpf_position(&cpi->twopass_frame, start_position);
3449
    // Rescan to get the correct error data for the forced kf group.
3450
0
    for (i = 0; i < rc->frames_to_key; ++i) {
3451
0
      if (EOF == input_stats(twopass, &cpi->twopass_frame, &tmp_frame)) break;
3452
0
    }
3453
0
    p_rc->next_key_frame_forced = 1;
3454
0
  } else if ((cpi->twopass_frame.stats_in ==
3455
0
                  twopass->stats_buf_ctx->stats_in_end &&
3456
0
              is_stat_consumption_stage_twopass(cpi)) ||
3457
0
             rc->frames_to_key >= kf_cfg->key_freq_max) {
3458
0
    p_rc->next_key_frame_forced = 1;
3459
0
  } else {
3460
0
    p_rc->next_key_frame_forced = 0;
3461
0
  }
3462
3463
0
  double kf_group_err = 0;
3464
0
  for (i = 0; i < rc->frames_to_key; ++i) {
3465
0
    const FIRSTPASS_STATS *this_stats =
3466
0
        av1_firstpass_info_peek(&twopass->firstpass_info, i);
3467
0
    if (this_stats != NULL) {
3468
      // Accumulate kf group error.
3469
0
      kf_group_err += calculate_modified_err_new(
3470
0
          frame_info, &firstpass_info->total_stats, this_stats,
3471
0
          oxcf->rc_cfg.vbrbias, twopass->modified_error_min,
3472
0
          twopass->modified_error_max);
3473
0
      ++p_rc->num_stats_used_for_kf_boost;
3474
0
    }
3475
0
  }
3476
3477
  // Calculate the number of bits that should be assigned to the kf group.
3478
0
  if ((twopass->bits_left > 0 && twopass->modified_error_left > 0.0) ||
3479
0
      (cpi->ppi->lap_enabled && oxcf->rc_cfg.mode != AOM_Q)) {
3480
    // Maximum number of bits for a single normal frame (not key frame).
3481
0
    const int max_bits = frame_max_bits(rc, oxcf);
3482
3483
    // Maximum number of bits allocated to the key frame group.
3484
0
    int64_t max_grp_bits;
3485
3486
0
    if (oxcf->rc_cfg.vbr_corpus_complexity_lap) {
3487
0
      kf_group_avg_error =
3488
0
          get_kf_group_avg_error(twopass, &cpi->twopass_frame, &first_frame,
3489
0
                                 start_position, rc->frames_to_key);
3490
0
    }
3491
3492
    // Default allocation based on bits left and relative
3493
    // complexity of the section.
3494
0
    twopass->kf_group_bits =
3495
0
        get_kf_group_bits(cpi, kf_group_err, kf_group_avg_error);
3496
    // Clip based on maximum per frame rate defined by the user.
3497
0
    max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
3498
0
    if (twopass->kf_group_bits > max_grp_bits)
3499
0
      twopass->kf_group_bits = max_grp_bits;
3500
0
  } else {
3501
0
    twopass->kf_group_bits = 0;
3502
0
  }
3503
0
  twopass->kf_group_bits = AOMMAX(0, twopass->kf_group_bits);
3504
3505
0
  if (cpi->ppi->lap_enabled) {
3506
    // In the case of single pass based on LAP, frames to  key may have an
3507
    // inaccurate value, and hence should be clipped to an appropriate
3508
    // interval.
3509
0
    frames_to_key_clipped =
3510
0
        (int)(MAX_KF_BITS_INTERVAL_SINGLE_PASS * cpi->framerate);
3511
3512
    // This variable calculates the bits allocated to kf_group with a clipped
3513
    // frames_to_key.
3514
0
    if (rc->frames_to_key > frames_to_key_clipped) {
3515
0
      kf_group_bits_clipped =
3516
0
          (int64_t)((double)twopass->kf_group_bits * frames_to_key_clipped /
3517
0
                    rc->frames_to_key);
3518
0
    }
3519
0
  }
3520
3521
  // Reset the first pass file position.
3522
0
  reset_fpf_position(&cpi->twopass_frame, start_position);
3523
3524
  // Scan through the kf group collating various stats used to determine
3525
  // how many bits to spend on it.
3526
0
  boost_score = get_kf_boost_score(cpi, kf_raw_err, &zero_motion_accumulator,
3527
0
                                   &sr_accumulator, 0);
3528
0
  reset_fpf_position(&cpi->twopass_frame, start_position);
3529
  // Store the zero motion percentage
3530
0
  twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
3531
3532
  // Calculate a section intra ratio used in setting max loop filter.
3533
0
  twopass->section_intra_rating = calculate_section_intra_ratio(
3534
0
      start_position, twopass->stats_buf_ctx->stats_in_end, rc->frames_to_key);
3535
3536
0
  p_rc->kf_boost = (int)boost_score;
3537
3538
0
  if (cpi->ppi->lap_enabled) {
3539
0
    if (oxcf->rc_cfg.mode == AOM_Q) {
3540
0
      p_rc->kf_boost = get_projected_kf_boost(cpi);
3541
0
    } else {
3542
      // TODO(any): Explore using average frame stats for AOM_Q as well.
3543
0
      boost_score = get_kf_boost_score(
3544
0
          cpi, kf_raw_err, &zero_motion_accumulator, &sr_accumulator, 1);
3545
0
      reset_fpf_position(&cpi->twopass_frame, start_position);
3546
0
      p_rc->kf_boost += (int)boost_score;
3547
0
    }
3548
0
  }
3549
3550
  // Special case for static / slide show content but don't apply
3551
  // if the kf group is very short.
3552
0
  if ((zero_motion_accumulator > STATIC_KF_GROUP_FLOAT_THRESH) &&
3553
0
      (rc->frames_to_key > 8)) {
3554
0
    p_rc->kf_boost = AOMMAX(p_rc->kf_boost, MIN_STATIC_KF_BOOST);
3555
0
  } else {
3556
    // Apply various clamps for min and max boost
3557
0
    p_rc->kf_boost = AOMMAX(p_rc->kf_boost, (rc->frames_to_key * 3));
3558
0
    p_rc->kf_boost = AOMMAX(p_rc->kf_boost, MIN_KF_BOOST);
3559
#ifdef STRICT_RC
3560
    p_rc->kf_boost = AOMMIN(p_rc->kf_boost, MAX_KF_BOOST);
3561
#endif
3562
0
  }
3563
3564
  // Work out how many bits to allocate for the key frame itself.
3565
  // In case of LAP enabled for VBR, if the frames_to_key value is
3566
  // very high, we calculate the bits based on a clipped value of
3567
  // frames_to_key.
3568
0
  kf_bits = calculate_boost_bits(
3569
0
      AOMMIN(rc->frames_to_key, frames_to_key_clipped) - 1, p_rc->kf_boost,
3570
0
      AOMMIN(twopass->kf_group_bits, kf_group_bits_clipped));
3571
0
  kf_bits = adjust_boost_bits_for_target_level(cpi, rc, kf_bits,
3572
0
                                               twopass->kf_group_bits, 0);
3573
3574
0
  twopass->kf_group_bits -= kf_bits;
3575
3576
  // Save the bits to spend on the key frame.
3577
0
  gf_group->bit_allocation[0] = kf_bits;
3578
0
  gf_group->update_type[0] = KF_UPDATE;
3579
3580
  // Note the total error score of the kf group minus the key frame itself.
3581
0
  if (cpi->ppi->lap_enabled)
3582
    // As we don't have enough stats to know the actual error of the group,
3583
    // we assume the complexity of each frame to be equal to 1, and set the
3584
    // error as the number of frames in the group(minus the keyframe).
3585
0
    twopass->kf_group_error_left = (double)(rc->frames_to_key - 1);
3586
0
  else
3587
0
    twopass->kf_group_error_left = kf_group_err - kf_mod_err;
3588
3589
  // Adjust the count of total modified error left.
3590
  // The count of bits left is adjusted elsewhere based on real coded frame
3591
  // sizes.
3592
0
  twopass->modified_error_left -= kf_group_err;
3593
0
}
3594
3595
#define ARF_STATS_OUTPUT 0
3596
#if ARF_STATS_OUTPUT
3597
unsigned int arf_count = 0;
3598
#endif
3599
3600
0
static int get_section_target_bandwidth(AV1_COMP *cpi) {
3601
0
  AV1_COMMON *const cm = &cpi->common;
3602
0
  CurrentFrame *const current_frame = &cm->current_frame;
3603
0
  RATE_CONTROL *const rc = &cpi->rc;
3604
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3605
0
  int64_t section_target_bandwidth;
3606
0
  const int frames_left = (int)(twopass->stats_buf_ctx->total_stats->count -
3607
0
                                current_frame->frame_number);
3608
0
  if (cpi->ppi->lap_enabled)
3609
0
    section_target_bandwidth = rc->avg_frame_bandwidth;
3610
0
  else {
3611
0
    section_target_bandwidth = twopass->bits_left / frames_left;
3612
0
    section_target_bandwidth = AOMMIN(section_target_bandwidth, INT_MAX);
3613
0
  }
3614
0
  return (int)section_target_bandwidth;
3615
0
}
3616
3617
static inline void set_twopass_params_based_on_fp_stats(
3618
0
    AV1_COMP *cpi, const FIRSTPASS_STATS *this_frame_ptr) {
3619
0
  if (this_frame_ptr == NULL) return;
3620
3621
0
  TWO_PASS_FRAME *twopass_frame = &cpi->twopass_frame;
3622
  // The multiplication by 256 reverses a scaling factor of (>> 8)
3623
  // applied when combining MB error values for the frame.
3624
0
  twopass_frame->mb_av_energy = log1p(this_frame_ptr->intra_error);
3625
3626
0
  const FIRSTPASS_STATS *const total_stats =
3627
0
      cpi->ppi->twopass.stats_buf_ctx->total_stats;
3628
0
  if (is_fp_wavelet_energy_invalid(total_stats) == 0) {
3629
0
    twopass_frame->frame_avg_haar_energy =
3630
0
        log1p(this_frame_ptr->frame_avg_wavelet_energy);
3631
0
  }
3632
3633
  // Set the frame content type flag.
3634
0
  if (this_frame_ptr->intra_skip_pct >= FC_ANIMATION_THRESH)
3635
0
    twopass_frame->fr_content_type = FC_GRAPHICS_ANIMATION;
3636
0
  else
3637
0
    twopass_frame->fr_content_type = FC_NORMAL;
3638
0
}
3639
3640
static void process_first_pass_stats(AV1_COMP *cpi,
3641
0
                                     FIRSTPASS_STATS *this_frame) {
3642
0
  AV1_COMMON *const cm = &cpi->common;
3643
0
  CurrentFrame *const current_frame = &cm->current_frame;
3644
0
  RATE_CONTROL *const rc = &cpi->rc;
3645
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3646
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3647
0
  FIRSTPASS_STATS *total_stats = twopass->stats_buf_ctx->total_stats;
3648
3649
0
  if (cpi->oxcf.rc_cfg.mode != AOM_Q && current_frame->frame_number == 0 &&
3650
0
      cpi->gf_frame_index == 0 && total_stats &&
3651
0
      twopass->stats_buf_ctx->total_left_stats) {
3652
0
    if (cpi->ppi->lap_enabled) {
3653
      /*
3654
       * Accumulate total_stats using available limited number of stats,
3655
       * and assign it to total_left_stats.
3656
       */
3657
0
      *twopass->stats_buf_ctx->total_left_stats = *total_stats;
3658
0
    }
3659
    // Special case code for first frame.
3660
0
    const int section_target_bandwidth = get_section_target_bandwidth(cpi);
3661
0
    const double section_length =
3662
0
        twopass->stats_buf_ctx->total_left_stats->count;
3663
0
    const double section_error =
3664
0
        twopass->stats_buf_ctx->total_left_stats->coded_error / section_length;
3665
0
    const double section_intra_skip =
3666
0
        twopass->stats_buf_ctx->total_left_stats->intra_skip_pct /
3667
0
        section_length;
3668
0
    const double section_inactive_zone =
3669
0
        (twopass->stats_buf_ctx->total_left_stats->inactive_zone_rows * 2) /
3670
0
        ((double)cm->mi_params.mb_rows * section_length);
3671
0
    const int tmp_q = get_twopass_worst_quality(
3672
0
        cpi, section_error, section_intra_skip + section_inactive_zone,
3673
0
        section_target_bandwidth);
3674
3675
0
    rc->active_worst_quality = tmp_q;
3676
0
    rc->ni_av_qi = tmp_q;
3677
0
    p_rc->last_q[INTER_FRAME] = tmp_q;
3678
0
    p_rc->avg_q = av1_convert_qindex_to_q(tmp_q, cm->seq_params->bit_depth);
3679
0
    p_rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
3680
0
    p_rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.rc_cfg.best_allowed_q) / 2;
3681
0
    p_rc->avg_frame_qindex[KEY_FRAME] = p_rc->last_q[KEY_FRAME];
3682
0
  }
3683
3684
0
  if (cpi->twopass_frame.stats_in < twopass->stats_buf_ctx->stats_in_end) {
3685
0
    *this_frame = *cpi->twopass_frame.stats_in;
3686
0
    ++cpi->twopass_frame.stats_in;
3687
0
  }
3688
0
  set_twopass_params_based_on_fp_stats(cpi, this_frame);
3689
0
}
3690
3691
0
void av1_setup_target_rate(AV1_COMP *cpi) {
3692
0
  RATE_CONTROL *const rc = &cpi->rc;
3693
0
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3694
3695
0
  int target_rate = gf_group->bit_allocation[cpi->gf_frame_index];
3696
3697
0
  if (has_no_stats_stage(cpi)) {
3698
0
    av1_rc_set_frame_target(cpi, target_rate, cpi->common.width,
3699
0
                            cpi->common.height);
3700
0
  }
3701
3702
0
  rc->base_frame_target = target_rate;
3703
0
}
3704
3705
static void mark_flashes(FIRSTPASS_STATS *first_stats,
3706
0
                         FIRSTPASS_STATS *last_stats) {
3707
0
  FIRSTPASS_STATS *this_stats = first_stats, *next_stats;
3708
0
  while (this_stats < last_stats - 1) {
3709
0
    next_stats = this_stats + 1;
3710
0
    if (next_stats->pcnt_second_ref > next_stats->pcnt_inter &&
3711
0
        next_stats->pcnt_second_ref >= 0.5) {
3712
0
      this_stats->is_flash = 1;
3713
0
    } else {
3714
0
      this_stats->is_flash = 0;
3715
0
    }
3716
0
    this_stats = next_stats;
3717
0
  }
3718
  // We always treat the last one as none flash.
3719
0
  if (last_stats - 1 >= first_stats) {
3720
0
    (last_stats - 1)->is_flash = 0;
3721
0
  }
3722
0
}
3723
3724
// Smooth-out the noise variance so it is more stable
3725
// Returns 0 on success, -1 on memory allocation failure.
3726
// TODO(bohanli): Use a better low-pass filter than averaging
3727
static int smooth_filter_noise(FIRSTPASS_STATS *first_stats,
3728
0
                               FIRSTPASS_STATS *last_stats) {
3729
0
  int len = (int)(last_stats - first_stats);
3730
0
  double *smooth_noise = aom_malloc(len * sizeof(*smooth_noise));
3731
0
  if (!smooth_noise) return -1;
3732
3733
0
  for (int i = 0; i < len; i++) {
3734
0
    double total_noise = 0;
3735
0
    double total_wt = 0;
3736
0
    for (int j = -HALF_FILT_LEN; j <= HALF_FILT_LEN; j++) {
3737
0
      int idx = clamp(i + j, 0, len - 1);
3738
0
      if (first_stats[idx].is_flash) continue;
3739
3740
0
      total_noise += first_stats[idx].noise_var;
3741
0
      total_wt += 1.0;
3742
0
    }
3743
0
    if (total_wt > 0.01) {
3744
0
      total_noise /= total_wt;
3745
0
    } else {
3746
0
      total_noise = first_stats[i].noise_var;
3747
0
    }
3748
0
    smooth_noise[i] = total_noise;
3749
0
  }
3750
3751
0
  for (int i = 0; i < len; i++) {
3752
0
    first_stats[i].noise_var = smooth_noise[i];
3753
0
  }
3754
3755
0
  aom_free(smooth_noise);
3756
0
  return 0;
3757
0
}
3758
3759
// Estimate the noise variance of each frame from the first pass stats
3760
static void estimate_noise(FIRSTPASS_STATS *first_stats,
3761
                           FIRSTPASS_STATS *last_stats,
3762
0
                           struct aom_internal_error_info *error_info) {
3763
0
  FIRSTPASS_STATS *this_stats, *next_stats;
3764
0
  double C1, C2, C3, noise;
3765
0
  for (this_stats = first_stats + 2; this_stats < last_stats; this_stats++) {
3766
0
    this_stats->noise_var = 0.0;
3767
    // flashes tend to have high correlation of innovations, so ignore them.
3768
0
    if (this_stats->is_flash || (this_stats - 1)->is_flash ||
3769
0
        (this_stats - 2)->is_flash)
3770
0
      continue;
3771
3772
0
    C1 = (this_stats - 1)->intra_error *
3773
0
         (this_stats->intra_error - this_stats->coded_error);
3774
0
    C2 = (this_stats - 2)->intra_error *
3775
0
         ((this_stats - 1)->intra_error - (this_stats - 1)->coded_error);
3776
0
    C3 = (this_stats - 2)->intra_error *
3777
0
         (this_stats->intra_error - this_stats->sr_coded_error);
3778
0
    if (C1 <= 0 || C2 <= 0 || C3 <= 0) continue;
3779
0
    C1 = sqrt(C1);
3780
0
    C2 = sqrt(C2);
3781
0
    C3 = sqrt(C3);
3782
3783
0
    noise = (this_stats - 1)->intra_error - C1 * C2 / C3;
3784
0
    noise = AOMMAX(noise, 0.01);
3785
0
    this_stats->noise_var = noise;
3786
0
  }
3787
3788
  // Copy noise from the neighbor if the noise value is not trustworthy
3789
0
  for (this_stats = first_stats + 2; this_stats < last_stats; this_stats++) {
3790
0
    if (this_stats->is_flash || (this_stats - 1)->is_flash ||
3791
0
        (this_stats - 2)->is_flash)
3792
0
      continue;
3793
0
    if (this_stats->noise_var < 1.0) {
3794
0
      int found = 0;
3795
      // TODO(bohanli): consider expanding to two directions at the same time
3796
0
      for (next_stats = this_stats + 1; next_stats < last_stats; next_stats++) {
3797
0
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3798
0
            (next_stats - 2)->is_flash || next_stats->noise_var < 1.0)
3799
0
          continue;
3800
0
        found = 1;
3801
0
        this_stats->noise_var = next_stats->noise_var;
3802
0
        break;
3803
0
      }
3804
0
      if (found) continue;
3805
0
      for (next_stats = this_stats - 1; next_stats >= first_stats + 2;
3806
0
           next_stats--) {
3807
0
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3808
0
            (next_stats - 2)->is_flash || next_stats->noise_var < 1.0)
3809
0
          continue;
3810
0
        this_stats->noise_var = next_stats->noise_var;
3811
0
        break;
3812
0
      }
3813
0
    }
3814
0
  }
3815
3816
  // copy the noise if this is a flash
3817
0
  for (this_stats = first_stats + 2; this_stats < last_stats; this_stats++) {
3818
0
    if (this_stats->is_flash || (this_stats - 1)->is_flash ||
3819
0
        (this_stats - 2)->is_flash) {
3820
0
      int found = 0;
3821
0
      for (next_stats = this_stats + 1; next_stats < last_stats; next_stats++) {
3822
0
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3823
0
            (next_stats - 2)->is_flash)
3824
0
          continue;
3825
0
        found = 1;
3826
0
        this_stats->noise_var = next_stats->noise_var;
3827
0
        break;
3828
0
      }
3829
0
      if (found) continue;
3830
0
      for (next_stats = this_stats - 1; next_stats >= first_stats + 2;
3831
0
           next_stats--) {
3832
0
        if (next_stats->is_flash || (next_stats - 1)->is_flash ||
3833
0
            (next_stats - 2)->is_flash)
3834
0
          continue;
3835
0
        this_stats->noise_var = next_stats->noise_var;
3836
0
        break;
3837
0
      }
3838
0
    }
3839
0
  }
3840
3841
  // if we are at the first 2 frames, copy the noise
3842
0
  for (this_stats = first_stats;
3843
0
       this_stats < first_stats + 2 && (first_stats + 2) < last_stats;
3844
0
       this_stats++) {
3845
0
    this_stats->noise_var = (first_stats + 2)->noise_var;
3846
0
  }
3847
3848
0
  if (smooth_filter_noise(first_stats, last_stats) == -1) {
3849
0
    aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
3850
0
                       "Error allocating buffers in smooth_filter_noise()");
3851
0
  }
3852
0
}
3853
3854
// Estimate correlation coefficient of each frame with its previous frame.
3855
static void estimate_coeff(FIRSTPASS_STATS *first_stats,
3856
0
                           FIRSTPASS_STATS *last_stats) {
3857
0
  FIRSTPASS_STATS *this_stats;
3858
0
  for (this_stats = first_stats + 1; this_stats < last_stats; this_stats++) {
3859
0
    const double C =
3860
0
        sqrt(AOMMAX((this_stats - 1)->intra_error *
3861
0
                        (this_stats->intra_error - this_stats->coded_error),
3862
0
                    0.001));
3863
0
    const double cor_coeff =
3864
0
        C /
3865
0
        AOMMAX((this_stats - 1)->intra_error - this_stats->noise_var, 0.001);
3866
3867
0
    this_stats->cor_coeff =
3868
0
        cor_coeff *
3869
0
        sqrt(AOMMAX((this_stats - 1)->intra_error - this_stats->noise_var,
3870
0
                    0.001) /
3871
0
             AOMMAX(this_stats->intra_error - this_stats->noise_var, 0.001));
3872
    // clip correlation coefficient.
3873
0
    this_stats->cor_coeff = fclamp(this_stats->cor_coeff, 0.0, 1.0);
3874
0
  }
3875
0
  first_stats->cor_coeff = 1.0;
3876
0
}
3877
3878
static void get_one_pass_rt_lag_params(AV1_COMP *cpi, unsigned int frame_flags,
3879
0
                                       EncodeFrameParams *const frame_params) {
3880
0
  RATE_CONTROL *const rc = &cpi->rc;
3881
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3882
0
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3883
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3884
  // Check forced key frames.
3885
0
  const int frames_to_next_forced_key = detect_app_forced_key(cpi);
3886
0
  if (frames_to_next_forced_key == 0) {
3887
0
    rc->frames_to_key = 0;
3888
0
    frame_flags &= FRAMEFLAGS_KEY;
3889
0
  } else if (frames_to_next_forced_key > 0 &&
3890
0
             frames_to_next_forced_key < rc->frames_to_key) {
3891
0
    rc->frames_to_key = frames_to_next_forced_key;
3892
0
  }
3893
0
  frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
3894
0
  if (cpi->gf_frame_index < gf_group->size && !(frame_flags & FRAMEFLAGS_KEY)) {
3895
0
    av1_setup_target_rate(cpi);
3896
0
  }
3897
  // Keyframe processing.
3898
0
  if (rc->frames_to_key <= 0) {
3899
0
    const KeyFrameCfg *const kf_cfg = &oxcf->kf_cfg;
3900
0
    assert(rc->frames_to_key == 0);
3901
    // Define next KF group.
3902
0
    frame_params->frame_type = KEY_FRAME;
3903
0
    rc->frames_since_key = 0;
3904
    // Use arfs if possible.
3905
0
    p_rc->use_arf_in_this_kf_group = is_altref_enabled(
3906
0
        oxcf->gf_cfg.lag_in_frames, oxcf->gf_cfg.enable_auto_arf);
3907
    // Reset the GF group data structures.
3908
0
    av1_zero(*gf_group);
3909
0
    cpi->gf_frame_index = 0;
3910
    // KF is always a GF so clear frames till next gf counter.
3911
0
    rc->frames_till_gf_update_due = 0;
3912
0
    int num_frames_to_app_forced_key = detect_app_forced_key(cpi);
3913
0
    p_rc->this_key_frame_forced =
3914
0
        cpi->common.current_frame.frame_number != 0 && rc->frames_to_key == 0;
3915
0
    if (num_frames_to_app_forced_key != -1)
3916
0
      rc->frames_to_key = num_frames_to_app_forced_key;
3917
0
    else
3918
0
      rc->frames_to_key = AOMMAX(1, kf_cfg->key_freq_max);
3919
0
    correct_frames_to_key(cpi);
3920
0
    p_rc->kf_boost = DEFAULT_KF_BOOST;
3921
0
    gf_group->update_type[0] = KF_UPDATE;
3922
0
  }
3923
  // Define a new GF/ARF group. (Should always enter here for key frames).
3924
0
  if (cpi->gf_frame_index == gf_group->size) {
3925
0
    int max_gop_length =
3926
0
        (oxcf->gf_cfg.lag_in_frames >= 32)
3927
0
            ? AOMMIN(MAX_GF_INTERVAL, oxcf->gf_cfg.lag_in_frames -
3928
0
                                          oxcf->algo_cfg.arnr_max_frames / 2)
3929
0
            : MAX_GF_LENGTH_LAP;
3930
    // Limit the max gop length for the last gop in 1 pass setting.
3931
0
    max_gop_length = AOMMIN(max_gop_length, rc->frames_to_key);
3932
    // Go through source frames in lookahead buffer and compute source metrics:
3933
    // scene change, frame average source sad, etc.
3934
0
    int num_frames = 1;
3935
0
    int scene_change_gop_frame_index = 0;
3936
0
    rc->frame_source_sad_lag[0] = 0;
3937
0
    rc->avg_source_sad = 0;
3938
0
    for (int i = 1; i < max_gop_length; i++) {
3939
0
      EncodeFrameInput frame_input;
3940
0
      memset(&frame_input, 0, sizeof(frame_input));
3941
0
      struct lookahead_entry *e =
3942
0
          av1_lookahead_peek(cpi->ppi->lookahead, i, cpi->compressor_stage);
3943
0
      struct lookahead_entry *e_prev =
3944
0
          av1_lookahead_peek(cpi->ppi->lookahead, i - 1, cpi->compressor_stage);
3945
0
      if (e != NULL && e_prev != NULL) {
3946
0
        frame_input.source = &e->img;
3947
0
        frame_input.last_source = &e_prev->img;
3948
0
        rc->high_source_sad_lag[i] = -1;
3949
0
        rc->frame_source_sad_lag[i] = 0;
3950
0
        av1_rc_scene_detection_onepass_rt(cpi, &frame_input);
3951
0
        rc->high_source_sad_lag[i] = rc->high_source_sad;
3952
0
        rc->frame_source_sad_lag[i] = rc->frame_source_sad;
3953
0
        if (rc->high_source_sad_lag[i] == 1 && i > 1) {
3954
          // Scene change, so exit and constrain the gop to this frame.
3955
0
          scene_change_gop_frame_index = i;
3956
0
          break;
3957
0
        }
3958
0
        num_frames++;
3959
0
        rc->frame_source_sad_lag[0] += rc->frame_source_sad_lag[i];
3960
0
      }
3961
0
    }
3962
0
    if (scene_change_gop_frame_index > 0)
3963
0
      max_gop_length = AOMMIN(max_gop_length, scene_change_gop_frame_index);
3964
0
    rc->frame_source_sad_lag[0] = rc->frame_source_sad_lag[0] / num_frames;
3965
0
    calculate_gf_length(cpi, max_gop_length, MAX_NUM_GF_INTERVALS);
3966
0
    define_gf_group(cpi, frame_params, 0);
3967
0
    rc->frames_till_gf_update_due = p_rc->baseline_gf_interval;
3968
0
    frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
3969
0
    av1_setup_target_rate(cpi);
3970
    // Reset the source_sad parameters for the encoding.
3971
0
    rc->high_source_sad = 0;
3972
0
    rc->frame_source_sad = UINT64_MAX;
3973
0
    rc->avg_source_sad = 0;
3974
0
  }
3975
0
}
3976
3977
void av1_get_second_pass_params(AV1_COMP *cpi,
3978
                                EncodeFrameParams *const frame_params,
3979
0
                                unsigned int frame_flags) {
3980
0
  RATE_CONTROL *const rc = &cpi->rc;
3981
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3982
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3983
0
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3984
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3985
3986
0
  if (is_one_pass_rt_lag_params(cpi)) {
3987
0
    get_one_pass_rt_lag_params(cpi, frame_flags, frame_params);
3988
0
    return;
3989
0
  }
3990
3991
0
  if (cpi->ext_ratectrl.ready &&
3992
0
      (cpi->ext_ratectrl.funcs.rc_type & AOM_RC_GOP) != 0 &&
3993
0
      cpi->ext_ratectrl.funcs.get_gop_decision != NULL) {
3994
0
    frame_params->show_frame =
3995
0
        !(gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE ||
3996
0
          gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE);
3997
0
  }
3998
3999
0
  if (cpi->use_ducky_encode &&
4000
0
      cpi->ducky_encode_info.frame_info.gop_mode == DUCKY_ENCODE_GOP_MODE_RCL) {
4001
0
    frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
4002
0
    frame_params->show_frame =
4003
0
        !(gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE ||
4004
0
          gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE);
4005
0
    if (cpi->gf_frame_index == 0) {
4006
0
      av1_tf_info_reset(&cpi->ppi->tf_info);
4007
0
      av1_tf_info_filtering(&cpi->ppi->tf_info, cpi, gf_group);
4008
0
    }
4009
0
    return;
4010
0
  }
4011
4012
0
  if (cpi->common.current_frame.frame_number == 0 &&
4013
0
      cpi->ext_ratectrl.funcs.send_firstpass_stats != NULL) {
4014
0
    const aom_codec_err_t codec_status = av1_extrc_send_firstpass_stats(
4015
0
        &cpi->ext_ratectrl, &cpi->ppi->twopass.firstpass_info);
4016
0
    if (codec_status != AOM_CODEC_OK) {
4017
0
      aom_internal_error(cpi->common.error, codec_status,
4018
0
                         "av1_extrc_send_firstpass_stats() failed");
4019
0
    }
4020
0
  }
4021
4022
0
  const FIRSTPASS_STATS *const start_pos = cpi->twopass_frame.stats_in;
4023
0
  int update_total_stats = 0;
4024
4025
0
  if (is_stat_consumption_stage(cpi) && !cpi->twopass_frame.stats_in) return;
4026
4027
  // Check forced key frames.
4028
0
  const int frames_to_next_forced_key = detect_app_forced_key(cpi);
4029
0
  if (frames_to_next_forced_key == 0) {
4030
0
    rc->frames_to_key = 0;
4031
0
    frame_flags &= FRAMEFLAGS_KEY;
4032
0
  } else if (frames_to_next_forced_key > 0 &&
4033
0
             frames_to_next_forced_key < rc->frames_to_key) {
4034
0
    rc->frames_to_key = frames_to_next_forced_key;
4035
0
  }
4036
4037
0
  assert(cpi->twopass_frame.stats_in != NULL);
4038
0
  const int update_type = gf_group->update_type[cpi->gf_frame_index];
4039
0
  frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
4040
4041
0
  if (cpi->gf_frame_index < gf_group->size && !(frame_flags & FRAMEFLAGS_KEY)) {
4042
0
    assert(cpi->gf_frame_index < gf_group->size);
4043
4044
0
    av1_setup_target_rate(cpi);
4045
4046
    // If this is an arf frame then we dont want to read the stats file or
4047
    // advance the input pointer as we already have what we need.
4048
0
    if (update_type == ARF_UPDATE || update_type == INTNL_ARF_UPDATE) {
4049
0
      const FIRSTPASS_STATS *const this_frame_ptr =
4050
0
          read_frame_stats(twopass, &cpi->twopass_frame,
4051
0
                           gf_group->arf_src_offset[cpi->gf_frame_index]);
4052
0
      set_twopass_params_based_on_fp_stats(cpi, this_frame_ptr);
4053
0
      return;
4054
0
    }
4055
0
  }
4056
4057
0
  if (oxcf->rc_cfg.mode == AOM_Q)
4058
0
    rc->active_worst_quality = oxcf->rc_cfg.cq_level;
4059
4060
0
  if (cpi->gf_frame_index == gf_group->size) {
4061
0
    if (cpi->ppi->lap_enabled && cpi->ppi->p_rc.enable_scenecut_detection) {
4062
0
      const int num_frames_to_detect_scenecut = MAX_GF_LENGTH_LAP + 1;
4063
0
      const int frames_to_key = define_kf_interval(
4064
0
          cpi, &twopass->firstpass_info, num_frames_to_detect_scenecut,
4065
0
          /*search_start_idx=*/0);
4066
0
      if (frames_to_key != -1)
4067
0
        rc->frames_to_key = AOMMIN(rc->frames_to_key, frames_to_key);
4068
0
    }
4069
0
  }
4070
4071
0
  FIRSTPASS_STATS this_frame;
4072
0
  av1_zero(this_frame);
4073
  // call above fn
4074
0
  if (is_stat_consumption_stage(cpi)) {
4075
0
    if (cpi->gf_frame_index < gf_group->size || rc->frames_to_key == 0) {
4076
0
      process_first_pass_stats(cpi, &this_frame);
4077
0
      update_total_stats = 1;
4078
0
    }
4079
0
  } else {
4080
0
    rc->active_worst_quality = oxcf->rc_cfg.cq_level;
4081
0
  }
4082
4083
  // Keyframe and section processing.
4084
0
  FIRSTPASS_STATS this_frame_copy;
4085
0
  this_frame_copy = this_frame;
4086
0
  if (rc->frames_to_key <= 0) {
4087
0
    assert(rc->frames_to_key == 0);
4088
    // Define next KF group and assign bits to it.
4089
0
    frame_params->frame_type = KEY_FRAME;
4090
0
    find_next_key_frame(cpi, &this_frame);
4091
0
    this_frame = this_frame_copy;
4092
    // Mark prev gop arf source as unusable
4093
0
    cpi->ppi->tpl_data.prev_gop_arf_disp_order = -1;
4094
0
  }
4095
4096
0
  if (rc->frames_to_fwd_kf <= 0)
4097
0
    rc->frames_to_fwd_kf = oxcf->kf_cfg.fwd_kf_dist;
4098
4099
  // Define a new GF/ARF group. (Should always enter here for key frames).
4100
0
  if (cpi->gf_frame_index == gf_group->size) {
4101
0
    av1_tf_info_reset(&cpi->ppi->tf_info);
4102
#if CONFIG_BITRATE_ACCURACY && !CONFIG_THREE_PASS
4103
    vbr_rc_reset_gop_data(&cpi->vbr_rc_info);
4104
#endif  // CONFIG_BITRATE_ACCURACY
4105
0
    int max_gop_length =
4106
0
        (oxcf->gf_cfg.lag_in_frames >= 32)
4107
0
            ? AOMMIN(MAX_GF_INTERVAL, oxcf->gf_cfg.lag_in_frames -
4108
0
                                          oxcf->algo_cfg.arnr_max_frames / 2)
4109
0
            : MAX_GF_LENGTH_LAP;
4110
4111
    // Handle forward key frame when enabled.
4112
0
    if (oxcf->kf_cfg.fwd_kf_dist > 0)
4113
0
      max_gop_length = AOMMIN(rc->frames_to_fwd_kf + 1, max_gop_length);
4114
4115
    // Use the provided gop size in low delay setting
4116
0
    if (oxcf->gf_cfg.lag_in_frames == 0) max_gop_length = rc->max_gf_interval;
4117
4118
    // Limit the max gop length for the last gop in 1 pass setting.
4119
0
    max_gop_length = AOMMIN(max_gop_length, rc->frames_to_key);
4120
4121
    // Identify regions if needed.
4122
    // TODO(bohanli): identify regions for all stats available.
4123
0
    if (rc->frames_since_key == 0 || rc->frames_since_key == 1 ||
4124
0
        (p_rc->frames_till_regions_update - rc->frames_since_key <
4125
0
             rc->frames_to_key &&
4126
0
         p_rc->frames_till_regions_update - rc->frames_since_key <
4127
0
             max_gop_length + 1)) {
4128
      // how many frames we can analyze from this frame
4129
0
      int rest_frames =
4130
0
          AOMMIN(rc->frames_to_key, MAX_FIRSTPASS_ANALYSIS_FRAMES);
4131
0
      int available_frames = (int)(twopass->stats_buf_ctx->stats_in_end -
4132
0
                                   cpi->twopass_frame.stats_in);
4133
0
      if (!cpi->ppi->lap_enabled) {
4134
0
        available_frames += (rc->frames_since_key == 0);
4135
0
      }
4136
0
      rest_frames = AOMMIN(rest_frames, available_frames);
4137
0
      p_rc->frames_till_regions_update = rest_frames;
4138
4139
0
      int ret;
4140
0
      if (cpi->ppi->lap_enabled) {
4141
0
        mark_flashes(twopass->stats_buf_ctx->stats_in_start,
4142
0
                     twopass->stats_buf_ctx->stats_in_end);
4143
0
        estimate_noise(twopass->stats_buf_ctx->stats_in_start,
4144
0
                       twopass->stats_buf_ctx->stats_in_end, cpi->common.error);
4145
0
        estimate_coeff(twopass->stats_buf_ctx->stats_in_start,
4146
0
                       twopass->stats_buf_ctx->stats_in_end);
4147
0
        ret = identify_regions(cpi->twopass_frame.stats_in, rest_frames, 0,
4148
0
                               p_rc->regions, &p_rc->num_regions);
4149
0
      } else {
4150
0
        ret = identify_regions(
4151
0
            cpi->twopass_frame.stats_in - (rc->frames_since_key == 0),
4152
0
            rest_frames, 0, p_rc->regions, &p_rc->num_regions);
4153
0
      }
4154
0
      if (ret == -1) {
4155
0
        aom_internal_error(cpi->common.error, AOM_CODEC_MEM_ERROR,
4156
0
                           "Error allocating buffers in identify_regions");
4157
0
      }
4158
0
    }
4159
4160
0
    int cur_region_idx =
4161
0
        find_regions_index(p_rc->regions, p_rc->num_regions,
4162
0
                           rc->frames_since_key - p_rc->regions_offset);
4163
0
    if ((cur_region_idx >= 0 &&
4164
0
         p_rc->regions[cur_region_idx].type == SCENECUT_REGION) ||
4165
0
        rc->frames_since_key == 0) {
4166
      // If we start from a scenecut, then the last GOP's arf boost is not
4167
      // needed for this GOP.
4168
0
      cpi->ppi->gf_state.arf_gf_boost_lst = 0;
4169
0
    }
4170
4171
0
    int need_gf_len = 1;
4172
#if CONFIG_THREE_PASS
4173
    if (cpi->third_pass_ctx && oxcf->pass == AOM_RC_THIRD_PASS) {
4174
      // set up bitstream to read
4175
      if (!cpi->third_pass_ctx->input_file_name && oxcf->two_pass_output) {
4176
        cpi->third_pass_ctx->input_file_name = oxcf->two_pass_output;
4177
      }
4178
      av1_open_second_pass_log(cpi, 1);
4179
      THIRD_PASS_GOP_INFO *gop_info = &cpi->third_pass_ctx->gop_info;
4180
      // Read in GOP information from the second pass file.
4181
      av1_read_second_pass_gop_info(cpi->second_pass_log_stream, gop_info,
4182
                                    cpi->common.error);
4183
#if CONFIG_BITRATE_ACCURACY
4184
      TPL_INFO *tpl_info;
4185
      AOM_CHECK_MEM_ERROR(cpi->common.error, tpl_info,
4186
                          aom_malloc(sizeof(*tpl_info)));
4187
      av1_read_tpl_info(tpl_info, cpi->second_pass_log_stream,
4188
                        cpi->common.error);
4189
      aom_free(tpl_info);
4190
#if CONFIG_THREE_PASS
4191
      // TODO(angiebird): Put this part into a func
4192
      cpi->vbr_rc_info.cur_gop_idx++;
4193
#endif  // CONFIG_THREE_PASS
4194
#endif  // CONFIG_BITRATE_ACCURACY
4195
      // Read in third_pass_info from the bitstream.
4196
      av1_set_gop_third_pass(cpi->third_pass_ctx);
4197
      // Read in per-frame info from second-pass encoding
4198
      av1_read_second_pass_per_frame_info(
4199
          cpi->second_pass_log_stream, cpi->third_pass_ctx->frame_info,
4200
          gop_info->num_frames, cpi->common.error);
4201
4202
      p_rc->cur_gf_index = 0;
4203
      p_rc->gf_intervals[0] = cpi->third_pass_ctx->gop_info.gf_length;
4204
      need_gf_len = 0;
4205
    }
4206
#endif  // CONFIG_THREE_PASS
4207
4208
0
    if (need_gf_len) {
4209
      // If we cannot obtain GF group length from second_pass_file
4210
      // TODO(jingning): Resolve the redundant calls here.
4211
0
      if (rc->intervals_till_gf_calculate_due == 0 || 1) {
4212
0
        calculate_gf_length(cpi, max_gop_length, MAX_NUM_GF_INTERVALS);
4213
0
      }
4214
0
      if (max_gop_length > 16 && oxcf->algo_cfg.enable_tpl_model &&
4215
0
          oxcf->gf_cfg.lag_in_frames >= 32 &&
4216
0
          cpi->sf.tpl_sf.gop_length_decision_method != 2) {
4217
0
        int this_idx = rc->frames_since_key +
4218
0
                       p_rc->gf_intervals[p_rc->cur_gf_index] -
4219
0
                       p_rc->regions_offset - 1;
4220
0
        int this_region =
4221
0
            find_regions_index(p_rc->regions, p_rc->num_regions, this_idx);
4222
0
        int next_region =
4223
0
            find_regions_index(p_rc->regions, p_rc->num_regions, this_idx + 1);
4224
        // TODO(angiebird): Figure out why this_region and next_region are -1 in
4225
        // unit test like AltRefFramePresenceTestLarge (aomedia:3134)
4226
0
        int is_last_scenecut =
4227
0
            p_rc->gf_intervals[p_rc->cur_gf_index] >= rc->frames_to_key ||
4228
0
            (this_region != -1 &&
4229
0
             p_rc->regions[this_region].type == SCENECUT_REGION) ||
4230
0
            (next_region != -1 &&
4231
0
             p_rc->regions[next_region].type == SCENECUT_REGION);
4232
4233
0
        int ori_gf_int = p_rc->gf_intervals[p_rc->cur_gf_index];
4234
4235
0
        if (p_rc->gf_intervals[p_rc->cur_gf_index] > 16 &&
4236
0
            rc->min_gf_interval <= 16) {
4237
          // The calculate_gf_length function is previously used with
4238
          // max_gop_length = 32 with look-ahead gf intervals.
4239
0
          define_gf_group(cpi, frame_params, 0);
4240
0
          av1_tf_info_filtering(&cpi->ppi->tf_info, cpi, gf_group);
4241
0
          this_frame = this_frame_copy;
4242
4243
0
          if (is_shorter_gf_interval_better(cpi, frame_params)) {
4244
            // A shorter gf interval is better.
4245
            // TODO(jingning): Remove redundant computations here.
4246
0
            max_gop_length = 16;
4247
0
            calculate_gf_length(cpi, max_gop_length, 1);
4248
0
            if (is_last_scenecut &&
4249
0
                (ori_gf_int - p_rc->gf_intervals[p_rc->cur_gf_index] < 4)) {
4250
0
              p_rc->gf_intervals[p_rc->cur_gf_index] = ori_gf_int;
4251
0
            }
4252
0
          }
4253
0
        }
4254
0
      }
4255
0
    }
4256
4257
0
    define_gf_group(cpi, frame_params, 0);
4258
4259
0
    if (gf_group->update_type[cpi->gf_frame_index] != ARF_UPDATE &&
4260
0
        rc->frames_since_key > 0)
4261
0
      process_first_pass_stats(cpi, &this_frame);
4262
4263
0
    define_gf_group(cpi, frame_params, 1);
4264
4265
#if CONFIG_THREE_PASS
4266
    // write gop info if needed for third pass. Per-frame info is written after
4267
    // each frame is encoded.
4268
    av1_write_second_pass_gop_info(cpi);
4269
#endif  // CONFIG_THREE_PASS
4270
4271
0
    av1_tf_info_filtering(&cpi->ppi->tf_info, cpi, gf_group);
4272
4273
0
    rc->frames_till_gf_update_due = p_rc->baseline_gf_interval;
4274
0
    assert(cpi->gf_frame_index == 0);
4275
#if ARF_STATS_OUTPUT
4276
    {
4277
      FILE *fpfile;
4278
      fpfile = fopen("arf.stt", "a");
4279
      ++arf_count;
4280
      fprintf(fpfile, "%10d %10d %10d %10d %10d\n",
4281
              cpi->common.current_frame.frame_number,
4282
              rc->frames_till_gf_update_due, cpi->ppi->p_rc.kf_boost, arf_count,
4283
              p_rc->gfu_boost);
4284
4285
      fclose(fpfile);
4286
    }
4287
#endif
4288
0
  }
4289
0
  assert(cpi->gf_frame_index < gf_group->size);
4290
4291
0
  if (gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE ||
4292
0
      gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE) {
4293
0
    reset_fpf_position(&cpi->twopass_frame, start_pos);
4294
4295
0
    const FIRSTPASS_STATS *const this_frame_ptr =
4296
0
        read_frame_stats(twopass, &cpi->twopass_frame,
4297
0
                         gf_group->arf_src_offset[cpi->gf_frame_index]);
4298
0
    set_twopass_params_based_on_fp_stats(cpi, this_frame_ptr);
4299
0
  } else {
4300
    // Back up this frame's stats for updating total stats during post encode.
4301
0
    cpi->twopass_frame.this_frame = update_total_stats ? start_pos : NULL;
4302
0
  }
4303
4304
0
  frame_params->frame_type = gf_group->frame_type[cpi->gf_frame_index];
4305
0
  av1_setup_target_rate(cpi);
4306
0
}
4307
4308
0
void av1_init_second_pass(AV1_COMP *cpi) {
4309
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
4310
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
4311
0
  FRAME_INFO *const frame_info = &cpi->frame_info;
4312
0
  double frame_rate;
4313
0
  FIRSTPASS_STATS *stats;
4314
4315
0
  if (!twopass->stats_buf_ctx->stats_in_end) return;
4316
4317
0
  mark_flashes(twopass->stats_buf_ctx->stats_in_start,
4318
0
               twopass->stats_buf_ctx->stats_in_end);
4319
0
  estimate_noise(twopass->stats_buf_ctx->stats_in_start,
4320
0
                 twopass->stats_buf_ctx->stats_in_end, cpi->common.error);
4321
0
  estimate_coeff(twopass->stats_buf_ctx->stats_in_start,
4322
0
                 twopass->stats_buf_ctx->stats_in_end);
4323
4324
0
  stats = twopass->stats_buf_ctx->total_stats;
4325
4326
0
  *stats = *twopass->stats_buf_ctx->stats_in_end;
4327
0
  *twopass->stats_buf_ctx->total_left_stats = *stats;
4328
4329
0
  frame_rate = 10000000.0 * stats->count / stats->duration;
4330
  // Each frame can have a different duration, as the frame rate in the source
4331
  // isn't guaranteed to be constant. The frame rate prior to the first frame
4332
  // encoded in the second pass is a guess. However, the sum duration is not.
4333
  // It is calculated based on the actual durations of all frames from the
4334
  // first pass.
4335
0
  av1_new_framerate(cpi, frame_rate);
4336
0
  twopass->bits_left =
4337
0
      (int64_t)(stats->duration * oxcf->rc_cfg.target_bandwidth / 10000000.0);
4338
4339
#if CONFIG_BITRATE_ACCURACY
4340
  av1_vbr_rc_init(&cpi->vbr_rc_info, twopass->bits_left,
4341
                  (int)round(stats->count));
4342
#endif
4343
4344
#if CONFIG_RATECTRL_LOG
4345
  rc_log_init(&cpi->rc_log);
4346
#endif
4347
4348
  // This variable monitors how far behind the second ref update is lagging.
4349
0
  twopass->sr_update_lag = 1;
4350
4351
  // Scan the first pass file and calculate a modified total error based upon
4352
  // the bias/power function used to allocate bits.
4353
0
  {
4354
0
    const double avg_error =
4355
0
        stats->coded_error / DOUBLE_DIVIDE_CHECK(stats->count);
4356
0
    const FIRSTPASS_STATS *s = cpi->twopass_frame.stats_in;
4357
0
    double modified_error_total = 0.0;
4358
0
    twopass->modified_error_min =
4359
0
        (avg_error * oxcf->rc_cfg.vbrmin_section) / 100;
4360
0
    twopass->modified_error_max =
4361
0
        (avg_error * oxcf->rc_cfg.vbrmax_section) / 100;
4362
0
    while (s < twopass->stats_buf_ctx->stats_in_end) {
4363
0
      modified_error_total +=
4364
0
          calculate_modified_err(frame_info, twopass, oxcf, s);
4365
0
      ++s;
4366
0
    }
4367
0
    twopass->modified_error_left = modified_error_total;
4368
0
  }
4369
4370
  // Reset the vbr bits off target counters
4371
0
  cpi->ppi->p_rc.vbr_bits_off_target = 0;
4372
0
  cpi->ppi->p_rc.vbr_bits_off_target_fast = 0;
4373
4374
0
  cpi->ppi->p_rc.rate_error_estimate = 0;
4375
4376
  // Static sequence monitor variables.
4377
0
  twopass->kf_zeromotion_pct = 100;
4378
0
  twopass->last_kfgroup_zeromotion_pct = 100;
4379
4380
  // Initialize bits per macro_block estimate correction factor.
4381
0
  twopass->bpm_factor = 1.0;
4382
  // Initialize actual and target bits counters for ARF groups so that
4383
  // at the start we have a neutral bpm adjustment.
4384
0
  twopass->rolling_arf_group_target_bits = 1;
4385
0
  twopass->rolling_arf_group_actual_bits = 1;
4386
0
}
4387
4388
0
void av1_init_single_pass_lap(AV1_COMP *cpi) {
4389
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
4390
4391
0
  if (!twopass->stats_buf_ctx->stats_in_end) return;
4392
4393
  // This variable monitors how far behind the second ref update is lagging.
4394
0
  twopass->sr_update_lag = 1;
4395
4396
0
  twopass->bits_left = 0;
4397
0
  twopass->modified_error_min = 0.0;
4398
0
  twopass->modified_error_max = 0.0;
4399
0
  twopass->modified_error_left = 0.0;
4400
4401
  // Reset the vbr bits off target counters
4402
0
  cpi->ppi->p_rc.vbr_bits_off_target = 0;
4403
0
  cpi->ppi->p_rc.vbr_bits_off_target_fast = 0;
4404
4405
0
  cpi->ppi->p_rc.rate_error_estimate = 0;
4406
4407
  // Static sequence monitor variables.
4408
0
  twopass->kf_zeromotion_pct = 100;
4409
0
  twopass->last_kfgroup_zeromotion_pct = 100;
4410
4411
  // Initialize bits per macro_block estimate correction factor.
4412
0
  twopass->bpm_factor = 1.0;
4413
  // Initialize actual and target bits counters for ARF groups so that
4414
  // at the start we have a neutral bpm adjustment.
4415
0
  twopass->rolling_arf_group_target_bits = 1;
4416
0
  twopass->rolling_arf_group_actual_bits = 1;
4417
0
}
4418
4419
0
#define MINQ_ADJ_LIMIT 48
4420
0
#define MINQ_ADJ_LIMIT_CQ 20
4421
0
#define HIGH_UNDERSHOOT_RATIO 2
4422
0
void av1_twopass_postencode_update(AV1_COMP *cpi) {
4423
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
4424
0
  RATE_CONTROL *const rc = &cpi->rc;
4425
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
4426
0
  const RateControlCfg *const rc_cfg = &cpi->oxcf.rc_cfg;
4427
4428
  // Increment the stats_in pointer.
4429
0
  if (is_stat_consumption_stage(cpi) &&
4430
0
      !(cpi->use_ducky_encode && cpi->ducky_encode_info.frame_info.gop_mode ==
4431
0
                                     DUCKY_ENCODE_GOP_MODE_RCL) &&
4432
0
      (cpi->gf_frame_index < cpi->ppi->gf_group.size ||
4433
0
       rc->frames_to_key == 0)) {
4434
0
    const int update_type = cpi->ppi->gf_group.update_type[cpi->gf_frame_index];
4435
0
    if (update_type != ARF_UPDATE && update_type != INTNL_ARF_UPDATE) {
4436
0
      FIRSTPASS_STATS this_frame;
4437
0
      assert(cpi->twopass_frame.stats_in >
4438
0
             twopass->stats_buf_ctx->stats_in_start);
4439
0
      --cpi->twopass_frame.stats_in;
4440
0
      if (cpi->ppi->lap_enabled) {
4441
0
        input_stats_lap(twopass, &cpi->twopass_frame, &this_frame);
4442
0
      } else {
4443
0
        input_stats(twopass, &cpi->twopass_frame, &this_frame);
4444
0
      }
4445
0
    } else if (cpi->ppi->lap_enabled) {
4446
0
      cpi->twopass_frame.stats_in = twopass->stats_buf_ctx->stats_in_start;
4447
0
    }
4448
0
  }
4449
4450
  // VBR correction is done through rc->vbr_bits_off_target. Based on the
4451
  // sign of this value, a limited % adjustment is made to the target rate
4452
  // of subsequent frames, to try and push it back towards 0. This method
4453
  // is designed to prevent extreme behaviour at the end of a clip
4454
  // or group of frames.
4455
0
  p_rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
4456
0
  twopass->bits_left = AOMMAX(twopass->bits_left - rc->base_frame_target, 0);
4457
4458
0
  if (cpi->do_update_vbr_bits_off_target_fast) {
4459
    // Subtract current frame's fast_extra_bits.
4460
0
    p_rc->vbr_bits_off_target_fast -= rc->frame_level_fast_extra_bits;
4461
0
    rc->frame_level_fast_extra_bits = 0;
4462
0
  }
4463
4464
  // Target vs actual bits for this arf group.
4465
0
  if (twopass->rolling_arf_group_target_bits >
4466
0
      INT_MAX - rc->base_frame_target) {
4467
0
    twopass->rolling_arf_group_target_bits = INT_MAX;
4468
0
  } else {
4469
0
    twopass->rolling_arf_group_target_bits += rc->base_frame_target;
4470
0
  }
4471
0
  twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
4472
4473
  // Calculate the pct rc error.
4474
0
  if (p_rc->total_actual_bits) {
4475
0
    p_rc->rate_error_estimate =
4476
0
        (int)((p_rc->vbr_bits_off_target * 100) / p_rc->total_actual_bits);
4477
0
    p_rc->rate_error_estimate = clamp(p_rc->rate_error_estimate, -100, 100);
4478
0
  } else {
4479
0
    p_rc->rate_error_estimate = 0;
4480
0
  }
4481
4482
#if CONFIG_FPMT_TEST
4483
  /* The variables temp_vbr_bits_off_target, temp_bits_left,
4484
   * temp_rolling_arf_group_target_bits, temp_rolling_arf_group_actual_bits
4485
   * temp_rate_error_estimate are introduced for quality simulation purpose,
4486
   * it retains the value previous to the parallel encode frames. The
4487
   * variables are updated based on the update flag.
4488
   *
4489
   * If there exist show_existing_frames between parallel frames, then to
4490
   * retain the temp state do not update it. */
4491
  const int simulate_parallel_frame =
4492
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
4493
  int show_existing_between_parallel_frames =
4494
      (cpi->ppi->gf_group.update_type[cpi->gf_frame_index] ==
4495
           INTNL_OVERLAY_UPDATE &&
4496
       cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index + 1] == 2);
4497
4498
  if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
4499
      simulate_parallel_frame) {
4500
    cpi->ppi->p_rc.temp_vbr_bits_off_target = p_rc->vbr_bits_off_target;
4501
    cpi->ppi->p_rc.temp_bits_left = twopass->bits_left;
4502
    cpi->ppi->p_rc.temp_rolling_arf_group_target_bits =
4503
        twopass->rolling_arf_group_target_bits;
4504
    cpi->ppi->p_rc.temp_rolling_arf_group_actual_bits =
4505
        twopass->rolling_arf_group_actual_bits;
4506
    cpi->ppi->p_rc.temp_rate_error_estimate = p_rc->rate_error_estimate;
4507
  }
4508
#endif
4509
  // Update the active best quality pyramid.
4510
0
  if (!rc->is_src_frame_alt_ref) {
4511
0
    const int pyramid_level =
4512
0
        cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index];
4513
0
    int i;
4514
0
    for (i = pyramid_level; i <= MAX_ARF_LAYERS; ++i) {
4515
0
      p_rc->active_best_quality[i] = cpi->common.quant_params.base_qindex;
4516
#if CONFIG_TUNE_VMAF
4517
      if (cpi->vmaf_info.original_qindex != -1 &&
4518
          is_vmaf_tuning_mode(cpi->oxcf.tune_cfg.tuning)) {
4519
        p_rc->active_best_quality[i] = cpi->vmaf_info.original_qindex;
4520
      }
4521
#endif
4522
0
    }
4523
0
  }
4524
4525
#if 0
4526
  {
4527
    AV1_COMMON *cm = &cpi->common;
4528
    FILE *fpfile;
4529
    fpfile = fopen("details.stt", "a");
4530
    fprintf(fpfile,
4531
            "%10d %10d %10d %10" PRId64 " %10" PRId64
4532
            " %10d %10d %10d %10.4lf %10.4lf %10.4lf %10.4lf\n",
4533
            cm->current_frame.frame_number, rc->base_frame_target,
4534
            rc->projected_frame_size, rc->total_actual_bits,
4535
            rc->vbr_bits_off_target, p_rc->rate_error_estimate,
4536
            twopass->rolling_arf_group_target_bits,
4537
            twopass->rolling_arf_group_actual_bits,
4538
            (double)twopass->rolling_arf_group_actual_bits /
4539
                (double)twopass->rolling_arf_group_target_bits,
4540
            twopass->bpm_factor,
4541
            av1_convert_qindex_to_q(cpi->common.quant_params.base_qindex,
4542
                                    cm->seq_params->bit_depth),
4543
            av1_convert_qindex_to_q(rc->active_worst_quality,
4544
                                    cm->seq_params->bit_depth));
4545
    fclose(fpfile);
4546
  }
4547
#endif
4548
4549
0
  if (cpi->common.current_frame.frame_type != KEY_FRAME) {
4550
0
    twopass->kf_group_bits -= rc->base_frame_target;
4551
0
    twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
4552
0
  }
4553
0
  twopass->kf_group_bits = AOMMAX(twopass->kf_group_bits, 0);
4554
4555
  // If the rate control is drifting consider adjustment to min or maxq.
4556
0
  if ((rc_cfg->mode != AOM_Q) && !cpi->rc.is_src_frame_alt_ref &&
4557
0
      (p_rc->rolling_target_bits > 0)) {
4558
0
    int minq_adj_limit;
4559
0
    int maxq_adj_limit;
4560
0
    minq_adj_limit =
4561
0
        (rc_cfg->mode == AOM_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
4562
0
    maxq_adj_limit = rc->worst_quality - rc->active_worst_quality;
4563
4564
    // Undershoot
4565
0
    if ((rc_cfg->under_shoot_pct < 100) &&
4566
0
        (p_rc->rolling_actual_bits < p_rc->rolling_target_bits)) {
4567
0
      int pct_error =
4568
0
          ((p_rc->rolling_target_bits - p_rc->rolling_actual_bits) * 100) /
4569
0
          p_rc->rolling_target_bits;
4570
4571
0
      if ((pct_error >= rc_cfg->under_shoot_pct) &&
4572
0
          (p_rc->rate_error_estimate > 0)) {
4573
0
        twopass->extend_minq += 1;
4574
0
      }
4575
0
      twopass->extend_maxq -= 1;
4576
      // Overshoot
4577
0
    } else if ((rc_cfg->over_shoot_pct <= 100) &&
4578
0
               (p_rc->rolling_actual_bits > p_rc->rolling_target_bits)) {
4579
0
      int pct_error =
4580
0
          ((p_rc->rolling_actual_bits - p_rc->rolling_target_bits) * 100) /
4581
0
          p_rc->rolling_target_bits;
4582
4583
0
      if ((pct_error >= rc_cfg->over_shoot_pct) &&
4584
0
          (p_rc->rate_error_estimate < 0)) {
4585
0
        twopass->extend_maxq += 1;
4586
0
      }
4587
0
      twopass->extend_minq -= 1;
4588
0
    } else {
4589
      // Adjustment for extreme local overshoot.
4590
      // Only applies when normal adjustment above is not used (e.g.
4591
      // when threshold is set to 100).
4592
0
      if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
4593
0
          rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
4594
0
        ++twopass->extend_maxq;
4595
      // Unwind extreme overshoot adjustment.
4596
0
      else if (p_rc->rolling_target_bits > p_rc->rolling_actual_bits)
4597
0
        --twopass->extend_maxq;
4598
0
    }
4599
0
    twopass->extend_minq =
4600
0
        clamp(twopass->extend_minq, -minq_adj_limit, minq_adj_limit);
4601
0
    twopass->extend_maxq = clamp(twopass->extend_maxq, 0, maxq_adj_limit);
4602
4603
    // If there is a big and undexpected undershoot then feed the extra
4604
    // bits back in quickly. One situation where this may happen is if a
4605
    // frame is unexpectedly almost perfectly predicted by the ARF or GF
4606
    // but not very well predcited by the previous frame.
4607
0
    if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
4608
0
#if CONFIG_AV1_HIGHBITDEPTH
4609
0
      if (cpi->common.seq_params->bit_depth > 8 &&
4610
0
          cpi->oxcf.algo_cfg.sharpness == 3 && p_rc->vbr_bits_off_target < 0) {
4611
0
        p_rc->vbr_bits_off_target_fast = 0;
4612
0
      } else
4613
0
#endif
4614
0
      {
4615
0
        int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
4616
0
        if (rc->projected_frame_size < fast_extra_thresh) {
4617
0
          p_rc->vbr_bits_off_target_fast +=
4618
0
              fast_extra_thresh - rc->projected_frame_size;
4619
0
          p_rc->vbr_bits_off_target_fast =
4620
0
              AOMMIN(p_rc->vbr_bits_off_target_fast,
4621
0
                     (4 * (int64_t)rc->avg_frame_bandwidth));
4622
0
        }
4623
0
      }
4624
0
    }
4625
4626
#if CONFIG_FPMT_TEST
4627
    if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
4628
        simulate_parallel_frame) {
4629
      cpi->ppi->p_rc.temp_vbr_bits_off_target_fast =
4630
          p_rc->vbr_bits_off_target_fast;
4631
      cpi->ppi->p_rc.temp_extend_minq = twopass->extend_minq;
4632
      cpi->ppi->p_rc.temp_extend_maxq = twopass->extend_maxq;
4633
    }
4634
#endif
4635
0
  }
4636
4637
  // Update the frame probabilities obtained from parallel encode frames
4638
0
  FrameProbInfo *const frame_probs = &cpi->ppi->frame_probs;
4639
#if CONFIG_FPMT_TEST
4640
  /* The variable temp_active_best_quality is introduced only for quality
4641
   * simulation purpose, it retains the value previous to the parallel
4642
   * encode frames. The variable is updated based on the update flag.
4643
   *
4644
   * If there exist show_existing_frames between parallel frames, then to
4645
   * retain the temp state do not update it. */
4646
  if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
4647
      simulate_parallel_frame) {
4648
    int i;
4649
    const int pyramid_level =
4650
        cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index];
4651
    if (!rc->is_src_frame_alt_ref) {
4652
      for (i = pyramid_level; i <= MAX_ARF_LAYERS; ++i)
4653
        cpi->ppi->p_rc.temp_active_best_quality[i] =
4654
            p_rc->active_best_quality[i];
4655
    }
4656
  }
4657
4658
  // Update the frame probabilities obtained from parallel encode frames
4659
  FrameProbInfo *const temp_frame_probs_simulation =
4660
      simulate_parallel_frame ? &cpi->ppi->temp_frame_probs_simulation
4661
                              : frame_probs;
4662
  FrameProbInfo *const temp_frame_probs =
4663
      simulate_parallel_frame ? &cpi->ppi->temp_frame_probs : NULL;
4664
#endif
4665
0
  int i, j, loop;
4666
  // Sequentially do average on temp_frame_probs_simulation which holds
4667
  // probabilities of last frame before parallel encode
4668
0
  for (loop = 0; loop <= cpi->num_frame_recode; loop++) {
4669
    // Sequentially update tx_type_probs
4670
0
    if (cpi->do_update_frame_probs_txtype[loop] &&
4671
0
        (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)) {
4672
0
      const FRAME_UPDATE_TYPE update_type =
4673
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4674
0
      for (i = 0; i < TX_SIZES_ALL; i++) {
4675
0
        int left = 1024;
4676
4677
0
        for (j = TX_TYPES - 1; j >= 0; j--) {
4678
0
          const int new_prob =
4679
0
              cpi->frame_new_probs[loop].tx_type_probs[update_type][i][j];
4680
#if CONFIG_FPMT_TEST
4681
          int prob =
4682
              (temp_frame_probs_simulation->tx_type_probs[update_type][i][j] +
4683
               new_prob) >>
4684
              1;
4685
          left -= prob;
4686
          if (j == 0) prob += left;
4687
          temp_frame_probs_simulation->tx_type_probs[update_type][i][j] = prob;
4688
#else
4689
0
          int prob =
4690
0
              (frame_probs->tx_type_probs[update_type][i][j] + new_prob) >> 1;
4691
0
          left -= prob;
4692
0
          if (j == 0) prob += left;
4693
0
          frame_probs->tx_type_probs[update_type][i][j] = prob;
4694
0
#endif
4695
0
        }
4696
0
      }
4697
0
    }
4698
4699
    // Sequentially update obmc_probs
4700
0
    if (cpi->do_update_frame_probs_obmc[loop] &&
4701
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
4702
0
      const FRAME_UPDATE_TYPE update_type =
4703
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4704
4705
0
      for (i = 0; i < BLOCK_SIZES_ALL; i++) {
4706
0
        const int new_prob =
4707
0
            cpi->frame_new_probs[loop].obmc_probs[update_type][i];
4708
#if CONFIG_FPMT_TEST
4709
        temp_frame_probs_simulation->obmc_probs[update_type][i] =
4710
            (temp_frame_probs_simulation->obmc_probs[update_type][i] +
4711
             new_prob) >>
4712
            1;
4713
#else
4714
0
        frame_probs->obmc_probs[update_type][i] =
4715
0
            (frame_probs->obmc_probs[update_type][i] + new_prob) >> 1;
4716
0
#endif
4717
0
      }
4718
0
    }
4719
4720
    // Sequentially update warped_probs
4721
0
    if (cpi->do_update_frame_probs_warp[loop] &&
4722
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
4723
0
      const FRAME_UPDATE_TYPE update_type =
4724
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4725
0
      const int new_prob = cpi->frame_new_probs[loop].warped_probs[update_type];
4726
#if CONFIG_FPMT_TEST
4727
      temp_frame_probs_simulation->warped_probs[update_type] =
4728
          (temp_frame_probs_simulation->warped_probs[update_type] + new_prob) >>
4729
          1;
4730
#else
4731
0
      frame_probs->warped_probs[update_type] =
4732
0
          (frame_probs->warped_probs[update_type] + new_prob) >> 1;
4733
0
#endif
4734
0
    }
4735
4736
    // Sequentially update switchable_interp_probs
4737
0
    if (cpi->do_update_frame_probs_interpfilter[loop] &&
4738
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
4739
0
      const FRAME_UPDATE_TYPE update_type =
4740
0
          get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
4741
4742
0
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4743
0
        int left = 1536;
4744
4745
0
        for (j = SWITCHABLE_FILTERS - 1; j >= 0; j--) {
4746
0
          const int new_prob = cpi->frame_new_probs[loop]
4747
0
                                   .switchable_interp_probs[update_type][i][j];
4748
#if CONFIG_FPMT_TEST
4749
          int prob = (temp_frame_probs_simulation
4750
                          ->switchable_interp_probs[update_type][i][j] +
4751
                      new_prob) >>
4752
                     1;
4753
          left -= prob;
4754
          if (j == 0) prob += left;
4755
4756
          temp_frame_probs_simulation
4757
              ->switchable_interp_probs[update_type][i][j] = prob;
4758
#else
4759
0
          int prob = (frame_probs->switchable_interp_probs[update_type][i][j] +
4760
0
                      new_prob) >>
4761
0
                     1;
4762
0
          left -= prob;
4763
0
          if (j == 0) prob += left;
4764
0
          frame_probs->switchable_interp_probs[update_type][i][j] = prob;
4765
0
#endif
4766
0
        }
4767
0
      }
4768
0
    }
4769
0
  }
4770
4771
#if CONFIG_FPMT_TEST
4772
  // Copying temp_frame_probs_simulation to temp_frame_probs based on
4773
  // the flag
4774
  if (cpi->do_frame_data_update &&
4775
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
4776
      simulate_parallel_frame) {
4777
    for (int update_type_idx = 0; update_type_idx < FRAME_UPDATE_TYPES;
4778
         update_type_idx++) {
4779
      for (i = 0; i < BLOCK_SIZES_ALL; i++) {
4780
        temp_frame_probs->obmc_probs[update_type_idx][i] =
4781
            temp_frame_probs_simulation->obmc_probs[update_type_idx][i];
4782
      }
4783
      temp_frame_probs->warped_probs[update_type_idx] =
4784
          temp_frame_probs_simulation->warped_probs[update_type_idx];
4785
      for (i = 0; i < TX_SIZES_ALL; i++) {
4786
        for (j = 0; j < TX_TYPES; j++) {
4787
          temp_frame_probs->tx_type_probs[update_type_idx][i][j] =
4788
              temp_frame_probs_simulation->tx_type_probs[update_type_idx][i][j];
4789
        }
4790
      }
4791
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4792
        for (j = 0; j < SWITCHABLE_FILTERS; j++) {
4793
          temp_frame_probs->switchable_interp_probs[update_type_idx][i][j] =
4794
              temp_frame_probs_simulation
4795
                  ->switchable_interp_probs[update_type_idx][i][j];
4796
        }
4797
      }
4798
    }
4799
  }
4800
#endif
4801
  // Update framerate obtained from parallel encode frames
4802
0
  if (cpi->common.show_frame &&
4803
0
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
4804
0
    cpi->framerate = cpi->new_framerate;
4805
#if CONFIG_FPMT_TEST
4806
  // SIMULATION PURPOSE
4807
  int show_existing_between_parallel_frames_cndn =
4808
      (cpi->ppi->gf_group.update_type[cpi->gf_frame_index] ==
4809
           INTNL_OVERLAY_UPDATE &&
4810
       cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index + 1] == 2);
4811
  if (cpi->common.show_frame && !show_existing_between_parallel_frames_cndn &&
4812
      cpi->do_frame_data_update && simulate_parallel_frame)
4813
    cpi->temp_framerate = cpi->framerate;
4814
#endif
4815
0
}