]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_firstpass.c
vp9_aq_complexity.c: remove unused macros
[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_dsp_rtcd.h"
16 #include "./vpx_scale_rtcd.h"
17
18 #include "vpx_dsp/vpx_dsp_common.h"
19 #include "vpx_mem/vpx_mem.h"
20 #include "vpx_ports/mem.h"
21 #include "vpx_ports/system_state.h"
22 #include "vpx_scale/vpx_scale.h"
23 #include "vpx_scale/yv12config.h"
24
25 #include "vp9/common/vp9_entropymv.h"
26 #include "vp9/common/vp9_quant_common.h"
27 #include "vp9/common/vp9_reconinter.h"  // vp9_setup_dst_planes()
28 #include "vp9/encoder/vp9_aq_variance.h"
29 #include "vp9/encoder/vp9_block.h"
30 #include "vp9/encoder/vp9_encodeframe.h"
31 #include "vp9/encoder/vp9_encodemb.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_encoder.h"
34 #include "vp9/encoder/vp9_extend.h"
35 #include "vp9/encoder/vp9_firstpass.h"
36 #include "vp9/encoder/vp9_mcomp.h"
37 #include "vp9/encoder/vp9_quantize.h"
38 #include "vp9/encoder/vp9_rd.h"
39 #include "vpx_dsp/variance.h"
40
41 #define OUTPUT_FPF          0
42 #define ARF_STATS_OUTPUT    0
43
44 #define GROUP_ADAPTIVE_MAXQ 1
45
46 #define BOOST_BREAKOUT      12.5
47 #define BOOST_FACTOR        12.5
48 #define ERR_DIVISOR         128.0
49 #define FACTOR_PT_LOW       0.70
50 #define FACTOR_PT_HIGH      0.90
51 #define FIRST_PASS_Q        10.0
52 #define GF_MAX_BOOST        96.0
53 #define INTRA_MODE_PENALTY  1024
54 #define KF_MAX_BOOST        128.0
55 #define MIN_ARF_GF_BOOST    240
56 #define MIN_DECAY_FACTOR    0.01
57 #define MIN_KF_BOOST        300
58 #define NEW_MV_MODE_PENALTY 32
59 #define SVC_FACTOR_PT_LOW   0.45
60 #define DARK_THRESH         64
61 #define DEFAULT_GRP_WEIGHT  1.0
62 #define RC_FACTOR_MIN       0.75
63 #define RC_FACTOR_MAX       1.75
64
65
66 #define NCOUNT_INTRA_THRESH 8192
67 #define NCOUNT_INTRA_FACTOR 3
68 #define NCOUNT_FRAME_II_THRESH 5.0
69
70 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x) - 0.000001 : (x) + 0.000001)
71
72 #if ARF_STATS_OUTPUT
73 unsigned int arf_count = 0;
74 #endif
75
76 // Resets the first pass file to the given position using a relative seek from
77 // the current position.
78 static void reset_fpf_position(TWO_PASS *p,
79                                const FIRSTPASS_STATS *position) {
80   p->stats_in = position;
81 }
82
83 // Read frame stats at an offset from the current position.
84 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
85   if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
86       (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
87     return NULL;
88   }
89
90   return &p->stats_in[offset];
91 }
92
93 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
94   if (p->stats_in >= p->stats_in_end)
95     return EOF;
96
97   *fps = *p->stats_in;
98   ++p->stats_in;
99   return 1;
100 }
101
102 static void output_stats(FIRSTPASS_STATS *stats,
103                          struct vpx_codec_pkt_list *pktlist) {
104   struct vpx_codec_cx_pkt pkt;
105   pkt.kind = VPX_CODEC_STATS_PKT;
106   pkt.data.twopass_stats.buf = stats;
107   pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
108   vpx_codec_pkt_list_add(pktlist, &pkt);
109
110 // TEMP debug code
111 #if OUTPUT_FPF
112   {
113     FILE *fpfile;
114     fpfile = fopen("firstpass.stt", "a");
115
116     fprintf(fpfile, "%12.0lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf"
117             "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
118             "%12.4lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf\n",
119             stats->frame,
120             stats->weight,
121             stats->intra_error,
122             stats->coded_error,
123             stats->sr_coded_error,
124             stats->pcnt_inter,
125             stats->pcnt_motion,
126             stats->pcnt_second_ref,
127             stats->pcnt_neutral,
128             stats->intra_skip_pct,
129             stats->inactive_zone_rows,
130             stats->inactive_zone_cols,
131             stats->MVr,
132             stats->mvr_abs,
133             stats->MVc,
134             stats->mvc_abs,
135             stats->MVrv,
136             stats->MVcv,
137             stats->mv_in_out_count,
138             stats->new_mv_count,
139             stats->count,
140             stats->duration);
141     fclose(fpfile);
142   }
143 #endif
144 }
145
146 #if CONFIG_FP_MB_STATS
147 static void output_fpmb_stats(uint8_t *this_frame_mb_stats, VP9_COMMON *cm,
148                          struct vpx_codec_pkt_list *pktlist) {
149   struct vpx_codec_cx_pkt pkt;
150   pkt.kind = VPX_CODEC_FPMB_STATS_PKT;
151   pkt.data.firstpass_mb_stats.buf = this_frame_mb_stats;
152   pkt.data.firstpass_mb_stats.sz = cm->initial_mbs * sizeof(uint8_t);
153   vpx_codec_pkt_list_add(pktlist, &pkt);
154 }
155 #endif
156
157 static void zero_stats(FIRSTPASS_STATS *section) {
158   section->frame = 0.0;
159   section->weight = 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->intra_skip_pct = 0.0;
168   section->inactive_zone_rows = 0.0;
169   section->inactive_zone_cols = 0.0;
170   section->MVr = 0.0;
171   section->mvr_abs     = 0.0;
172   section->MVc        = 0.0;
173   section->mvc_abs     = 0.0;
174   section->MVrv       = 0.0;
175   section->MVcv       = 0.0;
176   section->mv_in_out_count  = 0.0;
177   section->new_mv_count = 0.0;
178   section->count      = 0.0;
179   section->duration   = 1.0;
180   section->spatial_layer_id = 0;
181 }
182
183 static void accumulate_stats(FIRSTPASS_STATS *section,
184                              const FIRSTPASS_STATS *frame) {
185   section->frame += frame->frame;
186   section->weight += frame->weight;
187   section->spatial_layer_id = frame->spatial_layer_id;
188   section->intra_error += frame->intra_error;
189   section->coded_error += frame->coded_error;
190   section->sr_coded_error += frame->sr_coded_error;
191   section->pcnt_inter  += frame->pcnt_inter;
192   section->pcnt_motion += frame->pcnt_motion;
193   section->pcnt_second_ref += frame->pcnt_second_ref;
194   section->pcnt_neutral += frame->pcnt_neutral;
195   section->intra_skip_pct += frame->intra_skip_pct;
196   section->inactive_zone_rows += frame->inactive_zone_rows;
197   section->inactive_zone_cols += frame->inactive_zone_cols;
198   section->MVr += frame->MVr;
199   section->mvr_abs     += frame->mvr_abs;
200   section->MVc        += frame->MVc;
201   section->mvc_abs     += frame->mvc_abs;
202   section->MVrv       += frame->MVrv;
203   section->MVcv       += frame->MVcv;
204   section->mv_in_out_count  += frame->mv_in_out_count;
205   section->new_mv_count += frame->new_mv_count;
206   section->count      += frame->count;
207   section->duration   += frame->duration;
208 }
209
210 static void subtract_stats(FIRSTPASS_STATS *section,
211                            const FIRSTPASS_STATS *frame) {
212   section->frame -= frame->frame;
213   section->weight -= frame->weight;
214   section->intra_error -= frame->intra_error;
215   section->coded_error -= frame->coded_error;
216   section->sr_coded_error -= frame->sr_coded_error;
217   section->pcnt_inter  -= frame->pcnt_inter;
218   section->pcnt_motion -= frame->pcnt_motion;
219   section->pcnt_second_ref -= frame->pcnt_second_ref;
220   section->pcnt_neutral -= frame->pcnt_neutral;
221   section->intra_skip_pct -= frame->intra_skip_pct;
222   section->inactive_zone_rows -= frame->inactive_zone_rows;
223   section->inactive_zone_cols -= frame->inactive_zone_cols;
224   section->MVr -= frame->MVr;
225   section->mvr_abs     -= frame->mvr_abs;
226   section->MVc        -= frame->MVc;
227   section->mvc_abs     -= frame->mvc_abs;
228   section->MVrv       -= frame->MVrv;
229   section->MVcv       -= frame->MVcv;
230   section->mv_in_out_count  -= frame->mv_in_out_count;
231   section->new_mv_count -= frame->new_mv_count;
232   section->count      -= frame->count;
233   section->duration   -= frame->duration;
234 }
235
236 // Calculate an active area of the image that discounts formatting
237 // bars and partially discounts other 0 energy areas.
238 #define MIN_ACTIVE_AREA 0.5
239 #define MAX_ACTIVE_AREA 1.0
240 static double calculate_active_area(const VP9_COMP *cpi,
241                                     const FIRSTPASS_STATS *this_frame) {
242   double active_pct;
243
244   active_pct = 1.0 -
245     ((this_frame->intra_skip_pct / 2) +
246      ((this_frame->inactive_zone_rows * 2) / (double)cpi->common.mb_rows));
247   return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
248 }
249
250 // Calculate a modified Error used in distributing bits between easier and
251 // harder frames.
252 #define ACT_AREA_CORRECTION 0.5
253 static double calculate_modified_err(const VP9_COMP *cpi,
254                                      const TWO_PASS *twopass,
255                                      const VP9EncoderConfig *oxcf,
256                                      const FIRSTPASS_STATS *this_frame) {
257   const FIRSTPASS_STATS *const stats = &twopass->total_stats;
258   const double av_weight = stats->weight / stats->count;
259   const double av_err = (stats->coded_error * av_weight) / stats->count;
260   double modified_error =
261     av_err * pow(this_frame->coded_error * this_frame->weight /
262                  DOUBLE_DIVIDE_CHECK(av_err), oxcf->two_pass_vbrbias / 100.0);
263
264   // Correction for active area. Frames with a reduced active area
265   // (eg due to formatting bars) have a higher error per mb for the
266   // remaining active MBs. The correction here assumes that coding
267   // 0.5N blocks of complexity 2X is a little easier than coding N
268   // blocks of complexity X.
269   modified_error *=
270     pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);
271
272   return fclamp(modified_error,
273                 twopass->modified_error_min, twopass->modified_error_max);
274 }
275
276 // This function returns the maximum target rate per frame.
277 static int frame_max_bits(const RATE_CONTROL *rc,
278                           const VP9EncoderConfig *oxcf) {
279   int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
280                           (int64_t)oxcf->two_pass_vbrmax_section) / 100;
281   if (max_bits < 0)
282     max_bits = 0;
283   else if (max_bits > rc->max_frame_bandwidth)
284     max_bits = rc->max_frame_bandwidth;
285
286   return (int)max_bits;
287 }
288
289 void vp9_init_first_pass(VP9_COMP *cpi) {
290   zero_stats(&cpi->twopass.total_stats);
291 }
292
293 void vp9_end_first_pass(VP9_COMP *cpi) {
294   if (is_two_pass_svc(cpi)) {
295     int i;
296     for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
297       output_stats(&cpi->svc.layer_context[i].twopass.total_stats,
298                    cpi->output_pkt_list);
299     }
300   } else {
301     output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
302   }
303 }
304
305 static vpx_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
306   switch (bsize) {
307     case BLOCK_8X8:
308       return vpx_mse8x8;
309     case BLOCK_16X8:
310       return vpx_mse16x8;
311     case BLOCK_8X16:
312       return vpx_mse8x16;
313     default:
314       return vpx_mse16x16;
315   }
316 }
317
318 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
319                                          const struct buf_2d *src,
320                                          const struct buf_2d *ref) {
321   unsigned int sse;
322   const vpx_variance_fn_t fn = get_block_variance_fn(bsize);
323   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
324   return sse;
325 }
326
327 #if CONFIG_VP9_HIGHBITDEPTH
328 static vpx_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
329                                                       int bd) {
330   switch (bd) {
331     default:
332       switch (bsize) {
333         case BLOCK_8X8:
334           return vpx_highbd_8_mse8x8;
335         case BLOCK_16X8:
336           return vpx_highbd_8_mse16x8;
337         case BLOCK_8X16:
338           return vpx_highbd_8_mse8x16;
339         default:
340           return vpx_highbd_8_mse16x16;
341       }
342       break;
343     case 10:
344       switch (bsize) {
345         case BLOCK_8X8:
346           return vpx_highbd_10_mse8x8;
347         case BLOCK_16X8:
348           return vpx_highbd_10_mse16x8;
349         case BLOCK_8X16:
350           return vpx_highbd_10_mse8x16;
351         default:
352           return vpx_highbd_10_mse16x16;
353       }
354       break;
355     case 12:
356       switch (bsize) {
357         case BLOCK_8X8:
358           return vpx_highbd_12_mse8x8;
359         case BLOCK_16X8:
360           return vpx_highbd_12_mse16x8;
361         case BLOCK_8X16:
362           return vpx_highbd_12_mse8x16;
363         default:
364           return vpx_highbd_12_mse16x16;
365       }
366       break;
367   }
368 }
369
370 static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
371                                                 const struct buf_2d *src,
372                                                 const struct buf_2d *ref,
373                                                 int bd) {
374   unsigned int sse;
375   const vpx_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
376   fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
377   return sse;
378 }
379 #endif  // CONFIG_VP9_HIGHBITDEPTH
380
381 // Refine the motion search range according to the frame dimension
382 // for first pass test.
383 static int get_search_range(const VP9_COMP *cpi) {
384   int sr = 0;
385   const int dim = VPXMIN(cpi->initial_width, cpi->initial_height);
386
387   while ((dim << sr) < MAX_FULL_PEL_VAL)
388     ++sr;
389   return sr;
390 }
391
392 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
393                                      const MV *ref_mv, MV *best_mv,
394                                      int *best_motion_err) {
395   MACROBLOCKD *const xd = &x->e_mbd;
396   MV tmp_mv = {0, 0};
397   MV ref_mv_full = {ref_mv->row >> 3, ref_mv->col >> 3};
398   int num00, tmp_err, n;
399   const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
400   vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
401   const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
402
403   int step_param = 3;
404   int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
405   const int sr = get_search_range(cpi);
406   step_param += sr;
407   further_steps -= sr;
408
409   // Override the default variance function to use MSE.
410   v_fn_ptr.vf = get_block_variance_fn(bsize);
411 #if CONFIG_VP9_HIGHBITDEPTH
412   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
413     v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
414   }
415 #endif  // CONFIG_VP9_HIGHBITDEPTH
416
417   // Center the initial step/diamond search on best mv.
418   tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
419                                     step_param,
420                                     x->sadperbit16, &num00, &v_fn_ptr, ref_mv);
421   if (tmp_err < INT_MAX)
422     tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
423   if (tmp_err < INT_MAX - new_mv_mode_penalty)
424     tmp_err += new_mv_mode_penalty;
425
426   if (tmp_err < *best_motion_err) {
427     *best_motion_err = tmp_err;
428     *best_mv = tmp_mv;
429   }
430
431   // Carry out further step/diamond searches as necessary.
432   n = num00;
433   num00 = 0;
434
435   while (n < further_steps) {
436     ++n;
437
438     if (num00) {
439       --num00;
440     } else {
441       tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
442                                         step_param + n, x->sadperbit16,
443                                         &num00, &v_fn_ptr, ref_mv);
444       if (tmp_err < INT_MAX)
445         tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
446       if (tmp_err < INT_MAX - new_mv_mode_penalty)
447         tmp_err += new_mv_mode_penalty;
448
449       if (tmp_err < *best_motion_err) {
450         *best_motion_err = tmp_err;
451         *best_mv = tmp_mv;
452       }
453     }
454   }
455 }
456
457 static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
458   if (2 * mb_col + 1 < cm->mi_cols) {
459     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16
460                                         : BLOCK_16X8;
461   } else {
462     return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16
463                                         : BLOCK_8X8;
464   }
465 }
466
467 static int find_fp_qindex(vpx_bit_depth_t bit_depth) {
468   int i;
469
470   for (i = 0; i < QINDEX_RANGE; ++i)
471     if (vp9_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q)
472       break;
473
474   if (i == QINDEX_RANGE)
475     i--;
476
477   return i;
478 }
479
480 static void set_first_pass_params(VP9_COMP *cpi) {
481   VP9_COMMON *const cm = &cpi->common;
482   if (!cpi->refresh_alt_ref_frame &&
483       (cm->current_video_frame == 0 ||
484        (cpi->frame_flags & FRAMEFLAGS_KEY))) {
485     cm->frame_type = KEY_FRAME;
486   } else {
487     cm->frame_type = INTER_FRAME;
488   }
489   // Do not use periodic key frames.
490   cpi->rc.frames_to_key = INT_MAX;
491 }
492
493 #define UL_INTRA_THRESH 50
494 #define INVALID_ROW -1
495 void vp9_first_pass(VP9_COMP *cpi, const struct lookahead_entry *source) {
496   int mb_row, mb_col;
497   MACROBLOCK *const x = &cpi->td.mb;
498   VP9_COMMON *const cm = &cpi->common;
499   MACROBLOCKD *const xd = &x->e_mbd;
500   TileInfo tile;
501   struct macroblock_plane *const p = x->plane;
502   struct macroblockd_plane *const pd = xd->plane;
503   const PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
504   int i;
505
506   int recon_yoffset, recon_uvoffset;
507   int64_t intra_error = 0;
508   int64_t coded_error = 0;
509   int64_t sr_coded_error = 0;
510
511   int sum_mvr = 0, sum_mvc = 0;
512   int sum_mvr_abs = 0, sum_mvc_abs = 0;
513   int64_t sum_mvrs = 0, sum_mvcs = 0;
514   int mvcount = 0;
515   int intercount = 0;
516   int second_ref_count = 0;
517   const int intrapenalty = INTRA_MODE_PENALTY;
518   double neutral_count;
519   int intra_skip_count = 0;
520   int image_data_start_row = INVALID_ROW;
521   int new_mv_count = 0;
522   int sum_in_vectors = 0;
523   MV lastmv = {0, 0};
524   TWO_PASS *twopass = &cpi->twopass;
525   const MV zero_mv = {0, 0};
526   int recon_y_stride, recon_uv_stride, uv_mb_height;
527
528   YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
529   YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
530   YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
531   const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
532
533   LAYER_CONTEXT *const lc = is_two_pass_svc(cpi) ?
534         &cpi->svc.layer_context[cpi->svc.spatial_layer_id] : NULL;
535   double intra_factor;
536   double brightness_factor;
537   BufferPool *const pool = cm->buffer_pool;
538
539   // First pass code requires valid last and new frame buffers.
540   assert(new_yv12 != NULL);
541   assert((lc != NULL) || frame_is_intra_only(cm) || (lst_yv12 != NULL));
542
543 #if CONFIG_FP_MB_STATS
544   if (cpi->use_fp_mb_stats) {
545     vp9_zero_array(cpi->twopass.frame_mb_stats_buf, cm->initial_mbs);
546   }
547 #endif
548
549   vpx_clear_system_state();
550
551   intra_factor = 0.0;
552   brightness_factor = 0.0;
553   neutral_count = 0.0;
554
555   set_first_pass_params(cpi);
556   vp9_set_quantizer(cm, find_fp_qindex(cm->bit_depth));
557
558   if (lc != NULL) {
559     twopass = &lc->twopass;
560
561     cpi->lst_fb_idx = cpi->svc.spatial_layer_id;
562     cpi->ref_frame_flags = VP9_LAST_FLAG;
563
564     if (cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id <
565         REF_FRAMES) {
566       cpi->gld_fb_idx =
567           cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id;
568       cpi->ref_frame_flags |= VP9_GOLD_FLAG;
569       cpi->refresh_golden_frame = (lc->current_video_frame_in_layer == 0);
570     } else {
571       cpi->refresh_golden_frame = 0;
572     }
573
574     if (lc->current_video_frame_in_layer == 0)
575       cpi->ref_frame_flags = 0;
576
577     vp9_scale_references(cpi);
578
579     // Use either last frame or alt frame for motion search.
580     if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
581       first_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
582       if (first_ref_buf == NULL)
583         first_ref_buf = get_ref_frame_buffer(cpi, LAST_FRAME);
584     }
585
586     if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
587       gld_yv12 = vp9_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
588       if (gld_yv12 == NULL) {
589         gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
590       }
591     } else {
592       gld_yv12 = NULL;
593     }
594
595     set_ref_ptrs(cm, xd,
596                  (cpi->ref_frame_flags & VP9_LAST_FLAG) ? LAST_FRAME: NONE,
597                  (cpi->ref_frame_flags & VP9_GOLD_FLAG) ? GOLDEN_FRAME : NONE);
598
599     cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
600                                         &cpi->scaled_source, 0);
601   }
602
603   vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
604
605   vp9_setup_src_planes(x, cpi->Source, 0, 0);
606   vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
607
608   if (!frame_is_intra_only(cm)) {
609     vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
610   }
611
612   xd->mi = cm->mi_grid_visible;
613   xd->mi[0] = cm->mi;
614
615   vp9_frame_init_quantizer(cpi);
616
617   for (i = 0; i < MAX_MB_PLANE; ++i) {
618     p[i].coeff = ctx->coeff_pbuf[i][1];
619     p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
620     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
621     p[i].eobs = ctx->eobs_pbuf[i][1];
622   }
623   x->skip_recode = 0;
624
625   vp9_init_mv_probs(cm);
626   vp9_initialize_rd_consts(cpi);
627
628   // Tiling is ignored in the first pass.
629   vp9_tile_init(&tile, cm, 0, 0);
630
631   recon_y_stride = new_yv12->y_stride;
632   recon_uv_stride = new_yv12->uv_stride;
633   uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
634
635   for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
636     MV best_ref_mv = {0, 0};
637
638     // Reset above block coeffs.
639     recon_yoffset = (mb_row * recon_y_stride * 16);
640     recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height);
641
642     // Set up limit values for motion vectors to prevent them extending
643     // outside the UMV borders.
644     x->mv_row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
645     x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16)
646                     + BORDER_MV_PIXELS_B16;
647
648     for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
649       int this_error;
650       const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
651       const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
652       double log_intra;
653       int level_sample;
654
655 #if CONFIG_FP_MB_STATS
656       const int mb_index = mb_row * cm->mb_cols + mb_col;
657 #endif
658
659       vpx_clear_system_state();
660
661       xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
662       xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
663       xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
664       xd->mi[0]->sb_type = bsize;
665       xd->mi[0]->ref_frame[0] = INTRA_FRAME;
666       set_mi_row_col(xd, &tile,
667                      mb_row << 1, num_8x8_blocks_high_lookup[bsize],
668                      mb_col << 1, num_8x8_blocks_wide_lookup[bsize],
669                      cm->mi_rows, cm->mi_cols);
670
671       // Do intra 16x16 prediction.
672       x->skip_encode = 0;
673       xd->mi[0]->mode = DC_PRED;
674       xd->mi[0]->tx_size = use_dc_pred ?
675          (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
676       vp9_encode_intra_block_plane(x, bsize, 0);
677       this_error = vpx_get_mb_ss(x->plane[0].src_diff);
678
679       // Keep a record of blocks that have almost no intra error residual
680       // (i.e. are in effect completely flat and untextured in the intra
681       // domain). In natural videos this is uncommon, but it is much more
682       // common in animations, graphics and screen content, so may be used
683       // as a signal to detect these types of content.
684       if (this_error < UL_INTRA_THRESH) {
685         ++intra_skip_count;
686       } else if ((mb_col > 0) && (image_data_start_row == INVALID_ROW)) {
687         image_data_start_row = mb_row;
688       }
689
690 #if CONFIG_VP9_HIGHBITDEPTH
691       if (cm->use_highbitdepth) {
692         switch (cm->bit_depth) {
693           case VPX_BITS_8:
694             break;
695           case VPX_BITS_10:
696             this_error >>= 4;
697             break;
698           case VPX_BITS_12:
699             this_error >>= 8;
700             break;
701           default:
702             assert(0 && "cm->bit_depth should be VPX_BITS_8, "
703                         "VPX_BITS_10 or VPX_BITS_12");
704             return;
705         }
706       }
707 #endif  // CONFIG_VP9_HIGHBITDEPTH
708
709       vpx_clear_system_state();
710       log_intra = log(this_error + 1.0);
711       if (log_intra < 10.0)
712         intra_factor += 1.0 + ((10.0 - log_intra) * 0.05);
713       else
714         intra_factor += 1.0;
715
716 #if CONFIG_VP9_HIGHBITDEPTH
717       if (cm->use_highbitdepth)
718         level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
719       else
720         level_sample = x->plane[0].src.buf[0];
721 #else
722       level_sample = x->plane[0].src.buf[0];
723 #endif
724       if ((level_sample < DARK_THRESH) && (log_intra < 9.0))
725         brightness_factor += 1.0 + (0.01 * (DARK_THRESH - level_sample));
726       else
727         brightness_factor += 1.0;
728
729       // Intrapenalty below deals with situations where the intra and inter
730       // error scores are very low (e.g. a plain black frame).
731       // We do not have special cases in first pass for 0,0 and nearest etc so
732       // all inter modes carry an overhead cost estimate for the mv.
733       // When the error score is very low this causes us to pick all or lots of
734       // INTRA modes and throw lots of key frames.
735       // This penalty adds a cost matching that of a 0,0 mv to the intra case.
736       this_error += intrapenalty;
737
738       // Accumulate the intra error.
739       intra_error += (int64_t)this_error;
740
741 #if CONFIG_FP_MB_STATS
742       if (cpi->use_fp_mb_stats) {
743         // initialization
744         cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
745       }
746 #endif
747
748       // Set up limit values for motion vectors to prevent them extending
749       // outside the UMV borders.
750       x->mv_col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
751       x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
752
753       // Other than for the first frame do a motion search.
754       if ((lc == NULL && cm->current_video_frame > 0) ||
755           (lc != NULL && lc->current_video_frame_in_layer > 0)) {
756         int tmp_err, motion_error, raw_motion_error;
757         // Assume 0,0 motion with no mv overhead.
758         MV mv = {0, 0} , tmp_mv = {0, 0};
759         struct buf_2d unscaled_last_source_buf_2d;
760
761         xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
762 #if CONFIG_VP9_HIGHBITDEPTH
763         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
764           motion_error = highbd_get_prediction_error(
765               bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
766         } else {
767           motion_error = get_prediction_error(
768               bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
769         }
770 #else
771         motion_error = get_prediction_error(
772             bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
773 #endif  // CONFIG_VP9_HIGHBITDEPTH
774
775         // Compute the motion error of the 0,0 motion using the last source
776         // frame as the reference. Skip the further motion search on
777         // reconstructed frame if this error is small.
778         unscaled_last_source_buf_2d.buf =
779             cpi->unscaled_last_source->y_buffer + recon_yoffset;
780         unscaled_last_source_buf_2d.stride =
781             cpi->unscaled_last_source->y_stride;
782 #if CONFIG_VP9_HIGHBITDEPTH
783         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
784           raw_motion_error = highbd_get_prediction_error(
785               bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
786         } else {
787           raw_motion_error = get_prediction_error(
788               bsize, &x->plane[0].src, &unscaled_last_source_buf_2d);
789         }
790 #else
791         raw_motion_error = get_prediction_error(
792             bsize, &x->plane[0].src, &unscaled_last_source_buf_2d);
793 #endif  // CONFIG_VP9_HIGHBITDEPTH
794
795         // TODO(pengchong): Replace the hard-coded threshold
796         if (raw_motion_error > 25 || lc != NULL) {
797           // Test last reference frame using the previous best mv as the
798           // starting point (best reference) for the search.
799           first_pass_motion_search(cpi, x, &best_ref_mv, &mv, &motion_error);
800
801           // If the current best reference mv is not centered on 0,0 then do a
802           // 0,0 based search as well.
803           if (!is_zero_mv(&best_ref_mv)) {
804             tmp_err = INT_MAX;
805             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &tmp_err);
806
807             if (tmp_err < motion_error) {
808               motion_error = tmp_err;
809               mv = tmp_mv;
810             }
811           }
812
813           // Search in an older reference frame.
814           if (((lc == NULL && cm->current_video_frame > 1) ||
815                (lc != NULL && lc->current_video_frame_in_layer > 1))
816               && gld_yv12 != NULL) {
817             // Assume 0,0 motion with no mv overhead.
818             int gf_motion_error;
819
820             xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
821 #if CONFIG_VP9_HIGHBITDEPTH
822             if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
823               gf_motion_error = highbd_get_prediction_error(
824                   bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
825             } else {
826               gf_motion_error = get_prediction_error(
827                   bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
828             }
829 #else
830             gf_motion_error = get_prediction_error(
831                 bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
832 #endif  // CONFIG_VP9_HIGHBITDEPTH
833
834             first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv,
835                                      &gf_motion_error);
836
837             if (gf_motion_error < motion_error && gf_motion_error < this_error)
838               ++second_ref_count;
839
840             // Reset to last frame as reference buffer.
841             xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
842             xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
843             xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
844
845             // In accumulating a score for the older reference frame take the
846             // best of the motion predicted score and the intra coded error
847             // (just as will be done for) accumulation of "coded_error" for
848             // the last frame.
849             if (gf_motion_error < this_error)
850               sr_coded_error += gf_motion_error;
851             else
852               sr_coded_error += this_error;
853           } else {
854             sr_coded_error += motion_error;
855           }
856         } else {
857           sr_coded_error += motion_error;
858         }
859
860         // Start by assuming that intra mode is best.
861         best_ref_mv.row = 0;
862         best_ref_mv.col = 0;
863
864 #if CONFIG_FP_MB_STATS
865         if (cpi->use_fp_mb_stats) {
866           // intra predication statistics
867           cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
868           cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_DCINTRA_MASK;
869           cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
870           if (this_error > FPMB_ERROR_LARGE_TH) {
871             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_LARGE_MASK;
872           } else if (this_error < FPMB_ERROR_SMALL_TH) {
873             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_SMALL_MASK;
874           }
875         }
876 #endif
877
878         if (motion_error <= this_error) {
879           vpx_clear_system_state();
880
881           // Keep a count of cases where the inter and intra were very close
882           // and very low. This helps with scene cut detection for example in
883           // cropped clips with black bars at the sides or top and bottom.
884           if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
885               (this_error < (2 * intrapenalty))) {
886             neutral_count += 1.0;
887           // Also track cases where the intra is not much worse than the inter
888           // and use this in limiting the GF/arf group length.
889           } else if ((this_error > NCOUNT_INTRA_THRESH) &&
890                      (this_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
891             neutral_count += (double)motion_error /
892                              DOUBLE_DIVIDE_CHECK((double)this_error);
893           }
894
895           mv.row *= 8;
896           mv.col *= 8;
897           this_error = motion_error;
898           xd->mi[0]->mode = NEWMV;
899           xd->mi[0]->mv[0].as_mv = mv;
900           xd->mi[0]->tx_size = TX_4X4;
901           xd->mi[0]->ref_frame[0] = LAST_FRAME;
902           xd->mi[0]->ref_frame[1] = NONE;
903           vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
904           vp9_encode_sby_pass1(x, bsize);
905           sum_mvr += mv.row;
906           sum_mvr_abs += abs(mv.row);
907           sum_mvc += mv.col;
908           sum_mvc_abs += abs(mv.col);
909           sum_mvrs += mv.row * mv.row;
910           sum_mvcs += mv.col * mv.col;
911           ++intercount;
912
913           best_ref_mv = mv;
914
915 #if CONFIG_FP_MB_STATS
916           if (cpi->use_fp_mb_stats) {
917             // inter predication statistics
918             cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
919             cpi->twopass.frame_mb_stats_buf[mb_index] &= ~FPMB_DCINTRA_MASK;
920             cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
921             if (this_error > FPMB_ERROR_LARGE_TH) {
922               cpi->twopass.frame_mb_stats_buf[mb_index] |=
923                   FPMB_ERROR_LARGE_MASK;
924             } else if (this_error < FPMB_ERROR_SMALL_TH) {
925               cpi->twopass.frame_mb_stats_buf[mb_index] |=
926                   FPMB_ERROR_SMALL_MASK;
927             }
928           }
929 #endif
930
931           if (!is_zero_mv(&mv)) {
932             ++mvcount;
933
934 #if CONFIG_FP_MB_STATS
935             if (cpi->use_fp_mb_stats) {
936               cpi->twopass.frame_mb_stats_buf[mb_index] &=
937                   ~FPMB_MOTION_ZERO_MASK;
938               // check estimated motion direction
939               if (mv.as_mv.col > 0 && mv.as_mv.col >= abs(mv.as_mv.row)) {
940                 // right direction
941                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
942                     FPMB_MOTION_RIGHT_MASK;
943               } else if (mv.as_mv.row < 0 &&
944                          abs(mv.as_mv.row) >= abs(mv.as_mv.col)) {
945                 // up direction
946                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
947                     FPMB_MOTION_UP_MASK;
948               } else if (mv.as_mv.col < 0 &&
949                          abs(mv.as_mv.col) >= abs(mv.as_mv.row)) {
950                 // left direction
951                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
952                     FPMB_MOTION_LEFT_MASK;
953               } else {
954                 // down direction
955                 cpi->twopass.frame_mb_stats_buf[mb_index] |=
956                     FPMB_MOTION_DOWN_MASK;
957               }
958             }
959 #endif
960
961             // Non-zero vector, was it different from the last non zero vector?
962             if (!is_equal_mv(&mv, &lastmv))
963               ++new_mv_count;
964             lastmv = mv;
965
966             // Does the row vector point inwards or outwards?
967             if (mb_row < cm->mb_rows / 2) {
968               if (mv.row > 0)
969                 --sum_in_vectors;
970               else if (mv.row < 0)
971                 ++sum_in_vectors;
972             } else if (mb_row > cm->mb_rows / 2) {
973               if (mv.row > 0)
974                 ++sum_in_vectors;
975               else if (mv.row < 0)
976                 --sum_in_vectors;
977             }
978
979             // Does the col vector point inwards or outwards?
980             if (mb_col < cm->mb_cols / 2) {
981               if (mv.col > 0)
982                 --sum_in_vectors;
983               else if (mv.col < 0)
984                 ++sum_in_vectors;
985             } else if (mb_col > cm->mb_cols / 2) {
986               if (mv.col > 0)
987                 ++sum_in_vectors;
988               else if (mv.col < 0)
989                 --sum_in_vectors;
990             }
991           }
992         }
993       } else {
994         sr_coded_error += (int64_t)this_error;
995       }
996       coded_error += (int64_t)this_error;
997
998       // Adjust to the next column of MBs.
999       x->plane[0].src.buf += 16;
1000       x->plane[1].src.buf += uv_mb_height;
1001       x->plane[2].src.buf += uv_mb_height;
1002
1003       recon_yoffset += 16;
1004       recon_uvoffset += uv_mb_height;
1005     }
1006
1007     // Adjust to the next row of MBs.
1008     x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
1009     x->plane[1].src.buf += uv_mb_height * x->plane[1].src.stride -
1010                            uv_mb_height * cm->mb_cols;
1011     x->plane[2].src.buf += uv_mb_height * x->plane[1].src.stride -
1012                            uv_mb_height * cm->mb_cols;
1013
1014     vpx_clear_system_state();
1015   }
1016
1017   // Clamp the image start to rows/2. This number of rows is discarded top
1018   // and bottom as dead data so rows / 2 means the frame is blank.
1019   if ((image_data_start_row > cm->mb_rows / 2) ||
1020       (image_data_start_row == INVALID_ROW)) {
1021     image_data_start_row = cm->mb_rows / 2;
1022   }
1023   // Exclude any image dead zone
1024   if (image_data_start_row > 0) {
1025     intra_skip_count =
1026         VPXMAX(0, intra_skip_count - (image_data_start_row * cm->mb_cols * 2));
1027   }
1028
1029   {
1030     FIRSTPASS_STATS fps;
1031     // The minimum error here insures some bit allocation to frames even
1032     // in static regions. The allocation per MB declines for larger formats
1033     // where the typical "real" energy per MB also falls.
1034     // Initial estimate here uses sqrt(mbs) to define the min_err, where the
1035     // number of mbs is proportional to the image area.
1036     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1037                         ? cpi->initial_mbs : cpi->common.MBs;
1038     const double min_err = 200 * sqrt(num_mbs);
1039
1040     intra_factor = intra_factor / (double)num_mbs;
1041     brightness_factor = brightness_factor / (double)num_mbs;
1042     fps.weight = intra_factor * brightness_factor;
1043
1044     fps.frame = cm->current_video_frame;
1045     fps.spatial_layer_id = cpi->svc.spatial_layer_id;
1046     fps.coded_error = (double)(coded_error >> 8) + min_err;
1047     fps.sr_coded_error = (double)(sr_coded_error >> 8) + min_err;
1048     fps.intra_error = (double)(intra_error >> 8) + min_err;
1049     fps.count = 1.0;
1050     fps.pcnt_inter = (double)intercount / num_mbs;
1051     fps.pcnt_second_ref = (double)second_ref_count / num_mbs;
1052     fps.pcnt_neutral = (double)neutral_count / num_mbs;
1053     fps.intra_skip_pct = (double)intra_skip_count / num_mbs;
1054     fps.inactive_zone_rows = (double)image_data_start_row;
1055     fps.inactive_zone_cols = (double)0;  // TODO(paulwilkins): fix
1056
1057     if (mvcount > 0) {
1058       fps.MVr = (double)sum_mvr / mvcount;
1059       fps.mvr_abs = (double)sum_mvr_abs / mvcount;
1060       fps.MVc = (double)sum_mvc / mvcount;
1061       fps.mvc_abs = (double)sum_mvc_abs / mvcount;
1062       fps.MVrv = ((double)sum_mvrs -
1063                   ((double)sum_mvr * sum_mvr / mvcount)) / mvcount;
1064       fps.MVcv = ((double)sum_mvcs -
1065                   ((double)sum_mvc * sum_mvc / mvcount)) / mvcount;
1066       fps.mv_in_out_count = (double)sum_in_vectors / (mvcount * 2);
1067       fps.new_mv_count = new_mv_count;
1068       fps.pcnt_motion = (double)mvcount / num_mbs;
1069     } else {
1070       fps.MVr = 0.0;
1071       fps.mvr_abs = 0.0;
1072       fps.MVc = 0.0;
1073       fps.mvc_abs = 0.0;
1074       fps.MVrv = 0.0;
1075       fps.MVcv = 0.0;
1076       fps.mv_in_out_count = 0.0;
1077       fps.new_mv_count = 0.0;
1078       fps.pcnt_motion = 0.0;
1079     }
1080
1081     // TODO(paulwilkins):  Handle the case when duration is set to 0, or
1082     // something less than the full time between subsequent values of
1083     // cpi->source_time_stamp.
1084     fps.duration = (double)(source->ts_end - source->ts_start);
1085
1086     // Don't want to do output stats with a stack variable!
1087     twopass->this_frame_stats = fps;
1088     output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
1089     accumulate_stats(&twopass->total_stats, &fps);
1090
1091 #if CONFIG_FP_MB_STATS
1092     if (cpi->use_fp_mb_stats) {
1093       output_fpmb_stats(twopass->frame_mb_stats_buf, cm, cpi->output_pkt_list);
1094     }
1095 #endif
1096   }
1097
1098   // Copy the previous Last Frame back into gf and and arf buffers if
1099   // the prediction is good enough... but also don't allow it to lag too far.
1100   if ((twopass->sr_update_lag > 3) ||
1101       ((cm->current_video_frame > 0) &&
1102        (twopass->this_frame_stats.pcnt_inter > 0.20) &&
1103        ((twopass->this_frame_stats.intra_error /
1104          DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
1105     if (gld_yv12 != NULL) {
1106       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1107                  cm->ref_frame_map[cpi->lst_fb_idx]);
1108     }
1109     twopass->sr_update_lag = 1;
1110   } else {
1111     ++twopass->sr_update_lag;
1112   }
1113
1114   vpx_extend_frame_borders(new_yv12);
1115
1116   if (lc != NULL) {
1117     vp9_update_reference_frames(cpi);
1118   } else {
1119     // The frame we just compressed now becomes the last frame.
1120     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
1121                cm->new_fb_idx);
1122   }
1123
1124   // Special case for the first frame. Copy into the GF buffer as a second
1125   // reference.
1126   if (cm->current_video_frame == 0 && cpi->gld_fb_idx != INVALID_IDX &&
1127       lc == NULL) {
1128     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1129                cm->ref_frame_map[cpi->lst_fb_idx]);
1130   }
1131
1132   // Use this to see what the first pass reconstruction looks like.
1133   if (0) {
1134     char filename[512];
1135     FILE *recon_file;
1136     snprintf(filename, sizeof(filename), "enc%04d.yuv",
1137              (int)cm->current_video_frame);
1138
1139     if (cm->current_video_frame == 0)
1140       recon_file = fopen(filename, "wb");
1141     else
1142       recon_file = fopen(filename, "ab");
1143
1144     (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
1145     fclose(recon_file);
1146   }
1147
1148   ++cm->current_video_frame;
1149   if (cpi->use_svc)
1150     vp9_inc_frame_in_layer(cpi);
1151 }
1152
1153 static double calc_correction_factor(double err_per_mb,
1154                                      double err_divisor,
1155                                      double pt_low,
1156                                      double pt_high,
1157                                      int q,
1158                                      vpx_bit_depth_t bit_depth) {
1159   const double error_term = err_per_mb / err_divisor;
1160
1161   // Adjustment based on actual quantizer to power term.
1162   const double power_term =
1163       VPXMIN(vp9_convert_qindex_to_q(q, bit_depth) * 0.01 + pt_low, pt_high);
1164
1165   // Calculate correction factor.
1166   if (power_term < 1.0)
1167     assert(error_term >= 0.0);
1168
1169   return fclamp(pow(error_term, power_term), 0.05, 5.0);
1170 }
1171
1172 // Larger image formats are expected to be a little harder to code relatively
1173 // given the same prediction error score. This in part at least relates to the
1174 // increased size and hence coding cost of motion vectors.
1175 #define EDIV_SIZE_FACTOR 800
1176
1177 static int get_twopass_worst_quality(const VP9_COMP *cpi,
1178                                      const double section_err,
1179                                      double inactive_zone,
1180                                      int section_target_bandwidth,
1181                                      double group_weight_factor) {
1182   const RATE_CONTROL *const rc = &cpi->rc;
1183   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1184   // Clamp the target rate to VBR min / max limts.
1185   const int target_rate =
1186       vp9_rc_clamp_pframe_target_size(cpi, section_target_bandwidth);
1187
1188   inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
1189
1190   if (target_rate <= 0) {
1191     return rc->worst_quality;  // Highest value allowed
1192   } else {
1193     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1194                         ? cpi->initial_mbs : cpi->common.MBs;
1195     const int active_mbs = VPXMAX(1, num_mbs - (int)(num_mbs * inactive_zone));
1196     const double av_err_per_mb = section_err / active_mbs;
1197     const double speed_term = 1.0 + 0.04 * oxcf->speed;
1198     const double ediv_size_correction = (double)num_mbs / EDIV_SIZE_FACTOR;
1199     const int target_norm_bits_per_mb = ((uint64_t)target_rate <<
1200                                          BPER_MB_NORMBITS) / active_mbs;
1201
1202     int q;
1203     int is_svc_upper_layer = 0;
1204
1205     if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0)
1206       is_svc_upper_layer = 1;
1207
1208
1209     // Try and pick a max Q that will be high enough to encode the
1210     // content at the given rate.
1211     for (q = rc->best_quality; q < rc->worst_quality; ++q) {
1212       const double factor =
1213           calc_correction_factor(av_err_per_mb,
1214                                  ERR_DIVISOR - ediv_size_correction,
1215                                  is_svc_upper_layer ? SVC_FACTOR_PT_LOW :
1216                                  FACTOR_PT_LOW, FACTOR_PT_HIGH, q,
1217                                  cpi->common.bit_depth);
1218       const int bits_per_mb =
1219         vp9_rc_bits_per_mb(INTER_FRAME, q,
1220                            factor * speed_term * group_weight_factor,
1221                            cpi->common.bit_depth);
1222       if (bits_per_mb <= target_norm_bits_per_mb)
1223         break;
1224     }
1225
1226     // Restriction on active max q for constrained quality mode.
1227     if (cpi->oxcf.rc_mode == VPX_CQ)
1228       q = VPXMAX(q, oxcf->cq_level);
1229     return q;
1230   }
1231 }
1232
1233 static void setup_rf_level_maxq(VP9_COMP *cpi) {
1234   int i;
1235   RATE_CONTROL *const rc = &cpi->rc;
1236   for (i = INTER_NORMAL; i < RATE_FACTOR_LEVELS; ++i) {
1237     int qdelta = vp9_frame_type_qdelta(cpi, i, rc->worst_quality);
1238     rc->rf_level_maxq[i] = VPXMAX(rc->worst_quality + qdelta, rc->best_quality);
1239   }
1240 }
1241
1242 static void init_subsampling(VP9_COMP *cpi) {
1243   const VP9_COMMON *const cm = &cpi->common;
1244   RATE_CONTROL *const rc = &cpi->rc;
1245   const int w = cm->width;
1246   const int h = cm->height;
1247   int i;
1248
1249   for (i = 0; i < FRAME_SCALE_STEPS; ++i) {
1250     // Note: Frames with odd-sized dimensions may result from this scaling.
1251     rc->frame_width[i] = (w * 16) / frame_scale_factor[i];
1252     rc->frame_height[i] = (h * 16) / frame_scale_factor[i];
1253   }
1254
1255   setup_rf_level_maxq(cpi);
1256 }
1257
1258 void calculate_coded_size(VP9_COMP *cpi,
1259                           int *scaled_frame_width,
1260                           int *scaled_frame_height) {
1261   RATE_CONTROL *const rc = &cpi->rc;
1262   *scaled_frame_width = rc->frame_width[rc->frame_size_selector];
1263   *scaled_frame_height = rc->frame_height[rc->frame_size_selector];
1264 }
1265
1266 void vp9_init_second_pass(VP9_COMP *cpi) {
1267   SVC *const svc = &cpi->svc;
1268   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1269   const int is_two_pass_svc = (svc->number_spatial_layers > 1) ||
1270                               (svc->number_temporal_layers > 1);
1271   TWO_PASS *const twopass = is_two_pass_svc ?
1272       &svc->layer_context[svc->spatial_layer_id].twopass : &cpi->twopass;
1273   double frame_rate;
1274   FIRSTPASS_STATS *stats;
1275
1276   zero_stats(&twopass->total_stats);
1277   zero_stats(&twopass->total_left_stats);
1278
1279   if (!twopass->stats_in_end)
1280     return;
1281
1282   stats = &twopass->total_stats;
1283
1284   *stats = *twopass->stats_in_end;
1285   twopass->total_left_stats = *stats;
1286
1287   frame_rate = 10000000.0 * stats->count / stats->duration;
1288   // Each frame can have a different duration, as the frame rate in the source
1289   // isn't guaranteed to be constant. The frame rate prior to the first frame
1290   // encoded in the second pass is a guess. However, the sum duration is not.
1291   // It is calculated based on the actual durations of all frames from the
1292   // first pass.
1293
1294   if (is_two_pass_svc) {
1295     vp9_update_spatial_layer_framerate(cpi, frame_rate);
1296     twopass->bits_left = (int64_t)(stats->duration *
1297         svc->layer_context[svc->spatial_layer_id].target_bandwidth /
1298         10000000.0);
1299   } else {
1300     vp9_new_framerate(cpi, frame_rate);
1301     twopass->bits_left = (int64_t)(stats->duration * oxcf->target_bandwidth /
1302                              10000000.0);
1303   }
1304
1305   // This variable monitors how far behind the second ref update is lagging.
1306   twopass->sr_update_lag = 1;
1307
1308   // Scan the first pass file and calculate a modified total error based upon
1309   // the bias/power function used to allocate bits.
1310   {
1311     const double avg_error = stats->coded_error /
1312                              DOUBLE_DIVIDE_CHECK(stats->count);
1313     const FIRSTPASS_STATS *s = twopass->stats_in;
1314     double modified_error_total = 0.0;
1315     twopass->modified_error_min = (avg_error *
1316                                       oxcf->two_pass_vbrmin_section) / 100;
1317     twopass->modified_error_max = (avg_error *
1318                                       oxcf->two_pass_vbrmax_section) / 100;
1319     while (s < twopass->stats_in_end) {
1320       modified_error_total += calculate_modified_err(cpi, twopass, oxcf, s);
1321       ++s;
1322     }
1323     twopass->modified_error_left = modified_error_total;
1324   }
1325
1326   // Reset the vbr bits off target counters
1327   cpi->rc.vbr_bits_off_target = 0;
1328   cpi->rc.vbr_bits_off_target_fast = 0;
1329
1330   cpi->rc.rate_error_estimate = 0;
1331
1332   // Static sequence monitor variables.
1333   twopass->kf_zeromotion_pct = 100;
1334   twopass->last_kfgroup_zeromotion_pct = 100;
1335
1336   if (oxcf->resize_mode != RESIZE_NONE) {
1337     init_subsampling(cpi);
1338   }
1339 }
1340
1341 #define SR_DIFF_PART 0.0015
1342 #define MOTION_AMP_PART 0.003
1343 #define INTRA_PART 0.005
1344 #define DEFAULT_DECAY_LIMIT 0.75
1345 #define LOW_SR_DIFF_TRHESH 0.1
1346 #define SR_DIFF_MAX 128.0
1347
1348 static double get_sr_decay_rate(const VP9_COMP *cpi,
1349                                 const FIRSTPASS_STATS *frame) {
1350   const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1351                       ? cpi->initial_mbs : cpi->common.MBs;
1352   double sr_diff =
1353       (frame->sr_coded_error - frame->coded_error) / num_mbs;
1354   double sr_decay = 1.0;
1355   double modified_pct_inter;
1356   double modified_pcnt_intra;
1357   const double motion_amplitude_factor =
1358     frame->pcnt_motion * ((frame->mvc_abs + frame->mvr_abs) / 2);
1359
1360   modified_pct_inter = frame->pcnt_inter;
1361   if ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
1362       (double)NCOUNT_FRAME_II_THRESH) {
1363     modified_pct_inter = frame->pcnt_inter - frame->pcnt_neutral;
1364   }
1365   modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
1366
1367
1368   if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
1369     sr_diff = VPXMIN(sr_diff, SR_DIFF_MAX);
1370     sr_decay = 1.0 - (SR_DIFF_PART * sr_diff) -
1371                (MOTION_AMP_PART * motion_amplitude_factor) -
1372                (INTRA_PART * modified_pcnt_intra);
1373   }
1374   return VPXMAX(sr_decay, VPXMIN(DEFAULT_DECAY_LIMIT, modified_pct_inter));
1375 }
1376
1377 // This function gives an estimate of how badly we believe the prediction
1378 // quality is decaying from frame to frame.
1379 static double get_zero_motion_factor(const VP9_COMP *cpi,
1380                                      const FIRSTPASS_STATS *frame) {
1381   const double zero_motion_pct = frame->pcnt_inter -
1382                                  frame->pcnt_motion;
1383   double sr_decay = get_sr_decay_rate(cpi, frame);
1384   return VPXMIN(sr_decay, zero_motion_pct);
1385 }
1386
1387 #define ZM_POWER_FACTOR 0.75
1388
1389 static double get_prediction_decay_rate(const VP9_COMP *cpi,
1390                                         const FIRSTPASS_STATS *next_frame) {
1391   const double sr_decay_rate = get_sr_decay_rate(cpi, next_frame);
1392   const double zero_motion_factor =
1393     (0.95 * pow((next_frame->pcnt_inter - next_frame->pcnt_motion),
1394                 ZM_POWER_FACTOR));
1395
1396   return VPXMAX(zero_motion_factor,
1397                 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
1398 }
1399
1400 // Function to test for a condition where a complex transition is followed
1401 // by a static section. For example in slide shows where there is a fade
1402 // between slides. This is to help with more optimal kf and gf positioning.
1403 static int detect_transition_to_still(VP9_COMP *cpi,
1404                                       int frame_interval, int still_interval,
1405                                       double loop_decay_rate,
1406                                       double last_decay_rate) {
1407   TWO_PASS *const twopass = &cpi->twopass;
1408   RATE_CONTROL *const rc = &cpi->rc;
1409
1410   // Break clause to detect very still sections after motion
1411   // For example a static image after a fade or other transition
1412   // instead of a clean scene cut.
1413   if (frame_interval > rc->min_gf_interval &&
1414       loop_decay_rate >= 0.999 &&
1415       last_decay_rate < 0.9) {
1416     int j;
1417
1418     // Look ahead a few frames to see if static condition persists...
1419     for (j = 0; j < still_interval; ++j) {
1420       const FIRSTPASS_STATS *stats = &twopass->stats_in[j];
1421       if (stats >= twopass->stats_in_end)
1422         break;
1423
1424       if (stats->pcnt_inter - stats->pcnt_motion < 0.999)
1425         break;
1426     }
1427
1428     // Only if it does do we signal a transition to still.
1429     return j == still_interval;
1430   }
1431
1432   return 0;
1433 }
1434
1435 // This function detects a flash through the high relative pcnt_second_ref
1436 // score in the frame following a flash frame. The offset passed in should
1437 // reflect this.
1438 static int detect_flash(const TWO_PASS *twopass, int offset) {
1439   const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
1440
1441   // What we are looking for here is a situation where there is a
1442   // brief break in prediction (such as a flash) but subsequent frames
1443   // are reasonably well predicted by an earlier (pre flash) frame.
1444   // The recovery after a flash is indicated by a high pcnt_second_ref
1445   // compared to pcnt_inter.
1446   return next_frame != NULL &&
1447          next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
1448          next_frame->pcnt_second_ref >= 0.5;
1449 }
1450
1451 // Update the motion related elements to the GF arf boost calculation.
1452 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1453                                           double *mv_in_out,
1454                                           double *mv_in_out_accumulator,
1455                                           double *abs_mv_in_out_accumulator,
1456                                           double *mv_ratio_accumulator) {
1457   const double pct = stats->pcnt_motion;
1458
1459   // Accumulate Motion In/Out of frame stats.
1460   *mv_in_out = stats->mv_in_out_count * pct;
1461   *mv_in_out_accumulator += *mv_in_out;
1462   *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1463
1464   // Accumulate a measure of how uniform (or conversely how random) the motion
1465   // field is (a ratio of abs(mv) / mv).
1466   if (pct > 0.05) {
1467     const double mvr_ratio = fabs(stats->mvr_abs) /
1468                                  DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1469     const double mvc_ratio = fabs(stats->mvc_abs) /
1470                                  DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1471
1472     *mv_ratio_accumulator += pct * (mvr_ratio < stats->mvr_abs ?
1473                                        mvr_ratio : stats->mvr_abs);
1474     *mv_ratio_accumulator += pct * (mvc_ratio < stats->mvc_abs ?
1475                                        mvc_ratio : stats->mvc_abs);
1476   }
1477 }
1478
1479 #define BASELINE_ERR_PER_MB 1000.0
1480 static double calc_frame_boost(VP9_COMP *cpi,
1481                                const FIRSTPASS_STATS *this_frame,
1482                                double this_frame_mv_in_out,
1483                                double max_boost) {
1484   double frame_boost;
1485   const double lq =
1486     vp9_convert_qindex_to_q(cpi->rc.avg_frame_qindex[INTER_FRAME],
1487                             cpi->common.bit_depth);
1488   const double boost_q_correction = VPXMIN((0.5 + (lq * 0.015)), 1.5);
1489   int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1490                 ? cpi->initial_mbs : cpi->common.MBs;
1491
1492   // Correct for any inactive region in the image
1493   num_mbs = (int)VPXMAX(1, num_mbs * calculate_active_area(cpi, this_frame));
1494
1495   // Underlying boost factor is based on inter error ratio.
1496   frame_boost = (BASELINE_ERR_PER_MB * num_mbs) /
1497                 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
1498   frame_boost = frame_boost * BOOST_FACTOR * boost_q_correction;
1499
1500   // Increase boost for frames where new data coming into frame (e.g. zoom out).
1501   // Slightly reduce boost if there is a net balance of motion out of the frame
1502   // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
1503   if (this_frame_mv_in_out > 0.0)
1504     frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1505   // In the extreme case the boost is halved.
1506   else
1507     frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1508
1509   return VPXMIN(frame_boost, max_boost * boost_q_correction);
1510 }
1511
1512 static int calc_arf_boost(VP9_COMP *cpi, int offset,
1513                           int f_frames, int b_frames,
1514                           int *f_boost, int *b_boost) {
1515   TWO_PASS *const twopass = &cpi->twopass;
1516   int i;
1517   double boost_score = 0.0;
1518   double mv_ratio_accumulator = 0.0;
1519   double decay_accumulator = 1.0;
1520   double this_frame_mv_in_out = 0.0;
1521   double mv_in_out_accumulator = 0.0;
1522   double abs_mv_in_out_accumulator = 0.0;
1523   int arf_boost;
1524   int flash_detected = 0;
1525
1526   // Search forward from the proposed arf/next gf position.
1527   for (i = 0; i < f_frames; ++i) {
1528     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1529     if (this_frame == NULL)
1530       break;
1531
1532     // Update the motion related elements to the boost calculation.
1533     accumulate_frame_motion_stats(this_frame,
1534                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1535                                   &abs_mv_in_out_accumulator,
1536                                   &mv_ratio_accumulator);
1537
1538     // We want to discount the flash frame itself and the recovery
1539     // frame that follows as both will have poor scores.
1540     flash_detected = detect_flash(twopass, i + offset) ||
1541                      detect_flash(twopass, i + offset + 1);
1542
1543     // Accumulate the effect of prediction quality decay.
1544     if (!flash_detected) {
1545       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
1546       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1547                           ? MIN_DECAY_FACTOR : decay_accumulator;
1548     }
1549
1550     boost_score += decay_accumulator * calc_frame_boost(cpi, this_frame,
1551                                                         this_frame_mv_in_out,
1552                                                         GF_MAX_BOOST);
1553   }
1554
1555   *f_boost = (int)boost_score;
1556
1557   // Reset for backward looking loop.
1558   boost_score = 0.0;
1559   mv_ratio_accumulator = 0.0;
1560   decay_accumulator = 1.0;
1561   this_frame_mv_in_out = 0.0;
1562   mv_in_out_accumulator = 0.0;
1563   abs_mv_in_out_accumulator = 0.0;
1564
1565   // Search backward towards last gf position.
1566   for (i = -1; i >= -b_frames; --i) {
1567     const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1568     if (this_frame == NULL)
1569       break;
1570
1571     // Update the motion related elements to the boost calculation.
1572     accumulate_frame_motion_stats(this_frame,
1573                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1574                                   &abs_mv_in_out_accumulator,
1575                                   &mv_ratio_accumulator);
1576
1577     // We want to discount the the flash frame itself and the recovery
1578     // frame that follows as both will have poor scores.
1579     flash_detected = detect_flash(twopass, i + offset) ||
1580                      detect_flash(twopass, i + offset + 1);
1581
1582     // Cumulative effect of prediction quality decay.
1583     if (!flash_detected) {
1584       decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
1585       decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1586                               ? MIN_DECAY_FACTOR : decay_accumulator;
1587     }
1588
1589     boost_score += decay_accumulator * calc_frame_boost(cpi, this_frame,
1590                                                         this_frame_mv_in_out,
1591                                                         GF_MAX_BOOST);
1592   }
1593   *b_boost = (int)boost_score;
1594
1595   arf_boost = (*f_boost + *b_boost);
1596   if (arf_boost < ((b_frames + f_frames) * 20))
1597     arf_boost = ((b_frames + f_frames) * 20);
1598   arf_boost = VPXMAX(arf_boost, MIN_ARF_GF_BOOST);
1599
1600   return arf_boost;
1601 }
1602
1603 // Calculate a section intra ratio used in setting max loop filter.
1604 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
1605                                          const FIRSTPASS_STATS *end,
1606                                          int section_length) {
1607   const FIRSTPASS_STATS *s = begin;
1608   double intra_error = 0.0;
1609   double coded_error = 0.0;
1610   int i = 0;
1611
1612   while (s < end && i < section_length) {
1613     intra_error += s->intra_error;
1614     coded_error += s->coded_error;
1615     ++s;
1616     ++i;
1617   }
1618
1619   return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
1620 }
1621
1622 // Calculate the total bits to allocate in this GF/ARF group.
1623 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
1624                                              double gf_group_err) {
1625   const RATE_CONTROL *const rc = &cpi->rc;
1626   const TWO_PASS *const twopass = &cpi->twopass;
1627   const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1628   int64_t total_group_bits;
1629
1630   // Calculate the bits to be allocated to the group as a whole.
1631   if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
1632     total_group_bits = (int64_t)(twopass->kf_group_bits *
1633                                  (gf_group_err / twopass->kf_group_error_left));
1634   } else {
1635     total_group_bits = 0;
1636   }
1637
1638   // Clamp odd edge cases.
1639   total_group_bits = (total_group_bits < 0) ?
1640      0 : (total_group_bits > twopass->kf_group_bits) ?
1641      twopass->kf_group_bits : total_group_bits;
1642
1643   // Clip based on user supplied data rate variability limit.
1644   if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
1645     total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
1646
1647   return total_group_bits;
1648 }
1649
1650 // Calculate the number bits extra to assign to boosted frames in a group.
1651 static int calculate_boost_bits(int frame_count,
1652                                 int boost, int64_t total_group_bits) {
1653   int allocation_chunks;
1654
1655   // return 0 for invalid inputs (could arise e.g. through rounding errors)
1656   if (!boost || (total_group_bits <= 0) || (frame_count <= 0) )
1657     return 0;
1658
1659   allocation_chunks = (frame_count * 100) + boost;
1660
1661   // Prevent overflow.
1662   if (boost > 1023) {
1663     int divisor = boost >> 10;
1664     boost /= divisor;
1665     allocation_chunks /= divisor;
1666   }
1667
1668   // Calculate the number of extra bits for use in the boosted frame or frames.
1669   return VPXMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
1670                 0);
1671 }
1672
1673 // Current limit on maximum number of active arfs in a GF/ARF group.
1674 #define MAX_ACTIVE_ARFS 2
1675 #define ARF_SLOT1 2
1676 #define ARF_SLOT2 3
1677 // This function indirects the choice of buffers for arfs.
1678 // At the moment the values are fixed but this may change as part of
1679 // the integration process with other codec features that swap buffers around.
1680 static void get_arf_buffer_indices(unsigned char *arf_buffer_indices) {
1681   arf_buffer_indices[0] = ARF_SLOT1;
1682   arf_buffer_indices[1] = ARF_SLOT2;
1683 }
1684
1685 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
1686                                    double group_error, int gf_arf_bits) {
1687   RATE_CONTROL *const rc = &cpi->rc;
1688   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1689   TWO_PASS *const twopass = &cpi->twopass;
1690   GF_GROUP *const gf_group = &twopass->gf_group;
1691   FIRSTPASS_STATS frame_stats;
1692   int i;
1693   int frame_index = 1;
1694   int target_frame_size;
1695   int key_frame;
1696   const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
1697   int64_t total_group_bits = gf_group_bits;
1698   double modified_err = 0.0;
1699   double err_fraction;
1700   int mid_boost_bits = 0;
1701   int mid_frame_idx;
1702   unsigned char arf_buffer_indices[MAX_ACTIVE_ARFS];
1703   int alt_frame_index = frame_index;
1704   int has_temporal_layers = is_two_pass_svc(cpi) &&
1705                             cpi->svc.number_temporal_layers > 1;
1706
1707   // Only encode alt reference frame in temporal base layer.
1708   if (has_temporal_layers)
1709     alt_frame_index = cpi->svc.number_temporal_layers;
1710
1711   key_frame = cpi->common.frame_type == KEY_FRAME ||
1712               vp9_is_upper_layer_key_frame(cpi);
1713
1714   get_arf_buffer_indices(arf_buffer_indices);
1715
1716   // For key frames the frame target rate is already set and it
1717   // is also the golden frame.
1718   if (!key_frame) {
1719     if (rc->source_alt_ref_active) {
1720       gf_group->update_type[0] = OVERLAY_UPDATE;
1721       gf_group->rf_level[0] = INTER_NORMAL;
1722       gf_group->bit_allocation[0] = 0;
1723     } else {
1724       gf_group->update_type[0] = GF_UPDATE;
1725       gf_group->rf_level[0] = GF_ARF_STD;
1726       gf_group->bit_allocation[0] = gf_arf_bits;
1727     }
1728     gf_group->arf_update_idx[0] = arf_buffer_indices[0];
1729     gf_group->arf_ref_idx[0] = arf_buffer_indices[0];
1730
1731     // Step over the golden frame / overlay frame
1732     if (EOF == input_stats(twopass, &frame_stats))
1733       return;
1734   }
1735
1736   // Deduct the boost bits for arf (or gf if it is not a key frame)
1737   // from the group total.
1738   if (rc->source_alt_ref_pending || !key_frame)
1739     total_group_bits -= gf_arf_bits;
1740
1741   // Store the bits to spend on the ARF if there is one.
1742   if (rc->source_alt_ref_pending) {
1743     gf_group->update_type[alt_frame_index] = ARF_UPDATE;
1744     gf_group->rf_level[alt_frame_index] = GF_ARF_STD;
1745     gf_group->bit_allocation[alt_frame_index] = gf_arf_bits;
1746
1747     if (has_temporal_layers)
1748       gf_group->arf_src_offset[alt_frame_index] =
1749           (unsigned char)(rc->baseline_gf_interval -
1750                           cpi->svc.number_temporal_layers);
1751     else
1752       gf_group->arf_src_offset[alt_frame_index] =
1753           (unsigned char)(rc->baseline_gf_interval - 1);
1754
1755     gf_group->arf_update_idx[alt_frame_index] = arf_buffer_indices[0];
1756     gf_group->arf_ref_idx[alt_frame_index] =
1757       arf_buffer_indices[cpi->multi_arf_last_grp_enabled &&
1758                          rc->source_alt_ref_active];
1759     if (!has_temporal_layers)
1760       ++frame_index;
1761
1762     if (cpi->multi_arf_enabled) {
1763       // Set aside a slot for a level 1 arf.
1764       gf_group->update_type[frame_index] = ARF_UPDATE;
1765       gf_group->rf_level[frame_index] = GF_ARF_LOW;
1766       gf_group->arf_src_offset[frame_index] =
1767         (unsigned char)((rc->baseline_gf_interval >> 1) - 1);
1768       gf_group->arf_update_idx[frame_index] = arf_buffer_indices[1];
1769       gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
1770       ++frame_index;
1771     }
1772   }
1773
1774   // Define middle frame
1775   mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
1776
1777   // Allocate bits to the other frames in the group.
1778   for (i = 0; i < rc->baseline_gf_interval - rc->source_alt_ref_pending; ++i) {
1779     int arf_idx = 0;
1780     if (EOF == input_stats(twopass, &frame_stats))
1781       break;
1782
1783     if (has_temporal_layers && frame_index == alt_frame_index) {
1784       ++frame_index;
1785     }
1786
1787     modified_err = calculate_modified_err(cpi, twopass, oxcf, &frame_stats);
1788
1789     if (group_error > 0)
1790       err_fraction = modified_err / DOUBLE_DIVIDE_CHECK(group_error);
1791     else
1792       err_fraction = 0.0;
1793
1794     target_frame_size = (int)((double)total_group_bits * err_fraction);
1795
1796     if (rc->source_alt_ref_pending && cpi->multi_arf_enabled) {
1797       mid_boost_bits += (target_frame_size >> 4);
1798       target_frame_size -= (target_frame_size >> 4);
1799
1800       if (frame_index <= mid_frame_idx)
1801         arf_idx = 1;
1802     }
1803     gf_group->arf_update_idx[frame_index] = arf_buffer_indices[arf_idx];
1804     gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[arf_idx];
1805
1806     target_frame_size = clamp(target_frame_size, 0,
1807                               VPXMIN(max_bits, (int)total_group_bits));
1808
1809     gf_group->update_type[frame_index] = LF_UPDATE;
1810     gf_group->rf_level[frame_index] = INTER_NORMAL;
1811
1812     gf_group->bit_allocation[frame_index] = target_frame_size;
1813     ++frame_index;
1814   }
1815
1816   // Note:
1817   // We need to configure the frame at the end of the sequence + 1 that will be
1818   // the start frame for the next group. Otherwise prior to the call to
1819   // vp9_rc_get_second_pass_params() the data will be undefined.
1820   gf_group->arf_update_idx[frame_index] = arf_buffer_indices[0];
1821   gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
1822
1823   if (rc->source_alt_ref_pending) {
1824     gf_group->update_type[frame_index] = OVERLAY_UPDATE;
1825     gf_group->rf_level[frame_index] = INTER_NORMAL;
1826
1827     // Final setup for second arf and its overlay.
1828     if (cpi->multi_arf_enabled) {
1829       gf_group->bit_allocation[2] =
1830           gf_group->bit_allocation[mid_frame_idx] + mid_boost_bits;
1831       gf_group->update_type[mid_frame_idx] = OVERLAY_UPDATE;
1832       gf_group->bit_allocation[mid_frame_idx] = 0;
1833     }
1834   } else {
1835     gf_group->update_type[frame_index] = GF_UPDATE;
1836     gf_group->rf_level[frame_index] = GF_ARF_STD;
1837   }
1838
1839   // Note whether multi-arf was enabled this group for next time.
1840   cpi->multi_arf_last_grp_enabled = cpi->multi_arf_enabled;
1841 }
1842
1843 // Analyse and define a gf/arf group.
1844 static void define_gf_group(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1845   VP9_COMMON *const cm = &cpi->common;
1846   RATE_CONTROL *const rc = &cpi->rc;
1847   VP9EncoderConfig *const oxcf = &cpi->oxcf;
1848   TWO_PASS *const twopass = &cpi->twopass;
1849   FIRSTPASS_STATS next_frame;
1850   const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
1851   int i;
1852
1853   double boost_score = 0.0;
1854   double old_boost_score = 0.0;
1855   double gf_group_err = 0.0;
1856 #if GROUP_ADAPTIVE_MAXQ
1857   double gf_group_raw_error = 0.0;
1858 #endif
1859   double gf_group_skip_pct = 0.0;
1860   double gf_group_inactive_zone_rows = 0.0;
1861   double gf_first_frame_err = 0.0;
1862   double mod_frame_err = 0.0;
1863
1864   double mv_ratio_accumulator = 0.0;
1865   double decay_accumulator = 1.0;
1866   double zero_motion_accumulator = 1.0;
1867
1868   double loop_decay_rate = 1.00;
1869   double last_loop_decay_rate = 1.00;
1870
1871   double this_frame_mv_in_out = 0.0;
1872   double mv_in_out_accumulator = 0.0;
1873   double abs_mv_in_out_accumulator = 0.0;
1874   double mv_ratio_accumulator_thresh;
1875   unsigned int allow_alt_ref = is_altref_enabled(cpi);
1876
1877   int f_boost = 0;
1878   int b_boost = 0;
1879   int flash_detected;
1880   int active_max_gf_interval;
1881   int active_min_gf_interval;
1882   int64_t gf_group_bits;
1883   double gf_group_error_left;
1884   int gf_arf_bits;
1885   const int is_key_frame = frame_is_intra_only(cm);
1886   const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
1887
1888   // Reset the GF group data structures unless this is a key
1889   // frame in which case it will already have been done.
1890   if (is_key_frame == 0) {
1891     vp9_zero(twopass->gf_group);
1892   }
1893
1894   vpx_clear_system_state();
1895   vp9_zero(next_frame);
1896
1897   // Load stats for the current frame.
1898   mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
1899
1900   // Note the error of the frame at the start of the group. This will be
1901   // the GF frame error if we code a normal gf.
1902   gf_first_frame_err = mod_frame_err;
1903
1904   // If this is a key frame or the overlay from a previous arf then
1905   // the error score / cost of this frame has already been accounted for.
1906   if (arf_active_or_kf) {
1907     gf_group_err -= gf_first_frame_err;
1908 #if GROUP_ADAPTIVE_MAXQ
1909     gf_group_raw_error -= this_frame->coded_error;
1910 #endif
1911     gf_group_skip_pct -= this_frame->intra_skip_pct;
1912     gf_group_inactive_zone_rows -= this_frame->inactive_zone_rows;
1913   }
1914
1915   // Motion breakout threshold for loop below depends on image size.
1916   mv_ratio_accumulator_thresh =
1917       (cpi->initial_height + cpi->initial_width) / 4.0;
1918
1919   // Set a maximum and minimum interval for the GF group.
1920   // If the image appears almost completely static we can extend beyond this.
1921   {
1922     int int_max_q =
1923       (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
1924                                    cpi->common.bit_depth));
1925     int int_lbq =
1926       (int)(vp9_convert_qindex_to_q(rc->last_boosted_qindex,
1927                                    cpi->common.bit_depth));
1928     active_min_gf_interval = rc->min_gf_interval + VPXMIN(2, int_max_q / 200);
1929     if (active_min_gf_interval > rc->max_gf_interval)
1930       active_min_gf_interval = rc->max_gf_interval;
1931
1932     if (cpi->multi_arf_allowed) {
1933       active_max_gf_interval = rc->max_gf_interval;
1934     } else {
1935       // The value chosen depends on the active Q range. At low Q we have
1936       // bits to spare and are better with a smaller interval and smaller boost.
1937       // At high Q when there are few bits to spare we are better with a longer
1938       // interval to spread the cost of the GF.
1939       active_max_gf_interval = 12 + VPXMIN(4, (int_lbq / 6));
1940
1941       // We have: active_min_gf_interval <= rc->max_gf_interval
1942       if (active_max_gf_interval < active_min_gf_interval)
1943         active_max_gf_interval = active_min_gf_interval;
1944       else if (active_max_gf_interval > rc->max_gf_interval)
1945         active_max_gf_interval = rc->max_gf_interval;
1946     }
1947   }
1948
1949   i = 0;
1950   while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
1951     ++i;
1952
1953     // Accumulate error score of frames in this gf group.
1954     mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
1955     gf_group_err += mod_frame_err;
1956 #if GROUP_ADAPTIVE_MAXQ
1957     gf_group_raw_error += this_frame->coded_error;
1958 #endif
1959     gf_group_skip_pct += this_frame->intra_skip_pct;
1960     gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
1961
1962     if (EOF == input_stats(twopass, &next_frame))
1963       break;
1964
1965     // Test for the case where there is a brief flash but the prediction
1966     // quality back to an earlier frame is then restored.
1967     flash_detected = detect_flash(twopass, 0);
1968
1969     // Update the motion related elements to the boost calculation.
1970     accumulate_frame_motion_stats(&next_frame,
1971                                   &this_frame_mv_in_out, &mv_in_out_accumulator,
1972                                   &abs_mv_in_out_accumulator,
1973                                   &mv_ratio_accumulator);
1974
1975     // Accumulate the effect of prediction quality decay.
1976     if (!flash_detected) {
1977       last_loop_decay_rate = loop_decay_rate;
1978       loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
1979
1980       decay_accumulator = decay_accumulator * loop_decay_rate;
1981
1982       // Monitor for static sections.
1983       zero_motion_accumulator = VPXMIN(
1984           zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
1985
1986       // Break clause to detect very still sections after motion. For example,
1987       // a static image after a fade or other transition.
1988       if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
1989                                      last_loop_decay_rate)) {
1990         allow_alt_ref = 0;
1991         break;
1992       }
1993     }
1994
1995     // Calculate a boost number for this frame.
1996     boost_score += decay_accumulator * calc_frame_boost(cpi, &next_frame,
1997                                                         this_frame_mv_in_out,
1998                                                         GF_MAX_BOOST);
1999
2000     // Break out conditions.
2001     if (
2002       // Break at active_max_gf_interval unless almost totally static.
2003       (i >= (active_max_gf_interval + arf_active_or_kf) &&
2004             zero_motion_accumulator < 0.995) ||
2005       (
2006         // Don't break out with a very short interval.
2007         (i >= active_min_gf_interval + arf_active_or_kf) &&
2008         (!flash_detected) &&
2009         ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
2010          (abs_mv_in_out_accumulator > 3.0) ||
2011          (mv_in_out_accumulator < -2.0) ||
2012          ((boost_score - old_boost_score) < BOOST_BREAKOUT)))) {
2013       boost_score = old_boost_score;
2014       break;
2015     }
2016
2017     *this_frame = next_frame;
2018     old_boost_score = boost_score;
2019   }
2020
2021   twopass->gf_zeromotion_pct = (int)(zero_motion_accumulator * 1000.0);
2022
2023   // Was the group length constrained by the requirement for a new KF?
2024   rc->constrained_gf_group = (i >= rc->frames_to_key) ? 1 : 0;
2025
2026   // Should we use the alternate reference frame.
2027   if (allow_alt_ref &&
2028     (i < cpi->oxcf.lag_in_frames) &&
2029     (i >= rc->min_gf_interval)) {
2030     // Calculate the boost for alt ref.
2031     rc->gfu_boost = calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost,
2032       &b_boost);
2033     rc->source_alt_ref_pending = 1;
2034
2035     // Test to see if multi arf is appropriate.
2036     cpi->multi_arf_enabled =
2037       (cpi->multi_arf_allowed && (rc->baseline_gf_interval >= 6) &&
2038       (zero_motion_accumulator < 0.995)) ? 1 : 0;
2039   } else {
2040     rc->gfu_boost = VPXMAX((int)boost_score, MIN_ARF_GF_BOOST);
2041     rc->source_alt_ref_pending = 0;
2042   }
2043
2044   // Set the interval until the next gf.
2045   rc->baseline_gf_interval = i - (is_key_frame || rc->source_alt_ref_pending);
2046
2047   // Only encode alt reference frame in temporal base layer. So
2048   // baseline_gf_interval should be multiple of a temporal layer group
2049   // (typically the frame distance between two base layer frames)
2050   if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
2051     int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
2052     int new_gf_interval = (rc->baseline_gf_interval + count) & (~count);
2053     int j;
2054     for (j = 0; j < new_gf_interval - rc->baseline_gf_interval; ++j) {
2055       if (EOF == input_stats(twopass, this_frame))
2056         break;
2057       gf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2058 #if GROUP_ADAPTIVE_MAXQ
2059       gf_group_raw_error += this_frame->coded_error;
2060 #endif
2061       gf_group_skip_pct += this_frame->intra_skip_pct;
2062       gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
2063     }
2064     rc->baseline_gf_interval = new_gf_interval;
2065   }
2066
2067   rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2068
2069   // Reset the file position.
2070   reset_fpf_position(twopass, start_pos);
2071
2072   // Calculate the bits to be allocated to the gf/arf group as a whole
2073   gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
2074
2075 #if GROUP_ADAPTIVE_MAXQ
2076   // Calculate an estimate of the maxq needed for the group.
2077   // We are more agressive about correcting for sections
2078   // where there could be significant overshoot than for easier
2079   // sections where we do not wish to risk creating an overshoot
2080   // of the allocated bit budget.
2081   if ((cpi->oxcf.rc_mode != VPX_Q) && (rc->baseline_gf_interval > 1)) {
2082     const int vbr_group_bits_per_frame =
2083       (int)(gf_group_bits / rc->baseline_gf_interval);
2084     const double group_av_err = gf_group_raw_error  / rc->baseline_gf_interval;
2085     const double group_av_skip_pct =
2086       gf_group_skip_pct / rc->baseline_gf_interval;
2087     const double group_av_inactive_zone =
2088       ((gf_group_inactive_zone_rows * 2) /
2089        (rc->baseline_gf_interval * (double)cm->mb_rows));
2090
2091     int tmp_q;
2092     // rc factor is a weight factor that corrects for local rate control drift.
2093     double rc_factor = 1.0;
2094     if (rc->rate_error_estimate > 0) {
2095       rc_factor = VPXMAX(RC_FACTOR_MIN,
2096                          (double)(100 - rc->rate_error_estimate) / 100.0);
2097     } else {
2098       rc_factor = VPXMIN(RC_FACTOR_MAX,
2099                          (double)(100 - rc->rate_error_estimate) / 100.0);
2100     }
2101     tmp_q =
2102       get_twopass_worst_quality(cpi, group_av_err,
2103                                 (group_av_skip_pct + group_av_inactive_zone),
2104                                 vbr_group_bits_per_frame,
2105                                 twopass->kfgroup_inter_fraction * rc_factor);
2106     twopass->active_worst_quality =
2107         VPXMAX(tmp_q, twopass->active_worst_quality >> 1);
2108   }
2109 #endif
2110
2111   // Calculate the extra bits to be used for boosted frame(s)
2112   gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval,
2113                                      rc->gfu_boost, gf_group_bits);
2114
2115   // Adjust KF group bits and error remaining.
2116   twopass->kf_group_error_left -= (int64_t)gf_group_err;
2117
2118   // If this is an arf update we want to remove the score for the overlay
2119   // frame at the end which will usually be very cheap to code.
2120   // The overlay frame has already, in effect, been coded so we want to spread
2121   // the remaining bits among the other frames.
2122   // For normal GFs remove the score for the GF itself unless this is
2123   // also a key frame in which case it has already been accounted for.
2124   if (rc->source_alt_ref_pending) {
2125     gf_group_error_left = gf_group_err - mod_frame_err;
2126   } else if (is_key_frame == 0) {
2127     gf_group_error_left = gf_group_err - gf_first_frame_err;
2128   } else {
2129     gf_group_error_left = gf_group_err;
2130   }
2131
2132   // Allocate bits to each of the frames in the GF group.
2133   allocate_gf_group_bits(cpi, gf_group_bits, gf_group_error_left, gf_arf_bits);
2134
2135   // Reset the file position.
2136   reset_fpf_position(twopass, start_pos);
2137
2138   // Calculate a section intra ratio used in setting max loop filter.
2139   if (cpi->common.frame_type != KEY_FRAME) {
2140     twopass->section_intra_rating =
2141         calculate_section_intra_ratio(start_pos, twopass->stats_in_end,
2142                                       rc->baseline_gf_interval);
2143   }
2144
2145   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2146     // Default to starting GF groups at normal frame size.
2147     cpi->rc.next_frame_size_selector = UNSCALED;
2148   }
2149 }
2150
2151 // Threshold for use of the lagging second reference frame. High second ref
2152 // usage may point to a transient event like a flash or occlusion rather than
2153 // a real scene cut.
2154 #define SECOND_REF_USEAGE_THRESH 0.1
2155 // Minimum % intra coding observed in first pass (1.0 = 100%)
2156 #define MIN_INTRA_LEVEL 0.25
2157 // Minimum ratio between the % of intra coding and inter coding in the first
2158 // pass after discounting neutral blocks (discounting neutral blocks in this
2159 // way helps catch scene cuts in clips with very flat areas or letter box
2160 // format clips with image padding.
2161 #define INTRA_VS_INTER_THRESH 2.0
2162 // Hard threshold where the first pass chooses intra for almost all blocks.
2163 // In such a case even if the frame is not a scene cut coding a key frame
2164 // may be a good option.
2165 #define VERY_LOW_INTER_THRESH 0.05
2166 // Maximum threshold for the relative ratio of intra error score vs best
2167 // inter error score.
2168 #define KF_II_ERR_THRESHOLD 2.5
2169 // In real scene cuts there is almost always a sharp change in the intra
2170 // or inter error score.
2171 #define ERR_CHANGE_THRESHOLD 0.4
2172 // For real scene cuts we expect an improvment in the intra inter error
2173 // ratio in the next frame.
2174 #define II_IMPROVEMENT_THRESHOLD 3.5
2175 #define KF_II_MAX 128.0
2176
2177 static int test_candidate_kf(TWO_PASS *twopass,
2178                              const FIRSTPASS_STATS *last_frame,
2179                              const FIRSTPASS_STATS *this_frame,
2180                              const FIRSTPASS_STATS *next_frame) {
2181   int is_viable_kf = 0;
2182   double pcnt_intra = 1.0 - this_frame->pcnt_inter;
2183   double modified_pcnt_inter =
2184     this_frame->pcnt_inter - this_frame->pcnt_neutral;
2185
2186   // Does the frame satisfy the primary criteria of a key frame?
2187   // See above for an explanation of the test criteria.
2188   // If so, then examine how well it predicts subsequent frames.
2189   if ((this_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2190       (next_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2191       ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
2192        ((pcnt_intra > MIN_INTRA_LEVEL) &&
2193         (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
2194         ((this_frame->intra_error /
2195           DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
2196           KF_II_ERR_THRESHOLD) &&
2197         ((fabs(last_frame->coded_error - this_frame->coded_error) /
2198           DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
2199           ERR_CHANGE_THRESHOLD) ||
2200          (fabs(last_frame->intra_error - this_frame->intra_error) /
2201           DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
2202           ERR_CHANGE_THRESHOLD) ||
2203          ((next_frame->intra_error /
2204           DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) >
2205           II_IMPROVEMENT_THRESHOLD))))) {
2206     int i;
2207     const FIRSTPASS_STATS *start_pos = twopass->stats_in;
2208     FIRSTPASS_STATS local_next_frame = *next_frame;
2209     double boost_score = 0.0;
2210     double old_boost_score = 0.0;
2211     double decay_accumulator = 1.0;
2212
2213     // Examine how well the key frame predicts subsequent frames.
2214     for (i = 0; i < 16; ++i) {
2215       double next_iiratio = (BOOST_FACTOR * local_next_frame.intra_error /
2216                              DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
2217
2218       if (next_iiratio > KF_II_MAX)
2219         next_iiratio = KF_II_MAX;
2220
2221       // Cumulative effect of decay in prediction quality.
2222       if (local_next_frame.pcnt_inter > 0.85)
2223         decay_accumulator *= local_next_frame.pcnt_inter;
2224       else
2225         decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
2226
2227       // Keep a running total.
2228       boost_score += (decay_accumulator * next_iiratio);
2229
2230       // Test various breakout clauses.
2231       if ((local_next_frame.pcnt_inter < 0.05) ||
2232           (next_iiratio < 1.5) ||
2233           (((local_next_frame.pcnt_inter -
2234              local_next_frame.pcnt_neutral) < 0.20) &&
2235            (next_iiratio < 3.0)) ||
2236           ((boost_score - old_boost_score) < 3.0) ||
2237           (local_next_frame.intra_error < 200)) {
2238         break;
2239       }
2240
2241       old_boost_score = boost_score;
2242
2243       // Get the next frame details
2244       if (EOF == input_stats(twopass, &local_next_frame))
2245         break;
2246     }
2247
2248     // If there is tolerable prediction for at least the next 3 frames then
2249     // break out else discard this potential key frame and move on
2250     if (boost_score > 30.0 && (i > 3)) {
2251       is_viable_kf = 1;
2252     } else {
2253       // Reset the file position
2254       reset_fpf_position(twopass, start_pos);
2255
2256       is_viable_kf = 0;
2257     }
2258   }
2259
2260   return is_viable_kf;
2261 }
2262
2263 static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2264   int i, j;
2265   RATE_CONTROL *const rc = &cpi->rc;
2266   TWO_PASS *const twopass = &cpi->twopass;
2267   GF_GROUP *const gf_group = &twopass->gf_group;
2268   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2269   const FIRSTPASS_STATS first_frame = *this_frame;
2270   const FIRSTPASS_STATS *const start_position = twopass->stats_in;
2271   FIRSTPASS_STATS next_frame;
2272   FIRSTPASS_STATS last_frame;
2273   int kf_bits = 0;
2274   int loop_decay_counter = 0;
2275   double decay_accumulator = 1.0;
2276   double av_decay_accumulator = 0.0;
2277   double zero_motion_accumulator = 1.0;
2278   double boost_score = 0.0;
2279   double kf_mod_err = 0.0;
2280   double kf_group_err = 0.0;
2281   double recent_loop_decay[8] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
2282
2283   vp9_zero(next_frame);
2284
2285   cpi->common.frame_type = KEY_FRAME;
2286
2287   // Reset the GF group data structures.
2288   vp9_zero(*gf_group);
2289
2290   // Is this a forced key frame by interval.
2291   rc->this_key_frame_forced = rc->next_key_frame_forced;
2292
2293   // Clear the alt ref active flag and last group multi arf flags as they
2294   // can never be set for a key frame.
2295   rc->source_alt_ref_active = 0;
2296   cpi->multi_arf_last_grp_enabled = 0;
2297
2298   // KF is always a GF so clear frames till next gf counter.
2299   rc->frames_till_gf_update_due = 0;
2300
2301   rc->frames_to_key = 1;
2302
2303   twopass->kf_group_bits = 0;        // Total bits available to kf group
2304   twopass->kf_group_error_left = 0;  // Group modified error score.
2305
2306   kf_mod_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
2307
2308   // Find the next keyframe.
2309   i = 0;
2310   while (twopass->stats_in < twopass->stats_in_end &&
2311          rc->frames_to_key < cpi->oxcf.key_freq) {
2312     // Accumulate kf group error.
2313     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2314
2315     // Load the next frame's stats.
2316     last_frame = *this_frame;
2317     input_stats(twopass, this_frame);
2318
2319     // Provided that we are not at the end of the file...
2320     if (cpi->oxcf.auto_key && twopass->stats_in < twopass->stats_in_end) {
2321       double loop_decay_rate;
2322
2323       // Check for a scene cut.
2324       if (test_candidate_kf(twopass, &last_frame, this_frame,
2325                             twopass->stats_in))
2326         break;
2327
2328       // How fast is the prediction quality decaying?
2329       loop_decay_rate = get_prediction_decay_rate(cpi, twopass->stats_in);
2330
2331       // We want to know something about the recent past... rather than
2332       // as used elsewhere where we are concerned with decay in prediction
2333       // quality since the last GF or KF.
2334       recent_loop_decay[i % 8] = loop_decay_rate;
2335       decay_accumulator = 1.0;
2336       for (j = 0; j < 8; ++j)
2337         decay_accumulator *= recent_loop_decay[j];
2338
2339       // Special check for transition or high motion followed by a
2340       // static scene.
2341       if (detect_transition_to_still(cpi, i, cpi->oxcf.key_freq - i,
2342                                      loop_decay_rate, decay_accumulator))
2343         break;
2344
2345       // Step on to the next frame.
2346       ++rc->frames_to_key;
2347
2348       // If we don't have a real key frame within the next two
2349       // key_freq intervals then break out of the loop.
2350       if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq)
2351         break;
2352     } else {
2353       ++rc->frames_to_key;
2354     }
2355     ++i;
2356   }
2357
2358   // If there is a max kf interval set by the user we must obey it.
2359   // We already breakout of the loop above at 2x max.
2360   // This code centers the extra kf if the actual natural interval
2361   // is between 1x and 2x.
2362   if (cpi->oxcf.auto_key &&
2363       rc->frames_to_key > cpi->oxcf.key_freq) {
2364     FIRSTPASS_STATS tmp_frame = first_frame;
2365
2366     rc->frames_to_key /= 2;
2367
2368     // Reset to the start of the group.
2369     reset_fpf_position(twopass, start_position);
2370
2371     kf_group_err = 0.0;
2372
2373     // Rescan to get the correct error data for the forced kf group.
2374     for (i = 0; i < rc->frames_to_key; ++i) {
2375       kf_group_err += calculate_modified_err(cpi, twopass, oxcf, &tmp_frame);
2376       input_stats(twopass, &tmp_frame);
2377     }
2378     rc->next_key_frame_forced = 1;
2379   } else if (twopass->stats_in == twopass->stats_in_end ||
2380              rc->frames_to_key >= cpi->oxcf.key_freq) {
2381     rc->next_key_frame_forced = 1;
2382   } else {
2383     rc->next_key_frame_forced = 0;
2384   }
2385
2386   if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
2387     int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
2388     int new_frame_to_key = (rc->frames_to_key + count) & (~count);
2389     int j;
2390     for (j = 0; j < new_frame_to_key - rc->frames_to_key; ++j) {
2391       if (EOF == input_stats(twopass, this_frame))
2392         break;
2393       kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2394     }
2395     rc->frames_to_key = new_frame_to_key;
2396   }
2397
2398   // Special case for the last key frame of the file.
2399   if (twopass->stats_in >= twopass->stats_in_end) {
2400     // Accumulate kf group error.
2401     kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
2402   }
2403
2404   // Calculate the number of bits that should be assigned to the kf group.
2405   if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
2406     // Maximum number of bits for a single normal frame (not key frame).
2407     const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2408
2409     // Maximum number of bits allocated to the key frame group.
2410     int64_t max_grp_bits;
2411
2412     // Default allocation based on bits left and relative
2413     // complexity of the section.
2414     twopass->kf_group_bits = (int64_t)(twopass->bits_left *
2415        (kf_group_err / twopass->modified_error_left));
2416
2417     // Clip based on maximum per frame rate defined by the user.
2418     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
2419     if (twopass->kf_group_bits > max_grp_bits)
2420       twopass->kf_group_bits = max_grp_bits;
2421   } else {
2422     twopass->kf_group_bits = 0;
2423   }
2424   twopass->kf_group_bits = VPXMAX(0, twopass->kf_group_bits);
2425
2426   // Reset the first pass file position.
2427   reset_fpf_position(twopass, start_position);
2428
2429   // Scan through the kf group collating various stats used to determine
2430   // how many bits to spend on it.
2431   decay_accumulator = 1.0;
2432   boost_score = 0.0;
2433   for (i = 0; i < (rc->frames_to_key - 1); ++i) {
2434     if (EOF == input_stats(twopass, &next_frame))
2435       break;
2436
2437     // Monitor for static sections.
2438     zero_motion_accumulator = VPXMIN(
2439         zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
2440
2441     // Not all frames in the group are necessarily used in calculating boost.
2442     if ((i <= rc->max_gf_interval) ||
2443         ((i <= (rc->max_gf_interval * 4)) && (decay_accumulator > 0.5))) {
2444       const double frame_boost =
2445         calc_frame_boost(cpi, &next_frame, 0, KF_MAX_BOOST);
2446
2447       // How fast is prediction quality decaying.
2448       if (!detect_flash(twopass, 0)) {
2449         const double loop_decay_rate =
2450           get_prediction_decay_rate(cpi, &next_frame);
2451         decay_accumulator *= loop_decay_rate;
2452         decay_accumulator = VPXMAX(decay_accumulator, MIN_DECAY_FACTOR);
2453         av_decay_accumulator += decay_accumulator;
2454         ++loop_decay_counter;
2455       }
2456       boost_score += (decay_accumulator * frame_boost);
2457     }
2458   }
2459   av_decay_accumulator /= (double)loop_decay_counter;
2460
2461   reset_fpf_position(twopass, start_position);
2462
2463   // Store the zero motion percentage
2464   twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
2465
2466   // Calculate a section intra ratio used in setting max loop filter.
2467   twopass->section_intra_rating =
2468       calculate_section_intra_ratio(start_position, twopass->stats_in_end,
2469                                     rc->frames_to_key);
2470
2471   // Apply various clamps for min and max boost
2472   rc->kf_boost = (int)(av_decay_accumulator * boost_score);
2473   rc->kf_boost = VPXMAX(rc->kf_boost, (rc->frames_to_key * 3));
2474   rc->kf_boost = VPXMAX(rc->kf_boost, MIN_KF_BOOST);
2475
2476   // Work out how many bits to allocate for the key frame itself.
2477   kf_bits = calculate_boost_bits((rc->frames_to_key - 1),
2478                                   rc->kf_boost, twopass->kf_group_bits);
2479
2480   // Work out the fraction of the kf group bits reserved for the inter frames
2481   // within the group after discounting the bits for the kf itself.
2482   if (twopass->kf_group_bits) {
2483     twopass->kfgroup_inter_fraction =
2484       (double)(twopass->kf_group_bits - kf_bits) /
2485       (double)twopass->kf_group_bits;
2486   } else {
2487     twopass->kfgroup_inter_fraction = 1.0;
2488   }
2489
2490   twopass->kf_group_bits -= kf_bits;
2491
2492   // Save the bits to spend on the key frame.
2493   gf_group->bit_allocation[0] = kf_bits;
2494   gf_group->update_type[0] = KF_UPDATE;
2495   gf_group->rf_level[0] = KF_STD;
2496
2497   // Note the total error score of the kf group minus the key frame itself.
2498   twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
2499
2500   // Adjust the count of total modified error left.
2501   // The count of bits left is adjusted elsewhere based on real coded frame
2502   // sizes.
2503   twopass->modified_error_left -= kf_group_err;
2504
2505   if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2506     // Default to normal-sized frame on keyframes.
2507     cpi->rc.next_frame_size_selector = UNSCALED;
2508   }
2509 }
2510
2511 // Define the reference buffers that will be updated post encode.
2512 static void configure_buffer_updates(VP9_COMP *cpi) {
2513   TWO_PASS *const twopass = &cpi->twopass;
2514
2515   cpi->rc.is_src_frame_alt_ref = 0;
2516   switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
2517     case KF_UPDATE:
2518       cpi->refresh_last_frame = 1;
2519       cpi->refresh_golden_frame = 1;
2520       cpi->refresh_alt_ref_frame = 1;
2521       break;
2522     case LF_UPDATE:
2523       cpi->refresh_last_frame = 1;
2524       cpi->refresh_golden_frame = 0;
2525       cpi->refresh_alt_ref_frame = 0;
2526       break;
2527     case GF_UPDATE:
2528       cpi->refresh_last_frame = 1;
2529       cpi->refresh_golden_frame = 1;
2530       cpi->refresh_alt_ref_frame = 0;
2531       break;
2532     case OVERLAY_UPDATE:
2533       cpi->refresh_last_frame = 0;
2534       cpi->refresh_golden_frame = 1;
2535       cpi->refresh_alt_ref_frame = 0;
2536       cpi->rc.is_src_frame_alt_ref = 1;
2537       break;
2538     case ARF_UPDATE:
2539       cpi->refresh_last_frame = 0;
2540       cpi->refresh_golden_frame = 0;
2541       cpi->refresh_alt_ref_frame = 1;
2542       break;
2543     default:
2544       assert(0);
2545       break;
2546   }
2547   if (is_two_pass_svc(cpi)) {
2548     if (cpi->svc.temporal_layer_id > 0) {
2549       cpi->refresh_last_frame = 0;
2550       cpi->refresh_golden_frame = 0;
2551     }
2552     if (cpi->svc.layer_context[cpi->svc.spatial_layer_id].gold_ref_idx < 0)
2553       cpi->refresh_golden_frame = 0;
2554     if (cpi->alt_ref_source == NULL)
2555       cpi->refresh_alt_ref_frame = 0;
2556   }
2557 }
2558
2559 static int is_skippable_frame(const VP9_COMP *cpi) {
2560   // If the current frame does not have non-zero motion vector detected in the
2561   // first  pass, and so do its previous and forward frames, then this frame
2562   // can be skipped for partition check, and the partition size is assigned
2563   // according to the variance
2564   const SVC *const svc = &cpi->svc;
2565   const TWO_PASS *const twopass = is_two_pass_svc(cpi) ?
2566       &svc->layer_context[svc->spatial_layer_id].twopass : &cpi->twopass;
2567
2568   return (!frame_is_intra_only(&cpi->common) &&
2569     twopass->stats_in - 2 > twopass->stats_in_start &&
2570     twopass->stats_in < twopass->stats_in_end &&
2571     (twopass->stats_in - 1)->pcnt_inter - (twopass->stats_in - 1)->pcnt_motion
2572     == 1 &&
2573     (twopass->stats_in - 2)->pcnt_inter - (twopass->stats_in - 2)->pcnt_motion
2574     == 1 &&
2575     twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
2576 }
2577
2578 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
2579   VP9_COMMON *const cm = &cpi->common;
2580   RATE_CONTROL *const rc = &cpi->rc;
2581   TWO_PASS *const twopass = &cpi->twopass;
2582   GF_GROUP *const gf_group = &twopass->gf_group;
2583   int frames_left;
2584   FIRSTPASS_STATS this_frame;
2585
2586   int target_rate;
2587   LAYER_CONTEXT *const lc = is_two_pass_svc(cpi) ?
2588         &cpi->svc.layer_context[cpi->svc.spatial_layer_id] : 0;
2589
2590   if (lc != NULL) {
2591     frames_left = (int)(twopass->total_stats.count -
2592                   lc->current_video_frame_in_layer);
2593   } else {
2594     frames_left = (int)(twopass->total_stats.count -
2595                   cm->current_video_frame);
2596   }
2597
2598   if (!twopass->stats_in)
2599     return;
2600
2601   // If this is an arf frame then we dont want to read the stats file or
2602   // advance the input pointer as we already have what we need.
2603   if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
2604     int target_rate;
2605     configure_buffer_updates(cpi);
2606     target_rate = gf_group->bit_allocation[gf_group->index];
2607     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2608     rc->base_frame_target = target_rate;
2609
2610     cm->frame_type = INTER_FRAME;
2611
2612     if (lc != NULL) {
2613       if (cpi->svc.spatial_layer_id == 0) {
2614         lc->is_key_frame = 0;
2615       } else {
2616         lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2617
2618         if (lc->is_key_frame)
2619           cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2620       }
2621     }
2622
2623     // Do the firstpass stats indicate that this frame is skippable for the
2624     // partition search?
2625     if (cpi->sf.allow_partition_search_skip &&
2626         cpi->oxcf.pass == 2 && (!cpi->use_svc || is_two_pass_svc(cpi))) {
2627       cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
2628     }
2629
2630     return;
2631   }
2632
2633   vpx_clear_system_state();
2634
2635   if (cpi->oxcf.rc_mode == VPX_Q) {
2636     twopass->active_worst_quality = cpi->oxcf.cq_level;
2637   } else if (cm->current_video_frame == 0 ||
2638              (lc != NULL && lc->current_video_frame_in_layer == 0)) {
2639     // Special case code for first frame.
2640     const int section_target_bandwidth = (int)(twopass->bits_left /
2641                                                frames_left);
2642     const double section_length = twopass->total_left_stats.count;
2643     const double section_error =
2644       twopass->total_left_stats.coded_error / section_length;
2645     const double section_intra_skip =
2646       twopass->total_left_stats.intra_skip_pct / section_length;
2647     const double section_inactive_zone =
2648       (twopass->total_left_stats.inactive_zone_rows * 2) /
2649       ((double)cm->mb_rows * section_length);
2650     const int tmp_q =
2651       get_twopass_worst_quality(cpi, section_error,
2652                                 section_intra_skip + section_inactive_zone,
2653                                 section_target_bandwidth, DEFAULT_GRP_WEIGHT);
2654
2655     twopass->active_worst_quality = tmp_q;
2656     twopass->baseline_active_worst_quality = tmp_q;
2657     rc->ni_av_qi = tmp_q;
2658     rc->last_q[INTER_FRAME] = tmp_q;
2659     rc->avg_q = vp9_convert_qindex_to_q(tmp_q, cm->bit_depth);
2660     rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
2661     rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
2662     rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
2663   }
2664   vp9_zero(this_frame);
2665   if (EOF == input_stats(twopass, &this_frame))
2666     return;
2667
2668   // Set the frame content type flag.
2669   if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
2670     twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
2671   else
2672     twopass->fr_content_type = FC_NORMAL;
2673
2674   // Keyframe and section processing.
2675   if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
2676     FIRSTPASS_STATS this_frame_copy;
2677     this_frame_copy = this_frame;
2678     // Define next KF group and assign bits to it.
2679     find_next_key_frame(cpi, &this_frame);
2680     this_frame = this_frame_copy;
2681   } else {
2682     cm->frame_type = INTER_FRAME;
2683   }
2684
2685   if (lc != NULL) {
2686     if (cpi->svc.spatial_layer_id == 0) {
2687       lc->is_key_frame = (cm->frame_type == KEY_FRAME);
2688       if (lc->is_key_frame) {
2689         cpi->ref_frame_flags &=
2690             (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
2691         lc->frames_from_key_frame = 0;
2692         // Encode an intra only empty frame since we have a key frame.
2693         cpi->svc.encode_intra_empty_frame = 1;
2694       }
2695     } else {
2696       cm->frame_type = INTER_FRAME;
2697       lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2698
2699       if (lc->is_key_frame) {
2700         cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2701         lc->frames_from_key_frame = 0;
2702       }
2703     }
2704   }
2705
2706   // Define a new GF/ARF group. (Should always enter here for key frames).
2707   if (rc->frames_till_gf_update_due == 0) {
2708     define_gf_group(cpi, &this_frame);
2709
2710     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2711     if (lc != NULL)
2712       cpi->refresh_golden_frame = 1;
2713
2714 #if ARF_STATS_OUTPUT
2715     {
2716       FILE *fpfile;
2717       fpfile = fopen("arf.stt", "a");
2718       ++arf_count;
2719       fprintf(fpfile, "%10d %10ld %10d %10d %10ld\n",
2720               cm->current_video_frame, rc->frames_till_gf_update_due,
2721               rc->kf_boost, arf_count, rc->gfu_boost);
2722
2723       fclose(fpfile);
2724     }
2725 #endif
2726   }
2727
2728   configure_buffer_updates(cpi);
2729
2730   // Do the firstpass stats indicate that this frame is skippable for the
2731   // partition search?
2732   if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2 &&
2733       (!cpi->use_svc || is_two_pass_svc(cpi))) {
2734     cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
2735   }
2736
2737   target_rate = gf_group->bit_allocation[gf_group->index];
2738   rc->base_frame_target = target_rate;
2739
2740   {
2741     const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
2742                         ? cpi->initial_mbs : cpi->common.MBs;
2743     // The multiplication by 256 reverses a scaling factor of (>> 8)
2744     // applied when combining MB error values for the frame.
2745     twopass->mb_av_energy =
2746       log(((this_frame.intra_error * 256.0) / num_mbs) + 1.0);
2747   }
2748
2749   // Update the total stats remaining structure.
2750   subtract_stats(&twopass->total_left_stats, &this_frame);
2751 }
2752
2753 #define MINQ_ADJ_LIMIT 48
2754 #define MINQ_ADJ_LIMIT_CQ 20
2755 #define HIGH_UNDERSHOOT_RATIO 2
2756 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
2757   TWO_PASS *const twopass = &cpi->twopass;
2758   RATE_CONTROL *const rc = &cpi->rc;
2759   const int bits_used = rc->base_frame_target;
2760
2761   // VBR correction is done through rc->vbr_bits_off_target. Based on the
2762   // sign of this value, a limited % adjustment is made to the target rate
2763   // of subsequent frames, to try and push it back towards 0. This method
2764   // is designed to prevent extreme behaviour at the end of a clip
2765   // or group of frames.
2766   rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
2767   twopass->bits_left = VPXMAX(twopass->bits_left - bits_used, 0);
2768
2769   // Calculate the pct rc error.
2770   if (rc->total_actual_bits) {
2771     rc->rate_error_estimate =
2772       (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
2773     rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
2774   } else {
2775     rc->rate_error_estimate = 0;
2776   }
2777
2778   if (cpi->common.frame_type != KEY_FRAME &&
2779       !vp9_is_upper_layer_key_frame(cpi)) {
2780     twopass->kf_group_bits -= bits_used;
2781     twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
2782   }
2783   twopass->kf_group_bits = VPXMAX(twopass->kf_group_bits, 0);
2784
2785   // Increment the gf group index ready for the next frame.
2786   ++twopass->gf_group.index;
2787
2788   // If the rate control is drifting consider adjustment to min or maxq.
2789   if ((cpi->oxcf.rc_mode != VPX_Q) &&
2790       (cpi->twopass.gf_zeromotion_pct < VLOW_MOTION_THRESHOLD) &&
2791       !cpi->rc.is_src_frame_alt_ref) {
2792     const int maxq_adj_limit =
2793       rc->worst_quality - twopass->active_worst_quality;
2794     const int minq_adj_limit =
2795         (cpi->oxcf.rc_mode == VPX_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
2796
2797     // Undershoot.
2798     if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
2799       --twopass->extend_maxq;
2800       if (rc->rolling_target_bits >= rc->rolling_actual_bits)
2801         ++twopass->extend_minq;
2802     // Overshoot.
2803     } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
2804       --twopass->extend_minq;
2805       if (rc->rolling_target_bits < rc->rolling_actual_bits)
2806         ++twopass->extend_maxq;
2807     } else {
2808       // Adjustment for extreme local overshoot.
2809       if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
2810           rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
2811         ++twopass->extend_maxq;
2812
2813       // Unwind undershoot or overshoot adjustment.
2814       if (rc->rolling_target_bits < rc->rolling_actual_bits)
2815         --twopass->extend_minq;
2816       else if (rc->rolling_target_bits > rc->rolling_actual_bits)
2817         --twopass->extend_maxq;
2818     }
2819
2820     twopass->extend_minq = clamp(twopass->extend_minq, 0, minq_adj_limit);
2821     twopass->extend_maxq = clamp(twopass->extend_maxq, 0, maxq_adj_limit);
2822
2823     // If there is a big and undexpected undershoot then feed the extra
2824     // bits back in quickly. One situation where this may happen is if a
2825     // frame is unexpectedly almost perfectly predicted by the ARF or GF
2826     // but not very well predcited by the previous frame.
2827     if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
2828       int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
2829       if (rc->projected_frame_size < fast_extra_thresh) {
2830         rc->vbr_bits_off_target_fast +=
2831           fast_extra_thresh - rc->projected_frame_size;
2832         rc->vbr_bits_off_target_fast =
2833           VPXMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
2834
2835         // Fast adaptation of minQ if necessary to use up the extra bits.
2836         if (rc->avg_frame_bandwidth) {
2837           twopass->extend_minq_fast =
2838             (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
2839         }
2840         twopass->extend_minq_fast = VPXMIN(
2841             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
2842       } else if (rc->vbr_bits_off_target_fast) {
2843         twopass->extend_minq_fast = VPXMIN(
2844             twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
2845       } else {
2846         twopass->extend_minq_fast = 0;
2847       }
2848     }
2849   }
2850 }