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