]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_firstpass.c
Add casting to fix warning.
[libvpx] / vp9 / encoder / vp9_firstpass.c
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_extend.h"
35 #include "vp9/encoder/vp9_firstpass.h"
36 #include "vp9/encoder/vp9_mcomp.h"
37 #include "vp9/encoder/vp9_quantize.h"
38 #include "vp9/encoder/vp9_rd.h"
39 #include "vpx_dsp/variance.h"
40
41 #define OUTPUT_FPF 0
42 #define ARF_STATS_OUTPUT 0
43
44 #define BOOST_BREAKOUT 12.5
45 #define BOOST_FACTOR 12.5
46 #define FACTOR_PT_LOW 0.70
47 #define FACTOR_PT_HIGH 0.90
48 #define FIRST_PASS_Q 10.0
49 #define GF_MAX_BOOST 96.0
50 #define INTRA_MODE_PENALTY 1024
51 #define KF_MAX_BOOST 128.0
52 #define MIN_ARF_GF_BOOST 240
53 #define MIN_DECAY_FACTOR 0.01
54 #define MIN_KF_BOOST 300
55 #define NEW_MV_MODE_PENALTY 32
56 #define SVC_FACTOR_PT_LOW 0.45
57 #define DARK_THRESH 64
58 #define DEFAULT_GRP_WEIGHT 1.0
59 #define RC_FACTOR_MIN 0.75
60 #define RC_FACTOR_MAX 1.75
61 #define SECTION_NOISE_DEF 250.0
62 #define LOW_I_THRESH 24000
63
64 #define NCOUNT_INTRA_THRESH 8192
65 #define NCOUNT_INTRA_FACTOR 3
66
67 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x)-0.000001 : (x) + 0.000001)
68
69 #if ARF_STATS_OUTPUT
70 unsigned int arf_count = 0;
71 #endif
72
73 // Resets the first pass file to the given position using a relative seek from
74 // the current position.
75 static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
76   p->stats_in = position;
77 }
78
79 // Read frame stats at an offset from the current position.
80 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
81   if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
82       (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
83     return NULL;
84   }
85
86   return &p->stats_in[offset];
87 }
88
89 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
90   if (p->stats_in >= p->stats_in_end) return EOF;
91
92   *fps = *p->stats_in;
93   ++p->stats_in;
94   return 1;
95 }
96
97 static void output_stats(FIRSTPASS_STATS *stats,
98                          struct vpx_codec_pkt_list *pktlist) {
99   struct vpx_codec_cx_pkt pkt;
100   pkt.kind = VPX_CODEC_STATS_PKT;
101   pkt.data.twopass_stats.buf = stats;
102   pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
103   vpx_codec_pkt_list_add(pktlist, &pkt);
104
105 // TEMP debug code
106 #if OUTPUT_FPF
107   {
108     FILE *fpfile;
109     fpfile = fopen("firstpass.stt", "a");
110
111     fprintf(fpfile,
112             "%12.0lf %12.4lf %12.0lf %12.0lf %12.0lf %12.0lf %12.4lf"
113             "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
114             "%12.4lf %12.4lf %12.4lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf"
115             "\n",
116             stats->frame, stats->weight, stats->intra_error, stats->coded_error,
117             stats->sr_coded_error, stats->frame_noise_energy, stats->pcnt_inter,
118             stats->pcnt_motion, stats->pcnt_second_ref, stats->pcnt_neutral,
119             stats->intra_skip_pct, stats->intra_smooth_pct,
120             stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
121             stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
122             stats->MVcv, stats->mv_in_out_count, stats->new_mv_count,
123             stats->count, stats->duration);
124     fclose(fpfile);
125   }
126 #endif
127 }
128
129 #if CONFIG_FP_MB_STATS
130 static void output_fpmb_stats(uint8_t *this_frame_mb_stats, VP9_COMMON *cm,
131                               struct vpx_codec_pkt_list *pktlist) {
132   struct vpx_codec_cx_pkt pkt;
133   pkt.kind = VPX_CODEC_FPMB_STATS_PKT;
134   pkt.data.firstpass_mb_stats.buf = this_frame_mb_stats;
135   pkt.data.firstpass_mb_stats.sz = cm->initial_mbs * sizeof(uint8_t);
136   vpx_codec_pkt_list_add(pktlist, &pkt);
137 }
138 #endif
139
140 static void zero_stats(FIRSTPASS_STATS *section) {
141   section->frame = 0.0;
142   section->weight = 0.0;
143   section->intra_error = 0.0;
144   section->coded_error = 0.0;
145   section->sr_coded_error = 0.0;
146   section->frame_noise_energy = 0.0;
147   section->pcnt_inter = 0.0;
148   section->pcnt_motion = 0.0;
149   section->pcnt_second_ref = 0.0;
150   section->pcnt_neutral = 0.0;
151   section->intra_skip_pct = 0.0;
152   section->intra_smooth_pct = 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->new_mv_count = 0.0;
163   section->count = 0.0;
164   section->duration = 1.0;
165   section->spatial_layer_id = 0;
166 }
167
168 static void accumulate_stats(FIRSTPASS_STATS *section,
169                              const FIRSTPASS_STATS *frame) {
170   section->frame += frame->frame;
171   section->weight += frame->weight;
172   section->spatial_layer_id = frame->spatial_layer_id;
173   section->intra_error += frame->intra_error;
174   section->coded_error += frame->coded_error;
175   section->sr_coded_error += frame->sr_coded_error;
176   section->frame_noise_energy += frame->frame_noise_energy;
177   section->pcnt_inter += frame->pcnt_inter;
178   section->pcnt_motion += frame->pcnt_motion;
179   section->pcnt_second_ref += frame->pcnt_second_ref;
180   section->pcnt_neutral += frame->pcnt_neutral;
181   section->intra_skip_pct += frame->intra_skip_pct;
182   section->intra_smooth_pct += frame->intra_smooth_pct;
183   section->inactive_zone_rows += frame->inactive_zone_rows;
184   section->inactive_zone_cols += frame->inactive_zone_cols;
185   section->MVr += frame->MVr;
186   section->mvr_abs += frame->mvr_abs;
187   section->MVc += frame->MVc;
188   section->mvc_abs += frame->mvc_abs;
189   section->MVrv += frame->MVrv;
190   section->MVcv += frame->MVcv;
191   section->mv_in_out_count += frame->mv_in_out_count;
192   section->new_mv_count += frame->new_mv_count;
193   section->count += frame->count;
194   section->duration += frame->duration;
195 }
196
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->inactive_zone_rows -= frame->inactive_zone_rows;
212   section->inactive_zone_cols -= frame->inactive_zone_cols;
213   section->MVr -= frame->MVr;
214   section->mvr_abs -= frame->mvr_abs;
215   section->MVc -= frame->MVc;
216   section->mvc_abs -= frame->mvc_abs;
217   section->MVrv -= frame->MVrv;
218   section->MVcv -= frame->MVcv;
219   section->mv_in_out_count -= frame->mv_in_out_count;
220   section->new_mv_count -= frame->new_mv_count;
221   section->count -= frame->count;
222   section->duration -= frame->duration;
223 }
224
225 // Calculate an active area of the image that discounts formatting
226 // bars and partially discounts other 0 energy areas.
227 #define MIN_ACTIVE_AREA 0.5
228 #define MAX_ACTIVE_AREA 1.0
229 static double calculate_active_area(const VP9_COMP *cpi,
230                                     const FIRSTPASS_STATS *this_frame) {
231   double active_pct;
232
233   active_pct =
234       1.0 -
235       ((this_frame->intra_skip_pct / 2) +
236        ((this_frame->inactive_zone_rows * 2) / (double)cpi->common.mb_rows));
237   return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
238 }
239
240 // Calculate a modified Error used in distributing bits between easier and
241 // harder frames.
242 #define ACT_AREA_CORRECTION 0.5
243 static double calculate_modified_err(const VP9_COMP *cpi,
244                                      const TWO_PASS *twopass,
245                                      const VP9EncoderConfig *oxcf,
246                                      const FIRSTPASS_STATS *this_frame) {
247   const FIRSTPASS_STATS *const stats = &twopass->total_stats;
248   const double av_weight = stats->weight / stats->count;
249   const double av_err = (stats->coded_error * av_weight) / stats->count;
250   double modified_error =
251       av_err * pow(this_frame->coded_error * this_frame->weight /
252                        DOUBLE_DIVIDE_CHECK(av_err),
253                    oxcf->two_pass_vbrbias / 100.0);
254
255   // Correction for active area. Frames with a reduced active area
256   // (eg due to formatting bars) have a higher error per mb for the
257   // remaining active MBs. The correction here assumes that coding
258   // 0.5N blocks of complexity 2X is a little easier than coding N
259   // blocks of complexity X.
260   modified_error *=
261       pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);
262
263   return fclamp(modified_error, twopass->modified_error_min,
264                 twopass->modified_error_max);
265 }
266
267 // This function returns the maximum target rate per frame.
268 static int frame_max_bits(const RATE_CONTROL *rc,
269                           const VP9EncoderConfig *oxcf) {
270   int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
271                       (int64_t)oxcf->two_pass_vbrmax_section) /
272                      100;
273   if (max_bits < 0)
274     max_bits = 0;
275   else if (max_bits > rc->max_frame_bandwidth)
276     max_bits = rc->max_frame_bandwidth;
277
278   return (int)max_bits;
279 }
280
281 void vp9_init_first_pass(VP9_COMP *cpi) {
282   zero_stats(&cpi->twopass.total_stats);
283 }
284
285 void vp9_end_first_pass(VP9_COMP *cpi) {
286   if (is_two_pass_svc(cpi)) {
287     int i;
288     for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
289       output_stats(&cpi->svc.layer_context[i].twopass.total_stats,
290                    cpi->output_pkt_list);
291     }
292   } else {
293     output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
294   }
295 }
296
297 static vpx_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
298   switch (bsize) {
299     case BLOCK_8X8: return vpx_mse8x8;
300     case BLOCK_16X8: return vpx_mse16x8;
301     case BLOCK_8X16: return vpx_mse8x16;
302     default: return vpx_mse16x16;
303   }
304 }
305
306 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
307                                          const struct buf_2d *src,
308                                          const struct buf_2d *ref) {
309   unsigned int sse;
310   const vpx_variance_fn_t fn = get_block_variance_fn(bsize);
311   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
312   return sse;
313 }
314
315 #if CONFIG_VP9_HIGHBITDEPTH
316 static vpx_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
317                                                       int bd) {
318   switch (bd) {
319     default:
320       switch (bsize) {
321         case BLOCK_8X8: return vpx_highbd_8_mse8x8;
322         case BLOCK_16X8: return vpx_highbd_8_mse16x8;
323         case BLOCK_8X16: return vpx_highbd_8_mse8x16;
324         default: return vpx_highbd_8_mse16x16;
325       }
326       break;
327     case 10:
328       switch (bsize) {
329         case BLOCK_8X8: return vpx_highbd_10_mse8x8;
330         case BLOCK_16X8: return vpx_highbd_10_mse16x8;
331         case BLOCK_8X16: return vpx_highbd_10_mse8x16;
332         default: return vpx_highbd_10_mse16x16;
333       }
334       break;
335     case 12:
336       switch (bsize) {
337         case BLOCK_8X8: return vpx_highbd_12_mse8x8;
338         case BLOCK_16X8: return vpx_highbd_12_mse16x8;
339         case BLOCK_8X16: return vpx_highbd_12_mse8x16;
340         default: return vpx_highbd_12_mse16x16;
341       }
342       break;
343   }
344 }
345
346 static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
347                                                 const struct buf_2d *src,
348                                                 const struct buf_2d *ref,
349                                                 int bd) {
350   unsigned int sse;
351   const vpx_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
352   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
353   return sse;
354 }
355 #endif  // CONFIG_VP9_HIGHBITDEPTH
356
357 // Refine the motion search range according to the frame dimension
358 // for first pass test.
359 static int get_search_range(const VP9_COMP *cpi) {
360   int sr = 0;
361   const int dim = VPXMIN(cpi->initial_width, cpi->initial_height);
362
363   while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
364   return sr;
365 }
366
367 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
368                                      const MV *ref_mv, MV *best_mv,
369                                      int *best_motion_err) {
370   MACROBLOCKD *const xd = &x->e_mbd;
371   MV tmp_mv = { 0, 0 };
372   MV ref_mv_full = { ref_mv->row >> 3, ref_mv->col >> 3 };
373   int num00, tmp_err, n;
374   const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
375   vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
376   const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
377
378   int step_param = 3;
379   int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
380   const int sr = get_search_range(cpi);
381   step_param += sr;
382   further_steps -= sr;
383
384   // Override the default variance function to use MSE.
385   v_fn_ptr.vf = get_block_variance_fn(bsize);
386 #if CONFIG_VP9_HIGHBITDEPTH
387   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
388     v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
389   }
390 #endif  // CONFIG_VP9_HIGHBITDEPTH
391
392   // Center the initial step/diamond search on best mv.
393   tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
394                                     step_param, x->sadperbit16, &num00,
395                                     &v_fn_ptr, ref_mv);
396   if (tmp_err < INT_MAX)
397     tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
398   if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
399
400   if (tmp_err < *best_motion_err) {
401     *best_motion_err = tmp_err;
402     *best_mv = tmp_mv;
403   }
404
405   // Carry out further step/diamond searches as necessary.
406   n = num00;
407   num00 = 0;
408
409   while (n < further_steps) {
410     ++n;
411
412     if (num00) {
413       --num00;
414     } else {
415       tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
416                                         step_param + n, x->sadperbit16, &num00,
417                                         &v_fn_ptr, ref_mv);
418       if (tmp_err < INT_MAX)
419         tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
420       if (tmp_err < INT_MAX - new_mv_mode_penalty)
421         tmp_err += new_mv_mode_penalty;
422
423       if (tmp_err < *best_motion_err) {
424         *best_motion_err = tmp_err;
425         *best_mv = tmp_mv;
426       }
427     }
428   }
429 }
430
431 static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
432   if (2 * mb_col + 1 < cm->mi_cols) {
433     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16 : BLOCK_16X8;
434   } else {
435     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16 : BLOCK_8X8;
436   }
437 }
438
439 static int find_fp_qindex(vpx_bit_depth_t bit_depth) {
440   int i;
441
442   for (i = 0; i < QINDEX_RANGE; ++i)
443     if (vp9_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q) break;
444
445   if (i == QINDEX_RANGE) i--;
446
447   return i;
448 }
449
450 static void set_first_pass_params(VP9_COMP *cpi) {
451   VP9_COMMON *const cm = &cpi->common;
452   if (!cpi->refresh_alt_ref_frame &&
453       (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY))) {
454     cm->frame_type = KEY_FRAME;
455   } else {
456     cm->frame_type = INTER_FRAME;
457   }
458   // Do not use periodic key frames.
459   cpi->rc.frames_to_key = INT_MAX;
460 }
461
462 // Scale an sse threshold to account for 8/10/12 bit.
463 static int scale_sse_threshold(VP9_COMMON *cm, int thresh) {
464   int ret_val = thresh;
465 #if CONFIG_VP9_HIGHBITDEPTH
466   if (cm->use_highbitdepth) {
467     switch (cm->bit_depth) {
468       case VPX_BITS_8: ret_val = thresh; break;
469       case VPX_BITS_10: ret_val = thresh >> 4; break;
470       case VPX_BITS_12: ret_val = thresh >> 8; break;
471       default:
472         assert(0 &&
473                "cm->bit_depth should be VPX_BITS_8, "
474                "VPX_BITS_10 or VPX_BITS_12");
475     }
476   }
477 #else
478   (void)cm;
479 #endif  // CONFIG_VP9_HIGHBITDEPTH
480   return ret_val;
481 }
482
483 // This threshold is used to track blocks where to all intents and purposes
484 // the intra prediction error 0. Though the metric we test against
485 // is technically a sse we are mainly interested in blocks where all the pixels
486 // in the 8 bit domain have an error of <= 1 (where error = sse) so a
487 // linear scaling for 10 and 12 bit gives similar results.
488 #define UL_INTRA_THRESH 50
489 static int get_ul_intra_threshold(VP9_COMMON *cm) {
490   int ret_val = UL_INTRA_THRESH;
491 #if CONFIG_VP9_HIGHBITDEPTH
492   if (cm->use_highbitdepth) {
493     switch (cm->bit_depth) {
494       case VPX_BITS_8: ret_val = UL_INTRA_THRESH; break;
495       case VPX_BITS_10: ret_val = UL_INTRA_THRESH << 2; break;
496       case VPX_BITS_12: ret_val = UL_INTRA_THRESH << 4; break;
497       default:
498         assert(0 &&
499                "cm->bit_depth should be VPX_BITS_8, "
500                "VPX_BITS_10 or VPX_BITS_12");
501     }
502   }
503 #else
504   (void)cm;
505 #endif  // CONFIG_VP9_HIGHBITDEPTH
506   return ret_val;
507 }
508
509 #define SMOOTH_INTRA_THRESH 4000
510 static int get_smooth_intra_threshold(VP9_COMMON *cm) {
511   int ret_val = SMOOTH_INTRA_THRESH;
512 #if CONFIG_VP9_HIGHBITDEPTH
513   if (cm->use_highbitdepth) {
514     switch (cm->bit_depth) {
515       case VPX_BITS_8: ret_val = SMOOTH_INTRA_THRESH; break;
516       case VPX_BITS_10: ret_val = SMOOTH_INTRA_THRESH << 4; break;
517       case VPX_BITS_12: ret_val = SMOOTH_INTRA_THRESH << 8; break;
518       default:
519         assert(0 &&
520                "cm->bit_depth should be VPX_BITS_8, "
521                "VPX_BITS_10 or VPX_BITS_12");
522     }
523   }
524 #else
525   (void)cm;
526 #endif  // CONFIG_VP9_HIGHBITDEPTH
527   return ret_val;
528 }
529
530 #define FP_DN_THRESH 8
531 #define FP_MAX_DN_THRESH 16
532 #define KERNEL_SIZE 3
533
534 // Baseline Kernal weights for first pass noise metric
535 static uint8_t fp_dn_kernal_3[KERNEL_SIZE * KERNEL_SIZE] = { 1, 2, 1, 2, 4,
536                                                              2, 1, 2, 1 };
537
538 // Estimate noise at a single point based on the impace of a spatial kernal
539 // on the point value
540 static int fp_estimate_point_noise(uint8_t *src_ptr, const int stride) {
541   int sum_weight = 0;
542   int sum_val = 0;
543   int i, j;
544   int max_diff = 0;
545   int diff;
546   int dn_diff;
547   uint8_t *tmp_ptr;
548   uint8_t *kernal_ptr;
549   uint8_t dn_val;
550   uint8_t centre_val = *src_ptr;
551
552   kernal_ptr = fp_dn_kernal_3;
553
554   // Apply the kernal
555   tmp_ptr = src_ptr - stride - 1;
556   for (i = 0; i < KERNEL_SIZE; ++i) {
557     for (j = 0; j < KERNEL_SIZE; ++j) {
558       diff = abs((int)centre_val - (int)tmp_ptr[j]);
559       max_diff = VPXMAX(max_diff, diff);
560       if (diff <= FP_DN_THRESH) {
561         sum_weight += *kernal_ptr;
562         sum_val += (int)tmp_ptr[j] * (int)*kernal_ptr;
563       }
564       ++kernal_ptr;
565     }
566     tmp_ptr += stride;
567   }
568
569   if (max_diff < FP_MAX_DN_THRESH)
570     // Update the source value with the new filtered value
571     dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
572   else
573     dn_val = *src_ptr;
574
575   // return the noise energy as the square of the difference between the
576   // denoised and raw value.
577   dn_diff = (int)*src_ptr - (int)dn_val;
578   return dn_diff * dn_diff;
579 }
580 #if CONFIG_VP9_HIGHBITDEPTH
581 static int fp_highbd_estimate_point_noise(uint8_t *src_ptr, const int stride) {
582   int sum_weight = 0;
583   int sum_val = 0;
584   int i, j;
585   int max_diff = 0;
586   int diff;
587   int dn_diff;
588   uint8_t *tmp_ptr;
589   uint16_t *tmp_ptr16;
590   uint8_t *kernal_ptr;
591   uint16_t dn_val;
592   uint16_t centre_val = *CONVERT_TO_SHORTPTR(src_ptr);
593
594   kernal_ptr = fp_dn_kernal_3;
595
596   // Apply the kernal
597   tmp_ptr = src_ptr - stride - 1;
598   for (i = 0; i < KERNEL_SIZE; ++i) {
599     tmp_ptr16 = CONVERT_TO_SHORTPTR(tmp_ptr);
600     for (j = 0; j < KERNEL_SIZE; ++j) {
601       diff = abs((int)centre_val - (int)tmp_ptr16[j]);
602       max_diff = VPXMAX(max_diff, diff);
603       if (diff <= FP_DN_THRESH) {
604         sum_weight += *kernal_ptr;
605         sum_val += (int)tmp_ptr16[j] * (int)*kernal_ptr;
606       }
607       ++kernal_ptr;
608     }
609     tmp_ptr += stride;
610   }
611
612   if (max_diff < FP_MAX_DN_THRESH)
613     // Update the source value with the new filtered value
614     dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
615   else
616     dn_val = *CONVERT_TO_SHORTPTR(src_ptr);
617
618   // return the noise energy as the square of the difference between the
619   // denoised and raw value.
620   dn_diff = (int)(*CONVERT_TO_SHORTPTR(src_ptr)) - (int)dn_val;
621   return dn_diff * dn_diff;
622 }
623 #endif
624
625 // Estimate noise for a block.
626 static int fp_estimate_block_noise(MACROBLOCK *x, BLOCK_SIZE bsize) {
627 #if CONFIG_VP9_HIGHBITDEPTH
628   MACROBLOCKD *xd = &x->e_mbd;
629 #endif
630   uint8_t *src_ptr = &x->plane[0].src.buf[0];
631   const int width = num_4x4_blocks_wide_lookup[bsize] * 4;
632   const int height = num_4x4_blocks_high_lookup[bsize] * 4;
633   int w, h;
634   int stride = x->plane[0].src.stride;
635   int block_noise = 0;
636
637   // Sampled points to reduce cost overhead.
638   for (h = 0; h < height; h += 2) {
639     for (w = 0; w < width; w += 2) {
640 #if CONFIG_VP9_HIGHBITDEPTH
641       if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
642         block_noise += fp_highbd_estimate_point_noise(src_ptr, stride);
643       else
644         block_noise += fp_estimate_point_noise(src_ptr, stride);
645 #else
646       block_noise += fp_estimate_point_noise(src_ptr, stride);
647 #endif
648       ++src_ptr;
649     }
650     src_ptr += (stride - width);
651   }
652   return block_noise << 2;  // Scale << 2 to account for sampling.
653 }
654
655 #define INVALID_ROW -1
656 void vp9_first_pass(VP9_COMP *cpi, const struct lookahead_entry *source) {
657   int mb_row, mb_col;
658   MACROBLOCK *const x = &cpi->td.mb;
659   VP9_COMMON *const cm = &cpi->common;
660   MACROBLOCKD *const xd = &x->e_mbd;
661   TileInfo tile;
662   struct macroblock_plane *const p = x->plane;
663   struct macroblockd_plane *const pd = xd->plane;
664   const PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
665   int i;
666
667   int recon_yoffset, recon_uvoffset;
668   int64_t intra_error = 0;
669   int64_t coded_error = 0;
670   int64_t sr_coded_error = 0;
671   int64_t frame_noise_energy = 0;
672
673   int sum_mvr = 0, sum_mvc = 0;
674   int sum_mvr_abs = 0, sum_mvc_abs = 0;
675   int64_t sum_mvrs = 0, sum_mvcs = 0;
676   int mvcount = 0;
677   int intercount = 0;
678   int second_ref_count = 0;
679   const int intrapenalty = INTRA_MODE_PENALTY;
680   double neutral_count;
681   int intra_skip_count = 0;
682   int intra_smooth_count = 0;
683   int image_data_start_row = INVALID_ROW;
684   int new_mv_count = 0;
685   int sum_in_vectors = 0;
686   MV lastmv = { 0, 0 };
687   TWO_PASS *twopass = &cpi->twopass;
688   const MV zero_mv = { 0, 0 };
689   int recon_y_stride, recon_uv_stride, uv_mb_height;
690
691   YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
692   YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
693   YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
694   const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
695
696   LAYER_CONTEXT *const lc =
697       is_two_pass_svc(cpi) ? &cpi->svc.layer_context[cpi->svc.spatial_layer_id]
698                            : NULL;
699   double intra_factor;
700   double brightness_factor;
701   BufferPool *const pool = cm->buffer_pool;
702   MODE_INFO mi_above, mi_left;
703
704   // First pass code requires valid last and new frame buffers.
705   assert(new_yv12 != NULL);
706   assert((lc != NULL) || frame_is_intra_only(cm) || (lst_yv12 != NULL));
707
708 #if CONFIG_FP_MB_STATS
709   if (cpi->use_fp_mb_stats) {
710     vp9_zero_array(cpi->twopass.frame_mb_stats_buf, cm->initial_mbs);
711   }
712 #endif
713
714   vpx_clear_system_state();
715
716   intra_factor = 0.0;
717   brightness_factor = 0.0;
718   neutral_count = 0.0;
719
720   set_first_pass_params(cpi);
721   vp9_set_quantizer(cm, find_fp_qindex(cm->bit_depth));
722
723   if (lc != NULL) {
724     twopass = &lc->twopass;
725
726     cpi->lst_fb_idx = cpi->svc.spatial_layer_id;
727     cpi->ref_frame_flags = VP9_LAST_FLAG;
728
729     if (cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id <
730         REF_FRAMES) {
731       cpi->gld_fb_idx =
732           cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id;
733       cpi->ref_frame_flags |= VP9_GOLD_FLAG;
734       cpi->refresh_golden_frame = (lc->current_video_frame_in_layer == 0);
735     } else {
736       cpi->refresh_golden_frame = 0;
737     }
738
739     if (lc->current_video_frame_in_layer == 0) cpi->ref_frame_flags = 0;
740
741     vp9_scale_references(cpi);
742
743     // Use either last frame or alt frame for motion search.
744     if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
745       first_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
746       if (first_ref_buf == NULL)
747         first_ref_buf = get_ref_frame_buffer(cpi, LAST_FRAME);
748     }
749
750     if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
751       gld_yv12 = vp9_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
752       if (gld_yv12 == NULL) {
753         gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
754       }
755     } else {
756       gld_yv12 = NULL;
757     }
758
759     set_ref_ptrs(cm, xd,
760                  (cpi->ref_frame_flags & VP9_LAST_FLAG) ? LAST_FRAME : NONE,
761                  (cpi->ref_frame_flags & VP9_GOLD_FLAG) ? GOLDEN_FRAME : NONE);
762
763     cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
764                                         &cpi->scaled_source, 0);
765   }
766
767   vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
768
769   vp9_setup_src_planes(x, cpi->Source, 0, 0);
770   vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
771
772   if (!frame_is_intra_only(cm)) {
773     vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
774   }
775
776   xd->mi = cm->mi_grid_visible;
777   xd->mi[0] = cm->mi;
778
779   vp9_frame_init_quantizer(cpi);
780
781   for (i = 0; i < MAX_MB_PLANE; ++i) {
782     p[i].coeff = ctx->coeff_pbuf[i][1];
783     p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
784     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
785     p[i].eobs = ctx->eobs_pbuf[i][1];
786   }
787   x->skip_recode = 0;
788
789   vp9_init_mv_probs(cm);
790   vp9_initialize_rd_consts(cpi);
791
792   // Tiling is ignored in the first pass.
793   vp9_tile_init(&tile, cm, 0, 0);
794
795   recon_y_stride = new_yv12->y_stride;
796   recon_uv_stride = new_yv12->uv_stride;
797   uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
798
799   for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
800     MV best_ref_mv = { 0, 0 };
801
802     // Reset above block coeffs.
803     recon_yoffset = (mb_row * recon_y_stride * 16);
804     recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height);
805
806     // Set up limit values for motion vectors to prevent them extending
807     // outside the UMV borders.
808     x->mv_limits.row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
809     x->mv_limits.row_max =
810         ((cm->mb_rows - 1 - mb_row) * 16) + BORDER_MV_PIXELS_B16;
811
812     for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
813       int this_error;
814       int this_intra_error;
815       const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
816       const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
817       double log_intra;
818       int level_sample;
819
820 #if CONFIG_FP_MB_STATS
821       const int mb_index = mb_row * cm->mb_cols + mb_col;
822 #endif
823
824       vpx_clear_system_state();
825
826       xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
827       xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
828       xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
829       xd->mi[0]->sb_type = bsize;
830       xd->mi[0]->ref_frame[0] = INTRA_FRAME;
831       set_mi_row_col(xd, &tile, mb_row << 1, num_8x8_blocks_high_lookup[bsize],
832                      mb_col << 1, num_8x8_blocks_wide_lookup[bsize],
833                      cm->mi_rows, cm->mi_cols);
834       // Are edges available for intra prediction?
835       // Since the firstpass does not populate the mi_grid_visible,
836       // above_mi/left_mi must be overwritten with a nonzero value when edges
837       // are available.  Required by vp9_predict_intra_block().
838       xd->above_mi = (mb_row != 0) ? &mi_above : NULL;
839       xd->left_mi = (mb_col > tile.mi_col_start) ? &mi_left : NULL;
840
841       // Do intra 16x16 prediction.
842       x->skip_encode = 0;
843       xd->mi[0]->mode = DC_PRED;
844       xd->mi[0]->tx_size =
845           use_dc_pred ? (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
846       vp9_encode_intra_block_plane(x, bsize, 0, 0);
847       this_error = vpx_get_mb_ss(x->plane[0].src_diff);
848       this_intra_error = this_error;
849
850       // Keep a record of blocks that have very low intra error residual
851       // (i.e. are in effect completely flat and untextured in the intra
852       // domain). In natural videos this is uncommon, but it is much more
853       // common in animations, graphics and screen content, so may be used
854       // as a signal to detect these types of content.
855       if (this_error < get_ul_intra_threshold(cm)) {
856         ++intra_skip_count;
857       } else if ((mb_col > 0) && (image_data_start_row == INVALID_ROW)) {
858         image_data_start_row = mb_row;
859       }
860
861       // Blocks that are mainly smooth in the intra domain.
862       // Some special accounting for CQ but also these are better for testing
863       // noise levels.
864       if (this_error < get_smooth_intra_threshold(cm)) {
865         ++intra_smooth_count;
866       }
867
868       // Special case noise measurement for first frame.
869       if (cm->current_video_frame == 0) {
870         if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
871           frame_noise_energy += fp_estimate_block_noise(x, bsize);
872         } else {
873           frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
874         }
875       }
876
877 #if CONFIG_VP9_HIGHBITDEPTH
878       if (cm->use_highbitdepth) {
879         switch (cm->bit_depth) {
880           case VPX_BITS_8: break;
881           case VPX_BITS_10: this_error >>= 4; break;
882           case VPX_BITS_12: this_error >>= 8; break;
883           default:
884             assert(0 &&
885                    "cm->bit_depth should be VPX_BITS_8, "
886                    "VPX_BITS_10 or VPX_BITS_12");
887             return;
888         }
889       }
890 #endif  // CONFIG_VP9_HIGHBITDEPTH
891
892       vpx_clear_system_state();
893       log_intra = log(this_error + 1.0);
894       if (log_intra < 10.0)
895         intra_factor += 1.0 + ((10.0 - log_intra) * 0.05);
896       else
897         intra_factor += 1.0;
898
899 #if CONFIG_VP9_HIGHBITDEPTH
900       if (cm->use_highbitdepth)
901         level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
902       else
903         level_sample = x->plane[0].src.buf[0];
904 #else
905       level_sample = x->plane[0].src.buf[0];
906 #endif
907       if ((level_sample < DARK_THRESH) && (log_intra < 9.0))
908         brightness_factor += 1.0 + (0.01 * (DARK_THRESH - level_sample));
909       else
910         brightness_factor += 1.0;
911
912       // Intrapenalty below deals with situations where the intra and inter
913       // error scores are very low (e.g. a plain black frame).
914       // We do not have special cases in first pass for 0,0 and nearest etc so
915       // all inter modes carry an overhead cost estimate for the mv.
916       // When the error score is very low this causes us to pick all or lots of
917       // INTRA modes and throw lots of key frames.
918       // This penalty adds a cost matching that of a 0,0 mv to the intra case.
919       this_error += intrapenalty;
920
921       // Accumulate the intra error.
922       intra_error += (int64_t)this_error;
923
924 #if CONFIG_FP_MB_STATS
925       if (cpi->use_fp_mb_stats) {
926         // initialization
927         cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
928       }
929 #endif
930
931       // Set up limit values for motion vectors to prevent them extending
932       // outside the UMV borders.
933       x->mv_limits.col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
934       x->mv_limits.col_max =
935           ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
936
937       // Other than for the first frame do a motion search.
938       if ((lc == NULL && cm->current_video_frame > 0) ||
939           (lc != NULL && lc->current_video_frame_in_layer > 0)) {
940         int tmp_err, motion_error, raw_motion_error;
941         // Assume 0,0 motion with no mv overhead.
942         MV mv = { 0, 0 }, tmp_mv = { 0, 0 };
943         struct buf_2d unscaled_last_source_buf_2d;
944
945         xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
946 #if CONFIG_VP9_HIGHBITDEPTH
947         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
948           motion_error = highbd_get_prediction_error(
949               bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
950         } else {
951           motion_error = get_prediction_error(bsize, &x->plane[0].src,
952                                               &xd->plane[0].pre[0]);
953         }
954 #else
955         motion_error =
956             get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
957 #endif  // CONFIG_VP9_HIGHBITDEPTH
958
959         // Compute the motion error of the 0,0 motion using the last source
960         // frame as the reference. Skip the further motion search on
961         // reconstructed frame if this error is small.
962         unscaled_last_source_buf_2d.buf =
963             cpi->unscaled_last_source->y_buffer + recon_yoffset;
964         unscaled_last_source_buf_2d.stride =
965             cpi->unscaled_last_source->y_stride;
966 #if CONFIG_VP9_HIGHBITDEPTH
967         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
968           raw_motion_error = highbd_get_prediction_error(
969               bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
970         } else {
971           raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
972                                                   &unscaled_last_source_buf_2d);
973         }
974 #else
975         raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
976                                                 &unscaled_last_source_buf_2d);
977 #endif  // CONFIG_VP9_HIGHBITDEPTH
978
979         // TODO(pengchong): Replace the hard-coded threshold
980         if (raw_motion_error > 25 || lc != NULL) {
981           // Test last reference frame using the previous best mv as the
982           // starting point (best reference) for the search.
983           first_pass_motion_search(cpi, x, &best_ref_mv, &mv, &motion_error);
984
985           // If the current best reference mv is not centered on 0,0 then do a
986           // 0,0 based search as well.
987           if (!is_zero_mv(&best_ref_mv)) {
988             tmp_err = INT_MAX;
989             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &tmp_err);
990
991             if (tmp_err < motion_error) {
992               motion_error = tmp_err;
993               mv = tmp_mv;
994             }
995           }
996
997           // Search in an older reference frame.
998           if (((lc == NULL && cm->current_video_frame > 1) ||
999                (lc != NULL && lc->current_video_frame_in_layer > 1)) &&
1000               gld_yv12 != NULL) {
1001             // Assume 0,0 motion with no mv overhead.
1002             int gf_motion_error;
1003
1004             xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
1005 #if CONFIG_VP9_HIGHBITDEPTH
1006             if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1007               gf_motion_error = highbd_get_prediction_error(
1008                   bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
1009             } else {
1010               gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1011                                                      &xd->plane[0].pre[0]);
1012             }
1013 #else
1014             gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1015                                                    &xd->plane[0].pre[0]);
1016 #endif  // CONFIG_VP9_HIGHBITDEPTH
1017
1018             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv,
1019                                      &gf_motion_error);
1020
1021             if (gf_motion_error < motion_error && gf_motion_error < this_error)
1022               ++second_ref_count;
1023
1024             // Reset to last frame as reference buffer.
1025             xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
1026             xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
1027             xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
1028
1029             // In accumulating a score for the older reference frame take the
1030             // best of the motion predicted score and the intra coded error
1031             // (just as will be done for) accumulation of "coded_error" for
1032             // the last frame.
1033             if (gf_motion_error < this_error)
1034               sr_coded_error += gf_motion_error;
1035             else
1036               sr_coded_error += this_error;
1037           } else {
1038             sr_coded_error += motion_error;
1039           }
1040         } else {
1041           sr_coded_error += motion_error;
1042         }
1043
1044         // Start by assuming that intra mode is best.
1045         best_ref_mv.row = 0;
1046         best_ref_mv.col = 0;
1047
1048 #if CONFIG_FP_MB_STATS
1049         if (cpi->use_fp_mb_stats) {
1050           // intra prediction statistics
1051           cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
1052           cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_DCINTRA_MASK;
1053           cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
1054           if (this_error > FPMB_ERROR_LARGE_TH) {
1055             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_LARGE_MASK;
1056           } else if (this_error < FPMB_ERROR_SMALL_TH) {
1057             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_SMALL_MASK;
1058           }
1059         }
1060 #endif
1061
1062         if (motion_error <= this_error) {
1063           vpx_clear_system_state();
1064
1065           // Keep a count of cases where the inter and intra were very close
1066           // and very low. This helps with scene cut detection for example in
1067           // cropped clips with black bars at the sides or top and bottom.
1068           if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
1069               (this_error < (2 * intrapenalty))) {
1070             neutral_count += 1.0;
1071             // Also track cases where the intra is not much worse than the inter
1072             // and use this in limiting the GF/arf group length.
1073           } else if ((this_error > NCOUNT_INTRA_THRESH) &&
1074                      (this_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
1075             neutral_count +=
1076                 (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_error);
1077           }
1078
1079           mv.row *= 8;
1080           mv.col *= 8;
1081           this_error = motion_error;
1082           xd->mi[0]->mode = NEWMV;
1083           xd->mi[0]->mv[0].as_mv = mv;
1084           xd->mi[0]->tx_size = TX_4X4;
1085           xd->mi[0]->ref_frame[0] = LAST_FRAME;
1086           xd->mi[0]->ref_frame[1] = NONE;
1087           vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
1088           vp9_encode_sby_pass1(x, bsize);
1089           sum_mvr += mv.row;
1090           sum_mvr_abs += abs(mv.row);
1091           sum_mvc += mv.col;
1092           sum_mvc_abs += abs(mv.col);
1093           sum_mvrs += mv.row * mv.row;
1094           sum_mvcs += mv.col * mv.col;
1095           ++intercount;
1096
1097           best_ref_mv = mv;
1098
1099 #if CONFIG_FP_MB_STATS
1100           if (cpi->use_fp_mb_stats) {
1101             // inter prediction statistics
1102             cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
1103             cpi->twopass.frame_mb_stats_buf[mb_index] &= ~FPMB_DCINTRA_MASK;
1104             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
1105             if (this_error > FPMB_ERROR_LARGE_TH) {
1106               cpi->twopass.frame_mb_stats_buf[mb_index] |=
1107                   FPMB_ERROR_LARGE_MASK;
1108             } else if (this_error < FPMB_ERROR_SMALL_TH) {
1109               cpi->twopass.frame_mb_stats_buf[mb_index] |=
1110                   FPMB_ERROR_SMALL_MASK;
1111             }
1112           }
1113 #endif
1114
1115           if (!is_zero_mv(&mv)) {
1116             ++mvcount;
1117
1118 #if CONFIG_FP_MB_STATS
1119             if (cpi->use_fp_mb_stats) {
1120               cpi->twopass.frame_mb_stats_buf[mb_index] &=
1121                   ~FPMB_MOTION_ZERO_MASK;
1122               // check estimated motion direction
1123               if (mv.as_mv.col > 0 && mv.as_mv.col >= abs(mv.as_mv.row)) {
1124                 // right direction
1125                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
1126                     FPMB_MOTION_RIGHT_MASK;
1127               } else if (mv.as_mv.row < 0 &&
1128                          abs(mv.as_mv.row) >= abs(mv.as_mv.col)) {
1129                 // up direction
1130                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
1131                     FPMB_MOTION_UP_MASK;
1132               } else if (mv.as_mv.col < 0 &&
1133                          abs(mv.as_mv.col) >= abs(mv.as_mv.row)) {
1134                 // left direction
1135                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
1136                     FPMB_MOTION_LEFT_MASK;
1137               } else {
1138                 // down direction
1139                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
1140                     FPMB_MOTION_DOWN_MASK;
1141               }
1142             }
1143 #endif
1144
1145             // Non-zero vector, was it different from the last non zero vector?
1146             if (!is_equal_mv(&mv, &lastmv)) ++new_mv_count;
1147             lastmv = mv;
1148
1149             // Does the row vector point inwards or outwards?
1150             if (mb_row < cm->mb_rows / 2) {
1151               if (mv.row > 0)
1152                 --sum_in_vectors;
1153               else if (mv.row < 0)
1154                 ++sum_in_vectors;
1155             } else if (mb_row > cm->mb_rows / 2) {
1156               if (mv.row > 0)
1157                 ++sum_in_vectors;
1158               else if (mv.row < 0)
1159                 --sum_in_vectors;
1160             }
1161
1162             // Does the col vector point inwards or outwards?
1163             if (mb_col < cm->mb_cols / 2) {
1164               if (mv.col > 0)
1165                 --sum_in_vectors;
1166               else if (mv.col < 0)
1167                 ++sum_in_vectors;
1168             } else if (mb_col > cm->mb_cols / 2) {
1169               if (mv.col > 0)
1170                 ++sum_in_vectors;
1171               else if (mv.col < 0)
1172                 --sum_in_vectors;
1173             }
1174             frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1175           } else if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
1176             frame_noise_energy += fp_estimate_block_noise(x, bsize);
1177           } else {  // 0,0 mv but high error
1178             frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1179           }
1180         } else {  // Intra < inter error
1181           if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH))
1182             frame_noise_energy += fp_estimate_block_noise(x, bsize);
1183           else
1184             frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1185         }
1186       } else {
1187         sr_coded_error += (int64_t)this_error;
1188       }
1189       coded_error += (int64_t)this_error;
1190
1191       // Adjust to the next column of MBs.
1192       x->plane[0].src.buf += 16;
1193       x->plane[1].src.buf += uv_mb_height;
1194       x->plane[2].src.buf += uv_mb_height;
1195
1196       recon_yoffset += 16;
1197       recon_uvoffset += uv_mb_height;
1198     }
1199
1200     // Adjust to the next row of MBs.
1201     x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
1202     x->plane[1].src.buf +=
1203         uv_mb_height * x->plane[1].src.stride - uv_mb_height * cm->mb_cols;
1204     x->plane[2].src.buf +=
1205         uv_mb_height * x->plane[1].src.stride - uv_mb_height * cm->mb_cols;
1206
1207     vpx_clear_system_state();
1208   }
1209
1210   // Clamp the image start to rows/2. This number of rows is discarded top
1211   // and bottom as dead data so rows / 2 means the frame is blank.
1212   if ((image_data_start_row > cm->mb_rows / 2) ||
1213       (image_data_start_row == INVALID_ROW)) {
1214     image_data_start_row = cm->mb_rows / 2;
1215   }
1216   // Exclude any image dead zone
1217   if (image_data_start_row > 0) {
1218     intra_skip_count =
1219         VPXMAX(0, intra_skip_count - (image_data_start_row * cm->mb_cols * 2));
1220   }
1221
1222   {
1223     FIRSTPASS_STATS fps;
1224     // The minimum error here insures some bit allocation to frames even
1225     // in static regions. The allocation per MB declines for larger formats
1226     // where the typical "real" energy per MB also falls.
1227     // Initial estimate here uses sqrt(mbs) to define the min_err, where the
1228     // number of mbs is proportional to the image area.
1229     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1230                             ? cpi->initial_mbs
1231                             : cpi->common.MBs;
1232     const double min_err = 200 * sqrt(num_mbs);
1233
1234     intra_factor = intra_factor / (double)num_mbs;
1235     brightness_factor = brightness_factor / (double)num_mbs;
1236     fps.weight = intra_factor * brightness_factor;
1237
1238     fps.frame = cm->current_video_frame;
1239     fps.spatial_layer_id = cpi->svc.spatial_layer_id;
1240     fps.coded_error = (double)(coded_error >> 8) + min_err;
1241     fps.sr_coded_error = (double)(sr_coded_error >> 8) + min_err;
1242     fps.intra_error = (double)(intra_error >> 8) + min_err;
1243     fps.frame_noise_energy = (double)frame_noise_energy / (double)num_mbs;
1244     fps.count = 1.0;
1245     fps.pcnt_inter = (double)intercount / num_mbs;
1246     fps.pcnt_second_ref = (double)second_ref_count / num_mbs;
1247     fps.pcnt_neutral = (double)neutral_count / num_mbs;
1248     fps.intra_skip_pct = (double)intra_skip_count / num_mbs;
1249     fps.intra_smooth_pct = (double)intra_smooth_count / num_mbs;
1250     fps.inactive_zone_rows = (double)image_data_start_row;
1251     // Currently set to 0 as most issues relate to letter boxing.
1252     fps.inactive_zone_cols = (double)0;
1253
1254     if (mvcount > 0) {
1255       fps.MVr = (double)sum_mvr / mvcount;
1256       fps.mvr_abs = (double)sum_mvr_abs / mvcount;
1257       fps.MVc = (double)sum_mvc / mvcount;
1258       fps.mvc_abs = (double)sum_mvc_abs / mvcount;
1259       fps.MVrv =
1260           ((double)sum_mvrs - ((double)sum_mvr * sum_mvr / mvcount)) / mvcount;
1261       fps.MVcv =
1262           ((double)sum_mvcs - ((double)sum_mvc * sum_mvc / mvcount)) / mvcount;
1263       fps.mv_in_out_count = (double)sum_in_vectors / (mvcount * 2);
1264       fps.new_mv_count = new_mv_count;
1265       fps.pcnt_motion = (double)mvcount / num_mbs;
1266     } else {
1267       fps.MVr = 0.0;
1268       fps.mvr_abs = 0.0;
1269       fps.MVc = 0.0;
1270       fps.mvc_abs = 0.0;
1271       fps.MVrv = 0.0;
1272       fps.MVcv = 0.0;
1273       fps.mv_in_out_count = 0.0;
1274       fps.new_mv_count = 0.0;
1275       fps.pcnt_motion = 0.0;
1276     }
1277
1278     // Dont allow a value of 0 for duration.
1279     // (Section duration is also defaulted to minimum of 1.0).
1280     fps.duration = VPXMAX(1.0, (double)(source->ts_end - source->ts_start));
1281
1282     // Don't want to do output stats with a stack variable!
1283     twopass->this_frame_stats = fps;
1284     output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
1285     accumulate_stats(&twopass->total_stats, &fps);
1286
1287 #if CONFIG_FP_MB_STATS
1288     if (cpi->use_fp_mb_stats) {
1289       output_fpmb_stats(twopass->frame_mb_stats_buf, cm, cpi->output_pkt_list);
1290     }
1291 #endif
1292   }
1293
1294   // Copy the previous Last Frame back into gf and and arf buffers if
1295   // the prediction is good enough... but also don't allow it to lag too far.
1296   if ((twopass->sr_update_lag > 3) ||
1297       ((cm->current_video_frame > 0) &&
1298        (twopass->this_frame_stats.pcnt_inter > 0.20) &&
1299        ((twopass->this_frame_stats.intra_error /
1300          DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
1301     if (gld_yv12 != NULL) {
1302       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1303                  cm->ref_frame_map[cpi->lst_fb_idx]);
1304     }
1305     twopass->sr_update_lag = 1;
1306   } else {
1307     ++twopass->sr_update_lag;
1308   }
1309
1310   vpx_extend_frame_borders(new_yv12);
1311
1312   if (lc != NULL) {
1313     vp9_update_reference_frames(cpi);
1314   } else {
1315     // The frame we just compressed now becomes the last frame.
1316     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
1317                cm->new_fb_idx);
1318   }
1319
1320   // Special case for the first frame. Copy into the GF buffer as a second
1321   // reference.
1322   if (cm->current_video_frame == 0 && cpi->gld_fb_idx != INVALID_IDX &&
1323       lc == NULL) {
1324     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1325                cm->ref_frame_map[cpi->lst_fb_idx]);
1326   }
1327
1328   // Use this to see what the first pass reconstruction looks like.
1329   if (0) {
1330     char filename[512];
1331     FILE *recon_file;
1332     snprintf(filename, sizeof(filename), "enc%04d.yuv",
1333              (int)cm->current_video_frame);
1334
1335     if (cm->current_video_frame == 0)
1336       recon_file = fopen(filename, "wb");
1337     else
1338       recon_file = fopen(filename, "ab");
1339
1340     (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
1341     fclose(recon_file);
1342   }
1343
1344   ++cm->current_video_frame;
1345   if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
1346 }
1347
1348 static double calc_correction_factor(double err_per_mb, double err_divisor,
1349                                      double pt_low, double pt_high, int q,
1350                                      vpx_bit_depth_t bit_depth) {
1351   const double error_term = err_per_mb / err_divisor;
1352
1353   // Adjustment based on actual quantizer to power term.
1354   const double power_term =
1355       VPXMIN(vp9_convert_qindex_to_q(q, bit_depth) * 0.01 + pt_low, pt_high);
1356
1357   // Calculate correction factor.
1358   if (power_term < 1.0) assert(error_term >= 0.0);
1359
1360   return fclamp(pow(error_term, power_term), 0.05, 5.0);
1361 }
1362
1363 #define ERR_DIVISOR 115.0
1364 #define NOISE_FACTOR_MIN 0.9
1365 #define NOISE_FACTOR_MAX 1.1
1366 static int get_twopass_worst_quality(VP9_COMP *cpi, const double section_err,
1367                                      double inactive_zone, double section_noise,
1368                                      int section_target_bandwidth) {
1369   const RATE_CONTROL *const rc = &cpi->rc;
1370   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1371   TWO_PASS *const twopass = &cpi->twopass;
1372
1373   // Clamp the target rate to VBR min / max limts.
1374   const int target_rate =
1375       vp9_rc_clamp_pframe_target_size(cpi, section_target_bandwidth);
1376   double noise_factor = pow((section_noise / SECTION_NOISE_DEF), 0.5);
1377   noise_factor = fclamp(noise_factor, NOISE_FACTOR_MIN, NOISE_FACTOR_MAX);
1378   inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
1379
1380   if (target_rate <= 0) {
1381     return rc->worst_quality;  // Highest value allowed
1382   } else {
1383     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1384                             ? cpi->initial_mbs
1385                             : cpi->common.MBs;
1386     const int active_mbs = VPXMAX(1, num_mbs - (int)(num_mbs * inactive_zone));
1387     const double av_err_per_mb = section_err / active_mbs;
1388     const double speed_term = 1.0 + 0.04 * oxcf->speed;
1389     double last_group_rate_err;
1390     const int target_norm_bits_per_mb =
1391         ((uint64_t)target_rate << BPER_MB_NORMBITS) / active_mbs;
1392     int q;
1393     int is_svc_upper_layer = 0;
1394
1395     if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0)
1396       is_svc_upper_layer = 1;
1397
1398     // based on recent history adjust expectations of bits per macroblock.
1399     last_group_rate_err =
1400         (double)twopass->rolling_arf_group_actual_bits /
1401         DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
1402     last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
1403     twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
1404     twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
1405
1406     // Try and pick a max Q that will be high enough to encode the
1407     // content at the given rate.
1408     for (q = rc->best_quality; q < rc->worst_quality; ++q) {
1409       const double factor = calc_correction_factor(
1410           av_err_per_mb, ERR_DIVISOR,
1411           is_svc_upper_layer ? SVC_FACTOR_PT_LOW : FACTOR_PT_LOW,
1412           FACTOR_PT_HIGH, q, cpi->common.bit_depth);
1413       const int bits_per_mb = vp9_rc_bits_per_mb(
1414           INTER_FRAME, q,
1415           factor * speed_term * cpi->twopass.bpm_factor * noise_factor,
1416           cpi->common.bit_depth);
1417       if (bits_per_mb <= target_norm_bits_per_mb) break;
1418     }
1419
1420     // Restriction on active max q for constrained quality mode.
1421     if (cpi->oxcf.rc_mode == VPX_CQ) q = VPXMAX(q, oxcf->cq_level);
1422     return q;
1423   }
1424 }
1425
1426 static void setup_rf_level_maxq(VP9_COMP *cpi) {
1427   int i;
1428   RATE_CONTROL *const rc = &cpi->rc;
1429   for (i = INTER_NORMAL; i < RATE_FACTOR_LEVELS; ++i) {
1430     int qdelta = vp9_frame_type_qdelta(cpi, i, rc->worst_quality);
1431     rc->rf_level_maxq[i] = VPXMAX(rc->worst_quality + qdelta, rc->best_quality);
1432   }
1433 }
1434
1435 static void init_subsampling(VP9_COMP *cpi) {
1436   const VP9_COMMON *const cm = &cpi->common;
1437   RATE_CONTROL *const rc = &cpi->rc;
1438   const int w = cm->width;
1439   const int h = cm->height;
1440   int i;
1441
1442   for (i = 0; i < FRAME_SCALE_STEPS; ++i) {
1443     // Note: Frames with odd-sized dimensions may result from this scaling.
1444     rc->frame_width[i] = (w * 16) / frame_scale_factor[i];
1445     rc->frame_height[i] = (h * 16) / frame_scale_factor[i];
1446   }
1447
1448   setup_rf_level_maxq(cpi);
1449 }
1450
1451 void calculate_coded_size(VP9_COMP *cpi, int *scaled_frame_width,
1452                           int *scaled_frame_height) {
1453   RATE_CONTROL *const rc = &cpi->rc;
1454   *scaled_frame_width = rc->frame_width[rc->frame_size_selector];
1455   *scaled_frame_height = rc->frame_height[rc->frame_size_selector];
1456 }
1457
1458 void vp9_init_second_pass(VP9_COMP *cpi) {
1459   SVC *const svc = &cpi->svc;
1460   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1461   const int is_two_pass_svc =
1462       (svc->number_spatial_layers > 1) || (svc->number_temporal_layers > 1);
1463   RATE_CONTROL *const rc = &cpi->rc;
1464   TWO_PASS *const twopass =
1465       is_two_pass_svc ? &svc->layer_context[svc->spatial_layer_id].twopass
1466                       : &cpi->twopass;
1467   double frame_rate;
1468   FIRSTPASS_STATS *stats;
1469
1470   zero_stats(&twopass->total_stats);
1471   zero_stats(&twopass->total_left_stats);
1472
1473   if (!twopass->stats_in_end) return;
1474
1475   stats = &twopass->total_stats;
1476
1477   *stats = *twopass->stats_in_end;
1478   twopass->total_left_stats = *stats;
1479
1480   frame_rate = 10000000.0 * stats->count / stats->duration;
1481   // Each frame can have a different duration, as the frame rate in the source
1482   // isn't guaranteed to be constant. The frame rate prior to the first frame
1483   // encoded in the second pass is a guess. However, the sum duration is not.
1484   // It is calculated based on the actual durations of all frames from the
1485   // first pass.
1486
1487   if (is_two_pass_svc) {
1488     vp9_update_spatial_layer_framerate(cpi, frame_rate);
1489     twopass->bits_left =
1490         (int64_t)(stats->duration *
1491                   svc->layer_context[svc->spatial_layer_id].target_bandwidth /
1492                   10000000.0);
1493   } else {
1494     vp9_new_framerate(cpi, frame_rate);
1495     twopass->bits_left =
1496         (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
1497   }
1498
1499   // This variable monitors how far behind the second ref update is lagging.
1500   twopass->sr_update_lag = 1;
1501
1502   // Scan the first pass file and calculate a modified total error based upon
1503   // the bias/power function used to allocate bits.
1504   {
1505     const double avg_error =
1506         stats->coded_error / DOUBLE_DIVIDE_CHECK(stats->count);
1507     const FIRSTPASS_STATS *s = twopass->stats_in;
1508     double modified_error_total = 0.0;
1509     twopass->modified_error_min =
1510         (avg_error * oxcf->two_pass_vbrmin_section) / 100;
1511     twopass->modified_error_max =
1512         (avg_error * oxcf->two_pass_vbrmax_section) / 100;
1513     while (s < twopass->stats_in_end) {
1514       modified_error_total += calculate_modified_err(cpi, twopass, oxcf, s);
1515       ++s;
1516     }
1517     twopass->modified_error_left = modified_error_total;
1518   }
1519
1520   // Reset the vbr bits off target counters
1521   rc->vbr_bits_off_target = 0;
1522   rc->vbr_bits_off_target_fast = 0;
1523   rc->rate_error_estimate = 0;
1524
1525   // Static sequence monitor variables.
1526   twopass->kf_zeromotion_pct = 100;
1527   twopass->last_kfgroup_zeromotion_pct = 100;
1528
1529   // Initialize bits per macro_block estimate correction factor.
1530   twopass->bpm_factor = 1.0;
1531   // Initialize actual and target bits counters for ARF groups so that
1532   // at the start we have a neutral bpm adjustment.
1533   twopass->rolling_arf_group_target_bits = 1;
1534   twopass->rolling_arf_group_actual_bits = 1;
1535
1536   if (oxcf->resize_mode != RESIZE_NONE) {
1537     init_subsampling(cpi);
1538   }
1539
1540   // Initialize the arnr strangth adjustment to 0
1541   twopass->arnr_strength_adjustment = 0;
1542 }
1543
1544 #define SR_DIFF_PART 0.0015
1545 #define INTRA_PART 0.005
1546 #define DEFAULT_DECAY_LIMIT 0.75
1547 #define LOW_SR_DIFF_TRHESH 0.1
1548 #define SR_DIFF_MAX 128.0
1549 #define LOW_CODED_ERR_PER_MB 10.0
1550 #define NCOUNT_FRAME_II_THRESH 6.0
1551
1552 static double get_sr_decay_rate(const VP9_COMP *cpi,
1553                                 const FIRSTPASS_STATS *frame) {
1554   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
1555                                                              : cpi->common.MBs;
1556   double sr_diff = (frame->sr_coded_error - frame->coded_error) / num_mbs;
1557   double sr_decay = 1.0;
1558   double modified_pct_inter;
1559   double modified_pcnt_intra;
1560   const double motion_amplitude_part =
1561       frame->pcnt_motion * ((frame->mvc_abs + frame->mvr_abs) /
1562                             (cpi->initial_height + cpi->initial_width));
1563
1564   modified_pct_inter = frame->pcnt_inter;
1565   if (((frame->coded_error / num_mbs) > LOW_CODED_ERR_PER_MB) &&
1566       ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
1567        (double)NCOUNT_FRAME_II_THRESH)) {
1568     modified_pct_inter = frame->pcnt_inter - frame->pcnt_neutral;
1569   }
1570   modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
1571
1572   if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
1573     sr_diff = VPXMIN(sr_diff, SR_DIFF_MAX);
1574     sr_decay = 1.0 - (SR_DIFF_PART * sr_diff) - motion_amplitude_part -
1575                (INTRA_PART * modified_pcnt_intra);
1576   }
1577   return VPXMAX(sr_decay, VPXMIN(DEFAULT_DECAY_LIMIT, modified_pct_inter));
1578 }
1579
1580 // This function gives an estimate of how badly we believe the prediction
1581 // quality is decaying from frame to frame.
1582 static double get_zero_motion_factor(const VP9_COMP *cpi,
1583                                      const FIRSTPASS_STATS *frame) {
1584   const double zero_motion_pct = frame->pcnt_inter - frame->pcnt_motion;
1585   double sr_decay = get_sr_decay_rate(cpi, frame);
1586   return VPXMIN(sr_decay, zero_motion_pct);
1587 }
1588
1589 #define ZM_POWER_FACTOR 0.75
1590
1591 static double get_prediction_decay_rate(const VP9_COMP *cpi,
1592                                         const FIRSTPASS_STATS *next_frame) {
1593   const double sr_decay_rate = get_sr_decay_rate(cpi, next_frame);
1594   const double zero_motion_factor =
1595       (0.95 * pow((next_frame->pcnt_inter - next_frame->pcnt_motion),
1596                   ZM_POWER_FACTOR));
1597
1598   return VPXMAX(zero_motion_factor,
1599                 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
1600 }
1601
1602 // Function to test for a condition where a complex transition is followed
1603 // by a static section. For example in slide shows where there is a fade
1604 // between slides. This is to help with more optimal kf and gf positioning.
1605 static int detect_transition_to_still(VP9_COMP *cpi, int frame_interval,
1606                                       int still_interval,
1607                                       double loop_decay_rate,
1608                                       double last_decay_rate) {
1609   TWO_PASS *const twopass = &cpi->twopass;
1610   RATE_CONTROL *const rc = &cpi->rc;
1611
1612   // Break clause to detect very still sections after motion
1613   // For example a static image after a fade or other transition
1614   // instead of a clean scene cut.
1615   if (frame_interval > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
1616       last_decay_rate < 0.9) {
1617     int j;
1618
1619     // Look ahead a few frames to see if static condition persists...
1620     for (j = 0; j < still_interval; ++j) {
1621       const FIRSTPASS_STATS *stats = &twopass->stats_in[j];
1622       if (stats >= twopass->stats_in_end) break;
1623
1624       if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
1625     }
1626
1627     // Only if it does do we signal a transition to still.
1628     return j == still_interval;
1629   }
1630
1631   return 0;
1632 }
1633
1634 // This function detects a flash through the high relative pcnt_second_ref
1635 // score in the frame following a flash frame. The offset passed in should
1636 // reflect this.
1637 static int detect_flash(const TWO_PASS *twopass, int offset) {
1638   const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
1639
1640   // What we are looking for here is a situation where there is a
1641   // brief break in prediction (such as a flash) but subsequent frames
1642   // are reasonably well predicted by an earlier (pre flash) frame.
1643   // The recovery after a flash is indicated by a high pcnt_second_ref
1644   // compared to pcnt_inter.
1645   return next_frame != NULL &&
1646          next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
1647          next_frame->pcnt_second_ref >= 0.5;
1648 }
1649
1650 // Update the motion related elements to the GF arf boost calculation.
1651 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1652                                           double *mv_in_out,
1653                                           double *mv_in_out_accumulator,
1654                                           double *abs_mv_in_out_accumulator,
1655                                           double *mv_ratio_accumulator) {
1656   const double pct = stats->pcnt_motion;
1657
1658   // Accumulate Motion In/Out of frame stats.
1659   *mv_in_out = stats->mv_in_out_count * pct;
1660   *mv_in_out_accumulator += *mv_in_out;
1661   *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1662
1663   // Accumulate a measure of how uniform (or conversely how random) the motion
1664   // field is (a ratio of abs(mv) / mv).
1665   if (pct > 0.05) {
1666     const double mvr_ratio =
1667         fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1668     const double mvc_ratio =
1669         fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1670
1671     *mv_ratio_accumulator +=
1672         pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
1673     *mv_ratio_accumulator +=
1674         pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
1675   }
1676 }
1677
1678 #define BASELINE_ERR_PER_MB 1000.0
1679 static double calc_frame_boost(VP9_COMP *cpi, const FIRSTPASS_STATS *this_frame,
1680                                double this_frame_mv_in_out, double max_boost) {
1681   double frame_boost;
1682   const double lq = vp9_convert_qindex_to_q(
1683       cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.bit_depth);
1684   const double boost_q_correction = VPXMIN((0.5 + (lq * 0.015)), 1.5);
1685   int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
1686                                                        : cpi->common.MBs;
1687
1688   // Correct for any inactive region in the image
1689   num_mbs = (int)VPXMAX(1, num_mbs * calculate_active_area(cpi, this_frame));
1690
1691   // Underlying boost factor is based on inter error ratio.
1692   frame_boost = (BASELINE_ERR_PER_MB * num_mbs) /
1693                 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
1694   frame_boost = frame_boost * BOOST_FACTOR * boost_q_correction;
1695
1696   // Increase boost for frames where new data coming into frame (e.g. zoom out).
1697   // Slightly reduce boost if there is a net balance of motion out of the frame
1698   // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
1699   if (this_frame_mv_in_out > 0.0)
1700     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1701   // In the extreme case the boost is halved.
1702   else
1703     frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1704
1705   return VPXMIN(frame_boost, max_boost * boost_q_correction);
1706 }
1707
1708 static int calc_arf_boost(VP9_COMP *cpi, int offset, int f_frames, int b_frames,
1709                           int *f_boost, int *b_boost) {
1710   TWO_PASS *const twopass = &cpi->twopass;
1711   int i;
1712   double boost_score = 0.0;
1713   double mv_ratio_accumulator = 0.0;
1714   double decay_accumulator = 1.0;
1715   double this_frame_mv_in_out = 0.0;
1716   double mv_in_out_accumulator = 0.0;
1717   double abs_mv_in_out_accumulator = 0.0;
1718   int arf_boost;
1719   int flash_detected = 0;
1720
1721   // Search forward from the proposed arf/next gf position.
1722   for (i = 0; i < f_frames; ++i) {
1723     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1724     if (this_frame == NULL) break;
1725
1726     // Update the motion related elements to the boost calculation.
1727     accumulate_frame_motion_stats(
1728         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1729         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1730
1731     // We want to discount the flash frame itself and the recovery
1732     // frame that follows as both will have poor scores.
1733     flash_detected = detect_flash(twopass, i + offset) ||
1734                      detect_flash(twopass, i + offset + 1);
1735
1736     // Accumulate the effect of prediction quality decay.
1737     if (!flash_detected) {
1738       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
1739       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1740                               ? MIN_DECAY_FACTOR
1741                               : decay_accumulator;
1742     }
1743
1744     boost_score +=
1745         decay_accumulator *
1746         calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
1747   }
1748
1749   *f_boost = (int)boost_score;
1750
1751   // Reset for backward looking loop.
1752   boost_score = 0.0;
1753   mv_ratio_accumulator = 0.0;
1754   decay_accumulator = 1.0;
1755   this_frame_mv_in_out = 0.0;
1756   mv_in_out_accumulator = 0.0;
1757   abs_mv_in_out_accumulator = 0.0;
1758
1759   // Search backward towards last gf position.
1760   for (i = -1; i >= -b_frames; --i) {
1761     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1762     if (this_frame == NULL) break;
1763
1764     // Update the motion related elements to the boost calculation.
1765     accumulate_frame_motion_stats(
1766         this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
1767         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
1768
1769     // We want to discount the the flash frame itself and the recovery
1770     // frame that follows as both will have poor scores.
1771     flash_detected = detect_flash(twopass, i + offset) ||
1772                      detect_flash(twopass, i + offset + 1);
1773
1774     // Cumulative effect of prediction quality decay.
1775     if (!flash_detected) {
1776       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
1777       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1778                               ? MIN_DECAY_FACTOR
1779                               : decay_accumulator;
1780     }
1781
1782     boost_score +=
1783         decay_accumulator *
1784         calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
1785   }
1786   *b_boost = (int)boost_score;
1787
1788   arf_boost = (*f_boost + *b_boost);
1789   if (arf_boost < ((b_frames + f_frames) * 20))
1790     arf_boost = ((b_frames + f_frames) * 20);
1791   arf_boost = VPXMAX(arf_boost, MIN_ARF_GF_BOOST);
1792
1793   return arf_boost;
1794 }
1795
1796 // Calculate a section intra ratio used in setting max loop filter.
1797 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
1798                                          const FIRSTPASS_STATS *end,
1799                                          int section_length) {
1800   const FIRSTPASS_STATS *s = begin;
1801   double intra_error = 0.0;
1802   double coded_error = 0.0;
1803   int i = 0;
1804
1805   while (s < end && i < section_length) {
1806     intra_error += s->intra_error;
1807     coded_error += s->coded_error;
1808     ++s;
1809     ++i;
1810   }
1811
1812   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
1813 }
1814
1815 // Calculate the total bits to allocate in this GF/ARF group.
1816 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
1817                                              double gf_group_err) {
1818   const RATE_CONTROL *const rc = &cpi->rc;
1819   const TWO_PASS *const twopass = &cpi->twopass;
1820   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1821   int64_t total_group_bits;
1822
1823   // Calculate the bits to be allocated to the group as a whole.
1824   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
1825     total_group_bits = (int64_t)(twopass->kf_group_bits *
1826                                  (gf_group_err / twopass->kf_group_error_left));
1827   } else {
1828     total_group_bits = 0;
1829   }
1830
1831   // Clamp odd edge cases.
1832   total_group_bits =
1833       (total_group_bits < 0) ? 0 : (total_group_bits > twopass->kf_group_bits)
1834                                        ? twopass->kf_group_bits
1835                                        : total_group_bits;
1836
1837   // Clip based on user supplied data rate variability limit.
1838   if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
1839     total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
1840
1841   return total_group_bits;
1842 }
1843
1844 // Calculate the number bits extra to assign to boosted frames in a group.
1845 static int calculate_boost_bits(int frame_count, int boost,
1846                                 int64_t total_group_bits) {
1847   int allocation_chunks;
1848
1849   // return 0 for invalid inputs (could arise e.g. through rounding errors)
1850   if (!boost || (total_group_bits <= 0) || (frame_count <= 0)) return 0;
1851
1852   allocation_chunks = (frame_count * 100) + boost;
1853
1854   // Prevent overflow.
1855   if (boost > 1023) {
1856     int divisor = boost >> 10;
1857     boost /= divisor;
1858     allocation_chunks /= divisor;
1859   }
1860
1861   // Calculate the number of extra bits for use in the boosted frame or frames.
1862   return VPXMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
1863                 0);
1864 }
1865
1866 // Current limit on maximum number of active arfs in a GF/ARF group.
1867 #define MAX_ACTIVE_ARFS 2
1868 #define ARF_SLOT1 2
1869 #define ARF_SLOT2 3
1870 // This function indirects the choice of buffers for arfs.
1871 // At the moment the values are fixed but this may change as part of
1872 // the integration process with other codec features that swap buffers around.
1873 static void get_arf_buffer_indices(unsigned char *arf_buffer_indices) {
1874   arf_buffer_indices[0] = ARF_SLOT1;
1875   arf_buffer_indices[1] = ARF_SLOT2;
1876 }
1877
1878 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
1879                                    int gf_arf_bits) {
1880   RATE_CONTROL *const rc = &cpi->rc;
1881   TWO_PASS *const twopass = &cpi->twopass;
1882   GF_GROUP *const gf_group = &twopass->gf_group;
1883   FIRSTPASS_STATS frame_stats;
1884   int i;
1885   int frame_index = 1;
1886   int target_frame_size;
1887   int key_frame;
1888   const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
1889   int64_t total_group_bits = gf_group_bits;
1890   int mid_boost_bits = 0;
1891   int mid_frame_idx;
1892   unsigned char arf_buffer_indices[MAX_ACTIVE_ARFS];
1893   int alt_frame_index = frame_index;
1894   int has_temporal_layers =
1895       is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1;
1896   int normal_frames;
1897   int normal_frame_bits;
1898   int last_frame_bits;
1899   int last_frame_reduction;
1900
1901   // Only encode alt reference frame in temporal base layer.
1902   if (has_temporal_layers) alt_frame_index = cpi->svc.number_temporal_layers;
1903
1904   key_frame =
1905       cpi->common.frame_type == KEY_FRAME || vp9_is_upper_layer_key_frame(cpi);
1906
1907   get_arf_buffer_indices(arf_buffer_indices);
1908
1909   // For key frames the frame target rate is already set and it
1910   // is also the golden frame.
1911   if (!key_frame) {
1912     if (rc->source_alt_ref_active) {
1913       gf_group->update_type[0] = OVERLAY_UPDATE;
1914       gf_group->rf_level[0] = INTER_NORMAL;
1915       gf_group->bit_allocation[0] = 0;
1916     } else {
1917       gf_group->update_type[0] = GF_UPDATE;
1918       gf_group->rf_level[0] = GF_ARF_STD;
1919       gf_group->bit_allocation[0] = gf_arf_bits;
1920     }
1921     gf_group->arf_update_idx[0] = arf_buffer_indices[0];
1922     gf_group->arf_ref_idx[0] = arf_buffer_indices[0];
1923
1924     // Step over the golden frame / overlay frame
1925     if (EOF == input_stats(twopass, &frame_stats)) return;
1926   }
1927
1928   // Deduct the boost bits for arf (or gf if it is not a key frame)
1929   // from the group total.
1930   if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
1931
1932   // Store the bits to spend on the ARF if there is one.
1933   if (rc->source_alt_ref_pending) {
1934     gf_group->update_type[alt_frame_index] = ARF_UPDATE;
1935     gf_group->rf_level[alt_frame_index] = GF_ARF_STD;
1936     gf_group->bit_allocation[alt_frame_index] = gf_arf_bits;
1937
1938     if (has_temporal_layers)
1939       gf_group->arf_src_offset[alt_frame_index] =
1940           (unsigned char)(rc->baseline_gf_interval -
1941                           cpi->svc.number_temporal_layers);
1942     else
1943       gf_group->arf_src_offset[alt_frame_index] =
1944           (unsigned char)(rc->baseline_gf_interval - 1);
1945
1946     gf_group->arf_update_idx[alt_frame_index] = arf_buffer_indices[0];
1947     gf_group->arf_ref_idx[alt_frame_index] =
1948         arf_buffer_indices[cpi->multi_arf_last_grp_enabled &&
1949                            rc->source_alt_ref_active];
1950     if (!has_temporal_layers) ++frame_index;
1951
1952     if (cpi->multi_arf_enabled) {
1953       // Set aside a slot for a level 1 arf.
1954       gf_group->update_type[frame_index] = ARF_UPDATE;
1955       gf_group->rf_level[frame_index] = GF_ARF_LOW;
1956       gf_group->arf_src_offset[frame_index] =
1957           (unsigned char)((rc->baseline_gf_interval >> 1) - 1);
1958       gf_group->arf_update_idx[frame_index] = arf_buffer_indices[1];
1959       gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
1960       ++frame_index;
1961     }
1962   }
1963
1964   // Note index of the first normal inter frame int eh group (not gf kf arf)
1965   gf_group->first_inter_index = frame_index;
1966
1967   // Define middle frame
1968   mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
1969
1970   normal_frames = (rc->baseline_gf_interval - rc->source_alt_ref_pending);
1971
1972   // The last frame in the group is used less as a predictor so reduce
1973   // its allocation a little.
1974   if (normal_frames > 1) {
1975     normal_frame_bits = (int)(total_group_bits / normal_frames);
1976     last_frame_reduction = normal_frame_bits / 16;
1977     last_frame_bits = normal_frame_bits - last_frame_reduction;
1978   } else {
1979     normal_frame_bits = (int)total_group_bits;
1980     last_frame_bits = normal_frame_bits;
1981     last_frame_reduction = 0;
1982   }
1983
1984   // Allocate bits to the other frames in the group.
1985   for (i = 0; i < normal_frames; ++i) {
1986     int arf_idx = 0;
1987     if (EOF == input_stats(twopass, &frame_stats)) break;
1988
1989     if (has_temporal_layers && frame_index == alt_frame_index) {
1990       ++frame_index;
1991     }
1992
1993     target_frame_size = (i == (normal_frames - 1))
1994                             ? last_frame_bits
1995                             : (i == mid_frame_idx)
1996                                   ? normal_frame_bits + last_frame_reduction
1997                                   : normal_frame_bits;
1998
1999     if (rc->source_alt_ref_pending && cpi->multi_arf_enabled) {
2000       mid_boost_bits += (target_frame_size >> 4);
2001       target_frame_size -= (target_frame_size >> 4);
2002
2003       if (frame_index <= mid_frame_idx) arf_idx = 1;
2004     }
2005     gf_group->arf_update_idx[frame_index] = arf_buffer_indices[arf_idx];
2006     gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[arf_idx];
2007
2008     target_frame_size =
2009         clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2010
2011     gf_group->update_type[frame_index] = LF_UPDATE;
2012     gf_group->rf_level[frame_index] = INTER_NORMAL;
2013
2014     gf_group->bit_allocation[frame_index] = target_frame_size;
2015     ++frame_index;
2016   }
2017
2018   // Note:
2019   // We need to configure the frame at the end of the sequence + 1 that will be
2020   // the start frame for the next group. Otherwise prior to the call to
2021   // vp9_rc_get_second_pass_params() the data will be undefined.
2022   gf_group->arf_update_idx[frame_index] = arf_buffer_indices[0];
2023   gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
2024
2025   if (rc->source_alt_ref_pending) {
2026     gf_group->update_type[frame_index] = OVERLAY_UPDATE;
2027     gf_group->rf_level[frame_index] = INTER_NORMAL;
2028
2029     // Final setup for second arf and its overlay.
2030     if (cpi->multi_arf_enabled) {
2031       gf_group->bit_allocation[2] =
2032           gf_group->bit_allocation[mid_frame_idx] + mid_boost_bits;
2033       gf_group->update_type[mid_frame_idx] = OVERLAY_UPDATE;
2034       gf_group->bit_allocation[mid_frame_idx] = 0;
2035     }
2036   } else {
2037     gf_group->update_type[frame_index] = GF_UPDATE;
2038     gf_group->rf_level[frame_index] = GF_ARF_STD;
2039   }
2040
2041   // Note whether multi-arf was enabled this group for next time.
2042   cpi->multi_arf_last_grp_enabled = cpi->multi_arf_enabled;
2043 }
2044
2045 // Adjusts the ARNF filter for a GF group.
2046 static void adjust_group_arnr_filter(VP9_COMP *cpi, double section_noise,
2047                                      double section_inter,
2048                                      double section_motion) {
2049   TWO_PASS *const twopass = &cpi->twopass;
2050   double section_zeromv = section_inter - section_motion;
2051
2052   twopass->arnr_strength_adjustment = 0;
2053
2054   if ((section_zeromv < 0.10) || (section_noise <= (SECTION_NOISE_DEF * 0.75)))
2055     twopass->arnr_strength_adjustment -= 1;
2056   if (section_zeromv > 0.50) twopass->arnr_strength_adjustment += 1;
2057 }
2058
2059 // Analyse and define a gf/arf group.
2060 static void define_gf_group(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2061   VP9_COMMON *const cm = &cpi->common;
2062   RATE_CONTROL *const rc = &cpi->rc;
2063   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2064   TWO_PASS *const twopass = &cpi->twopass;
2065   FIRSTPASS_STATS next_frame;
2066   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2067   int i;
2068
2069   double boost_score = 0.0;
2070   double old_boost_score = 0.0;
2071   double gf_group_err = 0.0;
2072   double gf_group_raw_error = 0.0;
2073   double gf_group_noise = 0.0;
2074   double gf_group_skip_pct = 0.0;
2075   double gf_group_inactive_zone_rows = 0.0;
2076   double gf_group_inter = 0.0;
2077   double gf_group_motion = 0.0;
2078   double gf_first_frame_err = 0.0;
2079   double mod_frame_err = 0.0;
2080
2081   double mv_ratio_accumulator = 0.0;
2082   double decay_accumulator = 1.0;
2083   double zero_motion_accumulator = 1.0;
2084
2085   double loop_decay_rate = 1.00;
2086   double last_loop_decay_rate = 1.00;
2087
2088   double this_frame_mv_in_out = 0.0;
2089   double mv_in_out_accumulator = 0.0;
2090   double abs_mv_in_out_accumulator = 0.0;
2091   double mv_ratio_accumulator_thresh;
2092   unsigned int allow_alt_ref = is_altref_enabled(cpi);
2093
2094   int f_boost = 0;
2095   int b_boost = 0;
2096   int flash_detected;
2097   int active_max_gf_interval;
2098   int active_min_gf_interval;
2099   int64_t gf_group_bits;
2100   int gf_arf_bits;
2101   const int is_key_frame = frame_is_intra_only(cm);
2102   const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2103
2104   // Reset the GF group data structures unless this is a key
2105   // frame in which case it will already have been done.
2106   if (is_key_frame == 0) {
2107     vp9_zero(twopass->gf_group);
2108   }
2109
2110   vpx_clear_system_state();
2111   vp9_zero(next_frame);
2112
2113   // Load stats for the current frame.
2114   mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
2115
2116   // Note the error of the frame at the start of the group. This will be
2117   // the GF frame error if we code a normal gf.
2118   gf_first_frame_err = mod_frame_err;
2119
2120   // If this is a key frame or the overlay from a previous arf then
2121   // the error score / cost of this frame has already been accounted for.
2122   if (arf_active_or_kf) {
2123     gf_group_err -= gf_first_frame_err;
2124     gf_group_raw_error -= this_frame->coded_error;
2125     gf_group_noise -= this_frame->frame_noise_energy;
2126     gf_group_skip_pct -= this_frame->intra_skip_pct;
2127     gf_group_inactive_zone_rows -= this_frame->inactive_zone_rows;
2128     gf_group_inter -= this_frame->pcnt_inter;
2129     gf_group_motion -= this_frame->pcnt_motion;
2130   }
2131
2132   // Motion breakout threshold for loop below depends on image size.
2133   mv_ratio_accumulator_thresh =
2134       (cpi->initial_height + cpi->initial_width) / 4.0;
2135
2136   // Set a maximum and minimum interval for the GF group.
2137   // If the image appears almost completely static we can extend beyond this.
2138   {
2139     int int_max_q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
2140                                                   cpi->common.bit_depth));
2141     int int_lbq = (int)(vp9_convert_qindex_to_q(rc->last_boosted_qindex,
2142                                                 cpi->common.bit_depth));
2143     active_min_gf_interval =
2144         rc->min_gf_interval + arf_active_or_kf + VPXMIN(2, int_max_q / 200);
2145     if (active_min_gf_interval > rc->max_gf_interval)
2146       active_min_gf_interval = rc->max_gf_interval;
2147
2148     if (cpi->multi_arf_allowed) {
2149       active_max_gf_interval = rc->max_gf_interval;
2150     } else {
2151       // The value chosen depends on the active Q range. At low Q we have
2152       // bits to spare and are better with a smaller interval and smaller boost.
2153       // At high Q when there are few bits to spare we are better with a longer
2154       // interval to spread the cost of the GF.
2155       active_max_gf_interval = 12 + arf_active_or_kf + VPXMIN(4, (int_lbq / 6));
2156
2157       // We have: active_min_gf_interval <= rc->max_gf_interval
2158       if (active_max_gf_interval < active_min_gf_interval)
2159         active_max_gf_interval = active_min_gf_interval;
2160       else if (active_max_gf_interval > rc->max_gf_interval)
2161         active_max_gf_interval = rc->max_gf_interval;
2162
2163       // Would the active max drop us out just before the near the next kf?
2164       if ((active_max_gf_interval <= rc->frames_to_key) &&
2165           (active_max_gf_interval >= (rc->frames_to_key - rc->min_gf_interval)))
2166         active_max_gf_interval = rc->frames_to_key / 2;
2167     }
2168   }
2169
2170   i = 0;
2171   while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
2172     ++i;
2173
2174     // Accumulate error score of frames in this gf group.
2175     mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
2176     gf_group_err += mod_frame_err;
2177     gf_group_raw_error += this_frame->coded_error;
2178     gf_group_noise += this_frame->frame_noise_energy;
2179     gf_group_skip_pct += this_frame->intra_skip_pct;
2180     gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
2181     gf_group_inter += this_frame->pcnt_inter;
2182     gf_group_motion += this_frame->pcnt_motion;
2183
2184     if (EOF == input_stats(twopass, &next_frame)) break;
2185
2186     // Test for the case where there is a brief flash but the prediction
2187     // quality back to an earlier frame is then restored.
2188     flash_detected = detect_flash(twopass, 0);
2189
2190     // Update the motion related elements to the boost calculation.
2191     accumulate_frame_motion_stats(
2192         &next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2193         &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2194
2195     // Accumulate the effect of prediction quality decay.
2196     if (!flash_detected) {
2197       last_loop_decay_rate = loop_decay_rate;
2198       loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2199
2200       decay_accumulator = decay_accumulator * loop_decay_rate;
2201
2202       // Monitor for static sections.
2203       zero_motion_accumulator = VPXMIN(
2204           zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
2205
2206       // Break clause to detect very still sections after motion. For example,
2207       // a static image after a fade or other transition.
2208       if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
2209                                      last_loop_decay_rate)) {
2210         allow_alt_ref = 0;
2211         break;
2212       }
2213     }
2214
2215     // Calculate a boost number for this frame.
2216     boost_score +=
2217         decay_accumulator *
2218         calc_frame_boost(cpi, &next_frame, this_frame_mv_in_out, GF_MAX_BOOST);
2219
2220     // Break out conditions.
2221     if (
2222         // Break at active_max_gf_interval unless almost totally static.
2223         ((i >= active_max_gf_interval) && (zero_motion_accumulator < 0.995)) ||
2224         (
2225             // Don't break out with a very short interval.
2226             (i >= active_min_gf_interval) &&
2227             // If possible dont break very close to a kf
2228             ((rc->frames_to_key - i) >= rc->min_gf_interval) &&
2229             (!flash_detected) &&
2230             ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
2231              (abs_mv_in_out_accumulator > 3.0) ||
2232              (mv_in_out_accumulator < -2.0) ||
2233              ((boost_score - old_boost_score) < BOOST_BREAKOUT)))) {
2234       boost_score = old_boost_score;
2235       break;
2236     }
2237
2238     *this_frame = next_frame;
2239     old_boost_score = boost_score;
2240   }
2241
2242   // Was the group length constrained by the requirement for a new KF?
2243   rc->constrained_gf_group = (i >= rc->frames_to_key) ? 1 : 0;
2244
2245   // Should we use the alternate reference frame.
2246   if (allow_alt_ref && (i < cpi->oxcf.lag_in_frames) &&
2247       (i >= rc->min_gf_interval)) {
2248     // Calculate the boost for alt ref.
2249     rc->gfu_boost =
2250         calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost, &b_boost);
2251     rc->source_alt_ref_pending = 1;
2252
2253     // Test to see if multi arf is appropriate.
2254     cpi->multi_arf_enabled =
2255         (cpi->multi_arf_allowed && (rc->baseline_gf_interval >= 6) &&
2256          (zero_motion_accumulator < 0.995))
2257             ? 1
2258             : 0;
2259   } else {
2260     rc->gfu_boost = VPXMAX((int)boost_score, MIN_ARF_GF_BOOST);
2261     rc->source_alt_ref_pending = 0;
2262   }
2263
2264   // Set the interval until the next gf.
2265   rc->baseline_gf_interval = i - (is_key_frame || rc->source_alt_ref_pending);
2266
2267   // Only encode alt reference frame in temporal base layer. So
2268   // baseline_gf_interval should be multiple of a temporal layer group
2269   // (typically the frame distance between two base layer frames)
2270   if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
2271     int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
2272     int new_gf_interval = (rc->baseline_gf_interval + count) & (~count);
2273     int j;
2274     for (j = 0; j < new_gf_interval - rc->baseline_gf_interval; ++j) {
2275       if (EOF == input_stats(twopass, this_frame)) break;
2276       gf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2277       gf_group_raw_error += this_frame->coded_error;
2278       gf_group_noise += this_frame->frame_noise_energy;
2279       gf_group_skip_pct += this_frame->intra_skip_pct;
2280       gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
2281       gf_group_inter += this_frame->pcnt_inter;
2282       gf_group_motion += this_frame->pcnt_motion;
2283     }
2284     rc->baseline_gf_interval = new_gf_interval;
2285   }
2286
2287   rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2288
2289   // Reset the file position.
2290   reset_fpf_position(twopass, start_pos);
2291
2292   // Calculate the bits to be allocated to the gf/arf group as a whole
2293   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
2294
2295   // Calculate an estimate of the maxq needed for the group.
2296   // We are more agressive about correcting for sections
2297   // where there could be significant overshoot than for easier
2298   // sections where we do not wish to risk creating an overshoot
2299   // of the allocated bit budget.
2300   if ((cpi->oxcf.rc_mode != VPX_Q) && (rc->baseline_gf_interval > 1)) {
2301     const int vbr_group_bits_per_frame =
2302         (int)(gf_group_bits / rc->baseline_gf_interval);
2303     const double group_av_err = gf_group_raw_error / rc->baseline_gf_interval;
2304     const double group_av_noise = gf_group_noise / rc->baseline_gf_interval;
2305     const double group_av_skip_pct =
2306         gf_group_skip_pct / rc->baseline_gf_interval;
2307     const double group_av_inactive_zone =
2308         ((gf_group_inactive_zone_rows * 2) /
2309          (rc->baseline_gf_interval * (double)cm->mb_rows));
2310     int tmp_q = get_twopass_worst_quality(
2311         cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2312         group_av_noise, vbr_group_bits_per_frame);
2313     twopass->active_worst_quality =
2314         (tmp_q + (twopass->active_worst_quality * 3)) >> 2;
2315   }
2316
2317   // Context Adjustment of ARNR filter strength
2318   if (rc->baseline_gf_interval > 1) {
2319     adjust_group_arnr_filter(cpi, (gf_group_noise / rc->baseline_gf_interval),
2320                              (gf_group_inter / rc->baseline_gf_interval),
2321                              (gf_group_motion / rc->baseline_gf_interval));
2322   } else {
2323     twopass->arnr_strength_adjustment = 0;
2324   }
2325
2326   // Calculate the extra bits to be used for boosted frame(s)
2327   gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval, rc->gfu_boost,
2328                                      gf_group_bits);
2329
2330   // Adjust KF group bits and error remaining.
2331   twopass->kf_group_error_left -= (int64_t)gf_group_err;
2332
2333   // Allocate bits to each of the frames in the GF group.
2334   allocate_gf_group_bits(cpi, gf_group_bits, gf_arf_bits);
2335
2336   // Reset the file position.
2337   reset_fpf_position(twopass, start_pos);
2338
2339   // Calculate a section intra ratio used in setting max loop filter.
2340   if (cpi->common.frame_type != KEY_FRAME) {
2341     twopass->section_intra_rating = calculate_section_intra_ratio(
2342         start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
2343   }
2344
2345   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2346     // Default to starting GF groups at normal frame size.
2347     cpi->rc.next_frame_size_selector = UNSCALED;
2348   }
2349
2350   // Reset rolling actual and target bits counters for ARF groups.
2351   twopass->rolling_arf_group_target_bits = 0;
2352   twopass->rolling_arf_group_actual_bits = 0;
2353 }
2354
2355 // Threshold for use of the lagging second reference frame. High second ref
2356 // usage may point to a transient event like a flash or occlusion rather than
2357 // a real scene cut.
2358 #define SECOND_REF_USEAGE_THRESH 0.1
2359 // Minimum % intra coding observed in first pass (1.0 = 100%)
2360 #define MIN_INTRA_LEVEL 0.25
2361 // Minimum ratio between the % of intra coding and inter coding in the first
2362 // pass after discounting neutral blocks (discounting neutral blocks in this
2363 // way helps catch scene cuts in clips with very flat areas or letter box
2364 // format clips with image padding.
2365 #define INTRA_VS_INTER_THRESH 2.0
2366 // Hard threshold where the first pass chooses intra for almost all blocks.
2367 // In such a case even if the frame is not a scene cut coding a key frame
2368 // may be a good option.
2369 #define VERY_LOW_INTER_THRESH 0.05
2370 // Maximum threshold for the relative ratio of intra error score vs best
2371 // inter error score.
2372 #define KF_II_ERR_THRESHOLD 2.5
2373 // In real scene cuts there is almost always a sharp change in the intra
2374 // or inter error score.
2375 #define ERR_CHANGE_THRESHOLD 0.4
2376 // For real scene cuts we expect an improvment in the intra inter error
2377 // ratio in the next frame.
2378 #define II_IMPROVEMENT_THRESHOLD 3.5
2379 #define KF_II_MAX 128.0
2380
2381 static int test_candidate_kf(TWO_PASS *twopass,
2382                              const FIRSTPASS_STATS *last_frame,
2383                              const FIRSTPASS_STATS *this_frame,
2384                              const FIRSTPASS_STATS *next_frame) {
2385   int is_viable_kf = 0;
2386   double pcnt_intra = 1.0 - this_frame->pcnt_inter;
2387   double modified_pcnt_inter =
2388       this_frame->pcnt_inter - this_frame->pcnt_neutral;
2389
2390   // Does the frame satisfy the primary criteria of a key frame?
2391   // See above for an explanation of the test criteria.
2392   // If so, then examine how well it predicts subsequent frames.
2393   if ((this_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2394       (next_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2395       ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
2396        ((pcnt_intra > MIN_INTRA_LEVEL) &&
2397         (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
2398         ((this_frame->intra_error /
2399           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
2400          KF_II_ERR_THRESHOLD) &&
2401         ((fabs(last_frame->coded_error - this_frame->coded_error) /
2402               DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
2403           ERR_CHANGE_THRESHOLD) ||
2404          (fabs(last_frame->intra_error - this_frame->intra_error) /
2405               DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
2406           ERR_CHANGE_THRESHOLD) ||
2407          ((next_frame->intra_error /
2408            DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) >
2409           II_IMPROVEMENT_THRESHOLD))))) {
2410     int i;
2411     const FIRSTPASS_STATS *start_pos = twopass->stats_in;
2412     FIRSTPASS_STATS local_next_frame = *next_frame;
2413     double boost_score = 0.0;
2414     double old_boost_score = 0.0;
2415     double decay_accumulator = 1.0;
2416
2417     // Examine how well the key frame predicts subsequent frames.
2418     for (i = 0; i < 16; ++i) {
2419       double next_iiratio = (BOOST_FACTOR * local_next_frame.intra_error /
2420                              DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
2421
2422       if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
2423
2424       // Cumulative effect of decay in prediction quality.
2425       if (local_next_frame.pcnt_inter > 0.85)
2426         decay_accumulator *= local_next_frame.pcnt_inter;
2427       else
2428         decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
2429
2430       // Keep a running total.
2431       boost_score += (decay_accumulator * next_iiratio);
2432
2433       // Test various breakout clauses.
2434       if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
2435           (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
2436             0.20) &&
2437            (next_iiratio < 3.0)) ||
2438           ((boost_score - old_boost_score) < 3.0) ||
2439           (local_next_frame.intra_error < 200)) {
2440         break;
2441       }
2442
2443       old_boost_score = boost_score;
2444
2445       // Get the next frame details
2446       if (EOF == input_stats(twopass, &local_next_frame)) break;
2447     }
2448
2449     // If there is tolerable prediction for at least the next 3 frames then
2450     // break out else discard this potential key frame and move on
2451     if (boost_score > 30.0 && (i > 3)) {
2452       is_viable_kf = 1;
2453     } else {
2454       // Reset the file position
2455       reset_fpf_position(twopass, start_pos);
2456
2457       is_viable_kf = 0;
2458     }
2459   }
2460
2461   return is_viable_kf;
2462 }
2463
2464 #define FRAMES_TO_CHECK_DECAY 8
2465
2466 static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2467   int i, j;
2468   RATE_CONTROL *const rc = &cpi->rc;
2469   TWO_PASS *const twopass = &cpi->twopass;
2470   GF_GROUP *const gf_group = &twopass->gf_group;
2471   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2472   const FIRSTPASS_STATS first_frame = *this_frame;
2473   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
2474   FIRSTPASS_STATS next_frame;
2475   FIRSTPASS_STATS last_frame;
2476   int kf_bits = 0;
2477   int loop_decay_counter = 0;
2478   double decay_accumulator = 1.0;
2479   double av_decay_accumulator = 0.0;
2480   double zero_motion_accumulator = 1.0;
2481   double boost_score = 0.0;
2482   double kf_mod_err = 0.0;
2483   double kf_group_err = 0.0;
2484   double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
2485
2486   vp9_zero(next_frame);
2487
2488   cpi->common.frame_type = KEY_FRAME;
2489
2490   // Reset the GF group data structures.
2491   vp9_zero(*gf_group);
2492
2493   // Is this a forced key frame by interval.
2494   rc->this_key_frame_forced = rc->next_key_frame_forced;
2495
2496   // Clear the alt ref active flag and last group multi arf flags as they
2497   // can never be set for a key frame.
2498   rc->source_alt_ref_active = 0;
2499   cpi->multi_arf_last_grp_enabled = 0;
2500
2501   // KF is always a GF so clear frames till next gf counter.
2502   rc->frames_till_gf_update_due = 0;
2503
2504   rc->frames_to_key = 1;
2505
2506   twopass->kf_group_bits = 0;        // Total bits available to kf group
2507   twopass->kf_group_error_left = 0;  // Group modified error score.
2508
2509   kf_mod_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
2510
2511   // Initialize the decay rates for the recent frames to check
2512   for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
2513
2514   // Find the next keyframe.
2515   i = 0;
2516   while (twopass->stats_in < twopass->stats_in_end &&
2517          rc->frames_to_key < cpi->oxcf.key_freq) {
2518     // Accumulate kf group error.
2519     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2520
2521     // Load the next frame's stats.
2522     last_frame = *this_frame;
2523     input_stats(twopass, this_frame);
2524
2525     // Provided that we are not at the end of the file...
2526     if (cpi->oxcf.auto_key && twopass->stats_in < twopass->stats_in_end) {
2527       double loop_decay_rate;
2528
2529       // Check for a scene cut.
2530       if (test_candidate_kf(twopass, &last_frame, this_frame,
2531                             twopass->stats_in))
2532         break;
2533
2534       // How fast is the prediction quality decaying?
2535       loop_decay_rate = get_prediction_decay_rate(cpi, twopass->stats_in);
2536
2537       // We want to know something about the recent past... rather than
2538       // as used elsewhere where we are concerned with decay in prediction
2539       // quality since the last GF or KF.
2540       recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
2541       decay_accumulator = 1.0;
2542       for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
2543         decay_accumulator *= recent_loop_decay[j];
2544
2545       // Special check for transition or high motion followed by a
2546       // static scene.
2547       if (detect_transition_to_still(cpi, i, cpi->oxcf.key_freq - i,
2548                                      loop_decay_rate, decay_accumulator))
2549         break;
2550
2551       // Step on to the next frame.
2552       ++rc->frames_to_key;
2553
2554       // If we don't have a real key frame within the next two
2555       // key_freq intervals then break out of the loop.
2556       if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq) break;
2557     } else {
2558       ++rc->frames_to_key;
2559     }
2560     ++i;
2561   }
2562
2563   // If there is a max kf interval set by the user we must obey it.
2564   // We already breakout of the loop above at 2x max.
2565   // This code centers the extra kf if the actual natural interval
2566   // is between 1x and 2x.
2567   if (cpi->oxcf.auto_key && rc->frames_to_key > cpi->oxcf.key_freq) {
2568     FIRSTPASS_STATS tmp_frame = first_frame;
2569
2570     rc->frames_to_key /= 2;
2571
2572     // Reset to the start of the group.
2573     reset_fpf_position(twopass, start_position);
2574
2575     kf_group_err = 0.0;
2576
2577     // Rescan to get the correct error data for the forced kf group.
2578     for (i = 0; i < rc->frames_to_key; ++i) {
2579       kf_group_err += calculate_modified_err(cpi, twopass, oxcf, &tmp_frame);
2580       input_stats(twopass, &tmp_frame);
2581     }
2582     rc->next_key_frame_forced = 1;
2583   } else if (twopass->stats_in == twopass->stats_in_end ||
2584              rc->frames_to_key >= cpi->oxcf.key_freq) {
2585     rc->next_key_frame_forced = 1;
2586   } else {
2587     rc->next_key_frame_forced = 0;
2588   }
2589
2590   if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
2591     int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
2592     int new_frame_to_key = (rc->frames_to_key + count) & (~count);
2593     int j;
2594     for (j = 0; j < new_frame_to_key - rc->frames_to_key; ++j) {
2595       if (EOF == input_stats(twopass, this_frame)) break;
2596       kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2597     }
2598     rc->frames_to_key = new_frame_to_key;
2599   }
2600
2601   // Special case for the last key frame of the file.
2602   if (twopass->stats_in >= twopass->stats_in_end) {
2603     // Accumulate kf group error.
2604     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2605   }
2606
2607   // Calculate the number of bits that should be assigned to the kf group.
2608   if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
2609     // Maximum number of bits for a single normal frame (not key frame).
2610     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2611
2612     // Maximum number of bits allocated to the key frame group.
2613     int64_t max_grp_bits;
2614
2615     // Default allocation based on bits left and relative
2616     // complexity of the section.
2617     twopass->kf_group_bits = (int64_t)(
2618         twopass->bits_left * (kf_group_err / twopass->modified_error_left));
2619
2620     // Clip based on maximum per frame rate defined by the user.
2621     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
2622     if (twopass->kf_group_bits > max_grp_bits)
2623       twopass->kf_group_bits = max_grp_bits;
2624   } else {
2625     twopass->kf_group_bits = 0;
2626   }
2627   twopass->kf_group_bits = VPXMAX(0, twopass->kf_group_bits);
2628
2629   // Reset the first pass file position.
2630   reset_fpf_position(twopass, start_position);
2631
2632   // Scan through the kf group collating various stats used to determine
2633   // how many bits to spend on it.
2634   decay_accumulator = 1.0;
2635   boost_score = 0.0;
2636   for (i = 0; i < (rc->frames_to_key - 1); ++i) {
2637     if (EOF == input_stats(twopass, &next_frame)) break;
2638
2639     // Monitor for static sections.
2640     zero_motion_accumulator = VPXMIN(zero_motion_accumulator,
2641                                      get_zero_motion_factor(cpi, &next_frame));
2642
2643     // Not all frames in the group are necessarily used in calculating boost.
2644     if ((i <= rc->max_gf_interval) ||
2645         ((i <= (rc->max_gf_interval * 4)) && (decay_accumulator > 0.5))) {
2646       const double frame_boost =
2647           calc_frame_boost(cpi, &next_frame, 0, KF_MAX_BOOST);
2648
2649       // How fast is prediction quality decaying.
2650       if (!detect_flash(twopass, 0)) {
2651         const double loop_decay_rate =
2652             get_prediction_decay_rate(cpi, &next_frame);
2653         decay_accumulator *= loop_decay_rate;
2654         decay_accumulator = VPXMAX(decay_accumulator, MIN_DECAY_FACTOR);
2655         av_decay_accumulator += decay_accumulator;
2656         ++loop_decay_counter;
2657       }
2658       boost_score += (decay_accumulator * frame_boost);
2659     }
2660   }
2661   av_decay_accumulator /= (double)loop_decay_counter;
2662
2663   reset_fpf_position(twopass, start_position);
2664
2665   // Store the zero motion percentage
2666   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
2667
2668   // Calculate a section intra ratio used in setting max loop filter.
2669   twopass->section_intra_rating = calculate_section_intra_ratio(
2670       start_position, twopass->stats_in_end, rc->frames_to_key);
2671
2672   // Apply various clamps for min and max boost
2673   rc->kf_boost = (int)(av_decay_accumulator * boost_score);
2674   rc->kf_boost = VPXMAX(rc->kf_boost, (rc->frames_to_key * 3));
2675   rc->kf_boost = VPXMAX(rc->kf_boost, MIN_KF_BOOST);
2676
2677   // Work out how many bits to allocate for the key frame itself.
2678   kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
2679                                  twopass->kf_group_bits);
2680
2681   twopass->kf_group_bits -= kf_bits;
2682
2683   // Save the bits to spend on the key frame.
2684   gf_group->bit_allocation[0] = kf_bits;
2685   gf_group->update_type[0] = KF_UPDATE;
2686   gf_group->rf_level[0] = KF_STD;
2687
2688   // Note the total error score of the kf group minus the key frame itself.
2689   twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
2690
2691   // Adjust the count of total modified error left.
2692   // The count of bits left is adjusted elsewhere based on real coded frame
2693   // sizes.
2694   twopass->modified_error_left -= kf_group_err;
2695
2696   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2697     // Default to normal-sized frame on keyframes.
2698     cpi->rc.next_frame_size_selector = UNSCALED;
2699   }
2700 }
2701
2702 // Define the reference buffers that will be updated post encode.
2703 static void configure_buffer_updates(VP9_COMP *cpi) {
2704   TWO_PASS *const twopass = &cpi->twopass;
2705
2706   cpi->rc.is_src_frame_alt_ref = 0;
2707   switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
2708     case KF_UPDATE:
2709       cpi->refresh_last_frame = 1;
2710       cpi->refresh_golden_frame = 1;
2711       cpi->refresh_alt_ref_frame = 1;
2712       break;
2713     case LF_UPDATE:
2714       cpi->refresh_last_frame = 1;
2715       cpi->refresh_golden_frame = 0;
2716       cpi->refresh_alt_ref_frame = 0;
2717       break;
2718     case GF_UPDATE:
2719       cpi->refresh_last_frame = 1;
2720       cpi->refresh_golden_frame = 1;
2721       cpi->refresh_alt_ref_frame = 0;
2722       break;
2723     case OVERLAY_UPDATE:
2724       cpi->refresh_last_frame = 0;
2725       cpi->refresh_golden_frame = 1;
2726       cpi->refresh_alt_ref_frame = 0;
2727       cpi->rc.is_src_frame_alt_ref = 1;
2728       break;
2729     case ARF_UPDATE:
2730       cpi->refresh_last_frame = 0;
2731       cpi->refresh_golden_frame = 0;
2732       cpi->refresh_alt_ref_frame = 1;
2733       break;
2734     default: assert(0); break;
2735   }
2736   if (is_two_pass_svc(cpi)) {
2737     if (cpi->svc.temporal_layer_id > 0) {
2738       cpi->refresh_last_frame = 0;
2739       cpi->refresh_golden_frame = 0;
2740     }
2741     if (cpi->svc.layer_context[cpi->svc.spatial_layer_id].gold_ref_idx < 0)
2742       cpi->refresh_golden_frame = 0;
2743     if (cpi->alt_ref_source == NULL) cpi->refresh_alt_ref_frame = 0;
2744   }
2745 }
2746
2747 static int is_skippable_frame(const VP9_COMP *cpi) {
2748   // If the current frame does not have non-zero motion vector detected in the
2749   // first  pass, and so do its previous and forward frames, then this frame
2750   // can be skipped for partition check, and the partition size is assigned
2751   // according to the variance
2752   const SVC *const svc = &cpi->svc;
2753   const TWO_PASS *const twopass =
2754       is_two_pass_svc(cpi) ? &svc->layer_context[svc->spatial_layer_id].twopass
2755                            : &cpi->twopass;
2756
2757   return (!frame_is_intra_only(&cpi->common) &&
2758           twopass->stats_in - 2 > twopass->stats_in_start &&
2759           twopass->stats_in < twopass->stats_in_end &&
2760           (twopass->stats_in - 1)->pcnt_inter -
2761                   (twopass->stats_in - 1)->pcnt_motion ==
2762               1 &&
2763           (twopass->stats_in - 2)->pcnt_inter -
2764                   (twopass->stats_in - 2)->pcnt_motion ==
2765               1 &&
2766           twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
2767 }
2768
2769 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
2770   VP9_COMMON *const cm = &cpi->common;
2771   RATE_CONTROL *const rc = &cpi->rc;
2772   TWO_PASS *const twopass = &cpi->twopass;
2773   GF_GROUP *const gf_group = &twopass->gf_group;
2774   FIRSTPASS_STATS this_frame;
2775
2776   int target_rate;
2777   LAYER_CONTEXT *const lc =
2778       is_two_pass_svc(cpi) ? &cpi->svc.layer_context[cpi->svc.spatial_layer_id]
2779                            : 0;
2780
2781   if (!twopass->stats_in) return;
2782
2783   // If this is an arf frame then we dont want to read the stats file or
2784   // advance the input pointer as we already have what we need.
2785   if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
2786     int target_rate;
2787     configure_buffer_updates(cpi);
2788     target_rate = gf_group->bit_allocation[gf_group->index];
2789     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2790     rc->base_frame_target = target_rate;
2791
2792     cm->frame_type = INTER_FRAME;
2793
2794     if (lc != NULL) {
2795       if (cpi->svc.spatial_layer_id == 0) {
2796         lc->is_key_frame = 0;
2797       } else {
2798         lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2799
2800         if (lc->is_key_frame) cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2801       }
2802     }
2803
2804     // Do the firstpass stats indicate that this frame is skippable for the
2805     // partition search?
2806     if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2 &&
2807         (!cpi->use_svc || is_two_pass_svc(cpi))) {
2808       cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
2809     }
2810
2811     return;
2812   }
2813
2814   vpx_clear_system_state();
2815
2816   if (cpi->oxcf.rc_mode == VPX_Q) {
2817     twopass->active_worst_quality = cpi->oxcf.cq_level;
2818   } else if (cm->current_video_frame == 0 ||
2819              (lc != NULL && lc->current_video_frame_in_layer == 0)) {
2820     const int frames_left =
2821         (int)(twopass->total_stats.count -
2822               ((lc != NULL) ? lc->current_video_frame_in_layer
2823                             : cm->current_video_frame));
2824     // Special case code for first frame.
2825     const int section_target_bandwidth =
2826         (int)(twopass->bits_left / frames_left);
2827     const double section_length = twopass->total_left_stats.count;
2828     const double section_error =
2829         twopass->total_left_stats.coded_error / section_length;
2830     const double section_intra_skip =
2831         twopass->total_left_stats.intra_skip_pct / section_length;
2832     const double section_inactive_zone =
2833         (twopass->total_left_stats.inactive_zone_rows * 2) /
2834         ((double)cm->mb_rows * section_length);
2835     const double section_noise =
2836         twopass->total_left_stats.frame_noise_energy / section_length;
2837     int tmp_q;
2838
2839     tmp_q = get_twopass_worst_quality(
2840         cpi, section_error, section_intra_skip + section_inactive_zone,
2841         section_noise, section_target_bandwidth);
2842
2843     twopass->active_worst_quality = tmp_q;
2844     twopass->baseline_active_worst_quality = tmp_q;
2845     rc->ni_av_qi = tmp_q;
2846     rc->last_q[INTER_FRAME] = tmp_q;
2847     rc->avg_q = vp9_convert_qindex_to_q(tmp_q, cm->bit_depth);
2848     rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
2849     rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
2850     rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
2851   }
2852   vp9_zero(this_frame);
2853   if (EOF == input_stats(twopass, &this_frame)) return;
2854
2855   // Set the frame content type flag.
2856   if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
2857     twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
2858   else
2859     twopass->fr_content_type = FC_NORMAL;
2860
2861   // Keyframe and section processing.
2862   if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
2863     FIRSTPASS_STATS this_frame_copy;
2864     this_frame_copy = this_frame;
2865     // Define next KF group and assign bits to it.
2866     find_next_key_frame(cpi, &this_frame);
2867     this_frame = this_frame_copy;
2868   } else {
2869     cm->frame_type = INTER_FRAME;
2870   }
2871
2872   if (lc != NULL) {
2873     if (cpi->svc.spatial_layer_id == 0) {
2874       lc->is_key_frame = (cm->frame_type == KEY_FRAME);
2875       if (lc->is_key_frame) {
2876         cpi->ref_frame_flags &=
2877             (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
2878         lc->frames_from_key_frame = 0;
2879         // Encode an intra only empty frame since we have a key frame.
2880         cpi->svc.encode_intra_empty_frame = 1;
2881       }
2882     } else {
2883       cm->frame_type = INTER_FRAME;
2884       lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2885
2886       if (lc->is_key_frame) {
2887         cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2888         lc->frames_from_key_frame = 0;
2889       }
2890     }
2891   }
2892
2893   // Define a new GF/ARF group. (Should always enter here for key frames).
2894   if (rc->frames_till_gf_update_due == 0) {
2895     define_gf_group(cpi, &this_frame);
2896
2897     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2898     if (lc != NULL) cpi->refresh_golden_frame = 1;
2899
2900 #if ARF_STATS_OUTPUT
2901     {
2902       FILE *fpfile;
2903       fpfile = fopen("arf.stt", "a");
2904       ++arf_count;
2905       fprintf(fpfile, "%10d %10ld %10d %10d %10ld\n", cm->current_video_frame,
2906               rc->frames_till_gf_update_due, rc->kf_boost, arf_count,
2907               rc->gfu_boost);
2908
2909       fclose(fpfile);
2910     }
2911 #endif
2912   }
2913
2914   configure_buffer_updates(cpi);
2915
2916   // Do the firstpass stats indicate that this frame is skippable for the
2917   // partition search?
2918   if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2 &&
2919       (!cpi->use_svc || is_two_pass_svc(cpi))) {
2920     cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
2921   }
2922
2923   target_rate = gf_group->bit_allocation[gf_group->index];
2924   rc->base_frame_target = target_rate;
2925
2926   {
2927     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
2928                             ? cpi->initial_mbs
2929                             : cpi->common.MBs;
2930     // The multiplication by 256 reverses a scaling factor of (>> 8)
2931     // applied when combining MB error values for the frame.
2932     twopass->mb_av_energy =
2933         log(((this_frame.intra_error * 256.0) / num_mbs) + 1.0);
2934     twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
2935   }
2936
2937   // Update the total stats remaining structure.
2938   subtract_stats(&twopass->total_left_stats, &this_frame);
2939 }
2940
2941 #define MINQ_ADJ_LIMIT 48
2942 #define MINQ_ADJ_LIMIT_CQ 20
2943 #define HIGH_UNDERSHOOT_RATIO 2
2944 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
2945   TWO_PASS *const twopass = &cpi->twopass;
2946   RATE_CONTROL *const rc = &cpi->rc;
2947   VP9_COMMON *const cm = &cpi->common;
2948   const int bits_used = rc->base_frame_target;
2949
2950   // VBR correction is done through rc->vbr_bits_off_target. Based on the
2951   // sign of this value, a limited % adjustment is made to the target rate
2952   // of subsequent frames, to try and push it back towards 0. This method
2953   // is designed to prevent extreme behaviour at the end of a clip
2954   // or group of frames.
2955   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
2956   twopass->bits_left = VPXMAX(twopass->bits_left - bits_used, 0);
2957
2958   // Target vs actual bits for this arf group.
2959   twopass->rolling_arf_group_target_bits += rc->this_frame_target;
2960   twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
2961
2962   // Calculate the pct rc error.
2963   if (rc->total_actual_bits) {
2964     rc->rate_error_estimate =
2965         (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
2966     rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
2967   } else {
2968     rc->rate_error_estimate = 0;
2969   }
2970
2971   if (cpi->common.frame_type != KEY_FRAME &&
2972       !vp9_is_upper_layer_key_frame(cpi)) {
2973     twopass->kf_group_bits -= bits_used;
2974     twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
2975   }
2976   twopass->kf_group_bits = VPXMAX(twopass->kf_group_bits, 0);
2977
2978   // Increment the gf group index ready for the next frame.
2979   ++twopass->gf_group.index;
2980
2981   // If the rate control is drifting consider adjustment to min or maxq.
2982   if ((cpi->oxcf.rc_mode != VPX_Q) && !cpi->rc.is_src_frame_alt_ref) {
2983     const int maxq_adj_limit =
2984         rc->worst_quality - twopass->active_worst_quality;
2985     const int minq_adj_limit =
2986         (cpi->oxcf.rc_mode == VPX_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
2987     int aq_extend_min = 0;
2988     int aq_extend_max = 0;
2989
2990     // Extend min or Max Q range to account for imbalance from the base
2991     // value when using AQ.
2992     if (cpi->oxcf.aq_mode != NO_AQ) {
2993       if (cm->seg.aq_av_offset < 0) {
2994         // The balance of the AQ map tends towarda lowering the average Q.
2995         aq_extend_min = 0;
2996         aq_extend_max = VPXMIN(maxq_adj_limit, -cm->seg.aq_av_offset);
2997       } else {
2998         // The balance of the AQ map tends towards raising the average Q.
2999         aq_extend_min = VPXMIN(minq_adj_limit, cm->seg.aq_av_offset);
3000         aq_extend_max = 0;
3001       }
3002     }
3003
3004     // Undershoot.
3005     if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
3006       --twopass->extend_maxq;
3007       if (rc->rolling_target_bits >= rc->rolling_actual_bits)
3008         ++twopass->extend_minq;
3009       // Overshoot.
3010     } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
3011       --twopass->extend_minq;
3012       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3013         ++twopass->extend_maxq;
3014     } else {
3015       // Adjustment for extreme local overshoot.
3016       if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
3017           rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
3018         ++twopass->extend_maxq;
3019
3020       // Unwind undershoot or overshoot adjustment.
3021       if (rc->rolling_target_bits < rc->rolling_actual_bits)
3022         --twopass->extend_minq;
3023       else if (rc->rolling_target_bits > rc->rolling_actual_bits)
3024         --twopass->extend_maxq;
3025     }
3026
3027     twopass->extend_minq =
3028         clamp(twopass->extend_minq, aq_extend_min, minq_adj_limit);
3029     twopass->extend_maxq =
3030         clamp(twopass->extend_maxq, aq_extend_max, maxq_adj_limit);
3031
3032     // If there is a big and undexpected undershoot then feed the extra
3033     // bits back in quickly. One situation where this may happen is if a
3034     // frame is unexpectedly almost perfectly predicted by the ARF or GF
3035     // but not very well predcited by the previous frame.
3036     if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
3037       int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
3038       if (rc->projected_frame_size < fast_extra_thresh) {
3039         rc->vbr_bits_off_target_fast +=
3040             fast_extra_thresh - rc->projected_frame_size;
3041         rc->vbr_bits_off_target_fast =
3042             VPXMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
3043
3044         // Fast adaptation of minQ if necessary to use up the extra bits.
3045         if (rc->avg_frame_bandwidth) {
3046           twopass->extend_minq_fast =
3047               (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
3048         }
3049         twopass->extend_minq_fast = VPXMIN(
3050             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3051       } else if (rc->vbr_bits_off_target_fast) {
3052         twopass->extend_minq_fast = VPXMIN(
3053             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3054       } else {
3055         twopass->extend_minq_fast = 0;
3056       }
3057     }
3058   }
3059 }