• 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)
2117                          ? 0
2118                          : (total_group_bits > twopass->kf_group_bits)
2119                                ? twopass->kf_group_bits
2120                                : total_group_bits;
2121 
2122   // Clip based on user supplied data rate variability limit.
2123   if (total_group_bits > (int64_t)max_bits * gop_frames)
2124     total_group_bits = (int64_t)max_bits * gop_frames;
2125 
2126   return total_group_bits;
2127 }
2128 
2129 // 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)2130 static int calculate_boost_bits(int frame_count, int boost,
2131                                 int64_t total_group_bits) {
2132   int allocation_chunks;
2133 
2134   // return 0 for invalid inputs (could arise e.g. through rounding errors)
2135   if (!boost || (total_group_bits <= 0) || (frame_count < 0)) return 0;
2136 
2137   allocation_chunks = (frame_count * NORMAL_BOOST) + boost;
2138 
2139   // Prevent overflow.
2140   if (boost > 1023) {
2141     int divisor = boost >> 10;
2142     boost /= divisor;
2143     allocation_chunks /= divisor;
2144   }
2145 
2146   // Calculate the number of extra bits for use in the boosted frame or frames.
2147   return VPXMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
2148                 0);
2149 }
2150 
2151 // Used in corpus vbr: Calculates the total normalized group complexity score
2152 // for a given number of frames starting at the current position in the stats
2153 // file.
calculate_group_score(VP9_COMP * cpi,double av_score,int frame_count)2154 static double calculate_group_score(VP9_COMP *cpi, double av_score,
2155                                     int frame_count) {
2156   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2157   TWO_PASS *const twopass = &cpi->twopass;
2158   const FIRSTPASS_STATS *s = twopass->stats_in;
2159   double score_total = 0.0;
2160   int i = 0;
2161 
2162   // We dont ever want to return a 0 score here.
2163   if (frame_count == 0) return 1.0;
2164 
2165   while ((i < frame_count) && (s < twopass->stats_in_end)) {
2166     score_total += calculate_norm_frame_score(cpi, twopass, oxcf, s, av_score);
2167     ++s;
2168     ++i;
2169   }
2170 
2171   return score_total;
2172 }
2173 
find_arf_order(VP9_COMP * cpi,GF_GROUP * gf_group,int * index_counter,int depth,int start,int end)2174 static void find_arf_order(VP9_COMP *cpi, GF_GROUP *gf_group,
2175                            int *index_counter, int depth, int start, int end) {
2176   TWO_PASS *twopass = &cpi->twopass;
2177   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2178   FIRSTPASS_STATS fpf_frame;
2179   const int mid = (start + end + 1) >> 1;
2180   const int min_frame_interval = 2;
2181   int idx;
2182 
2183   // Process regular P frames
2184   if ((end - start < min_frame_interval) ||
2185       (depth > gf_group->allowed_max_layer_depth)) {
2186     for (idx = start; idx <= end; ++idx) {
2187       gf_group->update_type[*index_counter] = LF_UPDATE;
2188       gf_group->arf_src_offset[*index_counter] = 0;
2189       gf_group->frame_gop_index[*index_counter] = idx;
2190       gf_group->rf_level[*index_counter] = INTER_NORMAL;
2191       gf_group->layer_depth[*index_counter] = depth;
2192       gf_group->gfu_boost[*index_counter] = NORMAL_BOOST;
2193       ++(*index_counter);
2194     }
2195     gf_group->max_layer_depth = VPXMAX(gf_group->max_layer_depth, depth);
2196     return;
2197   }
2198 
2199   assert(abs(mid - start) >= 1 && abs(mid - end) >= 1);
2200 
2201   // Process ARF frame
2202   gf_group->layer_depth[*index_counter] = depth;
2203   gf_group->update_type[*index_counter] = ARF_UPDATE;
2204   gf_group->arf_src_offset[*index_counter] = mid - start;
2205   gf_group->frame_gop_index[*index_counter] = mid;
2206   gf_group->rf_level[*index_counter] = GF_ARF_LOW;
2207 
2208   for (idx = 0; idx <= mid; ++idx)
2209     if (EOF == input_stats(twopass, &fpf_frame)) break;
2210 
2211   gf_group->gfu_boost[*index_counter] =
2212       VPXMAX(MIN_ARF_GF_BOOST,
2213              calc_arf_boost(cpi, end - mid + 1, mid - start) >> depth);
2214 
2215   reset_fpf_position(twopass, start_pos);
2216 
2217   ++(*index_counter);
2218 
2219   find_arf_order(cpi, gf_group, index_counter, depth + 1, start, mid - 1);
2220 
2221   gf_group->update_type[*index_counter] = USE_BUF_FRAME;
2222   gf_group->arf_src_offset[*index_counter] = 0;
2223   gf_group->frame_gop_index[*index_counter] = mid;
2224   gf_group->rf_level[*index_counter] = INTER_NORMAL;
2225   gf_group->layer_depth[*index_counter] = depth;
2226   ++(*index_counter);
2227 
2228   find_arf_order(cpi, gf_group, index_counter, depth + 1, mid + 1, end);
2229 }
2230 
set_gf_overlay_frame_type(GF_GROUP * gf_group,int frame_index,int source_alt_ref_active)2231 static INLINE void set_gf_overlay_frame_type(GF_GROUP *gf_group,
2232                                              int frame_index,
2233                                              int source_alt_ref_active) {
2234   if (source_alt_ref_active) {
2235     gf_group->update_type[frame_index] = OVERLAY_UPDATE;
2236     gf_group->rf_level[frame_index] = INTER_NORMAL;
2237     gf_group->layer_depth[frame_index] = MAX_ARF_LAYERS - 1;
2238     gf_group->gfu_boost[frame_index] = NORMAL_BOOST;
2239   } else {
2240     gf_group->update_type[frame_index] = GF_UPDATE;
2241     gf_group->rf_level[frame_index] = GF_ARF_STD;
2242     gf_group->layer_depth[frame_index] = 0;
2243   }
2244 }
2245 
define_gf_group_structure(VP9_COMP * cpi)2246 static void define_gf_group_structure(VP9_COMP *cpi) {
2247   RATE_CONTROL *const rc = &cpi->rc;
2248   TWO_PASS *const twopass = &cpi->twopass;
2249   GF_GROUP *const gf_group = &twopass->gf_group;
2250   int frame_index = 0;
2251   int key_frame = cpi->common.frame_type == KEY_FRAME;
2252   int layer_depth = 1;
2253   int gop_frames =
2254       rc->baseline_gf_interval - (key_frame || rc->source_alt_ref_pending);
2255 
2256   gf_group->frame_start = cpi->common.current_video_frame;
2257   gf_group->frame_end = gf_group->frame_start + rc->baseline_gf_interval;
2258   gf_group->max_layer_depth = 0;
2259   gf_group->allowed_max_layer_depth = 0;
2260 
2261   // For key frames the frame target rate is already set and it
2262   // is also the golden frame.
2263   // === [frame_index == 0] ===
2264   if (!key_frame)
2265     set_gf_overlay_frame_type(gf_group, frame_index, rc->source_alt_ref_active);
2266 
2267   ++frame_index;
2268 
2269   // === [frame_index == 1] ===
2270   if (rc->source_alt_ref_pending) {
2271     gf_group->update_type[frame_index] = ARF_UPDATE;
2272     gf_group->rf_level[frame_index] = GF_ARF_STD;
2273     gf_group->layer_depth[frame_index] = layer_depth;
2274     gf_group->arf_src_offset[frame_index] =
2275         (unsigned char)(rc->baseline_gf_interval - 1);
2276     gf_group->frame_gop_index[frame_index] = rc->baseline_gf_interval;
2277     gf_group->max_layer_depth = 1;
2278     ++frame_index;
2279     ++layer_depth;
2280     gf_group->allowed_max_layer_depth = cpi->oxcf.enable_auto_arf;
2281   }
2282 
2283   find_arf_order(cpi, gf_group, &frame_index, layer_depth, 1, gop_frames);
2284 
2285   set_gf_overlay_frame_type(gf_group, frame_index, rc->source_alt_ref_pending);
2286   gf_group->arf_src_offset[frame_index] = 0;
2287   gf_group->frame_gop_index[frame_index] = rc->baseline_gf_interval;
2288 
2289   // Set the frame ops number.
2290   gf_group->gf_group_size = frame_index;
2291 }
2292 
allocate_gf_group_bits(VP9_COMP * cpi,int64_t gf_group_bits,int gf_arf_bits)2293 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
2294                                    int gf_arf_bits) {
2295   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2296   RATE_CONTROL *const rc = &cpi->rc;
2297   TWO_PASS *const twopass = &cpi->twopass;
2298   GF_GROUP *const gf_group = &twopass->gf_group;
2299   FIRSTPASS_STATS frame_stats;
2300   int i;
2301   int frame_index = 0;
2302   int target_frame_size;
2303   int key_frame;
2304   const int max_bits = frame_max_bits(&cpi->rc, oxcf);
2305   int64_t total_group_bits = gf_group_bits;
2306   int mid_frame_idx;
2307   int normal_frames;
2308   int normal_frame_bits;
2309   int last_frame_reduction = 0;
2310   double av_score = 1.0;
2311   double tot_norm_frame_score = 1.0;
2312   double this_frame_score = 1.0;
2313 
2314   // Define the GF structure and specify
2315   int gop_frames = gf_group->gf_group_size;
2316 
2317   key_frame = cpi->common.frame_type == KEY_FRAME;
2318 
2319   // For key frames the frame target rate is already set and it
2320   // is also the golden frame.
2321   // === [frame_index == 0] ===
2322   if (!key_frame) {
2323     gf_group->bit_allocation[frame_index] =
2324         rc->source_alt_ref_active ? 0 : gf_arf_bits;
2325   }
2326 
2327   // Deduct the boost bits for arf (or gf if it is not a key frame)
2328   // from the group total.
2329   if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
2330 
2331   ++frame_index;
2332 
2333   // === [frame_index == 1] ===
2334   // Store the bits to spend on the ARF if there is one.
2335   if (rc->source_alt_ref_pending) {
2336     gf_group->bit_allocation[frame_index] = gf_arf_bits;
2337 
2338     ++frame_index;
2339   }
2340 
2341   // Define middle frame
2342   mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
2343 
2344   normal_frames = (rc->baseline_gf_interval - 1);
2345   if (normal_frames > 1)
2346     normal_frame_bits = (int)(total_group_bits / normal_frames);
2347   else
2348     normal_frame_bits = (int)total_group_bits;
2349 
2350   gf_group->gfu_boost[1] = rc->gfu_boost;
2351 
2352   if (cpi->multi_layer_arf) {
2353     int idx;
2354     int arf_depth_bits[MAX_ARF_LAYERS] = { 0 };
2355     int arf_depth_count[MAX_ARF_LAYERS] = { 0 };
2356     int arf_depth_boost[MAX_ARF_LAYERS] = { 0 };
2357     int total_arfs = 1;  // Account for the base layer ARF.
2358 
2359     for (idx = 0; idx < gop_frames; ++idx) {
2360       if (gf_group->update_type[idx] == ARF_UPDATE) {
2361         arf_depth_boost[gf_group->layer_depth[idx]] += gf_group->gfu_boost[idx];
2362         ++arf_depth_count[gf_group->layer_depth[idx]];
2363       }
2364     }
2365 
2366     for (idx = 2; idx < MAX_ARF_LAYERS; ++idx) {
2367       if (arf_depth_boost[idx] == 0) break;
2368       arf_depth_bits[idx] = calculate_boost_bits(
2369           rc->baseline_gf_interval - total_arfs - arf_depth_count[idx],
2370           arf_depth_boost[idx], total_group_bits);
2371 
2372       total_group_bits -= arf_depth_bits[idx];
2373       total_arfs += arf_depth_count[idx];
2374     }
2375 
2376     // offset the base layer arf
2377     normal_frames -= (total_arfs - 1);
2378     if (normal_frames > 1)
2379       normal_frame_bits = (int)(total_group_bits / normal_frames);
2380     else
2381       normal_frame_bits = (int)total_group_bits;
2382 
2383     target_frame_size = normal_frame_bits;
2384     target_frame_size =
2385         clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2386 
2387     // The first layer ARF has its bit allocation assigned.
2388     for (idx = frame_index; idx < gop_frames; ++idx) {
2389       switch (gf_group->update_type[idx]) {
2390         case ARF_UPDATE:
2391           gf_group->bit_allocation[idx] =
2392               (int)(((int64_t)arf_depth_bits[gf_group->layer_depth[idx]] *
2393                      gf_group->gfu_boost[idx]) /
2394                     arf_depth_boost[gf_group->layer_depth[idx]]);
2395           break;
2396         case USE_BUF_FRAME: gf_group->bit_allocation[idx] = 0; break;
2397         default: gf_group->bit_allocation[idx] = target_frame_size; break;
2398       }
2399     }
2400     gf_group->bit_allocation[idx] = 0;
2401 
2402     return;
2403   }
2404 
2405   if (oxcf->vbr_corpus_complexity) {
2406     av_score = get_distribution_av_err(cpi, twopass);
2407     tot_norm_frame_score = calculate_group_score(cpi, av_score, normal_frames);
2408   }
2409 
2410   // Allocate bits to the other frames in the group.
2411   for (i = 0; i < normal_frames; ++i) {
2412     if (EOF == input_stats(twopass, &frame_stats)) break;
2413     if (oxcf->vbr_corpus_complexity) {
2414       this_frame_score = calculate_norm_frame_score(cpi, twopass, oxcf,
2415                                                     &frame_stats, av_score);
2416       normal_frame_bits = (int)((double)total_group_bits *
2417                                 (this_frame_score / tot_norm_frame_score));
2418     }
2419 
2420     target_frame_size = normal_frame_bits;
2421     if ((i == (normal_frames - 1)) && (i >= 1)) {
2422       last_frame_reduction = normal_frame_bits / 16;
2423       target_frame_size -= last_frame_reduction;
2424     }
2425 
2426     target_frame_size =
2427         clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2428 
2429     gf_group->bit_allocation[frame_index] = target_frame_size;
2430     ++frame_index;
2431   }
2432 
2433   // Add in some extra bits for the middle frame in the group.
2434   gf_group->bit_allocation[mid_frame_idx] += last_frame_reduction;
2435 
2436   // Note:
2437   // We need to configure the frame at the end of the sequence + 1 that will be
2438   // the start frame for the next group. Otherwise prior to the call to
2439   // vp9_rc_get_second_pass_params() the data will be undefined.
2440 }
2441 
2442 // Adjusts the ARNF filter for a GF group.
adjust_group_arnr_filter(VP9_COMP * cpi,double section_noise,double section_inter,double section_motion)2443 static void adjust_group_arnr_filter(VP9_COMP *cpi, double section_noise,
2444                                      double section_inter,
2445                                      double section_motion) {
2446   TWO_PASS *const twopass = &cpi->twopass;
2447   double section_zeromv = section_inter - section_motion;
2448 
2449   twopass->arnr_strength_adjustment = 0;
2450 
2451   if (section_noise < 150) {
2452     twopass->arnr_strength_adjustment -= 1;
2453     if (section_noise < 75) twopass->arnr_strength_adjustment -= 1;
2454   } else if (section_noise > 250)
2455     twopass->arnr_strength_adjustment += 1;
2456 
2457   if (section_zeromv > 0.50) twopass->arnr_strength_adjustment += 1;
2458 }
2459 
2460 // Analyse and define a gf/arf group.
2461 #define ARF_ABS_ZOOM_THRESH 4.0
2462 
2463 #define MAX_GF_BOOST 5400
2464 
2465 typedef struct RANGE {
2466   int min;
2467   int max;
2468 } RANGE;
2469 
2470 /* get_gop_coding_frame_num() depends on several fields in RATE_CONTROL *rc as
2471  * follows.
2472  * Static fields:
2473  * (The following fields will remain unchanged after initialization of encoder.)
2474  *   rc->static_scene_max_gf_interval
2475  *   rc->min_gf_interval
2476  *   twopass->sr_diff_factor
2477  *   twopass->sr_default_decay_limit
2478  *   twopass->zm_factor
2479  *
2480  * Dynamic fields:
2481  * (The following fields will be updated before or after coding each frame.)
2482  *   rc->frames_to_key
2483  *   rc->frames_since_key
2484  *   rc->source_alt_ref_active
2485  *
2486  * Special case: if CONFIG_RATE_CTRL is true, the external arf indexes will
2487  * determine the arf position.
2488  *
2489  * TODO(angiebird): Separate the dynamic fields and static fields into two
2490  * structs.
2491  */
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)2492 static int get_gop_coding_frame_num(
2493     int *use_alt_ref, const FRAME_INFO *frame_info,
2494     const TWO_PASS *const twopass, const RATE_CONTROL *rc,
2495     int gf_start_show_idx, const RANGE *active_gf_interval,
2496     double gop_intra_factor, int lag_in_frames) {
2497   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
2498   double loop_decay_rate = 1.00;
2499   double mv_ratio_accumulator = 0.0;
2500   double this_frame_mv_in_out = 0.0;
2501   double mv_in_out_accumulator = 0.0;
2502   double abs_mv_in_out_accumulator = 0.0;
2503   double sr_accumulator = 0.0;
2504   // Motion breakout threshold for loop below depends on image size.
2505   double mv_ratio_accumulator_thresh =
2506       (frame_info->frame_height + frame_info->frame_width) / 4.0;
2507   double zero_motion_accumulator = 1.0;
2508   int gop_coding_frames;
2509 
2510   *use_alt_ref = 1;
2511   gop_coding_frames = 0;
2512   while (gop_coding_frames < rc->static_scene_max_gf_interval &&
2513          gop_coding_frames < rc->frames_to_key) {
2514     const FIRSTPASS_STATS *next_next_frame;
2515     const FIRSTPASS_STATS *next_frame;
2516     int flash_detected;
2517     ++gop_coding_frames;
2518 
2519     next_frame = fps_get_frame_stats(first_pass_info,
2520                                      gf_start_show_idx + gop_coding_frames);
2521     if (next_frame == NULL) {
2522       break;
2523     }
2524 
2525     // Test for the case where there is a brief flash but the prediction
2526     // quality back to an earlier frame is then restored.
2527     next_next_frame = fps_get_frame_stats(
2528         first_pass_info, gf_start_show_idx + gop_coding_frames + 1);
2529     flash_detected = detect_flash_from_frame_stats(next_next_frame);
2530 
2531     // Update the motion related elements to the boost calculation.
2532     accumulate_frame_motion_stats(
2533         next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2534         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2535 
2536     // Monitor for static sections.
2537     if ((rc->frames_since_key + gop_coding_frames - 1) > 1) {
2538       zero_motion_accumulator = VPXMIN(
2539           zero_motion_accumulator, get_zero_motion_factor(twopass, next_frame));
2540     }
2541 
2542     // Accumulate the effect of prediction quality decay.
2543     if (!flash_detected) {
2544       double last_loop_decay_rate = loop_decay_rate;
2545       loop_decay_rate = get_prediction_decay_rate(twopass, next_frame);
2546 
2547       // Break clause to detect very still sections after motion. For example,
2548       // a static image after a fade or other transition.
2549       if (gop_coding_frames > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
2550           last_loop_decay_rate < 0.9) {
2551         int still_interval = 5;
2552         if (check_transition_to_still(first_pass_info,
2553                                       gf_start_show_idx + gop_coding_frames,
2554                                       still_interval)) {
2555           *use_alt_ref = 0;
2556           break;
2557         }
2558       }
2559 
2560       // Update the accumulator for second ref error difference.
2561       // This is intended to give an indication of how much the coded error is
2562       // increasing over time.
2563       if (gop_coding_frames == 1) {
2564         sr_accumulator += next_frame->coded_error;
2565       } else {
2566         sr_accumulator +=
2567             (next_frame->sr_coded_error - next_frame->coded_error);
2568       }
2569     }
2570 
2571     // Break out conditions.
2572     // Break at maximum of active_gf_interval->max unless almost totally
2573     // static.
2574     //
2575     // Note that the addition of a test of rc->source_alt_ref_active is
2576     // deliberate. The effect of this is that after a normal altref group even
2577     // if the material is static there will be one normal length GF group
2578     // before allowing longer GF groups. The reason for this is that in cases
2579     // such as slide shows where slides are separated by a complex transition
2580     // such as a fade, the arf group spanning the transition may not be coded
2581     // at a very high quality and hence this frame (with its overlay) is a
2582     // poor golden frame to use for an extended group.
2583     if ((gop_coding_frames >= active_gf_interval->max) &&
2584         ((zero_motion_accumulator < 0.995) || (rc->source_alt_ref_active))) {
2585       break;
2586     }
2587     if (
2588         // Don't break out with a very short interval.
2589         (gop_coding_frames >= active_gf_interval->min) &&
2590         // If possible dont break very close to a kf
2591         ((rc->frames_to_key - gop_coding_frames) >= rc->min_gf_interval) &&
2592         (gop_coding_frames & 0x01) && (!flash_detected) &&
2593         ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
2594          (abs_mv_in_out_accumulator > ARF_ABS_ZOOM_THRESH) ||
2595          (sr_accumulator > gop_intra_factor * next_frame->intra_error))) {
2596       break;
2597     }
2598   }
2599   *use_alt_ref &= zero_motion_accumulator < 0.995;
2600   *use_alt_ref &= gop_coding_frames < lag_in_frames;
2601   *use_alt_ref &= gop_coding_frames >= rc->min_gf_interval;
2602   return gop_coding_frames;
2603 }
2604 
get_active_gf_inverval_range_simple(int min_gf_interval,int arf_active_or_kf,int frames_to_key)2605 static RANGE get_active_gf_inverval_range_simple(int min_gf_interval,
2606                                                  int arf_active_or_kf,
2607                                                  int frames_to_key) {
2608   RANGE active_gf_interval;
2609   active_gf_interval.min = min_gf_interval + arf_active_or_kf + 2;
2610   active_gf_interval.max = 16 + arf_active_or_kf;
2611 
2612   if ((active_gf_interval.max <= frames_to_key) &&
2613       (active_gf_interval.max >= (frames_to_key - min_gf_interval))) {
2614     active_gf_interval.min = frames_to_key / 2;
2615     active_gf_interval.max = frames_to_key / 2;
2616   }
2617   return active_gf_interval;
2618 }
2619 
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)2620 static RANGE get_active_gf_inverval_range(
2621     const FRAME_INFO *frame_info, const RATE_CONTROL *rc, int arf_active_or_kf,
2622     int gf_start_show_idx, int active_worst_quality, int last_boosted_qindex) {
2623   RANGE active_gf_interval;
2624   int int_max_q = (int)(vp9_convert_qindex_to_q(active_worst_quality,
2625                                                 frame_info->bit_depth));
2626   int q_term = (gf_start_show_idx == 0)
2627                    ? int_max_q / 32
2628                    : (int)(vp9_convert_qindex_to_q(last_boosted_qindex,
2629                                                    frame_info->bit_depth) /
2630                            6);
2631   active_gf_interval.min =
2632       rc->min_gf_interval + arf_active_or_kf + VPXMIN(2, int_max_q / 200);
2633   active_gf_interval.min =
2634       VPXMIN(active_gf_interval.min, rc->max_gf_interval + arf_active_or_kf);
2635 
2636   // The value chosen depends on the active Q range. At low Q we have
2637   // bits to spare and are better with a smaller interval and smaller boost.
2638   // At high Q when there are few bits to spare we are better with a longer
2639   // interval to spread the cost of the GF.
2640   active_gf_interval.max = 11 + arf_active_or_kf + VPXMIN(5, q_term);
2641 
2642   // Force max GF interval to be odd.
2643   active_gf_interval.max = active_gf_interval.max | 0x01;
2644 
2645   // We have: active_gf_interval.min <=
2646   // rc->max_gf_interval + arf_active_or_kf.
2647   if (active_gf_interval.max < active_gf_interval.min) {
2648     active_gf_interval.max = active_gf_interval.min;
2649   } else {
2650     active_gf_interval.max =
2651         VPXMIN(active_gf_interval.max, rc->max_gf_interval + arf_active_or_kf);
2652   }
2653 
2654   // Would the active max drop us out just before the near the next kf?
2655   if ((active_gf_interval.max <= rc->frames_to_key) &&
2656       (active_gf_interval.max >= (rc->frames_to_key - rc->min_gf_interval))) {
2657     active_gf_interval.max = rc->frames_to_key / 2;
2658   }
2659   active_gf_interval.max =
2660       VPXMAX(active_gf_interval.max, active_gf_interval.min);
2661   return active_gf_interval;
2662 }
2663 
get_arf_layers(int multi_layer_arf,int max_layers,int coding_frame_num)2664 static int get_arf_layers(int multi_layer_arf, int max_layers,
2665                           int coding_frame_num) {
2666   assert(max_layers <= MAX_ARF_LAYERS);
2667   if (multi_layer_arf) {
2668     int layers = 0;
2669     int i;
2670     for (i = coding_frame_num; i > 0; i >>= 1) {
2671       ++layers;
2672     }
2673     layers = VPXMIN(max_layers, layers);
2674     return layers;
2675   } else {
2676     return 1;
2677   }
2678 }
2679 
define_gf_group(VP9_COMP * cpi,int gf_start_show_idx)2680 static void define_gf_group(VP9_COMP *cpi, int gf_start_show_idx) {
2681   VP9_COMMON *const cm = &cpi->common;
2682   RATE_CONTROL *const rc = &cpi->rc;
2683   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2684   TWO_PASS *const twopass = &cpi->twopass;
2685   const FRAME_INFO *frame_info = &cpi->frame_info;
2686   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
2687   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2688   int gop_coding_frames;
2689 
2690   double gf_group_err = 0.0;
2691   double gf_group_raw_error = 0.0;
2692   double gf_group_noise = 0.0;
2693   double gf_group_skip_pct = 0.0;
2694   double gf_group_inactive_zone_rows = 0.0;
2695   double gf_group_inter = 0.0;
2696   double gf_group_motion = 0.0;
2697 
2698   int allow_alt_ref = is_altref_enabled(cpi);
2699   int use_alt_ref;
2700 
2701   int64_t gf_group_bits;
2702   int gf_arf_bits;
2703   const int is_key_frame = frame_is_intra_only(cm);
2704   // If this is a key frame or the overlay from a previous arf then
2705   // the error score / cost of this frame has already been accounted for.
2706   const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2707   int is_alt_ref_flash = 0;
2708 
2709   double gop_intra_factor;
2710   int gop_frames;
2711   RANGE active_gf_interval;
2712 
2713   // Reset the GF group data structures unless this is a key
2714   // frame in which case it will already have been done.
2715   if (is_key_frame == 0) {
2716     vp9_zero(twopass->gf_group);
2717   }
2718 
2719   vpx_clear_system_state();
2720 
2721   if (oxcf->use_simple_encode_api) {
2722     active_gf_interval = get_active_gf_inverval_range_simple(
2723         rc->min_gf_interval, arf_active_or_kf, rc->frames_to_key);
2724   } else {
2725     active_gf_interval = get_active_gf_inverval_range(
2726         frame_info, rc, arf_active_or_kf, gf_start_show_idx,
2727         twopass->active_worst_quality, rc->last_boosted_qindex);
2728   }
2729 
2730   if (cpi->multi_layer_arf) {
2731     int arf_layers = get_arf_layers(cpi->multi_layer_arf, oxcf->enable_auto_arf,
2732                                     active_gf_interval.max);
2733     gop_intra_factor = 1.0 + 0.25 * arf_layers;
2734   } else {
2735     gop_intra_factor = 1.0;
2736   }
2737 
2738   gop_coding_frames = get_gop_coding_frame_num(
2739       &use_alt_ref, frame_info, twopass, rc, gf_start_show_idx,
2740       &active_gf_interval, gop_intra_factor, cpi->oxcf.lag_in_frames);
2741   use_alt_ref &= allow_alt_ref;
2742 #if CONFIG_RATE_CTRL
2743   // If the external gop_command is on, we will override the decisions
2744   // of gop_coding_frames and use_alt_ref.
2745   if (cpi->oxcf.use_simple_encode_api) {
2746     const GOP_COMMAND *gop_command = &cpi->encode_command.gop_command;
2747     assert(allow_alt_ref == 1);
2748     if (gop_command->use) {
2749       gop_coding_frames = gop_command_coding_frame_count(gop_command);
2750       use_alt_ref = gop_command->use_alt_ref;
2751     }
2752   }
2753 #endif
2754 
2755   // Was the group length constrained by the requirement for a new KF?
2756   rc->constrained_gf_group = (gop_coding_frames >= rc->frames_to_key) ? 1 : 0;
2757 
2758   // Should we use the alternate reference frame.
2759   if (use_alt_ref) {
2760     const int f_frames =
2761         (rc->frames_to_key - gop_coding_frames >= gop_coding_frames - 1)
2762             ? gop_coding_frames - 1
2763             : VPXMAX(0, rc->frames_to_key - gop_coding_frames);
2764     const int b_frames = gop_coding_frames - 1;
2765     const int avg_inter_frame_qindex = rc->avg_frame_qindex[INTER_FRAME];
2766     // TODO(angiebird): figure out why arf's location is assigned this way
2767     const int arf_show_idx = VPXMIN(gf_start_show_idx + gop_coding_frames + 1,
2768                                     fps_get_num_frames(first_pass_info));
2769 
2770     // Calculate the boost for alt ref.
2771     rc->gfu_boost =
2772         compute_arf_boost(frame_info, twopass, arf_show_idx, f_frames, b_frames,
2773                           avg_inter_frame_qindex);
2774     rc->source_alt_ref_pending = 1;
2775   } else {
2776     const int f_frames = gop_coding_frames - 1;
2777     const int b_frames = 0;
2778     const int avg_inter_frame_qindex = rc->avg_frame_qindex[INTER_FRAME];
2779     // TODO(angiebird): figure out why arf's location is assigned this way
2780     const int gld_show_idx =
2781         VPXMIN(gf_start_show_idx + 1, fps_get_num_frames(first_pass_info));
2782     const int arf_boost =
2783         compute_arf_boost(frame_info, twopass, gld_show_idx, f_frames, b_frames,
2784                           avg_inter_frame_qindex);
2785     rc->gfu_boost = VPXMIN((int)twopass->gf_max_total_boost, arf_boost);
2786     rc->source_alt_ref_pending = 0;
2787   }
2788 
2789 #define LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR 0.2
2790   rc->arf_active_best_quality_adjustment_factor = 1.0;
2791   rc->arf_increase_active_best_quality = 0;
2792 
2793   if (!is_lossless_requested(&cpi->oxcf)) {
2794     if (rc->frames_since_key >= rc->frames_to_key) {
2795       // Increase the active best quality in the second half of key frame
2796       // interval.
2797       rc->arf_active_best_quality_adjustment_factor =
2798           LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR +
2799           (1.0 - LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR) *
2800               (rc->frames_to_key - gop_coding_frames) /
2801               (VPXMAX(1, ((rc->frames_to_key + rc->frames_since_key) / 2 -
2802                           gop_coding_frames)));
2803       rc->arf_increase_active_best_quality = 1;
2804     } else if ((rc->frames_to_key - gop_coding_frames) > 0) {
2805       // Reduce the active best quality in the first half of key frame interval.
2806       rc->arf_active_best_quality_adjustment_factor =
2807           LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR +
2808           (1.0 - LAST_ALR_ACTIVE_BEST_QUALITY_ADJUSTMENT_FACTOR) *
2809               (rc->frames_since_key + gop_coding_frames) /
2810               (VPXMAX(1, (rc->frames_to_key + rc->frames_since_key) / 2 +
2811                              gop_coding_frames));
2812       rc->arf_increase_active_best_quality = -1;
2813     }
2814   }
2815 
2816 #ifdef AGGRESSIVE_VBR
2817   // Limit maximum boost based on interval length.
2818   rc->gfu_boost = VPXMIN((int)rc->gfu_boost, gop_coding_frames * 140);
2819 #else
2820   rc->gfu_boost = VPXMIN((int)rc->gfu_boost, gop_coding_frames * 200);
2821 #endif
2822 
2823   // Cap the ARF boost when perceptual quality AQ mode is enabled. This is
2824   // designed to improve the perceptual quality of high value content and to
2825   // make consistent quality across consecutive frames. It will hurt objective
2826   // quality.
2827   if (oxcf->aq_mode == PERCEPTUAL_AQ)
2828     rc->gfu_boost = VPXMIN(rc->gfu_boost, MIN_ARF_GF_BOOST);
2829 
2830   rc->baseline_gf_interval = gop_coding_frames - rc->source_alt_ref_pending;
2831 
2832   if (rc->source_alt_ref_pending)
2833     is_alt_ref_flash = detect_flash(twopass, rc->baseline_gf_interval);
2834 
2835   {
2836     const double av_err = get_distribution_av_err(cpi, twopass);
2837     const double mean_mod_score = twopass->mean_mod_score;
2838     // If the first frame is a key frame or the overlay from a previous arf then
2839     // the error score / cost of this frame has already been accounted for.
2840     int start_idx = arf_active_or_kf ? 1 : 0;
2841     int j;
2842     for (j = start_idx; j < gop_coding_frames; ++j) {
2843       int show_idx = gf_start_show_idx + j;
2844       const FIRSTPASS_STATS *frame_stats =
2845           fps_get_frame_stats(first_pass_info, show_idx);
2846       // Accumulate error score of frames in this gf group.
2847       gf_group_err += calc_norm_frame_score(oxcf, frame_info, frame_stats,
2848                                             mean_mod_score, av_err);
2849       gf_group_raw_error += frame_stats->coded_error;
2850       gf_group_noise += frame_stats->frame_noise_energy;
2851       gf_group_skip_pct += frame_stats->intra_skip_pct;
2852       gf_group_inactive_zone_rows += frame_stats->inactive_zone_rows;
2853       gf_group_inter += frame_stats->pcnt_inter;
2854       gf_group_motion += frame_stats->pcnt_motion;
2855     }
2856   }
2857 
2858   // Calculate the bits to be allocated to the gf/arf group as a whole
2859   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
2860 
2861   gop_frames =
2862       rc->baseline_gf_interval + rc->source_alt_ref_pending - arf_active_or_kf;
2863 
2864   // Store the average moise level measured for the group
2865   // TODO(any): Experiment with removal of else condition (gop_frames = 0) so
2866   // that consumption of group noise energy is based on previous gf group
2867   if (gop_frames > 0)
2868     twopass->gf_group.group_noise_energy = (int)(gf_group_noise / gop_frames);
2869   else
2870     twopass->gf_group.group_noise_energy = 0;
2871 
2872   // Calculate an estimate of the maxq needed for the group.
2873   // We are more aggressive about correcting for sections
2874   // where there could be significant overshoot than for easier
2875   // sections where we do not wish to risk creating an overshoot
2876   // of the allocated bit budget.
2877   if ((cpi->oxcf.rc_mode != VPX_Q) && (rc->baseline_gf_interval > 1)) {
2878     const int vbr_group_bits_per_frame = (int)(gf_group_bits / gop_frames);
2879     const double group_av_err = gf_group_raw_error / gop_frames;
2880     const double group_av_noise = gf_group_noise / gop_frames;
2881     const double group_av_skip_pct = gf_group_skip_pct / gop_frames;
2882     const double group_av_inactive_zone = ((gf_group_inactive_zone_rows * 2) /
2883                                            (gop_frames * (double)cm->mb_rows));
2884     int tmp_q = get_twopass_worst_quality(
2885         cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2886         group_av_noise, vbr_group_bits_per_frame);
2887     twopass->active_worst_quality =
2888         (int)((tmp_q + (twopass->active_worst_quality *
2889                         (twopass->active_wq_factor - 1))) /
2890               twopass->active_wq_factor);
2891 
2892 #if CONFIG_ALWAYS_ADJUST_BPM
2893     // Reset rolling actual and target bits counters for ARF groups.
2894     twopass->rolling_arf_group_target_bits = 0;
2895     twopass->rolling_arf_group_actual_bits = 0;
2896 #endif
2897   }
2898 
2899   // Context Adjustment of ARNR filter strength
2900   if (rc->baseline_gf_interval > 1) {
2901     adjust_group_arnr_filter(cpi, (gf_group_noise / gop_frames),
2902                              (gf_group_inter / gop_frames),
2903                              (gf_group_motion / gop_frames));
2904   } else {
2905     twopass->arnr_strength_adjustment = 0;
2906   }
2907 
2908   // Calculate the extra bits to be used for boosted frame(s)
2909   gf_arf_bits = calculate_boost_bits((rc->baseline_gf_interval - 1),
2910                                      rc->gfu_boost, gf_group_bits);
2911 
2912   // Adjust KF group bits and error remaining.
2913   twopass->kf_group_error_left -= gf_group_err;
2914 
2915   // Decide GOP structure.
2916   define_gf_group_structure(cpi);
2917 
2918   // Allocate bits to each of the frames in the GF group.
2919   allocate_gf_group_bits(cpi, gf_group_bits, gf_arf_bits);
2920 
2921   // Reset the file position.
2922   reset_fpf_position(twopass, start_pos);
2923 
2924   // Calculate a section intra ratio used in setting max loop filter.
2925   twopass->section_intra_rating = calculate_section_intra_ratio(
2926       start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
2927 
2928   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2929     // Default to starting GF groups at normal frame size.
2930     cpi->rc.next_frame_size_selector = UNSCALED;
2931   }
2932 #if !CONFIG_ALWAYS_ADJUST_BPM
2933   // Reset rolling actual and target bits counters for ARF groups.
2934   twopass->rolling_arf_group_target_bits = 0;
2935   twopass->rolling_arf_group_actual_bits = 0;
2936 #endif
2937   rc->preserve_arf_as_gld = rc->preserve_next_arf_as_gld;
2938   rc->preserve_next_arf_as_gld = 0;
2939   // If alt ref frame is flash do not set preserve_arf_as_gld
2940   if (!is_lossless_requested(&cpi->oxcf) && !cpi->use_svc &&
2941       cpi->oxcf.aq_mode == NO_AQ && cpi->multi_layer_arf && !is_alt_ref_flash)
2942     rc->preserve_next_arf_as_gld = 1;
2943 }
2944 
2945 // Intra / Inter threshold very low
2946 #define VERY_LOW_II 1.5
2947 // Clean slide transitions we expect a sharp single frame spike in error.
2948 #define ERROR_SPIKE 5.0
2949 
2950 // Slide show transition detection.
2951 // Tests for case where there is very low error either side of the current frame
2952 // but much higher just for this frame. This can help detect key frames in
2953 // slide shows even where the slides are pictures of different sizes.
2954 // Also requires that intra and inter errors are very similar to help eliminate
2955 // harmful false positives.
2956 // 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)2957 static int slide_transition(const FIRSTPASS_STATS *this_frame,
2958                             const FIRSTPASS_STATS *last_frame,
2959                             const FIRSTPASS_STATS *next_frame) {
2960   return (this_frame->intra_error < (this_frame->coded_error * VERY_LOW_II)) &&
2961          (this_frame->coded_error > (last_frame->coded_error * ERROR_SPIKE)) &&
2962          (this_frame->coded_error > (next_frame->coded_error * ERROR_SPIKE));
2963 }
2964 
2965 // This test looks for anomalous changes in the nature of the intra signal
2966 // related to the previous and next frame as an indicator for coding a key
2967 // frame. This test serves to detect some additional scene cuts,
2968 // especially in lowish motion and low contrast sections, that are missed
2969 // by the other tests.
intra_step_transition(const FIRSTPASS_STATS * this_frame,const FIRSTPASS_STATS * last_frame,const FIRSTPASS_STATS * next_frame)2970 static int intra_step_transition(const FIRSTPASS_STATS *this_frame,
2971                                  const FIRSTPASS_STATS *last_frame,
2972                                  const FIRSTPASS_STATS *next_frame) {
2973   double last_ii_ratio;
2974   double this_ii_ratio;
2975   double next_ii_ratio;
2976   double last_pcnt_intra = 1.0 - last_frame->pcnt_inter;
2977   double this_pcnt_intra = 1.0 - this_frame->pcnt_inter;
2978   double next_pcnt_intra = 1.0 - next_frame->pcnt_inter;
2979   double mod_this_intra = this_pcnt_intra + this_frame->pcnt_neutral;
2980 
2981   // Calculate ii ratio for this frame last frame and next frame.
2982   last_ii_ratio =
2983       last_frame->intra_error / DOUBLE_DIVIDE_CHECK(last_frame->coded_error);
2984   this_ii_ratio =
2985       this_frame->intra_error / DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
2986   next_ii_ratio =
2987       next_frame->intra_error / DOUBLE_DIVIDE_CHECK(next_frame->coded_error);
2988 
2989   // Return true the intra/inter ratio for the current frame is
2990   // low but better in the next and previous frame and the relative useage of
2991   // intra in the current frame is markedly higher than the last and next frame.
2992   if ((this_ii_ratio < 2.0) && (last_ii_ratio > 2.25) &&
2993       (next_ii_ratio > 2.25) && (this_pcnt_intra > (3 * last_pcnt_intra)) &&
2994       (this_pcnt_intra > (3 * next_pcnt_intra)) &&
2995       ((this_pcnt_intra > 0.075) || (mod_this_intra > 0.85))) {
2996     return 1;
2997     // Very low inter intra ratio (i.e. not much gain from inter coding), most
2998     // blocks neutral on coding method and better inter prediction either side
2999   } else if ((this_ii_ratio < 1.25) && (mod_this_intra > 0.85) &&
3000              (this_ii_ratio < last_ii_ratio * 0.9) &&
3001              (this_ii_ratio < next_ii_ratio * 0.9)) {
3002     return 1;
3003   } else {
3004     return 0;
3005   }
3006 }
3007 
3008 // Minimum % intra coding observed in first pass (1.0 = 100%)
3009 #define MIN_INTRA_LEVEL 0.25
3010 // Threshold for use of the lagging second reference frame. Scene cuts do not
3011 // usually have a high second ref useage.
3012 #define SECOND_REF_USEAGE_THRESH 0.2
3013 // Hard threshold where the first pass chooses intra for almost all blocks.
3014 // In such a case even if the frame is not a scene cut coding a key frame
3015 // may be a good option.
3016 #define VERY_LOW_INTER_THRESH 0.05
3017 // Maximum threshold for the relative ratio of intra error score vs best
3018 // inter error score.
3019 #define KF_II_ERR_THRESHOLD 2.5
3020 #define KF_II_MAX 128.0
3021 #define II_FACTOR 12.5
3022 // Test for very low intra complexity which could cause false key frames
3023 #define V_LOW_INTRA 0.5
3024 
test_candidate_kf(const FIRST_PASS_INFO * first_pass_info,int show_idx)3025 static int test_candidate_kf(const FIRST_PASS_INFO *first_pass_info,
3026                              int show_idx) {
3027   const FIRSTPASS_STATS *last_frame =
3028       fps_get_frame_stats(first_pass_info, show_idx - 1);
3029   const FIRSTPASS_STATS *this_frame =
3030       fps_get_frame_stats(first_pass_info, show_idx);
3031   const FIRSTPASS_STATS *next_frame =
3032       fps_get_frame_stats(first_pass_info, show_idx + 1);
3033   int is_viable_kf = 0;
3034   double pcnt_intra = 1.0 - this_frame->pcnt_inter;
3035 
3036   // Does the frame satisfy the primary criteria of a key frame?
3037   // See above for an explanation of the test criteria.
3038   // If so, then examine how well it predicts subsequent frames.
3039   detect_flash_from_frame_stats(next_frame);
3040   if (!detect_flash_from_frame_stats(this_frame) &&
3041       !detect_flash_from_frame_stats(next_frame) &&
3042       (this_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
3043       ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
3044        (slide_transition(this_frame, last_frame, next_frame)) ||
3045        (intra_step_transition(this_frame, last_frame, next_frame)) ||
3046        (((this_frame->coded_error > (next_frame->coded_error * 1.2)) &&
3047          (this_frame->coded_error > (last_frame->coded_error * 1.2))) &&
3048         (pcnt_intra > MIN_INTRA_LEVEL) &&
3049         ((pcnt_intra + this_frame->pcnt_neutral) > 0.5) &&
3050         ((this_frame->intra_error /
3051           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
3052          KF_II_ERR_THRESHOLD)))) {
3053     int i;
3054     double boost_score = 0.0;
3055     double old_boost_score = 0.0;
3056     double decay_accumulator = 1.0;
3057 
3058     // Examine how well the key frame predicts subsequent frames.
3059     for (i = 0; i < 16; ++i) {
3060       const FIRSTPASS_STATS *frame_stats =
3061           fps_get_frame_stats(first_pass_info, show_idx + 1 + i);
3062       double next_iiratio = (II_FACTOR * frame_stats->intra_error /
3063                              DOUBLE_DIVIDE_CHECK(frame_stats->coded_error));
3064 
3065       if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
3066 
3067       // Cumulative effect of decay in prediction quality.
3068       if (frame_stats->pcnt_inter > 0.85)
3069         decay_accumulator *= frame_stats->pcnt_inter;
3070       else
3071         decay_accumulator *= (0.85 + frame_stats->pcnt_inter) / 2.0;
3072 
3073       // Keep a running total.
3074       boost_score += (decay_accumulator * next_iiratio);
3075 
3076       // Test various breakout clauses.
3077       if ((frame_stats->pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
3078           (((frame_stats->pcnt_inter - frame_stats->pcnt_neutral) < 0.20) &&
3079            (next_iiratio < 3.0)) ||
3080           ((boost_score - old_boost_score) < 3.0) ||
3081           (frame_stats->intra_error < V_LOW_INTRA)) {
3082         break;
3083       }
3084 
3085       old_boost_score = boost_score;
3086 
3087       // Get the next frame details
3088       if (show_idx + 1 + i == fps_get_num_frames(first_pass_info) - 1) break;
3089     }
3090 
3091     // If there is tolerable prediction for at least the next 3 frames then
3092     // break out else discard this potential key frame and move on
3093     if (boost_score > 30.0 && (i > 3)) {
3094       is_viable_kf = 1;
3095     } else {
3096       is_viable_kf = 0;
3097     }
3098   }
3099 
3100   return is_viable_kf;
3101 }
3102 
3103 #define FRAMES_TO_CHECK_DECAY 8
3104 #define MIN_KF_TOT_BOOST 300
3105 #define DEFAULT_SCAN_FRAMES_FOR_KF_BOOST 32
3106 #define MAX_SCAN_FRAMES_FOR_KF_BOOST 48
3107 #define MIN_SCAN_FRAMES_FOR_KF_BOOST 32
3108 #define KF_ABS_ZOOM_THRESH 6.0
3109 
vp9_get_frames_to_next_key(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,int kf_show_idx,int min_gf_interval)3110 int vp9_get_frames_to_next_key(const VP9EncoderConfig *oxcf,
3111                                const TWO_PASS *const twopass, int kf_show_idx,
3112                                int min_gf_interval) {
3113   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3114   double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
3115   int j;
3116   int frames_to_key;
3117   int max_frames_to_key = first_pass_info->num_frames - kf_show_idx;
3118   max_frames_to_key = VPXMIN(max_frames_to_key, oxcf->key_freq);
3119 
3120   // Initialize the decay rates for the recent frames to check
3121   for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
3122   // Find the next keyframe.
3123   if (!oxcf->auto_key) {
3124     frames_to_key = max_frames_to_key;
3125   } else {
3126     frames_to_key = 1;
3127     while (frames_to_key < max_frames_to_key) {
3128       // Provided that we are not at the end of the file...
3129       if (kf_show_idx + frames_to_key + 1 < first_pass_info->num_frames) {
3130         double loop_decay_rate;
3131         double decay_accumulator;
3132         const FIRSTPASS_STATS *next_frame = fps_get_frame_stats(
3133             first_pass_info, kf_show_idx + frames_to_key + 1);
3134 
3135         // Check for a scene cut.
3136         if (test_candidate_kf(first_pass_info, kf_show_idx + frames_to_key))
3137           break;
3138 
3139         // How fast is the prediction quality decaying?
3140         loop_decay_rate = get_prediction_decay_rate(twopass, next_frame);
3141 
3142         // We want to know something about the recent past... rather than
3143         // as used elsewhere where we are concerned with decay in prediction
3144         // quality since the last GF or KF.
3145         recent_loop_decay[(frames_to_key - 1) % FRAMES_TO_CHECK_DECAY] =
3146             loop_decay_rate;
3147         decay_accumulator = 1.0;
3148         for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
3149           decay_accumulator *= recent_loop_decay[j];
3150 
3151         // Special check for transition or high motion followed by a
3152         // static scene.
3153         if ((frames_to_key - 1) > min_gf_interval && loop_decay_rate >= 0.999 &&
3154             decay_accumulator < 0.9) {
3155           int still_interval = oxcf->key_freq - (frames_to_key - 1);
3156           // TODO(angiebird): Figure out why we use "+1" here
3157           int show_idx = kf_show_idx + frames_to_key;
3158           if (check_transition_to_still(first_pass_info, show_idx,
3159                                         still_interval)) {
3160             break;
3161           }
3162         }
3163       }
3164       ++frames_to_key;
3165     }
3166   }
3167   return frames_to_key;
3168 }
3169 
find_next_key_frame(VP9_COMP * cpi,int kf_show_idx)3170 static void find_next_key_frame(VP9_COMP *cpi, int kf_show_idx) {
3171   int i;
3172   RATE_CONTROL *const rc = &cpi->rc;
3173   TWO_PASS *const twopass = &cpi->twopass;
3174   GF_GROUP *const gf_group = &twopass->gf_group;
3175   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3176   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3177   const FRAME_INFO *frame_info = &cpi->frame_info;
3178   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
3179   const FIRSTPASS_STATS *keyframe_stats =
3180       fps_get_frame_stats(first_pass_info, kf_show_idx);
3181   FIRSTPASS_STATS next_frame;
3182   int kf_bits = 0;
3183   int64_t max_kf_bits;
3184   double zero_motion_accumulator = 1.0;
3185   double zero_motion_sum = 0.0;
3186   double zero_motion_avg;
3187   double motion_compensable_sum = 0.0;
3188   double motion_compensable_avg;
3189   int num_frames = 0;
3190   int kf_boost_scan_frames = DEFAULT_SCAN_FRAMES_FOR_KF_BOOST;
3191   double boost_score = 0.0;
3192   double kf_mod_err = 0.0;
3193   double kf_raw_err = 0.0;
3194   double kf_group_err = 0.0;
3195   double sr_accumulator = 0.0;
3196   double abs_mv_in_out_accumulator = 0.0;
3197   const double av_err = get_distribution_av_err(cpi, twopass);
3198   const double mean_mod_score = twopass->mean_mod_score;
3199   vp9_zero(next_frame);
3200 
3201   cpi->common.frame_type = KEY_FRAME;
3202   rc->frames_since_key = 0;
3203 
3204   // Reset the GF group data structures.
3205   vp9_zero(*gf_group);
3206 
3207   // Is this a forced key frame by interval.
3208   rc->this_key_frame_forced = rc->next_key_frame_forced;
3209 
3210   // Clear the alt ref active flag and last group multi arf flags as they
3211   // can never be set for a key frame.
3212   rc->source_alt_ref_active = 0;
3213 
3214   // KF is always a GF so clear frames till next gf counter.
3215   rc->frames_till_gf_update_due = 0;
3216 
3217   rc->frames_to_key = 1;
3218 
3219   twopass->kf_group_bits = 0;          // Total bits available to kf group
3220   twopass->kf_group_error_left = 0.0;  // Group modified error score.
3221 
3222   kf_raw_err = keyframe_stats->intra_error;
3223   kf_mod_err = calc_norm_frame_score(oxcf, frame_info, keyframe_stats,
3224                                      mean_mod_score, av_err);
3225 
3226   rc->frames_to_key = vp9_get_frames_to_next_key(oxcf, twopass, kf_show_idx,
3227                                                  rc->min_gf_interval);
3228 
3229   // If there is a max kf interval set by the user we must obey it.
3230   // We already breakout of the loop above at 2x max.
3231   // This code centers the extra kf if the actual natural interval
3232   // is between 1x and 2x.
3233   if (rc->frames_to_key >= cpi->oxcf.key_freq) {
3234     rc->next_key_frame_forced = 1;
3235   } else {
3236     rc->next_key_frame_forced = 0;
3237   }
3238 
3239   for (i = 0; i < rc->frames_to_key; ++i) {
3240     const FIRSTPASS_STATS *frame_stats =
3241         fps_get_frame_stats(first_pass_info, kf_show_idx + i);
3242     // Accumulate kf group error.
3243     kf_group_err += calc_norm_frame_score(oxcf, frame_info, frame_stats,
3244                                           mean_mod_score, av_err);
3245   }
3246 
3247   // Calculate the number of bits that should be assigned to the kf group.
3248   if (twopass->bits_left > 0 && twopass->normalized_score_left > 0.0) {
3249     // Maximum number of bits for a single normal frame (not key frame).
3250     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
3251 
3252     // Maximum number of bits allocated to the key frame group.
3253     int64_t max_grp_bits;
3254 
3255     // Default allocation based on bits left and relative
3256     // complexity of the section.
3257     twopass->kf_group_bits = (int64_t)(
3258         twopass->bits_left * (kf_group_err / twopass->normalized_score_left));
3259 
3260     // Clip based on maximum per frame rate defined by the user.
3261     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
3262     if (twopass->kf_group_bits > max_grp_bits)
3263       twopass->kf_group_bits = max_grp_bits;
3264   } else {
3265     twopass->kf_group_bits = 0;
3266   }
3267   twopass->kf_group_bits = VPXMAX(0, twopass->kf_group_bits);
3268 
3269   // Scan through the kf group collating various stats used to determine
3270   // how many bits to spend on it.
3271   boost_score = 0.0;
3272 
3273   for (i = 0; i < VPXMIN(MAX_SCAN_FRAMES_FOR_KF_BOOST, (rc->frames_to_key - 1));
3274        ++i) {
3275     if (EOF == input_stats(twopass, &next_frame)) break;
3276 
3277     zero_motion_sum += next_frame.pcnt_inter - next_frame.pcnt_motion;
3278     motion_compensable_sum +=
3279         1 - (double)next_frame.coded_error / next_frame.intra_error;
3280     num_frames++;
3281   }
3282 
3283   if (num_frames >= MIN_SCAN_FRAMES_FOR_KF_BOOST) {
3284     zero_motion_avg = zero_motion_sum / num_frames;
3285     motion_compensable_avg = motion_compensable_sum / num_frames;
3286     kf_boost_scan_frames = (int)(VPXMAX(64 * zero_motion_avg - 16,
3287                                         160 * motion_compensable_avg - 112));
3288     kf_boost_scan_frames =
3289         VPXMAX(VPXMIN(kf_boost_scan_frames, MAX_SCAN_FRAMES_FOR_KF_BOOST),
3290                MIN_SCAN_FRAMES_FOR_KF_BOOST);
3291   }
3292   reset_fpf_position(twopass, start_position);
3293 
3294   for (i = 0; i < (rc->frames_to_key - 1); ++i) {
3295     if (EOF == input_stats(twopass, &next_frame)) break;
3296 
3297     // The zero motion test here insures that if we mark a kf group as static
3298     // it is static throughout not just the first KF_BOOST_SCAN_MAX_FRAMES.
3299     // It also allows for a larger boost on long static groups.
3300     if ((i <= kf_boost_scan_frames) || (zero_motion_accumulator >= 0.99)) {
3301       double frame_boost;
3302       double zm_factor;
3303 
3304       // Monitor for static sections.
3305       // First frame in kf group the second ref indicator is invalid.
3306       if (i > 0) {
3307         zero_motion_accumulator =
3308             VPXMIN(zero_motion_accumulator,
3309                    get_zero_motion_factor(twopass, &next_frame));
3310       } else {
3311         zero_motion_accumulator =
3312             next_frame.pcnt_inter - next_frame.pcnt_motion;
3313       }
3314 
3315       // Factor 0.75-1.25 based on how much of frame is static.
3316       zm_factor = (0.75 + (zero_motion_accumulator / 2.0));
3317 
3318       // The second (lagging) ref error is not valid immediately after
3319       // a key frame because either the lag has not built up (in the case of
3320       // the first key frame or it points to a refernce before the new key
3321       // frame.
3322       if (i < 2) sr_accumulator = 0.0;
3323       frame_boost =
3324           calc_kf_frame_boost(cpi, &next_frame, &sr_accumulator, 0, zm_factor);
3325 
3326       boost_score += frame_boost;
3327 
3328       // Measure of zoom. Large zoom tends to indicate reduced boost.
3329       abs_mv_in_out_accumulator +=
3330           fabs(next_frame.mv_in_out_count * next_frame.pcnt_motion);
3331 
3332       if ((frame_boost < 25.00) ||
3333           (abs_mv_in_out_accumulator > KF_ABS_ZOOM_THRESH) ||
3334           (sr_accumulator > (kf_raw_err * 1.50)))
3335         break;
3336     } else {
3337       break;
3338     }
3339   }
3340 
3341   reset_fpf_position(twopass, start_position);
3342 
3343   // Store the zero motion percentage
3344   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
3345 
3346   // Calculate a section intra ratio used in setting max loop filter.
3347   twopass->key_frame_section_intra_rating = calculate_section_intra_ratio(
3348       start_position, twopass->stats_in_end, rc->frames_to_key);
3349 
3350   // Special case for static / slide show content but dont apply
3351   // if the kf group is very short.
3352   if ((zero_motion_accumulator > 0.99) && (rc->frames_to_key > 8)) {
3353     rc->kf_boost = (int)(twopass->kf_max_total_boost);
3354   } else {
3355     // Apply various clamps for min and max oost
3356     rc->kf_boost = VPXMAX((int)boost_score, (rc->frames_to_key * 3));
3357     rc->kf_boost = VPXMAX(rc->kf_boost, MIN_KF_TOT_BOOST);
3358     rc->kf_boost = VPXMIN(rc->kf_boost, (int)(twopass->kf_max_total_boost));
3359   }
3360 
3361   // Work out how many bits to allocate for the key frame itself.
3362   kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
3363                                  twopass->kf_group_bits);
3364   // Based on the spatial complexity, increase the bits allocated to key frame.
3365   kf_bits +=
3366       (int)((twopass->kf_group_bits - kf_bits) * (kf_mod_err / kf_group_err));
3367   max_kf_bits =
3368       twopass->kf_group_bits - (rc->frames_to_key - 1) * FRAME_OVERHEAD_BITS;
3369   max_kf_bits = lclamp(max_kf_bits, 0, INT_MAX);
3370   kf_bits = VPXMIN(kf_bits, (int)max_kf_bits);
3371 
3372   twopass->kf_group_bits -= kf_bits;
3373 
3374   // Save the bits to spend on the key frame.
3375   gf_group->bit_allocation[0] = kf_bits;
3376   gf_group->update_type[0] = KF_UPDATE;
3377   gf_group->rf_level[0] = KF_STD;
3378   gf_group->layer_depth[0] = 0;
3379 
3380   // Note the total error score of the kf group minus the key frame itself.
3381   twopass->kf_group_error_left = (kf_group_err - kf_mod_err);
3382 
3383   // Adjust the count of total modified error left.
3384   // The count of bits left is adjusted elsewhere based on real coded frame
3385   // sizes.
3386   twopass->normalized_score_left -= kf_group_err;
3387 
3388   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
3389     // Default to normal-sized frame on keyframes.
3390     cpi->rc.next_frame_size_selector = UNSCALED;
3391   }
3392 }
3393 
3394 // Configure image size specific vizier parameters.
3395 // Later these will be set via additional command line options
vp9_init_vizier_params(TWO_PASS * const twopass,int screen_area)3396 void vp9_init_vizier_params(TWO_PASS *const twopass, int screen_area) {
3397   // When |use_vizier_rc_params| is 1, we expect the rc parameters below to
3398   // have been initialised on the command line as adjustment factors such
3399   // that a factor of 1.0 will match the default behavior when
3400   // |use_vizier_rc_params| is 0
3401   if (twopass->use_vizier_rc_params) {
3402     twopass->active_wq_factor *= AV_WQ_FACTOR;
3403     twopass->err_per_mb *= BASELINE_ERR_PER_MB;
3404     twopass->sr_default_decay_limit *= DEFAULT_DECAY_LIMIT;
3405     if (twopass->sr_default_decay_limit > 1.0)  // > 1.0 here makes no sense
3406       twopass->sr_default_decay_limit = 1.0;
3407     twopass->sr_diff_factor *= 1.0;
3408     twopass->gf_frame_max_boost *= GF_MAX_FRAME_BOOST;
3409     twopass->gf_max_total_boost *= MAX_GF_BOOST;
3410     // NOTE: In use max boost has precedence over min boost. So even if min is
3411     // somehow set higher than max the final boost value will be clamped to the
3412     // appropriate maximum.
3413     twopass->kf_frame_min_boost *= KF_MIN_FRAME_BOOST;
3414     twopass->kf_frame_max_boost_first *= KF_MAX_FRAME_BOOST;
3415     twopass->kf_frame_max_boost_subs *= KF_MAX_FRAME_BOOST;
3416     twopass->kf_max_total_boost *= MAX_KF_TOT_BOOST;
3417     twopass->zm_factor *= DEFAULT_ZM_FACTOR;
3418     if (twopass->zm_factor > 1.0)  // > 1.0 here makes no sense
3419       twopass->zm_factor = 1.0;
3420 
3421     // Correction for the fact that the kf_err_per_mb_factor default is
3422     // already different for different video formats and ensures that a passed
3423     // in value of 1.0 on the vizier command line will still match the current
3424     // default.
3425     if (screen_area < 1280 * 720) {
3426       twopass->kf_err_per_mb *= 2000.0;
3427     } else if (screen_area < 1920 * 1080) {
3428       twopass->kf_err_per_mb *= 500.0;
3429     } else {
3430       twopass->kf_err_per_mb *= 250.0;
3431     }
3432   } else {
3433     // When |use_vizier_rc_params| is 0, use defaults.
3434     twopass->active_wq_factor = AV_WQ_FACTOR;
3435     twopass->err_per_mb = BASELINE_ERR_PER_MB;
3436     twopass->sr_default_decay_limit = DEFAULT_DECAY_LIMIT;
3437     twopass->sr_diff_factor = 1.0;
3438     twopass->gf_frame_max_boost = GF_MAX_FRAME_BOOST;
3439     twopass->gf_max_total_boost = MAX_GF_BOOST;
3440     twopass->kf_frame_min_boost = KF_MIN_FRAME_BOOST;
3441     twopass->kf_frame_max_boost_first = KF_MAX_FRAME_BOOST;
3442     twopass->kf_frame_max_boost_subs = KF_MAX_FRAME_BOOST;
3443     twopass->kf_max_total_boost = MAX_KF_TOT_BOOST;
3444     twopass->zm_factor = DEFAULT_ZM_FACTOR;
3445 
3446     if (screen_area < 1280 * 720) {
3447       twopass->kf_err_per_mb = 2000.0;
3448     } else if (screen_area < 1920 * 1080) {
3449       twopass->kf_err_per_mb = 500.0;
3450     } else {
3451       twopass->kf_err_per_mb = 250.0;
3452     }
3453   }
3454 }
3455 
vp9_rc_get_second_pass_params(VP9_COMP * cpi)3456 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
3457   VP9_COMMON *const cm = &cpi->common;
3458   RATE_CONTROL *const rc = &cpi->rc;
3459   TWO_PASS *const twopass = &cpi->twopass;
3460   GF_GROUP *const gf_group = &twopass->gf_group;
3461   FIRSTPASS_STATS this_frame;
3462   const int show_idx = cm->current_video_frame;
3463 
3464   if (!twopass->stats_in) return;
3465 
3466   // Configure image size specific vizier parameters
3467   if (cm->current_video_frame == 0) {
3468     unsigned int screen_area = (cm->width * cm->height);
3469 
3470     vp9_init_vizier_params(twopass, screen_area);
3471   }
3472 
3473   // If this is an arf frame then we dont want to read the stats file or
3474   // advance the input pointer as we already have what we need.
3475   if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
3476     int target_rate;
3477 
3478     vp9_zero(this_frame);
3479     this_frame =
3480         cpi->twopass.stats_in_start[cm->current_video_frame +
3481                                     gf_group->arf_src_offset[gf_group->index]];
3482 
3483     vp9_configure_buffer_updates(cpi, gf_group->index);
3484 
3485     target_rate = gf_group->bit_allocation[gf_group->index];
3486     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
3487     rc->base_frame_target = target_rate;
3488 
3489     cm->frame_type = INTER_FRAME;
3490 
3491     // The multiplication by 256 reverses a scaling factor of (>> 8)
3492     // applied when combining MB error values for the frame.
3493     twopass->mb_av_energy = log((this_frame.intra_error * 256.0) + 1.0);
3494     twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
3495 
3496     return;
3497   }
3498 
3499   vpx_clear_system_state();
3500 
3501   if (cpi->oxcf.rc_mode == VPX_Q) {
3502     twopass->active_worst_quality = cpi->oxcf.cq_level;
3503   } else if (cm->current_video_frame == 0) {
3504     const int frames_left =
3505         (int)(twopass->total_stats.count - cm->current_video_frame);
3506     // Special case code for first frame.
3507     const int section_target_bandwidth =
3508         (int)(twopass->bits_left / frames_left);
3509     const double section_length = twopass->total_left_stats.count;
3510     const double section_error =
3511         twopass->total_left_stats.coded_error / section_length;
3512     const double section_intra_skip =
3513         twopass->total_left_stats.intra_skip_pct / section_length;
3514     const double section_inactive_zone =
3515         (twopass->total_left_stats.inactive_zone_rows * 2) /
3516         ((double)cm->mb_rows * section_length);
3517     const double section_noise =
3518         twopass->total_left_stats.frame_noise_energy / section_length;
3519     int tmp_q;
3520 
3521     tmp_q = get_twopass_worst_quality(
3522         cpi, section_error, section_intra_skip + section_inactive_zone,
3523         section_noise, section_target_bandwidth);
3524 
3525     twopass->active_worst_quality = tmp_q;
3526     twopass->baseline_active_worst_quality = tmp_q;
3527     rc->ni_av_qi = tmp_q;
3528     rc->last_q[INTER_FRAME] = tmp_q;
3529     rc->avg_q = vp9_convert_qindex_to_q(tmp_q, cm->bit_depth);
3530     rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
3531     rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
3532     rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
3533   }
3534   vp9_zero(this_frame);
3535   if (EOF == input_stats(twopass, &this_frame)) return;
3536 
3537   // Set the frame content type flag.
3538   if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
3539     twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
3540   else
3541     twopass->fr_content_type = FC_NORMAL;
3542 
3543   // Keyframe and section processing.
3544   if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
3545     // Define next KF group and assign bits to it.
3546     find_next_key_frame(cpi, show_idx);
3547   } else {
3548     cm->frame_type = INTER_FRAME;
3549   }
3550 
3551   // Define a new GF/ARF group. (Should always enter here for key frames).
3552   if (rc->frames_till_gf_update_due == 0) {
3553     define_gf_group(cpi, show_idx);
3554 
3555     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3556 
3557 #if ARF_STATS_OUTPUT
3558     {
3559       FILE *fpfile;
3560       fpfile = fopen("arf.stt", "a");
3561       ++arf_count;
3562       fprintf(fpfile, "%10d %10ld %10d %10d %10ld %10ld\n",
3563               cm->current_video_frame, rc->frames_till_gf_update_due,
3564               rc->kf_boost, arf_count, rc->gfu_boost, cm->frame_type);
3565 
3566       fclose(fpfile);
3567     }
3568 #endif
3569   }
3570 
3571   vp9_configure_buffer_updates(cpi, gf_group->index);
3572 
3573   rc->base_frame_target = gf_group->bit_allocation[gf_group->index];
3574 
3575   // The multiplication by 256 reverses a scaling factor of (>> 8)
3576   // applied when combining MB error values for the frame.
3577   twopass->mb_av_energy = log((this_frame.intra_error * 256.0) + 1.0);
3578   twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
3579 
3580   // Update the total stats remaining structure.
3581   subtract_stats(&twopass->total_left_stats, &this_frame);
3582 }
3583 
vp9_twopass_postencode_update(VP9_COMP * cpi)3584 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
3585   TWO_PASS *const twopass = &cpi->twopass;
3586   RATE_CONTROL *const rc = &cpi->rc;
3587   VP9_COMMON *const cm = &cpi->common;
3588   const int bits_used = rc->base_frame_target;
3589 
3590   // VBR correction is done through rc->vbr_bits_off_target. Based on the
3591   // sign of this value, a limited % adjustment is made to the target rate
3592   // of subsequent frames, to try and push it back towards 0. This method
3593   // is designed to prevent extreme behaviour at the end of a clip
3594   // or group of frames.
3595   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
3596   twopass->bits_left = VPXMAX(twopass->bits_left - bits_used, 0);
3597 
3598   // Target vs actual bits for this arf group.
3599   twopass->rolling_arf_group_target_bits += rc->this_frame_target;
3600   twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
3601 
3602   // Calculate the pct rc error.
3603   if (rc->total_actual_bits) {
3604     rc->rate_error_estimate =
3605         (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
3606     rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
3607   } else {
3608     rc->rate_error_estimate = 0;
3609   }
3610 
3611   if (cpi->common.frame_type != KEY_FRAME) {
3612     twopass->kf_group_bits -= bits_used;
3613     twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
3614   }
3615   twopass->kf_group_bits = VPXMAX(twopass->kf_group_bits, 0);
3616 
3617   // Increment the gf group index ready for the next frame.
3618   ++twopass->gf_group.index;
3619 
3620   // If the rate control is drifting consider adjustment to min or maxq.
3621   if ((cpi->oxcf.rc_mode != VPX_Q) && !cpi->rc.is_src_frame_alt_ref) {
3622     const int maxq_adj_limit =
3623         rc->worst_quality - twopass->active_worst_quality;
3624     const int minq_adj_limit =
3625         (cpi->oxcf.rc_mode == VPX_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
3626     int aq_extend_min = 0;
3627     int aq_extend_max = 0;
3628 
3629     // Extend min or Max Q range to account for imbalance from the base
3630     // value when using AQ.
3631     if (cpi->oxcf.aq_mode != NO_AQ && cpi->oxcf.aq_mode != PSNR_AQ &&
3632         cpi->oxcf.aq_mode != PERCEPTUAL_AQ) {
3633       if (cm->seg.aq_av_offset < 0) {
3634         // The balance of the AQ map tends towarda lowering the average Q.
3635         aq_extend_min = 0;
3636         aq_extend_max = VPXMIN(maxq_adj_limit, -cm->seg.aq_av_offset);
3637       } else {
3638         // The balance of the AQ map tends towards raising the average Q.
3639         aq_extend_min = VPXMIN(minq_adj_limit, cm->seg.aq_av_offset);
3640         aq_extend_max = 0;
3641       }
3642     }
3643 
3644     // Undershoot.
3645     if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
3646       --twopass->extend_maxq;
3647       if (rc->rolling_target_bits >= rc->rolling_actual_bits)
3648         ++twopass->extend_minq;
3649       // Overshoot.
3650     } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
3651       --twopass->extend_minq;
3652       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3653         ++twopass->extend_maxq;
3654     } else {
3655       // Adjustment for extreme local overshoot.
3656       if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
3657           rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
3658         ++twopass->extend_maxq;
3659 
3660       // Unwind undershoot or overshoot adjustment.
3661       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3662         --twopass->extend_minq;
3663       else if (rc->rolling_target_bits > rc->rolling_actual_bits)
3664         --twopass->extend_maxq;
3665     }
3666 
3667     twopass->extend_minq =
3668         clamp(twopass->extend_minq, aq_extend_min, minq_adj_limit);
3669     twopass->extend_maxq =
3670         clamp(twopass->extend_maxq, aq_extend_max, maxq_adj_limit);
3671 
3672     // If there is a big and undexpected undershoot then feed the extra
3673     // bits back in quickly. One situation where this may happen is if a
3674     // frame is unexpectedly almost perfectly predicted by the ARF or GF
3675     // but not very well predcited by the previous frame.
3676     if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
3677       int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
3678       if (rc->projected_frame_size < fast_extra_thresh) {
3679         rc->vbr_bits_off_target_fast +=
3680             fast_extra_thresh - rc->projected_frame_size;
3681         rc->vbr_bits_off_target_fast =
3682             VPXMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
3683 
3684         // Fast adaptation of minQ if necessary to use up the extra bits.
3685         if (rc->avg_frame_bandwidth) {
3686           twopass->extend_minq_fast =
3687               (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
3688         }
3689         twopass->extend_minq_fast = VPXMIN(
3690             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3691       } else if (rc->vbr_bits_off_target_fast) {
3692         twopass->extend_minq_fast = VPXMIN(
3693             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3694       } else {
3695         twopass->extend_minq_fast = 0;
3696       }
3697     }
3698   }
3699 }
3700 
3701 #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)3702 void vp9_get_next_group_of_picture(const VP9_COMP *cpi, int *first_is_key_frame,
3703                                    int *use_alt_ref, int *coding_frame_count,
3704                                    int *first_show_idx,
3705                                    int *last_gop_use_alt_ref) {
3706   const GOP_COMMAND *gop_command = &cpi->encode_command.gop_command;
3707   // We make a copy of rc here because we want to get information from the
3708   // encoder without changing its state.
3709   // TODO(angiebird): Avoid copying rc here.
3710   RATE_CONTROL rc = cpi->rc;
3711   const int multi_layer_arf = 0;
3712   const int allow_alt_ref = 1;
3713   // We assume that current_video_frame is updated to the show index of the
3714   // frame we are about to called. Note that current_video_frame is updated at
3715   // the end of encode_frame_to_data_rate().
3716   // TODO(angiebird): Avoid this kind of fragile style.
3717   *first_show_idx = cpi->common.current_video_frame;
3718   *last_gop_use_alt_ref = rc.source_alt_ref_active;
3719 
3720   *first_is_key_frame = 0;
3721   if (rc.frames_to_key == 0) {
3722     rc.frames_to_key = vp9_get_frames_to_next_key(
3723         &cpi->oxcf, &cpi->twopass, *first_show_idx, rc.min_gf_interval);
3724     rc.frames_since_key = 0;
3725     *first_is_key_frame = 1;
3726   }
3727 
3728   if (gop_command->use) {
3729     *coding_frame_count = gop_command_coding_frame_count(gop_command);
3730     *use_alt_ref = gop_command->use_alt_ref;
3731     assert(gop_command->show_frame_count <= rc.frames_to_key);
3732   } else {
3733     *coding_frame_count = vp9_get_gop_coding_frame_count(
3734         &cpi->oxcf, &cpi->twopass, &cpi->frame_info, &rc, *first_show_idx,
3735         multi_layer_arf, allow_alt_ref, *first_is_key_frame,
3736         *last_gop_use_alt_ref, use_alt_ref);
3737   }
3738 }
3739 
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)3740 int vp9_get_gop_coding_frame_count(const VP9EncoderConfig *oxcf,
3741                                    const TWO_PASS *const twopass,
3742                                    const FRAME_INFO *frame_info,
3743                                    const RATE_CONTROL *rc, int show_idx,
3744                                    int multi_layer_arf, int allow_alt_ref,
3745                                    int first_is_key_frame,
3746                                    int last_gop_use_alt_ref, int *use_alt_ref) {
3747   int frame_count;
3748   double gop_intra_factor;
3749   const int arf_active_or_kf = last_gop_use_alt_ref || first_is_key_frame;
3750   RANGE active_gf_interval;
3751   int arf_layers;
3752   if (oxcf->use_simple_encode_api) {
3753     active_gf_interval = get_active_gf_inverval_range_simple(
3754         rc->min_gf_interval, arf_active_or_kf, rc->frames_to_key);
3755   } else {
3756     active_gf_interval = get_active_gf_inverval_range(
3757         frame_info, rc, arf_active_or_kf, show_idx, /*active_worst_quality=*/0,
3758         /*last_boosted_qindex=*/0);
3759   }
3760 
3761   arf_layers = get_arf_layers(multi_layer_arf, oxcf->enable_auto_arf,
3762                               active_gf_interval.max);
3763   if (multi_layer_arf) {
3764     gop_intra_factor = 1.0 + 0.25 * arf_layers;
3765   } else {
3766     gop_intra_factor = 1.0;
3767   }
3768 
3769   frame_count = get_gop_coding_frame_num(use_alt_ref, frame_info, twopass, rc,
3770                                          show_idx, &active_gf_interval,
3771                                          gop_intra_factor, oxcf->lag_in_frames);
3772   *use_alt_ref &= allow_alt_ref;
3773   return frame_count;
3774 }
3775 
3776 // Under CONFIG_RATE_CTRL, once the first_pass_info is ready, the number of
3777 // 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)3778 int vp9_get_coding_frame_num(const VP9EncoderConfig *oxcf,
3779                              const TWO_PASS *const twopass,
3780                              const FRAME_INFO *frame_info, int multi_layer_arf,
3781                              int allow_alt_ref) {
3782   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3783   int coding_frame_num = 0;
3784   RATE_CONTROL rc;
3785   int gop_coding_frame_count;
3786   int gop_show_frames;
3787   int show_idx = 0;
3788   int last_gop_use_alt_ref = 0;
3789   vp9_rc_init(oxcf, 1, &rc);
3790 
3791   while (show_idx < first_pass_info->num_frames) {
3792     int use_alt_ref;
3793     int first_is_key_frame = 0;
3794     if (rc.frames_to_key == 0) {
3795       rc.frames_to_key = vp9_get_frames_to_next_key(oxcf, twopass, show_idx,
3796                                                     rc.min_gf_interval);
3797       rc.frames_since_key = 0;
3798       first_is_key_frame = 1;
3799     }
3800 
3801     gop_coding_frame_count = vp9_get_gop_coding_frame_count(
3802         oxcf, twopass, frame_info, &rc, show_idx, multi_layer_arf,
3803         allow_alt_ref, first_is_key_frame, last_gop_use_alt_ref, &use_alt_ref);
3804 
3805     rc.source_alt_ref_active = use_alt_ref;
3806     last_gop_use_alt_ref = use_alt_ref;
3807     gop_show_frames = gop_coding_frame_count - use_alt_ref;
3808     rc.frames_to_key -= gop_show_frames;
3809     rc.frames_since_key += gop_show_frames;
3810     show_idx += gop_show_frames;
3811     coding_frame_num += gop_show_frames + use_alt_ref;
3812   }
3813   return coding_frame_num;
3814 }
3815 
vp9_get_key_frame_map(const VP9EncoderConfig * oxcf,const TWO_PASS * const twopass,int * key_frame_map)3816 void vp9_get_key_frame_map(const VP9EncoderConfig *oxcf,
3817                            const TWO_PASS *const twopass, int *key_frame_map) {
3818   const FIRST_PASS_INFO *first_pass_info = &twopass->first_pass_info;
3819   int show_idx = 0;
3820   RATE_CONTROL rc;
3821   vp9_rc_init(oxcf, 1, &rc);
3822 
3823   // key_frame_map points to an int array with size equal to
3824   // first_pass_info->num_frames, which is also the number of show frames in the
3825   // video.
3826   memset(key_frame_map, 0,
3827          sizeof(*key_frame_map) * first_pass_info->num_frames);
3828   while (show_idx < first_pass_info->num_frames) {
3829     int key_frame_group_size;
3830     key_frame_map[show_idx] = 1;
3831     key_frame_group_size =
3832         vp9_get_frames_to_next_key(oxcf, twopass, show_idx, rc.min_gf_interval);
3833     assert(key_frame_group_size > 0);
3834     show_idx += key_frame_group_size;
3835   }
3836   assert(show_idx == first_pass_info->num_frames);
3837 }
3838 #endif  // CONFIG_RATE_CTRL
3839 
vp9_get_frame_stats(const TWO_PASS * twopass)3840 FIRSTPASS_STATS vp9_get_frame_stats(const TWO_PASS *twopass) {
3841   return twopass->this_frame_stats;
3842 }
vp9_get_total_stats(const TWO_PASS * twopass)3843 FIRSTPASS_STATS vp9_get_total_stats(const TWO_PASS *twopass) {
3844   return twopass->total_stats;
3845 }
3846