]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_firstpass.c
Merge "VP9 denoiser implemented FILTER_BLOCK case"
[libvpx] / vp9 / encoder / vp9_firstpass.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <limits.h>
12 #include <math.h>
13 #include <stdio.h>
14
15 #include "./vpx_scale_rtcd.h"
16
17 #include "vpx_mem/vpx_mem.h"
18 #include "vpx_scale/vpx_scale.h"
19 #include "vpx_scale/yv12config.h"
20
21 #include "vp9/common/vp9_entropymv.h"
22 #include "vp9/common/vp9_quant_common.h"
23 #include "vp9/common/vp9_reconinter.h"  // vp9_setup_dst_planes()
24 #include "vp9/common/vp9_systemdependent.h"
25
26 #include "vp9/encoder/vp9_aq_variance.h"
27 #include "vp9/encoder/vp9_block.h"
28 #include "vp9/encoder/vp9_encodeframe.h"
29 #include "vp9/encoder/vp9_encodemb.h"
30 #include "vp9/encoder/vp9_encodemv.h"
31 #include "vp9/encoder/vp9_encoder.h"
32 #include "vp9/encoder/vp9_extend.h"
33 #include "vp9/encoder/vp9_firstpass.h"
34 #include "vp9/encoder/vp9_mcomp.h"
35 #include "vp9/encoder/vp9_quantize.h"
36 #include "vp9/encoder/vp9_rdopt.h"
37 #include "vp9/encoder/vp9_variance.h"
38
39 #define OUTPUT_FPF 0
40
41 #define IIFACTOR   12.5
42 #define IIKFACTOR1 12.5
43 #define IIKFACTOR2 15.0
44 #define RMAX       512.0
45 #define GF_RMAX    96.0
46 #define ERR_DIVISOR   150.0
47 #define MIN_DECAY_FACTOR 0.1
48 #define SVC_FACTOR_PT_LOW 0.45
49 #define FACTOR_PT_LOW 0.5
50 #define FACTOR_PT_HIGH 0.9
51
52 #define KF_MB_INTRA_MIN 150
53 #define GF_MB_INTRA_MIN 100
54
55 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x) - 0.000001 : (x) + 0.000001)
56
57 #define MIN_KF_BOOST        300
58 #define MIN_GF_INTERVAL     4
59 #define LONG_TERM_VBR_CORRECTION
60
61 static void swap_yv12(YV12_BUFFER_CONFIG *a, YV12_BUFFER_CONFIG *b) {
62   YV12_BUFFER_CONFIG temp = *a;
63   *a = *b;
64   *b = temp;
65 }
66
67 static int gfboost_qadjust(int qindex) {
68   const double q = vp9_convert_qindex_to_q(qindex);
69   return (int)((0.00000828 * q * q * q) +
70                (-0.0055 * q * q) +
71                (1.32 * q) + 79.3);
72 }
73
74 // Resets the first pass file to the given position using a relative seek from
75 // the current position.
76 static void reset_fpf_position(TWO_PASS *p,
77                                const FIRSTPASS_STATS *position) {
78   p->stats_in = position;
79 }
80
81 static int lookup_next_frame_stats(const TWO_PASS *p,
82                                    FIRSTPASS_STATS *next_frame) {
83   if (p->stats_in >= p->stats_in_end)
84     return EOF;
85
86   *next_frame = *p->stats_in;
87   return 1;
88 }
89
90
91 // Read frame stats at an offset from the current position.
92 static int read_frame_stats(const TWO_PASS *p,
93                             FIRSTPASS_STATS *frame_stats, int offset) {
94   const FIRSTPASS_STATS *fps_ptr = p->stats_in;
95
96   // Check legality of offset.
97   if (offset >= 0) {
98     if (&fps_ptr[offset] >= p->stats_in_end)
99       return EOF;
100   } else if (offset < 0) {
101     if (&fps_ptr[offset] < p->stats_in_start)
102       return EOF;
103   }
104
105   *frame_stats = fps_ptr[offset];
106   return 1;
107 }
108
109 #if CONFIG_FP_MB_STATS
110 static int input_mb_stats(FIRSTPASS_FRAME_MB_STATS *fp_frame_stats,
111                           const VP9_COMMON *const cm) {
112   FILE *fpfile;
113   int ret;
114
115   fpfile = fopen("firstpass_mb.stt", "r");
116   fseek(fpfile, cm->current_video_frame * cm->MBs * sizeof(FIRSTPASS_MB_STATS),
117         SEEK_SET);
118   ret = fread(fp_frame_stats->mb_stats, sizeof(FIRSTPASS_MB_STATS), cm->MBs,
119               fpfile);
120   fclose(fpfile);
121   if (ret < cm->MBs) {
122     return EOF;
123   }
124   return 1;
125 }
126
127 static void output_mb_stats(FIRSTPASS_FRAME_MB_STATS *fp_frame_stats,
128                           const VP9_COMMON *const cm) {
129   FILE *fpfile;
130
131   fpfile = fopen("firstpass_mb.stt", "a");
132   fwrite(fp_frame_stats->mb_stats, sizeof(FIRSTPASS_MB_STATS), cm->MBs, fpfile);
133   fclose(fpfile);
134 }
135 #endif
136
137 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
138   if (p->stats_in >= p->stats_in_end)
139     return EOF;
140
141   *fps = *p->stats_in;
142   ++p->stats_in;
143   return 1;
144 }
145
146 static void output_stats(FIRSTPASS_STATS *stats,
147                          struct vpx_codec_pkt_list *pktlist) {
148   struct vpx_codec_cx_pkt pkt;
149   pkt.kind = VPX_CODEC_STATS_PKT;
150   pkt.data.twopass_stats.buf = stats;
151   pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
152   vpx_codec_pkt_list_add(pktlist, &pkt);
153
154 // TEMP debug code
155 #if OUTPUT_FPF
156   {
157     FILE *fpfile;
158     fpfile = fopen("firstpass.stt", "a");
159
160     fprintf(fpfile, "%12.0f %12.0f %12.0f %12.0f %12.4f %12.4f"
161             "%12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f"
162             "%12.0f %12.0f %12.4f %12.0f %12.0f %12.4f\n",
163             stats->frame,
164             stats->intra_error,
165             stats->coded_error,
166             stats->sr_coded_error,
167             stats->pcnt_inter,
168             stats->pcnt_motion,
169             stats->pcnt_second_ref,
170             stats->pcnt_neutral,
171             stats->MVr,
172             stats->mvr_abs,
173             stats->MVc,
174             stats->mvc_abs,
175             stats->MVrv,
176             stats->MVcv,
177             stats->mv_in_out_count,
178             stats->new_mv_count,
179             stats->count,
180             stats->duration);
181     fclose(fpfile);
182   }
183 #endif
184 }
185
186 static void zero_stats(FIRSTPASS_STATS *section) {
187   section->frame      = 0.0;
188   section->intra_error = 0.0;
189   section->coded_error = 0.0;
190   section->sr_coded_error = 0.0;
191   section->pcnt_inter  = 0.0;
192   section->pcnt_motion  = 0.0;
193   section->pcnt_second_ref = 0.0;
194   section->pcnt_neutral = 0.0;
195   section->MVr        = 0.0;
196   section->mvr_abs     = 0.0;
197   section->MVc        = 0.0;
198   section->mvc_abs     = 0.0;
199   section->MVrv       = 0.0;
200   section->MVcv       = 0.0;
201   section->mv_in_out_count  = 0.0;
202   section->new_mv_count = 0.0;
203   section->count      = 0.0;
204   section->duration   = 1.0;
205   section->spatial_layer_id = 0;
206 }
207
208 static void accumulate_stats(FIRSTPASS_STATS *section,
209                              const FIRSTPASS_STATS *frame) {
210   section->frame += frame->frame;
211   section->spatial_layer_id = frame->spatial_layer_id;
212   section->intra_error += frame->intra_error;
213   section->coded_error += frame->coded_error;
214   section->sr_coded_error += frame->sr_coded_error;
215   section->pcnt_inter  += frame->pcnt_inter;
216   section->pcnt_motion += frame->pcnt_motion;
217   section->pcnt_second_ref += frame->pcnt_second_ref;
218   section->pcnt_neutral += frame->pcnt_neutral;
219   section->MVr        += frame->MVr;
220   section->mvr_abs     += frame->mvr_abs;
221   section->MVc        += frame->MVc;
222   section->mvc_abs     += frame->mvc_abs;
223   section->MVrv       += frame->MVrv;
224   section->MVcv       += frame->MVcv;
225   section->mv_in_out_count  += frame->mv_in_out_count;
226   section->new_mv_count += frame->new_mv_count;
227   section->count      += frame->count;
228   section->duration   += frame->duration;
229 }
230
231 static void subtract_stats(FIRSTPASS_STATS *section,
232                            const FIRSTPASS_STATS *frame) {
233   section->frame -= frame->frame;
234   section->intra_error -= frame->intra_error;
235   section->coded_error -= frame->coded_error;
236   section->sr_coded_error -= frame->sr_coded_error;
237   section->pcnt_inter  -= frame->pcnt_inter;
238   section->pcnt_motion -= frame->pcnt_motion;
239   section->pcnt_second_ref -= frame->pcnt_second_ref;
240   section->pcnt_neutral -= frame->pcnt_neutral;
241   section->MVr        -= frame->MVr;
242   section->mvr_abs     -= frame->mvr_abs;
243   section->MVc        -= frame->MVc;
244   section->mvc_abs     -= frame->mvc_abs;
245   section->MVrv       -= frame->MVrv;
246   section->MVcv       -= frame->MVcv;
247   section->mv_in_out_count  -= frame->mv_in_out_count;
248   section->new_mv_count -= frame->new_mv_count;
249   section->count      -= frame->count;
250   section->duration   -= frame->duration;
251 }
252
253 static void avg_stats(FIRSTPASS_STATS *section) {
254   if (section->count < 1.0)
255     return;
256
257   section->intra_error /= section->count;
258   section->coded_error /= section->count;
259   section->sr_coded_error /= section->count;
260   section->pcnt_inter  /= section->count;
261   section->pcnt_second_ref /= section->count;
262   section->pcnt_neutral /= section->count;
263   section->pcnt_motion /= section->count;
264   section->MVr        /= section->count;
265   section->mvr_abs     /= section->count;
266   section->MVc        /= section->count;
267   section->mvc_abs     /= section->count;
268   section->MVrv       /= section->count;
269   section->MVcv       /= section->count;
270   section->mv_in_out_count   /= section->count;
271   section->duration   /= section->count;
272 }
273
274 // Calculate a modified Error used in distributing bits between easier and
275 // harder frames.
276 static double calculate_modified_err(const TWO_PASS *twopass,
277                                      const VP9EncoderConfig *oxcf,
278                                      const FIRSTPASS_STATS *this_frame) {
279   const FIRSTPASS_STATS *const stats = &twopass->total_stats;
280   const double av_err = stats->coded_error / stats->count;
281   const double modified_error = av_err *
282       pow(this_frame->coded_error / DOUBLE_DIVIDE_CHECK(av_err),
283           oxcf->two_pass_vbrbias / 100.0);
284   return fclamp(modified_error,
285                 twopass->modified_error_min, twopass->modified_error_max);
286 }
287
288 // This function returns the maximum target rate per frame.
289 static int frame_max_bits(const RATE_CONTROL *rc,
290                           const VP9EncoderConfig *oxcf) {
291   int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
292                           (int64_t)oxcf->two_pass_vbrmax_section) / 100;
293   if (max_bits < 0)
294     max_bits = 0;
295   else if (max_bits > rc->max_frame_bandwidth)
296     max_bits = rc->max_frame_bandwidth;
297
298   return (int)max_bits;
299 }
300
301 void vp9_init_first_pass(VP9_COMP *cpi) {
302   zero_stats(&cpi->twopass.total_stats);
303 }
304
305 void vp9_end_first_pass(VP9_COMP *cpi) {
306   if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
307     int i;
308     for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
309       output_stats(&cpi->svc.layer_context[i].twopass.total_stats,
310                    cpi->output_pkt_list);
311     }
312   } else {
313     output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
314   }
315 }
316
317 static vp9_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
318   switch (bsize) {
319     case BLOCK_8X8:
320       return vp9_mse8x8;
321     case BLOCK_16X8:
322       return vp9_mse16x8;
323     case BLOCK_8X16:
324       return vp9_mse8x16;
325     default:
326       return vp9_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 vp9_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 // Refine the motion search range according to the frame dimension
340 // for first pass test.
341 static int get_search_range(const VP9_COMMON *cm) {
342   int sr = 0;
343   const int dim = MIN(cm->width, cm->height);
344
345   while ((dim << sr) < MAX_FULL_PEL_VAL)
346     ++sr;
347   return sr;
348 }
349
350 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
351                                      const MV *ref_mv, MV *best_mv,
352                                      int *best_motion_err) {
353   MACROBLOCKD *const xd = &x->e_mbd;
354   MV tmp_mv = {0, 0};
355   MV ref_mv_full = {ref_mv->row >> 3, ref_mv->col >> 3};
356   int num00, tmp_err, n;
357   const BLOCK_SIZE bsize = xd->mi[0]->mbmi.sb_type;
358   vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
359   const int new_mv_mode_penalty = 256;
360
361   int step_param = 3;
362   int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
363   const int sr = get_search_range(&cpi->common);
364   step_param += sr;
365   further_steps -= sr;
366
367   // Override the default variance function to use MSE.
368   v_fn_ptr.vf = get_block_variance_fn(bsize);
369
370   // Center the initial step/diamond search on best mv.
371   tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
372                                     step_param,
373                                     x->sadperbit16, &num00, &v_fn_ptr, ref_mv);
374   if (tmp_err < INT_MAX)
375     tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
376   if (tmp_err < INT_MAX - new_mv_mode_penalty)
377     tmp_err += new_mv_mode_penalty;
378
379   if (tmp_err < *best_motion_err) {
380     *best_motion_err = tmp_err;
381     *best_mv = tmp_mv;
382   }
383
384   // Carry out further step/diamond searches as necessary.
385   n = num00;
386   num00 = 0;
387
388   while (n < further_steps) {
389     ++n;
390
391     if (num00) {
392       --num00;
393     } else {
394       tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
395                                         step_param + n, x->sadperbit16,
396                                         &num00, &v_fn_ptr, ref_mv);
397       if (tmp_err < INT_MAX)
398         tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
399       if (tmp_err < INT_MAX - new_mv_mode_penalty)
400         tmp_err += new_mv_mode_penalty;
401
402       if (tmp_err < *best_motion_err) {
403         *best_motion_err = tmp_err;
404         *best_mv = tmp_mv;
405       }
406     }
407   }
408 }
409
410 static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
411   if (2 * mb_col + 1 < cm->mi_cols) {
412     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16
413                                         : BLOCK_16X8;
414   } else {
415     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16
416                                         : BLOCK_8X8;
417   }
418 }
419
420 static int find_fp_qindex() {
421   int i;
422
423   for (i = 0; i < QINDEX_RANGE; ++i)
424     if (vp9_convert_qindex_to_q(i) >= 30.0)
425       break;
426
427   if (i == QINDEX_RANGE)
428     i--;
429
430   return i;
431 }
432
433 static void set_first_pass_params(VP9_COMP *cpi) {
434   VP9_COMMON *const cm = &cpi->common;
435   if (!cpi->refresh_alt_ref_frame &&
436       (cm->current_video_frame == 0 ||
437        (cpi->frame_flags & FRAMEFLAGS_KEY))) {
438     cm->frame_type = KEY_FRAME;
439   } else {
440     cm->frame_type = INTER_FRAME;
441   }
442   // Do not use periodic key frames.
443   cpi->rc.frames_to_key = INT_MAX;
444 }
445
446 void vp9_first_pass(VP9_COMP *cpi) {
447   int mb_row, mb_col;
448   MACROBLOCK *const x = &cpi->mb;
449   VP9_COMMON *const cm = &cpi->common;
450   MACROBLOCKD *const xd = &x->e_mbd;
451   TileInfo tile;
452   struct macroblock_plane *const p = x->plane;
453   struct macroblockd_plane *const pd = xd->plane;
454   const PICK_MODE_CONTEXT *ctx = &cpi->pc_root->none;
455   int i;
456
457   int recon_yoffset, recon_uvoffset;
458   YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
459   YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
460   YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
461   int recon_y_stride = lst_yv12->y_stride;
462   int recon_uv_stride = lst_yv12->uv_stride;
463   int uv_mb_height = 16 >> (lst_yv12->y_height > lst_yv12->uv_height);
464   int64_t intra_error = 0;
465   int64_t coded_error = 0;
466   int64_t sr_coded_error = 0;
467
468   int sum_mvr = 0, sum_mvc = 0;
469   int sum_mvr_abs = 0, sum_mvc_abs = 0;
470   int64_t sum_mvrs = 0, sum_mvcs = 0;
471   int mvcount = 0;
472   int intercount = 0;
473   int second_ref_count = 0;
474   int intrapenalty = 256;
475   int neutral_count = 0;
476   int new_mv_count = 0;
477   int sum_in_vectors = 0;
478   uint32_t lastmv_as_int = 0;
479   TWO_PASS *twopass = &cpi->twopass;
480   const MV zero_mv = {0, 0};
481   const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
482
483 #if CONFIG_FP_MB_STATS
484   FIRSTPASS_FRAME_MB_STATS *this_frame_mb_stats = &twopass->this_frame_mb_stats;
485 #endif
486
487   vp9_clear_system_state();
488
489   set_first_pass_params(cpi);
490   vp9_set_quantizer(cm, find_fp_qindex());
491
492   if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
493     MV_REFERENCE_FRAME ref_frame = LAST_FRAME;
494     const YV12_BUFFER_CONFIG *scaled_ref_buf = NULL;
495     twopass = &cpi->svc.layer_context[cpi->svc.spatial_layer_id].twopass;
496
497     vp9_scale_references(cpi);
498
499     // Use either last frame or alt frame for motion search.
500     if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
501       scaled_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
502       ref_frame = LAST_FRAME;
503     } else if (cpi->ref_frame_flags & VP9_ALT_FLAG) {
504       scaled_ref_buf = vp9_get_scaled_ref_frame(cpi, ALTREF_FRAME);
505       ref_frame = ALTREF_FRAME;
506     }
507
508     if (scaled_ref_buf != NULL) {
509       // Update the stride since we are using scaled reference buffer
510       first_ref_buf = scaled_ref_buf;
511       recon_y_stride = first_ref_buf->y_stride;
512       recon_uv_stride = first_ref_buf->uv_stride;
513       uv_mb_height = 16 >> (first_ref_buf->y_height > first_ref_buf->uv_height);
514     }
515
516     // Disable golden frame for svc first pass for now.
517     gld_yv12 = NULL;
518     set_ref_ptrs(cm, xd, ref_frame, NONE);
519
520     cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
521                                         &cpi->scaled_source);
522   }
523
524   vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
525
526   vp9_setup_src_planes(x, cpi->Source, 0, 0);
527   vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
528   vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
529
530   xd->mi = cm->mi_grid_visible;
531   xd->mi[0] = cm->mi;
532
533   vp9_frame_init_quantizer(cpi);
534
535   for (i = 0; i < MAX_MB_PLANE; ++i) {
536     p[i].coeff = ctx->coeff_pbuf[i][1];
537     p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
538     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
539     p[i].eobs = ctx->eobs_pbuf[i][1];
540   }
541   x->skip_recode = 0;
542
543   vp9_init_mv_probs(cm);
544   vp9_initialize_rd_consts(cpi);
545
546   // Tiling is ignored in the first pass.
547   vp9_tile_init(&tile, cm, 0, 0);
548
549   for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
550     int_mv best_ref_mv;
551
552     best_ref_mv.as_int = 0;
553
554     // Reset above block coeffs.
555     xd->up_available = (mb_row != 0);
556     recon_yoffset = (mb_row * recon_y_stride * 16);
557     recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height);
558
559     // Set up limit values for motion vectors to prevent them extending
560     // outside the UMV borders.
561     x->mv_row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
562     x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16)
563                     + BORDER_MV_PIXELS_B16;
564
565     for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
566       int this_error;
567       const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
568       double error_weight = 1.0;
569       const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
570
571       vp9_clear_system_state();
572
573       xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
574       xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
575       xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
576       xd->left_available = (mb_col != 0);
577       xd->mi[0]->mbmi.sb_type = bsize;
578       xd->mi[0]->mbmi.ref_frame[0] = INTRA_FRAME;
579       set_mi_row_col(xd, &tile,
580                      mb_row << 1, num_8x8_blocks_high_lookup[bsize],
581                      mb_col << 1, num_8x8_blocks_wide_lookup[bsize],
582                      cm->mi_rows, cm->mi_cols);
583
584       if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
585         const int energy = vp9_block_energy(cpi, x, bsize);
586         error_weight = vp9_vaq_inv_q_ratio(energy);
587       }
588
589       // Do intra 16x16 prediction.
590       x->skip_encode = 0;
591       xd->mi[0]->mbmi.mode = DC_PRED;
592       xd->mi[0]->mbmi.tx_size = use_dc_pred ?
593          (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
594       vp9_encode_intra_block_plane(x, bsize, 0);
595       this_error = vp9_get_mb_ss(x->plane[0].src_diff);
596
597       if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
598         vp9_clear_system_state();
599         this_error = (int)(this_error * error_weight);
600       }
601
602       // Intrapenalty below deals with situations where the intra and inter
603       // error scores are very low (e.g. a plain black frame).
604       // We do not have special cases in first pass for 0,0 and nearest etc so
605       // all inter modes carry an overhead cost estimate for the mv.
606       // When the error score is very low this causes us to pick all or lots of
607       // INTRA modes and throw lots of key frames.
608       // This penalty adds a cost matching that of a 0,0 mv to the intra case.
609       this_error += intrapenalty;
610
611       // Accumulate the intra error.
612       intra_error += (int64_t)this_error;
613
614 #if CONFIG_FP_MB_STATS
615       if (cpi->use_fp_mb_stats) {
616         this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mode =
617             DC_PRED;
618         this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].err =
619             this_error;
620         this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mv.as_int
621             = 0;
622       }
623 #endif
624
625       // Set up limit values for motion vectors to prevent them extending
626       // outside the UMV borders.
627       x->mv_col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
628       x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
629
630       // Other than for the first frame do a motion search.
631       if (cm->current_video_frame > 0) {
632         int tmp_err, motion_error, raw_motion_error;
633         int_mv mv, tmp_mv;
634         struct buf_2d unscaled_last_source_buf_2d;
635
636         xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
637         motion_error = get_prediction_error(bsize, &x->plane[0].src,
638                                             &xd->plane[0].pre[0]);
639         // Assume 0,0 motion with no mv overhead.
640         mv.as_int = tmp_mv.as_int = 0;
641
642         // Compute the motion error of the 0,0 motion using the last source
643         // frame as the reference. Skip the further motion search on
644         // reconstructed frame if this error is small.
645         unscaled_last_source_buf_2d.buf =
646             cpi->unscaled_last_source->y_buffer + recon_yoffset;
647         unscaled_last_source_buf_2d.stride =
648             cpi->unscaled_last_source->y_stride;
649         raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
650                                                 &unscaled_last_source_buf_2d);
651
652         // TODO(pengchong): Replace the hard-coded threshold
653         if (raw_motion_error > 25 ||
654             (cpi->use_svc && cpi->svc.number_temporal_layers == 1)) {
655           // Test last reference frame using the previous best mv as the
656           // starting point (best reference) for the search.
657           first_pass_motion_search(cpi, x, &best_ref_mv.as_mv, &mv.as_mv,
658                                    &motion_error);
659           if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
660             vp9_clear_system_state();
661             motion_error = (int)(motion_error * error_weight);
662           }
663
664           // If the current best reference mv is not centered on 0,0 then do a
665           // 0,0 based search as well.
666           if (best_ref_mv.as_int) {
667             tmp_err = INT_MAX;
668             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv.as_mv, &tmp_err);
669             if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
670               vp9_clear_system_state();
671               tmp_err = (int)(tmp_err * error_weight);
672             }
673
674             if (tmp_err < motion_error) {
675               motion_error = tmp_err;
676               mv.as_int = tmp_mv.as_int;
677             }
678           }
679
680           // Search in an older reference frame.
681           if (cm->current_video_frame > 1 && gld_yv12 != NULL) {
682             // Assume 0,0 motion with no mv overhead.
683             int gf_motion_error;
684
685             xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
686             gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
687                                                    &xd->plane[0].pre[0]);
688
689             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv.as_mv,
690                                      &gf_motion_error);
691             if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
692               vp9_clear_system_state();
693               gf_motion_error = (int)(gf_motion_error * error_weight);
694             }
695
696             if (gf_motion_error < motion_error && gf_motion_error < this_error)
697               ++second_ref_count;
698
699             // Reset to last frame as reference buffer.
700             xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
701             xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
702             xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
703
704             // In accumulating a score for the older reference frame take the
705             // best of the motion predicted score and the intra coded error
706             // (just as will be done for) accumulation of "coded_error" for
707             // the last frame.
708             if (gf_motion_error < this_error)
709               sr_coded_error += gf_motion_error;
710             else
711               sr_coded_error += this_error;
712           } else {
713             sr_coded_error += motion_error;
714           }
715         } else {
716           sr_coded_error += motion_error;
717         }
718
719         // Start by assuming that intra mode is best.
720         best_ref_mv.as_int = 0;
721
722         if (motion_error <= this_error) {
723           // Keep a count of cases where the inter and intra were very close
724           // and very low. This helps with scene cut detection for example in
725           // cropped clips with black bars at the sides or top and bottom.
726           if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
727               this_error < 2 * intrapenalty)
728             ++neutral_count;
729
730           mv.as_mv.row *= 8;
731           mv.as_mv.col *= 8;
732           this_error = motion_error;
733           xd->mi[0]->mbmi.mode = NEWMV;
734           xd->mi[0]->mbmi.mv[0] = mv;
735           xd->mi[0]->mbmi.tx_size = TX_4X4;
736           xd->mi[0]->mbmi.ref_frame[0] = LAST_FRAME;
737           xd->mi[0]->mbmi.ref_frame[1] = NONE;
738           vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
739           vp9_encode_sby_pass1(x, bsize);
740           sum_mvr += mv.as_mv.row;
741           sum_mvr_abs += abs(mv.as_mv.row);
742           sum_mvc += mv.as_mv.col;
743           sum_mvc_abs += abs(mv.as_mv.col);
744           sum_mvrs += mv.as_mv.row * mv.as_mv.row;
745           sum_mvcs += mv.as_mv.col * mv.as_mv.col;
746           ++intercount;
747
748           best_ref_mv.as_int = mv.as_int;
749
750 #if CONFIG_FP_MB_STATS
751           if (cpi->use_fp_mb_stats) {
752             this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mode =
753                 NEWMV;
754             this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].err =
755                 motion_error;
756             this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mv.
757                 as_int = mv.as_int;
758           }
759 #endif
760
761           if (mv.as_int) {
762             ++mvcount;
763
764             // Non-zero vector, was it different from the last non zero vector?
765             if (mv.as_int != lastmv_as_int)
766               ++new_mv_count;
767             lastmv_as_int = mv.as_int;
768
769             // Does the row vector point inwards or outwards?
770             if (mb_row < cm->mb_rows / 2) {
771               if (mv.as_mv.row > 0)
772                 --sum_in_vectors;
773               else if (mv.as_mv.row < 0)
774                 ++sum_in_vectors;
775             } else if (mb_row > cm->mb_rows / 2) {
776               if (mv.as_mv.row > 0)
777                 ++sum_in_vectors;
778               else if (mv.as_mv.row < 0)
779                 --sum_in_vectors;
780             }
781
782             // Does the col vector point inwards or outwards?
783             if (mb_col < cm->mb_cols / 2) {
784               if (mv.as_mv.col > 0)
785                 --sum_in_vectors;
786               else if (mv.as_mv.col < 0)
787                 ++sum_in_vectors;
788             } else if (mb_col > cm->mb_cols / 2) {
789               if (mv.as_mv.col > 0)
790                 ++sum_in_vectors;
791               else if (mv.as_mv.col < 0)
792                 --sum_in_vectors;
793             }
794           }
795         }
796       } else {
797         sr_coded_error += (int64_t)this_error;
798       }
799       coded_error += (int64_t)this_error;
800
801       // Adjust to the next column of MBs.
802       x->plane[0].src.buf += 16;
803       x->plane[1].src.buf += uv_mb_height;
804       x->plane[2].src.buf += uv_mb_height;
805
806       recon_yoffset += 16;
807       recon_uvoffset += uv_mb_height;
808     }
809
810     // Adjust to the next row of MBs.
811     x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
812     x->plane[1].src.buf += uv_mb_height * x->plane[1].src.stride -
813                            uv_mb_height * cm->mb_cols;
814     x->plane[2].src.buf += uv_mb_height * x->plane[1].src.stride -
815                            uv_mb_height * cm->mb_cols;
816
817     vp9_clear_system_state();
818   }
819
820   vp9_clear_system_state();
821   {
822     FIRSTPASS_STATS fps;
823
824     fps.frame = cm->current_video_frame;
825     fps.spatial_layer_id = cpi->svc.spatial_layer_id;
826     fps.intra_error = (double)(intra_error >> 8);
827     fps.coded_error = (double)(coded_error >> 8);
828     fps.sr_coded_error = (double)(sr_coded_error >> 8);
829     fps.count = 1.0;
830     fps.pcnt_inter = (double)intercount / cm->MBs;
831     fps.pcnt_second_ref = (double)second_ref_count / cm->MBs;
832     fps.pcnt_neutral = (double)neutral_count / cm->MBs;
833
834     if (mvcount > 0) {
835       fps.MVr = (double)sum_mvr / mvcount;
836       fps.mvr_abs = (double)sum_mvr_abs / mvcount;
837       fps.MVc = (double)sum_mvc / mvcount;
838       fps.mvc_abs = (double)sum_mvc_abs / mvcount;
839       fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / mvcount)) / mvcount;
840       fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / mvcount)) / mvcount;
841       fps.mv_in_out_count = (double)sum_in_vectors / (mvcount * 2);
842       fps.new_mv_count = new_mv_count;
843       fps.pcnt_motion = (double)mvcount / cm->MBs;
844     } else {
845       fps.MVr = 0.0;
846       fps.mvr_abs = 0.0;
847       fps.MVc = 0.0;
848       fps.mvc_abs = 0.0;
849       fps.MVrv = 0.0;
850       fps.MVcv = 0.0;
851       fps.mv_in_out_count = 0.0;
852       fps.new_mv_count = 0.0;
853       fps.pcnt_motion = 0.0;
854     }
855
856     // TODO(paulwilkins):  Handle the case when duration is set to 0, or
857     // something less than the full time between subsequent values of
858     // cpi->source_time_stamp.
859     fps.duration = (double)(cpi->source->ts_end - cpi->source->ts_start);
860
861     // Don't want to do output stats with a stack variable!
862     twopass->this_frame_stats = fps;
863     output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
864     accumulate_stats(&twopass->total_stats, &fps);
865
866 #if CONFIG_FP_MB_STATS
867     if (cpi->use_fp_mb_stats) {
868       output_mb_stats(this_frame_mb_stats, cm);
869     }
870 #endif
871   }
872
873   // Copy the previous Last Frame back into gf and and arf buffers if
874   // the prediction is good enough... but also don't allow it to lag too far.
875   if ((twopass->sr_update_lag > 3) ||
876       ((cm->current_video_frame > 0) &&
877        (twopass->this_frame_stats.pcnt_inter > 0.20) &&
878        ((twopass->this_frame_stats.intra_error /
879          DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
880     if (gld_yv12 != NULL) {
881       vp8_yv12_copy_frame(lst_yv12, gld_yv12);
882     }
883     twopass->sr_update_lag = 1;
884   } else {
885     ++twopass->sr_update_lag;
886   }
887
888   vp9_extend_frame_borders(new_yv12);
889
890   if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
891     vp9_update_reference_frames(cpi);
892   } else {
893     // Swap frame pointers so last frame refers to the frame we just compressed.
894     swap_yv12(lst_yv12, new_yv12);
895   }
896
897   // Special case for the first frame. Copy into the GF buffer as a second
898   // reference.
899   if (cm->current_video_frame == 0 && gld_yv12 != NULL) {
900     vp8_yv12_copy_frame(lst_yv12, gld_yv12);
901   }
902
903   // Use this to see what the first pass reconstruction looks like.
904   if (0) {
905     char filename[512];
906     FILE *recon_file;
907     snprintf(filename, sizeof(filename), "enc%04d.yuv",
908              (int)cm->current_video_frame);
909
910     if (cm->current_video_frame == 0)
911       recon_file = fopen(filename, "wb");
912     else
913       recon_file = fopen(filename, "ab");
914
915     (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
916     fclose(recon_file);
917   }
918
919   ++cm->current_video_frame;
920 }
921
922 static double calc_correction_factor(double err_per_mb,
923                                      double err_divisor,
924                                      double pt_low,
925                                      double pt_high,
926                                      int q) {
927   const double error_term = err_per_mb / err_divisor;
928
929   // Adjustment based on actual quantizer to power term.
930   const double power_term = MIN(vp9_convert_qindex_to_q(q) * 0.0125 + pt_low,
931                                 pt_high);
932
933   // Calculate correction factor.
934   if (power_term < 1.0)
935     assert(error_term >= 0.0);
936
937   return fclamp(pow(error_term, power_term), 0.05, 5.0);
938 }
939
940 static int get_twopass_worst_quality(const VP9_COMP *cpi,
941                                      const FIRSTPASS_STATS *stats,
942                                      int section_target_bandwidth) {
943   const RATE_CONTROL *const rc = &cpi->rc;
944   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
945
946   if (section_target_bandwidth <= 0) {
947     return rc->worst_quality;  // Highest value allowed
948   } else {
949     const int num_mbs = cpi->common.MBs;
950     const double section_err = stats->coded_error / stats->count;
951     const double err_per_mb = section_err / num_mbs;
952     const double speed_term = 1.0 + 0.04 * oxcf->speed;
953     const int target_norm_bits_per_mb = ((uint64_t)section_target_bandwidth <<
954                                             BPER_MB_NORMBITS) / num_mbs;
955     int q;
956     int is_svc_upper_layer = 0;
957     if (cpi->use_svc && cpi->svc.number_temporal_layers == 1 &&
958         cpi->svc.spatial_layer_id > 0) {
959       is_svc_upper_layer = 1;
960     }
961
962     // Try and pick a max Q that will be high enough to encode the
963     // content at the given rate.
964     for (q = rc->best_quality; q < rc->worst_quality; ++q) {
965       const double factor =
966           calc_correction_factor(err_per_mb, ERR_DIVISOR,
967                                  is_svc_upper_layer ? SVC_FACTOR_PT_LOW :
968                                  FACTOR_PT_LOW, FACTOR_PT_HIGH, q);
969       const int bits_per_mb = vp9_rc_bits_per_mb(INTER_FRAME, q,
970                                                  factor * speed_term);
971       if (bits_per_mb <= target_norm_bits_per_mb)
972         break;
973     }
974
975     // Restriction on active max q for constrained quality mode.
976     if (cpi->oxcf.rc_mode == VPX_CQ)
977       q = MAX(q, oxcf->cq_level);
978     return q;
979   }
980 }
981
982 extern void vp9_new_framerate(VP9_COMP *cpi, double framerate);
983
984 void vp9_init_second_pass(VP9_COMP *cpi) {
985   SVC *const svc = &cpi->svc;
986   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
987   const int is_spatial_svc = (svc->number_spatial_layers > 1) &&
988                              (svc->number_temporal_layers == 1);
989   TWO_PASS *const twopass = is_spatial_svc ?
990       &svc->layer_context[svc->spatial_layer_id].twopass : &cpi->twopass;
991   double frame_rate;
992   FIRSTPASS_STATS *stats;
993
994   zero_stats(&twopass->total_stats);
995   zero_stats(&twopass->total_left_stats);
996
997   if (!twopass->stats_in_end)
998     return;
999
1000   stats = &twopass->total_stats;
1001
1002   *stats = *twopass->stats_in_end;
1003   twopass->total_left_stats = *stats;
1004
1005   frame_rate = 10000000.0 * stats->count / stats->duration;
1006   // Each frame can have a different duration, as the frame rate in the source
1007   // isn't guaranteed to be constant. The frame rate prior to the first frame
1008   // encoded in the second pass is a guess. However, the sum duration is not.
1009   // It is calculated based on the actual durations of all frames from the
1010   // first pass.
1011
1012   if (is_spatial_svc) {
1013     vp9_update_spatial_layer_framerate(cpi, frame_rate);
1014     twopass->bits_left = (int64_t)(stats->duration *
1015         svc->layer_context[svc->spatial_layer_id].target_bandwidth /
1016         10000000.0);
1017   } else {
1018     vp9_new_framerate(cpi, frame_rate);
1019     twopass->bits_left = (int64_t)(stats->duration * oxcf->target_bandwidth /
1020                              10000000.0);
1021   }
1022
1023   // Calculate a minimum intra value to be used in determining the IIratio
1024   // scores used in the second pass. We have this minimum to make sure
1025   // that clips that are static but "low complexity" in the intra domain
1026   // are still boosted appropriately for KF/GF/ARF.
1027   if (!is_spatial_svc) {
1028     // We don't know the number of MBs for each layer at this point.
1029     // So we will do it later.
1030     twopass->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
1031     twopass->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
1032   }
1033
1034   // This variable monitors how far behind the second ref update is lagging.
1035   twopass->sr_update_lag = 1;
1036
1037   // Scan the first pass file and calculate a modified total error based upon
1038   // the bias/power function used to allocate bits.
1039   {
1040     const double avg_error = stats->coded_error /
1041                              DOUBLE_DIVIDE_CHECK(stats->count);
1042     const FIRSTPASS_STATS *s = twopass->stats_in;
1043     double modified_error_total = 0.0;
1044     twopass->modified_error_min = (avg_error *
1045                                       oxcf->two_pass_vbrmin_section) / 100;
1046     twopass->modified_error_max = (avg_error *
1047                                       oxcf->two_pass_vbrmax_section) / 100;
1048     while (s < twopass->stats_in_end) {
1049       modified_error_total += calculate_modified_err(twopass, oxcf, s);
1050       ++s;
1051     }
1052     twopass->modified_error_left = modified_error_total;
1053   }
1054
1055   // Reset the vbr bits off target counter
1056   cpi->rc.vbr_bits_off_target = 0;
1057 }
1058
1059 // This function gives an estimate of how badly we believe the prediction
1060 // quality is decaying from frame to frame.
1061 static double get_prediction_decay_rate(const VP9_COMMON *cm,
1062                                         const FIRSTPASS_STATS *next_frame) {
1063   // Look at the observed drop in prediction quality between the last frame
1064   // and the GF buffer (which contains an older frame).
1065   const double mb_sr_err_diff = (next_frame->sr_coded_error -
1066                                      next_frame->coded_error) / cm->MBs;
1067   const double second_ref_decay = mb_sr_err_diff <= 512.0
1068       ? fclamp(pow(1.0 - (mb_sr_err_diff / 512.0), 0.5), 0.85, 1.0)
1069       : 0.85;
1070
1071   return MIN(second_ref_decay, next_frame->pcnt_inter);
1072 }
1073
1074 // Function to test for a condition where a complex transition is followed
1075 // by a static section. For example in slide shows where there is a fade
1076 // between slides. This is to help with more optimal kf and gf positioning.
1077 static int detect_transition_to_still(TWO_PASS *twopass,
1078                                       int frame_interval, int still_interval,
1079                                       double loop_decay_rate,
1080                                       double last_decay_rate) {
1081   int trans_to_still = 0;
1082
1083   // Break clause to detect very still sections after motion
1084   // For example a static image after a fade or other transition
1085   // instead of a clean scene cut.
1086   if (frame_interval > MIN_GF_INTERVAL &&
1087       loop_decay_rate >= 0.999 &&
1088       last_decay_rate < 0.9) {
1089     int j;
1090     const FIRSTPASS_STATS *position = twopass->stats_in;
1091     FIRSTPASS_STATS tmp_next_frame;
1092
1093     // Look ahead a few frames to see if static condition persists...
1094     for (j = 0; j < still_interval; ++j) {
1095       if (EOF == input_stats(twopass, &tmp_next_frame))
1096         break;
1097
1098       if (tmp_next_frame.pcnt_inter - tmp_next_frame.pcnt_motion < 0.999)
1099         break;
1100     }
1101
1102     reset_fpf_position(twopass, position);
1103
1104     // Only if it does do we signal a transition to still.
1105     if (j == still_interval)
1106       trans_to_still = 1;
1107   }
1108
1109   return trans_to_still;
1110 }
1111
1112 // This function detects a flash through the high relative pcnt_second_ref
1113 // score in the frame following a flash frame. The offset passed in should
1114 // reflect this.
1115 static int detect_flash(const TWO_PASS *twopass, int offset) {
1116   FIRSTPASS_STATS next_frame;
1117
1118   int flash_detected = 0;
1119
1120   // Read the frame data.
1121   // The return is FALSE (no flash detected) if not a valid frame
1122   if (read_frame_stats(twopass, &next_frame, offset) != EOF) {
1123     // What we are looking for here is a situation where there is a
1124     // brief break in prediction (such as a flash) but subsequent frames
1125     // are reasonably well predicted by an earlier (pre flash) frame.
1126     // The recovery after a flash is indicated by a high pcnt_second_ref
1127     // compared to pcnt_inter.
1128     if (next_frame.pcnt_second_ref > next_frame.pcnt_inter &&
1129         next_frame.pcnt_second_ref >= 0.5)
1130       flash_detected = 1;
1131   }
1132
1133   return flash_detected;
1134 }
1135
1136 // Update the motion related elements to the GF arf boost calculation.
1137 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1138                                           double *mv_in_out,
1139                                           double *mv_in_out_accumulator,
1140                                           double *abs_mv_in_out_accumulator,
1141                                           double *mv_ratio_accumulator) {
1142   const double pct = stats->pcnt_motion;
1143
1144   // Accumulate Motion In/Out of frame stats.
1145   *mv_in_out = stats->mv_in_out_count * pct;
1146   *mv_in_out_accumulator += *mv_in_out;
1147   *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1148
1149   // Accumulate a measure of how uniform (or conversely how random) the motion
1150   // field is (a ratio of abs(mv) / mv).
1151   if (pct > 0.05) {
1152     const double mvr_ratio = fabs(stats->mvr_abs) /
1153                                  DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1154     const double mvc_ratio = fabs(stats->mvc_abs) /
1155                                  DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1156
1157     *mv_ratio_accumulator += pct * (mvr_ratio < stats->mvr_abs ?
1158                                        mvr_ratio : stats->mvr_abs);
1159     *mv_ratio_accumulator += pct * (mvc_ratio < stats->mvc_abs ?
1160                                        mvc_ratio : stats->mvc_abs);
1161   }
1162 }
1163
1164 // Calculate a baseline boost number for the current frame.
1165 static double calc_frame_boost(const TWO_PASS *twopass,
1166                                const FIRSTPASS_STATS *this_frame,
1167                                double this_frame_mv_in_out) {
1168   double frame_boost;
1169
1170   // Underlying boost factor is based on inter intra error ratio.
1171   if (this_frame->intra_error > twopass->gf_intra_err_min)
1172     frame_boost = (IIFACTOR * this_frame->intra_error /
1173                    DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1174   else
1175     frame_boost = (IIFACTOR * twopass->gf_intra_err_min /
1176                    DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1177
1178   // Increase boost for frames where new data coming into frame (e.g. zoom out).
1179   // Slightly reduce boost if there is a net balance of motion out of the frame
1180   // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
1181   if (this_frame_mv_in_out > 0.0)
1182     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1183   // In the extreme case the boost is halved.
1184   else
1185     frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1186
1187   return MIN(frame_boost, GF_RMAX);
1188 }
1189
1190 static int calc_arf_boost(VP9_COMP *cpi, int offset,
1191                           int f_frames, int b_frames,
1192                           int *f_boost, int *b_boost) {
1193   FIRSTPASS_STATS this_frame;
1194   TWO_PASS *const twopass = &cpi->twopass;
1195   int i;
1196   double boost_score = 0.0;
1197   double mv_ratio_accumulator = 0.0;
1198   double decay_accumulator = 1.0;
1199   double this_frame_mv_in_out = 0.0;
1200   double mv_in_out_accumulator = 0.0;
1201   double abs_mv_in_out_accumulator = 0.0;
1202   int arf_boost;
1203   int flash_detected = 0;
1204
1205   // Search forward from the proposed arf/next gf position.
1206   for (i = 0; i < f_frames; ++i) {
1207     if (read_frame_stats(twopass, &this_frame, (i + offset)) == EOF)
1208       break;
1209
1210     // Update the motion related elements to the boost calculation.
1211     accumulate_frame_motion_stats(&this_frame,
1212                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1213                                   &abs_mv_in_out_accumulator,
1214                                   &mv_ratio_accumulator);
1215
1216     // We want to discount the flash frame itself and the recovery
1217     // frame that follows as both will have poor scores.
1218     flash_detected = detect_flash(twopass, i + offset) ||
1219                      detect_flash(twopass, i + offset + 1);
1220
1221     // Accumulate the effect of prediction quality decay.
1222     if (!flash_detected) {
1223       decay_accumulator *= get_prediction_decay_rate(&cpi->common, &this_frame);
1224       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1225                           ? MIN_DECAY_FACTOR : decay_accumulator;
1226     }
1227
1228     boost_score += decay_accumulator * calc_frame_boost(twopass, &this_frame,
1229                                                         this_frame_mv_in_out);
1230   }
1231
1232   *f_boost = (int)boost_score;
1233
1234   // Reset for backward looking loop.
1235   boost_score = 0.0;
1236   mv_ratio_accumulator = 0.0;
1237   decay_accumulator = 1.0;
1238   this_frame_mv_in_out = 0.0;
1239   mv_in_out_accumulator = 0.0;
1240   abs_mv_in_out_accumulator = 0.0;
1241
1242   // Search backward towards last gf position.
1243   for (i = -1; i >= -b_frames; --i) {
1244     if (read_frame_stats(twopass, &this_frame, (i + offset)) == EOF)
1245       break;
1246
1247     // Update the motion related elements to the boost calculation.
1248     accumulate_frame_motion_stats(&this_frame,
1249                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1250                                   &abs_mv_in_out_accumulator,
1251                                   &mv_ratio_accumulator);
1252
1253     // We want to discount the the flash frame itself and the recovery
1254     // frame that follows as both will have poor scores.
1255     flash_detected = detect_flash(twopass, i + offset) ||
1256                      detect_flash(twopass, i + offset + 1);
1257
1258     // Cumulative effect of prediction quality decay.
1259     if (!flash_detected) {
1260       decay_accumulator *= get_prediction_decay_rate(&cpi->common, &this_frame);
1261       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1262                               ? MIN_DECAY_FACTOR : decay_accumulator;
1263     }
1264
1265     boost_score += decay_accumulator * calc_frame_boost(twopass, &this_frame,
1266                                                         this_frame_mv_in_out);
1267   }
1268   *b_boost = (int)boost_score;
1269
1270   arf_boost = (*f_boost + *b_boost);
1271   if (arf_boost < ((b_frames + f_frames) * 20))
1272     arf_boost = ((b_frames + f_frames) * 20);
1273
1274   return arf_boost;
1275 }
1276
1277 // Calculate a section intra ratio used in setting max loop filter.
1278 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
1279                                          const FIRSTPASS_STATS *end,
1280                                          int section_length) {
1281   const FIRSTPASS_STATS *s = begin;
1282   double intra_error = 0.0;
1283   double coded_error = 0.0;
1284   int i = 0;
1285
1286   while (s < end && i < section_length) {
1287     intra_error += s->intra_error;
1288     coded_error += s->coded_error;
1289     ++s;
1290     ++i;
1291   }
1292
1293   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
1294 }
1295
1296 // Calculate the total bits to allocate in this GF/ARF group.
1297 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
1298                                              double gf_group_err) {
1299   const RATE_CONTROL *const rc = &cpi->rc;
1300   const TWO_PASS *const twopass = &cpi->twopass;
1301   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1302   int64_t total_group_bits;
1303
1304   // Calculate the bits to be allocated to the group as a whole.
1305   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
1306     total_group_bits = (int64_t)(twopass->kf_group_bits *
1307                                  (gf_group_err / twopass->kf_group_error_left));
1308   } else {
1309     total_group_bits = 0;
1310   }
1311
1312   // Clamp odd edge cases.
1313   total_group_bits = (total_group_bits < 0) ?
1314      0 : (total_group_bits > twopass->kf_group_bits) ?
1315      twopass->kf_group_bits : total_group_bits;
1316
1317   // Clip based on user supplied data rate variability limit.
1318   if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
1319     total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
1320
1321   return total_group_bits;
1322 }
1323
1324 // Calculate the number bits extra to assign to boosted frames in a group.
1325 static int calculate_boost_bits(int frame_count,
1326                                 int boost, int64_t total_group_bits) {
1327   int allocation_chunks;
1328
1329   // return 0 for invalid inputs (could arise e.g. through rounding errors)
1330   if (!boost || (total_group_bits <= 0) || (frame_count <= 0) )
1331     return 0;
1332
1333   allocation_chunks = (frame_count * 100) + boost;
1334
1335   // Prevent overflow.
1336   if (boost > 1023) {
1337     int divisor = boost >> 10;
1338     boost /= divisor;
1339     allocation_chunks /= divisor;
1340   }
1341
1342   // Calculate the number of extra bits for use in the boosted frame or frames.
1343   return MAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks), 0);
1344 }
1345
1346 // Current limit on maximum number of active arfs in a GF/ARF group.
1347 #define MAX_ACTIVE_ARFS 2
1348 #define ARF_SLOT1 2
1349 #define ARF_SLOT2 3
1350 // This function indirects the choice of buffers for arfs.
1351 // At the moment the values are fixed but this may change as part of
1352 // the integration process with other codec features that swap buffers around.
1353 static void get_arf_buffer_indices(unsigned char *arf_buffer_indices) {
1354   arf_buffer_indices[0] = ARF_SLOT1;
1355   arf_buffer_indices[1] = ARF_SLOT2;
1356 }
1357
1358 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
1359                                    double group_error, int gf_arf_bits) {
1360   RATE_CONTROL *const rc = &cpi->rc;
1361   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1362   TWO_PASS *twopass = &cpi->twopass;
1363   FIRSTPASS_STATS frame_stats;
1364   int i;
1365   int frame_index = 1;
1366   int target_frame_size;
1367   int key_frame;
1368   const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
1369   int64_t total_group_bits = gf_group_bits;
1370   double modified_err = 0.0;
1371   double err_fraction;
1372   int mid_boost_bits = 0;
1373   int mid_frame_idx;
1374   unsigned char arf_buffer_indices[MAX_ACTIVE_ARFS];
1375
1376   key_frame = cpi->common.frame_type == KEY_FRAME ||
1377               vp9_is_upper_layer_key_frame(cpi);
1378
1379   get_arf_buffer_indices(arf_buffer_indices);
1380
1381   // For key frames the frame target rate is already set and it
1382   // is also the golden frame.
1383   if (!key_frame) {
1384     if (rc->source_alt_ref_active) {
1385       twopass->gf_group.update_type[0] = OVERLAY_UPDATE;
1386       twopass->gf_group.rf_level[0] = INTER_NORMAL;
1387       twopass->gf_group.bit_allocation[0] = 0;
1388       twopass->gf_group.arf_update_idx[0] = arf_buffer_indices[0];
1389       twopass->gf_group.arf_ref_idx[0] = arf_buffer_indices[0];
1390     } else {
1391       twopass->gf_group.update_type[0] = GF_UPDATE;
1392       twopass->gf_group.rf_level[0] = GF_ARF_STD;
1393       twopass->gf_group.bit_allocation[0] = gf_arf_bits;
1394       twopass->gf_group.arf_update_idx[0] = arf_buffer_indices[0];
1395       twopass->gf_group.arf_ref_idx[0] = arf_buffer_indices[0];
1396     }
1397
1398     // Step over the golden frame / overlay frame
1399     if (EOF == input_stats(twopass, &frame_stats))
1400       return;
1401   }
1402
1403   // Deduct the boost bits for arf (or gf if it is not a key frame)
1404   // from the group total.
1405   if (rc->source_alt_ref_pending || !key_frame)
1406     total_group_bits -= gf_arf_bits;
1407
1408   // Store the bits to spend on the ARF if there is one.
1409   if (rc->source_alt_ref_pending) {
1410     if (cpi->multi_arf_enabled) {
1411       // A portion of the gf / arf extra bits are set asside for lower level
1412       // boosted frames in the middle of the group.
1413       mid_boost_bits += gf_arf_bits >> 5;
1414       gf_arf_bits -= (gf_arf_bits >> 5);
1415     }
1416
1417     twopass->gf_group.update_type[frame_index] = ARF_UPDATE;
1418     twopass->gf_group.rf_level[frame_index] = GF_ARF_STD;
1419     twopass->gf_group.bit_allocation[frame_index] = gf_arf_bits;
1420     twopass->gf_group.arf_src_offset[frame_index] =
1421       (unsigned char)(rc->baseline_gf_interval - 1);
1422     twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[0];
1423     twopass->gf_group.arf_ref_idx[frame_index] =
1424       arf_buffer_indices[cpi->multi_arf_enabled && rc->source_alt_ref_active];
1425     ++frame_index;
1426
1427     if (cpi->multi_arf_enabled) {
1428       // Set aside a slot for a level 1 arf.
1429       twopass->gf_group.update_type[frame_index] = ARF_UPDATE;
1430       twopass->gf_group.rf_level[frame_index] = GF_ARF_LOW;
1431       twopass->gf_group.arf_src_offset[frame_index] =
1432         (unsigned char)((rc->baseline_gf_interval >> 1) - 1);
1433       twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[1];
1434       twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[0];
1435       ++frame_index;
1436     }
1437   }
1438
1439   // Define middle frame
1440   mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
1441
1442   // Allocate bits to the other frames in the group.
1443   for (i = 0; i < rc->baseline_gf_interval - 1; ++i) {
1444     int arf_idx = 0;
1445     if (EOF == input_stats(twopass, &frame_stats))
1446       break;
1447
1448     modified_err = calculate_modified_err(twopass, oxcf, &frame_stats);
1449
1450     if (group_error > 0)
1451       err_fraction = modified_err / DOUBLE_DIVIDE_CHECK(group_error);
1452     else
1453       err_fraction = 0.0;
1454
1455     target_frame_size = (int)((double)total_group_bits * err_fraction);
1456
1457     if (rc->source_alt_ref_pending && cpi->multi_arf_enabled) {
1458       mid_boost_bits += (target_frame_size >> 4);
1459       target_frame_size -= (target_frame_size >> 4);
1460
1461       if (frame_index <= mid_frame_idx)
1462         arf_idx = 1;
1463     }
1464     twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[arf_idx];
1465     twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[arf_idx];
1466
1467     target_frame_size = clamp(target_frame_size, 0,
1468                               MIN(max_bits, (int)total_group_bits));
1469
1470     twopass->gf_group.update_type[frame_index] = LF_UPDATE;
1471     twopass->gf_group.rf_level[frame_index] = INTER_NORMAL;
1472
1473     twopass->gf_group.bit_allocation[frame_index] = target_frame_size;
1474     ++frame_index;
1475   }
1476
1477   // Note:
1478   // We need to configure the frame at the end of the sequence + 1 that will be
1479   // the start frame for the next group. Otherwise prior to the call to
1480   // vp9_rc_get_second_pass_params() the data will be undefined.
1481   twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[0];
1482   twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[0];
1483
1484   if (rc->source_alt_ref_pending) {
1485     twopass->gf_group.update_type[frame_index] = OVERLAY_UPDATE;
1486     twopass->gf_group.rf_level[frame_index] = INTER_NORMAL;
1487
1488     // Final setup for second arf and its overlay.
1489     if (cpi->multi_arf_enabled) {
1490       twopass->gf_group.bit_allocation[2] =
1491         twopass->gf_group.bit_allocation[mid_frame_idx] + mid_boost_bits;
1492       twopass->gf_group.update_type[mid_frame_idx] = OVERLAY_UPDATE;
1493       twopass->gf_group.bit_allocation[mid_frame_idx] = 0;
1494     }
1495   } else {
1496     twopass->gf_group.update_type[frame_index] = GF_UPDATE;
1497     twopass->gf_group.rf_level[frame_index] = GF_ARF_STD;
1498   }
1499 }
1500
1501 // Analyse and define a gf/arf group.
1502 static void define_gf_group(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1503   RATE_CONTROL *const rc = &cpi->rc;
1504   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1505   TWO_PASS *const twopass = &cpi->twopass;
1506   FIRSTPASS_STATS next_frame;
1507   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
1508   int i;
1509
1510   double boost_score = 0.0;
1511   double old_boost_score = 0.0;
1512   double gf_group_err = 0.0;
1513   double gf_first_frame_err = 0.0;
1514   double mod_frame_err = 0.0;
1515
1516   double mv_ratio_accumulator = 0.0;
1517   double decay_accumulator = 1.0;
1518   double zero_motion_accumulator = 1.0;
1519
1520   double loop_decay_rate = 1.00;
1521   double last_loop_decay_rate = 1.00;
1522
1523   double this_frame_mv_in_out = 0.0;
1524   double mv_in_out_accumulator = 0.0;
1525   double abs_mv_in_out_accumulator = 0.0;
1526   double mv_ratio_accumulator_thresh;
1527   unsigned int allow_alt_ref = is_altref_enabled(oxcf);
1528
1529   int f_boost = 0;
1530   int b_boost = 0;
1531   int flash_detected;
1532   int active_max_gf_interval;
1533   int64_t gf_group_bits;
1534   double gf_group_error_left;
1535   int gf_arf_bits;
1536
1537   // Reset the GF group data structures unless this is a key
1538   // frame in which case it will already have been done.
1539   if (cpi->common.frame_type != KEY_FRAME) {
1540     vp9_zero(twopass->gf_group);
1541   }
1542
1543   vp9_clear_system_state();
1544   vp9_zero(next_frame);
1545
1546   gf_group_bits = 0;
1547
1548   // Load stats for the current frame.
1549   mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1550
1551   // Note the error of the frame at the start of the group. This will be
1552   // the GF frame error if we code a normal gf.
1553   gf_first_frame_err = mod_frame_err;
1554
1555   // If this is a key frame or the overlay from a previous arf then
1556   // the error score / cost of this frame has already been accounted for.
1557   if (cpi->common.frame_type == KEY_FRAME || rc->source_alt_ref_active)
1558     gf_group_err -= gf_first_frame_err;
1559
1560   // Motion breakout threshold for loop below depends on image size.
1561   mv_ratio_accumulator_thresh = (cpi->common.width + cpi->common.height) / 10.0;
1562
1563   // Work out a maximum interval for the GF.
1564   // If the image appears completely static we can extend beyond this.
1565   // The value chosen depends on the active Q range. At low Q we have
1566   // bits to spare and are better with a smaller interval and smaller boost.
1567   // At high Q when there are few bits to spare we are better with a longer
1568   // interval to spread the cost of the GF.
1569   //
1570   active_max_gf_interval =
1571     12 + ((int)vp9_convert_qindex_to_q(rc->last_q[INTER_FRAME]) >> 5);
1572
1573   if (active_max_gf_interval > rc->max_gf_interval)
1574     active_max_gf_interval = rc->max_gf_interval;
1575
1576   i = 0;
1577   while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
1578     ++i;
1579
1580     // Accumulate error score of frames in this gf group.
1581     mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1582     gf_group_err += mod_frame_err;
1583
1584     if (EOF == input_stats(twopass, &next_frame))
1585       break;
1586
1587     // Test for the case where there is a brief flash but the prediction
1588     // quality back to an earlier frame is then restored.
1589     flash_detected = detect_flash(twopass, 0);
1590
1591     // Update the motion related elements to the boost calculation.
1592     accumulate_frame_motion_stats(&next_frame,
1593                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1594                                   &abs_mv_in_out_accumulator,
1595                                   &mv_ratio_accumulator);
1596
1597     // Accumulate the effect of prediction quality decay.
1598     if (!flash_detected) {
1599       last_loop_decay_rate = loop_decay_rate;
1600       loop_decay_rate = get_prediction_decay_rate(&cpi->common, &next_frame);
1601       decay_accumulator = decay_accumulator * loop_decay_rate;
1602
1603       // Monitor for static sections.
1604       if ((next_frame.pcnt_inter - next_frame.pcnt_motion) <
1605           zero_motion_accumulator) {
1606         zero_motion_accumulator = next_frame.pcnt_inter -
1607                                       next_frame.pcnt_motion;
1608       }
1609
1610       // Break clause to detect very still sections after motion. For example,
1611       // a static image after a fade or other transition.
1612       if (detect_transition_to_still(twopass, i, 5, loop_decay_rate,
1613                                      last_loop_decay_rate)) {
1614         allow_alt_ref = 0;
1615         break;
1616       }
1617     }
1618
1619     // Calculate a boost number for this frame.
1620     boost_score += decay_accumulator * calc_frame_boost(twopass, &next_frame,
1621                                                         this_frame_mv_in_out);
1622
1623     // Break out conditions.
1624     if (
1625       // Break at active_max_gf_interval unless almost totally static.
1626       (i >= active_max_gf_interval && (zero_motion_accumulator < 0.995)) ||
1627       (
1628         // Don't break out with a very short interval.
1629         (i > MIN_GF_INTERVAL) &&
1630         ((boost_score > 125.0) || (next_frame.pcnt_inter < 0.75)) &&
1631         (!flash_detected) &&
1632         ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
1633          (abs_mv_in_out_accumulator > 3.0) ||
1634          (mv_in_out_accumulator < -2.0) ||
1635          ((boost_score - old_boost_score) < IIFACTOR)))) {
1636       boost_score = old_boost_score;
1637       break;
1638     }
1639
1640     *this_frame = next_frame;
1641
1642     old_boost_score = boost_score;
1643   }
1644
1645   twopass->gf_zeromotion_pct = (int)(zero_motion_accumulator * 1000.0);
1646
1647   // Don't allow a gf too near the next kf.
1648   if ((rc->frames_to_key - i) < MIN_GF_INTERVAL) {
1649     while (i < (rc->frames_to_key + !rc->next_key_frame_forced)) {
1650       ++i;
1651
1652       if (EOF == input_stats(twopass, this_frame))
1653         break;
1654
1655       if (i < rc->frames_to_key) {
1656         mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1657         gf_group_err += mod_frame_err;
1658       }
1659     }
1660   }
1661
1662   // Set the interval until the next gf.
1663   if (cpi->common.frame_type == KEY_FRAME || rc->source_alt_ref_active)
1664     rc->baseline_gf_interval = i - 1;
1665   else
1666     rc->baseline_gf_interval = i;
1667
1668   rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1669
1670   // Should we use the alternate reference frame.
1671   if (allow_alt_ref &&
1672       (i < cpi->oxcf.lag_in_frames) &&
1673       (i >= MIN_GF_INTERVAL) &&
1674       // For real scene cuts (not forced kfs) don't allow arf very near kf.
1675       (rc->next_key_frame_forced ||
1676       (i <= (rc->frames_to_key - MIN_GF_INTERVAL)))) {
1677     // Calculate the boost for alt ref.
1678     rc->gfu_boost = calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost,
1679                                    &b_boost);
1680     rc->source_alt_ref_pending = 1;
1681
1682   } else {
1683     rc->gfu_boost = (int)boost_score;
1684     rc->source_alt_ref_pending = 0;
1685   }
1686
1687   // Reset the file position.
1688   reset_fpf_position(twopass, start_pos);
1689
1690   // Calculate the bits to be allocated to the gf/arf group as a whole
1691   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
1692
1693   // Calculate the extra bits to be used for boosted frame(s)
1694   {
1695     int q = rc->last_q[INTER_FRAME];
1696     int boost = (rc->gfu_boost * gfboost_qadjust(q)) / 100;
1697
1698     // Set max and minimum boost and hence minimum allocation.
1699     boost = clamp(boost, 125, (rc->baseline_gf_interval + 1) * 200);
1700
1701     // Calculate the extra bits to be used for boosted frame(s)
1702     gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval,
1703                                        boost, gf_group_bits);
1704   }
1705
1706   // Adjust KF group bits and error remaining.
1707   twopass->kf_group_error_left -= (int64_t)gf_group_err;
1708
1709   // If this is an arf update we want to remove the score for the overlay
1710   // frame at the end which will usually be very cheap to code.
1711   // The overlay frame has already, in effect, been coded so we want to spread
1712   // the remaining bits among the other frames.
1713   // For normal GFs remove the score for the GF itself unless this is
1714   // also a key frame in which case it has already been accounted for.
1715   if (rc->source_alt_ref_pending) {
1716     gf_group_error_left = gf_group_err - mod_frame_err;
1717   } else if (cpi->common.frame_type != KEY_FRAME) {
1718     gf_group_error_left = gf_group_err - gf_first_frame_err;
1719   } else {
1720     gf_group_error_left = gf_group_err;
1721   }
1722
1723   // Allocate bits to each of the frames in the GF group.
1724   allocate_gf_group_bits(cpi, gf_group_bits, gf_group_error_left, gf_arf_bits);
1725
1726   // Reset the file position.
1727   reset_fpf_position(twopass, start_pos);
1728
1729   // Calculate a section intra ratio used in setting max loop filter.
1730   if (cpi->common.frame_type != KEY_FRAME) {
1731     twopass->section_intra_rating =
1732         calculate_section_intra_ratio(start_pos, twopass->stats_in_end,
1733                                       rc->baseline_gf_interval);
1734   }
1735 }
1736
1737 static int test_candidate_kf(TWO_PASS *twopass,
1738                              const FIRSTPASS_STATS *last_frame,
1739                              const FIRSTPASS_STATS *this_frame,
1740                              const FIRSTPASS_STATS *next_frame) {
1741   int is_viable_kf = 0;
1742
1743   // Does the frame satisfy the primary criteria of a key frame?
1744   // If so, then examine how well it predicts subsequent frames.
1745   if ((this_frame->pcnt_second_ref < 0.10) &&
1746       (next_frame->pcnt_second_ref < 0.10) &&
1747       ((this_frame->pcnt_inter < 0.05) ||
1748        (((this_frame->pcnt_inter - this_frame->pcnt_neutral) < 0.35) &&
1749         ((this_frame->intra_error /
1750           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) < 2.5) &&
1751         ((fabs(last_frame->coded_error - this_frame->coded_error) /
1752               DOUBLE_DIVIDE_CHECK(this_frame->coded_error) > 0.40) ||
1753          (fabs(last_frame->intra_error - this_frame->intra_error) /
1754               DOUBLE_DIVIDE_CHECK(this_frame->intra_error) > 0.40) ||
1755          ((next_frame->intra_error /
1756            DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) > 3.5))))) {
1757     int i;
1758     const FIRSTPASS_STATS *start_pos = twopass->stats_in;
1759     FIRSTPASS_STATS local_next_frame = *next_frame;
1760     double boost_score = 0.0;
1761     double old_boost_score = 0.0;
1762     double decay_accumulator = 1.0;
1763
1764     // Examine how well the key frame predicts subsequent frames.
1765     for (i = 0; i < 16; ++i) {
1766       double next_iiratio = (IIKFACTOR1 * local_next_frame.intra_error /
1767                              DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
1768
1769       if (next_iiratio > RMAX)
1770         next_iiratio = RMAX;
1771
1772       // Cumulative effect of decay in prediction quality.
1773       if (local_next_frame.pcnt_inter > 0.85)
1774         decay_accumulator *= local_next_frame.pcnt_inter;
1775       else
1776         decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
1777
1778       // Keep a running total.
1779       boost_score += (decay_accumulator * next_iiratio);
1780
1781       // Test various breakout clauses.
1782       if ((local_next_frame.pcnt_inter < 0.05) ||
1783           (next_iiratio < 1.5) ||
1784           (((local_next_frame.pcnt_inter -
1785              local_next_frame.pcnt_neutral) < 0.20) &&
1786            (next_iiratio < 3.0)) ||
1787           ((boost_score - old_boost_score) < 3.0) ||
1788           (local_next_frame.intra_error < 200)) {
1789         break;
1790       }
1791
1792       old_boost_score = boost_score;
1793
1794       // Get the next frame details
1795       if (EOF == input_stats(twopass, &local_next_frame))
1796         break;
1797     }
1798
1799     // If there is tolerable prediction for at least the next 3 frames then
1800     // break out else discard this potential key frame and move on
1801     if (boost_score > 30.0 && (i > 3)) {
1802       is_viable_kf = 1;
1803     } else {
1804       // Reset the file position
1805       reset_fpf_position(twopass, start_pos);
1806
1807       is_viable_kf = 0;
1808     }
1809   }
1810
1811   return is_viable_kf;
1812 }
1813
1814 static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1815   int i, j;
1816   RATE_CONTROL *const rc = &cpi->rc;
1817   TWO_PASS *const twopass = &cpi->twopass;
1818   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1819   const FIRSTPASS_STATS first_frame = *this_frame;
1820   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
1821   FIRSTPASS_STATS next_frame;
1822   FIRSTPASS_STATS last_frame;
1823   int kf_bits = 0;
1824   double decay_accumulator = 1.0;
1825   double zero_motion_accumulator = 1.0;
1826   double boost_score = 0.0;
1827   double kf_mod_err = 0.0;
1828   double kf_group_err = 0.0;
1829   double recent_loop_decay[8] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
1830
1831   vp9_zero(next_frame);
1832
1833   cpi->common.frame_type = KEY_FRAME;
1834
1835   // Reset the GF group data structures.
1836   vp9_zero(twopass->gf_group);
1837
1838   // Is this a forced key frame by interval.
1839   rc->this_key_frame_forced = rc->next_key_frame_forced;
1840
1841   // Clear the alt ref active flag as this can never be active on a key frame.
1842   rc->source_alt_ref_active = 0;
1843
1844   // KF is always a GF so clear frames till next gf counter.
1845   rc->frames_till_gf_update_due = 0;
1846
1847   rc->frames_to_key = 1;
1848
1849   twopass->kf_group_bits = 0;        // Total bits available to kf group
1850   twopass->kf_group_error_left = 0;  // Group modified error score.
1851
1852   kf_mod_err = calculate_modified_err(twopass, oxcf, this_frame);
1853
1854   // Find the next keyframe.
1855   i = 0;
1856   while (twopass->stats_in < twopass->stats_in_end &&
1857          rc->frames_to_key < cpi->oxcf.key_freq) {
1858     // Accumulate kf group error.
1859     kf_group_err += calculate_modified_err(twopass, oxcf, this_frame);
1860
1861     // Load the next frame's stats.
1862     last_frame = *this_frame;
1863     input_stats(twopass, this_frame);
1864
1865     // Provided that we are not at the end of the file...
1866     if (cpi->oxcf.auto_key &&
1867         lookup_next_frame_stats(twopass, &next_frame) != EOF) {
1868       double loop_decay_rate;
1869
1870       // Check for a scene cut.
1871       if (test_candidate_kf(twopass, &last_frame, this_frame, &next_frame))
1872         break;
1873
1874       // How fast is the prediction quality decaying?
1875       loop_decay_rate = get_prediction_decay_rate(&cpi->common, &next_frame);
1876
1877       // We want to know something about the recent past... rather than
1878       // as used elsewhere where we are concerned with decay in prediction
1879       // quality since the last GF or KF.
1880       recent_loop_decay[i % 8] = loop_decay_rate;
1881       decay_accumulator = 1.0;
1882       for (j = 0; j < 8; ++j)
1883         decay_accumulator *= recent_loop_decay[j];
1884
1885       // Special check for transition or high motion followed by a
1886       // static scene.
1887       if (detect_transition_to_still(twopass, i, cpi->oxcf.key_freq - i,
1888                                      loop_decay_rate, decay_accumulator))
1889         break;
1890
1891       // Step on to the next frame.
1892       ++rc->frames_to_key;
1893
1894       // If we don't have a real key frame within the next two
1895       // key_freq intervals then break out of the loop.
1896       if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq)
1897         break;
1898     } else {
1899       ++rc->frames_to_key;
1900     }
1901     ++i;
1902   }
1903
1904   // If there is a max kf interval set by the user we must obey it.
1905   // We already breakout of the loop above at 2x max.
1906   // This code centers the extra kf if the actual natural interval
1907   // is between 1x and 2x.
1908   if (cpi->oxcf.auto_key &&
1909       rc->frames_to_key > cpi->oxcf.key_freq) {
1910     FIRSTPASS_STATS tmp_frame = first_frame;
1911
1912     rc->frames_to_key /= 2;
1913
1914     // Reset to the start of the group.
1915     reset_fpf_position(twopass, start_position);
1916
1917     kf_group_err = 0;
1918
1919     // Rescan to get the correct error data for the forced kf group.
1920     for (i = 0; i < rc->frames_to_key; ++i) {
1921       kf_group_err += calculate_modified_err(twopass, oxcf, &tmp_frame);
1922       input_stats(twopass, &tmp_frame);
1923     }
1924     rc->next_key_frame_forced = 1;
1925   } else if (twopass->stats_in == twopass->stats_in_end ||
1926              rc->frames_to_key >= cpi->oxcf.key_freq) {
1927     rc->next_key_frame_forced = 1;
1928   } else {
1929     rc->next_key_frame_forced = 0;
1930   }
1931
1932   // Special case for the last key frame of the file.
1933   if (twopass->stats_in >= twopass->stats_in_end) {
1934     // Accumulate kf group error.
1935     kf_group_err += calculate_modified_err(twopass, oxcf, this_frame);
1936   }
1937
1938   // Calculate the number of bits that should be assigned to the kf group.
1939   if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
1940     // Maximum number of bits for a single normal frame (not key frame).
1941     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1942
1943     // Maximum number of bits allocated to the key frame group.
1944     int64_t max_grp_bits;
1945
1946     // Default allocation based on bits left and relative
1947     // complexity of the section.
1948     twopass->kf_group_bits = (int64_t)(twopass->bits_left *
1949        (kf_group_err / twopass->modified_error_left));
1950
1951     // Clip based on maximum per frame rate defined by the user.
1952     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
1953     if (twopass->kf_group_bits > max_grp_bits)
1954       twopass->kf_group_bits = max_grp_bits;
1955   } else {
1956     twopass->kf_group_bits = 0;
1957   }
1958   twopass->kf_group_bits = MAX(0, twopass->kf_group_bits);
1959
1960   // Reset the first pass file position.
1961   reset_fpf_position(twopass, start_position);
1962
1963   // Scan through the kf group collating various stats used to deteermine
1964   // how many bits to spend on it.
1965   decay_accumulator = 1.0;
1966   boost_score = 0.0;
1967   for (i = 0; i < rc->frames_to_key; ++i) {
1968     if (EOF == input_stats(twopass, &next_frame))
1969       break;
1970
1971     // Monitor for static sections.
1972     if ((next_frame.pcnt_inter - next_frame.pcnt_motion) <
1973             zero_motion_accumulator) {
1974       zero_motion_accumulator = (next_frame.pcnt_inter -
1975                                      next_frame.pcnt_motion);
1976     }
1977
1978     // For the first few frames collect data to decide kf boost.
1979     if (i <= (rc->max_gf_interval * 2)) {
1980       double r;
1981       if (next_frame.intra_error > twopass->kf_intra_err_min)
1982         r = (IIKFACTOR2 * next_frame.intra_error /
1983              DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1984       else
1985         r = (IIKFACTOR2 * twopass->kf_intra_err_min /
1986              DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1987
1988       if (r > RMAX)
1989         r = RMAX;
1990
1991       // How fast is prediction quality decaying.
1992       if (!detect_flash(twopass, 0)) {
1993         const double loop_decay_rate = get_prediction_decay_rate(&cpi->common,
1994                                                                  &next_frame);
1995         decay_accumulator *= loop_decay_rate;
1996         decay_accumulator = MAX(decay_accumulator, MIN_DECAY_FACTOR);
1997       }
1998
1999       boost_score += (decay_accumulator * r);
2000     }
2001   }
2002
2003   reset_fpf_position(twopass, start_position);
2004
2005   // Store the zero motion percentage
2006   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
2007
2008   // Calculate a section intra ratio used in setting max loop filter.
2009   twopass->section_intra_rating =
2010       calculate_section_intra_ratio(start_position, twopass->stats_in_end,
2011                                     rc->frames_to_key);
2012
2013   // Work out how many bits to allocate for the key frame itself.
2014   rc->kf_boost = (int)boost_score;
2015
2016   if (rc->kf_boost  < (rc->frames_to_key * 3))
2017     rc->kf_boost  = (rc->frames_to_key * 3);
2018   if (rc->kf_boost   < MIN_KF_BOOST)
2019     rc->kf_boost = MIN_KF_BOOST;
2020
2021   kf_bits = calculate_boost_bits((rc->frames_to_key - 1),
2022                                   rc->kf_boost, twopass->kf_group_bits);
2023
2024   twopass->kf_group_bits -= kf_bits;
2025
2026   // Save the bits to spend on the key frame.
2027   twopass->gf_group.bit_allocation[0] = kf_bits;
2028   twopass->gf_group.update_type[0] = KF_UPDATE;
2029   twopass->gf_group.rf_level[0] = KF_STD;
2030
2031   // Note the total error score of the kf group minus the key frame itself.
2032   twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
2033
2034   // Adjust the count of total modified error left.
2035   // The count of bits left is adjusted elsewhere based on real coded frame
2036   // sizes.
2037   twopass->modified_error_left -= kf_group_err;
2038 }
2039
2040 // For VBR...adjustment to the frame target based on error from previous frames
2041 void vbr_rate_correction(int * this_frame_target,
2042                          const int64_t vbr_bits_off_target) {
2043   int max_delta = (*this_frame_target * 15) / 100;
2044
2045   // vbr_bits_off_target > 0 means we have extra bits to spend
2046   if (vbr_bits_off_target > 0) {
2047     *this_frame_target +=
2048       (vbr_bits_off_target > max_delta) ? max_delta
2049                                         : (int)vbr_bits_off_target;
2050   } else {
2051     *this_frame_target -=
2052       (vbr_bits_off_target < -max_delta) ? max_delta
2053                                          : (int)-vbr_bits_off_target;
2054   }
2055 }
2056
2057 // Define the reference buffers that will be updated post encode.
2058 void configure_buffer_updates(VP9_COMP *cpi) {
2059   TWO_PASS *const twopass = &cpi->twopass;
2060
2061   cpi->rc.is_src_frame_alt_ref = 0;
2062   switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
2063     case KF_UPDATE:
2064       cpi->refresh_last_frame = 1;
2065       cpi->refresh_golden_frame = 1;
2066       cpi->refresh_alt_ref_frame = 1;
2067       break;
2068     case LF_UPDATE:
2069       cpi->refresh_last_frame = 1;
2070       cpi->refresh_golden_frame = 0;
2071       cpi->refresh_alt_ref_frame = 0;
2072       break;
2073     case GF_UPDATE:
2074       cpi->refresh_last_frame = 1;
2075       cpi->refresh_golden_frame = 1;
2076       cpi->refresh_alt_ref_frame = 0;
2077       break;
2078     case OVERLAY_UPDATE:
2079       cpi->refresh_last_frame = 0;
2080       cpi->refresh_golden_frame = 1;
2081       cpi->refresh_alt_ref_frame = 0;
2082       cpi->rc.is_src_frame_alt_ref = 1;
2083       break;
2084     case ARF_UPDATE:
2085       cpi->refresh_last_frame = 0;
2086       cpi->refresh_golden_frame = 0;
2087       cpi->refresh_alt_ref_frame = 1;
2088       break;
2089     default:
2090       assert(0);
2091   }
2092 }
2093
2094
2095 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
2096   VP9_COMMON *const cm = &cpi->common;
2097   RATE_CONTROL *const rc = &cpi->rc;
2098   TWO_PASS *const twopass = &cpi->twopass;
2099   int frames_left;
2100   FIRSTPASS_STATS this_frame;
2101   FIRSTPASS_STATS this_frame_copy;
2102
2103   int target_rate;
2104   LAYER_CONTEXT *lc = NULL;
2105   const int is_spatial_svc = (cpi->use_svc &&
2106                               cpi->svc.number_temporal_layers == 1);
2107   if (is_spatial_svc) {
2108     lc = &cpi->svc.layer_context[cpi->svc.spatial_layer_id];
2109     frames_left = (int)(twopass->total_stats.count -
2110                   lc->current_video_frame_in_layer);
2111   } else {
2112     frames_left = (int)(twopass->total_stats.count -
2113                   cm->current_video_frame);
2114   }
2115
2116   if (!twopass->stats_in)
2117     return;
2118
2119   // If this is an arf frame then we dont want to read the stats file or
2120   // advance the input pointer as we already have what we need.
2121   if (twopass->gf_group.update_type[twopass->gf_group.index] == ARF_UPDATE) {
2122     int target_rate;
2123     configure_buffer_updates(cpi);
2124     target_rate = twopass->gf_group.bit_allocation[twopass->gf_group.index];
2125     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2126     rc->base_frame_target = target_rate;
2127 #ifdef LONG_TERM_VBR_CORRECTION
2128     // Correction to rate target based on prior over or under shoot.
2129     if (cpi->oxcf.rc_mode == VPX_VBR)
2130       vbr_rate_correction(&target_rate, rc->vbr_bits_off_target);
2131 #endif
2132     vp9_rc_set_frame_target(cpi, target_rate);
2133     cm->frame_type = INTER_FRAME;
2134     return;
2135   }
2136
2137   vp9_clear_system_state();
2138
2139   if (is_spatial_svc && twopass->kf_intra_err_min == 0) {
2140     twopass->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
2141     twopass->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
2142   }
2143
2144   if (cpi->oxcf.rc_mode == VPX_Q) {
2145     twopass->active_worst_quality = cpi->oxcf.cq_level;
2146   } else if (cm->current_video_frame == 0 ||
2147              (is_spatial_svc && lc->current_video_frame_in_layer == 0)) {
2148     // Special case code for first frame.
2149     const int section_target_bandwidth = (int)(twopass->bits_left /
2150                                                frames_left);
2151     const int tmp_q = get_twopass_worst_quality(cpi, &twopass->total_left_stats,
2152                                                 section_target_bandwidth);
2153     twopass->active_worst_quality = tmp_q;
2154     rc->ni_av_qi = tmp_q;
2155     rc->avg_q = vp9_convert_qindex_to_q(tmp_q);
2156   }
2157   vp9_zero(this_frame);
2158   if (EOF == input_stats(twopass, &this_frame))
2159     return;
2160
2161   // Local copy of the current frame's first pass stats.
2162   this_frame_copy = this_frame;
2163
2164   // Keyframe and section processing.
2165   if (rc->frames_to_key == 0 ||
2166       (cpi->frame_flags & FRAMEFLAGS_KEY)) {
2167     // Define next KF group and assign bits to it.
2168     find_next_key_frame(cpi, &this_frame_copy);
2169   } else {
2170     cm->frame_type = INTER_FRAME;
2171   }
2172
2173   if (is_spatial_svc) {
2174     if (cpi->svc.spatial_layer_id == 0) {
2175       lc->is_key_frame = (cm->frame_type == KEY_FRAME);
2176     } else {
2177       cm->frame_type = INTER_FRAME;
2178       lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2179
2180       if (lc->is_key_frame) {
2181         cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2182       }
2183     }
2184   }
2185
2186   // Define a new GF/ARF group. (Should always enter here for key frames).
2187   if (rc->frames_till_gf_update_due == 0) {
2188     define_gf_group(cpi, &this_frame_copy);
2189
2190     if (twopass->gf_zeromotion_pct > 995) {
2191       // As long as max_thresh for encode breakout is small enough, it is ok
2192       // to enable it for show frame, i.e. set allow_encode_breakout to
2193       // ENCODE_BREAKOUT_LIMITED.
2194       if (!cm->show_frame)
2195         cpi->allow_encode_breakout = ENCODE_BREAKOUT_DISABLED;
2196       else
2197         cpi->allow_encode_breakout = ENCODE_BREAKOUT_LIMITED;
2198     }
2199
2200     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2201     cpi->refresh_golden_frame = 1;
2202   }
2203
2204   {
2205     FIRSTPASS_STATS next_frame;
2206     if (lookup_next_frame_stats(twopass, &next_frame) != EOF) {
2207       twopass->next_iiratio = (int)(next_frame.intra_error /
2208                                  DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2209     }
2210   }
2211
2212   configure_buffer_updates(cpi);
2213
2214   target_rate = twopass->gf_group.bit_allocation[twopass->gf_group.index];
2215   if (cpi->common.frame_type == KEY_FRAME)
2216     target_rate = vp9_rc_clamp_iframe_target_size(cpi, target_rate);
2217   else
2218     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2219
2220   rc->base_frame_target = target_rate;
2221 #ifdef LONG_TERM_VBR_CORRECTION
2222   // Correction to rate target based on prior over or under shoot.
2223   if (cpi->oxcf.rc_mode == VPX_VBR)
2224     vbr_rate_correction(&target_rate, rc->vbr_bits_off_target);
2225 #endif
2226   vp9_rc_set_frame_target(cpi, target_rate);
2227
2228   // Update the total stats remaining structure.
2229   subtract_stats(&twopass->total_left_stats, &this_frame);
2230
2231 #if CONFIG_FP_MB_STATS
2232   if (cpi->use_fp_mb_stats) {
2233     input_mb_stats(&twopass->this_frame_mb_stats, cm);
2234   }
2235 #endif
2236 }
2237
2238 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
2239   TWO_PASS *const twopass = &cpi->twopass;
2240   RATE_CONTROL *const rc = &cpi->rc;
2241 #ifdef LONG_TERM_VBR_CORRECTION
2242   // In this experimental mode, the VBR correction is done exclusively through
2243   // rc->vbr_bits_off_target. Based on the sign of this value, a limited %
2244   // adjustment is made to the target rate of subsequent frames, to try and
2245   // push it back towards 0. This mode is less likely to suffer from
2246   // extreme behaviour at the end of a clip or group of frames.
2247   const int bits_used = rc->base_frame_target;
2248   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
2249 #else
2250   // In this mode, VBR correction is acheived by altering bits_left,
2251   // kf_group_bits & gf_group_bits to reflect any deviation from the target
2252   // rate in this frame. This alters the allocation of bits to the
2253   // remaning frames in the group / clip.
2254   //
2255   // This method can give rise to unstable behaviour near the end of a clip
2256   // or kf/gf group of frames where any accumulated error is corrected over an
2257   // ever decreasing number of frames. Hence we change the balance of target
2258   // vs. actual bitrate gradually as we progress towards the end of the
2259   // sequence in order to mitigate this effect.
2260   const double progress =
2261       (double)(twopass->stats_in - twopass->stats_in_start) /
2262               (twopass->stats_in_end - twopass->stats_in_start);
2263   const int bits_used = (int)(progress * rc->this_frame_target +
2264                              (1.0 - progress) * rc->projected_frame_size);
2265 #endif
2266
2267   twopass->bits_left = MAX(twopass->bits_left - bits_used, 0);
2268
2269 #ifdef LONG_TERM_VBR_CORRECTION
2270   if (cpi->common.frame_type != KEY_FRAME &&
2271       !vp9_is_upper_layer_key_frame(cpi)) {
2272 #else
2273   if (cpi->common.frame_type == KEY_FRAME ||
2274       vp9_is_upper_layer_key_frame(cpi)) {
2275     // For key frames kf_group_bits already had the target bits subtracted out.
2276     // So now update to the correct value based on the actual bits used.
2277     twopass->kf_group_bits += rc->this_frame_target - bits_used;
2278   } else {
2279 #endif
2280     twopass->kf_group_bits -= bits_used;
2281   }
2282   twopass->kf_group_bits = MAX(twopass->kf_group_bits, 0);
2283
2284   // Increment the gf group index ready for the next frame.
2285   ++twopass->gf_group.index;
2286 }