Coverage Report

Created: 2026-07-25 07:03

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