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