• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/onyxc_int.h"
23 
24 #include "av1/encoder/encoder.h"
25 #include "av1/encoder/firstpass.h"
26 #include "av1/encoder/gop_structure.h"
27 
28 // Calculate an active area of the image that discounts formatting
29 // bars and partially discounts other 0 energy areas.
30 #define MIN_ACTIVE_AREA 0.5
31 #define MAX_ACTIVE_AREA 1.0
calculate_active_area(const AV1_COMP * cpi,const FIRSTPASS_STATS * this_frame)32 double calculate_active_area(const AV1_COMP *cpi,
33                              const FIRSTPASS_STATS *this_frame) {
34   double active_pct;
35 
36   active_pct =
37       1.0 -
38       ((this_frame->intra_skip_pct / 2) +
39        ((this_frame->inactive_zone_rows * 2) / (double)cpi->common.mb_rows));
40   return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
41 }
42 
43 // Calculate a modified Error used in distributing bits between easier and
44 // harder frames.
45 #define ACT_AREA_CORRECTION 0.5
calculate_modified_err(const AV1_COMP * cpi,const TWO_PASS * twopass,const AV1EncoderConfig * oxcf,const FIRSTPASS_STATS * this_frame)46 double calculate_modified_err(const AV1_COMP *cpi, const TWO_PASS *twopass,
47                               const AV1EncoderConfig *oxcf,
48                               const FIRSTPASS_STATS *this_frame) {
49   const FIRSTPASS_STATS *const stats = &twopass->total_stats;
50   const double av_weight = stats->weight / stats->count;
51   const double av_err = (stats->coded_error * av_weight) / stats->count;
52   double modified_error =
53       av_err * pow(this_frame->coded_error * this_frame->weight /
54                        DOUBLE_DIVIDE_CHECK(av_err),
55                    oxcf->two_pass_vbrbias / 100.0);
56 
57   // Correction for active area. Frames with a reduced active area
58   // (eg due to formatting bars) have a higher error per mb for the
59   // remaining active MBs. The correction here assumes that coding
60   // 0.5N blocks of complexity 2X is a little easier than coding N
61   // blocks of complexity X.
62   modified_error *=
63       pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);
64 
65   return fclamp(modified_error, twopass->modified_error_min,
66                 twopass->modified_error_max);
67 }
68 
69 // Resets the first pass file to the given position using a relative seek from
70 // the current position.
reset_fpf_position(TWO_PASS * p,const FIRSTPASS_STATS * position)71 static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
72   p->stats_in = position;
73 }
74 
input_stats(TWO_PASS * p,FIRSTPASS_STATS * fps)75 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
76   if (p->stats_in >= p->stats_in_end) return EOF;
77 
78   *fps = *p->stats_in;
79   ++p->stats_in;
80   return 1;
81 }
82 
83 // Read frame stats at an offset from the current position.
read_frame_stats(const TWO_PASS * p,int offset)84 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
85   if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
86       (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
87     return NULL;
88   }
89 
90   return &p->stats_in[offset];
91 }
92 
subtract_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)93 static void subtract_stats(FIRSTPASS_STATS *section,
94                            const FIRSTPASS_STATS *frame) {
95   section->frame -= frame->frame;
96   section->weight -= frame->weight;
97   section->intra_error -= frame->intra_error;
98   section->frame_avg_wavelet_energy -= frame->frame_avg_wavelet_energy;
99   section->coded_error -= frame->coded_error;
100   section->sr_coded_error -= frame->sr_coded_error;
101   section->pcnt_inter -= frame->pcnt_inter;
102   section->pcnt_motion -= frame->pcnt_motion;
103   section->pcnt_second_ref -= frame->pcnt_second_ref;
104   section->pcnt_neutral -= frame->pcnt_neutral;
105   section->intra_skip_pct -= frame->intra_skip_pct;
106   section->inactive_zone_rows -= frame->inactive_zone_rows;
107   section->inactive_zone_cols -= frame->inactive_zone_cols;
108   section->MVr -= frame->MVr;
109   section->mvr_abs -= frame->mvr_abs;
110   section->MVc -= frame->MVc;
111   section->mvc_abs -= frame->mvc_abs;
112   section->MVrv -= frame->MVrv;
113   section->MVcv -= frame->MVcv;
114   section->mv_in_out_count -= frame->mv_in_out_count;
115   section->new_mv_count -= frame->new_mv_count;
116   section->count -= frame->count;
117   section->duration -= frame->duration;
118 }
119 
120 // Calculate the linear size relative to a baseline of 1080P
121 #define BASE_SIZE 2073600.0  // 1920x1080
get_linear_size_factor(const AV1_COMP * cpi)122 static double get_linear_size_factor(const AV1_COMP *cpi) {
123   const double this_area = cpi->initial_width * cpi->initial_height;
124   return pow(this_area / BASE_SIZE, 0.5);
125 }
126 
127 // This function returns the maximum target rate per frame.
frame_max_bits(const RATE_CONTROL * rc,const AV1EncoderConfig * oxcf)128 static int frame_max_bits(const RATE_CONTROL *rc,
129                           const AV1EncoderConfig *oxcf) {
130   int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
131                       (int64_t)oxcf->two_pass_vbrmax_section) /
132                      100;
133   if (max_bits < 0)
134     max_bits = 0;
135   else if (max_bits > rc->max_frame_bandwidth)
136     max_bits = rc->max_frame_bandwidth;
137 
138   return (int)max_bits;
139 }
140 
calc_correction_factor(double err_per_mb,double err_divisor,double pt_low,double pt_high,int q,aom_bit_depth_t bit_depth)141 static double calc_correction_factor(double err_per_mb, double err_divisor,
142                                      double pt_low, double pt_high, int q,
143                                      aom_bit_depth_t bit_depth) {
144   const double error_term = err_per_mb / err_divisor;
145 
146   // Adjustment based on actual quantizer to power term.
147   const double power_term =
148       AOMMIN(av1_convert_qindex_to_q(q, bit_depth) * 0.01 + pt_low, pt_high);
149 
150   // Calculate correction factor.
151   if (power_term < 1.0) assert(error_term >= 0.0);
152 
153   return fclamp(pow(error_term, power_term), 0.05, 5.0);
154 }
155 
156 #define ERR_DIVISOR 100.0
157 #define FACTOR_PT_LOW 0.70
158 #define FACTOR_PT_HIGH 0.90
159 
160 // Similar to find_qindex_by_rate() function in ratectrl.c, but includes
161 // calculation of a correction_factor.
find_qindex_by_rate_with_correction(int desired_bits_per_mb,aom_bit_depth_t bit_depth,FRAME_TYPE frame_type,double error_per_mb,double ediv_size_correction,double group_weight_factor,int best_qindex,int worst_qindex)162 static int find_qindex_by_rate_with_correction(
163     int desired_bits_per_mb, aom_bit_depth_t bit_depth, FRAME_TYPE frame_type,
164     double error_per_mb, double ediv_size_correction,
165     double group_weight_factor, int best_qindex, int worst_qindex) {
166   assert(best_qindex <= worst_qindex);
167   int low = best_qindex;
168   int high = worst_qindex;
169   while (low < high) {
170     const int mid = (low + high) >> 1;
171     const double mid_factor =
172         calc_correction_factor(error_per_mb, ERR_DIVISOR - ediv_size_correction,
173                                FACTOR_PT_LOW, FACTOR_PT_HIGH, mid, bit_depth);
174     const int mid_bits_per_mb = av1_rc_bits_per_mb(
175         frame_type, mid, mid_factor * group_weight_factor, bit_depth);
176     if (mid_bits_per_mb > desired_bits_per_mb) {
177       low = mid + 1;
178     } else {
179       high = mid;
180     }
181   }
182 #if CONFIG_DEBUG
183   assert(low == high);
184   const double low_factor =
185       calc_correction_factor(error_per_mb, ERR_DIVISOR - ediv_size_correction,
186                              FACTOR_PT_LOW, FACTOR_PT_HIGH, low, bit_depth);
187   const int low_bits_per_mb = av1_rc_bits_per_mb(
188       frame_type, low, low_factor * group_weight_factor, bit_depth);
189   assert(low_bits_per_mb <= desired_bits_per_mb || low == worst_qindex);
190 #endif  // CONFIG_DEBUG
191   return low;
192 }
193 
get_twopass_worst_quality(const AV1_COMP * cpi,const double section_err,double inactive_zone,int section_target_bandwidth,double group_weight_factor)194 static int get_twopass_worst_quality(const AV1_COMP *cpi,
195                                      const double section_err,
196                                      double inactive_zone,
197                                      int section_target_bandwidth,
198                                      double group_weight_factor) {
199   const RATE_CONTROL *const rc = &cpi->rc;
200   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
201 
202   inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
203 
204   if (section_target_bandwidth <= 0) {
205     return rc->worst_quality;  // Highest value allowed
206   } else {
207     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
208                             ? cpi->initial_mbs
209                             : cpi->common.MBs;
210     const int active_mbs = AOMMAX(1, num_mbs - (int)(num_mbs * inactive_zone));
211     const double av_err_per_mb = section_err / active_mbs;
212     const int target_norm_bits_per_mb =
213         (int)((uint64_t)section_target_bandwidth << BPER_MB_NORMBITS) /
214         active_mbs;
215 
216     // Larger image formats are expected to be a little harder to code
217     // relatively given the same prediction error score. This in part at
218     // least relates to the increased size and hence coding overheads of
219     // motion vectors. Some account of this is made through adjustment of
220     // the error divisor.
221     double ediv_size_correction =
222         AOMMAX(0.2, AOMMIN(5.0, get_linear_size_factor(cpi)));
223     if (ediv_size_correction < 1.0)
224       ediv_size_correction = -(1.0 / ediv_size_correction);
225     ediv_size_correction *= 4.0;
226 
227     // Try and pick a max Q that will be high enough to encode the
228     // content at the given rate.
229     int q = find_qindex_by_rate_with_correction(
230         target_norm_bits_per_mb, cpi->common.seq_params.bit_depth, INTER_FRAME,
231         av_err_per_mb, ediv_size_correction, group_weight_factor,
232         rc->best_quality, rc->worst_quality);
233 
234     // Restriction on active max q for constrained quality mode.
235     if (cpi->oxcf.rc_mode == AOM_CQ) q = AOMMAX(q, oxcf->cq_level);
236     return q;
237   }
238 }
239 
240 #define SR_DIFF_PART 0.0015
241 #define MOTION_AMP_PART 0.003
242 #define INTRA_PART 0.005
243 #define DEFAULT_DECAY_LIMIT 0.75
244 #define LOW_SR_DIFF_TRHESH 0.1
245 #define SR_DIFF_MAX 128.0
246 #define NCOUNT_FRAME_II_THRESH 5.0
247 
get_sr_decay_rate(const AV1_COMP * cpi,const FIRSTPASS_STATS * frame)248 static double get_sr_decay_rate(const AV1_COMP *cpi,
249                                 const FIRSTPASS_STATS *frame) {
250   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
251                                                              : cpi->common.MBs;
252   double sr_diff = (frame->sr_coded_error - frame->coded_error) / num_mbs;
253   double sr_decay = 1.0;
254   double modified_pct_inter;
255   double modified_pcnt_intra;
256   const double motion_amplitude_factor =
257       frame->pcnt_motion * ((frame->mvc_abs + frame->mvr_abs) / 2);
258 
259   modified_pct_inter = frame->pcnt_inter;
260   if ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
261       (double)NCOUNT_FRAME_II_THRESH) {
262     modified_pct_inter = frame->pcnt_inter - frame->pcnt_neutral;
263   }
264   modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
265 
266   if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
267     sr_diff = AOMMIN(sr_diff, SR_DIFF_MAX);
268     sr_decay = 1.0 - (SR_DIFF_PART * sr_diff) -
269                (MOTION_AMP_PART * motion_amplitude_factor) -
270                (INTRA_PART * modified_pcnt_intra);
271   }
272   return AOMMAX(sr_decay, AOMMIN(DEFAULT_DECAY_LIMIT, modified_pct_inter));
273 }
274 
275 // This function gives an estimate of how badly we believe the prediction
276 // quality is decaying from frame to frame.
get_zero_motion_factor(const AV1_COMP * cpi,const FIRSTPASS_STATS * frame)277 static double get_zero_motion_factor(const AV1_COMP *cpi,
278                                      const FIRSTPASS_STATS *frame) {
279   const double zero_motion_pct = frame->pcnt_inter - frame->pcnt_motion;
280   double sr_decay = get_sr_decay_rate(cpi, frame);
281   return AOMMIN(sr_decay, zero_motion_pct);
282 }
283 
284 #define ZM_POWER_FACTOR 0.75
285 
get_prediction_decay_rate(const AV1_COMP * cpi,const FIRSTPASS_STATS * next_frame)286 static double get_prediction_decay_rate(const AV1_COMP *cpi,
287                                         const FIRSTPASS_STATS *next_frame) {
288   const double sr_decay_rate = get_sr_decay_rate(cpi, next_frame);
289   const double zero_motion_factor =
290       (0.95 * pow((next_frame->pcnt_inter - next_frame->pcnt_motion),
291                   ZM_POWER_FACTOR));
292 
293   return AOMMAX(zero_motion_factor,
294                 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
295 }
296 
297 // Function to test for a condition where a complex transition is followed
298 // by a static section. For example in slide shows where there is a fade
299 // between slides. This is to help with more optimal kf and gf positioning.
detect_transition_to_still(AV1_COMP * cpi,int frame_interval,int still_interval,double loop_decay_rate,double last_decay_rate)300 static int detect_transition_to_still(AV1_COMP *cpi, int frame_interval,
301                                       int still_interval,
302                                       double loop_decay_rate,
303                                       double last_decay_rate) {
304   TWO_PASS *const twopass = &cpi->twopass;
305   RATE_CONTROL *const rc = &cpi->rc;
306 
307   // Break clause to detect very still sections after motion
308   // For example a static image after a fade or other transition
309   // instead of a clean scene cut.
310   if (frame_interval > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
311       last_decay_rate < 0.9) {
312     int j;
313 
314     // Look ahead a few frames to see if static condition persists...
315     for (j = 0; j < still_interval; ++j) {
316       const FIRSTPASS_STATS *stats = &twopass->stats_in[j];
317       if (stats >= twopass->stats_in_end) break;
318 
319       if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
320     }
321 
322     // Only if it does do we signal a transition to still.
323     return j == still_interval;
324   }
325 
326   return 0;
327 }
328 
329 // This function detects a flash through the high relative pcnt_second_ref
330 // score in the frame following a flash frame. The offset passed in should
331 // reflect this.
detect_flash(const TWO_PASS * twopass,int offset)332 static int detect_flash(const TWO_PASS *twopass, int offset) {
333   const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
334 
335   // What we are looking for here is a situation where there is a
336   // brief break in prediction (such as a flash) but subsequent frames
337   // are reasonably well predicted by an earlier (pre flash) frame.
338   // The recovery after a flash is indicated by a high pcnt_second_ref
339   // compared to pcnt_inter.
340   return next_frame != NULL &&
341          next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
342          next_frame->pcnt_second_ref >= 0.5;
343 }
344 
345 // Update the motion related elements to the GF arf boost calculation.
accumulate_frame_motion_stats(const FIRSTPASS_STATS * stats,double * mv_in_out,double * mv_in_out_accumulator,double * abs_mv_in_out_accumulator,double * mv_ratio_accumulator)346 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
347                                           double *mv_in_out,
348                                           double *mv_in_out_accumulator,
349                                           double *abs_mv_in_out_accumulator,
350                                           double *mv_ratio_accumulator) {
351   const double pct = stats->pcnt_motion;
352 
353   // Accumulate Motion In/Out of frame stats.
354   *mv_in_out = stats->mv_in_out_count * pct;
355   *mv_in_out_accumulator += *mv_in_out;
356   *abs_mv_in_out_accumulator += fabs(*mv_in_out);
357 
358   // Accumulate a measure of how uniform (or conversely how random) the motion
359   // field is (a ratio of abs(mv) / mv).
360   if (pct > 0.05) {
361     const double mvr_ratio =
362         fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
363     const double mvc_ratio =
364         fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
365 
366     *mv_ratio_accumulator +=
367         pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
368     *mv_ratio_accumulator +=
369         pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
370   }
371 }
372 
373 #define BASELINE_ERR_PER_MB 1000.0
374 #define BOOST_FACTOR 12.5
375 
calc_frame_boost(AV1_COMP * cpi,const FIRSTPASS_STATS * this_frame,double this_frame_mv_in_out,double max_boost)376 static double calc_frame_boost(AV1_COMP *cpi, const FIRSTPASS_STATS *this_frame,
377                                double this_frame_mv_in_out, double max_boost) {
378   double frame_boost;
379   const double lq = av1_convert_qindex_to_q(
380       cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.seq_params.bit_depth);
381   const double boost_q_correction = AOMMIN((0.5 + (lq * 0.015)), 1.5);
382   int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
383                                                        : cpi->common.MBs;
384 
385   // Correct for any inactive region in the image
386   num_mbs = (int)AOMMAX(1, num_mbs * calculate_active_area(cpi, this_frame));
387 
388   // Underlying boost factor is based on inter error ratio.
389   frame_boost = (BASELINE_ERR_PER_MB * num_mbs) /
390                 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
391   frame_boost = frame_boost * BOOST_FACTOR * boost_q_correction;
392 
393   // Increase boost for frames where new data coming into frame (e.g. zoom out).
394   // Slightly reduce boost if there is a net balance of motion out of the frame
395   // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
396   if (this_frame_mv_in_out > 0.0)
397     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
398   // In the extreme case the boost is halved.
399   else
400     frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
401 
402   return AOMMIN(frame_boost, max_boost * boost_q_correction);
403 }
404 
405 #define GF_MAX_BOOST 90.0
406 #define MIN_ARF_GF_BOOST 240
407 #define MIN_DECAY_FACTOR 0.01
408 
calc_arf_boost(AV1_COMP * cpi,int offset,int f_frames,int b_frames,int * f_boost,int * b_boost)409 static int calc_arf_boost(AV1_COMP *cpi, int offset, int f_frames, int b_frames,
410                           int *f_boost, int *b_boost) {
411   TWO_PASS *const twopass = &cpi->twopass;
412   int i;
413   double boost_score = 0.0;
414   double mv_ratio_accumulator = 0.0;
415   double decay_accumulator = 1.0;
416   double this_frame_mv_in_out = 0.0;
417   double mv_in_out_accumulator = 0.0;
418   double abs_mv_in_out_accumulator = 0.0;
419   int arf_boost;
420   int flash_detected = 0;
421 
422   // Search forward from the proposed arf/next gf position.
423   for (i = 0; i < f_frames; ++i) {
424     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
425     if (this_frame == NULL) break;
426 
427     // Update the motion related elements to the boost calculation.
428     accumulate_frame_motion_stats(
429         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
430         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
431 
432     // We want to discount the flash frame itself and the recovery
433     // frame that follows as both will have poor scores.
434     flash_detected = detect_flash(twopass, i + offset) ||
435                      detect_flash(twopass, i + offset + 1);
436 
437     // Accumulate the effect of prediction quality decay.
438     if (!flash_detected) {
439       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
440       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
441                               ? MIN_DECAY_FACTOR
442                               : decay_accumulator;
443     }
444 
445     boost_score +=
446         decay_accumulator *
447         calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
448   }
449 
450   *f_boost = (int)boost_score;
451 
452   // Reset for backward looking loop.
453   boost_score = 0.0;
454   mv_ratio_accumulator = 0.0;
455   decay_accumulator = 1.0;
456   this_frame_mv_in_out = 0.0;
457   mv_in_out_accumulator = 0.0;
458   abs_mv_in_out_accumulator = 0.0;
459 
460   // Search backward towards last gf position.
461   for (i = -1; i >= -b_frames; --i) {
462     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
463     if (this_frame == NULL) break;
464 
465     // Update the motion related elements to the boost calculation.
466     accumulate_frame_motion_stats(
467         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
468         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
469 
470     // We want to discount the the flash frame itself and the recovery
471     // frame that follows as both will have poor scores.
472     flash_detected = detect_flash(twopass, i + offset) ||
473                      detect_flash(twopass, i + offset + 1);
474 
475     // Cumulative effect of prediction quality decay.
476     if (!flash_detected) {
477       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
478       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
479                               ? MIN_DECAY_FACTOR
480                               : decay_accumulator;
481     }
482 
483     boost_score +=
484         decay_accumulator *
485         calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
486   }
487   *b_boost = (int)boost_score;
488 
489   arf_boost = (*f_boost + *b_boost);
490   if (arf_boost < ((b_frames + f_frames) * 20))
491     arf_boost = ((b_frames + f_frames) * 20);
492   arf_boost = AOMMAX(arf_boost, MIN_ARF_GF_BOOST);
493 
494   return arf_boost;
495 }
496 
497 // 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)498 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
499                                          const FIRSTPASS_STATS *end,
500                                          int section_length) {
501   const FIRSTPASS_STATS *s = begin;
502   double intra_error = 0.0;
503   double coded_error = 0.0;
504   int i = 0;
505 
506   while (s < end && i < section_length) {
507     intra_error += s->intra_error;
508     coded_error += s->coded_error;
509     ++s;
510     ++i;
511   }
512 
513   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
514 }
515 
516 // Calculate the total bits to allocate in this GF/ARF group.
calculate_total_gf_group_bits(AV1_COMP * cpi,double gf_group_err)517 static int64_t calculate_total_gf_group_bits(AV1_COMP *cpi,
518                                              double gf_group_err) {
519   const RATE_CONTROL *const rc = &cpi->rc;
520   const TWO_PASS *const twopass = &cpi->twopass;
521   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
522   int64_t total_group_bits;
523 
524   // Calculate the bits to be allocated to the group as a whole.
525   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
526     total_group_bits = (int64_t)(twopass->kf_group_bits *
527                                  (gf_group_err / twopass->kf_group_error_left));
528   } else {
529     total_group_bits = 0;
530   }
531 
532   // Clamp odd edge cases.
533   total_group_bits = (total_group_bits < 0)
534                          ? 0
535                          : (total_group_bits > twopass->kf_group_bits)
536                                ? twopass->kf_group_bits
537                                : total_group_bits;
538 
539   // Clip based on user supplied data rate variability limit.
540   if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
541     total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
542 
543   return total_group_bits;
544 }
545 
546 // Calculate the number bits extra to assign to boosted frames in a group.
calculate_boost_bits(int frame_count,int boost,int64_t total_group_bits)547 static int calculate_boost_bits(int frame_count, int boost,
548                                 int64_t total_group_bits) {
549   int allocation_chunks;
550 
551   // return 0 for invalid inputs (could arise e.g. through rounding errors)
552   if (!boost || (total_group_bits <= 0) || (frame_count <= 0)) return 0;
553 
554   allocation_chunks = (frame_count * 100) + boost;
555 
556   // Prevent overflow.
557   if (boost > 1023) {
558     int divisor = boost >> 10;
559     boost /= divisor;
560     allocation_chunks /= divisor;
561   }
562 
563   // Calculate the number of extra bits for use in the boosted frame or frames.
564   return AOMMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
565                 0);
566 }
567 
568 #define LEAF_REDUCTION_FACTOR 0.75
569 static double lvl_budget_factor[MAX_PYRAMID_LVL - 1][MAX_PYRAMID_LVL - 1] = {
570   { 1.0, 0.0, 0.0 }, { 0.6, 0.4, 0 }, { 0.45, 0.35, 0.20 }
571 };
allocate_gf_group_bits(AV1_COMP * cpi,int64_t gf_group_bits,double group_error,int gf_arf_bits,const EncodeFrameParams * const frame_params)572 static void allocate_gf_group_bits(
573     AV1_COMP *cpi, int64_t gf_group_bits, double group_error, int gf_arf_bits,
574     const EncodeFrameParams *const frame_params) {
575   RATE_CONTROL *const rc = &cpi->rc;
576   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
577   TWO_PASS *const twopass = &cpi->twopass;
578   GF_GROUP *const gf_group = &twopass->gf_group;
579   const int key_frame = (frame_params->frame_type == KEY_FRAME);
580   const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
581   int64_t total_group_bits = gf_group_bits;
582 
583   // Check if GF group has any internal arfs.
584   int has_internal_arfs = 0;
585   for (int i = 0; i < gf_group->size; ++i) {
586     if (gf_group->update_type[i] == INTNL_ARF_UPDATE) {
587       has_internal_arfs = 1;
588       break;
589     }
590   }
591 
592   // For key frames the frame target rate is already set and it
593   // is also the golden frame.
594   // === [frame_index == 0] ===
595   int frame_index = 0;
596   if (!key_frame) {
597     if (rc->source_alt_ref_active)
598       gf_group->bit_allocation[frame_index] = 0;
599     else
600       gf_group->bit_allocation[frame_index] = gf_arf_bits;
601 
602     // Step over the golden frame / overlay frame
603     FIRSTPASS_STATS frame_stats;
604     if (EOF == input_stats(twopass, &frame_stats)) return;
605   }
606 
607   // Deduct the boost bits for arf (or gf if it is not a key frame)
608   // from the group total.
609   if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
610 
611   frame_index++;
612 
613   // Store the bits to spend on the ARF if there is one.
614   // === [frame_index == 1] ===
615   if (rc->source_alt_ref_pending) {
616     gf_group->bit_allocation[frame_index] = gf_arf_bits;
617 
618     ++frame_index;
619 
620     // Skip all the internal ARFs right after ARF at the starting segment of
621     // the current GF group.
622     if (has_internal_arfs) {
623       while (gf_group->update_type[frame_index] == INTNL_ARF_UPDATE) {
624         ++frame_index;
625       }
626     }
627   }
628 
629   // Save.
630   const int tmp_frame_index = frame_index;
631   int budget_reduced_from_leaf_level = 0;
632 
633   // Allocate bits to frames other than first frame, which is either a keyframe,
634   // overlay frame or golden frame.
635   const int normal_frames = rc->baseline_gf_interval - 1;
636 
637   for (int i = 0; i < normal_frames; ++i) {
638     FIRSTPASS_STATS frame_stats;
639     if (EOF == input_stats(twopass, &frame_stats)) break;
640 
641     const double modified_err =
642         calculate_modified_err(cpi, twopass, oxcf, &frame_stats);
643     const double err_fraction =
644         (group_error > 0) ? modified_err / DOUBLE_DIVIDE_CHECK(group_error)
645                           : 0.0;
646     const int target_frame_size =
647         clamp((int)((double)total_group_bits * err_fraction), 0,
648               AOMMIN(max_bits, (int)total_group_bits));
649 
650     if (gf_group->update_type[frame_index] == INTNL_OVERLAY_UPDATE) {
651       assert(gf_group->pyramid_height <= MAX_PYRAMID_LVL &&
652              "non-valid height for a pyramid structure");
653 
654       const int arf_pos = gf_group->arf_pos_in_gf[frame_index];
655       gf_group->bit_allocation[frame_index] = 0;
656 
657       gf_group->bit_allocation[arf_pos] = target_frame_size;
658       // Note: Boost, if needed, is added in the next loop.
659     } else {
660       assert(gf_group->update_type[frame_index] == LF_UPDATE);
661       gf_group->bit_allocation[frame_index] = target_frame_size;
662       if (has_internal_arfs) {
663         const int this_budget_reduction =
664             (int)(target_frame_size * LEAF_REDUCTION_FACTOR);
665         gf_group->bit_allocation[frame_index] -= this_budget_reduction;
666         budget_reduced_from_leaf_level += this_budget_reduction;
667       }
668     }
669 
670     ++frame_index;
671 
672     // Skip all the internal ARFs.
673     if (has_internal_arfs) {
674       while (gf_group->update_type[frame_index] == INTNL_ARF_UPDATE)
675         ++frame_index;
676     }
677   }
678 
679   if (budget_reduced_from_leaf_level > 0) {
680     assert(has_internal_arfs);
681     // Restore.
682     frame_index = tmp_frame_index;
683 
684     // Re-distribute this extra budget to overlay frames in the group.
685     for (int i = 0; i < normal_frames; ++i) {
686       if (gf_group->update_type[frame_index] == INTNL_OVERLAY_UPDATE) {
687         assert(gf_group->pyramid_height <= MAX_PYRAMID_LVL &&
688                "non-valid height for a pyramid structure");
689         const int arf_pos = gf_group->arf_pos_in_gf[frame_index];
690         const int this_lvl = gf_group->pyramid_level[arf_pos];
691         const int dist2top = gf_group->pyramid_height - 1 - this_lvl;
692         const double lvl_boost_factor =
693             lvl_budget_factor[gf_group->pyramid_height - 2][dist2top];
694         const int extra_size =
695             (int)(budget_reduced_from_leaf_level * lvl_boost_factor /
696                   gf_group->pyramid_lvl_nodes[this_lvl]);
697         gf_group->bit_allocation[arf_pos] += extra_size;
698       }
699       ++frame_index;
700 
701       // Skip all the internal ARFs.
702       if (has_internal_arfs) {
703         while (gf_group->update_type[frame_index] == INTNL_ARF_UPDATE) {
704           ++frame_index;
705         }
706       }
707     }
708   }
709 }
710 
711 // Given the maximum allowed height of the pyramid structure, return the fixed
712 // GF length to be used.
get_fixed_gf_length(int max_pyr_height)713 static INLINE int get_fixed_gf_length(int max_pyr_height) {
714   (void)max_pyr_height;
715   return MAX_GF_INTERVAL;
716 }
717 
718 // Returns true if KF group and GF group both are almost completely static.
is_almost_static(double gf_zero_motion,int kf_zero_motion)719 static INLINE int is_almost_static(double gf_zero_motion, int kf_zero_motion) {
720   return (gf_zero_motion >= 0.995) &&
721          (kf_zero_motion >= STATIC_KF_GROUP_THRESH);
722 }
723 
724 #define ARF_ABS_ZOOM_THRESH 4.4
725 #define GROUP_ADAPTIVE_MAXQ 1
726 #if GROUP_ADAPTIVE_MAXQ
727 #define RC_FACTOR_MIN 0.75
728 #define RC_FACTOR_MAX 1.75
729 #endif  // GROUP_ADAPTIVE_MAXQ
730 #define MIN_FWD_KF_INTERVAL 8
731 
732 // Analyse and define a gf/arf group.
define_gf_group(AV1_COMP * cpi,FIRSTPASS_STATS * this_frame,const EncodeFrameParams * const frame_params)733 static void define_gf_group(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame,
734                             const EncodeFrameParams *const frame_params) {
735   AV1_COMMON *const cm = &cpi->common;
736   RATE_CONTROL *const rc = &cpi->rc;
737   AV1EncoderConfig *const oxcf = &cpi->oxcf;
738   TWO_PASS *const twopass = &cpi->twopass;
739   FIRSTPASS_STATS next_frame;
740   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
741   int i;
742 
743   double boost_score = 0.0;
744   double gf_group_err = 0.0;
745 #if GROUP_ADAPTIVE_MAXQ
746   double gf_group_raw_error = 0.0;
747 #endif
748   double gf_group_skip_pct = 0.0;
749   double gf_group_inactive_zone_rows = 0.0;
750   double gf_first_frame_err = 0.0;
751   double mod_frame_err = 0.0;
752 
753   double mv_ratio_accumulator = 0.0;
754   double decay_accumulator = 1.0;
755   double zero_motion_accumulator = 1.0;
756 
757   double loop_decay_rate = 1.00;
758   double last_loop_decay_rate = 1.00;
759 
760   double this_frame_mv_in_out = 0.0;
761   double mv_in_out_accumulator = 0.0;
762   double abs_mv_in_out_accumulator = 0.0;
763 
764   unsigned int allow_alt_ref = is_altref_enabled(cpi);
765 
766   int f_boost = 0;
767   int b_boost = 0;
768   int flash_detected;
769   int64_t gf_group_bits;
770   double gf_group_error_left;
771   int gf_arf_bits;
772   const int is_intra_only = frame_params->frame_type == KEY_FRAME ||
773                             frame_params->frame_type == INTRA_ONLY_FRAME;
774   const int arf_active_or_kf = is_intra_only || rc->source_alt_ref_active;
775 
776   cpi->internal_altref_allowed = (oxcf->gf_max_pyr_height > 1);
777 
778   // Reset the GF group data structures unless this is a key
779   // frame in which case it will already have been done.
780   if (!is_intra_only) {
781     av1_zero(twopass->gf_group);
782   }
783 
784   aom_clear_system_state();
785   av1_zero(next_frame);
786 
787   // Load stats for the current frame.
788   mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
789 
790   // Note the error of the frame at the start of the group. This will be
791   // the GF frame error if we code a normal gf.
792   gf_first_frame_err = mod_frame_err;
793 
794   // If this is a key frame or the overlay from a previous arf then
795   // the error score / cost of this frame has already been accounted for.
796   if (arf_active_or_kf) {
797     gf_group_err -= gf_first_frame_err;
798 #if GROUP_ADAPTIVE_MAXQ
799     gf_group_raw_error -= this_frame->coded_error;
800 #endif
801     gf_group_skip_pct -= this_frame->intra_skip_pct;
802     gf_group_inactive_zone_rows -= this_frame->inactive_zone_rows;
803   }
804   // Motion breakout threshold for loop below depends on image size.
805   const double mv_ratio_accumulator_thresh =
806       (cpi->initial_height + cpi->initial_width) / 4.0;
807 
808   // TODO(urvang): Try logic to vary min and max interval based on q.
809   const int active_min_gf_interval = rc->min_gf_interval;
810   const int active_max_gf_interval =
811       AOMMIN(rc->max_gf_interval, get_fixed_gf_length(oxcf->gf_max_pyr_height));
812 
813   double avg_sr_coded_error = 0;
814   double avg_raw_err_stdev = 0;
815   int non_zero_stdev_count = 0;
816 
817   i = 0;
818   while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
819     ++i;
820 
821     // Accumulate error score of frames in this gf group.
822     mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
823     gf_group_err += mod_frame_err;
824 #if GROUP_ADAPTIVE_MAXQ
825     gf_group_raw_error += this_frame->coded_error;
826 #endif
827     gf_group_skip_pct += this_frame->intra_skip_pct;
828     gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
829 
830     if (EOF == input_stats(twopass, &next_frame)) break;
831 
832     // Test for the case where there is a brief flash but the prediction
833     // quality back to an earlier frame is then restored.
834     flash_detected = detect_flash(twopass, 0);
835 
836     // Update the motion related elements to the boost calculation.
837     accumulate_frame_motion_stats(
838         &next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
839         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
840     // sum up the metric values of current gf group
841     avg_sr_coded_error += next_frame.sr_coded_error;
842     if (fabs(next_frame.raw_error_stdev) > 0.000001) {
843       non_zero_stdev_count++;
844       avg_raw_err_stdev += next_frame.raw_error_stdev;
845     }
846 
847     // Accumulate the effect of prediction quality decay.
848     if (!flash_detected) {
849       last_loop_decay_rate = loop_decay_rate;
850       loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
851 
852       decay_accumulator = decay_accumulator * loop_decay_rate;
853 
854       // Monitor for static sections.
855       if ((rc->frames_since_key + i - 1) > 1) {
856         zero_motion_accumulator = AOMMIN(
857             zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
858       }
859 
860       // Break clause to detect very still sections after motion. For example,
861       // a static image after a fade or other transition.
862       if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
863                                      last_loop_decay_rate)) {
864         allow_alt_ref = 0;
865         break;
866       }
867     }
868 
869     // Calculate a boost number for this frame.
870     boost_score +=
871         decay_accumulator *
872         calc_frame_boost(cpi, &next_frame, this_frame_mv_in_out, GF_MAX_BOOST);
873     // If almost totally static, we will not use the the max GF length later,
874     // so we can continue for more frames.
875     if ((i >= active_max_gf_interval + 1) &&
876         !is_almost_static(zero_motion_accumulator,
877                           twopass->kf_zeromotion_pct)) {
878       break;
879     }
880 
881     // Some conditions to breakout after min interval.
882     if (i >= active_min_gf_interval &&
883         // If possible don't break very close to a kf
884         (rc->frames_to_key - i >= rc->min_gf_interval) && (i & 0x01) &&
885         !flash_detected &&
886         (mv_ratio_accumulator > mv_ratio_accumulator_thresh ||
887          abs_mv_in_out_accumulator > ARF_ABS_ZOOM_THRESH)) {
888       break;
889     }
890     *this_frame = next_frame;
891   }
892 
893   // Was the group length constrained by the requirement for a new KF?
894   rc->constrained_gf_group = (i >= rc->frames_to_key) ? 1 : 0;
895 
896   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
897                                                              : cpi->common.MBs;
898   assert(num_mbs > 0);
899   if (i) avg_sr_coded_error /= i;
900 
901   if (non_zero_stdev_count) avg_raw_err_stdev /= non_zero_stdev_count;
902 
903   // Disable internal ARFs for "still" gf groups.
904   //   zero_motion_accumulator: minimum percentage of (0,0) motion;
905   //   avg_sr_coded_error:      average of the SSE per pixel of each frame;
906   //   avg_raw_err_stdev:       average of the standard deviation of (0,0)
907   //                            motion error per block of each frame.
908   if (zero_motion_accumulator > MIN_ZERO_MOTION &&
909       avg_sr_coded_error / num_mbs < MAX_SR_CODED_ERROR &&
910       avg_raw_err_stdev < MAX_RAW_ERR_VAR) {
911     cpi->internal_altref_allowed = 0;
912   }
913 
914   const int use_alt_ref =
915       !is_almost_static(zero_motion_accumulator, twopass->kf_zeromotion_pct) &&
916       allow_alt_ref && (i < cpi->oxcf.lag_in_frames) &&
917       (i >= rc->min_gf_interval) &&
918       (cpi->oxcf.gf_max_pyr_height > MIN_PYRAMID_LVL);
919 
920 #define REDUCE_GF_LENGTH_THRESH 4
921 #define REDUCE_GF_LENGTH_TO_KEY_THRESH 9
922 #define REDUCE_GF_LENGTH_BY 1
923   int alt_offset = 0;
924   // The length reduction strategy is tweaked for certain cases, and doesn't
925   // work well for certain other cases.
926   const int allow_gf_length_reduction =
927       ((cpi->oxcf.rc_mode == AOM_Q && cpi->oxcf.cq_level <= 128) ||
928        !cpi->internal_altref_allowed) &&
929       !is_lossless_requested(&cpi->oxcf);
930 
931   if (allow_gf_length_reduction && use_alt_ref) {
932     // adjust length of this gf group if one of the following condition met
933     // 1: only one overlay frame left and this gf is too long
934     // 2: next gf group is too short to have arf compared to the current gf
935 
936     // maximum length of next gf group
937     const int next_gf_len = rc->frames_to_key - i;
938     const int single_overlay_left =
939         next_gf_len == 0 && i > REDUCE_GF_LENGTH_THRESH;
940     // the next gf is probably going to have a ARF but it will be shorter than
941     // this gf
942     const int unbalanced_gf =
943         i > REDUCE_GF_LENGTH_TO_KEY_THRESH &&
944         next_gf_len + 1 < REDUCE_GF_LENGTH_TO_KEY_THRESH &&
945         next_gf_len + 1 >= rc->min_gf_interval;
946 
947     if (single_overlay_left || unbalanced_gf) {
948       const int roll_back = REDUCE_GF_LENGTH_BY;
949       // Reduce length only if active_min_gf_interval will be respected later.
950       if (i - roll_back >= active_min_gf_interval + 1) {
951         alt_offset = -roll_back;
952         i -= roll_back;
953       }
954     }
955   }
956 
957   // Should we use the alternate reference frame.
958   if (use_alt_ref) {
959     // Calculate the boost for alt ref.
960     rc->gfu_boost =
961         calc_arf_boost(cpi, alt_offset, (i - 1), (i - 1), &f_boost, &b_boost);
962     rc->source_alt_ref_pending = 1;
963 
964     // do not replace ARFs with overlay frames, and keep it as GOLDEN_REF
965     cpi->preserve_arf_as_gld = 1;
966   } else {
967     rc->gfu_boost = AOMMAX((int)boost_score, MIN_ARF_GF_BOOST);
968     rc->source_alt_ref_pending = 0;
969     cpi->preserve_arf_as_gld = 0;
970   }
971 
972   // Set the interval until the next gf.
973   // If forward keyframes are enabled, ensure the final gf group obeys the
974   // MIN_FWD_KF_INTERVAL.
975   if (cpi->oxcf.fwd_kf_enabled &&
976       ((twopass->stats_in - i + rc->frames_to_key) < twopass->stats_in_end)) {
977     if (i == rc->frames_to_key) {
978       rc->baseline_gf_interval = i;
979       // if the last gf group will be smaller than MIN_FWD_KF_INTERVAL
980     } else if ((rc->frames_to_key - i <
981                 AOMMAX(MIN_FWD_KF_INTERVAL, rc->min_gf_interval)) &&
982                (rc->frames_to_key != i)) {
983       // if possible, merge the last two gf groups
984       if (rc->frames_to_key <= active_max_gf_interval) {
985         rc->baseline_gf_interval = rc->frames_to_key;
986         // if merging the last two gf groups creates a group that is too long,
987         // split them and force the last gf group to be the MIN_FWD_KF_INTERVAL
988       } else {
989         rc->baseline_gf_interval = rc->frames_to_key - MIN_FWD_KF_INTERVAL;
990       }
991     } else {
992       rc->baseline_gf_interval = i - rc->source_alt_ref_pending;
993     }
994   } else {
995     rc->baseline_gf_interval = i - rc->source_alt_ref_pending;
996   }
997 
998 #define LAST_ALR_BOOST_FACTOR 0.2f
999   rc->arf_boost_factor = 1.0;
1000   if (rc->source_alt_ref_pending && !is_lossless_requested(&cpi->oxcf)) {
1001     // Reduce the boost of altref in the last gf group
1002     if (rc->frames_to_key - i == REDUCE_GF_LENGTH_BY ||
1003         rc->frames_to_key - i == 0) {
1004       rc->arf_boost_factor = LAST_ALR_BOOST_FACTOR;
1005     }
1006   }
1007 
1008   rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1009 
1010   // Reset the file position.
1011   reset_fpf_position(twopass, start_pos);
1012 
1013   // Calculate the bits to be allocated to the gf/arf group as a whole
1014   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
1015 
1016 #if GROUP_ADAPTIVE_MAXQ
1017   // Calculate an estimate of the maxq needed for the group.
1018   // We are more agressive about correcting for sections
1019   // where there could be significant overshoot than for easier
1020   // sections where we do not wish to risk creating an overshoot
1021   // of the allocated bit budget.
1022   if ((cpi->oxcf.rc_mode != AOM_Q) && (rc->baseline_gf_interval > 1)) {
1023     const int vbr_group_bits_per_frame =
1024         (int)(gf_group_bits / rc->baseline_gf_interval);
1025     const double group_av_err = gf_group_raw_error / rc->baseline_gf_interval;
1026     const double group_av_skip_pct =
1027         gf_group_skip_pct / rc->baseline_gf_interval;
1028     const double group_av_inactive_zone =
1029         ((gf_group_inactive_zone_rows * 2) /
1030          (rc->baseline_gf_interval * (double)cm->mb_rows));
1031 
1032     int tmp_q;
1033     // rc factor is a weight factor that corrects for local rate control drift.
1034     double rc_factor = 1.0;
1035     if (rc->rate_error_estimate > 0) {
1036       rc_factor = AOMMAX(RC_FACTOR_MIN,
1037                          (double)(100 - rc->rate_error_estimate) / 100.0);
1038     } else {
1039       rc_factor = AOMMIN(RC_FACTOR_MAX,
1040                          (double)(100 - rc->rate_error_estimate) / 100.0);
1041     }
1042     tmp_q = get_twopass_worst_quality(
1043         cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
1044         vbr_group_bits_per_frame, twopass->kfgroup_inter_fraction * rc_factor);
1045     twopass->active_worst_quality =
1046         AOMMAX(tmp_q, twopass->active_worst_quality >> 1);
1047   }
1048 #endif
1049 
1050   // Calculate the extra bits to be used for boosted frame(s)
1051   gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval, rc->gfu_boost,
1052                                      gf_group_bits);
1053 
1054   // Adjust KF group bits and error remaining.
1055   twopass->kf_group_error_left -= (int64_t)gf_group_err;
1056 
1057   // If this is an arf update we want to remove the score for the overlay
1058   // frame at the end which will usually be very cheap to code.
1059   // The overlay frame has already, in effect, been coded so we want to spread
1060   // the remaining bits among the other frames.
1061   // For normal GFs remove the score for the GF itself unless this is
1062   // also a key frame in which case it has already been accounted for.
1063   if (rc->source_alt_ref_pending) {
1064     gf_group_error_left = gf_group_err - mod_frame_err;
1065   } else if (!is_intra_only) {
1066     gf_group_error_left = gf_group_err - gf_first_frame_err;
1067   } else {
1068     gf_group_error_left = gf_group_err;
1069   }
1070 
1071   // Set up the structure of this Group-Of-Pictures (same as GF_GROUP)
1072   av1_gop_setup_structure(cpi, frame_params);
1073 
1074   // Allocate bits to each of the frames in the GF group.
1075   allocate_gf_group_bits(cpi, gf_group_bits, gf_group_error_left, gf_arf_bits,
1076                          frame_params);
1077 
1078   // Reset the file position.
1079   reset_fpf_position(twopass, start_pos);
1080 
1081   // Calculate a section intra ratio used in setting max loop filter.
1082   if (frame_params->frame_type != KEY_FRAME) {
1083     twopass->section_intra_rating = calculate_section_intra_ratio(
1084         start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
1085   }
1086 }
1087 
1088 // Minimum % intra coding observed in first pass (1.0 = 100%)
1089 #define MIN_INTRA_LEVEL 0.25
1090 // Minimum ratio between the % of intra coding and inter coding in the first
1091 // pass after discounting neutral blocks (discounting neutral blocks in this
1092 // way helps catch scene cuts in clips with very flat areas or letter box
1093 // format clips with image padding.
1094 #define INTRA_VS_INTER_THRESH 2.0
1095 // Hard threshold where the first pass chooses intra for almost all blocks.
1096 // In such a case even if the frame is not a scene cut coding a key frame
1097 // may be a good option.
1098 #define VERY_LOW_INTER_THRESH 0.05
1099 // Maximum threshold for the relative ratio of intra error score vs best
1100 // inter error score.
1101 #define KF_II_ERR_THRESHOLD 2.5
1102 // In real scene cuts there is almost always a sharp change in the intra
1103 // or inter error score.
1104 #define ERR_CHANGE_THRESHOLD 0.4
1105 // For real scene cuts we expect an improvment in the intra inter error
1106 // ratio in the next frame.
1107 #define II_IMPROVEMENT_THRESHOLD 3.5
1108 #define KF_II_MAX 128.0
1109 
1110 // Threshold for use of the lagging second reference frame. High second ref
1111 // usage may point to a transient event like a flash or occlusion rather than
1112 // a real scene cut.
1113 // We adapt the threshold based on number of frames in this key-frame group so
1114 // far.
get_second_ref_usage_thresh(int frame_count_so_far)1115 static double get_second_ref_usage_thresh(int frame_count_so_far) {
1116   const int adapt_upto = 32;
1117   const double min_second_ref_usage_thresh = 0.085;
1118   const double second_ref_usage_thresh_max_delta = 0.035;
1119   if (frame_count_so_far >= adapt_upto) {
1120     return min_second_ref_usage_thresh + second_ref_usage_thresh_max_delta;
1121   }
1122   return min_second_ref_usage_thresh +
1123          ((double)frame_count_so_far / (adapt_upto - 1)) *
1124              second_ref_usage_thresh_max_delta;
1125 }
1126 
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)1127 static int test_candidate_kf(TWO_PASS *twopass,
1128                              const FIRSTPASS_STATS *last_frame,
1129                              const FIRSTPASS_STATS *this_frame,
1130                              const FIRSTPASS_STATS *next_frame,
1131                              int frame_count_so_far) {
1132   int is_viable_kf = 0;
1133   double pcnt_intra = 1.0 - this_frame->pcnt_inter;
1134   double modified_pcnt_inter =
1135       this_frame->pcnt_inter - this_frame->pcnt_neutral;
1136   const double second_ref_usage_thresh =
1137       get_second_ref_usage_thresh(frame_count_so_far);
1138 
1139   // Does the frame satisfy the primary criteria of a key frame?
1140   // See above for an explanation of the test criteria.
1141   // If so, then examine how well it predicts subsequent frames.
1142   if ((this_frame->pcnt_second_ref < second_ref_usage_thresh) &&
1143       (next_frame->pcnt_second_ref < second_ref_usage_thresh) &&
1144       ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
1145        ((pcnt_intra > MIN_INTRA_LEVEL) &&
1146         (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
1147         ((this_frame->intra_error /
1148           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
1149          KF_II_ERR_THRESHOLD) &&
1150         ((fabs(last_frame->coded_error - this_frame->coded_error) /
1151               DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
1152           ERR_CHANGE_THRESHOLD) ||
1153          (fabs(last_frame->intra_error - this_frame->intra_error) /
1154               DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
1155           ERR_CHANGE_THRESHOLD) ||
1156          ((next_frame->intra_error /
1157            DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) >
1158           II_IMPROVEMENT_THRESHOLD))))) {
1159     int i;
1160     const FIRSTPASS_STATS *start_pos = twopass->stats_in;
1161     FIRSTPASS_STATS local_next_frame = *next_frame;
1162     double boost_score = 0.0;
1163     double old_boost_score = 0.0;
1164     double decay_accumulator = 1.0;
1165 
1166     // Examine how well the key frame predicts subsequent frames.
1167     for (i = 0; i < 16; ++i) {
1168       double next_iiratio = (BOOST_FACTOR * local_next_frame.intra_error /
1169                              DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
1170 
1171       if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
1172 
1173       // Cumulative effect of decay in prediction quality.
1174       if (local_next_frame.pcnt_inter > 0.85)
1175         decay_accumulator *= local_next_frame.pcnt_inter;
1176       else
1177         decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
1178 
1179       // Keep a running total.
1180       boost_score += (decay_accumulator * next_iiratio);
1181 
1182       // Test various breakout clauses.
1183       if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
1184           (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
1185             0.20) &&
1186            (next_iiratio < 3.0)) ||
1187           ((boost_score - old_boost_score) < 3.0) ||
1188           (local_next_frame.intra_error < 200)) {
1189         break;
1190       }
1191 
1192       old_boost_score = boost_score;
1193 
1194       // Get the next frame details
1195       if (EOF == input_stats(twopass, &local_next_frame)) break;
1196     }
1197 
1198     // If there is tolerable prediction for at least the next 3 frames then
1199     // break out else discard this potential key frame and move on
1200     if (boost_score > 30.0 && (i > 3)) {
1201       is_viable_kf = 1;
1202     } else {
1203       // Reset the file position
1204       reset_fpf_position(twopass, start_pos);
1205 
1206       is_viable_kf = 0;
1207     }
1208   }
1209 
1210   return is_viable_kf;
1211 }
1212 
1213 #define FRAMES_TO_CHECK_DECAY 8
1214 #define KF_MIN_FRAME_BOOST 80.0
1215 #define KF_MAX_FRAME_BOOST 128.0
1216 #define MIN_KF_BOOST 300          // Minimum boost for non-static KF interval
1217 #define MIN_STATIC_KF_BOOST 5400  // Minimum boost for static KF interval
1218 
find_next_key_frame(AV1_COMP * cpi,FIRSTPASS_STATS * this_frame)1219 static void find_next_key_frame(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1220   int i, j;
1221   RATE_CONTROL *const rc = &cpi->rc;
1222   TWO_PASS *const twopass = &cpi->twopass;
1223   GF_GROUP *const gf_group = &twopass->gf_group;
1224   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1225   const FIRSTPASS_STATS first_frame = *this_frame;
1226   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
1227   FIRSTPASS_STATS next_frame;
1228   FIRSTPASS_STATS last_frame;
1229   int kf_bits = 0;
1230   int loop_decay_counter = 0;
1231   double decay_accumulator = 1.0;
1232   double av_decay_accumulator = 0.0;
1233   double zero_motion_accumulator = 1.0;
1234   double boost_score = 0.0;
1235   double kf_mod_err = 0.0;
1236   double kf_group_err = 0.0;
1237   double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
1238 
1239   av1_zero(next_frame);
1240 
1241   rc->frames_since_key = 0;
1242 
1243   // Reset the GF group data structures.
1244   av1_zero(*gf_group);
1245 
1246   // Is this a forced key frame by interval.
1247   rc->this_key_frame_forced = rc->next_key_frame_forced;
1248 
1249   // Clear the alt ref active flag and last group multi arf flags as they
1250   // can never be set for a key frame.
1251   rc->source_alt_ref_active = 0;
1252 
1253   // KF is always a GF so clear frames till next gf counter.
1254   rc->frames_till_gf_update_due = 0;
1255 
1256   rc->frames_to_key = 1;
1257 
1258   twopass->kf_group_bits = 0;        // Total bits available to kf group
1259   twopass->kf_group_error_left = 0;  // Group modified error score.
1260 
1261   kf_mod_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
1262 
1263   // Initialize the decay rates for the recent frames to check
1264   for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
1265 
1266   // Find the next keyframe.
1267   i = 0;
1268   while (twopass->stats_in < twopass->stats_in_end &&
1269          rc->frames_to_key < cpi->oxcf.key_freq) {
1270     // Accumulate kf group error.
1271     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
1272 
1273     // Load the next frame's stats.
1274     last_frame = *this_frame;
1275     input_stats(twopass, this_frame);
1276 
1277     // Provided that we are not at the end of the file...
1278     if (cpi->oxcf.auto_key && twopass->stats_in < twopass->stats_in_end) {
1279       double loop_decay_rate;
1280 
1281       // Check for a scene cut.
1282       if (test_candidate_kf(twopass, &last_frame, this_frame, twopass->stats_in,
1283                             rc->frames_to_key))
1284         break;
1285 
1286       // How fast is the prediction quality decaying?
1287       loop_decay_rate = get_prediction_decay_rate(cpi, twopass->stats_in);
1288 
1289       // We want to know something about the recent past... rather than
1290       // as used elsewhere where we are concerned with decay in prediction
1291       // quality since the last GF or KF.
1292       recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
1293       decay_accumulator = 1.0;
1294       for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
1295         decay_accumulator *= recent_loop_decay[j];
1296 
1297       // Special check for transition or high motion followed by a
1298       // static scene.
1299       if (detect_transition_to_still(cpi, i, cpi->oxcf.key_freq - i,
1300                                      loop_decay_rate, decay_accumulator))
1301         break;
1302 
1303       // Step on to the next frame.
1304       ++rc->frames_to_key;
1305 
1306       // If we don't have a real key frame within the next two
1307       // key_freq intervals then break out of the loop.
1308       if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq) break;
1309     } else {
1310       ++rc->frames_to_key;
1311     }
1312     ++i;
1313   }
1314 
1315   // If there is a max kf interval set by the user we must obey it.
1316   // We already breakout of the loop above at 2x max.
1317   // This code centers the extra kf if the actual natural interval
1318   // is between 1x and 2x.
1319   if (cpi->oxcf.auto_key && rc->frames_to_key > cpi->oxcf.key_freq) {
1320     FIRSTPASS_STATS tmp_frame = first_frame;
1321 
1322     rc->frames_to_key /= 2;
1323 
1324     // Reset to the start of the group.
1325     reset_fpf_position(twopass, start_position);
1326 
1327     kf_group_err = 0.0;
1328 
1329     // Rescan to get the correct error data for the forced kf group.
1330     for (i = 0; i < rc->frames_to_key; ++i) {
1331       kf_group_err += calculate_modified_err(cpi, twopass, oxcf, &tmp_frame);
1332       input_stats(twopass, &tmp_frame);
1333     }
1334     rc->next_key_frame_forced = 1;
1335   } else if (twopass->stats_in == twopass->stats_in_end ||
1336              rc->frames_to_key >= cpi->oxcf.key_freq) {
1337     rc->next_key_frame_forced = 1;
1338   } else {
1339     rc->next_key_frame_forced = 0;
1340   }
1341 
1342   // Special case for the last key frame of the file.
1343   if (twopass->stats_in >= twopass->stats_in_end) {
1344     // Accumulate kf group error.
1345     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
1346   }
1347 
1348   // Calculate the number of bits that should be assigned to the kf group.
1349   if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
1350     // Maximum number of bits for a single normal frame (not key frame).
1351     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1352 
1353     // Maximum number of bits allocated to the key frame group.
1354     int64_t max_grp_bits;
1355 
1356     // Default allocation based on bits left and relative
1357     // complexity of the section.
1358     twopass->kf_group_bits = (int64_t)(
1359         twopass->bits_left * (kf_group_err / twopass->modified_error_left));
1360 
1361     // Clip based on maximum per frame rate defined by the user.
1362     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
1363     if (twopass->kf_group_bits > max_grp_bits)
1364       twopass->kf_group_bits = max_grp_bits;
1365   } else {
1366     twopass->kf_group_bits = 0;
1367   }
1368   twopass->kf_group_bits = AOMMAX(0, twopass->kf_group_bits);
1369 
1370   // Reset the first pass file position.
1371   reset_fpf_position(twopass, start_position);
1372 
1373   // Scan through the kf group collating various stats used to determine
1374   // how many bits to spend on it.
1375   decay_accumulator = 1.0;
1376   boost_score = 0.0;
1377   const double kf_max_boost =
1378       cpi->oxcf.rc_mode == AOM_Q
1379           ? AOMMIN(AOMMAX(rc->frames_to_key * 2.0, KF_MIN_FRAME_BOOST),
1380                    KF_MAX_FRAME_BOOST)
1381           : KF_MAX_FRAME_BOOST;
1382   for (i = 0; i < (rc->frames_to_key - 1); ++i) {
1383     if (EOF == input_stats(twopass, &next_frame)) break;
1384 
1385     // Monitor for static sections.
1386     // For the first frame in kf group, the second ref indicator is invalid.
1387     if (i > 0) {
1388       zero_motion_accumulator = AOMMIN(
1389           zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
1390     } else {
1391       zero_motion_accumulator = next_frame.pcnt_inter - next_frame.pcnt_motion;
1392     }
1393 
1394     // Not all frames in the group are necessarily used in calculating boost.
1395     if ((i <= rc->max_gf_interval) ||
1396         ((i <= (rc->max_gf_interval * 4)) && (decay_accumulator > 0.5))) {
1397       const double frame_boost =
1398           calc_frame_boost(cpi, this_frame, 0, kf_max_boost);
1399 
1400       // How fast is prediction quality decaying.
1401       if (!detect_flash(twopass, 0)) {
1402         const double loop_decay_rate =
1403             get_prediction_decay_rate(cpi, &next_frame);
1404         decay_accumulator *= loop_decay_rate;
1405         decay_accumulator = AOMMAX(decay_accumulator, MIN_DECAY_FACTOR);
1406         av_decay_accumulator += decay_accumulator;
1407         ++loop_decay_counter;
1408       }
1409       boost_score += (decay_accumulator * frame_boost);
1410     }
1411   }
1412   if (loop_decay_counter > 0)
1413     av_decay_accumulator /= (double)loop_decay_counter;
1414 
1415   reset_fpf_position(twopass, start_position);
1416 
1417   // Store the zero motion percentage
1418   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
1419 
1420   // Calculate a section intra ratio used in setting max loop filter.
1421   twopass->section_intra_rating = calculate_section_intra_ratio(
1422       start_position, twopass->stats_in_end, rc->frames_to_key);
1423 
1424   rc->kf_boost = (int)(av_decay_accumulator * boost_score);
1425 
1426   // Special case for static / slide show content but don't apply
1427   // if the kf group is very short.
1428   if ((zero_motion_accumulator > STATIC_KF_GROUP_FLOAT_THRESH) &&
1429       (rc->frames_to_key > 8)) {
1430     rc->kf_boost = AOMMAX(rc->kf_boost, MIN_STATIC_KF_BOOST);
1431   } else {
1432     // Apply various clamps for min and max boost
1433     rc->kf_boost = AOMMAX(rc->kf_boost, (rc->frames_to_key * 3));
1434     rc->kf_boost = AOMMAX(rc->kf_boost, MIN_KF_BOOST);
1435   }
1436 
1437   // Work out how many bits to allocate for the key frame itself.
1438   kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
1439                                  twopass->kf_group_bits);
1440   // printf("kf boost = %d kf_bits = %d kf_zeromotion_pct = %d\n", rc->kf_boost,
1441   //        kf_bits, twopass->kf_zeromotion_pct);
1442 
1443   // Work out the fraction of the kf group bits reserved for the inter frames
1444   // within the group after discounting the bits for the kf itself.
1445   if (twopass->kf_group_bits) {
1446     twopass->kfgroup_inter_fraction =
1447         (double)(twopass->kf_group_bits - kf_bits) /
1448         (double)twopass->kf_group_bits;
1449   } else {
1450     twopass->kfgroup_inter_fraction = 1.0;
1451   }
1452 
1453   twopass->kf_group_bits -= kf_bits;
1454 
1455   // Save the bits to spend on the key frame.
1456   gf_group->bit_allocation[0] = kf_bits;
1457   gf_group->update_type[0] = KF_UPDATE;
1458 
1459   // Note the total error score of the kf group minus the key frame itself.
1460   twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
1461 
1462   // Adjust the count of total modified error left.
1463   // The count of bits left is adjusted elsewhere based on real coded frame
1464   // sizes.
1465   twopass->modified_error_left -= kf_group_err;
1466 }
1467 
is_skippable_frame(const AV1_COMP * cpi)1468 static int is_skippable_frame(const AV1_COMP *cpi) {
1469   // If the current frame does not have non-zero motion vector detected in the
1470   // first  pass, and so do its previous and forward frames, then this frame
1471   // can be skipped for partition check, and the partition size is assigned
1472   // according to the variance
1473   const TWO_PASS *const twopass = &cpi->twopass;
1474 
1475   return (!frame_is_intra_only(&cpi->common) &&
1476           twopass->stats_in - 2 > twopass->stats_in_start &&
1477           twopass->stats_in < twopass->stats_in_end &&
1478           (twopass->stats_in - 1)->pcnt_inter -
1479                   (twopass->stats_in - 1)->pcnt_motion ==
1480               1 &&
1481           (twopass->stats_in - 2)->pcnt_inter -
1482                   (twopass->stats_in - 2)->pcnt_motion ==
1483               1 &&
1484           twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
1485 }
1486 
1487 #define ARF_STATS_OUTPUT 0
1488 #if ARF_STATS_OUTPUT
1489 unsigned int arf_count = 0;
1490 #endif
1491 #define DEFAULT_GRP_WEIGHT 1.0
1492 
av1_get_second_pass_params(AV1_COMP * cpi,EncodeFrameParams * const frame_params,unsigned int frame_flags)1493 void av1_get_second_pass_params(AV1_COMP *cpi,
1494                                 EncodeFrameParams *const frame_params,
1495                                 unsigned int frame_flags) {
1496   AV1_COMMON *const cm = &cpi->common;
1497   CurrentFrame *const current_frame = &cm->current_frame;
1498   RATE_CONTROL *const rc = &cpi->rc;
1499   TWO_PASS *const twopass = &cpi->twopass;
1500   GF_GROUP *const gf_group = &twopass->gf_group;
1501   int frames_left;
1502   FIRSTPASS_STATS this_frame;
1503 
1504   int target_rate;
1505 
1506   frames_left = (int)(twopass->total_stats.count - current_frame->frame_number);
1507 
1508   if (!twopass->stats_in) return;
1509 
1510   // If this is an arf frame then we dont want to read the stats file or
1511   // advance the input pointer as we already have what we need.
1512   if (gf_group->update_type[gf_group->index] == ARF_UPDATE ||
1513       gf_group->update_type[gf_group->index] == INTNL_ARF_UPDATE) {
1514     target_rate = gf_group->bit_allocation[gf_group->index];
1515     target_rate = av1_rc_clamp_pframe_target_size(
1516         cpi, target_rate, gf_group->update_type[gf_group->index]);
1517     rc->base_frame_target = target_rate;
1518 
1519     if (cpi->no_show_kf) {
1520       assert(gf_group->update_type[gf_group->index] == ARF_UPDATE);
1521       frame_params->frame_type = KEY_FRAME;
1522     } else {
1523       frame_params->frame_type = INTER_FRAME;
1524     }
1525 
1526     // Do the firstpass stats indicate that this frame is skippable for the
1527     // partition search?
1528     if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2) {
1529       cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
1530     }
1531 
1532     return;
1533   }
1534 
1535   aom_clear_system_state();
1536 
1537   if (cpi->oxcf.rc_mode == AOM_Q) {
1538     twopass->active_worst_quality = cpi->oxcf.cq_level;
1539   } else if (current_frame->frame_number == 0) {
1540     // Special case code for first frame.
1541     const int section_target_bandwidth =
1542         (int)(twopass->bits_left / frames_left);
1543     const double section_length = twopass->total_left_stats.count;
1544     const double section_error =
1545         twopass->total_left_stats.coded_error / section_length;
1546     const double section_intra_skip =
1547         twopass->total_left_stats.intra_skip_pct / section_length;
1548     const double section_inactive_zone =
1549         (twopass->total_left_stats.inactive_zone_rows * 2) /
1550         ((double)cm->mb_rows * section_length);
1551     const int tmp_q = get_twopass_worst_quality(
1552         cpi, section_error, section_intra_skip + section_inactive_zone,
1553         section_target_bandwidth, DEFAULT_GRP_WEIGHT);
1554 
1555     twopass->active_worst_quality = tmp_q;
1556     twopass->baseline_active_worst_quality = tmp_q;
1557     rc->ni_av_qi = tmp_q;
1558     rc->last_q[INTER_FRAME] = tmp_q;
1559     rc->avg_q = av1_convert_qindex_to_q(tmp_q, cm->seq_params.bit_depth);
1560     rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
1561     rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
1562     rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
1563   }
1564 
1565   av1_zero(this_frame);
1566   if (EOF == input_stats(twopass, &this_frame)) return;
1567 
1568   // Set the frame content type flag.
1569   if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
1570     twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
1571   else
1572     twopass->fr_content_type = FC_NORMAL;
1573 
1574   // Keyframe and section processing.
1575   if (rc->frames_to_key == 0 || (frame_flags & FRAMEFLAGS_KEY)) {
1576     FIRSTPASS_STATS this_frame_copy;
1577     this_frame_copy = this_frame;
1578     frame_params->frame_type = KEY_FRAME;
1579     // Define next KF group and assign bits to it.
1580     find_next_key_frame(cpi, &this_frame);
1581     this_frame = this_frame_copy;
1582   } else {
1583     frame_params->frame_type = INTER_FRAME;
1584   }
1585 
1586   // Define a new GF/ARF group. (Should always enter here for key frames).
1587   if (rc->frames_till_gf_update_due == 0) {
1588     define_gf_group(cpi, &this_frame, frame_params);
1589 
1590     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1591 
1592 #if ARF_STATS_OUTPUT
1593     {
1594       FILE *fpfile;
1595       fpfile = fopen("arf.stt", "a");
1596       ++arf_count;
1597       fprintf(fpfile, "%10d %10d %10d %10d %10d\n", current_frame->frame_number,
1598               rc->frames_till_gf_update_due, rc->kf_boost, arf_count,
1599               rc->gfu_boost);
1600 
1601       fclose(fpfile);
1602     }
1603 #endif
1604   }
1605 
1606   // Do the firstpass stats indicate that this frame is skippable for the
1607   // partition search?
1608   if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2) {
1609     cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
1610   }
1611 
1612   target_rate = gf_group->bit_allocation[gf_group->index];
1613 
1614   if (frame_params->frame_type == KEY_FRAME) {
1615     target_rate = av1_rc_clamp_iframe_target_size(cpi, target_rate);
1616   } else {
1617     target_rate = av1_rc_clamp_pframe_target_size(
1618         cpi, target_rate, gf_group->update_type[gf_group->index]);
1619   }
1620 
1621   rc->base_frame_target = target_rate;
1622 
1623   {
1624     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1625                             ? cpi->initial_mbs
1626                             : cpi->common.MBs;
1627     // The multiplication by 256 reverses a scaling factor of (>> 8)
1628     // applied when combining MB error values for the frame.
1629     twopass->mb_av_energy = log((this_frame.intra_error / num_mbs) + 1.0);
1630     twopass->frame_avg_haar_energy =
1631         log((this_frame.frame_avg_wavelet_energy / num_mbs) + 1.0);
1632   }
1633 
1634   // Update the total stats remaining structure.
1635   subtract_stats(&twopass->total_left_stats, &this_frame);
1636 }
1637 
av1_init_second_pass(AV1_COMP * cpi)1638 void av1_init_second_pass(AV1_COMP *cpi) {
1639   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1640   TWO_PASS *const twopass = &cpi->twopass;
1641   double frame_rate;
1642   FIRSTPASS_STATS *stats;
1643 
1644   av1_twopass_zero_stats(&twopass->total_stats);
1645   av1_twopass_zero_stats(&twopass->total_left_stats);
1646 
1647   if (!twopass->stats_in_end) return;
1648 
1649   stats = &twopass->total_stats;
1650 
1651   *stats = *twopass->stats_in_end;
1652   twopass->total_left_stats = *stats;
1653 
1654   frame_rate = 10000000.0 * stats->count / stats->duration;
1655   // Each frame can have a different duration, as the frame rate in the source
1656   // isn't guaranteed to be constant. The frame rate prior to the first frame
1657   // encoded in the second pass is a guess. However, the sum duration is not.
1658   // It is calculated based on the actual durations of all frames from the
1659   // first pass.
1660   av1_new_framerate(cpi, frame_rate);
1661   twopass->bits_left =
1662       (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
1663 
1664   // This variable monitors how far behind the second ref update is lagging.
1665   twopass->sr_update_lag = 1;
1666 
1667   // Scan the first pass file and calculate a modified total error based upon
1668   // the bias/power function used to allocate bits.
1669   {
1670     const double avg_error =
1671         stats->coded_error / DOUBLE_DIVIDE_CHECK(stats->count);
1672     const FIRSTPASS_STATS *s = twopass->stats_in;
1673     double modified_error_total = 0.0;
1674     twopass->modified_error_min =
1675         (avg_error * oxcf->two_pass_vbrmin_section) / 100;
1676     twopass->modified_error_max =
1677         (avg_error * oxcf->two_pass_vbrmax_section) / 100;
1678     while (s < twopass->stats_in_end) {
1679       modified_error_total += calculate_modified_err(cpi, twopass, oxcf, s);
1680       ++s;
1681     }
1682     twopass->modified_error_left = modified_error_total;
1683   }
1684 
1685   // Reset the vbr bits off target counters
1686   cpi->rc.vbr_bits_off_target = 0;
1687   cpi->rc.vbr_bits_off_target_fast = 0;
1688 
1689   cpi->rc.rate_error_estimate = 0;
1690 
1691   // Static sequence monitor variables.
1692   twopass->kf_zeromotion_pct = 100;
1693   twopass->last_kfgroup_zeromotion_pct = 100;
1694 }
1695 
1696 #define MINQ_ADJ_LIMIT 48
1697 #define MINQ_ADJ_LIMIT_CQ 20
1698 #define HIGH_UNDERSHOOT_RATIO 2
av1_twopass_postencode_update(AV1_COMP * cpi)1699 void av1_twopass_postencode_update(AV1_COMP *cpi) {
1700   TWO_PASS *const twopass = &cpi->twopass;
1701   RATE_CONTROL *const rc = &cpi->rc;
1702   const int bits_used = rc->base_frame_target;
1703 
1704   // VBR correction is done through rc->vbr_bits_off_target. Based on the
1705   // sign of this value, a limited % adjustment is made to the target rate
1706   // of subsequent frames, to try and push it back towards 0. This method
1707   // is designed to prevent extreme behaviour at the end of a clip
1708   // or group of frames.
1709   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
1710   twopass->bits_left = AOMMAX(twopass->bits_left - bits_used, 0);
1711 
1712   // Calculate the pct rc error.
1713   if (rc->total_actual_bits) {
1714     rc->rate_error_estimate =
1715         (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
1716     rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
1717   } else {
1718     rc->rate_error_estimate = 0;
1719   }
1720 
1721   if (cpi->common.current_frame.frame_type != KEY_FRAME) {
1722     twopass->kf_group_bits -= bits_used;
1723     twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
1724   }
1725   twopass->kf_group_bits = AOMMAX(twopass->kf_group_bits, 0);
1726 
1727   // If the rate control is drifting consider adjustment to min or maxq.
1728   if ((cpi->oxcf.rc_mode != AOM_Q) && !cpi->rc.is_src_frame_alt_ref) {
1729     const int maxq_adj_limit =
1730         rc->worst_quality - twopass->active_worst_quality;
1731     const int minq_adj_limit =
1732         (cpi->oxcf.rc_mode == AOM_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
1733 
1734     // Undershoot.
1735     if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
1736       --twopass->extend_maxq;
1737       if (rc->rolling_target_bits >= rc->rolling_actual_bits)
1738         ++twopass->extend_minq;
1739       // Overshoot.
1740     } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
1741       --twopass->extend_minq;
1742       if (rc->rolling_target_bits < rc->rolling_actual_bits)
1743         ++twopass->extend_maxq;
1744     } else {
1745       // Adjustment for extreme local overshoot.
1746       if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
1747           rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
1748         ++twopass->extend_maxq;
1749 
1750       // Unwind undershoot or overshoot adjustment.
1751       if (rc->rolling_target_bits < rc->rolling_actual_bits)
1752         --twopass->extend_minq;
1753       else if (rc->rolling_target_bits > rc->rolling_actual_bits)
1754         --twopass->extend_maxq;
1755     }
1756 
1757     twopass->extend_minq = clamp(twopass->extend_minq, 0, minq_adj_limit);
1758     twopass->extend_maxq = clamp(twopass->extend_maxq, 0, maxq_adj_limit);
1759 
1760     // If there is a big and undexpected undershoot then feed the extra
1761     // bits back in quickly. One situation where this may happen is if a
1762     // frame is unexpectedly almost perfectly predicted by the ARF or GF
1763     // but not very well predcited by the previous frame.
1764     if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
1765       int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
1766       if (rc->projected_frame_size < fast_extra_thresh) {
1767         rc->vbr_bits_off_target_fast +=
1768             fast_extra_thresh - rc->projected_frame_size;
1769         rc->vbr_bits_off_target_fast =
1770             AOMMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
1771 
1772         // Fast adaptation of minQ if necessary to use up the extra bits.
1773         if (rc->avg_frame_bandwidth) {
1774           twopass->extend_minq_fast =
1775               (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
1776         }
1777         twopass->extend_minq_fast = AOMMIN(
1778             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
1779       } else if (rc->vbr_bits_off_target_fast) {
1780         twopass->extend_minq_fast = AOMMIN(
1781             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
1782       } else {
1783         twopass->extend_minq_fast = 0;
1784       }
1785     }
1786   }
1787 }
1788