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