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