1 /*
2  * Copyright (c) 2019, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include <stdint.h>
13 
14 #include "config/aom_config.h"
15 #include "config/aom_scale_rtcd.h"
16 
17 #include "aom/aom_codec.h"
18 #include "aom/aom_encoder.h"
19 
20 #include "aom_ports/system_state.h"
21 
22 #include "av1/common/av1_common_int.h"
23 
24 #include "av1/encoder/encoder.h"
25 #include "av1/encoder/firstpass.h"
26 #include "av1/encoder/gop_structure.h"
27 #include "av1/encoder/pass2_strategy.h"
28 #include "av1/encoder/ratectrl.h"
29 #include "av1/encoder/tpl_model.h"
30 #include "av1/encoder/use_flat_gop_model_params.h"
31 #include "av1/encoder/encode_strategy.h"
32 
33 #define DEFAULT_KF_BOOST 2300
34 #define DEFAULT_GF_BOOST 2000
35 #define GROUP_ADAPTIVE_MAXQ 1
36 static void init_gf_stats(GF_GROUP_STATS *gf_stats);
37 
38 // Calculate an active area of the image that discounts formatting
39 // bars and partially discounts other 0 energy areas.
40 #define MIN_ACTIVE_AREA 0.5
41 #define MAX_ACTIVE_AREA 1.0
calculate_active_area(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame)42 static double calculate_active_area(const FRAME_INFO *frame_info,
43                                     const FIRSTPASS_STATS *this_frame) {
44   const double active_pct =
45       1.0 -
46       ((this_frame->intra_skip_pct / 2) +
47        ((this_frame->inactive_zone_rows * 2) / (double)frame_info->mb_rows));
48   return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
49 }
50 
51 // Calculate a modified Error used in distributing bits between easier and
52 // harder frames.
53 #define ACT_AREA_CORRECTION 0.5
calculate_modified_err(const FRAME_INFO * frame_info,const TWO_PASS * twopass,const AV1EncoderConfig * oxcf,const FIRSTPASS_STATS * this_frame)54 static double calculate_modified_err(const FRAME_INFO *frame_info,
55                                      const TWO_PASS *twopass,
56                                      const AV1EncoderConfig *oxcf,
57                                      const FIRSTPASS_STATS *this_frame) {
58   const FIRSTPASS_STATS *const stats = twopass->stats_buf_ctx->total_stats;
59   if (stats == NULL) {
60     return 0;
61   }
62   const double av_weight = stats->weight / stats->count;
63   const double av_err = (stats->coded_error * av_weight) / stats->count;
64   double modified_error =
65       av_err * pow(this_frame->coded_error * this_frame->weight /
66                        DOUBLE_DIVIDE_CHECK(av_err),
67                    oxcf->two_pass_vbrbias / 100.0);
68 
69   // Correction for active area. Frames with a reduced active area
70   // (eg due to formatting bars) have a higher error per mb for the
71   // remaining active MBs. The correction here assumes that coding
72   // 0.5N blocks of complexity 2X is a little easier than coding N
73   // blocks of complexity X.
74   modified_error *=
75       pow(calculate_active_area(frame_info, this_frame), ACT_AREA_CORRECTION);
76 
77   return fclamp(modified_error, twopass->modified_error_min,
78                 twopass->modified_error_max);
79 }
80 
81 // Resets the first pass file to the given position using a relative seek from
82 // the current position.
reset_fpf_position(TWO_PASS * p,const FIRSTPASS_STATS * position)83 static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
84   p->stats_in = position;
85 }
86 
input_stats(TWO_PASS * p,FIRSTPASS_STATS * fps)87 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
88   if (p->stats_in >= p->stats_buf_ctx->stats_in_end) return EOF;
89 
90   *fps = *p->stats_in;
91   ++p->stats_in;
92   return 1;
93 }
94 
input_stats_lap(TWO_PASS * p,FIRSTPASS_STATS * fps)95 static int input_stats_lap(TWO_PASS *p, FIRSTPASS_STATS *fps) {
96   if (p->stats_in >= p->stats_buf_ctx->stats_in_end) return EOF;
97 
98   *fps = *p->stats_in;
99   /* Move old stats[0] out to accommodate for next frame stats  */
100   memmove(p->frame_stats_arr[0], p->frame_stats_arr[1],
101           (p->stats_buf_ctx->stats_in_end - p->stats_in - 1) *
102               sizeof(FIRSTPASS_STATS));
103   p->stats_buf_ctx->stats_in_end--;
104   return 1;
105 }
106 
107 // Read frame stats at an offset from the current position.
read_frame_stats(const TWO_PASS * p,int offset)108 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
109   if ((offset >= 0 && p->stats_in + offset >= p->stats_buf_ctx->stats_in_end) ||
110       (offset < 0 && p->stats_in + offset < p->stats_buf_ctx->stats_in_start)) {
111     return NULL;
112   }
113 
114   return &p->stats_in[offset];
115 }
116 
subtract_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)117 static void subtract_stats(FIRSTPASS_STATS *section,
118                            const FIRSTPASS_STATS *frame) {
119   section->frame -= frame->frame;
120   section->weight -= frame->weight;
121   section->intra_error -= frame->intra_error;
122   section->frame_avg_wavelet_energy -= frame->frame_avg_wavelet_energy;
123   section->coded_error -= frame->coded_error;
124   section->sr_coded_error -= frame->sr_coded_error;
125   section->pcnt_inter -= frame->pcnt_inter;
126   section->pcnt_motion -= frame->pcnt_motion;
127   section->pcnt_second_ref -= frame->pcnt_second_ref;
128   section->pcnt_neutral -= frame->pcnt_neutral;
129   section->intra_skip_pct -= frame->intra_skip_pct;
130   section->inactive_zone_rows -= frame->inactive_zone_rows;
131   section->inactive_zone_cols -= frame->inactive_zone_cols;
132   section->MVr -= frame->MVr;
133   section->mvr_abs -= frame->mvr_abs;
134   section->MVc -= frame->MVc;
135   section->mvc_abs -= frame->mvc_abs;
136   section->MVrv -= frame->MVrv;
137   section->MVcv -= frame->MVcv;
138   section->mv_in_out_count -= frame->mv_in_out_count;
139   section->new_mv_count -= frame->new_mv_count;
140   section->count -= frame->count;
141   section->duration -= frame->duration;
142 }
143 
144 // This function returns the maximum target rate per frame.
frame_max_bits(const RATE_CONTROL * rc,const AV1EncoderConfig * oxcf)145 static int frame_max_bits(const RATE_CONTROL *rc,
146                           const AV1EncoderConfig *oxcf) {
147   int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
148                       (int64_t)oxcf->two_pass_vbrmax_section) /
149                      100;
150   if (max_bits < 0)
151     max_bits = 0;
152   else if (max_bits > rc->max_frame_bandwidth)
153     max_bits = rc->max_frame_bandwidth;
154 
155   return (int)max_bits;
156 }
157 
158 static const double q_pow_term[(QINDEX_RANGE >> 5) + 1] = { 0.65, 0.70, 0.75,
159                                                             0.80, 0.85, 0.90,
160                                                             0.95, 0.95, 0.95 };
161 #define ERR_DIVISOR 96.0
calc_correction_factor(double err_per_mb,int q)162 static double calc_correction_factor(double err_per_mb, int q) {
163   const double error_term = err_per_mb / ERR_DIVISOR;
164   const int index = q >> 5;
165   // Adjustment to power term based on qindex
166   const double power_term =
167       q_pow_term[index] +
168       (((q_pow_term[index + 1] - q_pow_term[index]) * (q % 32)) / 32.0);
169   assert(error_term >= 0.0);
170   return fclamp(pow(error_term, power_term), 0.05, 5.0);
171 }
172 
twopass_update_bpm_factor(TWO_PASS * twopass)173 static void twopass_update_bpm_factor(TWO_PASS *twopass) {
174   // Based on recent history adjust expectations of bits per macroblock.
175   double last_group_rate_err =
176       (double)twopass->rolling_arf_group_actual_bits /
177       DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
178   last_group_rate_err = AOMMAX(0.25, AOMMIN(4.0, last_group_rate_err));
179   twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
180   twopass->bpm_factor = AOMMAX(0.25, AOMMIN(4.0, twopass->bpm_factor));
181 }
182 
qbpm_enumerator(int rate_err_tol)183 static int qbpm_enumerator(int rate_err_tol) {
184   return 1350000 + ((300000 * AOMMIN(75, AOMMAX(rate_err_tol - 25, 0))) / 75);
185 }
186 
187 // Similar to find_qindex_by_rate() function in ratectrl.c, but includes
188 // calculation of a correction_factor.
find_qindex_by_rate_with_correction(int desired_bits_per_mb,aom_bit_depth_t bit_depth,double error_per_mb,double group_weight_factor,int rate_err_tol,int best_qindex,int worst_qindex)189 static int find_qindex_by_rate_with_correction(
190     int desired_bits_per_mb, aom_bit_depth_t bit_depth, double error_per_mb,
191     double group_weight_factor, int rate_err_tol, int best_qindex,
192     int worst_qindex) {
193   assert(best_qindex <= worst_qindex);
194   int low = best_qindex;
195   int high = worst_qindex;
196 
197   while (low < high) {
198     const int mid = (low + high) >> 1;
199     const double mid_factor = calc_correction_factor(error_per_mb, mid);
200     const double q = av1_convert_qindex_to_q(mid, bit_depth);
201     const int enumerator = qbpm_enumerator(rate_err_tol);
202     const int mid_bits_per_mb =
203         (int)((enumerator * mid_factor * group_weight_factor) / q);
204 
205     if (mid_bits_per_mb > desired_bits_per_mb) {
206       low = mid + 1;
207     } else {
208       high = mid;
209     }
210   }
211   return low;
212 }
213 
get_twopass_worst_quality(AV1_COMP * cpi,const double section_err,double inactive_zone,int section_target_bandwidth,double group_weight_factor)214 static int get_twopass_worst_quality(AV1_COMP *cpi, const double section_err,
215                                      double inactive_zone,
216                                      int section_target_bandwidth,
217                                      double group_weight_factor) {
218   const RATE_CONTROL *const rc = &cpi->rc;
219   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
220 
221   inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
222 
223   if (section_target_bandwidth <= 0) {
224     return rc->worst_quality;  // Highest value allowed
225   } else {
226     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
227                             ? cpi->initial_mbs
228                             : cpi->common.mi_params.MBs;
229     const int active_mbs = AOMMAX(1, num_mbs - (int)(num_mbs * inactive_zone));
230     const double av_err_per_mb = section_err / active_mbs;
231     const int target_norm_bits_per_mb =
232         (int)((uint64_t)section_target_bandwidth << BPER_MB_NORMBITS) /
233         active_mbs;
234     int rate_err_tol =
235         AOMMIN(cpi->oxcf.under_shoot_pct, cpi->oxcf.over_shoot_pct);
236 
237     twopass_update_bpm_factor(&cpi->twopass);
238     // Try and pick a max Q that will be high enough to encode the
239     // content at the given rate.
240     int q = find_qindex_by_rate_with_correction(
241         target_norm_bits_per_mb, cpi->common.seq_params.bit_depth,
242         av_err_per_mb, group_weight_factor, rate_err_tol, rc->best_quality,
243         rc->worst_quality);
244 
245     // Restriction on active max q for constrained quality mode.
246     if (cpi->oxcf.rc_mode == AOM_CQ) q = AOMMAX(q, oxcf->cq_level);
247     return q;
248   }
249 }
250 
251 #define SR_DIFF_PART 0.0015
252 #define MOTION_AMP_PART 0.003
253 #define INTRA_PART 0.005
254 #define DEFAULT_DECAY_LIMIT 0.75
255 #define LOW_SR_DIFF_TRHESH 0.1
256 #define SR_DIFF_MAX 128.0
257 #define NCOUNT_FRAME_II_THRESH 5.0
258 
get_sr_decay_rate(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * frame)259 static double get_sr_decay_rate(const FRAME_INFO *frame_info,
260                                 const FIRSTPASS_STATS *frame) {
261   const int num_mbs = frame_info->num_mbs;
262   double sr_diff = (frame->sr_coded_error - frame->coded_error) / num_mbs;
263   double sr_decay = 1.0;
264   double modified_pct_inter;
265   double modified_pcnt_intra;
266   const double motion_amplitude_factor =
267       frame->pcnt_motion * ((frame->mvc_abs + frame->mvr_abs) / 2);
268 
269   modified_pct_inter = frame->pcnt_inter;
270   if ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
271       (double)NCOUNT_FRAME_II_THRESH) {
272     modified_pct_inter = frame->pcnt_inter - frame->pcnt_neutral;
273   }
274   modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
275 
276   if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
277     sr_diff = AOMMIN(sr_diff, SR_DIFF_MAX);
278     sr_decay = 1.0 - (SR_DIFF_PART * sr_diff) -
279                (MOTION_AMP_PART * motion_amplitude_factor) -
280                (INTRA_PART * modified_pcnt_intra);
281   }
282   return AOMMAX(sr_decay, AOMMIN(DEFAULT_DECAY_LIMIT, modified_pct_inter));
283 }
284 
285 // This function gives an estimate of how badly we believe the prediction
286 // quality is decaying from frame to frame.
get_zero_motion_factor(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * frame)287 static double get_zero_motion_factor(const FRAME_INFO *frame_info,
288                                      const FIRSTPASS_STATS *frame) {
289   const double zero_motion_pct = frame->pcnt_inter - frame->pcnt_motion;
290   double sr_decay = get_sr_decay_rate(frame_info, frame);
291   return AOMMIN(sr_decay, zero_motion_pct);
292 }
293 
294 #define ZM_POWER_FACTOR 0.75
295 
get_prediction_decay_rate(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * next_frame)296 static double get_prediction_decay_rate(const FRAME_INFO *frame_info,
297                                         const FIRSTPASS_STATS *next_frame) {
298   const double sr_decay_rate = get_sr_decay_rate(frame_info, next_frame);
299   const double zero_motion_factor =
300       (0.95 * pow((next_frame->pcnt_inter - next_frame->pcnt_motion),
301                   ZM_POWER_FACTOR));
302 
303   return AOMMAX(zero_motion_factor,
304                 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
305 }
306 
307 // Function to test for a condition where a complex transition is followed
308 // by a static section. For example in slide shows where there is a fade
309 // between slides. This is to help with more optimal kf and gf positioning.
detect_transition_to_still(TWO_PASS * const twopass,const int min_gf_interval,const int frame_interval,const int still_interval,const double loop_decay_rate,const double last_decay_rate)310 static int detect_transition_to_still(TWO_PASS *const twopass,
311                                       const int min_gf_interval,
312                                       const int frame_interval,
313                                       const int still_interval,
314                                       const double loop_decay_rate,
315                                       const double last_decay_rate) {
316   // Break clause to detect very still sections after motion
317   // For example a static image after a fade or other transition
318   // instead of a clean scene cut.
319   if (frame_interval > min_gf_interval && loop_decay_rate >= 0.999 &&
320       last_decay_rate < 0.9) {
321     int j;
322     // Look ahead a few frames to see if static condition persists...
323     for (j = 0; j < still_interval; ++j) {
324       const FIRSTPASS_STATS *stats = &twopass->stats_in[j];
325       if (stats >= twopass->stats_buf_ctx->stats_in_end) break;
326 
327       if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
328     }
329     // Only if it does do we signal a transition to still.
330     return j == still_interval;
331   }
332   return 0;
333 }
334 
335 // This function detects a flash through the high relative pcnt_second_ref
336 // score in the frame following a flash frame. The offset passed in should
337 // reflect this.
detect_flash(const TWO_PASS * twopass,const int offset)338 static int detect_flash(const TWO_PASS *twopass, const int offset) {
339   const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
340 
341   // What we are looking for here is a situation where there is a
342   // brief break in prediction (such as a flash) but subsequent frames
343   // are reasonably well predicted by an earlier (pre flash) frame.
344   // The recovery after a flash is indicated by a high pcnt_second_ref
345   // compared to pcnt_inter.
346   return next_frame != NULL &&
347          next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
348          next_frame->pcnt_second_ref >= 0.5;
349 }
350 
351 // Update the motion related elements to the GF arf boost calculation.
accumulate_frame_motion_stats(const FIRSTPASS_STATS * stats,GF_GROUP_STATS * gf_stats)352 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
353                                           GF_GROUP_STATS *gf_stats) {
354   const double pct = stats->pcnt_motion;
355 
356   // Accumulate Motion In/Out of frame stats.
357   gf_stats->this_frame_mv_in_out = stats->mv_in_out_count * pct;
358   gf_stats->mv_in_out_accumulator += gf_stats->this_frame_mv_in_out;
359   gf_stats->abs_mv_in_out_accumulator += fabs(gf_stats->this_frame_mv_in_out);
360 
361   // Accumulate a measure of how uniform (or conversely how random) the motion
362   // field is (a ratio of abs(mv) / mv).
363   if (pct > 0.05) {
364     const double mvr_ratio =
365         fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
366     const double mvc_ratio =
367         fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
368 
369     gf_stats->mv_ratio_accumulator +=
370         pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
371     gf_stats->mv_ratio_accumulator +=
372         pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
373   }
374 }
375 
accumulate_this_frame_stats(const FIRSTPASS_STATS * stats,const double mod_frame_err,GF_GROUP_STATS * gf_stats)376 static void accumulate_this_frame_stats(const FIRSTPASS_STATS *stats,
377                                         const double mod_frame_err,
378                                         GF_GROUP_STATS *gf_stats) {
379   gf_stats->gf_group_err += mod_frame_err;
380 #if GROUP_ADAPTIVE_MAXQ
381   gf_stats->gf_group_raw_error += stats->coded_error;
382 #endif
383   gf_stats->gf_group_skip_pct += stats->intra_skip_pct;
384   gf_stats->gf_group_inactive_zone_rows += stats->inactive_zone_rows;
385 }
386 
accumulate_next_frame_stats(const FIRSTPASS_STATS * stats,const FRAME_INFO * frame_info,TWO_PASS * const twopass,const int flash_detected,const int frames_since_key,const int cur_idx,const int can_disable_arf,const int min_gf_interval,GF_GROUP_STATS * gf_stats)387 static void accumulate_next_frame_stats(
388     const FIRSTPASS_STATS *stats, const FRAME_INFO *frame_info,
389     TWO_PASS *const twopass, const int flash_detected,
390     const int frames_since_key, const int cur_idx, const int can_disable_arf,
391     const int min_gf_interval, GF_GROUP_STATS *gf_stats) {
392   accumulate_frame_motion_stats(stats, gf_stats);
393   // sum up the metric values of current gf group
394   gf_stats->avg_sr_coded_error += stats->sr_coded_error;
395   gf_stats->avg_tr_coded_error += stats->tr_coded_error;
396   gf_stats->avg_pcnt_second_ref += stats->pcnt_second_ref;
397   gf_stats->avg_pcnt_third_ref += stats->pcnt_third_ref;
398   gf_stats->avg_new_mv_count += stats->new_mv_count;
399   gf_stats->avg_wavelet_energy += stats->frame_avg_wavelet_energy;
400   if (fabs(stats->raw_error_stdev) > 0.000001) {
401     gf_stats->non_zero_stdev_count++;
402     gf_stats->avg_raw_err_stdev += stats->raw_error_stdev;
403   }
404 
405   // Accumulate the effect of prediction quality decay
406   if (!flash_detected) {
407     gf_stats->last_loop_decay_rate = gf_stats->loop_decay_rate;
408     gf_stats->loop_decay_rate = get_prediction_decay_rate(frame_info, stats);
409 
410     gf_stats->decay_accumulator =
411         gf_stats->decay_accumulator * gf_stats->loop_decay_rate;
412 
413     // Monitor for static sections.
414     if ((frames_since_key + cur_idx - 1) > 1) {
415       gf_stats->zero_motion_accumulator =
416           AOMMIN(gf_stats->zero_motion_accumulator,
417                  get_zero_motion_factor(frame_info, stats));
418     }
419 
420     // Break clause to detect very still sections after motion. For example,
421     // a static image after a fade or other transition.
422     if (can_disable_arf &&
423         detect_transition_to_still(twopass, min_gf_interval, cur_idx, 5,
424                                    gf_stats->loop_decay_rate,
425                                    gf_stats->last_loop_decay_rate)) {
426       gf_stats->allow_alt_ref = 0;
427     }
428   }
429 }
430 
average_gf_stats(const int total_frame,const FIRSTPASS_STATS * last_stat,GF_GROUP_STATS * gf_stats)431 static void average_gf_stats(const int total_frame,
432                              const FIRSTPASS_STATS *last_stat,
433                              GF_GROUP_STATS *gf_stats) {
434   if (total_frame) {
435     gf_stats->avg_sr_coded_error /= total_frame;
436     gf_stats->avg_tr_coded_error /= total_frame;
437     gf_stats->avg_pcnt_second_ref /= total_frame;
438     if (total_frame - 1) {
439       gf_stats->avg_pcnt_third_ref_nolast =
440           (gf_stats->avg_pcnt_third_ref - last_stat->pcnt_third_ref) /
441           (total_frame - 1);
442     } else {
443       gf_stats->avg_pcnt_third_ref_nolast =
444           gf_stats->avg_pcnt_third_ref / total_frame;
445     }
446     gf_stats->avg_pcnt_third_ref /= total_frame;
447     gf_stats->avg_new_mv_count /= total_frame;
448     gf_stats->avg_wavelet_energy /= total_frame;
449   }
450 
451   if (gf_stats->non_zero_stdev_count)
452     gf_stats->avg_raw_err_stdev /= gf_stats->non_zero_stdev_count;
453 }
454 
get_features_from_gf_stats(const GF_GROUP_STATS * gf_stats,const GF_FRAME_STATS * first_frame,const GF_FRAME_STATS * last_frame,const int num_mbs,const int constrained_gf_group,const int kf_zeromotion_pct,const int num_frames,float * features)455 static void get_features_from_gf_stats(const GF_GROUP_STATS *gf_stats,
456                                        const GF_FRAME_STATS *first_frame,
457                                        const GF_FRAME_STATS *last_frame,
458                                        const int num_mbs,
459                                        const int constrained_gf_group,
460                                        const int kf_zeromotion_pct,
461                                        const int num_frames, float *features) {
462   *features++ = (float)gf_stats->abs_mv_in_out_accumulator;
463   *features++ = (float)(gf_stats->avg_new_mv_count / num_mbs);
464   *features++ = (float)gf_stats->avg_pcnt_second_ref;
465   *features++ = (float)gf_stats->avg_pcnt_third_ref;
466   *features++ = (float)gf_stats->avg_pcnt_third_ref_nolast;
467   *features++ = (float)(gf_stats->avg_sr_coded_error / num_mbs);
468   *features++ = (float)(gf_stats->avg_tr_coded_error / num_mbs);
469   *features++ = (float)(gf_stats->avg_wavelet_energy / num_mbs);
470   *features++ = (float)(constrained_gf_group);
471   *features++ = (float)gf_stats->decay_accumulator;
472   *features++ = (float)(first_frame->frame_coded_error / num_mbs);
473   *features++ = (float)(first_frame->frame_sr_coded_error / num_mbs);
474   *features++ = (float)(first_frame->frame_tr_coded_error / num_mbs);
475   *features++ = (float)(first_frame->frame_err / num_mbs);
476   *features++ = (float)(kf_zeromotion_pct);
477   *features++ = (float)(last_frame->frame_coded_error / num_mbs);
478   *features++ = (float)(last_frame->frame_sr_coded_error / num_mbs);
479   *features++ = (float)(last_frame->frame_tr_coded_error / num_mbs);
480   *features++ = (float)num_frames;
481   *features++ = (float)gf_stats->mv_ratio_accumulator;
482   *features++ = (float)gf_stats->non_zero_stdev_count;
483 }
484 
485 #define BOOST_FACTOR 12.5
baseline_err_per_mb(const FRAME_INFO * frame_info)486 static double baseline_err_per_mb(const FRAME_INFO *frame_info) {
487   unsigned int screen_area = frame_info->frame_height * frame_info->frame_width;
488 
489   // Use a different error per mb factor for calculating boost for
490   //  different formats.
491   if (screen_area <= 640 * 360) {
492     return 500.0;
493   } else {
494     return 1000.0;
495   }
496 }
497 
calc_frame_boost(const RATE_CONTROL * rc,const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame,double this_frame_mv_in_out,double max_boost)498 static double calc_frame_boost(const RATE_CONTROL *rc,
499                                const FRAME_INFO *frame_info,
500                                const FIRSTPASS_STATS *this_frame,
501                                double this_frame_mv_in_out, double max_boost) {
502   double frame_boost;
503   const double lq = av1_convert_qindex_to_q(rc->avg_frame_qindex[INTER_FRAME],
504                                             frame_info->bit_depth);
505   const double boost_q_correction = AOMMIN((0.5 + (lq * 0.015)), 1.5);
506   const double active_area = calculate_active_area(frame_info, this_frame);
507   int num_mbs = frame_info->num_mbs;
508 
509   // Correct for any inactive region in the image
510   num_mbs = (int)AOMMAX(1, num_mbs * active_area);
511 
512   // Underlying boost factor is based on inter error ratio.
513   frame_boost = AOMMAX(baseline_err_per_mb(frame_info) * num_mbs,
514                        this_frame->intra_error * active_area) /
515                 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
516   frame_boost = frame_boost * BOOST_FACTOR * boost_q_correction;
517 
518   // Increase boost for frames where new data coming into frame (e.g. zoom out).
519   // Slightly reduce boost if there is a net balance of motion out of the frame
520   // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
521   if (this_frame_mv_in_out > 0.0)
522     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
523   // In the extreme case the boost is halved.
524   else
525     frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
526 
527   return AOMMIN(frame_boost, max_boost * boost_q_correction);
528 }
529 
calc_kf_frame_boost(const RATE_CONTROL * rc,const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame,double * sr_accumulator,double max_boost)530 static double calc_kf_frame_boost(const RATE_CONTROL *rc,
531                                   const FRAME_INFO *frame_info,
532                                   const FIRSTPASS_STATS *this_frame,
533                                   double *sr_accumulator, double max_boost) {
534   double frame_boost;
535   const double lq = av1_convert_qindex_to_q(rc->avg_frame_qindex[INTER_FRAME],
536                                             frame_info->bit_depth);
537   const double boost_q_correction = AOMMIN((0.50 + (lq * 0.015)), 2.00);
538   const double active_area = calculate_active_area(frame_info, this_frame);
539   int num_mbs = frame_info->num_mbs;
540 
541   // Correct for any inactive region in the image
542   num_mbs = (int)AOMMAX(1, num_mbs * active_area);
543 
544   // Underlying boost factor is based on inter error ratio.
545   frame_boost = AOMMAX(baseline_err_per_mb(frame_info) * num_mbs,
546                        this_frame->intra_error * active_area) /
547                 DOUBLE_DIVIDE_CHECK(
548                     (this_frame->coded_error + *sr_accumulator) * active_area);
549 
550   // Update the accumulator for second ref error difference.
551   // This is intended to give an indication of how much the coded error is
552   // increasing over time.
553   *sr_accumulator += (this_frame->sr_coded_error - this_frame->coded_error);
554   *sr_accumulator = AOMMAX(0.0, *sr_accumulator);
555 
556   // Q correction and scaling
557   // The 40.0 value here is an experimentally derived baseline minimum.
558   // This value is in line with the minimum per frame boost in the alt_ref
559   // boost calculation.
560   frame_boost = ((frame_boost + 40.0) * boost_q_correction);
561 
562   return AOMMIN(frame_boost, max_boost * boost_q_correction);
563 }
564 
get_projected_gfu_boost(const RATE_CONTROL * rc,int gfu_boost,int frames_to_project,int num_stats_used_for_gfu_boost)565 static int get_projected_gfu_boost(const RATE_CONTROL *rc, int gfu_boost,
566                                    int frames_to_project,
567                                    int num_stats_used_for_gfu_boost) {
568   /*
569    * If frames_to_project is equal to num_stats_used_for_gfu_boost,
570    * it means that gfu_boost was calculated over frames_to_project to
571    * begin with(ie; all stats required were available), hence return
572    * the original boost.
573    */
574   if (num_stats_used_for_gfu_boost >= frames_to_project) return gfu_boost;
575 
576   double min_boost_factor = sqrt(rc->baseline_gf_interval);
577   // Get the current tpl factor (number of frames = frames_to_project).
578   double tpl_factor = av1_get_gfu_boost_projection_factor(
579       min_boost_factor, MAX_GFUBOOST_FACTOR, frames_to_project);
580   // Get the tpl factor when number of frames = num_stats_used_for_prior_boost.
581   double tpl_factor_num_stats = av1_get_gfu_boost_projection_factor(
582       min_boost_factor, MAX_GFUBOOST_FACTOR, num_stats_used_for_gfu_boost);
583   int projected_gfu_boost =
584       (int)rint((tpl_factor * gfu_boost) / tpl_factor_num_stats);
585   return projected_gfu_boost;
586 }
587 
588 #define GF_MAX_BOOST 90.0
589 #define MIN_DECAY_FACTOR 0.01
av1_calc_arf_boost(const TWO_PASS * twopass,const RATE_CONTROL * rc,FRAME_INFO * frame_info,int offset,int f_frames,int b_frames,int * num_fpstats_used,int * num_fpstats_required)590 int av1_calc_arf_boost(const TWO_PASS *twopass, const RATE_CONTROL *rc,
591                        FRAME_INFO *frame_info, int offset, int f_frames,
592                        int b_frames, int *num_fpstats_used,
593                        int *num_fpstats_required) {
594   int i;
595   GF_GROUP_STATS gf_stats;
596   init_gf_stats(&gf_stats);
597   double boost_score = (double)NORMAL_BOOST;
598   int arf_boost;
599   int flash_detected = 0;
600   if (num_fpstats_used) *num_fpstats_used = 0;
601 
602   // Search forward from the proposed arf/next gf position.
603   for (i = 0; i < f_frames; ++i) {
604     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
605     if (this_frame == NULL) break;
606 
607     // Update the motion related elements to the boost calculation.
608     accumulate_frame_motion_stats(this_frame, &gf_stats);
609 
610     // We want to discount the flash frame itself and the recovery
611     // frame that follows as both will have poor scores.
612     flash_detected = detect_flash(twopass, i + offset) ||
613                      detect_flash(twopass, i + offset + 1);
614 
615     // Accumulate the effect of prediction quality decay.
616     if (!flash_detected) {
617       gf_stats.decay_accumulator *=
618           get_prediction_decay_rate(frame_info, this_frame);
619       gf_stats.decay_accumulator = gf_stats.decay_accumulator < MIN_DECAY_FACTOR
620                                        ? MIN_DECAY_FACTOR
621                                        : gf_stats.decay_accumulator;
622     }
623 
624     boost_score +=
625         gf_stats.decay_accumulator *
626         calc_frame_boost(rc, frame_info, this_frame,
627                          gf_stats.this_frame_mv_in_out, GF_MAX_BOOST);
628     if (num_fpstats_used) (*num_fpstats_used)++;
629   }
630 
631   arf_boost = (int)boost_score;
632 
633   // Reset for backward looking loop.
634   boost_score = 0.0;
635   init_gf_stats(&gf_stats);
636   // Search backward towards last gf position.
637   for (i = -1; i >= -b_frames; --i) {
638     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
639     if (this_frame == NULL) break;
640 
641     // Update the motion related elements to the boost calculation.
642     accumulate_frame_motion_stats(this_frame, &gf_stats);
643 
644     // We want to discount the the flash frame itself and the recovery
645     // frame that follows as both will have poor scores.
646     flash_detected = detect_flash(twopass, i + offset) ||
647                      detect_flash(twopass, i + offset + 1);
648 
649     // Cumulative effect of prediction quality decay.
650     if (!flash_detected) {
651       gf_stats.decay_accumulator *=
652           get_prediction_decay_rate(frame_info, this_frame);
653       gf_stats.decay_accumulator = gf_stats.decay_accumulator < MIN_DECAY_FACTOR
654                                        ? MIN_DECAY_FACTOR
655                                        : gf_stats.decay_accumulator;
656     }
657 
658     boost_score +=
659         gf_stats.decay_accumulator *
660         calc_frame_boost(rc, frame_info, this_frame,
661                          gf_stats.this_frame_mv_in_out, GF_MAX_BOOST);
662     if (num_fpstats_used) (*num_fpstats_used)++;
663   }
664   arf_boost += (int)boost_score;
665 
666   if (num_fpstats_required) {
667     *num_fpstats_required = f_frames + b_frames;
668     if (num_fpstats_used) {
669       arf_boost = get_projected_gfu_boost(rc, arf_boost, *num_fpstats_required,
670                                           *num_fpstats_used);
671     }
672   }
673 
674   if (arf_boost < ((b_frames + f_frames) * 50))
675     arf_boost = ((b_frames + f_frames) * 50);
676 
677   return arf_boost;
678 }
679 
680 // 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)681 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
682                                          const FIRSTPASS_STATS *end,
683                                          int section_length) {
684   const FIRSTPASS_STATS *s = begin;
685   double intra_error = 0.0;
686   double coded_error = 0.0;
687   int i = 0;
688 
689   while (s < end && i < section_length) {
690     intra_error += s->intra_error;
691     coded_error += s->coded_error;
692     ++s;
693     ++i;
694   }
695 
696   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
697 }
698 
699 // Calculate the total bits to allocate in this GF/ARF group.
calculate_total_gf_group_bits(AV1_COMP * cpi,double gf_group_err)700 static int64_t calculate_total_gf_group_bits(AV1_COMP *cpi,
701                                              double gf_group_err) {
702   const RATE_CONTROL *const rc = &cpi->rc;
703   const TWO_PASS *const twopass = &cpi->twopass;
704   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
705   int64_t total_group_bits;
706 
707   // Calculate the bits to be allocated to the group as a whole.
708   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
709     total_group_bits = (int64_t)(twopass->kf_group_bits *
710                                  (gf_group_err / twopass->kf_group_error_left));
711   } else {
712     total_group_bits = 0;
713   }
714 
715   // Clamp odd edge cases.
716   total_group_bits = (total_group_bits < 0)
717                          ? 0
718                          : (total_group_bits > twopass->kf_group_bits)
719                                ? twopass->kf_group_bits
720                                : total_group_bits;
721 
722   // Clip based on user supplied data rate variability limit.
723   if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
724     total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
725 
726   return total_group_bits;
727 }
728 
729 // 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)730 static int calculate_boost_bits(int frame_count, int boost,
731                                 int64_t total_group_bits) {
732   int allocation_chunks;
733 
734   // return 0 for invalid inputs (could arise e.g. through rounding errors)
735   if (!boost || (total_group_bits <= 0)) return 0;
736 
737   if (frame_count <= 0) return (int)(AOMMIN(total_group_bits, INT_MAX));
738 
739   allocation_chunks = (frame_count * 100) + boost;
740 
741   // Prevent overflow.
742   if (boost > 1023) {
743     int divisor = boost >> 10;
744     boost /= divisor;
745     allocation_chunks /= divisor;
746   }
747 
748   // Calculate the number of extra bits for use in the boosted frame or frames.
749   return AOMMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
750                 0);
751 }
752 
753 // Calculate the boost factor based on the number of bits assigned, i.e. the
754 // inverse of calculate_boost_bits().
calculate_boost_factor(int frame_count,int bits,int64_t total_group_bits)755 static int calculate_boost_factor(int frame_count, int bits,
756                                   int64_t total_group_bits) {
757   aom_clear_system_state();
758   return (int)(100.0 * frame_count * bits / (total_group_bits - bits));
759 }
760 
761 // Reduce the number of bits assigned to keyframe or arf if necessary, to
762 // prevent bitrate spikes that may break level constraints.
763 // 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)764 static int adjust_boost_bits_for_target_level(const AV1_COMP *const cpi,
765                                               RATE_CONTROL *const rc,
766                                               int bits_assigned,
767                                               int64_t group_bits,
768                                               int frame_type) {
769   const AV1_COMMON *const cm = &cpi->common;
770   const SequenceHeader *const seq_params = &cm->seq_params;
771   const int temporal_layer_id = cm->temporal_layer_id;
772   const int spatial_layer_id = cm->spatial_layer_id;
773   for (int index = 0; index < seq_params->operating_points_cnt_minus_1 + 1;
774        ++index) {
775     if (!is_in_operating_point(seq_params->operating_point_idc[index],
776                                temporal_layer_id, spatial_layer_id)) {
777       continue;
778     }
779 
780     const AV1_LEVEL target_level =
781         cpi->level_params.target_seq_level_idx[index];
782     if (target_level >= SEQ_LEVELS) continue;
783 
784     assert(is_valid_seq_level_idx(target_level));
785 
786     const double level_bitrate_limit = av1_get_max_bitrate_for_level(
787         target_level, seq_params->tier[0], seq_params->profile);
788     const int target_bits_per_frame =
789         (int)(level_bitrate_limit / cpi->framerate);
790     if (frame_type == 0) {
791       // Maximum bits for keyframe is 8 times the target_bits_per_frame.
792       const int level_enforced_max_kf_bits = target_bits_per_frame * 8;
793       if (bits_assigned > level_enforced_max_kf_bits) {
794         const int frames = rc->frames_to_key - 1;
795         rc->kf_boost = calculate_boost_factor(
796             frames, level_enforced_max_kf_bits, group_bits);
797         bits_assigned = calculate_boost_bits(frames, rc->kf_boost, group_bits);
798       }
799     } else if (frame_type == 1) {
800       // Maximum bits for arf is 4 times the target_bits_per_frame.
801       const int level_enforced_max_arf_bits = target_bits_per_frame * 4;
802       if (bits_assigned > level_enforced_max_arf_bits) {
803         rc->gfu_boost = calculate_boost_factor(
804             rc->baseline_gf_interval, level_enforced_max_arf_bits, group_bits);
805         bits_assigned = calculate_boost_bits(rc->baseline_gf_interval,
806                                              rc->gfu_boost, group_bits);
807       }
808     } else {
809       assert(0);
810     }
811   }
812 
813   return bits_assigned;
814 }
815 
816 // Compile time switch on alternate algorithm to allocate bits in ARF groups
817 // #define ALT_ARF_ALLOCATION
818 #ifdef ALT_ARF_ALLOCATION
819 double layer_fraction[MAX_ARF_LAYERS + 1] = { 1.0,  0.70, 0.55, 0.60,
820                                               0.60, 1.0,  1.0 };
allocate_gf_group_bits(GF_GROUP * gf_group,RATE_CONTROL * const rc,int64_t gf_group_bits,int gf_arf_bits,int key_frame,int use_arf)821 static void allocate_gf_group_bits(GF_GROUP *gf_group, RATE_CONTROL *const rc,
822                                    int64_t gf_group_bits, int gf_arf_bits,
823                                    int key_frame, int use_arf) {
824   int64_t total_group_bits = gf_group_bits;
825   int base_frame_bits;
826   const int gf_group_size = gf_group->size;
827   int layer_frames[MAX_ARF_LAYERS + 1] = { 0 };
828 
829   // Subtract the extra bits set aside for ARF frames from the Group Total
830   if (use_arf || !key_frame) total_group_bits -= gf_arf_bits;
831 
832   if (rc->baseline_gf_interval)
833     base_frame_bits = (int)(total_group_bits / rc->baseline_gf_interval);
834   else
835     base_frame_bits = (int)1;
836 
837   // For key frames the frame target rate is already set and it
838   // is also the golden frame.
839   // === [frame_index == 0] ===
840   int frame_index = 0;
841   if (!key_frame) {
842     if (rc->source_alt_ref_active)
843       gf_group->bit_allocation[frame_index] = 0;
844     else
845       gf_group->bit_allocation[frame_index] =
846           base_frame_bits + (int)(gf_arf_bits * layer_fraction[1]);
847   }
848   frame_index++;
849 
850   // Check the number of frames in each layer in case we have a
851   // non standard group length.
852   int max_arf_layer = gf_group->max_layer_depth - 1;
853   for (int idx = frame_index; idx < gf_group_size; ++idx) {
854     if ((gf_group->update_type[idx] == ARF_UPDATE) ||
855         (gf_group->update_type[idx] == INTNL_ARF_UPDATE)) {
856       // max_arf_layer = AOMMAX(max_arf_layer, gf_group->layer_depth[idx]);
857       layer_frames[gf_group->layer_depth[idx]]++;
858     }
859   }
860 
861   // Allocate extra bits to each ARF layer
862   int i;
863   int layer_extra_bits[MAX_ARF_LAYERS + 1] = { 0 };
864   for (i = 1; i <= max_arf_layer; ++i) {
865     double fraction = (i == max_arf_layer) ? 1.0 : layer_fraction[i];
866     layer_extra_bits[i] =
867         (int)((gf_arf_bits * fraction) / AOMMAX(1, layer_frames[i]));
868     gf_arf_bits -= (int)(gf_arf_bits * fraction);
869   }
870 
871   // Now combine ARF layer and baseline bits to give total bits for each frame.
872   int arf_extra_bits;
873   for (int idx = frame_index; idx < gf_group_size; ++idx) {
874     switch (gf_group->update_type[idx]) {
875       case ARF_UPDATE:
876       case INTNL_ARF_UPDATE:
877         arf_extra_bits = layer_extra_bits[gf_group->layer_depth[idx]];
878         gf_group->bit_allocation[idx] = base_frame_bits + arf_extra_bits;
879         break;
880       case INTNL_OVERLAY_UPDATE:
881       case OVERLAY_UPDATE: gf_group->bit_allocation[idx] = 0; break;
882       default: gf_group->bit_allocation[idx] = base_frame_bits; break;
883     }
884   }
885 
886   // Set the frame following the current GOP to 0 bit allocation. For ARF
887   // groups, this next frame will be overlay frame, which is the first frame
888   // in the next GOP. For GF group, next GOP will overwrite the rate allocation.
889   // Setting this frame to use 0 bit (of out the current GOP budget) will
890   // simplify logics in reference frame management.
891   gf_group->bit_allocation[gf_group_size] = 0;
892 }
893 #else
allocate_gf_group_bits(GF_GROUP * gf_group,RATE_CONTROL * const rc,int64_t gf_group_bits,int gf_arf_bits,int key_frame,int use_arf)894 static void allocate_gf_group_bits(GF_GROUP *gf_group, RATE_CONTROL *const rc,
895                                    int64_t gf_group_bits, int gf_arf_bits,
896                                    int key_frame, int use_arf) {
897   int64_t total_group_bits = gf_group_bits;
898 
899   // For key frames the frame target rate is already set and it
900   // is also the golden frame.
901   // === [frame_index == 0] ===
902   int frame_index = 0;
903   if (!key_frame) {
904     if (rc->source_alt_ref_active)
905       gf_group->bit_allocation[frame_index] = 0;
906     else
907       gf_group->bit_allocation[frame_index] = gf_arf_bits;
908   }
909 
910   // Deduct the boost bits for arf (or gf if it is not a key frame)
911   // from the group total.
912   if (use_arf || !key_frame) total_group_bits -= gf_arf_bits;
913 
914   frame_index++;
915 
916   // Store the bits to spend on the ARF if there is one.
917   // === [frame_index == 1] ===
918   if (use_arf) {
919     gf_group->bit_allocation[frame_index] = gf_arf_bits;
920     ++frame_index;
921   }
922 
923   const int gf_group_size = gf_group->size;
924   int arf_depth_bits[MAX_ARF_LAYERS + 1] = { 0 };
925   int arf_depth_count[MAX_ARF_LAYERS + 1] = { 0 };
926   int arf_depth_boost[MAX_ARF_LAYERS + 1] = { 0 };
927   int total_arfs = 0;
928   int total_overlays = rc->source_alt_ref_active;
929 
930   for (int idx = 0; idx < gf_group_size; ++idx) {
931     if (gf_group->update_type[idx] == ARF_UPDATE ||
932         gf_group->update_type[idx] == INTNL_ARF_UPDATE ||
933         gf_group->update_type[idx] == LF_UPDATE) {
934       arf_depth_boost[gf_group->layer_depth[idx]] += gf_group->arf_boost[idx];
935       ++arf_depth_count[gf_group->layer_depth[idx]];
936     }
937   }
938 
939   for (int idx = 2; idx <= MAX_ARF_LAYERS; ++idx) {
940     arf_depth_bits[idx] =
941         calculate_boost_bits(rc->baseline_gf_interval - total_arfs -
942                                  total_overlays - arf_depth_count[idx],
943                              arf_depth_boost[idx], total_group_bits);
944     total_group_bits -= arf_depth_bits[idx];
945     total_arfs += arf_depth_count[idx];
946   }
947 
948   for (int idx = frame_index; idx < gf_group_size; ++idx) {
949     switch (gf_group->update_type[idx]) {
950       case ARF_UPDATE:
951       case INTNL_ARF_UPDATE:
952       case LF_UPDATE:
953         gf_group->bit_allocation[idx] =
954             (int)(((int64_t)arf_depth_bits[gf_group->layer_depth[idx]] *
955                    gf_group->arf_boost[idx]) /
956                   arf_depth_boost[gf_group->layer_depth[idx]]);
957         break;
958       case INTNL_OVERLAY_UPDATE:
959       case OVERLAY_UPDATE:
960       default: gf_group->bit_allocation[idx] = 0; break;
961     }
962   }
963 
964   // Set the frame following the current GOP to 0 bit allocation. For ARF
965   // groups, this next frame will be overlay frame, which is the first frame
966   // in the next GOP. For GF group, next GOP will overwrite the rate allocation.
967   // Setting this frame to use 0 bit (of out the current GOP budget) will
968   // simplify logics in reference frame management.
969   gf_group->bit_allocation[gf_group_size] = 0;
970 }
971 #endif
972 
973 // Returns true if KF group and GF group both are almost completely static.
is_almost_static(double gf_zero_motion,int kf_zero_motion)974 static INLINE int is_almost_static(double gf_zero_motion, int kf_zero_motion) {
975   return (gf_zero_motion >= 0.995) &&
976          (kf_zero_motion >= STATIC_KF_GROUP_THRESH);
977 }
978 
979 #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)980 static INLINE int detect_gf_cut(AV1_COMP *cpi, int frame_index, int cur_start,
981                                 int flash_detected, int active_max_gf_interval,
982                                 int active_min_gf_interval,
983                                 GF_GROUP_STATS *gf_stats) {
984   RATE_CONTROL *const rc = &cpi->rc;
985   TWO_PASS *const twopass = &cpi->twopass;
986   // Motion breakout threshold for loop below depends on image size.
987   const double mv_ratio_accumulator_thresh =
988       (cpi->initial_height + cpi->initial_width) / 4.0;
989 
990   if (!flash_detected) {
991     // Break clause to detect very still sections after motion. For example,
992     // a static image after a fade or other transition.
993     if (detect_transition_to_still(
994             twopass, rc->min_gf_interval, frame_index - cur_start, 5,
995             gf_stats->loop_decay_rate, gf_stats->last_loop_decay_rate)) {
996       return 1;
997     }
998   }
999 
1000   // Some conditions to breakout after min interval.
1001   if (frame_index - cur_start >= active_min_gf_interval &&
1002       // If possible don't break very close to a kf
1003       (rc->frames_to_key - frame_index >= rc->min_gf_interval) &&
1004       ((frame_index - cur_start) & 0x01) && !flash_detected &&
1005       (gf_stats->mv_ratio_accumulator > mv_ratio_accumulator_thresh ||
1006        gf_stats->abs_mv_in_out_accumulator > ARF_ABS_ZOOM_THRESH)) {
1007     return 1;
1008   }
1009 
1010   // If almost totally static, we will not use the the max GF length later,
1011   // so we can continue for more frames.
1012   if (((frame_index - cur_start) >= active_max_gf_interval + 1) &&
1013       !is_almost_static(gf_stats->zero_motion_accumulator,
1014                         twopass->kf_zeromotion_pct)) {
1015     return 1;
1016   }
1017   return 0;
1018 }
1019 
1020 #define MAX_PAD_GF_CHECK 6  // padding length to check for gf length
1021 #define AVG_SI_THRES 0.6    // thres for average silouette
1022 #define GF_SHRINK_OUTPUT 0  // print output for gf length decision
determine_high_err_gf(double * errs,int * is_high,double * si,int len,double * ratio,int gf_start,int gf_end,int before_pad)1023 int determine_high_err_gf(double *errs, int *is_high, double *si, int len,
1024                           double *ratio, int gf_start, int gf_end,
1025                           int before_pad) {
1026   (void)gf_start;
1027   (void)gf_end;
1028   (void)before_pad;
1029   // alpha and beta controls the threshold placement
1030   // e.g. a smaller alpha makes the lower group more rigid
1031   const double alpha = 0.5;
1032   const double beta = 1 - alpha;
1033   double mean = 0;
1034   double mean_low = 0;
1035   double mean_high = 0;
1036   double prev_mean_low = 0;
1037   double prev_mean_high = 0;
1038   int count_low = 0;
1039   int count_high = 0;
1040   // calculate mean of errs
1041   for (int i = 0; i < len; i++) {
1042     mean += errs[i];
1043   }
1044   mean /= len;
1045   // separate into two initial groups with greater / lower than mean
1046   for (int i = 0; i < len; i++) {
1047     if (errs[i] <= mean) {
1048       is_high[i] = 0;
1049       count_low++;
1050       prev_mean_low += errs[i];
1051     } else {
1052       is_high[i] = 1;
1053       count_high++;
1054       prev_mean_high += errs[i];
1055     }
1056   }
1057   prev_mean_low /= count_low;
1058   prev_mean_high /= count_high;
1059   // kmeans to refine
1060   int count = 0;
1061   while (count < 10) {
1062     // re-group
1063     mean_low = 0;
1064     mean_high = 0;
1065     count_low = 0;
1066     count_high = 0;
1067     double thres = prev_mean_low * alpha + prev_mean_high * beta;
1068     for (int i = 0; i < len; i++) {
1069       if (errs[i] <= thres) {
1070         is_high[i] = 0;
1071         count_low++;
1072         mean_low += errs[i];
1073       } else {
1074         is_high[i] = 1;
1075         count_high++;
1076         mean_high += errs[i];
1077       }
1078     }
1079     mean_low /= count_low;
1080     mean_high /= count_high;
1081 
1082     // break if not changed much
1083     if (fabs((mean_low - prev_mean_low) / (prev_mean_low + 0.00001)) <
1084             0.00001 &&
1085         fabs((mean_high - prev_mean_high) / (prev_mean_high + 0.00001)) <
1086             0.00001)
1087       break;
1088 
1089     // update means
1090     prev_mean_high = mean_high;
1091     prev_mean_low = mean_low;
1092 
1093     count++;
1094   }
1095 
1096   // count how many jumps of group changes
1097   int num_change = 0;
1098   for (int i = 0; i < len - 1; i++) {
1099     if (is_high[i] != is_high[i + 1]) num_change++;
1100   }
1101 
1102   // get silhouette as a measure of the classification quality
1103   double avg_si = 0;
1104   // ai: avg dist of its own class, bi: avg dist to the other class
1105   double ai, bi;
1106   if (count_low > 1 && count_high > 1) {
1107     for (int i = 0; i < len; i++) {
1108       ai = 0;
1109       bi = 0;
1110       // calculate average distance to everyone in the same group
1111       // and in the other group
1112       for (int j = 0; j < len; j++) {
1113         if (i == j) continue;
1114         if (is_high[i] == is_high[j]) {
1115           ai += fabs(errs[i] - errs[j]);
1116         } else {
1117           bi += fabs(errs[i] - errs[j]);
1118         }
1119       }
1120       if (is_high[i] == 0) {
1121         ai = ai / (count_low - 1);
1122         bi = bi / count_high;
1123       } else {
1124         ai = ai / (count_high - 1);
1125         bi = bi / count_low;
1126       }
1127       if (ai <= bi) {
1128         si[i] = 1 - ai / (bi + 0.00001);
1129       } else {
1130         si[i] = bi / (ai + 0.00001) - 1;
1131       }
1132       avg_si += si[i];
1133     }
1134     avg_si /= len;
1135   }
1136 
1137   int reset = 0;
1138   *ratio = mean_high / (mean_low + 0.00001);
1139   // if the two groups too similar, or
1140   // if too many numbers of changes, or
1141   // silhouette is too small, not confident
1142   // reset everything to 0 later so we fallback to the original decision
1143   if (*ratio < 1.3 || num_change > AOMMAX(len / 3, 6) ||
1144       avg_si < AVG_SI_THRES) {
1145     reset = 1;
1146   }
1147 
1148 #if GF_SHRINK_OUTPUT
1149   printf("\n");
1150   for (int i = 0; i < len; i++) {
1151     printf("%d: err %.1f, ishigh %d, si %.2f, (i=%d)\n",
1152            gf_start + i - before_pad, errs[i], is_high[i], si[i], gf_end);
1153   }
1154   printf(
1155       "count: %d, mean_high: %.1f, mean_low: %.1f, avg_si: %.2f, num_change: "
1156       "%d, ratio %.2f, reset: %d\n",
1157       count, mean_high, mean_low, avg_si, num_change,
1158       mean_high / (mean_low + 0.000001), reset);
1159 #endif
1160 
1161   if (reset) {
1162     memset(is_high, 0, sizeof(is_high[0]) * len);
1163     memset(si, 0, sizeof(si[0]) * len);
1164   }
1165   return reset;
1166 }
1167 
1168 #if GROUP_ADAPTIVE_MAXQ
1169 #define RC_FACTOR_MIN 0.75
1170 #define RC_FACTOR_MAX 1.25
1171 #endif  // GROUP_ADAPTIVE_MAXQ
1172 #define MIN_FWD_KF_INTERVAL 8
1173 #define MIN_SHRINK_LEN 6      // the minimum length of gf if we are shrinking
1174 #define SI_HIGH AVG_SI_THRES  // high quality classification
1175 #define SI_LOW 0.3            // very unsure classification
1176 // this function finds an low error frame previously to the current last frame
1177 // in the gf group, and set the last frame to it.
1178 // The resulting last frame is then returned by *cur_last_ptr
1179 // *cur_start_ptr and cut_pos[n] could also change due to shrinking
1180 // previous gf groups
set_last_prev_low_err(int * cur_start_ptr,int * cur_last_ptr,int * cut_pos,int count_cuts,int before_pad,double ratio,int * is_high,double * si,int prev_lows)1181 void set_last_prev_low_err(int *cur_start_ptr, int *cur_last_ptr, int *cut_pos,
1182                            int count_cuts, int before_pad, double ratio,
1183                            int *is_high, double *si, int prev_lows) {
1184   int n;
1185   int cur_start = *cur_start_ptr;
1186   int cur_last = *cur_last_ptr;
1187   for (n = cur_last; n >= cur_start + MIN_SHRINK_LEN; n--) {
1188     // try to find a point that is very probable to be good
1189     if (is_high[n - cur_start + before_pad] == 0 &&
1190         si[n - cur_start + before_pad] > SI_HIGH) {
1191       *cur_last_ptr = n;
1192       return;
1193     }
1194   }
1195   // could not find a low-err point, then let's try find an "unsure"
1196   // point at least
1197   for (n = cur_last; n >= cur_start + MIN_SHRINK_LEN; n--) {
1198     if ((is_high[n - cur_start + before_pad] == 0) ||
1199         (is_high[n - cur_start + before_pad] &&
1200          si[n - cur_start + before_pad] < SI_LOW)) {
1201       *cur_last_ptr = n;
1202       return;
1203     }
1204   }
1205   if (prev_lows) {
1206     // try with shrinking previous all_zero interval
1207     for (n = cur_start + MIN_SHRINK_LEN - 1; n > cur_start; n--) {
1208       if (is_high[n - cur_start + before_pad] == 0 &&
1209           si[n - cur_start + before_pad] > SI_HIGH) {
1210         int tentative_start = n - MIN_SHRINK_LEN;
1211         // check if the previous interval can shrink this much
1212         int available =
1213             tentative_start - cut_pos[count_cuts - 2] > MIN_SHRINK_LEN &&
1214             cur_start - tentative_start < prev_lows;
1215         // shrinking too agressively may worsen performance
1216         // set stricter thres for shorter length
1217         double ratio_thres =
1218             1.0 * (cur_start - tentative_start) / (double)(MIN_SHRINK_LEN) +
1219             1.0;
1220 
1221         if (available && (ratio > ratio_thres)) {
1222           cut_pos[count_cuts - 1] = tentative_start;
1223           *cur_start_ptr = tentative_start;
1224           *cur_last_ptr = n;
1225           return;
1226         }
1227       }
1228     }
1229   }
1230   if (prev_lows) {
1231     // try with shrinking previous all_zero interval with unsure points
1232     for (n = cur_start + MIN_SHRINK_LEN - 1; n > cur_start; n--) {
1233       if ((is_high[n - cur_start + before_pad] == 0) ||
1234           (is_high[n - cur_start + before_pad] &&
1235            si[n - cur_start + before_pad] < SI_LOW)) {
1236         int tentative_start = n - MIN_SHRINK_LEN;
1237         // check if the previous interval can shrink this much
1238         int available =
1239             tentative_start - cut_pos[count_cuts - 2] > MIN_SHRINK_LEN &&
1240             cur_start - tentative_start < prev_lows;
1241         // shrinking too agressively may worsen performance
1242         double ratio_thres =
1243             1.0 * (cur_start - tentative_start) / (double)(MIN_SHRINK_LEN) +
1244             1.0;
1245 
1246         if (available && (ratio > ratio_thres)) {
1247           cut_pos[count_cuts - 1] = tentative_start;
1248           *cur_start_ptr = tentative_start;
1249           *cur_last_ptr = n;
1250           return;
1251         }
1252       }
1253     }
1254   }  // prev_lows
1255   return;
1256 }
1257 
1258 // This function decides the gf group length of future frames in batch
1259 // rc->gf_intervals is modified to store the group lengths
calculate_gf_length(AV1_COMP * cpi,int max_gop_length,int max_intervals)1260 static void calculate_gf_length(AV1_COMP *cpi, int max_gop_length,
1261                                 int max_intervals) {
1262   RATE_CONTROL *const rc = &cpi->rc;
1263   TWO_PASS *const twopass = &cpi->twopass;
1264   FIRSTPASS_STATS next_frame;
1265   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
1266   FRAME_INFO *frame_info = &cpi->frame_info;
1267   int i;
1268 
1269   int flash_detected;
1270 
1271   aom_clear_system_state();
1272   av1_zero(next_frame);
1273 
1274   if (has_no_stats_stage(cpi)) {
1275     for (i = 0; i < MAX_NUM_GF_INTERVALS; i++) {
1276       rc->gf_intervals[i] = AOMMIN(rc->max_gf_interval, max_gop_length);
1277     }
1278     rc->cur_gf_index = 0;
1279     rc->intervals_till_gf_calculate_due = MAX_NUM_GF_INTERVALS;
1280     return;
1281   }
1282 
1283   // TODO(urvang): Try logic to vary min and max interval based on q.
1284   const int active_min_gf_interval = rc->min_gf_interval;
1285   const int active_max_gf_interval =
1286       AOMMIN(rc->max_gf_interval, max_gop_length);
1287 
1288   i = 0;
1289   max_intervals = cpi->lap_enabled ? 1 : max_intervals;
1290   int cut_pos[MAX_NUM_GF_INTERVALS + 1] = { 0 };
1291   int count_cuts = 1;
1292   int cur_start = 0, cur_last;
1293   int cut_here;
1294   int prev_lows = 0;
1295   GF_GROUP_STATS gf_stats;
1296   init_gf_stats(&gf_stats);
1297   while (count_cuts < max_intervals + 1) {
1298     ++i;
1299 
1300     // reaches next key frame, break here
1301     if (i >= rc->frames_to_key) {
1302       cut_pos[count_cuts] = i - 1;
1303       count_cuts++;
1304       break;
1305     }
1306 
1307     // reached maximum len, but nothing special yet (almost static)
1308     // let's look at the next interval
1309     if (i - cur_start >= rc->static_scene_max_gf_interval) {
1310       cut_here = 1;
1311     } else {
1312       // reaches last frame, break
1313       if (EOF == input_stats(twopass, &next_frame)) {
1314         cut_pos[count_cuts] = i - 1;
1315         count_cuts++;
1316         break;
1317       }
1318       // Test for the case where there is a brief flash but the prediction
1319       // quality back to an earlier frame is then restored.
1320       flash_detected = detect_flash(twopass, 0);
1321       // TODO(bohanli): remove redundant accumulations here, or unify
1322       // this and the ones in define_gf_group
1323       accumulate_next_frame_stats(&next_frame, frame_info, twopass,
1324                                   flash_detected, rc->frames_since_key, i, 0,
1325                                   rc->min_gf_interval, &gf_stats);
1326 
1327       cut_here = detect_gf_cut(cpi, i, cur_start, flash_detected,
1328                                active_max_gf_interval, active_min_gf_interval,
1329                                &gf_stats);
1330     }
1331     if (cut_here) {
1332       cur_last = i - 1;  // the current last frame in the gf group
1333       // only try shrinking if interval smaller than active_max_gf_interval
1334       if (cur_last - cur_start <= active_max_gf_interval) {
1335         // determine in the current decided gop the higher and lower errs
1336         int n;
1337         double ratio;
1338 
1339         // load neighboring coded errs
1340         int is_high[MAX_GF_INTERVAL + 1 + MAX_PAD_GF_CHECK * 2] = { 0 };
1341         double errs[MAX_GF_INTERVAL + 1 + MAX_PAD_GF_CHECK * 2] = { 0 };
1342         double si[MAX_GF_INTERVAL + 1 + MAX_PAD_GF_CHECK * 2] = { 0 };
1343         int before_pad =
1344             AOMMIN(MAX_PAD_GF_CHECK, rc->frames_since_key - 1 + cur_start);
1345         int after_pad =
1346             AOMMIN(MAX_PAD_GF_CHECK, rc->frames_to_key - cur_last - 1);
1347         for (n = cur_start - before_pad; n <= cur_last + after_pad; n++) {
1348           if (start_pos + n - 1 > twopass->stats_buf_ctx->stats_in_end) {
1349             after_pad = n - cur_last - 1;
1350             assert(after_pad >= 0);
1351             break;
1352           } else if (start_pos + n - 1 <
1353                      twopass->stats_buf_ctx->stats_in_start) {
1354             before_pad = cur_start - n - 1;
1355             continue;
1356           }
1357           errs[n + before_pad - cur_start] = (start_pos + n - 1)->coded_error;
1358         }
1359         const int len = before_pad + after_pad + cur_last - cur_start + 1;
1360         const int reset = determine_high_err_gf(
1361             errs, is_high, si, len, &ratio, cur_start, cur_last, before_pad);
1362 
1363         // if the current frame may have high error, try shrinking
1364         if (is_high[cur_last - cur_start + before_pad] == 1 ||
1365             (!reset && si[cur_last - cur_start + before_pad] < SI_LOW)) {
1366           // try not to cut in high err area
1367           set_last_prev_low_err(&cur_start, &cur_last, cut_pos, count_cuts,
1368                                 before_pad, ratio, is_high, si, prev_lows);
1369         }  // if current frame high error
1370         // count how many trailing lower error frames we have in this decided
1371         // gf group
1372         prev_lows = 0;
1373         for (n = cur_last - 1; n > cur_start + MIN_SHRINK_LEN; n--) {
1374           if (is_high[n - cur_start + before_pad] == 0 &&
1375               (si[n - cur_start + before_pad] > SI_HIGH || reset)) {
1376             prev_lows++;
1377           } else {
1378             break;
1379           }
1380         }
1381       }
1382       cut_pos[count_cuts] = cur_last;
1383       count_cuts++;
1384 
1385       // reset pointers to the shrinked location
1386       twopass->stats_in = start_pos + cur_last;
1387       cur_start = cur_last;
1388       i = cur_last;
1389 
1390       // reset accumulators
1391       init_gf_stats(&gf_stats);
1392     }
1393   }
1394 
1395   // save intervals
1396   rc->intervals_till_gf_calculate_due = count_cuts - 1;
1397   for (int n = 1; n < count_cuts; n++) {
1398     rc->gf_intervals[n - 1] = cut_pos[n] + 1 - cut_pos[n - 1];
1399   }
1400   rc->cur_gf_index = 0;
1401   twopass->stats_in = start_pos;
1402 
1403 #if GF_SHRINK_OUTPUT
1404   printf("\nf_to_key: %d, count_cut: %d. ", rc->frames_to_key, count_cuts);
1405   for (int n = 0; n < count_cuts; n++) {
1406     printf("%d ", cut_pos[n]);
1407   }
1408   printf("\n");
1409 
1410   for (int n = 0; n < rc->intervals_till_gf_calculate_due; n++) {
1411     printf("%d ", rc->gf_intervals[n]);
1412   }
1413   printf("\n\n");
1414 #endif
1415 }
1416 
correct_frames_to_key(AV1_COMP * cpi)1417 static void correct_frames_to_key(AV1_COMP *cpi) {
1418   int lookahead_size =
1419       (int)av1_lookahead_depth(cpi->lookahead, cpi->compressor_stage) + 1;
1420   if (lookahead_size <
1421       av1_lookahead_pop_sz(cpi->lookahead, cpi->compressor_stage)) {
1422     cpi->rc.frames_to_key = AOMMIN(cpi->rc.frames_to_key, lookahead_size);
1423   }
1424 }
1425 
define_gf_group_pass0(AV1_COMP * cpi,const EncodeFrameParams * const frame_params)1426 static void define_gf_group_pass0(AV1_COMP *cpi,
1427                                   const EncodeFrameParams *const frame_params) {
1428   RATE_CONTROL *const rc = &cpi->rc;
1429   GF_GROUP *const gf_group = &cpi->gf_group;
1430   int target;
1431 
1432   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1433     av1_cyclic_refresh_set_golden_update(cpi);
1434   } else {
1435     rc->baseline_gf_interval = rc->gf_intervals[rc->cur_gf_index];
1436     rc->intervals_till_gf_calculate_due--;
1437     rc->cur_gf_index++;
1438   }
1439 
1440   // correct frames_to_key when lookahead queue is flushing
1441   correct_frames_to_key(cpi);
1442 
1443   if (rc->baseline_gf_interval > rc->frames_to_key)
1444     rc->baseline_gf_interval = rc->frames_to_key;
1445 
1446   rc->gfu_boost = DEFAULT_GF_BOOST;
1447   rc->constrained_gf_group =
1448       (rc->baseline_gf_interval >= rc->frames_to_key) ? 1 : 0;
1449 
1450   gf_group->max_layer_depth_allowed = cpi->oxcf.gf_max_pyr_height;
1451 
1452   // Rare case when the look-ahead is less than the target GOP length, can't
1453   // generate ARF frame.
1454   if (rc->baseline_gf_interval > cpi->oxcf.lag_in_frames ||
1455       !is_altref_enabled(cpi) || rc->baseline_gf_interval < rc->min_gf_interval)
1456     gf_group->max_layer_depth_allowed = 0;
1457 
1458   // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
1459   av1_gop_setup_structure(cpi, frame_params);
1460 
1461   // Allocate bits to each of the frames in the GF group.
1462   // TODO(sarahparker) Extend this to work with pyramid structure.
1463   for (int cur_index = 0; cur_index < gf_group->size; ++cur_index) {
1464     const FRAME_UPDATE_TYPE cur_update_type = gf_group->update_type[cur_index];
1465     if (cpi->oxcf.rc_mode == AOM_CBR) {
1466       if (cur_update_type == KEY_FRAME) {
1467         target = av1_calc_iframe_target_size_one_pass_cbr(cpi);
1468       } else {
1469         target = av1_calc_pframe_target_size_one_pass_cbr(cpi, cur_update_type);
1470       }
1471     } else {
1472       if (cur_update_type == KEY_FRAME) {
1473         target = av1_calc_iframe_target_size_one_pass_vbr(cpi);
1474       } else {
1475         target = av1_calc_pframe_target_size_one_pass_vbr(cpi, cur_update_type);
1476       }
1477     }
1478     gf_group->bit_allocation[cur_index] = target;
1479   }
1480 }
1481 
set_baseline_gf_interval(AV1_COMP * cpi,int arf_position,int active_max_gf_interval,int use_alt_ref,int is_final_pass)1482 static INLINE void set_baseline_gf_interval(AV1_COMP *cpi, int arf_position,
1483                                             int active_max_gf_interval,
1484                                             int use_alt_ref,
1485                                             int is_final_pass) {
1486   RATE_CONTROL *const rc = &cpi->rc;
1487   TWO_PASS *const twopass = &cpi->twopass;
1488   // Set the interval until the next gf.
1489   // If forward keyframes are enabled, ensure the final gf group obeys the
1490   // MIN_FWD_KF_INTERVAL.
1491   if (cpi->oxcf.fwd_kf_enabled && use_alt_ref &&
1492       ((twopass->stats_in - arf_position + rc->frames_to_key) <
1493        twopass->stats_buf_ctx->stats_in_end) &&
1494       cpi->rc.next_is_fwd_key) {
1495     if (arf_position == rc->frames_to_key) {
1496       rc->baseline_gf_interval = arf_position;
1497       // if the last gf group will be smaller than MIN_FWD_KF_INTERVAL
1498     } else if ((rc->frames_to_key - arf_position <
1499                 AOMMAX(MIN_FWD_KF_INTERVAL, rc->min_gf_interval)) &&
1500                (rc->frames_to_key != arf_position)) {
1501       // if possible, merge the last two gf groups
1502       if (rc->frames_to_key <= active_max_gf_interval) {
1503         rc->baseline_gf_interval = rc->frames_to_key;
1504         if (is_final_pass) rc->intervals_till_gf_calculate_due = 0;
1505         // if merging the last two gf groups creates a group that is too long,
1506         // split them and force the last gf group to be the MIN_FWD_KF_INTERVAL
1507       } else {
1508         rc->baseline_gf_interval = rc->frames_to_key - MIN_FWD_KF_INTERVAL;
1509         if (is_final_pass) rc->intervals_till_gf_calculate_due = 0;
1510       }
1511     } else {
1512       rc->baseline_gf_interval = arf_position - rc->source_alt_ref_pending;
1513     }
1514   } else {
1515     rc->baseline_gf_interval = arf_position - rc->source_alt_ref_pending;
1516   }
1517 }
1518 
1519 // initialize GF_GROUP_STATS
init_gf_stats(GF_GROUP_STATS * gf_stats)1520 static void init_gf_stats(GF_GROUP_STATS *gf_stats) {
1521   gf_stats->gf_group_err = 0.0;
1522   gf_stats->gf_group_raw_error = 0.0;
1523   gf_stats->gf_group_skip_pct = 0.0;
1524   gf_stats->gf_group_inactive_zone_rows = 0.0;
1525 
1526   gf_stats->mv_ratio_accumulator = 0.0;
1527   gf_stats->decay_accumulator = 1.0;
1528   gf_stats->zero_motion_accumulator = 1.0;
1529   gf_stats->loop_decay_rate = 1.0;
1530   gf_stats->last_loop_decay_rate = 1.0;
1531   gf_stats->this_frame_mv_in_out = 0.0;
1532   gf_stats->mv_in_out_accumulator = 0.0;
1533   gf_stats->abs_mv_in_out_accumulator = 0.0;
1534 
1535   gf_stats->avg_sr_coded_error = 0.0;
1536   gf_stats->avg_tr_coded_error = 0.0;
1537   gf_stats->avg_pcnt_second_ref = 0.0;
1538   gf_stats->avg_pcnt_third_ref = 0.0;
1539   gf_stats->avg_pcnt_third_ref_nolast = 0.0;
1540   gf_stats->avg_new_mv_count = 0.0;
1541   gf_stats->avg_wavelet_energy = 0.0;
1542   gf_stats->avg_raw_err_stdev = 0.0;
1543   gf_stats->non_zero_stdev_count = 0;
1544 
1545   gf_stats->allow_alt_ref = 0;
1546 }
1547 
1548 // Analyse and define a gf/arf group.
1549 #define MAX_GF_BOOST 5400
define_gf_group(AV1_COMP * cpi,FIRSTPASS_STATS * this_frame,const EncodeFrameParams * const frame_params,int max_gop_length,int is_final_pass)1550 static void define_gf_group(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame,
1551                             const EncodeFrameParams *const frame_params,
1552                             int max_gop_length, int is_final_pass) {
1553   AV1_COMMON *const cm = &cpi->common;
1554   RATE_CONTROL *const rc = &cpi->rc;
1555   AV1EncoderConfig *const oxcf = &cpi->oxcf;
1556   TWO_PASS *const twopass = &cpi->twopass;
1557   FIRSTPASS_STATS next_frame;
1558   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
1559   GF_GROUP *gf_group = &cpi->gf_group;
1560   FRAME_INFO *frame_info = &cpi->frame_info;
1561   int i;
1562 
1563   int flash_detected;
1564   int64_t gf_group_bits;
1565   const int is_intra_only = frame_params->frame_type == KEY_FRAME ||
1566                             frame_params->frame_type == INTRA_ONLY_FRAME;
1567   const int arf_active_or_kf = is_intra_only || rc->source_alt_ref_active;
1568 
1569   cpi->internal_altref_allowed = (oxcf->gf_max_pyr_height > 1);
1570 
1571   // Reset the GF group data structures unless this is a key
1572   // frame in which case it will already have been done.
1573   if (!is_intra_only) {
1574     av1_zero(cpi->gf_group);
1575   }
1576 
1577   aom_clear_system_state();
1578   av1_zero(next_frame);
1579 
1580   if (has_no_stats_stage(cpi)) {
1581     define_gf_group_pass0(cpi, frame_params);
1582     return;
1583   }
1584 
1585   // correct frames_to_key when lookahead queue is emptying
1586   if (cpi->lap_enabled) {
1587     correct_frames_to_key(cpi);
1588   }
1589 
1590   GF_GROUP_STATS gf_stats;
1591   init_gf_stats(&gf_stats);
1592   GF_FRAME_STATS first_frame_stats, last_frame_stats;
1593 
1594   gf_stats.allow_alt_ref = is_altref_enabled(cpi);
1595   const int can_disable_arf = (oxcf->gf_min_pyr_height == MIN_PYRAMID_LVL);
1596 
1597   // Load stats for the current frame.
1598   double mod_frame_err =
1599       calculate_modified_err(frame_info, twopass, oxcf, this_frame);
1600 
1601   // Note the error of the frame at the start of the group. This will be
1602   // the GF frame error if we code a normal gf.
1603   first_frame_stats.frame_err = mod_frame_err;
1604   first_frame_stats.frame_coded_error = this_frame->coded_error;
1605   first_frame_stats.frame_sr_coded_error = this_frame->sr_coded_error;
1606   first_frame_stats.frame_tr_coded_error = this_frame->tr_coded_error;
1607 
1608   // If this is a key frame or the overlay from a previous arf then
1609   // the error score / cost of this frame has already been accounted for.
1610   if (arf_active_or_kf) {
1611     gf_stats.gf_group_err -= first_frame_stats.frame_err;
1612 #if GROUP_ADAPTIVE_MAXQ
1613     gf_stats.gf_group_raw_error -= this_frame->coded_error;
1614 #endif
1615     gf_stats.gf_group_skip_pct -= this_frame->intra_skip_pct;
1616     gf_stats.gf_group_inactive_zone_rows -= this_frame->inactive_zone_rows;
1617   }
1618 
1619   // TODO(urvang): Try logic to vary min and max interval based on q.
1620   const int active_min_gf_interval = rc->min_gf_interval;
1621   const int active_max_gf_interval =
1622       AOMMIN(rc->max_gf_interval, max_gop_length);
1623 
1624   i = 0;
1625   // get the determined gf group length from rc->gf_intervals
1626   while (i < rc->gf_intervals[rc->cur_gf_index]) {
1627     ++i;
1628     // Accumulate error score of frames in this gf group.
1629     mod_frame_err =
1630         calculate_modified_err(frame_info, twopass, oxcf, this_frame);
1631     // accumulate stats for this frame
1632     accumulate_this_frame_stats(this_frame, mod_frame_err, &gf_stats);
1633 
1634     // read in the next frame
1635     if (EOF == input_stats(twopass, &next_frame)) break;
1636 
1637     // Test for the case where there is a brief flash but the prediction
1638     // quality back to an earlier frame is then restored.
1639     flash_detected = detect_flash(twopass, 0);
1640 
1641     // accumulate stats for next frame
1642     accumulate_next_frame_stats(
1643         &next_frame, frame_info, twopass, flash_detected, rc->frames_since_key,
1644         i, can_disable_arf, rc->min_gf_interval, &gf_stats);
1645 
1646     *this_frame = next_frame;
1647   }
1648   // save the errs for the last frame
1649   last_frame_stats.frame_coded_error = next_frame.coded_error;
1650   last_frame_stats.frame_sr_coded_error = next_frame.sr_coded_error;
1651   last_frame_stats.frame_tr_coded_error = next_frame.tr_coded_error;
1652 
1653   if (is_final_pass) {
1654     rc->intervals_till_gf_calculate_due--;
1655     rc->cur_gf_index++;
1656   }
1657 
1658   // Was the group length constrained by the requirement for a new KF?
1659   rc->constrained_gf_group = (i >= rc->frames_to_key) ? 1 : 0;
1660 
1661   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1662                           ? cpi->initial_mbs
1663                           : cm->mi_params.MBs;
1664   assert(num_mbs > 0);
1665 
1666   average_gf_stats(i, &next_frame, &gf_stats);
1667 
1668   // Disable internal ARFs for "still" gf groups.
1669   //   zero_motion_accumulator: minimum percentage of (0,0) motion;
1670   //   avg_sr_coded_error:      average of the SSE per pixel of each frame;
1671   //   avg_raw_err_stdev:       average of the standard deviation of (0,0)
1672   //                            motion error per block of each frame.
1673   const int can_disable_internal_arfs =
1674       (oxcf->gf_min_pyr_height <= MIN_PYRAMID_LVL + 1);
1675   if (can_disable_internal_arfs &&
1676       gf_stats.zero_motion_accumulator > MIN_ZERO_MOTION &&
1677       gf_stats.avg_sr_coded_error / num_mbs < MAX_SR_CODED_ERROR &&
1678       gf_stats.avg_raw_err_stdev < MAX_RAW_ERR_VAR) {
1679     cpi->internal_altref_allowed = 0;
1680   }
1681 
1682   int use_alt_ref;
1683   if (can_disable_arf) {
1684     use_alt_ref = !is_almost_static(gf_stats.zero_motion_accumulator,
1685                                     twopass->kf_zeromotion_pct) &&
1686                   gf_stats.allow_alt_ref && (i < cpi->oxcf.lag_in_frames) &&
1687                   (i >= MIN_GF_INTERVAL) &&
1688                   (cpi->oxcf.gf_max_pyr_height > MIN_PYRAMID_LVL);
1689 
1690     // TODO(urvang): Improve and use model for VBR, CQ etc as well.
1691     if (use_alt_ref && cpi->oxcf.rc_mode == AOM_Q &&
1692         cpi->oxcf.cq_level <= 200) {
1693       aom_clear_system_state();
1694       float features[21];
1695       get_features_from_gf_stats(
1696           &gf_stats, &first_frame_stats, &last_frame_stats, num_mbs,
1697           rc->constrained_gf_group, twopass->kf_zeromotion_pct, i, features);
1698       // Infer using ML model.
1699       float score;
1700       av1_nn_predict(features, &av1_use_flat_gop_nn_config, 1, &score);
1701       use_alt_ref = (score <= 0.0);
1702     }
1703   } else {
1704     assert(cpi->oxcf.gf_max_pyr_height > MIN_PYRAMID_LVL);
1705     use_alt_ref =
1706         gf_stats.allow_alt_ref && (i < cpi->oxcf.lag_in_frames) && (i > 2);
1707   }
1708 
1709 #define REDUCE_GF_LENGTH_THRESH 4
1710 #define REDUCE_GF_LENGTH_TO_KEY_THRESH 9
1711 #define REDUCE_GF_LENGTH_BY 1
1712   int alt_offset = 0;
1713   // The length reduction strategy is tweaked for certain cases, and doesn't
1714   // work well for certain other cases.
1715   const int allow_gf_length_reduction =
1716       ((cpi->oxcf.rc_mode == AOM_Q && cpi->oxcf.cq_level <= 128) ||
1717        !cpi->internal_altref_allowed) &&
1718       !is_lossless_requested(&cpi->oxcf);
1719 
1720   if (allow_gf_length_reduction && use_alt_ref) {
1721     // adjust length of this gf group if one of the following condition met
1722     // 1: only one overlay frame left and this gf is too long
1723     // 2: next gf group is too short to have arf compared to the current gf
1724 
1725     // maximum length of next gf group
1726     const int next_gf_len = rc->frames_to_key - i;
1727     const int single_overlay_left =
1728         next_gf_len == 0 && i > REDUCE_GF_LENGTH_THRESH;
1729     // the next gf is probably going to have a ARF but it will be shorter than
1730     // this gf
1731     const int unbalanced_gf =
1732         i > REDUCE_GF_LENGTH_TO_KEY_THRESH &&
1733         next_gf_len + 1 < REDUCE_GF_LENGTH_TO_KEY_THRESH &&
1734         next_gf_len + 1 >= rc->min_gf_interval;
1735 
1736     if (single_overlay_left || unbalanced_gf) {
1737       const int roll_back = REDUCE_GF_LENGTH_BY;
1738       // Reduce length only if active_min_gf_interval will be respected later.
1739       if (i - roll_back >= active_min_gf_interval + 1) {
1740         alt_offset = -roll_back;
1741         i -= roll_back;
1742         if (is_final_pass) rc->intervals_till_gf_calculate_due = 0;
1743       }
1744     }
1745   }
1746 
1747   // Should we use the alternate reference frame.
1748   if (use_alt_ref) {
1749     rc->source_alt_ref_pending = 1;
1750     gf_group->max_layer_depth_allowed = cpi->oxcf.gf_max_pyr_height;
1751     set_baseline_gf_interval(cpi, i, active_max_gf_interval, use_alt_ref,
1752                              is_final_pass);
1753 
1754     const int forward_frames = (rc->frames_to_key - i >= i - 1)
1755                                    ? i - 1
1756                                    : AOMMAX(0, rc->frames_to_key - i);
1757 
1758     // Calculate the boost for alt ref.
1759     rc->gfu_boost = av1_calc_arf_boost(
1760         twopass, rc, frame_info, alt_offset, forward_frames, (i - 1),
1761         cpi->lap_enabled ? &rc->num_stats_used_for_gfu_boost : NULL,
1762         cpi->lap_enabled ? &rc->num_stats_required_for_gfu_boost : NULL);
1763   } else {
1764     reset_fpf_position(twopass, start_pos);
1765     rc->source_alt_ref_pending = 0;
1766     gf_group->max_layer_depth_allowed = 0;
1767     set_baseline_gf_interval(cpi, i, active_max_gf_interval, use_alt_ref,
1768                              is_final_pass);
1769 
1770     rc->gfu_boost = AOMMIN(
1771         MAX_GF_BOOST,
1772         av1_calc_arf_boost(
1773             twopass, rc, frame_info, alt_offset, (i - 1), 0,
1774             cpi->lap_enabled ? &rc->num_stats_used_for_gfu_boost : NULL,
1775             cpi->lap_enabled ? &rc->num_stats_required_for_gfu_boost : NULL));
1776   }
1777 
1778   // rc->gf_intervals assumes the usage of alt_ref, therefore adding one overlay
1779   // frame to the next gf. If no alt_ref is used, should substract 1 frame from
1780   // the next gf group.
1781   // TODO(bohanli): should incorporate the usage of alt_ref into
1782   // calculate_gf_length
1783   if (is_final_pass && rc->source_alt_ref_pending == 0 &&
1784       rc->intervals_till_gf_calculate_due > 0) {
1785     rc->gf_intervals[rc->cur_gf_index]--;
1786   }
1787 
1788 #define LAST_ALR_BOOST_FACTOR 0.2f
1789   rc->arf_boost_factor = 1.0;
1790   if (rc->source_alt_ref_pending && !is_lossless_requested(&cpi->oxcf)) {
1791     // Reduce the boost of altref in the last gf group
1792     if (rc->frames_to_key - i == REDUCE_GF_LENGTH_BY ||
1793         rc->frames_to_key - i == 0) {
1794       rc->arf_boost_factor = LAST_ALR_BOOST_FACTOR;
1795     }
1796   }
1797 
1798   rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1799 
1800   // Reset the file position.
1801   reset_fpf_position(twopass, start_pos);
1802 
1803   // Calculate the bits to be allocated to the gf/arf group as a whole
1804   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_stats.gf_group_err);
1805   rc->gf_group_bits = gf_group_bits;
1806 
1807 #if GROUP_ADAPTIVE_MAXQ
1808   // Calculate an estimate of the maxq needed for the group.
1809   // We are more agressive about correcting for sections
1810   // where there could be significant overshoot than for easier
1811   // sections where we do not wish to risk creating an overshoot
1812   // of the allocated bit budget.
1813   if ((cpi->oxcf.rc_mode != AOM_Q) && (rc->baseline_gf_interval > 1)) {
1814     const int vbr_group_bits_per_frame =
1815         (int)(gf_group_bits / rc->baseline_gf_interval);
1816     const double group_av_err =
1817         gf_stats.gf_group_raw_error / rc->baseline_gf_interval;
1818     const double group_av_skip_pct =
1819         gf_stats.gf_group_skip_pct / rc->baseline_gf_interval;
1820     const double group_av_inactive_zone =
1821         ((gf_stats.gf_group_inactive_zone_rows * 2) /
1822          (rc->baseline_gf_interval * (double)cm->mi_params.mb_rows));
1823 
1824     int tmp_q;
1825     // rc factor is a weight factor that corrects for local rate control drift.
1826     double rc_factor = 1.0;
1827     int64_t bits = cpi->oxcf.target_bandwidth;
1828 
1829     if (bits > 0) {
1830       int rate_error;
1831 
1832       rate_error = (int)((rc->vbr_bits_off_target * 100) / bits);
1833       rate_error = clamp(rate_error, -100, 100);
1834       if (rate_error > 0) {
1835         rc_factor = AOMMAX(RC_FACTOR_MIN, (double)(100 - rate_error) / 100.0);
1836       } else {
1837         rc_factor = AOMMIN(RC_FACTOR_MAX, (double)(100 - rate_error) / 100.0);
1838       }
1839     }
1840 
1841     tmp_q = get_twopass_worst_quality(
1842         cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
1843         vbr_group_bits_per_frame, rc_factor);
1844     rc->active_worst_quality = AOMMAX(tmp_q, rc->active_worst_quality >> 1);
1845   }
1846 #endif
1847 
1848   // Adjust KF group bits and error remaining.
1849   if (is_final_pass)
1850     twopass->kf_group_error_left -= (int64_t)gf_stats.gf_group_err;
1851 
1852   // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
1853   av1_gop_setup_structure(cpi, frame_params);
1854 
1855   // Reset the file position.
1856   reset_fpf_position(twopass, start_pos);
1857 
1858   // Calculate a section intra ratio used in setting max loop filter.
1859   if (frame_params->frame_type != KEY_FRAME) {
1860     twopass->section_intra_rating = calculate_section_intra_ratio(
1861         start_pos, twopass->stats_buf_ctx->stats_in_end,
1862         rc->baseline_gf_interval);
1863   }
1864 
1865   // Reset rolling actual and target bits counters for ARF groups.
1866   twopass->rolling_arf_group_target_bits = 1;
1867   twopass->rolling_arf_group_actual_bits = 1;
1868 
1869   av1_gop_bit_allocation(cpi, rc, gf_group,
1870                          frame_params->frame_type == KEY_FRAME, use_alt_ref,
1871                          gf_group_bits);
1872 }
1873 
1874 // #define FIXED_ARF_BITS
1875 #ifdef FIXED_ARF_BITS
1876 #define ARF_BITS_FRACTION 0.75
1877 #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)1878 void av1_gop_bit_allocation(const AV1_COMP *cpi, RATE_CONTROL *const rc,
1879                             GF_GROUP *gf_group, int is_key_frame, int use_arf,
1880                             int64_t gf_group_bits) {
1881   // Calculate the extra bits to be used for boosted frame(s)
1882 #ifdef FIXED_ARF_BITS
1883   int gf_arf_bits = (int)(ARF_BITS_FRACTION * gf_group_bits);
1884 #else
1885   int gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval,
1886                                          rc->gfu_boost, gf_group_bits);
1887 #endif
1888 
1889   gf_arf_bits = adjust_boost_bits_for_target_level(cpi, rc, gf_arf_bits,
1890                                                    gf_group_bits, 1);
1891 
1892   // Allocate bits to each of the frames in the GF group.
1893   allocate_gf_group_bits(gf_group, rc, gf_group_bits, gf_arf_bits, is_key_frame,
1894                          use_arf);
1895 }
1896 
1897 // Minimum % intra coding observed in first pass (1.0 = 100%)
1898 #define MIN_INTRA_LEVEL 0.25
1899 // Minimum ratio between the % of intra coding and inter coding in the first
1900 // pass after discounting neutral blocks (discounting neutral blocks in this
1901 // way helps catch scene cuts in clips with very flat areas or letter box
1902 // format clips with image padding.
1903 #define INTRA_VS_INTER_THRESH 2.0
1904 // Hard threshold where the first pass chooses intra for almost all blocks.
1905 // In such a case even if the frame is not a scene cut coding a key frame
1906 // may be a good option.
1907 #define VERY_LOW_INTER_THRESH 0.05
1908 // Maximum threshold for the relative ratio of intra error score vs best
1909 // inter error score.
1910 #define KF_II_ERR_THRESHOLD 2.5
1911 // In real scene cuts there is almost always a sharp change in the intra
1912 // or inter error score.
1913 #define ERR_CHANGE_THRESHOLD 0.4
1914 // For real scene cuts we expect an improvment in the intra inter error
1915 // ratio in the next frame.
1916 #define II_IMPROVEMENT_THRESHOLD 3.5
1917 #define KF_II_MAX 128.0
1918 
1919 // Threshold for use of the lagging second reference frame. High second ref
1920 // usage may point to a transient event like a flash or occlusion rather than
1921 // a real scene cut.
1922 // We adapt the threshold based on number of frames in this key-frame group so
1923 // far.
get_second_ref_usage_thresh(int frame_count_so_far)1924 static double get_second_ref_usage_thresh(int frame_count_so_far) {
1925   const int adapt_upto = 32;
1926   const double min_second_ref_usage_thresh = 0.085;
1927   const double second_ref_usage_thresh_max_delta = 0.035;
1928   if (frame_count_so_far >= adapt_upto) {
1929     return min_second_ref_usage_thresh + second_ref_usage_thresh_max_delta;
1930   }
1931   return min_second_ref_usage_thresh +
1932          ((double)frame_count_so_far / (adapt_upto - 1)) *
1933              second_ref_usage_thresh_max_delta;
1934 }
1935 
test_candidate_kf(TWO_PASS * twopass,const FIRSTPASS_STATS * last_frame,const FIRSTPASS_STATS * this_frame,const FIRSTPASS_STATS * next_frame,int frame_count_so_far,enum aom_rc_mode rc_mode)1936 static int test_candidate_kf(TWO_PASS *twopass,
1937                              const FIRSTPASS_STATS *last_frame,
1938                              const FIRSTPASS_STATS *this_frame,
1939                              const FIRSTPASS_STATS *next_frame,
1940                              int frame_count_so_far, enum aom_rc_mode rc_mode) {
1941   int is_viable_kf = 0;
1942   double pcnt_intra = 1.0 - this_frame->pcnt_inter;
1943   double modified_pcnt_inter =
1944       this_frame->pcnt_inter - this_frame->pcnt_neutral;
1945   const double second_ref_usage_thresh =
1946       get_second_ref_usage_thresh(frame_count_so_far);
1947 
1948   // Does the frame satisfy the primary criteria of a key frame?
1949   // See above for an explanation of the test criteria.
1950   // If so, then examine how well it predicts subsequent frames.
1951   if (IMPLIES(rc_mode == AOM_Q, frame_count_so_far >= 3) &&
1952       (this_frame->pcnt_second_ref < second_ref_usage_thresh) &&
1953       (next_frame->pcnt_second_ref < second_ref_usage_thresh) &&
1954       ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
1955        ((pcnt_intra > MIN_INTRA_LEVEL) &&
1956         (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
1957         ((this_frame->intra_error /
1958           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
1959          KF_II_ERR_THRESHOLD) &&
1960         ((fabs(last_frame->coded_error - this_frame->coded_error) /
1961               DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
1962           ERR_CHANGE_THRESHOLD) ||
1963          (fabs(last_frame->intra_error - this_frame->intra_error) /
1964               DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
1965           ERR_CHANGE_THRESHOLD) ||
1966          ((next_frame->intra_error /
1967            DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) >
1968           II_IMPROVEMENT_THRESHOLD))))) {
1969     int i;
1970     const FIRSTPASS_STATS *start_pos = twopass->stats_in;
1971     FIRSTPASS_STATS local_next_frame = *next_frame;
1972     double boost_score = 0.0;
1973     double old_boost_score = 0.0;
1974     double decay_accumulator = 1.0;
1975 
1976     // Examine how well the key frame predicts subsequent frames.
1977     for (i = 0; i < SCENE_CUT_KEY_TEST_INTERVAL; ++i) {
1978       double next_iiratio = (BOOST_FACTOR * local_next_frame.intra_error /
1979                              DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
1980 
1981       if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
1982 
1983       // Cumulative effect of decay in prediction quality.
1984       if (local_next_frame.pcnt_inter > 0.85)
1985         decay_accumulator *= local_next_frame.pcnt_inter;
1986       else
1987         decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
1988 
1989       // Keep a running total.
1990       boost_score += (decay_accumulator * next_iiratio);
1991 
1992       // Test various breakout clauses.
1993       if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
1994           (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
1995             0.20) &&
1996            (next_iiratio < 3.0)) ||
1997           ((boost_score - old_boost_score) < 3.0) ||
1998           (local_next_frame.intra_error < 200)) {
1999         break;
2000       }
2001 
2002       old_boost_score = boost_score;
2003 
2004       // Get the next frame details
2005       if (EOF == input_stats(twopass, &local_next_frame)) break;
2006     }
2007 
2008     // If there is tolerable prediction for at least the next 3 frames then
2009     // break out else discard this potential key frame and move on
2010     if (boost_score > 30.0 && (i > 3)) {
2011       is_viable_kf = 1;
2012     } else {
2013       // Reset the file position
2014       reset_fpf_position(twopass, start_pos);
2015 
2016       is_viable_kf = 0;
2017     }
2018   }
2019 
2020   return is_viable_kf;
2021 }
2022 
2023 #define FRAMES_TO_CHECK_DECAY 8
2024 #define KF_MIN_FRAME_BOOST 80.0
2025 #define KF_MAX_FRAME_BOOST 128.0
2026 #define MIN_KF_BOOST 600  // Minimum boost for non-static KF interval
2027 #define MAX_KF_BOOST 3200
2028 #define MIN_STATIC_KF_BOOST 5400  // Minimum boost for static KF interval
2029 
detect_app_forced_key(AV1_COMP * cpi)2030 static int detect_app_forced_key(AV1_COMP *cpi) {
2031   if (cpi->oxcf.fwd_kf_enabled) cpi->rc.next_is_fwd_key = 1;
2032   int num_frames_to_app_forced_key = is_forced_keyframe_pending(
2033       cpi->lookahead, cpi->lookahead->max_sz, cpi->compressor_stage);
2034   if (num_frames_to_app_forced_key != -1) cpi->rc.next_is_fwd_key = 0;
2035   return num_frames_to_app_forced_key;
2036 }
2037 
get_projected_kf_boost(AV1_COMP * cpi)2038 static int get_projected_kf_boost(AV1_COMP *cpi) {
2039   /*
2040    * If num_stats_used_for_kf_boost >= frames_to_key, then
2041    * all stats needed for prior boost calculation are available.
2042    * Hence projecting the prior boost is not needed in this cases.
2043    */
2044   if (cpi->rc.num_stats_used_for_kf_boost >= cpi->rc.frames_to_key)
2045     return cpi->rc.kf_boost;
2046 
2047   // Get the current tpl factor (number of frames = frames_to_key).
2048   double tpl_factor = av1_get_kf_boost_projection_factor(cpi->rc.frames_to_key);
2049   // Get the tpl factor when number of frames = num_stats_used_for_kf_boost.
2050   double tpl_factor_num_stats =
2051       av1_get_kf_boost_projection_factor(cpi->rc.num_stats_used_for_kf_boost);
2052   int projected_kf_boost =
2053       (int)rint((tpl_factor * cpi->rc.kf_boost) / tpl_factor_num_stats);
2054   return projected_kf_boost;
2055 }
2056 
define_kf_interval(AV1_COMP * cpi,FIRSTPASS_STATS * this_frame,double * kf_group_err,int num_frames_to_detect_scenecut)2057 static int define_kf_interval(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame,
2058                               double *kf_group_err,
2059                               int num_frames_to_detect_scenecut) {
2060   TWO_PASS *const twopass = &cpi->twopass;
2061   RATE_CONTROL *const rc = &cpi->rc;
2062   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2063   double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
2064   FIRSTPASS_STATS last_frame;
2065   double decay_accumulator = 1.0;
2066   int i = 0, j;
2067   int frames_to_key = 1;
2068   int frames_since_key = rc->frames_since_key + 1;
2069   FRAME_INFO *const frame_info = &cpi->frame_info;
2070   int num_stats_used_for_kf_boost = 1;
2071   int scenecut_detected = 0;
2072 
2073   int num_frames_to_next_key = detect_app_forced_key(cpi);
2074 
2075   if (num_frames_to_detect_scenecut == 0) {
2076     if (num_frames_to_next_key != -1)
2077       return num_frames_to_next_key;
2078     else
2079       return rc->frames_to_key;
2080   }
2081 
2082   if (num_frames_to_next_key != -1)
2083     num_frames_to_detect_scenecut =
2084         AOMMIN(num_frames_to_detect_scenecut, num_frames_to_next_key);
2085 
2086   // Initialize the decay rates for the recent frames to check
2087   for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
2088 
2089   i = 0;
2090   while (twopass->stats_in < twopass->stats_buf_ctx->stats_in_end &&
2091          frames_to_key < num_frames_to_detect_scenecut) {
2092     // Accumulate total number of stats available till next key frame
2093     num_stats_used_for_kf_boost++;
2094 
2095     // Accumulate kf group error.
2096     if (kf_group_err != NULL)
2097       *kf_group_err +=
2098           calculate_modified_err(frame_info, twopass, oxcf, this_frame);
2099 
2100     // Load the next frame's stats.
2101     last_frame = *this_frame;
2102     input_stats(twopass, this_frame);
2103 
2104     // Provided that we are not at the end of the file...
2105     if (cpi->rc.enable_scenecut_detection && cpi->oxcf.auto_key &&
2106         twopass->stats_in < twopass->stats_buf_ctx->stats_in_end) {
2107       double loop_decay_rate;
2108 
2109       // Check for a scene cut.
2110       if (test_candidate_kf(twopass, &last_frame, this_frame, twopass->stats_in,
2111                             frames_since_key, oxcf->rc_mode)) {
2112         scenecut_detected = 1;
2113         break;
2114       }
2115 
2116       // How fast is the prediction quality decaying?
2117       loop_decay_rate =
2118           get_prediction_decay_rate(frame_info, twopass->stats_in);
2119 
2120       // We want to know something about the recent past... rather than
2121       // as used elsewhere where we are concerned with decay in prediction
2122       // quality since the last GF or KF.
2123       recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
2124       decay_accumulator = 1.0;
2125       for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
2126         decay_accumulator *= recent_loop_decay[j];
2127 
2128       // Special check for transition or high motion followed by a
2129       // static scene.
2130       if (detect_transition_to_still(twopass, rc->min_gf_interval, i,
2131                                      cpi->oxcf.key_freq - i, loop_decay_rate,
2132                                      decay_accumulator)) {
2133         scenecut_detected = 1;
2134         break;
2135       }
2136 
2137       // Step on to the next frame.
2138       ++frames_to_key;
2139       ++frames_since_key;
2140 
2141       // If we don't have a real key frame within the next two
2142       // key_freq intervals then break out of the loop.
2143       if (frames_to_key >= 2 * cpi->oxcf.key_freq) break;
2144     } else {
2145       ++frames_to_key;
2146       ++frames_since_key;
2147     }
2148     ++i;
2149   }
2150 
2151   if (kf_group_err != NULL)
2152     rc->num_stats_used_for_kf_boost = num_stats_used_for_kf_boost;
2153 
2154   if (cpi->lap_enabled && !scenecut_detected)
2155     frames_to_key = num_frames_to_next_key;
2156 
2157   return frames_to_key;
2158 }
2159 
find_next_key_frame(AV1_COMP * cpi,FIRSTPASS_STATS * this_frame)2160 static void find_next_key_frame(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2161   RATE_CONTROL *const rc = &cpi->rc;
2162   TWO_PASS *const twopass = &cpi->twopass;
2163   GF_GROUP *const gf_group = &cpi->gf_group;
2164   FRAME_INFO *const frame_info = &cpi->frame_info;
2165   AV1_COMMON *const cm = &cpi->common;
2166   CurrentFrame *const current_frame = &cm->current_frame;
2167   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2168   const FIRSTPASS_STATS first_frame = *this_frame;
2169   FIRSTPASS_STATS next_frame;
2170   av1_zero(next_frame);
2171 
2172   rc->frames_since_key = 0;
2173 
2174   // Reset the GF group data structures.
2175   av1_zero(*gf_group);
2176 
2177   // Clear the alt ref active flag and last group multi arf flags as they
2178   // can never be set for a key frame.
2179   rc->source_alt_ref_active = 0;
2180 
2181   // KF is always a GF so clear frames till next gf counter.
2182   rc->frames_till_gf_update_due = 0;
2183 
2184   rc->frames_to_key = 1;
2185 
2186   if (has_no_stats_stage(cpi)) {
2187     int num_frames_to_app_forced_key = detect_app_forced_key(cpi);
2188     rc->this_key_frame_forced =
2189         current_frame->frame_number != 0 && rc->frames_to_key == 0;
2190     if (num_frames_to_app_forced_key != -1)
2191       rc->frames_to_key = num_frames_to_app_forced_key;
2192     else
2193       rc->frames_to_key = AOMMAX(1, cpi->oxcf.key_freq);
2194     correct_frames_to_key(cpi);
2195     rc->kf_boost = DEFAULT_KF_BOOST;
2196     rc->source_alt_ref_active = 0;
2197     gf_group->update_type[0] = KF_UPDATE;
2198     return;
2199   }
2200   int i;
2201   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
2202   int kf_bits = 0;
2203   double zero_motion_accumulator = 1.0;
2204   double boost_score = 0.0;
2205   double kf_raw_err = 0.0;
2206   double kf_mod_err = 0.0;
2207   double kf_group_err = 0.0;
2208   double sr_accumulator = 0.0;
2209   int frames_to_key;
2210   // Is this a forced key frame by interval.
2211   rc->this_key_frame_forced = rc->next_key_frame_forced;
2212 
2213   twopass->kf_group_bits = 0;        // Total bits available to kf group
2214   twopass->kf_group_error_left = 0;  // Group modified error score.
2215 
2216   kf_raw_err = this_frame->intra_error;
2217   kf_mod_err = calculate_modified_err(frame_info, twopass, oxcf, this_frame);
2218 
2219   frames_to_key =
2220       define_kf_interval(cpi, this_frame, &kf_group_err, oxcf->key_freq);
2221 
2222   if (frames_to_key != -1)
2223     rc->frames_to_key = AOMMIN(oxcf->key_freq, frames_to_key);
2224   else
2225     rc->frames_to_key = oxcf->key_freq;
2226 
2227   if (cpi->lap_enabled) correct_frames_to_key(cpi);
2228 
2229   // If there is a max kf interval set by the user we must obey it.
2230   // We already breakout of the loop above at 2x max.
2231   // This code centers the extra kf if the actual natural interval
2232   // is between 1x and 2x.
2233   if (cpi->oxcf.auto_key && rc->frames_to_key > cpi->oxcf.key_freq) {
2234     FIRSTPASS_STATS tmp_frame = first_frame;
2235 
2236     rc->frames_to_key /= 2;
2237 
2238     // Reset to the start of the group.
2239     reset_fpf_position(twopass, start_position);
2240 
2241     kf_group_err = 0.0;
2242 
2243     // Rescan to get the correct error data for the forced kf group.
2244     for (i = 0; i < rc->frames_to_key; ++i) {
2245       kf_group_err +=
2246           calculate_modified_err(frame_info, twopass, oxcf, &tmp_frame);
2247       if (EOF == input_stats(twopass, &tmp_frame)) break;
2248     }
2249     rc->next_key_frame_forced = 1;
2250   } else if ((twopass->stats_in == twopass->stats_buf_ctx->stats_in_end &&
2251               is_stat_consumption_stage_twopass(cpi)) ||
2252              rc->frames_to_key >= cpi->oxcf.key_freq) {
2253     rc->next_key_frame_forced = 1;
2254   } else {
2255     rc->next_key_frame_forced = 0;
2256   }
2257 
2258   // Special case for the last key frame of the file.
2259   if (twopass->stats_in >= twopass->stats_buf_ctx->stats_in_end) {
2260     // Accumulate kf group error.
2261     kf_group_err +=
2262         calculate_modified_err(frame_info, twopass, oxcf, this_frame);
2263   }
2264 
2265   // Calculate the number of bits that should be assigned to the kf group.
2266   if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
2267     // Maximum number of bits for a single normal frame (not key frame).
2268     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2269 
2270     // Maximum number of bits allocated to the key frame group.
2271     int64_t max_grp_bits;
2272 
2273     // Default allocation based on bits left and relative
2274     // complexity of the section.
2275     twopass->kf_group_bits = (int64_t)(
2276         twopass->bits_left * (kf_group_err / twopass->modified_error_left));
2277 
2278     // Clip based on maximum per frame rate defined by the user.
2279     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
2280     if (twopass->kf_group_bits > max_grp_bits)
2281       twopass->kf_group_bits = max_grp_bits;
2282   } else {
2283     twopass->kf_group_bits = 0;
2284   }
2285   twopass->kf_group_bits = AOMMAX(0, twopass->kf_group_bits);
2286 
2287   // Reset the first pass file position.
2288   reset_fpf_position(twopass, start_position);
2289 
2290   // Scan through the kf group collating various stats used to determine
2291   // how many bits to spend on it.
2292   boost_score = 0.0;
2293   const double kf_max_boost =
2294       cpi->oxcf.rc_mode == AOM_Q
2295           ? AOMMIN(AOMMAX(rc->frames_to_key * 2.0, KF_MIN_FRAME_BOOST),
2296                    KF_MAX_FRAME_BOOST)
2297           : KF_MAX_FRAME_BOOST;
2298   for (i = 0; i < (rc->frames_to_key - 1); ++i) {
2299     if (EOF == input_stats(twopass, &next_frame)) break;
2300 
2301     // Monitor for static sections.
2302     // For the first frame in kf group, the second ref indicator is invalid.
2303     if (i > 0) {
2304       zero_motion_accumulator =
2305           AOMMIN(zero_motion_accumulator,
2306                  get_zero_motion_factor(frame_info, &next_frame));
2307     } else {
2308       zero_motion_accumulator = next_frame.pcnt_inter - next_frame.pcnt_motion;
2309     }
2310 
2311     // Not all frames in the group are necessarily used in calculating boost.
2312     if ((sr_accumulator < (kf_raw_err * 1.50)) &&
2313         (i <= rc->max_gf_interval * 2)) {
2314       double frame_boost;
2315       double zm_factor;
2316 
2317       // Factor 0.75-1.25 based on how much of frame is static.
2318       zm_factor = (0.75 + (zero_motion_accumulator / 2.0));
2319 
2320       if (i < 2) sr_accumulator = 0.0;
2321       frame_boost = calc_kf_frame_boost(rc, frame_info, &next_frame,
2322                                         &sr_accumulator, kf_max_boost);
2323       boost_score += frame_boost * zm_factor;
2324     }
2325   }
2326 
2327   reset_fpf_position(twopass, start_position);
2328 
2329   // Store the zero motion percentage
2330   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
2331 
2332   // Calculate a section intra ratio used in setting max loop filter.
2333   twopass->section_intra_rating = calculate_section_intra_ratio(
2334       start_position, twopass->stats_buf_ctx->stats_in_end, rc->frames_to_key);
2335 
2336   rc->kf_boost = (int)boost_score;
2337 
2338   if (cpi->lap_enabled) {
2339     rc->kf_boost = get_projected_kf_boost(cpi);
2340   }
2341 
2342   // Special case for static / slide show content but don't apply
2343   // if the kf group is very short.
2344   if ((zero_motion_accumulator > STATIC_KF_GROUP_FLOAT_THRESH) &&
2345       (rc->frames_to_key > 8)) {
2346     rc->kf_boost = AOMMAX(rc->kf_boost, MIN_STATIC_KF_BOOST);
2347   } else {
2348     // Apply various clamps for min and max boost
2349     rc->kf_boost = AOMMAX(rc->kf_boost, (rc->frames_to_key * 3));
2350     rc->kf_boost = AOMMAX(rc->kf_boost, MIN_KF_BOOST);
2351 #ifdef STRICT_RC
2352     rc->kf_boost = AOMMIN(rc->kf_boost, MAX_KF_BOOST);
2353 #endif
2354   }
2355 
2356   // Work out how many bits to allocate for the key frame itself.
2357   kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
2358                                  twopass->kf_group_bits);
2359   // printf("kf boost = %d kf_bits = %d kf_zeromotion_pct = %d\n", rc->kf_boost,
2360   //        kf_bits, twopass->kf_zeromotion_pct);
2361   kf_bits = adjust_boost_bits_for_target_level(cpi, rc, kf_bits,
2362                                                twopass->kf_group_bits, 0);
2363 
2364   twopass->kf_group_bits -= kf_bits;
2365 
2366   // Save the bits to spend on the key frame.
2367   gf_group->bit_allocation[0] = kf_bits;
2368   gf_group->update_type[0] = KF_UPDATE;
2369 
2370   // Note the total error score of the kf group minus the key frame itself.
2371   twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
2372 
2373   // Adjust the count of total modified error left.
2374   // The count of bits left is adjusted elsewhere based on real coded frame
2375   // sizes.
2376   twopass->modified_error_left -= kf_group_err;
2377 }
2378 
is_skippable_frame(const AV1_COMP * cpi)2379 static int is_skippable_frame(const AV1_COMP *cpi) {
2380   if (has_no_stats_stage(cpi)) return 0;
2381   // If the current frame does not have non-zero motion vector detected in the
2382   // first  pass, and so do its previous and forward frames, then this frame
2383   // can be skipped for partition check, and the partition size is assigned
2384   // according to the variance
2385   const TWO_PASS *const twopass = &cpi->twopass;
2386 
2387   return (!frame_is_intra_only(&cpi->common) &&
2388           twopass->stats_in - 2 > twopass->stats_buf_ctx->stats_in_start &&
2389           twopass->stats_in < twopass->stats_buf_ctx->stats_in_end &&
2390           (twopass->stats_in - 1)->pcnt_inter -
2391                   (twopass->stats_in - 1)->pcnt_motion ==
2392               1 &&
2393           (twopass->stats_in - 2)->pcnt_inter -
2394                   (twopass->stats_in - 2)->pcnt_motion ==
2395               1 &&
2396           twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
2397 }
2398 
2399 #define ARF_STATS_OUTPUT 0
2400 #if ARF_STATS_OUTPUT
2401 unsigned int arf_count = 0;
2402 #endif
2403 #define DEFAULT_GRP_WEIGHT 1.0
2404 
process_first_pass_stats(AV1_COMP * cpi,FIRSTPASS_STATS * this_frame)2405 static void process_first_pass_stats(AV1_COMP *cpi,
2406                                      FIRSTPASS_STATS *this_frame) {
2407   AV1_COMMON *const cm = &cpi->common;
2408   CurrentFrame *const current_frame = &cm->current_frame;
2409   RATE_CONTROL *const rc = &cpi->rc;
2410   TWO_PASS *const twopass = &cpi->twopass;
2411 
2412   if (cpi->oxcf.rc_mode != AOM_Q && current_frame->frame_number == 0 &&
2413       cpi->twopass.stats_buf_ctx->total_stats &&
2414       cpi->twopass.stats_buf_ctx->total_left_stats) {
2415     if (cpi->lap_enabled) {
2416       /*
2417        * Accumulate total_stats using available limited number of stats,
2418        * and assign it to total_left_stats.
2419        */
2420       *cpi->twopass.stats_buf_ctx->total_left_stats =
2421           *cpi->twopass.stats_buf_ctx->total_stats;
2422     }
2423     const int frames_left = (int)(twopass->stats_buf_ctx->total_stats->count -
2424                                   current_frame->frame_number);
2425 
2426     // Special case code for first frame.
2427     const int section_target_bandwidth =
2428         (int)(twopass->bits_left / frames_left);
2429     const double section_length =
2430         twopass->stats_buf_ctx->total_left_stats->count;
2431     const double section_error =
2432         twopass->stats_buf_ctx->total_left_stats->coded_error / section_length;
2433     const double section_intra_skip =
2434         twopass->stats_buf_ctx->total_left_stats->intra_skip_pct /
2435         section_length;
2436     const double section_inactive_zone =
2437         (twopass->stats_buf_ctx->total_left_stats->inactive_zone_rows * 2) /
2438         ((double)cm->mi_params.mb_rows * section_length);
2439     const int tmp_q = get_twopass_worst_quality(
2440         cpi, section_error, section_intra_skip + section_inactive_zone,
2441         section_target_bandwidth, DEFAULT_GRP_WEIGHT);
2442 
2443     rc->active_worst_quality = tmp_q;
2444     rc->ni_av_qi = tmp_q;
2445     rc->last_q[INTER_FRAME] = tmp_q;
2446     rc->avg_q = av1_convert_qindex_to_q(tmp_q, cm->seq_params.bit_depth);
2447     rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
2448     rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
2449     rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
2450   }
2451 
2452   int err = 0;
2453   if (cpi->lap_enabled) {
2454     err = input_stats_lap(twopass, this_frame);
2455   } else {
2456     err = input_stats(twopass, this_frame);
2457   }
2458   if (err == EOF) return;
2459 
2460   {
2461     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
2462                             ? cpi->initial_mbs
2463                             : cm->mi_params.MBs;
2464     // The multiplication by 256 reverses a scaling factor of (>> 8)
2465     // applied when combining MB error values for the frame.
2466     twopass->mb_av_energy = log((this_frame->intra_error / num_mbs) + 1.0);
2467     twopass->frame_avg_haar_energy =
2468         log((this_frame->frame_avg_wavelet_energy / num_mbs) + 1.0);
2469   }
2470 
2471   // Update the total stats remaining structure.
2472   if (twopass->stats_buf_ctx->total_left_stats)
2473     subtract_stats(twopass->stats_buf_ctx->total_left_stats, this_frame);
2474 
2475   // Set the frame content type flag.
2476   if (this_frame->intra_skip_pct >= FC_ANIMATION_THRESH)
2477     twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
2478   else
2479     twopass->fr_content_type = FC_NORMAL;
2480 }
2481 
setup_target_rate(AV1_COMP * cpi)2482 static void setup_target_rate(AV1_COMP *cpi) {
2483   RATE_CONTROL *const rc = &cpi->rc;
2484   GF_GROUP *const gf_group = &cpi->gf_group;
2485 
2486   int target_rate = gf_group->bit_allocation[gf_group->index];
2487 
2488   if (has_no_stats_stage(cpi)) {
2489     av1_rc_set_frame_target(cpi, target_rate, cpi->common.width,
2490                             cpi->common.height);
2491   }
2492 
2493   rc->base_frame_target = target_rate;
2494 }
2495 
av1_get_second_pass_params(AV1_COMP * cpi,EncodeFrameParams * const frame_params,const EncodeFrameInput * const frame_input,unsigned int frame_flags)2496 void av1_get_second_pass_params(AV1_COMP *cpi,
2497                                 EncodeFrameParams *const frame_params,
2498                                 const EncodeFrameInput *const frame_input,
2499                                 unsigned int frame_flags) {
2500   RATE_CONTROL *const rc = &cpi->rc;
2501   TWO_PASS *const twopass = &cpi->twopass;
2502   GF_GROUP *const gf_group = &cpi->gf_group;
2503   AV1_COMMON *cm = &cpi->common;
2504 
2505   if (frame_is_intra_only(cm)) {
2506     FeatureFlags *const features = &cm->features;
2507     av1_set_screen_content_options(cpi, features);
2508     cpi->is_screen_content_type = features->allow_screen_content_tools;
2509   }
2510 
2511   if (is_stat_consumption_stage(cpi) && !twopass->stats_in) return;
2512 
2513   if (rc->frames_till_gf_update_due > 0 && !(frame_flags & FRAMEFLAGS_KEY)) {
2514     assert(gf_group->index < gf_group->size);
2515     const int update_type = gf_group->update_type[gf_group->index];
2516 
2517     setup_target_rate(cpi);
2518 
2519     // If this is an arf frame then we dont want to read the stats file or
2520     // advance the input pointer as we already have what we need.
2521     if (update_type == ARF_UPDATE || update_type == INTNL_ARF_UPDATE) {
2522       if (cpi->no_show_kf) {
2523         assert(update_type == ARF_UPDATE);
2524         frame_params->frame_type = KEY_FRAME;
2525       } else {
2526         frame_params->frame_type = INTER_FRAME;
2527       }
2528 
2529       // Do the firstpass stats indicate that this frame is skippable for the
2530       // partition search?
2531       if (cpi->sf.part_sf.allow_partition_search_skip && cpi->oxcf.pass == 2) {
2532         cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
2533       }
2534 
2535       return;
2536     }
2537   }
2538 
2539   aom_clear_system_state();
2540 
2541   if (cpi->oxcf.rc_mode == AOM_Q) rc->active_worst_quality = cpi->oxcf.cq_level;
2542   FIRSTPASS_STATS this_frame;
2543   av1_zero(this_frame);
2544   // call above fn
2545   if (is_stat_consumption_stage(cpi)) {
2546     process_first_pass_stats(cpi, &this_frame);
2547   } else {
2548     rc->active_worst_quality = cpi->oxcf.cq_level;
2549   }
2550 
2551   // Keyframe and section processing.
2552   if (rc->frames_to_key == 0 || (frame_flags & FRAMEFLAGS_KEY)) {
2553     FIRSTPASS_STATS this_frame_copy;
2554     this_frame_copy = this_frame;
2555     frame_params->frame_type = KEY_FRAME;
2556     // Define next KF group and assign bits to it.
2557     find_next_key_frame(cpi, &this_frame);
2558     this_frame = this_frame_copy;
2559   } else {
2560     frame_params->frame_type = INTER_FRAME;
2561     const int altref_enabled = is_altref_enabled(cpi);
2562     const int sframe_dist = cpi->oxcf.sframe_dist;
2563     const int sframe_mode = cpi->oxcf.sframe_mode;
2564     const int sframe_enabled = cpi->oxcf.sframe_enabled;
2565     const int update_type = gf_group->update_type[gf_group->index];
2566     CurrentFrame *const current_frame = &cpi->common.current_frame;
2567     if (sframe_enabled) {
2568       if (altref_enabled) {
2569         if (sframe_mode == 1) {
2570           // sframe_mode == 1: insert sframe if it matches altref frame.
2571           if (current_frame->frame_number % sframe_dist == 0 &&
2572               current_frame->frame_number != 0 && update_type == ARF_UPDATE) {
2573             frame_params->frame_type = S_FRAME;
2574           }
2575         } else {
2576           // sframe_mode != 1: if sframe will be inserted at the next available
2577           // altref frame
2578           if (current_frame->frame_number % sframe_dist == 0 &&
2579               current_frame->frame_number != 0) {
2580             rc->sframe_due = 1;
2581           }
2582           if (rc->sframe_due && update_type == ARF_UPDATE) {
2583             frame_params->frame_type = S_FRAME;
2584             rc->sframe_due = 0;
2585           }
2586         }
2587       } else {
2588         if (current_frame->frame_number % sframe_dist == 0 &&
2589             current_frame->frame_number != 0) {
2590           frame_params->frame_type = S_FRAME;
2591         }
2592       }
2593     }
2594   }
2595 
2596   // Define a new GF/ARF group. (Should always enter here for key frames).
2597   if (rc->frames_till_gf_update_due == 0) {
2598     assert(cpi->common.current_frame.frame_number == 0 ||
2599            gf_group->index == gf_group->size);
2600     const FIRSTPASS_STATS *const start_position = twopass->stats_in;
2601     int num_frames_to_detect_scenecut, frames_to_key;
2602     if (cpi->lap_enabled && cpi->rc.enable_scenecut_detection)
2603       num_frames_to_detect_scenecut = MAX_GF_LENGTH_LAP + 1;
2604     else
2605       num_frames_to_detect_scenecut = 0;
2606     frames_to_key = define_kf_interval(cpi, &this_frame, NULL,
2607                                        num_frames_to_detect_scenecut);
2608     reset_fpf_position(twopass, start_position);
2609     if (frames_to_key != -1)
2610       rc->frames_to_key = AOMMIN(rc->frames_to_key, frames_to_key);
2611 
2612     int max_gop_length = (cpi->oxcf.lag_in_frames >= 32 &&
2613                           is_stat_consumption_stage_twopass(cpi))
2614                              ? MAX_GF_INTERVAL
2615                              : MAX_GF_LENGTH_LAP;
2616     if (rc->intervals_till_gf_calculate_due == 0) {
2617       calculate_gf_length(cpi, max_gop_length, MAX_NUM_GF_INTERVALS);
2618     }
2619 
2620     if (max_gop_length > 16) {
2621       if (rc->gf_intervals[rc->cur_gf_index] - 1 > 16) {
2622         // The calculate_gf_length function is previously used with
2623         // max_gop_length = 32 with look-ahead gf intervals.
2624         define_gf_group(cpi, &this_frame, frame_params, max_gop_length, 0);
2625         if (!av1_tpl_setup_stats(cpi, 1, frame_params, frame_input)) {
2626           // Tpl decides that a shorter gf interval is better.
2627           // TODO(jingning): Remove redundant computations here.
2628           max_gop_length = 16;
2629           calculate_gf_length(cpi, max_gop_length, 1);
2630         }
2631       } else {
2632         // Even based on 32 we still decide to use a short gf interval.
2633         // Better to re-decide based on 16 then
2634         max_gop_length = 16;
2635         calculate_gf_length(cpi, max_gop_length, 1);
2636       }
2637     }
2638     define_gf_group(cpi, &this_frame, frame_params, max_gop_length, 1);
2639     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2640     cpi->num_gf_group_show_frames = 0;
2641     assert(gf_group->index == 0);
2642 
2643 #if ARF_STATS_OUTPUT
2644     {
2645       FILE *fpfile;
2646       fpfile = fopen("arf.stt", "a");
2647       ++arf_count;
2648       fprintf(fpfile, "%10d %10d %10d %10d %10d\n",
2649               cpi->common.current_frame.frame_number,
2650               rc->frames_till_gf_update_due, rc->kf_boost, arf_count,
2651               rc->gfu_boost);
2652 
2653       fclose(fpfile);
2654     }
2655 #endif
2656   }
2657   assert(gf_group->index < gf_group->size);
2658 
2659   // Do the firstpass stats indicate that this frame is skippable for the
2660   // partition search?
2661   if (cpi->sf.part_sf.allow_partition_search_skip && cpi->oxcf.pass == 2) {
2662     cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
2663   }
2664 
2665   setup_target_rate(cpi);
2666 }
2667 
av1_init_second_pass(AV1_COMP * cpi)2668 void av1_init_second_pass(AV1_COMP *cpi) {
2669   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2670   TWO_PASS *const twopass = &cpi->twopass;
2671   FRAME_INFO *const frame_info = &cpi->frame_info;
2672   double frame_rate;
2673   FIRSTPASS_STATS *stats;
2674 
2675   if (!twopass->stats_buf_ctx->stats_in_end) return;
2676 
2677   stats = twopass->stats_buf_ctx->total_stats;
2678 
2679   *stats = *twopass->stats_buf_ctx->stats_in_end;
2680   *twopass->stats_buf_ctx->total_left_stats = *stats;
2681 
2682   frame_rate = 10000000.0 * stats->count / stats->duration;
2683   // Each frame can have a different duration, as the frame rate in the source
2684   // isn't guaranteed to be constant. The frame rate prior to the first frame
2685   // encoded in the second pass is a guess. However, the sum duration is not.
2686   // It is calculated based on the actual durations of all frames from the
2687   // first pass.
2688   av1_new_framerate(cpi, frame_rate);
2689   twopass->bits_left =
2690       (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
2691 
2692   // This variable monitors how far behind the second ref update is lagging.
2693   twopass->sr_update_lag = 1;
2694 
2695   // Scan the first pass file and calculate a modified total error based upon
2696   // the bias/power function used to allocate bits.
2697   {
2698     const double avg_error =
2699         stats->coded_error / DOUBLE_DIVIDE_CHECK(stats->count);
2700     const FIRSTPASS_STATS *s = twopass->stats_in;
2701     double modified_error_total = 0.0;
2702     twopass->modified_error_min =
2703         (avg_error * oxcf->two_pass_vbrmin_section) / 100;
2704     twopass->modified_error_max =
2705         (avg_error * oxcf->two_pass_vbrmax_section) / 100;
2706     while (s < twopass->stats_buf_ctx->stats_in_end) {
2707       modified_error_total +=
2708           calculate_modified_err(frame_info, twopass, oxcf, s);
2709       ++s;
2710     }
2711     twopass->modified_error_left = modified_error_total;
2712   }
2713 
2714   // Reset the vbr bits off target counters
2715   cpi->rc.vbr_bits_off_target = 0;
2716   cpi->rc.vbr_bits_off_target_fast = 0;
2717 
2718   cpi->rc.rate_error_estimate = 0;
2719 
2720   // Static sequence monitor variables.
2721   twopass->kf_zeromotion_pct = 100;
2722   twopass->last_kfgroup_zeromotion_pct = 100;
2723 
2724   // Initialize bits per macro_block estimate correction factor.
2725   twopass->bpm_factor = 1.0;
2726   // Initialize actual and target bits counters for ARF groups so that
2727   // at the start we have a neutral bpm adjustment.
2728   twopass->rolling_arf_group_target_bits = 1;
2729   twopass->rolling_arf_group_actual_bits = 1;
2730 }
2731 
av1_init_single_pass_lap(AV1_COMP * cpi)2732 void av1_init_single_pass_lap(AV1_COMP *cpi) {
2733   TWO_PASS *const twopass = &cpi->twopass;
2734 
2735   if (!twopass->stats_buf_ctx->stats_in_end) return;
2736 
2737   // This variable monitors how far behind the second ref update is lagging.
2738   twopass->sr_update_lag = 1;
2739 
2740   twopass->bits_left = 0;
2741   twopass->modified_error_min = 0.0;
2742   twopass->modified_error_max = 0.0;
2743   twopass->modified_error_left = 0.0;
2744 
2745   // Reset the vbr bits off target counters
2746   cpi->rc.vbr_bits_off_target = 0;
2747   cpi->rc.vbr_bits_off_target_fast = 0;
2748 
2749   cpi->rc.rate_error_estimate = 0;
2750 
2751   // Static sequence monitor variables.
2752   twopass->kf_zeromotion_pct = 100;
2753   twopass->last_kfgroup_zeromotion_pct = 100;
2754 
2755   // Initialize bits per macro_block estimate correction factor.
2756   twopass->bpm_factor = 1.0;
2757   // Initialize actual and target bits counters for ARF groups so that
2758   // at the start we have a neutral bpm adjustment.
2759   twopass->rolling_arf_group_target_bits = 1;
2760   twopass->rolling_arf_group_actual_bits = 1;
2761 }
2762 
2763 #define MINQ_ADJ_LIMIT 48
2764 #define MINQ_ADJ_LIMIT_CQ 20
2765 #define HIGH_UNDERSHOOT_RATIO 2
av1_twopass_postencode_update(AV1_COMP * cpi)2766 void av1_twopass_postencode_update(AV1_COMP *cpi) {
2767   TWO_PASS *const twopass = &cpi->twopass;
2768   RATE_CONTROL *const rc = &cpi->rc;
2769   const int bits_used = rc->base_frame_target;
2770 
2771   // VBR correction is done through rc->vbr_bits_off_target. Based on the
2772   // sign of this value, a limited % adjustment is made to the target rate
2773   // of subsequent frames, to try and push it back towards 0. This method
2774   // is designed to prevent extreme behaviour at the end of a clip
2775   // or group of frames.
2776   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
2777   twopass->bits_left = AOMMAX(twopass->bits_left - bits_used, 0);
2778 
2779   // Target vs actual bits for this arf group.
2780   twopass->rolling_arf_group_target_bits += rc->this_frame_target;
2781   twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
2782 
2783   // Calculate the pct rc error.
2784   if (rc->total_actual_bits) {
2785     rc->rate_error_estimate =
2786         (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
2787     rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
2788   } else {
2789     rc->rate_error_estimate = 0;
2790   }
2791 
2792   // Update the active best quality pyramid.
2793   if (!rc->is_src_frame_alt_ref) {
2794     const int pyramid_level = cpi->gf_group.layer_depth[cpi->gf_group.index];
2795     int i;
2796     for (i = pyramid_level; i <= MAX_ARF_LAYERS; ++i) {
2797       rc->active_best_quality[i] = cpi->common.quant_params.base_qindex;
2798       // if (pyramid_level >= 2) {
2799       //   rc->active_best_quality[pyramid_level] =
2800       //     AOMMAX(rc->active_best_quality[pyramid_level],
2801       //            cpi->common.base_qindex);
2802       // }
2803     }
2804   }
2805 
2806 #if 0
2807   {
2808     AV1_COMMON *cm = &cpi->common;
2809     FILE *fpfile;
2810     fpfile = fopen("details.stt", "a");
2811     fprintf(fpfile,
2812             "%10d %10d %10d %10" PRId64 " %10" PRId64
2813             " %10d %10d %10d %10.4lf %10.4lf %10.4lf %10.4lf\n",
2814             cm->current_frame.frame_number, rc->base_frame_target,
2815             rc->projected_frame_size, rc->total_actual_bits,
2816             rc->vbr_bits_off_target, rc->rate_error_estimate,
2817             twopass->rolling_arf_group_target_bits,
2818             twopass->rolling_arf_group_actual_bits,
2819             (double)twopass->rolling_arf_group_actual_bits /
2820                 (double)twopass->rolling_arf_group_target_bits,
2821             twopass->bpm_factor,
2822             av1_convert_qindex_to_q(quant_params->base_qindex,
2823                                     cm->seq_params.bit_depth),
2824             av1_convert_qindex_to_q(rc->active_worst_quality,
2825                                     cm->seq_params.bit_depth));
2826     fclose(fpfile);
2827   }
2828 #endif
2829 
2830   if (cpi->common.current_frame.frame_type != KEY_FRAME) {
2831     twopass->kf_group_bits -= bits_used;
2832     twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
2833   }
2834   twopass->kf_group_bits = AOMMAX(twopass->kf_group_bits, 0);
2835 
2836   // If the rate control is drifting consider adjustment to min or maxq.
2837   if ((cpi->oxcf.rc_mode != AOM_Q) && !cpi->rc.is_src_frame_alt_ref) {
2838     const int maxq_adj_limit = rc->worst_quality - rc->active_worst_quality;
2839     const int minq_adj_limit =
2840         (cpi->oxcf.rc_mode == AOM_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
2841 
2842     // Undershoot.
2843     if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
2844       --twopass->extend_maxq;
2845       if (rc->rolling_target_bits >= rc->rolling_actual_bits)
2846         ++twopass->extend_minq;
2847       // Overshoot.
2848     } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
2849       --twopass->extend_minq;
2850       if (rc->rolling_target_bits < rc->rolling_actual_bits)
2851         ++twopass->extend_maxq;
2852     } else {
2853       // Adjustment for extreme local overshoot.
2854       if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
2855           rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
2856         ++twopass->extend_maxq;
2857 
2858       // Unwind undershoot or overshoot adjustment.
2859       if (rc->rolling_target_bits < rc->rolling_actual_bits)
2860         --twopass->extend_minq;
2861       else if (rc->rolling_target_bits > rc->rolling_actual_bits)
2862         --twopass->extend_maxq;
2863     }
2864 
2865     twopass->extend_minq = clamp(twopass->extend_minq, 0, minq_adj_limit);
2866     twopass->extend_maxq = clamp(twopass->extend_maxq, 0, maxq_adj_limit);
2867 
2868     // If there is a big and undexpected undershoot then feed the extra
2869     // bits back in quickly. One situation where this may happen is if a
2870     // frame is unexpectedly almost perfectly predicted by the ARF or GF
2871     // but not very well predcited by the previous frame.
2872     if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
2873       int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
2874       if (rc->projected_frame_size < fast_extra_thresh) {
2875         rc->vbr_bits_off_target_fast +=
2876             fast_extra_thresh - rc->projected_frame_size;
2877         rc->vbr_bits_off_target_fast =
2878             AOMMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
2879 
2880         // Fast adaptation of minQ if necessary to use up the extra bits.
2881         if (rc->avg_frame_bandwidth) {
2882           twopass->extend_minq_fast =
2883               (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
2884         }
2885         twopass->extend_minq_fast = AOMMIN(
2886             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
2887       } else if (rc->vbr_bits_off_target_fast) {
2888         twopass->extend_minq_fast = AOMMIN(
2889             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
2890       } else {
2891         twopass->extend_minq_fast = 0;
2892       }
2893     }
2894   }
2895 }
2896