1 /*
2  * Copyright (c) 2016, 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 <limits.h>
13 #include <math.h>
14 #include <stdio.h>
15 
16 #include "config/aom_dsp_rtcd.h"
17 #include "config/aom_scale_rtcd.h"
18 
19 #include "aom_dsp/aom_dsp_common.h"
20 #include "aom_mem/aom_mem.h"
21 #include "aom_ports/mem.h"
22 #include "aom_ports/system_state.h"
23 #include "aom_scale/aom_scale.h"
24 #include "aom_scale/yv12config.h"
25 
26 #include "aom_dsp/variance.h"
27 #include "av1/common/entropymv.h"
28 #include "av1/common/quant_common.h"
29 #include "av1/common/reconinter.h"  // av1_setup_dst_planes()
30 #include "av1/common/txb_common.h"
31 #include "av1/encoder/aq_variance.h"
32 #include "av1/encoder/av1_quantize.h"
33 #include "av1/encoder/block.h"
34 #include "av1/encoder/dwt.h"
35 #include "av1/encoder/encodeframe.h"
36 #include "av1/encoder/encodemb.h"
37 #include "av1/encoder/encodemv.h"
38 #include "av1/encoder/encoder.h"
39 #include "av1/encoder/extend.h"
40 #include "av1/encoder/firstpass.h"
41 #include "av1/encoder/mcomp.h"
42 #include "av1/encoder/rd.h"
43 #include "av1/encoder/reconinter_enc.h"
44 
45 #define OUTPUT_FPF 0
46 #define ARF_STATS_OUTPUT 0
47 
48 #define GROUP_ADAPTIVE_MAXQ 1
49 
50 #define BOOST_BREAKOUT 12.5
51 #define BOOST_FACTOR 12.5
52 #define FACTOR_PT_LOW 0.70
53 #define FACTOR_PT_HIGH 0.90
54 #define FIRST_PASS_Q 10.0
55 #define GF_MAX_BOOST 90.0
56 #define INTRA_MODE_PENALTY 1024
57 #define KF_MIN_FRAME_BOOST 80.0
58 #define KF_MAX_FRAME_BOOST 128.0
59 #define MIN_ARF_GF_BOOST 240
60 #define MIN_DECAY_FACTOR 0.01
61 #define MIN_KF_BOOST 300
62 #define NEW_MV_MODE_PENALTY 32
63 #define DARK_THRESH 64
64 #define DEFAULT_GRP_WEIGHT 1.0
65 #define RC_FACTOR_MIN 0.75
66 #define RC_FACTOR_MAX 1.75
67 #define MIN_FWD_KF_INTERVAL 8
68 
69 #define NCOUNT_INTRA_THRESH 8192
70 #define NCOUNT_INTRA_FACTOR 3
71 #define NCOUNT_FRAME_II_THRESH 5.0
72 
73 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x)-0.000001 : (x) + 0.000001)
74 
75 #if ARF_STATS_OUTPUT
76 unsigned int arf_count = 0;
77 #endif
78 
79 // Resets the first pass file to the given position using a relative seek from
80 // the current position.
reset_fpf_position(TWO_PASS * p,const FIRSTPASS_STATS * position)81 static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
82   p->stats_in = position;
83 }
84 
85 // Read frame stats at an offset from the current position.
read_frame_stats(const TWO_PASS * p,int offset)86 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
87   if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
88       (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
89     return NULL;
90   }
91 
92   return &p->stats_in[offset];
93 }
94 
input_stats(TWO_PASS * p,FIRSTPASS_STATS * fps)95 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
96   if (p->stats_in >= p->stats_in_end) return EOF;
97 
98   *fps = *p->stats_in;
99   ++p->stats_in;
100   return 1;
101 }
102 
output_stats(FIRSTPASS_STATS * stats,struct aom_codec_pkt_list * pktlist)103 static void output_stats(FIRSTPASS_STATS *stats,
104                          struct aom_codec_pkt_list *pktlist) {
105   struct aom_codec_cx_pkt pkt;
106   pkt.kind = AOM_CODEC_STATS_PKT;
107   pkt.data.twopass_stats.buf = stats;
108   pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
109   aom_codec_pkt_list_add(pktlist, &pkt);
110 
111 // TEMP debug code
112 #if OUTPUT_FPF
113   {
114     FILE *fpfile;
115     fpfile = fopen("firstpass.stt", "a");
116 
117     fprintf(fpfile,
118             "%12.0lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf"
119             "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
120             "%12.4lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf\n",
121             stats->frame, stats->weight, stats->intra_error, stats->coded_error,
122             stats->sr_coded_error, stats->pcnt_inter, stats->pcnt_motion,
123             stats->pcnt_second_ref, stats->pcnt_neutral, stats->intra_skip_pct,
124             stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
125             stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
126             stats->MVcv, stats->mv_in_out_count, stats->new_mv_count,
127             stats->count, stats->duration);
128     fclose(fpfile);
129   }
130 #endif
131 }
132 
133 #if CONFIG_FP_MB_STATS
output_fpmb_stats(uint8_t * this_frame_mb_stats,int stats_size,struct aom_codec_pkt_list * pktlist)134 static void output_fpmb_stats(uint8_t *this_frame_mb_stats, int stats_size,
135                               struct aom_codec_pkt_list *pktlist) {
136   struct aom_codec_cx_pkt pkt;
137   pkt.kind = AOM_CODEC_FPMB_STATS_PKT;
138   pkt.data.firstpass_mb_stats.buf = this_frame_mb_stats;
139   pkt.data.firstpass_mb_stats.sz = stats_size * sizeof(*this_frame_mb_stats);
140   aom_codec_pkt_list_add(pktlist, &pkt);
141 }
142 #endif
143 
zero_stats(FIRSTPASS_STATS * section)144 static void zero_stats(FIRSTPASS_STATS *section) {
145   section->frame = 0.0;
146   section->weight = 0.0;
147   section->intra_error = 0.0;
148   section->frame_avg_wavelet_energy = 0.0;
149   section->coded_error = 0.0;
150   section->sr_coded_error = 0.0;
151   section->pcnt_inter = 0.0;
152   section->pcnt_motion = 0.0;
153   section->pcnt_second_ref = 0.0;
154   section->pcnt_neutral = 0.0;
155   section->intra_skip_pct = 0.0;
156   section->inactive_zone_rows = 0.0;
157   section->inactive_zone_cols = 0.0;
158   section->MVr = 0.0;
159   section->mvr_abs = 0.0;
160   section->MVc = 0.0;
161   section->mvc_abs = 0.0;
162   section->MVrv = 0.0;
163   section->MVcv = 0.0;
164   section->mv_in_out_count = 0.0;
165   section->new_mv_count = 0.0;
166   section->count = 0.0;
167   section->duration = 1.0;
168 }
169 
accumulate_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)170 static void accumulate_stats(FIRSTPASS_STATS *section,
171                              const FIRSTPASS_STATS *frame) {
172   section->frame += frame->frame;
173   section->weight += frame->weight;
174   section->intra_error += frame->intra_error;
175   section->frame_avg_wavelet_energy += frame->frame_avg_wavelet_energy;
176   section->coded_error += frame->coded_error;
177   section->sr_coded_error += frame->sr_coded_error;
178   section->pcnt_inter += frame->pcnt_inter;
179   section->pcnt_motion += frame->pcnt_motion;
180   section->pcnt_second_ref += frame->pcnt_second_ref;
181   section->pcnt_neutral += frame->pcnt_neutral;
182   section->intra_skip_pct += frame->intra_skip_pct;
183   section->inactive_zone_rows += frame->inactive_zone_rows;
184   section->inactive_zone_cols += frame->inactive_zone_cols;
185   section->MVr += frame->MVr;
186   section->mvr_abs += frame->mvr_abs;
187   section->MVc += frame->MVc;
188   section->mvc_abs += frame->mvc_abs;
189   section->MVrv += frame->MVrv;
190   section->MVcv += frame->MVcv;
191   section->mv_in_out_count += frame->mv_in_out_count;
192   section->new_mv_count += frame->new_mv_count;
193   section->count += frame->count;
194   section->duration += frame->duration;
195 }
196 
subtract_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)197 static void subtract_stats(FIRSTPASS_STATS *section,
198                            const FIRSTPASS_STATS *frame) {
199   section->frame -= frame->frame;
200   section->weight -= frame->weight;
201   section->intra_error -= frame->intra_error;
202   section->frame_avg_wavelet_energy -= frame->frame_avg_wavelet_energy;
203   section->coded_error -= frame->coded_error;
204   section->sr_coded_error -= frame->sr_coded_error;
205   section->pcnt_inter -= frame->pcnt_inter;
206   section->pcnt_motion -= frame->pcnt_motion;
207   section->pcnt_second_ref -= frame->pcnt_second_ref;
208   section->pcnt_neutral -= frame->pcnt_neutral;
209   section->intra_skip_pct -= frame->intra_skip_pct;
210   section->inactive_zone_rows -= frame->inactive_zone_rows;
211   section->inactive_zone_cols -= frame->inactive_zone_cols;
212   section->MVr -= frame->MVr;
213   section->mvr_abs -= frame->mvr_abs;
214   section->MVc -= frame->MVc;
215   section->mvc_abs -= frame->mvc_abs;
216   section->MVrv -= frame->MVrv;
217   section->MVcv -= frame->MVcv;
218   section->mv_in_out_count -= frame->mv_in_out_count;
219   section->new_mv_count -= frame->new_mv_count;
220   section->count -= frame->count;
221   section->duration -= frame->duration;
222 }
223 
224 // Calculate the linear size relative to a baseline of 1080P
225 #define BASE_SIZE 2073600.0  // 1920x1080
get_linear_size_factor(const AV1_COMP * cpi)226 static double get_linear_size_factor(const AV1_COMP *cpi) {
227   const double this_area = cpi->initial_width * cpi->initial_height;
228   return pow(this_area / BASE_SIZE, 0.5);
229 }
230 
231 // Calculate an active area of the image that discounts formatting
232 // bars and partially discounts other 0 energy areas.
233 #define MIN_ACTIVE_AREA 0.5
234 #define MAX_ACTIVE_AREA 1.0
calculate_active_area(const AV1_COMP * cpi,const FIRSTPASS_STATS * this_frame)235 static double calculate_active_area(const AV1_COMP *cpi,
236                                     const FIRSTPASS_STATS *this_frame) {
237   double active_pct;
238 
239   active_pct =
240       1.0 -
241       ((this_frame->intra_skip_pct / 2) +
242        ((this_frame->inactive_zone_rows * 2) / (double)cpi->common.mb_rows));
243   return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
244 }
245 
246 // Calculate a modified Error used in distributing bits between easier and
247 // harder frames.
248 #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)249 static double calculate_modified_err(const AV1_COMP *cpi,
250                                      const TWO_PASS *twopass,
251                                      const AV1EncoderConfig *oxcf,
252                                      const FIRSTPASS_STATS *this_frame) {
253   const FIRSTPASS_STATS *const stats = &twopass->total_stats;
254   const double av_weight = stats->weight / stats->count;
255   const double av_err = (stats->coded_error * av_weight) / stats->count;
256   double modified_error =
257       av_err * pow(this_frame->coded_error * this_frame->weight /
258                        DOUBLE_DIVIDE_CHECK(av_err),
259                    oxcf->two_pass_vbrbias / 100.0);
260 
261   // Correction for active area. Frames with a reduced active area
262   // (eg due to formatting bars) have a higher error per mb for the
263   // remaining active MBs. The correction here assumes that coding
264   // 0.5N blocks of complexity 2X is a little easier than coding N
265   // blocks of complexity X.
266   modified_error *=
267       pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);
268 
269   return fclamp(modified_error, twopass->modified_error_min,
270                 twopass->modified_error_max);
271 }
272 
273 // This function returns the maximum target rate per frame.
frame_max_bits(const RATE_CONTROL * rc,const AV1EncoderConfig * oxcf)274 static int frame_max_bits(const RATE_CONTROL *rc,
275                           const AV1EncoderConfig *oxcf) {
276   int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
277                       (int64_t)oxcf->two_pass_vbrmax_section) /
278                      100;
279   if (max_bits < 0)
280     max_bits = 0;
281   else if (max_bits > rc->max_frame_bandwidth)
282     max_bits = rc->max_frame_bandwidth;
283 
284   return (int)max_bits;
285 }
286 
av1_init_first_pass(AV1_COMP * cpi)287 void av1_init_first_pass(AV1_COMP *cpi) {
288   zero_stats(&cpi->twopass.total_stats);
289 }
290 
av1_end_first_pass(AV1_COMP * cpi)291 void av1_end_first_pass(AV1_COMP *cpi) {
292   output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
293 }
294 
get_block_variance_fn(BLOCK_SIZE bsize)295 static aom_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
296   switch (bsize) {
297     case BLOCK_8X8: return aom_mse8x8;
298     case BLOCK_16X8: return aom_mse16x8;
299     case BLOCK_8X16: return aom_mse8x16;
300     default: return aom_mse16x16;
301   }
302 }
303 
get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref)304 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
305                                          const struct buf_2d *src,
306                                          const struct buf_2d *ref) {
307   unsigned int sse;
308   const aom_variance_fn_t fn = get_block_variance_fn(bsize);
309   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
310   return sse;
311 }
312 
highbd_get_block_variance_fn(BLOCK_SIZE bsize,int bd)313 static aom_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
314                                                       int bd) {
315   switch (bd) {
316     default:
317       switch (bsize) {
318         case BLOCK_8X8: return aom_highbd_8_mse8x8;
319         case BLOCK_16X8: return aom_highbd_8_mse16x8;
320         case BLOCK_8X16: return aom_highbd_8_mse8x16;
321         default: return aom_highbd_8_mse16x16;
322       }
323       break;
324     case 10:
325       switch (bsize) {
326         case BLOCK_8X8: return aom_highbd_10_mse8x8;
327         case BLOCK_16X8: return aom_highbd_10_mse16x8;
328         case BLOCK_8X16: return aom_highbd_10_mse8x16;
329         default: return aom_highbd_10_mse16x16;
330       }
331       break;
332     case 12:
333       switch (bsize) {
334         case BLOCK_8X8: return aom_highbd_12_mse8x8;
335         case BLOCK_16X8: return aom_highbd_12_mse16x8;
336         case BLOCK_8X16: return aom_highbd_12_mse8x16;
337         default: return aom_highbd_12_mse16x16;
338       }
339       break;
340   }
341 }
342 
highbd_get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref,int bd)343 static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
344                                                 const struct buf_2d *src,
345                                                 const struct buf_2d *ref,
346                                                 int bd) {
347   unsigned int sse;
348   const aom_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
349   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
350   return sse;
351 }
352 
353 // Refine the motion search range according to the frame dimension
354 // for first pass test.
get_search_range(const AV1_COMP * cpi)355 static int get_search_range(const AV1_COMP *cpi) {
356   int sr = 0;
357   const int dim = AOMMIN(cpi->initial_width, cpi->initial_height);
358 
359   while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
360   return sr;
361 }
362 
first_pass_motion_search(AV1_COMP * cpi,MACROBLOCK * x,const MV * ref_mv,MV * best_mv,int * best_motion_err)363 static void first_pass_motion_search(AV1_COMP *cpi, MACROBLOCK *x,
364                                      const MV *ref_mv, MV *best_mv,
365                                      int *best_motion_err) {
366   MACROBLOCKD *const xd = &x->e_mbd;
367   MV tmp_mv = kZeroMv;
368   MV ref_mv_full = { ref_mv->row >> 3, ref_mv->col >> 3 };
369   int num00, tmp_err, n;
370   const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
371   aom_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
372   const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
373 
374   int step_param = 3;
375   int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
376   const int sr = get_search_range(cpi);
377   step_param += sr;
378   further_steps -= sr;
379 
380   // Override the default variance function to use MSE.
381   v_fn_ptr.vf = get_block_variance_fn(bsize);
382   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
383     v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
384   }
385 
386   // Center the initial step/diamond search on best mv.
387   tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
388                                     step_param, x->sadperbit16, &num00,
389                                     &v_fn_ptr, ref_mv);
390   if (tmp_err < INT_MAX)
391     tmp_err = av1_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
392   if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
393 
394   if (tmp_err < *best_motion_err) {
395     *best_motion_err = tmp_err;
396     *best_mv = tmp_mv;
397   }
398 
399   // Carry out further step/diamond searches as necessary.
400   n = num00;
401   num00 = 0;
402 
403   while (n < further_steps) {
404     ++n;
405 
406     if (num00) {
407       --num00;
408     } else {
409       tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
410                                         step_param + n, x->sadperbit16, &num00,
411                                         &v_fn_ptr, ref_mv);
412       if (tmp_err < INT_MAX)
413         tmp_err = av1_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
414       if (tmp_err < INT_MAX - new_mv_mode_penalty)
415         tmp_err += new_mv_mode_penalty;
416 
417       if (tmp_err < *best_motion_err) {
418         *best_motion_err = tmp_err;
419         *best_mv = tmp_mv;
420       }
421     }
422   }
423 }
424 
get_bsize(const AV1_COMMON * cm,int mb_row,int mb_col)425 static BLOCK_SIZE get_bsize(const AV1_COMMON *cm, int mb_row, int mb_col) {
426   if (mi_size_wide[BLOCK_16X16] * mb_col + mi_size_wide[BLOCK_8X8] <
427       cm->mi_cols) {
428     return mi_size_wide[BLOCK_16X16] * mb_row + mi_size_wide[BLOCK_8X8] <
429                    cm->mi_rows
430                ? BLOCK_16X16
431                : BLOCK_16X8;
432   } else {
433     return mi_size_wide[BLOCK_16X16] * mb_row + mi_size_wide[BLOCK_8X8] <
434                    cm->mi_rows
435                ? BLOCK_8X16
436                : BLOCK_8X8;
437   }
438 }
439 
find_fp_qindex(aom_bit_depth_t bit_depth)440 static int find_fp_qindex(aom_bit_depth_t bit_depth) {
441   int i;
442 
443   for (i = 0; i < QINDEX_RANGE; ++i)
444     if (av1_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q) break;
445 
446   if (i == QINDEX_RANGE) i--;
447 
448   return i;
449 }
450 
set_first_pass_params(AV1_COMP * cpi)451 static void set_first_pass_params(AV1_COMP *cpi) {
452   AV1_COMMON *const cm = &cpi->common;
453   if (!cpi->refresh_alt_ref_frame &&
454       (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY))) {
455     cm->frame_type = KEY_FRAME;
456   } else {
457     cm->frame_type = INTER_FRAME;
458   }
459   // Do not use periodic key frames.
460   cpi->rc.frames_to_key = INT_MAX;
461 }
462 
raw_motion_error_stdev(int * raw_motion_err_list,int raw_motion_err_counts)463 static double raw_motion_error_stdev(int *raw_motion_err_list,
464                                      int raw_motion_err_counts) {
465   int64_t sum_raw_err = 0;
466   double raw_err_avg = 0;
467   double raw_err_stdev = 0;
468   if (raw_motion_err_counts == 0) return 0;
469 
470   int i;
471   for (i = 0; i < raw_motion_err_counts; i++) {
472     sum_raw_err += raw_motion_err_list[i];
473   }
474   raw_err_avg = (double)sum_raw_err / raw_motion_err_counts;
475   for (i = 0; i < raw_motion_err_counts; i++) {
476     raw_err_stdev += (raw_motion_err_list[i] - raw_err_avg) *
477                      (raw_motion_err_list[i] - raw_err_avg);
478   }
479   // Calculate the standard deviation for the motion error of all the inter
480   // blocks of the 0,0 motion using the last source
481   // frame as the reference.
482   raw_err_stdev = sqrt(raw_err_stdev / raw_motion_err_counts);
483   return raw_err_stdev;
484 }
485 
486 #define UL_INTRA_THRESH 50
487 #define INVALID_ROW -1
av1_first_pass(AV1_COMP * cpi,const struct lookahead_entry * source)488 void av1_first_pass(AV1_COMP *cpi, const struct lookahead_entry *source) {
489   int mb_row, mb_col;
490   MACROBLOCK *const x = &cpi->td.mb;
491   AV1_COMMON *const cm = &cpi->common;
492   const SequenceHeader *const seq_params = &cm->seq_params;
493   const int num_planes = av1_num_planes(cm);
494   MACROBLOCKD *const xd = &x->e_mbd;
495   TileInfo tile;
496   struct macroblock_plane *const p = x->plane;
497   struct macroblockd_plane *const pd = xd->plane;
498   const PICK_MODE_CONTEXT *ctx =
499       &cpi->td.pc_root[MAX_MIB_SIZE_LOG2 - MIN_MIB_SIZE_LOG2]->none;
500   int i;
501 
502   int recon_yoffset, recon_uvoffset;
503   int64_t intra_error = 0;
504   int64_t frame_avg_wavelet_energy = 0;
505   int64_t coded_error = 0;
506   int64_t sr_coded_error = 0;
507 
508   int sum_mvr = 0, sum_mvc = 0;
509   int sum_mvr_abs = 0, sum_mvc_abs = 0;
510   int64_t sum_mvrs = 0, sum_mvcs = 0;
511   int mvcount = 0;
512   int intercount = 0;
513   int second_ref_count = 0;
514   const int intrapenalty = INTRA_MODE_PENALTY;
515   double neutral_count;
516   int intra_skip_count = 0;
517   int image_data_start_row = INVALID_ROW;
518   int new_mv_count = 0;
519   int sum_in_vectors = 0;
520   MV lastmv = kZeroMv;
521   TWO_PASS *twopass = &cpi->twopass;
522   int recon_y_stride, recon_uv_stride, uv_mb_height;
523 
524   YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
525   YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
526   YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
527   const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
528   double intra_factor;
529   double brightness_factor;
530   BufferPool *const pool = cm->buffer_pool;
531   const int qindex = find_fp_qindex(seq_params->bit_depth);
532   const int mb_scale = mi_size_wide[BLOCK_16X16];
533 
534   int *raw_motion_err_list;
535   int raw_motion_err_counts = 0;
536   CHECK_MEM_ERROR(
537       cm, raw_motion_err_list,
538       aom_calloc(cm->mb_rows * cm->mb_cols, sizeof(*raw_motion_err_list)));
539   // First pass code requires valid last and new frame buffers.
540   assert(new_yv12 != NULL);
541   assert(frame_is_intra_only(cm) || (lst_yv12 != NULL));
542 
543 #if CONFIG_FP_MB_STATS
544   if (cpi->use_fp_mb_stats) {
545     av1_zero_array(cpi->twopass.frame_mb_stats_buf, cpi->initial_mbs);
546   }
547 #endif
548 
549   aom_clear_system_state();
550 
551   xd->mi = cm->mi_grid_visible;
552   xd->mi[0] = cm->mi;
553   x->e_mbd.mi[0]->sb_type = BLOCK_16X16;
554 
555   intra_factor = 0.0;
556   brightness_factor = 0.0;
557   neutral_count = 0.0;
558 
559   set_first_pass_params(cpi);
560   av1_set_quantizer(cm, qindex);
561 
562   av1_setup_block_planes(&x->e_mbd, seq_params->subsampling_x,
563                          seq_params->subsampling_y, num_planes);
564 
565   av1_setup_src_planes(x, cpi->source, 0, 0, num_planes);
566   av1_setup_dst_planes(xd->plane, seq_params->sb_size, new_yv12, 0, 0, 0,
567                        num_planes);
568 
569   if (!frame_is_intra_only(cm)) {
570     av1_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL, num_planes);
571   }
572 
573   xd->mi = cm->mi_grid_visible;
574   xd->mi[0] = cm->mi;
575 
576   // Don't store luma on the fist pass since chroma is not computed
577   xd->cfl.store_y = 0;
578   av1_frame_init_quantizer(cpi);
579 
580   for (i = 0; i < num_planes; ++i) {
581     p[i].coeff = ctx->coeff[i];
582     p[i].qcoeff = ctx->qcoeff[i];
583     pd[i].dqcoeff = ctx->dqcoeff[i];
584     p[i].eobs = ctx->eobs[i];
585     p[i].txb_entropy_ctx = ctx->txb_entropy_ctx[i];
586   }
587 
588   av1_init_mv_probs(cm);
589   av1_init_lv_map(cm);
590   av1_initialize_rd_consts(cpi);
591 
592   // Tiling is ignored in the first pass.
593   av1_tile_init(&tile, cm, 0, 0);
594 
595   recon_y_stride = new_yv12->y_stride;
596   recon_uv_stride = new_yv12->uv_stride;
597   uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
598 
599   for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
600     MV best_ref_mv = kZeroMv;
601 
602     // Reset above block coeffs.
603     xd->up_available = (mb_row != 0);
604     recon_yoffset = (mb_row * recon_y_stride * 16);
605     recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height);
606 
607     // Set up limit values for motion vectors to prevent them extending
608     // outside the UMV borders.
609     x->mv_limits.row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
610     x->mv_limits.row_max =
611         ((cm->mb_rows - 1 - mb_row) * 16) + BORDER_MV_PIXELS_B16;
612 
613     for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
614       int this_error;
615       const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
616       const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
617       double log_intra;
618       int level_sample;
619 
620 #if CONFIG_FP_MB_STATS
621       const int mb_index = mb_row * cm->mb_cols + mb_col;
622 #endif
623 
624       aom_clear_system_state();
625 
626       const int idx_str = xd->mi_stride * mb_row * mb_scale + mb_col * mb_scale;
627       xd->mi = cm->mi_grid_visible + idx_str;
628       xd->mi[0] = cm->mi + idx_str;
629       xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
630       xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
631       xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
632       xd->left_available = (mb_col != 0);
633       xd->mi[0]->sb_type = bsize;
634       xd->mi[0]->ref_frame[0] = INTRA_FRAME;
635       set_mi_row_col(xd, &tile, mb_row * mb_scale, mi_size_high[bsize],
636                      mb_col * mb_scale, mi_size_wide[bsize], cm->mi_rows,
637                      cm->mi_cols);
638 
639       set_plane_n4(xd, mi_size_wide[bsize], mi_size_high[bsize], num_planes);
640 
641       // Do intra 16x16 prediction.
642       xd->mi[0]->segment_id = 0;
643       xd->lossless[xd->mi[0]->segment_id] = (qindex == 0);
644       xd->mi[0]->mode = DC_PRED;
645       xd->mi[0]->tx_size =
646           use_dc_pred ? (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
647       av1_encode_intra_block_plane(cpi, x, bsize, 0, 0, mb_row * 2, mb_col * 2);
648       this_error = aom_get_mb_ss(x->plane[0].src_diff);
649 
650       // Keep a record of blocks that have almost no intra error residual
651       // (i.e. are in effect completely flat and untextured in the intra
652       // domain). In natural videos this is uncommon, but it is much more
653       // common in animations, graphics and screen content, so may be used
654       // as a signal to detect these types of content.
655       if (this_error < UL_INTRA_THRESH) {
656         ++intra_skip_count;
657       } else if ((mb_col > 0) && (image_data_start_row == INVALID_ROW)) {
658         image_data_start_row = mb_row;
659       }
660 
661       if (seq_params->use_highbitdepth) {
662         switch (seq_params->bit_depth) {
663           case AOM_BITS_8: break;
664           case AOM_BITS_10: this_error >>= 4; break;
665           case AOM_BITS_12: this_error >>= 8; break;
666           default:
667             assert(0 &&
668                    "seq_params->bit_depth should be AOM_BITS_8, "
669                    "AOM_BITS_10 or AOM_BITS_12");
670             return;
671         }
672       }
673 
674       aom_clear_system_state();
675       log_intra = log(this_error + 1.0);
676       if (log_intra < 10.0)
677         intra_factor += 1.0 + ((10.0 - log_intra) * 0.05);
678       else
679         intra_factor += 1.0;
680 
681       if (seq_params->use_highbitdepth)
682         level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
683       else
684         level_sample = x->plane[0].src.buf[0];
685       if ((level_sample < DARK_THRESH) && (log_intra < 9.0))
686         brightness_factor += 1.0 + (0.01 * (DARK_THRESH - level_sample));
687       else
688         brightness_factor += 1.0;
689 
690       // Intrapenalty below deals with situations where the intra and inter
691       // error scores are very low (e.g. a plain black frame).
692       // We do not have special cases in first pass for 0,0 and nearest etc so
693       // all inter modes carry an overhead cost estimate for the mv.
694       // When the error score is very low this causes us to pick all or lots of
695       // INTRA modes and throw lots of key frames.
696       // This penalty adds a cost matching that of a 0,0 mv to the intra case.
697       this_error += intrapenalty;
698 
699       // Accumulate the intra error.
700       intra_error += (int64_t)this_error;
701 
702       int stride = x->plane[0].src.stride;
703       uint8_t *buf = x->plane[0].src.buf;
704       for (int r8 = 0; r8 < 2; ++r8)
705         for (int c8 = 0; c8 < 2; ++c8) {
706           int hbd = xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH;
707           frame_avg_wavelet_energy += av1_haar_ac_sad_8x8_uint8_input(
708               buf + c8 * 8 + r8 * 8 * stride, stride, hbd);
709         }
710 
711 #if CONFIG_FP_MB_STATS
712       if (cpi->use_fp_mb_stats) {
713         // initialization
714         cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
715       }
716 #endif
717 
718       // Set up limit values for motion vectors to prevent them extending
719       // outside the UMV borders.
720       x->mv_limits.col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
721       x->mv_limits.col_max =
722           ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
723 
724       if (!frame_is_intra_only(cm)) {  // Do a motion search
725         int tmp_err, motion_error, raw_motion_error;
726         // Assume 0,0 motion with no mv overhead.
727         MV mv = kZeroMv, tmp_mv = kZeroMv;
728         struct buf_2d unscaled_last_source_buf_2d;
729 
730         xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
731         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
732           motion_error = highbd_get_prediction_error(
733               bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
734         } else {
735           motion_error = get_prediction_error(bsize, &x->plane[0].src,
736                                               &xd->plane[0].pre[0]);
737         }
738 
739         // Compute the motion error of the 0,0 motion using the last source
740         // frame as the reference. Skip the further motion search on
741         // reconstructed frame if this error is small.
742         unscaled_last_source_buf_2d.buf =
743             cpi->unscaled_last_source->y_buffer + recon_yoffset;
744         unscaled_last_source_buf_2d.stride =
745             cpi->unscaled_last_source->y_stride;
746         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
747           raw_motion_error = highbd_get_prediction_error(
748               bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
749         } else {
750           raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
751                                                   &unscaled_last_source_buf_2d);
752         }
753 
754         // TODO(pengchong): Replace the hard-coded threshold
755         if (raw_motion_error > 25) {
756           // Test last reference frame using the previous best mv as the
757           // starting point (best reference) for the search.
758           first_pass_motion_search(cpi, x, &best_ref_mv, &mv, &motion_error);
759 
760           // If the current best reference mv is not centered on 0,0 then do a
761           // 0,0 based search as well.
762           if (!is_zero_mv(&best_ref_mv)) {
763             tmp_err = INT_MAX;
764             first_pass_motion_search(cpi, x, &kZeroMv, &tmp_mv, &tmp_err);
765 
766             if (tmp_err < motion_error) {
767               motion_error = tmp_err;
768               mv = tmp_mv;
769             }
770           }
771 
772           // Search in an older reference frame.
773           if ((cm->current_video_frame > 1) && gld_yv12 != NULL) {
774             // Assume 0,0 motion with no mv overhead.
775             int gf_motion_error;
776 
777             xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
778             if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
779               gf_motion_error = highbd_get_prediction_error(
780                   bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
781             } else {
782               gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
783                                                      &xd->plane[0].pre[0]);
784             }
785 
786             first_pass_motion_search(cpi, x, &kZeroMv, &tmp_mv,
787                                      &gf_motion_error);
788 
789             if (gf_motion_error < motion_error && gf_motion_error < this_error)
790               ++second_ref_count;
791 
792             // Reset to last frame as reference buffer.
793             xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
794             xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
795             xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
796 
797             // In accumulating a score for the older reference frame take the
798             // best of the motion predicted score and the intra coded error
799             // (just as will be done for) accumulation of "coded_error" for
800             // the last frame.
801             if (gf_motion_error < this_error)
802               sr_coded_error += gf_motion_error;
803             else
804               sr_coded_error += this_error;
805           } else {
806             sr_coded_error += motion_error;
807           }
808         } else {
809           sr_coded_error += motion_error;
810         }
811 
812         // Start by assuming that intra mode is best.
813         best_ref_mv.row = 0;
814         best_ref_mv.col = 0;
815 
816 #if CONFIG_FP_MB_STATS
817         if (cpi->use_fp_mb_stats) {
818           // intra predication statistics
819           cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
820           cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_DCINTRA_MASK;
821           cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
822           if (this_error > FPMB_ERROR_LARGE_TH) {
823             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_LARGE_MASK;
824           } else if (this_error < FPMB_ERROR_SMALL_TH) {
825             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_SMALL_MASK;
826           }
827         }
828 #endif
829 
830         if (motion_error <= this_error) {
831           aom_clear_system_state();
832 
833           // Keep a count of cases where the inter and intra were very close
834           // and very low. This helps with scene cut detection for example in
835           // cropped clips with black bars at the sides or top and bottom.
836           if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
837               (this_error < (2 * intrapenalty))) {
838             neutral_count += 1.0;
839             // Also track cases where the intra is not much worse than the inter
840             // and use this in limiting the GF/arf group length.
841           } else if ((this_error > NCOUNT_INTRA_THRESH) &&
842                      (this_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
843             neutral_count +=
844                 (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_error);
845           }
846 
847           mv.row *= 8;
848           mv.col *= 8;
849           this_error = motion_error;
850           xd->mi[0]->mode = NEWMV;
851           xd->mi[0]->mv[0].as_mv = mv;
852           xd->mi[0]->tx_size = TX_4X4;
853           xd->mi[0]->ref_frame[0] = LAST_FRAME;
854           xd->mi[0]->ref_frame[1] = NONE_FRAME;
855           av1_build_inter_predictors_sby(cm, xd, mb_row * mb_scale,
856                                          mb_col * mb_scale, NULL, bsize);
857           av1_encode_sby_pass1(cm, x, bsize);
858           sum_mvr += mv.row;
859           sum_mvr_abs += abs(mv.row);
860           sum_mvc += mv.col;
861           sum_mvc_abs += abs(mv.col);
862           sum_mvrs += mv.row * mv.row;
863           sum_mvcs += mv.col * mv.col;
864           ++intercount;
865 
866           best_ref_mv = mv;
867 
868 #if CONFIG_FP_MB_STATS
869           if (cpi->use_fp_mb_stats) {
870             // inter predication statistics
871             cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
872             cpi->twopass.frame_mb_stats_buf[mb_index] &= ~FPMB_DCINTRA_MASK;
873             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
874             if (this_error > FPMB_ERROR_LARGE_TH) {
875               cpi->twopass.frame_mb_stats_buf[mb_index] |=
876                   FPMB_ERROR_LARGE_MASK;
877             } else if (this_error < FPMB_ERROR_SMALL_TH) {
878               cpi->twopass.frame_mb_stats_buf[mb_index] |=
879                   FPMB_ERROR_SMALL_MASK;
880             }
881           }
882 #endif
883 
884           if (!is_zero_mv(&mv)) {
885             ++mvcount;
886 
887 #if CONFIG_FP_MB_STATS
888             if (cpi->use_fp_mb_stats) {
889               cpi->twopass.frame_mb_stats_buf[mb_index] &=
890                   ~FPMB_MOTION_ZERO_MASK;
891               // check estimated motion direction
892               if (mv.col > 0 && mv.col >= abs(mv.row)) {
893                 // right direction
894                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
895                     FPMB_MOTION_RIGHT_MASK;
896               } else if (mv.row < 0 && abs(mv.row) >= abs(mv.col)) {
897                 // up direction
898                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
899                     FPMB_MOTION_UP_MASK;
900               } else if (mv.col < 0 && abs(mv.col) >= abs(mv.row)) {
901                 // left direction
902                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
903                     FPMB_MOTION_LEFT_MASK;
904               } else {
905                 // down direction
906                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
907                     FPMB_MOTION_DOWN_MASK;
908               }
909             }
910 #endif
911 
912             // Non-zero vector, was it different from the last non zero vector?
913             if (!is_equal_mv(&mv, &lastmv)) ++new_mv_count;
914             lastmv = mv;
915 
916             // Does the row vector point inwards or outwards?
917             if (mb_row < cm->mb_rows / 2) {
918               if (mv.row > 0)
919                 --sum_in_vectors;
920               else if (mv.row < 0)
921                 ++sum_in_vectors;
922             } else if (mb_row > cm->mb_rows / 2) {
923               if (mv.row > 0)
924                 ++sum_in_vectors;
925               else if (mv.row < 0)
926                 --sum_in_vectors;
927             }
928 
929             // Does the col vector point inwards or outwards?
930             if (mb_col < cm->mb_cols / 2) {
931               if (mv.col > 0)
932                 --sum_in_vectors;
933               else if (mv.col < 0)
934                 ++sum_in_vectors;
935             } else if (mb_col > cm->mb_cols / 2) {
936               if (mv.col > 0)
937                 ++sum_in_vectors;
938               else if (mv.col < 0)
939                 --sum_in_vectors;
940             }
941           }
942         }
943         raw_motion_err_list[raw_motion_err_counts++] = raw_motion_error;
944       } else {
945         sr_coded_error += (int64_t)this_error;
946       }
947       coded_error += (int64_t)this_error;
948 
949       // Adjust to the next column of MBs.
950       x->plane[0].src.buf += 16;
951       x->plane[1].src.buf += uv_mb_height;
952       x->plane[2].src.buf += uv_mb_height;
953 
954       recon_yoffset += 16;
955       recon_uvoffset += uv_mb_height;
956     }
957     // Adjust to the next row of MBs.
958     x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
959     x->plane[1].src.buf +=
960         uv_mb_height * x->plane[1].src.stride - uv_mb_height * cm->mb_cols;
961     x->plane[2].src.buf +=
962         uv_mb_height * x->plane[1].src.stride - uv_mb_height * cm->mb_cols;
963 
964     aom_clear_system_state();
965   }
966   const double raw_err_stdev =
967       raw_motion_error_stdev(raw_motion_err_list, raw_motion_err_counts);
968   aom_free(raw_motion_err_list);
969 
970   // Clamp the image start to rows/2. This number of rows is discarded top
971   // and bottom as dead data so rows / 2 means the frame is blank.
972   if ((image_data_start_row > cm->mb_rows / 2) ||
973       (image_data_start_row == INVALID_ROW)) {
974     image_data_start_row = cm->mb_rows / 2;
975   }
976   // Exclude any image dead zone
977   if (image_data_start_row > 0) {
978     intra_skip_count =
979         AOMMAX(0, intra_skip_count - (image_data_start_row * cm->mb_cols * 2));
980   }
981 
982   {
983     FIRSTPASS_STATS fps;
984     // The minimum error here insures some bit allocation to frames even
985     // in static regions. The allocation per MB declines for larger formats
986     // where the typical "real" energy per MB also falls.
987     // Initial estimate here uses sqrt(mbs) to define the min_err, where the
988     // number of mbs is proportional to the image area.
989     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
990                             ? cpi->initial_mbs
991                             : cpi->common.MBs;
992     const double min_err = 200 * sqrt(num_mbs);
993 
994     intra_factor = intra_factor / (double)num_mbs;
995     brightness_factor = brightness_factor / (double)num_mbs;
996     fps.weight = intra_factor * brightness_factor;
997 
998     fps.frame = cm->current_video_frame;
999     fps.coded_error = (double)(coded_error >> 8) + min_err;
1000     fps.sr_coded_error = (double)(sr_coded_error >> 8) + min_err;
1001     fps.intra_error = (double)(intra_error >> 8) + min_err;
1002     fps.frame_avg_wavelet_energy = (double)frame_avg_wavelet_energy;
1003     fps.count = 1.0;
1004     fps.pcnt_inter = (double)intercount / num_mbs;
1005     fps.pcnt_second_ref = (double)second_ref_count / num_mbs;
1006     fps.pcnt_neutral = (double)neutral_count / num_mbs;
1007     fps.intra_skip_pct = (double)intra_skip_count / num_mbs;
1008     fps.inactive_zone_rows = (double)image_data_start_row;
1009     fps.inactive_zone_cols = (double)0;  // TODO(paulwilkins): fix
1010     fps.raw_error_stdev = raw_err_stdev;
1011 
1012     if (mvcount > 0) {
1013       fps.MVr = (double)sum_mvr / mvcount;
1014       fps.mvr_abs = (double)sum_mvr_abs / mvcount;
1015       fps.MVc = (double)sum_mvc / mvcount;
1016       fps.mvc_abs = (double)sum_mvc_abs / mvcount;
1017       fps.MVrv =
1018           ((double)sum_mvrs - ((double)sum_mvr * sum_mvr / mvcount)) / mvcount;
1019       fps.MVcv =
1020           ((double)sum_mvcs - ((double)sum_mvc * sum_mvc / mvcount)) / mvcount;
1021       fps.mv_in_out_count = (double)sum_in_vectors / (mvcount * 2);
1022       fps.new_mv_count = new_mv_count;
1023       fps.pcnt_motion = (double)mvcount / num_mbs;
1024     } else {
1025       fps.MVr = 0.0;
1026       fps.mvr_abs = 0.0;
1027       fps.MVc = 0.0;
1028       fps.mvc_abs = 0.0;
1029       fps.MVrv = 0.0;
1030       fps.MVcv = 0.0;
1031       fps.mv_in_out_count = 0.0;
1032       fps.new_mv_count = 0.0;
1033       fps.pcnt_motion = 0.0;
1034     }
1035 
1036     // TODO(paulwilkins):  Handle the case when duration is set to 0, or
1037     // something less than the full time between subsequent values of
1038     // cpi->source_time_stamp.
1039     fps.duration = (double)(source->ts_end - source->ts_start);
1040 
1041     // Don't want to do output stats with a stack variable!
1042     twopass->this_frame_stats = fps;
1043     output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
1044     accumulate_stats(&twopass->total_stats, &fps);
1045 
1046 #if CONFIG_FP_MB_STATS
1047     if (cpi->use_fp_mb_stats) {
1048       output_fpmb_stats(twopass->frame_mb_stats_buf, cpi->initial_mbs,
1049                         cpi->output_pkt_list);
1050     }
1051 #endif
1052   }
1053 
1054   // Copy the previous Last Frame back into gf and and arf buffers if
1055   // the prediction is good enough... but also don't allow it to lag too far.
1056   if ((twopass->sr_update_lag > 3) ||
1057       ((cm->current_video_frame > 0) &&
1058        (twopass->this_frame_stats.pcnt_inter > 0.20) &&
1059        ((twopass->this_frame_stats.intra_error /
1060          DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
1061     if (gld_yv12 != NULL) {
1062       ref_cnt_fb(pool->frame_bufs,
1063                  &cm->ref_frame_map[cpi->ref_fb_idx[GOLDEN_FRAME - 1]],
1064                  cm->ref_frame_map[cpi->ref_fb_idx[LAST_FRAME - 1]]);
1065     }
1066     twopass->sr_update_lag = 1;
1067   } else {
1068     ++twopass->sr_update_lag;
1069   }
1070 
1071   aom_extend_frame_borders(new_yv12, num_planes);
1072 
1073   // The frame we just compressed now becomes the last frame.
1074   ref_cnt_fb(pool->frame_bufs,
1075              &cm->ref_frame_map[cpi->ref_fb_idx[LAST_FRAME - 1]],
1076              cm->new_fb_idx);
1077 
1078   // Special case for the first frame. Copy into the GF buffer as a second
1079   // reference.
1080   if (cm->current_video_frame == 0 &&
1081       cpi->ref_fb_idx[GOLDEN_FRAME - 1] != INVALID_IDX) {
1082     ref_cnt_fb(pool->frame_bufs,
1083                &cm->ref_frame_map[cpi->ref_fb_idx[GOLDEN_FRAME - 1]],
1084                cm->ref_frame_map[cpi->ref_fb_idx[LAST_FRAME - 1]]);
1085   }
1086 
1087   // Use this to see what the first pass reconstruction looks like.
1088   if (0) {
1089     char filename[512];
1090     FILE *recon_file;
1091     snprintf(filename, sizeof(filename), "enc%04d.yuv",
1092              (int)cm->current_video_frame);
1093 
1094     if (cm->current_video_frame == 0)
1095       recon_file = fopen(filename, "wb");
1096     else
1097       recon_file = fopen(filename, "ab");
1098 
1099     (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
1100     fclose(recon_file);
1101   }
1102 
1103   ++cm->current_video_frame;
1104 }
1105 
calc_correction_factor(double err_per_mb,double err_divisor,double pt_low,double pt_high,int q,aom_bit_depth_t bit_depth)1106 static double calc_correction_factor(double err_per_mb, double err_divisor,
1107                                      double pt_low, double pt_high, int q,
1108                                      aom_bit_depth_t bit_depth) {
1109   const double error_term = err_per_mb / err_divisor;
1110 
1111   // Adjustment based on actual quantizer to power term.
1112   const double power_term =
1113       AOMMIN(av1_convert_qindex_to_q(q, bit_depth) * 0.01 + pt_low, pt_high);
1114 
1115   // Calculate correction factor.
1116   if (power_term < 1.0) assert(error_term >= 0.0);
1117 
1118   return fclamp(pow(error_term, power_term), 0.05, 5.0);
1119 }
1120 
1121 #define ERR_DIVISOR 100.0
get_twopass_worst_quality(const AV1_COMP * cpi,const double section_err,double inactive_zone,int section_target_bandwidth,double group_weight_factor)1122 static int get_twopass_worst_quality(const AV1_COMP *cpi,
1123                                      const double section_err,
1124                                      double inactive_zone,
1125                                      int section_target_bandwidth,
1126                                      double group_weight_factor) {
1127   const RATE_CONTROL *const rc = &cpi->rc;
1128   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1129 
1130   inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
1131 
1132   if (section_target_bandwidth <= 0) {
1133     return rc->worst_quality;  // Highest value allowed
1134   } else {
1135     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1136                             ? cpi->initial_mbs
1137                             : cpi->common.MBs;
1138     const int active_mbs = AOMMAX(1, num_mbs - (int)(num_mbs * inactive_zone));
1139     const double av_err_per_mb = section_err / active_mbs;
1140     const double speed_term = 1.0;
1141     double ediv_size_correction;
1142     const int target_norm_bits_per_mb =
1143         (int)((uint64_t)section_target_bandwidth << BPER_MB_NORMBITS) /
1144         active_mbs;
1145     int q;
1146 
1147     // Larger image formats are expected to be a little harder to code
1148     // relatively given the same prediction error score. This in part at
1149     // least relates to the increased size and hence coding overheads of
1150     // motion vectors. Some account of this is made through adjustment of
1151     // the error divisor.
1152     ediv_size_correction =
1153         AOMMAX(0.2, AOMMIN(5.0, get_linear_size_factor(cpi)));
1154     if (ediv_size_correction < 1.0)
1155       ediv_size_correction = -(1.0 / ediv_size_correction);
1156     ediv_size_correction *= 4.0;
1157 
1158     // Try and pick a max Q that will be high enough to encode the
1159     // content at the given rate.
1160     for (q = rc->best_quality; q < rc->worst_quality; ++q) {
1161       const double factor = calc_correction_factor(
1162           av_err_per_mb, ERR_DIVISOR - ediv_size_correction, FACTOR_PT_LOW,
1163           FACTOR_PT_HIGH, q, cpi->common.seq_params.bit_depth);
1164       const int bits_per_mb = av1_rc_bits_per_mb(
1165           INTER_FRAME, q, factor * speed_term * group_weight_factor,
1166           cpi->common.seq_params.bit_depth);
1167       if (bits_per_mb <= target_norm_bits_per_mb) break;
1168     }
1169 
1170     // Restriction on active max q for constrained quality mode.
1171     if (cpi->oxcf.rc_mode == AOM_CQ) q = AOMMAX(q, oxcf->cq_level);
1172     return q;
1173   }
1174 }
1175 
setup_rf_level_maxq(AV1_COMP * cpi)1176 static void setup_rf_level_maxq(AV1_COMP *cpi) {
1177   int i;
1178   RATE_CONTROL *const rc = &cpi->rc;
1179   for (i = INTER_NORMAL; i < RATE_FACTOR_LEVELS; ++i) {
1180     int qdelta = av1_frame_type_qdelta(cpi, i, rc->worst_quality);
1181     rc->rf_level_maxq[i] = AOMMAX(rc->worst_quality + qdelta, rc->best_quality);
1182   }
1183 }
1184 
av1_init_second_pass(AV1_COMP * cpi)1185 void av1_init_second_pass(AV1_COMP *cpi) {
1186   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1187   TWO_PASS *const twopass = &cpi->twopass;
1188   double frame_rate;
1189   FIRSTPASS_STATS *stats;
1190 
1191   zero_stats(&twopass->total_stats);
1192   zero_stats(&twopass->total_left_stats);
1193 
1194   if (!twopass->stats_in_end) return;
1195 
1196   stats = &twopass->total_stats;
1197 
1198   *stats = *twopass->stats_in_end;
1199   twopass->total_left_stats = *stats;
1200 
1201   frame_rate = 10000000.0 * stats->count / stats->duration;
1202   // Each frame can have a different duration, as the frame rate in the source
1203   // isn't guaranteed to be constant. The frame rate prior to the first frame
1204   // encoded in the second pass is a guess. However, the sum duration is not.
1205   // It is calculated based on the actual durations of all frames from the
1206   // first pass.
1207   av1_new_framerate(cpi, frame_rate);
1208   twopass->bits_left =
1209       (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
1210 
1211   // This variable monitors how far behind the second ref update is lagging.
1212   twopass->sr_update_lag = 1;
1213 
1214   // Scan the first pass file and calculate a modified total error based upon
1215   // the bias/power function used to allocate bits.
1216   {
1217     const double avg_error =
1218         stats->coded_error / DOUBLE_DIVIDE_CHECK(stats->count);
1219     const FIRSTPASS_STATS *s = twopass->stats_in;
1220     double modified_error_total = 0.0;
1221     twopass->modified_error_min =
1222         (avg_error * oxcf->two_pass_vbrmin_section) / 100;
1223     twopass->modified_error_max =
1224         (avg_error * oxcf->two_pass_vbrmax_section) / 100;
1225     while (s < twopass->stats_in_end) {
1226       modified_error_total += calculate_modified_err(cpi, twopass, oxcf, s);
1227       ++s;
1228     }
1229     twopass->modified_error_left = modified_error_total;
1230   }
1231 
1232   // Reset the vbr bits off target counters
1233   cpi->rc.vbr_bits_off_target = 0;
1234   cpi->rc.vbr_bits_off_target_fast = 0;
1235 
1236   cpi->rc.rate_error_estimate = 0;
1237 
1238   // Static sequence monitor variables.
1239   twopass->kf_zeromotion_pct = 100;
1240   twopass->last_kfgroup_zeromotion_pct = 100;
1241 
1242   if (oxcf->resize_mode != RESIZE_NONE) {
1243     setup_rf_level_maxq(cpi);
1244   }
1245 }
1246 
1247 #define SR_DIFF_PART 0.0015
1248 #define MOTION_AMP_PART 0.003
1249 #define INTRA_PART 0.005
1250 #define DEFAULT_DECAY_LIMIT 0.75
1251 #define LOW_SR_DIFF_TRHESH 0.1
1252 #define SR_DIFF_MAX 128.0
1253 
get_sr_decay_rate(const AV1_COMP * cpi,const FIRSTPASS_STATS * frame)1254 static double get_sr_decay_rate(const AV1_COMP *cpi,
1255                                 const FIRSTPASS_STATS *frame) {
1256   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
1257                                                              : cpi->common.MBs;
1258   double sr_diff = (frame->sr_coded_error - frame->coded_error) / num_mbs;
1259   double sr_decay = 1.0;
1260   double modified_pct_inter;
1261   double modified_pcnt_intra;
1262   const double motion_amplitude_factor =
1263       frame->pcnt_motion * ((frame->mvc_abs + frame->mvr_abs) / 2);
1264 
1265   modified_pct_inter = frame->pcnt_inter;
1266   if ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
1267       (double)NCOUNT_FRAME_II_THRESH) {
1268     modified_pct_inter = frame->pcnt_inter - frame->pcnt_neutral;
1269   }
1270   modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
1271 
1272   if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
1273     sr_diff = AOMMIN(sr_diff, SR_DIFF_MAX);
1274     sr_decay = 1.0 - (SR_DIFF_PART * sr_diff) -
1275                (MOTION_AMP_PART * motion_amplitude_factor) -
1276                (INTRA_PART * modified_pcnt_intra);
1277   }
1278   return AOMMAX(sr_decay, AOMMIN(DEFAULT_DECAY_LIMIT, modified_pct_inter));
1279 }
1280 
1281 // This function gives an estimate of how badly we believe the prediction
1282 // quality is decaying from frame to frame.
get_zero_motion_factor(const AV1_COMP * cpi,const FIRSTPASS_STATS * frame)1283 static double get_zero_motion_factor(const AV1_COMP *cpi,
1284                                      const FIRSTPASS_STATS *frame) {
1285   const double zero_motion_pct = frame->pcnt_inter - frame->pcnt_motion;
1286   double sr_decay = get_sr_decay_rate(cpi, frame);
1287   return AOMMIN(sr_decay, zero_motion_pct);
1288 }
1289 
1290 #define ZM_POWER_FACTOR 0.75
1291 
get_prediction_decay_rate(const AV1_COMP * cpi,const FIRSTPASS_STATS * next_frame)1292 static double get_prediction_decay_rate(const AV1_COMP *cpi,
1293                                         const FIRSTPASS_STATS *next_frame) {
1294   const double sr_decay_rate = get_sr_decay_rate(cpi, next_frame);
1295   const double zero_motion_factor =
1296       (0.95 * pow((next_frame->pcnt_inter - next_frame->pcnt_motion),
1297                   ZM_POWER_FACTOR));
1298 
1299   return AOMMAX(zero_motion_factor,
1300                 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
1301 }
1302 
1303 // Function to test for a condition where a complex transition is followed
1304 // by a static section. For example in slide shows where there is a fade
1305 // 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)1306 static int detect_transition_to_still(AV1_COMP *cpi, int frame_interval,
1307                                       int still_interval,
1308                                       double loop_decay_rate,
1309                                       double last_decay_rate) {
1310   TWO_PASS *const twopass = &cpi->twopass;
1311   RATE_CONTROL *const rc = &cpi->rc;
1312 
1313   // Break clause to detect very still sections after motion
1314   // For example a static image after a fade or other transition
1315   // instead of a clean scene cut.
1316   if (frame_interval > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
1317       last_decay_rate < 0.9) {
1318     int j;
1319 
1320     // Look ahead a few frames to see if static condition persists...
1321     for (j = 0; j < still_interval; ++j) {
1322       const FIRSTPASS_STATS *stats = &twopass->stats_in[j];
1323       if (stats >= twopass->stats_in_end) break;
1324 
1325       if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
1326     }
1327 
1328     // Only if it does do we signal a transition to still.
1329     return j == still_interval;
1330   }
1331 
1332   return 0;
1333 }
1334 
1335 // This function detects a flash through the high relative pcnt_second_ref
1336 // score in the frame following a flash frame. The offset passed in should
1337 // reflect this.
detect_flash(const TWO_PASS * twopass,int offset)1338 static int detect_flash(const TWO_PASS *twopass, int offset) {
1339   const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
1340 
1341   // What we are looking for here is a situation where there is a
1342   // brief break in prediction (such as a flash) but subsequent frames
1343   // are reasonably well predicted by an earlier (pre flash) frame.
1344   // The recovery after a flash is indicated by a high pcnt_second_ref
1345   // compared to pcnt_inter.
1346   return next_frame != NULL &&
1347          next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
1348          next_frame->pcnt_second_ref >= 0.5;
1349 }
1350 
1351 // 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)1352 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1353                                           double *mv_in_out,
1354                                           double *mv_in_out_accumulator,
1355                                           double *abs_mv_in_out_accumulator,
1356                                           double *mv_ratio_accumulator) {
1357   const double pct = stats->pcnt_motion;
1358 
1359   // Accumulate Motion In/Out of frame stats.
1360   *mv_in_out = stats->mv_in_out_count * pct;
1361   *mv_in_out_accumulator += *mv_in_out;
1362   *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1363 
1364   // Accumulate a measure of how uniform (or conversely how random) the motion
1365   // field is (a ratio of abs(mv) / mv).
1366   if (pct > 0.05) {
1367     const double mvr_ratio =
1368         fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1369     const double mvc_ratio =
1370         fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1371 
1372     *mv_ratio_accumulator +=
1373         pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
1374     *mv_ratio_accumulator +=
1375         pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
1376   }
1377 }
1378 
1379 #define BASELINE_ERR_PER_MB 1000.0
calc_frame_boost(AV1_COMP * cpi,const FIRSTPASS_STATS * this_frame,double this_frame_mv_in_out,double max_boost)1380 static double calc_frame_boost(AV1_COMP *cpi, const FIRSTPASS_STATS *this_frame,
1381                                double this_frame_mv_in_out, double max_boost) {
1382   double frame_boost;
1383   const double lq = av1_convert_qindex_to_q(
1384       cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.seq_params.bit_depth);
1385   const double boost_q_correction = AOMMIN((0.5 + (lq * 0.015)), 1.5);
1386   int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
1387                                                        : cpi->common.MBs;
1388 
1389   // Correct for any inactive region in the image
1390   num_mbs = (int)AOMMAX(1, num_mbs * calculate_active_area(cpi, this_frame));
1391 
1392   // Underlying boost factor is based on inter error ratio.
1393   frame_boost = (BASELINE_ERR_PER_MB * num_mbs) /
1394                 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
1395   frame_boost = frame_boost * BOOST_FACTOR * boost_q_correction;
1396 
1397   // Increase boost for frames where new data coming into frame (e.g. zoom out).
1398   // Slightly reduce boost if there is a net balance of motion out of the frame
1399   // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
1400   if (this_frame_mv_in_out > 0.0)
1401     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1402   // In the extreme case the boost is halved.
1403   else
1404     frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1405 
1406   return AOMMIN(frame_boost, max_boost * boost_q_correction);
1407 }
1408 
calc_arf_boost(AV1_COMP * cpi,int offset,int f_frames,int b_frames,int * f_boost,int * b_boost)1409 static int calc_arf_boost(AV1_COMP *cpi, int offset, int f_frames, int b_frames,
1410                           int *f_boost, int *b_boost) {
1411   TWO_PASS *const twopass = &cpi->twopass;
1412   int i;
1413   double boost_score = 0.0;
1414   double mv_ratio_accumulator = 0.0;
1415   double decay_accumulator = 1.0;
1416   double this_frame_mv_in_out = 0.0;
1417   double mv_in_out_accumulator = 0.0;
1418   double abs_mv_in_out_accumulator = 0.0;
1419   int arf_boost;
1420   int flash_detected = 0;
1421 
1422   // Search forward from the proposed arf/next gf position.
1423   for (i = 0; i < f_frames; ++i) {
1424     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1425     if (this_frame == NULL) break;
1426 
1427     // Update the motion related elements to the boost calculation.
1428     accumulate_frame_motion_stats(
1429         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1430         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1431 
1432     // We want to discount the flash frame itself and the recovery
1433     // frame that follows as both will have poor scores.
1434     flash_detected = detect_flash(twopass, i + offset) ||
1435                      detect_flash(twopass, i + offset + 1);
1436 
1437     // Accumulate the effect of prediction quality decay.
1438     if (!flash_detected) {
1439       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
1440       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1441                               ? MIN_DECAY_FACTOR
1442                               : decay_accumulator;
1443     }
1444 
1445     boost_score +=
1446         decay_accumulator *
1447         calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
1448   }
1449 
1450   *f_boost = (int)boost_score;
1451 
1452   // Reset for backward looking loop.
1453   boost_score = 0.0;
1454   mv_ratio_accumulator = 0.0;
1455   decay_accumulator = 1.0;
1456   this_frame_mv_in_out = 0.0;
1457   mv_in_out_accumulator = 0.0;
1458   abs_mv_in_out_accumulator = 0.0;
1459 
1460   // Search backward towards last gf position.
1461   for (i = -1; i >= -b_frames; --i) {
1462     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1463     if (this_frame == NULL) break;
1464 
1465     // Update the motion related elements to the boost calculation.
1466     accumulate_frame_motion_stats(
1467         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1468         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1469 
1470     // We want to discount the the flash frame itself and the recovery
1471     // frame that follows as both will have poor scores.
1472     flash_detected = detect_flash(twopass, i + offset) ||
1473                      detect_flash(twopass, i + offset + 1);
1474 
1475     // Cumulative effect of prediction quality decay.
1476     if (!flash_detected) {
1477       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
1478       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1479                               ? MIN_DECAY_FACTOR
1480                               : decay_accumulator;
1481     }
1482 
1483     boost_score +=
1484         decay_accumulator *
1485         calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
1486   }
1487   *b_boost = (int)boost_score;
1488 
1489   arf_boost = (*f_boost + *b_boost);
1490   if (arf_boost < ((b_frames + f_frames) * 20))
1491     arf_boost = ((b_frames + f_frames) * 20);
1492   arf_boost = AOMMAX(arf_boost, MIN_ARF_GF_BOOST);
1493 
1494   return arf_boost;
1495 }
1496 
1497 // 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)1498 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
1499                                          const FIRSTPASS_STATS *end,
1500                                          int section_length) {
1501   const FIRSTPASS_STATS *s = begin;
1502   double intra_error = 0.0;
1503   double coded_error = 0.0;
1504   int i = 0;
1505 
1506   while (s < end && i < section_length) {
1507     intra_error += s->intra_error;
1508     coded_error += s->coded_error;
1509     ++s;
1510     ++i;
1511   }
1512 
1513   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
1514 }
1515 
1516 // Calculate the total bits to allocate in this GF/ARF group.
calculate_total_gf_group_bits(AV1_COMP * cpi,double gf_group_err)1517 static int64_t calculate_total_gf_group_bits(AV1_COMP *cpi,
1518                                              double gf_group_err) {
1519   const RATE_CONTROL *const rc = &cpi->rc;
1520   const TWO_PASS *const twopass = &cpi->twopass;
1521   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1522   int64_t total_group_bits;
1523 
1524   // Calculate the bits to be allocated to the group as a whole.
1525   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
1526     total_group_bits = (int64_t)(twopass->kf_group_bits *
1527                                  (gf_group_err / twopass->kf_group_error_left));
1528   } else {
1529     total_group_bits = 0;
1530   }
1531 
1532   // Clamp odd edge cases.
1533   total_group_bits = (total_group_bits < 0)
1534                          ? 0
1535                          : (total_group_bits > twopass->kf_group_bits)
1536                                ? twopass->kf_group_bits
1537                                : total_group_bits;
1538 
1539   // Clip based on user supplied data rate variability limit.
1540   if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
1541     total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
1542 
1543   return total_group_bits;
1544 }
1545 
1546 // 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)1547 static int calculate_boost_bits(int frame_count, int boost,
1548                                 int64_t total_group_bits) {
1549   int allocation_chunks;
1550 
1551   // return 0 for invalid inputs (could arise e.g. through rounding errors)
1552   if (!boost || (total_group_bits <= 0) || (frame_count <= 0)) return 0;
1553 
1554   allocation_chunks = (frame_count * 100) + boost;
1555 
1556   // Prevent overflow.
1557   if (boost > 1023) {
1558     int divisor = boost >> 10;
1559     boost /= divisor;
1560     allocation_chunks /= divisor;
1561   }
1562 
1563   // Calculate the number of extra bits for use in the boosted frame or frames.
1564   return AOMMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
1565                 0);
1566 }
1567 
1568 #if USE_SYMM_MULTI_LAYER
1569 // #define CHCEK_GF_PARAMETER
1570 #ifdef CHCEK_GF_PARAMETER
check_frame_params(GF_GROUP * const gf_group,int gf_interval,int frame_nums)1571 void check_frame_params(GF_GROUP *const gf_group, int gf_interval,
1572                         int frame_nums) {
1573   static const char *update_type_strings[] = {
1574     "KF_UPDATE",          "LF_UPDATE",      "GF_UPDATE",
1575     "ARF_UPDATE",         "OVERLAY_UPDATE", "BRF_UPDATE",
1576     "LAST_BIPRED_UPDATE", "BIPRED_UPDATE",  "INTNL_OVERLAY_UPDATE",
1577     "INTNL_ARF_UPDATE"
1578   };
1579   FILE *fid = fopen("GF_PARAMS.txt", "a");
1580 
1581   fprintf(fid, "\n{%d}\n", gf_interval);
1582   for (int i = 0; i <= frame_nums; ++i) {
1583     fprintf(fid, "%s %d %d %d %d\n",
1584             update_type_strings[gf_group->update_type[i]],
1585             gf_group->arf_src_offset[i], gf_group->arf_pos_in_gf[i],
1586             gf_group->arf_update_idx[i], gf_group->pyramid_level[i]);
1587   }
1588 
1589   fprintf(fid, "number of nodes in each level: \n");
1590   for (int i = 0; i < MAX_PYRAMID_LVL; ++i) {
1591     fprintf(fid, "lvl %d: %d ", i, gf_group->pyramid_lvl_nodes[i]);
1592   }
1593   fprintf(fid, "\n");
1594   fclose(fid);
1595 }
1596 #endif  // CHCEK_GF_PARAMETER
update_type_2_rf_level(FRAME_UPDATE_TYPE update_type)1597 static int update_type_2_rf_level(FRAME_UPDATE_TYPE update_type) {
1598   // Derive rf_level from update_type
1599   switch (update_type) {
1600     case LF_UPDATE: return INTER_NORMAL;
1601     case ARF_UPDATE: return GF_ARF_STD;
1602     case OVERLAY_UPDATE: return INTER_NORMAL;
1603     case BRF_UPDATE: return GF_ARF_LOW;
1604     case LAST_BIPRED_UPDATE: return INTER_NORMAL;
1605     case BIPRED_UPDATE: return INTER_NORMAL;
1606     case INTNL_ARF_UPDATE: return GF_ARF_LOW;
1607     case INTNL_OVERLAY_UPDATE: return INTER_NORMAL;
1608     default: return INTER_NORMAL;
1609   }
1610 }
1611 
set_multi_layer_params(GF_GROUP * const gf_group,int l,int r,int * frame_ind,int arf_ind,int level)1612 static void set_multi_layer_params(GF_GROUP *const gf_group, int l, int r,
1613                                    int *frame_ind, int arf_ind, int level) {
1614   if (r - l < 4) {
1615     while (++l < r) {
1616       // leaf nodes, not a look-ahead frame
1617       gf_group->update_type[*frame_ind] = LF_UPDATE;
1618       gf_group->arf_src_offset[*frame_ind] = 0;
1619       gf_group->arf_pos_in_gf[*frame_ind] = 0;
1620       gf_group->arf_update_idx[*frame_ind] = arf_ind;
1621       gf_group->pyramid_level[*frame_ind] = 0;
1622       ++gf_group->pyramid_lvl_nodes[0];
1623       ++(*frame_ind);
1624     }
1625   } else {
1626     int m = (l + r) / 2;
1627     int arf_pos_in_gf = *frame_ind;
1628 
1629     gf_group->update_type[*frame_ind] = INTNL_ARF_UPDATE;
1630     gf_group->arf_src_offset[*frame_ind] = m - l - 1;
1631     gf_group->arf_pos_in_gf[*frame_ind] = 0;
1632     gf_group->arf_update_idx[*frame_ind] = 1;  // mark all internal ARF 1
1633     gf_group->pyramid_level[*frame_ind] = level;
1634     ++gf_group->pyramid_lvl_nodes[level];
1635     ++(*frame_ind);
1636 
1637     // set parameters for frames displayed before this frame
1638     set_multi_layer_params(gf_group, l, m, frame_ind, 1, level - 1);
1639 
1640     // for overlay frames, we need to record the position of its corresponding
1641     // arf frames for bit allocation
1642     gf_group->update_type[*frame_ind] = INTNL_OVERLAY_UPDATE;
1643     gf_group->arf_src_offset[*frame_ind] = 0;
1644     gf_group->arf_pos_in_gf[*frame_ind] = arf_pos_in_gf;
1645     gf_group->arf_update_idx[*frame_ind] = 1;
1646     gf_group->pyramid_level[*frame_ind] = 0;
1647     ++(*frame_ind);
1648 
1649     // set parameters for frames displayed after this frame
1650     set_multi_layer_params(gf_group, m, r, frame_ind, arf_ind, level - 1);
1651   }
1652 }
1653 
get_pyramid_height(int pyramid_width)1654 static INLINE unsigned char get_pyramid_height(int pyramid_width) {
1655   assert(pyramid_width <= 16 && pyramid_width >= 4 &&
1656          "invalid gf interval for pyramid structure");
1657 
1658   return pyramid_width > 12 ? 4 : (pyramid_width > 6 ? 3 : 2);
1659 }
1660 
construct_multi_layer_gf_structure(GF_GROUP * const gf_group,const int gf_interval)1661 static int construct_multi_layer_gf_structure(GF_GROUP *const gf_group,
1662                                               const int gf_interval) {
1663   int frame_index = 0;
1664   gf_group->pyramid_height = get_pyramid_height(gf_interval);
1665 
1666   assert(gf_group->pyramid_height <= MAX_PYRAMID_LVL);
1667 
1668   av1_zero_array(gf_group->pyramid_lvl_nodes, MAX_PYRAMID_LVL);
1669 
1670   // At the beginning of each GF group it will be a key or overlay frame,
1671   gf_group->update_type[frame_index] = OVERLAY_UPDATE;
1672   gf_group->arf_src_offset[frame_index] = 0;
1673   gf_group->arf_pos_in_gf[frame_index] = 0;
1674   gf_group->arf_update_idx[frame_index] = 0;
1675   gf_group->pyramid_level[frame_index] = 0;
1676   ++frame_index;
1677 
1678   // ALT0
1679   gf_group->update_type[frame_index] = ARF_UPDATE;
1680   gf_group->arf_src_offset[frame_index] = gf_interval - 1;
1681   gf_group->arf_pos_in_gf[frame_index] = 0;
1682   gf_group->arf_update_idx[frame_index] = 0;
1683   gf_group->pyramid_level[frame_index] = gf_group->pyramid_height;
1684   ++frame_index;
1685 
1686   // set parameters for the rest of the frames
1687   set_multi_layer_params(gf_group, 0, gf_interval, &frame_index, 0,
1688                          gf_group->pyramid_height - 1);
1689   return frame_index;
1690 }
1691 
define_customized_gf_group_structure(AV1_COMP * cpi)1692 void define_customized_gf_group_structure(AV1_COMP *cpi) {
1693   RATE_CONTROL *const rc = &cpi->rc;
1694   TWO_PASS *const twopass = &cpi->twopass;
1695   GF_GROUP *const gf_group = &twopass->gf_group;
1696   const int key_frame = cpi->common.frame_type == KEY_FRAME;
1697 
1698   assert(rc->baseline_gf_interval >= 4 &&
1699          rc->baseline_gf_interval <= MAX_PYRAMID_SIZE);
1700 
1701   const int gf_update_frames =
1702       construct_multi_layer_gf_structure(gf_group, rc->baseline_gf_interval);
1703   int frame_index;
1704 
1705   cpi->num_extra_arfs = 0;
1706 
1707   for (frame_index = 0; frame_index < gf_update_frames; ++frame_index) {
1708     // Set unused variables to default values
1709     gf_group->bidir_pred_enabled[frame_index] = 0;
1710     gf_group->brf_src_offset[frame_index] = 0;
1711 
1712     // Special handle for the first frame for assigning update_type
1713     if (frame_index == 0) {
1714       // For key frames the frame target rate is already set and it
1715       // is also the golden frame.
1716       if (key_frame) {
1717         gf_group->update_type[frame_index] = KF_UPDATE;
1718         continue;
1719       }
1720 
1721       if (rc->source_alt_ref_active) {
1722         gf_group->update_type[frame_index] = OVERLAY_UPDATE;
1723       } else {
1724         gf_group->update_type[frame_index] = GF_UPDATE;
1725       }
1726     } else {
1727       if (gf_group->update_type[frame_index] == INTNL_ARF_UPDATE)
1728         ++cpi->num_extra_arfs;
1729     }
1730 
1731     // Assign rf level based on update type
1732     gf_group->rf_level[frame_index] =
1733         update_type_2_rf_level(gf_group->update_type[frame_index]);
1734   }
1735 
1736   // NOTE: We need to configure the frame at the end of the sequence + 1 that
1737   //       will be the start frame for the next group. Otherwise prior to the
1738   //       call to av1_rc_get_second_pass_params() the data will be undefined.
1739   if (rc->source_alt_ref_pending) {
1740     gf_group->update_type[frame_index] = OVERLAY_UPDATE;
1741     gf_group->rf_level[frame_index] = INTER_NORMAL;
1742   } else {
1743     gf_group->update_type[frame_index] = GF_UPDATE;
1744     gf_group->rf_level[frame_index] = GF_ARF_STD;
1745   }
1746 
1747   gf_group->bidir_pred_enabled[frame_index] = 0;
1748   gf_group->brf_src_offset[frame_index] = 0;
1749   gf_group->arf_update_idx[frame_index] = 0;
1750   // This value is only used for INTNL_OVERLAY_UPDATE
1751   gf_group->arf_pos_in_gf[frame_index] = 0;
1752 
1753   // This parameter is useless?
1754   gf_group->arf_ref_idx[frame_index] = 0;
1755 #ifdef CHCEK_GF_PARAMETER
1756   check_frame_params(gf_group, rc->baseline_gf_interval, gf_update_frames);
1757 #endif
1758 }
1759 
1760 // It is an example of how to define a GF stucture manually. The function will
1761 // result in exactly the same GF group structure as
1762 // define_customized_gf_group_structure() when rc->baseline_gf_interval == 4
1763 #if USE_MANUAL_GF4_STRUCT
1764 #define GF_INTERVAL_4 4
1765 static const unsigned char gf4_multi_layer_params[][GF_FRAME_PARAMS] = {
1766   {
1767       // gf_group->index == 0 (Frame 0)
1768       // It can also be KEY frame. Will assign the proper value
1769       // in define_gf_group_structure
1770       OVERLAY_UPDATE,  // update_type (default value)
1771       0,               // arf_src_offset
1772       0,               // arf_pos_in_gf
1773       0                // arf_update_idx
1774   },
1775   {
1776       // gf_group->index == 1 (Frame 4)
1777       ARF_UPDATE,         // update_type
1778       GF_INTERVAL_4 - 1,  // arf_src_offset
1779       0,                  // arf_pos_in_gf
1780       0                   // arf_update_idx
1781   },
1782   {
1783       // gf_group->index == 2 (Frame 2)
1784       INTNL_ARF_UPDATE,          // update_type
1785       (GF_INTERVAL_4 >> 1) - 1,  // arf_src_offset
1786       0,                         // arf_pos_in_gf
1787       0                          // arf_update_idx
1788   },
1789   {
1790       // gf_group->index == 3 (Frame 1)
1791       LAST_BIPRED_UPDATE,  // update_type
1792       0,                   // arf_src_offset
1793       0,                   // arf_pos_in_gf
1794       0                    // arf_update_idx
1795   },
1796 
1797   {
1798       // gf_group->index == 4 (Frame 2 - OVERLAY)
1799       INTNL_OVERLAY_UPDATE,  // update_type
1800       0,                     // arf_src_offset
1801       2,                     // arf_pos_in_gf
1802       0                      // arf_update_idx
1803   },
1804   {
1805       // gf_group->index == 5 (Frame 3)
1806       LF_UPDATE,  // update_type
1807       0,          // arf_src_offset
1808       0,          // arf_pos_in_gf
1809       1           // arf_update_idx
1810   }
1811 };
1812 
define_gf_group_structure_4(AV1_COMP * cpi)1813 static int define_gf_group_structure_4(AV1_COMP *cpi) {
1814   RATE_CONTROL *const rc = &cpi->rc;
1815   TWO_PASS *const twopass = &cpi->twopass;
1816   GF_GROUP *const gf_group = &twopass->gf_group;
1817   const int key_frame = cpi->common.frame_type == KEY_FRAME;
1818 
1819   assert(rc->baseline_gf_interval == GF_INTERVAL_4);
1820 
1821   const int gf_update_frames = rc->baseline_gf_interval + 2;
1822   int frame_index;
1823 
1824   for (frame_index = 0; frame_index < gf_update_frames; ++frame_index) {
1825     int param_idx = 0;
1826 
1827     gf_group->bidir_pred_enabled[frame_index] = 0;
1828 
1829     if (frame_index == 0) {
1830       // gf_group->arf_src_offset[frame_index] = 0;
1831       gf_group->brf_src_offset[frame_index] = 0;
1832       gf_group->bidir_pred_enabled[frame_index] = 0;
1833 
1834       // For key frames the frame target rate is already set and it
1835       // is also the golden frame.
1836       if (key_frame) continue;
1837 
1838       gf_group->update_type[frame_index] =
1839           gf4_multi_layer_params[frame_index][param_idx++];
1840 
1841       if (rc->source_alt_ref_active) {
1842         gf_group->update_type[frame_index] = OVERLAY_UPDATE;
1843       } else {
1844         gf_group->update_type[frame_index] = GF_UPDATE;
1845       }
1846       param_idx++;
1847     } else {
1848       gf_group->update_type[frame_index] =
1849           gf4_multi_layer_params[frame_index][param_idx++];
1850     }
1851 
1852     // setup other parameters
1853     gf_group->rf_level[frame_index] =
1854         update_type_2_rf_level(gf_group->update_type[frame_index]);
1855 
1856     // == arf_src_offset ==
1857     gf_group->arf_src_offset[frame_index] =
1858         gf4_multi_layer_params[frame_index][param_idx++];
1859 
1860     // == arf_pos_in_gf ==
1861     gf_group->arf_pos_in_gf[frame_index] =
1862         gf4_multi_layer_params[frame_index][param_idx++];
1863 
1864     // == arf_update_idx ==
1865     gf_group->brf_src_offset[frame_index] =
1866         gf4_multi_layer_params[frame_index][param_idx];
1867   }
1868 
1869   // NOTE: We need to configure the frame at the end of the sequence + 1 that
1870   //       will be the start frame for the next group. Otherwise prior to the
1871   //       call to av1_rc_get_second_pass_params() the data will be undefined.
1872   gf_group->arf_update_idx[frame_index] = 0;
1873   gf_group->arf_ref_idx[frame_index] = 0;
1874 
1875   if (rc->source_alt_ref_pending) {
1876     gf_group->update_type[frame_index] = OVERLAY_UPDATE;
1877     gf_group->rf_level[frame_index] = INTER_NORMAL;
1878 
1879   } else {
1880     gf_group->update_type[frame_index] = GF_UPDATE;
1881     gf_group->rf_level[frame_index] = GF_ARF_STD;
1882   }
1883 
1884   gf_group->bidir_pred_enabled[frame_index] = 0;
1885   gf_group->brf_src_offset[frame_index] = 0;
1886 
1887   // This value is only used for INTNL_OVERLAY_UPDATE
1888   gf_group->arf_pos_in_gf[frame_index] = 0;
1889 
1890   return gf_update_frames;
1891 }
1892 #endif  // USE_MANUAL_GF4_STRUCT
1893 #endif  // USE_SYMM_MULTI_LAYER
1894 
define_gf_group_structure(AV1_COMP * cpi)1895 static void define_gf_group_structure(AV1_COMP *cpi) {
1896   RATE_CONTROL *const rc = &cpi->rc;
1897 
1898 #if USE_SYMM_MULTI_LAYER
1899   const int valid_customized_gf_length =
1900       rc->baseline_gf_interval >= 4 &&
1901       rc->baseline_gf_interval <= MAX_PYRAMID_SIZE;
1902   // used the new structure only if extra_arf is allowed
1903   if (valid_customized_gf_length && rc->source_alt_ref_pending &&
1904       cpi->extra_arf_allowed > 0) {
1905 #if USE_MANUAL_GF4_STRUCT
1906     if (rc->baseline_gf_interval == 4)
1907       define_gf_group_structure_4(cpi);
1908     else
1909 #endif
1910       define_customized_gf_group_structure(cpi);
1911     cpi->new_bwdref_update_rule = 1;
1912     return;
1913   } else {
1914     cpi->new_bwdref_update_rule = 0;
1915   }
1916 #endif
1917 
1918   TWO_PASS *const twopass = &cpi->twopass;
1919   GF_GROUP *const gf_group = &twopass->gf_group;
1920   int i;
1921   int frame_index = 0;
1922   const int key_frame = cpi->common.frame_type == KEY_FRAME;
1923 
1924   // The use of bi-predictive frames are only enabled when following 3
1925   // conditions are met:
1926   // (1) ALTREF is enabled;
1927   // (2) The bi-predictive group interval is at least 2; and
1928   // (3) The bi-predictive group interval is strictly smaller than the
1929   //     golden group interval.
1930   const int is_bipred_enabled =
1931       cpi->extra_arf_allowed && rc->source_alt_ref_pending &&
1932       rc->bipred_group_interval &&
1933       rc->bipred_group_interval <=
1934           (rc->baseline_gf_interval - rc->source_alt_ref_pending);
1935   int bipred_group_end = 0;
1936   int bipred_frame_index = 0;
1937 
1938   const unsigned char ext_arf_interval =
1939       (unsigned char)(rc->baseline_gf_interval / (cpi->num_extra_arfs + 1) - 1);
1940   int which_arf = cpi->num_extra_arfs;
1941   int subgroup_interval[MAX_EXT_ARFS + 1];
1942   int is_sg_bipred_enabled = is_bipred_enabled;
1943   int accumulative_subgroup_interval = 0;
1944 
1945   // For key frames the frame target rate is already set and it
1946   // is also the golden frame.
1947   // === [frame_index == 0] ===
1948   if (!key_frame) {
1949     if (rc->source_alt_ref_active) {
1950       gf_group->update_type[frame_index] = OVERLAY_UPDATE;
1951       gf_group->rf_level[frame_index] = INTER_NORMAL;
1952     } else {
1953       gf_group->update_type[frame_index] = GF_UPDATE;
1954       gf_group->rf_level[frame_index] = GF_ARF_STD;
1955     }
1956     gf_group->arf_update_idx[frame_index] = 0;
1957     gf_group->arf_ref_idx[frame_index] = 0;
1958   }
1959 
1960   gf_group->bidir_pred_enabled[frame_index] = 0;
1961   gf_group->brf_src_offset[frame_index] = 0;
1962 
1963   frame_index++;
1964 
1965   bipred_frame_index++;
1966 
1967   // === [frame_index == 1] ===
1968   if (rc->source_alt_ref_pending) {
1969     gf_group->update_type[frame_index] = ARF_UPDATE;
1970     gf_group->rf_level[frame_index] = GF_ARF_STD;
1971     gf_group->arf_src_offset[frame_index] =
1972         (unsigned char)(rc->baseline_gf_interval - 1);
1973 
1974     gf_group->arf_update_idx[frame_index] = 0;
1975     gf_group->arf_ref_idx[frame_index] = 0;
1976 
1977     gf_group->bidir_pred_enabled[frame_index] = 0;
1978     gf_group->brf_src_offset[frame_index] = 0;
1979     // NOTE: "bidir_pred_frame_index" stays unchanged for ARF_UPDATE frames.
1980 
1981     // Work out the ARFs' positions in this gf group
1982     // NOTE(weitinglin): ALT_REFs' are indexed inversely, but coded in display
1983     // order (except for the original ARF). In the example of three ALT_REF's,
1984     // We index ALTREF's as: KEY ----- ALT2 ----- ALT1 ----- ALT0
1985     // but code them in the following order:
1986     // KEY-ALT0-ALT2 ----- OVERLAY2-ALT1 ----- OVERLAY1 ----- OVERLAY0
1987     //
1988     // arf_pos_for_ovrly[]: Position for OVERLAY
1989     // arf_pos_in_gf[]:     Position for ALTREF
1990     cpi->arf_pos_for_ovrly[0] = frame_index + cpi->num_extra_arfs +
1991                                 gf_group->arf_src_offset[frame_index] + 1;
1992     for (i = 0; i < cpi->num_extra_arfs; ++i) {
1993       cpi->arf_pos_for_ovrly[i + 1] =
1994           frame_index + (cpi->num_extra_arfs - i) * (ext_arf_interval + 2);
1995       subgroup_interval[i] = cpi->arf_pos_for_ovrly[i] -
1996                              cpi->arf_pos_for_ovrly[i + 1] - (i == 0 ? 1 : 2);
1997     }
1998     subgroup_interval[cpi->num_extra_arfs] =
1999         cpi->arf_pos_for_ovrly[cpi->num_extra_arfs] - frame_index -
2000         (cpi->num_extra_arfs == 0 ? 1 : 2);
2001 
2002     ++frame_index;
2003 
2004     // Insert an extra ARF
2005     // === [frame_index == 2] ===
2006     if (cpi->num_extra_arfs) {
2007       gf_group->update_type[frame_index] = INTNL_ARF_UPDATE;
2008       gf_group->rf_level[frame_index] = GF_ARF_LOW;
2009       gf_group->arf_src_offset[frame_index] = ext_arf_interval;
2010 
2011       gf_group->arf_update_idx[frame_index] = which_arf;
2012       gf_group->arf_ref_idx[frame_index] = 0;
2013       ++frame_index;
2014     }
2015     accumulative_subgroup_interval += subgroup_interval[cpi->num_extra_arfs];
2016   }
2017 
2018   for (i = 0; i < rc->baseline_gf_interval - rc->source_alt_ref_pending; ++i) {
2019     gf_group->arf_update_idx[frame_index] = which_arf;
2020     gf_group->arf_ref_idx[frame_index] = which_arf;
2021 
2022     // If we are going to have ARFs, check whether we can have BWDREF in this
2023     // subgroup, and further, whether we can have ARF subgroup which contains
2024     // the BWDREF subgroup but contained within the GF group:
2025     //
2026     // GF group --> ARF subgroup --> BWDREF subgroup
2027     if (rc->source_alt_ref_pending) {
2028       is_sg_bipred_enabled =
2029           is_bipred_enabled &&
2030           (subgroup_interval[which_arf] > rc->bipred_group_interval);
2031     }
2032 
2033     // NOTE: BIDIR_PRED is only enabled when the length of the bi-predictive
2034     //       frame group interval is strictly smaller than that of the GOLDEN
2035     //       FRAME group interval.
2036     // TODO(zoeliu): Currently BIDIR_PRED is only enabled when alt-ref is on.
2037     if (is_sg_bipred_enabled && !bipred_group_end) {
2038       const int cur_brf_src_offset = rc->bipred_group_interval - 1;
2039 
2040       if (bipred_frame_index == 1) {
2041         // --- BRF_UPDATE ---
2042         gf_group->update_type[frame_index] = BRF_UPDATE;
2043         gf_group->rf_level[frame_index] = GF_ARF_LOW;
2044         gf_group->brf_src_offset[frame_index] = cur_brf_src_offset;
2045       } else if (bipred_frame_index == rc->bipred_group_interval) {
2046         // --- LAST_BIPRED_UPDATE ---
2047         gf_group->update_type[frame_index] = LAST_BIPRED_UPDATE;
2048         gf_group->rf_level[frame_index] = INTER_NORMAL;
2049         gf_group->brf_src_offset[frame_index] = 0;
2050 
2051         // Reset the bi-predictive frame index.
2052         bipred_frame_index = 0;
2053       } else {
2054         // --- BIPRED_UPDATE ---
2055         gf_group->update_type[frame_index] = BIPRED_UPDATE;
2056         gf_group->rf_level[frame_index] = INTER_NORMAL;
2057         gf_group->brf_src_offset[frame_index] = 0;
2058       }
2059       gf_group->bidir_pred_enabled[frame_index] = 1;
2060 
2061       bipred_frame_index++;
2062       // Check whether the next bi-predictive frame group would entirely be
2063       // included within the current golden frame group.
2064       // In addition, we need to avoid coding a BRF right before an ARF.
2065       if (bipred_frame_index == 1 &&
2066           (i + 2 + cur_brf_src_offset) >= accumulative_subgroup_interval) {
2067         bipred_group_end = 1;
2068       }
2069     } else {
2070       gf_group->update_type[frame_index] = LF_UPDATE;
2071       gf_group->rf_level[frame_index] = INTER_NORMAL;
2072       gf_group->bidir_pred_enabled[frame_index] = 0;
2073       gf_group->brf_src_offset[frame_index] = 0;
2074     }
2075 
2076     ++frame_index;
2077 
2078     // Check if we need to update the ARF.
2079     if (is_sg_bipred_enabled && cpi->num_extra_arfs && which_arf > 0 &&
2080         frame_index > cpi->arf_pos_for_ovrly[which_arf]) {
2081       --which_arf;
2082       accumulative_subgroup_interval += subgroup_interval[which_arf] + 1;
2083 
2084       // Meet the new subgroup; Reset the bipred_group_end flag.
2085       bipred_group_end = 0;
2086       // Insert another extra ARF after the overlay frame
2087       if (which_arf) {
2088         gf_group->update_type[frame_index] = INTNL_ARF_UPDATE;
2089         gf_group->rf_level[frame_index] = GF_ARF_LOW;
2090         gf_group->arf_src_offset[frame_index] = ext_arf_interval;
2091 
2092         gf_group->arf_update_idx[frame_index] = which_arf;
2093         gf_group->arf_ref_idx[frame_index] = 0;
2094         ++frame_index;
2095       }
2096     }
2097   }
2098 
2099   // NOTE: We need to configure the frame at the end of the sequence + 1 that
2100   //       will be the start frame for the next group. Otherwise prior to the
2101   //       call to av1_rc_get_second_pass_params() the data will be undefined.
2102   gf_group->arf_update_idx[frame_index] = 0;
2103   gf_group->arf_ref_idx[frame_index] = 0;
2104 
2105   if (rc->source_alt_ref_pending) {
2106     gf_group->update_type[frame_index] = OVERLAY_UPDATE;
2107     gf_group->rf_level[frame_index] = INTER_NORMAL;
2108 
2109     cpi->arf_pos_in_gf[0] = 1;
2110     if (cpi->num_extra_arfs) {
2111       // Overwrite the update_type for extra-ARF's corresponding internal
2112       // OVERLAY's: Change from LF_UPDATE to INTNL_OVERLAY_UPDATE.
2113       for (i = cpi->num_extra_arfs; i > 0; --i) {
2114         cpi->arf_pos_in_gf[i] =
2115             (i == cpi->num_extra_arfs ? 2 : cpi->arf_pos_for_ovrly[i + 1] + 1);
2116 
2117         gf_group->update_type[cpi->arf_pos_for_ovrly[i]] = INTNL_OVERLAY_UPDATE;
2118         gf_group->rf_level[cpi->arf_pos_for_ovrly[i]] = INTER_NORMAL;
2119       }
2120     }
2121   } else {
2122     gf_group->update_type[frame_index] = GF_UPDATE;
2123     gf_group->rf_level[frame_index] = GF_ARF_STD;
2124   }
2125 
2126   gf_group->bidir_pred_enabled[frame_index] = 0;
2127   gf_group->brf_src_offset[frame_index] = 0;
2128 }
2129 
2130 #if USE_SYMM_MULTI_LAYER
2131 #define LEAF_REDUCTION_FACTOR 0.75f
2132 #define LVL_3_BOOST_FACTOR 0.8f
2133 #define LVL_2_BOOST_FACTOR 0.3f
2134 
2135 static float_t lvl_budget_factor[MAX_PYRAMID_LVL - 1][MAX_PYRAMID_LVL - 1] = {
2136   { 1, 0, 0 },
2137   { LVL_3_BOOST_FACTOR, 0, 0 },  // Leaking budget works better
2138   { LVL_3_BOOST_FACTOR, (1 - LVL_3_BOOST_FACTOR) * LVL_2_BOOST_FACTOR,
2139     (1 - LVL_3_BOOST_FACTOR) * (1 - LVL_2_BOOST_FACTOR) }
2140 };
2141 #endif  // USE_SYMM_MULTI_LAYER
allocate_gf_group_bits(AV1_COMP * cpi,int64_t gf_group_bits,double group_error,int gf_arf_bits)2142 static void allocate_gf_group_bits(AV1_COMP *cpi, int64_t gf_group_bits,
2143                                    double group_error, int gf_arf_bits) {
2144   RATE_CONTROL *const rc = &cpi->rc;
2145   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2146   TWO_PASS *const twopass = &cpi->twopass;
2147   GF_GROUP *const gf_group = &twopass->gf_group;
2148   FIRSTPASS_STATS frame_stats;
2149   int i;
2150   int frame_index = 0;
2151   int target_frame_size;
2152   int key_frame;
2153   const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
2154   int64_t total_group_bits = gf_group_bits;
2155   double modified_err = 0.0;
2156   double err_fraction;
2157   int ext_arf_boost[MAX_EXT_ARFS];
2158 
2159   define_gf_group_structure(cpi);
2160 
2161   av1_zero_array(ext_arf_boost, MAX_EXT_ARFS);
2162 
2163   key_frame = cpi->common.frame_type == KEY_FRAME;
2164 
2165   // For key frames the frame target rate is already set and it
2166   // is also the golden frame.
2167   // === [frame_index == 0] ===
2168   if (!key_frame) {
2169     if (rc->source_alt_ref_active)
2170       gf_group->bit_allocation[frame_index] = 0;
2171     else
2172       gf_group->bit_allocation[frame_index] = gf_arf_bits;
2173 
2174     // Step over the golden frame / overlay frame
2175     if (EOF == input_stats(twopass, &frame_stats)) return;
2176   }
2177 
2178   // Deduct the boost bits for arf (or gf if it is not a key frame)
2179   // from the group total.
2180   if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
2181 
2182   frame_index++;
2183 
2184   // Store the bits to spend on the ARF if there is one.
2185   // === [frame_index == 1] ===
2186   if (rc->source_alt_ref_pending) {
2187     gf_group->bit_allocation[frame_index] = gf_arf_bits;
2188 
2189     ++frame_index;
2190 
2191     // Skip all the extra-ARF's right after ARF at the starting segment of
2192     // the current GF group.
2193     if (cpi->num_extra_arfs) {
2194       while (gf_group->update_type[frame_index] == INTNL_ARF_UPDATE)
2195         ++frame_index;
2196     }
2197   }
2198 
2199   // Allocate bits to the other frames in the group.
2200   for (i = 0; i < rc->baseline_gf_interval - rc->source_alt_ref_pending; ++i) {
2201     if (EOF == input_stats(twopass, &frame_stats)) break;
2202 
2203     modified_err = calculate_modified_err(cpi, twopass, oxcf, &frame_stats);
2204 
2205     if (group_error > 0)
2206       err_fraction = modified_err / DOUBLE_DIVIDE_CHECK(group_error);
2207     else
2208       err_fraction = 0.0;
2209 
2210     target_frame_size = (int)((double)total_group_bits * err_fraction);
2211 
2212     target_frame_size =
2213         clamp(target_frame_size, 0, AOMMIN(max_bits, (int)total_group_bits));
2214 
2215     if (gf_group->update_type[frame_index] == BRF_UPDATE) {
2216       // Boost up the allocated bits on BWDREF_FRAME
2217       gf_group->bit_allocation[frame_index] =
2218           target_frame_size + (target_frame_size >> 2);
2219     } else if (gf_group->update_type[frame_index] == LAST_BIPRED_UPDATE) {
2220       // Press down the allocated bits on LAST_BIPRED_UPDATE frames
2221       gf_group->bit_allocation[frame_index] =
2222           target_frame_size - (target_frame_size >> 1);
2223     } else if (gf_group->update_type[frame_index] == BIPRED_UPDATE) {
2224       // TODO(zoeliu): To investigate whether the allocated bits on
2225       // BIPRED_UPDATE frames need to be further adjusted.
2226       gf_group->bit_allocation[frame_index] = target_frame_size;
2227 #if USE_SYMM_MULTI_LAYER
2228     } else if (cpi->new_bwdref_update_rule &&
2229                gf_group->update_type[frame_index] == INTNL_OVERLAY_UPDATE) {
2230       assert(gf_group->pyramid_height <= MAX_PYRAMID_LVL &&
2231              gf_group->pyramid_height >= 0 &&
2232              "non-valid height for a pyramid structure");
2233 
2234       int arf_pos = gf_group->arf_pos_in_gf[frame_index];
2235       gf_group->bit_allocation[frame_index] = 0;
2236 
2237       gf_group->bit_allocation[arf_pos] = target_frame_size;
2238 #if MULTI_LVL_BOOST_VBR_CQ
2239       const int pyr_h = gf_group->pyramid_height - 2;
2240       const int this_lvl = gf_group->pyramid_level[arf_pos];
2241       const int dist2top = gf_group->pyramid_height - 1 - this_lvl;
2242 
2243       const float_t budget =
2244           LEAF_REDUCTION_FACTOR * gf_group->pyramid_lvl_nodes[0];
2245       const float_t lvl_boost = budget * lvl_budget_factor[pyr_h][dist2top] /
2246                                 gf_group->pyramid_lvl_nodes[this_lvl];
2247 
2248       gf_group->bit_allocation[arf_pos] += (int)(target_frame_size * lvl_boost);
2249 #endif  // MULTI_LVL_BOOST_VBR_CQ
2250 #endif  // USE_SYMM_MULTI_LAYER
2251     } else {
2252       assert(gf_group->update_type[frame_index] == LF_UPDATE ||
2253              gf_group->update_type[frame_index] == INTNL_OVERLAY_UPDATE);
2254       gf_group->bit_allocation[frame_index] = target_frame_size;
2255 #if MULTI_LVL_BOOST_VBR_CQ
2256       if (cpi->new_bwdref_update_rule) {
2257         gf_group->bit_allocation[frame_index] -=
2258             (int)(target_frame_size * LEAF_REDUCTION_FACTOR);
2259       }
2260 #endif  // MULTI_LVL_BOOST_VBR_CQ
2261     }
2262 
2263     ++frame_index;
2264 
2265     // Skip all the extra-ARF's.
2266     if (cpi->num_extra_arfs) {
2267       while (gf_group->update_type[frame_index] == INTNL_ARF_UPDATE)
2268         ++frame_index;
2269     }
2270   }
2271 
2272 #if USE_SYMM_MULTI_LAYER
2273   if (cpi->new_bwdref_update_rule == 0 && rc->source_alt_ref_pending) {
2274 #else
2275   if (rc->source_alt_ref_pending) {
2276 #endif
2277     if (cpi->num_extra_arfs) {
2278       // NOTE: For bit allocation, move the allocated bits associated with
2279       //       INTNL_OVERLAY_UPDATE to the corresponding INTNL_ARF_UPDATE.
2280       //       i > 0 for extra-ARF's and i == 0 for ARF:
2281       //         arf_pos_for_ovrly[i]: Position for INTNL_OVERLAY_UPDATE
2282       //         arf_pos_in_gf[i]: Position for INTNL_ARF_UPDATE
2283       for (i = cpi->num_extra_arfs; i > 0; --i) {
2284         assert(gf_group->update_type[cpi->arf_pos_for_ovrly[i]] ==
2285                INTNL_OVERLAY_UPDATE);
2286 
2287         // Encoder's choice:
2288         //   Set show_existing_frame == 1 for all extra-ARF's, and hence
2289         //   allocate zero bit for both all internal OVERLAY frames.
2290         gf_group->bit_allocation[cpi->arf_pos_in_gf[i]] =
2291             gf_group->bit_allocation[cpi->arf_pos_for_ovrly[i]];
2292         gf_group->bit_allocation[cpi->arf_pos_for_ovrly[i]] = 0;
2293       }
2294     }
2295   }
2296 }
2297 
2298 // Analyse and define a gf/arf group.
2299 static void define_gf_group(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2300   AV1_COMMON *const cm = &cpi->common;
2301   RATE_CONTROL *const rc = &cpi->rc;
2302   AV1EncoderConfig *const oxcf = &cpi->oxcf;
2303   TWO_PASS *const twopass = &cpi->twopass;
2304   FIRSTPASS_STATS next_frame;
2305   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2306   int i;
2307 
2308   double boost_score = 0.0;
2309 #if !CONFIG_FIX_GF_LENGTH
2310   double old_boost_score = 0.0;
2311   double mv_ratio_accumulator_thresh;
2312   int active_max_gf_interval;
2313   int active_min_gf_interval;
2314 #endif
2315   double gf_group_err = 0.0;
2316 #if GROUP_ADAPTIVE_MAXQ
2317   double gf_group_raw_error = 0.0;
2318 #endif
2319   double gf_group_skip_pct = 0.0;
2320   double gf_group_inactive_zone_rows = 0.0;
2321   double gf_first_frame_err = 0.0;
2322   double mod_frame_err = 0.0;
2323 
2324   double mv_ratio_accumulator = 0.0;
2325   double decay_accumulator = 1.0;
2326   double zero_motion_accumulator = 1.0;
2327 
2328   double loop_decay_rate = 1.00;
2329   double last_loop_decay_rate = 1.00;
2330 
2331   double this_frame_mv_in_out = 0.0;
2332   double mv_in_out_accumulator = 0.0;
2333   double abs_mv_in_out_accumulator = 0.0;
2334 
2335   unsigned int allow_alt_ref = is_altref_enabled(cpi);
2336 
2337   int f_boost = 0;
2338   int b_boost = 0;
2339   int flash_detected;
2340   int64_t gf_group_bits;
2341   double gf_group_error_left;
2342   int gf_arf_bits;
2343   const int is_key_frame = frame_is_intra_only(cm);
2344   const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2345 
2346   cpi->extra_arf_allowed = 1;
2347 
2348   // Reset the GF group data structures unless this is a key
2349   // frame in which case it will already have been done.
2350   if (is_key_frame == 0) {
2351     av1_zero(twopass->gf_group);
2352   }
2353 
2354   aom_clear_system_state();
2355   av1_zero(next_frame);
2356 
2357   // Load stats for the current frame.
2358   mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
2359 
2360   // Note the error of the frame at the start of the group. This will be
2361   // the GF frame error if we code a normal gf.
2362   gf_first_frame_err = mod_frame_err;
2363 
2364   // If this is a key frame or the overlay from a previous arf then
2365   // the error score / cost of this frame has already been accounted for.
2366   if (arf_active_or_kf) {
2367     gf_group_err -= gf_first_frame_err;
2368 #if GROUP_ADAPTIVE_MAXQ
2369     gf_group_raw_error -= this_frame->coded_error;
2370 #endif
2371     gf_group_skip_pct -= this_frame->intra_skip_pct;
2372     gf_group_inactive_zone_rows -= this_frame->inactive_zone_rows;
2373   }
2374 #if !CONFIG_FIX_GF_LENGTH
2375   // Motion breakout threshold for loop below depends on image size.
2376   mv_ratio_accumulator_thresh =
2377       (cpi->initial_height + cpi->initial_width) / 4.0;
2378   // Set a maximum and minimum interval for the GF group.
2379   // If the image appears almost completely static we can extend beyond this.
2380   {
2381     int int_max_q = (int)(av1_convert_qindex_to_q(
2382         twopass->active_worst_quality, cpi->common.seq_params.bit_depth));
2383     int int_lbq = (int)(av1_convert_qindex_to_q(
2384         rc->last_boosted_qindex, cpi->common.seq_params.bit_depth));
2385 
2386     active_min_gf_interval = rc->min_gf_interval + AOMMIN(2, int_max_q / 200);
2387     if (active_min_gf_interval > rc->max_gf_interval)
2388       active_min_gf_interval = rc->max_gf_interval;
2389 
2390     // The value chosen depends on the active Q range. At low Q we have
2391     // bits to spare and are better with a smaller interval and smaller boost.
2392     // At high Q when there are few bits to spare we are better with a longer
2393     // interval to spread the cost of the GF.
2394     active_max_gf_interval = 12 + AOMMIN(4, (int_lbq / 6));
2395 
2396     // We have: active_min_gf_interval <= rc->max_gf_interval
2397     if (active_max_gf_interval < active_min_gf_interval)
2398       active_max_gf_interval = active_min_gf_interval;
2399     else if (active_max_gf_interval > rc->max_gf_interval)
2400       active_max_gf_interval = rc->max_gf_interval;
2401   }
2402 #endif  // !CONFIG_FIX_GF_LENGTH
2403   double avg_sr_coded_error = 0;
2404   double avg_raw_err_stdev = 0;
2405   int non_zero_stdev_count = 0;
2406 
2407   i = 0;
2408   while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
2409     ++i;
2410 
2411     // Accumulate error score of frames in this gf group.
2412     mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
2413     gf_group_err += mod_frame_err;
2414 #if GROUP_ADAPTIVE_MAXQ
2415     gf_group_raw_error += this_frame->coded_error;
2416 #endif
2417     gf_group_skip_pct += this_frame->intra_skip_pct;
2418     gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
2419 
2420     if (EOF == input_stats(twopass, &next_frame)) break;
2421 
2422     // Test for the case where there is a brief flash but the prediction
2423     // quality back to an earlier frame is then restored.
2424     flash_detected = detect_flash(twopass, 0);
2425 
2426     // Update the motion related elements to the boost calculation.
2427     accumulate_frame_motion_stats(
2428         &next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2429         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2430     // sum up the metric values of current gf group
2431     avg_sr_coded_error += next_frame.sr_coded_error;
2432     if (fabs(next_frame.raw_error_stdev) > 0.000001) {
2433       non_zero_stdev_count++;
2434       avg_raw_err_stdev += next_frame.raw_error_stdev;
2435     }
2436 
2437     // Accumulate the effect of prediction quality decay.
2438     if (!flash_detected) {
2439       last_loop_decay_rate = loop_decay_rate;
2440       loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2441 
2442       decay_accumulator = decay_accumulator * loop_decay_rate;
2443 
2444       // Monitor for static sections.
2445       zero_motion_accumulator = AOMMIN(
2446           zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
2447 
2448       // Break clause to detect very still sections after motion. For example,
2449       // a static image after a fade or other transition.
2450       if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
2451                                      last_loop_decay_rate)) {
2452         allow_alt_ref = 0;
2453         break;
2454       }
2455     }
2456 
2457     // Calculate a boost number for this frame.
2458     boost_score +=
2459         decay_accumulator *
2460         calc_frame_boost(cpi, &next_frame, this_frame_mv_in_out, GF_MAX_BOOST);
2461 #if CONFIG_FIX_GF_LENGTH
2462     if (i == (FIXED_GF_LENGTH + 1)) break;
2463 #else
2464     // Skip breaking condition for CONFIG_FIX_GF_LENGTH
2465     // Break out conditions.
2466     if (
2467         // Break at active_max_gf_interval unless almost totally static.
2468         (i >= (active_max_gf_interval + arf_active_or_kf) &&
2469          zero_motion_accumulator < 0.995) ||
2470         (
2471             // Don't break out with a very short interval.
2472             (i >= active_min_gf_interval + arf_active_or_kf) &&
2473             (!flash_detected) &&
2474             ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
2475              (abs_mv_in_out_accumulator > 3.0) ||
2476              (mv_in_out_accumulator < -2.0) ||
2477              ((boost_score - old_boost_score) < BOOST_BREAKOUT)))) {
2478       // If GF group interval is < 12, we force it to be 8. Otherwise,
2479       // if it is >= 12, we keep it as is.
2480       // NOTE: 'i' is 1 more than the GF group interval candidate that is being
2481       //       checked.
2482       if (i == (8 + 1) || i >= (12 + 1)) {
2483         boost_score = old_boost_score;
2484         break;
2485       }
2486     }
2487     old_boost_score = boost_score;
2488 #endif  // CONFIG_FIX_GF_LENGTH
2489     *this_frame = next_frame;
2490   }
2491   twopass->gf_zeromotion_pct = (int)(zero_motion_accumulator * 1000.0);
2492 
2493   // Was the group length constrained by the requirement for a new KF?
2494   rc->constrained_gf_group = (i >= rc->frames_to_key) ? 1 : 0;
2495 
2496   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
2497                                                              : cpi->common.MBs;
2498   assert(num_mbs > 0);
2499   if (i) avg_sr_coded_error /= i;
2500 
2501   if (non_zero_stdev_count) avg_raw_err_stdev /= non_zero_stdev_count;
2502 
2503   // Disable extra altrefs and backward refs for "still" gf group:
2504   //   zero_motion_accumulator: minimum percentage of (0,0) motion;
2505   //   avg_sr_coded_error:      average of the SSE per pixel of each frame;
2506   //   avg_raw_err_stdev:       average of the standard deviation of (0,0)
2507   //                            motion error per block of each frame.
2508   const int disable_bwd_extarf =
2509       (zero_motion_accumulator > MIN_ZERO_MOTION &&
2510        avg_sr_coded_error / num_mbs < MAX_SR_CODED_ERROR &&
2511        avg_raw_err_stdev < MAX_RAW_ERR_VAR);
2512 
2513   if (disable_bwd_extarf) cpi->extra_arf_allowed = 0;
2514 
2515 #define REDUCE_GF_LENGTH_THRESH 4
2516 #define REDUCE_GF_LENGTH_TO_KEY_THRESH 9
2517 #define REDUCE_GF_LENGTH_BY 1
2518   int alt_offset = 0;
2519 #if REDUCE_LAST_GF_LENGTH
2520   // TODO(weitinglin): The length reduction stretagy is tweaking using AOM_Q
2521   // mode, and hurting the performance of VBR mode. We need to investigate how
2522   // to adjust GF length for other modes.
2523 
2524   int allow_gf_length_reduction =
2525       cpi->oxcf.rc_mode == AOM_Q || cpi->extra_arf_allowed == 0;
2526 
2527   // We are going to have an alt ref, but we don't have do adjustment for
2528   // lossless mode
2529   if (allow_alt_ref && allow_gf_length_reduction &&
2530       (i < cpi->oxcf.lag_in_frames) && (i >= rc->min_gf_interval) &&
2531       !is_lossless_requested(&cpi->oxcf)) {
2532     // adjust length of this gf group if one of the following condition met
2533     // 1: only one overlay frame left and this gf is too long
2534     // 2: next gf group is too short to have arf compared to the current gf
2535 
2536     // maximum length of next gf group
2537     const int next_gf_len = rc->frames_to_key - i;
2538     const int single_overlay_left =
2539         next_gf_len == 0 && i > REDUCE_GF_LENGTH_THRESH;
2540     // the next gf is probably going to have a ARF but it will be shorter than
2541     // this gf
2542     const int unbalanced_gf =
2543         i > REDUCE_GF_LENGTH_TO_KEY_THRESH &&
2544         next_gf_len + 1 < REDUCE_GF_LENGTH_TO_KEY_THRESH &&
2545         next_gf_len + 1 >= rc->min_gf_interval;
2546 
2547     if (single_overlay_left || unbalanced_gf) {
2548       // Note: Tried roll_back = DIVIDE_AND_ROUND(i, 8), but is does not work
2549       // better in the current setting
2550       const int roll_back = REDUCE_GF_LENGTH_BY;
2551       alt_offset = -roll_back;
2552       i -= roll_back;
2553     }
2554   }
2555 #endif
2556 
2557   // Should we use the alternate reference frame.
2558   if (allow_alt_ref && (i < cpi->oxcf.lag_in_frames) &&
2559       (i >= rc->min_gf_interval)) {
2560     // Calculate the boost for alt ref.
2561     rc->gfu_boost =
2562         calc_arf_boost(cpi, alt_offset, (i - 1), (i - 1), &f_boost, &b_boost);
2563     rc->source_alt_ref_pending = 1;
2564 
2565     // do not replace ARFs with overlay frames, and keep it as GOLDEN_REF
2566     cpi->preserve_arf_as_gld = 1;
2567   } else {
2568     rc->gfu_boost = AOMMAX((int)boost_score, MIN_ARF_GF_BOOST);
2569     rc->source_alt_ref_pending = 0;
2570     cpi->preserve_arf_as_gld = 0;
2571   }
2572 
2573   // Set the interval until the next gf.
2574   // If forward keyframes are enabled, ensure the final gf group obeys the
2575   // MIN_FWD_KF_INTERVAL.
2576   if (cpi->oxcf.fwd_kf_enabled &&
2577       ((twopass->stats_in - i + rc->frames_to_key) < twopass->stats_in_end)) {
2578     if (i == rc->frames_to_key) {
2579       rc->baseline_gf_interval = i;
2580       // if the last gf group will be smaller than MIN_FWD_KF_INTERVAL
2581     } else if ((rc->frames_to_key - i <
2582                 AOMMAX(MIN_FWD_KF_INTERVAL, rc->min_gf_interval)) &&
2583                (rc->frames_to_key != i)) {
2584       // if possible, merge the last two gf groups
2585       if (rc->frames_to_key <= MAX_PYRAMID_SIZE) {
2586         rc->baseline_gf_interval = rc->frames_to_key;
2587         // if merging the last two gf groups creates a group that is too long,
2588         // split them and force the last gf group to be the MIN_FWD_KF_INTERVAL
2589       } else {
2590         rc->baseline_gf_interval = rc->frames_to_key - MIN_FWD_KF_INTERVAL;
2591       }
2592     } else {
2593       rc->baseline_gf_interval =
2594           i - (is_key_frame || rc->source_alt_ref_pending);
2595     }
2596   } else {
2597     rc->baseline_gf_interval = i - (is_key_frame || rc->source_alt_ref_pending);
2598   }
2599 
2600 #if REDUCE_LAST_ALT_BOOST
2601 #define LAST_ALR_BOOST_FACTOR 0.2f
2602   rc->arf_boost_factor = 1.0;
2603   if (rc->source_alt_ref_pending && !is_lossless_requested(&cpi->oxcf)) {
2604     // Reduce the boost of altref in the last gf group
2605     if (rc->frames_to_key - i == REDUCE_GF_LENGTH_BY ||
2606         rc->frames_to_key - i == 0) {
2607       rc->arf_boost_factor = LAST_ALR_BOOST_FACTOR;
2608     }
2609   }
2610 #endif
2611 
2612   if (!cpi->extra_arf_allowed) {
2613     cpi->num_extra_arfs = 0;
2614   } else {
2615 #if USE_SYMM_MULTI_LAYER
2616     if (rc->baseline_gf_interval == 4 && rc->source_alt_ref_pending)
2617       cpi->num_extra_arfs = 1;
2618     else
2619       cpi->num_extra_arfs = get_number_of_extra_arfs(
2620           rc->baseline_gf_interval, rc->source_alt_ref_pending);
2621 #else
2622     // Compute how many extra alt_refs we can have
2623     cpi->num_extra_arfs = get_number_of_extra_arfs(rc->baseline_gf_interval,
2624                                                    rc->source_alt_ref_pending);
2625 #endif  // USE_SYMM_MULTI_LAYER
2626   }
2627 
2628 #if !USE_SYMM_MULTI_LAYER
2629   // Currently at maximum two extra ARFs' are allowed
2630   assert(cpi->num_extra_arfs <= MAX_EXT_ARFS);
2631 #endif
2632 
2633   rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2634 
2635   rc->bipred_group_interval = BFG_INTERVAL;
2636   // The minimum bi-predictive frame group interval is 2.
2637   if (rc->bipred_group_interval < 2) rc->bipred_group_interval = 0;
2638 
2639   // Reset the file position.
2640   reset_fpf_position(twopass, start_pos);
2641 
2642   // Calculate the bits to be allocated to the gf/arf group as a whole
2643   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
2644 
2645 #if GROUP_ADAPTIVE_MAXQ
2646   // Calculate an estimate of the maxq needed for the group.
2647   // We are more agressive about correcting for sections
2648   // where there could be significant overshoot than for easier
2649   // sections where we do not wish to risk creating an overshoot
2650   // of the allocated bit budget.
2651   if ((cpi->oxcf.rc_mode != AOM_Q) && (rc->baseline_gf_interval > 1)) {
2652     const int vbr_group_bits_per_frame =
2653         (int)(gf_group_bits / rc->baseline_gf_interval);
2654     const double group_av_err = gf_group_raw_error / rc->baseline_gf_interval;
2655     const double group_av_skip_pct =
2656         gf_group_skip_pct / rc->baseline_gf_interval;
2657     const double group_av_inactive_zone =
2658         ((gf_group_inactive_zone_rows * 2) /
2659          (rc->baseline_gf_interval * (double)cm->mb_rows));
2660 
2661     int tmp_q;
2662     // rc factor is a weight factor that corrects for local rate control drift.
2663     double rc_factor = 1.0;
2664     if (rc->rate_error_estimate > 0) {
2665       rc_factor = AOMMAX(RC_FACTOR_MIN,
2666                          (double)(100 - rc->rate_error_estimate) / 100.0);
2667     } else {
2668       rc_factor = AOMMIN(RC_FACTOR_MAX,
2669                          (double)(100 - rc->rate_error_estimate) / 100.0);
2670     }
2671     tmp_q = get_twopass_worst_quality(
2672         cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2673         vbr_group_bits_per_frame, twopass->kfgroup_inter_fraction * rc_factor);
2674     twopass->active_worst_quality =
2675         AOMMAX(tmp_q, twopass->active_worst_quality >> 1);
2676   }
2677 #endif
2678 
2679   // Calculate the extra bits to be used for boosted frame(s)
2680   gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval, rc->gfu_boost,
2681                                      gf_group_bits);
2682 
2683   // Adjust KF group bits and error remaining.
2684   twopass->kf_group_error_left -= (int64_t)gf_group_err;
2685 
2686   // If this is an arf update we want to remove the score for the overlay
2687   // frame at the end which will usually be very cheap to code.
2688   // The overlay frame has already, in effect, been coded so we want to spread
2689   // the remaining bits among the other frames.
2690   // For normal GFs remove the score for the GF itself unless this is
2691   // also a key frame in which case it has already been accounted for.
2692   if (rc->source_alt_ref_pending) {
2693     gf_group_error_left = gf_group_err - mod_frame_err;
2694   } else if (is_key_frame == 0) {
2695     gf_group_error_left = gf_group_err - gf_first_frame_err;
2696   } else {
2697     gf_group_error_left = gf_group_err;
2698   }
2699 
2700   // Allocate bits to each of the frames in the GF group.
2701   allocate_gf_group_bits(cpi, gf_group_bits, gf_group_error_left, gf_arf_bits);
2702 
2703   // Reset the file position.
2704   reset_fpf_position(twopass, start_pos);
2705 
2706   // Calculate a section intra ratio used in setting max loop filter.
2707   if (cpi->common.frame_type != KEY_FRAME) {
2708     twopass->section_intra_rating = calculate_section_intra_ratio(
2709         start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
2710   }
2711 }
2712 
2713 // Threshold for use of the lagging second reference frame. High second ref
2714 // usage may point to a transient event like a flash or occlusion rather than
2715 // a real scene cut.
2716 #define SECOND_REF_USEAGE_THRESH 0.1
2717 // Minimum % intra coding observed in first pass (1.0 = 100%)
2718 #define MIN_INTRA_LEVEL 0.25
2719 // Minimum ratio between the % of intra coding and inter coding in the first
2720 // pass after discounting neutral blocks (discounting neutral blocks in this
2721 // way helps catch scene cuts in clips with very flat areas or letter box
2722 // format clips with image padding.
2723 #define INTRA_VS_INTER_THRESH 2.0
2724 // Hard threshold where the first pass chooses intra for almost all blocks.
2725 // In such a case even if the frame is not a scene cut coding a key frame
2726 // may be a good option.
2727 #define VERY_LOW_INTER_THRESH 0.05
2728 // Maximum threshold for the relative ratio of intra error score vs best
2729 // inter error score.
2730 #define KF_II_ERR_THRESHOLD 2.5
2731 // In real scene cuts there is almost always a sharp change in the intra
2732 // or inter error score.
2733 #define ERR_CHANGE_THRESHOLD 0.4
2734 // For real scene cuts we expect an improvment in the intra inter error
2735 // ratio in the next frame.
2736 #define II_IMPROVEMENT_THRESHOLD 3.5
2737 #define KF_II_MAX 128.0
2738 
2739 static int test_candidate_kf(TWO_PASS *twopass,
2740                              const FIRSTPASS_STATS *last_frame,
2741                              const FIRSTPASS_STATS *this_frame,
2742                              const FIRSTPASS_STATS *next_frame) {
2743   int is_viable_kf = 0;
2744   double pcnt_intra = 1.0 - this_frame->pcnt_inter;
2745   double modified_pcnt_inter =
2746       this_frame->pcnt_inter - this_frame->pcnt_neutral;
2747 
2748   // Does the frame satisfy the primary criteria of a key frame?
2749   // See above for an explanation of the test criteria.
2750   // If so, then examine how well it predicts subsequent frames.
2751   if ((this_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2752       (next_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2753       ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
2754        ((pcnt_intra > MIN_INTRA_LEVEL) &&
2755         (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
2756         ((this_frame->intra_error /
2757           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
2758          KF_II_ERR_THRESHOLD) &&
2759         ((fabs(last_frame->coded_error - this_frame->coded_error) /
2760               DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
2761           ERR_CHANGE_THRESHOLD) ||
2762          (fabs(last_frame->intra_error - this_frame->intra_error) /
2763               DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
2764           ERR_CHANGE_THRESHOLD) ||
2765          ((next_frame->intra_error /
2766            DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) >
2767           II_IMPROVEMENT_THRESHOLD))))) {
2768     int i;
2769     const FIRSTPASS_STATS *start_pos = twopass->stats_in;
2770     FIRSTPASS_STATS local_next_frame = *next_frame;
2771     double boost_score = 0.0;
2772     double old_boost_score = 0.0;
2773     double decay_accumulator = 1.0;
2774 
2775     // Examine how well the key frame predicts subsequent frames.
2776     for (i = 0; i < 16; ++i) {
2777       double next_iiratio = (BOOST_FACTOR * local_next_frame.intra_error /
2778                              DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
2779 
2780       if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
2781 
2782       // Cumulative effect of decay in prediction quality.
2783       if (local_next_frame.pcnt_inter > 0.85)
2784         decay_accumulator *= local_next_frame.pcnt_inter;
2785       else
2786         decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
2787 
2788       // Keep a running total.
2789       boost_score += (decay_accumulator * next_iiratio);
2790 
2791       // Test various breakout clauses.
2792       if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
2793           (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
2794             0.20) &&
2795            (next_iiratio < 3.0)) ||
2796           ((boost_score - old_boost_score) < 3.0) ||
2797           (local_next_frame.intra_error < 200)) {
2798         break;
2799       }
2800 
2801       old_boost_score = boost_score;
2802 
2803       // Get the next frame details
2804       if (EOF == input_stats(twopass, &local_next_frame)) break;
2805     }
2806 
2807     // If there is tolerable prediction for at least the next 3 frames then
2808     // break out else discard this potential key frame and move on
2809     if (boost_score > 30.0 && (i > 3)) {
2810       is_viable_kf = 1;
2811     } else {
2812       // Reset the file position
2813       reset_fpf_position(twopass, start_pos);
2814 
2815       is_viable_kf = 0;
2816     }
2817   }
2818 
2819   return is_viable_kf;
2820 }
2821 
2822 #define FRAMES_TO_CHECK_DECAY 8
2823 
2824 static void find_next_key_frame(AV1_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2825   int i, j;
2826   RATE_CONTROL *const rc = &cpi->rc;
2827   TWO_PASS *const twopass = &cpi->twopass;
2828   GF_GROUP *const gf_group = &twopass->gf_group;
2829   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2830   const FIRSTPASS_STATS first_frame = *this_frame;
2831   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
2832   FIRSTPASS_STATS next_frame;
2833   FIRSTPASS_STATS last_frame;
2834   int kf_bits = 0;
2835   int loop_decay_counter = 0;
2836   double decay_accumulator = 1.0;
2837   double av_decay_accumulator = 0.0;
2838   double zero_motion_accumulator = 1.0;
2839   double boost_score = 0.0;
2840   double kf_mod_err = 0.0;
2841   double kf_group_err = 0.0;
2842   double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
2843 
2844   av1_zero(next_frame);
2845 
2846   cpi->common.frame_type = KEY_FRAME;
2847 
2848   // Reset the GF group data structures.
2849   av1_zero(*gf_group);
2850 
2851   // Is this a forced key frame by interval.
2852   rc->this_key_frame_forced = rc->next_key_frame_forced;
2853 
2854   // Clear the alt ref active flag and last group multi arf flags as they
2855   // can never be set for a key frame.
2856   rc->source_alt_ref_active = 0;
2857 
2858   // KF is always a GF so clear frames till next gf counter.
2859   rc->frames_till_gf_update_due = 0;
2860 
2861   rc->frames_to_key = 1;
2862 
2863   twopass->kf_group_bits = 0;        // Total bits available to kf group
2864   twopass->kf_group_error_left = 0;  // Group modified error score.
2865 
2866   kf_mod_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
2867 
2868   // Initialize the decay rates for the recent frames to check
2869   for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
2870 
2871   // Find the next keyframe.
2872   i = 0;
2873   while (twopass->stats_in < twopass->stats_in_end &&
2874          rc->frames_to_key < cpi->oxcf.key_freq) {
2875     // Accumulate kf group error.
2876     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2877 
2878     // Load the next frame's stats.
2879     last_frame = *this_frame;
2880     input_stats(twopass, this_frame);
2881 
2882     // Provided that we are not at the end of the file...
2883     if (cpi->oxcf.auto_key && twopass->stats_in < twopass->stats_in_end) {
2884       double loop_decay_rate;
2885 
2886       // Check for a scene cut.
2887       if (test_candidate_kf(twopass, &last_frame, this_frame,
2888                             twopass->stats_in))
2889         break;
2890 
2891       // How fast is the prediction quality decaying?
2892       loop_decay_rate = get_prediction_decay_rate(cpi, twopass->stats_in);
2893 
2894       // We want to know something about the recent past... rather than
2895       // as used elsewhere where we are concerned with decay in prediction
2896       // quality since the last GF or KF.
2897       recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
2898       decay_accumulator = 1.0;
2899       for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
2900         decay_accumulator *= recent_loop_decay[j];
2901 
2902       // Special check for transition or high motion followed by a
2903       // static scene.
2904       if (detect_transition_to_still(cpi, i, cpi->oxcf.key_freq - i,
2905                                      loop_decay_rate, decay_accumulator))
2906         break;
2907 
2908       // Step on to the next frame.
2909       ++rc->frames_to_key;
2910 
2911       // If we don't have a real key frame within the next two
2912       // key_freq intervals then break out of the loop.
2913       if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq) break;
2914     } else {
2915       ++rc->frames_to_key;
2916     }
2917     ++i;
2918   }
2919 
2920   // If there is a max kf interval set by the user we must obey it.
2921   // We already breakout of the loop above at 2x max.
2922   // This code centers the extra kf if the actual natural interval
2923   // is between 1x and 2x.
2924   if (cpi->oxcf.auto_key && rc->frames_to_key > cpi->oxcf.key_freq) {
2925     FIRSTPASS_STATS tmp_frame = first_frame;
2926 
2927     rc->frames_to_key /= 2;
2928 
2929     // Reset to the start of the group.
2930     reset_fpf_position(twopass, start_position);
2931 
2932     kf_group_err = 0.0;
2933 
2934     // Rescan to get the correct error data for the forced kf group.
2935     for (i = 0; i < rc->frames_to_key; ++i) {
2936       kf_group_err += calculate_modified_err(cpi, twopass, oxcf, &tmp_frame);
2937       input_stats(twopass, &tmp_frame);
2938     }
2939     rc->next_key_frame_forced = 1;
2940   } else if (twopass->stats_in == twopass->stats_in_end ||
2941              rc->frames_to_key >= cpi->oxcf.key_freq) {
2942     rc->next_key_frame_forced = 1;
2943   } else {
2944     rc->next_key_frame_forced = 0;
2945   }
2946 
2947   // Special case for the last key frame of the file.
2948   if (twopass->stats_in >= twopass->stats_in_end) {
2949     // Accumulate kf group error.
2950     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2951   }
2952 
2953   // Calculate the number of bits that should be assigned to the kf group.
2954   if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
2955     // Maximum number of bits for a single normal frame (not key frame).
2956     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2957 
2958     // Maximum number of bits allocated to the key frame group.
2959     int64_t max_grp_bits;
2960 
2961     // Default allocation based on bits left and relative
2962     // complexity of the section.
2963     twopass->kf_group_bits = (int64_t)(
2964         twopass->bits_left * (kf_group_err / twopass->modified_error_left));
2965 
2966     // Clip based on maximum per frame rate defined by the user.
2967     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
2968     if (twopass->kf_group_bits > max_grp_bits)
2969       twopass->kf_group_bits = max_grp_bits;
2970   } else {
2971     twopass->kf_group_bits = 0;
2972   }
2973   twopass->kf_group_bits = AOMMAX(0, twopass->kf_group_bits);
2974 
2975   // Reset the first pass file position.
2976   reset_fpf_position(twopass, start_position);
2977 
2978   // Scan through the kf group collating various stats used to determine
2979   // how many bits to spend on it.
2980   decay_accumulator = 1.0;
2981   boost_score = 0.0;
2982   const double kf_max_boost =
2983       cpi->oxcf.rc_mode == AOM_Q
2984           ? AOMMIN(AOMMAX(rc->frames_to_key * 2.0, KF_MIN_FRAME_BOOST),
2985                    KF_MAX_FRAME_BOOST)
2986           : KF_MAX_FRAME_BOOST;
2987   for (i = 0; i < (rc->frames_to_key - 1); ++i) {
2988     if (EOF == input_stats(twopass, &next_frame)) break;
2989 
2990     // Monitor for static sections.
2991     zero_motion_accumulator = AOMMIN(zero_motion_accumulator,
2992                                      get_zero_motion_factor(cpi, &next_frame));
2993 
2994     // Not all frames in the group are necessarily used in calculating boost.
2995     if ((i <= rc->max_gf_interval) ||
2996         ((i <= (rc->max_gf_interval * 4)) && (decay_accumulator > 0.5))) {
2997       const double frame_boost =
2998           calc_frame_boost(cpi, this_frame, 0, kf_max_boost);
2999 
3000       // How fast is prediction quality decaying.
3001       if (!detect_flash(twopass, 0)) {
3002         const double loop_decay_rate =
3003             get_prediction_decay_rate(cpi, &next_frame);
3004         decay_accumulator *= loop_decay_rate;
3005         decay_accumulator = AOMMAX(decay_accumulator, MIN_DECAY_FACTOR);
3006         av_decay_accumulator += decay_accumulator;
3007         ++loop_decay_counter;
3008       }
3009       boost_score += (decay_accumulator * frame_boost);
3010     }
3011   }
3012   if (loop_decay_counter > 0)
3013     av_decay_accumulator /= (double)loop_decay_counter;
3014 
3015   reset_fpf_position(twopass, start_position);
3016 
3017   // Store the zero motion percentage
3018   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
3019 
3020   // Calculate a section intra ratio used in setting max loop filter.
3021   twopass->section_intra_rating = calculate_section_intra_ratio(
3022       start_position, twopass->stats_in_end, rc->frames_to_key);
3023 
3024   // Apply various clamps for min and max boost
3025   rc->kf_boost = (int)(av_decay_accumulator * boost_score);
3026   rc->kf_boost = AOMMAX(rc->kf_boost, (rc->frames_to_key * 3));
3027   rc->kf_boost = AOMMAX(rc->kf_boost, MIN_KF_BOOST);
3028 
3029   // Work out how many bits to allocate for the key frame itself.
3030   kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
3031                                  twopass->kf_group_bits);
3032   // printf("kf boost = %d kf_bits = %d kf_zeromotion_pct = %d\n", rc->kf_boost,
3033   //        kf_bits, twopass->kf_zeromotion_pct);
3034 
3035   // Work out the fraction of the kf group bits reserved for the inter frames
3036   // within the group after discounting the bits for the kf itself.
3037   if (twopass->kf_group_bits) {
3038     twopass->kfgroup_inter_fraction =
3039         (double)(twopass->kf_group_bits - kf_bits) /
3040         (double)twopass->kf_group_bits;
3041   } else {
3042     twopass->kfgroup_inter_fraction = 1.0;
3043   }
3044 
3045   twopass->kf_group_bits -= kf_bits;
3046 
3047   // Save the bits to spend on the key frame.
3048   gf_group->bit_allocation[0] = kf_bits;
3049   gf_group->update_type[0] = KF_UPDATE;
3050   gf_group->rf_level[0] = KF_STD;
3051 
3052   // Note the total error score of the kf group minus the key frame itself.
3053   twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
3054 
3055   // Adjust the count of total modified error left.
3056   // The count of bits left is adjusted elsewhere based on real coded frame
3057   // sizes.
3058   twopass->modified_error_left -= kf_group_err;
3059 }
3060 
3061 // Define the reference buffers that will be updated post encode.
3062 static void configure_buffer_updates(AV1_COMP *cpi) {
3063   TWO_PASS *const twopass = &cpi->twopass;
3064 
3065   // NOTE(weitinglin): Should we define another function to take care of
3066   // cpi->rc.is_$Source_Type to make this function as it is in the comment?
3067 
3068   cpi->rc.is_src_frame_alt_ref = 0;
3069   cpi->rc.is_bwd_ref_frame = 0;
3070   cpi->rc.is_last_bipred_frame = 0;
3071   cpi->rc.is_bipred_frame = 0;
3072   cpi->rc.is_src_frame_ext_arf = 0;
3073 
3074   switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
3075     case KF_UPDATE:
3076       cpi->refresh_last_frame = 1;
3077       cpi->refresh_golden_frame = 1;
3078       cpi->refresh_bwd_ref_frame = 1;
3079       cpi->refresh_alt2_ref_frame = 1;
3080       cpi->refresh_alt_ref_frame = 1;
3081       break;
3082 
3083     case LF_UPDATE:
3084       cpi->refresh_last_frame = 1;
3085       cpi->refresh_golden_frame = 0;
3086       cpi->refresh_bwd_ref_frame = 0;
3087       cpi->refresh_alt2_ref_frame = 0;
3088       cpi->refresh_alt_ref_frame = 0;
3089       break;
3090 
3091     case GF_UPDATE:
3092       // TODO(zoeliu): To further investigate whether 'refresh_last_frame' is
3093       //               needed.
3094       cpi->refresh_last_frame = 1;
3095       cpi->refresh_golden_frame = 1;
3096       cpi->refresh_bwd_ref_frame = 0;
3097       cpi->refresh_alt2_ref_frame = 0;
3098       cpi->refresh_alt_ref_frame = 0;
3099       break;
3100 
3101     case OVERLAY_UPDATE:
3102       cpi->refresh_last_frame = 0;
3103       cpi->refresh_golden_frame = 1;
3104       cpi->refresh_bwd_ref_frame = 0;
3105       cpi->refresh_alt2_ref_frame = 0;
3106       cpi->refresh_alt_ref_frame = 0;
3107 
3108       cpi->rc.is_src_frame_alt_ref = 1;
3109       break;
3110 
3111     case ARF_UPDATE:
3112       cpi->refresh_last_frame = 0;
3113       cpi->refresh_golden_frame = 0;
3114       // NOTE: BWDREF does not get updated along with ALTREF_FRAME.
3115       cpi->refresh_bwd_ref_frame = 0;
3116       cpi->refresh_alt2_ref_frame = 0;
3117       cpi->refresh_alt_ref_frame = 1;
3118       break;
3119 
3120     case BRF_UPDATE:
3121       cpi->refresh_last_frame = 0;
3122       cpi->refresh_golden_frame = 0;
3123       cpi->refresh_bwd_ref_frame = 1;
3124       cpi->refresh_alt2_ref_frame = 0;
3125       cpi->refresh_alt_ref_frame = 0;
3126 
3127       cpi->rc.is_bwd_ref_frame = 1;
3128       break;
3129 
3130     case LAST_BIPRED_UPDATE:
3131       cpi->refresh_last_frame = 1;
3132       cpi->refresh_golden_frame = 0;
3133       cpi->refresh_bwd_ref_frame = 0;
3134       cpi->refresh_alt2_ref_frame = 0;
3135       cpi->refresh_alt_ref_frame = 0;
3136 
3137       cpi->rc.is_last_bipred_frame = 1;
3138       break;
3139 
3140     case BIPRED_UPDATE:
3141       cpi->refresh_last_frame = 1;
3142       cpi->refresh_golden_frame = 0;
3143       cpi->refresh_bwd_ref_frame = 0;
3144       cpi->refresh_alt2_ref_frame = 0;
3145       cpi->refresh_alt_ref_frame = 0;
3146 
3147       cpi->rc.is_bipred_frame = 1;
3148       break;
3149 
3150     case INTNL_OVERLAY_UPDATE:
3151       cpi->refresh_last_frame = 1;
3152       cpi->refresh_golden_frame = 0;
3153       cpi->refresh_bwd_ref_frame = 0;
3154       cpi->refresh_alt2_ref_frame = 0;
3155       cpi->refresh_alt_ref_frame = 0;
3156 
3157       cpi->rc.is_src_frame_alt_ref = 1;
3158       cpi->rc.is_src_frame_ext_arf = 1;
3159       break;
3160 
3161     case INTNL_ARF_UPDATE:
3162       cpi->refresh_last_frame = 0;
3163       cpi->refresh_golden_frame = 0;
3164 #if USE_SYMM_MULTI_LAYER
3165       if (cpi->new_bwdref_update_rule == 1) {
3166         cpi->refresh_bwd_ref_frame = 1;
3167         cpi->refresh_alt2_ref_frame = 0;
3168       } else {
3169 #endif
3170         cpi->refresh_bwd_ref_frame = 0;
3171         cpi->refresh_alt2_ref_frame = 1;
3172 #if USE_SYMM_MULTI_LAYER
3173       }
3174 #endif
3175       cpi->refresh_alt_ref_frame = 0;
3176       break;
3177 
3178     default: assert(0); break;
3179   }
3180 }
3181 
3182 void av1_configure_buffer_updates_firstpass(AV1_COMP *cpi,
3183                                             FRAME_UPDATE_TYPE update_type) {
3184   RATE_CONTROL *rc = &cpi->rc;
3185 
3186   cpi->refresh_last_frame = 1;
3187   cpi->refresh_golden_frame = 0;
3188   cpi->refresh_bwd_ref_frame = 0;
3189   cpi->refresh_alt2_ref_frame = 0;
3190   cpi->refresh_alt_ref_frame = 0;
3191 
3192   rc->is_bwd_ref_frame = 0;
3193 
3194   switch (update_type) {
3195     case ARF_UPDATE:
3196       cpi->refresh_alt_ref_frame = 1;
3197       cpi->refresh_last_frame = 0;
3198       cpi->refresh_golden_frame = 0;
3199       cpi->refresh_bwd_ref_frame = 0;
3200       cpi->refresh_alt2_ref_frame = 0;
3201 
3202       rc->is_src_frame_alt_ref = 0;
3203       break;
3204     case INTNL_ARF_UPDATE:
3205       cpi->refresh_alt2_ref_frame = 1;
3206       cpi->refresh_last_frame = 0;
3207       cpi->refresh_golden_frame = 0;
3208       cpi->refresh_bwd_ref_frame = 0;
3209       cpi->refresh_alt_ref_frame = 0;
3210       rc->is_src_frame_alt_ref = 0;
3211       rc->is_src_frame_ext_arf = 0;
3212 
3213       break;
3214     case BIPRED_UPDATE:
3215       cpi->refresh_bwd_ref_frame = 1;
3216       cpi->refresh_last_frame = 0;
3217       cpi->refresh_golden_frame = 0;
3218       cpi->refresh_alt2_ref_frame = 0;
3219       cpi->refresh_alt_ref_frame = 0;
3220 
3221       rc->is_bwd_ref_frame = 1;
3222       break;
3223     default: break;
3224   }
3225 }
3226 
3227 static int is_skippable_frame(const AV1_COMP *cpi) {
3228   // If the current frame does not have non-zero motion vector detected in the
3229   // first  pass, and so do its previous and forward frames, then this frame
3230   // can be skipped for partition check, and the partition size is assigned
3231   // according to the variance
3232   const TWO_PASS *const twopass = &cpi->twopass;
3233 
3234   return (!frame_is_intra_only(&cpi->common) &&
3235           twopass->stats_in - 2 > twopass->stats_in_start &&
3236           twopass->stats_in < twopass->stats_in_end &&
3237           (twopass->stats_in - 1)->pcnt_inter -
3238                   (twopass->stats_in - 1)->pcnt_motion ==
3239               1 &&
3240           (twopass->stats_in - 2)->pcnt_inter -
3241                   (twopass->stats_in - 2)->pcnt_motion ==
3242               1 &&
3243           twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
3244 }
3245 
3246 void av1_rc_get_second_pass_params(AV1_COMP *cpi) {
3247   AV1_COMMON *const cm = &cpi->common;
3248   RATE_CONTROL *const rc = &cpi->rc;
3249   TWO_PASS *const twopass = &cpi->twopass;
3250   GF_GROUP *const gf_group = &twopass->gf_group;
3251   int frames_left;
3252   FIRSTPASS_STATS this_frame;
3253 
3254   int target_rate;
3255 
3256   frames_left = (int)(twopass->total_stats.count - cm->current_video_frame);
3257 
3258   if (!twopass->stats_in) return;
3259 
3260   // If this is an arf frame then we dont want to read the stats file or
3261   // advance the input pointer as we already have what we need.
3262   if (gf_group->update_type[gf_group->index] == ARF_UPDATE ||
3263       gf_group->update_type[gf_group->index] == INTNL_ARF_UPDATE) {
3264     configure_buffer_updates(cpi);
3265     target_rate = gf_group->bit_allocation[gf_group->index];
3266     target_rate = av1_rc_clamp_pframe_target_size(cpi, target_rate);
3267     rc->base_frame_target = target_rate;
3268 
3269     if (cpi->no_show_kf) {
3270       assert(gf_group->update_type[gf_group->index] == ARF_UPDATE);
3271       cm->frame_type = KEY_FRAME;
3272     } else {
3273       cm->frame_type = INTER_FRAME;
3274     }
3275 
3276     // Do the firstpass stats indicate that this frame is skippable for the
3277     // partition search?
3278     if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2) {
3279       cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
3280     }
3281 
3282     return;
3283   }
3284 
3285   aom_clear_system_state();
3286 
3287   if (cpi->oxcf.rc_mode == AOM_Q) {
3288     twopass->active_worst_quality = cpi->oxcf.cq_level;
3289   } else if (cm->current_video_frame == 0) {
3290     // Special case code for first frame.
3291     const int section_target_bandwidth =
3292         (int)(twopass->bits_left / frames_left);
3293     const double section_length = twopass->total_left_stats.count;
3294     const double section_error =
3295         twopass->total_left_stats.coded_error / section_length;
3296     const double section_intra_skip =
3297         twopass->total_left_stats.intra_skip_pct / section_length;
3298     const double section_inactive_zone =
3299         (twopass->total_left_stats.inactive_zone_rows * 2) /
3300         ((double)cm->mb_rows * section_length);
3301     const int tmp_q = get_twopass_worst_quality(
3302         cpi, section_error, section_intra_skip + section_inactive_zone,
3303         section_target_bandwidth, DEFAULT_GRP_WEIGHT);
3304 
3305     twopass->active_worst_quality = tmp_q;
3306     twopass->baseline_active_worst_quality = tmp_q;
3307     rc->ni_av_qi = tmp_q;
3308     rc->last_q[INTER_FRAME] = tmp_q;
3309     rc->avg_q = av1_convert_qindex_to_q(tmp_q, cm->seq_params.bit_depth);
3310     rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
3311     rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
3312     rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
3313   }
3314 
3315   av1_zero(this_frame);
3316   if (EOF == input_stats(twopass, &this_frame)) return;
3317 
3318   // Set the frame content type flag.
3319   if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
3320     twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
3321   else
3322     twopass->fr_content_type = FC_NORMAL;
3323 
3324   // Keyframe and section processing.
3325   if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
3326     FIRSTPASS_STATS this_frame_copy;
3327     this_frame_copy = this_frame;
3328     // Define next KF group and assign bits to it.
3329     find_next_key_frame(cpi, &this_frame);
3330     this_frame = this_frame_copy;
3331   } else {
3332     cm->frame_type = INTER_FRAME;
3333   }
3334 
3335   // Define a new GF/ARF group. (Should always enter here for key frames).
3336   if (rc->frames_till_gf_update_due == 0) {
3337     define_gf_group(cpi, &this_frame);
3338 
3339     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3340 
3341 #if ARF_STATS_OUTPUT
3342     {
3343       FILE *fpfile;
3344       fpfile = fopen("arf.stt", "a");
3345       ++arf_count;
3346       fprintf(fpfile, "%10d %10d %10d %10d %10d\n", cm->current_video_frame,
3347               rc->frames_till_gf_update_due, rc->kf_boost, arf_count,
3348               rc->gfu_boost);
3349 
3350       fclose(fpfile);
3351     }
3352 #endif
3353   }
3354 
3355   configure_buffer_updates(cpi);
3356 
3357   // Do the firstpass stats indicate that this frame is skippable for the
3358   // partition search?
3359   if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2) {
3360     cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
3361   }
3362 
3363   target_rate = gf_group->bit_allocation[gf_group->index];
3364 
3365   if (cpi->common.frame_type == KEY_FRAME)
3366     target_rate = av1_rc_clamp_iframe_target_size(cpi, target_rate);
3367   else
3368     target_rate = av1_rc_clamp_pframe_target_size(cpi, target_rate);
3369 
3370   rc->base_frame_target = target_rate;
3371 
3372   {
3373     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
3374                             ? cpi->initial_mbs
3375                             : cpi->common.MBs;
3376     // The multiplication by 256 reverses a scaling factor of (>> 8)
3377     // applied when combining MB error values for the frame.
3378     twopass->mb_av_energy = log((this_frame.intra_error / num_mbs) + 1.0);
3379     twopass->frame_avg_haar_energy =
3380         log((this_frame.frame_avg_wavelet_energy / num_mbs) + 1.0);
3381   }
3382 
3383   // Update the total stats remaining structure.
3384   subtract_stats(&twopass->total_left_stats, &this_frame);
3385 }
3386 
3387 #define MINQ_ADJ_LIMIT 48
3388 #define MINQ_ADJ_LIMIT_CQ 20
3389 #define HIGH_UNDERSHOOT_RATIO 2
3390 void av1_twopass_postencode_update(AV1_COMP *cpi) {
3391   TWO_PASS *const twopass = &cpi->twopass;
3392   RATE_CONTROL *const rc = &cpi->rc;
3393   const int bits_used = rc->base_frame_target;
3394 
3395   // VBR correction is done through rc->vbr_bits_off_target. Based on the
3396   // sign of this value, a limited % adjustment is made to the target rate
3397   // of subsequent frames, to try and push it back towards 0. This method
3398   // is designed to prevent extreme behaviour at the end of a clip
3399   // or group of frames.
3400   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
3401   twopass->bits_left = AOMMAX(twopass->bits_left - bits_used, 0);
3402 
3403   // Calculate the pct rc error.
3404   if (rc->total_actual_bits) {
3405     rc->rate_error_estimate =
3406         (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
3407     rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
3408   } else {
3409     rc->rate_error_estimate = 0;
3410   }
3411 
3412   if (cpi->common.frame_type != KEY_FRAME) {
3413     twopass->kf_group_bits -= bits_used;
3414     twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
3415   }
3416   twopass->kf_group_bits = AOMMAX(twopass->kf_group_bits, 0);
3417 
3418   // If the rate control is drifting consider adjustment to min or maxq.
3419   if ((cpi->oxcf.rc_mode != AOM_Q) &&
3420       (cpi->twopass.gf_zeromotion_pct < VLOW_MOTION_THRESHOLD) &&
3421       !cpi->rc.is_src_frame_alt_ref) {
3422     const int maxq_adj_limit =
3423         rc->worst_quality - twopass->active_worst_quality;
3424     const int minq_adj_limit =
3425         (cpi->oxcf.rc_mode == AOM_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
3426 
3427     // Undershoot.
3428     if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
3429       --twopass->extend_maxq;
3430       if (rc->rolling_target_bits >= rc->rolling_actual_bits)
3431         ++twopass->extend_minq;
3432       // Overshoot.
3433     } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
3434       --twopass->extend_minq;
3435       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3436         ++twopass->extend_maxq;
3437     } else {
3438       // Adjustment for extreme local overshoot.
3439       if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
3440           rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
3441         ++twopass->extend_maxq;
3442 
3443       // Unwind undershoot or overshoot adjustment.
3444       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3445         --twopass->extend_minq;
3446       else if (rc->rolling_target_bits > rc->rolling_actual_bits)
3447         --twopass->extend_maxq;
3448     }
3449 
3450     twopass->extend_minq = clamp(twopass->extend_minq, 0, minq_adj_limit);
3451     twopass->extend_maxq = clamp(twopass->extend_maxq, 0, maxq_adj_limit);
3452 
3453     // If there is a big and undexpected undershoot then feed the extra
3454     // bits back in quickly. One situation where this may happen is if a
3455     // frame is unexpectedly almost perfectly predicted by the ARF or GF
3456     // but not very well predcited by the previous frame.
3457     if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
3458       int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
3459       if (rc->projected_frame_size < fast_extra_thresh) {
3460         rc->vbr_bits_off_target_fast +=
3461             fast_extra_thresh - rc->projected_frame_size;
3462         rc->vbr_bits_off_target_fast =
3463             AOMMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
3464 
3465         // Fast adaptation of minQ if necessary to use up the extra bits.
3466         if (rc->avg_frame_bandwidth) {
3467           twopass->extend_minq_fast =
3468               (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
3469         }
3470         twopass->extend_minq_fast = AOMMIN(
3471             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3472       } else if (rc->vbr_bits_off_target_fast) {
3473         twopass->extend_minq_fast = AOMMIN(
3474             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3475       } else {
3476         twopass->extend_minq_fast = 0;
3477       }
3478     }
3479   }
3480 }
3481