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