]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_firstpass.c
Merge "BITSTREAM: Handle transform size and motion vectors more logically for non...
[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             (cpi->use_svc && cpi->svc.number_temporal_layers == 1)) {
612           // Test last reference frame using the previous best mv as the
613           // starting point (best reference) for the search.
614           first_pass_motion_search(cpi, x, &best_ref_mv.as_mv, &mv.as_mv,
615                                    &motion_error);
616           if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
617             vp9_clear_system_state();
618             motion_error = (int)(motion_error * error_weight);
619           }
620
621           // If the current best reference mv is not centered on 0,0 then do a
622           // 0,0 based search as well.
623           if (best_ref_mv.as_int) {
624             tmp_err = INT_MAX;
625             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv.as_mv, &tmp_err);
626             if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
627               vp9_clear_system_state();
628               tmp_err = (int)(tmp_err * error_weight);
629             }
630
631             if (tmp_err < motion_error) {
632               motion_error = tmp_err;
633               mv.as_int = tmp_mv.as_int;
634             }
635           }
636
637           // Search in an older reference frame.
638           if (cm->current_video_frame > 1 && gld_yv12 != NULL) {
639             // Assume 0,0 motion with no mv overhead.
640             int gf_motion_error;
641
642             xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
643             gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
644                                                    &xd->plane[0].pre[0]);
645
646             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv.as_mv,
647                                      &gf_motion_error);
648             if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
649               vp9_clear_system_state();
650               gf_motion_error = (int)(gf_motion_error * error_weight);
651             }
652
653             if (gf_motion_error < motion_error && gf_motion_error < this_error)
654               ++second_ref_count;
655
656             // Reset to last frame as reference buffer.
657             xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
658             xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
659             xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
660
661             // In accumulating a score for the older reference frame take the
662             // best of the motion predicted score and the intra coded error
663             // (just as will be done for) accumulation of "coded_error" for
664             // the last frame.
665             if (gf_motion_error < this_error)
666               sr_coded_error += gf_motion_error;
667             else
668               sr_coded_error += this_error;
669           } else {
670             sr_coded_error += motion_error;
671           }
672         } else {
673           sr_coded_error += motion_error;
674         }
675
676         // Start by assuming that intra mode is best.
677         best_ref_mv.as_int = 0;
678
679         if (motion_error <= this_error) {
680           // Keep a count of cases where the inter and intra were very close
681           // and very low. This helps with scene cut detection for example in
682           // cropped clips with black bars at the sides or top and bottom.
683           if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
684               this_error < 2 * intrapenalty)
685             ++neutral_count;
686
687           mv.as_mv.row *= 8;
688           mv.as_mv.col *= 8;
689           this_error = motion_error;
690           xd->mi[0]->mbmi.mode = NEWMV;
691           xd->mi[0]->mbmi.mv[0] = mv;
692           xd->mi[0]->mbmi.tx_size = TX_4X4;
693           xd->mi[0]->mbmi.ref_frame[0] = LAST_FRAME;
694           xd->mi[0]->mbmi.ref_frame[1] = NONE;
695           vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
696           vp9_encode_sby_pass1(x, bsize);
697           sum_mvr += mv.as_mv.row;
698           sum_mvr_abs += abs(mv.as_mv.row);
699           sum_mvc += mv.as_mv.col;
700           sum_mvc_abs += abs(mv.as_mv.col);
701           sum_mvrs += mv.as_mv.row * mv.as_mv.row;
702           sum_mvcs += mv.as_mv.col * mv.as_mv.col;
703           ++intercount;
704
705           best_ref_mv.as_int = mv.as_int;
706
707           if (mv.as_int) {
708             ++mvcount;
709
710             // Non-zero vector, was it different from the last non zero vector?
711             if (mv.as_int != lastmv_as_int)
712               ++new_mv_count;
713             lastmv_as_int = mv.as_int;
714
715             // Does the row vector point inwards or outwards?
716             if (mb_row < cm->mb_rows / 2) {
717               if (mv.as_mv.row > 0)
718                 --sum_in_vectors;
719               else if (mv.as_mv.row < 0)
720                 ++sum_in_vectors;
721             } else if (mb_row > cm->mb_rows / 2) {
722               if (mv.as_mv.row > 0)
723                 ++sum_in_vectors;
724               else if (mv.as_mv.row < 0)
725                 --sum_in_vectors;
726             }
727
728             // Does the col vector point inwards or outwards?
729             if (mb_col < cm->mb_cols / 2) {
730               if (mv.as_mv.col > 0)
731                 --sum_in_vectors;
732               else if (mv.as_mv.col < 0)
733                 ++sum_in_vectors;
734             } else if (mb_col > cm->mb_cols / 2) {
735               if (mv.as_mv.col > 0)
736                 ++sum_in_vectors;
737               else if (mv.as_mv.col < 0)
738                 --sum_in_vectors;
739             }
740           }
741         }
742       } else {
743         sr_coded_error += (int64_t)this_error;
744       }
745       coded_error += (int64_t)this_error;
746
747       // Adjust to the next column of MBs.
748       x->plane[0].src.buf += 16;
749       x->plane[1].src.buf += uv_mb_height;
750       x->plane[2].src.buf += uv_mb_height;
751
752       recon_yoffset += 16;
753       recon_uvoffset += uv_mb_height;
754     }
755
756     // Adjust to the next row of MBs.
757     x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
758     x->plane[1].src.buf += uv_mb_height * x->plane[1].src.stride -
759                            uv_mb_height * cm->mb_cols;
760     x->plane[2].src.buf += uv_mb_height * x->plane[1].src.stride -
761                            uv_mb_height * cm->mb_cols;
762
763     vp9_clear_system_state();
764   }
765
766   vp9_clear_system_state();
767   {
768     FIRSTPASS_STATS fps;
769
770     fps.frame = cm->current_video_frame;
771     fps.spatial_layer_id = cpi->svc.spatial_layer_id;
772     fps.intra_error = (double)(intra_error >> 8);
773     fps.coded_error = (double)(coded_error >> 8);
774     fps.sr_coded_error = (double)(sr_coded_error >> 8);
775     fps.count = 1.0;
776     fps.pcnt_inter = (double)intercount / cm->MBs;
777     fps.pcnt_second_ref = (double)second_ref_count / cm->MBs;
778     fps.pcnt_neutral = (double)neutral_count / cm->MBs;
779
780     if (mvcount > 0) {
781       fps.MVr = (double)sum_mvr / mvcount;
782       fps.mvr_abs = (double)sum_mvr_abs / mvcount;
783       fps.MVc = (double)sum_mvc / mvcount;
784       fps.mvc_abs = (double)sum_mvc_abs / mvcount;
785       fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / mvcount)) / mvcount;
786       fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / mvcount)) / mvcount;
787       fps.mv_in_out_count = (double)sum_in_vectors / (mvcount * 2);
788       fps.new_mv_count = new_mv_count;
789       fps.pcnt_motion = (double)mvcount / cm->MBs;
790     } else {
791       fps.MVr = 0.0;
792       fps.mvr_abs = 0.0;
793       fps.MVc = 0.0;
794       fps.mvc_abs = 0.0;
795       fps.MVrv = 0.0;
796       fps.MVcv = 0.0;
797       fps.mv_in_out_count = 0.0;
798       fps.new_mv_count = 0.0;
799       fps.pcnt_motion = 0.0;
800     }
801
802     // TODO(paulwilkins):  Handle the case when duration is set to 0, or
803     // something less than the full time between subsequent values of
804     // cpi->source_time_stamp.
805     fps.duration = (double)(cpi->source->ts_end - cpi->source->ts_start);
806
807     // Don't want to do output stats with a stack variable!
808     twopass->this_frame_stats = fps;
809     output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
810     accumulate_stats(&twopass->total_stats, &fps);
811   }
812
813   // Copy the previous Last Frame back into gf and and arf buffers if
814   // the prediction is good enough... but also don't allow it to lag too far.
815   if ((twopass->sr_update_lag > 3) ||
816       ((cm->current_video_frame > 0) &&
817        (twopass->this_frame_stats.pcnt_inter > 0.20) &&
818        ((twopass->this_frame_stats.intra_error /
819          DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
820     if (gld_yv12 != NULL) {
821       vp8_yv12_copy_frame(lst_yv12, gld_yv12);
822     }
823     twopass->sr_update_lag = 1;
824   } else {
825     ++twopass->sr_update_lag;
826   }
827
828   vp9_extend_frame_borders(new_yv12);
829
830   if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
831     vp9_update_reference_frames(cpi);
832   } else {
833     // Swap frame pointers so last frame refers to the frame we just compressed.
834     swap_yv12(lst_yv12, new_yv12);
835   }
836
837   // Special case for the first frame. Copy into the GF buffer as a second
838   // reference.
839   if (cm->current_video_frame == 0 && gld_yv12 != NULL) {
840     vp8_yv12_copy_frame(lst_yv12, gld_yv12);
841   }
842
843   // Use this to see what the first pass reconstruction looks like.
844   if (0) {
845     char filename[512];
846     FILE *recon_file;
847     snprintf(filename, sizeof(filename), "enc%04d.yuv",
848              (int)cm->current_video_frame);
849
850     if (cm->current_video_frame == 0)
851       recon_file = fopen(filename, "wb");
852     else
853       recon_file = fopen(filename, "ab");
854
855     (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
856     fclose(recon_file);
857   }
858
859   ++cm->current_video_frame;
860 }
861
862 static double calc_correction_factor(double err_per_mb,
863                                      double err_divisor,
864                                      double pt_low,
865                                      double pt_high,
866                                      int q) {
867   const double error_term = err_per_mb / err_divisor;
868
869   // Adjustment based on actual quantizer to power term.
870   const double power_term = MIN(vp9_convert_qindex_to_q(q) * 0.0125 + pt_low,
871                                 pt_high);
872
873   // Calculate correction factor.
874   if (power_term < 1.0)
875     assert(error_term >= 0.0);
876
877   return fclamp(pow(error_term, power_term), 0.05, 5.0);
878 }
879
880 static int get_twopass_worst_quality(const VP9_COMP *cpi,
881                                      const FIRSTPASS_STATS *stats,
882                                      int section_target_bandwidth) {
883   const RATE_CONTROL *const rc = &cpi->rc;
884   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
885
886   if (section_target_bandwidth <= 0) {
887     return rc->worst_quality;  // Highest value allowed
888   } else {
889     const int num_mbs = cpi->common.MBs;
890     const double section_err = stats->coded_error / stats->count;
891     const double err_per_mb = section_err / num_mbs;
892     const double speed_term = 1.0 + 0.04 * oxcf->speed;
893     const int target_norm_bits_per_mb = ((uint64_t)section_target_bandwidth <<
894                                             BPER_MB_NORMBITS) / num_mbs;
895     int q;
896     int is_svc_upper_layer = 0;
897     if (cpi->use_svc && cpi->svc.number_temporal_layers == 1 &&
898         cpi->svc.spatial_layer_id > 0) {
899       is_svc_upper_layer = 1;
900     }
901
902     // Try and pick a max Q that will be high enough to encode the
903     // content at the given rate.
904     for (q = rc->best_quality; q < rc->worst_quality; ++q) {
905       const double factor =
906           calc_correction_factor(err_per_mb, ERR_DIVISOR,
907                                  is_svc_upper_layer ? SVC_FACTOR_PT_LOW :
908                                  FACTOR_PT_LOW, FACTOR_PT_HIGH, q);
909       const int bits_per_mb = vp9_rc_bits_per_mb(INTER_FRAME, q,
910                                                  factor * speed_term);
911       if (bits_per_mb <= target_norm_bits_per_mb)
912         break;
913     }
914
915     // Restriction on active max q for constrained quality mode.
916     if (cpi->oxcf.rc_mode == VPX_CQ)
917       q = MAX(q, oxcf->cq_level);
918     return q;
919   }
920 }
921
922 extern void vp9_new_framerate(VP9_COMP *cpi, double framerate);
923
924 void vp9_init_second_pass(VP9_COMP *cpi) {
925   SVC *const svc = &cpi->svc;
926   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
927   const int is_spatial_svc = (svc->number_spatial_layers > 1) &&
928                              (svc->number_temporal_layers == 1);
929   TWO_PASS *const twopass = is_spatial_svc ?
930       &svc->layer_context[svc->spatial_layer_id].twopass : &cpi->twopass;
931   double frame_rate;
932   FIRSTPASS_STATS *stats;
933
934   zero_stats(&twopass->total_stats);
935   zero_stats(&twopass->total_left_stats);
936
937   if (!twopass->stats_in_end)
938     return;
939
940   stats = &twopass->total_stats;
941
942   *stats = *twopass->stats_in_end;
943   twopass->total_left_stats = *stats;
944
945   frame_rate = 10000000.0 * stats->count / stats->duration;
946   // Each frame can have a different duration, as the frame rate in the source
947   // isn't guaranteed to be constant. The frame rate prior to the first frame
948   // encoded in the second pass is a guess. However, the sum duration is not.
949   // It is calculated based on the actual durations of all frames from the
950   // first pass.
951
952   if (is_spatial_svc) {
953     vp9_update_spatial_layer_framerate(cpi, frame_rate);
954     twopass->bits_left = (int64_t)(stats->duration *
955         svc->layer_context[svc->spatial_layer_id].target_bandwidth /
956         10000000.0);
957   } else {
958     vp9_new_framerate(cpi, frame_rate);
959     twopass->bits_left = (int64_t)(stats->duration * oxcf->target_bandwidth /
960                              10000000.0);
961   }
962
963   // Calculate a minimum intra value to be used in determining the IIratio
964   // scores used in the second pass. We have this minimum to make sure
965   // that clips that are static but "low complexity" in the intra domain
966   // are still boosted appropriately for KF/GF/ARF.
967   if (!is_spatial_svc) {
968     // We don't know the number of MBs for each layer at this point.
969     // So we will do it later.
970     twopass->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
971     twopass->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
972   }
973
974   // This variable monitors how far behind the second ref update is lagging.
975   twopass->sr_update_lag = 1;
976
977   // Scan the first pass file and calculate a modified total error based upon
978   // the bias/power function used to allocate bits.
979   {
980     const double avg_error = stats->coded_error /
981                              DOUBLE_DIVIDE_CHECK(stats->count);
982     const FIRSTPASS_STATS *s = twopass->stats_in;
983     double modified_error_total = 0.0;
984     twopass->modified_error_min = (avg_error *
985                                       oxcf->two_pass_vbrmin_section) / 100;
986     twopass->modified_error_max = (avg_error *
987                                       oxcf->two_pass_vbrmax_section) / 100;
988     while (s < twopass->stats_in_end) {
989       modified_error_total += calculate_modified_err(twopass, oxcf, s);
990       ++s;
991     }
992     twopass->modified_error_left = modified_error_total;
993   }
994
995   // Reset the vbr bits off target counter
996   cpi->rc.vbr_bits_off_target = 0;
997 }
998
999 // This function gives an estimate of how badly we believe the prediction
1000 // quality is decaying from frame to frame.
1001 static double get_prediction_decay_rate(const VP9_COMMON *cm,
1002                                         const FIRSTPASS_STATS *next_frame) {
1003   // Look at the observed drop in prediction quality between the last frame
1004   // and the GF buffer (which contains an older frame).
1005   const double mb_sr_err_diff = (next_frame->sr_coded_error -
1006                                      next_frame->coded_error) / cm->MBs;
1007   const double second_ref_decay = mb_sr_err_diff <= 512.0
1008       ? fclamp(pow(1.0 - (mb_sr_err_diff / 512.0), 0.5), 0.85, 1.0)
1009       : 0.85;
1010
1011   return MIN(second_ref_decay, next_frame->pcnt_inter);
1012 }
1013
1014 // Function to test for a condition where a complex transition is followed
1015 // by a static section. For example in slide shows where there is a fade
1016 // between slides. This is to help with more optimal kf and gf positioning.
1017 static int detect_transition_to_still(TWO_PASS *twopass,
1018                                       int frame_interval, int still_interval,
1019                                       double loop_decay_rate,
1020                                       double last_decay_rate) {
1021   int trans_to_still = 0;
1022
1023   // Break clause to detect very still sections after motion
1024   // For example a static image after a fade or other transition
1025   // instead of a clean scene cut.
1026   if (frame_interval > MIN_GF_INTERVAL &&
1027       loop_decay_rate >= 0.999 &&
1028       last_decay_rate < 0.9) {
1029     int j;
1030     const FIRSTPASS_STATS *position = twopass->stats_in;
1031     FIRSTPASS_STATS tmp_next_frame;
1032
1033     // Look ahead a few frames to see if static condition persists...
1034     for (j = 0; j < still_interval; ++j) {
1035       if (EOF == input_stats(twopass, &tmp_next_frame))
1036         break;
1037
1038       if (tmp_next_frame.pcnt_inter - tmp_next_frame.pcnt_motion < 0.999)
1039         break;
1040     }
1041
1042     reset_fpf_position(twopass, position);
1043
1044     // Only if it does do we signal a transition to still.
1045     if (j == still_interval)
1046       trans_to_still = 1;
1047   }
1048
1049   return trans_to_still;
1050 }
1051
1052 // This function detects a flash through the high relative pcnt_second_ref
1053 // score in the frame following a flash frame. The offset passed in should
1054 // reflect this.
1055 static int detect_flash(const TWO_PASS *twopass, int offset) {
1056   FIRSTPASS_STATS next_frame;
1057
1058   int flash_detected = 0;
1059
1060   // Read the frame data.
1061   // The return is FALSE (no flash detected) if not a valid frame
1062   if (read_frame_stats(twopass, &next_frame, offset) != EOF) {
1063     // What we are looking for here is a situation where there is a
1064     // brief break in prediction (such as a flash) but subsequent frames
1065     // are reasonably well predicted by an earlier (pre flash) frame.
1066     // The recovery after a flash is indicated by a high pcnt_second_ref
1067     // compared to pcnt_inter.
1068     if (next_frame.pcnt_second_ref > next_frame.pcnt_inter &&
1069         next_frame.pcnt_second_ref >= 0.5)
1070       flash_detected = 1;
1071   }
1072
1073   return flash_detected;
1074 }
1075
1076 // Update the motion related elements to the GF arf boost calculation.
1077 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1078                                           double *mv_in_out,
1079                                           double *mv_in_out_accumulator,
1080                                           double *abs_mv_in_out_accumulator,
1081                                           double *mv_ratio_accumulator) {
1082   const double pct = stats->pcnt_motion;
1083
1084   // Accumulate Motion In/Out of frame stats.
1085   *mv_in_out = stats->mv_in_out_count * pct;
1086   *mv_in_out_accumulator += *mv_in_out;
1087   *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1088
1089   // Accumulate a measure of how uniform (or conversely how random) the motion
1090   // field is (a ratio of abs(mv) / mv).
1091   if (pct > 0.05) {
1092     const double mvr_ratio = fabs(stats->mvr_abs) /
1093                                  DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1094     const double mvc_ratio = fabs(stats->mvc_abs) /
1095                                  DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1096
1097     *mv_ratio_accumulator += pct * (mvr_ratio < stats->mvr_abs ?
1098                                        mvr_ratio : stats->mvr_abs);
1099     *mv_ratio_accumulator += pct * (mvc_ratio < stats->mvc_abs ?
1100                                        mvc_ratio : stats->mvc_abs);
1101   }
1102 }
1103
1104 // Calculate a baseline boost number for the current frame.
1105 static double calc_frame_boost(const TWO_PASS *twopass,
1106                                const FIRSTPASS_STATS *this_frame,
1107                                double this_frame_mv_in_out) {
1108   double frame_boost;
1109
1110   // Underlying boost factor is based on inter intra error ratio.
1111   if (this_frame->intra_error > twopass->gf_intra_err_min)
1112     frame_boost = (IIFACTOR * this_frame->intra_error /
1113                    DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1114   else
1115     frame_boost = (IIFACTOR * twopass->gf_intra_err_min /
1116                    DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1117
1118   // Increase boost for frames where new data coming into frame (e.g. zoom out).
1119   // Slightly reduce boost if there is a net balance of motion out of the frame
1120   // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
1121   if (this_frame_mv_in_out > 0.0)
1122     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1123   // In the extreme case the boost is halved.
1124   else
1125     frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1126
1127   return MIN(frame_boost, GF_RMAX);
1128 }
1129
1130 static int calc_arf_boost(VP9_COMP *cpi, int offset,
1131                           int f_frames, int b_frames,
1132                           int *f_boost, int *b_boost) {
1133   FIRSTPASS_STATS this_frame;
1134   TWO_PASS *const twopass = &cpi->twopass;
1135   int i;
1136   double boost_score = 0.0;
1137   double mv_ratio_accumulator = 0.0;
1138   double decay_accumulator = 1.0;
1139   double this_frame_mv_in_out = 0.0;
1140   double mv_in_out_accumulator = 0.0;
1141   double abs_mv_in_out_accumulator = 0.0;
1142   int arf_boost;
1143   int flash_detected = 0;
1144
1145   // Search forward from the proposed arf/next gf position.
1146   for (i = 0; i < f_frames; ++i) {
1147     if (read_frame_stats(twopass, &this_frame, (i + offset)) == EOF)
1148       break;
1149
1150     // Update the motion related elements to the boost calculation.
1151     accumulate_frame_motion_stats(&this_frame,
1152                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1153                                   &abs_mv_in_out_accumulator,
1154                                   &mv_ratio_accumulator);
1155
1156     // We want to discount the flash frame itself and the recovery
1157     // frame that follows as both will have poor scores.
1158     flash_detected = detect_flash(twopass, i + offset) ||
1159                      detect_flash(twopass, i + offset + 1);
1160
1161     // Accumulate the effect of prediction quality decay.
1162     if (!flash_detected) {
1163       decay_accumulator *= get_prediction_decay_rate(&cpi->common, &this_frame);
1164       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1165                           ? MIN_DECAY_FACTOR : decay_accumulator;
1166     }
1167
1168     boost_score += decay_accumulator * calc_frame_boost(twopass, &this_frame,
1169                                                         this_frame_mv_in_out);
1170   }
1171
1172   *f_boost = (int)boost_score;
1173
1174   // Reset for backward looking loop.
1175   boost_score = 0.0;
1176   mv_ratio_accumulator = 0.0;
1177   decay_accumulator = 1.0;
1178   this_frame_mv_in_out = 0.0;
1179   mv_in_out_accumulator = 0.0;
1180   abs_mv_in_out_accumulator = 0.0;
1181
1182   // Search backward towards last gf position.
1183   for (i = -1; i >= -b_frames; --i) {
1184     if (read_frame_stats(twopass, &this_frame, (i + offset)) == EOF)
1185       break;
1186
1187     // Update the motion related elements to the boost calculation.
1188     accumulate_frame_motion_stats(&this_frame,
1189                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1190                                   &abs_mv_in_out_accumulator,
1191                                   &mv_ratio_accumulator);
1192
1193     // We want to discount the the flash frame itself and the recovery
1194     // frame that follows as both will have poor scores.
1195     flash_detected = detect_flash(twopass, i + offset) ||
1196                      detect_flash(twopass, i + offset + 1);
1197
1198     // Cumulative effect of prediction quality decay.
1199     if (!flash_detected) {
1200       decay_accumulator *= get_prediction_decay_rate(&cpi->common, &this_frame);
1201       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1202                               ? MIN_DECAY_FACTOR : decay_accumulator;
1203     }
1204
1205     boost_score += decay_accumulator * calc_frame_boost(twopass, &this_frame,
1206                                                         this_frame_mv_in_out);
1207   }
1208   *b_boost = (int)boost_score;
1209
1210   arf_boost = (*f_boost + *b_boost);
1211   if (arf_boost < ((b_frames + f_frames) * 20))
1212     arf_boost = ((b_frames + f_frames) * 20);
1213
1214   return arf_boost;
1215 }
1216
1217 // Calculate a section intra ratio used in setting max loop filter.
1218 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
1219                                          const FIRSTPASS_STATS *end,
1220                                          int section_length) {
1221   const FIRSTPASS_STATS *s = begin;
1222   double intra_error = 0.0;
1223   double coded_error = 0.0;
1224   int i = 0;
1225
1226   while (s < end && i < section_length) {
1227     intra_error += s->intra_error;
1228     coded_error += s->coded_error;
1229     ++s;
1230     ++i;
1231   }
1232
1233   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
1234 }
1235
1236 // Calculate the total bits to allocate in this GF/ARF group.
1237 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
1238                                              double gf_group_err) {
1239   const RATE_CONTROL *const rc = &cpi->rc;
1240   const TWO_PASS *const twopass = &cpi->twopass;
1241   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1242   int64_t total_group_bits;
1243
1244   // Calculate the bits to be allocated to the group as a whole.
1245   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
1246     total_group_bits = (int64_t)(twopass->kf_group_bits *
1247                                  (gf_group_err / twopass->kf_group_error_left));
1248   } else {
1249     total_group_bits = 0;
1250   }
1251
1252   // Clamp odd edge cases.
1253   total_group_bits = (total_group_bits < 0) ?
1254      0 : (total_group_bits > twopass->kf_group_bits) ?
1255      twopass->kf_group_bits : total_group_bits;
1256
1257   // Clip based on user supplied data rate variability limit.
1258   if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
1259     total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
1260
1261   return total_group_bits;
1262 }
1263
1264 // Calculate the number bits extra to assign to boosted frames in a group.
1265 static int calculate_boost_bits(int frame_count,
1266                                 int boost, int64_t total_group_bits) {
1267   int allocation_chunks;
1268
1269   // return 0 for invalid inputs (could arise e.g. through rounding errors)
1270   if (!boost || (total_group_bits <= 0) || (frame_count <= 0) )
1271     return 0;
1272
1273   allocation_chunks = (frame_count * 100) + boost;
1274
1275   // Prevent overflow.
1276   if (boost > 1023) {
1277     int divisor = boost >> 10;
1278     boost /= divisor;
1279     allocation_chunks /= divisor;
1280   }
1281
1282   // Calculate the number of extra bits for use in the boosted frame or frames.
1283   return MAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks), 0);
1284 }
1285
1286 // Current limit on maximum number of active arfs in a GF/ARF group.
1287 #define MAX_ACTIVE_ARFS 2
1288 #define ARF_SLOT1 2
1289 #define ARF_SLOT2 3
1290 // This function indirects the choice of buffers for arfs.
1291 // At the moment the values are fixed but this may change as part of
1292 // the integration process with other codec features that swap buffers around.
1293 static void get_arf_buffer_indices(unsigned char *arf_buffer_indices) {
1294   arf_buffer_indices[0] = ARF_SLOT1;
1295   arf_buffer_indices[1] = ARF_SLOT2;
1296 }
1297
1298 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
1299                                    double group_error, int gf_arf_bits) {
1300   RATE_CONTROL *const rc = &cpi->rc;
1301   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1302   TWO_PASS *twopass = &cpi->twopass;
1303   FIRSTPASS_STATS frame_stats;
1304   int i;
1305   int frame_index = 1;
1306   int target_frame_size;
1307   int key_frame;
1308   const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
1309   int64_t total_group_bits = gf_group_bits;
1310   double modified_err = 0.0;
1311   double err_fraction;
1312   int mid_boost_bits = 0;
1313   int mid_frame_idx;
1314   unsigned char arf_buffer_indices[MAX_ACTIVE_ARFS];
1315
1316   key_frame = cpi->common.frame_type == KEY_FRAME ||
1317               vp9_is_upper_layer_key_frame(cpi);
1318
1319   get_arf_buffer_indices(arf_buffer_indices);
1320
1321   // For key frames the frame target rate is already set and it
1322   // is also the golden frame.
1323   if (!key_frame) {
1324     if (rc->source_alt_ref_active) {
1325       twopass->gf_group.update_type[0] = OVERLAY_UPDATE;
1326       twopass->gf_group.rf_level[0] = INTER_NORMAL;
1327       twopass->gf_group.bit_allocation[0] = 0;
1328       twopass->gf_group.arf_update_idx[0] = arf_buffer_indices[0];
1329       twopass->gf_group.arf_ref_idx[0] = arf_buffer_indices[0];
1330     } else {
1331       twopass->gf_group.update_type[0] = GF_UPDATE;
1332       twopass->gf_group.rf_level[0] = GF_ARF_STD;
1333       twopass->gf_group.bit_allocation[0] = gf_arf_bits;
1334       twopass->gf_group.arf_update_idx[0] = arf_buffer_indices[0];
1335       twopass->gf_group.arf_ref_idx[0] = arf_buffer_indices[0];
1336     }
1337
1338     // Step over the golden frame / overlay frame
1339     if (EOF == input_stats(twopass, &frame_stats))
1340       return;
1341   }
1342
1343   // Deduct the boost bits for arf (or gf if it is not a key frame)
1344   // from the group total.
1345   if (rc->source_alt_ref_pending || !key_frame)
1346     total_group_bits -= gf_arf_bits;
1347
1348   // Store the bits to spend on the ARF if there is one.
1349   if (rc->source_alt_ref_pending) {
1350     if (cpi->multi_arf_enabled) {
1351       // A portion of the gf / arf extra bits are set asside for lower level
1352       // boosted frames in the middle of the group.
1353       mid_boost_bits += gf_arf_bits >> 5;
1354       gf_arf_bits -= (gf_arf_bits >> 5);
1355     }
1356
1357     twopass->gf_group.update_type[frame_index] = ARF_UPDATE;
1358     twopass->gf_group.rf_level[frame_index] = GF_ARF_STD;
1359     twopass->gf_group.bit_allocation[frame_index] = gf_arf_bits;
1360     twopass->gf_group.arf_src_offset[frame_index] =
1361       (unsigned char)(rc->baseline_gf_interval - 1);
1362     twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[0];
1363     twopass->gf_group.arf_ref_idx[frame_index] =
1364       arf_buffer_indices[cpi->multi_arf_enabled && rc->source_alt_ref_active];
1365     ++frame_index;
1366
1367     if (cpi->multi_arf_enabled) {
1368       // Set aside a slot for a level 1 arf.
1369       twopass->gf_group.update_type[frame_index] = ARF_UPDATE;
1370       twopass->gf_group.rf_level[frame_index] = GF_ARF_LOW;
1371       twopass->gf_group.arf_src_offset[frame_index] =
1372         (unsigned char)((rc->baseline_gf_interval >> 1) - 1);
1373       twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[1];
1374       twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[0];
1375       ++frame_index;
1376     }
1377   }
1378
1379   // Define middle frame
1380   mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
1381
1382   // Allocate bits to the other frames in the group.
1383   for (i = 0; i < rc->baseline_gf_interval - 1; ++i) {
1384     int arf_idx = 0;
1385     if (EOF == input_stats(twopass, &frame_stats))
1386       break;
1387
1388     modified_err = calculate_modified_err(twopass, oxcf, &frame_stats);
1389
1390     if (group_error > 0)
1391       err_fraction = modified_err / DOUBLE_DIVIDE_CHECK(group_error);
1392     else
1393       err_fraction = 0.0;
1394
1395     target_frame_size = (int)((double)total_group_bits * err_fraction);
1396
1397     if (rc->source_alt_ref_pending && cpi->multi_arf_enabled) {
1398       mid_boost_bits += (target_frame_size >> 4);
1399       target_frame_size -= (target_frame_size >> 4);
1400
1401       if (frame_index <= mid_frame_idx)
1402         arf_idx = 1;
1403     }
1404     twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[arf_idx];
1405     twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[arf_idx];
1406
1407     target_frame_size = clamp(target_frame_size, 0,
1408                               MIN(max_bits, (int)total_group_bits));
1409
1410     twopass->gf_group.update_type[frame_index] = LF_UPDATE;
1411     twopass->gf_group.rf_level[frame_index] = INTER_NORMAL;
1412
1413     twopass->gf_group.bit_allocation[frame_index] = target_frame_size;
1414     ++frame_index;
1415   }
1416
1417   // Note:
1418   // We need to configure the frame at the end of the sequence + 1 that will be
1419   // the start frame for the next group. Otherwise prior to the call to
1420   // vp9_rc_get_second_pass_params() the data will be undefined.
1421   twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[0];
1422   twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[0];
1423
1424   if (rc->source_alt_ref_pending) {
1425     twopass->gf_group.update_type[frame_index] = OVERLAY_UPDATE;
1426     twopass->gf_group.rf_level[frame_index] = INTER_NORMAL;
1427
1428     // Final setup for second arf and its overlay.
1429     if (cpi->multi_arf_enabled) {
1430       twopass->gf_group.bit_allocation[2] =
1431         twopass->gf_group.bit_allocation[mid_frame_idx] + mid_boost_bits;
1432       twopass->gf_group.update_type[mid_frame_idx] = OVERLAY_UPDATE;
1433       twopass->gf_group.bit_allocation[mid_frame_idx] = 0;
1434     }
1435   } else {
1436     twopass->gf_group.update_type[frame_index] = GF_UPDATE;
1437     twopass->gf_group.rf_level[frame_index] = GF_ARF_STD;
1438   }
1439 }
1440
1441 // Analyse and define a gf/arf group.
1442 static void define_gf_group(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1443   RATE_CONTROL *const rc = &cpi->rc;
1444   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1445   TWO_PASS *const twopass = &cpi->twopass;
1446   FIRSTPASS_STATS next_frame;
1447   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
1448   int i;
1449
1450   double boost_score = 0.0;
1451   double old_boost_score = 0.0;
1452   double gf_group_err = 0.0;
1453   double gf_first_frame_err = 0.0;
1454   double mod_frame_err = 0.0;
1455
1456   double mv_ratio_accumulator = 0.0;
1457   double decay_accumulator = 1.0;
1458   double zero_motion_accumulator = 1.0;
1459
1460   double loop_decay_rate = 1.00;
1461   double last_loop_decay_rate = 1.00;
1462
1463   double this_frame_mv_in_out = 0.0;
1464   double mv_in_out_accumulator = 0.0;
1465   double abs_mv_in_out_accumulator = 0.0;
1466   double mv_ratio_accumulator_thresh;
1467   unsigned int allow_alt_ref = is_altref_enabled(oxcf);
1468
1469   int f_boost = 0;
1470   int b_boost = 0;
1471   int flash_detected;
1472   int active_max_gf_interval;
1473   int64_t gf_group_bits;
1474   double gf_group_error_left;
1475   int gf_arf_bits;
1476
1477   // Reset the GF group data structures unless this is a key
1478   // frame in which case it will already have been done.
1479   if (cpi->common.frame_type != KEY_FRAME) {
1480     vp9_zero(twopass->gf_group);
1481   }
1482
1483   vp9_clear_system_state();
1484   vp9_zero(next_frame);
1485
1486   gf_group_bits = 0;
1487
1488   // Load stats for the current frame.
1489   mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1490
1491   // Note the error of the frame at the start of the group. This will be
1492   // the GF frame error if we code a normal gf.
1493   gf_first_frame_err = mod_frame_err;
1494
1495   // If this is a key frame or the overlay from a previous arf then
1496   // the error score / cost of this frame has already been accounted for.
1497   if (cpi->common.frame_type == KEY_FRAME || rc->source_alt_ref_active)
1498     gf_group_err -= gf_first_frame_err;
1499
1500   // Motion breakout threshold for loop below depends on image size.
1501   mv_ratio_accumulator_thresh = (cpi->common.width + cpi->common.height) / 10.0;
1502
1503   // Work out a maximum interval for the GF.
1504   // If the image appears completely static we can extend beyond this.
1505   // The value chosen depends on the active Q range. At low Q we have
1506   // bits to spare and are better with a smaller interval and smaller boost.
1507   // At high Q when there are few bits to spare we are better with a longer
1508   // interval to spread the cost of the GF.
1509   //
1510   active_max_gf_interval =
1511     12 + ((int)vp9_convert_qindex_to_q(rc->last_q[INTER_FRAME]) >> 5);
1512
1513   if (active_max_gf_interval > rc->max_gf_interval)
1514     active_max_gf_interval = rc->max_gf_interval;
1515
1516   i = 0;
1517   while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
1518     ++i;
1519
1520     // Accumulate error score of frames in this gf group.
1521     mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1522     gf_group_err += mod_frame_err;
1523
1524     if (EOF == input_stats(twopass, &next_frame))
1525       break;
1526
1527     // Test for the case where there is a brief flash but the prediction
1528     // quality back to an earlier frame is then restored.
1529     flash_detected = detect_flash(twopass, 0);
1530
1531     // Update the motion related elements to the boost calculation.
1532     accumulate_frame_motion_stats(&next_frame,
1533                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1534                                   &abs_mv_in_out_accumulator,
1535                                   &mv_ratio_accumulator);
1536
1537     // Accumulate the effect of prediction quality decay.
1538     if (!flash_detected) {
1539       last_loop_decay_rate = loop_decay_rate;
1540       loop_decay_rate = get_prediction_decay_rate(&cpi->common, &next_frame);
1541       decay_accumulator = decay_accumulator * loop_decay_rate;
1542
1543       // Monitor for static sections.
1544       if ((next_frame.pcnt_inter - next_frame.pcnt_motion) <
1545           zero_motion_accumulator) {
1546         zero_motion_accumulator = next_frame.pcnt_inter -
1547                                       next_frame.pcnt_motion;
1548       }
1549
1550       // Break clause to detect very still sections after motion. For example,
1551       // a static image after a fade or other transition.
1552       if (detect_transition_to_still(twopass, i, 5, loop_decay_rate,
1553                                      last_loop_decay_rate)) {
1554         allow_alt_ref = 0;
1555         break;
1556       }
1557     }
1558
1559     // Calculate a boost number for this frame.
1560     boost_score += decay_accumulator * calc_frame_boost(twopass, &next_frame,
1561                                                         this_frame_mv_in_out);
1562
1563     // Break out conditions.
1564     if (
1565       // Break at active_max_gf_interval unless almost totally static.
1566       (i >= active_max_gf_interval && (zero_motion_accumulator < 0.995)) ||
1567       (
1568         // Don't break out with a very short interval.
1569         (i > MIN_GF_INTERVAL) &&
1570         ((boost_score > 125.0) || (next_frame.pcnt_inter < 0.75)) &&
1571         (!flash_detected) &&
1572         ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
1573          (abs_mv_in_out_accumulator > 3.0) ||
1574          (mv_in_out_accumulator < -2.0) ||
1575          ((boost_score - old_boost_score) < IIFACTOR)))) {
1576       boost_score = old_boost_score;
1577       break;
1578     }
1579
1580     *this_frame = next_frame;
1581
1582     old_boost_score = boost_score;
1583   }
1584
1585   twopass->gf_zeromotion_pct = (int)(zero_motion_accumulator * 1000.0);
1586
1587   // Don't allow a gf too near the next kf.
1588   if ((rc->frames_to_key - i) < MIN_GF_INTERVAL) {
1589     while (i < (rc->frames_to_key + !rc->next_key_frame_forced)) {
1590       ++i;
1591
1592       if (EOF == input_stats(twopass, this_frame))
1593         break;
1594
1595       if (i < rc->frames_to_key) {
1596         mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1597         gf_group_err += mod_frame_err;
1598       }
1599     }
1600   }
1601
1602   // Set the interval until the next gf.
1603   if (cpi->common.frame_type == KEY_FRAME || rc->source_alt_ref_active)
1604     rc->baseline_gf_interval = i - 1;
1605   else
1606     rc->baseline_gf_interval = i;
1607
1608   rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1609
1610   // Should we use the alternate reference frame.
1611   if (allow_alt_ref &&
1612       (i < cpi->oxcf.lag_in_frames) &&
1613       (i >= MIN_GF_INTERVAL) &&
1614       // For real scene cuts (not forced kfs) don't allow arf very near kf.
1615       (rc->next_key_frame_forced ||
1616       (i <= (rc->frames_to_key - MIN_GF_INTERVAL)))) {
1617     // Calculate the boost for alt ref.
1618     rc->gfu_boost = calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost,
1619                                    &b_boost);
1620     rc->source_alt_ref_pending = 1;
1621
1622   } else {
1623     rc->gfu_boost = (int)boost_score;
1624     rc->source_alt_ref_pending = 0;
1625   }
1626
1627   // Reset the file position.
1628   reset_fpf_position(twopass, start_pos);
1629
1630   // Calculate the bits to be allocated to the gf/arf group as a whole
1631   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
1632
1633   // Calculate the extra bits to be used for boosted frame(s)
1634   {
1635     int q = rc->last_q[INTER_FRAME];
1636     int boost = (rc->gfu_boost * gfboost_qadjust(q)) / 100;
1637
1638     // Set max and minimum boost and hence minimum allocation.
1639     boost = clamp(boost, 125, (rc->baseline_gf_interval + 1) * 200);
1640
1641     // Calculate the extra bits to be used for boosted frame(s)
1642     gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval,
1643                                        boost, gf_group_bits);
1644   }
1645
1646   // Adjust KF group bits and error remaining.
1647   twopass->kf_group_error_left -= (int64_t)gf_group_err;
1648
1649   // If this is an arf update we want to remove the score for the overlay
1650   // frame at the end which will usually be very cheap to code.
1651   // The overlay frame has already, in effect, been coded so we want to spread
1652   // the remaining bits among the other frames.
1653   // For normal GFs remove the score for the GF itself unless this is
1654   // also a key frame in which case it has already been accounted for.
1655   if (rc->source_alt_ref_pending) {
1656     gf_group_error_left = gf_group_err - mod_frame_err;
1657   } else if (cpi->common.frame_type != KEY_FRAME) {
1658     gf_group_error_left = gf_group_err - gf_first_frame_err;
1659   } else {
1660     gf_group_error_left = gf_group_err;
1661   }
1662
1663   // Allocate bits to each of the frames in the GF group.
1664   allocate_gf_group_bits(cpi, gf_group_bits, gf_group_error_left, gf_arf_bits);
1665
1666   // Reset the file position.
1667   reset_fpf_position(twopass, start_pos);
1668
1669   // Calculate a section intra ratio used in setting max loop filter.
1670   if (cpi->common.frame_type != KEY_FRAME) {
1671     twopass->section_intra_rating =
1672         calculate_section_intra_ratio(start_pos, twopass->stats_in_end,
1673                                       rc->baseline_gf_interval);
1674   }
1675 }
1676
1677 static int test_candidate_kf(TWO_PASS *twopass,
1678                              const FIRSTPASS_STATS *last_frame,
1679                              const FIRSTPASS_STATS *this_frame,
1680                              const FIRSTPASS_STATS *next_frame) {
1681   int is_viable_kf = 0;
1682
1683   // Does the frame satisfy the primary criteria of a key frame?
1684   // If so, then examine how well it predicts subsequent frames.
1685   if ((this_frame->pcnt_second_ref < 0.10) &&
1686       (next_frame->pcnt_second_ref < 0.10) &&
1687       ((this_frame->pcnt_inter < 0.05) ||
1688        (((this_frame->pcnt_inter - this_frame->pcnt_neutral) < 0.35) &&
1689         ((this_frame->intra_error /
1690           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) < 2.5) &&
1691         ((fabs(last_frame->coded_error - this_frame->coded_error) /
1692               DOUBLE_DIVIDE_CHECK(this_frame->coded_error) > 0.40) ||
1693          (fabs(last_frame->intra_error - this_frame->intra_error) /
1694               DOUBLE_DIVIDE_CHECK(this_frame->intra_error) > 0.40) ||
1695          ((next_frame->intra_error /
1696            DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) > 3.5))))) {
1697     int i;
1698     const FIRSTPASS_STATS *start_pos = twopass->stats_in;
1699     FIRSTPASS_STATS local_next_frame = *next_frame;
1700     double boost_score = 0.0;
1701     double old_boost_score = 0.0;
1702     double decay_accumulator = 1.0;
1703
1704     // Examine how well the key frame predicts subsequent frames.
1705     for (i = 0; i < 16; ++i) {
1706       double next_iiratio = (IIKFACTOR1 * local_next_frame.intra_error /
1707                              DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
1708
1709       if (next_iiratio > RMAX)
1710         next_iiratio = RMAX;
1711
1712       // Cumulative effect of decay in prediction quality.
1713       if (local_next_frame.pcnt_inter > 0.85)
1714         decay_accumulator *= local_next_frame.pcnt_inter;
1715       else
1716         decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
1717
1718       // Keep a running total.
1719       boost_score += (decay_accumulator * next_iiratio);
1720
1721       // Test various breakout clauses.
1722       if ((local_next_frame.pcnt_inter < 0.05) ||
1723           (next_iiratio < 1.5) ||
1724           (((local_next_frame.pcnt_inter -
1725              local_next_frame.pcnt_neutral) < 0.20) &&
1726            (next_iiratio < 3.0)) ||
1727           ((boost_score - old_boost_score) < 3.0) ||
1728           (local_next_frame.intra_error < 200)) {
1729         break;
1730       }
1731
1732       old_boost_score = boost_score;
1733
1734       // Get the next frame details
1735       if (EOF == input_stats(twopass, &local_next_frame))
1736         break;
1737     }
1738
1739     // If there is tolerable prediction for at least the next 3 frames then
1740     // break out else discard this potential key frame and move on
1741     if (boost_score > 30.0 && (i > 3)) {
1742       is_viable_kf = 1;
1743     } else {
1744       // Reset the file position
1745       reset_fpf_position(twopass, start_pos);
1746
1747       is_viable_kf = 0;
1748     }
1749   }
1750
1751   return is_viable_kf;
1752 }
1753
1754 static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1755   int i, j;
1756   RATE_CONTROL *const rc = &cpi->rc;
1757   TWO_PASS *const twopass = &cpi->twopass;
1758   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1759   const FIRSTPASS_STATS first_frame = *this_frame;
1760   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
1761   FIRSTPASS_STATS next_frame;
1762   FIRSTPASS_STATS last_frame;
1763   int kf_bits = 0;
1764   double decay_accumulator = 1.0;
1765   double zero_motion_accumulator = 1.0;
1766   double boost_score = 0.0;
1767   double kf_mod_err = 0.0;
1768   double kf_group_err = 0.0;
1769   double recent_loop_decay[8] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
1770
1771   vp9_zero(next_frame);
1772
1773   cpi->common.frame_type = KEY_FRAME;
1774
1775   // Reset the GF group data structures.
1776   vp9_zero(twopass->gf_group);
1777
1778   // Is this a forced key frame by interval.
1779   rc->this_key_frame_forced = rc->next_key_frame_forced;
1780
1781   // Clear the alt ref active flag as this can never be active on a key frame.
1782   rc->source_alt_ref_active = 0;
1783
1784   // KF is always a GF so clear frames till next gf counter.
1785   rc->frames_till_gf_update_due = 0;
1786
1787   rc->frames_to_key = 1;
1788
1789   twopass->kf_group_bits = 0;        // Total bits available to kf group
1790   twopass->kf_group_error_left = 0;  // Group modified error score.
1791
1792   kf_mod_err = calculate_modified_err(twopass, oxcf, this_frame);
1793
1794   // Find the next keyframe.
1795   i = 0;
1796   while (twopass->stats_in < twopass->stats_in_end &&
1797          rc->frames_to_key < cpi->oxcf.key_freq) {
1798     // Accumulate kf group error.
1799     kf_group_err += calculate_modified_err(twopass, oxcf, this_frame);
1800
1801     // Load the next frame's stats.
1802     last_frame = *this_frame;
1803     input_stats(twopass, this_frame);
1804
1805     // Provided that we are not at the end of the file...
1806     if (cpi->oxcf.auto_key &&
1807         lookup_next_frame_stats(twopass, &next_frame) != EOF) {
1808       double loop_decay_rate;
1809
1810       // Check for a scene cut.
1811       if (test_candidate_kf(twopass, &last_frame, this_frame, &next_frame))
1812         break;
1813
1814       // How fast is the prediction quality decaying?
1815       loop_decay_rate = get_prediction_decay_rate(&cpi->common, &next_frame);
1816
1817       // We want to know something about the recent past... rather than
1818       // as used elsewhere where we are concerned with decay in prediction
1819       // quality since the last GF or KF.
1820       recent_loop_decay[i % 8] = loop_decay_rate;
1821       decay_accumulator = 1.0;
1822       for (j = 0; j < 8; ++j)
1823         decay_accumulator *= recent_loop_decay[j];
1824
1825       // Special check for transition or high motion followed by a
1826       // static scene.
1827       if (detect_transition_to_still(twopass, i, cpi->oxcf.key_freq - i,
1828                                      loop_decay_rate, decay_accumulator))
1829         break;
1830
1831       // Step on to the next frame.
1832       ++rc->frames_to_key;
1833
1834       // If we don't have a real key frame within the next two
1835       // key_freq intervals then break out of the loop.
1836       if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq)
1837         break;
1838     } else {
1839       ++rc->frames_to_key;
1840     }
1841     ++i;
1842   }
1843
1844   // If there is a max kf interval set by the user we must obey it.
1845   // We already breakout of the loop above at 2x max.
1846   // This code centers the extra kf if the actual natural interval
1847   // is between 1x and 2x.
1848   if (cpi->oxcf.auto_key &&
1849       rc->frames_to_key > cpi->oxcf.key_freq) {
1850     FIRSTPASS_STATS tmp_frame = first_frame;
1851
1852     rc->frames_to_key /= 2;
1853
1854     // Reset to the start of the group.
1855     reset_fpf_position(twopass, start_position);
1856
1857     kf_group_err = 0;
1858
1859     // Rescan to get the correct error data for the forced kf group.
1860     for (i = 0; i < rc->frames_to_key; ++i) {
1861       kf_group_err += calculate_modified_err(twopass, oxcf, &tmp_frame);
1862       input_stats(twopass, &tmp_frame);
1863     }
1864     rc->next_key_frame_forced = 1;
1865   } else if (twopass->stats_in == twopass->stats_in_end ||
1866              rc->frames_to_key >= cpi->oxcf.key_freq) {
1867     rc->next_key_frame_forced = 1;
1868   } else {
1869     rc->next_key_frame_forced = 0;
1870   }
1871
1872   // Special case for the last key frame of the file.
1873   if (twopass->stats_in >= twopass->stats_in_end) {
1874     // Accumulate kf group error.
1875     kf_group_err += calculate_modified_err(twopass, oxcf, this_frame);
1876   }
1877
1878   // Calculate the number of bits that should be assigned to the kf group.
1879   if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
1880     // Maximum number of bits for a single normal frame (not key frame).
1881     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1882
1883     // Maximum number of bits allocated to the key frame group.
1884     int64_t max_grp_bits;
1885
1886     // Default allocation based on bits left and relative
1887     // complexity of the section.
1888     twopass->kf_group_bits = (int64_t)(twopass->bits_left *
1889        (kf_group_err / twopass->modified_error_left));
1890
1891     // Clip based on maximum per frame rate defined by the user.
1892     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
1893     if (twopass->kf_group_bits > max_grp_bits)
1894       twopass->kf_group_bits = max_grp_bits;
1895   } else {
1896     twopass->kf_group_bits = 0;
1897   }
1898   twopass->kf_group_bits = MAX(0, twopass->kf_group_bits);
1899
1900   // Reset the first pass file position.
1901   reset_fpf_position(twopass, start_position);
1902
1903   // Scan through the kf group collating various stats used to deteermine
1904   // how many bits to spend on it.
1905   decay_accumulator = 1.0;
1906   boost_score = 0.0;
1907   for (i = 0; i < rc->frames_to_key; ++i) {
1908     if (EOF == input_stats(twopass, &next_frame))
1909       break;
1910
1911     // Monitor for static sections.
1912     if ((next_frame.pcnt_inter - next_frame.pcnt_motion) <
1913             zero_motion_accumulator) {
1914       zero_motion_accumulator = (next_frame.pcnt_inter -
1915                                      next_frame.pcnt_motion);
1916     }
1917
1918     // For the first few frames collect data to decide kf boost.
1919     if (i <= (rc->max_gf_interval * 2)) {
1920       double r;
1921       if (next_frame.intra_error > twopass->kf_intra_err_min)
1922         r = (IIKFACTOR2 * next_frame.intra_error /
1923              DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1924       else
1925         r = (IIKFACTOR2 * twopass->kf_intra_err_min /
1926              DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1927
1928       if (r > RMAX)
1929         r = RMAX;
1930
1931       // How fast is prediction quality decaying.
1932       if (!detect_flash(twopass, 0)) {
1933         const double loop_decay_rate = get_prediction_decay_rate(&cpi->common,
1934                                                                  &next_frame);
1935         decay_accumulator *= loop_decay_rate;
1936         decay_accumulator = MAX(decay_accumulator, MIN_DECAY_FACTOR);
1937       }
1938
1939       boost_score += (decay_accumulator * r);
1940     }
1941   }
1942
1943   reset_fpf_position(twopass, start_position);
1944
1945   // Store the zero motion percentage
1946   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
1947
1948   // Calculate a section intra ratio used in setting max loop filter.
1949   twopass->section_intra_rating =
1950       calculate_section_intra_ratio(start_position, twopass->stats_in_end,
1951                                     rc->frames_to_key);
1952
1953   // Work out how many bits to allocate for the key frame itself.
1954   rc->kf_boost = (int)boost_score;
1955
1956   if (rc->kf_boost  < (rc->frames_to_key * 3))
1957     rc->kf_boost  = (rc->frames_to_key * 3);
1958   if (rc->kf_boost   < MIN_KF_BOOST)
1959     rc->kf_boost = MIN_KF_BOOST;
1960
1961   kf_bits = calculate_boost_bits((rc->frames_to_key - 1),
1962                                   rc->kf_boost, twopass->kf_group_bits);
1963
1964   twopass->kf_group_bits -= kf_bits;
1965
1966   // Save the bits to spend on the key frame.
1967   twopass->gf_group.bit_allocation[0] = kf_bits;
1968   twopass->gf_group.update_type[0] = KF_UPDATE;
1969   twopass->gf_group.rf_level[0] = KF_STD;
1970
1971   // Note the total error score of the kf group minus the key frame itself.
1972   twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
1973
1974   // Adjust the count of total modified error left.
1975   // The count of bits left is adjusted elsewhere based on real coded frame
1976   // sizes.
1977   twopass->modified_error_left -= kf_group_err;
1978 }
1979
1980 // For VBR...adjustment to the frame target based on error from previous frames
1981 void vbr_rate_correction(int * this_frame_target,
1982                          const int64_t vbr_bits_off_target) {
1983   int max_delta = (*this_frame_target * 15) / 100;
1984
1985   // vbr_bits_off_target > 0 means we have extra bits to spend
1986   if (vbr_bits_off_target > 0) {
1987     *this_frame_target +=
1988       (vbr_bits_off_target > max_delta) ? max_delta
1989                                         : (int)vbr_bits_off_target;
1990   } else {
1991     *this_frame_target -=
1992       (vbr_bits_off_target < -max_delta) ? max_delta
1993                                          : (int)-vbr_bits_off_target;
1994   }
1995 }
1996
1997 // Define the reference buffers that will be updated post encode.
1998 void configure_buffer_updates(VP9_COMP *cpi) {
1999   TWO_PASS *const twopass = &cpi->twopass;
2000
2001   cpi->rc.is_src_frame_alt_ref = 0;
2002   switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
2003     case KF_UPDATE:
2004       cpi->refresh_last_frame = 1;
2005       cpi->refresh_golden_frame = 1;
2006       cpi->refresh_alt_ref_frame = 1;
2007       break;
2008     case LF_UPDATE:
2009       cpi->refresh_last_frame = 1;
2010       cpi->refresh_golden_frame = 0;
2011       cpi->refresh_alt_ref_frame = 0;
2012       break;
2013     case GF_UPDATE:
2014       cpi->refresh_last_frame = 1;
2015       cpi->refresh_golden_frame = 1;
2016       cpi->refresh_alt_ref_frame = 0;
2017       break;
2018     case OVERLAY_UPDATE:
2019       cpi->refresh_last_frame = 0;
2020       cpi->refresh_golden_frame = 1;
2021       cpi->refresh_alt_ref_frame = 0;
2022       cpi->rc.is_src_frame_alt_ref = 1;
2023       break;
2024     case ARF_UPDATE:
2025       cpi->refresh_last_frame = 0;
2026       cpi->refresh_golden_frame = 0;
2027       cpi->refresh_alt_ref_frame = 1;
2028       break;
2029     default:
2030       assert(0);
2031   }
2032 }
2033
2034
2035 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
2036   VP9_COMMON *const cm = &cpi->common;
2037   RATE_CONTROL *const rc = &cpi->rc;
2038   TWO_PASS *const twopass = &cpi->twopass;
2039   int frames_left;
2040   FIRSTPASS_STATS this_frame;
2041   FIRSTPASS_STATS this_frame_copy;
2042
2043   int target_rate;
2044   LAYER_CONTEXT *lc = NULL;
2045   const int is_spatial_svc = (cpi->use_svc &&
2046                               cpi->svc.number_temporal_layers == 1);
2047   if (is_spatial_svc) {
2048     lc = &cpi->svc.layer_context[cpi->svc.spatial_layer_id];
2049     frames_left = (int)(twopass->total_stats.count -
2050                   lc->current_video_frame_in_layer);
2051   } else {
2052     frames_left = (int)(twopass->total_stats.count -
2053                   cm->current_video_frame);
2054   }
2055
2056   if (!twopass->stats_in)
2057     return;
2058
2059   // If this is an arf frame then we dont want to read the stats file or
2060   // advance the input pointer as we already have what we need.
2061   if (twopass->gf_group.update_type[twopass->gf_group.index] == ARF_UPDATE) {
2062     int target_rate;
2063     configure_buffer_updates(cpi);
2064     target_rate = twopass->gf_group.bit_allocation[twopass->gf_group.index];
2065     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2066     rc->base_frame_target = target_rate;
2067 #ifdef LONG_TERM_VBR_CORRECTION
2068     // Correction to rate target based on prior over or under shoot.
2069     if (cpi->oxcf.rc_mode == VPX_VBR)
2070       vbr_rate_correction(&target_rate, rc->vbr_bits_off_target);
2071 #endif
2072     vp9_rc_set_frame_target(cpi, target_rate);
2073     cm->frame_type = INTER_FRAME;
2074     return;
2075   }
2076
2077   vp9_clear_system_state();
2078
2079   if (is_spatial_svc && twopass->kf_intra_err_min == 0) {
2080     twopass->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
2081     twopass->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
2082   }
2083
2084   if (cpi->oxcf.rc_mode == VPX_Q) {
2085     twopass->active_worst_quality = cpi->oxcf.cq_level;
2086   } else if (cm->current_video_frame == 0 ||
2087              (is_spatial_svc && lc->current_video_frame_in_layer == 0)) {
2088     // Special case code for first frame.
2089     const int section_target_bandwidth = (int)(twopass->bits_left /
2090                                                frames_left);
2091     const int tmp_q = get_twopass_worst_quality(cpi, &twopass->total_left_stats,
2092                                                 section_target_bandwidth);
2093     twopass->active_worst_quality = tmp_q;
2094     rc->ni_av_qi = tmp_q;
2095     rc->avg_q = vp9_convert_qindex_to_q(tmp_q);
2096   }
2097   vp9_zero(this_frame);
2098   if (EOF == input_stats(twopass, &this_frame))
2099     return;
2100
2101   // Local copy of the current frame's first pass stats.
2102   this_frame_copy = this_frame;
2103
2104   // Keyframe and section processing.
2105   if (rc->frames_to_key == 0 ||
2106       (cpi->frame_flags & FRAMEFLAGS_KEY)) {
2107     // Define next KF group and assign bits to it.
2108     find_next_key_frame(cpi, &this_frame_copy);
2109   } else {
2110     cm->frame_type = INTER_FRAME;
2111   }
2112
2113   if (is_spatial_svc) {
2114     if (cpi->svc.spatial_layer_id == 0) {
2115       lc->is_key_frame = (cm->frame_type == KEY_FRAME);
2116     } else {
2117       cm->frame_type = INTER_FRAME;
2118       lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2119
2120       if (lc->is_key_frame) {
2121         cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2122       }
2123     }
2124   }
2125
2126   // Define a new GF/ARF group. (Should always enter here for key frames).
2127   if (rc->frames_till_gf_update_due == 0) {
2128     define_gf_group(cpi, &this_frame_copy);
2129
2130     if (twopass->gf_zeromotion_pct > 995) {
2131       // As long as max_thresh for encode breakout is small enough, it is ok
2132       // to enable it for show frame, i.e. set allow_encode_breakout to
2133       // ENCODE_BREAKOUT_LIMITED.
2134       if (!cm->show_frame)
2135         cpi->allow_encode_breakout = ENCODE_BREAKOUT_DISABLED;
2136       else
2137         cpi->allow_encode_breakout = ENCODE_BREAKOUT_LIMITED;
2138     }
2139
2140     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2141     cpi->refresh_golden_frame = 1;
2142   }
2143
2144   {
2145     FIRSTPASS_STATS next_frame;
2146     if (lookup_next_frame_stats(twopass, &next_frame) != EOF) {
2147       twopass->next_iiratio = (int)(next_frame.intra_error /
2148                                  DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2149     }
2150   }
2151
2152   configure_buffer_updates(cpi);
2153
2154   target_rate = twopass->gf_group.bit_allocation[twopass->gf_group.index];
2155   if (cpi->common.frame_type == KEY_FRAME)
2156     target_rate = vp9_rc_clamp_iframe_target_size(cpi, target_rate);
2157   else
2158     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2159
2160   rc->base_frame_target = target_rate;
2161 #ifdef LONG_TERM_VBR_CORRECTION
2162   // Correction to rate target based on prior over or under shoot.
2163   if (cpi->oxcf.rc_mode == VPX_VBR)
2164     vbr_rate_correction(&target_rate, rc->vbr_bits_off_target);
2165 #endif
2166   vp9_rc_set_frame_target(cpi, target_rate);
2167
2168   // Update the total stats remaining structure.
2169   subtract_stats(&twopass->total_left_stats, &this_frame);
2170 }
2171
2172 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
2173   TWO_PASS *const twopass = &cpi->twopass;
2174   RATE_CONTROL *const rc = &cpi->rc;
2175 #ifdef LONG_TERM_VBR_CORRECTION
2176   // In this experimental mode, the VBR correction is done exclusively through
2177   // rc->vbr_bits_off_target. Based on the sign of this value, a limited %
2178   // adjustment is made to the target rate of subsequent frames, to try and
2179   // push it back towards 0. This mode is less likely to suffer from
2180   // extreme behaviour at the end of a clip or group of frames.
2181   const int bits_used = rc->base_frame_target;
2182   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
2183 #else
2184   // In this mode, VBR correction is acheived by altering bits_left,
2185   // kf_group_bits & gf_group_bits to reflect any deviation from the target
2186   // rate in this frame. This alters the allocation of bits to the
2187   // remaning frames in the group / clip.
2188   //
2189   // This method can give rise to unstable behaviour near the end of a clip
2190   // or kf/gf group of frames where any accumulated error is corrected over an
2191   // ever decreasing number of frames. Hence we change the balance of target
2192   // vs. actual bitrate gradually as we progress towards the end of the
2193   // sequence in order to mitigate this effect.
2194   const double progress =
2195       (double)(twopass->stats_in - twopass->stats_in_start) /
2196               (twopass->stats_in_end - twopass->stats_in_start);
2197   const int bits_used = (int)(progress * rc->this_frame_target +
2198                              (1.0 - progress) * rc->projected_frame_size);
2199 #endif
2200
2201   twopass->bits_left = MAX(twopass->bits_left - bits_used, 0);
2202
2203 #ifdef LONG_TERM_VBR_CORRECTION
2204   if (cpi->common.frame_type != KEY_FRAME &&
2205       !vp9_is_upper_layer_key_frame(cpi)) {
2206 #else
2207   if (cpi->common.frame_type == KEY_FRAME ||
2208       vp9_is_upper_layer_key_frame(cpi)) {
2209     // For key frames kf_group_bits already had the target bits subtracted out.
2210     // So now update to the correct value based on the actual bits used.
2211     twopass->kf_group_bits += rc->this_frame_target - bits_used;
2212   } else {
2213 #endif
2214     twopass->kf_group_bits -= bits_used;
2215   }
2216   twopass->kf_group_bits = MAX(twopass->kf_group_bits, 0);
2217
2218   // Increment the gf group index ready for the next frame.
2219   ++twopass->gf_group.index;
2220 }