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