2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
15 #include "./vpx_scale_rtcd.h"
17 #include "vpx_mem/vpx_mem.h"
18 #include "vpx_scale/vpx_scale.h"
19 #include "vpx_scale/yv12config.h"
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"
26 #include "vp9/encoder/vp9_aq_variance.h"
27 #include "vp9/encoder/vp9_block.h"
28 #include "vp9/encoder/vp9_encodeframe.h"
29 #include "vp9/encoder/vp9_encodemb.h"
30 #include "vp9/encoder/vp9_encodemv.h"
31 #include "vp9/encoder/vp9_encoder.h"
32 #include "vp9/encoder/vp9_extend.h"
33 #include "vp9/encoder/vp9_firstpass.h"
34 #include "vp9/encoder/vp9_mcomp.h"
35 #include "vp9/encoder/vp9_quantize.h"
36 #include "vp9/encoder/vp9_rd.h"
37 #include "vp9/encoder/vp9_variance.h"
42 #define IIKFACTOR1 12.5
43 #define IIKFACTOR2 15.0
46 #define ERR_DIVISOR 150.0
47 #define MIN_DECAY_FACTOR 0.1
48 #define SVC_FACTOR_PT_LOW 0.45
49 #define FACTOR_PT_LOW 0.5
50 #define FACTOR_PT_HIGH 0.9
52 #define KF_MB_INTRA_MIN 150
53 #define GF_MB_INTRA_MIN 100
55 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x) - 0.000001 : (x) + 0.000001)
57 #define MIN_KF_BOOST 300
58 #define MIN_GF_INTERVAL 4
59 #define LONG_TERM_VBR_CORRECTION
61 static void swap_yv12(YV12_BUFFER_CONFIG *a, YV12_BUFFER_CONFIG *b) {
62 YV12_BUFFER_CONFIG temp = *a;
67 static int gfboost_qadjust(int qindex) {
68 const double q = vp9_convert_qindex_to_q(qindex);
69 return (int)((0.00000828 * q * q * q) +
74 // Resets the first pass file to the given position using a relative seek from
75 // the current position.
76 static void reset_fpf_position(TWO_PASS *p,
77 const FIRSTPASS_STATS *position) {
78 p->stats_in = position;
81 static int lookup_next_frame_stats(const TWO_PASS *p,
82 FIRSTPASS_STATS *next_frame) {
83 if (p->stats_in >= p->stats_in_end)
86 *next_frame = *p->stats_in;
91 // Read frame stats at an offset from the current position.
92 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
93 if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
94 (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
98 return &p->stats_in[offset];
101 #if CONFIG_FP_MB_STATS
102 static int input_mb_stats(FIRSTPASS_FRAME_MB_STATS *fp_frame_stats,
103 const VP9_COMMON *const cm) {
107 fpfile = fopen("firstpass_mb.stt", "r");
108 fseek(fpfile, cm->current_video_frame * cm->MBs * sizeof(FIRSTPASS_MB_STATS),
110 ret = fread(fp_frame_stats->mb_stats, sizeof(FIRSTPASS_MB_STATS), cm->MBs,
119 static void output_mb_stats(FIRSTPASS_FRAME_MB_STATS *fp_frame_stats,
120 const VP9_COMMON *const cm) {
123 fpfile = fopen("firstpass_mb.stt", "a");
124 fwrite(fp_frame_stats->mb_stats, sizeof(FIRSTPASS_MB_STATS), cm->MBs, fpfile);
129 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
130 if (p->stats_in >= p->stats_in_end)
138 static void output_stats(FIRSTPASS_STATS *stats,
139 struct vpx_codec_pkt_list *pktlist) {
140 struct vpx_codec_cx_pkt pkt;
141 pkt.kind = VPX_CODEC_STATS_PKT;
142 pkt.data.twopass_stats.buf = stats;
143 pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
144 vpx_codec_pkt_list_add(pktlist, &pkt);
150 fpfile = fopen("firstpass.stt", "a");
152 fprintf(fpfile, "%12.0f %12.0f %12.0f %12.0f %12.4f %12.4f"
153 "%12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f"
154 "%12.0f %12.0f %12.4f %12.0f %12.0f %12.4f\n",
158 stats->sr_coded_error,
161 stats->pcnt_second_ref,
169 stats->mv_in_out_count,
178 static void zero_stats(FIRSTPASS_STATS *section) {
179 section->frame = 0.0;
180 section->intra_error = 0.0;
181 section->coded_error = 0.0;
182 section->sr_coded_error = 0.0;
183 section->pcnt_inter = 0.0;
184 section->pcnt_motion = 0.0;
185 section->pcnt_second_ref = 0.0;
186 section->pcnt_neutral = 0.0;
188 section->mvr_abs = 0.0;
190 section->mvc_abs = 0.0;
193 section->mv_in_out_count = 0.0;
194 section->new_mv_count = 0.0;
195 section->count = 0.0;
196 section->duration = 1.0;
197 section->spatial_layer_id = 0;
200 static void accumulate_stats(FIRSTPASS_STATS *section,
201 const FIRSTPASS_STATS *frame) {
202 section->frame += frame->frame;
203 section->spatial_layer_id = frame->spatial_layer_id;
204 section->intra_error += frame->intra_error;
205 section->coded_error += frame->coded_error;
206 section->sr_coded_error += frame->sr_coded_error;
207 section->pcnt_inter += frame->pcnt_inter;
208 section->pcnt_motion += frame->pcnt_motion;
209 section->pcnt_second_ref += frame->pcnt_second_ref;
210 section->pcnt_neutral += frame->pcnt_neutral;
211 section->MVr += frame->MVr;
212 section->mvr_abs += frame->mvr_abs;
213 section->MVc += frame->MVc;
214 section->mvc_abs += frame->mvc_abs;
215 section->MVrv += frame->MVrv;
216 section->MVcv += frame->MVcv;
217 section->mv_in_out_count += frame->mv_in_out_count;
218 section->new_mv_count += frame->new_mv_count;
219 section->count += frame->count;
220 section->duration += frame->duration;
223 static void subtract_stats(FIRSTPASS_STATS *section,
224 const FIRSTPASS_STATS *frame) {
225 section->frame -= frame->frame;
226 section->intra_error -= frame->intra_error;
227 section->coded_error -= frame->coded_error;
228 section->sr_coded_error -= frame->sr_coded_error;
229 section->pcnt_inter -= frame->pcnt_inter;
230 section->pcnt_motion -= frame->pcnt_motion;
231 section->pcnt_second_ref -= frame->pcnt_second_ref;
232 section->pcnt_neutral -= frame->pcnt_neutral;
233 section->MVr -= frame->MVr;
234 section->mvr_abs -= frame->mvr_abs;
235 section->MVc -= frame->MVc;
236 section->mvc_abs -= frame->mvc_abs;
237 section->MVrv -= frame->MVrv;
238 section->MVcv -= frame->MVcv;
239 section->mv_in_out_count -= frame->mv_in_out_count;
240 section->new_mv_count -= frame->new_mv_count;
241 section->count -= frame->count;
242 section->duration -= frame->duration;
245 static void avg_stats(FIRSTPASS_STATS *section) {
246 if (section->count < 1.0)
249 section->intra_error /= section->count;
250 section->coded_error /= section->count;
251 section->sr_coded_error /= section->count;
252 section->pcnt_inter /= section->count;
253 section->pcnt_second_ref /= section->count;
254 section->pcnt_neutral /= section->count;
255 section->pcnt_motion /= section->count;
256 section->MVr /= section->count;
257 section->mvr_abs /= section->count;
258 section->MVc /= section->count;
259 section->mvc_abs /= section->count;
260 section->MVrv /= section->count;
261 section->MVcv /= section->count;
262 section->mv_in_out_count /= section->count;
263 section->duration /= section->count;
266 // Calculate a modified Error used in distributing bits between easier and
268 static double calculate_modified_err(const TWO_PASS *twopass,
269 const VP9EncoderConfig *oxcf,
270 const FIRSTPASS_STATS *this_frame) {
271 const FIRSTPASS_STATS *const stats = &twopass->total_stats;
272 const double av_err = stats->coded_error / stats->count;
273 const double modified_error = av_err *
274 pow(this_frame->coded_error / DOUBLE_DIVIDE_CHECK(av_err),
275 oxcf->two_pass_vbrbias / 100.0);
276 return fclamp(modified_error,
277 twopass->modified_error_min, twopass->modified_error_max);
280 // This function returns the maximum target rate per frame.
281 static int frame_max_bits(const RATE_CONTROL *rc,
282 const VP9EncoderConfig *oxcf) {
283 int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
284 (int64_t)oxcf->two_pass_vbrmax_section) / 100;
287 else if (max_bits > rc->max_frame_bandwidth)
288 max_bits = rc->max_frame_bandwidth;
290 return (int)max_bits;
293 void vp9_init_first_pass(VP9_COMP *cpi) {
294 zero_stats(&cpi->twopass.total_stats);
297 void vp9_end_first_pass(VP9_COMP *cpi) {
298 if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
300 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
301 output_stats(&cpi->svc.layer_context[i].twopass.total_stats,
302 cpi->output_pkt_list);
305 output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
309 static vp9_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
322 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
323 const struct buf_2d *src,
324 const struct buf_2d *ref) {
326 const vp9_variance_fn_t fn = get_block_variance_fn(bsize);
327 fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
331 // Refine the motion search range according to the frame dimension
332 // for first pass test.
333 static int get_search_range(const VP9_COMMON *cm) {
335 const int dim = MIN(cm->width, cm->height);
337 while ((dim << sr) < MAX_FULL_PEL_VAL)
342 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
343 const MV *ref_mv, MV *best_mv,
344 int *best_motion_err) {
345 MACROBLOCKD *const xd = &x->e_mbd;
347 MV ref_mv_full = {ref_mv->row >> 3, ref_mv->col >> 3};
348 int num00, tmp_err, n;
349 const BLOCK_SIZE bsize = xd->mi[0]->mbmi.sb_type;
350 vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
351 const int new_mv_mode_penalty = 256;
354 int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
355 const int sr = get_search_range(&cpi->common);
359 // Override the default variance function to use MSE.
360 v_fn_ptr.vf = get_block_variance_fn(bsize);
362 // Center the initial step/diamond search on best mv.
363 tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
365 x->sadperbit16, &num00, &v_fn_ptr, ref_mv);
366 if (tmp_err < INT_MAX)
367 tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
368 if (tmp_err < INT_MAX - new_mv_mode_penalty)
369 tmp_err += new_mv_mode_penalty;
371 if (tmp_err < *best_motion_err) {
372 *best_motion_err = tmp_err;
376 // Carry out further step/diamond searches as necessary.
380 while (n < further_steps) {
386 tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
387 step_param + n, x->sadperbit16,
388 &num00, &v_fn_ptr, ref_mv);
389 if (tmp_err < INT_MAX)
390 tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
391 if (tmp_err < INT_MAX - new_mv_mode_penalty)
392 tmp_err += new_mv_mode_penalty;
394 if (tmp_err < *best_motion_err) {
395 *best_motion_err = tmp_err;
402 static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
403 if (2 * mb_col + 1 < cm->mi_cols) {
404 return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16
407 return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16
412 static int find_fp_qindex() {
415 for (i = 0; i < QINDEX_RANGE; ++i)
416 if (vp9_convert_qindex_to_q(i) >= 30.0)
419 if (i == QINDEX_RANGE)
425 static void set_first_pass_params(VP9_COMP *cpi) {
426 VP9_COMMON *const cm = &cpi->common;
427 if (!cpi->refresh_alt_ref_frame &&
428 (cm->current_video_frame == 0 ||
429 (cpi->frame_flags & FRAMEFLAGS_KEY))) {
430 cm->frame_type = KEY_FRAME;
432 cm->frame_type = INTER_FRAME;
434 // Do not use periodic key frames.
435 cpi->rc.frames_to_key = INT_MAX;
438 void vp9_first_pass(VP9_COMP *cpi) {
440 MACROBLOCK *const x = &cpi->mb;
441 VP9_COMMON *const cm = &cpi->common;
442 MACROBLOCKD *const xd = &x->e_mbd;
444 struct macroblock_plane *const p = x->plane;
445 struct macroblockd_plane *const pd = xd->plane;
446 const PICK_MODE_CONTEXT *ctx = &cpi->pc_root->none;
449 int recon_yoffset, recon_uvoffset;
450 YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
451 YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
452 YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
453 int recon_y_stride = lst_yv12->y_stride;
454 int recon_uv_stride = lst_yv12->uv_stride;
455 int uv_mb_height = 16 >> (lst_yv12->y_height > lst_yv12->uv_height);
456 int64_t intra_error = 0;
457 int64_t coded_error = 0;
458 int64_t sr_coded_error = 0;
460 int sum_mvr = 0, sum_mvc = 0;
461 int sum_mvr_abs = 0, sum_mvc_abs = 0;
462 int64_t sum_mvrs = 0, sum_mvcs = 0;
465 int second_ref_count = 0;
466 int intrapenalty = 256;
467 int neutral_count = 0;
468 int new_mv_count = 0;
469 int sum_in_vectors = 0;
470 uint32_t lastmv_as_int = 0;
471 TWO_PASS *twopass = &cpi->twopass;
472 const MV zero_mv = {0, 0};
473 const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
475 #if CONFIG_FP_MB_STATS
476 FIRSTPASS_FRAME_MB_STATS *this_frame_mb_stats = &twopass->this_frame_mb_stats;
479 vp9_clear_system_state();
481 set_first_pass_params(cpi);
482 vp9_set_quantizer(cm, find_fp_qindex());
484 if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
485 MV_REFERENCE_FRAME ref_frame = LAST_FRAME;
486 const YV12_BUFFER_CONFIG *scaled_ref_buf = NULL;
487 twopass = &cpi->svc.layer_context[cpi->svc.spatial_layer_id].twopass;
489 if (cpi->common.current_video_frame == 0) {
490 cpi->ref_frame_flags = 0;
492 LAYER_CONTEXT *lc = &cpi->svc.layer_context[cpi->svc.spatial_layer_id];
493 if (lc->current_video_frame_in_layer == 0)
494 cpi->ref_frame_flags = VP9_GOLD_FLAG;
496 cpi->ref_frame_flags = VP9_LAST_FLAG | VP9_GOLD_FLAG;
499 vp9_scale_references(cpi);
501 // Use either last frame or alt frame for motion search.
502 if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
503 scaled_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
504 ref_frame = LAST_FRAME;
505 } else if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
506 scaled_ref_buf = vp9_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
507 ref_frame = GOLDEN_FRAME;
510 if (scaled_ref_buf != NULL)
511 first_ref_buf = scaled_ref_buf;
513 recon_y_stride = new_yv12->y_stride;
514 recon_uv_stride = new_yv12->uv_stride;
515 uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
517 // Disable golden frame for svc first pass for now.
519 set_ref_ptrs(cm, xd, ref_frame, NONE);
521 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
522 &cpi->scaled_source);
525 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
527 vp9_setup_src_planes(x, cpi->Source, 0, 0);
528 vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
529 vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
531 xd->mi = cm->mi_grid_visible;
534 vp9_frame_init_quantizer(cpi);
536 for (i = 0; i < MAX_MB_PLANE; ++i) {
537 p[i].coeff = ctx->coeff_pbuf[i][1];
538 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
539 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
540 p[i].eobs = ctx->eobs_pbuf[i][1];
544 vp9_init_mv_probs(cm);
545 vp9_initialize_rd_consts(cpi);
547 // Tiling is ignored in the first pass.
548 vp9_tile_init(&tile, cm, 0, 0);
550 for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
553 best_ref_mv.as_int = 0;
555 // Reset above block coeffs.
556 xd->up_available = (mb_row != 0);
557 recon_yoffset = (mb_row * recon_y_stride * 16);
558 recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height);
560 // Set up limit values for motion vectors to prevent them extending
561 // outside the UMV borders.
562 x->mv_row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
563 x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16)
564 + BORDER_MV_PIXELS_B16;
566 for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
568 const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
569 double error_weight = 1.0;
570 const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
572 vp9_clear_system_state();
574 xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
575 xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
576 xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
577 xd->left_available = (mb_col != 0);
578 xd->mi[0]->mbmi.sb_type = bsize;
579 xd->mi[0]->mbmi.ref_frame[0] = INTRA_FRAME;
580 set_mi_row_col(xd, &tile,
581 mb_row << 1, num_8x8_blocks_high_lookup[bsize],
582 mb_col << 1, num_8x8_blocks_wide_lookup[bsize],
583 cm->mi_rows, cm->mi_cols);
585 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
586 const int energy = vp9_block_energy(cpi, x, bsize);
587 error_weight = vp9_vaq_inv_q_ratio(energy);
590 // Do intra 16x16 prediction.
592 xd->mi[0]->mbmi.mode = DC_PRED;
593 xd->mi[0]->mbmi.tx_size = use_dc_pred ?
594 (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
595 vp9_encode_intra_block_plane(x, bsize, 0);
596 this_error = vp9_get_mb_ss(x->plane[0].src_diff);
598 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
599 vp9_clear_system_state();
600 this_error = (int)(this_error * error_weight);
603 // Intrapenalty below deals with situations where the intra and inter
604 // error scores are very low (e.g. a plain black frame).
605 // We do not have special cases in first pass for 0,0 and nearest etc so
606 // all inter modes carry an overhead cost estimate for the mv.
607 // When the error score is very low this causes us to pick all or lots of
608 // INTRA modes and throw lots of key frames.
609 // This penalty adds a cost matching that of a 0,0 mv to the intra case.
610 this_error += intrapenalty;
612 // Accumulate the intra error.
613 intra_error += (int64_t)this_error;
615 #if CONFIG_FP_MB_STATS
616 if (cpi->use_fp_mb_stats) {
617 this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mode =
619 this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].err =
621 this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mv.as_int
626 // Set up limit values for motion vectors to prevent them extending
627 // outside the UMV borders.
628 x->mv_col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
629 x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
631 // Other than for the first frame do a motion search.
632 if (cm->current_video_frame > 0) {
633 int tmp_err, motion_error, raw_motion_error;
635 struct buf_2d unscaled_last_source_buf_2d;
637 xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
638 motion_error = get_prediction_error(bsize, &x->plane[0].src,
639 &xd->plane[0].pre[0]);
640 // Assume 0,0 motion with no mv overhead.
641 mv.as_int = tmp_mv.as_int = 0;
643 // Compute the motion error of the 0,0 motion using the last source
644 // frame as the reference. Skip the further motion search on
645 // reconstructed frame if this error is small.
646 unscaled_last_source_buf_2d.buf =
647 cpi->unscaled_last_source->y_buffer + recon_yoffset;
648 unscaled_last_source_buf_2d.stride =
649 cpi->unscaled_last_source->y_stride;
650 raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
651 &unscaled_last_source_buf_2d);
653 // TODO(pengchong): Replace the hard-coded threshold
654 if (raw_motion_error > 25 ||
655 (cpi->use_svc && cpi->svc.number_temporal_layers == 1)) {
656 // Test last reference frame using the previous best mv as the
657 // starting point (best reference) for the search.
658 first_pass_motion_search(cpi, x, &best_ref_mv.as_mv, &mv.as_mv,
660 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
661 vp9_clear_system_state();
662 motion_error = (int)(motion_error * error_weight);
665 // If the current best reference mv is not centered on 0,0 then do a
666 // 0,0 based search as well.
667 if (best_ref_mv.as_int) {
669 first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv.as_mv, &tmp_err);
670 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
671 vp9_clear_system_state();
672 tmp_err = (int)(tmp_err * error_weight);
675 if (tmp_err < motion_error) {
676 motion_error = tmp_err;
677 mv.as_int = tmp_mv.as_int;
681 // Search in an older reference frame.
682 if (cm->current_video_frame > 1 && gld_yv12 != NULL) {
683 // Assume 0,0 motion with no mv overhead.
686 xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
687 gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
688 &xd->plane[0].pre[0]);
690 first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv.as_mv,
692 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
693 vp9_clear_system_state();
694 gf_motion_error = (int)(gf_motion_error * error_weight);
697 if (gf_motion_error < motion_error && gf_motion_error < this_error)
700 // Reset to last frame as reference buffer.
701 xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
702 xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
703 xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
705 // In accumulating a score for the older reference frame take the
706 // best of the motion predicted score and the intra coded error
707 // (just as will be done for) accumulation of "coded_error" for
709 if (gf_motion_error < this_error)
710 sr_coded_error += gf_motion_error;
712 sr_coded_error += this_error;
714 sr_coded_error += motion_error;
717 sr_coded_error += motion_error;
720 // Start by assuming that intra mode is best.
721 best_ref_mv.as_int = 0;
723 if (motion_error <= this_error) {
724 // Keep a count of cases where the inter and intra were very close
725 // and very low. This helps with scene cut detection for example in
726 // cropped clips with black bars at the sides or top and bottom.
727 if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
728 this_error < 2 * intrapenalty)
733 this_error = motion_error;
734 xd->mi[0]->mbmi.mode = NEWMV;
735 xd->mi[0]->mbmi.mv[0] = mv;
736 xd->mi[0]->mbmi.tx_size = TX_4X4;
737 xd->mi[0]->mbmi.ref_frame[0] = LAST_FRAME;
738 xd->mi[0]->mbmi.ref_frame[1] = NONE;
739 vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
740 vp9_encode_sby_pass1(x, bsize);
741 sum_mvr += mv.as_mv.row;
742 sum_mvr_abs += abs(mv.as_mv.row);
743 sum_mvc += mv.as_mv.col;
744 sum_mvc_abs += abs(mv.as_mv.col);
745 sum_mvrs += mv.as_mv.row * mv.as_mv.row;
746 sum_mvcs += mv.as_mv.col * mv.as_mv.col;
749 best_ref_mv.as_int = mv.as_int;
751 #if CONFIG_FP_MB_STATS
752 if (cpi->use_fp_mb_stats) {
753 this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mode =
755 this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].err =
757 this_frame_mb_stats->mb_stats[mb_row * cm->mb_cols + mb_col].mv.
765 // Non-zero vector, was it different from the last non zero vector?
766 if (mv.as_int != lastmv_as_int)
768 lastmv_as_int = mv.as_int;
770 // Does the row vector point inwards or outwards?
771 if (mb_row < cm->mb_rows / 2) {
772 if (mv.as_mv.row > 0)
774 else if (mv.as_mv.row < 0)
776 } else if (mb_row > cm->mb_rows / 2) {
777 if (mv.as_mv.row > 0)
779 else if (mv.as_mv.row < 0)
783 // Does the col vector point inwards or outwards?
784 if (mb_col < cm->mb_cols / 2) {
785 if (mv.as_mv.col > 0)
787 else if (mv.as_mv.col < 0)
789 } else if (mb_col > cm->mb_cols / 2) {
790 if (mv.as_mv.col > 0)
792 else if (mv.as_mv.col < 0)
798 sr_coded_error += (int64_t)this_error;
800 coded_error += (int64_t)this_error;
802 // Adjust to the next column of MBs.
803 x->plane[0].src.buf += 16;
804 x->plane[1].src.buf += uv_mb_height;
805 x->plane[2].src.buf += uv_mb_height;
808 recon_uvoffset += uv_mb_height;
811 // Adjust to the next row of MBs.
812 x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
813 x->plane[1].src.buf += uv_mb_height * x->plane[1].src.stride -
814 uv_mb_height * cm->mb_cols;
815 x->plane[2].src.buf += uv_mb_height * x->plane[1].src.stride -
816 uv_mb_height * cm->mb_cols;
818 vp9_clear_system_state();
821 vp9_clear_system_state();
825 fps.frame = cm->current_video_frame;
826 fps.spatial_layer_id = cpi->svc.spatial_layer_id;
827 fps.intra_error = (double)(intra_error >> 8);
828 fps.coded_error = (double)(coded_error >> 8);
829 fps.sr_coded_error = (double)(sr_coded_error >> 8);
831 fps.pcnt_inter = (double)intercount / cm->MBs;
832 fps.pcnt_second_ref = (double)second_ref_count / cm->MBs;
833 fps.pcnt_neutral = (double)neutral_count / cm->MBs;
836 fps.MVr = (double)sum_mvr / mvcount;
837 fps.mvr_abs = (double)sum_mvr_abs / mvcount;
838 fps.MVc = (double)sum_mvc / mvcount;
839 fps.mvc_abs = (double)sum_mvc_abs / mvcount;
840 fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / mvcount)) / mvcount;
841 fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / mvcount)) / mvcount;
842 fps.mv_in_out_count = (double)sum_in_vectors / (mvcount * 2);
843 fps.new_mv_count = new_mv_count;
844 fps.pcnt_motion = (double)mvcount / cm->MBs;
852 fps.mv_in_out_count = 0.0;
853 fps.new_mv_count = 0.0;
854 fps.pcnt_motion = 0.0;
857 // TODO(paulwilkins): Handle the case when duration is set to 0, or
858 // something less than the full time between subsequent values of
859 // cpi->source_time_stamp.
860 fps.duration = (double)(cpi->source->ts_end - cpi->source->ts_start);
862 // Don't want to do output stats with a stack variable!
863 twopass->this_frame_stats = fps;
864 output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
865 accumulate_stats(&twopass->total_stats, &fps);
867 #if CONFIG_FP_MB_STATS
868 if (cpi->use_fp_mb_stats) {
869 output_mb_stats(this_frame_mb_stats, cm);
874 // Copy the previous Last Frame back into gf and and arf buffers if
875 // the prediction is good enough... but also don't allow it to lag too far.
876 if ((twopass->sr_update_lag > 3) ||
877 ((cm->current_video_frame > 0) &&
878 (twopass->this_frame_stats.pcnt_inter > 0.20) &&
879 ((twopass->this_frame_stats.intra_error /
880 DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
881 if (gld_yv12 != NULL) {
882 vp8_yv12_copy_frame(lst_yv12, gld_yv12);
884 twopass->sr_update_lag = 1;
886 ++twopass->sr_update_lag;
889 vp9_extend_frame_borders(new_yv12);
891 if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
892 vp9_update_reference_frames(cpi);
894 // Swap frame pointers so last frame refers to the frame we just compressed.
895 swap_yv12(lst_yv12, new_yv12);
898 // Special case for the first frame. Copy into the GF buffer as a second
900 if (cm->current_video_frame == 0 && gld_yv12 != NULL) {
901 vp8_yv12_copy_frame(lst_yv12, gld_yv12);
904 // Use this to see what the first pass reconstruction looks like.
908 snprintf(filename, sizeof(filename), "enc%04d.yuv",
909 (int)cm->current_video_frame);
911 if (cm->current_video_frame == 0)
912 recon_file = fopen(filename, "wb");
914 recon_file = fopen(filename, "ab");
916 (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
920 ++cm->current_video_frame;
922 vp9_inc_frame_in_layer(&cpi->svc);
925 static double calc_correction_factor(double err_per_mb,
930 const double error_term = err_per_mb / err_divisor;
932 // Adjustment based on actual quantizer to power term.
933 const double power_term = MIN(vp9_convert_qindex_to_q(q) * 0.0125 + pt_low,
936 // Calculate correction factor.
937 if (power_term < 1.0)
938 assert(error_term >= 0.0);
940 return fclamp(pow(error_term, power_term), 0.05, 5.0);
943 static int get_twopass_worst_quality(const VP9_COMP *cpi,
944 const FIRSTPASS_STATS *stats,
945 int section_target_bandwidth) {
946 const RATE_CONTROL *const rc = &cpi->rc;
947 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
949 if (section_target_bandwidth <= 0) {
950 return rc->worst_quality; // Highest value allowed
952 const int num_mbs = cpi->common.MBs;
953 const double section_err = stats->coded_error / stats->count;
954 const double err_per_mb = section_err / num_mbs;
955 const double speed_term = 1.0 + 0.04 * oxcf->speed;
956 const int target_norm_bits_per_mb = ((uint64_t)section_target_bandwidth <<
957 BPER_MB_NORMBITS) / num_mbs;
959 int is_svc_upper_layer = 0;
960 if (cpi->use_svc && cpi->svc.number_temporal_layers == 1 &&
961 cpi->svc.spatial_layer_id > 0) {
962 is_svc_upper_layer = 1;
965 // Try and pick a max Q that will be high enough to encode the
966 // content at the given rate.
967 for (q = rc->best_quality; q < rc->worst_quality; ++q) {
968 const double factor =
969 calc_correction_factor(err_per_mb, ERR_DIVISOR,
970 is_svc_upper_layer ? SVC_FACTOR_PT_LOW :
971 FACTOR_PT_LOW, FACTOR_PT_HIGH, q);
972 const int bits_per_mb = vp9_rc_bits_per_mb(INTER_FRAME, q,
973 factor * speed_term);
974 if (bits_per_mb <= target_norm_bits_per_mb)
978 // Restriction on active max q for constrained quality mode.
979 if (cpi->oxcf.rc_mode == VPX_CQ)
980 q = MAX(q, oxcf->cq_level);
985 extern void vp9_new_framerate(VP9_COMP *cpi, double framerate);
987 void vp9_init_second_pass(VP9_COMP *cpi) {
988 SVC *const svc = &cpi->svc;
989 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
990 const int is_spatial_svc = (svc->number_spatial_layers > 1) &&
991 (svc->number_temporal_layers == 1);
992 TWO_PASS *const twopass = is_spatial_svc ?
993 &svc->layer_context[svc->spatial_layer_id].twopass : &cpi->twopass;
995 FIRSTPASS_STATS *stats;
997 zero_stats(&twopass->total_stats);
998 zero_stats(&twopass->total_left_stats);
1000 if (!twopass->stats_in_end)
1003 stats = &twopass->total_stats;
1005 *stats = *twopass->stats_in_end;
1006 twopass->total_left_stats = *stats;
1008 frame_rate = 10000000.0 * stats->count / stats->duration;
1009 // Each frame can have a different duration, as the frame rate in the source
1010 // isn't guaranteed to be constant. The frame rate prior to the first frame
1011 // encoded in the second pass is a guess. However, the sum duration is not.
1012 // It is calculated based on the actual durations of all frames from the
1015 if (is_spatial_svc) {
1016 vp9_update_spatial_layer_framerate(cpi, frame_rate);
1017 twopass->bits_left = (int64_t)(stats->duration *
1018 svc->layer_context[svc->spatial_layer_id].target_bandwidth /
1021 vp9_new_framerate(cpi, frame_rate);
1022 twopass->bits_left = (int64_t)(stats->duration * oxcf->target_bandwidth /
1026 // Calculate a minimum intra value to be used in determining the IIratio
1027 // scores used in the second pass. We have this minimum to make sure
1028 // that clips that are static but "low complexity" in the intra domain
1029 // are still boosted appropriately for KF/GF/ARF.
1030 if (!is_spatial_svc) {
1031 // We don't know the number of MBs for each layer at this point.
1032 // So we will do it later.
1033 twopass->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
1034 twopass->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
1037 // This variable monitors how far behind the second ref update is lagging.
1038 twopass->sr_update_lag = 1;
1040 // Scan the first pass file and calculate a modified total error based upon
1041 // the bias/power function used to allocate bits.
1043 const double avg_error = stats->coded_error /
1044 DOUBLE_DIVIDE_CHECK(stats->count);
1045 const FIRSTPASS_STATS *s = twopass->stats_in;
1046 double modified_error_total = 0.0;
1047 twopass->modified_error_min = (avg_error *
1048 oxcf->two_pass_vbrmin_section) / 100;
1049 twopass->modified_error_max = (avg_error *
1050 oxcf->two_pass_vbrmax_section) / 100;
1051 while (s < twopass->stats_in_end) {
1052 modified_error_total += calculate_modified_err(twopass, oxcf, s);
1055 twopass->modified_error_left = modified_error_total;
1058 // Reset the vbr bits off target counter
1059 cpi->rc.vbr_bits_off_target = 0;
1062 // This function gives an estimate of how badly we believe the prediction
1063 // quality is decaying from frame to frame.
1064 static double get_prediction_decay_rate(const VP9_COMMON *cm,
1065 const FIRSTPASS_STATS *next_frame) {
1066 // Look at the observed drop in prediction quality between the last frame
1067 // and the GF buffer (which contains an older frame).
1068 const double mb_sr_err_diff = (next_frame->sr_coded_error -
1069 next_frame->coded_error) / cm->MBs;
1070 const double second_ref_decay = mb_sr_err_diff <= 512.0
1071 ? fclamp(pow(1.0 - (mb_sr_err_diff / 512.0), 0.5), 0.85, 1.0)
1074 return MIN(second_ref_decay, next_frame->pcnt_inter);
1077 // Function to test for a condition where a complex transition is followed
1078 // by a static section. For example in slide shows where there is a fade
1079 // between slides. This is to help with more optimal kf and gf positioning.
1080 static int detect_transition_to_still(TWO_PASS *twopass,
1081 int frame_interval, int still_interval,
1082 double loop_decay_rate,
1083 double last_decay_rate) {
1084 int trans_to_still = 0;
1086 // Break clause to detect very still sections after motion
1087 // For example a static image after a fade or other transition
1088 // instead of a clean scene cut.
1089 if (frame_interval > MIN_GF_INTERVAL &&
1090 loop_decay_rate >= 0.999 &&
1091 last_decay_rate < 0.9) {
1093 const FIRSTPASS_STATS *position = twopass->stats_in;
1094 FIRSTPASS_STATS tmp_next_frame;
1096 // Look ahead a few frames to see if static condition persists...
1097 for (j = 0; j < still_interval; ++j) {
1098 if (EOF == input_stats(twopass, &tmp_next_frame))
1101 if (tmp_next_frame.pcnt_inter - tmp_next_frame.pcnt_motion < 0.999)
1105 reset_fpf_position(twopass, position);
1107 // Only if it does do we signal a transition to still.
1108 if (j == still_interval)
1112 return trans_to_still;
1115 // This function detects a flash through the high relative pcnt_second_ref
1116 // score in the frame following a flash frame. The offset passed in should
1118 static int detect_flash(const TWO_PASS *twopass, int offset) {
1119 const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
1121 // What we are looking for here is a situation where there is a
1122 // brief break in prediction (such as a flash) but subsequent frames
1123 // are reasonably well predicted by an earlier (pre flash) frame.
1124 // The recovery after a flash is indicated by a high pcnt_second_ref
1125 // compared to pcnt_inter.
1126 return next_frame != NULL &&
1127 next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
1128 next_frame->pcnt_second_ref >= 0.5;
1131 // Update the motion related elements to the GF arf boost calculation.
1132 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1134 double *mv_in_out_accumulator,
1135 double *abs_mv_in_out_accumulator,
1136 double *mv_ratio_accumulator) {
1137 const double pct = stats->pcnt_motion;
1139 // Accumulate Motion In/Out of frame stats.
1140 *mv_in_out = stats->mv_in_out_count * pct;
1141 *mv_in_out_accumulator += *mv_in_out;
1142 *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1144 // Accumulate a measure of how uniform (or conversely how random) the motion
1145 // field is (a ratio of abs(mv) / mv).
1147 const double mvr_ratio = fabs(stats->mvr_abs) /
1148 DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1149 const double mvc_ratio = fabs(stats->mvc_abs) /
1150 DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1152 *mv_ratio_accumulator += pct * (mvr_ratio < stats->mvr_abs ?
1153 mvr_ratio : stats->mvr_abs);
1154 *mv_ratio_accumulator += pct * (mvc_ratio < stats->mvc_abs ?
1155 mvc_ratio : stats->mvc_abs);
1159 // Calculate a baseline boost number for the current frame.
1160 static double calc_frame_boost(const TWO_PASS *twopass,
1161 const FIRSTPASS_STATS *this_frame,
1162 double this_frame_mv_in_out) {
1165 // Underlying boost factor is based on inter intra error ratio.
1166 if (this_frame->intra_error > twopass->gf_intra_err_min)
1167 frame_boost = (IIFACTOR * this_frame->intra_error /
1168 DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1170 frame_boost = (IIFACTOR * twopass->gf_intra_err_min /
1171 DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1173 // Increase boost for frames where new data coming into frame (e.g. zoom out).
1174 // Slightly reduce boost if there is a net balance of motion out of the frame
1175 // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
1176 if (this_frame_mv_in_out > 0.0)
1177 frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1178 // In the extreme case the boost is halved.
1180 frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1182 return MIN(frame_boost, GF_RMAX);
1185 static int calc_arf_boost(VP9_COMP *cpi, int offset,
1186 int f_frames, int b_frames,
1187 int *f_boost, int *b_boost) {
1188 TWO_PASS *const twopass = &cpi->twopass;
1190 double boost_score = 0.0;
1191 double mv_ratio_accumulator = 0.0;
1192 double decay_accumulator = 1.0;
1193 double this_frame_mv_in_out = 0.0;
1194 double mv_in_out_accumulator = 0.0;
1195 double abs_mv_in_out_accumulator = 0.0;
1197 int flash_detected = 0;
1199 // Search forward from the proposed arf/next gf position.
1200 for (i = 0; i < f_frames; ++i) {
1201 const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1202 if (this_frame == NULL)
1205 // Update the motion related elements to the boost calculation.
1206 accumulate_frame_motion_stats(this_frame,
1207 &this_frame_mv_in_out, &mv_in_out_accumulator,
1208 &abs_mv_in_out_accumulator,
1209 &mv_ratio_accumulator);
1211 // We want to discount the flash frame itself and the recovery
1212 // frame that follows as both will have poor scores.
1213 flash_detected = detect_flash(twopass, i + offset) ||
1214 detect_flash(twopass, i + offset + 1);
1216 // Accumulate the effect of prediction quality decay.
1217 if (!flash_detected) {
1218 decay_accumulator *= get_prediction_decay_rate(&cpi->common, this_frame);
1219 decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1220 ? MIN_DECAY_FACTOR : decay_accumulator;
1223 boost_score += decay_accumulator * calc_frame_boost(twopass, this_frame,
1224 this_frame_mv_in_out);
1227 *f_boost = (int)boost_score;
1229 // Reset for backward looking loop.
1231 mv_ratio_accumulator = 0.0;
1232 decay_accumulator = 1.0;
1233 this_frame_mv_in_out = 0.0;
1234 mv_in_out_accumulator = 0.0;
1235 abs_mv_in_out_accumulator = 0.0;
1237 // Search backward towards last gf position.
1238 for (i = -1; i >= -b_frames; --i) {
1239 const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
1240 if (this_frame == NULL)
1243 // Update the motion related elements to the boost calculation.
1244 accumulate_frame_motion_stats(this_frame,
1245 &this_frame_mv_in_out, &mv_in_out_accumulator,
1246 &abs_mv_in_out_accumulator,
1247 &mv_ratio_accumulator);
1249 // We want to discount the the flash frame itself and the recovery
1250 // frame that follows as both will have poor scores.
1251 flash_detected = detect_flash(twopass, i + offset) ||
1252 detect_flash(twopass, i + offset + 1);
1254 // Cumulative effect of prediction quality decay.
1255 if (!flash_detected) {
1256 decay_accumulator *= get_prediction_decay_rate(&cpi->common, this_frame);
1257 decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
1258 ? MIN_DECAY_FACTOR : decay_accumulator;
1261 boost_score += decay_accumulator * calc_frame_boost(twopass, this_frame,
1262 this_frame_mv_in_out);
1264 *b_boost = (int)boost_score;
1266 arf_boost = (*f_boost + *b_boost);
1267 if (arf_boost < ((b_frames + f_frames) * 20))
1268 arf_boost = ((b_frames + f_frames) * 20);
1273 // Calculate a section intra ratio used in setting max loop filter.
1274 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
1275 const FIRSTPASS_STATS *end,
1276 int section_length) {
1277 const FIRSTPASS_STATS *s = begin;
1278 double intra_error = 0.0;
1279 double coded_error = 0.0;
1282 while (s < end && i < section_length) {
1283 intra_error += s->intra_error;
1284 coded_error += s->coded_error;
1289 return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
1292 // Calculate the total bits to allocate in this GF/ARF group.
1293 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
1294 double gf_group_err) {
1295 const RATE_CONTROL *const rc = &cpi->rc;
1296 const TWO_PASS *const twopass = &cpi->twopass;
1297 const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1298 int64_t total_group_bits;
1300 // Calculate the bits to be allocated to the group as a whole.
1301 if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
1302 total_group_bits = (int64_t)(twopass->kf_group_bits *
1303 (gf_group_err / twopass->kf_group_error_left));
1305 total_group_bits = 0;
1308 // Clamp odd edge cases.
1309 total_group_bits = (total_group_bits < 0) ?
1310 0 : (total_group_bits > twopass->kf_group_bits) ?
1311 twopass->kf_group_bits : total_group_bits;
1313 // Clip based on user supplied data rate variability limit.
1314 if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
1315 total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
1317 return total_group_bits;
1320 // Calculate the number bits extra to assign to boosted frames in a group.
1321 static int calculate_boost_bits(int frame_count,
1322 int boost, int64_t total_group_bits) {
1323 int allocation_chunks;
1325 // return 0 for invalid inputs (could arise e.g. through rounding errors)
1326 if (!boost || (total_group_bits <= 0) || (frame_count <= 0) )
1329 allocation_chunks = (frame_count * 100) + boost;
1331 // Prevent overflow.
1333 int divisor = boost >> 10;
1335 allocation_chunks /= divisor;
1338 // Calculate the number of extra bits for use in the boosted frame or frames.
1339 return MAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks), 0);
1342 // Current limit on maximum number of active arfs in a GF/ARF group.
1343 #define MAX_ACTIVE_ARFS 2
1346 // This function indirects the choice of buffers for arfs.
1347 // At the moment the values are fixed but this may change as part of
1348 // the integration process with other codec features that swap buffers around.
1349 static void get_arf_buffer_indices(unsigned char *arf_buffer_indices) {
1350 arf_buffer_indices[0] = ARF_SLOT1;
1351 arf_buffer_indices[1] = ARF_SLOT2;
1354 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
1355 double group_error, int gf_arf_bits) {
1356 RATE_CONTROL *const rc = &cpi->rc;
1357 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1358 TWO_PASS *twopass = &cpi->twopass;
1359 FIRSTPASS_STATS frame_stats;
1361 int frame_index = 1;
1362 int target_frame_size;
1364 const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
1365 int64_t total_group_bits = gf_group_bits;
1366 double modified_err = 0.0;
1367 double err_fraction;
1368 int mid_boost_bits = 0;
1370 unsigned char arf_buffer_indices[MAX_ACTIVE_ARFS];
1372 key_frame = cpi->common.frame_type == KEY_FRAME ||
1373 vp9_is_upper_layer_key_frame(cpi);
1375 get_arf_buffer_indices(arf_buffer_indices);
1377 // For key frames the frame target rate is already set and it
1378 // is also the golden frame.
1380 if (rc->source_alt_ref_active) {
1381 twopass->gf_group.update_type[0] = OVERLAY_UPDATE;
1382 twopass->gf_group.rf_level[0] = INTER_NORMAL;
1383 twopass->gf_group.bit_allocation[0] = 0;
1384 twopass->gf_group.arf_update_idx[0] = arf_buffer_indices[0];
1385 twopass->gf_group.arf_ref_idx[0] = arf_buffer_indices[0];
1387 twopass->gf_group.update_type[0] = GF_UPDATE;
1388 twopass->gf_group.rf_level[0] = GF_ARF_STD;
1389 twopass->gf_group.bit_allocation[0] = gf_arf_bits;
1390 twopass->gf_group.arf_update_idx[0] = arf_buffer_indices[0];
1391 twopass->gf_group.arf_ref_idx[0] = arf_buffer_indices[0];
1394 // Step over the golden frame / overlay frame
1395 if (EOF == input_stats(twopass, &frame_stats))
1399 // Deduct the boost bits for arf (or gf if it is not a key frame)
1400 // from the group total.
1401 if (rc->source_alt_ref_pending || !key_frame)
1402 total_group_bits -= gf_arf_bits;
1404 // Store the bits to spend on the ARF if there is one.
1405 if (rc->source_alt_ref_pending) {
1406 twopass->gf_group.update_type[frame_index] = ARF_UPDATE;
1407 twopass->gf_group.rf_level[frame_index] = GF_ARF_STD;
1408 twopass->gf_group.bit_allocation[frame_index] = gf_arf_bits;
1409 twopass->gf_group.arf_src_offset[frame_index] =
1410 (unsigned char)(rc->baseline_gf_interval - 1);
1411 twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[0];
1412 twopass->gf_group.arf_ref_idx[frame_index] =
1413 arf_buffer_indices[cpi->multi_arf_last_grp_enabled &&
1414 rc->source_alt_ref_active];
1417 if (cpi->multi_arf_enabled) {
1418 // Set aside a slot for a level 1 arf.
1419 twopass->gf_group.update_type[frame_index] = ARF_UPDATE;
1420 twopass->gf_group.rf_level[frame_index] = GF_ARF_LOW;
1421 twopass->gf_group.arf_src_offset[frame_index] =
1422 (unsigned char)((rc->baseline_gf_interval >> 1) - 1);
1423 twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[1];
1424 twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[0];
1429 // Define middle frame
1430 mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
1432 // Allocate bits to the other frames in the group.
1433 for (i = 0; i < rc->baseline_gf_interval - 1; ++i) {
1435 if (EOF == input_stats(twopass, &frame_stats))
1438 modified_err = calculate_modified_err(twopass, oxcf, &frame_stats);
1440 if (group_error > 0)
1441 err_fraction = modified_err / DOUBLE_DIVIDE_CHECK(group_error);
1445 target_frame_size = (int)((double)total_group_bits * err_fraction);
1447 if (rc->source_alt_ref_pending && cpi->multi_arf_enabled) {
1448 mid_boost_bits += (target_frame_size >> 4);
1449 target_frame_size -= (target_frame_size >> 4);
1451 if (frame_index <= mid_frame_idx)
1454 twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[arf_idx];
1455 twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[arf_idx];
1457 target_frame_size = clamp(target_frame_size, 0,
1458 MIN(max_bits, (int)total_group_bits));
1460 twopass->gf_group.update_type[frame_index] = LF_UPDATE;
1461 twopass->gf_group.rf_level[frame_index] = INTER_NORMAL;
1463 twopass->gf_group.bit_allocation[frame_index] = target_frame_size;
1468 // We need to configure the frame at the end of the sequence + 1 that will be
1469 // the start frame for the next group. Otherwise prior to the call to
1470 // vp9_rc_get_second_pass_params() the data will be undefined.
1471 twopass->gf_group.arf_update_idx[frame_index] = arf_buffer_indices[0];
1472 twopass->gf_group.arf_ref_idx[frame_index] = arf_buffer_indices[0];
1474 if (rc->source_alt_ref_pending) {
1475 twopass->gf_group.update_type[frame_index] = OVERLAY_UPDATE;
1476 twopass->gf_group.rf_level[frame_index] = INTER_NORMAL;
1478 // Final setup for second arf and its overlay.
1479 if (cpi->multi_arf_enabled) {
1480 twopass->gf_group.bit_allocation[2] =
1481 twopass->gf_group.bit_allocation[mid_frame_idx] + mid_boost_bits;
1482 twopass->gf_group.update_type[mid_frame_idx] = OVERLAY_UPDATE;
1483 twopass->gf_group.bit_allocation[mid_frame_idx] = 0;
1486 twopass->gf_group.update_type[frame_index] = GF_UPDATE;
1487 twopass->gf_group.rf_level[frame_index] = GF_ARF_STD;
1490 // Note whether multi-arf was enabled this group for next time.
1491 cpi->multi_arf_last_grp_enabled = cpi->multi_arf_enabled;
1494 // Analyse and define a gf/arf group.
1495 static void define_gf_group(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1496 RATE_CONTROL *const rc = &cpi->rc;
1497 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1498 TWO_PASS *const twopass = &cpi->twopass;
1499 FIRSTPASS_STATS next_frame;
1500 const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
1503 double boost_score = 0.0;
1504 double old_boost_score = 0.0;
1505 double gf_group_err = 0.0;
1506 double gf_first_frame_err = 0.0;
1507 double mod_frame_err = 0.0;
1509 double mv_ratio_accumulator = 0.0;
1510 double decay_accumulator = 1.0;
1511 double zero_motion_accumulator = 1.0;
1513 double loop_decay_rate = 1.00;
1514 double last_loop_decay_rate = 1.00;
1516 double this_frame_mv_in_out = 0.0;
1517 double mv_in_out_accumulator = 0.0;
1518 double abs_mv_in_out_accumulator = 0.0;
1519 double mv_ratio_accumulator_thresh;
1520 unsigned int allow_alt_ref = is_altref_enabled(cpi);
1525 int active_max_gf_interval;
1526 int64_t gf_group_bits;
1527 double gf_group_error_left;
1530 // Reset the GF group data structures unless this is a key
1531 // frame in which case it will already have been done.
1532 if (cpi->common.frame_type != KEY_FRAME) {
1533 vp9_zero(twopass->gf_group);
1536 vp9_clear_system_state();
1537 vp9_zero(next_frame);
1541 // Load stats for the current frame.
1542 mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1544 // Note the error of the frame at the start of the group. This will be
1545 // the GF frame error if we code a normal gf.
1546 gf_first_frame_err = mod_frame_err;
1548 // If this is a key frame or the overlay from a previous arf then
1549 // the error score / cost of this frame has already been accounted for.
1550 if (cpi->common.frame_type == KEY_FRAME || rc->source_alt_ref_active)
1551 gf_group_err -= gf_first_frame_err;
1553 // Motion breakout threshold for loop below depends on image size.
1554 mv_ratio_accumulator_thresh = (cpi->common.width + cpi->common.height) / 10.0;
1556 // Work out a maximum interval for the GF group.
1557 // If the image appears almost completely static we can extend beyond this.
1558 if (cpi->multi_arf_allowed) {
1559 active_max_gf_interval = rc->max_gf_interval;
1561 // The value chosen depends on the active Q range. At low Q we have
1562 // bits to spare and are better with a smaller interval and smaller boost.
1563 // At high Q when there are few bits to spare we are better with a longer
1564 // interval to spread the cost of the GF.
1565 active_max_gf_interval =
1566 12 + ((int)vp9_convert_qindex_to_q(rc->last_q[INTER_FRAME]) >> 5);
1568 if (active_max_gf_interval > rc->max_gf_interval)
1569 active_max_gf_interval = rc->max_gf_interval;
1573 while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
1576 // Accumulate error score of frames in this gf group.
1577 mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1578 gf_group_err += mod_frame_err;
1580 if (EOF == input_stats(twopass, &next_frame))
1583 // Test for the case where there is a brief flash but the prediction
1584 // quality back to an earlier frame is then restored.
1585 flash_detected = detect_flash(twopass, 0);
1587 // Update the motion related elements to the boost calculation.
1588 accumulate_frame_motion_stats(&next_frame,
1589 &this_frame_mv_in_out, &mv_in_out_accumulator,
1590 &abs_mv_in_out_accumulator,
1591 &mv_ratio_accumulator);
1593 // Accumulate the effect of prediction quality decay.
1594 if (!flash_detected) {
1595 last_loop_decay_rate = loop_decay_rate;
1596 loop_decay_rate = get_prediction_decay_rate(&cpi->common, &next_frame);
1597 decay_accumulator = decay_accumulator * loop_decay_rate;
1599 // Monitor for static sections.
1600 if ((next_frame.pcnt_inter - next_frame.pcnt_motion) <
1601 zero_motion_accumulator) {
1602 zero_motion_accumulator = next_frame.pcnt_inter -
1603 next_frame.pcnt_motion;
1606 // Break clause to detect very still sections after motion. For example,
1607 // a static image after a fade or other transition.
1608 if (detect_transition_to_still(twopass, i, 5, loop_decay_rate,
1609 last_loop_decay_rate)) {
1615 // Calculate a boost number for this frame.
1616 boost_score += decay_accumulator * calc_frame_boost(twopass, &next_frame,
1617 this_frame_mv_in_out);
1619 // Break out conditions.
1621 // Break at active_max_gf_interval unless almost totally static.
1622 (i >= active_max_gf_interval && (zero_motion_accumulator < 0.995)) ||
1624 // Don't break out with a very short interval.
1625 (i > MIN_GF_INTERVAL) &&
1626 ((boost_score > 125.0) || (next_frame.pcnt_inter < 0.75)) &&
1627 (!flash_detected) &&
1628 ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
1629 (abs_mv_in_out_accumulator > 3.0) ||
1630 (mv_in_out_accumulator < -2.0) ||
1631 ((boost_score - old_boost_score) < IIFACTOR)))) {
1632 boost_score = old_boost_score;
1636 *this_frame = next_frame;
1638 old_boost_score = boost_score;
1641 twopass->gf_zeromotion_pct = (int)(zero_motion_accumulator * 1000.0);
1643 // Don't allow a gf too near the next kf.
1644 if ((rc->frames_to_key - i) < MIN_GF_INTERVAL) {
1645 while (i < (rc->frames_to_key + !rc->next_key_frame_forced)) {
1648 if (EOF == input_stats(twopass, this_frame))
1651 if (i < rc->frames_to_key) {
1652 mod_frame_err = calculate_modified_err(twopass, oxcf, this_frame);
1653 gf_group_err += mod_frame_err;
1658 // Set the interval until the next gf.
1659 if (cpi->common.frame_type == KEY_FRAME || rc->source_alt_ref_active)
1660 rc->baseline_gf_interval = i - 1;
1662 rc->baseline_gf_interval = i;
1664 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1666 // Should we use the alternate reference frame.
1667 if (allow_alt_ref &&
1668 (i < cpi->oxcf.lag_in_frames) &&
1669 (i >= MIN_GF_INTERVAL) &&
1670 // For real scene cuts (not forced kfs) don't allow arf very near kf.
1671 (rc->next_key_frame_forced ||
1672 (i <= (rc->frames_to_key - MIN_GF_INTERVAL)))) {
1673 // Calculate the boost for alt ref.
1674 rc->gfu_boost = calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost,
1676 rc->source_alt_ref_pending = 1;
1678 // Test to see if multi arf is appropriate.
1679 cpi->multi_arf_enabled =
1680 (cpi->multi_arf_allowed && (rc->baseline_gf_interval >= 6) &&
1681 (zero_motion_accumulator < 0.995)) ? 1 : 0;
1683 rc->gfu_boost = (int)boost_score;
1684 rc->source_alt_ref_pending = 0;
1687 // Reset the file position.
1688 reset_fpf_position(twopass, start_pos);
1690 // Calculate the bits to be allocated to the gf/arf group as a whole
1691 gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
1693 // Calculate the extra bits to be used for boosted frame(s)
1695 int q = rc->last_q[INTER_FRAME];
1696 int boost = (rc->gfu_boost * gfboost_qadjust(q)) / 100;
1698 // Set max and minimum boost and hence minimum allocation.
1699 boost = clamp(boost, 125, (rc->baseline_gf_interval + 1) * 200);
1701 // Calculate the extra bits to be used for boosted frame(s)
1702 gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval,
1703 boost, gf_group_bits);
1706 // Adjust KF group bits and error remaining.
1707 twopass->kf_group_error_left -= (int64_t)gf_group_err;
1709 // If this is an arf update we want to remove the score for the overlay
1710 // frame at the end which will usually be very cheap to code.
1711 // The overlay frame has already, in effect, been coded so we want to spread
1712 // the remaining bits among the other frames.
1713 // For normal GFs remove the score for the GF itself unless this is
1714 // also a key frame in which case it has already been accounted for.
1715 if (rc->source_alt_ref_pending) {
1716 gf_group_error_left = gf_group_err - mod_frame_err;
1717 } else if (cpi->common.frame_type != KEY_FRAME) {
1718 gf_group_error_left = gf_group_err - gf_first_frame_err;
1720 gf_group_error_left = gf_group_err;
1723 // Allocate bits to each of the frames in the GF group.
1724 allocate_gf_group_bits(cpi, gf_group_bits, gf_group_error_left, gf_arf_bits);
1726 // Reset the file position.
1727 reset_fpf_position(twopass, start_pos);
1729 // Calculate a section intra ratio used in setting max loop filter.
1730 if (cpi->common.frame_type != KEY_FRAME) {
1731 twopass->section_intra_rating =
1732 calculate_section_intra_ratio(start_pos, twopass->stats_in_end,
1733 rc->baseline_gf_interval);
1737 static int test_candidate_kf(TWO_PASS *twopass,
1738 const FIRSTPASS_STATS *last_frame,
1739 const FIRSTPASS_STATS *this_frame,
1740 const FIRSTPASS_STATS *next_frame) {
1741 int is_viable_kf = 0;
1743 // Does the frame satisfy the primary criteria of a key frame?
1744 // If so, then examine how well it predicts subsequent frames.
1745 if ((this_frame->pcnt_second_ref < 0.10) &&
1746 (next_frame->pcnt_second_ref < 0.10) &&
1747 ((this_frame->pcnt_inter < 0.05) ||
1748 (((this_frame->pcnt_inter - this_frame->pcnt_neutral) < 0.35) &&
1749 ((this_frame->intra_error /
1750 DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) < 2.5) &&
1751 ((fabs(last_frame->coded_error - this_frame->coded_error) /
1752 DOUBLE_DIVIDE_CHECK(this_frame->coded_error) > 0.40) ||
1753 (fabs(last_frame->intra_error - this_frame->intra_error) /
1754 DOUBLE_DIVIDE_CHECK(this_frame->intra_error) > 0.40) ||
1755 ((next_frame->intra_error /
1756 DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) > 3.5))))) {
1758 const FIRSTPASS_STATS *start_pos = twopass->stats_in;
1759 FIRSTPASS_STATS local_next_frame = *next_frame;
1760 double boost_score = 0.0;
1761 double old_boost_score = 0.0;
1762 double decay_accumulator = 1.0;
1764 // Examine how well the key frame predicts subsequent frames.
1765 for (i = 0; i < 16; ++i) {
1766 double next_iiratio = (IIKFACTOR1 * local_next_frame.intra_error /
1767 DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
1769 if (next_iiratio > RMAX)
1770 next_iiratio = RMAX;
1772 // Cumulative effect of decay in prediction quality.
1773 if (local_next_frame.pcnt_inter > 0.85)
1774 decay_accumulator *= local_next_frame.pcnt_inter;
1776 decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
1778 // Keep a running total.
1779 boost_score += (decay_accumulator * next_iiratio);
1781 // Test various breakout clauses.
1782 if ((local_next_frame.pcnt_inter < 0.05) ||
1783 (next_iiratio < 1.5) ||
1784 (((local_next_frame.pcnt_inter -
1785 local_next_frame.pcnt_neutral) < 0.20) &&
1786 (next_iiratio < 3.0)) ||
1787 ((boost_score - old_boost_score) < 3.0) ||
1788 (local_next_frame.intra_error < 200)) {
1792 old_boost_score = boost_score;
1794 // Get the next frame details
1795 if (EOF == input_stats(twopass, &local_next_frame))
1799 // If there is tolerable prediction for at least the next 3 frames then
1800 // break out else discard this potential key frame and move on
1801 if (boost_score > 30.0 && (i > 3)) {
1804 // Reset the file position
1805 reset_fpf_position(twopass, start_pos);
1811 return is_viable_kf;
1814 static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
1816 RATE_CONTROL *const rc = &cpi->rc;
1817 TWO_PASS *const twopass = &cpi->twopass;
1818 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1819 const FIRSTPASS_STATS first_frame = *this_frame;
1820 const FIRSTPASS_STATS *const start_position = twopass->stats_in;
1821 FIRSTPASS_STATS next_frame;
1822 FIRSTPASS_STATS last_frame;
1824 double decay_accumulator = 1.0;
1825 double zero_motion_accumulator = 1.0;
1826 double boost_score = 0.0;
1827 double kf_mod_err = 0.0;
1828 double kf_group_err = 0.0;
1829 double recent_loop_decay[8] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
1831 vp9_zero(next_frame);
1833 cpi->common.frame_type = KEY_FRAME;
1835 // Reset the GF group data structures.
1836 vp9_zero(twopass->gf_group);
1838 // Is this a forced key frame by interval.
1839 rc->this_key_frame_forced = rc->next_key_frame_forced;
1841 // Clear the alt ref active flag and last group multi arf flags as they
1842 // can never be set for a key frame.
1843 rc->source_alt_ref_active = 0;
1844 cpi->multi_arf_last_grp_enabled = 0;
1846 // KF is always a GF so clear frames till next gf counter.
1847 rc->frames_till_gf_update_due = 0;
1849 rc->frames_to_key = 1;
1851 twopass->kf_group_bits = 0; // Total bits available to kf group
1852 twopass->kf_group_error_left = 0; // Group modified error score.
1854 kf_mod_err = calculate_modified_err(twopass, oxcf, this_frame);
1856 // Find the next keyframe.
1858 while (twopass->stats_in < twopass->stats_in_end &&
1859 rc->frames_to_key < cpi->oxcf.key_freq) {
1860 // Accumulate kf group error.
1861 kf_group_err += calculate_modified_err(twopass, oxcf, this_frame);
1863 // Load the next frame's stats.
1864 last_frame = *this_frame;
1865 input_stats(twopass, this_frame);
1867 // Provided that we are not at the end of the file...
1868 if (cpi->oxcf.auto_key &&
1869 lookup_next_frame_stats(twopass, &next_frame) != EOF) {
1870 double loop_decay_rate;
1872 // Check for a scene cut.
1873 if (test_candidate_kf(twopass, &last_frame, this_frame, &next_frame))
1876 // How fast is the prediction quality decaying?
1877 loop_decay_rate = get_prediction_decay_rate(&cpi->common, &next_frame);
1879 // We want to know something about the recent past... rather than
1880 // as used elsewhere where we are concerned with decay in prediction
1881 // quality since the last GF or KF.
1882 recent_loop_decay[i % 8] = loop_decay_rate;
1883 decay_accumulator = 1.0;
1884 for (j = 0; j < 8; ++j)
1885 decay_accumulator *= recent_loop_decay[j];
1887 // Special check for transition or high motion followed by a
1889 if (detect_transition_to_still(twopass, i, cpi->oxcf.key_freq - i,
1890 loop_decay_rate, decay_accumulator))
1893 // Step on to the next frame.
1894 ++rc->frames_to_key;
1896 // If we don't have a real key frame within the next two
1897 // key_freq intervals then break out of the loop.
1898 if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq)
1901 ++rc->frames_to_key;
1906 // If there is a max kf interval set by the user we must obey it.
1907 // We already breakout of the loop above at 2x max.
1908 // This code centers the extra kf if the actual natural interval
1909 // is between 1x and 2x.
1910 if (cpi->oxcf.auto_key &&
1911 rc->frames_to_key > cpi->oxcf.key_freq) {
1912 FIRSTPASS_STATS tmp_frame = first_frame;
1914 rc->frames_to_key /= 2;
1916 // Reset to the start of the group.
1917 reset_fpf_position(twopass, start_position);
1921 // Rescan to get the correct error data for the forced kf group.
1922 for (i = 0; i < rc->frames_to_key; ++i) {
1923 kf_group_err += calculate_modified_err(twopass, oxcf, &tmp_frame);
1924 input_stats(twopass, &tmp_frame);
1926 rc->next_key_frame_forced = 1;
1927 } else if (twopass->stats_in == twopass->stats_in_end ||
1928 rc->frames_to_key >= cpi->oxcf.key_freq) {
1929 rc->next_key_frame_forced = 1;
1931 rc->next_key_frame_forced = 0;
1934 // Special case for the last key frame of the file.
1935 if (twopass->stats_in >= twopass->stats_in_end) {
1936 // Accumulate kf group error.
1937 kf_group_err += calculate_modified_err(twopass, oxcf, this_frame);
1940 // Calculate the number of bits that should be assigned to the kf group.
1941 if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
1942 // Maximum number of bits for a single normal frame (not key frame).
1943 const int max_bits = frame_max_bits(rc, &cpi->oxcf);
1945 // Maximum number of bits allocated to the key frame group.
1946 int64_t max_grp_bits;
1948 // Default allocation based on bits left and relative
1949 // complexity of the section.
1950 twopass->kf_group_bits = (int64_t)(twopass->bits_left *
1951 (kf_group_err / twopass->modified_error_left));
1953 // Clip based on maximum per frame rate defined by the user.
1954 max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
1955 if (twopass->kf_group_bits > max_grp_bits)
1956 twopass->kf_group_bits = max_grp_bits;
1958 twopass->kf_group_bits = 0;
1960 twopass->kf_group_bits = MAX(0, twopass->kf_group_bits);
1962 // Reset the first pass file position.
1963 reset_fpf_position(twopass, start_position);
1965 // Scan through the kf group collating various stats used to deteermine
1966 // how many bits to spend on it.
1967 decay_accumulator = 1.0;
1969 for (i = 0; i < rc->frames_to_key; ++i) {
1970 if (EOF == input_stats(twopass, &next_frame))
1973 // Monitor for static sections.
1974 if ((next_frame.pcnt_inter - next_frame.pcnt_motion) <
1975 zero_motion_accumulator) {
1976 zero_motion_accumulator = (next_frame.pcnt_inter -
1977 next_frame.pcnt_motion);
1980 // For the first few frames collect data to decide kf boost.
1981 if (i <= (rc->max_gf_interval * 2)) {
1983 if (next_frame.intra_error > twopass->kf_intra_err_min)
1984 r = (IIKFACTOR2 * next_frame.intra_error /
1985 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1987 r = (IIKFACTOR2 * twopass->kf_intra_err_min /
1988 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1993 // How fast is prediction quality decaying.
1994 if (!detect_flash(twopass, 0)) {
1995 const double loop_decay_rate = get_prediction_decay_rate(&cpi->common,
1997 decay_accumulator *= loop_decay_rate;
1998 decay_accumulator = MAX(decay_accumulator, MIN_DECAY_FACTOR);
2001 boost_score += (decay_accumulator * r);
2005 reset_fpf_position(twopass, start_position);
2007 // Store the zero motion percentage
2008 twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
2010 // Calculate a section intra ratio used in setting max loop filter.
2011 twopass->section_intra_rating =
2012 calculate_section_intra_ratio(start_position, twopass->stats_in_end,
2015 // Work out how many bits to allocate for the key frame itself.
2016 rc->kf_boost = (int)boost_score;
2018 if (rc->kf_boost < (rc->frames_to_key * 3))
2019 rc->kf_boost = (rc->frames_to_key * 3);
2020 if (rc->kf_boost < MIN_KF_BOOST)
2021 rc->kf_boost = MIN_KF_BOOST;
2023 kf_bits = calculate_boost_bits((rc->frames_to_key - 1),
2024 rc->kf_boost, twopass->kf_group_bits);
2026 twopass->kf_group_bits -= kf_bits;
2028 // Save the bits to spend on the key frame.
2029 twopass->gf_group.bit_allocation[0] = kf_bits;
2030 twopass->gf_group.update_type[0] = KF_UPDATE;
2031 twopass->gf_group.rf_level[0] = KF_STD;
2033 // Note the total error score of the kf group minus the key frame itself.
2034 twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
2036 // Adjust the count of total modified error left.
2037 // The count of bits left is adjusted elsewhere based on real coded frame
2039 twopass->modified_error_left -= kf_group_err;
2042 // For VBR...adjustment to the frame target based on error from previous frames
2043 void vbr_rate_correction(int * this_frame_target,
2044 const int64_t vbr_bits_off_target) {
2045 int max_delta = (*this_frame_target * 15) / 100;
2047 // vbr_bits_off_target > 0 means we have extra bits to spend
2048 if (vbr_bits_off_target > 0) {
2049 *this_frame_target +=
2050 (vbr_bits_off_target > max_delta) ? max_delta
2051 : (int)vbr_bits_off_target;
2053 *this_frame_target -=
2054 (vbr_bits_off_target < -max_delta) ? max_delta
2055 : (int)-vbr_bits_off_target;
2059 // Define the reference buffers that will be updated post encode.
2060 void configure_buffer_updates(VP9_COMP *cpi) {
2061 TWO_PASS *const twopass = &cpi->twopass;
2063 cpi->rc.is_src_frame_alt_ref = 0;
2064 switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
2066 cpi->refresh_last_frame = 1;
2067 cpi->refresh_golden_frame = 1;
2068 cpi->refresh_alt_ref_frame = 1;
2071 cpi->refresh_last_frame = 1;
2072 cpi->refresh_golden_frame = 0;
2073 cpi->refresh_alt_ref_frame = 0;
2076 cpi->refresh_last_frame = 1;
2077 cpi->refresh_golden_frame = 1;
2078 cpi->refresh_alt_ref_frame = 0;
2080 case OVERLAY_UPDATE:
2081 cpi->refresh_last_frame = 0;
2082 cpi->refresh_golden_frame = 1;
2083 cpi->refresh_alt_ref_frame = 0;
2084 cpi->rc.is_src_frame_alt_ref = 1;
2087 cpi->refresh_last_frame = 0;
2088 cpi->refresh_golden_frame = 0;
2089 cpi->refresh_alt_ref_frame = 1;
2094 if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
2095 cpi->refresh_golden_frame = 0;
2096 if (cpi->alt_ref_source == NULL)
2097 cpi->refresh_alt_ref_frame = 0;
2102 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
2103 VP9_COMMON *const cm = &cpi->common;
2104 RATE_CONTROL *const rc = &cpi->rc;
2105 TWO_PASS *const twopass = &cpi->twopass;
2107 FIRSTPASS_STATS this_frame;
2108 FIRSTPASS_STATS this_frame_copy;
2111 LAYER_CONTEXT *lc = NULL;
2112 const int is_spatial_svc = (cpi->use_svc &&
2113 cpi->svc.number_temporal_layers == 1);
2114 if (is_spatial_svc) {
2115 lc = &cpi->svc.layer_context[cpi->svc.spatial_layer_id];
2116 frames_left = (int)(twopass->total_stats.count -
2117 lc->current_video_frame_in_layer);
2119 frames_left = (int)(twopass->total_stats.count -
2120 cm->current_video_frame);
2123 if (!twopass->stats_in)
2126 // If this is an arf frame then we dont want to read the stats file or
2127 // advance the input pointer as we already have what we need.
2128 if (twopass->gf_group.update_type[twopass->gf_group.index] == ARF_UPDATE) {
2130 configure_buffer_updates(cpi);
2131 target_rate = twopass->gf_group.bit_allocation[twopass->gf_group.index];
2132 target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2133 rc->base_frame_target = target_rate;
2134 #ifdef LONG_TERM_VBR_CORRECTION
2135 // Correction to rate target based on prior over or under shoot.
2136 if (cpi->oxcf.rc_mode == VPX_VBR)
2137 vbr_rate_correction(&target_rate, rc->vbr_bits_off_target);
2139 vp9_rc_set_frame_target(cpi, target_rate);
2140 cm->frame_type = INTER_FRAME;
2142 if (is_spatial_svc) {
2143 if (cpi->svc.spatial_layer_id == 0) {
2144 lc->is_key_frame = 0;
2146 lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2148 if (lc->is_key_frame)
2149 cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2156 vp9_clear_system_state();
2158 if (is_spatial_svc && twopass->kf_intra_err_min == 0) {
2159 twopass->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
2160 twopass->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
2163 if (cpi->oxcf.rc_mode == VPX_Q) {
2164 twopass->active_worst_quality = cpi->oxcf.cq_level;
2165 } else if (cm->current_video_frame == 0 ||
2166 (is_spatial_svc && lc->current_video_frame_in_layer == 0)) {
2167 // Special case code for first frame.
2168 const int section_target_bandwidth = (int)(twopass->bits_left /
2170 const int tmp_q = get_twopass_worst_quality(cpi, &twopass->total_left_stats,
2171 section_target_bandwidth);
2172 twopass->active_worst_quality = tmp_q;
2173 rc->ni_av_qi = tmp_q;
2174 rc->avg_q = vp9_convert_qindex_to_q(tmp_q);
2176 vp9_zero(this_frame);
2177 if (EOF == input_stats(twopass, &this_frame))
2180 // Local copy of the current frame's first pass stats.
2181 this_frame_copy = this_frame;
2183 // Keyframe and section processing.
2184 if (rc->frames_to_key == 0 ||
2185 (cpi->frame_flags & FRAMEFLAGS_KEY)) {
2186 // Define next KF group and assign bits to it.
2187 find_next_key_frame(cpi, &this_frame_copy);
2189 cm->frame_type = INTER_FRAME;
2192 if (is_spatial_svc) {
2193 if (cpi->svc.spatial_layer_id == 0) {
2194 lc->is_key_frame = (cm->frame_type == KEY_FRAME);
2196 cm->frame_type = INTER_FRAME;
2197 lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
2199 if (lc->is_key_frame) {
2200 cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
2205 // Define a new GF/ARF group. (Should always enter here for key frames).
2206 if (rc->frames_till_gf_update_due == 0) {
2207 define_gf_group(cpi, &this_frame_copy);
2209 if (twopass->gf_zeromotion_pct > 995) {
2210 // As long as max_thresh for encode breakout is small enough, it is ok
2211 // to enable it for show frame, i.e. set allow_encode_breakout to
2212 // ENCODE_BREAKOUT_LIMITED.
2213 if (!cm->show_frame)
2214 cpi->allow_encode_breakout = ENCODE_BREAKOUT_DISABLED;
2216 cpi->allow_encode_breakout = ENCODE_BREAKOUT_LIMITED;
2219 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2220 if (!is_spatial_svc)
2221 cpi->refresh_golden_frame = 1;
2225 FIRSTPASS_STATS next_frame;
2226 if (lookup_next_frame_stats(twopass, &next_frame) != EOF) {
2227 twopass->next_iiratio = (int)(next_frame.intra_error /
2228 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2232 configure_buffer_updates(cpi);
2234 target_rate = twopass->gf_group.bit_allocation[twopass->gf_group.index];
2235 if (cpi->common.frame_type == KEY_FRAME)
2236 target_rate = vp9_rc_clamp_iframe_target_size(cpi, target_rate);
2238 target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2240 rc->base_frame_target = target_rate;
2241 #ifdef LONG_TERM_VBR_CORRECTION
2242 // Correction to rate target based on prior over or under shoot.
2243 if (cpi->oxcf.rc_mode == VPX_VBR)
2244 vbr_rate_correction(&target_rate, rc->vbr_bits_off_target);
2246 vp9_rc_set_frame_target(cpi, target_rate);
2248 // Update the total stats remaining structure.
2249 subtract_stats(&twopass->total_left_stats, &this_frame);
2251 #if CONFIG_FP_MB_STATS
2252 if (cpi->use_fp_mb_stats) {
2253 input_mb_stats(&twopass->this_frame_mb_stats, cm);
2258 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
2259 TWO_PASS *const twopass = &cpi->twopass;
2260 RATE_CONTROL *const rc = &cpi->rc;
2261 #ifdef LONG_TERM_VBR_CORRECTION
2262 // In this experimental mode, the VBR correction is done exclusively through
2263 // rc->vbr_bits_off_target. Based on the sign of this value, a limited %
2264 // adjustment is made to the target rate of subsequent frames, to try and
2265 // push it back towards 0. This mode is less likely to suffer from
2266 // extreme behaviour at the end of a clip or group of frames.
2267 const int bits_used = rc->base_frame_target;
2268 rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
2270 // In this mode, VBR correction is acheived by altering bits_left,
2271 // kf_group_bits & gf_group_bits to reflect any deviation from the target
2272 // rate in this frame. This alters the allocation of bits to the
2273 // remaning frames in the group / clip.
2275 // This method can give rise to unstable behaviour near the end of a clip
2276 // or kf/gf group of frames where any accumulated error is corrected over an
2277 // ever decreasing number of frames. Hence we change the balance of target
2278 // vs. actual bitrate gradually as we progress towards the end of the
2279 // sequence in order to mitigate this effect.
2280 const double progress =
2281 (double)(twopass->stats_in - twopass->stats_in_start) /
2282 (twopass->stats_in_end - twopass->stats_in_start);
2283 const int bits_used = (int)(progress * rc->this_frame_target +
2284 (1.0 - progress) * rc->projected_frame_size);
2287 twopass->bits_left = MAX(twopass->bits_left - bits_used, 0);
2289 #ifdef LONG_TERM_VBR_CORRECTION
2290 if (cpi->common.frame_type != KEY_FRAME &&
2291 !vp9_is_upper_layer_key_frame(cpi)) {
2293 if (cpi->common.frame_type == KEY_FRAME ||
2294 vp9_is_upper_layer_key_frame(cpi)) {
2295 // For key frames kf_group_bits already had the target bits subtracted out.
2296 // So now update to the correct value based on the actual bits used.
2297 twopass->kf_group_bits += rc->this_frame_target - bits_used;
2300 twopass->kf_group_bits -= bits_used;
2302 twopass->kf_group_bits = MAX(twopass->kf_group_bits, 0);
2304 // Increment the gf group index ready for the next frame.
2305 ++twopass->gf_group.index;