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