Coverage Report

Created: 2025-06-22 08:04

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