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