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