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