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