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_dsp_rtcd.h"
16 #include "./vpx_scale_rtcd.h"
18 #include "vpx_dsp/vpx_dsp_common.h"
19 #include "vpx_mem/vpx_mem.h"
20 #include "vpx_ports/mem.h"
21 #include "vpx_ports/system_state.h"
22 #include "vpx_scale/vpx_scale.h"
23 #include "vpx_scale/yv12config.h"
25 #include "vp9/common/vp9_entropymv.h"
26 #include "vp9/common/vp9_quant_common.h"
27 #include "vp9/common/vp9_reconinter.h" // vp9_setup_dst_planes()
28 #include "vp9/encoder/vp9_aq_variance.h"
29 #include "vp9/encoder/vp9_block.h"
30 #include "vp9/encoder/vp9_encodeframe.h"
31 #include "vp9/encoder/vp9_encodemb.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_encoder.h"
34 #include "vp9/encoder/vp9_ethread.h"
35 #include "vp9/encoder/vp9_extend.h"
36 #include "vp9/encoder/vp9_firstpass.h"
37 #include "vp9/encoder/vp9_mcomp.h"
38 #include "vp9/encoder/vp9_quantize.h"
39 #include "vp9/encoder/vp9_rd.h"
40 #include "vpx_dsp/variance.h"
43 #define ARF_STATS_OUTPUT 0
44 #define COMPLEXITY_STATS_OUTPUT 0
46 #define FIRST_PASS_Q 10.0
47 #define INTRA_MODE_PENALTY 1024
48 #define MIN_ARF_GF_BOOST 240
49 #define MIN_DECAY_FACTOR 0.01
50 #define NEW_MV_MODE_PENALTY 32
51 #define DARK_THRESH 64
52 #define DEFAULT_GRP_WEIGHT 1.0
53 #define RC_FACTOR_MIN 0.75
54 #define RC_FACTOR_MAX 1.75
55 #define SECTION_NOISE_DEF 250.0
56 #define LOW_I_THRESH 24000
58 #define NCOUNT_INTRA_THRESH 8192
59 #define NCOUNT_INTRA_FACTOR 3
61 #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x)-0.000001 : (x) + 0.000001)
64 unsigned int arf_count = 0;
67 // Resets the first pass file to the given position using a relative seek from
68 // the current position.
69 static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
70 p->stats_in = position;
73 // Read frame stats at an offset from the current position.
74 static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
75 if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
76 (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
80 return &p->stats_in[offset];
83 static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
84 if (p->stats_in >= p->stats_in_end) return EOF;
91 static void output_stats(FIRSTPASS_STATS *stats,
92 struct vpx_codec_pkt_list *pktlist) {
93 struct vpx_codec_cx_pkt pkt;
94 pkt.kind = VPX_CODEC_STATS_PKT;
95 pkt.data.twopass_stats.buf = stats;
96 pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
97 vpx_codec_pkt_list_add(pktlist, &pkt);
103 fpfile = fopen("firstpass.stt", "a");
106 "%12.0lf %12.4lf %12.2lf %12.2lf %12.2lf %12.0lf %12.4lf %12.4lf"
107 "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
108 "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.0lf %12.0lf %12.0lf"
111 stats->frame, stats->weight, stats->intra_error, stats->coded_error,
112 stats->sr_coded_error, stats->frame_noise_energy, stats->pcnt_inter,
113 stats->pcnt_motion, stats->pcnt_second_ref, stats->pcnt_neutral,
114 stats->pcnt_intra_low, stats->pcnt_intra_high,
115 stats->intra_skip_pct, stats->intra_smooth_pct,
116 stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
117 stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
118 stats->MVcv, stats->mv_in_out_count, stats->count, stats->duration);
124 #if CONFIG_FP_MB_STATS
125 static void output_fpmb_stats(uint8_t *this_frame_mb_stats, VP9_COMMON *cm,
126 struct vpx_codec_pkt_list *pktlist) {
127 struct vpx_codec_cx_pkt pkt;
128 pkt.kind = VPX_CODEC_FPMB_STATS_PKT;
129 pkt.data.firstpass_mb_stats.buf = this_frame_mb_stats;
130 pkt.data.firstpass_mb_stats.sz = cm->initial_mbs * sizeof(uint8_t);
131 vpx_codec_pkt_list_add(pktlist, &pkt);
135 static void zero_stats(FIRSTPASS_STATS *section) {
136 section->frame = 0.0;
137 section->weight = 0.0;
138 section->intra_error = 0.0;
139 section->coded_error = 0.0;
140 section->sr_coded_error = 0.0;
141 section->frame_noise_energy = 0.0;
142 section->pcnt_inter = 0.0;
143 section->pcnt_motion = 0.0;
144 section->pcnt_second_ref = 0.0;
145 section->pcnt_neutral = 0.0;
146 section->intra_skip_pct = 0.0;
147 section->intra_smooth_pct = 0.0;
148 section->pcnt_intra_low = 0.0;
149 section->pcnt_intra_high = 0.0;
150 section->inactive_zone_rows = 0.0;
151 section->inactive_zone_cols = 0.0;
153 section->mvr_abs = 0.0;
155 section->mvc_abs = 0.0;
158 section->mv_in_out_count = 0.0;
159 section->count = 0.0;
160 section->duration = 1.0;
161 section->spatial_layer_id = 0;
164 static void accumulate_stats(FIRSTPASS_STATS *section,
165 const FIRSTPASS_STATS *frame) {
166 section->frame += frame->frame;
167 section->weight += frame->weight;
168 section->spatial_layer_id = frame->spatial_layer_id;
169 section->intra_error += frame->intra_error;
170 section->coded_error += frame->coded_error;
171 section->sr_coded_error += frame->sr_coded_error;
172 section->frame_noise_energy += frame->frame_noise_energy;
173 section->pcnt_inter += frame->pcnt_inter;
174 section->pcnt_motion += frame->pcnt_motion;
175 section->pcnt_second_ref += frame->pcnt_second_ref;
176 section->pcnt_neutral += frame->pcnt_neutral;
177 section->intra_skip_pct += frame->intra_skip_pct;
178 section->intra_smooth_pct += frame->intra_smooth_pct;
179 section->pcnt_intra_low += frame->pcnt_intra_low;
180 section->pcnt_intra_high += frame->pcnt_intra_high;
181 section->inactive_zone_rows += frame->inactive_zone_rows;
182 section->inactive_zone_cols += frame->inactive_zone_cols;
183 section->MVr += frame->MVr;
184 section->mvr_abs += frame->mvr_abs;
185 section->MVc += frame->MVc;
186 section->mvc_abs += frame->mvc_abs;
187 section->MVrv += frame->MVrv;
188 section->MVcv += frame->MVcv;
189 section->mv_in_out_count += frame->mv_in_out_count;
190 section->count += frame->count;
191 section->duration += frame->duration;
194 static void subtract_stats(FIRSTPASS_STATS *section,
195 const FIRSTPASS_STATS *frame) {
196 section->frame -= frame->frame;
197 section->weight -= frame->weight;
198 section->intra_error -= frame->intra_error;
199 section->coded_error -= frame->coded_error;
200 section->sr_coded_error -= frame->sr_coded_error;
201 section->frame_noise_energy -= frame->frame_noise_energy;
202 section->pcnt_inter -= frame->pcnt_inter;
203 section->pcnt_motion -= frame->pcnt_motion;
204 section->pcnt_second_ref -= frame->pcnt_second_ref;
205 section->pcnt_neutral -= frame->pcnt_neutral;
206 section->intra_skip_pct -= frame->intra_skip_pct;
207 section->intra_smooth_pct -= frame->intra_smooth_pct;
208 section->pcnt_intra_low -= frame->pcnt_intra_low;
209 section->pcnt_intra_high -= frame->pcnt_intra_high;
210 section->inactive_zone_rows -= frame->inactive_zone_rows;
211 section->inactive_zone_cols -= frame->inactive_zone_cols;
212 section->MVr -= frame->MVr;
213 section->mvr_abs -= frame->mvr_abs;
214 section->MVc -= frame->MVc;
215 section->mvc_abs -= frame->mvc_abs;
216 section->MVrv -= frame->MVrv;
217 section->MVcv -= frame->MVcv;
218 section->mv_in_out_count -= frame->mv_in_out_count;
219 section->count -= frame->count;
220 section->duration -= frame->duration;
223 // Calculate an active area of the image that discounts formatting
224 // bars and partially discounts other 0 energy areas.
225 #define MIN_ACTIVE_AREA 0.5
226 #define MAX_ACTIVE_AREA 1.0
227 static double calculate_active_area(const VP9_COMP *cpi,
228 const FIRSTPASS_STATS *this_frame) {
233 ((this_frame->intra_skip_pct / 2) +
234 ((this_frame->inactive_zone_rows * 2) / (double)cpi->common.mb_rows));
235 return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
238 // Get the average weighted error for the clip (or corpus)
239 static double get_distribution_av_err(VP9_COMP *cpi, TWO_PASS *const twopass) {
240 const double av_weight =
241 twopass->total_stats.weight / twopass->total_stats.count;
243 if (cpi->oxcf.vbr_corpus_complexity)
244 return av_weight * twopass->mean_mod_score;
246 return (twopass->total_stats.coded_error * av_weight) /
247 twopass->total_stats.count;
250 #define ACT_AREA_CORRECTION 0.5
251 // Calculate a modified Error used in distributing bits between easier and
253 static double calculate_mod_frame_score(const VP9_COMP *cpi,
254 const VP9EncoderConfig *oxcf,
255 const FIRSTPASS_STATS *this_frame,
256 const double av_err) {
257 double modified_score =
258 av_err * pow(this_frame->coded_error * this_frame->weight /
259 DOUBLE_DIVIDE_CHECK(av_err),
260 oxcf->two_pass_vbrbias / 100.0);
262 // Correction for active area. Frames with a reduced active area
263 // (eg due to formatting bars) have a higher error per mb for the
264 // remaining active MBs. The correction here assumes that coding
265 // 0.5N blocks of complexity 2X is a little easier than coding N
266 // blocks of complexity X.
268 pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);
270 return modified_score;
273 static double calculate_norm_frame_score(const VP9_COMP *cpi,
274 const TWO_PASS *twopass,
275 const VP9EncoderConfig *oxcf,
276 const FIRSTPASS_STATS *this_frame,
277 const double av_err) {
278 double modified_score =
279 av_err * pow(this_frame->coded_error * this_frame->weight /
280 DOUBLE_DIVIDE_CHECK(av_err),
281 oxcf->two_pass_vbrbias / 100.0);
283 const double min_score = (double)(oxcf->two_pass_vbrmin_section) / 100.0;
284 const double max_score = (double)(oxcf->two_pass_vbrmax_section) / 100.0;
286 // Correction for active area. Frames with a reduced active area
287 // (eg due to formatting bars) have a higher error per mb for the
288 // remaining active MBs. The correction here assumes that coding
289 // 0.5N blocks of complexity 2X is a little easier than coding N
290 // blocks of complexity X.
292 pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);
294 // Normalize to a midpoint score.
295 modified_score /= DOUBLE_DIVIDE_CHECK(twopass->mean_mod_score);
297 return fclamp(modified_score, min_score, max_score);
300 // This function returns the maximum target rate per frame.
301 static int frame_max_bits(const RATE_CONTROL *rc,
302 const VP9EncoderConfig *oxcf) {
303 int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
304 (int64_t)oxcf->two_pass_vbrmax_section) /
308 else if (max_bits > rc->max_frame_bandwidth)
309 max_bits = rc->max_frame_bandwidth;
311 return (int)max_bits;
314 void vp9_init_first_pass(VP9_COMP *cpi) {
315 zero_stats(&cpi->twopass.total_stats);
318 void vp9_end_first_pass(VP9_COMP *cpi) {
319 if (is_two_pass_svc(cpi)) {
321 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
322 output_stats(&cpi->svc.layer_context[i].twopass.total_stats,
323 cpi->output_pkt_list);
326 output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
329 vpx_free(cpi->twopass.fp_mb_float_stats);
330 cpi->twopass.fp_mb_float_stats = NULL;
333 static vpx_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
335 case BLOCK_8X8: return vpx_mse8x8;
336 case BLOCK_16X8: return vpx_mse16x8;
337 case BLOCK_8X16: return vpx_mse8x16;
338 default: return vpx_mse16x16;
342 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
343 const struct buf_2d *src,
344 const struct buf_2d *ref) {
346 const vpx_variance_fn_t fn = get_block_variance_fn(bsize);
347 fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
351 #if CONFIG_VP9_HIGHBITDEPTH
352 static vpx_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
357 case BLOCK_8X8: return vpx_highbd_8_mse8x8;
358 case BLOCK_16X8: return vpx_highbd_8_mse16x8;
359 case BLOCK_8X16: return vpx_highbd_8_mse8x16;
360 default: return vpx_highbd_8_mse16x16;
365 case BLOCK_8X8: return vpx_highbd_10_mse8x8;
366 case BLOCK_16X8: return vpx_highbd_10_mse16x8;
367 case BLOCK_8X16: return vpx_highbd_10_mse8x16;
368 default: return vpx_highbd_10_mse16x16;
373 case BLOCK_8X8: return vpx_highbd_12_mse8x8;
374 case BLOCK_16X8: return vpx_highbd_12_mse16x8;
375 case BLOCK_8X16: return vpx_highbd_12_mse8x16;
376 default: return vpx_highbd_12_mse16x16;
382 static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
383 const struct buf_2d *src,
384 const struct buf_2d *ref,
387 const vpx_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
388 fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
391 #endif // CONFIG_VP9_HIGHBITDEPTH
393 // Refine the motion search range according to the frame dimension
394 // for first pass test.
395 static int get_search_range(const VP9_COMP *cpi) {
397 const int dim = VPXMIN(cpi->initial_width, cpi->initial_height);
399 while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
403 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
404 const MV *ref_mv, MV *best_mv,
405 int *best_motion_err) {
406 MACROBLOCKD *const xd = &x->e_mbd;
407 MV tmp_mv = { 0, 0 };
408 MV ref_mv_full = { ref_mv->row >> 3, ref_mv->col >> 3 };
409 int num00, tmp_err, n;
410 const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
411 vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
412 const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
415 int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
416 const int sr = get_search_range(cpi);
420 // Override the default variance function to use MSE.
421 v_fn_ptr.vf = get_block_variance_fn(bsize);
422 #if CONFIG_VP9_HIGHBITDEPTH
423 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
424 v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
426 #endif // CONFIG_VP9_HIGHBITDEPTH
428 // Center the initial step/diamond search on best mv.
429 tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
430 step_param, x->sadperbit16, &num00,
432 if (tmp_err < INT_MAX)
433 tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
434 if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
436 if (tmp_err < *best_motion_err) {
437 *best_motion_err = tmp_err;
441 // Carry out further step/diamond searches as necessary.
445 while (n < further_steps) {
451 tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
452 step_param + n, x->sadperbit16, &num00,
454 if (tmp_err < INT_MAX)
455 tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
456 if (tmp_err < INT_MAX - new_mv_mode_penalty)
457 tmp_err += new_mv_mode_penalty;
459 if (tmp_err < *best_motion_err) {
460 *best_motion_err = tmp_err;
467 static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
468 if (2 * mb_col + 1 < cm->mi_cols) {
469 return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16 : BLOCK_16X8;
471 return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16 : BLOCK_8X8;
475 static int find_fp_qindex(vpx_bit_depth_t bit_depth) {
478 for (i = 0; i < QINDEX_RANGE; ++i)
479 if (vp9_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q) break;
481 if (i == QINDEX_RANGE) i--;
486 static void set_first_pass_params(VP9_COMP *cpi) {
487 VP9_COMMON *const cm = &cpi->common;
488 if (!cpi->refresh_alt_ref_frame &&
489 (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY))) {
490 cm->frame_type = KEY_FRAME;
492 cm->frame_type = INTER_FRAME;
494 // Do not use periodic key frames.
495 cpi->rc.frames_to_key = INT_MAX;
498 // Scale an sse threshold to account for 8/10/12 bit.
499 static int scale_sse_threshold(VP9_COMMON *cm, int thresh) {
500 int ret_val = thresh;
501 #if CONFIG_VP9_HIGHBITDEPTH
502 if (cm->use_highbitdepth) {
503 switch (cm->bit_depth) {
504 case VPX_BITS_8: ret_val = thresh; break;
505 case VPX_BITS_10: ret_val = thresh << 4; break;
506 case VPX_BITS_12: ret_val = thresh << 8; break;
509 "cm->bit_depth should be VPX_BITS_8, "
510 "VPX_BITS_10 or VPX_BITS_12");
515 #endif // CONFIG_VP9_HIGHBITDEPTH
519 // This threshold is used to track blocks where to all intents and purposes
520 // the intra prediction error 0. Though the metric we test against
521 // is technically a sse we are mainly interested in blocks where all the pixels
522 // in the 8 bit domain have an error of <= 1 (where error = sse) so a
523 // linear scaling for 10 and 12 bit gives similar results.
524 #define UL_INTRA_THRESH 50
525 static int get_ul_intra_threshold(VP9_COMMON *cm) {
526 int ret_val = UL_INTRA_THRESH;
527 #if CONFIG_VP9_HIGHBITDEPTH
528 if (cm->use_highbitdepth) {
529 switch (cm->bit_depth) {
530 case VPX_BITS_8: ret_val = UL_INTRA_THRESH; break;
531 case VPX_BITS_10: ret_val = UL_INTRA_THRESH << 2; break;
532 case VPX_BITS_12: ret_val = UL_INTRA_THRESH << 4; break;
535 "cm->bit_depth should be VPX_BITS_8, "
536 "VPX_BITS_10 or VPX_BITS_12");
541 #endif // CONFIG_VP9_HIGHBITDEPTH
545 #define SMOOTH_INTRA_THRESH 4000
546 static int get_smooth_intra_threshold(VP9_COMMON *cm) {
547 int ret_val = SMOOTH_INTRA_THRESH;
548 #if CONFIG_VP9_HIGHBITDEPTH
549 if (cm->use_highbitdepth) {
550 switch (cm->bit_depth) {
551 case VPX_BITS_8: ret_val = SMOOTH_INTRA_THRESH; break;
552 case VPX_BITS_10: ret_val = SMOOTH_INTRA_THRESH << 4; break;
553 case VPX_BITS_12: ret_val = SMOOTH_INTRA_THRESH << 8; break;
556 "cm->bit_depth should be VPX_BITS_8, "
557 "VPX_BITS_10 or VPX_BITS_12");
562 #endif // CONFIG_VP9_HIGHBITDEPTH
566 #define FP_DN_THRESH 8
567 #define FP_MAX_DN_THRESH 16
568 #define KERNEL_SIZE 3
570 // Baseline Kernal weights for first pass noise metric
571 static uint8_t fp_dn_kernal_3[KERNEL_SIZE * KERNEL_SIZE] = { 1, 2, 1, 2, 4,
574 // Estimate noise at a single point based on the impace of a spatial kernal
575 // on the point value
576 static int fp_estimate_point_noise(uint8_t *src_ptr, const int stride) {
586 uint8_t centre_val = *src_ptr;
588 kernal_ptr = fp_dn_kernal_3;
591 tmp_ptr = src_ptr - stride - 1;
592 for (i = 0; i < KERNEL_SIZE; ++i) {
593 for (j = 0; j < KERNEL_SIZE; ++j) {
594 diff = abs((int)centre_val - (int)tmp_ptr[j]);
595 max_diff = VPXMAX(max_diff, diff);
596 if (diff <= FP_DN_THRESH) {
597 sum_weight += *kernal_ptr;
598 sum_val += (int)tmp_ptr[j] * (int)*kernal_ptr;
605 if (max_diff < FP_MAX_DN_THRESH)
606 // Update the source value with the new filtered value
607 dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
611 // return the noise energy as the square of the difference between the
612 // denoised and raw value.
613 dn_diff = (int)*src_ptr - (int)dn_val;
614 return dn_diff * dn_diff;
616 #if CONFIG_VP9_HIGHBITDEPTH
617 static int fp_highbd_estimate_point_noise(uint8_t *src_ptr, const int stride) {
628 uint16_t centre_val = *CONVERT_TO_SHORTPTR(src_ptr);
630 kernal_ptr = fp_dn_kernal_3;
633 tmp_ptr = src_ptr - stride - 1;
634 for (i = 0; i < KERNEL_SIZE; ++i) {
635 tmp_ptr16 = CONVERT_TO_SHORTPTR(tmp_ptr);
636 for (j = 0; j < KERNEL_SIZE; ++j) {
637 diff = abs((int)centre_val - (int)tmp_ptr16[j]);
638 max_diff = VPXMAX(max_diff, diff);
639 if (diff <= FP_DN_THRESH) {
640 sum_weight += *kernal_ptr;
641 sum_val += (int)tmp_ptr16[j] * (int)*kernal_ptr;
648 if (max_diff < FP_MAX_DN_THRESH)
649 // Update the source value with the new filtered value
650 dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
652 dn_val = *CONVERT_TO_SHORTPTR(src_ptr);
654 // return the noise energy as the square of the difference between the
655 // denoised and raw value.
656 dn_diff = (int)(*CONVERT_TO_SHORTPTR(src_ptr)) - (int)dn_val;
657 return dn_diff * dn_diff;
661 // Estimate noise for a block.
662 static int fp_estimate_block_noise(MACROBLOCK *x, BLOCK_SIZE bsize) {
663 #if CONFIG_VP9_HIGHBITDEPTH
664 MACROBLOCKD *xd = &x->e_mbd;
666 uint8_t *src_ptr = &x->plane[0].src.buf[0];
667 const int width = num_4x4_blocks_wide_lookup[bsize] * 4;
668 const int height = num_4x4_blocks_high_lookup[bsize] * 4;
670 int stride = x->plane[0].src.stride;
673 // Sampled points to reduce cost overhead.
674 for (h = 0; h < height; h += 2) {
675 for (w = 0; w < width; w += 2) {
676 #if CONFIG_VP9_HIGHBITDEPTH
677 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
678 block_noise += fp_highbd_estimate_point_noise(src_ptr, stride);
680 block_noise += fp_estimate_point_noise(src_ptr, stride);
682 block_noise += fp_estimate_point_noise(src_ptr, stride);
686 src_ptr += (stride - width);
688 return block_noise << 2; // Scale << 2 to account for sampling.
691 // This function is called to test the functionality of row based
692 // multi-threading in unit tests for bit-exactness
693 static void accumulate_floating_point_stats(VP9_COMP *cpi,
694 TileDataEnc *first_tile_col) {
695 VP9_COMMON *const cm = &cpi->common;
697 first_tile_col->fp_data.intra_factor = 0;
698 first_tile_col->fp_data.brightness_factor = 0;
699 first_tile_col->fp_data.neutral_count = 0;
700 for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
701 for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
702 const int mb_index = mb_row * cm->mb_cols + mb_col;
703 first_tile_col->fp_data.intra_factor +=
704 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor;
705 first_tile_col->fp_data.brightness_factor +=
706 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor;
707 first_tile_col->fp_data.neutral_count +=
708 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count;
713 static void first_pass_stat_calc(VP9_COMP *cpi, FIRSTPASS_STATS *fps,
714 FIRSTPASS_DATA *fp_acc_data) {
715 VP9_COMMON *const cm = &cpi->common;
716 // The minimum error here insures some bit allocation to frames even
717 // in static regions. The allocation per MB declines for larger formats
718 // where the typical "real" energy per MB also falls.
719 // Initial estimate here uses sqrt(mbs) to define the min_err, where the
720 // number of mbs is proportional to the image area.
721 const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
723 const double min_err = 200 * sqrt(num_mbs);
725 // Clamp the image start to rows/2. This number of rows is discarded top
726 // and bottom as dead data so rows / 2 means the frame is blank.
727 if ((fp_acc_data->image_data_start_row > cm->mb_rows / 2) ||
728 (fp_acc_data->image_data_start_row == INVALID_ROW)) {
729 fp_acc_data->image_data_start_row = cm->mb_rows / 2;
731 // Exclude any image dead zone
732 if (fp_acc_data->image_data_start_row > 0) {
733 fp_acc_data->intra_skip_count =
734 VPXMAX(0, fp_acc_data->intra_skip_count -
735 (fp_acc_data->image_data_start_row * cm->mb_cols * 2));
738 fp_acc_data->intra_factor = fp_acc_data->intra_factor / (double)num_mbs;
739 fp_acc_data->brightness_factor =
740 fp_acc_data->brightness_factor / (double)num_mbs;
741 fps->weight = fp_acc_data->intra_factor * fp_acc_data->brightness_factor;
743 fps->frame = cm->current_video_frame;
744 fps->spatial_layer_id = cpi->svc.spatial_layer_id;
747 ((double)(fp_acc_data->coded_error >> 8) + min_err) / num_mbs;
748 fps->sr_coded_error =
749 ((double)(fp_acc_data->sr_coded_error >> 8) + min_err) / num_mbs;
751 ((double)(fp_acc_data->intra_error >> 8) + min_err) / num_mbs;
753 fps->frame_noise_energy =
754 (double)(fp_acc_data->frame_noise_energy) / (double)num_mbs;
756 fps->pcnt_inter = (double)(fp_acc_data->intercount) / num_mbs;
757 fps->pcnt_second_ref = (double)(fp_acc_data->second_ref_count) / num_mbs;
758 fps->pcnt_neutral = (double)(fp_acc_data->neutral_count) / num_mbs;
759 fps->pcnt_intra_low = (double)(fp_acc_data->intra_count_low) / num_mbs;
760 fps->pcnt_intra_high = (double)(fp_acc_data->intra_count_high) / num_mbs;
761 fps->intra_skip_pct = (double)(fp_acc_data->intra_skip_count) / num_mbs;
762 fps->intra_smooth_pct = (double)(fp_acc_data->intra_smooth_count) / num_mbs;
763 fps->inactive_zone_rows = (double)(fp_acc_data->image_data_start_row);
764 // Currently set to 0 as most issues relate to letter boxing.
765 fps->inactive_zone_cols = (double)0;
767 if (fp_acc_data->mvcount > 0) {
768 fps->MVr = (double)(fp_acc_data->sum_mvr) / fp_acc_data->mvcount;
769 fps->mvr_abs = (double)(fp_acc_data->sum_mvr_abs) / fp_acc_data->mvcount;
770 fps->MVc = (double)(fp_acc_data->sum_mvc) / fp_acc_data->mvcount;
771 fps->mvc_abs = (double)(fp_acc_data->sum_mvc_abs) / fp_acc_data->mvcount;
772 fps->MVrv = ((double)(fp_acc_data->sum_mvrs) -
773 ((double)(fp_acc_data->sum_mvr) * (fp_acc_data->sum_mvr) /
774 fp_acc_data->mvcount)) /
775 fp_acc_data->mvcount;
776 fps->MVcv = ((double)(fp_acc_data->sum_mvcs) -
777 ((double)(fp_acc_data->sum_mvc) * (fp_acc_data->sum_mvc) /
778 fp_acc_data->mvcount)) /
779 fp_acc_data->mvcount;
780 fps->mv_in_out_count =
781 (double)(fp_acc_data->sum_in_vectors) / (fp_acc_data->mvcount * 2);
782 fps->pcnt_motion = (double)(fp_acc_data->mvcount) / num_mbs;
790 fps->mv_in_out_count = 0.0;
791 fps->pcnt_motion = 0.0;
795 static void accumulate_fp_mb_row_stat(TileDataEnc *this_tile,
796 FIRSTPASS_DATA *fp_acc_data) {
797 this_tile->fp_data.intra_factor += fp_acc_data->intra_factor;
798 this_tile->fp_data.brightness_factor += fp_acc_data->brightness_factor;
799 this_tile->fp_data.coded_error += fp_acc_data->coded_error;
800 this_tile->fp_data.sr_coded_error += fp_acc_data->sr_coded_error;
801 this_tile->fp_data.frame_noise_energy += fp_acc_data->frame_noise_energy;
802 this_tile->fp_data.intra_error += fp_acc_data->intra_error;
803 this_tile->fp_data.intercount += fp_acc_data->intercount;
804 this_tile->fp_data.second_ref_count += fp_acc_data->second_ref_count;
805 this_tile->fp_data.neutral_count += fp_acc_data->neutral_count;
806 this_tile->fp_data.intra_count_low += fp_acc_data->intra_count_low;
807 this_tile->fp_data.intra_count_high += fp_acc_data->intra_count_high;
808 this_tile->fp_data.intra_skip_count += fp_acc_data->intra_skip_count;
809 this_tile->fp_data.mvcount += fp_acc_data->mvcount;
810 this_tile->fp_data.sum_mvr += fp_acc_data->sum_mvr;
811 this_tile->fp_data.sum_mvr_abs += fp_acc_data->sum_mvr_abs;
812 this_tile->fp_data.sum_mvc += fp_acc_data->sum_mvc;
813 this_tile->fp_data.sum_mvc_abs += fp_acc_data->sum_mvc_abs;
814 this_tile->fp_data.sum_mvrs += fp_acc_data->sum_mvrs;
815 this_tile->fp_data.sum_mvcs += fp_acc_data->sum_mvcs;
816 this_tile->fp_data.sum_in_vectors += fp_acc_data->sum_in_vectors;
817 this_tile->fp_data.intra_smooth_count += fp_acc_data->intra_smooth_count;
818 this_tile->fp_data.image_data_start_row =
819 VPXMIN(this_tile->fp_data.image_data_start_row,
820 fp_acc_data->image_data_start_row) == INVALID_ROW
821 ? VPXMAX(this_tile->fp_data.image_data_start_row,
822 fp_acc_data->image_data_start_row)
823 : VPXMIN(this_tile->fp_data.image_data_start_row,
824 fp_acc_data->image_data_start_row);
827 void vp9_first_pass_encode_tile_mb_row(VP9_COMP *cpi, ThreadData *td,
828 FIRSTPASS_DATA *fp_acc_data,
829 TileDataEnc *tile_data, MV *best_ref_mv,
832 MACROBLOCK *const x = &td->mb;
833 VP9_COMMON *const cm = &cpi->common;
834 MACROBLOCKD *const xd = &x->e_mbd;
835 TileInfo tile = tile_data->tile_info;
836 struct macroblock_plane *const p = x->plane;
837 struct macroblockd_plane *const pd = xd->plane;
838 const PICK_MODE_CONTEXT *ctx = &td->pc_root->none;
840 int num_mb_cols = get_num_cols(tile_data->tile_info, 1);
842 int recon_yoffset, recon_uvoffset;
843 const int intrapenalty = INTRA_MODE_PENALTY;
844 const MV zero_mv = { 0, 0 };
845 int recon_y_stride, recon_uv_stride, uv_mb_height;
847 YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
848 YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
849 YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
850 const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
852 LAYER_CONTEXT *const lc =
853 is_two_pass_svc(cpi) ? &cpi->svc.layer_context[cpi->svc.spatial_layer_id]
855 MODE_INFO mi_above, mi_left;
857 double mb_intra_factor;
858 double mb_brightness_factor;
859 double mb_neutral_count;
861 // First pass code requires valid last and new frame buffers.
862 assert(new_yv12 != NULL);
863 assert((lc != NULL) || frame_is_intra_only(cm) || (lst_yv12 != NULL));
866 // Use either last frame or alt frame for motion search.
867 if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
868 first_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
869 if (first_ref_buf == NULL)
870 first_ref_buf = get_ref_frame_buffer(cpi, LAST_FRAME);
873 if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
874 gld_yv12 = vp9_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
875 if (gld_yv12 == NULL) {
876 gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
883 xd->mi = cm->mi_grid_visible + xd->mi_stride * (mb_row << 1) +
884 (tile.mi_col_start >> 1);
885 xd->mi[0] = cm->mi + xd->mi_stride * (mb_row << 1) + (tile.mi_col_start >> 1);
887 for (i = 0; i < MAX_MB_PLANE; ++i) {
888 p[i].coeff = ctx->coeff_pbuf[i][1];
889 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
890 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
891 p[i].eobs = ctx->eobs_pbuf[i][1];
894 recon_y_stride = new_yv12->y_stride;
895 recon_uv_stride = new_yv12->uv_stride;
896 uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
898 // Reset above block coeffs.
900 (mb_row * recon_y_stride * 16) + (tile.mi_col_start >> 1) * 16;
901 recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height) +
902 (tile.mi_col_start >> 1) * uv_mb_height;
904 // Set up limit values for motion vectors to prevent them extending
905 // outside the UMV borders.
906 x->mv_limits.row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
907 x->mv_limits.row_max =
908 ((cm->mb_rows - 1 - mb_row) * 16) + BORDER_MV_PIXELS_B16;
910 for (mb_col = tile.mi_col_start >> 1, c = 0; mb_col < (tile.mi_col_end >> 1);
913 int this_intra_error;
914 const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
915 const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
918 const int mb_index = mb_row * cm->mb_cols + mb_col;
920 #if CONFIG_FP_MB_STATS
921 const int mb_index = mb_row * cm->mb_cols + mb_col;
924 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, mb_row, c);
926 // Adjust to the next column of MBs.
927 x->plane[0].src.buf = cpi->Source->y_buffer +
928 mb_row * 16 * x->plane[0].src.stride + mb_col * 16;
929 x->plane[1].src.buf = cpi->Source->u_buffer +
930 mb_row * uv_mb_height * x->plane[1].src.stride +
931 mb_col * uv_mb_height;
932 x->plane[2].src.buf = cpi->Source->v_buffer +
933 mb_row * uv_mb_height * x->plane[1].src.stride +
934 mb_col * uv_mb_height;
936 vpx_clear_system_state();
938 xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
939 xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
940 xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
941 xd->mi[0]->sb_type = bsize;
942 xd->mi[0]->ref_frame[0] = INTRA_FRAME;
943 set_mi_row_col(xd, &tile, mb_row << 1, num_8x8_blocks_high_lookup[bsize],
944 mb_col << 1, num_8x8_blocks_wide_lookup[bsize], cm->mi_rows,
946 // Are edges available for intra prediction?
947 // Since the firstpass does not populate the mi_grid_visible,
948 // above_mi/left_mi must be overwritten with a nonzero value when edges
949 // are available. Required by vp9_predict_intra_block().
950 xd->above_mi = (mb_row != 0) ? &mi_above : NULL;
951 xd->left_mi = ((mb_col << 1) > tile.mi_col_start) ? &mi_left : NULL;
953 // Do intra 16x16 prediction.
956 // Do intra prediction based on source pixels for tile boundaries
957 if ((mb_col == (tile.mi_col_start >> 1)) && mb_col != 0) {
958 xd->left_mi = &mi_left;
961 xd->mi[0]->mode = DC_PRED;
963 use_dc_pred ? (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
964 // Fix - zero the 16x16 block first. This ensures correct this_error for
965 // block sizes smaller than 16x16.
966 vp9_zero_array(x->plane[0].src_diff, 256);
967 vp9_encode_intra_block_plane(x, bsize, 0, 0);
968 this_error = vpx_get_mb_ss(x->plane[0].src_diff);
969 this_intra_error = this_error;
971 // Keep a record of blocks that have very low intra error residual
972 // (i.e. are in effect completely flat and untextured in the intra
973 // domain). In natural videos this is uncommon, but it is much more
974 // common in animations, graphics and screen content, so may be used
975 // as a signal to detect these types of content.
976 if (this_error < get_ul_intra_threshold(cm)) {
977 ++(fp_acc_data->intra_skip_count);
978 } else if ((mb_col > 0) &&
979 (fp_acc_data->image_data_start_row == INVALID_ROW)) {
980 fp_acc_data->image_data_start_row = mb_row;
983 // Blocks that are mainly smooth in the intra domain.
984 // Some special accounting for CQ but also these are better for testing
986 if (this_error < get_smooth_intra_threshold(cm)) {
987 ++(fp_acc_data->intra_smooth_count);
990 // Special case noise measurement for first frame.
991 if (cm->current_video_frame == 0) {
992 if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
993 fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
995 fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
999 #if CONFIG_VP9_HIGHBITDEPTH
1000 if (cm->use_highbitdepth) {
1001 switch (cm->bit_depth) {
1002 case VPX_BITS_8: break;
1003 case VPX_BITS_10: this_error >>= 4; break;
1004 case VPX_BITS_12: this_error >>= 8; break;
1007 "cm->bit_depth should be VPX_BITS_8, "
1008 "VPX_BITS_10 or VPX_BITS_12");
1012 #endif // CONFIG_VP9_HIGHBITDEPTH
1014 vpx_clear_system_state();
1015 log_intra = log(this_error + 1.0);
1016 if (log_intra < 10.0) {
1017 mb_intra_factor = 1.0 + ((10.0 - log_intra) * 0.05);
1018 fp_acc_data->intra_factor += mb_intra_factor;
1019 if (cpi->row_mt_bit_exact)
1020 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor =
1023 fp_acc_data->intra_factor += 1.0;
1024 if (cpi->row_mt_bit_exact)
1025 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_intra_factor = 1.0;
1028 #if CONFIG_VP9_HIGHBITDEPTH
1029 if (cm->use_highbitdepth)
1030 level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
1032 level_sample = x->plane[0].src.buf[0];
1034 level_sample = x->plane[0].src.buf[0];
1036 if ((level_sample < DARK_THRESH) && (log_intra < 9.0)) {
1037 mb_brightness_factor = 1.0 + (0.01 * (DARK_THRESH - level_sample));
1038 fp_acc_data->brightness_factor += mb_brightness_factor;
1039 if (cpi->row_mt_bit_exact)
1040 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor =
1041 mb_brightness_factor;
1043 fp_acc_data->brightness_factor += 1.0;
1044 if (cpi->row_mt_bit_exact)
1045 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_brightness_factor =
1049 // Intrapenalty below deals with situations where the intra and inter
1050 // error scores are very low (e.g. a plain black frame).
1051 // We do not have special cases in first pass for 0,0 and nearest etc so
1052 // all inter modes carry an overhead cost estimate for the mv.
1053 // When the error score is very low this causes us to pick all or lots of
1054 // INTRA modes and throw lots of key frames.
1055 // This penalty adds a cost matching that of a 0,0 mv to the intra case.
1056 this_error += intrapenalty;
1058 // Accumulate the intra error.
1059 fp_acc_data->intra_error += (int64_t)this_error;
1061 #if CONFIG_FP_MB_STATS
1062 if (cpi->use_fp_mb_stats) {
1064 cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
1068 // Set up limit values for motion vectors to prevent them extending
1069 // outside the UMV borders.
1070 x->mv_limits.col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
1071 x->mv_limits.col_max =
1072 ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
1074 // Other than for the first frame do a motion search.
1075 if ((lc == NULL && cm->current_video_frame > 0) ||
1076 (lc != NULL && lc->current_video_frame_in_layer > 0)) {
1077 int tmp_err, motion_error, raw_motion_error;
1078 // Assume 0,0 motion with no mv overhead.
1079 MV mv = { 0, 0 }, tmp_mv = { 0, 0 };
1080 struct buf_2d unscaled_last_source_buf_2d;
1082 xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
1083 #if CONFIG_VP9_HIGHBITDEPTH
1084 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1085 motion_error = highbd_get_prediction_error(
1086 bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
1089 get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
1093 get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
1094 #endif // CONFIG_VP9_HIGHBITDEPTH
1096 // Compute the motion error of the 0,0 motion using the last source
1097 // frame as the reference. Skip the further motion search on
1098 // reconstructed frame if this error is small.
1099 unscaled_last_source_buf_2d.buf =
1100 cpi->unscaled_last_source->y_buffer + recon_yoffset;
1101 unscaled_last_source_buf_2d.stride = cpi->unscaled_last_source->y_stride;
1102 #if CONFIG_VP9_HIGHBITDEPTH
1103 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1104 raw_motion_error = highbd_get_prediction_error(
1105 bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
1107 raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1108 &unscaled_last_source_buf_2d);
1111 raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1112 &unscaled_last_source_buf_2d);
1113 #endif // CONFIG_VP9_HIGHBITDEPTH
1115 // TODO(pengchong): Replace the hard-coded threshold
1116 if (raw_motion_error > 25 || lc != NULL) {
1117 // Test last reference frame using the previous best mv as the
1118 // starting point (best reference) for the search.
1119 first_pass_motion_search(cpi, x, best_ref_mv, &mv, &motion_error);
1121 // If the current best reference mv is not centered on 0,0 then do a
1122 // 0,0 based search as well.
1123 if (!is_zero_mv(best_ref_mv)) {
1125 first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &tmp_err);
1127 if (tmp_err < motion_error) {
1128 motion_error = tmp_err;
1133 // Search in an older reference frame.
1134 if (((lc == NULL && cm->current_video_frame > 1) ||
1135 (lc != NULL && lc->current_video_frame_in_layer > 1)) &&
1137 // Assume 0,0 motion with no mv overhead.
1138 int gf_motion_error;
1140 xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
1141 #if CONFIG_VP9_HIGHBITDEPTH
1142 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1143 gf_motion_error = highbd_get_prediction_error(
1144 bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
1146 gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1147 &xd->plane[0].pre[0]);
1150 gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
1151 &xd->plane[0].pre[0]);
1152 #endif // CONFIG_VP9_HIGHBITDEPTH
1154 first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &gf_motion_error);
1156 if (gf_motion_error < motion_error && gf_motion_error < this_error)
1157 ++(fp_acc_data->second_ref_count);
1159 // Reset to last frame as reference buffer.
1160 xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
1161 xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
1162 xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
1164 // In accumulating a score for the older reference frame take the
1165 // best of the motion predicted score and the intra coded error
1166 // (just as will be done for) accumulation of "coded_error" for
1168 if (gf_motion_error < this_error)
1169 fp_acc_data->sr_coded_error += gf_motion_error;
1171 fp_acc_data->sr_coded_error += this_error;
1173 fp_acc_data->sr_coded_error += motion_error;
1176 fp_acc_data->sr_coded_error += motion_error;
1179 // Start by assuming that intra mode is best.
1180 best_ref_mv->row = 0;
1181 best_ref_mv->col = 0;
1183 #if CONFIG_FP_MB_STATS
1184 if (cpi->use_fp_mb_stats) {
1185 // intra prediction statistics
1186 cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
1187 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_DCINTRA_MASK;
1188 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
1189 if (this_error > FPMB_ERROR_LARGE_TH) {
1190 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_LARGE_MASK;
1191 } else if (this_error < FPMB_ERROR_SMALL_TH) {
1192 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_SMALL_MASK;
1197 if (motion_error <= this_error) {
1198 vpx_clear_system_state();
1200 // Keep a count of cases where the inter and intra were very close
1201 // and very low. This helps with scene cut detection for example in
1202 // cropped clips with black bars at the sides or top and bottom.
1203 if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
1204 (this_error < (2 * intrapenalty))) {
1205 fp_acc_data->neutral_count += 1.0;
1206 if (cpi->row_mt_bit_exact)
1207 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count =
1209 // Also track cases where the intra is not much worse than the inter
1210 // and use this in limiting the GF/arf group length.
1211 } else if ((this_error > NCOUNT_INTRA_THRESH) &&
1212 (this_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
1214 (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_error);
1215 fp_acc_data->neutral_count += mb_neutral_count;
1216 if (cpi->row_mt_bit_exact)
1217 cpi->twopass.fp_mb_float_stats[mb_index].frame_mb_neutral_count =
1223 this_error = motion_error;
1224 xd->mi[0]->mode = NEWMV;
1225 xd->mi[0]->mv[0].as_mv = mv;
1226 xd->mi[0]->tx_size = TX_4X4;
1227 xd->mi[0]->ref_frame[0] = LAST_FRAME;
1228 xd->mi[0]->ref_frame[1] = NONE;
1229 vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
1230 vp9_encode_sby_pass1(x, bsize);
1231 fp_acc_data->sum_mvr += mv.row;
1232 fp_acc_data->sum_mvr_abs += abs(mv.row);
1233 fp_acc_data->sum_mvc += mv.col;
1234 fp_acc_data->sum_mvc_abs += abs(mv.col);
1235 fp_acc_data->sum_mvrs += mv.row * mv.row;
1236 fp_acc_data->sum_mvcs += mv.col * mv.col;
1237 ++(fp_acc_data->intercount);
1241 #if CONFIG_FP_MB_STATS
1242 if (cpi->use_fp_mb_stats) {
1243 // inter prediction statistics
1244 cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
1245 cpi->twopass.frame_mb_stats_buf[mb_index] &= ~FPMB_DCINTRA_MASK;
1246 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
1247 if (this_error > FPMB_ERROR_LARGE_TH) {
1248 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_LARGE_MASK;
1249 } else if (this_error < FPMB_ERROR_SMALL_TH) {
1250 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_SMALL_MASK;
1255 if (!is_zero_mv(&mv)) {
1256 ++(fp_acc_data->mvcount);
1258 #if CONFIG_FP_MB_STATS
1259 if (cpi->use_fp_mb_stats) {
1260 cpi->twopass.frame_mb_stats_buf[mb_index] &= ~FPMB_MOTION_ZERO_MASK;
1261 // check estimated motion direction
1262 if (mv.as_mv.col > 0 && mv.as_mv.col >= abs(mv.as_mv.row)) {
1264 cpi->twopass.frame_mb_stats_buf[mb_index] |=
1265 FPMB_MOTION_RIGHT_MASK;
1266 } else if (mv.as_mv.row < 0 &&
1267 abs(mv.as_mv.row) >= abs(mv.as_mv.col)) {
1269 cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_UP_MASK;
1270 } else if (mv.as_mv.col < 0 &&
1271 abs(mv.as_mv.col) >= abs(mv.as_mv.row)) {
1273 cpi->twopass.frame_mb_stats_buf[mb_index] |=
1274 FPMB_MOTION_LEFT_MASK;
1277 cpi->twopass.frame_mb_stats_buf[mb_index] |=
1278 FPMB_MOTION_DOWN_MASK;
1283 // Does the row vector point inwards or outwards?
1284 if (mb_row < cm->mb_rows / 2) {
1286 --(fp_acc_data->sum_in_vectors);
1287 else if (mv.row < 0)
1288 ++(fp_acc_data->sum_in_vectors);
1289 } else if (mb_row > cm->mb_rows / 2) {
1291 ++(fp_acc_data->sum_in_vectors);
1292 else if (mv.row < 0)
1293 --(fp_acc_data->sum_in_vectors);
1296 // Does the col vector point inwards or outwards?
1297 if (mb_col < cm->mb_cols / 2) {
1299 --(fp_acc_data->sum_in_vectors);
1300 else if (mv.col < 0)
1301 ++(fp_acc_data->sum_in_vectors);
1302 } else if (mb_col > cm->mb_cols / 2) {
1304 ++(fp_acc_data->sum_in_vectors);
1305 else if (mv.col < 0)
1306 --(fp_acc_data->sum_in_vectors);
1308 fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1309 } else if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
1310 fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1311 } else { // 0,0 mv but high error
1312 fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1314 } else { // Intra < inter error
1315 int scaled_low_intra_thresh = scale_sse_threshold(cm, LOW_I_THRESH);
1316 if (this_intra_error < scaled_low_intra_thresh) {
1317 fp_acc_data->frame_noise_energy += fp_estimate_block_noise(x, bsize);
1318 if (motion_error < scaled_low_intra_thresh) {
1319 fp_acc_data->intra_count_low += 1.0;
1321 fp_acc_data->intra_count_high += 1.0;
1324 fp_acc_data->frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
1325 fp_acc_data->intra_count_high += 1.0;
1329 fp_acc_data->sr_coded_error += (int64_t)this_error;
1331 fp_acc_data->coded_error += (int64_t)this_error;
1333 recon_yoffset += 16;
1334 recon_uvoffset += uv_mb_height;
1336 // Accumulate row level stats to the corresponding tile stats
1337 if (cpi->row_mt && mb_col == (tile.mi_col_end >> 1) - 1)
1338 accumulate_fp_mb_row_stat(tile_data, fp_acc_data);
1340 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, mb_row, c,
1343 vpx_clear_system_state();
1346 static void first_pass_encode(VP9_COMP *cpi, FIRSTPASS_DATA *fp_acc_data) {
1347 VP9_COMMON *const cm = &cpi->common;
1349 TileDataEnc tile_data;
1350 TileInfo *tile = &tile_data.tile_info;
1351 MV zero_mv = { 0, 0 };
1353 // Tiling is ignored in the first pass.
1354 vp9_tile_init(tile, cm, 0, 0);
1356 for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
1357 best_ref_mv = zero_mv;
1358 vp9_first_pass_encode_tile_mb_row(cpi, &cpi->td, fp_acc_data, &tile_data,
1359 &best_ref_mv, mb_row);
1363 void vp9_first_pass(VP9_COMP *cpi, const struct lookahead_entry *source) {
1364 MACROBLOCK *const x = &cpi->td.mb;
1365 VP9_COMMON *const cm = &cpi->common;
1366 MACROBLOCKD *const xd = &x->e_mbd;
1367 TWO_PASS *twopass = &cpi->twopass;
1369 YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1370 YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1371 YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
1372 const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
1374 LAYER_CONTEXT *const lc =
1375 is_two_pass_svc(cpi) ? &cpi->svc.layer_context[cpi->svc.spatial_layer_id]
1377 BufferPool *const pool = cm->buffer_pool;
1379 FIRSTPASS_DATA fp_temp_data;
1380 FIRSTPASS_DATA *fp_acc_data = &fp_temp_data;
1382 vpx_clear_system_state();
1383 vp9_zero(fp_temp_data);
1384 fp_acc_data->image_data_start_row = INVALID_ROW;
1386 // First pass code requires valid last and new frame buffers.
1387 assert(new_yv12 != NULL);
1388 assert((lc != NULL) || frame_is_intra_only(cm) || (lst_yv12 != NULL));
1390 #if CONFIG_FP_MB_STATS
1391 if (cpi->use_fp_mb_stats) {
1392 vp9_zero_array(cpi->twopass.frame_mb_stats_buf, cm->initial_mbs);
1396 set_first_pass_params(cpi);
1397 vp9_set_quantizer(cm, find_fp_qindex(cm->bit_depth));
1400 twopass = &lc->twopass;
1402 cpi->lst_fb_idx = cpi->svc.spatial_layer_id;
1403 cpi->ref_frame_flags = VP9_LAST_FLAG;
1405 if (cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id <
1408 cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id;
1409 cpi->ref_frame_flags |= VP9_GOLD_FLAG;
1410 cpi->refresh_golden_frame = (lc->current_video_frame_in_layer == 0);
1412 cpi->refresh_golden_frame = 0;
1415 if (lc->current_video_frame_in_layer == 0) cpi->ref_frame_flags = 0;
1417 vp9_scale_references(cpi);
1419 // Use either last frame or alt frame for motion search.
1420 if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
1421 first_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
1422 if (first_ref_buf == NULL)
1423 first_ref_buf = get_ref_frame_buffer(cpi, LAST_FRAME);
1426 if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
1427 gld_yv12 = vp9_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
1428 if (gld_yv12 == NULL) {
1429 gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1435 set_ref_ptrs(cm, xd,
1436 (cpi->ref_frame_flags & VP9_LAST_FLAG) ? LAST_FRAME : NONE,
1437 (cpi->ref_frame_flags & VP9_GOLD_FLAG) ? GOLDEN_FRAME : NONE);
1439 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
1440 &cpi->scaled_source, 0, EIGHTTAP, 0);
1443 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
1445 vp9_setup_src_planes(x, cpi->Source, 0, 0);
1446 vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
1448 if (!frame_is_intra_only(cm)) {
1449 vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
1452 xd->mi = cm->mi_grid_visible;
1455 vp9_frame_init_quantizer(cpi);
1459 vp9_init_mv_probs(cm);
1460 vp9_initialize_rd_consts(cpi);
1462 cm->log2_tile_rows = 0;
1464 if (cpi->row_mt_bit_exact && cpi->twopass.fp_mb_float_stats == NULL)
1466 cm, cpi->twopass.fp_mb_float_stats,
1467 vpx_calloc(cm->MBs * sizeof(*cpi->twopass.fp_mb_float_stats), 1));
1470 FIRSTPASS_STATS fps;
1471 TileDataEnc *first_tile_col;
1473 cm->log2_tile_cols = 0;
1474 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
1475 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
1476 first_pass_encode(cpi, fp_acc_data);
1477 first_pass_stat_calc(cpi, &fps, fp_acc_data);
1479 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
1480 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
1481 if (cpi->row_mt_bit_exact) {
1482 cm->log2_tile_cols = 0;
1483 vp9_zero_array(cpi->twopass.fp_mb_float_stats, cm->MBs);
1485 vp9_encode_fp_row_mt(cpi);
1486 first_tile_col = &cpi->tile_data[0];
1487 if (cpi->row_mt_bit_exact)
1488 accumulate_floating_point_stats(cpi, first_tile_col);
1489 first_pass_stat_calc(cpi, &fps, &(first_tile_col->fp_data));
1492 // Dont allow a value of 0 for duration.
1493 // (Section duration is also defaulted to minimum of 1.0).
1494 fps.duration = VPXMAX(1.0, (double)(source->ts_end - source->ts_start));
1496 // Don't want to do output stats with a stack variable!
1497 twopass->this_frame_stats = fps;
1498 output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
1499 accumulate_stats(&twopass->total_stats, &fps);
1501 #if CONFIG_FP_MB_STATS
1502 if (cpi->use_fp_mb_stats) {
1503 output_fpmb_stats(twopass->frame_mb_stats_buf, cm, cpi->output_pkt_list);
1508 // Copy the previous Last Frame back into gf and and arf buffers if
1509 // the prediction is good enough... but also don't allow it to lag too far.
1510 if ((twopass->sr_update_lag > 3) ||
1511 ((cm->current_video_frame > 0) &&
1512 (twopass->this_frame_stats.pcnt_inter > 0.20) &&
1513 ((twopass->this_frame_stats.intra_error /
1514 DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
1515 if (gld_yv12 != NULL) {
1516 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1517 cm->ref_frame_map[cpi->lst_fb_idx]);
1519 twopass->sr_update_lag = 1;
1521 ++twopass->sr_update_lag;
1524 vpx_extend_frame_borders(new_yv12);
1527 vp9_update_reference_frames(cpi);
1529 // The frame we just compressed now becomes the last frame.
1530 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
1534 // Special case for the first frame. Copy into the GF buffer as a second
1536 if (cm->current_video_frame == 0 && cpi->gld_fb_idx != INVALID_IDX &&
1538 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
1539 cm->ref_frame_map[cpi->lst_fb_idx]);
1542 // Use this to see what the first pass reconstruction looks like.
1546 snprintf(filename, sizeof(filename), "enc%04d.yuv",
1547 (int)cm->current_video_frame);
1549 if (cm->current_video_frame == 0)
1550 recon_file = fopen(filename, "wb");
1552 recon_file = fopen(filename, "ab");
1554 (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
1558 ++cm->current_video_frame;
1559 if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
1562 static const double q_pow_term[(QINDEX_RANGE >> 5) + 1] = {
1563 0.65, 0.70, 0.75, 0.85, 0.90, 0.90, 0.90, 1.00, 1.25
1566 static double calc_correction_factor(double err_per_mb, double err_divisor,
1568 const double error_term = err_per_mb / DOUBLE_DIVIDE_CHECK(err_divisor);
1569 const int index = q >> 5;
1572 assert((index >= 0) && (index < (QINDEX_RANGE >> 5)));
1574 // Adjustment based on quantizer to the power term.
1577 (((q_pow_term[index + 1] - q_pow_term[index]) * (q % 32)) / 32.0);
1579 // Calculate correction factor.
1580 if (power_term < 1.0) assert(error_term >= 0.0);
1582 return fclamp(pow(error_term, power_term), 0.05, 5.0);
1585 #define ERR_DIVISOR 115.0
1586 #define NOISE_FACTOR_MIN 0.9
1587 #define NOISE_FACTOR_MAX 1.1
1588 static int get_twopass_worst_quality(VP9_COMP *cpi, const double section_err,
1589 double inactive_zone, double section_noise,
1590 int section_target_bandwidth) {
1591 const RATE_CONTROL *const rc = &cpi->rc;
1592 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1593 TWO_PASS *const twopass = &cpi->twopass;
1594 double last_group_rate_err;
1596 // Clamp the target rate to VBR min / max limts.
1597 const int target_rate =
1598 vp9_rc_clamp_pframe_target_size(cpi, section_target_bandwidth);
1599 double noise_factor = pow((section_noise / SECTION_NOISE_DEF), 0.5);
1600 noise_factor = fclamp(noise_factor, NOISE_FACTOR_MIN, NOISE_FACTOR_MAX);
1601 inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
1603 // TODO(jimbankoski): remove #if here or below when this has been
1605 #if CONFIG_ALWAYS_ADJUST_BPM
1606 // based on recent history adjust expectations of bits per macroblock.
1607 last_group_rate_err =
1608 (double)twopass->rolling_arf_group_actual_bits /
1609 DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
1610 last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
1611 twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
1612 twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
1615 if (target_rate <= 0) {
1616 return rc->worst_quality; // Highest value allowed
1618 const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
1621 const double active_pct = VPXMAX(0.01, 1.0 - inactive_zone);
1622 const int active_mbs = (int)VPXMAX(1, (double)num_mbs * active_pct);
1623 const double av_err_per_mb = section_err / active_pct;
1624 const double speed_term = 1.0 + 0.04 * oxcf->speed;
1625 const int target_norm_bits_per_mb =
1626 (int)(((uint64_t)target_rate << BPER_MB_NORMBITS) / active_mbs);
1629 // TODO(jimbankoski): remove #if here or above when this has been
1631 #if !CONFIG_ALWAYS_ADJUST_BPM
1632 // based on recent history adjust expectations of bits per macroblock.
1633 last_group_rate_err =
1634 (double)twopass->rolling_arf_group_actual_bits /
1635 DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
1636 last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
1637 twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
1638 twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
1641 // Try and pick a max Q that will be high enough to encode the
1642 // content at the given rate.
1643 for (q = rc->best_quality; q < rc->worst_quality; ++q) {
1644 const double factor =
1645 calc_correction_factor(av_err_per_mb, ERR_DIVISOR, q);
1646 const int bits_per_mb = vp9_rc_bits_per_mb(
1648 factor * speed_term * cpi->twopass.bpm_factor * noise_factor,
1649 cpi->common.bit_depth);
1650 if (bits_per_mb <= target_norm_bits_per_mb) break;
1653 // Restriction on active max q for constrained quality mode.
1654 if (cpi->oxcf.rc_mode == VPX_CQ) q = VPXMAX(q, oxcf->cq_level);
1659 static void setup_rf_level_maxq(VP9_COMP *cpi) {
1661 RATE_CONTROL *const rc = &cpi->rc;
1662 for (i = INTER_NORMAL; i < RATE_FACTOR_LEVELS; ++i) {
1663 int qdelta = vp9_frame_type_qdelta(cpi, i, rc->worst_quality);
1664 rc->rf_level_maxq[i] = VPXMAX(rc->worst_quality + qdelta, rc->best_quality);
1668 static void init_subsampling(VP9_COMP *cpi) {
1669 const VP9_COMMON *const cm = &cpi->common;
1670 RATE_CONTROL *const rc = &cpi->rc;
1671 const int w = cm->width;
1672 const int h = cm->height;
1675 for (i = 0; i < FRAME_SCALE_STEPS; ++i) {
1676 // Note: Frames with odd-sized dimensions may result from this scaling.
1677 rc->frame_width[i] = (w * 16) / frame_scale_factor[i];
1678 rc->frame_height[i] = (h * 16) / frame_scale_factor[i];
1681 setup_rf_level_maxq(cpi);
1684 void calculate_coded_size(VP9_COMP *cpi, int *scaled_frame_width,
1685 int *scaled_frame_height) {
1686 RATE_CONTROL *const rc = &cpi->rc;
1687 *scaled_frame_width = rc->frame_width[rc->frame_size_selector];
1688 *scaled_frame_height = rc->frame_height[rc->frame_size_selector];
1691 void vp9_init_second_pass(VP9_COMP *cpi) {
1692 SVC *const svc = &cpi->svc;
1693 VP9EncoderConfig *const oxcf = &cpi->oxcf;
1694 const int is_two_pass_svc =
1695 (svc->number_spatial_layers > 1) || (svc->number_temporal_layers > 1);
1696 RATE_CONTROL *const rc = &cpi->rc;
1697 TWO_PASS *const twopass =
1698 is_two_pass_svc ? &svc->layer_context[svc->spatial_layer_id].twopass
1701 FIRSTPASS_STATS *stats;
1703 zero_stats(&twopass->total_stats);
1704 zero_stats(&twopass->total_left_stats);
1706 if (!twopass->stats_in_end) return;
1708 stats = &twopass->total_stats;
1710 *stats = *twopass->stats_in_end;
1711 twopass->total_left_stats = *stats;
1713 // Scan the first pass file and calculate a modified score for each
1714 // frame that is used to distribute bits. The modified score is assumed
1715 // to provide a linear basis for bit allocation. I.e a frame A with a score
1716 // that is double that of frame B will be allocated 2x as many bits.
1718 double modified_score_total = 0.0;
1719 const FIRSTPASS_STATS *s = twopass->stats_in;
1722 if (oxcf->vbr_corpus_complexity) {
1723 twopass->mean_mod_score = (double)oxcf->vbr_corpus_complexity / 10.0;
1724 av_err = get_distribution_av_err(cpi, twopass);
1726 av_err = get_distribution_av_err(cpi, twopass);
1727 // The first scan is unclamped and gives a raw average.
1728 while (s < twopass->stats_in_end) {
1729 modified_score_total += calculate_mod_frame_score(cpi, oxcf, s, av_err);
1733 // The average error from this first scan is used to define the midpoint
1734 // error for the rate distribution function.
1735 twopass->mean_mod_score =
1736 modified_score_total / DOUBLE_DIVIDE_CHECK(stats->count);
1739 // Second scan using clamps based on the previous cycle average.
1740 // This may modify the total and average somewhat but we dont bother with
1741 // further itterations.
1742 modified_score_total = 0.0;
1743 s = twopass->stats_in;
1744 while (s < twopass->stats_in_end) {
1745 modified_score_total +=
1746 calculate_norm_frame_score(cpi, twopass, oxcf, s, av_err);
1749 twopass->normalized_score_left = modified_score_total;
1751 // If using Corpus wide VBR mode then update the clip target bandwidth to
1752 // reflect how the clip compares to the rest of the corpus.
1753 if (oxcf->vbr_corpus_complexity) {
1754 oxcf->target_bandwidth =
1755 (int64_t)((double)oxcf->target_bandwidth *
1756 (twopass->normalized_score_left / stats->count));
1759 #if COMPLEXITY_STATS_OUTPUT
1762 compstats = fopen("complexity_stats.stt", "a");
1763 fprintf(compstats, "%10.3lf\n",
1764 twopass->normalized_score_left / stats->count);
1770 frame_rate = 10000000.0 * stats->count / stats->duration;
1771 // Each frame can have a different duration, as the frame rate in the source
1772 // isn't guaranteed to be constant. The frame rate prior to the first frame
1773 // encoded in the second pass is a guess. However, the sum duration is not.
1774 // It is calculated based on the actual durations of all frames from the
1777 if (is_two_pass_svc) {
1778 vp9_update_spatial_layer_framerate(cpi, frame_rate);
1779 twopass->bits_left =
1780 (int64_t)(stats->duration *
1781 svc->layer_context[svc->spatial_layer_id].target_bandwidth /
1784 vp9_new_framerate(cpi, frame_rate);
1785 twopass->bits_left =
1786 (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
1789 // This variable monitors how far behind the second ref update is lagging.
1790 twopass->sr_update_lag = 1;
1792 // Reset the vbr bits off target counters
1793 rc->vbr_bits_off_target = 0;
1794 rc->vbr_bits_off_target_fast = 0;
1795 rc->rate_error_estimate = 0;
1797 // Static sequence monitor variables.
1798 twopass->kf_zeromotion_pct = 100;
1799 twopass->last_kfgroup_zeromotion_pct = 100;
1801 // Initialize bits per macro_block estimate correction factor.
1802 twopass->bpm_factor = 1.0;
1803 // Initialize actual and target bits counters for ARF groups so that
1804 // at the start we have a neutral bpm adjustment.
1805 twopass->rolling_arf_group_target_bits = 1;
1806 twopass->rolling_arf_group_actual_bits = 1;
1808 if (oxcf->resize_mode != RESIZE_NONE) {
1809 init_subsampling(cpi);
1812 // Initialize the arnr strangth adjustment to 0
1813 twopass->arnr_strength_adjustment = 0;
1816 #define SR_DIFF_PART 0.0015
1817 #define INTRA_PART 0.005
1818 #define DEFAULT_DECAY_LIMIT 0.75
1819 #define LOW_SR_DIFF_TRHESH 0.1
1820 #define SR_DIFF_MAX 128.0
1821 #define LOW_CODED_ERR_PER_MB 10.0
1822 #define NCOUNT_FRAME_II_THRESH 6.0
1824 static double get_sr_decay_rate(const VP9_COMP *cpi,
1825 const FIRSTPASS_STATS *frame) {
1826 double sr_diff = (frame->sr_coded_error - frame->coded_error);
1827 double sr_decay = 1.0;
1828 double modified_pct_inter;
1829 double modified_pcnt_intra;
1830 const double motion_amplitude_part =
1831 frame->pcnt_motion * ((frame->mvc_abs + frame->mvr_abs) /
1832 (cpi->initial_height + cpi->initial_width));
1834 modified_pct_inter = frame->pcnt_inter;
1835 if ((frame->coded_error > LOW_CODED_ERR_PER_MB) &&
1836 ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
1837 (double)NCOUNT_FRAME_II_THRESH)) {
1838 modified_pct_inter =
1839 frame->pcnt_inter + frame->pcnt_intra_low - frame->pcnt_neutral;
1841 modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
1843 if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
1844 sr_diff = VPXMIN(sr_diff, SR_DIFF_MAX);
1845 sr_decay = 1.0 - (SR_DIFF_PART * sr_diff) - motion_amplitude_part -
1846 (INTRA_PART * modified_pcnt_intra);
1848 return VPXMAX(sr_decay, DEFAULT_DECAY_LIMIT);
1851 // This function gives an estimate of how badly we believe the prediction
1852 // quality is decaying from frame to frame.
1853 static double get_zero_motion_factor(const VP9_COMP *cpi,
1854 const FIRSTPASS_STATS *frame) {
1855 const double zero_motion_pct = frame->pcnt_inter - frame->pcnt_motion;
1856 double sr_decay = get_sr_decay_rate(cpi, frame);
1857 return VPXMIN(sr_decay, zero_motion_pct);
1860 #define ZM_POWER_FACTOR 0.75
1862 static double get_prediction_decay_rate(const VP9_COMP *cpi,
1863 const FIRSTPASS_STATS *next_frame) {
1864 const double sr_decay_rate = get_sr_decay_rate(cpi, next_frame);
1865 const double zero_motion_factor =
1866 (0.95 * pow((next_frame->pcnt_inter - next_frame->pcnt_motion),
1869 return VPXMAX(zero_motion_factor,
1870 (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
1873 // Function to test for a condition where a complex transition is followed
1874 // by a static section. For example in slide shows where there is a fade
1875 // between slides. This is to help with more optimal kf and gf positioning.
1876 static int detect_transition_to_still(VP9_COMP *cpi, int frame_interval,
1878 double loop_decay_rate,
1879 double last_decay_rate) {
1880 TWO_PASS *const twopass = &cpi->twopass;
1881 RATE_CONTROL *const rc = &cpi->rc;
1883 // Break clause to detect very still sections after motion
1884 // For example a static image after a fade or other transition
1885 // instead of a clean scene cut.
1886 if (frame_interval > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
1887 last_decay_rate < 0.9) {
1890 // Look ahead a few frames to see if static condition persists...
1891 for (j = 0; j < still_interval; ++j) {
1892 const FIRSTPASS_STATS *stats = &twopass->stats_in[j];
1893 if (stats >= twopass->stats_in_end) break;
1895 if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
1898 // Only if it does do we signal a transition to still.
1899 return j == still_interval;
1905 // This function detects a flash through the high relative pcnt_second_ref
1906 // score in the frame following a flash frame. The offset passed in should
1908 static int detect_flash(const TWO_PASS *twopass, int offset) {
1909 const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
1911 // What we are looking for here is a situation where there is a
1912 // brief break in prediction (such as a flash) but subsequent frames
1913 // are reasonably well predicted by an earlier (pre flash) frame.
1914 // The recovery after a flash is indicated by a high pcnt_second_ref
1915 // compared to pcnt_inter.
1916 return next_frame != NULL &&
1917 next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
1918 next_frame->pcnt_second_ref >= 0.5;
1921 // Update the motion related elements to the GF arf boost calculation.
1922 static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
1924 double *mv_in_out_accumulator,
1925 double *abs_mv_in_out_accumulator,
1926 double *mv_ratio_accumulator) {
1927 const double pct = stats->pcnt_motion;
1929 // Accumulate Motion In/Out of frame stats.
1930 *mv_in_out = stats->mv_in_out_count * pct;
1931 *mv_in_out_accumulator += *mv_in_out;
1932 *abs_mv_in_out_accumulator += fabs(*mv_in_out);
1934 // Accumulate a measure of how uniform (or conversely how random) the motion
1935 // field is (a ratio of abs(mv) / mv).
1937 const double mvr_ratio =
1938 fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
1939 const double mvc_ratio =
1940 fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
1942 *mv_ratio_accumulator +=
1943 pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
1944 *mv_ratio_accumulator +=
1945 pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
1949 #define BASELINE_ERR_PER_MB 12500.0
1950 #define GF_MAX_BOOST 96.0
1951 static double calc_frame_boost(VP9_COMP *cpi, const FIRSTPASS_STATS *this_frame,
1952 double this_frame_mv_in_out) {
1954 const double lq = vp9_convert_qindex_to_q(
1955 cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.bit_depth);
1956 const double boost_q_correction = VPXMIN((0.5 + (lq * 0.015)), 1.5);
1957 const double active_area = calculate_active_area(cpi, this_frame);
1959 // Underlying boost factor is based on inter error ratio.
1960 frame_boost = (BASELINE_ERR_PER_MB * active_area) /
1961 DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
1963 // Small adjustment for cases where there is a zoom out
1964 if (this_frame_mv_in_out > 0.0)
1965 frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1967 // Q correction and scalling
1968 frame_boost = frame_boost * boost_q_correction;
1970 return VPXMIN(frame_boost, GF_MAX_BOOST * boost_q_correction);
1973 #define KF_BASELINE_ERR_PER_MB 12500.0
1974 static double calc_kf_frame_boost(VP9_COMP *cpi,
1975 const FIRSTPASS_STATS *this_frame,
1976 double *sr_accumulator,
1977 double this_frame_mv_in_out,
1980 const double lq = vp9_convert_qindex_to_q(
1981 cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.bit_depth);
1982 const double boost_q_correction = VPXMIN((0.50 + (lq * 0.015)), 2.00);
1983 const double active_area = calculate_active_area(cpi, this_frame);
1985 // Underlying boost factor is based on inter error ratio.
1986 frame_boost = (KF_BASELINE_ERR_PER_MB * active_area) /
1987 DOUBLE_DIVIDE_CHECK(this_frame->coded_error + *sr_accumulator);
1989 // Update the accumulator for second ref error difference.
1990 // This is intended to give an indication of how much the coded error is
1991 // increasing over time.
1992 *sr_accumulator += (this_frame->sr_coded_error - this_frame->coded_error);
1993 *sr_accumulator = VPXMAX(0.0, *sr_accumulator);
1995 // Small adjustment for cases where there is a zoom out
1996 if (this_frame_mv_in_out > 0.0)
1997 frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1999 // Q correction and scalling
2000 frame_boost = frame_boost * boost_q_correction;
2002 return VPXMIN(frame_boost, max_boost * boost_q_correction);
2005 static int calc_arf_boost(VP9_COMP *cpi, int f_frames, int b_frames) {
2006 TWO_PASS *const twopass = &cpi->twopass;
2008 double boost_score = 0.0;
2009 double mv_ratio_accumulator = 0.0;
2010 double decay_accumulator = 1.0;
2011 double this_frame_mv_in_out = 0.0;
2012 double mv_in_out_accumulator = 0.0;
2013 double abs_mv_in_out_accumulator = 0.0;
2015 int flash_detected = 0;
2017 // Search forward from the proposed arf/next gf position.
2018 for (i = 0; i < f_frames; ++i) {
2019 const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i);
2020 if (this_frame == NULL) break;
2022 // Update the motion related elements to the boost calculation.
2023 accumulate_frame_motion_stats(
2024 this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2025 &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2027 // We want to discount the flash frame itself and the recovery
2028 // frame that follows as both will have poor scores.
2029 flash_detected = detect_flash(twopass, i) || detect_flash(twopass, i + 1);
2031 // Accumulate the effect of prediction quality decay.
2032 if (!flash_detected) {
2033 decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
2034 decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
2036 : decay_accumulator;
2038 boost_score += decay_accumulator *
2039 calc_frame_boost(cpi, this_frame, this_frame_mv_in_out);
2042 arf_boost = (int)boost_score;
2044 // Reset for backward looking loop.
2046 mv_ratio_accumulator = 0.0;
2047 decay_accumulator = 1.0;
2048 this_frame_mv_in_out = 0.0;
2049 mv_in_out_accumulator = 0.0;
2050 abs_mv_in_out_accumulator = 0.0;
2052 // Search backward towards last gf position.
2053 for (i = -1; i >= -b_frames; --i) {
2054 const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i);
2055 if (this_frame == NULL) break;
2057 // Update the motion related elements to the boost calculation.
2058 accumulate_frame_motion_stats(
2059 this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2060 &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2062 // We want to discount the the flash frame itself and the recovery
2063 // frame that follows as both will have poor scores.
2064 flash_detected = detect_flash(twopass, i) || detect_flash(twopass, i + 1);
2066 // Cumulative effect of prediction quality decay.
2067 if (!flash_detected) {
2068 decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
2069 decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
2071 : decay_accumulator;
2073 boost_score += decay_accumulator *
2074 calc_frame_boost(cpi, this_frame, this_frame_mv_in_out);
2076 arf_boost += (int)boost_score;
2078 if (arf_boost < ((b_frames + f_frames) * 40))
2079 arf_boost = ((b_frames + f_frames) * 40);
2080 arf_boost = VPXMAX(arf_boost, MIN_ARF_GF_BOOST);
2085 // Calculate a section intra ratio used in setting max loop filter.
2086 static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
2087 const FIRSTPASS_STATS *end,
2088 int section_length) {
2089 const FIRSTPASS_STATS *s = begin;
2090 double intra_error = 0.0;
2091 double coded_error = 0.0;
2094 while (s < end && i < section_length) {
2095 intra_error += s->intra_error;
2096 coded_error += s->coded_error;
2101 return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
2104 // Calculate the total bits to allocate in this GF/ARF group.
2105 static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
2106 double gf_group_err) {
2107 const RATE_CONTROL *const rc = &cpi->rc;
2108 const TWO_PASS *const twopass = &cpi->twopass;
2109 const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2110 int64_t total_group_bits;
2112 // Calculate the bits to be allocated to the group as a whole.
2113 if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0.0)) {
2114 total_group_bits = (int64_t)(twopass->kf_group_bits *
2115 (gf_group_err / twopass->kf_group_error_left));
2117 total_group_bits = 0;
2120 // Clamp odd edge cases.
2121 total_group_bits = (total_group_bits < 0)
2123 : (total_group_bits > twopass->kf_group_bits)
2124 ? twopass->kf_group_bits
2127 // Clip based on user supplied data rate variability limit.
2128 if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
2129 total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
2131 return total_group_bits;
2134 // Calculate the number bits extra to assign to boosted frames in a group.
2135 static int calculate_boost_bits(int frame_count, int boost,
2136 int64_t total_group_bits) {
2137 int allocation_chunks;
2139 // return 0 for invalid inputs (could arise e.g. through rounding errors)
2140 if (!boost || (total_group_bits <= 0) || (frame_count < 0)) return 0;
2142 allocation_chunks = (frame_count * 100) + boost;
2144 // Prevent overflow.
2146 int divisor = boost >> 10;
2148 allocation_chunks /= divisor;
2151 // Calculate the number of extra bits for use in the boosted frame or frames.
2152 return VPXMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
2156 // Current limit on maximum number of active arfs in a GF/ARF group.
2157 #define MAX_ACTIVE_ARFS 2
2160 // This function indirects the choice of buffers for arfs.
2161 // At the moment the values are fixed but this may change as part of
2162 // the integration process with other codec features that swap buffers around.
2163 static void get_arf_buffer_indices(unsigned char *arf_buffer_indices) {
2164 arf_buffer_indices[0] = ARF_SLOT1;
2165 arf_buffer_indices[1] = ARF_SLOT2;
2168 // Used in corpus vbr: Calculates the total normalized group complexity score
2169 // for a given number of frames starting at the current position in the stats
2171 static double calculate_group_score(VP9_COMP *cpi, double av_score,
2173 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2174 TWO_PASS *const twopass = &cpi->twopass;
2175 const FIRSTPASS_STATS *s = twopass->stats_in;
2176 double score_total = 0.0;
2179 // We dont ever want to return a 0 score here.
2180 if (frame_count == 0) return 1.0;
2182 while ((i < frame_count) && (s < twopass->stats_in_end)) {
2183 score_total += calculate_norm_frame_score(cpi, twopass, oxcf, s, av_score);
2187 assert(i == frame_count);
2192 static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
2194 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2195 RATE_CONTROL *const rc = &cpi->rc;
2196 TWO_PASS *const twopass = &cpi->twopass;
2197 GF_GROUP *const gf_group = &twopass->gf_group;
2198 FIRSTPASS_STATS frame_stats;
2200 int frame_index = 1;
2201 int target_frame_size;
2203 const int max_bits = frame_max_bits(&cpi->rc, oxcf);
2204 int64_t total_group_bits = gf_group_bits;
2205 int mid_boost_bits = 0;
2207 unsigned char arf_buffer_indices[MAX_ACTIVE_ARFS];
2208 int alt_frame_index = frame_index;
2209 int has_temporal_layers =
2210 is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1;
2212 int normal_frame_bits;
2213 int last_frame_reduction = 0;
2214 double av_score = 1.0;
2215 double tot_norm_frame_score = 1.0;
2216 double this_frame_score = 1.0;
2218 // Only encode alt reference frame in temporal base layer.
2219 if (has_temporal_layers) alt_frame_index = cpi->svc.number_temporal_layers;
2222 cpi->common.frame_type == KEY_FRAME || vp9_is_upper_layer_key_frame(cpi);
2224 get_arf_buffer_indices(arf_buffer_indices);
2226 // For key frames the frame target rate is already set and it
2227 // is also the golden frame.
2229 if (rc->source_alt_ref_active) {
2230 gf_group->update_type[0] = OVERLAY_UPDATE;
2231 gf_group->rf_level[0] = INTER_NORMAL;
2232 gf_group->bit_allocation[0] = 0;
2234 gf_group->update_type[0] = GF_UPDATE;
2235 gf_group->rf_level[0] = GF_ARF_STD;
2236 gf_group->bit_allocation[0] = gf_arf_bits;
2238 gf_group->arf_update_idx[0] = arf_buffer_indices[0];
2239 gf_group->arf_ref_idx[0] = arf_buffer_indices[0];
2241 // Step over the golden frame / overlay frame
2242 if (EOF == input_stats(twopass, &frame_stats)) return;
2245 // Deduct the boost bits for arf (or gf if it is not a key frame)
2246 // from the group total.
2247 if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
2249 // Store the bits to spend on the ARF if there is one.
2250 if (rc->source_alt_ref_pending) {
2251 gf_group->update_type[alt_frame_index] = ARF_UPDATE;
2252 gf_group->rf_level[alt_frame_index] = GF_ARF_STD;
2253 gf_group->bit_allocation[alt_frame_index] = gf_arf_bits;
2255 if (has_temporal_layers)
2256 gf_group->arf_src_offset[alt_frame_index] =
2257 (unsigned char)(rc->baseline_gf_interval -
2258 cpi->svc.number_temporal_layers);
2260 gf_group->arf_src_offset[alt_frame_index] =
2261 (unsigned char)(rc->baseline_gf_interval - 1);
2263 gf_group->arf_update_idx[alt_frame_index] = arf_buffer_indices[0];
2264 gf_group->arf_ref_idx[alt_frame_index] =
2265 arf_buffer_indices[cpi->multi_arf_last_grp_enabled &&
2266 rc->source_alt_ref_active];
2267 if (!has_temporal_layers) ++frame_index;
2269 if (cpi->multi_arf_enabled) {
2270 // Set aside a slot for a level 1 arf.
2271 gf_group->update_type[frame_index] = ARF_UPDATE;
2272 gf_group->rf_level[frame_index] = GF_ARF_LOW;
2273 gf_group->arf_src_offset[frame_index] =
2274 (unsigned char)((rc->baseline_gf_interval >> 1) - 1);
2275 gf_group->arf_update_idx[frame_index] = arf_buffer_indices[1];
2276 gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
2281 // Note index of the first normal inter frame int eh group (not gf kf arf)
2282 gf_group->first_inter_index = frame_index;
2284 // Define middle frame
2285 mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
2287 normal_frames = (rc->baseline_gf_interval - rc->source_alt_ref_pending);
2288 if (normal_frames > 1)
2289 normal_frame_bits = (int)(total_group_bits / normal_frames);
2291 normal_frame_bits = (int)total_group_bits;
2293 if (oxcf->vbr_corpus_complexity) {
2294 av_score = get_distribution_av_err(cpi, twopass);
2295 tot_norm_frame_score = calculate_group_score(cpi, av_score, normal_frames);
2298 // Allocate bits to the other frames in the group.
2299 for (i = 0; i < normal_frames; ++i) {
2301 if (EOF == input_stats(twopass, &frame_stats)) break;
2303 if (has_temporal_layers && frame_index == alt_frame_index) {
2307 if (oxcf->vbr_corpus_complexity) {
2308 this_frame_score = calculate_norm_frame_score(cpi, twopass, oxcf,
2309 &frame_stats, av_score);
2310 normal_frame_bits = (int)((double)total_group_bits *
2311 (this_frame_score / tot_norm_frame_score));
2314 target_frame_size = normal_frame_bits;
2315 if ((i == (normal_frames - 1)) && (i >= 1)) {
2316 last_frame_reduction = normal_frame_bits / 16;
2317 target_frame_size -= last_frame_reduction;
2320 if (rc->source_alt_ref_pending && cpi->multi_arf_enabled) {
2321 mid_boost_bits += (target_frame_size >> 4);
2322 target_frame_size -= (target_frame_size >> 4);
2324 if (frame_index <= mid_frame_idx) arf_idx = 1;
2326 gf_group->arf_update_idx[frame_index] = arf_buffer_indices[arf_idx];
2327 gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[arf_idx];
2330 clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
2332 gf_group->update_type[frame_index] = LF_UPDATE;
2333 gf_group->rf_level[frame_index] = INTER_NORMAL;
2335 gf_group->bit_allocation[frame_index] = target_frame_size;
2339 // Add in some extra bits for the middle frame in the group.
2340 gf_group->bit_allocation[mid_frame_idx] += last_frame_reduction;
2343 // We need to configure the frame at the end of the sequence + 1 that will be
2344 // the start frame for the next group. Otherwise prior to the call to
2345 // vp9_rc_get_second_pass_params() the data will be undefined.
2346 gf_group->arf_update_idx[frame_index] = arf_buffer_indices[0];
2347 gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
2349 if (rc->source_alt_ref_pending) {
2350 gf_group->update_type[frame_index] = OVERLAY_UPDATE;
2351 gf_group->rf_level[frame_index] = INTER_NORMAL;
2353 // Final setup for second arf and its overlay.
2354 if (cpi->multi_arf_enabled) {
2355 gf_group->bit_allocation[2] =
2356 gf_group->bit_allocation[mid_frame_idx] + mid_boost_bits;
2357 gf_group->update_type[mid_frame_idx] = OVERLAY_UPDATE;
2358 gf_group->bit_allocation[mid_frame_idx] = 0;
2361 gf_group->update_type[frame_index] = GF_UPDATE;
2362 gf_group->rf_level[frame_index] = GF_ARF_STD;
2365 // Note whether multi-arf was enabled this group for next time.
2366 cpi->multi_arf_last_grp_enabled = cpi->multi_arf_enabled;
2369 // Adjusts the ARNF filter for a GF group.
2370 static void adjust_group_arnr_filter(VP9_COMP *cpi, double section_noise,
2371 double section_inter,
2372 double section_motion) {
2373 TWO_PASS *const twopass = &cpi->twopass;
2374 double section_zeromv = section_inter - section_motion;
2376 twopass->arnr_strength_adjustment = 0;
2378 if ((section_zeromv < 0.10) || (section_noise <= (SECTION_NOISE_DEF * 0.75)))
2379 twopass->arnr_strength_adjustment -= 1;
2380 if (section_zeromv > 0.50) twopass->arnr_strength_adjustment += 1;
2383 // Analyse and define a gf/arf group.
2384 #define ARF_DECAY_BREAKOUT 0.10
2385 #define ARF_ABS_ZOOM_THRESH 4.0
2387 static void define_gf_group(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2388 VP9_COMMON *const cm = &cpi->common;
2389 RATE_CONTROL *const rc = &cpi->rc;
2390 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2391 TWO_PASS *const twopass = &cpi->twopass;
2392 FIRSTPASS_STATS next_frame;
2393 const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
2396 double gf_group_err = 0.0;
2397 double gf_group_raw_error = 0.0;
2398 double gf_group_noise = 0.0;
2399 double gf_group_skip_pct = 0.0;
2400 double gf_group_inactive_zone_rows = 0.0;
2401 double gf_group_inter = 0.0;
2402 double gf_group_motion = 0.0;
2403 double gf_first_frame_err = 0.0;
2404 double mod_frame_err = 0.0;
2406 double mv_ratio_accumulator = 0.0;
2407 double zero_motion_accumulator = 1.0;
2408 double loop_decay_rate = 1.00;
2409 double last_loop_decay_rate = 1.00;
2411 double this_frame_mv_in_out = 0.0;
2412 double mv_in_out_accumulator = 0.0;
2413 double abs_mv_in_out_accumulator = 0.0;
2414 double mv_ratio_accumulator_thresh;
2415 double abs_mv_in_out_thresh;
2416 double sr_accumulator = 0.0;
2417 const double av_err = get_distribution_av_err(cpi, twopass);
2418 unsigned int allow_alt_ref = is_altref_enabled(cpi);
2421 int active_max_gf_interval;
2422 int active_min_gf_interval;
2423 int64_t gf_group_bits;
2425 const int is_key_frame = frame_is_intra_only(cm);
2426 const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
2428 // Reset the GF group data structures unless this is a key
2429 // frame in which case it will already have been done.
2430 if (is_key_frame == 0) {
2431 vp9_zero(twopass->gf_group);
2434 vpx_clear_system_state();
2435 vp9_zero(next_frame);
2437 // Load stats for the current frame.
2439 calculate_norm_frame_score(cpi, twopass, oxcf, this_frame, av_err);
2441 // Note the error of the frame at the start of the group. This will be
2442 // the GF frame error if we code a normal gf.
2443 gf_first_frame_err = mod_frame_err;
2445 // If this is a key frame or the overlay from a previous arf then
2446 // the error score / cost of this frame has already been accounted for.
2447 if (arf_active_or_kf) {
2448 gf_group_err -= gf_first_frame_err;
2449 gf_group_raw_error -= this_frame->coded_error;
2450 gf_group_noise -= this_frame->frame_noise_energy;
2451 gf_group_skip_pct -= this_frame->intra_skip_pct;
2452 gf_group_inactive_zone_rows -= this_frame->inactive_zone_rows;
2453 gf_group_inter -= this_frame->pcnt_inter;
2454 gf_group_motion -= this_frame->pcnt_motion;
2457 // Motion breakout threshold for loop below depends on image size.
2458 mv_ratio_accumulator_thresh =
2459 (cpi->initial_height + cpi->initial_width) / 4.0;
2460 abs_mv_in_out_thresh = ARF_ABS_ZOOM_THRESH;
2462 // Set a maximum and minimum interval for the GF group.
2463 // If the image appears almost completely static we can extend beyond this.
2465 int int_max_q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
2466 cpi->common.bit_depth));
2467 int int_lbq = (int)(vp9_convert_qindex_to_q(rc->last_boosted_qindex,
2468 cpi->common.bit_depth));
2469 active_min_gf_interval =
2470 rc->min_gf_interval + arf_active_or_kf + VPXMIN(2, int_max_q / 200);
2471 active_min_gf_interval =
2472 VPXMIN(active_min_gf_interval, rc->max_gf_interval + arf_active_or_kf);
2474 if (cpi->multi_arf_allowed) {
2475 active_max_gf_interval = rc->max_gf_interval;
2477 // The value chosen depends on the active Q range. At low Q we have
2478 // bits to spare and are better with a smaller interval and smaller boost.
2479 // At high Q when there are few bits to spare we are better with a longer
2480 // interval to spread the cost of the GF.
2481 active_max_gf_interval = 12 + arf_active_or_kf + VPXMIN(4, (int_lbq / 6));
2483 // We have: active_min_gf_interval <=
2484 // rc->max_gf_interval + arf_active_or_kf.
2485 if (active_max_gf_interval < active_min_gf_interval) {
2486 active_max_gf_interval = active_min_gf_interval;
2488 active_max_gf_interval = VPXMIN(active_max_gf_interval,
2489 rc->max_gf_interval + arf_active_or_kf);
2492 // Would the active max drop us out just before the near the next kf?
2493 if ((active_max_gf_interval <= rc->frames_to_key) &&
2494 (active_max_gf_interval >= (rc->frames_to_key - rc->min_gf_interval)))
2495 active_max_gf_interval = rc->frames_to_key / 2;
2500 while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
2503 // Accumulate error score of frames in this gf group.
2505 calculate_norm_frame_score(cpi, twopass, oxcf, this_frame, av_err);
2506 gf_group_err += mod_frame_err;
2507 gf_group_raw_error += this_frame->coded_error;
2508 gf_group_noise += this_frame->frame_noise_energy;
2509 gf_group_skip_pct += this_frame->intra_skip_pct;
2510 gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
2511 gf_group_inter += this_frame->pcnt_inter;
2512 gf_group_motion += this_frame->pcnt_motion;
2514 if (EOF == input_stats(twopass, &next_frame)) break;
2516 // Test for the case where there is a brief flash but the prediction
2517 // quality back to an earlier frame is then restored.
2518 flash_detected = detect_flash(twopass, 0);
2520 // Update the motion related elements to the boost calculation.
2521 accumulate_frame_motion_stats(
2522 &next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
2523 &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
2525 // Accumulate the effect of prediction quality decay.
2526 if (!flash_detected) {
2527 last_loop_decay_rate = loop_decay_rate;
2528 loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2530 // Monitor for static sections.
2531 zero_motion_accumulator = VPXMIN(
2532 zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
2534 // Break clause to detect very still sections after motion. For example,
2535 // a static image after a fade or other transition.
2536 if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
2537 last_loop_decay_rate)) {
2542 // Update the accumulator for second ref error difference.
2543 // This is intended to give an indication of how much the coded error is
2544 // increasing over time.
2546 sr_accumulator += next_frame.coded_error;
2548 sr_accumulator += (next_frame.sr_coded_error - next_frame.coded_error);
2552 // Break out conditions.
2554 // Break at active_max_gf_interval unless almost totally static.
2555 ((i >= active_max_gf_interval) && (zero_motion_accumulator < 0.995)) ||
2557 // Don't break out with a very short interval.
2558 (i >= active_min_gf_interval) &&
2559 // If possible dont break very close to a kf
2560 ((rc->frames_to_key - i) >= rc->min_gf_interval) &&
2561 (!flash_detected) &&
2562 ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
2563 (abs_mv_in_out_accumulator > abs_mv_in_out_thresh) ||
2564 (sr_accumulator > next_frame.intra_error)))) {
2568 *this_frame = next_frame;
2571 // Was the group length constrained by the requirement for a new KF?
2572 rc->constrained_gf_group = (i >= rc->frames_to_key) ? 1 : 0;
2574 // Should we use the alternate reference frame.
2575 if (allow_alt_ref && (i < cpi->oxcf.lag_in_frames) &&
2576 (i >= rc->min_gf_interval)) {
2577 const int forward_frames = (rc->frames_to_key - i >= i - 1)
2579 : VPXMAX(0, rc->frames_to_key - i);
2581 // Calculate the boost for alt ref.
2582 rc->gfu_boost = calc_arf_boost(cpi, forward_frames, (i - 1));
2583 rc->source_alt_ref_pending = 1;
2585 // Test to see if multi arf is appropriate.
2586 cpi->multi_arf_enabled =
2587 (cpi->multi_arf_allowed && (rc->baseline_gf_interval >= 6) &&
2588 (zero_motion_accumulator < 0.995))
2592 rc->gfu_boost = calc_arf_boost(cpi, 0, (i - 1));
2593 rc->source_alt_ref_pending = 0;
2596 #ifdef AGGRESSIVE_VBR
2597 // Limit maximum boost based on interval length.
2598 rc->gfu_boost = VPXMIN((int)rc->gfu_boost, i * 140);
2600 rc->gfu_boost = VPXMIN((int)rc->gfu_boost, i * 200);
2603 // Set the interval until the next gf.
2604 rc->baseline_gf_interval = i - (is_key_frame || rc->source_alt_ref_pending);
2606 // Only encode alt reference frame in temporal base layer. So
2607 // baseline_gf_interval should be multiple of a temporal layer group
2608 // (typically the frame distance between two base layer frames)
2609 if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
2610 int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
2611 int new_gf_interval = (rc->baseline_gf_interval + count) & (~count);
2613 for (j = 0; j < new_gf_interval - rc->baseline_gf_interval; ++j) {
2614 if (EOF == input_stats(twopass, this_frame)) break;
2616 calculate_norm_frame_score(cpi, twopass, oxcf, this_frame, av_err);
2617 gf_group_raw_error += this_frame->coded_error;
2618 gf_group_noise += this_frame->frame_noise_energy;
2619 gf_group_skip_pct += this_frame->intra_skip_pct;
2620 gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
2621 gf_group_inter += this_frame->pcnt_inter;
2622 gf_group_motion += this_frame->pcnt_motion;
2624 rc->baseline_gf_interval = new_gf_interval;
2627 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2629 // Reset the file position.
2630 reset_fpf_position(twopass, start_pos);
2632 // Calculate the bits to be allocated to the gf/arf group as a whole
2633 gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
2635 // Calculate an estimate of the maxq needed for the group.
2636 // We are more aggressive about correcting for sections
2637 // where there could be significant overshoot than for easier
2638 // sections where we do not wish to risk creating an overshoot
2639 // of the allocated bit budget.
2640 if ((cpi->oxcf.rc_mode != VPX_Q) && (rc->baseline_gf_interval > 1)) {
2641 const int vbr_group_bits_per_frame =
2642 (int)(gf_group_bits / rc->baseline_gf_interval);
2643 const double group_av_err = gf_group_raw_error / rc->baseline_gf_interval;
2644 const double group_av_noise = gf_group_noise / rc->baseline_gf_interval;
2645 const double group_av_skip_pct =
2646 gf_group_skip_pct / rc->baseline_gf_interval;
2647 const double group_av_inactive_zone =
2648 ((gf_group_inactive_zone_rows * 2) /
2649 (rc->baseline_gf_interval * (double)cm->mb_rows));
2650 int tmp_q = get_twopass_worst_quality(
2651 cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
2652 group_av_noise, vbr_group_bits_per_frame);
2653 twopass->active_worst_quality =
2654 (tmp_q + (twopass->active_worst_quality * 3)) >> 2;
2656 #if CONFIG_ALWAYS_ADJUST_BPM
2657 // Reset rolling actual and target bits counters for ARF groups.
2658 twopass->rolling_arf_group_target_bits = 0;
2659 twopass->rolling_arf_group_actual_bits = 0;
2663 // Context Adjustment of ARNR filter strength
2664 if (rc->baseline_gf_interval > 1) {
2665 adjust_group_arnr_filter(cpi, (gf_group_noise / rc->baseline_gf_interval),
2666 (gf_group_inter / rc->baseline_gf_interval),
2667 (gf_group_motion / rc->baseline_gf_interval));
2669 twopass->arnr_strength_adjustment = 0;
2672 // Calculate the extra bits to be used for boosted frame(s)
2673 gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval, rc->gfu_boost,
2676 // Adjust KF group bits and error remaining.
2677 twopass->kf_group_error_left -= gf_group_err;
2679 // Allocate bits to each of the frames in the GF group.
2680 allocate_gf_group_bits(cpi, gf_group_bits, gf_arf_bits);
2682 // Reset the file position.
2683 reset_fpf_position(twopass, start_pos);
2685 // Calculate a section intra ratio used in setting max loop filter.
2686 if (cpi->common.frame_type != KEY_FRAME) {
2687 twopass->section_intra_rating = calculate_section_intra_ratio(
2688 start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
2691 if (oxcf->resize_mode == RESIZE_DYNAMIC) {
2692 // Default to starting GF groups at normal frame size.
2693 cpi->rc.next_frame_size_selector = UNSCALED;
2695 #if !CONFIG_ALWAYS_ADJUST_BPM
2696 // Reset rolling actual and target bits counters for ARF groups.
2697 twopass->rolling_arf_group_target_bits = 0;
2698 twopass->rolling_arf_group_actual_bits = 0;
2702 // Slide show transition detection.
2703 // Tests for case where there is very low error either side of the current frame
2704 // but much higher just for this frame. This can help detect key frames in
2705 // slide shows even where the slides are pictures of different sizes.
2706 // It will not help if the transition is a fade or other multi-frame effect.
2707 static int slide_transition(double this_err, double last_err, double next_err) {
2708 return (this_err > (last_err * 5.0)) && (this_err > (next_err * 5.0));
2711 // Threshold for use of the lagging second reference frame. High second ref
2712 // usage may point to a transient event like a flash or occlusion rather than
2713 // a real scene cut.
2714 #define SECOND_REF_USEAGE_THRESH 0.1
2715 // Minimum % intra coding observed in first pass (1.0 = 100%)
2716 #define MIN_INTRA_LEVEL 0.25
2717 // Minimum ratio between the % of intra coding and inter coding in the first
2718 // pass after discounting neutral blocks (discounting neutral blocks in this
2719 // way helps catch scene cuts in clips with very flat areas or letter box
2720 // format clips with image padding.
2721 #define INTRA_VS_INTER_THRESH 2.0
2722 // Hard threshold where the first pass chooses intra for almost all blocks.
2723 // In such a case even if the frame is not a scene cut coding a key frame
2724 // may be a good option.
2725 #define VERY_LOW_INTER_THRESH 0.05
2726 // Maximum threshold for the relative ratio of intra error score vs best
2727 // inter error score.
2728 #define KF_II_ERR_THRESHOLD 2.5
2729 // In real scene cuts there is almost always a sharp change in the intra
2730 // or inter error score.
2731 #define ERR_CHANGE_THRESHOLD 0.4
2732 // For real scene cuts we expect an improvment in the intra inter error
2733 // ratio in the next frame.
2734 #define II_IMPROVEMENT_THRESHOLD 3.5
2735 #define KF_II_MAX 128.0
2736 #define II_FACTOR 12.5
2737 // Test for very low intra complexity which could cause false key frames
2738 #define V_LOW_INTRA 0.5
2740 static int test_candidate_kf(TWO_PASS *twopass,
2741 const FIRSTPASS_STATS *last_frame,
2742 const FIRSTPASS_STATS *this_frame,
2743 const FIRSTPASS_STATS *next_frame) {
2744 int is_viable_kf = 0;
2745 double pcnt_intra = 1.0 - this_frame->pcnt_inter;
2746 double modified_pcnt_inter =
2747 this_frame->pcnt_inter - this_frame->pcnt_neutral;
2749 // Does the frame satisfy the primary criteria of a key frame?
2750 // See above for an explanation of the test criteria.
2751 // If so, then examine how well it predicts subsequent frames.
2752 if ((this_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2753 (next_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
2754 ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
2755 (slide_transition(this_frame->coded_error, last_frame->coded_error,
2756 next_frame->coded_error)) ||
2757 ((pcnt_intra > MIN_INTRA_LEVEL) &&
2758 (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
2759 ((this_frame->intra_error /
2760 DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
2761 KF_II_ERR_THRESHOLD) &&
2762 ((fabs(last_frame->coded_error - this_frame->coded_error) /
2763 DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
2764 ERR_CHANGE_THRESHOLD) ||
2765 (fabs(last_frame->intra_error - this_frame->intra_error) /
2766 DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
2767 ERR_CHANGE_THRESHOLD) ||
2768 ((next_frame->intra_error /
2769 DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) >
2770 II_IMPROVEMENT_THRESHOLD))))) {
2772 const FIRSTPASS_STATS *start_pos = twopass->stats_in;
2773 FIRSTPASS_STATS local_next_frame = *next_frame;
2774 double boost_score = 0.0;
2775 double old_boost_score = 0.0;
2776 double decay_accumulator = 1.0;
2778 // Examine how well the key frame predicts subsequent frames.
2779 for (i = 0; i < 16; ++i) {
2780 double next_iiratio = (II_FACTOR * local_next_frame.intra_error /
2781 DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
2783 if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
2785 // Cumulative effect of decay in prediction quality.
2786 if (local_next_frame.pcnt_inter > 0.85)
2787 decay_accumulator *= local_next_frame.pcnt_inter;
2789 decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
2791 // Keep a running total.
2792 boost_score += (decay_accumulator * next_iiratio);
2794 // Test various breakout clauses.
2795 if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
2796 (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
2798 (next_iiratio < 3.0)) ||
2799 ((boost_score - old_boost_score) < 3.0) ||
2800 (local_next_frame.intra_error < V_LOW_INTRA)) {
2804 old_boost_score = boost_score;
2806 // Get the next frame details
2807 if (EOF == input_stats(twopass, &local_next_frame)) break;
2810 // If there is tolerable prediction for at least the next 3 frames then
2811 // break out else discard this potential key frame and move on
2812 if (boost_score > 30.0 && (i > 3)) {
2815 // Reset the file position
2816 reset_fpf_position(twopass, start_pos);
2822 return is_viable_kf;
2825 #define FRAMES_TO_CHECK_DECAY 8
2826 #define MIN_KF_TOT_BOOST 300
2827 #define KF_BOOST_SCAN_MAX_FRAMES 32
2828 #define KF_ABS_ZOOM_THRESH 6.0
2830 #ifdef AGGRESSIVE_VBR
2831 #define KF_MAX_FRAME_BOOST 80.0
2832 #define MAX_KF_TOT_BOOST 4800
2834 #define KF_MAX_FRAME_BOOST 96.0
2835 #define MAX_KF_TOT_BOOST 5400
2838 static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
2840 RATE_CONTROL *const rc = &cpi->rc;
2841 TWO_PASS *const twopass = &cpi->twopass;
2842 GF_GROUP *const gf_group = &twopass->gf_group;
2843 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2844 const FIRSTPASS_STATS first_frame = *this_frame;
2845 const FIRSTPASS_STATS *const start_position = twopass->stats_in;
2846 FIRSTPASS_STATS next_frame;
2847 FIRSTPASS_STATS last_frame;
2849 double decay_accumulator = 1.0;
2850 double zero_motion_accumulator = 1.0;
2851 double boost_score = 0.0;
2852 double kf_mod_err = 0.0;
2853 double kf_group_err = 0.0;
2854 double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
2855 double sr_accumulator = 0.0;
2856 double abs_mv_in_out_accumulator = 0.0;
2857 const double av_err = get_distribution_av_err(cpi, twopass);
2858 vp9_zero(next_frame);
2860 cpi->common.frame_type = KEY_FRAME;
2862 // Reset the GF group data structures.
2863 vp9_zero(*gf_group);
2865 // Is this a forced key frame by interval.
2866 rc->this_key_frame_forced = rc->next_key_frame_forced;
2868 // Clear the alt ref active flag and last group multi arf flags as they
2869 // can never be set for a key frame.
2870 rc->source_alt_ref_active = 0;
2871 cpi->multi_arf_last_grp_enabled = 0;
2873 // KF is always a GF so clear frames till next gf counter.
2874 rc->frames_till_gf_update_due = 0;
2876 rc->frames_to_key = 1;
2878 twopass->kf_group_bits = 0; // Total bits available to kf group
2879 twopass->kf_group_error_left = 0.0; // Group modified error score.
2882 calculate_norm_frame_score(cpi, twopass, oxcf, this_frame, av_err);
2884 // Initialize the decay rates for the recent frames to check
2885 for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
2887 // Find the next keyframe.
2889 while (twopass->stats_in < twopass->stats_in_end &&
2890 rc->frames_to_key < cpi->oxcf.key_freq) {
2891 // Accumulate kf group error.
2893 calculate_norm_frame_score(cpi, twopass, oxcf, this_frame, av_err);
2895 // Load the next frame's stats.
2896 last_frame = *this_frame;
2897 input_stats(twopass, this_frame);
2899 // Provided that we are not at the end of the file...
2900 if (cpi->oxcf.auto_key && twopass->stats_in < twopass->stats_in_end) {
2901 double loop_decay_rate;
2903 // Check for a scene cut.
2904 if (test_candidate_kf(twopass, &last_frame, this_frame,
2908 // How fast is the prediction quality decaying?
2909 loop_decay_rate = get_prediction_decay_rate(cpi, twopass->stats_in);
2911 // We want to know something about the recent past... rather than
2912 // as used elsewhere where we are concerned with decay in prediction
2913 // quality since the last GF or KF.
2914 recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
2915 decay_accumulator = 1.0;
2916 for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
2917 decay_accumulator *= recent_loop_decay[j];
2919 // Special check for transition or high motion followed by a
2921 if (detect_transition_to_still(cpi, i, cpi->oxcf.key_freq - i,
2922 loop_decay_rate, decay_accumulator))
2925 // Step on to the next frame.
2926 ++rc->frames_to_key;
2928 // If we don't have a real key frame within the next two
2929 // key_freq intervals then break out of the loop.
2930 if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq) break;
2932 ++rc->frames_to_key;
2937 // If there is a max kf interval set by the user we must obey it.
2938 // We already breakout of the loop above at 2x max.
2939 // This code centers the extra kf if the actual natural interval
2940 // is between 1x and 2x.
2941 if (cpi->oxcf.auto_key && rc->frames_to_key > cpi->oxcf.key_freq) {
2942 FIRSTPASS_STATS tmp_frame = first_frame;
2944 rc->frames_to_key /= 2;
2946 // Reset to the start of the group.
2947 reset_fpf_position(twopass, start_position);
2951 // Rescan to get the correct error data for the forced kf group.
2952 for (i = 0; i < rc->frames_to_key; ++i) {
2954 calculate_norm_frame_score(cpi, twopass, oxcf, &tmp_frame, av_err);
2955 input_stats(twopass, &tmp_frame);
2957 rc->next_key_frame_forced = 1;
2958 } else if (twopass->stats_in == twopass->stats_in_end ||
2959 rc->frames_to_key >= cpi->oxcf.key_freq) {
2960 rc->next_key_frame_forced = 1;
2962 rc->next_key_frame_forced = 0;
2965 if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
2966 int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
2967 int new_frame_to_key = (rc->frames_to_key + count) & (~count);
2969 for (j = 0; j < new_frame_to_key - rc->frames_to_key; ++j) {
2970 if (EOF == input_stats(twopass, this_frame)) break;
2972 calculate_norm_frame_score(cpi, twopass, oxcf, this_frame, av_err);
2974 rc->frames_to_key = new_frame_to_key;
2977 // Special case for the last key frame of the file.
2978 if (twopass->stats_in >= twopass->stats_in_end) {
2979 // Accumulate kf group error.
2981 calculate_norm_frame_score(cpi, twopass, oxcf, this_frame, av_err);
2984 // Calculate the number of bits that should be assigned to the kf group.
2985 if (twopass->bits_left > 0 && twopass->normalized_score_left > 0.0) {
2986 // Maximum number of bits for a single normal frame (not key frame).
2987 const int max_bits = frame_max_bits(rc, &cpi->oxcf);
2989 // Maximum number of bits allocated to the key frame group.
2990 int64_t max_grp_bits;
2992 // Default allocation based on bits left and relative
2993 // complexity of the section.
2994 twopass->kf_group_bits = (int64_t)(
2995 twopass->bits_left * (kf_group_err / twopass->normalized_score_left));
2997 // Clip based on maximum per frame rate defined by the user.
2998 max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
2999 if (twopass->kf_group_bits > max_grp_bits)
3000 twopass->kf_group_bits = max_grp_bits;
3002 twopass->kf_group_bits = 0;
3004 twopass->kf_group_bits = VPXMAX(0, twopass->kf_group_bits);
3006 // Reset the first pass file position.
3007 reset_fpf_position(twopass, start_position);
3009 // Scan through the kf group collating various stats used to determine
3010 // how many bits to spend on it.
3013 for (i = 0; i < (rc->frames_to_key - 1); ++i) {
3014 if (EOF == input_stats(twopass, &next_frame)) break;
3016 if (i <= KF_BOOST_SCAN_MAX_FRAMES) {
3020 // Monitor for static sections.
3021 zero_motion_accumulator = VPXMIN(
3022 zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
3024 // Factor 0.75-1.25 based on how much of frame is static.
3025 zm_factor = (0.75 + (zero_motion_accumulator / 2.0));
3027 // The second (lagging) ref error is not valid immediately after
3028 // a key frame because either the lag has not built up (in the case of
3029 // the first key frame or it points to a refernce before the new key
3031 if (i < 2) sr_accumulator = 0.0;
3032 frame_boost = calc_kf_frame_boost(cpi, &next_frame, &sr_accumulator, 0,
3033 KF_MAX_FRAME_BOOST * zm_factor);
3035 boost_score += frame_boost;
3037 // Measure of zoom. Large zoom tends to indicate reduced boost.
3038 abs_mv_in_out_accumulator +=
3039 fabs(next_frame.mv_in_out_count * next_frame.pcnt_motion);
3041 if ((frame_boost < 25.00) ||
3042 (abs_mv_in_out_accumulator > KF_ABS_ZOOM_THRESH))
3049 reset_fpf_position(twopass, start_position);
3051 // Store the zero motion percentage
3052 twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
3054 // Calculate a section intra ratio used in setting max loop filter.
3055 twopass->section_intra_rating = calculate_section_intra_ratio(
3056 start_position, twopass->stats_in_end, rc->frames_to_key);
3058 // Apply various clamps for min and max boost
3059 rc->kf_boost = VPXMAX((int)boost_score, (rc->frames_to_key * 3));
3060 rc->kf_boost = VPXMAX(rc->kf_boost, MIN_KF_TOT_BOOST);
3061 rc->kf_boost = VPXMIN(rc->kf_boost, MAX_KF_TOT_BOOST);
3063 // Work out how many bits to allocate for the key frame itself.
3064 kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
3065 twopass->kf_group_bits);
3067 twopass->kf_group_bits -= kf_bits;
3069 // Save the bits to spend on the key frame.
3070 gf_group->bit_allocation[0] = kf_bits;
3071 gf_group->update_type[0] = KF_UPDATE;
3072 gf_group->rf_level[0] = KF_STD;
3074 // Note the total error score of the kf group minus the key frame itself.
3075 twopass->kf_group_error_left = (kf_group_err - kf_mod_err);
3077 // Adjust the count of total modified error left.
3078 // The count of bits left is adjusted elsewhere based on real coded frame
3080 twopass->normalized_score_left -= kf_group_err;
3082 if (oxcf->resize_mode == RESIZE_DYNAMIC) {
3083 // Default to normal-sized frame on keyframes.
3084 cpi->rc.next_frame_size_selector = UNSCALED;
3088 // Define the reference buffers that will be updated post encode.
3089 static void configure_buffer_updates(VP9_COMP *cpi) {
3090 TWO_PASS *const twopass = &cpi->twopass;
3092 cpi->rc.is_src_frame_alt_ref = 0;
3093 switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
3095 cpi->refresh_last_frame = 1;
3096 cpi->refresh_golden_frame = 1;
3097 cpi->refresh_alt_ref_frame = 1;
3100 cpi->refresh_last_frame = 1;
3101 cpi->refresh_golden_frame = 0;
3102 cpi->refresh_alt_ref_frame = 0;
3105 cpi->refresh_last_frame = 1;
3106 cpi->refresh_golden_frame = 1;
3107 cpi->refresh_alt_ref_frame = 0;
3109 case OVERLAY_UPDATE:
3110 cpi->refresh_last_frame = 0;
3111 cpi->refresh_golden_frame = 1;
3112 cpi->refresh_alt_ref_frame = 0;
3113 cpi->rc.is_src_frame_alt_ref = 1;
3116 cpi->refresh_last_frame = 0;
3117 cpi->refresh_golden_frame = 0;
3118 cpi->refresh_alt_ref_frame = 1;
3120 default: assert(0); break;
3122 if (is_two_pass_svc(cpi)) {
3123 if (cpi->svc.temporal_layer_id > 0) {
3124 cpi->refresh_last_frame = 0;
3125 cpi->refresh_golden_frame = 0;
3127 if (cpi->svc.layer_context[cpi->svc.spatial_layer_id].gold_ref_idx < 0)
3128 cpi->refresh_golden_frame = 0;
3129 if (cpi->alt_ref_source == NULL) cpi->refresh_alt_ref_frame = 0;
3133 static int is_skippable_frame(const VP9_COMP *cpi) {
3134 // If the current frame does not have non-zero motion vector detected in the
3135 // first pass, and so do its previous and forward frames, then this frame
3136 // can be skipped for partition check, and the partition size is assigned
3137 // according to the variance
3138 const SVC *const svc = &cpi->svc;
3139 const TWO_PASS *const twopass =
3140 is_two_pass_svc(cpi) ? &svc->layer_context[svc->spatial_layer_id].twopass
3143 return (!frame_is_intra_only(&cpi->common) &&
3144 twopass->stats_in - 2 > twopass->stats_in_start &&
3145 twopass->stats_in < twopass->stats_in_end &&
3146 (twopass->stats_in - 1)->pcnt_inter -
3147 (twopass->stats_in - 1)->pcnt_motion ==
3149 (twopass->stats_in - 2)->pcnt_inter -
3150 (twopass->stats_in - 2)->pcnt_motion ==
3152 twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
3155 void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
3156 VP9_COMMON *const cm = &cpi->common;
3157 RATE_CONTROL *const rc = &cpi->rc;
3158 TWO_PASS *const twopass = &cpi->twopass;
3159 GF_GROUP *const gf_group = &twopass->gf_group;
3160 FIRSTPASS_STATS this_frame;
3163 LAYER_CONTEXT *const lc =
3164 is_two_pass_svc(cpi) ? &cpi->svc.layer_context[cpi->svc.spatial_layer_id]
3167 if (!twopass->stats_in) return;
3169 // If this is an arf frame then we dont want to read the stats file or
3170 // advance the input pointer as we already have what we need.
3171 if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
3173 configure_buffer_updates(cpi);
3174 target_rate = gf_group->bit_allocation[gf_group->index];
3175 target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
3176 rc->base_frame_target = target_rate;
3178 cm->frame_type = INTER_FRAME;
3181 if (cpi->svc.spatial_layer_id == 0) {
3182 lc->is_key_frame = 0;
3184 lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
3186 if (lc->is_key_frame) cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
3190 // Do the firstpass stats indicate that this frame is skippable for the
3191 // partition search?
3192 if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2 &&
3193 (!cpi->use_svc || is_two_pass_svc(cpi))) {
3194 cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
3200 vpx_clear_system_state();
3202 if (cpi->oxcf.rc_mode == VPX_Q) {
3203 twopass->active_worst_quality = cpi->oxcf.cq_level;
3204 } else if (cm->current_video_frame == 0 ||
3205 (lc != NULL && lc->current_video_frame_in_layer == 0)) {
3206 const int frames_left =
3207 (int)(twopass->total_stats.count -
3208 ((lc != NULL) ? lc->current_video_frame_in_layer
3209 : cm->current_video_frame));
3210 // Special case code for first frame.
3211 const int section_target_bandwidth =
3212 (int)(twopass->bits_left / frames_left);
3213 const double section_length = twopass->total_left_stats.count;
3214 const double section_error =
3215 twopass->total_left_stats.coded_error / section_length;
3216 const double section_intra_skip =
3217 twopass->total_left_stats.intra_skip_pct / section_length;
3218 const double section_inactive_zone =
3219 (twopass->total_left_stats.inactive_zone_rows * 2) /
3220 ((double)cm->mb_rows * section_length);
3221 const double section_noise =
3222 twopass->total_left_stats.frame_noise_energy / section_length;
3225 tmp_q = get_twopass_worst_quality(
3226 cpi, section_error, section_intra_skip + section_inactive_zone,
3227 section_noise, section_target_bandwidth);
3229 twopass->active_worst_quality = tmp_q;
3230 twopass->baseline_active_worst_quality = tmp_q;
3231 rc->ni_av_qi = tmp_q;
3232 rc->last_q[INTER_FRAME] = tmp_q;
3233 rc->avg_q = vp9_convert_qindex_to_q(tmp_q, cm->bit_depth);
3234 rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
3235 rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
3236 rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
3238 vp9_zero(this_frame);
3239 if (EOF == input_stats(twopass, &this_frame)) return;
3241 // Set the frame content type flag.
3242 if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
3243 twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
3245 twopass->fr_content_type = FC_NORMAL;
3247 // Keyframe and section processing.
3248 if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
3249 FIRSTPASS_STATS this_frame_copy;
3250 this_frame_copy = this_frame;
3251 // Define next KF group and assign bits to it.
3252 find_next_key_frame(cpi, &this_frame);
3253 this_frame = this_frame_copy;
3255 cm->frame_type = INTER_FRAME;
3259 if (cpi->svc.spatial_layer_id == 0) {
3260 lc->is_key_frame = (cm->frame_type == KEY_FRAME);
3261 if (lc->is_key_frame) {
3262 cpi->ref_frame_flags &=
3263 (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
3264 lc->frames_from_key_frame = 0;
3265 // Encode an intra only empty frame since we have a key frame.
3266 cpi->svc.encode_intra_empty_frame = 1;
3269 cm->frame_type = INTER_FRAME;
3270 lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
3272 if (lc->is_key_frame) {
3273 cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
3274 lc->frames_from_key_frame = 0;
3279 // Define a new GF/ARF group. (Should always enter here for key frames).
3280 if (rc->frames_till_gf_update_due == 0) {
3281 define_gf_group(cpi, &this_frame);
3283 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3284 if (lc != NULL) cpi->refresh_golden_frame = 1;
3286 #if ARF_STATS_OUTPUT
3289 fpfile = fopen("arf.stt", "a");
3291 fprintf(fpfile, "%10d %10ld %10d %10d %10ld\n", cm->current_video_frame,
3292 rc->frames_till_gf_update_due, rc->kf_boost, arf_count,
3300 configure_buffer_updates(cpi);
3302 // Do the firstpass stats indicate that this frame is skippable for the
3303 // partition search?
3304 if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2 &&
3305 (!cpi->use_svc || is_two_pass_svc(cpi))) {
3306 cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
3309 target_rate = gf_group->bit_allocation[gf_group->index];
3310 rc->base_frame_target = target_rate;
3312 // The multiplication by 256 reverses a scaling factor of (>> 8)
3313 // applied when combining MB error values for the frame.
3314 twopass->mb_av_energy = log((this_frame.intra_error * 256.0) + 1.0);
3315 twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
3317 // Update the total stats remaining structure.
3318 subtract_stats(&twopass->total_left_stats, &this_frame);
3321 #define MINQ_ADJ_LIMIT 48
3322 #define MINQ_ADJ_LIMIT_CQ 20
3323 #define HIGH_UNDERSHOOT_RATIO 2
3324 void vp9_twopass_postencode_update(VP9_COMP *cpi) {
3325 TWO_PASS *const twopass = &cpi->twopass;
3326 RATE_CONTROL *const rc = &cpi->rc;
3327 VP9_COMMON *const cm = &cpi->common;
3328 const int bits_used = rc->base_frame_target;
3330 // VBR correction is done through rc->vbr_bits_off_target. Based on the
3331 // sign of this value, a limited % adjustment is made to the target rate
3332 // of subsequent frames, to try and push it back towards 0. This method
3333 // is designed to prevent extreme behaviour at the end of a clip
3334 // or group of frames.
3335 rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
3336 twopass->bits_left = VPXMAX(twopass->bits_left - bits_used, 0);
3338 // Target vs actual bits for this arf group.
3339 twopass->rolling_arf_group_target_bits += rc->this_frame_target;
3340 twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
3342 // Calculate the pct rc error.
3343 if (rc->total_actual_bits) {
3344 rc->rate_error_estimate =
3345 (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
3346 rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
3348 rc->rate_error_estimate = 0;
3351 if (cpi->common.frame_type != KEY_FRAME &&
3352 !vp9_is_upper_layer_key_frame(cpi)) {
3353 twopass->kf_group_bits -= bits_used;
3354 twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
3356 twopass->kf_group_bits = VPXMAX(twopass->kf_group_bits, 0);
3358 // Increment the gf group index ready for the next frame.
3359 ++twopass->gf_group.index;
3361 // If the rate control is drifting consider adjustment to min or maxq.
3362 if ((cpi->oxcf.rc_mode != VPX_Q) && !cpi->rc.is_src_frame_alt_ref) {
3363 const int maxq_adj_limit =
3364 rc->worst_quality - twopass->active_worst_quality;
3365 const int minq_adj_limit =
3366 (cpi->oxcf.rc_mode == VPX_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
3367 int aq_extend_min = 0;
3368 int aq_extend_max = 0;
3370 // Extend min or Max Q range to account for imbalance from the base
3371 // value when using AQ.
3372 if (cpi->oxcf.aq_mode != NO_AQ) {
3373 if (cm->seg.aq_av_offset < 0) {
3374 // The balance of the AQ map tends towarda lowering the average Q.
3376 aq_extend_max = VPXMIN(maxq_adj_limit, -cm->seg.aq_av_offset);
3378 // The balance of the AQ map tends towards raising the average Q.
3379 aq_extend_min = VPXMIN(minq_adj_limit, cm->seg.aq_av_offset);
3385 if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
3386 --twopass->extend_maxq;
3387 if (rc->rolling_target_bits >= rc->rolling_actual_bits)
3388 ++twopass->extend_minq;
3390 } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
3391 --twopass->extend_minq;
3392 if (rc->rolling_target_bits < rc->rolling_actual_bits)
3393 ++twopass->extend_maxq;
3395 // Adjustment for extreme local overshoot.
3396 if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
3397 rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
3398 ++twopass->extend_maxq;
3400 // Unwind undershoot or overshoot adjustment.
3401 if (rc->rolling_target_bits < rc->rolling_actual_bits)
3402 --twopass->extend_minq;
3403 else if (rc->rolling_target_bits > rc->rolling_actual_bits)
3404 --twopass->extend_maxq;
3407 twopass->extend_minq =
3408 clamp(twopass->extend_minq, aq_extend_min, minq_adj_limit);
3409 twopass->extend_maxq =
3410 clamp(twopass->extend_maxq, aq_extend_max, maxq_adj_limit);
3412 // If there is a big and undexpected undershoot then feed the extra
3413 // bits back in quickly. One situation where this may happen is if a
3414 // frame is unexpectedly almost perfectly predicted by the ARF or GF
3415 // but not very well predcited by the previous frame.
3416 if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
3417 int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
3418 if (rc->projected_frame_size < fast_extra_thresh) {
3419 rc->vbr_bits_off_target_fast +=
3420 fast_extra_thresh - rc->projected_frame_size;
3421 rc->vbr_bits_off_target_fast =
3422 VPXMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
3424 // Fast adaptation of minQ if necessary to use up the extra bits.
3425 if (rc->avg_frame_bandwidth) {
3426 twopass->extend_minq_fast =
3427 (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
3429 twopass->extend_minq_fast = VPXMIN(
3430 twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3431 } else if (rc->vbr_bits_off_target_fast) {
3432 twopass->extend_minq_fast = VPXMIN(
3433 twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
3435 twopass->extend_minq_fast = 0;