• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include <limits.h>
12 #include <math.h>
13 #include <stdio.h>
14 
15 #include "./vpx_dsp_rtcd.h"
16 #include "./vpx_scale_rtcd.h"
17 
18 #include "vpx_dsp/vpx_dsp_common.h"
19 #include "vpx_mem/vpx_mem.h"
20 #include "vpx_ports/mem.h"
21 #include "vpx_ports/system_state.h"
22 #include "vpx_scale/vpx_scale.h"
23 #include "vpx_scale/yv12config.h"
24 
25 #include "vp9/common/vp9_entropymv.h"
26 #include "vp9/common/vp9_quant_common.h"
27 #include "vp9/common/vp9_reconinter.h"  // vp9_setup_dst_planes()
28 #include "vp9/encoder/vp9_aq_variance.h"
29 #include "vp9/encoder/vp9_block.h"
30 #include "vp9/encoder/vp9_encodeframe.h"
31 #include "vp9/encoder/vp9_encodemb.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_encoder.h"
34 #include "vp9/encoder/vp9_ethread.h"
35 #include "vp9/encoder/vp9_extend.h"
36 #include "vp9/encoder/vp9_firstpass.h"
37 #include "vp9/encoder/vp9_mcomp.h"
38 #include "vp9/encoder/vp9_quantize.h"
39 #include "vp9/encoder/vp9_rd.h"
40 #include "vpx_dsp/variance.h"
41 
42 #define OUTPUT_FPF 0
43 #define ARF_STATS_OUTPUT 0
44 #define COMPLEXITY_STATS_OUTPUT 0
45 
46 #define FIRST_PASS_Q 10.0
47 #define NORMAL_BOOST 100
48 #define MIN_ARF_GF_BOOST 250
49 #define MIN_DECAY_FACTOR 0.01
50 #define NEW_MV_MODE_PENALTY 32
51 #define DARK_THRESH 64
52 #define LOW_I_THRESH 24000
53 
54 #define NCOUNT_INTRA_THRESH 8192
55 #define NCOUNT_INTRA_FACTOR 3
56 
57 #define INTRA_PART 0.005
58 #define DEFAULT_DECAY_LIMIT 0.75
59 #define LOW_SR_DIFF_TRHESH 0.1
60 #define LOW_CODED_ERR_PER_MB 10.0
61 #define NCOUNT_FRAME_II_THRESH 6.0
62 #define BASELINE_ERR_PER_MB 12500.0
63 #define GF_MAX_FRAME_BOOST 96.0
64 
65 #ifdef AGGRESSIVE_VBR
66 #define KF_MIN_FRAME_BOOST 40.0
67 #define KF_MAX_FRAME_BOOST 80.0
68 #define MAX_KF_TOT_BOOST 4800
69 #else
70 #define KF_MIN_FRAME_BOOST 40.0
71 #define KF_MAX_FRAME_BOOST 96.0
72 #define MAX_KF_TOT_BOOST 5400
73 #endif
74 
75 #define DEFAULT_ZM_FACTOR 0.5
76 #define MINQ_ADJ_LIMIT 48
77 #define MINQ_ADJ_LIMIT_CQ 20
78 #define HIGH_UNDERSHOOT_RATIO 2
79 #define AV_WQ_FACTOR 4.0
80 
81 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x)-0.000001 : (x) + 0.000001)
82 
83 #if ARF_STATS_OUTPUT
84 unsigned int arf_count = 0;
85 #endif
86 
87 // Resets the first pass file to the given position using a relative seek from
88 // the current position.
reset_fpf_position(TWO_PASS * p,const FIRSTPASS_STATS * position)89 static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
90   p->stats_in = position;
91 }
92 
93 // Read frame stats at an offset from the current position.
read_frame_stats(const TWO_PASS * p,int offset)94 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
95   if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
96       (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
97     return NULL;
98   }
99 
100   return &p->stats_in[offset];
101 }
102 
input_stats(TWO_PASS * p,FIRSTPASS_STATS * fps)103 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
104   if (p->stats_in >= p->stats_in_end) return EOF;
105 
106   *fps = *p->stats_in;
107   ++p->stats_in;
108   return 1;
109 }
110 
output_stats(FIRSTPASS_STATS * stats)111 static void output_stats(FIRSTPASS_STATS *stats) {
112   (void)stats;
113 // TEMP debug code
114 #if OUTPUT_FPF
115   {
116     FILE *fpfile;
117     fpfile = fopen("firstpass.stt", "a");
118 
119     fprintf(fpfile,
120             "%12.0lf %12.4lf %12.2lf %12.2lf %12.2lf %12.0lf %12.4lf %12.4lf"
121             "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
122             "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.0lf %12.4lf %12.0lf"
123             "%12.4lf"
124             "\n",
125             stats->frame, stats->weight, stats->intra_error, stats->coded_error,
126             stats->sr_coded_error, stats->frame_noise_energy, stats->pcnt_inter,
127             stats->pcnt_motion, stats->pcnt_second_ref, stats->pcnt_neutral,
128             stats->pcnt_intra_low, stats->pcnt_intra_high,
129             stats->intra_skip_pct, stats->intra_smooth_pct,
130             stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
131             stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
132             stats->MVcv, stats->mv_in_out_count, stats->count, stats->duration);
133     fclose(fpfile);
134   }
135 #endif
136 }
137 
zero_stats(FIRSTPASS_STATS * section)138 static void zero_stats(FIRSTPASS_STATS *section) {
139   section->frame = 0.0;
140   section->weight = 0.0;
141   section->intra_error = 0.0;
142   section->coded_error = 0.0;
143   section->sr_coded_error = 0.0;
144   section->frame_noise_energy = 0.0;
145   section->pcnt_inter = 0.0;
146   section->pcnt_motion = 0.0;
147   section->pcnt_second_ref = 0.0;
148   section->pcnt_neutral = 0.0;
149   section->intra_skip_pct = 0.0;
150   section->intra_smooth_pct = 0.0;
151   section->pcnt_intra_low = 0.0;
152   section->pcnt_intra_high = 0.0;
153   section->inactive_zone_rows = 0.0;
154   section->inactive_zone_cols = 0.0;
155   section->MVr = 0.0;
156   section->mvr_abs = 0.0;
157   section->MVc = 0.0;
158   section->mvc_abs = 0.0;
159   section->MVrv = 0.0;
160   section->MVcv = 0.0;
161   section->mv_in_out_count = 0.0;
162   section->count = 0.0;
163   section->duration = 1.0;
164   section->spatial_layer_id = 0;
165 }
166 
accumulate_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)167 static void accumulate_stats(FIRSTPASS_STATS *section,
168                              const FIRSTPASS_STATS *frame) {
169   section->frame += frame->frame;
170   section->weight += frame->weight;
171   section->spatial_layer_id = frame->spatial_layer_id;
172   section->intra_error += frame->intra_error;
173   section->coded_error += frame->coded_error;
174   section->sr_coded_error += frame->sr_coded_error;
175   section->frame_noise_energy += frame->frame_noise_energy;
176   section->pcnt_inter += frame->pcnt_inter;
177   section->pcnt_motion += frame->pcnt_motion;
178   section->pcnt_second_ref += frame->pcnt_second_ref;
179   section->pcnt_neutral += frame->pcnt_neutral;
180   section->intra_skip_pct += frame->intra_skip_pct;
181   section->intra_smooth_pct += frame->intra_smooth_pct;
182   section->pcnt_intra_low += frame->pcnt_intra_low;
183   section->pcnt_intra_high += frame->pcnt_intra_high;
184   section->inactive_zone_rows += frame->inactive_zone_rows;
185   section->inactive_zone_cols += frame->inactive_zone_cols;
186   section->MVr += frame->MVr;
187   section->mvr_abs += frame->mvr_abs;
188   section->MVc += frame->MVc;
189   section->mvc_abs += frame->mvc_abs;
190   section->MVrv += frame->MVrv;
191   section->MVcv += frame->MVcv;
192   section->mv_in_out_count += frame->mv_in_out_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->coded_error -= frame->coded_error;
203   section->sr_coded_error -= frame->sr_coded_error;
204   section->frame_noise_energy -= frame->frame_noise_energy;
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->intra_smooth_pct -= frame->intra_smooth_pct;
211   section->pcnt_intra_low -= frame->pcnt_intra_low;
212   section->pcnt_intra_high -= frame->pcnt_intra_high;
213   section->inactive_zone_rows -= frame->inactive_zone_rows;
214   section->inactive_zone_cols -= frame->inactive_zone_cols;
215   section->MVr -= frame->MVr;
216   section->mvr_abs -= frame->mvr_abs;
217   section->MVc -= frame->MVc;
218   section->mvc_abs -= frame->mvc_abs;
219   section->MVrv -= frame->MVrv;
220   section->MVcv -= frame->MVcv;
221   section->mv_in_out_count -= frame->mv_in_out_count;
222   section->count -= frame->count;
223   section->duration -= frame->duration;
224 }
225 
226 // Calculate an active area of the image that discounts formatting
227 // bars and partially discounts other 0 energy areas.
228 #define MIN_ACTIVE_AREA 0.5
229 #define MAX_ACTIVE_AREA 1.0
calculate_active_area(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame)230 static double calculate_active_area(const FRAME_INFO *frame_info,
231                                     const FIRSTPASS_STATS *this_frame) {
232   double active_pct;
233 
234   active_pct =
235       1.0 -
236       ((this_frame->intra_skip_pct / 2) +
237        ((this_frame->inactive_zone_rows * 2) / (double)frame_info->mb_rows));
238   return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
239 }
240 
241 // Get the average weighted error for the clip (or corpus)
get_distribution_av_err(VP9_COMP * cpi,TWO_PASS * const twopass)242 static double get_distribution_av_err(VP9_COMP *cpi, TWO_PASS *const twopass) {
243   const double av_weight =
244       twopass->total_stats.weight / twopass->total_stats.count;
245 
246   if (cpi->oxcf.vbr_corpus_complexity)
247     return av_weight * twopass->mean_mod_score;
248   else
249     return (twopass->total_stats.coded_error * av_weight) /
250            twopass->total_stats.count;
251 }
252 
253 #define ACT_AREA_CORRECTION 0.5
254 // Calculate a modified Error used in distributing bits between easier and
255 // harder frames.
calculate_mod_frame_score(const VP9_COMP * cpi,const VP9EncoderConfig * oxcf,const FIRSTPASS_STATS * this_frame,const double av_err)256 static double calculate_mod_frame_score(const VP9_COMP *cpi,
257                                         const VP9EncoderConfig *oxcf,
258                                         const FIRSTPASS_STATS *this_frame,
259                                         const double av_err) {
260   double modified_score =
261       av_err * pow(this_frame->coded_error * this_frame->weight /
262                        DOUBLE_DIVIDE_CHECK(av_err),
263                    oxcf->two_pass_vbrbias / 100.0);
264 
265   // Correction for active area. Frames with a reduced active area
266   // (eg due to formatting bars) have a higher error per mb for the
267   // remaining active MBs. The correction here assumes that coding
268   // 0.5N blocks of complexity 2X is a little easier than coding N
269   // blocks of complexity X.
270   modified_score *= pow(calculate_active_area(&cpi->frame_info, this_frame),
271                         ACT_AREA_CORRECTION);
272 
273   return modified_score;
274 }
275 
calc_norm_frame_score(const VP9EncoderConfig * oxcf,const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame,double mean_mod_score,double av_err)276 static double calc_norm_frame_score(const VP9EncoderConfig *oxcf,
277                                     const FRAME_INFO *frame_info,
278                                     const FIRSTPASS_STATS *this_frame,
279                                     double mean_mod_score, double av_err) {
280   double modified_score =
281       av_err * pow(this_frame->coded_error * this_frame->weight /
282                        DOUBLE_DIVIDE_CHECK(av_err),
283                    oxcf->two_pass_vbrbias / 100.0);
284 
285   const double min_score = (double)(oxcf->two_pass_vbrmin_section) / 100.0;
286   const double max_score = (double)(oxcf->two_pass_vbrmax_section) / 100.0;
287 
288   // Correction for active area. Frames with a reduced active area
289   // (eg due to formatting bars) have a higher error per mb for the
290   // remaining active MBs. The correction here assumes that coding
291   // 0.5N blocks of complexity 2X is a little easier than coding N
292   // blocks of complexity X.
293   modified_score *=
294       pow(calculate_active_area(frame_info, this_frame), ACT_AREA_CORRECTION);
295 
296   // Normalize to a midpoint score.
297   modified_score /= DOUBLE_DIVIDE_CHECK(mean_mod_score);
298   return fclamp(modified_score, min_score, max_score);
299 }
300 
calculate_norm_frame_score(const VP9_COMP * cpi,const TWO_PASS * twopass,const VP9EncoderConfig * oxcf,const FIRSTPASS_STATS * this_frame,const double av_err)301 static double calculate_norm_frame_score(const VP9_COMP *cpi,
302                                          const TWO_PASS *twopass,
303                                          const VP9EncoderConfig *oxcf,
304                                          const FIRSTPASS_STATS *this_frame,
305                                          const double av_err) {
306   return calc_norm_frame_score(oxcf, &cpi->frame_info, this_frame,
307                                twopass->mean_mod_score, av_err);
308 }
309 
310 // This function returns the maximum target rate per frame.
frame_max_bits(const RATE_CONTROL * rc,const VP9EncoderConfig * oxcf)311 static int frame_max_bits(const RATE_CONTROL *rc,
312                           const VP9EncoderConfig *oxcf) {
313   int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
314                       (int64_t)oxcf->two_pass_vbrmax_section) /
315                      100;
316   if (max_bits < 0)
317     max_bits = 0;
318   else if (max_bits > rc->max_frame_bandwidth)
319     max_bits = rc->max_frame_bandwidth;
320 
321   return (int)max_bits;
322 }
323 
vp9_init_first_pass(VP9_COMP * cpi)324 void vp9_init_first_pass(VP9_COMP *cpi) {
325   zero_stats(&cpi->twopass.total_stats);
326 }
327 
vp9_end_first_pass(VP9_COMP * cpi)328 void vp9_end_first_pass(VP9_COMP *cpi) {
329   output_stats(&cpi->twopass.total_stats);
330   cpi->twopass.first_pass_done = 1;
331   vpx_free(cpi->twopass.fp_mb_float_stats);
332   cpi->twopass.fp_mb_float_stats = NULL;
333 }
334 
get_block_variance_fn(BLOCK_SIZE bsize)335 static vpx_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
336   switch (bsize) {
337     case BLOCK_8X8: return vpx_mse8x8;
338     case BLOCK_16X8: return vpx_mse16x8;
339     case BLOCK_8X16: return vpx_mse8x16;
340     default: return vpx_mse16x16;
341   }
342 }
343 
get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref)344 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
345                                          const struct buf_2d *src,
346                                          const struct buf_2d *ref) {
347   unsigned int sse;
348   const vpx_variance_fn_t fn = get_block_variance_fn(bsize);
349   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
350   return sse;
351 }
352 
353 #if CONFIG_VP9_HIGHBITDEPTH
highbd_get_block_variance_fn(BLOCK_SIZE bsize,int bd)354 static vpx_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
355                                                       int bd) {
356   switch (bd) {
357     default:
358       switch (bsize) {
359         case BLOCK_8X8: return vpx_highbd_8_mse8x8;
360         case BLOCK_16X8: return vpx_highbd_8_mse16x8;
361         case BLOCK_8X16: return vpx_highbd_8_mse8x16;
362         default: return vpx_highbd_8_mse16x16;
363       }
364       break;
365     case 10:
366       switch (bsize) {
367         case BLOCK_8X8: return vpx_highbd_10_mse8x8;
368         case BLOCK_16X8: return vpx_highbd_10_mse16x8;
369         case BLOCK_8X16: return vpx_highbd_10_mse8x16;
370         default: return vpx_highbd_10_mse16x16;
371       }
372       break;
373     case 12:
374       switch (bsize) {
375         case BLOCK_8X8: return vpx_highbd_12_mse8x8;
376         case BLOCK_16X8: return vpx_highbd_12_mse16x8;
377         case BLOCK_8X16: return vpx_highbd_12_mse8x16;
378         default: return vpx_highbd_12_mse16x16;
379       }
380       break;
381   }
382 }
383 
highbd_get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref,int bd)384 static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
385                                                 const struct buf_2d *src,
386                                                 const struct buf_2d *ref,
387                                                 int bd) {
388   unsigned int sse;
389   const vpx_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
390   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
391   return sse;
392 }
393 #endif  // CONFIG_VP9_HIGHBITDEPTH
394 
395 // Refine the motion search range according to the frame dimension
396 // for first pass test.
get_search_range(const VP9_COMP * cpi)397 static int get_search_range(const VP9_COMP *cpi) {
398   int sr = 0;
399   const int dim = VPXMIN(cpi->initial_width, cpi->initial_height);
400 
401   while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
402   return sr;
403 }
404 
405 // Reduce limits to keep the motion search within MV_MAX of ref_mv. Not doing
406 // this can be problematic for big videos (8K) and may cause assert failure
407 // (or memory violation) in mv_cost. Limits are only modified if they would
408 // be non-empty. Returns 1 if limits are non-empty.
intersect_limits_with_mv_max(MvLimits * mv_limits,const MV * ref_mv)409 static int intersect_limits_with_mv_max(MvLimits *mv_limits, const MV *ref_mv) {
410   const int row_min =
411       VPXMAX(mv_limits->row_min, (ref_mv->row + 7 - MV_MAX) >> 3);
412   const int row_max =
413       VPXMIN(mv_limits->row_max, (ref_mv->row - 1 + MV_MAX) >> 3);
414   const int col_min =
415       VPXMAX(mv_limits->col_min, (ref_mv->col + 7 - MV_MAX) >> 3);
416   const int col_max =
417       VPXMIN(mv_limits->col_max, (ref_mv->col - 1 + MV_MAX) >> 3);
418   if (row_min > row_max || col_min > col_max) {
419     return 0;
420   }
421   mv_limits->row_min = row_min;
422   mv_limits->row_max = row_max;
423   mv_limits->col_min = col_min;
424   mv_limits->col_max = col_max;
425   return 1;
426 }
427 
first_pass_motion_search(VP9_COMP * cpi,MACROBLOCK * x,const MV * ref_mv,MV * best_mv,int * best_motion_err)428 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
429                                      const MV *ref_mv, MV *best_mv,
430                                      int *best_motion_err) {
431   MACROBLOCKD *const xd = &x->e_mbd;
432   MV tmp_mv = { 0, 0 };
433   MV ref_mv_full = { ref_mv->row >> 3, ref_mv->col >> 3 };
434   int num00, tmp_err, n;
435   const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
436   vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
437   const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
438 
439   int step_param = 3;
440   int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
441   const int sr = get_search_range(cpi);
442   const MvLimits tmp_mv_limits = x->mv_limits;
443   step_param += sr;
444   further_steps -= sr;
445 
446   if (!intersect_limits_with_mv_max(&x->mv_limits, ref_mv)) {
447     return;
448   }
449 
450   // Override the default variance function to use MSE.
451   v_fn_ptr.vf = get_block_variance_fn(bsize);
452 #if CONFIG_VP9_HIGHBITDEPTH
453   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
454     v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
455   }
456 #endif  // CONFIG_VP9_HIGHBITDEPTH
457 
458   // Center the initial step/diamond search on best mv.
459   tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
460                                     step_param, x->sadperbit16, &num00,
461                                     &v_fn_ptr, ref_mv);
462   if (tmp_err < INT_MAX)
463     tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
464   if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
465 
466   if (tmp_err < *best_motion_err) {
467     *best_motion_err = tmp_err;
468     *best_mv = tmp_mv;
469   }
470 
471   // Carry out further step/diamond searches as necessary.
472   n = num00;
473   num00 = 0;
474 
475   while (n < further_steps) {
476     ++n;
477 
478     if (num00) {
479       --num00;
480     } else {
481       tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
482                                         step_param + n, x->sadperbit16, &num00,
483                                         &v_fn_ptr, ref_mv);
484       if (tmp_err < INT_MAX)
485         tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
486       if (tmp_err < INT_MAX - new_mv_mode_penalty)
487         tmp_err += new_mv_mode_penalty;
488 
489       if (tmp_err < *best_motion_err) {
490         *best_motion_err = tmp_err;
491         *best_mv = tmp_mv;
492       }
493     }
494   }
495   x->mv_limits = tmp_mv_limits;
496 }
497 
get_bsize(const VP9_COMMON * cm,int mb_row,int mb_col)498 static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
499   if (2 * mb_col + 1 < cm->mi_cols) {
500     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16 : BLOCK_16X8;
501   } else {
502     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16 : BLOCK_8X8;
503   }
504 }
505 
find_fp_qindex(vpx_bit_depth_t bit_depth)506 static int find_fp_qindex(vpx_bit_depth_t bit_depth) {
507   int i;
508 
509   for (i = 0; i < QINDEX_RANGE; ++i)
510     if (vp9_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q) break;
511 
512   if (i == QINDEX_RANGE) i--;
513 
514   return i;
515 }
516 
set_first_pass_params(VP9_COMP * cpi)517 static void set_first_pass_params(VP9_COMP *cpi) {
518   VP9_COMMON *const cm = &cpi->common;
519   if (!cpi->refresh_alt_ref_frame &&
520       (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY))) {
521     cm->frame_type = KEY_FRAME;
522   } else {
523     cm->frame_type = INTER_FRAME;
524   }
525   // Do not use periodic key frames.
526   cpi->rc.frames_to_key = INT_MAX;
527 }
528 
529 // Scale an sse threshold to account for 8/10/12 bit.
scale_sse_threshold(VP9_COMMON * cm,int thresh)530 static int scale_sse_threshold(VP9_COMMON *cm, int thresh) {
531   int ret_val = thresh;
532 #if CONFIG_VP9_HIGHBITDEPTH
533   if (cm->use_highbitdepth) {
534     switch (cm->bit_depth) {
535       case VPX_BITS_8: ret_val = thresh; break;
536       case VPX_BITS_10: ret_val = thresh << 4; break;
537       default:
538         assert(cm->bit_depth == VPX_BITS_12);
539         ret_val = thresh << 8;
540         break;
541     }
542   }
543 #else
544   (void)cm;
545 #endif  // CONFIG_VP9_HIGHBITDEPTH
546   return ret_val;
547 }
548 
549 // This threshold is used to track blocks where to all intents and purposes
550 // the intra prediction error 0. Though the metric we test against
551 // is technically a sse we are mainly interested in blocks where all the pixels
552 // in the 8 bit domain have an error of <= 1 (where error = sse) so a
553 // linear scaling for 10 and 12 bit gives similar results.
554 #define UL_INTRA_THRESH 50
get_ul_intra_threshold(VP9_COMMON * cm)555 static int get_ul_intra_threshold(VP9_COMMON *cm) {
556   int ret_val = UL_INTRA_THRESH;
557 #if CONFIG_VP9_HIGHBITDEPTH
558   if (cm->use_highbitdepth) {
559     switch (cm->bit_depth) {
560       case VPX_BITS_8: ret_val = UL_INTRA_THRESH; break;
561       case VPX_BITS_10: ret_val = UL_INTRA_THRESH << 2; break;
562       default:
563         assert(cm->bit_depth == VPX_BITS_12);
564         ret_val = UL_INTRA_THRESH << 4;
565         break;
566     }
567   }
568 #else
569   (void)cm;
570 #endif  // CONFIG_VP9_HIGHBITDEPTH
571   return ret_val;
572 }
573 
574 #define SMOOTH_INTRA_THRESH 4000
get_smooth_intra_threshold(VP9_COMMON * cm)575 static int get_smooth_intra_threshold(VP9_COMMON *cm) {
576   int ret_val = SMOOTH_INTRA_THRESH;
577 #if CONFIG_VP9_HIGHBITDEPTH
578   if (cm->use_highbitdepth) {
579     switch (cm->bit_depth) {
580       case VPX_BITS_8: ret_val = SMOOTH_INTRA_THRESH; break;
581       case VPX_BITS_10: ret_val = SMOOTH_INTRA_THRESH << 4; break;
582       default:
583         assert(cm->bit_depth == VPX_BITS_12);
584         ret_val = SMOOTH_INTRA_THRESH << 8;
585         break;
586     }
587   }
588 #else
589   (void)cm;
590 #endif  // CONFIG_VP9_HIGHBITDEPTH
591   return ret_val;
592 }
593 
594 #define FP_DN_THRESH 8
595 #define FP_MAX_DN_THRESH 24
596 #define KERNEL_SIZE 3
597 
598 // Baseline Kernal weights for first pass noise metric
599 static uint8_t fp_dn_kernal_3[KERNEL_SIZE * KERNEL_SIZE] = { 1, 2, 1, 2, 4,
600                                                              2, 1, 2, 1 };
601 
602 // Estimate noise at a single point based on the impace of a spatial kernal
603 // on the point value
fp_estimate_point_noise(uint8_t * src_ptr,const int stride)604 static int fp_estimate_point_noise(uint8_t *src_ptr, const int stride) {
605   int sum_weight = 0;
606   int sum_val = 0;
607   int i, j;
608   int max_diff = 0;
609   int diff;
610   int dn_diff;
611   uint8_t *tmp_ptr;
612   uint8_t *kernal_ptr;
613   uint8_t dn_val;
614   uint8_t centre_val = *src_ptr;
615 
616   kernal_ptr = fp_dn_kernal_3;
617 
618   // Apply the kernal
619   tmp_ptr = src_ptr - stride - 1;
620   for (i = 0; i < KERNEL_SIZE; ++i) {
621     for (j = 0; j < KERNEL_SIZE; ++j) {
622       diff = abs((int)centre_val - (int)tmp_ptr[j]);
623       max_diff = VPXMAX(max_diff, diff);
624       if (diff <= FP_DN_THRESH) {
625         sum_weight += *kernal_ptr;
626         sum_val += (int)tmp_ptr[j] * (int)*kernal_ptr;
627       }
628       ++kernal_ptr;
629     }
630     tmp_ptr += stride;
631   }
632 
633   if (max_diff < FP_MAX_DN_THRESH)
634     // Update the source value with the new filtered value
635     dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
636   else
637     dn_val = *src_ptr;
638 
639   // return the noise energy as the square of the difference between the
640   // denoised and raw value.
641   dn_diff = (int)*src_ptr - (int)dn_val;
642   return dn_diff * dn_diff;
643 }
644 #if CONFIG_VP9_HIGHBITDEPTH
fp_highbd_estimate_point_noise(uint8_t * src_ptr,const int stride)645 static int fp_highbd_estimate_point_noise(uint8_t *src_ptr, const int stride) {
646   int sum_weight = 0;
647   int sum_val = 0;
648   int i, j;
649   int max_diff = 0;
650   int diff;
651   int dn_diff;
652   uint8_t *tmp_ptr;
653   uint16_t *tmp_ptr16;
654   uint8_t *kernal_ptr;
655   uint16_t dn_val;
656   uint16_t centre_val = *CONVERT_TO_SHORTPTR(src_ptr);
657 
658   kernal_ptr = fp_dn_kernal_3;
659 
660   // Apply the kernal
661   tmp_ptr = src_ptr - stride - 1;
662   for (i = 0; i < KERNEL_SIZE; ++i) {
663     tmp_ptr16 = CONVERT_TO_SHORTPTR(tmp_ptr);
664     for (j = 0; j < KERNEL_SIZE; ++j) {
665       diff = abs((int)centre_val - (int)tmp_ptr16[j]);
666       max_diff = VPXMAX(max_diff, diff);
667       if (diff <= FP_DN_THRESH) {
668         sum_weight += *kernal_ptr;
669         sum_val += (int)tmp_ptr16[j] * (int)*kernal_ptr;
670       }
671       ++kernal_ptr;
672     }
673     tmp_ptr += stride;
674   }
675 
676   if (max_diff < FP_MAX_DN_THRESH)
677     // Update the source value with the new filtered value
678     dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
679   else
680     dn_val = *CONVERT_TO_SHORTPTR(src_ptr);
681 
682   // return the noise energy as the square of the difference between the
683   // denoised and raw value.
684   dn_diff = (int)(*CONVERT_TO_SHORTPTR(src_ptr)) - (int)dn_val;
685   return dn_diff * dn_diff;
686 }
687 #endif
688 
689 // Estimate noise for a block.
fp_estimate_block_noise(MACROBLOCK * x,BLOCK_SIZE bsize)690 static int fp_estimate_block_noise(MACROBLOCK *x, BLOCK_SIZE bsize) {
691 #if CONFIG_VP9_HIGHBITDEPTH
692   MACROBLOCKD *xd = &x->e_mbd;
693 #endif
694   uint8_t *src_ptr = &x->plane[0].src.buf[0];
695   const int width = num_4x4_blocks_wide_lookup[bsize] * 4;
696   const int height = num_4x4_blocks_high_lookup[bsize] * 4;
697   int w, h;
698   int stride = x->plane[0].src.stride;
699   int block_noise = 0;
700 
701   // Sampled points to reduce cost overhead.
702   for (h = 0; h < height; h += 2) {
703     for (w = 0; w < width; w += 2) {
704 #if CONFIG_VP9_HIGHBITDEPTH
705       if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
706         block_noise += fp_highbd_estimate_point_noise(src_ptr, stride);
707       else
708         block_noise += fp_estimate_point_noise(src_ptr, stride);
709 #else
710       block_noise += fp_estimate_point_noise(src_ptr, stride);
711 #endif
712       ++src_ptr;
713     }
714     src_ptr += (stride - width);
715   }
716   return block_noise << 2;  // Scale << 2 to account for sampling.
717 }
718 
719 // This function is called to test the functionality of row based
720 // multi-threading in unit tests for bit-exactness
accumulate_floating_point_stats(VP9_COMP * cpi,TileDataEnc * first_tile_col)721 static void accumulate_floating_point_stats(VP9_COMP *cpi,
722                                             TileDataEnc *first_tile_col) {
723   VP9_COMMON *const cm = &cpi->common;
724   int mb_row, mb_col;
725   first_tile_col->fp_data.intra_factor = 0;
726   first_tile_col->fp_data.brightness_factor = 0;
727   first_tile_col->fp_data.neutral_count = 0;
728   for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
729     for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
730       const int mb_index = mb_row * cm->mb_cols + mb_col;
731       first_tile_col->fp_data.intra_factor +=
732           cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor;
733       first_tile_col->fp_data.brightness_factor +=
734           cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor;
735       first_tile_col->fp_data.neutral_count +=
736           cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count;
737     }
738   }
739 }
740 
first_pass_stat_calc(VP9_COMP * cpi,FIRSTPASS_STATS * fps,FIRSTPASS_DATA * fp_acc_data)741 static void first_pass_stat_calc(VP9_COMP *cpi, FIRSTPASS_STATS *fps,
742                                  FIRSTPASS_DATA *fp_acc_data) {
743   VP9_COMMON *const cm = &cpi->common;
744   // The minimum error here insures some bit allocation to frames even
745   // in static regions. The allocation per MB declines for larger formats
746   // where the typical "real" energy per MB also falls.
747   // Initial estimate here uses sqrt(mbs) to define the min_err, where the
748   // number of mbs is proportional to the image area.
749   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
750                                                              : cpi->common.MBs;
751   const double min_err = 200 * sqrt(num_mbs);
752 
753   // Clamp the image start to rows/2. This number of rows is discarded top
754   // and bottom as dead data so rows / 2 means the frame is blank.
755   if ((fp_acc_data->image_data_start_row > cm->mb_rows / 2) ||
756       (fp_acc_data->image_data_start_row == INVALID_ROW)) {
757     fp_acc_data->image_data_start_row = cm->mb_rows / 2;
758   }
759   // Exclude any image dead zone
760   if (fp_acc_data->image_data_start_row > 0) {
761     fp_acc_data->intra_skip_count =
762         VPXMAX(0, fp_acc_data->intra_skip_count -
763                       (fp_acc_data->image_data_start_row * cm->mb_cols * 2));
764   }
765 
766   fp_acc_data->intra_factor = fp_acc_data->intra_factor / (double)num_mbs;
767   fp_acc_data->brightness_factor =
768       fp_acc_data->brightness_factor / (double)num_mbs;
769   fps->weight = fp_acc_data->intra_factor * fp_acc_data->brightness_factor;
770 
771   fps->frame = cm->current_video_frame;
772   fps->spatial_layer_id = cpi->svc.spatial_layer_id;
773 
774   fps->coded_error =
775       ((double)(fp_acc_data->coded_error >> 8) + min_err) / num_mbs;
776   fps->sr_coded_error =
777       ((double)(fp_acc_data->sr_coded_error >> 8) + min_err) / num_mbs;
778   fps->intra_error =
779       ((double)(fp_acc_data->intra_error >> 8) + min_err) / num_mbs;
780 
781   fps->frame_noise_energy =
782       (double)(fp_acc_data->frame_noise_energy) / (double)num_mbs;
783   fps->count = 1.0;
784   fps->pcnt_inter = (double)(fp_acc_data->intercount) / num_mbs;
785   fps->pcnt_second_ref = (double)(fp_acc_data->second_ref_count) / num_mbs;
786   fps->pcnt_neutral = (double)(fp_acc_data->neutral_count) / num_mbs;
787   fps->pcnt_intra_low = (double)(fp_acc_data->intra_count_low) / num_mbs;
788   fps->pcnt_intra_high = (double)(fp_acc_data->intra_count_high) / num_mbs;
789   fps->intra_skip_pct = (double)(fp_acc_data->intra_skip_count) / num_mbs;
790   fps->intra_smooth_pct = (double)(fp_acc_data->intra_smooth_count) / num_mbs;
791   fps->inactive_zone_rows = (double)(fp_acc_data->image_data_start_row);
792   // Currently set to 0 as most issues relate to letter boxing.
793   fps->inactive_zone_cols = (double)0;
794 
795   if (fp_acc_data->mvcount > 0) {
796     fps->MVr = (double)(fp_acc_data->sum_mvr) / fp_acc_data->mvcount;
797     fps->mvr_abs = (double)(fp_acc_data->sum_mvr_abs) / fp_acc_data->mvcount;
798     fps->MVc = (double)(fp_acc_data->sum_mvc) / fp_acc_data->mvcount;
799     fps->mvc_abs = (double)(fp_acc_data->sum_mvc_abs) / fp_acc_data->mvcount;
800     fps->MVrv = ((double)(fp_acc_data->sum_mvrs) -
801                  ((double)(fp_acc_data->sum_mvr) * (fp_acc_data->sum_mvr) /
802                   fp_acc_data->mvcount)) /
803                 fp_acc_data->mvcount;
804     fps->MVcv = ((double)(fp_acc_data->sum_mvcs) -
805                  ((double)(fp_acc_data->sum_mvc) * (fp_acc_data->sum_mvc) /
806                   fp_acc_data->mvcount)) /
807                 fp_acc_data->mvcount;
808     fps->mv_in_out_count =
809         (double)(fp_acc_data->sum_in_vectors) / (fp_acc_data->mvcount * 2);
810     fps->pcnt_motion = (double)(fp_acc_data->mvcount) / num_mbs;
811   } else {
812     fps->MVr = 0.0;
813     fps->mvr_abs = 0.0;
814     fps->MVc = 0.0;
815     fps->mvc_abs = 0.0;
816     fps->MVrv = 0.0;
817     fps->MVcv = 0.0;
818     fps->mv_in_out_count = 0.0;
819     fps->pcnt_motion = 0.0;
820   }
821 }
822 
accumulate_fp_mb_row_stat(TileDataEnc * this_tile,FIRSTPASS_DATA * fp_acc_data)823 static void accumulate_fp_mb_row_stat(TileDataEnc *this_tile,
824                                       FIRSTPASS_DATA *fp_acc_data) {
825   this_tile->fp_data.intra_factor += fp_acc_data->intra_factor;
826   this_tile->fp_data.brightness_factor += fp_acc_data->brightness_factor;
827   this_tile->fp_data.coded_error += fp_acc_data->coded_error;
828   this_tile->fp_data.sr_coded_error += fp_acc_data->sr_coded_error;
829   this_tile->fp_data.frame_noise_energy += fp_acc_data->frame_noise_energy;
830   this_tile->fp_data.intra_error += fp_acc_data->intra_error;
831   this_tile->fp_data.intercount += fp_acc_data->intercount;
832   this_tile->fp_data.second_ref_count += fp_acc_data->second_ref_count;
833   this_tile->fp_data.neutral_count += fp_acc_data->neutral_count;
834   this_tile->fp_data.intra_count_low += fp_acc_data->intra_count_low;
835   this_tile->fp_data.intra_count_high += fp_acc_data->intra_count_high;
836   this_tile->fp_data.intra_skip_count += fp_acc_data->intra_skip_count;
837   this_tile->fp_data.mvcount += fp_acc_data->mvcount;
838   this_tile->fp_data.sum_mvr += fp_acc_data->sum_mvr;
839   this_tile->fp_data.sum_mvr_abs += fp_acc_data->sum_mvr_abs;
840   this_tile->fp_data.sum_mvc += fp_acc_data->sum_mvc;
841   this_tile->fp_data.sum_mvc_abs += fp_acc_data->sum_mvc_abs;
842   this_tile->fp_data.sum_mvrs += fp_acc_data->sum_mvrs;
843   this_tile->fp_data.sum_mvcs += fp_acc_data->sum_mvcs;
844   this_tile->fp_data.sum_in_vectors += fp_acc_data->sum_in_vectors;
845   this_tile->fp_data.intra_smooth_count += fp_acc_data->intra_smooth_count;
846   this_tile->fp_data.image_data_start_row =
847       VPXMIN(this_tile->fp_data.image_data_start_row,
848              fp_acc_data->image_data_start_row) == INVALID_ROW
849           ? VPXMAX(this_tile->fp_data.image_data_start_row,
850                    fp_acc_data->image_data_start_row)
851           : VPXMIN(this_tile->fp_data.image_data_start_row,
852                    fp_acc_data->image_data_start_row);
853 }
854 
855 #if CONFIG_RATE_CTRL
store_fp_motion_vector(VP9_COMP * cpi,const MV * mv,const int mb_row,const int mb_col,MV_REFERENCE_FRAME frame_type,const int mv_idx)856 static void store_fp_motion_vector(VP9_COMP *cpi, const MV *mv,
857                                    const int mb_row, const int mb_col,
858                                    MV_REFERENCE_FRAME frame_type,
859                                    const int mv_idx) {
860   VP9_COMMON *const cm = &cpi->common;
861   const int mb_index = mb_row * cm->mb_cols + mb_col;
862   MOTION_VECTOR_INFO *this_motion_vector_info =
863       &cpi->fp_motion_vector_info[mb_index];
864   this_motion_vector_info->ref_frame[mv_idx] = frame_type;
865   if (frame_type != INTRA_FRAME) {
866     this_motion_vector_info->mv[mv_idx].as_mv = *mv;
867   }
868 }
869 #endif  // CONFIG_RATE_CTRL
870 
871 #define NZ_MOTION_PENALTY 128
872 #define INTRA_MODE_PENALTY 1024
vp9_first_pass_encode_tile_mb_row(VP9_COMP * cpi,ThreadData * td,FIRSTPASS_DATA * fp_acc_data,TileDataEnc * tile_data,MV * best_ref_mv,int mb_row)873 void vp9_first_pass_encode_tile_mb_row(VP9_COMP *cpi, ThreadData *td,
874                                        FIRSTPASS_DATA *fp_acc_data,
875                                        TileDataEnc *tile_data, MV *best_ref_mv,
876                                        int mb_row) {
877   int mb_col;
878   MACROBLOCK *const x = &td->mb;
879   VP9_COMMON *const cm = &cpi->common;
880   MACROBLOCKD *const xd = &x->e_mbd;
881   TileInfo tile = tile_data->tile_info;
882   const int mb_col_start = ROUND_POWER_OF_TWO(tile.mi_col_start, 1);
883   const int mb_col_end = ROUND_POWER_OF_TWO(tile.mi_col_end, 1);
884   struct macroblock_plane *const p = x->plane;
885   struct macroblockd_plane *const pd = xd->plane;
886   const PICK_MODE_CONTEXT *ctx = &td->pc_root->none;
887   int i, c;
888   int num_mb_cols = get_num_cols(tile_data->tile_info, 1);
889 
890   int recon_yoffset, recon_uvoffset;
891   const int intrapenalty = INTRA_MODE_PENALTY;
892   const MV zero_mv = { 0, 0 };
893   int recon_y_stride, recon_uv_stride, uv_mb_height;
894 
895   YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
896   YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
897   YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
898   const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
899 
900   MODE_INFO mi_above, mi_left;
901 
902   double mb_intra_factor;
903   double mb_brightness_factor;
904   double mb_neutral_count;
905   int scaled_low_intra_thresh = scale_sse_threshold(cm, LOW_I_THRESH);
906 
907   // First pass code requires valid last and new frame buffers.
908   assert(new_yv12 != NULL);
909   assert(frame_is_intra_only(cm) || (lst_yv12 != NULL));
910 
911   xd->mi = cm->mi_grid_visible + xd->mi_stride * (mb_row << 1) + mb_col_start;
912   xd->mi[0] = cm->mi + xd->mi_stride * (mb_row << 1) + mb_col_start;
913 
914   for (i = 0; i < MAX_MB_PLANE; ++i) {
915     p[i].coeff = ctx->coeff_pbuf[i][1];
916     p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
917     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
918     p[i].eobs = ctx->eobs_pbuf[i][1];
919   }
920 
921   recon_y_stride = new_yv12->y_stride;
922   recon_uv_stride = new_yv12->uv_stride;
923   uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
924 
925   // Reset above block coeffs.
926   recon_yoffset = (mb_row * recon_y_stride * 16) + mb_col_start * 16;
927   recon_uvoffset =
928       (mb_row * recon_uv_stride * uv_mb_height) + mb_col_start * uv_mb_height;
929 
930   // Set up limit values for motion vectors to prevent them extending
931   // outside the UMV borders.
932   x->mv_limits.row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
933   x->mv_limits.row_max =
934       ((cm->mb_rows - 1 - mb_row) * 16) + BORDER_MV_PIXELS_B16;
935 
936   for (mb_col = mb_col_start, c = 0; mb_col < mb_col_end; ++mb_col, c++) {
937     int this_error;
938     int this_intra_error;
939     const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
940     const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
941     double log_intra;
942     int level_sample;
943     const int mb_index = mb_row * cm->mb_cols + mb_col;
944 
945     (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, mb_row, c);
946 
947     // Adjust to the next column of MBs.
948     x->plane[0].src.buf = cpi->Source->y_buffer +
949                           mb_row * 16 * x->plane[0].src.stride + mb_col * 16;
950     x->plane[1].src.buf = cpi->Source->u_buffer +
951                           mb_row * uv_mb_height * x->plane[1].src.stride +
952                           mb_col * uv_mb_height;
953     x->plane[2].src.buf = cpi->Source->v_buffer +
954                           mb_row * uv_mb_height * x->plane[1].src.stride +
955                           mb_col * uv_mb_height;
956 
957     vpx_clear_system_state();
958 
959     xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
960     xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
961     xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
962     xd->mi[0]->sb_type = bsize;
963     xd->mi[0]->ref_frame[0] = INTRA_FRAME;
964     set_mi_row_col(xd, &tile, mb_row << 1, num_8x8_blocks_high_lookup[bsize],
965                    mb_col << 1, num_8x8_blocks_wide_lookup[bsize], cm->mi_rows,
966                    cm->mi_cols);
967     // Are edges available for intra prediction?
968     // Since the firstpass does not populate the mi_grid_visible,
969     // above_mi/left_mi must be overwritten with a nonzero value when edges
970     // are available.  Required by vp9_predict_intra_block().
971     xd->above_mi = (mb_row != 0) ? &mi_above : NULL;
972     xd->left_mi = ((mb_col << 1) > tile.mi_col_start) ? &mi_left : NULL;
973 
974     // Do intra 16x16 prediction.
975     x->skip_encode = 0;
976     x->fp_src_pred = 0;
977     // Do intra prediction based on source pixels for tile boundaries
978     if (mb_col == mb_col_start && mb_col != 0) {
979       xd->left_mi = &mi_left;
980       x->fp_src_pred = 1;
981     }
982     xd->mi[0]->mode = DC_PRED;
983     xd->mi[0]->tx_size =
984         use_dc_pred ? (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
985     // Fix - zero the 16x16 block first. This ensures correct this_error for
986     // block sizes smaller than 16x16.
987     vp9_zero_array(x->plane[0].src_diff, 256);
988     vp9_encode_intra_block_plane(x, bsize, 0, 0);
989     this_error = vpx_get_mb_ss(x->plane[0].src_diff);
990     this_intra_error = this_error;
991 
992     // Keep a record of blocks that have very low intra error residual
993     // (i.e. are in effect completely flat and untextured in the intra
994     // domain). In natural videos this is uncommon, but it is much more
995     // common in animations, graphics and screen content, so may be used
996     // as a signal to detect these types of content.
997     if (this_error < get_ul_intra_threshold(cm)) {
998       ++(fp_acc_data->intra_skip_count);
999     } else if ((mb_col > 0) &&
1000                (fp_acc_data->image_data_start_row == INVALID_ROW)) {
1001       fp_acc_data->image_data_start_row = mb_row;
1002     }
1003 
1004     // Blocks that are mainly smooth in the intra domain.
1005     // Some special accounting for CQ but also these are better for testing
1006     // noise levels.
1007     if (this_error < get_smooth_intra_threshold(cm)) {
1008       ++(fp_acc_data->intra_smooth_count);
1009     }
1010 
1011     // Special case noise measurement for first frame.
1012     if (cm->current_video_frame == 0) {
1013       if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
1014         fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1015       } else {
1016         fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1017       }
1018     }
1019 
1020 #if CONFIG_VP9_HIGHBITDEPTH
1021     if (cm->use_highbitdepth) {
1022       switch (cm->bit_depth) {
1023         case VPX_BITS_8: break;
1024         case VPX_BITS_10: this_error >>= 4; break;
1025         default:
1026           assert(cm->bit_depth == VPX_BITS_12);
1027           this_error >>= 8;
1028           break;
1029       }
1030     }
1031 #endif  // CONFIG_VP9_HIGHBITDEPTH
1032 
1033     vpx_clear_system_state();
1034     log_intra = log(this_error + 1.0);
1035     if (log_intra < 10.0) {
1036       mb_intra_factor = 1.0 + ((10.0 - log_intra) * 0.05);
1037       fp_acc_data->intra_factor += mb_intra_factor;
1038       if (cpi->row_mt_bit_exact)
1039         cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor =
1040             mb_intra_factor;
1041     } else {
1042       fp_acc_data->intra_factor += 1.0;
1043       if (cpi->row_mt_bit_exact)
1044         cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor = 1.0;
1045     }
1046 
1047 #if CONFIG_VP9_HIGHBITDEPTH
1048     if (cm->use_highbitdepth)
1049       level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
1050     else
1051       level_sample = x->plane[0].src.buf[0];
1052 #else
1053     level_sample = x->plane[0].src.buf[0];
1054 #endif
1055     if ((level_sample < DARK_THRESH) && (log_intra < 9.0)) {
1056       mb_brightness_factor = 1.0 + (0.01 * (DARK_THRESH - level_sample));
1057       fp_acc_data->brightness_factor += mb_brightness_factor;
1058       if (cpi->row_mt_bit_exact)
1059         cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor =
1060             mb_brightness_factor;
1061     } else {
1062       fp_acc_data->brightness_factor += 1.0;
1063       if (cpi->row_mt_bit_exact)
1064         cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor =
1065             1.0;
1066     }
1067 
1068     // Intrapenalty below deals with situations where the intra and inter
1069     // error scores are very low (e.g. a plain black frame).
1070     // We do not have special cases in first pass for 0,0 and nearest etc so
1071     // all inter modes carry an overhead cost estimate for the mv.
1072     // When the error score is very low this causes us to pick all or lots of
1073     // INTRA modes and throw lots of key frames.
1074     // This penalty adds a cost matching that of a 0,0 mv to the intra case.
1075     this_error += intrapenalty;
1076 
1077     // Accumulate the intra error.
1078     fp_acc_data->intra_error += (int64_t)this_error;
1079 
1080     // Set up limit values for motion vectors to prevent them extending
1081     // outside the UMV borders.
1082     x->mv_limits.col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
1083     x->mv_limits.col_max =
1084         ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
1085 
1086     // Other than for intra-only frame do a motion search.
1087     if (!frame_is_intra_only(cm)) {
1088       int tmp_err, motion_error, this_motion_error, raw_motion_error;
1089       // Assume 0,0 motion with no mv overhead.
1090       MV mv = { 0, 0 }, tmp_mv = { 0, 0 };
1091       struct buf_2d unscaled_last_source_buf_2d;
1092       vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
1093 
1094 #if CONFIG_RATE_CTRL
1095       if (cpi->oxcf.use_simple_encode_api) {
1096         // Store zero mv as default
1097         store_fp_motion_vector(cpi, &mv, mb_row, mb_col, LAST_FRAME, 0);
1098       }
1099 #endif  // CONFIG_RAGE_CTRL
1100 
1101       xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
1102 #if CONFIG_VP9_HIGHBITDEPTH
1103       if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1104         motion_error = highbd_get_prediction_error(
1105             bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
1106         this_motion_error = highbd_get_prediction_error(
1107             bsize, &x->plane[0].src, &xd->plane[0].pre[0], 8);
1108       } else {
1109         motion_error =
1110             get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
1111         this_motion_error = motion_error;
1112       }
1113 #else
1114       motion_error =
1115           get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
1116       this_motion_error = motion_error;
1117 #endif  // CONFIG_VP9_HIGHBITDEPTH
1118 
1119       // Compute the motion error of the 0,0 motion using the last source
1120       // frame as the reference. Skip the further motion search on
1121       // reconstructed frame if this error is very small.
1122       unscaled_last_source_buf_2d.buf =
1123           cpi->unscaled_last_source->y_buffer + recon_yoffset;
1124       unscaled_last_source_buf_2d.stride = cpi->unscaled_last_source->y_stride;
1125 #if CONFIG_VP9_HIGHBITDEPTH
1126       if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1127         raw_motion_error = highbd_get_prediction_error(
1128             bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
1129       } else {
1130         raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1131                                                 &unscaled_last_source_buf_2d);
1132       }
1133 #else
1134       raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1135                                               &unscaled_last_source_buf_2d);
1136 #endif  // CONFIG_VP9_HIGHBITDEPTH
1137 
1138       if (raw_motion_error > NZ_MOTION_PENALTY) {
1139         // Test last reference frame using the previous best mv as the
1140         // starting point (best reference) for the search.
1141         first_pass_motion_search(cpi, x, best_ref_mv, &mv, &motion_error);
1142 
1143         v_fn_ptr.vf = get_block_variance_fn(bsize);
1144 #if CONFIG_VP9_HIGHBITDEPTH
1145         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1146           v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, 8);
1147         }
1148 #endif  // CONFIG_VP9_HIGHBITDEPTH
1149         this_motion_error =
1150             vp9_get_mvpred_var(x, &mv, best_ref_mv, &v_fn_ptr, 0);
1151 
1152         // If the current best reference mv is not centered on 0,0 then do a
1153         // 0,0 based search as well.
1154         if (!is_zero_mv(best_ref_mv)) {
1155           tmp_err = INT_MAX;
1156           first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &tmp_err);
1157 
1158           if (tmp_err < motion_error) {
1159             motion_error = tmp_err;
1160             mv = tmp_mv;
1161             this_motion_error =
1162                 vp9_get_mvpred_var(x, &tmp_mv, &zero_mv, &v_fn_ptr, 0);
1163           }
1164         }
1165 #if CONFIG_RATE_CTRL
1166         if (cpi->oxcf.use_simple_encode_api) {
1167           store_fp_motion_vector(cpi, &mv, mb_row, mb_col, LAST_FRAME, 0);
1168         }
1169 #endif  // CONFIG_RAGE_CTRL
1170 
1171         // Search in an older reference frame.
1172         if ((cm->current_video_frame > 1) && gld_yv12 != NULL) {
1173           // Assume 0,0 motion with no mv overhead.
1174           int gf_motion_error;
1175 
1176           xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
1177 #if CONFIG_VP9_HIGHBITDEPTH
1178           if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1179             gf_motion_error = highbd_get_prediction_error(
1180                 bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
1181           } else {
1182             gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1183                                                    &xd->plane[0].pre[0]);
1184           }
1185 #else
1186           gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1187                                                  &xd->plane[0].pre[0]);
1188 #endif  // CONFIG_VP9_HIGHBITDEPTH
1189 
1190           first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &gf_motion_error);
1191 #if CONFIG_RATE_CTRL
1192           if (cpi->oxcf.use_simple_encode_api) {
1193             store_fp_motion_vector(cpi, &tmp_mv, mb_row, mb_col, GOLDEN_FRAME,
1194                                    1);
1195           }
1196 #endif  // CONFIG_RAGE_CTRL
1197 
1198           if (gf_motion_error < motion_error && gf_motion_error < this_error)
1199             ++(fp_acc_data->second_ref_count);
1200 
1201           // Reset to last frame as reference buffer.
1202           xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
1203           xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
1204           xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
1205 
1206           // In accumulating a score for the older reference frame take the
1207           // best of the motion predicted score and the intra coded error
1208           // (just as will be done for) accumulation of "coded_error" for
1209           // the last frame.
1210           if (gf_motion_error < this_error)
1211             fp_acc_data->sr_coded_error += gf_motion_error;
1212           else
1213             fp_acc_data->sr_coded_error += this_error;
1214         } else {
1215           fp_acc_data->sr_coded_error += motion_error;
1216         }
1217       } else {
1218         fp_acc_data->sr_coded_error += motion_error;
1219       }
1220 
1221       // Start by assuming that intra mode is best.
1222       best_ref_mv->row = 0;
1223       best_ref_mv->col = 0;
1224 
1225       if (motion_error <= this_error) {
1226         vpx_clear_system_state();
1227 
1228         // Keep a count of cases where the inter and intra were very close
1229         // and very low. This helps with scene cut detection for example in
1230         // cropped clips with black bars at the sides or top and bottom.
1231         if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
1232             (this_error < (2 * intrapenalty))) {
1233           fp_acc_data->neutral_count += 1.0;
1234           if (cpi->row_mt_bit_exact)
1235             cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count =
1236                 1.0;
1237           // Also track cases where the intra is not much worse than the inter
1238           // and use this in limiting the GF/arf group length.
1239         } else if ((this_error > NCOUNT_INTRA_THRESH) &&
1240                    (this_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
1241           mb_neutral_count =
1242               (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_error);
1243           fp_acc_data->neutral_count += mb_neutral_count;
1244           if (cpi->row_mt_bit_exact)
1245             cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count =
1246                 mb_neutral_count;
1247         }
1248 
1249         mv.row *= 8;
1250         mv.col *= 8;
1251         this_error = motion_error;
1252         xd->mi[0]->mode = NEWMV;
1253         xd->mi[0]->mv[0].as_mv = mv;
1254         xd->mi[0]->tx_size = TX_4X4;
1255         xd->mi[0]->ref_frame[0] = LAST_FRAME;
1256         xd->mi[0]->ref_frame[1] = NONE;
1257         vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
1258         vp9_encode_sby_pass1(x, bsize);
1259         fp_acc_data->sum_mvr += mv.row;
1260         fp_acc_data->sum_mvr_abs += abs(mv.row);
1261         fp_acc_data->sum_mvc += mv.col;
1262         fp_acc_data->sum_mvc_abs += abs(mv.col);
1263         fp_acc_data->sum_mvrs += mv.row * mv.row;
1264         fp_acc_data->sum_mvcs += mv.col * mv.col;
1265         ++(fp_acc_data->intercount);
1266 
1267         *best_ref_mv = mv;
1268 
1269         if (!is_zero_mv(&mv)) {
1270           ++(fp_acc_data->mvcount);
1271 
1272           // Does the row vector point inwards or outwards?
1273           if (mb_row < cm->mb_rows / 2) {
1274             if (mv.row > 0)
1275               --(fp_acc_data->sum_in_vectors);
1276             else if (mv.row < 0)
1277               ++(fp_acc_data->sum_in_vectors);
1278           } else if (mb_row > cm->mb_rows / 2) {
1279             if (mv.row > 0)
1280               ++(fp_acc_data->sum_in_vectors);
1281             else if (mv.row < 0)
1282               --(fp_acc_data->sum_in_vectors);
1283           }
1284 
1285           // Does the col vector point inwards or outwards?
1286           if (mb_col < cm->mb_cols / 2) {
1287             if (mv.col > 0)
1288               --(fp_acc_data->sum_in_vectors);
1289             else if (mv.col < 0)
1290               ++(fp_acc_data->sum_in_vectors);
1291           } else if (mb_col > cm->mb_cols / 2) {
1292             if (mv.col > 0)
1293               ++(fp_acc_data->sum_in_vectors);
1294             else if (mv.col < 0)
1295               --(fp_acc_data->sum_in_vectors);
1296           }
1297         }
1298         if (this_intra_error < scaled_low_intra_thresh) {
1299           fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1300         } else {
1301           fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1302         }
1303       } else {  // Intra < inter error
1304         if (this_intra_error < scaled_low_intra_thresh) {
1305           fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1306           if (this_motion_error < scaled_low_intra_thresh) {
1307             fp_acc_data->intra_count_low += 1.0;
1308           } else {
1309             fp_acc_data->intra_count_high += 1.0;
1310           }
1311         } else {
1312           fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1313           fp_acc_data->intra_count_high += 1.0;
1314         }
1315       }
1316     } else {
1317       fp_acc_data->sr_coded_error += (int64_t)this_error;
1318 #if CONFIG_RATE_CTRL
1319       if (cpi->oxcf.use_simple_encode_api) {
1320         store_fp_motion_vector(cpi, NULL, mb_row, mb_col, INTRA_FRAME, 0);
1321       }
1322 #endif  // CONFIG_RAGE_CTRL
1323     }
1324     fp_acc_data->coded_error += (int64_t)this_error;
1325 
1326     recon_yoffset += 16;
1327     recon_uvoffset += uv_mb_height;
1328 
1329     // Accumulate row level stats to the corresponding tile stats
1330     if (cpi->row_mt && mb_col == mb_col_end - 1)
1331       accumulate_fp_mb_row_stat(tile_data, fp_acc_data);
1332 
1333     (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, mb_row, c,
1334                                     num_mb_cols);
1335   }
1336   vpx_clear_system_state();
1337 }
1338 
first_pass_encode(VP9_COMP * cpi,FIRSTPASS_DATA * fp_acc_data)1339 static void first_pass_encode(VP9_COMP *cpi, FIRSTPASS_DATA *fp_acc_data) {
1340   VP9_COMMON *const cm = &cpi->common;
1341   int mb_row;
1342   TileDataEnc tile_data;
1343   TileInfo *tile = &tile_data.tile_info;
1344   MV zero_mv = { 0, 0 };
1345   MV best_ref_mv;
1346   // Tiling is ignored in the first pass.
1347   vp9_tile_init(tile, cm, 0, 0);
1348 
1349 #if CONFIG_RATE_CTRL
1350   if (cpi->oxcf.use_simple_encode_api) {
1351     fp_motion_vector_info_reset(cpi->frame_info.frame_width,
1352                                 cpi->frame_info.frame_height,
1353                                 cpi->fp_motion_vector_info);
1354   }
1355 #endif
1356 
1357   for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
1358     best_ref_mv = zero_mv;
1359     vp9_first_pass_encode_tile_mb_row(cpi, &cpi->td, fp_acc_data, &tile_data,
1360                                       &best_ref_mv, mb_row);
1361   }
1362 }
1363 
vp9_first_pass(VP9_COMP * cpi,const struct lookahead_entry * source)1364 void vp9_first_pass(VP9_COMP *cpi, const struct lookahead_entry *source) {
1365   MACROBLOCK *const x = &cpi->td.mb;
1366   VP9_COMMON *const cm = &cpi->common;
1367   MACROBLOCKD *const xd = &x->e_mbd;
1368   TWO_PASS *twopass = &cpi->twopass;
1369 
1370   YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1371   YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1372   YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
1373   const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
1374 
1375   BufferPool *const pool = cm->buffer_pool;
1376 
1377   FIRSTPASS_DATA fp_temp_data;
1378   FIRSTPASS_DATA *fp_acc_data = &fp_temp_data;
1379 
1380   vpx_clear_system_state();
1381   vp9_zero(fp_temp_data);
1382   fp_acc_data->image_data_start_row = INVALID_ROW;
1383 
1384   // First pass code requires valid last and new frame buffers.
1385   assert(new_yv12 != NULL);
1386   assert(frame_is_intra_only(cm) || (lst_yv12 != NULL));
1387 
1388   set_first_pass_params(cpi);
1389   vp9_set_quantizer(cpi, find_fp_qindex(cm->bit_depth));
1390 
1391   vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
1392 
1393   vp9_setup_src_planes(x, cpi->Source, 0, 0);
1394   vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
1395 
1396   if (!frame_is_intra_only(cm)) {
1397     vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
1398   }
1399 
1400   xd->mi = cm->mi_grid_visible;
1401   xd->mi[0] = cm->mi;
1402 
1403   vp9_frame_init_quantizer(cpi);
1404 
1405   x->skip_recode = 0;
1406 
1407   vp9_init_mv_probs(cm);
1408   vp9_initialize_rd_consts(cpi);
1409 
1410   cm->log2_tile_rows = 0;
1411 
1412   if (cpi->row_mt_bit_exact && cpi->twopass.fp_mb_float_stats == NULL)
1413     CHECK_MEM_ERROR(
1414         cm, cpi->twopass.fp_mb_float_stats,
1415         vpx_calloc(cm->MBs * sizeof(*cpi->twopass.fp_mb_float_stats), 1));
1416 
1417   {
1418     FIRSTPASS_STATS fps;
1419     TileDataEnc *first_tile_col;
1420     if (!cpi->row_mt) {
1421       cm->log2_tile_cols = 0;
1422       cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
1423       cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
1424       first_pass_encode(cpi, fp_acc_data);
1425       first_pass_stat_calc(cpi, &fps, fp_acc_data);
1426     } else {
1427       cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
1428       cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
1429       if (cpi->row_mt_bit_exact) {
1430         cm->log2_tile_cols = 0;
1431         vp9_zero_array(cpi->twopass.fp_mb_float_stats, cm->MBs);
1432       }
1433       vp9_encode_fp_row_mt(cpi);
1434       first_tile_col = &cpi->tile_data[0];
1435       if (cpi->row_mt_bit_exact)
1436         accumulate_floating_point_stats(cpi, first_tile_col);
1437       first_pass_stat_calc(cpi, &fps, &(first_tile_col->fp_data));
1438     }
1439 
1440     // Dont allow a value of 0 for duration.
1441     // (Section duration is also defaulted to minimum of 1.0).
1442     fps.duration = VPXMAX(1.0, (double)(source->ts_end - source->ts_start));
1443 
1444     // Don't want to do output stats with a stack variable!
1445     twopass->this_frame_stats = fps;
1446     output_stats(&twopass->this_frame_stats);
1447     accumulate_stats(&twopass->total_stats, &fps);
1448   }
1449 
1450   // Copy the previous Last Frame back into gf and and arf buffers if
1451   // the prediction is good enough... but also don't allow it to lag too far.
1452   if ((twopass->sr_update_lag > 3) ||
1453       ((cm->current_video_frame > 0) &&
1454        (twopass->this_frame_stats.pcnt_inter > 0.20) &&
1455        ((twopass->this_frame_stats.intra_error /
1456          DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
1457     if (gld_yv12 != NULL) {
1458       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1459                  cm->ref_frame_map[cpi->lst_fb_idx]);
1460     }
1461     twopass->sr_update_lag = 1;
1462   } else {
1463     ++twopass->sr_update_lag;
1464   }
1465 
1466   vpx_extend_frame_borders(new_yv12);
1467 
1468   // The frame we just compressed now becomes the last frame.
1469   ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
1470              cm->new_fb_idx);
1471 
1472   // Special case for the first frame. Copy into the GF buffer as a second
1473   // reference.
1474   if (cm->current_video_frame == 0 && cpi->gld_fb_idx != INVALID_IDX) {
1475     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1476                cm->ref_frame_map[cpi->lst_fb_idx]);
1477   }
1478 
1479   // Use this to see what the first pass reconstruction looks like.
1480   if (0) {
1481     char filename[512];
1482     FILE *recon_file;
1483     snprintf(filename, sizeof(filename), "enc%04d.yuv",
1484              (int)cm->current_video_frame);
1485 
1486     if (cm->current_video_frame == 0)
1487       recon_file = fopen(filename, "wb");
1488     else
1489       recon_file = fopen(filename, "ab");
1490 
1491     (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
1492     fclose(recon_file);
1493   }
1494 
1495   // In the first pass, every frame is considered as a show frame.
1496   update_frame_indexes(cm, /*show_frame=*/1);
1497   if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
1498 }
1499 
1500 static const double q_pow_term[(QINDEX_RANGE >> 5) + 1] = { 0.65, 0.70, 0.75,
1501                                                             0.85, 0.90, 0.90,
1502                                                             0.90, 1.00, 1.25 };
1503 
calc_correction_factor(double err_per_mb,double err_divisor,int q)1504 static double calc_correction_factor(double err_per_mb, double err_divisor,
1505                                      int q) {
1506   const double error_term = err_per_mb / DOUBLE_DIVIDE_CHECK(err_divisor);
1507   const int index = q >> 5;
1508   double power_term;
1509 
1510   assert((index >= 0) && (index < (QINDEX_RANGE >> 5)));
1511 
1512   // Adjustment based on quantizer to the power term.
1513   power_term =
1514       q_pow_term[index] +
1515       (((q_pow_term[index + 1] - q_pow_term[index]) * (q % 32)) / 32.0);
1516 
1517   // Calculate correction factor.
1518   if (power_term < 1.0) assert(error_term >= 0.0);
1519 
1520   return fclamp(pow(error_term, power_term), 0.05, 5.0);
1521 }
1522 
wq_err_divisor(VP9_COMP * cpi)1523 static double wq_err_divisor(VP9_COMP *cpi) {
1524   const VP9_COMMON *const cm = &cpi->common;
1525   unsigned int screen_area = (cm->width * cm->height);
1526 
1527   // Use a different error per mb factor for calculating boost for
1528   //  different formats.
1529   if (screen_area <= 640 * 360) {
1530     return 115.0;
1531   } else if (screen_area < 1280 * 720) {
1532     return 125.0;
1533   } else if (screen_area <= 1920 * 1080) {
1534     return 130.0;
1535   } else if (screen_area < 3840 * 2160) {
1536     return 150.0;
1537   }
1538 
1539   // Fall through to here only for 4K and above.
1540   return 200.0;
1541 }
1542 
1543 #define NOISE_FACTOR_MIN 0.9
1544 #define NOISE_FACTOR_MAX 1.1
get_twopass_worst_quality(VP9_COMP * cpi,const double section_err,double inactive_zone,double section_noise,int section_target_bandwidth)1545 static int get_twopass_worst_quality(VP9_COMP *cpi, const double section_err,
1546                                      double inactive_zone, double section_noise,
1547                                      int section_target_bandwidth) {
1548   const RATE_CONTROL *const rc = &cpi->rc;
1549   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1550   TWO_PASS *const twopass = &cpi->twopass;
1551   double last_group_rate_err;
1552 
1553   // Clamp the target rate to VBR min / max limts.
1554   const int target_rate =
1555       vp9_rc_clamp_pframe_target_size(cpi, section_target_bandwidth);
1556   double noise_factor = pow((section_noise / SECTION_NOISE_DEF), 0.5);
1557   noise_factor = fclamp(noise_factor, NOISE_FACTOR_MIN, NOISE_FACTOR_MAX);
1558   inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
1559 
1560 // TODO(jimbankoski): remove #if here or below when this has been
1561 // well tested.
1562 #if CONFIG_ALWAYS_ADJUST_BPM
1563   // based on recent history adjust expectations of bits per macroblock.
1564   last_group_rate_err =
1565       (double)twopass->rolling_arf_group_actual_bits /
1566       DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
1567   last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
1568   twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
1569   twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
1570 #endif
1571 
1572   if (target_rate <= 0) {
1573     return rc->worst_quality;  // Highest value allowed
1574   } else {
1575     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1576                             ? cpi->initial_mbs
1577                             : cpi->common.MBs;
1578     const double active_pct = VPXMAX(0.01, 1.0 - inactive_zone);
1579     const int active_mbs = (int)VPXMAX(1, (double)num_mbs * active_pct);
1580     const double av_err_per_mb = section_err / active_pct;
1581     const double speed_term = 1.0 + 0.04 * oxcf->speed;
1582     const int target_norm_bits_per_mb =
1583         (int)(((uint64_t)target_rate << BPER_MB_NORMBITS) / active_mbs);
1584     int q;
1585 
1586 // TODO(jimbankoski): remove #if here or above when this has been
1587 // well tested.
1588 #if !CONFIG_ALWAYS_ADJUST_BPM
1589     // based on recent history adjust expectations of bits per macroblock.
1590     last_group_rate_err =
1591         (double)twopass->rolling_arf_group_actual_bits /
1592         DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
1593     last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
1594     twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
1595     twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
1596 #endif
1597 
1598     // Try and pick a max Q that will be high enough to encode the
1599     // content at the given rate.
1600     for (q = rc->best_quality; q < rc->worst_quality; ++q) {
1601       const double factor =
1602           calc_correction_factor(av_err_per_mb, wq_err_divisor(cpi), q);
1603       const int bits_per_mb = vp9_rc_bits_per_mb(
1604           INTER_FRAME, q,
1605           factor * speed_term * cpi->twopass.bpm_factor * noise_factor,
1606           cpi->common.bit_depth);
1607       if (bits_per_mb <= target_norm_bits_per_mb) break;
1608     }
1609 
1610     // Restriction on active max q for constrained quality mode.
1611     if (cpi->oxcf.rc_mode == VPX_CQ) q = VPXMAX(q, oxcf->cq_level);
1612     return q;
1613   }
1614 }
1615 
setup_rf_level_maxq(VP9_COMP * cpi)1616 static void setup_rf_level_maxq(VP9_COMP *cpi) {
1617   int i;
1618   RATE_CONTROL *const rc = &cpi->rc;
1619   for (i = INTER_NORMAL; i < RATE_FACTOR_LEVELS; ++i) {
1620     int qdelta = vp9_frame_type_qdelta(cpi, i, rc->worst_quality);
1621     rc->rf_level_maxq[i] = VPXMAX(rc->worst_quality + qdelta, rc->best_quality);
1622   }
1623 }
1624 
init_subsampling(VP9_COMP * cpi)1625 static void init_subsampling(VP9_COMP *cpi) {
1626   const VP9_COMMON *const cm = &cpi->common;
1627   RATE_CONTROL *const rc = &cpi->rc;
1628   const int w = cm->width;
1629   const int h = cm->height;
1630   int i;
1631 
1632   for (i = 0; i < FRAME_SCALE_STEPS; ++i) {
1633     // Note: Frames with odd-sized dimensions may result from this scaling.
1634     rc->frame_width[i] = (w * 16) / frame_scale_factor[i];
1635     rc->frame_height[i] = (h * 16) / frame_scale_factor[i];
1636   }
1637 
1638   setup_rf_level_maxq(cpi);
1639 }
1640 
calculate_coded_size(VP9_COMP * cpi,int * scaled_frame_width,int * scaled_frame_height)1641 void calculate_coded_size(VP9_COMP *cpi, int *scaled_frame_width,
1642                           int *scaled_frame_height) {
1643   RATE_CONTROL *const rc = &cpi->rc;
1644   *scaled_frame_width = rc->frame_width[rc->frame_size_selector];
1645   *scaled_frame_height = rc->frame_height[rc->frame_size_selector];
1646 }
1647 
vp9_init_second_pass(VP9_COMP * cpi)1648 void vp9_init_second_pass(VP9_COMP *cpi) {
1649   VP9EncoderConfig *const oxcf = &cpi->oxcf;
1650   RATE_CONTROL *const rc = &cpi->rc;
1651   TWO_PASS *const twopass = &cpi->twopass;
1652   double frame_rate;
1653   FIRSTPASS_STATS *stats;
1654 
1655   zero_stats(&twopass->total_stats);
1656   zero_stats(&twopass->total_left_stats);
1657 
1658   if (!twopass->stats_in_end) return;
1659 
1660   stats = &twopass->total_stats;
1661 
1662   *stats = *twopass->stats_in_end;
1663   twopass->total_left_stats = *stats;
1664 
1665   // Scan the first pass file and calculate a modified score for each
1666   // frame that is used to distribute bits. The modified score is assumed
1667   // to provide a linear basis for bit allocation. I.e a frame A with a score
1668   // that is double that of frame B will be allocated 2x as many bits.
1669   {
1670     double modified_score_total = 0.0;
1671     const FIRSTPASS_STATS *s = twopass->stats_in;
1672     double av_err;
1673 
1674     if (oxcf->vbr_corpus_complexity) {
1675       twopass->mean_mod_score = (double)oxcf->vbr_corpus_complexity / 10.0;
1676       av_err = get_distribution_av_err(cpi, twopass);
1677     } else {
1678       av_err = get_distribution_av_err(cpi, twopass);
1679       // The first scan is unclamped and gives a raw average.
1680       while (s < twopass->stats_in_end) {
1681         modified_score_total += calculate_mod_frame_score(cpi, oxcf, s, av_err);
1682         ++s;
1683       }
1684 
1685       // The average error from this first scan is used to define the midpoint
1686       // error for the rate distribution function.
1687       twopass->mean_mod_score =
1688           modified_score_total / DOUBLE_DIVIDE_CHECK(stats->count);
1689     }
1690 
1691     // Second scan using clamps based on the previous cycle average.
1692     // This may modify the total and average somewhat but we dont bother with
1693     // further itterations.
1694     modified_score_total = 0.0;
1695     s = twopass->stats_in;
1696     while (s < twopass->stats_in_end) {
1697       modified_score_total +=
1698           calculate_norm_frame_score(cpi, twopass, oxcf, s, av_err);
1699       ++s;
1700     }
1701     twopass->normalized_score_left = modified_score_total;
1702 
1703     // If using Corpus wide VBR mode then update the clip target bandwidth to
1704     // reflect how the clip compares to the rest of the corpus.
1705     if (oxcf->vbr_corpus_complexity) {
1706       oxcf->target_bandwidth =
1707           (int64_t)((double)oxcf->target_bandwidth *
1708                     (twopass->normalized_score_left / stats->count));
1709     }
1710 
1711 #if COMPLEXITY_STATS_OUTPUT
1712     {
1713       FILE *compstats;
1714       compstats = fopen("complexity_stats.stt", "a");
1715       fprintf(compstats, "%10.3lf\n",
1716               twopass->normalized_score_left / stats->count);
1717       fclose(compstats);
1718     }
1719 #endif
1720   }
1721 
1722   frame_rate = 10000000.0 * stats->count / stats->duration;
1723   // Each frame can have a different duration, as the frame rate in the source
1724   // isn't guaranteed to be constant. The frame rate prior to the first frame
1725   // encoded in the second pass is a guess. However, the sum duration is not.
1726   // It is calculated based on the actual durations of all frames from the
1727   // first pass.
1728   vp9_new_framerate(cpi, frame_rate);
1729   twopass->bits_left =
1730       (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
1731 
1732   // This variable monitors how far behind the second ref update is lagging.
1733   twopass->sr_update_lag = 1;
1734 
1735   // Reset the vbr bits off target counters
1736   rc->vbr_bits_off_target = 0;
1737   rc->vbr_bits_off_target_fast = 0;
1738   rc->rate_error_estimate = 0;
1739 
1740   // Static sequence monitor variables.
1741   twopass->kf_zeromotion_pct = 100;
1742   twopass->last_kfgroup_zeromotion_pct = 100;
1743 
1744   // Initialize bits per macro_block estimate correction factor.
1745   twopass->bpm_factor = 1.0;
1746   // Initialize actual and target bits counters for ARF groups so that
1747   // at the start we have a neutral bpm adjustment.
1748   twopass->rolling_arf_group_target_bits = 1;
1749   twopass->rolling_arf_group_actual_bits = 1;
1750 
1751   if (oxcf->resize_mode != RESIZE_NONE) {
1752     init_subsampling(cpi);
1753   }
1754 
1755   // Initialize the arnr strangth adjustment to 0
1756   twopass->arnr_strength_adjustment = 0;
1757 }
1758 
1759 /* This function considers how the quality of prediction may be deteriorating
1760  * with distance. It compares the coded error for the last frame and the
1761  * second reference frame (usually two frames old) and also applies a factor
1762  * based on the extent of INTRA coding.
1763  *
1764  * The decay factor is then used to reduce the contribution of frames further
1765  * from the alt-ref or golden frame, to the bitrate boost calculation for that
1766  * alt-ref or golden frame.
1767  */
get_sr_decay_rate(const TWO_PASS * const twopass,const FIRSTPASS_STATS * frame)1768 static double get_sr_decay_rate(const TWO_PASS *const twopass,
1769                                 const FIRSTPASS_STATS *frame) {
1770   double sr_diff = (frame->sr_coded_error - frame->coded_error);
1771   double sr_decay = 1.0;
1772 
1773   // Do nothing if the second ref to last frame error difference is
1774   // very small or even negative.
1775   if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
1776     const double sr_diff_part =
1777         twopass->sr_diff_factor * ((sr_diff * 0.25) / frame->intra_error);
1778     double modified_pct_inter = frame->pcnt_inter;
1779     double modified_pcnt_intra;
1780 
1781     if ((frame->coded_error > LOW_CODED_ERR_PER_MB) &&
1782         ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
1783          (double)NCOUNT_FRAME_II_THRESH)) {
1784       modified_pct_inter =
1785           frame->pcnt_inter + frame->pcnt_intra_low - frame->pcnt_neutral;
1786     }
1787     modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
1788 
1789     sr_decay = 1.0 - sr_diff_part - (INTRA_PART * modified_pcnt_intra);
1790   }
1791   return VPXMAX(sr_decay, twopass->sr_default_decay_limit);
1792 }
1793 
1794 // This function gives an estimate of how badly we believe the prediction
1795 // quality is decaying from frame to frame.
get_zero_motion_factor(const TWO_PASS * const twopass,const FIRSTPASS_STATS * frame_stats)1796 static double get_zero_motion_factor(const TWO_PASS *const twopass,
1797                                      const FIRSTPASS_STATS *frame_stats) {
1798   const double zero_motion_pct =
1799       frame_stats->pcnt_inter - frame_stats->pcnt_motion;
1800   double sr_decay = get_sr_decay_rate(twopass, frame_stats);
1801   return VPXMIN(sr_decay, zero_motion_pct);
1802 }
1803 
get_prediction_decay_rate(const TWO_PASS * const twopass,const FIRSTPASS_STATS * frame_stats)1804 static double get_prediction_decay_rate(const TWO_PASS *const twopass,
1805                                         const FIRSTPASS_STATS *frame_stats) {
1806   const double sr_decay_rate = get_sr_decay_rate(twopass, frame_stats);
1807   double zero_motion_factor =
1808       twopass->zm_factor * (frame_stats->pcnt_inter - frame_stats->pcnt_motion);
1809 
1810   // Check that the zero motion factor is valid
1811   assert(zero_motion_factor >= 0.0 && zero_motion_factor <= 1.0);
1812 
1813   return VPXMAX(zero_motion_factor,
1814                 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
1815 }
1816 
get_show_idx(const TWO_PASS * twopass)1817 static int get_show_idx(const TWO_PASS *twopass) {
1818   return (int)(twopass->stats_in - twopass->stats_in_start);
1819 }
1820 // Function to test for a condition where a complex transition is followed
1821 // by a static section. For example in slide shows where there is a fade
1822 // between slides. This is to help with more optimal kf and gf positioning.
check_transition_to_still(const FIRST_PASS_INFO * first_pass_info,int show_idx,int still_interval)1823 static int check_transition_to_still(const FIRST_PASS_INFO *first_pass_info,
1824                                      int show_idx, int still_interval) {
1825   int j;
1826   int num_frames = fps_get_num_frames(first_pass_info);
1827   if (show_idx + still_interval > num_frames) {
1828     return 0;
1829   }
1830 
1831   // Look ahead a few frames to see if static condition persists...
1832   for (j = 0; j < still_interval; ++j) {
1833     const FIRSTPASS_STATS *stats =
1834         fps_get_frame_stats(first_pass_info, show_idx + j);
1835     if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
1836   }
1837 
1838   // Only if it does do we signal a transition to still.
1839   return j == still_interval;
1840 }
1841 
1842 // This function detects a flash through the high relative pcnt_second_ref
1843 // score in the frame following a flash frame. The offset passed in should
1844 // reflect this.
detect_flash_from_frame_stats(const FIRSTPASS_STATS * frame_stats)1845 static int detect_flash_from_frame_stats(const FIRSTPASS_STATS *frame_stats) {
1846   // What we are looking for here is a situation where there is a
1847   // brief break in prediction (such as a flash) but subsequent frames
1848   // are reasonably well predicted by an earlier (pre flash) frame.
1849   // The recovery after a flash is indicated by a high pcnt_second_ref
1850   // useage or a second ref coded error notabley lower than the last
1851   // frame coded error.
1852   if (frame_stats == NULL) {
1853     return 0;
1854   }
1855   return (frame_stats->sr_coded_error < frame_stats->coded_error) ||
1856          ((frame_stats->pcnt_second_ref > frame_stats->pcnt_inter) &&
1857           (frame_stats->pcnt_second_ref >= 0.5));
1858 }
1859 
detect_flash(const TWO_PASS * twopass,int offset)1860 static int detect_flash(const TWO_PASS *twopass, int offset) {
1861   const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
1862   return detect_flash_from_frame_stats(next_frame);
1863 }
1864 
1865 // 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)1866 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1867                                           double *mv_in_out,
1868                                           double *mv_in_out_accumulator,
1869                                           double *abs_mv_in_out_accumulator,
1870                                           double *mv_ratio_accumulator) {
1871   const double pct = stats->pcnt_motion;
1872 
1873   // Accumulate Motion In/Out of frame stats.
1874   *mv_in_out = stats->mv_in_out_count * pct;
1875   *mv_in_out_accumulator += *mv_in_out;
1876   *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1877 
1878   // Accumulate a measure of how uniform (or conversely how random) the motion
1879   // field is (a ratio of abs(mv) / mv).
1880   if (pct > 0.05) {
1881     const double mvr_ratio =
1882         fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1883     const double mvc_ratio =
1884         fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1885 
1886     *mv_ratio_accumulator +=
1887         pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
1888     *mv_ratio_accumulator +=
1889         pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
1890   }
1891 }
1892 
calc_frame_boost(const FRAME_INFO * frame_info,const FIRSTPASS_STATS * this_frame,const TWO_PASS * const twopass,int avg_frame_qindex,double this_frame_mv_in_out)1893 static double calc_frame_boost(const FRAME_INFO *frame_info,
1894                                const FIRSTPASS_STATS *this_frame,
1895                                const TWO_PASS *const twopass,
1896                                int avg_frame_qindex,
1897                                double this_frame_mv_in_out) {
1898   double frame_boost;
1899   const double lq =
1900       vp9_convert_qindex_to_q(avg_frame_qindex, frame_info->bit_depth);
1901   const double boost_q_correction = VPXMIN((0.5 + (lq * 0.015)), 1.5);
1902   const double active_area = calculate_active_area(frame_info, this_frame);
1903 
1904   // Frame booost is based on inter error.
1905   frame_boost = (twopass->err_per_mb * active_area) /
1906                 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
1907 
1908   // Small adjustment for cases where there is a zoom out
1909   if (this_frame_mv_in_out > 0.0)
1910     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1911 
1912   // Q correction and scalling
1913   frame_boost = frame_boost * boost_q_correction;
1914 
1915   return VPXMIN(frame_boost, twopass->gf_frame_max_boost * boost_q_correction);
1916 }
1917 
calc_kf_frame_boost(VP9_COMP * cpi,const FIRSTPASS_STATS * this_frame,double * sr_accumulator,double this_frame_mv_in_out,double zm_factor)1918 static double calc_kf_frame_boost(VP9_COMP *cpi,
1919                                   const FIRSTPASS_STATS *this_frame,
1920                                   double *sr_accumulator,
1921                                   double this_frame_mv_in_out,
1922                                   double zm_factor) {
1923   TWO_PASS *const twopass = &cpi->twopass;
1924   double frame_boost;
1925   const double lq = vp9_convert_qindex_to_q(
1926       cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.bit_depth);
1927   const double boost_q_correction = VPXMIN((0.50 + (lq * 0.015)), 2.00);
1928   const double active_area =
1929       calculate_active_area(&cpi->frame_info, this_frame);
1930   double max_boost;
1931 
1932   // Frame booost is based on inter error.
1933   frame_boost = (twopass->kf_err_per_mb * active_area) /
1934                 DOUBLE_DIVIDE_CHECK(this_frame->coded_error + *sr_accumulator);
1935 
1936   // Update the accumulator for second ref error difference.
1937   // This is intended to give an indication of how much the coded error is
1938   // increasing over time.
1939   *sr_accumulator += (this_frame->sr_coded_error - this_frame->coded_error);
1940   *sr_accumulator = VPXMAX(0.0, *sr_accumulator);
1941 
1942   // Small adjustment for cases where there is a zoom out
1943   if (this_frame_mv_in_out > 0.0)
1944     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1945 
1946   // Q correction and scaling
1947   // The 40.0 value here is an experimentally derived baseline minimum.
1948   // This value is in line with the minimum per frame boost in the alt_ref
1949   // boost calculation.
1950   frame_boost =
1951       (frame_boost + twopass->kf_frame_min_boost) * boost_q_correction;
1952 
1953   // Maximum allowed boost this frame. May be different for first vs subsequent
1954   // key frames.
1955   max_boost = (cpi->common.current_video_frame == 0)
1956                   ? twopass->kf_frame_max_boost_first
1957                   : twopass->kf_frame_max_boost_subs;
1958   max_boost *= zm_factor * boost_q_correction;
1959 
1960   return VPXMIN(frame_boost, max_boost);
1961 }
1962 
compute_arf_boost(const FRAME_INFO * frame_info,TWO_PASS * const twopass,int arf_show_idx,int f_frames,int b_frames,int avg_frame_qindex)1963 static int compute_arf_boost(const FRAME_INFO *frame_info,
1964                              TWO_PASS *const twopass, int arf_show_idx,
1965                              int f_frames, int b_frames, int avg_frame_qindex) {
1966   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
1967   int i;
1968   double boost_score = 0.0;
1969   double mv_ratio_accumulator = 0.0;
1970   double decay_accumulator = 1.0;
1971   double this_frame_mv_in_out = 0.0;
1972   double mv_in_out_accumulator = 0.0;
1973   double abs_mv_in_out_accumulator = 0.0;
1974   int arf_boost;
1975   int flash_detected = 0;
1976 
1977   // Search forward from the proposed arf/next gf position.
1978   for (i = 0; i < f_frames; ++i) {
1979     const FIRSTPASS_STATS *this_frame =
1980         fps_get_frame_stats(first_pass_info, arf_show_idx + i);
1981     const FIRSTPASS_STATS *next_frame =
1982         fps_get_frame_stats(first_pass_info, arf_show_idx + i + 1);
1983     if (this_frame == NULL) break;
1984 
1985     // Update the motion related elements to the boost calculation.
1986     accumulate_frame_motion_stats(
1987         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1988         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1989 
1990     // We want to discount the flash frame itself and the recovery
1991     // frame that follows as both will have poor scores.
1992     flash_detected = detect_flash_from_frame_stats(this_frame) ||
1993                      detect_flash_from_frame_stats(next_frame);
1994 
1995     // Accumulate the effect of prediction quality decay.
1996     if (!flash_detected) {
1997       decay_accumulator *= get_prediction_decay_rate(twopass, this_frame);
1998       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1999                               ? MIN_DECAY_FACTOR
2000                               : decay_accumulator;
2001     }
2002     boost_score += decay_accumulator *
2003                    calc_frame_boost(frame_info, this_frame, twopass,
2004                                     avg_frame_qindex, this_frame_mv_in_out);
2005   }
2006 
2007   arf_boost = (int)boost_score;
2008 
2009   // Reset for backward looking loop.
2010   boost_score = 0.0;
2011   mv_ratio_accumulator = 0.0;
2012   decay_accumulator = 1.0;
2013   this_frame_mv_in_out = 0.0;
2014   mv_in_out_accumulator = 0.0;
2015   abs_mv_in_out_accumulator = 0.0;
2016 
2017   // Search backward towards last gf position.
2018   for (i = -1; i >= -b_frames; --i) {
2019     const FIRSTPASS_STATS *this_frame =
2020         fps_get_frame_stats(first_pass_info, arf_show_idx + i);
2021     const FIRSTPASS_STATS *next_frame =
2022         fps_get_frame_stats(first_pass_info, arf_show_idx + i + 1);
2023     if (this_frame == NULL) break;
2024 
2025     // Update the motion related elements to the boost calculation.
2026     accumulate_frame_motion_stats(
2027         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2028         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2029 
2030     // We want to discount the the flash frame itself and the recovery
2031     // frame that follows as both will have poor scores.
2032     flash_detected = detect_flash_from_frame_stats(this_frame) ||
2033                      detect_flash_from_frame_stats(next_frame);
2034 
2035     // Cumulative effect of prediction quality decay.
2036     if (!flash_detected) {
2037       decay_accumulator *= get_prediction_decay_rate(twopass, this_frame);
2038       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
2039                               ? MIN_DECAY_FACTOR
2040                               : decay_accumulator;
2041     }
2042     boost_score += decay_accumulator *
2043                    calc_frame_boost(frame_info, this_frame, twopass,
2044                                     avg_frame_qindex, this_frame_mv_in_out);
2045   }
2046   arf_boost += (int)boost_score;
2047 
2048   if (arf_boost < ((b_frames + f_frames) * 40))
2049     arf_boost = ((b_frames + f_frames) * 40);
2050   arf_boost = VPXMAX(arf_boost, MIN_ARF_GF_BOOST);
2051 
2052   return arf_boost;
2053 }
2054 
calc_arf_boost(VP9_COMP * cpi,int f_frames,int b_frames)2055 static int calc_arf_boost(VP9_COMP *cpi, int f_frames, int b_frames) {
2056   const FRAME_INFO *frame_info = &cpi->frame_info;
2057   TWO_PASS *const twopass = &cpi->twopass;
2058   const int avg_inter_frame_qindex = cpi->rc.avg_frame_qindex[INTER_FRAME];
2059   int arf_show_idx = get_show_idx(twopass);
2060   return compute_arf_boost(frame_info, twopass, arf_show_idx, f_frames,
2061                            b_frames, avg_inter_frame_qindex);
2062 }
2063 
2064 // 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)2065 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
2066                                          const FIRSTPASS_STATS *end,
2067                                          int section_length) {
2068   const FIRSTPASS_STATS *s = begin;
2069   double intra_error = 0.0;
2070   double coded_error = 0.0;
2071   int i = 0;
2072 
2073   while (s < end && i < section_length) {
2074     intra_error += s->intra_error;
2075     coded_error += s->coded_error;
2076     ++s;
2077     ++i;
2078   }
2079 
2080   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
2081 }
2082 
2083 // Calculate the total bits to allocate in this GF/ARF group.
calculate_total_gf_group_bits(VP9_COMP * cpi,double gf_group_err)2084 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
2085                                              double gf_group_err) {
2086   VP9_COMMON *const cm = &cpi->common;
2087   const RATE_CONTROL *const rc = &cpi->rc;
2088   const TWO_PASS *const twopass = &cpi->twopass;
2089   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2090   int64_t total_group_bits;
2091   const int is_key_frame = frame_is_intra_only(cm);
2092   const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2093   int gop_frames =
2094       rc->baseline_gf_interval + rc->source_alt_ref_pending - arf_active_or_kf;
2095 
2096   // Calculate the bits to be allocated to the group as a whole.
2097   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0.0)) {
2098     int key_frame_interval = rc->frames_since_key + rc->frames_to_key;
2099     int distance_from_next_key_frame =
2100         rc->frames_to_key -
2101         (rc->baseline_gf_interval + rc->source_alt_ref_pending);
2102     int max_gf_bits_bias = rc->avg_frame_bandwidth;
2103     double gf_interval_bias_bits_normalize_factor =
2104         (double)rc->baseline_gf_interval / 16;
2105     total_group_bits = (int64_t)(twopass->kf_group_bits *
2106                                  (gf_group_err / twopass->kf_group_error_left));
2107     // TODO(ravi): Experiment with different values of max_gf_bits_bias
2108     total_group_bits +=
2109         (int64_t)((double)distance_from_next_key_frame / key_frame_interval *
2110                   max_gf_bits_bias * gf_interval_bias_bits_normalize_factor);
2111   } else {
2112     total_group_bits = 0;
2113   }
2114 
2115   // Clamp odd edge cases.
2116   total_group_bits = (total_group_bits < 0) ? 0
2117                      : (total_group_bits > twopass->kf_group_bits)
2118                          ? twopass->kf_group_bits
2119                          : total_group_bits;
2120 
2121   // Clip based on user supplied data rate variability limit.
2122   if (total_group_bits > (int64_t)max_bits * gop_frames)
2123     total_group_bits = (int64_t)max_bits * gop_frames;
2124 
2125   return total_group_bits;
2126 }
2127 
2128 // 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)2129 static int calculate_boost_bits(int frame_count, int boost,
2130                                 int64_t total_group_bits) {
2131   int allocation_chunks;
2132 
2133   // return 0 for invalid inputs (could arise e.g. through rounding errors)
2134   if (!boost || (total_group_bits <= 0) || (frame_count < 0)) return 0;
2135 
2136   allocation_chunks = (frame_count * NORMAL_BOOST) + boost;
2137 
2138   // Prevent overflow.
2139   if (boost > 1023) {
2140     int divisor = boost >> 10;
2141     boost /= divisor;
2142     allocation_chunks /= divisor;
2143   }
2144 
2145   // Calculate the number of extra bits for use in the boosted frame or frames.
2146   return VPXMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
2147                 0);
2148 }
2149 
2150 // Used in corpus vbr: Calculates the total normalized group complexity score
2151 // for a given number of frames starting at the current position in the stats
2152 // file.
calculate_group_score(VP9_COMP * cpi,double av_score,int frame_count)2153 static double calculate_group_score(VP9_COMP *cpi, double av_score,
2154                                     int frame_count) {
2155   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2156   TWO_PASS *const twopass = &cpi->twopass;
2157   const FIRSTPASS_STATS *s = twopass->stats_in;
2158   double score_total = 0.0;
2159   int i = 0;
2160 
2161   // We dont ever want to return a 0 score here.
2162   if (frame_count == 0) return 1.0;
2163 
2164   while ((i < frame_count) && (s < twopass->stats_in_end)) {
2165     score_total += calculate_norm_frame_score(cpi, twopass, oxcf, s, av_score);
2166     ++s;
2167     ++i;
2168   }
2169 
2170   return score_total;
2171 }
2172 
find_arf_order(VP9_COMP * cpi,GF_GROUP * gf_group,int * index_counter,int depth,int start,int end)2173 static void find_arf_order(VP9_COMP *cpi, GF_GROUP *gf_group,
2174                            int *index_counter, int depth, int start, int end) {
2175   TWO_PASS *twopass = &cpi->twopass;
2176   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2177   FIRSTPASS_STATS fpf_frame;
2178   const int mid = (start + end + 1) >> 1;
2179   const int min_frame_interval = 2;
2180   int idx;
2181 
2182   // Process regular P frames
2183   if ((end - start < min_frame_interval) ||
2184       (depth > gf_group->allowed_max_layer_depth)) {
2185     for (idx = start; idx <= end; ++idx) {
2186       gf_group->update_type[*index_counter] = LF_UPDATE;
2187       gf_group->arf_src_offset[*index_counter] = 0;
2188       gf_group->frame_gop_index[*index_counter] = idx;
2189       gf_group->rf_level[*index_counter] = INTER_NORMAL;
2190       gf_group->layer_depth[*index_counter] = depth;
2191       gf_group->gfu_boost[*index_counter] = NORMAL_BOOST;
2192       ++(*index_counter);
2193     }
2194     gf_group->max_layer_depth = VPXMAX(gf_group->max_layer_depth, depth);
2195     return;
2196   }
2197 
2198   assert(abs(mid - start) >= 1 && abs(mid - end) >= 1);
2199 
2200   // Process ARF frame
2201   gf_group->layer_depth[*index_counter] = depth;
2202   gf_group->update_type[*index_counter] = ARF_UPDATE;
2203   gf_group->arf_src_offset[*index_counter] = mid - start;
2204   gf_group->frame_gop_index[*index_counter] = mid;
2205   gf_group->rf_level[*index_counter] = GF_ARF_LOW;
2206 
2207   for (idx = 0; idx <= mid; ++idx)
2208     if (EOF == input_stats(twopass, &fpf_frame)) break;
2209 
2210   gf_group->gfu_boost[*index_counter] =
2211       VPXMAX(MIN_ARF_GF_BOOST,
2212              calc_arf_boost(cpi, end - mid + 1, mid - start) >> depth);
2213 
2214   reset_fpf_position(twopass, start_pos);
2215 
2216   ++(*index_counter);
2217 
2218   find_arf_order(cpi, gf_group, index_counter, depth + 1, start, mid - 1);
2219 
2220   gf_group->update_type[*index_counter] = USE_BUF_FRAME;
2221   gf_group->arf_src_offset[*index_counter] = 0;
2222   gf_group->frame_gop_index[*index_counter] = mid;
2223   gf_group->rf_level[*index_counter] = INTER_NORMAL;
2224   gf_group->layer_depth[*index_counter] = depth;
2225   ++(*index_counter);
2226 
2227   find_arf_order(cpi, gf_group, index_counter, depth + 1, mid + 1, end);
2228 }
2229 
set_gf_overlay_frame_type(GF_GROUP * gf_group,int frame_index,int source_alt_ref_active)2230 static INLINE void set_gf_overlay_frame_type(GF_GROUP *gf_group,
2231                                              int frame_index,
2232                                              int source_alt_ref_active) {
2233   if (source_alt_ref_active) {
2234     gf_group->update_type[frame_index] = OVERLAY_UPDATE;
2235     gf_group->rf_level[frame_index] = INTER_NORMAL;
2236     gf_group->layer_depth[frame_index] = MAX_ARF_LAYERS - 1;
2237     gf_group->gfu_boost[frame_index] = NORMAL_BOOST;
2238   } else {
2239     gf_group->update_type[frame_index] = GF_UPDATE;
2240     gf_group->rf_level[frame_index] = GF_ARF_STD;
2241     gf_group->layer_depth[frame_index] = 0;
2242   }
2243 }
2244 
define_gf_group_structure(VP9_COMP * cpi)2245 static void define_gf_group_structure(VP9_COMP *cpi) {
2246   RATE_CONTROL *const rc = &cpi->rc;
2247   TWO_PASS *const twopass = &cpi->twopass;
2248   GF_GROUP *const gf_group = &twopass->gf_group;
2249   int frame_index = 0;
2250   int key_frame = cpi->common.frame_type == KEY_FRAME;
2251   int layer_depth = 1;
2252   int gop_frames =
2253       rc->baseline_gf_interval - (key_frame || rc->source_alt_ref_pending);
2254 
2255   gf_group->frame_start = cpi->common.current_video_frame;
2256   gf_group->frame_end = gf_group->frame_start + rc->baseline_gf_interval;
2257   gf_group->max_layer_depth = 0;
2258   gf_group->allowed_max_layer_depth = 0;
2259 
2260   // For key frames the frame target rate is already set and it
2261   // is also the golden frame.
2262   // === [frame_index == 0] ===
2263   if (!key_frame)
2264     set_gf_overlay_frame_type(gf_group, frame_index, rc->source_alt_ref_active);
2265 
2266   ++frame_index;
2267 
2268   // === [frame_index == 1] ===
2269   if (rc->source_alt_ref_pending) {
2270     gf_group->update_type[frame_index] = ARF_UPDATE;
2271     gf_group->rf_level[frame_index] = GF_ARF_STD;
2272     gf_group->layer_depth[frame_index] = layer_depth;
2273     gf_group->arf_src_offset[frame_index] =
2274         (unsigned char)(rc->baseline_gf_interval - 1);
2275     gf_group->frame_gop_index[frame_index] = rc->baseline_gf_interval;
2276     gf_group->max_layer_depth = 1;
2277     ++frame_index;
2278     ++layer_depth;
2279     gf_group->allowed_max_layer_depth = cpi->oxcf.enable_auto_arf;
2280   }
2281 
2282   find_arf_order(cpi, gf_group, &frame_index, layer_depth, 1, gop_frames);
2283 
2284   set_gf_overlay_frame_type(gf_group, frame_index, rc->source_alt_ref_pending);
2285   gf_group->arf_src_offset[frame_index] = 0;
2286   gf_group->frame_gop_index[frame_index] = rc->baseline_gf_interval;
2287 
2288   // Set the frame ops number.
2289   gf_group->gf_group_size = frame_index;
2290 }
2291 
allocate_gf_group_bits(VP9_COMP * cpi,int64_t gf_group_bits,int gf_arf_bits)2292 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
2293                                    int gf_arf_bits) {
2294   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2295   RATE_CONTROL *const rc = &cpi->rc;
2296   TWO_PASS *const twopass = &cpi->twopass;
2297   GF_GROUP *const gf_group = &twopass->gf_group;
2298   FIRSTPASS_STATS frame_stats;
2299   int i;
2300   int frame_index = 0;
2301   int target_frame_size;
2302   int key_frame;
2303   const int max_bits = frame_max_bits(&cpi->rc, oxcf);
2304   int64_t total_group_bits = gf_group_bits;
2305   int mid_frame_idx;
2306   int normal_frames;
2307   int normal_frame_bits;
2308   int last_frame_reduction = 0;
2309   double av_score = 1.0;
2310   double tot_norm_frame_score = 1.0;
2311   double this_frame_score = 1.0;
2312 
2313   // Define the GF structure and specify
2314   int gop_frames = gf_group->gf_group_size;
2315 
2316   key_frame = cpi->common.frame_type == KEY_FRAME;
2317 
2318   // For key frames the frame target rate is already set and it
2319   // is also the golden frame.
2320   // === [frame_index == 0] ===
2321   if (!key_frame) {
2322     gf_group->bit_allocation[frame_index] =
2323         rc->source_alt_ref_active ? 0 : gf_arf_bits;
2324   }
2325 
2326   // Deduct the boost bits for arf (or gf if it is not a key frame)
2327   // from the group total.
2328   if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
2329 
2330   ++frame_index;
2331 
2332   // === [frame_index == 1] ===
2333   // Store the bits to spend on the ARF if there is one.
2334   if (rc->source_alt_ref_pending) {
2335     gf_group->bit_allocation[frame_index] = gf_arf_bits;
2336 
2337     ++frame_index;
2338   }
2339 
2340   // Define middle frame
2341   mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
2342 
2343   normal_frames = (rc->baseline_gf_interval - 1);
2344   if (normal_frames > 1)
2345     normal_frame_bits = (int)(total_group_bits / normal_frames);
2346   else
2347     normal_frame_bits = (int)total_group_bits;
2348 
2349   gf_group->gfu_boost[1] = rc->gfu_boost;
2350 
2351   if (cpi->multi_layer_arf) {
2352     int idx;
2353     int arf_depth_bits[MAX_ARF_LAYERS] = { 0 };
2354     int arf_depth_count[MAX_ARF_LAYERS] = { 0 };
2355     int arf_depth_boost[MAX_ARF_LAYERS] = { 0 };
2356     int total_arfs = 1;  // Account for the base layer ARF.
2357 
2358     for (idx = 0; idx < gop_frames; ++idx) {
2359       if (gf_group->update_type[idx] == ARF_UPDATE) {
2360         arf_depth_boost[gf_group->layer_depth[idx]] += gf_group->gfu_boost[idx];
2361         ++arf_depth_count[gf_group->layer_depth[idx]];
2362       }
2363     }
2364 
2365     for (idx = 2; idx < MAX_ARF_LAYERS; ++idx) {
2366       if (arf_depth_boost[idx] == 0) break;
2367       arf_depth_bits[idx] = calculate_boost_bits(
2368           rc->baseline_gf_interval - total_arfs - arf_depth_count[idx],
2369           arf_depth_boost[idx], total_group_bits);
2370 
2371       total_group_bits -= arf_depth_bits[idx];
2372       total_arfs += arf_depth_count[idx];
2373     }
2374 
2375     // offset the base layer arf
2376     normal_frames -= (total_arfs - 1);
2377     if (normal_frames > 1)
2378       normal_frame_bits = (int)(total_group_bits / normal_frames);
2379     else
2380       normal_frame_bits = (int)total_group_bits;
2381 
2382     target_frame_size = normal_frame_bits;
2383     target_frame_size =
2384         clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2385 
2386     // The first layer ARF has its bit allocation assigned.
2387     for (idx = frame_index; idx < gop_frames; ++idx) {
2388       switch (gf_group->update_type[idx]) {
2389         case ARF_UPDATE:
2390           gf_group->bit_allocation[idx] =
2391               (int)(((int64_t)arf_depth_bits[gf_group->layer_depth[idx]] *
2392                      gf_group->gfu_boost[idx]) /
2393                     arf_depth_boost[gf_group->layer_depth[idx]]);
2394           break;
2395         case USE_BUF_FRAME: gf_group->bit_allocation[idx] = 0; break;
2396         default: gf_group->bit_allocation[idx] = target_frame_size; break;
2397       }
2398     }
2399     gf_group->bit_allocation[idx] = 0;
2400 
2401     return;
2402   }
2403 
2404   if (oxcf->vbr_corpus_complexity) {
2405     av_score = get_distribution_av_err(cpi, twopass);
2406     tot_norm_frame_score = calculate_group_score(cpi, av_score, normal_frames);
2407   }
2408 
2409   // Allocate bits to the other frames in the group.
2410   for (i = 0; i < normal_frames; ++i) {
2411     if (EOF == input_stats(twopass, &frame_stats)) break;
2412     if (oxcf->vbr_corpus_complexity) {
2413       this_frame_score = calculate_norm_frame_score(cpi, twopass, oxcf,
2414                                                     &frame_stats, av_score);
2415       normal_frame_bits = (int)((double)total_group_bits *
2416                                 (this_frame_score / tot_norm_frame_score));
2417     }
2418 
2419     target_frame_size = normal_frame_bits;
2420     if ((i == (normal_frames - 1)) && (i >= 1)) {
2421       last_frame_reduction = normal_frame_bits / 16;
2422       target_frame_size -= last_frame_reduction;
2423     }
2424 
2425     target_frame_size =
2426         clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2427 
2428     gf_group->bit_allocation[frame_index] = target_frame_size;
2429     ++frame_index;
2430   }
2431 
2432   // Add in some extra bits for the middle frame in the group.
2433   gf_group->bit_allocation[mid_frame_idx] += last_frame_reduction;
2434 
2435   // Note:
2436   // We need to configure the frame at the end of the sequence + 1 that will be
2437   // the start frame for the next group. Otherwise prior to the call to
2438   // vp9_rc_get_second_pass_params() the data will be undefined.
2439 }
2440 
2441 // Adjusts the ARNF filter for a GF group.
adjust_group_arnr_filter(VP9_COMP * cpi,double section_noise,double section_inter,double section_motion)2442 static void adjust_group_arnr_filter(VP9_COMP *cpi, double section_noise,
2443                                      double section_inter,
2444                                      double section_motion) {
2445   TWO_PASS *const twopass = &cpi->twopass;
2446   double section_zeromv = section_inter - section_motion;
2447 
2448   twopass->arnr_strength_adjustment = 0;
2449 
2450   if (section_noise < 150) {
2451     twopass->arnr_strength_adjustment -= 1;
2452     if (section_noise < 75) twopass->arnr_strength_adjustment -= 1;
2453   } else if (section_noise > 250)
2454     twopass->arnr_strength_adjustment += 1;
2455 
2456   if (section_zeromv > 0.50) twopass->arnr_strength_adjustment += 1;
2457 }
2458 
2459 // Analyse and define a gf/arf group.
2460 #define ARF_ABS_ZOOM_THRESH 4.0
2461 
2462 #define MAX_GF_BOOST 5400
2463 
2464 typedef struct RANGE {
2465   int min;
2466   int max;
2467 } RANGE;
2468 
2469 /* get_gop_coding_frame_num() depends on several fields in RATE_CONTROL *rc as
2470  * follows.
2471  * Static fields:
2472  * (The following fields will remain unchanged after initialization of encoder.)
2473  *   rc->static_scene_max_gf_interval
2474  *   rc->min_gf_interval
2475  *   twopass->sr_diff_factor
2476  *   twopass->sr_default_decay_limit
2477  *   twopass->zm_factor
2478  *
2479  * Dynamic fields:
2480  * (The following fields will be updated before or after coding each frame.)
2481  *   rc->frames_to_key
2482  *   rc->frames_since_key
2483  *   rc->source_alt_ref_active
2484  *
2485  * Special case: if CONFIG_RATE_CTRL is true, the external arf indexes will
2486  * determine the arf position.
2487  *
2488  * TODO(angiebird): Separate the dynamic fields and static fields into two
2489  * structs.
2490  */
get_gop_coding_frame_num(int * use_alt_ref,const FRAME_INFO * frame_info,const TWO_PASS * const twopass,const RATE_CONTROL * rc,int gf_start_show_idx,const RANGE * active_gf_interval,double gop_intra_factor,int lag_in_frames)2491 static int get_gop_coding_frame_num(
2492     int *use_alt_ref, const FRAME_INFO *frame_info,
2493     const TWO_PASS *const twopass, const RATE_CONTROL *rc,
2494     int gf_start_show_idx, const RANGE *active_gf_interval,
2495     double gop_intra_factor, int lag_in_frames) {
2496   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
2497   double loop_decay_rate = 1.00;
2498   double mv_ratio_accumulator = 0.0;
2499   double this_frame_mv_in_out = 0.0;
2500   double mv_in_out_accumulator = 0.0;
2501   double abs_mv_in_out_accumulator = 0.0;
2502   double sr_accumulator = 0.0;
2503   // Motion breakout threshold for loop below depends on image size.
2504   double mv_ratio_accumulator_thresh =
2505       (frame_info->frame_height + frame_info->frame_width) / 4.0;
2506   double zero_motion_accumulator = 1.0;
2507   int gop_coding_frames;
2508 
2509   *use_alt_ref = 1;
2510   gop_coding_frames = 0;
2511   while (gop_coding_frames < rc->static_scene_max_gf_interval &&
2512          gop_coding_frames < rc->frames_to_key) {
2513     const FIRSTPASS_STATS *next_next_frame;
2514     const FIRSTPASS_STATS *next_frame;
2515     int flash_detected;
2516     ++gop_coding_frames;
2517 
2518     next_frame = fps_get_frame_stats(first_pass_info,
2519                                      gf_start_show_idx + gop_coding_frames);
2520     if (next_frame == NULL) {
2521       break;
2522     }
2523 
2524     // Test for the case where there is a brief flash but the prediction
2525     // quality back to an earlier frame is then restored.
2526     next_next_frame = fps_get_frame_stats(
2527         first_pass_info, gf_start_show_idx + gop_coding_frames + 1);
2528     flash_detected = detect_flash_from_frame_stats(next_next_frame);
2529 
2530     // Update the motion related elements to the boost calculation.
2531     accumulate_frame_motion_stats(
2532         next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2533         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2534 
2535     // Monitor for static sections.
2536     if ((rc->frames_since_key + gop_coding_frames - 1) > 1) {
2537       zero_motion_accumulator = VPXMIN(
2538           zero_motion_accumulator, get_zero_motion_factor(twopass, next_frame));
2539     }
2540 
2541     // Accumulate the effect of prediction quality decay.
2542     if (!flash_detected) {
2543       double last_loop_decay_rate = loop_decay_rate;
2544       loop_decay_rate = get_prediction_decay_rate(twopass, next_frame);
2545 
2546       // Break clause to detect very still sections after motion. For example,
2547       // a static image after a fade or other transition.
2548       if (gop_coding_frames > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
2549           last_loop_decay_rate < 0.9) {
2550         int still_interval = 5;
2551         if (check_transition_to_still(first_pass_info,
2552                                       gf_start_show_idx + gop_coding_frames,
2553                                       still_interval)) {
2554           *use_alt_ref = 0;
2555           break;
2556         }
2557       }
2558 
2559       // Update the accumulator for second ref error difference.
2560       // This is intended to give an indication of how much the coded error is
2561       // increasing over time.
2562       if (gop_coding_frames == 1) {
2563         sr_accumulator += next_frame->coded_error;
2564       } else {
2565         sr_accumulator +=
2566             (next_frame->sr_coded_error - next_frame->coded_error);
2567       }
2568     }
2569 
2570     // Break out conditions.
2571     // Break at maximum of active_gf_interval->max unless almost totally
2572     // static.
2573     //
2574     // Note that the addition of a test of rc->source_alt_ref_active is
2575     // deliberate. The effect of this is that after a normal altref group even
2576     // if the material is static there will be one normal length GF group
2577     // before allowing longer GF groups. The reason for this is that in cases
2578     // such as slide shows where slides are separated by a complex transition
2579     // such as a fade, the arf group spanning the transition may not be coded
2580     // at a very high quality and hence this frame (with its overlay) is a
2581     // poor golden frame to use for an extended group.
2582     if ((gop_coding_frames >= active_gf_interval->max) &&
2583         ((zero_motion_accumulator < 0.995) || (rc->source_alt_ref_active))) {
2584       break;
2585     }
2586     if (
2587         // Don't break out with a very short interval.
2588         (gop_coding_frames >= active_gf_interval->min) &&
2589         // If possible dont break very close to a kf
2590         ((rc->frames_to_key - gop_coding_frames) >= rc->min_gf_interval) &&
2591         (gop_coding_frames & 0x01) && (!flash_detected) &&
2592         ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
2593          (abs_mv_in_out_accumulator > ARF_ABS_ZOOM_THRESH) ||
2594          (sr_accumulator > gop_intra_factor * next_frame->intra_error))) {
2595       break;
2596     }
2597   }
2598   *use_alt_ref &= zero_motion_accumulator < 0.995;
2599   *use_alt_ref &= gop_coding_frames < lag_in_frames;
2600   *use_alt_ref &= gop_coding_frames >= rc->min_gf_interval;
2601   return gop_coding_frames;
2602 }
2603 
get_active_gf_inverval_range_simple(int min_gf_interval,int arf_active_or_kf,int frames_to_key)2604 static RANGE get_active_gf_inverval_range_simple(int min_gf_interval,
2605                                                  int arf_active_or_kf,
2606                                                  int frames_to_key) {
2607   RANGE active_gf_interval;
2608   active_gf_interval.min = min_gf_interval + arf_active_or_kf + 2;
2609   active_gf_interval.max = 16 + arf_active_or_kf;
2610 
2611   if ((active_gf_interval.max <= frames_to_key) &&
2612       (active_gf_interval.max >= (frames_to_key - min_gf_interval))) {
2613     active_gf_interval.min = frames_to_key / 2;
2614     active_gf_interval.max = frames_to_key / 2;
2615   }
2616   return active_gf_interval;
2617 }
2618 
get_active_gf_inverval_range(const FRAME_INFO * frame_info,const RATE_CONTROL * rc,int arf_active_or_kf,int gf_start_show_idx,int active_worst_quality,int last_boosted_qindex)2619 static RANGE get_active_gf_inverval_range(
2620     const FRAME_INFO *frame_info, const RATE_CONTROL *rc, int arf_active_or_kf,
2621     int gf_start_show_idx, int active_worst_quality, int last_boosted_qindex) {
2622   RANGE active_gf_interval;
2623   int int_max_q = (int)(vp9_convert_qindex_to_q(active_worst_quality,
2624                                                 frame_info->bit_depth));
2625   int q_term = (gf_start_show_idx == 0)
2626                    ? int_max_q / 32
2627                    : (int)(vp9_convert_qindex_to_q(last_boosted_qindex,
2628                                                    frame_info->bit_depth) /
2629                            6);
2630   active_gf_interval.min =
2631       rc->min_gf_interval + arf_active_or_kf + VPXMIN(2, int_max_q / 200);
2632   active_gf_interval.min =
2633       VPXMIN(active_gf_interval.min, rc->max_gf_interval + arf_active_or_kf);
2634 
2635   // The value chosen depends on the active Q range. At low Q we have
2636   // bits to spare and are better with a smaller interval and smaller boost.
2637   // At high Q when there are few bits to spare we are better with a longer
2638   // interval to spread the cost of the GF.
2639   active_gf_interval.max = 11 + arf_active_or_kf + VPXMIN(5, q_term);
2640 
2641   // Force max GF interval to be odd.
2642   active_gf_interval.max = active_gf_interval.max | 0x01;
2643 
2644   // We have: active_gf_interval.min <=
2645   // rc->max_gf_interval + arf_active_or_kf.
2646   if (active_gf_interval.max < active_gf_interval.min) {
2647     active_gf_interval.max = active_gf_interval.min;
2648   } else {
2649     active_gf_interval.max =
2650         VPXMIN(active_gf_interval.max, rc->max_gf_interval + arf_active_or_kf);
2651   }
2652 
2653   // Would the active max drop us out just before the near the next kf?
2654   if ((active_gf_interval.max <= rc->frames_to_key) &&
2655       (active_gf_interval.max >= (rc->frames_to_key - rc->min_gf_interval))) {
2656     active_gf_interval.max = rc->frames_to_key / 2;
2657   }
2658   active_gf_interval.max =
2659       VPXMAX(active_gf_interval.max, active_gf_interval.min);
2660   return active_gf_interval;
2661 }
2662 
get_arf_layers(int multi_layer_arf,int max_layers,int coding_frame_num)2663 static int get_arf_layers(int multi_layer_arf, int max_layers,
2664                           int coding_frame_num) {
2665   assert(max_layers <= MAX_ARF_LAYERS);
2666   if (multi_layer_arf) {
2667     int layers = 0;
2668     int i;
2669     for (i = coding_frame_num; i > 0; i >>= 1) {
2670       ++layers;
2671     }
2672     layers = VPXMIN(max_layers, layers);
2673     return layers;
2674   } else {
2675     return 1;
2676   }
2677 }
2678 
define_gf_group(VP9_COMP * cpi,int gf_start_show_idx)2679 static void define_gf_group(VP9_COMP *cpi, int gf_start_show_idx) {
2680   VP9_COMMON *const cm = &cpi->common;
2681   RATE_CONTROL *const rc = &cpi->rc;
2682   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2683   TWO_PASS *const twopass = &cpi->twopass;
2684   const FRAME_INFO *frame_info = &cpi->frame_info;
2685   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
2686   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2687   int gop_coding_frames;
2688 
2689   double gf_group_err = 0.0;
2690   double gf_group_raw_error = 0.0;
2691   double gf_group_noise = 0.0;
2692   double gf_group_skip_pct = 0.0;
2693   double gf_group_inactive_zone_rows = 0.0;
2694   double gf_group_inter = 0.0;
2695   double gf_group_motion = 0.0;
2696 
2697   int allow_alt_ref = is_altref_enabled(cpi);
2698   int use_alt_ref;
2699 
2700   int64_t gf_group_bits;
2701   int gf_arf_bits;
2702   const int is_key_frame = frame_is_intra_only(cm);
2703   // If this is a key frame or the overlay from a previous arf then
2704   // the error score / cost of this frame has already been accounted for.
2705   const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2706   int is_alt_ref_flash = 0;
2707 
2708   double gop_intra_factor;
2709   int gop_frames;
2710   RANGE active_gf_interval;
2711 
2712   // Reset the GF group data structures unless this is a key
2713   // frame in which case it will already have been done.
2714   if (is_key_frame == 0) {
2715     vp9_zero(twopass->gf_group);
2716     ++rc->gop_global_index;
2717   } else {
2718     rc->gop_global_index = 0;
2719   }
2720 
2721   vpx_clear_system_state();
2722 
2723   if (oxcf->use_simple_encode_api) {
2724     active_gf_interval = get_active_gf_inverval_range_simple(
2725         rc->min_gf_interval, arf_active_or_kf, rc->frames_to_key);
2726   } else {
2727     active_gf_interval = get_active_gf_inverval_range(
2728         frame_info, rc, arf_active_or_kf, gf_start_show_idx,
2729         twopass->active_worst_quality, rc->last_boosted_qindex);
2730   }
2731 
2732   if (cpi->multi_layer_arf) {
2733     int arf_layers = get_arf_layers(cpi->multi_layer_arf, oxcf->enable_auto_arf,
2734                                     active_gf_interval.max);
2735     gop_intra_factor = 1.0 + 0.25 * arf_layers;
2736   } else {
2737     gop_intra_factor = 1.0;
2738   }
2739 
2740   gop_coding_frames = get_gop_coding_frame_num(
2741       &use_alt_ref, frame_info, twopass, rc, gf_start_show_idx,
2742       &active_gf_interval, gop_intra_factor, cpi->oxcf.lag_in_frames);
2743   use_alt_ref &= allow_alt_ref;
2744 #if CONFIG_RATE_CTRL
2745   // If the external gop_command is on, we will override the decisions
2746   // of gop_coding_frames and use_alt_ref.
2747   if (cpi->oxcf.use_simple_encode_api) {
2748     const GOP_COMMAND *gop_command = &cpi->encode_command.gop_command;
2749     assert(allow_alt_ref == 1);
2750     if (gop_command->use) {
2751       gop_coding_frames = gop_command_coding_frame_count(gop_command);
2752       use_alt_ref = gop_command->use_alt_ref;
2753     }
2754   }
2755 #endif
2756   // If the external rate control model for GOP is used, the gop decisions
2757   // are overwritten. Specifically, |gop_coding_frames| and |use_alt_ref|
2758   // will be overwritten.
2759   if (cpi->ext_ratectrl.ready &&
2760       (cpi->ext_ratectrl.funcs.rc_type & VPX_RC_GOP) != 0) {
2761     vpx_codec_err_t codec_status;
2762     vpx_rc_gop_decision_t gop_decision;
2763     vpx_rc_gop_info_t gop_info;
2764     gop_info.min_gf_interval = rc->min_gf_interval;
2765     gop_info.max_gf_interval = rc->max_gf_interval;
2766     gop_info.active_min_gf_interval = active_gf_interval.min;
2767     gop_info.active_max_gf_interval = active_gf_interval.max;
2768     gop_info.allow_alt_ref = allow_alt_ref;
2769     gop_info.is_key_frame = is_key_frame;
2770     gop_info.last_gop_use_alt_ref = rc->source_alt_ref_active;
2771     gop_info.frames_since_key = rc->frames_since_key;
2772     gop_info.frames_to_key = rc->frames_to_key;
2773     gop_info.lag_in_frames = cpi->oxcf.lag_in_frames;
2774     gop_info.show_index = cm->current_video_frame;
2775     gop_info.coding_index = cm->current_frame_coding_index;
2776     gop_info.gop_global_index = rc->gop_global_index;
2777 
2778     codec_status = vp9_extrc_get_gop_decision(&cpi->ext_ratectrl, &gop_info,
2779                                               &gop_decision);
2780     if (codec_status != VPX_CODEC_OK) {
2781       vpx_internal_error(&cm->error, codec_status,
2782                          "vp9_extrc_get_gop_decision() failed");
2783     }
2784     gop_coding_frames = gop_decision.gop_coding_frames;
2785     use_alt_ref = gop_decision.use_alt_ref;
2786   }
2787 
2788   // Was the group length constrained by the requirement for a new KF?
2789   rc->constrained_gf_group = (gop_coding_frames >= rc->frames_to_key) ? 1 : 0;
2790 
2791   // Should we use the alternate reference frame.
2792   if (use_alt_ref) {
2793     const int f_frames =
2794         (rc->frames_to_key - gop_coding_frames >= gop_coding_frames - 1)
2795             ? gop_coding_frames - 1
2796             : VPXMAX(0, rc->frames_to_key - gop_coding_frames);
2797     const int b_frames = gop_coding_frames - 1;
2798     const int avg_inter_frame_qindex = rc->avg_frame_qindex[INTER_FRAME];
2799     // TODO(angiebird): figure out why arf's location is assigned this way
2800     const int arf_show_idx = VPXMIN(gf_start_show_idx + gop_coding_frames + 1,
2801                                     fps_get_num_frames(first_pass_info));
2802 
2803     // Calculate the boost for alt ref.
2804     rc->gfu_boost =
2805         compute_arf_boost(frame_info, twopass, arf_show_idx, f_frames, b_frames,
2806                           avg_inter_frame_qindex);
2807     rc->source_alt_ref_pending = 1;
2808   } else {
2809     const int f_frames = gop_coding_frames - 1;
2810     const int b_frames = 0;
2811     const int avg_inter_frame_qindex = rc->avg_frame_qindex[INTER_FRAME];
2812     // TODO(angiebird): figure out why arf's location is assigned this way
2813     const int gld_show_idx =
2814         VPXMIN(gf_start_show_idx + 1, fps_get_num_frames(first_pass_info));
2815     const int arf_boost =
2816         compute_arf_boost(frame_info, twopass, gld_show_idx, f_frames, b_frames,
2817                           avg_inter_frame_qindex);
2818     rc->gfu_boost = VPXMIN((int)twopass->gf_max_total_boost, arf_boost);
2819     rc->source_alt_ref_pending = 0;
2820   }
2821 
2822 #define LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR 0.2
2823   rc->arf_active_best_quality_adjustment_factor = 1.0;
2824   rc->arf_increase_active_best_quality = 0;
2825 
2826   if (!is_lossless_requested(&cpi->oxcf)) {
2827     if (rc->frames_since_key >= rc->frames_to_key) {
2828       // Increase the active best quality in the second half of key frame
2829       // interval.
2830       rc->arf_active_best_quality_adjustment_factor =
2831           LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR +
2832           (1.0 - LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR) *
2833               (rc->frames_to_key - gop_coding_frames) /
2834               (VPXMAX(1, ((rc->frames_to_key + rc->frames_since_key) / 2 -
2835                           gop_coding_frames)));
2836       rc->arf_increase_active_best_quality = 1;
2837     } else if ((rc->frames_to_key - gop_coding_frames) > 0) {
2838       // Reduce the active best quality in the first half of key frame interval.
2839       rc->arf_active_best_quality_adjustment_factor =
2840           LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR +
2841           (1.0 - LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR) *
2842               (rc->frames_since_key + gop_coding_frames) /
2843               (VPXMAX(1, (rc->frames_to_key + rc->frames_since_key) / 2 +
2844                              gop_coding_frames));
2845       rc->arf_increase_active_best_quality = -1;
2846     }
2847   }
2848 
2849 #ifdef AGGRESSIVE_VBR
2850   // Limit maximum boost based on interval length.
2851   rc->gfu_boost = VPXMIN((int)rc->gfu_boost, gop_coding_frames * 140);
2852 #else
2853   rc->gfu_boost = VPXMIN((int)rc->gfu_boost, gop_coding_frames * 200);
2854 #endif
2855 
2856   // Cap the ARF boost when perceptual quality AQ mode is enabled. This is
2857   // designed to improve the perceptual quality of high value content and to
2858   // make consistent quality across consecutive frames. It will hurt objective
2859   // quality.
2860   if (oxcf->aq_mode == PERCEPTUAL_AQ)
2861     rc->gfu_boost = VPXMIN(rc->gfu_boost, MIN_ARF_GF_BOOST);
2862 
2863   rc->baseline_gf_interval = gop_coding_frames - rc->source_alt_ref_pending;
2864 
2865   if (rc->source_alt_ref_pending)
2866     is_alt_ref_flash = detect_flash(twopass, rc->baseline_gf_interval);
2867 
2868   {
2869     const double av_err = get_distribution_av_err(cpi, twopass);
2870     const double mean_mod_score = twopass->mean_mod_score;
2871     // If the first frame is a key frame or the overlay from a previous arf then
2872     // the error score / cost of this frame has already been accounted for.
2873     int start_idx = arf_active_or_kf ? 1 : 0;
2874     int j;
2875     for (j = start_idx; j < gop_coding_frames; ++j) {
2876       int show_idx = gf_start_show_idx + j;
2877       const FIRSTPASS_STATS *frame_stats =
2878           fps_get_frame_stats(first_pass_info, show_idx);
2879       // Accumulate error score of frames in this gf group.
2880       gf_group_err += calc_norm_frame_score(oxcf, frame_info, frame_stats,
2881                                             mean_mod_score, av_err);
2882       gf_group_raw_error += frame_stats->coded_error;
2883       gf_group_noise += frame_stats->frame_noise_energy;
2884       gf_group_skip_pct += frame_stats->intra_skip_pct;
2885       gf_group_inactive_zone_rows += frame_stats->inactive_zone_rows;
2886       gf_group_inter += frame_stats->pcnt_inter;
2887       gf_group_motion += frame_stats->pcnt_motion;
2888     }
2889   }
2890 
2891   // Calculate the bits to be allocated to the gf/arf group as a whole
2892   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
2893 
2894   gop_frames =
2895       rc->baseline_gf_interval + rc->source_alt_ref_pending - arf_active_or_kf;
2896 
2897   // Store the average moise level measured for the group
2898   // TODO(any): Experiment with removal of else condition (gop_frames = 0) so
2899   // that consumption of group noise energy is based on previous gf group
2900   if (gop_frames > 0)
2901     twopass->gf_group.group_noise_energy = (int)(gf_group_noise / gop_frames);
2902   else
2903     twopass->gf_group.group_noise_energy = 0;
2904 
2905   // Calculate an estimate of the maxq needed for the group.
2906   // We are more aggressive about correcting for sections
2907   // where there could be significant overshoot than for easier
2908   // sections where we do not wish to risk creating an overshoot
2909   // of the allocated bit budget.
2910   if ((cpi->oxcf.rc_mode != VPX_Q) && (rc->baseline_gf_interval > 1)) {
2911     const int vbr_group_bits_per_frame = (int)(gf_group_bits / gop_frames);
2912     const double group_av_err = gf_group_raw_error / gop_frames;
2913     const double group_av_noise = gf_group_noise / gop_frames;
2914     const double group_av_skip_pct = gf_group_skip_pct / gop_frames;
2915     const double group_av_inactive_zone = ((gf_group_inactive_zone_rows * 2) /
2916                                            (gop_frames * (double)cm->mb_rows));
2917     int tmp_q = get_twopass_worst_quality(
2918         cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2919         group_av_noise, vbr_group_bits_per_frame);
2920     twopass->active_worst_quality =
2921         (int)((tmp_q + (twopass->active_worst_quality *
2922                         (twopass->active_wq_factor - 1))) /
2923               twopass->active_wq_factor);
2924 
2925 #if CONFIG_ALWAYS_ADJUST_BPM
2926     // Reset rolling actual and target bits counters for ARF groups.
2927     twopass->rolling_arf_group_target_bits = 0;
2928     twopass->rolling_arf_group_actual_bits = 0;
2929 #endif
2930   }
2931 
2932   // Context Adjustment of ARNR filter strength
2933   if (rc->baseline_gf_interval > 1) {
2934     adjust_group_arnr_filter(cpi, (gf_group_noise / gop_frames),
2935                              (gf_group_inter / gop_frames),
2936                              (gf_group_motion / gop_frames));
2937   } else {
2938     twopass->arnr_strength_adjustment = 0;
2939   }
2940 
2941   // Calculate the extra bits to be used for boosted frame(s)
2942   gf_arf_bits = calculate_boost_bits((rc->baseline_gf_interval - 1),
2943                                      rc->gfu_boost, gf_group_bits);
2944 
2945   // Adjust KF group bits and error remaining.
2946   twopass->kf_group_error_left -= gf_group_err;
2947 
2948   // Decide GOP structure.
2949   define_gf_group_structure(cpi);
2950 
2951   // Allocate bits to each of the frames in the GF group.
2952   allocate_gf_group_bits(cpi, gf_group_bits, gf_arf_bits);
2953 
2954   // Reset the file position.
2955   reset_fpf_position(twopass, start_pos);
2956 
2957   // Calculate a section intra ratio used in setting max loop filter.
2958   twopass->section_intra_rating = calculate_section_intra_ratio(
2959       start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
2960 
2961   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2962     // Default to starting GF groups at normal frame size.
2963     cpi->rc.next_frame_size_selector = UNSCALED;
2964   }
2965 #if !CONFIG_ALWAYS_ADJUST_BPM
2966   // Reset rolling actual and target bits counters for ARF groups.
2967   twopass->rolling_arf_group_target_bits = 0;
2968   twopass->rolling_arf_group_actual_bits = 0;
2969 #endif
2970   rc->preserve_arf_as_gld = rc->preserve_next_arf_as_gld;
2971   rc->preserve_next_arf_as_gld = 0;
2972   // If alt ref frame is flash do not set preserve_arf_as_gld
2973   if (!is_lossless_requested(&cpi->oxcf) && !cpi->use_svc &&
2974       cpi->oxcf.aq_mode == NO_AQ && cpi->multi_layer_arf && !is_alt_ref_flash)
2975     rc->preserve_next_arf_as_gld = 1;
2976 }
2977 
2978 // Intra / Inter threshold very low
2979 #define VERY_LOW_II 1.5
2980 // Clean slide transitions we expect a sharp single frame spike in error.
2981 #define ERROR_SPIKE 5.0
2982 
2983 // Slide show transition detection.
2984 // Tests for case where there is very low error either side of the current frame
2985 // but much higher just for this frame. This can help detect key frames in
2986 // slide shows even where the slides are pictures of different sizes.
2987 // Also requires that intra and inter errors are very similar to help eliminate
2988 // harmful false positives.
2989 // It will not help if the transition is a fade or other multi-frame effect.
slide_transition(const FIRSTPASS_STATS * this_frame,const FIRSTPASS_STATS * last_frame,const FIRSTPASS_STATS * next_frame)2990 static int slide_transition(const FIRSTPASS_STATS *this_frame,
2991                             const FIRSTPASS_STATS *last_frame,
2992                             const FIRSTPASS_STATS *next_frame) {
2993   return (this_frame->intra_error < (this_frame->coded_error * VERY_LOW_II)) &&
2994          (this_frame->coded_error > (last_frame->coded_error * ERROR_SPIKE)) &&
2995          (this_frame->coded_error > (next_frame->coded_error * ERROR_SPIKE));
2996 }
2997 
2998 // This test looks for anomalous changes in the nature of the intra signal
2999 // related to the previous and next frame as an indicator for coding a key
3000 // frame. This test serves to detect some additional scene cuts,
3001 // especially in lowish motion and low contrast sections, that are missed
3002 // by the other tests.
intra_step_transition(const FIRSTPASS_STATS * this_frame,const FIRSTPASS_STATS * last_frame,const FIRSTPASS_STATS * next_frame)3003 static int intra_step_transition(const FIRSTPASS_STATS *this_frame,
3004                                  const FIRSTPASS_STATS *last_frame,
3005                                  const FIRSTPASS_STATS *next_frame) {
3006   double last_ii_ratio;
3007   double this_ii_ratio;
3008   double next_ii_ratio;
3009   double last_pcnt_intra = 1.0 - last_frame->pcnt_inter;
3010   double this_pcnt_intra = 1.0 - this_frame->pcnt_inter;
3011   double next_pcnt_intra = 1.0 - next_frame->pcnt_inter;
3012   double mod_this_intra = this_pcnt_intra + this_frame->pcnt_neutral;
3013 
3014   // Calculate ii ratio for this frame last frame and next frame.
3015   last_ii_ratio =
3016       last_frame->intra_error / DOUBLE_DIVIDE_CHECK(last_frame->coded_error);
3017   this_ii_ratio =
3018       this_frame->intra_error / DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
3019   next_ii_ratio =
3020       next_frame->intra_error / DOUBLE_DIVIDE_CHECK(next_frame->coded_error);
3021 
3022   // Return true the intra/inter ratio for the current frame is
3023   // low but better in the next and previous frame and the relative useage of
3024   // intra in the current frame is markedly higher than the last and next frame.
3025   if ((this_ii_ratio < 2.0) && (last_ii_ratio > 2.25) &&
3026       (next_ii_ratio > 2.25) && (this_pcnt_intra > (3 * last_pcnt_intra)) &&
3027       (this_pcnt_intra > (3 * next_pcnt_intra)) &&
3028       ((this_pcnt_intra > 0.075) || (mod_this_intra > 0.85))) {
3029     return 1;
3030     // Very low inter intra ratio (i.e. not much gain from inter coding), most
3031     // blocks neutral on coding method and better inter prediction either side
3032   } else if ((this_ii_ratio < 1.25) && (mod_this_intra > 0.85) &&
3033              (this_ii_ratio < last_ii_ratio * 0.9) &&
3034              (this_ii_ratio < next_ii_ratio * 0.9)) {
3035     return 1;
3036   } else {
3037     return 0;
3038   }
3039 }
3040 
3041 // Minimum % intra coding observed in first pass (1.0 = 100%)
3042 #define MIN_INTRA_LEVEL 0.25
3043 // Threshold for use of the lagging second reference frame. Scene cuts do not
3044 // usually have a high second ref useage.
3045 #define SECOND_REF_USEAGE_THRESH 0.2
3046 // Hard threshold where the first pass chooses intra for almost all blocks.
3047 // In such a case even if the frame is not a scene cut coding a key frame
3048 // may be a good option.
3049 #define VERY_LOW_INTER_THRESH 0.05
3050 // Maximum threshold for the relative ratio of intra error score vs best
3051 // inter error score.
3052 #define KF_II_ERR_THRESHOLD 2.5
3053 #define KF_II_MAX 128.0
3054 #define II_FACTOR 12.5
3055 // Test for very low intra complexity which could cause false key frames
3056 #define V_LOW_INTRA 0.5
3057 
test_candidate_kf(const FIRST_PASS_INFO * first_pass_info,int show_idx)3058 static int test_candidate_kf(const FIRST_PASS_INFO *first_pass_info,
3059                              int show_idx) {
3060   const FIRSTPASS_STATS *last_frame =
3061       fps_get_frame_stats(first_pass_info, show_idx - 1);
3062   const FIRSTPASS_STATS *this_frame =
3063       fps_get_frame_stats(first_pass_info, show_idx);
3064   const FIRSTPASS_STATS *next_frame =
3065       fps_get_frame_stats(first_pass_info, show_idx + 1);
3066   int is_viable_kf = 0;
3067   double pcnt_intra = 1.0 - this_frame->pcnt_inter;
3068 
3069   // Does the frame satisfy the primary criteria of a key frame?
3070   // See above for an explanation of the test criteria.
3071   // If so, then examine how well it predicts subsequent frames.
3072   detect_flash_from_frame_stats(next_frame);
3073   if (!detect_flash_from_frame_stats(this_frame) &&
3074       !detect_flash_from_frame_stats(next_frame) &&
3075       (this_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
3076       ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
3077        (slide_transition(this_frame, last_frame, next_frame)) ||
3078        (intra_step_transition(this_frame, last_frame, next_frame)) ||
3079        (((this_frame->coded_error > (next_frame->coded_error * 1.2)) &&
3080          (this_frame->coded_error > (last_frame->coded_error * 1.2))) &&
3081         (pcnt_intra > MIN_INTRA_LEVEL) &&
3082         ((pcnt_intra + this_frame->pcnt_neutral) > 0.5) &&
3083         ((this_frame->intra_error /
3084           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
3085          KF_II_ERR_THRESHOLD)))) {
3086     int i;
3087     double boost_score = 0.0;
3088     double old_boost_score = 0.0;
3089     double decay_accumulator = 1.0;
3090 
3091     // Examine how well the key frame predicts subsequent frames.
3092     for (i = 0; i < 16; ++i) {
3093       const FIRSTPASS_STATS *frame_stats =
3094           fps_get_frame_stats(first_pass_info, show_idx + 1 + i);
3095       double next_iiratio = (II_FACTOR * frame_stats->intra_error /
3096                              DOUBLE_DIVIDE_CHECK(frame_stats->coded_error));
3097 
3098       if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
3099 
3100       // Cumulative effect of decay in prediction quality.
3101       if (frame_stats->pcnt_inter > 0.85)
3102         decay_accumulator *= frame_stats->pcnt_inter;
3103       else
3104         decay_accumulator *= (0.85 + frame_stats->pcnt_inter) / 2.0;
3105 
3106       // Keep a running total.
3107       boost_score += (decay_accumulator * next_iiratio);
3108 
3109       // Test various breakout clauses.
3110       if ((frame_stats->pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
3111           (((frame_stats->pcnt_inter - frame_stats->pcnt_neutral) < 0.20) &&
3112            (next_iiratio < 3.0)) ||
3113           ((boost_score - old_boost_score) < 3.0) ||
3114           (frame_stats->intra_error < V_LOW_INTRA)) {
3115         break;
3116       }
3117 
3118       old_boost_score = boost_score;
3119 
3120       // Get the next frame details
3121       if (show_idx + 1 + i == fps_get_num_frames(first_pass_info) - 1) break;
3122     }
3123 
3124     // If there is tolerable prediction for at least the next 3 frames then
3125     // break out else discard this potential key frame and move on
3126     if (boost_score > 30.0 && (i > 3)) {
3127       is_viable_kf = 1;
3128     } else {
3129       is_viable_kf = 0;
3130     }
3131   }
3132 
3133   return is_viable_kf;
3134 }
3135 
3136 #define FRAMES_TO_CHECK_DECAY 8
3137 #define MIN_KF_TOT_BOOST 300
3138 #define DEFAULT_SCAN_FRAMES_FOR_KF_BOOST 32
3139 #define MAX_SCAN_FRAMES_FOR_KF_BOOST 48
3140 #define MIN_SCAN_FRAMES_FOR_KF_BOOST 32
3141 #define KF_ABS_ZOOM_THRESH 6.0
3142 
vp9_get_frames_to_next_key(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,int kf_show_idx,int min_gf_interval)3143 int vp9_get_frames_to_next_key(const VP9EncoderConfig *oxcf,
3144                                const TWO_PASS *const twopass, int kf_show_idx,
3145                                int min_gf_interval) {
3146   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3147   double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
3148   int j;
3149   int frames_to_key;
3150   int max_frames_to_key = first_pass_info->num_frames - kf_show_idx;
3151   max_frames_to_key = VPXMIN(max_frames_to_key, oxcf->key_freq);
3152 
3153   // Initialize the decay rates for the recent frames to check
3154   for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
3155   // Find the next keyframe.
3156   if (!oxcf->auto_key) {
3157     frames_to_key = max_frames_to_key;
3158   } else {
3159     frames_to_key = 1;
3160     while (frames_to_key < max_frames_to_key) {
3161       // Provided that we are not at the end of the file...
3162       if (kf_show_idx + frames_to_key + 1 < first_pass_info->num_frames) {
3163         double loop_decay_rate;
3164         double decay_accumulator;
3165         const FIRSTPASS_STATS *next_frame = fps_get_frame_stats(
3166             first_pass_info, kf_show_idx + frames_to_key + 1);
3167 
3168         // Check for a scene cut.
3169         if (test_candidate_kf(first_pass_info, kf_show_idx + frames_to_key))
3170           break;
3171 
3172         // How fast is the prediction quality decaying?
3173         loop_decay_rate = get_prediction_decay_rate(twopass, next_frame);
3174 
3175         // We want to know something about the recent past... rather than
3176         // as used elsewhere where we are concerned with decay in prediction
3177         // quality since the last GF or KF.
3178         recent_loop_decay[(frames_to_key - 1) % FRAMES_TO_CHECK_DECAY] =
3179             loop_decay_rate;
3180         decay_accumulator = 1.0;
3181         for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
3182           decay_accumulator *= recent_loop_decay[j];
3183 
3184         // Special check for transition or high motion followed by a
3185         // static scene.
3186         if ((frames_to_key - 1) > min_gf_interval && loop_decay_rate >= 0.999 &&
3187             decay_accumulator < 0.9) {
3188           int still_interval = oxcf->key_freq - (frames_to_key - 1);
3189           // TODO(angiebird): Figure out why we use "+1" here
3190           int show_idx = kf_show_idx + frames_to_key;
3191           if (check_transition_to_still(first_pass_info, show_idx,
3192                                         still_interval)) {
3193             break;
3194           }
3195         }
3196       }
3197       ++frames_to_key;
3198     }
3199   }
3200   return frames_to_key;
3201 }
3202 
find_next_key_frame(VP9_COMP * cpi,int kf_show_idx)3203 static void find_next_key_frame(VP9_COMP *cpi, int kf_show_idx) {
3204   int i;
3205   RATE_CONTROL *const rc = &cpi->rc;
3206   TWO_PASS *const twopass = &cpi->twopass;
3207   GF_GROUP *const gf_group = &twopass->gf_group;
3208   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3209   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3210   const FRAME_INFO *frame_info = &cpi->frame_info;
3211   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
3212   const FIRSTPASS_STATS *keyframe_stats =
3213       fps_get_frame_stats(first_pass_info, kf_show_idx);
3214   FIRSTPASS_STATS next_frame;
3215   int kf_bits = 0;
3216   int64_t max_kf_bits;
3217   double zero_motion_accumulator = 1.0;
3218   double zero_motion_sum = 0.0;
3219   double zero_motion_avg;
3220   double motion_compensable_sum = 0.0;
3221   double motion_compensable_avg;
3222   int num_frames = 0;
3223   int kf_boost_scan_frames = DEFAULT_SCAN_FRAMES_FOR_KF_BOOST;
3224   double boost_score = 0.0;
3225   double kf_mod_err = 0.0;
3226   double kf_raw_err = 0.0;
3227   double kf_group_err = 0.0;
3228   double sr_accumulator = 0.0;
3229   double abs_mv_in_out_accumulator = 0.0;
3230   const double av_err = get_distribution_av_err(cpi, twopass);
3231   const double mean_mod_score = twopass->mean_mod_score;
3232   vp9_zero(next_frame);
3233 
3234   cpi->common.frame_type = KEY_FRAME;
3235   rc->frames_since_key = 0;
3236 
3237   // Reset the GF group data structures.
3238   vp9_zero(*gf_group);
3239 
3240   // Is this a forced key frame by interval.
3241   rc->this_key_frame_forced = rc->next_key_frame_forced;
3242 
3243   // Clear the alt ref active flag and last group multi arf flags as they
3244   // can never be set for a key frame.
3245   rc->source_alt_ref_active = 0;
3246 
3247   // KF is always a GF so clear frames till next gf counter.
3248   rc->frames_till_gf_update_due = 0;
3249 
3250   rc->frames_to_key = 1;
3251 
3252   twopass->kf_group_bits = 0;          // Total bits available to kf group
3253   twopass->kf_group_error_left = 0.0;  // Group modified error score.
3254 
3255   kf_raw_err = keyframe_stats->intra_error;
3256   kf_mod_err = calc_norm_frame_score(oxcf, frame_info, keyframe_stats,
3257                                      mean_mod_score, av_err);
3258 
3259   rc->frames_to_key = vp9_get_frames_to_next_key(oxcf, twopass, kf_show_idx,
3260                                                  rc->min_gf_interval);
3261 
3262   // If there is a max kf interval set by the user we must obey it.
3263   // We already breakout of the loop above at 2x max.
3264   // This code centers the extra kf if the actual natural interval
3265   // is between 1x and 2x.
3266   if (rc->frames_to_key >= cpi->oxcf.key_freq) {
3267     rc->next_key_frame_forced = 1;
3268   } else {
3269     rc->next_key_frame_forced = 0;
3270   }
3271 
3272   for (i = 0; i < rc->frames_to_key; ++i) {
3273     const FIRSTPASS_STATS *frame_stats =
3274         fps_get_frame_stats(first_pass_info, kf_show_idx + i);
3275     // Accumulate kf group error.
3276     kf_group_err += calc_norm_frame_score(oxcf, frame_info, frame_stats,
3277                                           mean_mod_score, av_err);
3278   }
3279 
3280   // Calculate the number of bits that should be assigned to the kf group.
3281   if (twopass->bits_left > 0 && twopass->normalized_score_left > 0.0) {
3282     // Maximum number of bits for a single normal frame (not key frame).
3283     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
3284 
3285     // Maximum number of bits allocated to the key frame group.
3286     int64_t max_grp_bits;
3287 
3288     // Default allocation based on bits left and relative
3289     // complexity of the section.
3290     twopass->kf_group_bits = (int64_t)(
3291         twopass->bits_left * (kf_group_err / twopass->normalized_score_left));
3292 
3293     // Clip based on maximum per frame rate defined by the user.
3294     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
3295     if (twopass->kf_group_bits > max_grp_bits)
3296       twopass->kf_group_bits = max_grp_bits;
3297   } else {
3298     twopass->kf_group_bits = 0;
3299   }
3300   twopass->kf_group_bits = VPXMAX(0, twopass->kf_group_bits);
3301 
3302   // Scan through the kf group collating various stats used to determine
3303   // how many bits to spend on it.
3304   boost_score = 0.0;
3305 
3306   for (i = 0; i < VPXMIN(MAX_SCAN_FRAMES_FOR_KF_BOOST, (rc->frames_to_key - 1));
3307        ++i) {
3308     if (EOF == input_stats(twopass, &next_frame)) break;
3309 
3310     zero_motion_sum += next_frame.pcnt_inter - next_frame.pcnt_motion;
3311     motion_compensable_sum +=
3312         1 - (double)next_frame.coded_error / next_frame.intra_error;
3313     num_frames++;
3314   }
3315 
3316   if (num_frames >= MIN_SCAN_FRAMES_FOR_KF_BOOST) {
3317     zero_motion_avg = zero_motion_sum / num_frames;
3318     motion_compensable_avg = motion_compensable_sum / num_frames;
3319     kf_boost_scan_frames = (int)(VPXMAX(64 * zero_motion_avg - 16,
3320                                         160 * motion_compensable_avg - 112));
3321     kf_boost_scan_frames =
3322         VPXMAX(VPXMIN(kf_boost_scan_frames, MAX_SCAN_FRAMES_FOR_KF_BOOST),
3323                MIN_SCAN_FRAMES_FOR_KF_BOOST);
3324   }
3325   reset_fpf_position(twopass, start_position);
3326 
3327   for (i = 0; i < (rc->frames_to_key - 1); ++i) {
3328     if (EOF == input_stats(twopass, &next_frame)) break;
3329 
3330     // The zero motion test here insures that if we mark a kf group as static
3331     // it is static throughout not just the first KF_BOOST_SCAN_MAX_FRAMES.
3332     // It also allows for a larger boost on long static groups.
3333     if ((i <= kf_boost_scan_frames) || (zero_motion_accumulator >= 0.99)) {
3334       double frame_boost;
3335       double zm_factor;
3336 
3337       // Monitor for static sections.
3338       // First frame in kf group the second ref indicator is invalid.
3339       if (i > 0) {
3340         zero_motion_accumulator =
3341             VPXMIN(zero_motion_accumulator,
3342                    get_zero_motion_factor(twopass, &next_frame));
3343       } else {
3344         zero_motion_accumulator =
3345             next_frame.pcnt_inter - next_frame.pcnt_motion;
3346       }
3347 
3348       // Factor 0.75-1.25 based on how much of frame is static.
3349       zm_factor = (0.75 + (zero_motion_accumulator / 2.0));
3350 
3351       // The second (lagging) ref error is not valid immediately after
3352       // a key frame because either the lag has not built up (in the case of
3353       // the first key frame or it points to a refernce before the new key
3354       // frame.
3355       if (i < 2) sr_accumulator = 0.0;
3356       frame_boost =
3357           calc_kf_frame_boost(cpi, &next_frame, &sr_accumulator, 0, zm_factor);
3358 
3359       boost_score += frame_boost;
3360 
3361       // Measure of zoom. Large zoom tends to indicate reduced boost.
3362       abs_mv_in_out_accumulator +=
3363           fabs(next_frame.mv_in_out_count * next_frame.pcnt_motion);
3364 
3365       if ((frame_boost < 25.00) ||
3366           (abs_mv_in_out_accumulator > KF_ABS_ZOOM_THRESH) ||
3367           (sr_accumulator > (kf_raw_err * 1.50)))
3368         break;
3369     } else {
3370       break;
3371     }
3372   }
3373 
3374   reset_fpf_position(twopass, start_position);
3375 
3376   // Store the zero motion percentage
3377   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
3378 
3379   // Calculate a section intra ratio used in setting max loop filter.
3380   twopass->key_frame_section_intra_rating = calculate_section_intra_ratio(
3381       start_position, twopass->stats_in_end, rc->frames_to_key);
3382 
3383   // Special case for static / slide show content but dont apply
3384   // if the kf group is very short.
3385   if ((zero_motion_accumulator > 0.99) && (rc->frames_to_key > 8)) {
3386     rc->kf_boost = (int)(twopass->kf_max_total_boost);
3387   } else {
3388     // Apply various clamps for min and max oost
3389     rc->kf_boost = VPXMAX((int)boost_score, (rc->frames_to_key * 3));
3390     rc->kf_boost = VPXMAX(rc->kf_boost, MIN_KF_TOT_BOOST);
3391     rc->kf_boost = VPXMIN(rc->kf_boost, (int)(twopass->kf_max_total_boost));
3392   }
3393 
3394   // Work out how many bits to allocate for the key frame itself.
3395   kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
3396                                  twopass->kf_group_bits);
3397   // Based on the spatial complexity, increase the bits allocated to key frame.
3398   kf_bits +=
3399       (int)((twopass->kf_group_bits - kf_bits) * (kf_mod_err / kf_group_err));
3400   max_kf_bits =
3401       twopass->kf_group_bits - (rc->frames_to_key - 1) * FRAME_OVERHEAD_BITS;
3402   max_kf_bits = lclamp(max_kf_bits, 0, INT_MAX);
3403   kf_bits = VPXMIN(kf_bits, (int)max_kf_bits);
3404 
3405   twopass->kf_group_bits -= kf_bits;
3406 
3407   // Save the bits to spend on the key frame.
3408   gf_group->bit_allocation[0] = kf_bits;
3409   gf_group->update_type[0] = KF_UPDATE;
3410   gf_group->rf_level[0] = KF_STD;
3411   gf_group->layer_depth[0] = 0;
3412 
3413   // Note the total error score of the kf group minus the key frame itself.
3414   twopass->kf_group_error_left = (kf_group_err - kf_mod_err);
3415 
3416   // Adjust the count of total modified error left.
3417   // The count of bits left is adjusted elsewhere based on real coded frame
3418   // sizes.
3419   twopass->normalized_score_left -= kf_group_err;
3420 
3421   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
3422     // Default to normal-sized frame on keyframes.
3423     cpi->rc.next_frame_size_selector = UNSCALED;
3424   }
3425 }
3426 
3427 // Configure image size specific vizier parameters.
3428 // Later these will be set via additional command line options
vp9_init_vizier_params(TWO_PASS * const twopass,int screen_area)3429 void vp9_init_vizier_params(TWO_PASS *const twopass, int screen_area) {
3430   // When |use_vizier_rc_params| is 1, we expect the rc parameters below to
3431   // have been initialised on the command line as adjustment factors such
3432   // that a factor of 1.0 will match the default behavior when
3433   // |use_vizier_rc_params| is 0
3434   if (twopass->use_vizier_rc_params) {
3435     twopass->active_wq_factor *= AV_WQ_FACTOR;
3436     twopass->err_per_mb *= BASELINE_ERR_PER_MB;
3437     twopass->sr_default_decay_limit *= DEFAULT_DECAY_LIMIT;
3438     if (twopass->sr_default_decay_limit > 1.0)  // > 1.0 here makes no sense
3439       twopass->sr_default_decay_limit = 1.0;
3440     twopass->sr_diff_factor *= 1.0;
3441     twopass->gf_frame_max_boost *= GF_MAX_FRAME_BOOST;
3442     twopass->gf_max_total_boost *= MAX_GF_BOOST;
3443     // NOTE: In use max boost has precedence over min boost. So even if min is
3444     // somehow set higher than max the final boost value will be clamped to the
3445     // appropriate maximum.
3446     twopass->kf_frame_min_boost *= KF_MIN_FRAME_BOOST;
3447     twopass->kf_frame_max_boost_first *= KF_MAX_FRAME_BOOST;
3448     twopass->kf_frame_max_boost_subs *= KF_MAX_FRAME_BOOST;
3449     twopass->kf_max_total_boost *= MAX_KF_TOT_BOOST;
3450     twopass->zm_factor *= DEFAULT_ZM_FACTOR;
3451     if (twopass->zm_factor > 1.0)  // > 1.0 here makes no sense
3452       twopass->zm_factor = 1.0;
3453 
3454     // Correction for the fact that the kf_err_per_mb_factor default is
3455     // already different for different video formats and ensures that a passed
3456     // in value of 1.0 on the vizier command line will still match the current
3457     // default.
3458     if (screen_area < 1280 * 720) {
3459       twopass->kf_err_per_mb *= 2000.0;
3460     } else if (screen_area < 1920 * 1080) {
3461       twopass->kf_err_per_mb *= 500.0;
3462     } else {
3463       twopass->kf_err_per_mb *= 250.0;
3464     }
3465   } else {
3466     // When |use_vizier_rc_params| is 0, use defaults.
3467     twopass->active_wq_factor = AV_WQ_FACTOR;
3468     twopass->err_per_mb = BASELINE_ERR_PER_MB;
3469     twopass->sr_default_decay_limit = DEFAULT_DECAY_LIMIT;
3470     twopass->sr_diff_factor = 1.0;
3471     twopass->gf_frame_max_boost = GF_MAX_FRAME_BOOST;
3472     twopass->gf_max_total_boost = MAX_GF_BOOST;
3473     twopass->kf_frame_min_boost = KF_MIN_FRAME_BOOST;
3474     twopass->kf_frame_max_boost_first = KF_MAX_FRAME_BOOST;
3475     twopass->kf_frame_max_boost_subs = KF_MAX_FRAME_BOOST;
3476     twopass->kf_max_total_boost = MAX_KF_TOT_BOOST;
3477     twopass->zm_factor = DEFAULT_ZM_FACTOR;
3478 
3479     if (screen_area < 1280 * 720) {
3480       twopass->kf_err_per_mb = 2000.0;
3481     } else if (screen_area < 1920 * 1080) {
3482       twopass->kf_err_per_mb = 500.0;
3483     } else {
3484       twopass->kf_err_per_mb = 250.0;
3485     }
3486   }
3487 }
3488 
vp9_rc_get_second_pass_params(VP9_COMP * cpi)3489 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
3490   VP9_COMMON *const cm = &cpi->common;
3491   RATE_CONTROL *const rc = &cpi->rc;
3492   TWO_PASS *const twopass = &cpi->twopass;
3493   GF_GROUP *const gf_group = &twopass->gf_group;
3494   FIRSTPASS_STATS this_frame;
3495   const int show_idx = cm->current_video_frame;
3496 
3497   if (cpi->common.current_frame_coding_index == 0) {
3498     VP9_COMMON *cm = &cpi->common;
3499     const vpx_codec_err_t codec_status = vp9_extrc_send_firstpass_stats(
3500         &cpi->ext_ratectrl, &cpi->twopass.first_pass_info);
3501     if (codec_status != VPX_CODEC_OK) {
3502       vpx_internal_error(&cm->error, codec_status,
3503                          "vp9_extrc_send_firstpass_stats() failed");
3504     }
3505   }
3506 
3507   if (!twopass->stats_in) return;
3508 
3509   // Configure image size specific vizier parameters
3510   if (cm->current_video_frame == 0) {
3511     unsigned int screen_area = (cm->width * cm->height);
3512 
3513     vp9_init_vizier_params(twopass, screen_area);
3514   }
3515 
3516   // If this is an arf frame then we dont want to read the stats file or
3517   // advance the input pointer as we already have what we need.
3518   if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
3519     int target_rate;
3520 
3521     vp9_zero(this_frame);
3522     this_frame =
3523         cpi->twopass.stats_in_start[cm->current_video_frame +
3524                                     gf_group->arf_src_offset[gf_group->index]];
3525 
3526     vp9_configure_buffer_updates(cpi, gf_group->index);
3527 
3528     target_rate = gf_group->bit_allocation[gf_group->index];
3529     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
3530     rc->base_frame_target = target_rate;
3531 
3532     cm->frame_type = INTER_FRAME;
3533 
3534     // The multiplication by 256 reverses a scaling factor of (>> 8)
3535     // applied when combining MB error values for the frame.
3536     twopass->mb_av_energy = log((this_frame.intra_error * 256.0) + 1.0);
3537     twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
3538 
3539     return;
3540   }
3541 
3542   vpx_clear_system_state();
3543 
3544   if (cpi->oxcf.rc_mode == VPX_Q) {
3545     twopass->active_worst_quality = cpi->oxcf.cq_level;
3546   } else if (cm->current_video_frame == 0) {
3547     const int frames_left =
3548         (int)(twopass->total_stats.count - cm->current_video_frame);
3549     // Special case code for first frame.
3550     const int section_target_bandwidth =
3551         (int)(twopass->bits_left / frames_left);
3552     const double section_length = twopass->total_left_stats.count;
3553     const double section_error =
3554         twopass->total_left_stats.coded_error / section_length;
3555     const double section_intra_skip =
3556         twopass->total_left_stats.intra_skip_pct / section_length;
3557     const double section_inactive_zone =
3558         (twopass->total_left_stats.inactive_zone_rows * 2) /
3559         ((double)cm->mb_rows * section_length);
3560     const double section_noise =
3561         twopass->total_left_stats.frame_noise_energy / section_length;
3562     int tmp_q;
3563 
3564     tmp_q = get_twopass_worst_quality(
3565         cpi, section_error, section_intra_skip + section_inactive_zone,
3566         section_noise, section_target_bandwidth);
3567 
3568     twopass->active_worst_quality = tmp_q;
3569     twopass->baseline_active_worst_quality = tmp_q;
3570     rc->ni_av_qi = tmp_q;
3571     rc->last_q[INTER_FRAME] = tmp_q;
3572     rc->avg_q = vp9_convert_qindex_to_q(tmp_q, cm->bit_depth);
3573     rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
3574     rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
3575     rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
3576   }
3577   vp9_zero(this_frame);
3578   if (EOF == input_stats(twopass, &this_frame)) return;
3579 
3580   // Set the frame content type flag.
3581   if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
3582     twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
3583   else
3584     twopass->fr_content_type = FC_NORMAL;
3585 
3586   // Keyframe and section processing.
3587   if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
3588     // Define next KF group and assign bits to it.
3589     find_next_key_frame(cpi, show_idx);
3590   } else {
3591     cm->frame_type = INTER_FRAME;
3592   }
3593 
3594   // Define a new GF/ARF group. (Should always enter here for key frames).
3595   if (rc->frames_till_gf_update_due == 0) {
3596     define_gf_group(cpi, show_idx);
3597 
3598     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3599 
3600 #if ARF_STATS_OUTPUT
3601     {
3602       FILE *fpfile;
3603       fpfile = fopen("arf.stt", "a");
3604       ++arf_count;
3605       fprintf(fpfile, "%10d %10ld %10d %10d %10ld %10ld\n",
3606               cm->current_video_frame, rc->frames_till_gf_update_due,
3607               rc->kf_boost, arf_count, rc->gfu_boost, cm->frame_type);
3608 
3609       fclose(fpfile);
3610     }
3611 #endif
3612   }
3613 
3614   vp9_configure_buffer_updates(cpi, gf_group->index);
3615 
3616   rc->base_frame_target = gf_group->bit_allocation[gf_group->index];
3617 
3618   // The multiplication by 256 reverses a scaling factor of (>> 8)
3619   // applied when combining MB error values for the frame.
3620   twopass->mb_av_energy = log((this_frame.intra_error * 256.0) + 1.0);
3621   twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
3622 
3623   // Update the total stats remaining structure.
3624   subtract_stats(&twopass->total_left_stats, &this_frame);
3625 }
3626 
vp9_twopass_postencode_update(VP9_COMP * cpi)3627 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
3628   TWO_PASS *const twopass = &cpi->twopass;
3629   RATE_CONTROL *const rc = &cpi->rc;
3630   VP9_COMMON *const cm = &cpi->common;
3631   const int bits_used = rc->base_frame_target;
3632 
3633   // VBR correction is done through rc->vbr_bits_off_target. Based on the
3634   // sign of this value, a limited % adjustment is made to the target rate
3635   // of subsequent frames, to try and push it back towards 0. This method
3636   // is designed to prevent extreme behaviour at the end of a clip
3637   // or group of frames.
3638   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
3639   twopass->bits_left = VPXMAX(twopass->bits_left - bits_used, 0);
3640 
3641   // Target vs actual bits for this arf group.
3642   twopass->rolling_arf_group_target_bits += rc->this_frame_target;
3643   twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
3644 
3645   // Calculate the pct rc error.
3646   if (rc->total_actual_bits) {
3647     rc->rate_error_estimate =
3648         (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
3649     rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
3650   } else {
3651     rc->rate_error_estimate = 0;
3652   }
3653 
3654   if (cpi->common.frame_type != KEY_FRAME) {
3655     twopass->kf_group_bits -= bits_used;
3656     twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
3657   }
3658   twopass->kf_group_bits = VPXMAX(twopass->kf_group_bits, 0);
3659 
3660   // Increment the gf group index ready for the next frame.
3661   ++twopass->gf_group.index;
3662 
3663   // If the rate control is drifting consider adjustment to min or maxq.
3664   if ((cpi->oxcf.rc_mode != VPX_Q) && !cpi->rc.is_src_frame_alt_ref) {
3665     const int maxq_adj_limit =
3666         rc->worst_quality - twopass->active_worst_quality;
3667     const int minq_adj_limit =
3668         (cpi->oxcf.rc_mode == VPX_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
3669     int aq_extend_min = 0;
3670     int aq_extend_max = 0;
3671 
3672     // Extend min or Max Q range to account for imbalance from the base
3673     // value when using AQ.
3674     if (cpi->oxcf.aq_mode != NO_AQ && cpi->oxcf.aq_mode != PSNR_AQ &&
3675         cpi->oxcf.aq_mode != PERCEPTUAL_AQ) {
3676       if (cm->seg.aq_av_offset < 0) {
3677         // The balance of the AQ map tends towarda lowering the average Q.
3678         aq_extend_min = 0;
3679         aq_extend_max = VPXMIN(maxq_adj_limit, -cm->seg.aq_av_offset);
3680       } else {
3681         // The balance of the AQ map tends towards raising the average Q.
3682         aq_extend_min = VPXMIN(minq_adj_limit, cm->seg.aq_av_offset);
3683         aq_extend_max = 0;
3684       }
3685     }
3686 
3687     // Undershoot.
3688     if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
3689       --twopass->extend_maxq;
3690       if (rc->rolling_target_bits >= rc->rolling_actual_bits)
3691         ++twopass->extend_minq;
3692       // Overshoot.
3693     } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
3694       --twopass->extend_minq;
3695       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3696         ++twopass->extend_maxq;
3697     } else {
3698       // Adjustment for extreme local overshoot.
3699       if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
3700           rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
3701         ++twopass->extend_maxq;
3702 
3703       // Unwind undershoot or overshoot adjustment.
3704       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3705         --twopass->extend_minq;
3706       else if (rc->rolling_target_bits > rc->rolling_actual_bits)
3707         --twopass->extend_maxq;
3708     }
3709 
3710     twopass->extend_minq =
3711         clamp(twopass->extend_minq, aq_extend_min, minq_adj_limit);
3712     twopass->extend_maxq =
3713         clamp(twopass->extend_maxq, aq_extend_max, maxq_adj_limit);
3714 
3715     // If there is a big and undexpected undershoot then feed the extra
3716     // bits back in quickly. One situation where this may happen is if a
3717     // frame is unexpectedly almost perfectly predicted by the ARF or GF
3718     // but not very well predcited by the previous frame.
3719     if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
3720       int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
3721       if (rc->projected_frame_size < fast_extra_thresh) {
3722         rc->vbr_bits_off_target_fast +=
3723             fast_extra_thresh - rc->projected_frame_size;
3724         rc->vbr_bits_off_target_fast =
3725             VPXMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
3726 
3727         // Fast adaptation of minQ if necessary to use up the extra bits.
3728         if (rc->avg_frame_bandwidth) {
3729           twopass->extend_minq_fast =
3730               (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
3731         }
3732         twopass->extend_minq_fast = VPXMIN(
3733             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3734       } else if (rc->vbr_bits_off_target_fast) {
3735         twopass->extend_minq_fast = VPXMIN(
3736             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3737       } else {
3738         twopass->extend_minq_fast = 0;
3739       }
3740     }
3741   }
3742 }
3743 
3744 #if CONFIG_RATE_CTRL
vp9_get_next_group_of_picture(const VP9_COMP * cpi,int * first_is_key_frame,int * use_alt_ref,int * coding_frame_count,int * first_show_idx,int * last_gop_use_alt_ref)3745 void vp9_get_next_group_of_picture(const VP9_COMP *cpi, int *first_is_key_frame,
3746                                    int *use_alt_ref, int *coding_frame_count,
3747                                    int *first_show_idx,
3748                                    int *last_gop_use_alt_ref) {
3749   const GOP_COMMAND *gop_command = &cpi->encode_command.gop_command;
3750   // We make a copy of rc here because we want to get information from the
3751   // encoder without changing its state.
3752   // TODO(angiebird): Avoid copying rc here.
3753   RATE_CONTROL rc = cpi->rc;
3754   const int multi_layer_arf = 0;
3755   const int allow_alt_ref = 1;
3756   // We assume that current_video_frame is updated to the show index of the
3757   // frame we are about to called. Note that current_video_frame is updated at
3758   // the end of encode_frame_to_data_rate().
3759   // TODO(angiebird): Avoid this kind of fragile style.
3760   *first_show_idx = cpi->common.current_video_frame;
3761   *last_gop_use_alt_ref = rc.source_alt_ref_active;
3762 
3763   *first_is_key_frame = 0;
3764   if (rc.frames_to_key == 0) {
3765     rc.frames_to_key = vp9_get_frames_to_next_key(
3766         &cpi->oxcf, &cpi->twopass, *first_show_idx, rc.min_gf_interval);
3767     rc.frames_since_key = 0;
3768     *first_is_key_frame = 1;
3769   }
3770 
3771   if (gop_command->use) {
3772     *coding_frame_count = gop_command_coding_frame_count(gop_command);
3773     *use_alt_ref = gop_command->use_alt_ref;
3774     assert(gop_command->show_frame_count <= rc.frames_to_key);
3775   } else {
3776     *coding_frame_count = vp9_get_gop_coding_frame_count(
3777         &cpi->oxcf, &cpi->twopass, &cpi->frame_info, &rc, *first_show_idx,
3778         multi_layer_arf, allow_alt_ref, *first_is_key_frame,
3779         *last_gop_use_alt_ref, use_alt_ref);
3780   }
3781 }
3782 
vp9_get_gop_coding_frame_count(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,const FRAME_INFO * frame_info,const RATE_CONTROL * rc,int show_idx,int multi_layer_arf,int allow_alt_ref,int first_is_key_frame,int last_gop_use_alt_ref,int * use_alt_ref)3783 int vp9_get_gop_coding_frame_count(const VP9EncoderConfig *oxcf,
3784                                    const TWO_PASS *const twopass,
3785                                    const FRAME_INFO *frame_info,
3786                                    const RATE_CONTROL *rc, int show_idx,
3787                                    int multi_layer_arf, int allow_alt_ref,
3788                                    int first_is_key_frame,
3789                                    int last_gop_use_alt_ref, int *use_alt_ref) {
3790   int frame_count;
3791   double gop_intra_factor;
3792   const int arf_active_or_kf = last_gop_use_alt_ref || first_is_key_frame;
3793   RANGE active_gf_interval;
3794   int arf_layers;
3795   if (oxcf->use_simple_encode_api) {
3796     active_gf_interval = get_active_gf_inverval_range_simple(
3797         rc->min_gf_interval, arf_active_or_kf, rc->frames_to_key);
3798   } else {
3799     active_gf_interval = get_active_gf_inverval_range(
3800         frame_info, rc, arf_active_or_kf, show_idx, /*active_worst_quality=*/0,
3801         /*last_boosted_qindex=*/0);
3802   }
3803 
3804   arf_layers = get_arf_layers(multi_layer_arf, oxcf->enable_auto_arf,
3805                               active_gf_interval.max);
3806   if (multi_layer_arf) {
3807     gop_intra_factor = 1.0 + 0.25 * arf_layers;
3808   } else {
3809     gop_intra_factor = 1.0;
3810   }
3811 
3812   frame_count = get_gop_coding_frame_num(use_alt_ref, frame_info, twopass, rc,
3813                                          show_idx, &active_gf_interval,
3814                                          gop_intra_factor, oxcf->lag_in_frames);
3815   *use_alt_ref &= allow_alt_ref;
3816   return frame_count;
3817 }
3818 
3819 // Under CONFIG_RATE_CTRL, once the first_pass_info is ready, the number of
3820 // coding frames (including show frame and alt ref) can be determined.
vp9_get_coding_frame_num(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,const FRAME_INFO * frame_info,int multi_layer_arf,int allow_alt_ref)3821 int vp9_get_coding_frame_num(const VP9EncoderConfig *oxcf,
3822                              const TWO_PASS *const twopass,
3823                              const FRAME_INFO *frame_info, int multi_layer_arf,
3824                              int allow_alt_ref) {
3825   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3826   int coding_frame_num = 0;
3827   RATE_CONTROL rc;
3828   int gop_coding_frame_count;
3829   int gop_show_frames;
3830   int show_idx = 0;
3831   int last_gop_use_alt_ref = 0;
3832   vp9_rc_init(oxcf, 1, &rc);
3833 
3834   while (show_idx < first_pass_info->num_frames) {
3835     int use_alt_ref;
3836     int first_is_key_frame = 0;
3837     if (rc.frames_to_key == 0) {
3838       rc.frames_to_key = vp9_get_frames_to_next_key(oxcf, twopass, show_idx,
3839                                                     rc.min_gf_interval);
3840       rc.frames_since_key = 0;
3841       first_is_key_frame = 1;
3842     }
3843 
3844     gop_coding_frame_count = vp9_get_gop_coding_frame_count(
3845         oxcf, twopass, frame_info, &rc, show_idx, multi_layer_arf,
3846         allow_alt_ref, first_is_key_frame, last_gop_use_alt_ref, &use_alt_ref);
3847 
3848     rc.source_alt_ref_active = use_alt_ref;
3849     last_gop_use_alt_ref = use_alt_ref;
3850     gop_show_frames = gop_coding_frame_count - use_alt_ref;
3851     rc.frames_to_key -= gop_show_frames;
3852     rc.frames_since_key += gop_show_frames;
3853     show_idx += gop_show_frames;
3854     coding_frame_num += gop_show_frames + use_alt_ref;
3855   }
3856   return coding_frame_num;
3857 }
3858 
vp9_get_key_frame_map(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,int * key_frame_map)3859 void vp9_get_key_frame_map(const VP9EncoderConfig *oxcf,
3860                            const TWO_PASS *const twopass, int *key_frame_map) {
3861   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3862   int show_idx = 0;
3863   RATE_CONTROL rc;
3864   vp9_rc_init(oxcf, 1, &rc);
3865 
3866   // key_frame_map points to an int array with size equal to
3867   // first_pass_info->num_frames, which is also the number of show frames in the
3868   // video.
3869   memset(key_frame_map, 0,
3870          sizeof(*key_frame_map) * first_pass_info->num_frames);
3871   while (show_idx < first_pass_info->num_frames) {
3872     int key_frame_group_size;
3873     key_frame_map[show_idx] = 1;
3874     key_frame_group_size =
3875         vp9_get_frames_to_next_key(oxcf, twopass, show_idx, rc.min_gf_interval);
3876     assert(key_frame_group_size > 0);
3877     show_idx += key_frame_group_size;
3878   }
3879   assert(show_idx == first_pass_info->num_frames);
3880 }
3881 #endif  // CONFIG_RATE_CTRL
3882 
vp9_get_frame_stats(const TWO_PASS * twopass)3883 FIRSTPASS_STATS vp9_get_frame_stats(const TWO_PASS *twopass) {
3884   return twopass->this_frame_stats;
3885 }
vp9_get_total_stats(const TWO_PASS * twopass)3886 FIRSTPASS_STATS vp9_get_total_stats(const TWO_PASS *twopass) {
3887   return twopass->total_stats;
3888 }
3889